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