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