blob: 4bd251f727a4353da699102e9c1ee4e0b5bdac18 [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"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
21#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000022#include "llvm/Bitcode/BitcodeReader.h"
23#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000024#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"
Peter Collingbourne192d8522017-03-28 23:35:34 +000030#include "llvm/Object/ModuleSymbolTable.h"
Davide Italianoec9612d2016-09-07 17:46:16 +000031#include "llvm/Passes/PassBuilder.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000032#include "llvm/Support/Error.h"
33#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/TargetRegistry.h"
35#include "llvm/Support/ThreadPool.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Transforms/IPO.h"
38#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000039#include "llvm/Transforms/Scalar/LoopPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000040#include "llvm/Transforms/Utils/FunctionImportUtils.h"
41#include "llvm/Transforms/Utils/SplitModule.h"
42
43using namespace llvm;
44using namespace lto;
45
Davide Italiano0dd200e2017-01-24 00:58:24 +000046static cl::opt<bool>
47 LTOUseNewPM("lto-use-new-pm",
48 cl::desc("Run LTO passes using the new pass manager"),
49 cl::init(false), cl::Hidden);
50
Benjamin Kramer4c2582a2016-10-18 19:39:31 +000051LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
Davide Italianoa416d112016-09-17 22:32:42 +000052 errs() << "failed to open " << Path << ": " << Msg << '\n';
53 errs().flush();
54 exit(1);
55}
56
Teresa Johnson9ba95f92016-08-11 14:58:12 +000057Error Config::addSaveTemps(std::string OutputFileName,
58 bool UseInputModulePath) {
59 ShouldDiscardValueNames = false;
60
61 std::error_code EC;
62 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminieccffad2016-08-18 00:12:33 +000063 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000064 if (EC)
65 return errorCodeToError(EC);
66
67 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
68 // Keep track of the hook provided by the linker, which also needs to run.
69 ModuleHookFn LinkerHook = Hook;
Mehdi Aminif8c2f082016-08-22 16:17:40 +000070 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000071 // If the linker's hook returned false, we need to pass that result
72 // through.
73 if (LinkerHook && !LinkerHook(Task, M))
74 return false;
75
76 std::string PathPrefix;
77 // If this is the combined module (not a ThinLTO backend compile) or the
78 // user hasn't requested using the input module's path, emit to a file
79 // named from the provided OutputFileName with the Task ID appended.
80 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000081 PathPrefix = OutputFileName + utostr(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000082 } else
83 PathPrefix = M.getModuleIdentifier();
84 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
85 std::error_code EC;
86 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +000087 // Because -save-temps is a debugging feature, we report the error
88 // directly and exit.
89 if (EC)
90 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +000091 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
92 return true;
93 };
94 };
95
96 setHook("0.preopt", PreOptModuleHook);
97 setHook("1.promote", PostPromoteModuleHook);
98 setHook("2.internalize", PostInternalizeModuleHook);
99 setHook("3.import", PostImportModuleHook);
100 setHook("4.opt", PostOptModuleHook);
101 setHook("5.precodegen", PreCodeGenModuleHook);
102
103 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +0000104 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000105 std::error_code EC;
106 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +0000107 // Because -save-temps is a debugging feature, we report the error
108 // directly and exit.
109 if (EC)
110 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000111 WriteIndexToFile(Index, OS);
112 return true;
113 };
114
Mehdi Amini41af4302016-11-11 04:28:40 +0000115 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000116}
117
118namespace {
119
120std::unique_ptr<TargetMachine>
Davide Italiano24c29b12016-09-07 01:08:31 +0000121createTargetMachine(Config &Conf, StringRef TheTriple,
122 const Target *TheTarget) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000123 SubtargetFeatures Features;
124 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano24c29b12016-09-07 01:08:31 +0000125 for (const std::string &A : Conf.MAttrs)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000126 Features.AddFeature(A);
127
128 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Davide Italiano24c29b12016-09-07 01:08:31 +0000129 TheTriple, Conf.CPU, Features.getString(), Conf.Options, Conf.RelocModel,
130 Conf.CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000131}
132
Davide Italiano0dd200e2017-01-24 00:58:24 +0000133static void runNewPMPasses(Module &Mod, TargetMachine *TM, unsigned OptLevel) {
134 PassBuilder PB(TM);
135 AAManager AA;
136
137 // Parse a custom AA pipeline if asked to.
138 assert(PB.parseAAPipeline(AA, "default"));
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 // FIXME (davide): verify the input.
157
158 PassBuilder::OptimizationLevel OL;
159
160 switch (OptLevel) {
161 default:
162 llvm_unreachable("Invalid optimization level");
163 case 0:
164 OL = PassBuilder::O0;
165 break;
166 case 1:
167 OL = PassBuilder::O1;
168 break;
169 case 2:
170 OL = PassBuilder::O2;
171 break;
172 case 3:
173 OL = PassBuilder::O3;
174 break;
175 }
176
177 MPM = PB.buildLTODefaultPipeline(OL, false /* DebugLogging */);
178 MPM.run(Mod, MAM);
179
180 // FIXME (davide): verify the output.
181}
182
Davide Italianoec9612d2016-09-07 17:46:16 +0000183static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
184 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000185 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000186 bool DisableVerify) {
187 PassBuilder PB(TM);
188 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000189
190 // Parse a custom AA pipeline if asked to.
191 if (!AAPipelineDesc.empty())
192 if (!PB.parseAAPipeline(AA, AAPipelineDesc))
193 report_fatal_error("unable to parse AA pipeline description: " +
194 AAPipelineDesc);
195
Davide Italianoec9612d2016-09-07 17:46:16 +0000196 LoopAnalysisManager LAM;
197 FunctionAnalysisManager FAM;
198 CGSCCAnalysisManager CGAM;
199 ModuleAnalysisManager MAM;
200
201 // Register the AA manager first so that our version is the one used.
202 FAM.registerPass([&] { return std::move(AA); });
203
204 // Register all the basic analyses with the managers.
205 PB.registerModuleAnalyses(MAM);
206 PB.registerCGSCCAnalyses(CGAM);
207 PB.registerFunctionAnalyses(FAM);
208 PB.registerLoopAnalyses(LAM);
209 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
210
211 ModulePassManager MPM;
212
213 // Always verify the input.
214 MPM.addPass(VerifierPass());
215
216 // Now, add all the passes we've been requested to.
217 if (!PB.parsePassPipeline(MPM, PipelineDesc))
218 report_fatal_error("unable to parse pass pipeline description: " +
219 PipelineDesc);
220
221 if (!DisableVerify)
222 MPM.addPass(VerifierPass());
223 MPM.run(Mod, MAM);
224}
225
Davide Italiano24c29b12016-09-07 01:08:31 +0000226static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000227 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
228 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000229 legacy::PassManager passes;
230 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
231
232 PassManagerBuilder PMB;
233 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
234 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000235 PMB.ExportSummary = ExportSummary;
236 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000237 // Unconditionally verify input since it is not verified before this
238 // point and has unknown origin.
239 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000240 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000241 PMB.LoopVectorize = true;
242 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000243 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000244 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano8812f282016-11-24 00:23:09 +0000245 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000246 PMB.populateThinLTOPassManager(passes);
247 else
248 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000249 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000250}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000251
Davide Italiano24c29b12016-09-07 01:08:31 +0000252bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000253 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
254 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000255 // There's still no ThinLTO pipeline hooked up in the new pass manager,
256 // once there is one, we can just remove this.
257 if (LTOUseNewPM && IsThinLTO)
258 report_fatal_error("ThinLTO not supported with the new PM yet!");
259
260 // FIXME: Plumb the combined index into the new pass manager.
261 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000262 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
263 Conf.DisableVerify);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000264 else if (LTOUseNewPM)
265 runNewPMPasses(Mod, TM, Conf.OptLevel);
266 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000267 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000268 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000269}
270
Peter Collingbourne80186a52016-09-23 21:33:43 +0000271void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000272 unsigned Task, Module &Mod) {
273 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000274 return;
275
Peter Collingbourne80186a52016-09-23 21:33:43 +0000276 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000277 legacy::PassManager CodeGenPasses;
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000278 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000279 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000280 CodeGenPasses.run(Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000281}
282
Peter Collingbourne80186a52016-09-23 21:33:43 +0000283void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000284 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000285 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000286 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
287 unsigned ThreadCount = 0;
288 const Target *T = &TM->getTarget();
289
290 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000291 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000292 [&](std::unique_ptr<Module> MPart) {
293 // We want to clone the module in a new context to multi-thread the
294 // codegen. We do it by serializing partition modules to bitcode
295 // (while still on the main thread, in order to avoid data races) and
296 // spinning up new threads which deserialize the partitions into
297 // separate contexts.
298 // FIXME: Provide a more direct way to do this in LLVM.
299 SmallString<0> BC;
300 raw_svector_ostream BCOS(BC);
301 WriteBitcodeToFile(MPart.get(), BCOS);
302
303 // Enqueue the task
304 CodegenThreadPool.async(
305 [&](const SmallString<0> &BC, unsigned ThreadId) {
306 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000307 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000308 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
309 Ctx);
310 if (!MOrErr)
311 report_fatal_error("Failed to read bitcode");
312 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
313
314 std::unique_ptr<TargetMachine> TM =
315 createTargetMachine(C, MPartInCtx->getTargetTriple(), T);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000316
Peter Collingbourne80186a52016-09-23 21:33:43 +0000317 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000318 },
319 // Pass BC using std::move to ensure that it get moved rather than
320 // copied into the thread's context.
321 std::move(BC), ThreadCount++);
322 },
323 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000324
325 // Because the inner lambda (which runs in a worker thread) captures our local
326 // variables, we need to wait for the worker threads to terminate before we
327 // can leave the function scope.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000328 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000329}
330
Davide Italiano24c29b12016-09-07 01:08:31 +0000331Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000332 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000333 Mod.setTargetTriple(C.OverrideTriple);
334 else if (Mod.getTargetTriple().empty())
335 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000336
337 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000338 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000339 if (!T)
340 return make_error<StringError>(Msg, inconvertibleErrorCode());
341 return T;
342}
343
344}
345
Davide Italiano20a895c2017-02-13 14:39:51 +0000346static void
347finalizeOptimizationRemarks(std::unique_ptr<tool_output_file> DiagOutputFile) {
348 // Make sure we flush the diagnostic remarks file in case the linker doesn't
349 // call the global destructors before exiting.
350 if (!DiagOutputFile)
351 return;
352 DiagOutputFile->keep();
353 DiagOutputFile->os().flush();
354}
355
Davide Italianodc8e07b2016-09-16 16:05:25 +0000356static void handleAsmUndefinedRefs(Module &Mod, TargetMachine &TM) {
357 // Collect the list of undefined symbols used in asm and update
358 // llvm.compiler.used to prevent optimization to drop these from the output.
359 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000360 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000361 Mod,
Davide Italianodc8e07b2016-09-16 16:05:25 +0000362 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
363 if (Flags & object::BasicSymbolRef::SF_Undefined)
364 AsmUndefinedRefs.insert(Name);
365 });
366 updateCompilerUsed(Mod, TM, AsmUndefinedRefs);
367}
368
Peter Collingbourne80186a52016-09-23 21:33:43 +0000369Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000370 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000371 std::unique_ptr<Module> Mod,
372 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000373 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374 if (!TOrErr)
375 return TOrErr.takeError();
376
377 std::unique_ptr<TargetMachine> TM =
Davide Italiano24c29b12016-09-07 01:08:31 +0000378 createTargetMachine(C, Mod->getTargetTriple(), *TOrErr);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000379
Davide Italianodc8e07b2016-09-16 16:05:25 +0000380 handleAsmUndefinedRefs(*Mod, *TM);
381
Davide Italianoebd47192017-02-12 03:31:30 +0000382 // Setup optimization remarks.
383 auto DiagFileOrErr = lto::setupOptimizationRemarks(
384 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
385 if (!DiagFileOrErr)
386 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000387 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000388
Davide Italiano20a895c2017-02-13 14:39:51 +0000389 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000390 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
391 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000392 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000393 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000394 }
395 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000396
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000397 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000398 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000399 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000400 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000401 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000402 }
Davide Italiano20a895c2017-02-13 14:39:51 +0000403 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000404 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405}
406
Peter Collingbourne80186a52016-09-23 21:33:43 +0000407Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000408 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000409 const FunctionImporter::ImportMapTy &ImportList,
410 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000411 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000412 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413 if (!TOrErr)
414 return TOrErr.takeError();
415
416 std::unique_ptr<TargetMachine> TM =
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000417 createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000418
Davide Italianodc8e07b2016-09-16 16:05:25 +0000419 handleAsmUndefinedRefs(Mod, *TM);
420
Mehdi Aminid310b472016-08-22 06:25:41 +0000421 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000422 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000423 return Error::success();
Mehdi Aminid310b472016-08-22 06:25:41 +0000424 }
425
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000426 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000427 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000428
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000429 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000430
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000431 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
432
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000433 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000434 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000435
436 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000437 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000438
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000439 if (Conf.PostInternalizeModuleHook &&
440 !Conf.PostInternalizeModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000441 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000442
443 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000444 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000445 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000446 auto I = ModuleMap.find(Identifier);
447 assert(I != ModuleMap.end());
448 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000449 /*ShouldLazyLoadMetadata=*/true,
450 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000451 };
452
453 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000454 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
455 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000456
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000457 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000458 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000459
Peter Collingbournef7691d82017-03-22 18:22:59 +0000460 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
461 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000462 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000463
Peter Collingbourne80186a52016-09-23 21:33:43 +0000464 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000465 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000466}