1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
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 "backend" phase of LTO, i.e. it performs
10 // optimization and code generation on a loaded module. It is generally used
11 // internally by the LTO class but can also be used independently, for example
12 // to implement a standalone ThinLTO backend.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/LTO/LTOBackend.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/CGSCCPassManager.h"
19 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/Bitcode/BitcodeWriter.h"
24 #include "llvm/IR/LLVMRemarkStreamer.h"
25 #include "llvm/IR/LegacyPassManager.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/LTO/LTO.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Object/ModuleSymbolTable.h"
31 #include "llvm/Passes/PassBuilder.h"
32 #include "llvm/Passes/PassPlugin.h"
33 #include "llvm/Passes/StandardInstrumentations.h"
34 #include "llvm/Support/Error.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Program.h"
39 #include "llvm/Support/SmallVectorMemoryBuffer.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/ThreadPool.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Transforms/IPO.h"
45 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
46 #include "llvm/Transforms/Scalar/LoopPassManager.h"
47 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
48 #include "llvm/Transforms/Utils/SplitModule.h"
49 
50 using namespace llvm;
51 using namespace lto;
52 
53 #define DEBUG_TYPE "lto-backend"
54 
55 enum class LTOBitcodeEmbedding {
56   DoNotEmbed = 0,
57   EmbedOptimized = 1,
58   EmbedPostMergePreOptimized = 2
59 };
60 
61 static cl::opt<LTOBitcodeEmbedding> EmbedBitcode(
62     "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
63     cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none",
64                           "Do not embed"),
65                clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized",
66                           "Embed after all optimization passes"),
67                clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized,
68                           "post-merge-pre-opt",
69                           "Embed post merge, but before optimizations")),
70     cl::desc("Embed LLVM bitcode in object files produced by LTO"));
71 
72 static cl::opt<bool> ThinLTOAssumeMerged(
73     "thinlto-assume-merged", cl::init(false),
74     cl::desc("Assume the input has already undergone ThinLTO function "
75              "importing and the other pre-optimization pipeline changes."));
76 
77 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
78   errs() << "failed to open " << Path << ": " << Msg << '\n';
79   errs().flush();
80   exit(1);
81 }
82 
83 Error Config::addSaveTemps(std::string OutputFileName,
84                            bool UseInputModulePath) {
85   ShouldDiscardValueNames = false;
86 
87   std::error_code EC;
88   ResolutionFile = std::make_unique<raw_fd_ostream>(
89       OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
90   if (EC) {
91     ResolutionFile.reset();
92     return errorCodeToError(EC);
93   }
94 
95   auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
96     // Keep track of the hook provided by the linker, which also needs to run.
97     ModuleHookFn LinkerHook = Hook;
98     Hook = [=](unsigned Task, const Module &M) {
99       // If the linker's hook returned false, we need to pass that result
100       // through.
101       if (LinkerHook && !LinkerHook(Task, M))
102         return false;
103 
104       std::string PathPrefix;
105       // If this is the combined module (not a ThinLTO backend compile) or the
106       // user hasn't requested using the input module's path, emit to a file
107       // named from the provided OutputFileName with the Task ID appended.
108       if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
109         PathPrefix = OutputFileName;
110         if (Task != (unsigned)-1)
111           PathPrefix += utostr(Task) + ".";
112       } else
113         PathPrefix = M.getModuleIdentifier() + ".";
114       std::string Path = PathPrefix + PathSuffix + ".bc";
115       std::error_code EC;
116       raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
117       // Because -save-temps is a debugging feature, we report the error
118       // directly and exit.
119       if (EC)
120         reportOpenError(Path, EC.message());
121       WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
122       return true;
123     };
124   };
125 
126   setHook("0.preopt", PreOptModuleHook);
127   setHook("1.promote", PostPromoteModuleHook);
128   setHook("2.internalize", PostInternalizeModuleHook);
129   setHook("3.import", PostImportModuleHook);
130   setHook("4.opt", PostOptModuleHook);
131   setHook("5.precodegen", PreCodeGenModuleHook);
132 
133   CombinedIndexHook =
134       [=](const ModuleSummaryIndex &Index,
135           const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
136         std::string Path = OutputFileName + "index.bc";
137         std::error_code EC;
138         raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
139         // Because -save-temps is a debugging feature, we report the error
140         // directly and exit.
141         if (EC)
142           reportOpenError(Path, EC.message());
143         WriteIndexToFile(Index, OS);
144 
145         Path = OutputFileName + "index.dot";
146         raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
147         if (EC)
148           reportOpenError(Path, EC.message());
149         Index.exportToDot(OSDot, GUIDPreservedSymbols);
150         return true;
151       };
152 
153   return Error::success();
154 }
155 
156 #define HANDLE_EXTENSION(Ext)                                                  \
157   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
158 #include "llvm/Support/Extension.def"
159 
160 static void RegisterPassPlugins(ArrayRef<std::string> PassPlugins,
161                                 PassBuilder &PB) {
162 #define HANDLE_EXTENSION(Ext)                                                  \
163   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
164 #include "llvm/Support/Extension.def"
165 
166   // Load requested pass plugins and let them register pass builder callbacks
167   for (auto &PluginFN : PassPlugins) {
168     auto PassPlugin = PassPlugin::Load(PluginFN);
169     if (!PassPlugin) {
170       errs() << "Failed to load passes from '" << PluginFN
171              << "'. Request ignored.\n";
172       continue;
173     }
174 
175     PassPlugin->registerPassBuilderCallbacks(PB);
176   }
177 }
178 
179 namespace {
180 
181 std::unique_ptr<TargetMachine>
182 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
183   StringRef TheTriple = M.getTargetTriple();
184   SubtargetFeatures Features;
185   Features.getDefaultSubtargetFeatures(Triple(TheTriple));
186   for (const std::string &A : Conf.MAttrs)
187     Features.AddFeature(A);
188 
189   Reloc::Model RelocModel;
190   if (Conf.RelocModel)
191     RelocModel = *Conf.RelocModel;
192   else
193     RelocModel =
194         M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
195 
196   Optional<CodeModel::Model> CodeModel;
197   if (Conf.CodeModel)
198     CodeModel = *Conf.CodeModel;
199   else
200     CodeModel = M.getCodeModel();
201 
202   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
203       TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
204       CodeModel, Conf.CGOptLevel));
205 }
206 
207 static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
208                            unsigned OptLevel, bool IsThinLTO,
209                            ModuleSummaryIndex *ExportSummary,
210                            const ModuleSummaryIndex *ImportSummary) {
211   Optional<PGOOptions> PGOOpt;
212   if (!Conf.SampleProfile.empty())
213     PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
214                         PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
215   else if (Conf.RunCSIRInstr) {
216     PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
217                         PGOOptions::IRUse, PGOOptions::CSIRInstr);
218   } else if (!Conf.CSIRProfile.empty()) {
219     PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
220                         PGOOptions::IRUse, PGOOptions::CSIRUse);
221   }
222 
223   PassInstrumentationCallbacks PIC;
224   StandardInstrumentations SI(Conf.DebugPassManager);
225   SI.registerCallbacks(PIC);
226   PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
227   AAManager AA;
228 
229   // Parse a custom AA pipeline if asked to.
230   if (auto Err = PB.parseAAPipeline(AA, "default"))
231     report_fatal_error("Error parsing default AA pipeline");
232 
233   RegisterPassPlugins(Conf.PassPlugins, PB);
234 
235   LoopAnalysisManager LAM(Conf.DebugPassManager);
236   FunctionAnalysisManager FAM(Conf.DebugPassManager);
237   CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
238   ModuleAnalysisManager MAM(Conf.DebugPassManager);
239 
240   // Register the AA manager first so that our version is the one used.
241   FAM.registerPass([&] { return std::move(AA); });
242 
243   // Register all the basic analyses with the managers.
244   PB.registerModuleAnalyses(MAM);
245   PB.registerCGSCCAnalyses(CGAM);
246   PB.registerFunctionAnalyses(FAM);
247   PB.registerLoopAnalyses(LAM);
248   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
249 
250   ModulePassManager MPM(Conf.DebugPassManager);
251   // FIXME (davide): verify the input.
252 
253   PassBuilder::OptimizationLevel OL;
254 
255   switch (OptLevel) {
256   default:
257     llvm_unreachable("Invalid optimization level");
258   case 0:
259     OL = PassBuilder::OptimizationLevel::O0;
260     break;
261   case 1:
262     OL = PassBuilder::OptimizationLevel::O1;
263     break;
264   case 2:
265     OL = PassBuilder::OptimizationLevel::O2;
266     break;
267   case 3:
268     OL = PassBuilder::OptimizationLevel::O3;
269     break;
270   }
271 
272   if (IsThinLTO)
273     MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
274                                          ImportSummary);
275   else
276     MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
277   MPM.run(Mod, MAM);
278 
279   // FIXME (davide): verify the output.
280 }
281 
282 static void runNewPMCustomPasses(const Config &Conf, Module &Mod,
283                                  TargetMachine *TM, std::string PipelineDesc,
284                                  std::string AAPipelineDesc,
285                                  bool DisableVerify) {
286   PassBuilder PB(TM);
287   AAManager AA;
288 
289   // Parse a custom AA pipeline if asked to.
290   if (!AAPipelineDesc.empty())
291     if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
292       report_fatal_error("unable to parse AA pipeline description '" +
293                          AAPipelineDesc + "': " + toString(std::move(Err)));
294 
295   RegisterPassPlugins(Conf.PassPlugins, PB);
296 
297   LoopAnalysisManager LAM;
298   FunctionAnalysisManager FAM;
299   CGSCCAnalysisManager CGAM;
300   ModuleAnalysisManager MAM;
301 
302   // Register the AA manager first so that our version is the one used.
303   FAM.registerPass([&] { return std::move(AA); });
304 
305   // Register all the basic analyses with the managers.
306   PB.registerModuleAnalyses(MAM);
307   PB.registerCGSCCAnalyses(CGAM);
308   PB.registerFunctionAnalyses(FAM);
309   PB.registerLoopAnalyses(LAM);
310   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
311 
312   ModulePassManager MPM;
313 
314   // Always verify the input.
315   MPM.addPass(VerifierPass());
316 
317   // Now, add all the passes we've been requested to.
318   if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
319     report_fatal_error("unable to parse pass pipeline description '" +
320                        PipelineDesc + "': " + toString(std::move(Err)));
321 
322   if (!DisableVerify)
323     MPM.addPass(VerifierPass());
324   MPM.run(Mod, MAM);
325 }
326 
327 static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
328                            bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
329                            const ModuleSummaryIndex *ImportSummary) {
330   legacy::PassManager passes;
331   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
332 
333   PassManagerBuilder PMB;
334   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
335   PMB.Inliner = createFunctionInliningPass();
336   PMB.ExportSummary = ExportSummary;
337   PMB.ImportSummary = ImportSummary;
338   // Unconditionally verify input since it is not verified before this
339   // point and has unknown origin.
340   PMB.VerifyInput = true;
341   PMB.VerifyOutput = !Conf.DisableVerify;
342   PMB.LoopVectorize = true;
343   PMB.SLPVectorize = true;
344   PMB.OptLevel = Conf.OptLevel;
345   PMB.PGOSampleUse = Conf.SampleProfile;
346   PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
347   if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
348     PMB.EnablePGOCSInstrUse = true;
349     PMB.PGOInstrUse = Conf.CSIRProfile;
350   }
351   if (IsThinLTO)
352     PMB.populateThinLTOPassManager(passes);
353   else
354     PMB.populateLTOPassManager(passes);
355   passes.run(Mod);
356 }
357 
358 bool opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
359          bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
360          const ModuleSummaryIndex *ImportSummary,
361          const std::vector<uint8_t> &CmdArgs) {
362   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
363     // FIXME: the motivation for capturing post-merge bitcode and command line
364     // is replicating the compilation environment from bitcode, without needing
365     // to understand the dependencies (the functions to be imported). This
366     // assumes a clang - based invocation, case in which we have the command
367     // line.
368     // It's not very clear how the above motivation would map in the
369     // linker-based case, so we currently don't plumb the command line args in
370     // that case.
371     if (CmdArgs.empty())
372       LLVM_DEBUG(
373           dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
374                     "command line arguments are not available");
375     llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
376                                /*EmbedBitcode*/ true,
377                                /*EmbedMarker*/ false,
378                                /*Cmdline*/ CmdArgs);
379   }
380   // FIXME: Plumb the combined index into the new pass manager.
381   if (!Conf.OptPipeline.empty())
382     runNewPMCustomPasses(Conf, Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
383                          Conf.DisableVerify);
384   else if (Conf.UseNewPM)
385     runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
386                    ImportSummary);
387   else
388     runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
389   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
390 }
391 
392 void codegen(const Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
393              unsigned Task, Module &Mod,
394              const ModuleSummaryIndex &CombinedIndex) {
395   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
396     return;
397 
398   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
399     llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
400                                /*EmbedBitcode*/ true,
401                                /*EmbedMarker*/ false,
402                                /*CmdArgs*/ std::vector<uint8_t>());
403 
404   std::unique_ptr<ToolOutputFile> DwoOut;
405   SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
406   if (!Conf.DwoDir.empty()) {
407     std::error_code EC;
408     if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
409       report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
410                          EC.message());
411 
412     DwoFile = Conf.DwoDir;
413     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
414     TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
415   } else
416     TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
417 
418   if (!DwoFile.empty()) {
419     std::error_code EC;
420     DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
421     if (EC)
422       report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
423   }
424 
425   auto Stream = AddStream(Task);
426   legacy::PassManager CodeGenPasses;
427   CodeGenPasses.add(
428       createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
429   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
430                               DwoOut ? &DwoOut->os() : nullptr,
431                               Conf.CGFileType))
432     report_fatal_error("Failed to setup codegen");
433   CodeGenPasses.run(Mod);
434 
435   if (DwoOut)
436     DwoOut->keep();
437 }
438 
439 void splitCodeGen(const Config &C, TargetMachine *TM, AddStreamFn AddStream,
440                   unsigned ParallelCodeGenParallelismLevel,
441                   std::unique_ptr<Module> Mod,
442                   const ModuleSummaryIndex &CombinedIndex) {
443   ThreadPool CodegenThreadPool(
444       heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
445   unsigned ThreadCount = 0;
446   const Target *T = &TM->getTarget();
447 
448   SplitModule(
449       std::move(Mod), ParallelCodeGenParallelismLevel,
450       [&](std::unique_ptr<Module> MPart) {
451         // We want to clone the module in a new context to multi-thread the
452         // codegen. We do it by serializing partition modules to bitcode
453         // (while still on the main thread, in order to avoid data races) and
454         // spinning up new threads which deserialize the partitions into
455         // separate contexts.
456         // FIXME: Provide a more direct way to do this in LLVM.
457         SmallString<0> BC;
458         raw_svector_ostream BCOS(BC);
459         WriteBitcodeToFile(*MPart, BCOS);
460 
461         // Enqueue the task
462         CodegenThreadPool.async(
463             [&](const SmallString<0> &BC, unsigned ThreadId) {
464               LTOLLVMContext Ctx(C);
465               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
466                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
467                   Ctx);
468               if (!MOrErr)
469                 report_fatal_error("Failed to read bitcode");
470               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
471 
472               std::unique_ptr<TargetMachine> TM =
473                   createTargetMachine(C, T, *MPartInCtx);
474 
475               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
476                       CombinedIndex);
477             },
478             // Pass BC using std::move to ensure that it get moved rather than
479             // copied into the thread's context.
480             std::move(BC), ThreadCount++);
481       },
482       false);
483 
484   // Because the inner lambda (which runs in a worker thread) captures our local
485   // variables, we need to wait for the worker threads to terminate before we
486   // can leave the function scope.
487   CodegenThreadPool.wait();
488 }
489 
490 Expected<const Target *> initAndLookupTarget(const Config &C, Module &Mod) {
491   if (!C.OverrideTriple.empty())
492     Mod.setTargetTriple(C.OverrideTriple);
493   else if (Mod.getTargetTriple().empty())
494     Mod.setTargetTriple(C.DefaultTriple);
495 
496   std::string Msg;
497   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
498   if (!T)
499     return make_error<StringError>(Msg, inconvertibleErrorCode());
500   return T;
501 }
502 }
503 
504 Error lto::finalizeOptimizationRemarks(
505     std::unique_ptr<ToolOutputFile> DiagOutputFile) {
506   // Make sure we flush the diagnostic remarks file in case the linker doesn't
507   // call the global destructors before exiting.
508   if (!DiagOutputFile)
509     return Error::success();
510   DiagOutputFile->keep();
511   DiagOutputFile->os().flush();
512   return Error::success();
513 }
514 
515 Error lto::backend(const Config &C, AddStreamFn AddStream,
516                    unsigned ParallelCodeGenParallelismLevel,
517                    std::unique_ptr<Module> Mod,
518                    ModuleSummaryIndex &CombinedIndex) {
519   Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
520   if (!TOrErr)
521     return TOrErr.takeError();
522 
523   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
524 
525   if (!C.CodeGenOnly) {
526     if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
527              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
528              /*CmdArgs*/ std::vector<uint8_t>()))
529       return Error::success();
530   }
531 
532   if (ParallelCodeGenParallelismLevel == 1) {
533     codegen(C, TM.get(), AddStream, 0, *Mod, CombinedIndex);
534   } else {
535     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
536                  std::move(Mod), CombinedIndex);
537   }
538   return Error::success();
539 }
540 
541 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
542                             const ModuleSummaryIndex &Index) {
543   std::vector<GlobalValue*> DeadGVs;
544   for (auto &GV : Mod.global_values())
545     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
546       if (!Index.isGlobalValueLive(GVS)) {
547         DeadGVs.push_back(&GV);
548         convertToDeclaration(GV);
549       }
550 
551   // Now that all dead bodies have been dropped, delete the actual objects
552   // themselves when possible.
553   for (GlobalValue *GV : DeadGVs) {
554     GV->removeDeadConstantUsers();
555     // Might reference something defined in native object (i.e. dropped a
556     // non-prevailing IR def, but we need to keep the declaration).
557     if (GV->use_empty())
558       GV->eraseFromParent();
559   }
560 }
561 
562 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
563                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
564                        const FunctionImporter::ImportMapTy &ImportList,
565                        const GVSummaryMapTy &DefinedGlobals,
566                        MapVector<StringRef, BitcodeModule> &ModuleMap,
567                        const std::vector<uint8_t> &CmdArgs) {
568   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
569   if (!TOrErr)
570     return TOrErr.takeError();
571 
572   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
573 
574   // Setup optimization remarks.
575   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
576       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
577       Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
578   if (!DiagFileOrErr)
579     return DiagFileOrErr.takeError();
580   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
581 
582   // Set the partial sample profile ratio in the profile summary module flag of
583   // the module, if applicable.
584   Mod.setPartialSampleProfileRatio(CombinedIndex);
585 
586   if (Conf.CodeGenOnly) {
587     codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
588     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
589   }
590 
591   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
592     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
593 
594   auto OptimizeAndCodegen =
595       [&](Module &Mod, TargetMachine *TM,
596           std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
597         if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
598                  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
599                  CmdArgs))
600           return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
601 
602         codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
603         return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
604       };
605 
606   if (ThinLTOAssumeMerged)
607     return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
608 
609   // When linking an ELF shared object, dso_local should be dropped. We
610   // conservatively do this for -fpic.
611   bool ClearDSOLocalOnDeclarations =
612       TM->getTargetTriple().isOSBinFormatELF() &&
613       TM->getRelocationModel() != Reloc::Static &&
614       Mod.getPIELevel() == PIELevel::Default;
615   renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
616 
617   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
618 
619   thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
620 
621   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
622     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
623 
624   if (!DefinedGlobals.empty())
625     thinLTOInternalizeModule(Mod, DefinedGlobals);
626 
627   if (Conf.PostInternalizeModuleHook &&
628       !Conf.PostInternalizeModuleHook(Task, Mod))
629     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
630 
631   auto ModuleLoader = [&](StringRef Identifier) {
632     assert(Mod.getContext().isODRUniquingDebugTypes() &&
633            "ODR Type uniquing should be enabled on the context");
634     auto I = ModuleMap.find(Identifier);
635     assert(I != ModuleMap.end());
636     return I->second.getLazyModule(Mod.getContext(),
637                                    /*ShouldLazyLoadMetadata=*/true,
638                                    /*IsImporting*/ true);
639   };
640 
641   FunctionImporter Importer(CombinedIndex, ModuleLoader,
642                             ClearDSOLocalOnDeclarations);
643   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
644     return Err;
645 
646   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
647     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
648 
649   return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
650 }
651 
652 BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
653   if (ThinLTOAssumeMerged && BMs.size() == 1)
654     return BMs.begin();
655 
656   for (BitcodeModule &BM : BMs) {
657     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
658     if (LTOInfo && LTOInfo->IsThinLTO)
659       return &BM;
660   }
661   return nullptr;
662 }
663 
664 Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
665   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
666   if (!BMsOrErr)
667     return BMsOrErr.takeError();
668 
669   // The bitcode file may contain multiple modules, we want the one that is
670   // marked as being the ThinLTO module.
671   if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
672     return *Bm;
673 
674   return make_error<StringError>("Could not find module summary",
675                                  inconvertibleErrorCode());
676 }
677 
678 bool lto::loadReferencedModules(
679     const Module &M, const ModuleSummaryIndex &CombinedIndex,
680     FunctionImporter::ImportMapTy &ImportList,
681     MapVector<llvm::StringRef, llvm::BitcodeModule> &ModuleMap,
682     std::vector<std::unique_ptr<llvm::MemoryBuffer>>
683         &OwnedImportsLifetimeManager) {
684   if (ThinLTOAssumeMerged)
685     return true;
686   // We can simply import the values mentioned in the combined index, since
687   // we should only invoke this using the individual indexes written out
688   // via a WriteIndexesThinBackend.
689   for (const auto &GlobalList : CombinedIndex) {
690     // Ignore entries for undefined references.
691     if (GlobalList.second.SummaryList.empty())
692       continue;
693 
694     auto GUID = GlobalList.first;
695     for (const auto &Summary : GlobalList.second.SummaryList) {
696       // Skip the summaries for the importing module. These are included to
697       // e.g. record required linkage changes.
698       if (Summary->modulePath() == M.getModuleIdentifier())
699         continue;
700       // Add an entry to provoke importing by thinBackend.
701       ImportList[Summary->modulePath()].insert(GUID);
702     }
703   }
704 
705   for (auto &I : ImportList) {
706     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
707         llvm::MemoryBuffer::getFile(I.first());
708     if (!MBOrErr) {
709       errs() << "Error loading imported file '" << I.first()
710              << "': " << MBOrErr.getError().message() << "\n";
711       return false;
712     }
713 
714     Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
715     if (!BMOrErr) {
716       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
717         errs() << "Error loading imported file '" << I.first()
718                << "': " << EIB.message() << '\n';
719       });
720       return false;
721     }
722     ModuleMap.insert({I.first(), *BMOrErr});
723     OwnedImportsLifetimeManager.push_back(std::move(*MBOrErr));
724   }
725   return true;
726 }