blob: 4256704f906ff541d0b673689ea36a761a5c9fec [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(
53 SmallString<40> &Key, const ModuleSummaryIndex &Index, StringRef ModuleID,
54 const FunctionImporter::ImportMapTy &ImportList,
55 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
70 // Include the hash for the current module
71 auto ModHash = Index.getModuleHash(ModuleID);
72 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
73 for (auto F : ExportList)
74 // The export list can impact the internalization, be conservative here
75 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
76
77 // Include the hash for every module we import functions from
78 for (auto &Entry : ImportList) {
79 auto ModHash = Index.getModuleHash(Entry.first());
80 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
81 }
82
83 // Include the hash for the resolved ODR.
84 for (auto &Entry : ResolvedODR) {
85 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
86 sizeof(GlobalValue::GUID)));
87 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
88 sizeof(GlobalValue::LinkageTypes)));
89 }
90
91 // Include the hash for the linkage type to reflect internalization and weak
92 // resolution.
93 for (auto &GS : DefinedGlobals) {
94 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
95 Hasher.update(
96 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
97 }
98
99 Key = toHex(Hasher.result());
100}
101
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000102// Simple helper to load a module from bitcode
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000103std::unique_ptr<Module>
104llvm::loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
105 bool Lazy) {
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000106 SMDiagnostic Err;
Peter Collingbourned9445c42016-11-13 07:00:17 +0000107 Expected<std::unique_ptr<Module>> ModuleOrErr =
108 Lazy ? getLazyBitcodeModule(Buffer, Context,
109 /* ShouldLazyLoadMetadata */ true)
110 : parseBitcodeFile(Buffer, Context);
111 if (!ModuleOrErr) {
112 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
113 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
114 SourceMgr::DK_Error, EIB.message());
115 Err.print("ThinLTO", errs());
116 });
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000117 report_fatal_error("Can't load module, abort.");
118 }
119 return std::move(ModuleOrErr.get());
120}
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000121
122static void thinLTOResolveWeakForLinkerGUID(
123 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
124 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000125 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000126 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000127 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000128 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000129 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000130 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
131 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
132 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000133 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000134 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000135 // This is both a compile-time optimization and a correctness
136 // transformation. This is necessary for correctness when we have exported
137 // a reference - we need to convert the linkonce to weak to
138 // ensure a copy is kept to satisfy the exported reference.
139 // FIXME: We may want to split the compile time and correctness
140 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000141 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000142 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
143 S->setLinkage(GlobalValue::getWeakLinkage(
144 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000145 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000146 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000147 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000148 !GlobalInvolvedWithAlias.count(S.get()) &&
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000149 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
150 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
151 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
152 if (S->linkage() != OriginalLinkage)
153 recordNewLinkage(S->modulePath(), GUID, S->linkage());
154 }
155}
156
157// Resolve Weak and LinkOnce values in the \p Index.
158//
159// We'd like to drop these functions if they are no longer referenced in the
160// current module. However there is a chance that another module is still
161// referencing them because of the import. We make sure we always emit at least
162// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000163void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000164 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000165 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000166 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000167 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000169 // We won't optimize the globals that are referenced by an alias for now
170 // Ideally we should turn the alias into a global and duplicate the definition
171 // when needed.
172 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
173 for (auto &I : Index)
174 for (auto &S : I.second)
175 if (auto AS = dyn_cast<AliasSummary>(S.get()))
176 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
177
178 for (auto &I : Index)
179 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000180 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000181}
182
183static void thinLTOInternalizeAndPromoteGUID(
184 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000185 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000186 for (auto &S : GVSummaryList) {
187 if (isExported(S->modulePath(), GUID)) {
188 if (GlobalValue::isLocalLinkage(S->linkage()))
189 S->setLinkage(GlobalValue::ExternalLinkage);
190 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
191 S->setLinkage(GlobalValue::InternalLinkage);
192 }
193}
194
195// Update the linkages in the given \p Index to mark exported values
196// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000197void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000198 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000199 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000200 for (auto &I : Index)
201 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
202}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000203
204Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
205 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000206
Peter Collingbourned9445c42016-11-13 07:00:17 +0000207 Expected<std::unique_ptr<object::IRObjectFile>> IRObj =
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000208 IRObjectFile::create(Object, File->Ctx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000209 if (!IRObj)
Peter Collingbourned9445c42016-11-13 07:00:17 +0000210 return IRObj.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000211 File->Obj = std::move(*IRObj);
212
Rafael Espindola79121102016-10-25 12:02:03 +0000213 for (const auto &C : File->Obj->getModule().getComdatSymbolTable()) {
214 auto P =
215 File->ComdatMap.insert(std::make_pair(&C.second, File->Comdats.size()));
216 assert(P.second);
Rafael Espindola20aa1772016-10-25 12:28:26 +0000217 (void)P;
Rafael Espindola79121102016-10-25 12:02:03 +0000218 File->Comdats.push_back(C.first());
219 }
220
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000221 return std::move(File);
222}
223
Rafael Espindola79121102016-10-25 12:02:03 +0000224Expected<int> InputFile::Symbol::getComdatIndex() const {
225 if (!GV)
226 return -1;
227 const GlobalObject *GO;
228 if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
229 GO = GA->getBaseObject();
230 if (!GO)
231 return make_error<StringError>("Unable to determine comdat of alias!",
232 inconvertibleErrorCode());
233 } else {
234 GO = cast<GlobalObject>(GV);
235 }
236 if (const Comdat *C = GO->getComdat()) {
237 auto I = File->ComdatMap.find(C);
238 assert(I != File->ComdatMap.end());
239 return I->second;
240 }
241 return -1;
242}
243
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000244LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
245 Config &Conf)
246 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000247 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000248
249LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
250 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000251 this->Backend =
252 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000253}
254
255LTO::LTO(Config Conf, ThinBackend Backend,
256 unsigned ParallelCodeGenParallelismLevel)
257 : Conf(std::move(Conf)),
258 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000259 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000260
261// Add the given symbol to the GlobalResolutions map, and resolve its partition.
262void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
263 SmallPtrSet<GlobalValue *, 8> &Used,
264 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000265 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
267
268 auto &GlobalRes = GlobalResolutions[Sym.getName()];
269 if (GV) {
270 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
271 if (Res.Prevailing)
272 GlobalRes.IRName = GV->getName();
273 }
274 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
275 (GlobalRes.Partition != GlobalResolution::Unknown &&
276 GlobalRes.Partition != Partition))
277 GlobalRes.Partition = GlobalResolution::External;
278 else
279 GlobalRes.Partition = Partition;
280}
281
Rafael Espindola7775c332016-08-26 20:19:35 +0000282static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
283 ArrayRef<SymbolResolution> Res) {
284 StringRef Path = Input->getMemoryBufferRef().getBufferIdentifier();
285 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000286 auto ResI = Res.begin();
287 for (const InputFile::Symbol &Sym : Input->symbols()) {
288 assert(ResI != Res.end());
289 SymbolResolution Res = *ResI++;
290
Rafael Espindola7775c332016-08-26 20:19:35 +0000291 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000292 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000293 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000294 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000295 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000296 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000297 OS << 'x';
298 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000299 }
300 assert(ResI == Res.end());
301}
302
303Error LTO::add(std::unique_ptr<InputFile> Input,
304 ArrayRef<SymbolResolution> Res) {
305 assert(!CalledGetMaxTasks);
306
307 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000308 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000309
Mehdi Amini9989f802016-08-19 15:35:44 +0000310 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000311 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000312 if (!Conf.OverrideTriple.empty())
313 M.setTargetTriple(Conf.OverrideTriple);
314 else if (M.getTargetTriple().empty())
315 M.setTargetTriple(Conf.DefaultTriple);
316
317 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000318 Expected<bool> HasThinLTOSummary = hasGlobalValueSummary(MBRef);
319 if (!HasThinLTOSummary)
320 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000321
Peter Collingbournecd513a42016-11-11 19:50:24 +0000322 if (*HasThinLTOSummary)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000323 return addThinLTO(std::move(Input), Res);
324 else
325 return addRegularLTO(std::move(Input), Res);
326}
327
328// Add a regular LTO object to the link.
329Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
330 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000331 if (!RegularLTO.CombinedModule) {
332 RegularLTO.CombinedModule =
333 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
334 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
335 }
Peter Collingbourned9445c42016-11-13 07:00:17 +0000336 Expected<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000337 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
338 if (!ObjOrErr)
Peter Collingbourned9445c42016-11-13 07:00:17 +0000339 return ObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000340 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
341
342 Module &M = Obj->getModule();
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000343 if (Error Err = M.materializeMetadata())
344 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000345 UpgradeDebugInfo(M);
346
347 SmallPtrSet<GlobalValue *, 8> Used;
348 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
349
350 std::vector<GlobalValue *> Keep;
351
352 for (GlobalVariable &GV : M.globals())
353 if (GV.hasAppendingLinkage())
354 Keep.push_back(&GV);
355
356 auto ResI = Res.begin();
357 for (const InputFile::Symbol &Sym :
Rafael Espindola79121102016-10-25 12:02:03 +0000358 make_range(InputFile::symbol_iterator(Obj->symbol_begin(), nullptr),
359 InputFile::symbol_iterator(Obj->symbol_end(), nullptr))) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000360 assert(ResI != Res.end());
361 SymbolResolution Res = *ResI++;
362 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
363
364 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
Davide Italiano39ccd242016-09-13 18:45:13 +0000365 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
366 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000367 if (Res.Prevailing && GV) {
368 Keep.push_back(GV);
369 switch (GV->getLinkage()) {
370 default:
371 break;
372 case GlobalValue::LinkOnceAnyLinkage:
373 GV->setLinkage(GlobalValue::WeakAnyLinkage);
374 break;
375 case GlobalValue::LinkOnceODRLinkage:
376 GV->setLinkage(GlobalValue::WeakODRLinkage);
377 break;
378 }
379 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000380 // Common resolution: collect the maximum size/alignment over all commons.
381 // We also record if we see an instance of a common as prevailing, so that
382 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000383 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000384 // FIXME: We should figure out what to do about commons defined by asm.
385 // For now they aren't reported correctly by ModuleSymbolTable.
386 assert(GV);
387 auto &CommonRes = RegularLTO.Commons[GV->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000388 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
389 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000390 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000391 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000392
393 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
394 }
395 assert(ResI == Res.end());
396
Mehdi Aminie7494532016-08-23 18:39:12 +0000397 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000398 [](GlobalValue &, IRMover::ValueAdder) {},
399 /* LinkModuleInlineAsm */ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400}
401
402// Add a ThinLTO object to the link.
403Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
404 ArrayRef<SymbolResolution> Res) {
405 Module &M = Input->Obj->getModule();
406 SmallPtrSet<GlobalValue *, 8> Used;
407 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
408
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000409 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000410 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
411 SummaryObjOrErr = object::ModuleSummaryIndexObjectFile::create(MBRef);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000412 if (!SummaryObjOrErr)
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000413 return SummaryObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000414 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
415 ThinLTO.ModuleMap.size());
416
417 auto ResI = Res.begin();
418 for (const InputFile::Symbol &Sym : Input->symbols()) {
419 assert(ResI != Res.end());
420 SymbolResolution Res = *ResI++;
421 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
422 ThinLTO.ModuleMap.size() + 1);
423
424 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
425 if (Res.Prevailing && GV)
426 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
427 MBRef.getBufferIdentifier();
428 }
429 assert(ResI == Res.end());
430
431 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
Mehdi Amini41af4302016-11-11 04:28:40 +0000432 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000433}
434
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000435unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000436 CalledGetMaxTasks = true;
437 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
438}
439
Peter Collingbourne80186a52016-09-23 21:33:43 +0000440Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000441 // Save the status of having a regularLTO combined module, as
442 // this is needed for generating the ThinLTO Task ID, and
443 // the CombinedModule will be moved at the end of runRegularLTO.
444 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000445 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000446 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000447 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000448 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000449 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000450}
451
Peter Collingbourne80186a52016-09-23 21:33:43 +0000452Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000453 // Make sure commons have the right size/alignment: we kept the largest from
454 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000455 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000456 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000457 if (!I.second.Prevailing)
458 // Don't do anything if no instance of this common was prevailing.
459 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000460 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000461 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000462 // Don't create a new global if the type is already correct, just make
463 // sure the alignment is correct.
464 OldGV->setAlignment(I.second.Align);
465 continue;
466 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000467 ArrayType *Ty =
468 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000469 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
470 GlobalValue::CommonLinkage,
471 ConstantAggregateZero::get(Ty), "");
472 GV->setAlignment(I.second.Align);
473 if (OldGV) {
474 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
475 GV->takeName(OldGV);
476 OldGV->eraseFromParent();
477 } else {
478 GV->setName(I.first);
479 }
480 }
481
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000482 if (Conf.PreOptModuleHook &&
483 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000484 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000485
Mehdi Aminid310b472016-08-22 06:25:41 +0000486 if (!Conf.CodeGenOnly) {
487 for (const auto &R : GlobalResolutions) {
488 if (R.second.IRName.empty())
489 continue;
490 if (R.second.Partition != 0 &&
491 R.second.Partition != GlobalResolution::External)
492 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493
Mehdi Aminid310b472016-08-22 06:25:41 +0000494 GlobalValue *GV =
495 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
496 // Ignore symbols defined in other partitions.
497 if (!GV || GV->hasLocalLinkage())
498 continue;
499 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
500 : GlobalValue::UnnamedAddr::None);
501 if (R.second.Partition == 0)
502 GV->setLinkage(GlobalValue::InternalLinkage);
503 }
504
505 if (Conf.PostInternalizeModuleHook &&
506 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000507 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000508 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000509 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000510 std::move(RegularLTO.CombinedModule));
511}
512
513/// This class defines the interface to the ThinLTO backend.
514class lto::ThinBackendProc {
515protected:
516 Config &Conf;
517 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000518 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000519
520public:
521 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000522 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000523 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000524 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
525
526 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000527 virtual Error start(
528 unsigned Task, MemoryBufferRef MBRef,
529 const FunctionImporter::ImportMapTy &ImportList,
530 const FunctionImporter::ExportSetTy &ExportList,
531 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
532 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000533 virtual Error wait() = 0;
534};
535
Benjamin Kramerffd37152016-11-19 20:44:26 +0000536namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000537class InProcessThinBackend : public ThinBackendProc {
538 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000539 AddStreamFn AddStream;
540 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000541
542 Optional<Error> Err;
543 std::mutex ErrMu;
544
545public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000546 InProcessThinBackend(
547 Config &Conf, ModuleSummaryIndex &CombinedIndex,
548 unsigned ThinLTOParallelismLevel,
549 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000550 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000551 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
552 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000553 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000554
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000555 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000556 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
557 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000558 const FunctionImporter::ImportMapTy &ImportList,
559 const FunctionImporter::ExportSetTy &ExportList,
560 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
561 const GVSummaryMapTy &DefinedGlobals,
562 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000563 auto RunThinBackend = [&](AddStreamFn AddStream) {
564 LTOLLVMContext BackendContext(Conf);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000565 Expected<std::unique_ptr<Module>> MOrErr =
Peter Collingbourne80186a52016-09-23 21:33:43 +0000566 parseBitcodeFile(MBRef, BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000567 if (!MOrErr)
568 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000569
Peter Collingbourne80186a52016-09-23 21:33:43 +0000570 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
571 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000572 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000573
Mehdi Amini00fa1402016-10-08 04:44:18 +0000574 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000575
576 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
577 all_of(CombinedIndex.getModuleHash(ModuleID),
578 [](uint32_t V) { return V == 0; }))
579 // Cache disabled or no entry for this module in the combined index or
580 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000581 return RunThinBackend(AddStream);
582
583 SmallString<40> Key;
584 // The module may be cached, this helps handling it.
Mehdi Amini00fa1402016-10-08 04:44:18 +0000585 computeCacheKey(Key, CombinedIndex, ModuleID, ImportList, ExportList,
586 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000587 if (AddStreamFn CacheAddStream = Cache(Task, Key))
588 return RunThinBackend(CacheAddStream);
589
Mehdi Amini41af4302016-11-11 04:28:40 +0000590 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000591 }
592
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000593 Error start(
594 unsigned Task, MemoryBufferRef MBRef,
595 const FunctionImporter::ImportMapTy &ImportList,
596 const FunctionImporter::ExportSetTy &ExportList,
597 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
598 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000599 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000600 assert(ModuleToDefinedGVSummaries.count(ModulePath));
601 const GVSummaryMapTy &DefinedGlobals =
602 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000603 BackendThreadPool.async(
604 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
605 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000606 const FunctionImporter::ExportSetTy &ExportList,
607 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
608 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000609 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000610 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000611 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000612 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
613 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000614 if (E) {
615 std::unique_lock<std::mutex> L(ErrMu);
616 if (Err)
617 Err = joinErrors(std::move(*Err), std::move(E));
618 else
619 Err = std::move(E);
620 }
621 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000622 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000623 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
624 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000625 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000626 }
627
628 Error wait() override {
629 BackendThreadPool.wait();
630 if (Err)
631 return std::move(*Err);
632 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000633 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000634 }
635};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000636} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000637
638ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
639 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000640 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000641 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000642 return llvm::make_unique<InProcessThinBackend>(
643 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000644 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000645 };
646}
647
Teresa Johnson3f212b82016-09-21 19:12:05 +0000648// Given the original \p Path to an output file, replace any path
649// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
650// resulting directory if it does not yet exist.
651std::string lto::getThinLTOOutputFile(const std::string &Path,
652 const std::string &OldPrefix,
653 const std::string &NewPrefix) {
654 if (OldPrefix.empty() && NewPrefix.empty())
655 return Path;
656 SmallString<128> NewPath(Path);
657 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
658 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
659 if (!ParentPath.empty()) {
660 // Make sure the new directory exists, creating it if necessary.
661 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
662 llvm::errs() << "warning: could not create directory '" << ParentPath
663 << "': " << EC.message() << '\n';
664 }
665 return NewPath.str();
666}
667
Benjamin Kramerffd37152016-11-19 20:44:26 +0000668namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000669class WriteIndexesThinBackend : public ThinBackendProc {
670 std::string OldPrefix, NewPrefix;
671 bool ShouldEmitImportsFiles;
672
673 std::string LinkedObjectsFileName;
674 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
675
676public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000677 WriteIndexesThinBackend(
678 Config &Conf, ModuleSummaryIndex &CombinedIndex,
679 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
680 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
681 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000682 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000683 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
684 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
685 LinkedObjectsFileName(LinkedObjectsFileName) {}
686
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000687 Error start(
688 unsigned Task, MemoryBufferRef MBRef,
689 const FunctionImporter::ImportMapTy &ImportList,
690 const FunctionImporter::ExportSetTy &ExportList,
691 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
692 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000693 StringRef ModulePath = MBRef.getBufferIdentifier();
694 std::string NewModulePath =
695 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
696
697 std::error_code EC;
698 if (!LinkedObjectsFileName.empty()) {
699 if (!LinkedObjectsFile) {
700 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
701 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
702 if (EC)
703 return errorCodeToError(EC);
704 }
705 *LinkedObjectsFile << NewModulePath << '\n';
706 }
707
708 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
709 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000710 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000711
712 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
713 sys::fs::OpenFlags::F_None);
714 if (EC)
715 return errorCodeToError(EC);
716 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
717
718 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000719 return errorCodeToError(
720 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000721 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000722 }
723
Mehdi Amini41af4302016-11-11 04:28:40 +0000724 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000725};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000726} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000727
728ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
729 std::string NewPrefix,
730 bool ShouldEmitImportsFiles,
731 std::string LinkedObjectsFile) {
732 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000733 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000734 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000735 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000736 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
737 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000738 };
739}
740
Peter Collingbourne80186a52016-09-23 21:33:43 +0000741Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
742 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000743 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000744 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000745
746 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000747 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000748
749 // Collect for each module the list of function it defines (GUID ->
750 // Summary).
751 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
752 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
753 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
754 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000755 // Create entries for any modules that didn't have any GV summaries
756 // (either they didn't have any GVs to start with, or we suppressed
757 // generation of the summaries because they e.g. had inline assembly
758 // uses that couldn't be promoted/renamed on export). This is so
759 // InProcessThinBackend::start can still launch a backend thread, which
760 // is passed the map of summaries for the module, without any special
761 // handling for this case.
762 for (auto &Mod : ThinLTO.ModuleMap)
763 if (!ModuleToDefinedGVSummaries.count(Mod.first))
764 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000765
766 StringMap<FunctionImporter::ImportMapTy> ImportLists(
767 ThinLTO.ModuleMap.size());
768 StringMap<FunctionImporter::ExportSetTy> ExportLists(
769 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000770 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000771
Teresa Johnson002af9b2016-10-31 22:12:21 +0000772 if (Conf.OptLevel > 0) {
773 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
774 ImportLists, ExportLists);
775
776 std::set<GlobalValue::GUID> ExportedGUIDs;
777 for (auto &Res : GlobalResolutions) {
778 if (!Res.second.IRName.empty() &&
779 Res.second.Partition == GlobalResolution::External)
780 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
781 }
782
783 auto isPrevailing = [&](GlobalValue::GUID GUID,
784 const GlobalValueSummary *S) {
785 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
786 };
787 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
788 const auto &ExportList = ExportLists.find(ModuleIdentifier);
789 return (ExportList != ExportLists.end() &&
790 ExportList->second.count(GUID)) ||
791 ExportedGUIDs.count(GUID);
792 };
793 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
794
795 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
796 GlobalValue::GUID GUID,
797 GlobalValue::LinkageTypes NewLinkage) {
798 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
799 };
800
801 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
802 recordNewLinkage);
803 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000804
Peter Collingbourne80186a52016-09-23 21:33:43 +0000805 std::unique_ptr<ThinBackendProc> BackendProc =
806 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
807 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000808
809 // Partition numbers for ThinLTO jobs start at 1 (see comments for
810 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000811 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
812 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
813 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000814 unsigned Task =
815 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000816 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000817
818 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000819 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000820 ExportLists[Mod.first],
821 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000822 return E;
823
824 ++Task;
825 ++Partition;
826 }
827
828 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000829}