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