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