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