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