149ec6a4f372549aacb65c4ea6ee6ae40c53c5ef
[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 std::unique_ptr<MemoryBuffer>
254 LTOCodeGenerator::compileOptimized(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
268   // remove temp files
269   sys::fs::remove(NativeObjectPath);
270
271   return std::move(*BufferOrErr);
272 }
273
274
275 bool LTOCodeGenerator::compile_to_file(const char **name,
276                                        bool disableInline,
277                                        bool disableGVNLoadPRE,
278                                        bool disableVectorization,
279                                        std::string &errMsg) {
280   if (!optimize(disableInline, disableGVNLoadPRE,
281                 disableVectorization, errMsg))
282     return false;
283
284   return compileOptimizedToFile(name, errMsg);
285 }
286
287 std::unique_ptr<MemoryBuffer>
288 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
289                           bool disableVectorization, std::string &errMsg) {
290   if (!optimize(disableInline, disableGVNLoadPRE,
291                 disableVectorization, errMsg))
292     return nullptr;
293
294   return compileOptimized(errMsg);
295 }
296
297 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
298   if (TargetMach)
299     return true;
300
301   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
302   if (TripleStr.empty())
303     TripleStr = sys::getDefaultTargetTriple();
304   llvm::Triple Triple(TripleStr);
305
306   // create target machine from info for merged modules
307   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
308   if (!march)
309     return false;
310
311   // The relocation model is actually a static member of TargetMachine and
312   // needs to be set before the TargetMachine is instantiated.
313   Reloc::Model RelocModel = Reloc::Default;
314   switch (CodeModel) {
315   case LTO_CODEGEN_PIC_MODEL_STATIC:
316     RelocModel = Reloc::Static;
317     break;
318   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
319     RelocModel = Reloc::PIC_;
320     break;
321   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
322     RelocModel = Reloc::DynamicNoPIC;
323     break;
324   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
325     // RelocModel is already the default, so leave it that way.
326     break;
327   }
328
329   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
330   // the default set of features.
331   SubtargetFeatures Features(MAttr);
332   Features.getDefaultSubtargetFeatures(Triple);
333   std::string FeatureStr = Features.getString();
334   // Set a default CPU for Darwin triples.
335   if (MCpu.empty() && Triple.isOSDarwin()) {
336     if (Triple.getArch() == llvm::Triple::x86_64)
337       MCpu = "core2";
338     else if (Triple.getArch() == llvm::Triple::x86)
339       MCpu = "yonah";
340     else if (Triple.getArch() == llvm::Triple::aarch64)
341       MCpu = "cyclone";
342   }
343
344   CodeGenOpt::Level CGOptLevel;
345   switch (OptLevel) {
346   case 0:
347     CGOptLevel = CodeGenOpt::None;
348     break;
349   case 1:
350     CGOptLevel = CodeGenOpt::Less;
351     break;
352   case 2:
353     CGOptLevel = CodeGenOpt::Default;
354     break;
355   case 3:
356     CGOptLevel = CodeGenOpt::Aggressive;
357     break;
358   }
359
360   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
361                                           RelocModel, CodeModel::Default,
362                                           CGOptLevel);
363   return true;
364 }
365
366 void LTOCodeGenerator::
367 applyRestriction(GlobalValue &GV,
368                  ArrayRef<StringRef> Libcalls,
369                  std::vector<const char*> &MustPreserveList,
370                  SmallPtrSetImpl<GlobalValue*> &AsmUsed,
371                  Mangler &Mangler) {
372   // There are no restrictions to apply to declarations.
373   if (GV.isDeclaration())
374     return;
375
376   // There is nothing more restrictive than private linkage.
377   if (GV.hasPrivateLinkage())
378     return;
379
380   SmallString<64> Buffer;
381   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
382
383   if (MustPreserveSymbols.count(Buffer))
384     MustPreserveList.push_back(GV.getName().data());
385   if (AsmUndefinedRefs.count(Buffer))
386     AsmUsed.insert(&GV);
387
388   // Conservatively append user-supplied runtime library functions to
389   // llvm.compiler.used.  These could be internalized and deleted by
390   // optimizations like -globalopt, causing problems when later optimizations
391   // add new library calls (e.g., llvm.memset => memset and printf => puts).
392   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
393   if (isa<Function>(GV) &&
394       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
395     AsmUsed.insert(&GV);
396 }
397
398 static void findUsedValues(GlobalVariable *LLVMUsed,
399                            SmallPtrSetImpl<GlobalValue*> &UsedValues) {
400   if (!LLVMUsed) return;
401
402   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
403   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
404     if (GlobalValue *GV =
405         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
406       UsedValues.insert(GV);
407 }
408
409 // Collect names of runtime library functions. User-defined functions with the
410 // same names are added to llvm.compiler.used to prevent them from being
411 // deleted by optimizations.
412 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
413                                       const TargetLibraryInfo& TLI,
414                                       const Module &Mod,
415                                       const TargetMachine &TM) {
416   // TargetLibraryInfo has info on C runtime library calls on the current
417   // target.
418   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
419        I != E; ++I) {
420     LibFunc::Func F = static_cast<LibFunc::Func>(I);
421     if (TLI.has(F))
422       Libcalls.push_back(TLI.getName(F));
423   }
424
425   SmallPtrSet<const TargetLowering *, 1> TLSet;
426
427   for (const Function &F : Mod) {
428     const TargetLowering *Lowering =
429         TM.getSubtargetImpl(F)->getTargetLowering();
430
431     if (Lowering && TLSet.insert(Lowering).second)
432       // TargetLowering has info on library calls that CodeGen expects to be
433       // available, both from the C runtime and compiler-rt.
434       for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
435            I != E; ++I)
436         if (const char *Name =
437                 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
438           Libcalls.push_back(Name);
439   }
440
441   array_pod_sort(Libcalls.begin(), Libcalls.end());
442   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
443                  Libcalls.end());
444 }
445
446 void LTOCodeGenerator::applyScopeRestrictions() {
447   if (ScopeRestrictionsDone || !ShouldInternalize)
448     return;
449   Module *mergedModule = IRLinker.getModule();
450
451   // Start off with a verification pass.
452   legacy::PassManager passes;
453   passes.add(createVerifierPass());
454
455   // mark which symbols can not be internalized
456   Mangler Mangler;
457   std::vector<const char*> MustPreserveList;
458   SmallPtrSet<GlobalValue*, 8> AsmUsed;
459   std::vector<StringRef> Libcalls;
460   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
461   TargetLibraryInfo TLI(TLII);
462
463   accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
464
465   for (Module::iterator f = mergedModule->begin(),
466          e = mergedModule->end(); f != e; ++f)
467     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
468   for (Module::global_iterator v = mergedModule->global_begin(),
469          e = mergedModule->global_end(); v !=  e; ++v)
470     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
471   for (Module::alias_iterator a = mergedModule->alias_begin(),
472          e = mergedModule->alias_end(); a != e; ++a)
473     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
474
475   GlobalVariable *LLVMCompilerUsed =
476     mergedModule->getGlobalVariable("llvm.compiler.used");
477   findUsedValues(LLVMCompilerUsed, AsmUsed);
478   if (LLVMCompilerUsed)
479     LLVMCompilerUsed->eraseFromParent();
480
481   if (!AsmUsed.empty()) {
482     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
483     std::vector<Constant*> asmUsed2;
484     for (auto *GV : AsmUsed) {
485       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
486       asmUsed2.push_back(c);
487     }
488
489     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
490     LLVMCompilerUsed =
491       new llvm::GlobalVariable(*mergedModule, ATy, false,
492                                llvm::GlobalValue::AppendingLinkage,
493                                llvm::ConstantArray::get(ATy, asmUsed2),
494                                "llvm.compiler.used");
495
496     LLVMCompilerUsed->setSection("llvm.metadata");
497   }
498
499   passes.add(createInternalizePass(MustPreserveList));
500
501   // apply scope restrictions
502   passes.run(*mergedModule);
503
504   ScopeRestrictionsDone = true;
505 }
506
507 /// Optimize merged modules using various IPO passes
508 bool LTOCodeGenerator::optimize(bool DisableInline,
509                                 bool DisableGVNLoadPRE,
510                                 bool DisableVectorization,
511                                 std::string &errMsg) {
512   if (!this->determineTarget(errMsg))
513     return false;
514
515   Module *mergedModule = IRLinker.getModule();
516
517   // Mark which symbols can not be internalized
518   this->applyScopeRestrictions();
519
520   // Instantiate the pass manager to organize the passes.
521   legacy::PassManager passes;
522
523   // Add an appropriate DataLayout instance for this module...
524   mergedModule->setDataLayout(*TargetMach->getDataLayout());
525
526   passes.add(
527       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
528
529   Triple TargetTriple(TargetMach->getTargetTriple());
530   PassManagerBuilder PMB;
531   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
532   PMB.LoopVectorize = !DisableVectorization;
533   PMB.SLPVectorize = !DisableVectorization;
534   if (!DisableInline)
535     PMB.Inliner = createFunctionInliningPass();
536   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
537   PMB.OptLevel = OptLevel;
538   PMB.VerifyInput = true;
539   PMB.VerifyOutput = true;
540
541   PMB.populateLTOPassManager(passes);
542
543   // Run our queue of passes all at once now, efficiently.
544   passes.run(*mergedModule);
545
546   return true;
547 }
548
549 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
550                                         std::string &errMsg) {
551   if (!this->determineTarget(errMsg))
552     return false;
553
554   Module *mergedModule = IRLinker.getModule();
555
556   legacy::PassManager codeGenPasses;
557
558   // If the bitcode files contain ARC code and were compiled with optimization,
559   // the ObjCARCContractPass must be run, so do it unconditionally here.
560   codeGenPasses.add(createObjCARCContractPass());
561
562   if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
563                                       TargetMachine::CGFT_ObjectFile)) {
564     errMsg = "target file type not supported";
565     return false;
566   }
567
568   // Run the code generator, and write assembly file
569   codeGenPasses.run(*mergedModule);
570
571   return true;
572 }
573
574 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
575 /// LTO problems.
576 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
577   for (std::pair<StringRef, StringRef> o = getToken(options);
578        !o.first.empty(); o = getToken(o.second)) {
579     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
580     // that.
581     if (CodegenOptions.empty())
582       CodegenOptions.push_back(strdup("libLLVMLTO"));
583     CodegenOptions.push_back(strdup(o.first.str().c_str()));
584   }
585 }
586
587 void LTOCodeGenerator::parseCodeGenDebugOptions() {
588   // if options were requested, set them
589   if (!CodegenOptions.empty())
590     cl::ParseCommandLineOptions(CodegenOptions.size(),
591                                 const_cast<char **>(&CodegenOptions[0]));
592 }
593
594 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
595                                          void *Context) {
596   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
597 }
598
599 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
600   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
601   lto_codegen_diagnostic_severity_t Severity;
602   switch (DI.getSeverity()) {
603   case DS_Error:
604     Severity = LTO_DS_ERROR;
605     break;
606   case DS_Warning:
607     Severity = LTO_DS_WARNING;
608     break;
609   case DS_Remark:
610     Severity = LTO_DS_REMARK;
611     break;
612   case DS_Note:
613     Severity = LTO_DS_NOTE;
614     break;
615   }
616   // Create the string that will be reported to the external diagnostic handler.
617   std::string MsgStorage;
618   raw_string_ostream Stream(MsgStorage);
619   DiagnosticPrinterRawOStream DP(Stream);
620   DI.print(DP);
621   Stream.flush();
622
623   // If this method has been called it means someone has set up an external
624   // diagnostic handler. Assert on that.
625   assert(DiagHandler && "Invalid diagnostic handler");
626   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
627 }
628
629 void
630 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
631                                        void *Ctxt) {
632   this->DiagHandler = DiagHandler;
633   this->DiagContext = Ctxt;
634   if (!DiagHandler)
635     return Context.setDiagnosticHandler(nullptr, nullptr);
636   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
637   // diagnostic to the external DiagHandler.
638   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
639                                /* RespectFilters */ true);
640 }