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/LTO/legacy/UpdateCompilerUsed.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/Passes/PassBuilder.h"
31 #include "llvm/Support/Error.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/ThreadPool.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/IPO.h"
37 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38 #include "llvm/Transforms/Scalar/LoopPassManager.h"
39 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
40 #include "llvm/Transforms/Utils/SplitModule.h"
41 
42 using namespace llvm;
43 using namespace lto;
44 
45 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
46   errs() << "failed to open " << Path << ": " << Msg << '\n';
47   errs().flush();
48   exit(1);
49 }
50 
51 Error Config::addSaveTemps(std::string OutputFileName,
52                            bool UseInputModulePath) {
53   ShouldDiscardValueNames = false;
54 
55   std::error_code EC;
56   ResolutionFile = llvm::make_unique<raw_fd_ostream>(
57       OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
58   if (EC)
59     return errorCodeToError(EC);
60 
61   auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
62     // Keep track of the hook provided by the linker, which also needs to run.
63     ModuleHookFn LinkerHook = Hook;
64     Hook = [=](unsigned Task, const Module &M) {
65       // If the linker's hook returned false, we need to pass that result
66       // through.
67       if (LinkerHook && !LinkerHook(Task, M))
68         return false;
69 
70       std::string PathPrefix;
71       // If this is the combined module (not a ThinLTO backend compile) or the
72       // user hasn't requested using the input module's path, emit to a file
73       // named from the provided OutputFileName with the Task ID appended.
74       if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
75         PathPrefix = OutputFileName + utostr(Task);
76       } else
77         PathPrefix = M.getModuleIdentifier();
78       std::string Path = PathPrefix + "." + PathSuffix + ".bc";
79       std::error_code EC;
80       raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
81       // Because -save-temps is a debugging feature, we report the error
82       // directly and exit.
83       if (EC)
84         reportOpenError(Path, EC.message());
85       WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
86       return true;
87     };
88   };
89 
90   setHook("0.preopt", PreOptModuleHook);
91   setHook("1.promote", PostPromoteModuleHook);
92   setHook("2.internalize", PostInternalizeModuleHook);
93   setHook("3.import", PostImportModuleHook);
94   setHook("4.opt", PostOptModuleHook);
95   setHook("5.precodegen", PreCodeGenModuleHook);
96 
97   CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
98     std::string Path = OutputFileName + "index.bc";
99     std::error_code EC;
100     raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
101     // Because -save-temps is a debugging feature, we report the error
102     // directly and exit.
103     if (EC)
104       reportOpenError(Path, EC.message());
105     WriteIndexToFile(Index, OS);
106     return true;
107   };
108 
109   return Error::success();
110 }
111 
112 namespace {
113 
114 std::unique_ptr<TargetMachine>
115 createTargetMachine(Config &Conf, StringRef TheTriple,
116                     const Target *TheTarget) {
117   SubtargetFeatures Features;
118   Features.getDefaultSubtargetFeatures(Triple(TheTriple));
119   for (const std::string &A : Conf.MAttrs)
120     Features.AddFeature(A);
121 
122   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
123       TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
124       Conf.CodeModel, Conf.CGOptLevel));
125 }
126 
127 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
128                                  std::string PipelineDesc,
129                                  std::string AAPipelineDesc,
130                                  bool DisableVerify) {
131   PassBuilder PB(TM);
132   AAManager AA;
133 
134   // Parse a custom AA pipeline if asked to.
135   if (!AAPipelineDesc.empty())
136     if (!PB.parseAAPipeline(AA, AAPipelineDesc))
137       report_fatal_error("unable to parse AA pipeline description: " +
138                          AAPipelineDesc);
139 
140   LoopAnalysisManager LAM;
141   FunctionAnalysisManager FAM;
142   CGSCCAnalysisManager CGAM;
143   ModuleAnalysisManager MAM;
144 
145   // Register the AA manager first so that our version is the one used.
146   FAM.registerPass([&] { return std::move(AA); });
147 
148   // Register all the basic analyses with the managers.
149   PB.registerModuleAnalyses(MAM);
150   PB.registerCGSCCAnalyses(CGAM);
151   PB.registerFunctionAnalyses(FAM);
152   PB.registerLoopAnalyses(LAM);
153   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
154 
155   ModulePassManager MPM;
156 
157   // Always verify the input.
158   MPM.addPass(VerifierPass());
159 
160   // Now, add all the passes we've been requested to.
161   if (!PB.parsePassPipeline(MPM, PipelineDesc))
162     report_fatal_error("unable to parse pass pipeline description: " +
163                        PipelineDesc);
164 
165   if (!DisableVerify)
166     MPM.addPass(VerifierPass());
167   MPM.run(Mod, MAM);
168 }
169 
170 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
171                            bool IsThinLTO, ModuleSummaryIndex &CombinedIndex) {
172   legacy::PassManager passes;
173   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
174 
175   PassManagerBuilder PMB;
176   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
177   PMB.Inliner = createFunctionInliningPass();
178   PMB.Summary = &CombinedIndex;
179   // Unconditionally verify input since it is not verified before this
180   // point and has unknown origin.
181   PMB.VerifyInput = true;
182   PMB.VerifyOutput = !Conf.DisableVerify;
183   PMB.LoopVectorize = true;
184   PMB.SLPVectorize = true;
185   PMB.OptLevel = Conf.OptLevel;
186   PMB.PGOSampleUse = Conf.SampleProfile;
187   if (IsThinLTO)
188     PMB.populateThinLTOPassManager(passes);
189   else
190     PMB.populateLTOPassManager(passes);
191   passes.run(Mod);
192 }
193 
194 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
195          bool IsThinLTO, ModuleSummaryIndex &CombinedIndex) {
196   if (Conf.OptPipeline.empty())
197     runOldPMPasses(Conf, Mod, TM, IsThinLTO, CombinedIndex);
198   else
199     // FIXME: Plumb the combined index into the new pass manager.
200     runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
201                          Conf.DisableVerify);
202   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
203 }
204 
205 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
206              unsigned Task, Module &Mod) {
207   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
208     return;
209 
210   auto Stream = AddStream(Task);
211   legacy::PassManager CodeGenPasses;
212   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
213                               TargetMachine::CGFT_ObjectFile))
214     report_fatal_error("Failed to setup codegen");
215   CodeGenPasses.run(Mod);
216 }
217 
218 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
219                   unsigned ParallelCodeGenParallelismLevel,
220                   std::unique_ptr<Module> Mod) {
221   ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
222   unsigned ThreadCount = 0;
223   const Target *T = &TM->getTarget();
224 
225   SplitModule(
226       std::move(Mod), ParallelCodeGenParallelismLevel,
227       [&](std::unique_ptr<Module> MPart) {
228         // We want to clone the module in a new context to multi-thread the
229         // codegen. We do it by serializing partition modules to bitcode
230         // (while still on the main thread, in order to avoid data races) and
231         // spinning up new threads which deserialize the partitions into
232         // separate contexts.
233         // FIXME: Provide a more direct way to do this in LLVM.
234         SmallString<0> BC;
235         raw_svector_ostream BCOS(BC);
236         WriteBitcodeToFile(MPart.get(), BCOS);
237 
238         // Enqueue the task
239         CodegenThreadPool.async(
240             [&](const SmallString<0> &BC, unsigned ThreadId) {
241               LTOLLVMContext Ctx(C);
242               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
243                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
244                   Ctx);
245               if (!MOrErr)
246                 report_fatal_error("Failed to read bitcode");
247               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
248 
249               std::unique_ptr<TargetMachine> TM =
250                   createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
251 
252               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
253             },
254             // Pass BC using std::move to ensure that it get moved rather than
255             // copied into the thread's context.
256             std::move(BC), ThreadCount++);
257       },
258       false);
259 
260   // Because the inner lambda (which runs in a worker thread) captures our local
261   // variables, we need to wait for the worker threads to terminate before we
262   // can leave the function scope.
263   CodegenThreadPool.wait();
264 }
265 
266 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
267   if (!C.OverrideTriple.empty())
268     Mod.setTargetTriple(C.OverrideTriple);
269   else if (Mod.getTargetTriple().empty())
270     Mod.setTargetTriple(C.DefaultTriple);
271 
272   std::string Msg;
273   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
274   if (!T)
275     return make_error<StringError>(Msg, inconvertibleErrorCode());
276   return T;
277 }
278 
279 }
280 
281 static void handleAsmUndefinedRefs(Module &Mod, TargetMachine &TM) {
282   // Collect the list of undefined symbols used in asm and update
283   // llvm.compiler.used to prevent optimization to drop these from the output.
284   StringSet<> AsmUndefinedRefs;
285   ModuleSymbolTable::CollectAsmSymbols(
286       Triple(Mod.getTargetTriple()), Mod.getModuleInlineAsm(),
287       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
288         if (Flags & object::BasicSymbolRef::SF_Undefined)
289           AsmUndefinedRefs.insert(Name);
290       });
291   updateCompilerUsed(Mod, TM, AsmUndefinedRefs);
292 }
293 
294 Error lto::backend(Config &C, AddStreamFn AddStream,
295                    unsigned ParallelCodeGenParallelismLevel,
296                    std::unique_ptr<Module> Mod,
297                    ModuleSummaryIndex &CombinedIndex) {
298   Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
299   if (!TOrErr)
300     return TOrErr.takeError();
301 
302   std::unique_ptr<TargetMachine> TM =
303       createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
304 
305   handleAsmUndefinedRefs(*Mod, *TM);
306 
307   if (!C.CodeGenOnly)
308     if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false, CombinedIndex))
309       return Error::success();
310 
311   if (ParallelCodeGenParallelismLevel == 1) {
312     codegen(C, TM.get(), AddStream, 0, *Mod);
313   } else {
314     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
315                  std::move(Mod));
316   }
317   return Error::success();
318 }
319 
320 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
321                        Module &Mod, ModuleSummaryIndex &CombinedIndex,
322                        const FunctionImporter::ImportMapTy &ImportList,
323                        const GVSummaryMapTy &DefinedGlobals,
324                        MapVector<StringRef, BitcodeModule> &ModuleMap) {
325   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
326   if (!TOrErr)
327     return TOrErr.takeError();
328 
329   std::unique_ptr<TargetMachine> TM =
330       createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
331 
332   handleAsmUndefinedRefs(Mod, *TM);
333 
334   if (Conf.CodeGenOnly) {
335     codegen(Conf, TM.get(), AddStream, Task, Mod);
336     return Error::success();
337   }
338 
339   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
340     return Error::success();
341 
342   renameModuleForThinLTO(Mod, CombinedIndex);
343 
344   thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
345 
346   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
347     return Error::success();
348 
349   if (!DefinedGlobals.empty())
350     thinLTOInternalizeModule(Mod, DefinedGlobals);
351 
352   if (Conf.PostInternalizeModuleHook &&
353       !Conf.PostInternalizeModuleHook(Task, Mod))
354     return Error::success();
355 
356   auto ModuleLoader = [&](StringRef Identifier) {
357     assert(Mod.getContext().isODRUniquingDebugTypes() &&
358            "ODR Type uniquing should be enabled on the context");
359     auto I = ModuleMap.find(Identifier);
360     assert(I != ModuleMap.end());
361     return I->second.getLazyModule(Mod.getContext(),
362                                    /*ShouldLazyLoadMetadata=*/true,
363                                    /*IsImporting*/ true);
364   };
365 
366   FunctionImporter Importer(CombinedIndex, ModuleLoader);
367   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
368     return Err;
369 
370   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
371     return Error::success();
372 
373   if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true, CombinedIndex))
374     return Error::success();
375 
376   codegen(Conf, TM.get(), AddStream, Task, Mod);
377   return Error::success();
378 }
379