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