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