xref: /freebsd-src/contrib/llvm-project/llvm/lib/LTO/LTOBackend.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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   if (TM)
233     TM->setPGOOption(PGOOpt);
234 
235   LoopAnalysisManager LAM;
236   FunctionAnalysisManager FAM;
237   CGSCCAnalysisManager CGAM;
238   ModuleAnalysisManager MAM;
239 
240   PassInstrumentationCallbacks PIC;
241   StandardInstrumentations SI(Conf.DebugPassManager);
242   SI.registerCallbacks(PIC, &FAM);
243   PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
244 
245   RegisterPassPlugins(Conf.PassPlugins, PB);
246 
247   std::unique_ptr<TargetLibraryInfoImpl> TLII(
248       new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
249   if (Conf.Freestanding)
250     TLII->disableAllFunctions();
251   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
252 
253   // Parse a custom AA pipeline if asked to.
254   if (!Conf.AAPipeline.empty()) {
255     AAManager AA;
256     if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
257       report_fatal_error(Twine("unable to parse AA pipeline description '") +
258                          Conf.AAPipeline + "': " + toString(std::move(Err)));
259     }
260     // Register the AA manager first so that our version is the one used.
261     FAM.registerPass([&] { return std::move(AA); });
262   }
263 
264   // Register all the basic analyses with the managers.
265   PB.registerModuleAnalyses(MAM);
266   PB.registerCGSCCAnalyses(CGAM);
267   PB.registerFunctionAnalyses(FAM);
268   PB.registerLoopAnalyses(LAM);
269   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
270 
271   ModulePassManager MPM;
272 
273   if (!Conf.DisableVerify)
274     MPM.addPass(VerifierPass());
275 
276   OptimizationLevel OL;
277 
278   switch (OptLevel) {
279   default:
280     llvm_unreachable("Invalid optimization level");
281   case 0:
282     OL = OptimizationLevel::O0;
283     break;
284   case 1:
285     OL = OptimizationLevel::O1;
286     break;
287   case 2:
288     OL = OptimizationLevel::O2;
289     break;
290   case 3:
291     OL = OptimizationLevel::O3;
292     break;
293   }
294 
295   // Parse a custom pipeline if asked to.
296   if (!Conf.OptPipeline.empty()) {
297     if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
298       report_fatal_error(Twine("unable to parse pass pipeline description '") +
299                          Conf.OptPipeline + "': " + toString(std::move(Err)));
300     }
301   } else if (IsThinLTO) {
302     MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
303   } else {
304     MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
305   }
306 
307   if (!Conf.DisableVerify)
308     MPM.addPass(VerifierPass());
309 
310   MPM.run(Mod, MAM);
311 }
312 
313 static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
314                            bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
315                            const ModuleSummaryIndex *ImportSummary) {
316   legacy::PassManager passes;
317   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
318 
319   PassManagerBuilder PMB;
320   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
321   if (Conf.Freestanding)
322     PMB.LibraryInfo->disableAllFunctions();
323   PMB.Inliner = createFunctionInliningPass();
324   PMB.ExportSummary = ExportSummary;
325   PMB.ImportSummary = ImportSummary;
326   // Unconditionally verify input since it is not verified before this
327   // point and has unknown origin.
328   PMB.VerifyInput = true;
329   PMB.VerifyOutput = !Conf.DisableVerify;
330   PMB.LoopVectorize = true;
331   PMB.SLPVectorize = true;
332   PMB.OptLevel = Conf.OptLevel;
333   PMB.PGOSampleUse = Conf.SampleProfile;
334   PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
335   if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
336     PMB.EnablePGOCSInstrUse = true;
337     PMB.PGOInstrUse = Conf.CSIRProfile;
338   }
339   if (IsThinLTO)
340     PMB.populateThinLTOPassManager(passes);
341   else
342     PMB.populateLTOPassManager(passes);
343   passes.run(Mod);
344 }
345 
346 bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
347               bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
348               const ModuleSummaryIndex *ImportSummary,
349               const std::vector<uint8_t> &CmdArgs) {
350   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
351     // FIXME: the motivation for capturing post-merge bitcode and command line
352     // is replicating the compilation environment from bitcode, without needing
353     // to understand the dependencies (the functions to be imported). This
354     // assumes a clang - based invocation, case in which we have the command
355     // line.
356     // It's not very clear how the above motivation would map in the
357     // linker-based case, so we currently don't plumb the command line args in
358     // that case.
359     if (CmdArgs.empty())
360       LLVM_DEBUG(
361           dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
362                     "command line arguments are not available");
363     llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
364                                /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
365                                /*Cmdline*/ CmdArgs);
366   }
367   // FIXME: Plumb the combined index into the new pass manager.
368   if (Conf.UseNewPM || !Conf.OptPipeline.empty()) {
369     runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
370                    ImportSummary);
371   } else {
372     runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
373   }
374   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
375 }
376 
377 static void codegen(const Config &Conf, TargetMachine *TM,
378                     AddStreamFn AddStream, unsigned Task, Module &Mod,
379                     const ModuleSummaryIndex &CombinedIndex) {
380   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
381     return;
382 
383   if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
384     llvm::EmbedBitcodeInModule(Mod, llvm::MemoryBufferRef(),
385                                /*EmbedBitcode*/ true,
386                                /*EmbedCmdline*/ false,
387                                /*CmdArgs*/ std::vector<uint8_t>());
388 
389   std::unique_ptr<ToolOutputFile> DwoOut;
390   SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
391   if (!Conf.DwoDir.empty()) {
392     std::error_code EC;
393     if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
394       report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
395                          ": " + EC.message());
396 
397     DwoFile = Conf.DwoDir;
398     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
399     TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
400   } else
401     TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
402 
403   if (!DwoFile.empty()) {
404     std::error_code EC;
405     DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
406     if (EC)
407       report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
408                          EC.message());
409   }
410 
411   Expected<std::unique_ptr<CachedFileStream>> StreamOrErr = AddStream(Task);
412   if (Error Err = StreamOrErr.takeError())
413     report_fatal_error(std::move(Err));
414   std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
415   TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
416 
417   legacy::PassManager CodeGenPasses;
418   CodeGenPasses.add(
419       createImmutableModuleSummaryIndexWrapperPass(&CombinedIndex));
420   if (Conf.PreCodeGenPassesHook)
421     Conf.PreCodeGenPassesHook(CodeGenPasses);
422   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
423                               DwoOut ? &DwoOut->os() : nullptr,
424                               Conf.CGFileType))
425     report_fatal_error("Failed to setup codegen");
426   CodeGenPasses.run(Mod);
427 
428   if (DwoOut)
429     DwoOut->keep();
430 }
431 
432 static void splitCodeGen(const Config &C, TargetMachine *TM,
433                          AddStreamFn AddStream,
434                          unsigned ParallelCodeGenParallelismLevel, Module &Mod,
435                          const ModuleSummaryIndex &CombinedIndex) {
436   ThreadPool CodegenThreadPool(
437       heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
438   unsigned ThreadCount = 0;
439   const Target *T = &TM->getTarget();
440 
441   SplitModule(
442       Mod, ParallelCodeGenParallelismLevel,
443       [&](std::unique_ptr<Module> MPart) {
444         // We want to clone the module in a new context to multi-thread the
445         // codegen. We do it by serializing partition modules to bitcode
446         // (while still on the main thread, in order to avoid data races) and
447         // spinning up new threads which deserialize the partitions into
448         // separate contexts.
449         // FIXME: Provide a more direct way to do this in LLVM.
450         SmallString<0> BC;
451         raw_svector_ostream BCOS(BC);
452         WriteBitcodeToFile(*MPart, BCOS);
453 
454         // Enqueue the task
455         CodegenThreadPool.async(
456             [&](const SmallString<0> &BC, unsigned ThreadId) {
457               LTOLLVMContext Ctx(C);
458               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
459                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
460                   Ctx);
461               if (!MOrErr)
462                 report_fatal_error("Failed to read bitcode");
463               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
464 
465               std::unique_ptr<TargetMachine> TM =
466                   createTargetMachine(C, T, *MPartInCtx);
467 
468               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
469                       CombinedIndex);
470             },
471             // Pass BC using std::move to ensure that it get moved rather than
472             // copied into the thread's context.
473             std::move(BC), ThreadCount++);
474       },
475       false);
476 
477   // Because the inner lambda (which runs in a worker thread) captures our local
478   // variables, we need to wait for the worker threads to terminate before we
479   // can leave the function scope.
480   CodegenThreadPool.wait();
481 }
482 
483 static Expected<const Target *> initAndLookupTarget(const Config &C,
484                                                     Module &Mod) {
485   if (!C.OverrideTriple.empty())
486     Mod.setTargetTriple(C.OverrideTriple);
487   else if (Mod.getTargetTriple().empty())
488     Mod.setTargetTriple(C.DefaultTriple);
489 
490   std::string Msg;
491   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
492   if (!T)
493     return make_error<StringError>(Msg, inconvertibleErrorCode());
494   return T;
495 }
496 
497 Error lto::finalizeOptimizationRemarks(
498     std::unique_ptr<ToolOutputFile> DiagOutputFile) {
499   // Make sure we flush the diagnostic remarks file in case the linker doesn't
500   // call the global destructors before exiting.
501   if (!DiagOutputFile)
502     return Error::success();
503   DiagOutputFile->keep();
504   DiagOutputFile->os().flush();
505   return Error::success();
506 }
507 
508 Error lto::backend(const Config &C, AddStreamFn AddStream,
509                    unsigned ParallelCodeGenParallelismLevel, Module &Mod,
510                    ModuleSummaryIndex &CombinedIndex) {
511   Expected<const Target *> TOrErr = initAndLookupTarget(C, Mod);
512   if (!TOrErr)
513     return TOrErr.takeError();
514 
515   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
516 
517   if (!C.CodeGenOnly) {
518     if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
519              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
520              /*CmdArgs*/ std::vector<uint8_t>()))
521       return Error::success();
522   }
523 
524   if (ParallelCodeGenParallelismLevel == 1) {
525     codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
526   } else {
527     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
528                  CombinedIndex);
529   }
530   return Error::success();
531 }
532 
533 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
534                             const ModuleSummaryIndex &Index) {
535   std::vector<GlobalValue*> DeadGVs;
536   for (auto &GV : Mod.global_values())
537     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
538       if (!Index.isGlobalValueLive(GVS)) {
539         DeadGVs.push_back(&GV);
540         convertToDeclaration(GV);
541       }
542 
543   // Now that all dead bodies have been dropped, delete the actual objects
544   // themselves when possible.
545   for (GlobalValue *GV : DeadGVs) {
546     GV->removeDeadConstantUsers();
547     // Might reference something defined in native object (i.e. dropped a
548     // non-prevailing IR def, but we need to keep the declaration).
549     if (GV->use_empty())
550       GV->eraseFromParent();
551   }
552 }
553 
554 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
555                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
556                        const FunctionImporter::ImportMapTy &ImportList,
557                        const GVSummaryMapTy &DefinedGlobals,
558                        MapVector<StringRef, BitcodeModule> *ModuleMap,
559                        const std::vector<uint8_t> &CmdArgs) {
560   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
561   if (!TOrErr)
562     return TOrErr.takeError();
563 
564   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
565 
566   // Setup optimization remarks.
567   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
568       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
569       Conf.RemarksFormat, Conf.RemarksWithHotness, Conf.RemarksHotnessThreshold,
570       Task);
571   if (!DiagFileOrErr)
572     return DiagFileOrErr.takeError();
573   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
574 
575   // Set the partial sample profile ratio in the profile summary module flag of
576   // the module, if applicable.
577   Mod.setPartialSampleProfileRatio(CombinedIndex);
578 
579   if (Conf.CodeGenOnly) {
580     codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
581     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
582   }
583 
584   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
585     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
586 
587   auto OptimizeAndCodegen =
588       [&](Module &Mod, TargetMachine *TM,
589           std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
590         if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
591                  /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
592                  CmdArgs))
593           return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
594 
595         codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
596         return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
597       };
598 
599   if (ThinLTOAssumeMerged)
600     return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
601 
602   // When linking an ELF shared object, dso_local should be dropped. We
603   // conservatively do this for -fpic.
604   bool ClearDSOLocalOnDeclarations =
605       TM->getTargetTriple().isOSBinFormatELF() &&
606       TM->getRelocationModel() != Reloc::Static &&
607       Mod.getPIELevel() == PIELevel::Default;
608   renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
609 
610   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
611 
612   thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
613 
614   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
615     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
616 
617   if (!DefinedGlobals.empty())
618     thinLTOInternalizeModule(Mod, DefinedGlobals);
619 
620   if (Conf.PostInternalizeModuleHook &&
621       !Conf.PostInternalizeModuleHook(Task, Mod))
622     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
623 
624   auto ModuleLoader = [&](StringRef Identifier) {
625     assert(Mod.getContext().isODRUniquingDebugTypes() &&
626            "ODR Type uniquing should be enabled on the context");
627     if (ModuleMap) {
628       auto I = ModuleMap->find(Identifier);
629       assert(I != ModuleMap->end());
630       return I->second.getLazyModule(Mod.getContext(),
631                                      /*ShouldLazyLoadMetadata=*/true,
632                                      /*IsImporting*/ true);
633     }
634 
635     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
636         llvm::MemoryBuffer::getFile(Identifier);
637     if (!MBOrErr)
638       return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
639           Twine("Error loading imported file ") + Identifier + " : ",
640           MBOrErr.getError()));
641 
642     Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
643     if (!BMOrErr)
644       return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
645           Twine("Error loading imported file ") + Identifier + " : " +
646               toString(BMOrErr.takeError()),
647           inconvertibleErrorCode()));
648 
649     Expected<std::unique_ptr<Module>> MOrErr =
650         BMOrErr->getLazyModule(Mod.getContext(),
651                                /*ShouldLazyLoadMetadata=*/true,
652                                /*IsImporting*/ true);
653     if (MOrErr)
654       (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
655     return MOrErr;
656   };
657 
658   FunctionImporter Importer(CombinedIndex, ModuleLoader,
659                             ClearDSOLocalOnDeclarations);
660   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
661     return Err;
662 
663   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
664     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
665 
666   return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
667 }
668 
669 BitcodeModule *lto::findThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
670   if (ThinLTOAssumeMerged && BMs.size() == 1)
671     return BMs.begin();
672 
673   for (BitcodeModule &BM : BMs) {
674     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
675     if (LTOInfo && LTOInfo->IsThinLTO)
676       return &BM;
677   }
678   return nullptr;
679 }
680 
681 Expected<BitcodeModule> lto::findThinLTOModule(MemoryBufferRef MBRef) {
682   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
683   if (!BMsOrErr)
684     return BMsOrErr.takeError();
685 
686   // The bitcode file may contain multiple modules, we want the one that is
687   // marked as being the ThinLTO module.
688   if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
689     return *Bm;
690 
691   return make_error<StringError>("Could not find module summary",
692                                  inconvertibleErrorCode());
693 }
694 
695 bool lto::initImportList(const Module &M,
696                          const ModuleSummaryIndex &CombinedIndex,
697                          FunctionImporter::ImportMapTy &ImportList) {
698   if (ThinLTOAssumeMerged)
699     return true;
700   // We can simply import the values mentioned in the combined index, since
701   // we should only invoke this using the individual indexes written out
702   // via a WriteIndexesThinBackend.
703   for (const auto &GlobalList : CombinedIndex) {
704     // Ignore entries for undefined references.
705     if (GlobalList.second.SummaryList.empty())
706       continue;
707 
708     auto GUID = GlobalList.first;
709     for (const auto &Summary : GlobalList.second.SummaryList) {
710       // Skip the summaries for the importing module. These are included to
711       // e.g. record required linkage changes.
712       if (Summary->modulePath() == M.getModuleIdentifier())
713         continue;
714       // Add an entry to provoke importing by thinBackend.
715       ImportList[Summary->modulePath()].insert(GUID);
716     }
717   }
718   return true;
719 }
720