blob: dc087bb443e2cd5fb4d57d179da58918a8e6c91f [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"
Rui Ueyama25992482016-03-22 20:52:10 +000028#include "llvm/Linker/IRMover.h"
Davide Italianod26c4a12016-05-15 19:29:38 +000029#include "llvm/Passes/PassBuilder.h"
Rui Ueyama25992482016-03-22 20:52:10 +000030#include "llvm/Support/StringSaver.h"
31#include "llvm/Support/TargetRegistry.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Transforms/IPO.h"
34#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Rafael Espindola9fdd0712016-04-27 23:54:04 +000035#include "llvm/Transforms/Utils/ModuleUtils.h"
Rui Ueyama25992482016-03-22 20:52:10 +000036
37using namespace llvm;
38using namespace llvm::object;
39using namespace llvm::ELF;
40
41using namespace lld;
42using namespace lld::elf;
43
44// This is for use when debugging LTO.
Davide Italianobc176632016-04-15 22:38:10 +000045static void saveLtoObjectFile(StringRef Buffer, unsigned I, bool Many) {
46 SmallString<128> Filename = Config->OutputFile;
47 if (Many)
48 Filename += utostr(I);
49 Filename += ".lto.o";
Rui Ueyama25992482016-03-22 20:52:10 +000050 std::error_code EC;
Davide Italianobc176632016-04-15 22:38:10 +000051 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
Rui Ueyama25992482016-03-22 20:52:10 +000052 check(EC);
53 OS << Buffer;
54}
55
56// This is for use when debugging LTO.
57static void saveBCFile(Module &M, StringRef Suffix) {
58 std::error_code EC;
59 raw_fd_ostream OS(Config->OutputFile.str() + Suffix.str(), EC,
60 sys::fs::OpenFlags::F_None);
61 check(EC);
62 WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
63}
64
Davide Italianod26c4a12016-05-15 19:29:38 +000065static void runNewCustomLtoPasses(Module &M, TargetMachine &TM) {
66 PassBuilder PB(&TM);
67
68 AAManager AA;
69 LoopAnalysisManager LAM;
70 FunctionAnalysisManager FAM;
71 CGSCCAnalysisManager CGAM;
72 ModuleAnalysisManager MAM;
73
74 // Register the AA manager first so that our version is the one used.
75 FAM.registerPass([&] { return std::move(AA); });
76
77 // Register all the basic analyses with the managers.
78 PB.registerModuleAnalyses(MAM);
79 PB.registerCGSCCAnalyses(CGAM);
80 PB.registerFunctionAnalyses(FAM);
81 PB.registerLoopAnalyses(LAM);
82 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
83
84 ModulePassManager MPM;
85 if (!Config->DisableVerify)
86 MPM.addPass(VerifierPass());
87
88 // Now, add all the passes we've been requested to.
89 if (!PB.parsePassPipeline(MPM, Config->LtoNewPmPasses)) {
90 error("unable to parse pass pipeline description: " +
91 Config->LtoNewPmPasses);
92 return;
93 }
94
95 if (!Config->DisableVerify)
96 MPM.addPass(VerifierPass());
97 MPM.run(M, MAM);
98}
99
100static void runOldLtoPasses(Module &M, TargetMachine &TM) {
101 // Note that the gold plugin has a similar piece of code, so
102 // it is probably better to move this code to a common place.
Rui Ueyama25992482016-03-22 20:52:10 +0000103 legacy::PassManager LtoPasses;
104 LtoPasses.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
105 PassManagerBuilder PMB;
106 PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
107 PMB.Inliner = createFunctionInliningPass();
Davide Italiano842fa532016-04-03 03:39:09 +0000108 PMB.VerifyInput = PMB.VerifyOutput = !Config->DisableVerify;
Rui Ueyama25992482016-03-22 20:52:10 +0000109 PMB.LoopVectorize = true;
110 PMB.SLPVectorize = true;
Peter Collingbourneed22f9b2016-03-31 21:00:27 +0000111 PMB.OptLevel = Config->LtoO;
Rui Ueyama25992482016-03-22 20:52:10 +0000112 PMB.populateLTOPassManager(LtoPasses);
113 LtoPasses.run(M);
Davide Italianod26c4a12016-05-15 19:29:38 +0000114}
115
116static void runLTOPasses(Module &M, TargetMachine &TM) {
117 if (!Config->LtoNewPmPasses.empty()) {
118 // The user explicitly asked for a set of passes to be run.
119 // This needs the new PM to work as there's no clean way to
120 // pass a set of passes to run in the legacy PM.
121 runNewCustomLtoPasses(M, TM);
122 if (HasError)
123 return;
124 } else {
125 // Run the 'default' set of LTO passes. This code still uses
126 // the legacy PM as the new one is not the default.
127 runOldLtoPasses(M, TM);
128 }
Rui Ueyama25992482016-03-22 20:52:10 +0000129
130 if (Config->SaveTemps)
131 saveBCFile(M, ".lto.opt.bc");
132}
133
Rafael Espindolaae605c12016-04-21 20:35:25 +0000134static bool shouldInternalize(const SmallPtrSet<GlobalValue *, 8> &Used,
Peter Collingbourne4f952702016-05-01 04:55:03 +0000135 Symbol *S, GlobalValue *GV) {
136 if (S->IsUsedInRegularObj)
Rafael Espindolaae605c12016-04-21 20:35:25 +0000137 return false;
138
139 if (Used.count(GV))
140 return false;
141
Peter Collingbourne4f952702016-05-01 04:55:03 +0000142 return !S->includeInDynsym();
Rafael Espindolaae605c12016-04-21 20:35:25 +0000143}
144
Rui Ueyama412c8022016-04-22 21:16:18 +0000145BitcodeCompiler::BitcodeCompiler()
Rafael Espindola156f4ee2016-04-28 19:30:41 +0000146 : Combined(new llvm::Module("ld-temp.o", Driver->Context)),
147 Mover(*Combined) {}
Rui Ueyama412c8022016-04-22 21:16:18 +0000148
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000149static void undefine(Symbol *S) {
Davide Italiano64ebf322016-06-01 16:38:13 +0000150 replaceBody<Undefined>(S, S->body()->getName(), STV_DEFAULT, S->body()->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000151}
152
Rui Ueyama25992482016-03-22 20:52:10 +0000153void BitcodeCompiler::add(BitcodeFile &F) {
Rafael Espindola156f4ee2016-04-28 19:30:41 +0000154 std::unique_ptr<IRObjectFile> Obj = std::move(F.Obj);
Rui Ueyama25992482016-03-22 20:52:10 +0000155 std::vector<GlobalValue *> Keep;
156 unsigned BodyIndex = 0;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000157 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyama25992482016-03-22 20:52:10 +0000158
Davide Italiano86f2bd52016-03-29 21:46:35 +0000159 Module &M = Obj->getModule();
Davide Italiano493b6832016-04-16 01:33:33 +0000160 if (M.getDataLayoutStr().empty())
161 fatal("invalid bitcode file: " + F.getName() + " has no datalayout");
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000162
Davide Italiano334fce92016-05-11 01:07:22 +0000163 // Discard non-compatible debug infos if necessary.
164 M.materializeMetadata();
165 UpgradeDebugInfo(M);
166
Davide Italiano49fe4ed2016-03-29 23:57:22 +0000167 // If a symbol appears in @llvm.used, the linker is required
168 // to treat the symbol as there is a reference to the symbol
169 // that it cannot see. Therefore, we can't internalize.
Davide Italiano86f2bd52016-03-29 21:46:35 +0000170 SmallPtrSet<GlobalValue *, 8> Used;
171 collectUsedGlobalVariables(M, Used, /* CompilerUsed */ false);
172
Rui Ueyama25992482016-03-22 20:52:10 +0000173 for (const BasicSymbolRef &Sym : Obj->symbols()) {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000174 uint32_t Flags = Sym.getFlags();
Rui Ueyama25992482016-03-22 20:52:10 +0000175 GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
Peter Collingbourne4f952702016-05-01 04:55:03 +0000176 if (GV && GV->hasAppendingLinkage())
Rui Ueyama25992482016-03-22 20:52:10 +0000177 Keep.push_back(GV);
Peter Collingbourne4f952702016-05-01 04:55:03 +0000178 if (BitcodeFile::shouldSkip(Flags))
179 continue;
180 Symbol *S = Syms[BodyIndex++];
181 if (Flags & BasicSymbolRef::SF_Undefined)
182 continue;
Peter Collingbourne4f952702016-05-01 04:55:03 +0000183 auto *B = dyn_cast<DefinedBitcode>(S->body());
184 if (!B || B->File != &F)
Davide Italiano1460e9f2016-03-26 18:33:09 +0000185 continue;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000186
187 // We collect the set of symbols we want to internalize here
188 // and change the linkage after the IRMover executed, i.e. after
189 // we imported the symbols and satisfied undefined references
190 // to it. We can't just change linkage here because otherwise
191 // the IRMover will just rename the symbol.
192 if (GV && shouldInternalize(Used, S, GV))
193 InternalizedSyms.insert(GV->getName());
194
195 // At this point we know that either the combined LTO object will provide a
196 // definition of a symbol, or we will internalize it. In either case, we
197 // need to undefine the symbol. In the former case, the real definition
198 // needs to be able to replace the original definition without conflicting.
199 // In the latter case, we need to allow the combined LTO object to provide a
200 // definition with the same name, for example when doing parallel codegen.
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000201 undefine(S);
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000202
203 if (!GV)
204 // Module asm symbol.
205 continue;
206
Davide Italiano1460e9f2016-03-26 18:33:09 +0000207 switch (GV->getLinkage()) {
208 default:
209 break;
210 case llvm::GlobalValue::LinkOnceAnyLinkage:
211 GV->setLinkage(GlobalValue::WeakAnyLinkage);
212 break;
213 case llvm::GlobalValue::LinkOnceODRLinkage:
214 GV->setLinkage(GlobalValue::WeakODRLinkage);
215 break;
Davide Italianod4c2a032016-03-22 22:31:34 +0000216 }
Davide Italiano828ac5412016-03-28 15:44:21 +0000217
Davide Italiano1460e9f2016-03-26 18:33:09 +0000218 Keep.push_back(GV);
Rui Ueyama25992482016-03-22 20:52:10 +0000219 }
220
Peter Collingbourne5079f3b2016-05-27 05:21:45 +0000221 if (Error E = Mover.move(Obj->takeModule(), Keep,
222 [](GlobalValue &, IRMover::ValueAdder) {})) {
223 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
224 fatal("failed to link module " + F.getName() + ": " + EIB.message());
225 });
226 }
Rui Ueyama25992482016-03-22 20:52:10 +0000227}
228
Davide Italiano828ac5412016-03-28 15:44:21 +0000229static void internalize(GlobalValue &GV) {
230 assert(!GV.hasLocalLinkage() &&
Davide Italiano47c33f02016-03-29 21:48:25 +0000231 "Trying to internalize a symbol with local linkage!");
Davide Italiano828ac5412016-03-28 15:44:21 +0000232 GV.setLinkage(GlobalValue::InternalLinkage);
233}
234
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000235std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::runSplitCodegen(
236 const std::function<std::unique_ptr<TargetMachine>()> &TMFactory) {
Davide Italianobc176632016-04-15 22:38:10 +0000237 unsigned NumThreads = Config->LtoJobs;
238 OwningData.resize(NumThreads);
239
240 std::list<raw_svector_ostream> OSs;
241 std::vector<raw_pwrite_stream *> OSPtrs;
242 for (SmallString<0> &Obj : OwningData) {
243 OSs.emplace_back(Obj);
244 OSPtrs.push_back(&OSs.back());
245 }
246
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000247 splitCodeGen(std::move(Combined), OSPtrs, {}, TMFactory);
Davide Italianobc176632016-04-15 22:38:10 +0000248
249 std::vector<std::unique_ptr<InputFile>> ObjFiles;
250 for (SmallString<0> &Obj : OwningData)
251 ObjFiles.push_back(createObjectFile(
252 MemoryBufferRef(Obj, "LLD-INTERNAL-combined-lto-object")));
253
254 if (Config->SaveTemps)
255 for (unsigned I = 0; I < NumThreads; ++I)
256 saveLtoObjectFile(OwningData[I], I, NumThreads > 1);
257
258 return ObjFiles;
259}
260
Rui Ueyama25992482016-03-22 20:52:10 +0000261// Merge all the bitcode files we have seen, codegen the result
262// and return the resulting ObjectFile.
Davide Italianobc176632016-04-15 22:38:10 +0000263std::vector<std::unique_ptr<InputFile>> BitcodeCompiler::compile() {
264 TheTriple = Combined->getTargetTriple();
Davide Italiano828ac5412016-03-28 15:44:21 +0000265 for (const auto &Name : InternalizedSyms) {
Davide Italiano15c41b22016-04-11 22:39:51 +0000266 GlobalValue *GV = Combined->getNamedValue(Name.first());
Davide Italiano828ac5412016-03-28 15:44:21 +0000267 assert(GV);
268 internalize(*GV);
269 }
270
Rui Ueyama25992482016-03-22 20:52:10 +0000271 if (Config->SaveTemps)
Davide Italiano15c41b22016-04-11 22:39:51 +0000272 saveBCFile(*Combined, ".lto.bc");
Rui Ueyama25992482016-03-22 20:52:10 +0000273
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000274 std::string Msg;
Davide Italianobc176632016-04-15 22:38:10 +0000275 const Target *T = TargetRegistry::lookupTarget(TheTriple, Msg);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000276 if (!T)
277 fatal("target not found: " + Msg);
Davide Italiano8eca2822016-04-01 00:35:29 +0000278 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000279 Reloc::Model R = Config->Pic ? Reloc::PIC_ : Reloc::Static;
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000280
281 auto CreateTargetMachine = [&]() {
282 return std::unique_ptr<TargetMachine>(
283 T->createTargetMachine(TheTriple, "", "", Options, R));
284 };
285
286 std::unique_ptr<TargetMachine> TM = CreateTargetMachine();
287 runLTOPasses(*Combined, *TM);
Davide Italianod26c4a12016-05-15 19:29:38 +0000288 if (HasError)
289 return {};
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000290
291 return runSplitCodegen(CreateTargetMachine);
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000292}