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