1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
45 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
46 errs() << "failed to open " << Path << ": " << Msg << '\n';
51 Error Config::addSaveTemps(std::string OutputFileName,
52 bool UseInputModulePath) {
53 ShouldDiscardValueNames = false;
56 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
57 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
59 return errorCodeToError(EC);
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
67 if (LinkerHook && !LinkerHook(Task, M))
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);
77 PathPrefix = M.getModuleIdentifier();
78 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
80 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
81 // Because -save-temps is a debugging feature, we report the error
84 reportOpenError(Path, EC.message());
85 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
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);
97 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
98 std::string Path = OutputFileName + "index.bc";
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.
104 reportOpenError(Path, EC.message());
105 WriteIndexToFile(Index, OS);
109 return Error::success();
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);
122 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
123 TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
124 Conf.CodeModel, Conf.CGOptLevel));
127 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
128 std::string PipelineDesc,
129 std::string AAPipelineDesc,
130 bool DisableVerify) {
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: " +
140 LoopAnalysisManager LAM;
141 FunctionAnalysisManager FAM;
142 CGSCCAnalysisManager CGAM;
143 ModuleAnalysisManager MAM;
145 // Register the AA manager first so that our version is the one used.
146 FAM.registerPass([&] { return std::move(AA); });
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);
155 ModulePassManager MPM;
157 // Always verify the input.
158 MPM.addPass(VerifierPass());
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: " +
166 MPM.addPass(VerifierPass());
170 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
172 legacy::PassManager passes;
173 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
175 PassManagerBuilder PMB;
176 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
177 PMB.Inliner = createFunctionInliningPass();
178 // Unconditionally verify input since it is not verified before this
179 // point and has unknown origin.
180 PMB.VerifyInput = true;
181 PMB.VerifyOutput = !Conf.DisableVerify;
182 PMB.LoopVectorize = true;
183 PMB.SLPVectorize = true;
184 PMB.OptLevel = Conf.OptLevel;
185 PMB.PGOSampleUse = Conf.SampleProfile;
187 PMB.populateThinLTOPassManager(passes);
189 PMB.populateLTOPassManager(passes);
193 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
195 if (Conf.OptPipeline.empty())
196 runOldPMPasses(Conf, Mod, TM, IsThinLTO);
198 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
200 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
203 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
204 unsigned Task, Module &Mod) {
205 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
208 auto Stream = AddStream(Task);
209 legacy::PassManager CodeGenPasses;
210 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
211 TargetMachine::CGFT_ObjectFile))
212 report_fatal_error("Failed to setup codegen");
213 CodeGenPasses.run(Mod);
216 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
217 unsigned ParallelCodeGenParallelismLevel,
218 std::unique_ptr<Module> Mod) {
219 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
220 unsigned ThreadCount = 0;
221 const Target *T = &TM->getTarget();
224 std::move(Mod), ParallelCodeGenParallelismLevel,
225 [&](std::unique_ptr<Module> MPart) {
226 // We want to clone the module in a new context to multi-thread the
227 // codegen. We do it by serializing partition modules to bitcode
228 // (while still on the main thread, in order to avoid data races) and
229 // spinning up new threads which deserialize the partitions into
230 // separate contexts.
231 // FIXME: Provide a more direct way to do this in LLVM.
233 raw_svector_ostream BCOS(BC);
234 WriteBitcodeToFile(MPart.get(), BCOS);
237 CodegenThreadPool.async(
238 [&](const SmallString<0> &BC, unsigned ThreadId) {
239 LTOLLVMContext Ctx(C);
240 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
241 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
244 report_fatal_error("Failed to read bitcode");
245 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
247 std::unique_ptr<TargetMachine> TM =
248 createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
250 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
252 // Pass BC using std::move to ensure that it get moved rather than
253 // copied into the thread's context.
254 std::move(BC), ThreadCount++);
258 // Because the inner lambda (which runs in a worker thread) captures our local
259 // variables, we need to wait for the worker threads to terminate before we
260 // can leave the function scope.
261 CodegenThreadPool.wait();
264 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
265 if (!C.OverrideTriple.empty())
266 Mod.setTargetTriple(C.OverrideTriple);
267 else if (Mod.getTargetTriple().empty())
268 Mod.setTargetTriple(C.DefaultTriple);
271 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
273 return make_error<StringError>(Msg, inconvertibleErrorCode());
279 static void handleAsmUndefinedRefs(Module &Mod, TargetMachine &TM) {
280 // Collect the list of undefined symbols used in asm and update
281 // llvm.compiler.used to prevent optimization to drop these from the output.
282 StringSet<> AsmUndefinedRefs;
283 ModuleSymbolTable::CollectAsmSymbols(
284 Triple(Mod.getTargetTriple()), Mod.getModuleInlineAsm(),
285 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
286 if (Flags & object::BasicSymbolRef::SF_Undefined)
287 AsmUndefinedRefs.insert(Name);
289 updateCompilerUsed(Mod, TM, AsmUndefinedRefs);
292 Error lto::backend(Config &C, AddStreamFn AddStream,
293 unsigned ParallelCodeGenParallelismLevel,
294 std::unique_ptr<Module> Mod) {
295 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
297 return TOrErr.takeError();
299 std::unique_ptr<TargetMachine> TM =
300 createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
302 handleAsmUndefinedRefs(*Mod, *TM);
305 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false))
306 return Error::success();
308 if (ParallelCodeGenParallelismLevel == 1) {
309 codegen(C, TM.get(), AddStream, 0, *Mod);
311 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
314 return Error::success();
317 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
318 Module &Mod, ModuleSummaryIndex &CombinedIndex,
319 const FunctionImporter::ImportMapTy &ImportList,
320 const GVSummaryMapTy &DefinedGlobals,
321 MapVector<StringRef, BitcodeModule> &ModuleMap) {
322 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
324 return TOrErr.takeError();
326 std::unique_ptr<TargetMachine> TM =
327 createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
329 handleAsmUndefinedRefs(Mod, *TM);
331 if (Conf.CodeGenOnly) {
332 codegen(Conf, TM.get(), AddStream, Task, Mod);
333 return Error::success();
336 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
337 return Error::success();
339 renameModuleForThinLTO(Mod, CombinedIndex);
341 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
343 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
344 return Error::success();
346 if (!DefinedGlobals.empty())
347 thinLTOInternalizeModule(Mod, DefinedGlobals);
349 if (Conf.PostInternalizeModuleHook &&
350 !Conf.PostInternalizeModuleHook(Task, Mod))
351 return Error::success();
353 auto ModuleLoader = [&](StringRef Identifier) {
354 assert(Mod.getContext().isODRUniquingDebugTypes() &&
355 "ODR Type uniquing should be enabled on the context");
356 auto I = ModuleMap.find(Identifier);
357 assert(I != ModuleMap.end());
358 return I->second.getLazyModule(Mod.getContext(),
359 /*ShouldLazyLoadMetadata=*/true,
360 /*IsImporting*/ true);
363 FunctionImporter Importer(CombinedIndex, ModuleLoader);
364 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
367 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
368 return Error::success();
370 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true))
371 return Error::success();
373 codegen(Conf, TM.get(), AddStream, Task, Mod);
374 return Error::success();