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