xref: /freebsd-src/contrib/llvm-project/llvm/lib/LTO/LTOCodeGenerator.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/LTO/legacy/LTOCodeGenerator.h"
15 
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Bitcode/BitcodeWriter.h"
22 #include "llvm/CodeGen/ParallelCG.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/Config/config.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LLVMRemarkStreamer.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassTimingInfo.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LTO/LTO.h"
40 #include "llvm/LTO/LTOBackend.h"
41 #include "llvm/LTO/legacy/LTOModule.h"
42 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
43 #include "llvm/Linker/Linker.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/SubtargetFeature.h"
47 #include "llvm/MC/TargetRegistry.h"
48 #include "llvm/Remarks/HotnessThresholdParser.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/Host.h"
52 #include "llvm/Support/MemoryBuffer.h"
53 #include "llvm/Support/Signals.h"
54 #include "llvm/Support/TargetSelect.h"
55 #include "llvm/Support/ToolOutputFile.h"
56 #include "llvm/Support/YAMLTraits.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetOptions.h"
59 #include "llvm/Transforms/IPO.h"
60 #include "llvm/Transforms/IPO/Internalize.h"
61 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
62 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
63 #include "llvm/Transforms/ObjCARC.h"
64 #include "llvm/Transforms/Utils/ModuleUtils.h"
65 #include <system_error>
66 using namespace llvm;
67 
68 const char* LTOCodeGenerator::getVersionString() {
69 #ifdef LLVM_VERSION_INFO
70   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
71 #else
72   return PACKAGE_NAME " version " PACKAGE_VERSION;
73 #endif
74 }
75 
76 namespace llvm {
77 cl::opt<bool> LTODiscardValueNames(
78     "lto-discard-value-names",
79     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
80 #ifdef NDEBUG
81     cl::init(true),
82 #else
83     cl::init(false),
84 #endif
85     cl::Hidden);
86 
87 cl::opt<bool> RemarksWithHotness(
88     "lto-pass-remarks-with-hotness",
89     cl::desc("With PGO, include profile count in optimization remarks"),
90     cl::Hidden);
91 
92 cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
93     RemarksHotnessThreshold(
94         "lto-pass-remarks-hotness-threshold",
95         cl::desc("Minimum profile count required for an "
96                  "optimization remark to be output."
97                  " Use 'auto' to apply the threshold from profile summary."),
98         cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden);
99 
100 cl::opt<std::string>
101     RemarksFilename("lto-pass-remarks-output",
102                     cl::desc("Output filename for pass remarks"),
103                     cl::value_desc("filename"));
104 
105 cl::opt<std::string>
106     RemarksPasses("lto-pass-remarks-filter",
107                   cl::desc("Only record optimization remarks from passes whose "
108                            "names match the given regular expression"),
109                   cl::value_desc("regex"));
110 
111 cl::opt<std::string> RemarksFormat(
112     "lto-pass-remarks-format",
113     cl::desc("The format used for serializing remarks (default: YAML)"),
114     cl::value_desc("format"), cl::init("yaml"));
115 
116 cl::opt<std::string> LTOStatsFile(
117     "lto-stats-file",
118     cl::desc("Save statistics to the specified file"),
119     cl::Hidden);
120 }
121 
122 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
123     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
124       TheLinker(new Linker(*MergedModule)) {
125   Context.setDiscardValueNames(LTODiscardValueNames);
126   Context.enableDebugTypeODRUniquing();
127 
128   Config.CodeModel = None;
129   Config.StatsFile = LTOStatsFile;
130   Config.PreCodeGenPassesHook = [](legacy::PassManager &PM) {
131     PM.add(createObjCARCContractPass());
132   };
133 }
134 
135 LTOCodeGenerator::~LTOCodeGenerator() {}
136 
137 void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
138   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
139   for (int i = 0, e = undefs.size(); i != e; ++i)
140     AsmUndefinedRefs.insert(undefs[i]);
141 }
142 
143 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
144   assert(&Mod->getModule().getContext() == &Context &&
145          "Expected module in same context");
146 
147   bool ret = TheLinker->linkInModule(Mod->takeModule());
148   setAsmUndefinedRefs(Mod);
149 
150   // We've just changed the input, so let's make sure we verify it.
151   HasVerifiedInput = false;
152 
153   return !ret;
154 }
155 
156 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
157   assert(&Mod->getModule().getContext() == &Context &&
158          "Expected module in same context");
159 
160   AsmUndefinedRefs.clear();
161 
162   MergedModule = Mod->takeModule();
163   TheLinker = std::make_unique<Linker>(*MergedModule);
164   setAsmUndefinedRefs(&*Mod);
165 
166   // We've just changed the input, so let's make sure we verify it.
167   HasVerifiedInput = false;
168 }
169 
170 void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
171   Config.Options = Options;
172 }
173 
174 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
175   switch (Debug) {
176   case LTO_DEBUG_MODEL_NONE:
177     EmitDwarfDebugInfo = false;
178     return;
179 
180   case LTO_DEBUG_MODEL_DWARF:
181     EmitDwarfDebugInfo = true;
182     return;
183   }
184   llvm_unreachable("Unknown debug format!");
185 }
186 
187 void LTOCodeGenerator::setOptLevel(unsigned Level) {
188   Config.OptLevel = Level;
189   Config.PTO.LoopVectorization = Config.OptLevel > 1;
190   Config.PTO.SLPVectorization = Config.OptLevel > 1;
191   switch (Config.OptLevel) {
192   case 0:
193     Config.CGOptLevel = CodeGenOpt::None;
194     return;
195   case 1:
196     Config.CGOptLevel = CodeGenOpt::Less;
197     return;
198   case 2:
199     Config.CGOptLevel = CodeGenOpt::Default;
200     return;
201   case 3:
202     Config.CGOptLevel = CodeGenOpt::Aggressive;
203     return;
204   }
205   llvm_unreachable("Unknown optimization level!");
206 }
207 
208 bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
209   if (!determineTarget())
210     return false;
211 
212   // We always run the verifier once on the merged module.
213   verifyMergedModuleOnce();
214 
215   // mark which symbols can not be internalized
216   applyScopeRestrictions();
217 
218   // create output file
219   std::error_code EC;
220   ToolOutputFile Out(Path, EC, sys::fs::OF_None);
221   if (EC) {
222     std::string ErrMsg = "could not open bitcode file for writing: ";
223     ErrMsg += Path.str() + ": " + EC.message();
224     emitError(ErrMsg);
225     return false;
226   }
227 
228   // write bitcode to it
229   WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
230   Out.os().close();
231 
232   if (Out.os().has_error()) {
233     std::string ErrMsg = "could not write bitcode file: ";
234     ErrMsg += Path.str() + ": " + Out.os().error().message();
235     emitError(ErrMsg);
236     Out.os().clear_error();
237     return false;
238   }
239 
240   Out.keep();
241   return true;
242 }
243 
244 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
245   // make unique temp output file to put generated code
246   SmallString<128> Filename;
247 
248   auto AddStream = [&](size_t Task) -> std::unique_ptr<CachedFileStream> {
249     StringRef Extension(Config.CGFileType == CGFT_AssemblyFile ? "s" : "o");
250 
251     int FD;
252     std::error_code EC =
253         sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
254     if (EC)
255       emitError(EC.message());
256 
257     return std::make_unique<CachedFileStream>(
258         std::make_unique<llvm::raw_fd_ostream>(FD, true));
259   };
260 
261   bool genResult = compileOptimized(AddStream, 1);
262 
263   if (!genResult) {
264     sys::fs::remove(Twine(Filename));
265     return false;
266   }
267 
268   // If statistics were requested, save them to the specified file or
269   // print them out after codegen.
270   if (StatsFile)
271     PrintStatisticsJSON(StatsFile->os());
272   else if (AreStatisticsEnabled())
273     PrintStatistics();
274 
275   NativeObjectPath = Filename.c_str();
276   *Name = NativeObjectPath.c_str();
277   return true;
278 }
279 
280 std::unique_ptr<MemoryBuffer>
281 LTOCodeGenerator::compileOptimized() {
282   const char *name;
283   if (!compileOptimizedToFile(&name))
284     return nullptr;
285 
286   // read .o file into memory buffer
287   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(
288       name, /*IsText=*/false, /*RequiresNullTerminator=*/false);
289   if (std::error_code EC = BufferOrErr.getError()) {
290     emitError(EC.message());
291     sys::fs::remove(NativeObjectPath);
292     return nullptr;
293   }
294 
295   // remove temp files
296   sys::fs::remove(NativeObjectPath);
297 
298   return std::move(*BufferOrErr);
299 }
300 
301 bool LTOCodeGenerator::compile_to_file(const char **Name) {
302   if (!optimize())
303     return false;
304 
305   return compileOptimizedToFile(Name);
306 }
307 
308 std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compile() {
309   if (!optimize())
310     return nullptr;
311 
312   return compileOptimized();
313 }
314 
315 bool LTOCodeGenerator::determineTarget() {
316   if (TargetMach)
317     return true;
318 
319   TripleStr = MergedModule->getTargetTriple();
320   if (TripleStr.empty()) {
321     TripleStr = sys::getDefaultTargetTriple();
322     MergedModule->setTargetTriple(TripleStr);
323   }
324   llvm::Triple Triple(TripleStr);
325 
326   // create target machine from info for merged modules
327   std::string ErrMsg;
328   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
329   if (!MArch) {
330     emitError(ErrMsg);
331     return false;
332   }
333 
334   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
335   // the default set of features.
336   SubtargetFeatures Features(join(Config.MAttrs, ""));
337   Features.getDefaultSubtargetFeatures(Triple);
338   FeatureStr = Features.getString();
339   // Set a default CPU for Darwin triples.
340   if (Config.CPU.empty() && Triple.isOSDarwin()) {
341     if (Triple.getArch() == llvm::Triple::x86_64)
342       Config.CPU = "core2";
343     else if (Triple.getArch() == llvm::Triple::x86)
344       Config.CPU = "yonah";
345     else if (Triple.isArm64e())
346       Config.CPU = "apple-a12";
347     else if (Triple.getArch() == llvm::Triple::aarch64 ||
348              Triple.getArch() == llvm::Triple::aarch64_32)
349       Config.CPU = "cyclone";
350   }
351 
352   TargetMach = createTargetMachine();
353   assert(TargetMach && "Unable to create target machine");
354 
355   return true;
356 }
357 
358 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
359   assert(MArch && "MArch is not set!");
360   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
361       TripleStr, Config.CPU, FeatureStr, Config.Options, Config.RelocModel,
362       None, Config.CGOptLevel));
363 }
364 
365 // If a linkonce global is present in the MustPreserveSymbols, we need to make
366 // sure we honor this. To force the compiler to not drop it, we add it to the
367 // "llvm.compiler.used" global.
368 void LTOCodeGenerator::preserveDiscardableGVs(
369     Module &TheModule,
370     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
371   std::vector<GlobalValue *> Used;
372   auto mayPreserveGlobal = [&](GlobalValue &GV) {
373     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
374         !mustPreserveGV(GV))
375       return;
376     if (GV.hasAvailableExternallyLinkage())
377       return emitWarning(
378           (Twine("Linker asked to preserve available_externally global: '") +
379            GV.getName() + "'").str());
380     if (GV.hasInternalLinkage())
381       return emitWarning((Twine("Linker asked to preserve internal global: '") +
382                    GV.getName() + "'").str());
383     Used.push_back(&GV);
384   };
385   for (auto &GV : TheModule)
386     mayPreserveGlobal(GV);
387   for (auto &GV : TheModule.globals())
388     mayPreserveGlobal(GV);
389   for (auto &GV : TheModule.aliases())
390     mayPreserveGlobal(GV);
391 
392   if (Used.empty())
393     return;
394 
395   appendToCompilerUsed(TheModule, Used);
396 }
397 
398 void LTOCodeGenerator::applyScopeRestrictions() {
399   if (ScopeRestrictionsDone)
400     return;
401 
402   // Declare a callback for the internalize pass that will ask for every
403   // candidate GlobalValue if it can be internalized or not.
404   Mangler Mang;
405   SmallString<64> MangledName;
406   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
407     // Unnamed globals can't be mangled, but they can't be preserved either.
408     if (!GV.hasName())
409       return false;
410 
411     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
412     // with the linker supplied name, which on Darwin includes a leading
413     // underscore.
414     MangledName.clear();
415     MangledName.reserve(GV.getName().size() + 1);
416     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
417     return MustPreserveSymbols.count(MangledName);
418   };
419 
420   // Preserve linkonce value on linker request
421   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
422 
423   if (!ShouldInternalize)
424     return;
425 
426   if (ShouldRestoreGlobalsLinkage) {
427     // Record the linkage type of non-local symbols so they can be restored
428     // prior
429     // to module splitting.
430     auto RecordLinkage = [&](const GlobalValue &GV) {
431       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
432           GV.hasName())
433         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
434     };
435     for (auto &GV : *MergedModule)
436       RecordLinkage(GV);
437     for (auto &GV : MergedModule->globals())
438       RecordLinkage(GV);
439     for (auto &GV : MergedModule->aliases())
440       RecordLinkage(GV);
441   }
442 
443   // Update the llvm.compiler_used globals to force preserving libcalls and
444   // symbols referenced from asm
445   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
446 
447   internalizeModule(*MergedModule, mustPreserveGV);
448 
449   ScopeRestrictionsDone = true;
450 }
451 
452 /// Restore original linkage for symbols that may have been internalized
453 void LTOCodeGenerator::restoreLinkageForExternals() {
454   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
455     return;
456 
457   assert(ScopeRestrictionsDone &&
458          "Cannot externalize without internalization!");
459 
460   if (ExternalSymbols.empty())
461     return;
462 
463   auto externalize = [this](GlobalValue &GV) {
464     if (!GV.hasLocalLinkage() || !GV.hasName())
465       return;
466 
467     auto I = ExternalSymbols.find(GV.getName());
468     if (I == ExternalSymbols.end())
469       return;
470 
471     GV.setLinkage(I->second);
472   };
473 
474   llvm::for_each(MergedModule->functions(), externalize);
475   llvm::for_each(MergedModule->globals(), externalize);
476   llvm::for_each(MergedModule->aliases(), externalize);
477 }
478 
479 void LTOCodeGenerator::verifyMergedModuleOnce() {
480   // Only run on the first call.
481   if (HasVerifiedInput)
482     return;
483   HasVerifiedInput = true;
484 
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 
494 void LTOCodeGenerator::finishOptimizationRemarks() {
495   if (DiagnosticOutputFile) {
496     DiagnosticOutputFile->keep();
497     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
498     DiagnosticOutputFile->os().flush();
499   }
500 }
501 
502 /// Optimize merged modules using various IPO passes
503 bool LTOCodeGenerator::optimize() {
504   if (!this->determineTarget())
505     return false;
506 
507   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
508       Context, RemarksFilename, RemarksPasses, RemarksFormat,
509       RemarksWithHotness, RemarksHotnessThreshold);
510   if (!DiagFileOrErr) {
511     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
512     report_fatal_error("Can't get an output file for the remarks");
513   }
514   DiagnosticOutputFile = std::move(*DiagFileOrErr);
515 
516   // Setup output file to emit statistics.
517   auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
518   if (!StatsFileOrErr) {
519     errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
520     report_fatal_error("Can't get an output file for the statistics");
521   }
522   StatsFile = std::move(StatsFileOrErr.get());
523 
524   // Currently there is no support for enabling whole program visibility via a
525   // linker option in the old LTO API, but this call allows it to be specified
526   // via the internal option. Must be done before WPD invoked via the optimizer
527   // pipeline run below.
528   updateVCallVisibilityInModule(*MergedModule,
529                                 /* WholeProgramVisibilityEnabledInLTO */ false,
530                                 // FIXME: This needs linker information via a
531                                 // TBD new interface.
532                                 /* DynamicExportSymbols */ {});
533 
534   // We always run the verifier once on the merged module, the `DisableVerify`
535   // parameter only applies to subsequent verify.
536   verifyMergedModuleOnce();
537 
538   // Mark which symbols can not be internalized
539   this->applyScopeRestrictions();
540 
541   // Write LTOPostLink flag for passes that require all the modules.
542   MergedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
543 
544   // Add an appropriate DataLayout instance for this module...
545   MergedModule->setDataLayout(TargetMach->createDataLayout());
546 
547   ModuleSummaryIndex CombinedIndex(false);
548   TargetMach = createTargetMachine();
549   if (!opt(Config, TargetMach.get(), 0, *MergedModule, /*IsThinLTO=*/false,
550            /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
551            /*CmdArgs*/ std::vector<uint8_t>())) {
552     emitError("LTO middle-end optimizations failed");
553     return false;
554   }
555 
556   return true;
557 }
558 
559 bool LTOCodeGenerator::compileOptimized(AddStreamFn AddStream,
560                                         unsigned ParallelismLevel) {
561   if (!this->determineTarget())
562     return false;
563 
564   // We always run the verifier once on the merged module.  If it has already
565   // been called in optimize(), this call will return early.
566   verifyMergedModuleOnce();
567 
568   // Re-externalize globals that may have been internalized to increase scope
569   // for splitting
570   restoreLinkageForExternals();
571 
572   ModuleSummaryIndex CombinedIndex(false);
573 
574   Config.CodeGenOnly = true;
575   Error Err = backend(Config, AddStream, ParallelismLevel, *MergedModule,
576                       CombinedIndex);
577   assert(!Err && "unexpected code-generation failure");
578   (void)Err;
579 
580   // If statistics were requested, save them to the specified file or
581   // print them out after codegen.
582   if (StatsFile)
583     PrintStatisticsJSON(StatsFile->os());
584   else if (AreStatisticsEnabled())
585     PrintStatistics();
586 
587   reportAndResetTimings();
588 
589   finishOptimizationRemarks();
590 
591   return true;
592 }
593 
594 void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {
595   for (StringRef Option : Options)
596     CodegenOptions.push_back(Option.str());
597 }
598 
599 void LTOCodeGenerator::parseCodeGenDebugOptions() {
600   if (!CodegenOptions.empty())
601     llvm::parseCommandLineOptions(CodegenOptions);
602 }
603 
604 void llvm::parseCommandLineOptions(std::vector<std::string> &Options) {
605   if (!Options.empty()) {
606     // ParseCommandLineOptions() expects argv[0] to be program name.
607     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
608     for (std::string &Arg : Options)
609       CodegenArgv.push_back(Arg.c_str());
610     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
611   }
612 }
613 
614 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
615   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
616   lto_codegen_diagnostic_severity_t Severity;
617   switch (DI.getSeverity()) {
618   case DS_Error:
619     Severity = LTO_DS_ERROR;
620     break;
621   case DS_Warning:
622     Severity = LTO_DS_WARNING;
623     break;
624   case DS_Remark:
625     Severity = LTO_DS_REMARK;
626     break;
627   case DS_Note:
628     Severity = LTO_DS_NOTE;
629     break;
630   }
631   // Create the string that will be reported to the external diagnostic handler.
632   std::string MsgStorage;
633   raw_string_ostream Stream(MsgStorage);
634   DiagnosticPrinterRawOStream DP(Stream);
635   DI.print(DP);
636   Stream.flush();
637 
638   // If this method has been called it means someone has set up an external
639   // diagnostic handler. Assert on that.
640   assert(DiagHandler && "Invalid diagnostic handler");
641   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
642 }
643 
644 namespace {
645 struct LTODiagnosticHandler : public DiagnosticHandler {
646   LTOCodeGenerator *CodeGenerator;
647   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
648       : CodeGenerator(CodeGenPtr) {}
649   bool handleDiagnostics(const DiagnosticInfo &DI) override {
650     CodeGenerator->DiagnosticHandler(DI);
651     return true;
652   }
653 };
654 }
655 
656 void
657 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
658                                        void *Ctxt) {
659   this->DiagHandler = DiagHandler;
660   this->DiagContext = Ctxt;
661   if (!DiagHandler)
662     return Context.setDiagnosticHandler(nullptr);
663   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
664   // diagnostic to the external DiagHandler.
665   Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),
666                                true);
667 }
668 
669 namespace {
670 class LTODiagnosticInfo : public DiagnosticInfo {
671   const Twine &Msg;
672 public:
673   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
674       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
675   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
676 };
677 }
678 
679 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
680   if (DiagHandler)
681     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
682   else
683     Context.diagnose(LTODiagnosticInfo(ErrMsg));
684 }
685 
686 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
687   if (DiagHandler)
688     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
689   else
690     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
691 }
692