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