blob: 09198591da9ca8bb4fceca393cc5a3c0eb29df53 [file] [log] [blame]
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
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 functions and classes used to support LTO.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000015#include "llvm/Analysis/TargetLibraryInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000017#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000019#include "llvm/CodeGen/Analysis.h"
20#include "llvm/IR/AutoUpgrade.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/LTO/LTOBackend.h"
24#include "llvm/Linker/IRMover.h"
25#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
26#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000027#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000028#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000029#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000030#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include "llvm/Support/TargetRegistry.h"
32#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000033#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000035#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
37#include "llvm/Transforms/IPO.h"
38#include "llvm/Transforms/IPO/PassManagerBuilder.h"
39#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000040
Teresa Johnson9ba95f92016-08-11 14:58:12 +000041#include <set>
42
43using namespace llvm;
44using namespace lto;
45using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000046
Mehdi Aminiadc0e262016-08-23 21:30:12 +000047#define DEBUG_TYPE "lto"
48
49// Returns a unique hash for the Module considering the current list of
50// export/import and other global analysis results.
51// The hash is produced in \p Key.
52static void computeCacheKey(
Peter Collingbournef4257522016-12-08 05:28:30 +000053 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
54 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +000055 const FunctionImporter::ExportSetTy &ExportList,
56 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
57 const GVSummaryMapTy &DefinedGlobals) {
58 // Compute the unique hash for this entry.
59 // This is based on the current compiler version, the module itself, the
60 // export list, the hash for every single module in the import list, the
61 // list of ResolvedODR for the module, and the list of preserved symbols.
62 SHA1 Hasher;
63
64 // Start with the compiler revision
65 Hasher.update(LLVM_VERSION_STRING);
66#ifdef HAVE_LLVM_REVISION
67 Hasher.update(LLVM_REVISION);
68#endif
69
Peter Collingbournef4257522016-12-08 05:28:30 +000070 // Include the parts of the LTO configuration that affect code generation.
71 auto AddString = [&](StringRef Str) {
72 Hasher.update(Str);
73 Hasher.update(ArrayRef<uint8_t>{0});
74 };
75 auto AddUnsigned = [&](unsigned I) {
76 uint8_t Data[4];
77 Data[0] = I;
78 Data[1] = I >> 8;
79 Data[2] = I >> 16;
80 Data[3] = I >> 24;
81 Hasher.update(ArrayRef<uint8_t>{Data, 4});
82 };
83 AddString(Conf.CPU);
84 // FIXME: Hash more of Options. For now all clients initialize Options from
85 // command-line flags (which is unsupported in production), but may set
86 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
87 // DataSections and DebuggerTuning via command line flags.
88 AddUnsigned(Conf.Options.RelaxELFRelocations);
89 AddUnsigned(Conf.Options.FunctionSections);
90 AddUnsigned(Conf.Options.DataSections);
91 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
92 for (auto &A : Conf.MAttrs)
93 AddString(A);
94 AddUnsigned(Conf.RelocModel);
95 AddUnsigned(Conf.CodeModel);
96 AddUnsigned(Conf.CGOptLevel);
97 AddUnsigned(Conf.OptLevel);
98 AddString(Conf.OptPipeline);
99 AddString(Conf.AAPipeline);
100 AddString(Conf.OverrideTriple);
101 AddString(Conf.DefaultTriple);
102
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000103 // Include the hash for the current module
104 auto ModHash = Index.getModuleHash(ModuleID);
105 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
106 for (auto F : ExportList)
107 // The export list can impact the internalization, be conservative here
108 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
109
110 // Include the hash for every module we import functions from
111 for (auto &Entry : ImportList) {
112 auto ModHash = Index.getModuleHash(Entry.first());
113 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
114 }
115
116 // Include the hash for the resolved ODR.
117 for (auto &Entry : ResolvedODR) {
118 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
119 sizeof(GlobalValue::GUID)));
120 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
121 sizeof(GlobalValue::LinkageTypes)));
122 }
123
124 // Include the hash for the linkage type to reflect internalization and weak
125 // resolution.
126 for (auto &GS : DefinedGlobals) {
127 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
128 Hasher.update(
129 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
130 }
131
Dehao Chen27978002016-12-16 16:48:46 +0000132 if (!Conf.SampleProfile.empty()) {
133 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
134 if (FileOrErr)
135 Hasher.update(FileOrErr.get()->getBuffer());
136 }
137
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000138 Key = toHex(Hasher.result());
139}
140
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000141static void thinLTOResolveWeakForLinkerGUID(
142 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
143 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000144 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000145 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000146 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000147 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000148 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000149 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
150 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
151 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000152 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000153 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000154 // This is both a compile-time optimization and a correctness
155 // transformation. This is necessary for correctness when we have exported
156 // a reference - we need to convert the linkonce to weak to
157 // ensure a copy is kept to satisfy the exported reference.
158 // FIXME: We may want to split the compile time and correctness
159 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000160 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000161 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
162 S->setLinkage(GlobalValue::getWeakLinkage(
163 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000164 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000165 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000166 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000167 !GlobalInvolvedWithAlias.count(S.get()) &&
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
169 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
170 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
171 if (S->linkage() != OriginalLinkage)
172 recordNewLinkage(S->modulePath(), GUID, S->linkage());
173 }
174}
175
176// Resolve Weak and LinkOnce values in the \p Index.
177//
178// We'd like to drop these functions if they are no longer referenced in the
179// current module. However there is a chance that another module is still
180// referencing them because of the import. We make sure we always emit at least
181// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000182void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000183 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000184 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000185 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000186 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000187 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000188 // We won't optimize the globals that are referenced by an alias for now
189 // Ideally we should turn the alias into a global and duplicate the definition
190 // when needed.
191 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
192 for (auto &I : Index)
193 for (auto &S : I.second)
194 if (auto AS = dyn_cast<AliasSummary>(S.get()))
195 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
196
197 for (auto &I : Index)
198 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000199 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000200}
201
202static void thinLTOInternalizeAndPromoteGUID(
203 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000204 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000205 for (auto &S : GVSummaryList) {
206 if (isExported(S->modulePath(), GUID)) {
207 if (GlobalValue::isLocalLinkage(S->linkage()))
208 S->setLinkage(GlobalValue::ExternalLinkage);
209 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
210 S->setLinkage(GlobalValue::InternalLinkage);
211 }
212}
213
214// Update the linkages in the given \p Index to mark exported values
215// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000216void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000217 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000218 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000219 for (auto &I : Index)
220 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
221}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000222
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000223struct InputFile::InputModule {
224 BitcodeModule BM;
225 std::unique_ptr<Module> Mod;
226
227 // The range of ModuleSymbolTable entries for this input module.
228 size_t SymBegin, SymEnd;
229};
230
231// Requires a destructor for std::vector<InputModule>.
232InputFile::~InputFile() = default;
233
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
235 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000236
Peter Collingbournead903692016-12-13 19:43:49 +0000237 ErrorOr<MemoryBufferRef> BCOrErr =
238 IRObjectFile::findBitcodeInMemBuffer(Object);
239 if (!BCOrErr)
240 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000241
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000242 Expected<std::vector<BitcodeModule>> BMsOrErr =
243 getBitcodeModuleList(*BCOrErr);
244 if (!BMsOrErr)
245 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000246
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000247 if (BMsOrErr->empty())
248 return make_error<StringError>("Bitcode file does not contain any modules",
249 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000250
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000251 // Create an InputModule for each module in the InputFile, and add it to the
252 // ModuleSymbolTable.
253 for (auto BM : *BMsOrErr) {
254 Expected<std::unique_ptr<Module>> MOrErr =
255 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true);
256 if (!MOrErr)
257 return MOrErr.takeError();
258
259 size_t SymBegin = File->SymTab.symbols().size();
260 File->SymTab.addModule(MOrErr->get());
261 size_t SymEnd = File->SymTab.symbols().size();
262
263 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
264 auto P = File->ComdatMap.insert(
265 std::make_pair(&C.second, File->Comdats.size()));
266 assert(P.second);
267 (void)P;
268 File->Comdats.push_back(C.first());
269 }
270
271 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000272 }
273
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000274 return std::move(File);
275}
276
Rafael Espindola79121102016-10-25 12:02:03 +0000277Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000278 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000279 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000280 const GlobalObject *GO = getGV()->getBaseObject();
281 if (!GO)
282 return make_error<StringError>("Unable to determine comdat of alias!",
283 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000284 if (const Comdat *C = GO->getComdat()) {
285 auto I = File->ComdatMap.find(C);
286 assert(I != File->ComdatMap.end());
287 return I->second;
288 }
289 return -1;
290}
291
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000292StringRef InputFile::getName() const {
293 return Mods[0].BM.getModuleIdentifier();
294}
295
296StringRef InputFile::getSourceFileName() const {
297 return Mods[0].Mod->getSourceFileName();
298}
299
300iterator_range<InputFile::symbol_iterator>
301InputFile::module_symbols(InputModule &IM) {
302 return llvm::make_range(
303 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
304 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
305}
306
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000307LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
308 Config &Conf)
309 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000310 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000311
312LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
313 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000314 this->Backend =
315 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000316}
317
318LTO::LTO(Config Conf, ThinBackend Backend,
319 unsigned ParallelCodeGenParallelismLevel)
320 : Conf(std::move(Conf)),
321 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000322 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000323
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000324// Requires a destructor for MapVector<BitcodeModule>.
325LTO::~LTO() = default;
326
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000327// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000328void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000329 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000330 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000331 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000332
333 auto &GlobalRes = GlobalResolutions[Sym.getName()];
334 if (GV) {
335 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
336 if (Res.Prevailing)
337 GlobalRes.IRName = GV->getName();
338 }
339 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
340 (GlobalRes.Partition != GlobalResolution::Unknown &&
341 GlobalRes.Partition != Partition))
342 GlobalRes.Partition = GlobalResolution::External;
343 else
344 GlobalRes.Partition = Partition;
345}
346
Rafael Espindola7775c332016-08-26 20:19:35 +0000347static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
348 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000349 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000350 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000351 auto ResI = Res.begin();
352 for (const InputFile::Symbol &Sym : Input->symbols()) {
353 assert(ResI != Res.end());
354 SymbolResolution Res = *ResI++;
355
Rafael Espindola7775c332016-08-26 20:19:35 +0000356 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000357 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000358 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000359 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000360 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000362 OS << 'x';
363 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000364 }
365 assert(ResI == Res.end());
366}
367
368Error LTO::add(std::unique_ptr<InputFile> Input,
369 ArrayRef<SymbolResolution> Res) {
370 assert(!CalledGetMaxTasks);
371
372 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000373 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000375 const SymbolResolution *ResI = Res.begin();
376 for (InputFile::InputModule &IM : Input->Mods)
377 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
378 return Err;
379
380 assert(ResI == Res.end());
381 return Error::success();
382}
383
384Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
385 const SymbolResolution *&ResI,
386 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000387 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000388 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000389
390 if (M.getDataLayoutStr().empty())
391 return make_error<StringError>("input module has no datalayout",
392 inconvertibleErrorCode());
393
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000394 if (!Conf.OverrideTriple.empty())
395 M.setTargetTriple(Conf.OverrideTriple);
396 else if (M.getTargetTriple().empty())
397 M.setTargetTriple(Conf.DefaultTriple);
398
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000399 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000400 if (!HasThinLTOSummary)
401 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000402
Peter Collingbournecd513a42016-11-11 19:50:24 +0000403 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000404 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000406 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000407}
408
409// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000410Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
411 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000412 if (!RegularLTO.CombinedModule) {
413 RegularLTO.CombinedModule =
414 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
415 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
416 }
Peter Collingbournead903692016-12-13 19:43:49 +0000417 Expected<std::unique_ptr<Module>> MOrErr =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000418 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true);
Peter Collingbournead903692016-12-13 19:43:49 +0000419 if (!MOrErr)
420 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000421
Peter Collingbournead903692016-12-13 19:43:49 +0000422 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000423 if (Error Err = M.materializeMetadata())
424 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000425 UpgradeDebugInfo(M);
426
Peter Collingbournead903692016-12-13 19:43:49 +0000427 ModuleSymbolTable SymTab;
428 SymTab.addModule(&M);
429
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000430 SmallPtrSet<GlobalValue *, 8> Used;
431 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
432
433 std::vector<GlobalValue *> Keep;
434
435 for (GlobalVariable &GV : M.globals())
436 if (GV.hasAppendingLinkage())
437 Keep.push_back(&GV);
438
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000439 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000440 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
441 nullptr),
442 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
443 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000444 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000445 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000446 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000447
Davide Italiano39ccd242016-09-13 18:45:13 +0000448 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
449 continue;
Peter Collingbournead903692016-12-13 19:43:49 +0000450 if (Res.Prevailing && Sym.isGV()) {
451 GlobalValue *GV = Sym.getGV();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000452 Keep.push_back(GV);
453 switch (GV->getLinkage()) {
454 default:
455 break;
456 case GlobalValue::LinkOnceAnyLinkage:
457 GV->setLinkage(GlobalValue::WeakAnyLinkage);
458 break;
459 case GlobalValue::LinkOnceODRLinkage:
460 GV->setLinkage(GlobalValue::WeakODRLinkage);
461 break;
462 }
463 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000464 // Common resolution: collect the maximum size/alignment over all commons.
465 // We also record if we see an instance of a common as prevailing, so that
466 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000467 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000468 // FIXME: We should figure out what to do about commons defined by asm.
469 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000470 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000471 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
472 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000473 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000474 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000475
476 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
477 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000478
Peter Collingbournead903692016-12-13 19:43:49 +0000479 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000480 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000481 /* LinkModuleInlineAsm */ true,
482 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000483}
484
485// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000486// FIXME: This function should not need to take as many parameters once we have
487// a bitcode symbol table.
488Error LTO::addThinLTO(BitcodeModule BM, Module &M,
489 iterator_range<InputFile::symbol_iterator> Syms,
490 const SymbolResolution *&ResI,
491 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 SmallPtrSet<GlobalValue *, 8> Used;
493 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
494
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000495 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
496 if (!SummaryOrErr)
497 return SummaryOrErr.takeError();
498 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000499 ThinLTO.ModuleMap.size());
500
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000501 for (const InputFile::Symbol &Sym : Syms) {
502 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000503 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000504 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000505
Peter Collingbournead903692016-12-13 19:43:49 +0000506 if (Res.Prevailing && Sym.isGV())
507 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000508 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000509 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000510
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000511 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
512 return make_error<StringError>(
513 "Expected at most one ThinLTO module per bitcode file",
514 inconvertibleErrorCode());
515
Mehdi Amini41af4302016-11-11 04:28:40 +0000516 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000517}
518
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000519unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000520 CalledGetMaxTasks = true;
521 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
522}
523
Peter Collingbourne80186a52016-09-23 21:33:43 +0000524Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000525 // Save the status of having a regularLTO combined module, as
526 // this is needed for generating the ThinLTO Task ID, and
527 // the CombinedModule will be moved at the end of runRegularLTO.
528 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000529 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000530 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000531 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000533 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000534}
535
Peter Collingbourne80186a52016-09-23 21:33:43 +0000536Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000537 // Make sure commons have the right size/alignment: we kept the largest from
538 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000539 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000540 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000541 if (!I.second.Prevailing)
542 // Don't do anything if no instance of this common was prevailing.
543 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000544 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000545 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000546 // Don't create a new global if the type is already correct, just make
547 // sure the alignment is correct.
548 OldGV->setAlignment(I.second.Align);
549 continue;
550 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000551 ArrayType *Ty =
552 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000553 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
554 GlobalValue::CommonLinkage,
555 ConstantAggregateZero::get(Ty), "");
556 GV->setAlignment(I.second.Align);
557 if (OldGV) {
558 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
559 GV->takeName(OldGV);
560 OldGV->eraseFromParent();
561 } else {
562 GV->setName(I.first);
563 }
564 }
565
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000566 if (Conf.PreOptModuleHook &&
567 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000568 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000569
Mehdi Aminid310b472016-08-22 06:25:41 +0000570 if (!Conf.CodeGenOnly) {
571 for (const auto &R : GlobalResolutions) {
572 if (R.second.IRName.empty())
573 continue;
574 if (R.second.Partition != 0 &&
575 R.second.Partition != GlobalResolution::External)
576 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000577
Mehdi Aminid310b472016-08-22 06:25:41 +0000578 GlobalValue *GV =
579 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
580 // Ignore symbols defined in other partitions.
581 if (!GV || GV->hasLocalLinkage())
582 continue;
583 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
584 : GlobalValue::UnnamedAddr::None);
585 if (R.second.Partition == 0)
586 GV->setLinkage(GlobalValue::InternalLinkage);
587 }
588
589 if (Conf.PostInternalizeModuleHook &&
590 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000591 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000592 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000593 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000594 std::move(RegularLTO.CombinedModule));
595}
596
597/// This class defines the interface to the ThinLTO backend.
598class lto::ThinBackendProc {
599protected:
600 Config &Conf;
601 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000602 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000603
604public:
605 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000606 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000607 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000608 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
609
610 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000611 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000612 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000613 const FunctionImporter::ImportMapTy &ImportList,
614 const FunctionImporter::ExportSetTy &ExportList,
615 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000616 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000617 virtual Error wait() = 0;
618};
619
Benjamin Kramerffd37152016-11-19 20:44:26 +0000620namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000621class InProcessThinBackend : public ThinBackendProc {
622 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000623 AddStreamFn AddStream;
624 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000625
626 Optional<Error> Err;
627 std::mutex ErrMu;
628
629public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000630 InProcessThinBackend(
631 Config &Conf, ModuleSummaryIndex &CombinedIndex,
632 unsigned ThinLTOParallelismLevel,
633 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000634 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000635 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
636 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000637 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000638
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000639 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000640 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000641 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000642 const FunctionImporter::ImportMapTy &ImportList,
643 const FunctionImporter::ExportSetTy &ExportList,
644 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
645 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000646 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000647 auto RunThinBackend = [&](AddStreamFn AddStream) {
648 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000649 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000650 if (!MOrErr)
651 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000652
Peter Collingbourne80186a52016-09-23 21:33:43 +0000653 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
654 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000655 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000656
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000657 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000658
659 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
660 all_of(CombinedIndex.getModuleHash(ModuleID),
661 [](uint32_t V) { return V == 0; }))
662 // Cache disabled or no entry for this module in the combined index or
663 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000664 return RunThinBackend(AddStream);
665
666 SmallString<40> Key;
667 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000668 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000669 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000670 if (AddStreamFn CacheAddStream = Cache(Task, Key))
671 return RunThinBackend(CacheAddStream);
672
Mehdi Amini41af4302016-11-11 04:28:40 +0000673 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000674 }
675
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000676 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000677 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000678 const FunctionImporter::ImportMapTy &ImportList,
679 const FunctionImporter::ExportSetTy &ExportList,
680 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000681 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
682 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000683 assert(ModuleToDefinedGVSummaries.count(ModulePath));
684 const GVSummaryMapTy &DefinedGlobals =
685 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000686 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000687 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000688 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000689 const FunctionImporter::ExportSetTy &ExportList,
690 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
691 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000692 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000693 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000694 Error E = runThinLTOBackendThread(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000695 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000696 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000697 if (E) {
698 std::unique_lock<std::mutex> L(ErrMu);
699 if (Err)
700 Err = joinErrors(std::move(*Err), std::move(E));
701 else
702 Err = std::move(E);
703 }
704 },
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000705 BM, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000706 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
707 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000708 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000709 }
710
711 Error wait() override {
712 BackendThreadPool.wait();
713 if (Err)
714 return std::move(*Err);
715 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000716 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000717 }
718};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000719} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000720
721ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
722 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000723 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000724 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000725 return llvm::make_unique<InProcessThinBackend>(
726 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000727 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000728 };
729}
730
Teresa Johnson3f212b82016-09-21 19:12:05 +0000731// Given the original \p Path to an output file, replace any path
732// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
733// resulting directory if it does not yet exist.
734std::string lto::getThinLTOOutputFile(const std::string &Path,
735 const std::string &OldPrefix,
736 const std::string &NewPrefix) {
737 if (OldPrefix.empty() && NewPrefix.empty())
738 return Path;
739 SmallString<128> NewPath(Path);
740 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
741 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
742 if (!ParentPath.empty()) {
743 // Make sure the new directory exists, creating it if necessary.
744 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
745 llvm::errs() << "warning: could not create directory '" << ParentPath
746 << "': " << EC.message() << '\n';
747 }
748 return NewPath.str();
749}
750
Benjamin Kramerffd37152016-11-19 20:44:26 +0000751namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000752class WriteIndexesThinBackend : public ThinBackendProc {
753 std::string OldPrefix, NewPrefix;
754 bool ShouldEmitImportsFiles;
755
756 std::string LinkedObjectsFileName;
757 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
758
759public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000760 WriteIndexesThinBackend(
761 Config &Conf, ModuleSummaryIndex &CombinedIndex,
762 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
763 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
764 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000765 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000766 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
767 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
768 LinkedObjectsFileName(LinkedObjectsFileName) {}
769
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000770 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000771 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000772 const FunctionImporter::ImportMapTy &ImportList,
773 const FunctionImporter::ExportSetTy &ExportList,
774 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000775 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
776 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000777 std::string NewModulePath =
778 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
779
780 std::error_code EC;
781 if (!LinkedObjectsFileName.empty()) {
782 if (!LinkedObjectsFile) {
783 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
784 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
785 if (EC)
786 return errorCodeToError(EC);
787 }
788 *LinkedObjectsFile << NewModulePath << '\n';
789 }
790
791 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
792 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000793 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000794
795 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
796 sys::fs::OpenFlags::F_None);
797 if (EC)
798 return errorCodeToError(EC);
799 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
800
801 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000802 return errorCodeToError(
803 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000804 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000805 }
806
Mehdi Amini41af4302016-11-11 04:28:40 +0000807 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000808};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000809} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000810
811ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
812 std::string NewPrefix,
813 bool ShouldEmitImportsFiles,
814 std::string LinkedObjectsFile) {
815 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000816 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000817 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000818 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000819 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
820 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000821 };
822}
823
Peter Collingbourne80186a52016-09-23 21:33:43 +0000824Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
825 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000826 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000827 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000828
829 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000830 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000831
832 // Collect for each module the list of function it defines (GUID ->
833 // Summary).
834 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
835 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
836 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
837 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000838 // Create entries for any modules that didn't have any GV summaries
839 // (either they didn't have any GVs to start with, or we suppressed
840 // generation of the summaries because they e.g. had inline assembly
841 // uses that couldn't be promoted/renamed on export). This is so
842 // InProcessThinBackend::start can still launch a backend thread, which
843 // is passed the map of summaries for the module, without any special
844 // handling for this case.
845 for (auto &Mod : ThinLTO.ModuleMap)
846 if (!ModuleToDefinedGVSummaries.count(Mod.first))
847 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000848
849 StringMap<FunctionImporter::ImportMapTy> ImportLists(
850 ThinLTO.ModuleMap.size());
851 StringMap<FunctionImporter::ExportSetTy> ExportLists(
852 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000853 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000854
Teresa Johnson002af9b2016-10-31 22:12:21 +0000855 if (Conf.OptLevel > 0) {
856 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
857 ImportLists, ExportLists);
858
859 std::set<GlobalValue::GUID> ExportedGUIDs;
860 for (auto &Res : GlobalResolutions) {
861 if (!Res.second.IRName.empty() &&
862 Res.second.Partition == GlobalResolution::External)
863 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
864 }
865
866 auto isPrevailing = [&](GlobalValue::GUID GUID,
867 const GlobalValueSummary *S) {
868 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
869 };
870 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
871 const auto &ExportList = ExportLists.find(ModuleIdentifier);
872 return (ExportList != ExportLists.end() &&
873 ExportList->second.count(GUID)) ||
874 ExportedGUIDs.count(GUID);
875 };
876 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
877
878 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
879 GlobalValue::GUID GUID,
880 GlobalValue::LinkageTypes NewLinkage) {
881 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
882 };
883
884 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
885 recordNewLinkage);
886 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000887
Peter Collingbourne80186a52016-09-23 21:33:43 +0000888 std::unique_ptr<ThinBackendProc> BackendProc =
889 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
890 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000891
892 // Partition numbers for ThinLTO jobs start at 1 (see comments for
893 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000894 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
895 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
896 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000897 unsigned Task =
898 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000899 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000900
901 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000902 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000903 ExportLists[Mod.first],
904 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000905 return E;
906
907 ++Task;
908 ++Partition;
909 }
910
911 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000912}