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, bool DisableVerify,
330                                        bool DisableInline,
331                                        bool DisableGVNLoadPRE,
332                                        bool DisableVectorization) {
333   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
334                 DisableVectorization))
335     return false;
336 
337   return compileOptimizedToFile(Name);
338 }
339 
340 std::unique_ptr<MemoryBuffer>
341 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
342                           bool DisableGVNLoadPRE, bool DisableVectorization) {
343   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
344                 DisableVectorization))
345     return nullptr;
346 
347   return compileOptimized();
348 }
349 
350 bool LTOCodeGenerator::determineTarget() {
351   if (TargetMach)
352     return true;
353 
354   TripleStr = MergedModule->getTargetTriple();
355   if (TripleStr.empty()) {
356     TripleStr = sys::getDefaultTargetTriple();
357     MergedModule->setTargetTriple(TripleStr);
358   }
359   llvm::Triple Triple(TripleStr);
360 
361   // create target machine from info for merged modules
362   std::string ErrMsg;
363   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
364   if (!MArch) {
365     emitError(ErrMsg);
366     return false;
367   }
368 
369   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
370   // the default set of features.
371   SubtargetFeatures Features(MAttr);
372   Features.getDefaultSubtargetFeatures(Triple);
373   FeatureStr = Features.getString();
374   // Set a default CPU for Darwin triples.
375   if (MCpu.empty() && Triple.isOSDarwin()) {
376     if (Triple.getArch() == llvm::Triple::x86_64)
377       MCpu = "core2";
378     else if (Triple.getArch() == llvm::Triple::x86)
379       MCpu = "yonah";
380     else if (Triple.getArch() == llvm::Triple::aarch64 ||
381              Triple.getArch() == llvm::Triple::aarch64_32)
382       MCpu = "cyclone";
383   }
384 
385   TargetMach = createTargetMachine();
386   assert(TargetMach && "Unable to create target machine");
387 
388   return true;
389 }
390 
391 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
392   assert(MArch && "MArch is not set!");
393   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
394       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
395 }
396 
397 // If a linkonce global is present in the MustPreserveSymbols, we need to make
398 // sure we honor this. To force the compiler to not drop it, we add it to the
399 // "llvm.compiler.used" global.
400 void LTOCodeGenerator::preserveDiscardableGVs(
401     Module &TheModule,
402     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
403   std::vector<GlobalValue *> Used;
404   auto mayPreserveGlobal = [&](GlobalValue &GV) {
405     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
406         !mustPreserveGV(GV))
407       return;
408     if (GV.hasAvailableExternallyLinkage())
409       return emitWarning(
410           (Twine("Linker asked to preserve available_externally global: '") +
411            GV.getName() + "'").str());
412     if (GV.hasInternalLinkage())
413       return emitWarning((Twine("Linker asked to preserve internal global: '") +
414                    GV.getName() + "'").str());
415     Used.push_back(&GV);
416   };
417   for (auto &GV : TheModule)
418     mayPreserveGlobal(GV);
419   for (auto &GV : TheModule.globals())
420     mayPreserveGlobal(GV);
421   for (auto &GV : TheModule.aliases())
422     mayPreserveGlobal(GV);
423 
424   if (Used.empty())
425     return;
426 
427   appendToCompilerUsed(TheModule, Used);
428 }
429 
430 void LTOCodeGenerator::applyScopeRestrictions() {
431   if (ScopeRestrictionsDone)
432     return;
433 
434   // Declare a callback for the internalize pass that will ask for every
435   // candidate GlobalValue if it can be internalized or not.
436   Mangler Mang;
437   SmallString<64> MangledName;
438   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
439     // Unnamed globals can't be mangled, but they can't be preserved either.
440     if (!GV.hasName())
441       return false;
442 
443     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
444     // with the linker supplied name, which on Darwin includes a leading
445     // underscore.
446     MangledName.clear();
447     MangledName.reserve(GV.getName().size() + 1);
448     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
449     return MustPreserveSymbols.count(MangledName);
450   };
451 
452   // Preserve linkonce value on linker request
453   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
454 
455   if (!ShouldInternalize)
456     return;
457 
458   if (ShouldRestoreGlobalsLinkage) {
459     // Record the linkage type of non-local symbols so they can be restored
460     // prior
461     // to module splitting.
462     auto RecordLinkage = [&](const GlobalValue &GV) {
463       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
464           GV.hasName())
465         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
466     };
467     for (auto &GV : *MergedModule)
468       RecordLinkage(GV);
469     for (auto &GV : MergedModule->globals())
470       RecordLinkage(GV);
471     for (auto &GV : MergedModule->aliases())
472       RecordLinkage(GV);
473   }
474 
475   // Update the llvm.compiler_used globals to force preserving libcalls and
476   // symbols referenced from asm
477   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
478 
479   internalizeModule(*MergedModule, mustPreserveGV);
480 
481   ScopeRestrictionsDone = true;
482 }
483 
484 /// Restore original linkage for symbols that may have been internalized
485 void LTOCodeGenerator::restoreLinkageForExternals() {
486   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
487     return;
488 
489   assert(ScopeRestrictionsDone &&
490          "Cannot externalize without internalization!");
491 
492   if (ExternalSymbols.empty())
493     return;
494 
495   auto externalize = [this](GlobalValue &GV) {
496     if (!GV.hasLocalLinkage() || !GV.hasName())
497       return;
498 
499     auto I = ExternalSymbols.find(GV.getName());
500     if (I == ExternalSymbols.end())
501       return;
502 
503     GV.setLinkage(I->second);
504   };
505 
506   llvm::for_each(MergedModule->functions(), externalize);
507   llvm::for_each(MergedModule->globals(), externalize);
508   llvm::for_each(MergedModule->aliases(), externalize);
509 }
510 
511 void LTOCodeGenerator::verifyMergedModuleOnce() {
512   // Only run on the first call.
513   if (HasVerifiedInput)
514     return;
515   HasVerifiedInput = true;
516 
517   bool BrokenDebugInfo = false;
518   if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
519     report_fatal_error("Broken module found, compilation aborted!");
520   if (BrokenDebugInfo) {
521     emitWarning("Invalid debug info found, debug info will be stripped");
522     StripDebugInfo(*MergedModule);
523   }
524 }
525 
526 void LTOCodeGenerator::finishOptimizationRemarks() {
527   if (DiagnosticOutputFile) {
528     DiagnosticOutputFile->keep();
529     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
530     DiagnosticOutputFile->os().flush();
531   }
532 }
533 
534 /// Optimize merged modules using various IPO passes
535 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
536                                 bool DisableGVNLoadPRE,
537                                 bool DisableVectorization) {
538   if (!this->determineTarget())
539     return false;
540 
541   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
542       Context, RemarksFilename, RemarksPasses, RemarksFormat,
543       RemarksWithHotness, RemarksHotnessThreshold);
544   if (!DiagFileOrErr) {
545     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
546     report_fatal_error("Can't get an output file for the remarks");
547   }
548   DiagnosticOutputFile = std::move(*DiagFileOrErr);
549 
550   // Setup output file to emit statistics.
551   auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
552   if (!StatsFileOrErr) {
553     errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
554     report_fatal_error("Can't get an output file for the statistics");
555   }
556   StatsFile = std::move(StatsFileOrErr.get());
557 
558   // Currently there is no support for enabling whole program visibility via a
559   // linker option in the old LTO API, but this call allows it to be specified
560   // via the internal option. Must be done before WPD invoked via the optimizer
561   // pipeline run below.
562   updateVCallVisibilityInModule(*MergedModule,
563                                 /* WholeProgramVisibilityEnabledInLTO */ false);
564 
565   // We always run the verifier once on the merged module, the `DisableVerify`
566   // parameter only applies to subsequent verify.
567   verifyMergedModuleOnce();
568 
569   // Mark which symbols can not be internalized
570   this->applyScopeRestrictions();
571 
572   // Write LTOPostLink flag for passes that require all the modules.
573   MergedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
574 
575   // Instantiate the pass manager to organize the passes.
576   legacy::PassManager passes;
577 
578   // Add an appropriate DataLayout instance for this module...
579   MergedModule->setDataLayout(TargetMach->createDataLayout());
580 
581   passes.add(
582       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
583 
584   Triple TargetTriple(TargetMach->getTargetTriple());
585   PassManagerBuilder PMB;
586   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
587   PMB.LoopVectorize = !DisableVectorization;
588   PMB.SLPVectorize = !DisableVectorization;
589   if (!DisableInline)
590     PMB.Inliner = createFunctionInliningPass();
591   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
592   if (Freestanding)
593     PMB.LibraryInfo->disableAllFunctions();
594   PMB.OptLevel = OptLevel;
595   PMB.VerifyInput = !DisableVerify;
596   PMB.VerifyOutput = !DisableVerify;
597 
598   PMB.populateLTOPassManager(passes);
599 
600   // Run our queue of passes all at once now, efficiently.
601   passes.run(*MergedModule);
602 
603   return true;
604 }
605 
606 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
607   if (!this->determineTarget())
608     return false;
609 
610   // We always run the verifier once on the merged module.  If it has already
611   // been called in optimize(), this call will return early.
612   verifyMergedModuleOnce();
613 
614   legacy::PassManager preCodeGenPasses;
615 
616   // If the bitcode files contain ARC code and were compiled with optimization,
617   // the ObjCARCContractPass must be run, so do it unconditionally here.
618   preCodeGenPasses.add(createObjCARCContractPass());
619   preCodeGenPasses.run(*MergedModule);
620 
621   // Re-externalize globals that may have been internalized to increase scope
622   // for splitting
623   restoreLinkageForExternals();
624 
625   // Do code generation. We need to preserve the module in case the client calls
626   // writeMergedModules() after compilation, but we only need to allow this at
627   // parallelism level 1. This is achieved by having splitCodeGen return the
628   // original module at parallelism level 1 which we then assign back to
629   // MergedModule.
630   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
631                               [&]() { return createTargetMachine(); }, FileType,
632                               ShouldRestoreGlobalsLinkage);
633 
634   // If statistics were requested, save them to the specified file or
635   // print them out after codegen.
636   if (StatsFile)
637     PrintStatisticsJSON(StatsFile->os());
638   else if (AreStatisticsEnabled())
639     PrintStatistics();
640 
641   reportAndResetTimings();
642 
643   finishOptimizationRemarks();
644 
645   return true;
646 }
647 
648 void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {
649   for (StringRef Option : Options)
650     CodegenOptions.push_back(Option.str());
651 }
652 
653 void LTOCodeGenerator::parseCodeGenDebugOptions() {
654   // if options were requested, set them
655   if (!CodegenOptions.empty()) {
656     // ParseCommandLineOptions() expects argv[0] to be program name.
657     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
658     for (std::string &Arg : CodegenOptions)
659       CodegenArgv.push_back(Arg.c_str());
660     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
661   }
662 }
663 
664 
665 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
666   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
667   lto_codegen_diagnostic_severity_t Severity;
668   switch (DI.getSeverity()) {
669   case DS_Error:
670     Severity = LTO_DS_ERROR;
671     break;
672   case DS_Warning:
673     Severity = LTO_DS_WARNING;
674     break;
675   case DS_Remark:
676     Severity = LTO_DS_REMARK;
677     break;
678   case DS_Note:
679     Severity = LTO_DS_NOTE;
680     break;
681   }
682   // Create the string that will be reported to the external diagnostic handler.
683   std::string MsgStorage;
684   raw_string_ostream Stream(MsgStorage);
685   DiagnosticPrinterRawOStream DP(Stream);
686   DI.print(DP);
687   Stream.flush();
688 
689   // If this method has been called it means someone has set up an external
690   // diagnostic handler. Assert on that.
691   assert(DiagHandler && "Invalid diagnostic handler");
692   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
693 }
694 
695 namespace {
696 struct LTODiagnosticHandler : public DiagnosticHandler {
697   LTOCodeGenerator *CodeGenerator;
698   LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
699       : CodeGenerator(CodeGenPtr) {}
700   bool handleDiagnostics(const DiagnosticInfo &DI) override {
701     CodeGenerator->DiagnosticHandler(DI);
702     return true;
703   }
704 };
705 }
706 
707 void
708 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
709                                        void *Ctxt) {
710   this->DiagHandler = DiagHandler;
711   this->DiagContext = Ctxt;
712   if (!DiagHandler)
713     return Context.setDiagnosticHandler(nullptr);
714   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
715   // diagnostic to the external DiagHandler.
716   Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),
717                                true);
718 }
719 
720 namespace {
721 class LTODiagnosticInfo : public DiagnosticInfo {
722   const Twine &Msg;
723 public:
724   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
725       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
726   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
727 };
728 }
729 
730 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
731   if (DiagHandler)
732     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
733   else
734     Context.diagnose(LTODiagnosticInfo(ErrMsg));
735 }
736 
737 void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
738   if (DiagHandler)
739     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
740   else
741     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
742 }
743