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