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