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