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 <system_error>
62 using namespace llvm;
63 
64 const char* LTOCodeGenerator::getVersionString() {
65 #ifdef LLVM_VERSION_INFO
66   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
67 #else
68   return PACKAGE_NAME " version " PACKAGE_VERSION;
69 #endif
70 }
71 
72 namespace llvm {
73 cl::opt<bool> LTODiscardValueNames(
74     "lto-discard-value-names",
75     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
76 #ifdef NDEBUG
77     cl::init(true),
78 #else
79     cl::init(false),
80 #endif
81     cl::Hidden);
82 
83 cl::opt<bool> LTOStripInvalidDebugInfo(
84     "lto-strip-invalid-debug-info",
85     cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
86 #ifdef NDEBUG
87     cl::init(true),
88 #else
89     cl::init(false),
90 #endif
91     cl::Hidden);
92 }
93 
94 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
95     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
96       TheLinker(new Linker(*MergedModule)) {
97   Context.setDiscardValueNames(LTODiscardValueNames);
98   Context.enableDebugTypeODRUniquing();
99   initializeLTOPasses();
100 }
101 
102 LTOCodeGenerator::~LTOCodeGenerator() {}
103 
104 // Initialize LTO passes. Please keep this function in sync with
105 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
106 // passes are initialized.
107 void LTOCodeGenerator::initializeLTOPasses() {
108   PassRegistry &R = *PassRegistry::getPassRegistry();
109 
110   initializeInternalizeLegacyPassPass(R);
111   initializeIPSCCPLegacyPassPass(R);
112   initializeGlobalOptLegacyPassPass(R);
113   initializeConstantMergeLegacyPassPass(R);
114   initializeDAHPass(R);
115   initializeInstructionCombiningPassPass(R);
116   initializeSimpleInlinerPass(R);
117   initializePruneEHPass(R);
118   initializeGlobalDCELegacyPassPass(R);
119   initializeArgPromotionPass(R);
120   initializeJumpThreadingPass(R);
121   initializeSROALegacyPassPass(R);
122   initializePostOrderFunctionAttrsLegacyPassPass(R);
123   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
124   initializeGlobalsAAWrapperPassPass(R);
125   initializeLegacyLICMPassPass(R);
126   initializeMergedLoadStoreMotionLegacyPassPass(R);
127   initializeGVNLegacyPassPass(R);
128   initializeMemCpyOptLegacyPassPass(R);
129   initializeDCELegacyPassPass(R);
130   initializeCFGSimplifyPassPass(R);
131 }
132 
133 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
134   const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
135   for (int i = 0, e = undefs.size(); i != e; ++i)
136     AsmUndefinedRefs[undefs[i]] = 1;
137 }
138 
139 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
140   assert(&Mod->getModule().getContext() == &Context &&
141          "Expected module in same context");
142 
143   bool ret = TheLinker->linkInModule(Mod->takeModule());
144   setAsmUndefinedRefs(Mod);
145 
146   // We've just changed the input, so let's make sure we verify it.
147   HasVerifiedInput = false;
148 
149   return !ret;
150 }
151 
152 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
153   assert(&Mod->getModule().getContext() == &Context &&
154          "Expected module in same context");
155 
156   AsmUndefinedRefs.clear();
157 
158   MergedModule = Mod->takeModule();
159   TheLinker = make_unique<Linker>(*MergedModule);
160   setAsmUndefinedRefs(&*Mod);
161 
162   // We've just changed the input, so let's make sure we verify it.
163   HasVerifiedInput = false;
164 }
165 
166 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
167   this->Options = Options;
168 }
169 
170 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
171   switch (Debug) {
172   case LTO_DEBUG_MODEL_NONE:
173     EmitDwarfDebugInfo = false;
174     return;
175 
176   case LTO_DEBUG_MODEL_DWARF:
177     EmitDwarfDebugInfo = true;
178     return;
179   }
180   llvm_unreachable("Unknown debug format!");
181 }
182 
183 void LTOCodeGenerator::setOptLevel(unsigned Level) {
184   OptLevel = Level;
185   switch (OptLevel) {
186   case 0:
187     CGOptLevel = CodeGenOpt::None;
188     return;
189   case 1:
190     CGOptLevel = CodeGenOpt::Less;
191     return;
192   case 2:
193     CGOptLevel = CodeGenOpt::Default;
194     return;
195   case 3:
196     CGOptLevel = CodeGenOpt::Aggressive;
197     return;
198   }
199   llvm_unreachable("Unknown optimization level!");
200 }
201 
202 bool LTOCodeGenerator::writeMergedModules(const char *Path) {
203   if (!determineTarget())
204     return false;
205 
206   // We always run the verifier once on the merged module.
207   verifyMergedModuleOnce();
208 
209   // mark which symbols can not be internalized
210   applyScopeRestrictions();
211 
212   // create output file
213   std::error_code EC;
214   tool_output_file Out(Path, EC, sys::fs::F_None);
215   if (EC) {
216     std::string ErrMsg = "could not open bitcode file for writing: ";
217     ErrMsg += Path;
218     emitError(ErrMsg);
219     return false;
220   }
221 
222   // write bitcode to it
223   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
224   Out.os().close();
225 
226   if (Out.os().has_error()) {
227     std::string ErrMsg = "could not write bitcode file: ";
228     ErrMsg += Path;
229     emitError(ErrMsg);
230     Out.os().clear_error();
231     return false;
232   }
233 
234   Out.keep();
235   return true;
236 }
237 
238 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
239   // make unique temp output file to put generated code
240   SmallString<128> Filename;
241   int FD;
242 
243   const char *Extension =
244       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
245 
246   std::error_code EC =
247       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
248   if (EC) {
249     emitError(EC.message());
250     return false;
251   }
252 
253   // generate object file
254   tool_output_file objFile(Filename.c_str(), FD);
255 
256   bool genResult = compileOptimized(&objFile.os());
257   objFile.os().close();
258   if (objFile.os().has_error()) {
259     objFile.os().clear_error();
260     sys::fs::remove(Twine(Filename));
261     return false;
262   }
263 
264   objFile.keep();
265   if (!genResult) {
266     sys::fs::remove(Twine(Filename));
267     return false;
268   }
269 
270   NativeObjectPath = Filename.c_str();
271   *Name = NativeObjectPath.c_str();
272   return true;
273 }
274 
275 std::unique_ptr<MemoryBuffer>
276 LTOCodeGenerator::compileOptimized() {
277   const char *name;
278   if (!compileOptimizedToFile(&name))
279     return nullptr;
280 
281   // read .o file into memory buffer
282   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
283       MemoryBuffer::getFile(name, -1, false);
284   if (std::error_code EC = BufferOrErr.getError()) {
285     emitError(EC.message());
286     sys::fs::remove(NativeObjectPath);
287     return nullptr;
288   }
289 
290   // remove temp files
291   sys::fs::remove(NativeObjectPath);
292 
293   return std::move(*BufferOrErr);
294 }
295 
296 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
297                                        bool DisableInline,
298                                        bool DisableGVNLoadPRE,
299                                        bool DisableVectorization) {
300   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
301                 DisableVectorization))
302     return false;
303 
304   return compileOptimizedToFile(Name);
305 }
306 
307 std::unique_ptr<MemoryBuffer>
308 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
309                           bool DisableGVNLoadPRE, bool DisableVectorization) {
310   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
311                 DisableVectorization))
312     return nullptr;
313 
314   return compileOptimized();
315 }
316 
317 bool LTOCodeGenerator::determineTarget() {
318   if (TargetMach)
319     return true;
320 
321   TripleStr = MergedModule->getTargetTriple();
322   if (TripleStr.empty()) {
323     TripleStr = sys::getDefaultTargetTriple();
324     MergedModule->setTargetTriple(TripleStr);
325   }
326   llvm::Triple Triple(TripleStr);
327 
328   // create target machine from info for merged modules
329   std::string ErrMsg;
330   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
331   if (!MArch) {
332     emitError(ErrMsg);
333     return false;
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   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   TargetMach = createTargetMachine();
352   return true;
353 }
354 
355 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
356   return std::unique_ptr<TargetMachine>(
357       MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
358                                  RelocModel, CodeModel::Default, CGOptLevel));
359 }
360 
361 // If a linkonce global is present in the MustPreserveSymbols, we need to make
362 // sure we honor this. To force the compiler to not drop it, we add it to the
363 // "llvm.compiler.used" global.
364 void LTOCodeGenerator::preserveDiscardableGVs(
365     Module &TheModule,
366     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
367   SetVector<Constant *> UsedValuesSet;
368   if (GlobalVariable *LLVMUsed =
369           TheModule.getGlobalVariable("llvm.compiler.used")) {
370     ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
371     for (auto &V : Inits->operands())
372       UsedValuesSet.insert(cast<Constant>(&V));
373     LLVMUsed->eraseFromParent();
374   }
375   llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(TheModule.getContext());
376   auto mayPreserveGlobal = [&](GlobalValue &GV) {
377     if (!GV.isDiscardableIfUnused() || GV.isDeclaration())
378       return;
379     if (!mustPreserveGV(GV))
380       return;
381     if (GV.hasAvailableExternallyLinkage()) {
382       emitWarning(
383           (Twine("Linker asked to preserve available_externally global: '") +
384            GV.getName() + "'").str());
385       return;
386     }
387     if (GV.hasInternalLinkage()) {
388       emitWarning((Twine("Linker asked to preserve internal global: '") +
389                    GV.getName() + "'").str());
390       return;
391     }
392     UsedValuesSet.insert(ConstantExpr::getBitCast(&GV, i8PTy));
393   };
394   for (auto &GV : TheModule)
395     mayPreserveGlobal(GV);
396   for (auto &GV : TheModule.globals())
397     mayPreserveGlobal(GV);
398   for (auto &GV : TheModule.aliases())
399     mayPreserveGlobal(GV);
400 
401   if (UsedValuesSet.empty())
402     return;
403 
404   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedValuesSet.size());
405   auto *LLVMUsed = new llvm::GlobalVariable(
406       TheModule, ATy, false, llvm::GlobalValue::AppendingLinkage,
407       llvm::ConstantArray::get(ATy, UsedValuesSet.getArrayRef()),
408       "llvm.compiler.used");
409   LLVMUsed->setSection("llvm.metadata");
410 }
411 
412 void LTOCodeGenerator::applyScopeRestrictions() {
413   if (ScopeRestrictionsDone)
414     return;
415 
416   // Declare a callback for the internalize pass that will ask for every
417   // candidate GlobalValue if it can be internalized or not.
418   SmallString<64> MangledName;
419   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
420     // Unnamed globals can't be mangled, but they can't be preserved either.
421     if (!GV.hasName())
422       return false;
423 
424     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
425     // with the linker supplied name, which on Darwin includes a leading
426     // underscore.
427     MangledName.clear();
428     MangledName.reserve(GV.getName().size() + 1);
429     Mangler::getNameWithPrefix(MangledName, GV.getName(),
430                                MergedModule->getDataLayout());
431     return MustPreserveSymbols.count(MangledName);
432   };
433 
434   // Preserve linkonce value on linker request
435   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
436 
437   if (!ShouldInternalize)
438     return;
439 
440   if (ShouldRestoreGlobalsLinkage) {
441     // Record the linkage type of non-local symbols so they can be restored
442     // prior
443     // to module splitting.
444     auto RecordLinkage = [&](const GlobalValue &GV) {
445       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
446           GV.hasName())
447         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
448     };
449     for (auto &GV : *MergedModule)
450       RecordLinkage(GV);
451     for (auto &GV : MergedModule->globals())
452       RecordLinkage(GV);
453     for (auto &GV : MergedModule->aliases())
454       RecordLinkage(GV);
455   }
456 
457   // Update the llvm.compiler_used globals to force preserving libcalls and
458   // symbols referenced from asm
459   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
460 
461   internalizeModule(*MergedModule, mustPreserveGV);
462 
463   ScopeRestrictionsDone = true;
464 }
465 
466 /// Restore original linkage for symbols that may have been internalized
467 void LTOCodeGenerator::restoreLinkageForExternals() {
468   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
469     return;
470 
471   assert(ScopeRestrictionsDone &&
472          "Cannot externalize without internalization!");
473 
474   if (ExternalSymbols.empty())
475     return;
476 
477   auto externalize = [this](GlobalValue &GV) {
478     if (!GV.hasLocalLinkage() || !GV.hasName())
479       return;
480 
481     auto I = ExternalSymbols.find(GV.getName());
482     if (I == ExternalSymbols.end())
483       return;
484 
485     GV.setLinkage(I->second);
486   };
487 
488   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
489   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
490                 externalize);
491   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
492                 externalize);
493 }
494 
495 void LTOCodeGenerator::verifyMergedModuleOnce() {
496   // Only run on the first call.
497   if (HasVerifiedInput)
498     return;
499   HasVerifiedInput = true;
500 
501   if (LTOStripInvalidDebugInfo) {
502     bool BrokenDebugInfo = false;
503     if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
504       report_fatal_error("Broken module found, compilation aborted!");
505     if (BrokenDebugInfo) {
506       emitWarning("Invalid debug info found, debug info will be stripped");
507       StripDebugInfo(*MergedModule);
508     }
509   }
510   if (verifyModule(*MergedModule, &dbgs()))
511     report_fatal_error("Broken module found, compilation aborted!");
512 }
513 
514 /// Optimize merged modules using various IPO passes
515 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
516                                 bool DisableGVNLoadPRE,
517                                 bool DisableVectorization) {
518   if (!this->determineTarget())
519     return false;
520 
521   // We always run the verifier once on the merged module, the `DisableVerify`
522   // parameter only applies to subsequent verify.
523   verifyMergedModuleOnce();
524 
525   // Mark which symbols can not be internalized
526   this->applyScopeRestrictions();
527 
528   // Instantiate the pass manager to organize the passes.
529   legacy::PassManager passes;
530 
531   // Add an appropriate DataLayout instance for this module...
532   MergedModule->setDataLayout(TargetMach->createDataLayout());
533 
534   passes.add(
535       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
536 
537   Triple TargetTriple(TargetMach->getTargetTriple());
538   PassManagerBuilder PMB;
539   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
540   PMB.LoopVectorize = !DisableVectorization;
541   PMB.SLPVectorize = !DisableVectorization;
542   if (!DisableInline)
543     PMB.Inliner = createFunctionInliningPass();
544   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
545   PMB.OptLevel = OptLevel;
546   PMB.VerifyInput = !DisableVerify;
547   PMB.VerifyOutput = !DisableVerify;
548 
549   PMB.populateLTOPassManager(passes);
550 
551   // Run our queue of passes all at once now, efficiently.
552   passes.run(*MergedModule);
553 
554   return true;
555 }
556 
557 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
558   if (!this->determineTarget())
559     return false;
560 
561   // We always run the verifier once on the merged module.  If it has already
562   // been called in optimize(), this call will return early.
563   verifyMergedModuleOnce();
564 
565   legacy::PassManager preCodeGenPasses;
566 
567   // If the bitcode files contain ARC code and were compiled with optimization,
568   // the ObjCARCContractPass must be run, so do it unconditionally here.
569   preCodeGenPasses.add(createObjCARCContractPass());
570   preCodeGenPasses.run(*MergedModule);
571 
572   // Re-externalize globals that may have been internalized to increase scope
573   // for splitting
574   restoreLinkageForExternals();
575 
576   // Do code generation. We need to preserve the module in case the client calls
577   // writeMergedModules() after compilation, but we only need to allow this at
578   // parallelism level 1. This is achieved by having splitCodeGen return the
579   // original module at parallelism level 1 which we then assign back to
580   // MergedModule.
581   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
582                               [&]() { return createTargetMachine(); }, FileType,
583                               ShouldRestoreGlobalsLinkage);
584 
585   // If statistics were requested, print them out after codegen.
586   if (llvm::AreStatisticsEnabled())
587     llvm::PrintStatistics();
588 
589   return true;
590 }
591 
592 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
593 /// LTO problems.
594 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
595   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
596        o = getToken(o.second))
597     CodegenOptions.push_back(o.first);
598 }
599 
600 void LTOCodeGenerator::parseCodeGenDebugOptions() {
601   // if options were requested, set them
602   if (!CodegenOptions.empty()) {
603     // ParseCommandLineOptions() expects argv[0] to be program name.
604     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
605     for (std::string &Arg : CodegenOptions)
606       CodegenArgv.push_back(Arg.c_str());
607     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
608   }
609 }
610 
611 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
612                                          void *Context) {
613   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
614 }
615 
616 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
617   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
618   lto_codegen_diagnostic_severity_t Severity;
619   switch (DI.getSeverity()) {
620   case DS_Error:
621     Severity = LTO_DS_ERROR;
622     break;
623   case DS_Warning:
624     Severity = LTO_DS_WARNING;
625     break;
626   case DS_Remark:
627     Severity = LTO_DS_REMARK;
628     break;
629   case DS_Note:
630     Severity = LTO_DS_NOTE;
631     break;
632   }
633   // Create the string that will be reported to the external diagnostic handler.
634   std::string MsgStorage;
635   raw_string_ostream Stream(MsgStorage);
636   DiagnosticPrinterRawOStream DP(Stream);
637   DI.print(DP);
638   Stream.flush();
639 
640   // If this method has been called it means someone has set up an external
641   // diagnostic handler. Assert on that.
642   assert(DiagHandler && "Invalid diagnostic handler");
643   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
644 }
645 
646 void
647 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
648                                        void *Ctxt) {
649   this->DiagHandler = DiagHandler;
650   this->DiagContext = Ctxt;
651   if (!DiagHandler)
652     return Context.setDiagnosticHandler(nullptr, nullptr);
653   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
654   // diagnostic to the external DiagHandler.
655   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
656                                /* RespectFilters */ true);
657 }
658 
659 namespace {
660 class LTODiagnosticInfo : public DiagnosticInfo {
661   const Twine &Msg;
662 public:
663   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
664       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
665   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
666 };
667 }
668 
669 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
670   if (DiagHandler)
671     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
672   else
673     Context.diagnose(LTODiagnosticInfo(ErrMsg));
674 }
675 
676 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
677   if (DiagHandler)
678     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
679   else
680     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
681 }
682