blob: 926c419e34a84c35a3b9470e7ed29758c420e39e [file] [log] [blame]
Teresa Johnson2d320e52016-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 Italianofab897d2016-09-07 17:46:16 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/CGSCCPassManager.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
21#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsona5479192016-11-11 05:34:58 +000022#include "llvm/Bitcode/BitcodeReader.h"
23#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000024#include "llvm/IR/LegacyPassManager.h"
Davide Italianofab897d2016-09-07 17:46:16 +000025#include "llvm/IR/PassManager.h"
26#include "llvm/IR/Verifier.h"
Mehdi Aminibba5e182016-08-17 06:23:09 +000027#include "llvm/LTO/LTO.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000028#include "llvm/MC/SubtargetFeature.h"
Peter Collingbourne14ecedf2017-03-28 23:35:34 +000029#include "llvm/Object/ModuleSymbolTable.h"
Davide Italianofab897d2016-09-07 17:46:16 +000030#include "llvm/Passes/PassBuilder.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000031#include "llvm/Support/Error.h"
32#include "llvm/Support/FileSystem.h"
Yunlian Jiangedd00e42018-04-13 05:03:28 +000033#include "llvm/Support/MemoryBuffer.h"
34#include "llvm/Support/Path.h"
35#include "llvm/Support/Program.h"
36#include "llvm/Support/raw_ostream.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000037#include "llvm/Support/TargetRegistry.h"
38#include "llvm/Support/ThreadPool.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Transforms/IPO.h"
41#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruthc68d25f2017-01-11 09:43:56 +000042#include "llvm/Transforms/Scalar/LoopPassManager.h"
Teresa Johnson2d320e52016-08-11 14:58:12 +000043#include "llvm/Transforms/Utils/FunctionImportUtils.h"
44#include "llvm/Transforms/Utils/SplitModule.h"
45
46using namespace llvm;
47using namespace lto;
48
Benjamin Kramer6e3c4da2016-10-18 19:39:31 +000049LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
Davide Italianoa64fbcf2016-09-17 22:32:42 +000050 errs() << "failed to open " << Path << ": " << Msg << '\n';
51 errs().flush();
52 exit(1);
53}
54
Teresa Johnson2d320e52016-08-11 14:58:12 +000055Error Config::addSaveTemps(std::string OutputFileName,
56 bool UseInputModulePath) {
57 ShouldDiscardValueNames = false;
58
59 std::error_code EC;
60 ResolutionFile = llvm::make_unique<raw_fd_ostream>(
Mehdi Aminia53e50c2016-08-18 00:12:33 +000061 OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
Teresa Johnson2d320e52016-08-11 14:58:12 +000062 if (EC)
63 return errorCodeToError(EC);
64
65 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
66 // Keep track of the hook provided by the linker, which also needs to run.
67 ModuleHookFn LinkerHook = Hook;
Mehdi Amini5c134562016-08-22 16:17:40 +000068 Hook = [=](unsigned Task, const Module &M) {
Teresa Johnson2d320e52016-08-11 14:58:12 +000069 // If the linker's hook returned false, we need to pass that result
70 // through.
71 if (LinkerHook && !LinkerHook(Task, M))
72 return false;
73
74 std::string PathPrefix;
75 // If this is the combined module (not a ThinLTO backend compile) or the
76 // user hasn't requested using the input module's path, emit to a file
77 // named from the provided OutputFileName with the Task ID appended.
78 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
Teresa Johnson5a921532018-05-05 14:37:20 +000079 PathPrefix = OutputFileName;
80 if (Task != (unsigned)-1)
81 PathPrefix += utostr(Task) + ".";
Teresa Johnson2d320e52016-08-11 14:58:12 +000082 } else
Teresa Johnson5a921532018-05-05 14:37:20 +000083 PathPrefix = M.getModuleIdentifier() + ".";
84 std::string Path = PathPrefix + PathSuffix + ".bc";
Teresa Johnson2d320e52016-08-11 14:58:12 +000085 std::error_code EC;
86 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa64fbcf2016-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());
Rafael Espindola06d62072018-02-14 19:11:32 +000091 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
Teresa Johnson2d320e52016-08-11 14:58:12 +000092 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 Aminia53e50c2016-08-18 00:12:33 +0000104 std::string Path = OutputFileName + "index.bc";
Teresa Johnson2d320e52016-08-11 14:58:12 +0000105 std::error_code EC;
106 raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
Davide Italianoa64fbcf2016-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 Johnson2d320e52016-08-11 14:58:12 +0000111 WriteIndexToFile(Index, OS);
Eugene Leviant731becc2018-01-22 13:35:40 +0000112
113 Path = OutputFileName + "index.dot";
114 raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
115 if (EC)
116 reportOpenError(Path, EC.message());
117 Index.exportToDot(OSDot);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000118 return true;
119 };
120
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000121 return Error::success();
Teresa Johnson2d320e52016-08-11 14:58:12 +0000122}
123
124namespace {
125
126std::unique_ptr<TargetMachine>
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000127createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
128 StringRef TheTriple = M.getTargetTriple();
Teresa Johnson2d320e52016-08-11 14:58:12 +0000129 SubtargetFeatures Features;
130 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
Davide Italiano5c494e72016-09-07 01:08:31 +0000131 for (const std::string &A : Conf.MAttrs)
Teresa Johnson2d320e52016-08-11 14:58:12 +0000132 Features.AddFeature(A);
133
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000134 Reloc::Model RelocModel;
135 if (Conf.RelocModel)
136 RelocModel = *Conf.RelocModel;
137 else
138 RelocModel =
139 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
140
Caroline Ticea53c5202018-09-21 18:41:31 +0000141 Optional<CodeModel::Model> CodeModel;
142 if (Conf.CodeModel)
143 CodeModel = *Conf.CodeModel;
144 else
145 CodeModel = M.getCodeModel();
146
Teresa Johnson2d320e52016-08-11 14:58:12 +0000147 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000148 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
Caroline Ticea53c5202018-09-21 18:41:31 +0000149 CodeModel, Conf.CGOptLevel));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000150}
151
Dehao Chencbd28412017-08-02 01:28:31 +0000152static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Teresa Johnson2a478d42018-07-19 14:51:32 +0000153 unsigned OptLevel, bool IsThinLTO,
154 ModuleSummaryIndex *ExportSummary,
155 const ModuleSummaryIndex *ImportSummary) {
Dehao Chencbd28412017-08-02 01:28:31 +0000156 Optional<PGOOptions> PGOOpt;
157 if (!Conf.SampleProfile.empty())
Richard Smith63ec2562018-10-10 23:13:47 +0000158 PGOOpt = PGOOptions("", "", Conf.SampleProfile, Conf.ProfileRemapping,
159 false, true);
Dehao Chencbd28412017-08-02 01:28:31 +0000160
161 PassBuilder PB(TM, PGOOpt);
Davide Italianofa5f3e42017-01-24 00:58:24 +0000162 AAManager AA;
163
164 // Parse a custom AA pipeline if asked to.
Fedor Sergeevff886492018-10-17 10:36:23 +0000165 if (auto Err = PB.parseAAPipeline(AA, "default"))
Dehao Chenb929c3e2017-08-02 03:03:19 +0000166 report_fatal_error("Error parsing default AA pipeline");
Davide Italianofa5f3e42017-01-24 00:58:24 +0000167
Dehao Chenb929c3e2017-08-02 03:03:19 +0000168 LoopAnalysisManager LAM(Conf.DebugPassManager);
169 FunctionAnalysisManager FAM(Conf.DebugPassManager);
170 CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
171 ModuleAnalysisManager MAM(Conf.DebugPassManager);
Davide Italianofa5f3e42017-01-24 00:58:24 +0000172
173 // Register the AA manager first so that our version is the one used.
174 FAM.registerPass([&] { return std::move(AA); });
175
176 // Register all the basic analyses with the managers.
177 PB.registerModuleAnalyses(MAM);
178 PB.registerCGSCCAnalyses(CGAM);
179 PB.registerFunctionAnalyses(FAM);
180 PB.registerLoopAnalyses(LAM);
181 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
182
Dehao Chenb929c3e2017-08-02 03:03:19 +0000183 ModulePassManager MPM(Conf.DebugPassManager);
Davide Italianofa5f3e42017-01-24 00:58:24 +0000184 // FIXME (davide): verify the input.
185
186 PassBuilder::OptimizationLevel OL;
187
188 switch (OptLevel) {
189 default:
190 llvm_unreachable("Invalid optimization level");
191 case 0:
192 OL = PassBuilder::O0;
193 break;
194 case 1:
195 OL = PassBuilder::O1;
196 break;
197 case 2:
198 OL = PassBuilder::O2;
199 break;
200 case 3:
201 OL = PassBuilder::O3;
202 break;
203 }
204
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000205 if (IsThinLTO)
Teresa Johnson2a478d42018-07-19 14:51:32 +0000206 MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
207 ImportSummary);
Chandler Carruthdf1cbec2017-06-01 11:39:39 +0000208 else
Teresa Johnson2a478d42018-07-19 14:51:32 +0000209 MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
Davide Italianofa5f3e42017-01-24 00:58:24 +0000210 MPM.run(Mod, MAM);
211
212 // FIXME (davide): verify the output.
213}
214
Davide Italianofab897d2016-09-07 17:46:16 +0000215static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
216 std::string PipelineDesc,
Davide Italiano463cfe42016-09-16 21:03:21 +0000217 std::string AAPipelineDesc,
Davide Italianofab897d2016-09-07 17:46:16 +0000218 bool DisableVerify) {
219 PassBuilder PB(TM);
220 AAManager AA;
Davide Italiano463cfe42016-09-16 21:03:21 +0000221
222 // Parse a custom AA pipeline if asked to.
223 if (!AAPipelineDesc.empty())
Fedor Sergeevff886492018-10-17 10:36:23 +0000224 if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
225 report_fatal_error("unable to parse AA pipeline description '" +
226 AAPipelineDesc + "': " + toString(std::move(Err)));
Davide Italiano463cfe42016-09-16 21:03:21 +0000227
Davide Italianofab897d2016-09-07 17:46:16 +0000228 LoopAnalysisManager LAM;
229 FunctionAnalysisManager FAM;
230 CGSCCAnalysisManager CGAM;
231 ModuleAnalysisManager MAM;
232
233 // Register the AA manager first so that our version is the one used.
234 FAM.registerPass([&] { return std::move(AA); });
235
236 // Register all the basic analyses with the managers.
237 PB.registerModuleAnalyses(MAM);
238 PB.registerCGSCCAnalyses(CGAM);
239 PB.registerFunctionAnalyses(FAM);
240 PB.registerLoopAnalyses(LAM);
241 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
242
243 ModulePassManager MPM;
244
245 // Always verify the input.
246 MPM.addPass(VerifierPass());
247
248 // Now, add all the passes we've been requested to.
Fedor Sergeevff886492018-10-17 10:36:23 +0000249 if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
250 report_fatal_error("unable to parse pass pipeline description '" +
251 PipelineDesc + "': " + toString(std::move(Err)));
Davide Italianofab897d2016-09-07 17:46:16 +0000252
253 if (!DisableVerify)
254 MPM.addPass(VerifierPass());
255 MPM.run(Mod, MAM);
256}
257
Davide Italiano5c494e72016-09-07 01:08:31 +0000258static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
Peter Collingbournee53e5852017-03-22 18:22:59 +0000259 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
260 const ModuleSummaryIndex *ImportSummary) {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000261 legacy::PassManager passes;
262 passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
263
264 PassManagerBuilder PMB;
265 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
266 PMB.Inliner = createFunctionInliningPass();
Peter Collingbournee53e5852017-03-22 18:22:59 +0000267 PMB.ExportSummary = ExportSummary;
268 PMB.ImportSummary = ImportSummary;
Teresa Johnson2d320e52016-08-11 14:58:12 +0000269 // Unconditionally verify input since it is not verified before this
270 // point and has unknown origin.
271 PMB.VerifyInput = true;
Davide Italiano5c494e72016-09-07 01:08:31 +0000272 PMB.VerifyOutput = !Conf.DisableVerify;
Teresa Johnson2d320e52016-08-11 14:58:12 +0000273 PMB.LoopVectorize = true;
274 PMB.SLPVectorize = true;
Davide Italiano5c494e72016-09-07 01:08:31 +0000275 PMB.OptLevel = Conf.OptLevel;
Dehao Chen7e436002016-12-16 16:48:46 +0000276 PMB.PGOSampleUse = Conf.SampleProfile;
Davide Italiano6c409822016-11-24 00:23:09 +0000277 if (IsThinLTO)
Teresa Johnson2d320e52016-08-11 14:58:12 +0000278 PMB.populateThinLTOPassManager(passes);
279 else
280 PMB.populateLTOPassManager(passes);
Davide Italiano5c494e72016-09-07 01:08:31 +0000281 passes.run(Mod);
Davide Italianoc163bf52016-08-31 17:02:44 +0000282}
Teresa Johnson2d320e52016-08-11 14:58:12 +0000283
Davide Italiano5c494e72016-09-07 01:08:31 +0000284bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
Peter Collingbournee53e5852017-03-22 18:22:59 +0000285 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
286 const ModuleSummaryIndex *ImportSummary) {
Davide Italianofa5f3e42017-01-24 00:58:24 +0000287 // FIXME: Plumb the combined index into the new pass manager.
288 if (!Conf.OptPipeline.empty())
Davide Italiano463cfe42016-09-16 21:03:21 +0000289 runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
290 Conf.DisableVerify);
Tim Shena950eb92017-06-01 23:13:44 +0000291 else if (Conf.UseNewPM)
Teresa Johnson2a478d42018-07-19 14:51:32 +0000292 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
293 ImportSummary);
Davide Italianofa5f3e42017-01-24 00:58:24 +0000294 else
Peter Collingbournee53e5852017-03-22 18:22:59 +0000295 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
Davide Italiano5c494e72016-09-07 01:08:31 +0000296 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000297}
298
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000299void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
Davide Italiano5c494e72016-09-07 01:08:31 +0000300 unsigned Task, Module &Mod) {
301 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
Teresa Johnson2d320e52016-08-11 14:58:12 +0000302 return;
303
Peter Collingbourneaadeae82018-05-21 20:26:49 +0000304 std::unique_ptr<ToolOutputFile> DwoOut;
Peter Collingbourned24e9c32018-05-31 18:25:59 +0000305 SmallString<1024> DwoFile(Conf.DwoPath);
Yunlian Jiangedd00e42018-04-13 05:03:28 +0000306 if (!Conf.DwoDir.empty()) {
Peter Collingbourneaadeae82018-05-21 20:26:49 +0000307 std::error_code EC;
308 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
309 report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
310 EC.message());
311
Peter Collingbourned24e9c32018-05-31 18:25:59 +0000312 DwoFile = Conf.DwoDir;
Peter Collingbourneaadeae82018-05-21 20:26:49 +0000313 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
Peter Collingbourned24e9c32018-05-31 18:25:59 +0000314 }
315
316 if (!DwoFile.empty()) {
317 std::error_code EC;
Peter Collingbourneaadeae82018-05-21 20:26:49 +0000318 TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
Peter Collingbourne2527cbc2018-05-21 20:56:28 +0000319 DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
Peter Collingbourneaadeae82018-05-21 20:26:49 +0000320 if (EC)
321 report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
Yunlian Jiangedd00e42018-04-13 05:03:28 +0000322 }
323
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000324 auto Stream = AddStream(Task);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000325 legacy::PassManager CodeGenPasses;
Peter Collingbourneaadeae82018-05-21 20:26:49 +0000326 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
327 DwoOut ? &DwoOut->os() : nullptr,
Peter Collingbourne9ffe0732018-05-21 20:16:41 +0000328 Conf.CGFileType))
Teresa Johnson2d320e52016-08-11 14:58:12 +0000329 report_fatal_error("Failed to setup codegen");
Davide Italiano5c494e72016-09-07 01:08:31 +0000330 CodeGenPasses.run(Mod);
Peter Collingbourneaadeae82018-05-21 20:26:49 +0000331
332 if (DwoOut)
333 DwoOut->keep();
Teresa Johnson2d320e52016-08-11 14:58:12 +0000334}
335
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000336void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
Teresa Johnson2d320e52016-08-11 14:58:12 +0000337 unsigned ParallelCodeGenParallelismLevel,
Davide Italiano5c494e72016-09-07 01:08:31 +0000338 std::unique_ptr<Module> Mod) {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000339 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
340 unsigned ThreadCount = 0;
341 const Target *T = &TM->getTarget();
342
343 SplitModule(
Davide Italiano5c494e72016-09-07 01:08:31 +0000344 std::move(Mod), ParallelCodeGenParallelismLevel,
Teresa Johnson2d320e52016-08-11 14:58:12 +0000345 [&](std::unique_ptr<Module> MPart) {
346 // We want to clone the module in a new context to multi-thread the
347 // codegen. We do it by serializing partition modules to bitcode
348 // (while still on the main thread, in order to avoid data races) and
349 // spinning up new threads which deserialize the partitions into
350 // separate contexts.
351 // FIXME: Provide a more direct way to do this in LLVM.
352 SmallString<0> BC;
353 raw_svector_ostream BCOS(BC);
Rafael Espindola06d62072018-02-14 19:11:32 +0000354 WriteBitcodeToFile(*MPart, BCOS);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000355
356 // Enqueue the task
357 CodegenThreadPool.async(
358 [&](const SmallString<0> &BC, unsigned ThreadId) {
359 LTOLLVMContext Ctx(C);
Peter Collingbournedead0812016-11-13 07:00:17 +0000360 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
Teresa Johnson2d320e52016-08-11 14:58:12 +0000361 MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
362 Ctx);
363 if (!MOrErr)
364 report_fatal_error("Failed to read bitcode");
365 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
366
367 std::unique_ptr<TargetMachine> TM =
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000368 createTargetMachine(C, T, *MPartInCtx);
Mehdi Amini242275b2016-08-23 21:30:12 +0000369
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000370 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000371 },
372 // Pass BC using std::move to ensure that it get moved rather than
373 // copied into the thread's context.
374 std::move(BC), ThreadCount++);
375 },
376 false);
Peter Collingbourne8579d6c2016-09-29 03:29:28 +0000377
378 // Because the inner lambda (which runs in a worker thread) captures our local
379 // variables, we need to wait for the worker threads to terminate before we
380 // can leave the function scope.
Peter Collingbourne0b61d072016-09-29 01:28:36 +0000381 CodegenThreadPool.wait();
Teresa Johnson2d320e52016-08-11 14:58:12 +0000382}
383
Davide Italiano5c494e72016-09-07 01:08:31 +0000384Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
Teresa Johnson2d320e52016-08-11 14:58:12 +0000385 if (!C.OverrideTriple.empty())
Davide Italiano5c494e72016-09-07 01:08:31 +0000386 Mod.setTargetTriple(C.OverrideTriple);
387 else if (Mod.getTargetTriple().empty())
388 Mod.setTargetTriple(C.DefaultTriple);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000389
390 std::string Msg;
Davide Italiano5c494e72016-09-07 01:08:31 +0000391 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000392 if (!T)
393 return make_error<StringError>(Msg, inconvertibleErrorCode());
394 return T;
395}
396
397}
398
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000399static Error
Reid Kleckner97ca9642017-09-23 01:03:17 +0000400finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
Davide Italiano92b9c722017-02-13 14:39:51 +0000401 // Make sure we flush the diagnostic remarks file in case the linker doesn't
402 // call the global destructors before exiting.
403 if (!DiagOutputFile)
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000404 return Error::success();
Davide Italiano92b9c722017-02-13 14:39:51 +0000405 DiagOutputFile->keep();
406 DiagOutputFile->os().flush();
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000407 return Error::success();
Davide Italiano92b9c722017-02-13 14:39:51 +0000408}
409
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000410Error lto::backend(Config &C, AddStreamFn AddStream,
Teresa Johnson2d320e52016-08-11 14:58:12 +0000411 unsigned ParallelCodeGenParallelismLevel,
Peter Collingbourne87d73e92017-01-20 22:18:52 +0000412 std::unique_ptr<Module> Mod,
413 ModuleSummaryIndex &CombinedIndex) {
Davide Italiano5c494e72016-09-07 01:08:31 +0000414 Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000415 if (!TOrErr)
416 return TOrErr.takeError();
417
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000418 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000419
Davide Italiano9c7400c2017-02-12 03:31:30 +0000420 // Setup optimization remarks.
421 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarman17f0b882018-03-08 01:13:10 +0000422 Mod->getContext(), C.RemarksFilename, C.RemarksWithHotness);
Davide Italiano9c7400c2017-02-12 03:31:30 +0000423 if (!DiagFileOrErr)
424 return DiagFileOrErr.takeError();
Davide Italiano92b9c722017-02-13 14:39:51 +0000425 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
Davide Italiano9c7400c2017-02-12 03:31:30 +0000426
Davide Italiano92b9c722017-02-13 14:39:51 +0000427 if (!C.CodeGenOnly) {
Peter Collingbournee53e5852017-03-22 18:22:59 +0000428 if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000429 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
430 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Davide Italiano92b9c722017-02-13 14:39:51 +0000431 }
Teresa Johnson2d320e52016-08-11 14:58:12 +0000432
Mehdi Amini242275b2016-08-23 21:30:12 +0000433 if (ParallelCodeGenParallelismLevel == 1) {
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000434 codegen(C, TM.get(), AddStream, 0, *Mod);
Mehdi Amini242275b2016-08-23 21:30:12 +0000435 } else {
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000436 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
Davide Italiano5c494e72016-09-07 01:08:31 +0000437 std::move(Mod));
Mehdi Amini242275b2016-08-23 21:30:12 +0000438 }
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000439 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000440}
441
George Rimar426dcef2018-01-29 08:03:30 +0000442static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
443 const ModuleSummaryIndex &Index) {
Teresa Johnsondfa57662018-02-06 00:43:39 +0000444 std::vector<GlobalValue*> DeadGVs;
Teresa Johnsonb46c3d92018-02-05 15:44:27 +0000445 for (auto &GV : Mod.global_values())
George Rimar16a6b672018-02-02 12:21:26 +0000446 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
Teresa Johnsondfa57662018-02-06 00:43:39 +0000447 if (!Index.isGlobalValueLive(GVS)) {
448 DeadGVs.push_back(&GV);
449 convertToDeclaration(GV);
450 }
George Rimar89df7492018-02-02 12:17:33 +0000451
Teresa Johnsondfa57662018-02-06 00:43:39 +0000452 // Now that all dead bodies have been dropped, delete the actual objects
453 // themselves when possible.
454 for (GlobalValue *GV : DeadGVs) {
455 GV->removeDeadConstantUsers();
456 // Might reference something defined in native object (i.e. dropped a
457 // non-prevailing IR def, but we need to keep the declaration).
458 if (GV->use_empty())
459 GV->eraseFromParent();
460 }
George Rimar426dcef2018-01-29 08:03:30 +0000461}
462
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000463Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
Peter Collingbournee53e5852017-03-22 18:22:59 +0000464 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
Teresa Johnson2d320e52016-08-11 14:58:12 +0000465 const FunctionImporter::ImportMapTy &ImportList,
466 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne08850162016-12-14 01:17:59 +0000467 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminicbcae432016-08-16 00:44:46 +0000468 Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000469 if (!TOrErr)
470 return TOrErr.takeError();
471
Evgeniy Stepanov49f70cc2017-05-22 21:11:35 +0000472 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000473
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000474 // Setup optimization remarks.
475 auto DiagFileOrErr = lto::setupOptimizationRemarks(
476 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksWithHotness, Task);
477 if (!DiagFileOrErr)
478 return DiagFileOrErr.takeError();
479 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
480
Mehdi Amini1282b192016-08-22 06:25:41 +0000481 if (Conf.CodeGenOnly) {
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000482 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000483 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Mehdi Amini1282b192016-08-22 06:25:41 +0000484 }
485
Mehdi Aminicbcae432016-08-16 00:44:46 +0000486 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000487 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000488
Mehdi Aminicbcae432016-08-16 00:44:46 +0000489 renameModuleForThinLTO(Mod, CombinedIndex);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000490
George Rimar426dcef2018-01-29 08:03:30 +0000491 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
492
Pirama Arumuga Nainar32530662018-11-08 20:10:07 +0000493 thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
Mehdi Aminidcd27e42016-08-18 00:59:24 +0000494
Mehdi Aminicbcae432016-08-16 00:44:46 +0000495 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000496 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000497
498 if (!DefinedGlobals.empty())
Mehdi Aminicbcae432016-08-16 00:44:46 +0000499 thinLTOInternalizeModule(Mod, DefinedGlobals);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000500
Mehdi Aminicbcae432016-08-16 00:44:46 +0000501 if (Conf.PostInternalizeModuleHook &&
502 !Conf.PostInternalizeModuleHook(Task, Mod))
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000503 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000504
505 auto ModuleLoader = [&](StringRef Identifier) {
Mehdi Amini52a318c2016-08-23 16:53:34 +0000506 assert(Mod.getContext().isODRUniquingDebugTypes() &&
Davide Italianod41f2272016-09-14 18:48:43 +0000507 "ODR Type uniquing should be enabled on the context");
Peter Collingbourne08850162016-12-14 01:17:59 +0000508 auto I = ModuleMap.find(Identifier);
509 assert(I != ModuleMap.end());
510 return I->second.getLazyModule(Mod.getContext(),
Teresa Johnsonf6380132016-12-16 21:25:01 +0000511 /*ShouldLazyLoadMetadata=*/true,
512 /*IsImporting*/ true);
Teresa Johnson2d320e52016-08-11 14:58:12 +0000513 };
514
515 FunctionImporter Importer(CombinedIndex, ModuleLoader);
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000516 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
517 return Err;
Teresa Johnson2d320e52016-08-11 14:58:12 +0000518
Mehdi Aminicbcae432016-08-16 00:44:46 +0000519 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000520 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000521
Peter Collingbournee53e5852017-03-22 18:22:59 +0000522 if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
523 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000524 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000525
Peter Collingbourne91d99c62016-09-23 21:33:43 +0000526 codegen(Conf, TM.get(), AddStream, Task, Mod);
Teresa Johnson3a0c2762018-05-03 20:24:12 +0000527 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
Teresa Johnson2d320e52016-08-11 14:58:12 +0000528}