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.str() + ": " + EC.message();
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.str() + ": " + Out.os().error().message();
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 + ": " +
264                objFile.os().error().message())
265                   .str());
266     objFile.os().clear_error();
267     sys::fs::remove(Twine(Filename));
268     return false;
269   }
270 
271   objFile.keep();
272   if (!genResult) {
273     sys::fs::remove(Twine(Filename));
274     return false;
275   }
276 
277   NativeObjectPath = Filename.c_str();
278   *Name = NativeObjectPath.c_str();
279   return true;
280 }
281 
282 std::unique_ptr<MemoryBuffer>
283 LTOCodeGenerator::compileOptimized() {
284   const char *name;
285   if (!compileOptimizedToFile(&name))
286     return nullptr;
287 
288   // read .o file into memory buffer
289   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
290       MemoryBuffer::getFile(name, -1, false);
291   if (std::error_code EC = BufferOrErr.getError()) {
292     emitError(EC.message());
293     sys::fs::remove(NativeObjectPath);
294     return nullptr;
295   }
296 
297   // remove temp files
298   sys::fs::remove(NativeObjectPath);
299 
300   return std::move(*BufferOrErr);
301 }
302 
303 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
304                                        bool DisableInline,
305                                        bool DisableGVNLoadPRE,
306                                        bool DisableVectorization) {
307   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
308                 DisableVectorization))
309     return false;
310 
311   return compileOptimizedToFile(Name);
312 }
313 
314 std::unique_ptr<MemoryBuffer>
315 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
316                           bool DisableGVNLoadPRE, bool DisableVectorization) {
317   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
318                 DisableVectorization))
319     return nullptr;
320 
321   return compileOptimized();
322 }
323 
324 bool LTOCodeGenerator::determineTarget() {
325   if (TargetMach)
326     return true;
327 
328   TripleStr = MergedModule->getTargetTriple();
329   if (TripleStr.empty()) {
330     TripleStr = sys::getDefaultTargetTriple();
331     MergedModule->setTargetTriple(TripleStr);
332   }
333   llvm::Triple Triple(TripleStr);
334 
335   // create target machine from info for merged modules
336   std::string ErrMsg;
337   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
338   if (!MArch) {
339     emitError(ErrMsg);
340     return false;
341   }
342 
343   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
344   // the default set of features.
345   SubtargetFeatures Features(MAttr);
346   Features.getDefaultSubtargetFeatures(Triple);
347   FeatureStr = Features.getString();
348   // Set a default CPU for Darwin triples.
349   if (MCpu.empty() && Triple.isOSDarwin()) {
350     if (Triple.getArch() == llvm::Triple::x86_64)
351       MCpu = "core2";
352     else if (Triple.getArch() == llvm::Triple::x86)
353       MCpu = "yonah";
354     else if (Triple.getArch() == llvm::Triple::aarch64)
355       MCpu = "cyclone";
356   }
357 
358   TargetMach = createTargetMachine();
359   return true;
360 }
361 
362 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
363   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
364       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
365 }
366 
367 // If a linkonce global is present in the MustPreserveSymbols, we need to make
368 // sure we honor this. To force the compiler to not drop it, we add it to the
369 // "llvm.compiler.used" global.
370 void LTOCodeGenerator::preserveDiscardableGVs(
371     Module &TheModule,
372     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
373   std::vector<GlobalValue *> Used;
374   auto mayPreserveGlobal = [&](GlobalValue &GV) {
375     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
376         !mustPreserveGV(GV))
377       return;
378     if (GV.hasAvailableExternallyLinkage())
379       return emitWarning(
380           (Twine("Linker asked to preserve available_externally global: '") +
381            GV.getName() + "'").str());
382     if (GV.hasInternalLinkage())
383       return emitWarning((Twine("Linker asked to preserve internal global: '") +
384                    GV.getName() + "'").str());
385     Used.push_back(&GV);
386   };
387   for (auto &GV : TheModule)
388     mayPreserveGlobal(GV);
389   for (auto &GV : TheModule.globals())
390     mayPreserveGlobal(GV);
391   for (auto &GV : TheModule.aliases())
392     mayPreserveGlobal(GV);
393 
394   if (Used.empty())
395     return;
396 
397   appendToCompilerUsed(TheModule, Used);
398 }
399 
400 void LTOCodeGenerator::applyScopeRestrictions() {
401   if (ScopeRestrictionsDone)
402     return;
403 
404   // Declare a callback for the internalize pass that will ask for every
405   // candidate GlobalValue if it can be internalized or not.
406   Mangler Mang;
407   SmallString<64> MangledName;
408   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
409     // Unnamed globals can't be mangled, but they can't be preserved either.
410     if (!GV.hasName())
411       return false;
412 
413     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
414     // with the linker supplied name, which on Darwin includes a leading
415     // underscore.
416     MangledName.clear();
417     MangledName.reserve(GV.getName().size() + 1);
418     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
419     return MustPreserveSymbols.count(MangledName);
420   };
421 
422   // Preserve linkonce value on linker request
423   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
424 
425   if (!ShouldInternalize)
426     return;
427 
428   if (ShouldRestoreGlobalsLinkage) {
429     // Record the linkage type of non-local symbols so they can be restored
430     // prior
431     // to module splitting.
432     auto RecordLinkage = [&](const GlobalValue &GV) {
433       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
434           GV.hasName())
435         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
436     };
437     for (auto &GV : *MergedModule)
438       RecordLinkage(GV);
439     for (auto &GV : MergedModule->globals())
440       RecordLinkage(GV);
441     for (auto &GV : MergedModule->aliases())
442       RecordLinkage(GV);
443   }
444 
445   // Update the llvm.compiler_used globals to force preserving libcalls and
446   // symbols referenced from asm
447   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
448 
449   internalizeModule(*MergedModule, mustPreserveGV);
450 
451   ScopeRestrictionsDone = true;
452 }
453 
454 /// Restore original linkage for symbols that may have been internalized
455 void LTOCodeGenerator::restoreLinkageForExternals() {
456   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
457     return;
458 
459   assert(ScopeRestrictionsDone &&
460          "Cannot externalize without internalization!");
461 
462   if (ExternalSymbols.empty())
463     return;
464 
465   auto externalize = [this](GlobalValue &GV) {
466     if (!GV.hasLocalLinkage() || !GV.hasName())
467       return;
468 
469     auto I = ExternalSymbols.find(GV.getName());
470     if (I == ExternalSymbols.end())
471       return;
472 
473     GV.setLinkage(I->second);
474   };
475 
476   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
477   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
478                 externalize);
479   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
480                 externalize);
481 }
482 
483 void LTOCodeGenerator::verifyMergedModuleOnce() {
484   // Only run on the first call.
485   if (HasVerifiedInput)
486     return;
487   HasVerifiedInput = true;
488 
489   bool BrokenDebugInfo = false;
490   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
491     report_fatal_error("Broken module found, compilation aborted!");
492   if (BrokenDebugInfo) {
493     emitWarning("Invalid debug info found, debug info will be stripped");
494     StripDebugInfo(*MergedModule);
495   }
496 }
497 
498 void LTOCodeGenerator::finishOptimizationRemarks() {
499   if (DiagnosticOutputFile) {
500     DiagnosticOutputFile->keep();
501     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
502     DiagnosticOutputFile->os().flush();
503   }
504 }
505 
506 /// Optimize merged modules using various IPO passes
507 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
508                                 bool DisableGVNLoadPRE,
509                                 bool DisableVectorization) {
510   if (!this->determineTarget())
511     return false;
512 
513   auto DiagFileOrErr = lto::setupOptimizationRemarks(
514       Context, LTORemarksFilename, LTOPassRemarksWithHotness);
515   if (!DiagFileOrErr) {
516     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
517     report_fatal_error("Can't get an output file for the remarks");
518   }
519   DiagnosticOutputFile = std::move(*DiagFileOrErr);
520 
521   // We always run the verifier once on the merged module, the `DisableVerify`
522   // parameter only applies to subsequent verify.
523   verifyMergedModuleOnce();
524 
525   // Mark which symbols can not be internalized
526   this->applyScopeRestrictions();
527 
528   // Instantiate the pass manager to organize the passes.
529   legacy::PassManager passes;
530 
531   // Add an appropriate DataLayout instance for this module...
532   MergedModule->setDataLayout(TargetMach->createDataLayout());
533 
534   passes.add(
535       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
536 
537   Triple TargetTriple(TargetMach->getTargetTriple());
538   PassManagerBuilder PMB;
539   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
540   PMB.LoopVectorize = !DisableVectorization;
541   PMB.SLPVectorize = !DisableVectorization;
542   if (!DisableInline)
543     PMB.Inliner = createFunctionInliningPass();
544   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
545   if (Freestanding)
546     PMB.LibraryInfo->disableAllFunctions();
547   PMB.OptLevel = OptLevel;
548   PMB.VerifyInput = !DisableVerify;
549   PMB.VerifyOutput = !DisableVerify;
550 
551   PMB.populateLTOPassManager(passes);
552 
553   // Run our queue of passes all at once now, efficiently.
554   passes.run(*MergedModule);
555 
556   return true;
557 }
558 
559 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
560   if (!this->determineTarget())
561     return false;
562 
563   // We always run the verifier once on the merged module.  If it has already
564   // been called in optimize(), this call will return early.
565   verifyMergedModuleOnce();
566 
567   legacy::PassManager preCodeGenPasses;
568 
569   // If the bitcode files contain ARC code and were compiled with optimization,
570   // the ObjCARCContractPass must be run, so do it unconditionally here.
571   preCodeGenPasses.add(createObjCARCContractPass());
572   preCodeGenPasses.run(*MergedModule);
573 
574   // Re-externalize globals that may have been internalized to increase scope
575   // for splitting
576   restoreLinkageForExternals();
577 
578   // Do code generation. We need to preserve the module in case the client calls
579   // writeMergedModules() after compilation, but we only need to allow this at
580   // parallelism level 1. This is achieved by having splitCodeGen return the
581   // original module at parallelism level 1 which we then assign back to
582   // MergedModule.
583   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
584                               [&]() { return createTargetMachine(); }, FileType,
585                               ShouldRestoreGlobalsLinkage);
586 
587   // If statistics were requested, print them out after codegen.
588   if (llvm::AreStatisticsEnabled())
589     llvm::PrintStatistics();
590   reportAndResetTimings();
591 
592   finishOptimizationRemarks();
593 
594   return true;
595 }
596 
597 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
598 /// LTO problems.
599 void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
600   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
601        o = getToken(o.second))
602     CodegenOptions.push_back(o.first);
603 }
604 
605 void LTOCodeGenerator::parseCodeGenDebugOptions() {
606   // if options were requested, set them
607   if (!CodegenOptions.empty()) {
608     // ParseCommandLineOptions() expects argv[0] to be program name.
609     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
610     for (std::string &Arg : CodegenOptions)
611       CodegenArgv.push_back(Arg.c_str());
612     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
613   }
614 }
615 
616 
617 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
618   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
619   lto_codegen_diagnostic_severity_t Severity;
620   switch (DI.getSeverity()) {
621   case DS_Error:
622     Severity = LTO_DS_ERROR;
623     break;
624   case DS_Warning:
625     Severity = LTO_DS_WARNING;
626     break;
627   case DS_Remark:
628     Severity = LTO_DS_REMARK;
629     break;
630   case DS_Note:
631     Severity = LTO_DS_NOTE;
632     break;
633   }
634   // Create the string that will be reported to the external diagnostic handler.
635   std::string MsgStorage;
636   raw_string_ostream Stream(MsgStorage);
637   DiagnosticPrinterRawOStream DP(Stream);
638   DI.print(DP);
639   Stream.flush();
640 
641   // If this method has been called it means someone has set up an external
642   // diagnostic handler. Assert on that.
643   assert(DiagHandler && "Invalid diagnostic handler");
644   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
645 }
646 
647 namespace {
648 struct LTODiagnosticHandler : public DiagnosticHandler {
649   LTOCodeGenerator *CodeGenerator;
650   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
651       : CodeGenerator(CodeGenPtr) {}
652   bool handleDiagnostics(const DiagnosticInfo &DI) override {
653     CodeGenerator->DiagnosticHandler(DI);
654     return true;
655   }
656 };
657 }
658 
659 void
660 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
661                                        void *Ctxt) {
662   this->DiagHandler = DiagHandler;
663   this->DiagContext = Ctxt;
664   if (!DiagHandler)
665     return Context.setDiagnosticHandler(nullptr);
666   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
667   // diagnostic to the external DiagHandler.
668   Context.setDiagnosticHandler(llvm::make_unique<LTODiagnosticHandler>(this),
669                                true);
670 }
671 
672 namespace {
673 class LTODiagnosticInfo : public DiagnosticInfo {
674   const Twine &Msg;
675 public:
676   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
677       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
678   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
679 };
680 }
681 
682 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
683   if (DiagHandler)
684     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
685   else
686     Context.diagnose(LTODiagnosticInfo(ErrMsg));
687 }
688 
689 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
690   if (DiagHandler)
691     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
692   else
693     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
694 }
695