blob: 0e8006a3b32aa35f805bdc8fd5b8851c3935fcbd [file] [log] [blame]
Rui Ueyama25992482016-03-22 20:52:10 +00001//===- LTO.cpp ------------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "LTO.h"
11#include "Config.h"
Rafael Espindola156f4ee2016-04-28 19:30:41 +000012#include "Driver.h"
Rui Ueyama25992482016-03-22 20:52:10 +000013#include "Error.h"
14#include "InputFiles.h"
15#include "Symbols.h"
Davide Italianod26c4a12016-05-15 19:29:38 +000016#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/CGSCCPassManager.h"
18#include "llvm/Analysis/LoopPassManager.h"
Rui Ueyama25992482016-03-22 20:52:10 +000019#include "llvm/Analysis/TargetLibraryInfo.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
21#include "llvm/Bitcode/ReaderWriter.h"
Davide Italiano8eca2822016-04-01 00:35:29 +000022#include "llvm/CodeGen/CommandFlags.h"
Davide Italianobc176632016-04-15 22:38:10 +000023#include "llvm/CodeGen/ParallelCG.h"
Davide Italiano334fce92016-05-11 01:07:22 +000024#include "llvm/IR/AutoUpgrade.h"
Rui Ueyama25992482016-03-22 20:52:10 +000025#include "llvm/IR/LegacyPassManager.h"
Davide Italianod26c4a12016-05-15 19:29:38 +000026#include "llvm/IR/PassManager.h"
Davide Italiano5020d2a2016-05-15 19:43:02 +000027#include "llvm/IR/Verifier.h"
Peter Collingbourne6ccb2572016-07-14 21:21:20 +000028#include "llvm/LTO/legacy/UpdateCompilerUsed.h"
Rui Ueyama25992482016-03-22 20:52:10 +000029#include "llvm/Linker/IRMover.h"
Davide Italianod26c4a12016-05-15 19:29:38 +000030#include "llvm/Passes/PassBuilder.h"
Rui Ueyama25992482016-03-22 20:52:10 +000031#include "llvm/Support/StringSaver.h"
32#include "llvm/Support/TargetRegistry.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Transforms/IPO.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Rafael Espindola9fdd0712016-04-27 23:54:04 +000036#include "llvm/Transforms/Utils/ModuleUtils.h"
Rui Ueyama25992482016-03-22 20:52:10 +000037
38using namespace llvm;
39using namespace llvm::object;
40using namespace llvm::ELF;
41
42using namespace lld;
43using namespace lld::elf;
44
45// This is for use when debugging LTO.
Rui Ueyama48da5cf2016-07-15 02:17:13 +000046static void saveBuffer(StringRef Buffer, const Twine &Path) {
Rui Ueyama25992482016-03-22 20:52:10 +000047 std::error_code EC;
Rui Ueyama48da5cf2016-07-15 02:17:13 +000048 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
Rui Ueyamaf8292e92016-07-15 02:01:03 +000049 if (EC)
50 error(EC, "cannot create " + Path);
Rui Ueyama25992482016-03-22 20:52:10 +000051 OS << Buffer;
52}
53
54// This is for use when debugging LTO.
Rui Ueyama48da5cf2016-07-15 02:17:13 +000055static void saveBCFile(Module &M, const Twine &Path) {
Rui Ueyama25992482016-03-22 20:52:10 +000056 std::error_code EC;
Rui Ueyama48da5cf2016-07-15 02:17:13 +000057 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
Rui Ueyamaf8292e92016-07-15 02:01:03 +000058 if (EC)
59 error(EC, "cannot create " + Path);
Rui Ueyama25992482016-03-22 20:52:10 +000060 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
61}
62
Davide Italianod26c4a12016-05-15 19:29:38 +000063static void runNewCustomLtoPasses(Module &M, TargetMachine &TM) {
64 PassBuilder PB(&TM);
65
66 AAManager AA;
Davide Italianodf24d5b2016-06-02 22:58:11 +000067
68 // Parse a custom AA pipeline if asked to.
69 if (!PB.parseAAPipeline(AA, Config->LtoAAPipeline)) {
70 error("Unable to parse AA pipeline description: " + Config->LtoAAPipeline);
71 return;
72 }
73
Davide Italianod26c4a12016-05-15 19:29:38 +000074 LoopAnalysisManager LAM;
75 FunctionAnalysisManager FAM;
76 CGSCCAnalysisManager CGAM;
77 ModuleAnalysisManager MAM;
78
79 // Register the AA manager first so that our version is the one used.
80 FAM.registerPass([&] { return std::move(AA); });
81
82 // Register all the basic analyses with the managers.
83 PB.registerModuleAnalyses(MAM);
84 PB.registerCGSCCAnalyses(CGAM);
85 PB.registerFunctionAnalyses(FAM);
86 PB.registerLoopAnalyses(LAM);
87 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
88
89 ModulePassManager MPM;
90 if (!Config->DisableVerify)
91 MPM.addPass(VerifierPass());
92
93 // Now, add all the passes we've been requested to.
94 if (!PB.parsePassPipeline(MPM, Config->LtoNewPmPasses)) {
95 error("unable to parse pass pipeline description: " +
96 Config->LtoNewPmPasses);
97 return;
98 }
99
100 if (!Config->DisableVerify)
101 MPM.addPass(VerifierPass());
102 MPM.run(M, MAM);
103}
104
105static void runOldLtoPasses(Module &M, TargetMachine &TM) {
106 // Note that the gold plugin has a similar piece of code, so
107 // it is probably better to move this code to a common place.
Rui Ueyama25992482016-03-22 20:52:10 +0000108 legacy::PassManager LtoPasses;
109 LtoPasses.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
110 PassManagerBuilder PMB;
111 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
112 PMB.Inliner = createFunctionInliningPass();
Davide Italiano842fa532016-04-03 03:39:09 +0000113 PMB.VerifyInput = PMB.VerifyOutput = !Config->DisableVerify;
Rui Ueyama25992482016-03-22 20:52:10 +0000114 PMB.LoopVectorize = true;
115 PMB.SLPVectorize = true;
Peter Collingbourneed22f9b2016-03-31 21:00:27 +0000116 PMB.OptLevel = Config->LtoO;
Rui Ueyama25992482016-03-22 20:52:10 +0000117 PMB.populateLTOPassManager(LtoPasses);
118 LtoPasses.run(M);
Davide Italianod26c4a12016-05-15 19:29:38 +0000119}
120
121static void runLTOPasses(Module &M, TargetMachine &TM) {
122 if (!Config->LtoNewPmPasses.empty()) {
123 // The user explicitly asked for a set of passes to be run.
124 // This needs the new PM to work as there's no clean way to
125 // pass a set of passes to run in the legacy PM.
126 runNewCustomLtoPasses(M, TM);
127 if (HasError)
128 return;
129 } else {
130 // Run the 'default' set of LTO passes. This code still uses
131 // the legacy PM as the new one is not the default.
132 runOldLtoPasses(M, TM);
133 }
Rui Ueyama25992482016-03-22 20:52:10 +0000134
135 if (Config->SaveTemps)
Rui Ueyama48da5cf2016-07-15 02:17:13 +0000136 saveBCFile(M, Config->OutputFile + ".lto.opt.bc");
Rui Ueyama25992482016-03-22 20:52:10 +0000137}
138
Rafael Espindolaae605c12016-04-21 20:35:25 +0000139static bool shouldInternalize(const SmallPtrSet<GlobalValue *, 8> &Used,
Peter Collingbourne4f952702016-05-01 04:55:03 +0000140 Symbol *S, GlobalValue *GV) {
Davide Italiano39356902016-06-11 14:21:38 +0000141 if (S->IsUsedInRegularObj || Used.count(GV))
Rafael Espindolaae605c12016-04-21 20:35:25 +0000142 return false;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000143 return !S->includeInDynsym();
Rafael Espindolaae605c12016-04-21 20:35:25 +0000144}
145
Rui Ueyama412c8022016-04-22 21:16:18 +0000146BitcodeCompiler::BitcodeCompiler()
Rui Ueyama818bb2f2016-07-16 18:55:47 +0000147 : Combined(new Module("ld-temp.o", Driver->Context)) {}
Rui Ueyama412c8022016-04-22 21:16:18 +0000148
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000149static void undefine(Symbol *S) {
Rui Ueyama434b5612016-07-17 03:11:46 +0000150 replaceBody<Undefined>(S, S->body()->getName(), STV_DEFAULT, S->body()->Type,
151 nullptr);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000152}
153
Davide Italiano595ee8c2016-06-22 18:09:23 +0000154static void handleUndefinedAsmRefs(const BasicSymbolRef &Sym, GlobalValue *GV,
155 StringSet<> &AsmUndefinedRefs) {
156 // GV associated => not an assembly symbol, bail out.
157 if (GV)
158 return;
159
160 // This is an undefined reference to a symbol in asm. We put that in
161 // compiler.used, so that we can preserve it from being dropped from
162 // the output, without necessarily preventing its internalization.
163 SmallString<64> Name;
164 raw_svector_ostream OS(Name);
165 Sym.printName(OS);
166 AsmUndefinedRefs.insert(Name.str());
167}
168
Rui Ueyama25992482016-03-22 20:52:10 +0000169void BitcodeCompiler::add(BitcodeFile &F) {
Rafael Espindola156f4ee2016-04-28 19:30:41 +0000170 std::unique_ptr<IRObjectFile> Obj = std::move(F.Obj);
Rui Ueyama25992482016-03-22 20:52:10 +0000171 std::vector<GlobalValue *> Keep;
172 unsigned BodyIndex = 0;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000173 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyama25992482016-03-22 20:52:10 +0000174
Davide Italiano86f2bd52016-03-29 21:46:35 +0000175 Module &M = Obj->getModule();
Davide Italiano493b6832016-04-16 01:33:33 +0000176 if (M.getDataLayoutStr().empty())
177 fatal("invalid bitcode file: " + F.getName() + " has no datalayout");
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000178
Davide Italiano334fce92016-05-11 01:07:22 +0000179 // Discard non-compatible debug infos if necessary.
180 M.materializeMetadata();
181 UpgradeDebugInfo(M);
182
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000183 // If a symbol appears in @llvm.used, the linker is required
184 // to treat the symbol as there is a reference to the symbol
185 // that it cannot see. Therefore, we can't internalize.
Davide Italiano86f2bd52016-03-29 21:46:35 +0000186 SmallPtrSet<GlobalValue *, 8> Used;
187 collectUsedGlobalVariables(M, Used, /* CompilerUsed */ false);
188
Rui Ueyama25992482016-03-22 20:52:10 +0000189 for (const BasicSymbolRef &Sym : Obj->symbols()) {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000190 uint32_t Flags = Sym.getFlags();
Rui Ueyama25992482016-03-22 20:52:10 +0000191 GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
Peter Collingbourne4f952702016-05-01 04:55:03 +0000192 if (GV && GV->hasAppendingLinkage())
Rui Ueyama25992482016-03-22 20:52:10 +0000193 Keep.push_back(GV);
Peter Collingbourne4f952702016-05-01 04:55:03 +0000194 if (BitcodeFile::shouldSkip(Flags))
195 continue;
196 Symbol *S = Syms[BodyIndex++];
Davide Italiano595ee8c2016-06-22 18:09:23 +0000197 if (Flags & BasicSymbolRef::SF_Undefined) {
198 handleUndefinedAsmRefs(Sym, GV, AsmUndefinedRefs);
Peter Collingbourne4f952702016-05-01 04:55:03 +0000199 continue;
Davide Italiano595ee8c2016-06-22 18:09:23 +0000200 }
Peter Collingbourne4f952702016-05-01 04:55:03 +0000201 auto *B = dyn_cast<DefinedBitcode>(S->body());
Rui Ueyama434b5612016-07-17 03:11:46 +0000202 if (!B || B->file() != &F)
Davide Italiano1460e9f2016-03-26 18:33:09 +0000203 continue;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000204
205 // We collect the set of symbols we want to internalize here
206 // and change the linkage after the IRMover executed, i.e. after
207 // we imported the symbols and satisfied undefined references
208 // to it. We can't just change linkage here because otherwise
209 // the IRMover will just rename the symbol.
210 if (GV && shouldInternalize(Used, S, GV))
211 InternalizedSyms.insert(GV->getName());
212
213 // At this point we know that either the combined LTO object will provide a
214 // definition of a symbol, or we will internalize it. In either case, we
215 // need to undefine the symbol. In the former case, the real definition
216 // needs to be able to replace the original definition without conflicting.
217 // In the latter case, we need to allow the combined LTO object to provide a
218 // definition with the same name, for example when doing parallel codegen.
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000219 undefine(S);
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000220
221 if (!GV)
222 // Module asm symbol.
223 continue;
224
Davide Italiano1460e9f2016-03-26 18:33:09 +0000225 switch (GV->getLinkage()) {
226 default:
227 break;
Rui Ueyama818bb2f2016-07-16 18:55:47 +0000228 case GlobalValue::LinkOnceAnyLinkage:
Davide Italiano1460e9f2016-03-26 18:33:09 +0000229 GV->setLinkage(GlobalValue::WeakAnyLinkage);
230 break;
Rui Ueyama818bb2f2016-07-16 18:55:47 +0000231 case GlobalValue::LinkOnceODRLinkage:
Davide Italiano1460e9f2016-03-26 18:33:09 +0000232 GV->setLinkage(GlobalValue::WeakODRLinkage);
233 break;
Davide Italianod4c2a032016-03-22 22:31:34 +0000234 }
Davide Italiano828ac5412016-03-28 15:44:21 +0000235
Davide Italiano1460e9f2016-03-26 18:33:09 +0000236 Keep.push_back(GV);
Rui Ueyama25992482016-03-22 20:52:10 +0000237 }
238
Rui Ueyama601b07c2016-07-15 03:06:42 +0000239 IRMover Mover(*Combined);
Peter Collingbourne5079f3b2016-05-27 05:21:45 +0000240 if (Error E = Mover.move(Obj->takeModule(), Keep,
241 [](GlobalValue &, IRMover::ValueAdder) {})) {
Rui Ueyama818bb2f2016-07-16 18:55:47 +0000242 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EIB) {
Peter Collingbourne5079f3b2016-05-27 05:21:45 +0000243 fatal("failed to link module " + F.getName() + ": " + EIB.message());
244 });
245 }
Rui Ueyama25992482016-03-22 20:52:10 +0000246}
247
Davide Italiano828ac5412016-03-28 15:44:21 +0000248static void internalize(GlobalValue &GV) {
249 assert(!GV.hasLocalLinkage() &&
Davide Italiano47c33f02016-03-29 21:48:25 +0000250 "Trying to internalize a symbol with local linkage!");
Davide Italiano828ac5412016-03-28 15:44:21 +0000251 GV.setLinkage(GlobalValue::InternalLinkage);
252}
253
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000254std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::runSplitCodegen(
255 const std::function<std::unique_ptr<TargetMachine>()> &TMFactory) {
Davide Italianobc176632016-04-15 22:38:10 +0000256 unsigned NumThreads = Config->LtoJobs;
257 OwningData.resize(NumThreads);
258
259 std::list<raw_svector_ostream> OSs;
260 std::vector<raw_pwrite_stream *> OSPtrs;
261 for (SmallString<0> &Obj : OwningData) {
262 OSs.emplace_back(Obj);
263 OSPtrs.push_back(&OSs.back());
264 }
265
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000266 splitCodeGen(std::move(Combined), OSPtrs, {}, TMFactory);
Davide Italianobc176632016-04-15 22:38:10 +0000267
268 std::vector<std::unique_ptr<InputFile>> ObjFiles;
269 for (SmallString<0> &Obj : OwningData)
270 ObjFiles.push_back(createObjectFile(
271 MemoryBufferRef(Obj, "LLD-INTERNAL-combined-lto-object")));
272
Rui Ueyama48da5cf2016-07-15 02:17:13 +0000273 // If -save-temps is given, we need to save temporary objects to files.
274 // This is for debugging.
275 if (Config->SaveTemps) {
276 if (NumThreads == 1) {
277 saveBuffer(OwningData[0], Config->OutputFile + ".lto.o");
278 } else {
279 for (unsigned I = 0; I < NumThreads; ++I)
280 saveBuffer(OwningData[I], Config->OutputFile + Twine(I) + ".lto.o");
281 }
282 }
Davide Italianobc176632016-04-15 22:38:10 +0000283
284 return ObjFiles;
285}
286
Rui Ueyama25992482016-03-22 20:52:10 +0000287// Merge all the bitcode files we have seen, codegen the result
288// and return the resulting ObjectFile.
Davide Italianobc176632016-04-15 22:38:10 +0000289std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::compile() {
Davide Italiano828ac5412016-03-28 15:44:21 +0000290 for (const auto &Name : InternalizedSyms) {
Davide Italiano15c41b22016-04-11 22:39:51 +0000291 GlobalValue *GV = Combined->getNamedValue(Name.first());
Davide Italiano828ac5412016-03-28 15:44:21 +0000292 assert(GV);
293 internalize(*GV);
294 }
295
Rui Ueyama601b07c2016-07-15 03:06:42 +0000296 std::string TheTriple = Combined->getTargetTriple();
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000297 std::string Msg;
Davide Italianobc176632016-04-15 22:38:10 +0000298 const Target *T = TargetRegistry::lookupTarget(TheTriple, Msg);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000299 if (!T)
300 fatal("target not found: " + Msg);
Rafael Espindola254b58d2016-06-21 14:47:43 +0000301
Rui Ueyamaa9d9eda2016-07-15 02:42:18 +0000302 // LLD supports the new relocations.
303 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola254b58d2016-06-21 14:47:43 +0000304 Options.RelaxELFRelocations = true;
305
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000306 auto CreateTargetMachine = [&]() {
Rui Ueyamaa9d9eda2016-07-15 02:42:18 +0000307 return std::unique_ptr<TargetMachine>(T->createTargetMachine(
308 TheTriple, "", "", Options, Config->Pic ? Reloc::PIC_ : Reloc::Static));
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000309 };
310
311 std::unique_ptr<TargetMachine> TM = CreateTargetMachine();
Davide Italiano595ee8c2016-06-22 18:09:23 +0000312
313 // Update llvm.compiler.used so that optimizations won't strip
314 // off AsmUndefinedReferences.
Davide Italiano30afae12016-06-22 19:51:05 +0000315 updateCompilerUsed(*Combined, *TM, AsmUndefinedRefs);
Davide Italiano595ee8c2016-06-22 18:09:23 +0000316
317 if (Config->SaveTemps)
Rui Ueyama48da5cf2016-07-15 02:17:13 +0000318 saveBCFile(*Combined, Config->OutputFile + ".lto.bc");
Davide Italiano595ee8c2016-06-22 18:09:23 +0000319
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000320 runLTOPasses(*Combined, *TM);
Davide Italianod26c4a12016-05-15 19:29:38 +0000321 if (HasError)
322 return {};
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000323
324 return runSplitCodegen(CreateTargetMachine);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000325}