1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the "backend" phase of LTO, i.e. it performs
11 // optimization and code generation on a loaded module. It is generally used
12 // internally by the LTO class but can also be used independently, for example
13 // to implement a standalone ThinLTO backend.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/LTO/LTOBackend.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/CGSCCPassManager.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/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/Object/ModuleSymbolTable.h"
30 #include "llvm/Passes/PassBuilder.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/Program.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/ThreadPool.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Transforms/IPO.h"
41 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
42 #include "llvm/Transforms/Scalar/LoopPassManager.h"
43 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
44 #include "llvm/Transforms/Utils/SplitModule.h"
45 
46 using namespace llvm;
47 using namespace lto;
48 
49 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
50   errs() << "failed to open " << Path << ": " << Msg << '\n';
51   errs().flush();
52   exit(1);
53 }
54 
55 Error Config::addSaveTemps(std::string OutputFileName,
56                            bool UseInputModulePath) {
57   ShouldDiscardValueNames = false;
58 
59   std::error_code EC;
60   ResolutionFile = llvm::make_unique<raw_fd_ostream>(
61       OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
62   if (EC)
63     return errorCodeToError(EC);
64 
65   auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
66     // Keep track of the hook provided by the linker, which also needs to run.
67     ModuleHookFn LinkerHook = Hook;
68     Hook = [=](unsigned Task, const Module &M) {
69       // If the linker's hook returned false, we need to pass that result
70       // through.
71       if (LinkerHook && !LinkerHook(Task, M))
72         return false;
73 
74       std::string PathPrefix;
75       // If this is the combined module (not a ThinLTO backend compile) or the
76       // user hasn't requested using the input module's path, emit to a file
77       // named from the provided OutputFileName with the Task ID appended.
78       if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
79         PathPrefix = OutputFileName;
80         if (Task != (unsigned)-1)
81           PathPrefix += utostr(Task) + ".";
82       } else
83         PathPrefix = M.getModuleIdentifier() + ".";
84       std::string Path = PathPrefix + PathSuffix + ".bc";
85       std::error_code EC;
86       raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
87       // Because -save-temps is a debugging feature, we report the error
88       // directly and exit.
89       if (EC)
90         reportOpenError(Path, EC.message());
91       WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
92       return true;
93     };
94   };
95 
96   setHook("0.preopt", PreOptModuleHook);
97   setHook("1.promote", PostPromoteModuleHook);
98   setHook("2.internalize", PostInternalizeModuleHook);
99   setHook("3.import", PostImportModuleHook);
100   setHook("4.opt", PostOptModuleHook);
101   setHook("5.precodegen", PreCodeGenModuleHook);
102 
103   CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
104     std::string Path = OutputFileName + "index.bc";
105     std::error_code EC;
106     raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
107     // Because -save-temps is a debugging feature, we report the error
108     // directly and exit.
109     if (EC)
110       reportOpenError(Path, EC.message());
111     WriteIndexToFile(Index, OS);
112 
113     Path = OutputFileName + "index.dot";
114     raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
115     if (EC)
116       reportOpenError(Path, EC.message());
117     Index.exportToDot(OSDot);
118     return true;
119   };
120 
121   return Error::success();
122 }
123 
124 namespace {
125 
126 std::unique_ptr<TargetMachine>
127 createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
128   StringRef TheTriple = M.getTargetTriple();
129   SubtargetFeatures Features;
130   Features.getDefaultSubtargetFeatures(Triple(TheTriple));
131   for (const std::string &A : Conf.MAttrs)
132     Features.AddFeature(A);
133 
134   Reloc::Model RelocModel;
135   if (Conf.RelocModel)
136     RelocModel = *Conf.RelocModel;
137   else
138     RelocModel =
139         M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
140 
141   Optional<CodeModel::Model> CodeModel;
142   if (Conf.CodeModel)
143     CodeModel = *Conf.CodeModel;
144   else
145     CodeModel = M.getCodeModel();
146 
147   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
148       TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
149       CodeModel, Conf.CGOptLevel));
150 }
151 
152 static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
153                            unsigned OptLevel, bool IsThinLTO,
154                            ModuleSummaryIndex *ExportSummary,
155                            const ModuleSummaryIndex *ImportSummary) {
156   Optional<PGOOptions> PGOOpt;
157   if (!Conf.SampleProfile.empty())
158     PGOOpt = PGOOptions("", "", Conf.SampleProfile, false, true);
159 
160   PassBuilder PB(TM, PGOOpt);
161   AAManager AA;
162 
163   // Parse a custom AA pipeline if asked to.
164   if (!PB.parseAAPipeline(AA, "default"))
165     report_fatal_error("Error parsing default AA pipeline");
166 
167   LoopAnalysisManager LAM(Conf.DebugPassManager);
168   FunctionAnalysisManager FAM(Conf.DebugPassManager);
169   CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
170   ModuleAnalysisManager MAM(Conf.DebugPassManager);
171 
172   // Register the AA manager first so that our version is the one used.
173   FAM.registerPass([&] { return std::move(AA); });
174 
175   // Register all the basic analyses with the managers.
176   PB.registerModuleAnalyses(MAM);
177   PB.registerCGSCCAnalyses(CGAM);
178   PB.registerFunctionAnalyses(FAM);
179   PB.registerLoopAnalyses(LAM);
180   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
181 
182   ModulePassManager MPM(Conf.DebugPassManager);
183   // FIXME (davide): verify the input.
184 
185   PassBuilder::OptimizationLevel OL;
186 
187   switch (OptLevel) {
188   default:
189     llvm_unreachable("Invalid optimization level");
190   case 0:
191     OL = PassBuilder::O0;
192     break;
193   case 1:
194     OL = PassBuilder::O1;
195     break;
196   case 2:
197     OL = PassBuilder::O2;
198     break;
199   case 3:
200     OL = PassBuilder::O3;
201     break;
202   }
203 
204   if (IsThinLTO)
205     MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
206                                          ImportSummary);
207   else
208     MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
209   MPM.run(Mod, MAM);
210 
211   // FIXME (davide): verify the output.
212 }
213 
214 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
215                                  std::string PipelineDesc,
216                                  std::string AAPipelineDesc,
217                                  bool DisableVerify) {
218   PassBuilder PB(TM);
219   AAManager AA;
220 
221   // Parse a custom AA pipeline if asked to.
222   if (!AAPipelineDesc.empty())
223     if (!PB.parseAAPipeline(AA, AAPipelineDesc))
224       report_fatal_error("unable to parse AA pipeline description: " +
225                          AAPipelineDesc);
226 
227   LoopAnalysisManager LAM;
228   FunctionAnalysisManager FAM;
229   CGSCCAnalysisManager CGAM;
230   ModuleAnalysisManager MAM;
231 
232   // Register the AA manager first so that our version is the one used.
233   FAM.registerPass([&] { return std::move(AA); });
234 
235   // Register all the basic analyses with the managers.
236   PB.registerModuleAnalyses(MAM);
237   PB.registerCGSCCAnalyses(CGAM);
238   PB.registerFunctionAnalyses(FAM);
239   PB.registerLoopAnalyses(LAM);
240   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
241 
242   ModulePassManager MPM;
243 
244   // Always verify the input.
245   MPM.addPass(VerifierPass());
246 
247   // Now, add all the passes we've been requested to.
248   if (!PB.parsePassPipeline(MPM, PipelineDesc))
249     report_fatal_error("unable to parse pass pipeline description: " +
250                        PipelineDesc);
251 
252   if (!DisableVerify)
253     MPM.addPass(VerifierPass());
254   MPM.run(Mod, MAM);
255 }
256 
257 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
258                            bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
259                            const ModuleSummaryIndex *ImportSummary) {
260   legacy::PassManager passes;
261   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
262 
263   PassManagerBuilder PMB;
264   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
265   PMB.Inliner = createFunctionInliningPass();
266   PMB.ExportSummary = ExportSummary;
267   PMB.ImportSummary = ImportSummary;
268   // Unconditionally verify input since it is not verified before this
269   // point and has unknown origin.
270   PMB.VerifyInput = true;
271   PMB.VerifyOutput = !Conf.DisableVerify;
272   PMB.LoopVectorize = true;
273   PMB.SLPVectorize = true;
274   PMB.OptLevel = Conf.OptLevel;
275   PMB.PGOSampleUse = Conf.SampleProfile;
276   if (IsThinLTO)
277     PMB.populateThinLTOPassManager(passes);
278   else
279     PMB.populateLTOPassManager(passes);
280   passes.run(Mod);
281 }
282 
283 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
284          bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
285          const ModuleSummaryIndex *ImportSummary) {
286   // FIXME: Plumb the combined index into the new pass manager.
287   if (!Conf.OptPipeline.empty())
288     runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
289                          Conf.DisableVerify);
290   else if (Conf.UseNewPM)
291     runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
292                    ImportSummary);
293   else
294     runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
295   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
296 }
297 
298 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
299              unsigned Task, Module &Mod) {
300   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
301     return;
302 
303   std::unique_ptr<ToolOutputFile> DwoOut;
304   SmallString<1024> DwoFile(Conf.DwoPath);
305   if (!Conf.DwoDir.empty()) {
306     std::error_code EC;
307     if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
308       report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
309                          EC.message());
310 
311     DwoFile = Conf.DwoDir;
312     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
313   }
314 
315   if (!DwoFile.empty()) {
316     std::error_code EC;
317     TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
318     DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
319     if (EC)
320       report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
321   }
322 
323   auto Stream = AddStream(Task);
324   legacy::PassManager CodeGenPasses;
325   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
326                               DwoOut ? &DwoOut->os() : nullptr,
327                               Conf.CGFileType))
328     report_fatal_error("Failed to setup codegen");
329   CodeGenPasses.run(Mod);
330 
331   if (DwoOut)
332     DwoOut->keep();
333 }
334 
335 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
336                   unsigned ParallelCodeGenParallelismLevel,
337                   std::unique_ptr<Module> Mod) {
338   ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
339   unsigned ThreadCount = 0;
340   const Target *T = &TM->getTarget();
341 
342   SplitModule(
343       std::move(Mod), ParallelCodeGenParallelismLevel,
344       [&](std::unique_ptr<Module> MPart) {
345         // We want to clone the module in a new context to multi-thread the
346         // codegen. We do it by serializing partition modules to bitcode
347         // (while still on the main thread, in order to avoid data races) and
348         // spinning up new threads which deserialize the partitions into
349         // separate contexts.
350         // FIXME: Provide a more direct way to do this in LLVM.
351         SmallString<0> BC;
352         raw_svector_ostream BCOS(BC);
353         WriteBitcodeToFile(*MPart, BCOS);
354 
355         // Enqueue the task
356         CodegenThreadPool.async(
357             [&](const SmallString<0> &BC, unsigned ThreadId) {
358               LTOLLVMContext Ctx(C);
359               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
360                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
361                   Ctx);
362               if (!MOrErr)
363                 report_fatal_error("Failed to read bitcode");
364               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
365 
366               std::unique_ptr<TargetMachine> TM =
367                   createTargetMachine(C, T, *MPartInCtx);
368 
369               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
370             },
371             // Pass BC using std::move to ensure that it get moved rather than
372             // copied into the thread's context.
373             std::move(BC), ThreadCount++);
374       },
375       false);
376 
377   // Because the inner lambda (which runs in a worker thread) captures our local
378   // variables, we need to wait for the worker threads to terminate before we
379   // can leave the function scope.
380   CodegenThreadPool.wait();
381 }
382 
383 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
384   if (!C.OverrideTriple.empty())
385     Mod.setTargetTriple(C.OverrideTriple);
386   else if (Mod.getTargetTriple().empty())
387     Mod.setTargetTriple(C.DefaultTriple);
388 
389   std::string Msg;
390   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
391   if (!T)
392     return make_error<StringError>(Msg, inconvertibleErrorCode());
393   return T;
394 }
395 
396 }
397 
398 static Error
399 finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
400   // Make sure we flush the diagnostic remarks file in case the linker doesn't
401   // call the global destructors before exiting.
402   if (!DiagOutputFile)
403     return Error::success();
404   DiagOutputFile->keep();
405   DiagOutputFile->os().flush();
406   return Error::success();
407 }
408 
409 Error lto::backend(Config &C, AddStreamFn AddStream,
410                    unsigned ParallelCodeGenParallelismLevel,
411                    std::unique_ptr<Module> Mod,
412                    ModuleSummaryIndex &CombinedIndex) {
413   Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
414   if (!TOrErr)
415     return TOrErr.takeError();
416 
417   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
418 
419   // Setup optimization remarks.
420   auto DiagFileOrErr = lto::setupOptimizationRemarks(
421       Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
422   if (!DiagFileOrErr)
423     return DiagFileOrErr.takeError();
424   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
425 
426   if (!C.CodeGenOnly) {
427     if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
428              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
429       return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
430   }
431 
432   if (ParallelCodeGenParallelismLevel == 1) {
433     codegen(C, TM.get(), AddStream, 0, *Mod);
434   } else {
435     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
436                  std::move(Mod));
437   }
438   return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
439 }
440 
441 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
442                             const ModuleSummaryIndex &Index) {
443   std::vector<GlobalValue*> DeadGVs;
444   for (auto &GV : Mod.global_values())
445     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
446       if (!Index.isGlobalValueLive(GVS)) {
447         DeadGVs.push_back(&GV);
448         convertToDeclaration(GV);
449       }
450 
451   // Now that all dead bodies have been dropped, delete the actual objects
452   // themselves when possible.
453   for (GlobalValue *GV : DeadGVs) {
454     GV->removeDeadConstantUsers();
455     // Might reference something defined in native object (i.e. dropped a
456     // non-prevailing IR def, but we need to keep the declaration).
457     if (GV->use_empty())
458       GV->eraseFromParent();
459   }
460 }
461 
462 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
463                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
464                        const FunctionImporter::ImportMapTy &ImportList,
465                        const GVSummaryMapTy &DefinedGlobals,
466                        MapVector<StringRef, BitcodeModule> &ModuleMap) {
467   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
468   if (!TOrErr)
469     return TOrErr.takeError();
470 
471   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
472 
473   // Setup optimization remarks.
474   auto DiagFileOrErr = lto::setupOptimizationRemarks(
475       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
476   if (!DiagFileOrErr)
477     return DiagFileOrErr.takeError();
478   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
479 
480   if (Conf.CodeGenOnly) {
481     codegen(Conf, TM.get(), AddStream, Task, Mod);
482     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
483   }
484 
485   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
486     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
487 
488   renameModuleForThinLTO(Mod, CombinedIndex);
489 
490   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
491 
492   thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
493 
494   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
495     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
496 
497   if (!DefinedGlobals.empty())
498     thinLTOInternalizeModule(Mod, DefinedGlobals);
499 
500   if (Conf.PostInternalizeModuleHook &&
501       !Conf.PostInternalizeModuleHook(Task, Mod))
502     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
503 
504   auto ModuleLoader = [&](StringRef Identifier) {
505     assert(Mod.getContext().isODRUniquingDebugTypes() &&
506            "ODR Type uniquing should be enabled on the context");
507     auto I = ModuleMap.find(Identifier);
508     assert(I != ModuleMap.end());
509     return I->second.getLazyModule(Mod.getContext(),
510                                    /*ShouldLazyLoadMetadata=*/true,
511                                    /*IsImporting*/ true);
512   };
513 
514   FunctionImporter Importer(CombinedIndex, ModuleLoader);
515   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
516     return Err;
517 
518   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
519     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
520 
521   if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
522            /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
523     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
524 
525   codegen(Conf, TM.get(), AddStream, Task, Mod);
526   return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
527 }
528