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/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/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);
107 Path = OutputFileName + "index.dot";
108 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
110 reportOpenError(Path, EC.message());
111 Index.exportToDot(OSDot);
115 return Error::success();
120 std::unique_ptr<TargetMachine>
121 createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
122 StringRef TheTriple = M.getTargetTriple();
123 SubtargetFeatures Features;
124 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
125 for (const std::string &A : Conf.MAttrs)
126 Features.AddFeature(A);
128 Reloc::Model RelocModel;
130 RelocModel = *Conf.RelocModel;
133 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
135 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
136 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
137 Conf.CodeModel, Conf.CGOptLevel));
140 static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
141 unsigned OptLevel, bool IsThinLTO) {
142 Optional<PGOOptions> PGOOpt;
143 if (!Conf.SampleProfile.empty())
144 PGOOpt = PGOOptions("", "", Conf.SampleProfile, false, true);
146 PassBuilder PB(TM, PGOOpt);
149 // Parse a custom AA pipeline if asked to.
150 if (!PB.parseAAPipeline(AA, "default"))
151 report_fatal_error("Error parsing default AA pipeline");
153 LoopAnalysisManager LAM(Conf.DebugPassManager);
154 FunctionAnalysisManager FAM(Conf.DebugPassManager);
155 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
156 ModuleAnalysisManager MAM(Conf.DebugPassManager);
158 // Register the AA manager first so that our version is the one used.
159 FAM.registerPass([&] { return std::move(AA); });
161 // Register all the basic analyses with the managers.
162 PB.registerModuleAnalyses(MAM);
163 PB.registerCGSCCAnalyses(CGAM);
164 PB.registerFunctionAnalyses(FAM);
165 PB.registerLoopAnalyses(LAM);
166 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
168 ModulePassManager MPM(Conf.DebugPassManager);
169 // FIXME (davide): verify the input.
171 PassBuilder::OptimizationLevel OL;
175 llvm_unreachable("Invalid optimization level");
177 OL = PassBuilder::O0;
180 OL = PassBuilder::O1;
183 OL = PassBuilder::O2;
186 OL = PassBuilder::O3;
191 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager);
193 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager);
196 // FIXME (davide): verify the output.
199 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
200 std::string PipelineDesc,
201 std::string AAPipelineDesc,
202 bool DisableVerify) {
206 // Parse a custom AA pipeline if asked to.
207 if (!AAPipelineDesc.empty())
208 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
209 report_fatal_error("unable to parse AA pipeline description: " +
212 LoopAnalysisManager LAM;
213 FunctionAnalysisManager FAM;
214 CGSCCAnalysisManager CGAM;
215 ModuleAnalysisManager MAM;
217 // Register the AA manager first so that our version is the one used.
218 FAM.registerPass([&] { return std::move(AA); });
220 // Register all the basic analyses with the managers.
221 PB.registerModuleAnalyses(MAM);
222 PB.registerCGSCCAnalyses(CGAM);
223 PB.registerFunctionAnalyses(FAM);
224 PB.registerLoopAnalyses(LAM);
225 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
227 ModulePassManager MPM;
229 // Always verify the input.
230 MPM.addPass(VerifierPass());
232 // Now, add all the passes we've been requested to.
233 if (!PB.parsePassPipeline(MPM, PipelineDesc))
234 report_fatal_error("unable to parse pass pipeline description: " +
238 MPM.addPass(VerifierPass());
242 static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
243 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
244 const ModuleSummaryIndex *ImportSummary) {
245 legacy::PassManager passes;
246 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
248 PassManagerBuilder PMB;
249 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
250 PMB.Inliner = createFunctionInliningPass();
251 PMB.ExportSummary = ExportSummary;
252 PMB.ImportSummary = ImportSummary;
253 // Unconditionally verify input since it is not verified before this
254 // point and has unknown origin.
255 PMB.VerifyInput = true;
256 PMB.VerifyOutput = !Conf.DisableVerify;
257 PMB.LoopVectorize = true;
258 PMB.SLPVectorize = true;
259 PMB.OptLevel = Conf.OptLevel;
260 PMB.PGOSampleUse = Conf.SampleProfile;
262 PMB.populateThinLTOPassManager(passes);
264 PMB.populateLTOPassManager(passes);
268 bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
269 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
270 const ModuleSummaryIndex *ImportSummary) {
271 // FIXME: Plumb the combined index into the new pass manager.
272 if (!Conf.OptPipeline.empty())
273 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
275 else if (Conf.UseNewPM)
276 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO);
278 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
279 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
282 void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
283 unsigned Task, Module &Mod) {
284 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
287 auto Stream = AddStream(Task);
288 legacy::PassManager CodeGenPasses;
289 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
290 report_fatal_error("Failed to setup codegen");
291 CodeGenPasses.run(Mod);
294 void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
295 unsigned ParallelCodeGenParallelismLevel,
296 std::unique_ptr<Module> Mod) {
297 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
298 unsigned ThreadCount = 0;
299 const Target *T = &TM->getTarget();
302 std::move(Mod), ParallelCodeGenParallelismLevel,
303 [&](std::unique_ptr<Module> MPart) {
304 // We want to clone the module in a new context to multi-thread the
305 // codegen. We do it by serializing partition modules to bitcode
306 // (while still on the main thread, in order to avoid data races) and
307 // spinning up new threads which deserialize the partitions into
308 // separate contexts.
309 // FIXME: Provide a more direct way to do this in LLVM.
311 raw_svector_ostream BCOS(BC);
312 WriteBitcodeToFile(*MPart, BCOS);
315 CodegenThreadPool.async(
316 [&](const SmallString<0> &BC, unsigned ThreadId) {
317 LTOLLVMContext Ctx(C);
318 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
319 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
322 report_fatal_error("Failed to read bitcode");
323 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
325 std::unique_ptr<TargetMachine> TM =
326 createTargetMachine(C, T, *MPartInCtx);
328 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
330 // Pass BC using std::move to ensure that it get moved rather than
331 // copied into the thread's context.
332 std::move(BC), ThreadCount++);
336 // Because the inner lambda (which runs in a worker thread) captures our local
337 // variables, we need to wait for the worker threads to terminate before we
338 // can leave the function scope.
339 CodegenThreadPool.wait();
342 Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
343 if (!C.OverrideTriple.empty())
344 Mod.setTargetTriple(C.OverrideTriple);
345 else if (Mod.getTargetTriple().empty())
346 Mod.setTargetTriple(C.DefaultTriple);
349 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
351 return make_error<StringError>(Msg, inconvertibleErrorCode());
358 finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
359 // Make sure we flush the diagnostic remarks file in case the linker doesn't
360 // call the global destructors before exiting.
363 DiagOutputFile->keep();
364 DiagOutputFile->os().flush();
367 Error lto::backend(Config &C, AddStreamFn AddStream,
368 unsigned ParallelCodeGenParallelismLevel,
369 std::unique_ptr<Module> Mod,
370 ModuleSummaryIndex &CombinedIndex) {
371 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
373 return TOrErr.takeError();
375 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
377 // Setup optimization remarks.
378 auto DiagFileOrErr = lto::setupOptimizationRemarks(
379 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
381 return DiagFileOrErr.takeError();
382 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
384 if (!C.CodeGenOnly) {
385 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
386 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) {
387 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
388 return Error::success();
392 if (ParallelCodeGenParallelismLevel == 1) {
393 codegen(C, TM.get(), AddStream, 0, *Mod);
395 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
398 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
399 return Error::success();
402 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
403 const ModuleSummaryIndex &Index) {
404 std::vector<GlobalValue*> DeadGVs;
405 for (auto &GV : Mod.global_values())
406 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
407 if (!Index.isGlobalValueLive(GVS)) {
408 DeadGVs.push_back(&GV);
409 convertToDeclaration(GV);
412 // Now that all dead bodies have been dropped, delete the actual objects
413 // themselves when possible.
414 for (GlobalValue *GV : DeadGVs) {
415 GV->removeDeadConstantUsers();
416 // Might reference something defined in native object (i.e. dropped a
417 // non-prevailing IR def, but we need to keep the declaration).
419 GV->eraseFromParent();
423 Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
424 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
425 const FunctionImporter::ImportMapTy &ImportList,
426 const GVSummaryMapTy &DefinedGlobals,
427 MapVector<StringRef, BitcodeModule> &ModuleMap) {
428 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
430 return TOrErr.takeError();
432 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
434 if (Conf.CodeGenOnly) {
435 codegen(Conf, TM.get(), AddStream, Task, Mod);
436 return Error::success();
439 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
440 return Error::success();
442 renameModuleForThinLTO(Mod, CombinedIndex);
444 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
446 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
448 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
449 return Error::success();
451 if (!DefinedGlobals.empty())
452 thinLTOInternalizeModule(Mod, DefinedGlobals);
454 if (Conf.PostInternalizeModuleHook &&
455 !Conf.PostInternalizeModuleHook(Task, Mod))
456 return Error::success();
458 auto ModuleLoader = [&](StringRef Identifier) {
459 assert(Mod.getContext().isODRUniquingDebugTypes() &&
460 "ODR Type uniquing should be enabled on the context");
461 auto I = ModuleMap.find(Identifier);
462 assert(I != ModuleMap.end());
463 return I->second.getLazyModule(Mod.getContext(),
464 /*ShouldLazyLoadMetadata=*/true,
465 /*IsImporting*/ true);
468 FunctionImporter Importer(CombinedIndex, ModuleLoader);
469 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
472 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
473 return Error::success();
475 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
476 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
477 return Error::success();
479 codegen(Conf, TM.get(), AddStream, Task, Mod);
480 return Error::success();