blob: 49c0c2e15b3f0cdbf4095067bbc2cbb53648a59b [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"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000028#include "llvm/MC/SubtargetFeature.h"
Peter Collingbourne192d8522017-03-28 23:35:34 +000029#include "llvm/Object/ModuleSymbolTable.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"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000038#include "llvm/Transforms/Scalar/LoopPassManager.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000039#include "llvm/Transforms/Utils/FunctionImportUtils.h"
40#include "llvm/Transforms/Utils/SplitModule.h"
41
42using namespace llvm;
43using namespace lto;
44
Benjamin Kramer4c2582a2016-10-18 19:39:31 +000045LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
Davide Italianoa416d112016-09-17 22:32:42 +000046 errs() << "failed to open " << Path << ": " << Msg << '\n';
47 errs().flush();
48 exit(1);
49}
50
Teresa Johnson9ba95f92016-08-11 14:58:12 +000051Error Config::addSaveTemps(std::string OutputFileName,
52 bool UseInputModulePath) {
53 ShouldDiscardValueNames = false;
54
55 std::error_code EC;
56 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminieccffad2016-08-18 00:12:33 +000057 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000058 if (EC)
59 return errorCodeToError(EC);
60
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;
Mehdi Aminif8c2f082016-08-22 16:17:40 +000064 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +000065 // If the linker's hook returned false, we need to pass that result
66 // through.
67 if (LinkerHook && !LinkerHook(Task, M))
68 return false;
69
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) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000075 PathPrefix = OutputFileName + utostr(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +000076 } else
77 PathPrefix = M.getModuleIdentifier();
78 std::string Path = PathPrefix + "." + PathSuffix + ".bc";
79 std::error_code EC;
80 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +000081 // Because -save-temps is a debugging feature, we report the error
82 // directly and exit.
83 if (EC)
84 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +000085 WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false);
86 return true;
87 };
88 };
89
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);
96
97 CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
Mehdi Aminieccffad2016-08-18 00:12:33 +000098 std::string Path = OutputFileName + "index.bc";
Teresa Johnson9ba95f92016-08-11 14:58:12 +000099 std::error_code EC;
100 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa416d112016-09-17 22:32:42 +0000101 // Because -save-temps is a debugging feature, we report the error
102 // directly and exit.
103 if (EC)
104 reportOpenError(Path, EC.message());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000105 WriteIndexToFile(Index, OS);
Eugene Leviant28d8a492018-01-22 13:35:40 +0000106
107 Path = OutputFileName + "index.dot";
108 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
109 if (EC)
110 reportOpenError(Path, EC.message());
111 Index.exportToDot(OSDot);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000112 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>
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000121createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
122 StringRef TheTriple = M.getTargetTriple();
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
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000128 Reloc::Model RelocModel;
129 if (Conf.RelocModel)
130 RelocModel = *Conf.RelocModel;
131 else
132 RelocModel =
133 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
134
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000135 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000136 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000137 Conf.CodeModel, Conf.CGOptLevel));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000138}
139
Dehao Chen89d32262017-08-02 01:28:31 +0000140static 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);
145
146 PassBuilder PB(TM, PGOOpt);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000147 AAManager AA;
148
149 // Parse a custom AA pipeline if asked to.
Dehao Chen3246dc32017-08-02 03:03:19 +0000150 if (!PB.parseAAPipeline(AA, "default"))
151 report_fatal_error("Error parsing default AA pipeline");
Davide Italiano0dd200e2017-01-24 00:58:24 +0000152
Dehao Chen3246dc32017-08-02 03:03:19 +0000153 LoopAnalysisManager LAM(Conf.DebugPassManager);
154 FunctionAnalysisManager FAM(Conf.DebugPassManager);
155 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
156 ModuleAnalysisManager MAM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000157
158 // Register the AA manager first so that our version is the one used.
159 FAM.registerPass([&] { return std::move(AA); });
160
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);
167
Dehao Chen3246dc32017-08-02 03:03:19 +0000168 ModulePassManager MPM(Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000169 // FIXME (davide): verify the input.
170
171 PassBuilder::OptimizationLevel OL;
172
173 switch (OptLevel) {
174 default:
175 llvm_unreachable("Invalid optimization level");
176 case 0:
177 OL = PassBuilder::O0;
178 break;
179 case 1:
180 OL = PassBuilder::O1;
181 break;
182 case 2:
183 OL = PassBuilder::O2;
184 break;
185 case 3:
186 OL = PassBuilder::O3;
187 break;
188 }
189
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000190 if (IsThinLTO)
Dehao Chen3246dc32017-08-02 03:03:19 +0000191 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager);
Chandler Carruth8b3be4e2017-06-01 11:39:39 +0000192 else
Dehao Chen3246dc32017-08-02 03:03:19 +0000193 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000194 MPM.run(Mod, MAM);
195
196 // FIXME (davide): verify the output.
197}
198
Davide Italianoec9612d2016-09-07 17:46:16 +0000199static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
200 std::string PipelineDesc,
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000201 std::string AAPipelineDesc,
Davide Italianoec9612d2016-09-07 17:46:16 +0000202 bool DisableVerify) {
203 PassBuilder PB(TM);
204 AAManager AA;
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000205
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: " +
210 AAPipelineDesc);
211
Davide Italianoec9612d2016-09-07 17:46:16 +0000212 LoopAnalysisManager LAM;
213 FunctionAnalysisManager FAM;
214 CGSCCAnalysisManager CGAM;
215 ModuleAnalysisManager MAM;
216
217 // Register the AA manager first so that our version is the one used.
218 FAM.registerPass([&] { return std::move(AA); });
219
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);
226
227 ModulePassManager MPM;
228
229 // Always verify the input.
230 MPM.addPass(VerifierPass());
231
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: " +
235 PipelineDesc);
236
237 if (!DisableVerify)
238 MPM.addPass(VerifierPass());
239 MPM.run(Mod, MAM);
240}
241
Davide Italiano24c29b12016-09-07 01:08:31 +0000242static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000243 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
244 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000245 legacy::PassManager passes;
246 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
247
248 PassManagerBuilder PMB;
249 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
250 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournef7691d82017-03-22 18:22:59 +0000251 PMB.ExportSummary = ExportSummary;
252 PMB.ImportSummary = ImportSummary;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000253 // Unconditionally verify input since it is not verified before this
254 // point and has unknown origin.
255 PMB.VerifyInput = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000256 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000257 PMB.LoopVectorize = true;
258 PMB.SLPVectorize = true;
Davide Italiano24c29b12016-09-07 01:08:31 +0000259 PMB.OptLevel = Conf.OptLevel;
Dehao Chen27978002016-12-16 16:48:46 +0000260 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano8812f282016-11-24 00:23:09 +0000261 if (IsThinLTO)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000262 PMB.populateThinLTOPassManager(passes);
263 else
264 PMB.populateLTOPassManager(passes);
Davide Italiano24c29b12016-09-07 01:08:31 +0000265 passes.run(Mod);
Davide Italiano1e9d3d32016-08-31 17:02:44 +0000266}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000267
Davide Italiano24c29b12016-09-07 01:08:31 +0000268bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000269 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
270 const ModuleSummaryIndex *ImportSummary) {
Davide Italiano0dd200e2017-01-24 00:58:24 +0000271 // FIXME: Plumb the combined index into the new pass manager.
272 if (!Conf.OptPipeline.empty())
Davide Italiano14e9e8a2016-09-16 21:03:21 +0000273 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
274 Conf.DisableVerify);
Tim Shen4e912aa2017-06-01 23:13:44 +0000275 else if (Conf.UseNewPM)
Dehao Chen89d32262017-08-02 01:28:31 +0000276 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO);
Davide Italiano0dd200e2017-01-24 00:58:24 +0000277 else
Peter Collingbournef7691d82017-03-22 18:22:59 +0000278 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano24c29b12016-09-07 01:08:31 +0000279 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000280}
281
Peter Collingbourne80186a52016-09-23 21:33:43 +0000282void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano24c29b12016-09-07 01:08:31 +0000283 unsigned Task, Module &Mod) {
284 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000285 return;
286
Peter Collingbourne80186a52016-09-23 21:33:43 +0000287 auto Stream = AddStream(Task);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000288 legacy::PassManager CodeGenPasses;
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000289 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS, Conf.CGFileType))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000290 report_fatal_error("Failed to setup codegen");
Davide Italiano24c29b12016-09-07 01:08:31 +0000291 CodeGenPasses.run(Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000292}
293
Peter Collingbourne80186a52016-09-23 21:33:43 +0000294void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000295 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000296 std::unique_ptr<Module> Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000297 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
298 unsigned ThreadCount = 0;
299 const Target *T = &TM->getTarget();
300
301 SplitModule(
Davide Italiano24c29b12016-09-07 01:08:31 +0000302 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000303 [&](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.
310 SmallString<0> BC;
311 raw_svector_ostream BCOS(BC);
312 WriteBitcodeToFile(MPart.get(), BCOS);
313
314 // Enqueue the task
315 CodegenThreadPool.async(
316 [&](const SmallString<0> &BC, unsigned ThreadId) {
317 LTOLLVMContext Ctx(C);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000318 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000319 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
320 Ctx);
321 if (!MOrErr)
322 report_fatal_error("Failed to read bitcode");
323 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
324
325 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000326 createTargetMachine(C, T, *MPartInCtx);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000327
Peter Collingbourne80186a52016-09-23 21:33:43 +0000328 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000329 },
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++);
333 },
334 false);
Peter Collingbournef75609e2016-09-29 03:29:28 +0000335
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.
Peter Collingbourne0d5636e2016-09-29 01:28:36 +0000339 CodegenThreadPool.wait();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000340}
341
Davide Italiano24c29b12016-09-07 01:08:31 +0000342Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000343 if (!C.OverrideTriple.empty())
Davide Italiano24c29b12016-09-07 01:08:31 +0000344 Mod.setTargetTriple(C.OverrideTriple);
345 else if (Mod.getTargetTriple().empty())
346 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347
348 std::string Msg;
Davide Italiano24c29b12016-09-07 01:08:31 +0000349 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000350 if (!T)
351 return make_error<StringError>(Msg, inconvertibleErrorCode());
352 return T;
353}
354
355}
356
Davide Italiano20a895c2017-02-13 14:39:51 +0000357static void
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000358finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000359 // Make sure we flush the diagnostic remarks file in case the linker doesn't
360 // call the global destructors before exiting.
361 if (!DiagOutputFile)
362 return;
363 DiagOutputFile->keep();
364 DiagOutputFile->os().flush();
365}
366
Peter Collingbourne80186a52016-09-23 21:33:43 +0000367Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000368 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000369 std::unique_ptr<Module> Mod,
370 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano24c29b12016-09-07 01:08:31 +0000371 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000372 if (!TOrErr)
373 return TOrErr.takeError();
374
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000375 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000376
Davide Italianoebd47192017-02-12 03:31:30 +0000377 // Setup optimization remarks.
378 auto DiagFileOrErr = lto::setupOptimizationRemarks(
379 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
380 if (!DiagFileOrErr)
381 return DiagFileOrErr.takeError();
Davide Italiano20a895c2017-02-13 14:39:51 +0000382 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italianoebd47192017-02-12 03:31:30 +0000383
Davide Italiano20a895c2017-02-13 14:39:51 +0000384 if (!C.CodeGenOnly) {
Peter Collingbournef7691d82017-03-22 18:22:59 +0000385 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
386 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr)) {
Davide Italiano20a895c2017-02-13 14:39:51 +0000387 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000388 return Error::success();
Davide Italiano20a895c2017-02-13 14:39:51 +0000389 }
390 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000391
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000392 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000393 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000394 } else {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000395 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano24c29b12016-09-07 01:08:31 +0000396 std::move(Mod));
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000397 }
Davide Italiano20a895c2017-02-13 14:39:51 +0000398 finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini41af4302016-11-11 04:28:40 +0000399 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400}
401
George Rimareaf51722018-01-29 08:03:30 +0000402static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
403 const ModuleSummaryIndex &Index) {
Teresa Johnson5a95c472018-02-05 15:44:27 +0000404 std::vector<GlobalValue *> ReplacedGlobals;
405 for (auto &GV : Mod.global_values())
George Rimarf5de2712018-02-02 12:21:26 +0000406 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnson5a95c472018-02-05 15:44:27 +0000407 if (!Index.isGlobalValueLive(GVS) && !convertToDeclaration(GV))
408 ReplacedGlobals.push_back(&GV);
George Rimar76c5fae2018-02-02 12:17:33 +0000409
Teresa Johnson5a95c472018-02-05 15:44:27 +0000410 for (GlobalValue *GV : ReplacedGlobals)
411 GV->eraseFromParent();
George Rimareaf51722018-01-29 08:03:30 +0000412}
413
Peter Collingbourne80186a52016-09-23 21:33:43 +0000414Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournef7691d82017-03-22 18:22:59 +0000415 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416 const FunctionImporter::ImportMapTy &ImportList,
417 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000418 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000419 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000420 if (!TOrErr)
421 return TOrErr.takeError();
422
Evgeniy Stepanovb9f1b012017-05-22 21:11:35 +0000423 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000424
Mehdi Aminid310b472016-08-22 06:25:41 +0000425 if (Conf.CodeGenOnly) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000426 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000427 return Error::success();
Mehdi Aminid310b472016-08-22 06:25:41 +0000428 }
429
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000430 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000431 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000432
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000433 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000434
George Rimareaf51722018-01-29 08:03:30 +0000435 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
436
Mehdi Amini8ac7b322016-08-18 00:59:24 +0000437 thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals);
438
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000439 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000440 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000441
442 if (!DefinedGlobals.empty())
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000443 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000445 if (Conf.PostInternalizeModuleHook &&
446 !Conf.PostInternalizeModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000447 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000448
449 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000450 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italiano63e8f442016-09-14 18:48:43 +0000451 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000452 auto I = ModuleMap.find(Identifier);
453 assert(I != ModuleMap.end());
454 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000455 /*ShouldLazyLoadMetadata=*/true,
456 /*IsImporting*/ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457 };
458
459 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000460 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
461 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462
Mehdi Aminiacc50c42016-08-16 00:44:46 +0000463 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Mehdi Amini41af4302016-11-11 04:28:40 +0000464 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465
Peter Collingbournef7691d82017-03-22 18:22:59 +0000466 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
467 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000468 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000469
Peter Collingbourne80186a52016-09-23 21:33:43 +0000470 codegen(Conf, TM.get(), AddStream, Task, Mod);
Mehdi Amini41af4302016-11-11 04:28:40 +0000471 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000472}