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