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