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