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