blob: 9e53972a9d428539666742f0ecc9e25ee8ee48a4 [file] [log] [blame]
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001//===-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"
Davide Italianoec9612d2016-09-07 17:46:16 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/CGSCCPassManager.h"
20#include "llvm/Analysis/LoopPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
23#include "llvm/Bitcode/ReaderWriter.h"
24#include "llvm/IR/LegacyPassManager.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000025#include "llvm/IR/PassManager.h"
26#include "llvm/IR/Verifier.h"
Mehdi Amini970800e2016-08-17 06:23:09 +000027#include "llvm/LTO/LTO.h"
Davide Italianodc8e07b2016-09-16 16:05:25 +000028#include "llvm/LTO/legacy/UpdateCompilerUsed.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000029#include "llvm/MC/SubtargetFeature.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000030#include "llvm/Passes/PassBuilder.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#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/Utils/FunctionImportUtils.h"
39#include "llvm/Transforms/Utils/SplitModule.h"
40
41using namespace llvm;
42using namespace lto;
43
44Error Config::addSaveTemps(std::string OutputFileName,
45 bool UseInputModulePath) {
46 ShouldDiscardValueNames = false;
47
48 std::error_code EC;
49 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminieccffad2016-08-18 00:12:33 +000050 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000051 if (EC)
52 return errorCodeToError(EC);
53
54 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
55 // Keep track of the hook provided by the linker, which also needs to run.
56 ModuleHookFn LinkerHook = Hook;
Mehdi Aminif8c2f082016-08-22 16:17:40 +000057 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000058 // If the linker's hook returned false, we need to pass that result
59 // through.
60 if (LinkerHook && !LinkerHook(Task, M))
61 return false;
62
63 std::string PathPrefix;
64 // If this is the combined module (not a ThinLTO backend compile) or the
65 // user hasn't requested using the input module's path, emit to a file
66 // named from the provided OutputFileName with the Task ID appended.
67 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000068 PathPrefix = OutputFileName + utostr(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000069 } else
70 PathPrefix = M.getModuleIdentifier();
71 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
72 std::error_code EC;
73 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
74 if (EC) {
75 // Because -save-temps is a debugging feature, we report the error
76 // directly and exit.
77 llvm::errs() << "failed to open " << Path << ": " << EC.message()
78 << '\n';
79 exit(1);
80 }
81 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
82 return true;
83 };
84 };
85
86 setHook("0.preopt", PreOptModuleHook);
87 setHook("1.promote", PostPromoteModuleHook);
88 setHook("2.internalize", PostInternalizeModuleHook);
89 setHook("3.import", PostImportModuleHook);
90 setHook("4.opt", PostOptModuleHook);
91 setHook("5.precodegen", PreCodeGenModuleHook);
92
93 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000094 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +000095 std::error_code EC;
96 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
97 if (EC) {
98 // Because -save-temps is a debugging feature, we report the error
99 // directly and exit.
100 llvm::errs() << "failed to open " << Path << ": " << EC.message() << '\n';
101 exit(1);
102 }
103 WriteIndexToFile(Index, OS);
104 return true;
105 };
106
107 return Error();
108}
109
110namespace {
111
112std::unique_ptr<TargetMachine>
Davide Italiano24c29b12016-09-07 01:08:31 +0000113createTargetMachine(Config &Conf, StringRef TheTriple,
114 const Target *TheTarget) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000115 SubtargetFeatures Features;
116 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano24c29b12016-09-07 01:08:31 +0000117 for (const std::string &A : Conf.MAttrs)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000118 Features.AddFeature(A);
119
120 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Davide Italiano24c29b12016-09-07 01:08:31 +0000121 TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
122 Conf.CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000123}
124
Davide Italianoec9612d2016-09-07 17:46:16 +0000125static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
126 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000127 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000128 bool DisableVerify) {
129 PassBuilder PB(TM);
130 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000131
132 // Parse a custom AA pipeline if asked to.
133 if (!AAPipelineDesc.empty())
134 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
135 report_fatal_error("unable to parse AA pipeline description: " +
136 AAPipelineDesc);
137
Davide Italianoec9612d2016-09-07 17:46:16 +0000138 LoopAnalysisManager LAM;
139 FunctionAnalysisManager FAM;
140 CGSCCAnalysisManager CGAM;
141 ModuleAnalysisManager MAM;
142
143 // Register the AA manager first so that our version is the one used.
144 FAM.registerPass([&] { return std::move(AA); });
145
146 // Register all the basic analyses with the managers.
147 PB.registerModuleAnalyses(MAM);
148 PB.registerCGSCCAnalyses(CGAM);
149 PB.registerFunctionAnalyses(FAM);
150 PB.registerLoopAnalyses(LAM);
151 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
152
153 ModulePassManager MPM;
154
155 // Always verify the input.
156 MPM.addPass(VerifierPass());
157
158 // Now, add all the passes we've been requested to.
159 if (!PB.parsePassPipeline(MPM, PipelineDesc))
160 report_fatal_error("unable to parse pass pipeline description: " +
161 PipelineDesc);
162
163 if (!DisableVerify)
164 MPM.addPass(VerifierPass());
165 MPM.run(Mod, MAM);
166}
167
Davide Italiano24c29b12016-09-07 01:08:31 +0000168static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000169 bool IsThinLto) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000170 legacy::PassManager passes;
171 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
172
173 PassManagerBuilder PMB;
174 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
175 PMB.Inliner = createFunctionInliningPass();
176 // Unconditionally verify input since it is not verified before this
177 // point and has unknown origin.
178 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000179 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000180 PMB.LoopVectorize = true;
181 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000182 PMB.OptLevel = Conf.OptLevel;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000183 if (IsThinLto)
184 PMB.populateThinLTOPassManager(passes);
185 else
186 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000187 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000188}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000189
Davide Italiano24c29b12016-09-07 01:08:31 +0000190bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000191 bool IsThinLto) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000192 Mod.setDataLayout(TM->createDataLayout());
Davide Italianoec9612d2016-09-07 17:46:16 +0000193 if (Conf.OptPipeline.empty())
194 runOldPMPasses(Conf, Mod, TM, IsThinLto);
195 else
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000196 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
197 Conf.DisableVerify);
Davide Italiano24c29b12016-09-07 01:08:31 +0000198 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000199}
200
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000201/// Monolithic LTO does not support caching (yet), this is a convenient wrapper
202/// around AddOutput to workaround this.
203static AddOutputFn getUncachedOutputWrapper(AddOutputFn &AddOutput,
204 unsigned Task) {
205 return [Task, &AddOutput](unsigned TaskId) {
206 auto Output = AddOutput(Task);
207 if (Output->isCachingEnabled() && Output->tryLoadFromCache(""))
208 report_fatal_error("Cache hit without a valid key?");
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000209 assert(Task == TaskId && "Unexpexted TaskId mismatch");
210 return Output;
211 };
212}
213
Davide Italiano24c29b12016-09-07 01:08:31 +0000214void codegen(Config &Conf, TargetMachine *TM, AddOutputFn AddOutput,
215 unsigned Task, Module &Mod) {
216 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000217 return;
218
Mehdi Amini970800e2016-08-17 06:23:09 +0000219 auto Output = AddOutput(Task);
220 std::unique_ptr<raw_pwrite_stream> OS = Output->getStream();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000221 legacy::PassManager CodeGenPasses;
222 if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
223 TargetMachine::CGFT_ObjectFile))
224 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000225 CodeGenPasses.run(Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000226}
227
Mehdi Amini970800e2016-08-17 06:23:09 +0000228void splitCodeGen(Config &C, TargetMachine *TM, AddOutputFn AddOutput,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000229 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000230 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000231 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
232 unsigned ThreadCount = 0;
233 const Target *T = &TM->getTarget();
234
235 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000236 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000237 [&](std::unique_ptr<Module> MPart) {
238 // We want to clone the module in a new context to multi-thread the
239 // codegen. We do it by serializing partition modules to bitcode
240 // (while still on the main thread, in order to avoid data races) and
241 // spinning up new threads which deserialize the partitions into
242 // separate contexts.
243 // FIXME: Provide a more direct way to do this in LLVM.
244 SmallString<0> BC;
245 raw_svector_ostream BCOS(BC);
246 WriteBitcodeToFile(MPart.get(), BCOS);
247
248 // Enqueue the task
249 CodegenThreadPool.async(
250 [&](const SmallString<0> &BC, unsigned ThreadId) {
251 LTOLLVMContext Ctx(C);
252 ErrorOr<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
253 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
254 Ctx);
255 if (!MOrErr)
256 report_fatal_error("Failed to read bitcode");
257 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
258
259 std::unique_ptr<TargetMachine> TM =
260 createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000261
262 codegen(C, TM.get(),
263 getUncachedOutputWrapper(AddOutput, ThreadId), ThreadId,
264 *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000265 },
266 // Pass BC using std::move to ensure that it get moved rather than
267 // copied into the thread's context.
268 std::move(BC), ThreadCount++);
269 },
270 false);
271}
272
Davide Italiano24c29b12016-09-07 01:08:31 +0000273Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000274 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000275 Mod.setTargetTriple(C.OverrideTriple);
276 else if (Mod.getTargetTriple().empty())
277 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000278
279 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000280 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000281 if (!T)
282 return make_error<StringError>(Msg, inconvertibleErrorCode());
283 return T;
284}
285
286}
287
Davide Italianodc8e07b2016-09-16 16:05:25 +0000288static void handleAsmUndefinedRefs(Module &Mod, TargetMachine &TM) {
289 // Collect the list of undefined symbols used in asm and update
290 // llvm.compiler.used to prevent optimization to drop these from the output.
291 StringSet<> AsmUndefinedRefs;
292 object::IRObjectFile::CollectAsmUndefinedRefs(
293 Triple(Mod.getTargetTriple()), Mod.getModuleInlineAsm(),
294 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
295 if (Flags & object::BasicSymbolRef::SF_Undefined)
296 AsmUndefinedRefs.insert(Name);
297 });
298 updateCompilerUsed(Mod, TM, AsmUndefinedRefs);
299}
300
Mehdi Amini970800e2016-08-17 06:23:09 +0000301Error lto::backend(Config &C, AddOutputFn AddOutput,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000302 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000303 std::unique_ptr<Module> Mod) {
304 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000305 if (!TOrErr)
306 return TOrErr.takeError();
307
308 std::unique_ptr<TargetMachine> TM =
Davide Italiano24c29b12016-09-07 01:08:31 +0000309 createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000310
Davide Italianodc8e07b2016-09-16 16:05:25 +0000311 handleAsmUndefinedRefs(*Mod, *TM);
312
Mehdi Aminid310b472016-08-22 06:25:41 +0000313 if (!C.CodeGenOnly)
Davide Italiano24c29b12016-09-07 01:08:31 +0000314 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLto=*/false))
Mehdi Aminid310b472016-08-22 06:25:41 +0000315 return Error();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000316
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000317 if (ParallelCodeGenParallelismLevel == 1) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000318 codegen(C, TM.get(), getUncachedOutputWrapper(AddOutput, 0), 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000319 } else {
Mehdi Amini970800e2016-08-17 06:23:09 +0000320 splitCodeGen(C, TM.get(), AddOutput, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000321 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000322 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000323 return Error();
324}
325
Mehdi Amini970800e2016-08-17 06:23:09 +0000326Error lto::thinBackend(Config &Conf, unsigned Task, AddOutputFn AddOutput,
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000327 Module &Mod, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000328 const FunctionImporter::ImportMapTy &ImportList,
329 const GVSummaryMapTy &DefinedGlobals,
330 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000331 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000332 if (!TOrErr)
333 return TOrErr.takeError();
334
335 std::unique_ptr<TargetMachine> TM =
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000336 createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000337
Davide Italianodc8e07b2016-09-16 16:05:25 +0000338 handleAsmUndefinedRefs(Mod, *TM);
339
Mehdi Aminid310b472016-08-22 06:25:41 +0000340 if (Conf.CodeGenOnly) {
341 codegen(Conf, TM.get(), AddOutput, Task, Mod);
342 return Error();
343 }
344
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000345 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000346 return Error();
347
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000348 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000349
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000350 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
351
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000352 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000353 return Error();
354
355 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000356 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000357
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000358 if (Conf.PostInternalizeModuleHook &&
359 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000360 return Error();
361
362 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000363 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000364 "ODR Type uniquing should be enabled on the context");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000365 return std::move(getLazyBitcodeModule(MemoryBuffer::getMemBuffer(
366 ModuleMap[Identifier], false),
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000367 Mod.getContext(),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000368 /*ShouldLazyLoadMetadata=*/true)
369 .get());
370 };
371
372 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000373 Importer.importFunctions(Mod, ImportList);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000375 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000376 return Error();
377
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000378 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLto=*/true))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000379 return Error();
380
Mehdi Amini970800e2016-08-17 06:23:09 +0000381 codegen(Conf, TM.get(), AddOutput, Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000382 return Error();
383}