1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/LTO/legacy/LTOCodeGenerator.h"
15 
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Bitcode/BitcodeWriter.h"
22 #include "llvm/CodeGen/ParallelCG.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/PassTimingInfo.h"
36 #include "llvm/IR/RemarkStreamer.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LTO/LTO.h"
40 #include "llvm/LTO/legacy/LTOModule.h"
41 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
42 #include "llvm/Linker/Linker.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/SubtargetFeature.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Signals.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/ToolOutputFile.h"
54 #include "llvm/Support/YAMLTraits.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetOptions.h"
57 #include "llvm/Transforms/IPO.h"
58 #include "llvm/Transforms/IPO/Internalize.h"
59 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
60 #include "llvm/Transforms/ObjCARC.h"
61 #include "llvm/Transforms/Utils/ModuleUtils.h"
62 #include <system_error>
63 using namespace llvm;
64 
65 const char* LTOCodeGenerator::getVersionString() {
66 #ifdef LLVM_VERSION_INFO
67   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
68 #else
69   return PACKAGE_NAME " version " PACKAGE_VERSION;
70 #endif
71 }
72 
73 namespace llvm {
74 cl::opt<bool> LTODiscardValueNames(
75     "lto-discard-value-names",
76     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
77 #ifdef NDEBUG
78     cl::init(true),
79 #else
80     cl::init(false),
81 #endif
82     cl::Hidden);
83 
84 cl::opt<bool> RemarksWithHotness(
85     "lto-pass-remarks-with-hotness",
86     cl::desc("With PGO, include profile count in optimization remarks"),
87     cl::Hidden);
88 
89 cl::opt<std::string>
90     RemarksFilename("lto-pass-remarks-output",
91                     cl::desc("Output filename for pass remarks"),
92                     cl::value_desc("filename"));
93 
94 cl::opt<std::string>
95     RemarksPasses("lto-pass-remarks-filter",
96                   cl::desc("Only record optimization remarks from passes whose "
97                            "names match the given regular expression"),
98                   cl::value_desc("regex"));
99 
100 cl::opt<std::string> LTOStatsFile(
101     "lto-stats-file",
102     cl::desc("Save statistics to the specified file"),
103     cl::Hidden);
104 }
105 
106 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
107     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
108       TheLinker(new Linker(*MergedModule)) {
109   Context.setDiscardValueNames(LTODiscardValueNames);
110   Context.enableDebugTypeODRUniquing();
111   initializeLTOPasses();
112 }
113 
114 LTOCodeGenerator::~LTOCodeGenerator() {}
115 
116 // Initialize LTO passes. Please keep this function in sync with
117 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
118 // passes are initialized.
119 void LTOCodeGenerator::initializeLTOPasses() {
120   PassRegistry &R = *PassRegistry::getPassRegistry();
121 
122   initializeInternalizeLegacyPassPass(R);
123   initializeIPSCCPLegacyPassPass(R);
124   initializeGlobalOptLegacyPassPass(R);
125   initializeConstantMergeLegacyPassPass(R);
126   initializeDAHPass(R);
127   initializeInstructionCombiningPassPass(R);
128   initializeSimpleInlinerPass(R);
129   initializePruneEHPass(R);
130   initializeGlobalDCELegacyPassPass(R);
131   initializeArgPromotionPass(R);
132   initializeJumpThreadingPass(R);
133   initializeSROALegacyPassPass(R);
134   initializeAttributorLegacyPassPass(R);
135   initializePostOrderFunctionAttrsLegacyPassPass(R);
136   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
137   initializeGlobalsAAWrapperPassPass(R);
138   initializeLegacyLICMPassPass(R);
139   initializeMergedLoadStoreMotionLegacyPassPass(R);
140   initializeGVNLegacyPassPass(R);
141   initializeMemCpyOptLegacyPassPass(R);
142   initializeDCELegacyPassPass(R);
143   initializeCFGSimplifyPassPass(R);
144 }
145 
146 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
147   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
148   for (int i = 0, e = undefs.size(); i != e; ++i)
149     AsmUndefinedRefs[undefs[i]] = 1;
150 }
151 
152 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
153   assert(&Mod->getModule().getContext() == &Context &&
154          "Expected module in same context");
155 
156   bool ret = TheLinker->linkInModule(Mod->takeModule());
157   setAsmUndefinedRefs(Mod);
158 
159   // We've just changed the input, so let's make sure we verify it.
160   HasVerifiedInput = false;
161 
162   return !ret;
163 }
164 
165 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
166   assert(&Mod->getModule().getContext() == &Context &&
167          "Expected module in same context");
168 
169   AsmUndefinedRefs.clear();
170 
171   MergedModule = Mod->takeModule();
172   TheLinker = make_unique<Linker>(*MergedModule);
173   setAsmUndefinedRefs(&*Mod);
174 
175   // We've just changed the input, so let's make sure we verify it.
176   HasVerifiedInput = false;
177 }
178 
179 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
180   this->Options = Options;
181 }
182 
183 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
184   switch (Debug) {
185   case LTO_DEBUG_MODEL_NONE:
186     EmitDwarfDebugInfo = false;
187     return;
188 
189   case LTO_DEBUG_MODEL_DWARF:
190     EmitDwarfDebugInfo = true;
191     return;
192   }
193   llvm_unreachable("Unknown debug format!");
194 }
195 
196 void LTOCodeGenerator::setOptLevel(unsigned Level) {
197   OptLevel = Level;
198   switch (OptLevel) {
199   case 0:
200     CGOptLevel = CodeGenOpt::None;
201     return;
202   case 1:
203     CGOptLevel = CodeGenOpt::Less;
204     return;
205   case 2:
206     CGOptLevel = CodeGenOpt::Default;
207     return;
208   case 3:
209     CGOptLevel = CodeGenOpt::Aggressive;
210     return;
211   }
212   llvm_unreachable("Unknown optimization level!");
213 }
214 
215 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
216   if (!determineTarget())
217     return false;
218 
219   // We always run the verifier once on the merged module.
220   verifyMergedModuleOnce();
221 
222   // mark which symbols can not be internalized
223   applyScopeRestrictions();
224 
225   // create output file
226   std::error_code EC;
227   ToolOutputFile Out(Path, EC, sys::fs::F_None);
228   if (EC) {
229     std::string ErrMsg = "could not open bitcode file for writing: ";
230     ErrMsg += Path.str() + ": " + EC.message();
231     emitError(ErrMsg);
232     return false;
233   }
234 
235   // write bitcode to it
236   WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
237   Out.os().close();
238 
239   if (Out.os().has_error()) {
240     std::string ErrMsg = "could not write bitcode file: ";
241     ErrMsg += Path.str() + ": " + Out.os().error().message();
242     emitError(ErrMsg);
243     Out.os().clear_error();
244     return false;
245   }
246 
247   Out.keep();
248   return true;
249 }
250 
251 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
252   // make unique temp output file to put generated code
253   SmallString<128> Filename;
254   int FD;
255 
256   StringRef Extension
257       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
258 
259   std::error_code EC =
260       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
261   if (EC) {
262     emitError(EC.message());
263     return false;
264   }
265 
266   // generate object file
267   ToolOutputFile objFile(Filename, FD);
268 
269   bool genResult = compileOptimized(&objFile.os());
270   objFile.os().close();
271   if (objFile.os().has_error()) {
272     emitError((Twine("could not write object file: ") + Filename + ": " +
273                objFile.os().error().message())
274                   .str());
275     objFile.os().clear_error();
276     sys::fs::remove(Twine(Filename));
277     return false;
278   }
279 
280   objFile.keep();
281   if (!genResult) {
282     sys::fs::remove(Twine(Filename));
283     return false;
284   }
285 
286   NativeObjectPath = Filename.c_str();
287   *Name = NativeObjectPath.c_str();
288   return true;
289 }
290 
291 std::unique_ptr<MemoryBuffer>
292 LTOCodeGenerator::compileOptimized() {
293   const char *name;
294   if (!compileOptimizedToFile(&name))
295     return nullptr;
296 
297   // read .o file into memory buffer
298   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
299       MemoryBuffer::getFile(name, -1, false);
300   if (std::error_code EC = BufferOrErr.getError()) {
301     emitError(EC.message());
302     sys::fs::remove(NativeObjectPath);
303     return nullptr;
304   }
305 
306   // remove temp files
307   sys::fs::remove(NativeObjectPath);
308 
309   return std::move(*BufferOrErr);
310 }
311 
312 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
313                                        bool DisableInline,
314                                        bool DisableGVNLoadPRE,
315                                        bool DisableVectorization) {
316   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
317                 DisableVectorization))
318     return false;
319 
320   return compileOptimizedToFile(Name);
321 }
322 
323 std::unique_ptr<MemoryBuffer>
324 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
325                           bool DisableGVNLoadPRE, bool DisableVectorization) {
326   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
327                 DisableVectorization))
328     return nullptr;
329 
330   return compileOptimized();
331 }
332 
333 bool LTOCodeGenerator::determineTarget() {
334   if (TargetMach)
335     return true;
336 
337   TripleStr = MergedModule->getTargetTriple();
338   if (TripleStr.empty()) {
339     TripleStr = sys::getDefaultTargetTriple();
340     MergedModule->setTargetTriple(TripleStr);
341   }
342   llvm::Triple Triple(TripleStr);
343 
344   // create target machine from info for merged modules
345   std::string ErrMsg;
346   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
347   if (!MArch) {
348     emitError(ErrMsg);
349     return false;
350   }
351 
352   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
353   // the default set of features.
354   SubtargetFeatures Features(MAttr);
355   Features.getDefaultSubtargetFeatures(Triple);
356   FeatureStr = Features.getString();
357   // Set a default CPU for Darwin triples.
358   if (MCpu.empty() && Triple.isOSDarwin()) {
359     if (Triple.getArch() == llvm::Triple::x86_64)
360       MCpu = "core2";
361     else if (Triple.getArch() == llvm::Triple::x86)
362       MCpu = "yonah";
363     else if (Triple.getArch() == llvm::Triple::aarch64)
364       MCpu = "cyclone";
365   }
366 
367   TargetMach = createTargetMachine();
368   return true;
369 }
370 
371 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
372   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
373       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
374 }
375 
376 // If a linkonce global is present in the MustPreserveSymbols, we need to make
377 // sure we honor this. To force the compiler to not drop it, we add it to the
378 // "llvm.compiler.used" global.
379 void LTOCodeGenerator::preserveDiscardableGVs(
380     Module &TheModule,
381     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
382   std::vector<GlobalValue *> Used;
383   auto mayPreserveGlobal = [&](GlobalValue &GV) {
384     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
385         !mustPreserveGV(GV))
386       return;
387     if (GV.hasAvailableExternallyLinkage())
388       return emitWarning(
389           (Twine("Linker asked to preserve available_externally global: '") +
390            GV.getName() + "'").str());
391     if (GV.hasInternalLinkage())
392       return emitWarning((Twine("Linker asked to preserve internal global: '") +
393                    GV.getName() + "'").str());
394     Used.push_back(&GV);
395   };
396   for (auto &GV : TheModule)
397     mayPreserveGlobal(GV);
398   for (auto &GV : TheModule.globals())
399     mayPreserveGlobal(GV);
400   for (auto &GV : TheModule.aliases())
401     mayPreserveGlobal(GV);
402 
403   if (Used.empty())
404     return;
405 
406   appendToCompilerUsed(TheModule, Used);
407 }
408 
409 void LTOCodeGenerator::applyScopeRestrictions() {
410   if (ScopeRestrictionsDone)
411     return;
412 
413   // Declare a callback for the internalize pass that will ask for every
414   // candidate GlobalValue if it can be internalized or not.
415   Mangler Mang;
416   SmallString<64> MangledName;
417   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
418     // Unnamed globals can't be mangled, but they can't be preserved either.
419     if (!GV.hasName())
420       return false;
421 
422     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
423     // with the linker supplied name, which on Darwin includes a leading
424     // underscore.
425     MangledName.clear();
426     MangledName.reserve(GV.getName().size() + 1);
427     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
428     return MustPreserveSymbols.count(MangledName);
429   };
430 
431   // Preserve linkonce value on linker request
432   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
433 
434   if (!ShouldInternalize)
435     return;
436 
437   if (ShouldRestoreGlobalsLinkage) {
438     // Record the linkage type of non-local symbols so they can be restored
439     // prior
440     // to module splitting.
441     auto RecordLinkage = [&](const GlobalValue &GV) {
442       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
443           GV.hasName())
444         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
445     };
446     for (auto &GV : *MergedModule)
447       RecordLinkage(GV);
448     for (auto &GV : MergedModule->globals())
449       RecordLinkage(GV);
450     for (auto &GV : MergedModule->aliases())
451       RecordLinkage(GV);
452   }
453 
454   // Update the llvm.compiler_used globals to force preserving libcalls and
455   // symbols referenced from asm
456   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
457 
458   internalizeModule(*MergedModule, mustPreserveGV);
459 
460   ScopeRestrictionsDone = true;
461 }
462 
463 /// Restore original linkage for symbols that may have been internalized
464 void LTOCodeGenerator::restoreLinkageForExternals() {
465   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
466     return;
467 
468   assert(ScopeRestrictionsDone &&
469          "Cannot externalize without internalization!");
470 
471   if (ExternalSymbols.empty())
472     return;
473 
474   auto externalize = [this](GlobalValue &GV) {
475     if (!GV.hasLocalLinkage() || !GV.hasName())
476       return;
477 
478     auto I = ExternalSymbols.find(GV.getName());
479     if (I == ExternalSymbols.end())
480       return;
481 
482     GV.setLinkage(I->second);
483   };
484 
485   llvm::for_each(MergedModule->functions(), externalize);
486   llvm::for_each(MergedModule->globals(), externalize);
487   llvm::for_each(MergedModule->aliases(), externalize);
488 }
489 
490 void LTOCodeGenerator::verifyMergedModuleOnce() {
491   // Only run on the first call.
492   if (HasVerifiedInput)
493     return;
494   HasVerifiedInput = true;
495 
496   bool BrokenDebugInfo = false;
497   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
498     report_fatal_error("Broken module found, compilation aborted!");
499   if (BrokenDebugInfo) {
500     emitWarning("Invalid debug info found, debug info will be stripped");
501     StripDebugInfo(*MergedModule);
502   }
503 }
504 
505 void LTOCodeGenerator::finishOptimizationRemarks() {
506   if (DiagnosticOutputFile) {
507     DiagnosticOutputFile->keep();
508     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
509     DiagnosticOutputFile->os().flush();
510   }
511 }
512 
513 /// Optimize merged modules using various IPO passes
514 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
515                                 bool DisableGVNLoadPRE,
516                                 bool DisableVectorization) {
517   if (!this->determineTarget())
518     return false;
519 
520   auto DiagFileOrErr = lto::setupOptimizationRemarks(
521       Context, RemarksFilename, RemarksPasses, RemarksWithHotness);
522   if (!DiagFileOrErr) {
523     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
524     report_fatal_error("Can't get an output file for the remarks");
525   }
526   DiagnosticOutputFile = std::move(*DiagFileOrErr);
527 
528   // Setup output file to emit statistics.
529   auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
530   if (!StatsFileOrErr) {
531     errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
532     report_fatal_error("Can't get an output file for the statistics");
533   }
534   StatsFile = std::move(StatsFileOrErr.get());
535 
536   // We always run the verifier once on the merged module, the `DisableVerify`
537   // parameter only applies to subsequent verify.
538   verifyMergedModuleOnce();
539 
540   // Mark which symbols can not be internalized
541   this->applyScopeRestrictions();
542 
543   // Instantiate the pass manager to organize the passes.
544   legacy::PassManager passes;
545 
546   // Add an appropriate DataLayout instance for this module...
547   MergedModule->setDataLayout(TargetMach->createDataLayout());
548 
549   passes.add(
550       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
551 
552   Triple TargetTriple(TargetMach->getTargetTriple());
553   PassManagerBuilder PMB;
554   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
555   PMB.LoopVectorize = !DisableVectorization;
556   PMB.SLPVectorize = !DisableVectorization;
557   if (!DisableInline)
558     PMB.Inliner = createFunctionInliningPass();
559   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
560   if (Freestanding)
561     PMB.LibraryInfo->disableAllFunctions();
562   PMB.OptLevel = OptLevel;
563   PMB.VerifyInput = !DisableVerify;
564   PMB.VerifyOutput = !DisableVerify;
565 
566   PMB.populateLTOPassManager(passes);
567 
568   // Run our queue of passes all at once now, efficiently.
569   passes.run(*MergedModule);
570 
571   return true;
572 }
573 
574 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
575   if (!this->determineTarget())
576     return false;
577 
578   // We always run the verifier once on the merged module.  If it has already
579   // been called in optimize(), this call will return early.
580   verifyMergedModuleOnce();
581 
582   legacy::PassManager preCodeGenPasses;
583 
584   // If the bitcode files contain ARC code and were compiled with optimization,
585   // the ObjCARCContractPass must be run, so do it unconditionally here.
586   preCodeGenPasses.add(createObjCARCContractPass());
587   preCodeGenPasses.run(*MergedModule);
588 
589   // Re-externalize globals that may have been internalized to increase scope
590   // for splitting
591   restoreLinkageForExternals();
592 
593   // Do code generation. We need to preserve the module in case the client calls
594   // writeMergedModules() after compilation, but we only need to allow this at
595   // parallelism level 1. This is achieved by having splitCodeGen return the
596   // original module at parallelism level 1 which we then assign back to
597   // MergedModule.
598   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
599                               [&]() { return createTargetMachine(); }, FileType,
600                               ShouldRestoreGlobalsLinkage);
601 
602   // If statistics were requested, save them to the specified file or
603   // print them out after codegen.
604   if (StatsFile)
605     PrintStatisticsJSON(StatsFile->os());
606   else if (AreStatisticsEnabled())
607     PrintStatistics();
608 
609   reportAndResetTimings();
610 
611   finishOptimizationRemarks();
612 
613   return true;
614 }
615 
616 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
617 /// LTO problems.
618 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
619   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
620        o = getToken(o.second))
621     CodegenOptions.push_back(o.first);
622 }
623 
624 void LTOCodeGenerator::parseCodeGenDebugOptions() {
625   // if options were requested, set them
626   if (!CodegenOptions.empty()) {
627     // ParseCommandLineOptions() expects argv[0] to be program name.
628     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
629     for (std::string &Arg : CodegenOptions)
630       CodegenArgv.push_back(Arg.c_str());
631     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
632   }
633 }
634 
635 
636 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
637   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
638   lto_codegen_diagnostic_severity_t Severity;
639   switch (DI.getSeverity()) {
640   case DS_Error:
641     Severity = LTO_DS_ERROR;
642     break;
643   case DS_Warning:
644     Severity = LTO_DS_WARNING;
645     break;
646   case DS_Remark:
647     Severity = LTO_DS_REMARK;
648     break;
649   case DS_Note:
650     Severity = LTO_DS_NOTE;
651     break;
652   }
653   // Create the string that will be reported to the external diagnostic handler.
654   std::string MsgStorage;
655   raw_string_ostream Stream(MsgStorage);
656   DiagnosticPrinterRawOStream DP(Stream);
657   DI.print(DP);
658   Stream.flush();
659 
660   // If this method has been called it means someone has set up an external
661   // diagnostic handler. Assert on that.
662   assert(DiagHandler && "Invalid diagnostic handler");
663   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
664 }
665 
666 namespace {
667 struct LTODiagnosticHandler : public DiagnosticHandler {
668   LTOCodeGenerator *CodeGenerator;
669   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
670       : CodeGenerator(CodeGenPtr) {}
671   bool handleDiagnostics(const DiagnosticInfo &DI) override {
672     CodeGenerator->DiagnosticHandler(DI);
673     return true;
674   }
675 };
676 }
677 
678 void
679 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
680                                        void *Ctxt) {
681   this->DiagHandler = DiagHandler;
682   this->DiagContext = Ctxt;
683   if (!DiagHandler)
684     return Context.setDiagnosticHandler(nullptr);
685   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
686   // diagnostic to the external DiagHandler.
687   Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
688                                true);
689 }
690 
691 namespace {
692 class LTODiagnosticInfo : public DiagnosticInfo {
693   const Twine &Msg;
694 public:
695   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
696       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
697   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
698 };
699 }
700 
701 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
702   if (DiagHandler)
703     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
704   else
705     Context.diagnose(LTODiagnosticInfo(ErrMsg));
706 }
707 
708 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
709   if (DiagHandler)
710     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
711   else
712     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
713 }
714