blob: cf40bfd4ebc37d5203ecd01d0aa056483ec56aa4 [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;
107 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
108 if (Lazy) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000109 ModuleOrErr = getLazyBitcodeModule(Buffer, Context,
110 /* ShouldLazyLoadMetadata */ Lazy);
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000111 } else {
112 ModuleOrErr = parseBitcodeFile(Buffer, Context);
113 }
114 if (std::error_code EC = ModuleOrErr.getError()) {
115 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
116 EC.message());
117 Err.print("ThinLTO", errs());
118 report_fatal_error("Can't load module, abort.");
119 }
120 return std::move(ModuleOrErr.get());
121}
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000122
123static void thinLTOResolveWeakForLinkerGUID(
124 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
125 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000126 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000127 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000128 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000129 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000130 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000131 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
132 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
133 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000134 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000135 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000136 // This is both a compile-time optimization and a correctness
137 // transformation. This is necessary for correctness when we have exported
138 // a reference - we need to convert the linkonce to weak to
139 // ensure a copy is kept to satisfy the exported reference.
140 // FIXME: We may want to split the compile time and correctness
141 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000142 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000143 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
144 S->setLinkage(GlobalValue::getWeakLinkage(
145 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000146 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000147 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000148 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000149 !GlobalInvolvedWithAlias.count(S.get()) &&
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000150 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
151 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
152 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
153 if (S->linkage() != OriginalLinkage)
154 recordNewLinkage(S->modulePath(), GUID, S->linkage());
155 }
156}
157
158// Resolve Weak and LinkOnce values in the \p Index.
159//
160// We'd like to drop these functions if they are no longer referenced in the
161// current module. However there is a chance that another module is still
162// referencing them because of the import. We make sure we always emit at least
163// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000164void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000165 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000166 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000167 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000168 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000169 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000170 // We won't optimize the globals that are referenced by an alias for now
171 // Ideally we should turn the alias into a global and duplicate the definition
172 // when needed.
173 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
174 for (auto &I : Index)
175 for (auto &S : I.second)
176 if (auto AS = dyn_cast<AliasSummary>(S.get()))
177 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
178
179 for (auto &I : Index)
180 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000181 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000182}
183
184static void thinLTOInternalizeAndPromoteGUID(
185 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000186 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000187 for (auto &S : GVSummaryList) {
188 if (isExported(S->modulePath(), GUID)) {
189 if (GlobalValue::isLocalLinkage(S->linkage()))
190 S->setLinkage(GlobalValue::ExternalLinkage);
191 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
192 S->setLinkage(GlobalValue::InternalLinkage);
193 }
194}
195
196// Update the linkages in the given \p Index to mark exported values
197// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000198void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000199 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000200 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000201 for (auto &I : Index)
202 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
203}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000204
205Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
206 std::unique_ptr<InputFile> File(new InputFile);
207 std::string Msg;
208 auto DiagHandler = [](const DiagnosticInfo &DI, void *MsgP) {
209 auto *Msg = reinterpret_cast<std::string *>(MsgP);
210 raw_string_ostream OS(*Msg);
211 DiagnosticPrinterRawOStream DP(OS);
212 DI.print(DP);
213 };
214 File->Ctx.setDiagnosticHandler(DiagHandler, static_cast<void *>(&Msg));
215
216 ErrorOr<std::unique_ptr<object::IRObjectFile>> IRObj =
217 IRObjectFile::create(Object, File->Ctx);
218 if (!Msg.empty())
219 return make_error<StringError>(Msg, inconvertibleErrorCode());
220 if (!IRObj)
221 return errorCodeToError(IRObj.getError());
222 File->Obj = std::move(*IRObj);
223
224 File->Ctx.setDiagnosticHandler(nullptr, nullptr);
225
Rafael Espindola79121102016-10-25 12:02:03 +0000226 for (const auto &C : File->Obj->getModule().getComdatSymbolTable()) {
227 auto P =
228 File->ComdatMap.insert(std::make_pair(&C.second, File->Comdats.size()));
229 assert(P.second);
Rafael Espindola20aa1772016-10-25 12:28:26 +0000230 (void)P;
Rafael Espindola79121102016-10-25 12:02:03 +0000231 File->Comdats.push_back(C.first());
232 }
233
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234 return std::move(File);
235}
236
Rafael Espindola79121102016-10-25 12:02:03 +0000237Expected<int> InputFile::Symbol::getComdatIndex() const {
238 if (!GV)
239 return -1;
240 const GlobalObject *GO;
241 if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
242 GO = GA->getBaseObject();
243 if (!GO)
244 return make_error<StringError>("Unable to determine comdat of alias!",
245 inconvertibleErrorCode());
246 } else {
247 GO = cast<GlobalObject>(GV);
248 }
249 if (const Comdat *C = GO->getComdat()) {
250 auto I = File->ComdatMap.find(C);
251 assert(I != File->ComdatMap.end());
252 return I->second;
253 }
254 return -1;
255}
256
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000257LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
258 Config &Conf)
259 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000260 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000261
262LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
263 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000264 this->Backend =
265 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000266}
267
268LTO::LTO(Config Conf, ThinBackend Backend,
269 unsigned ParallelCodeGenParallelismLevel)
270 : Conf(std::move(Conf)),
271 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000272 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000273
274// Add the given symbol to the GlobalResolutions map, and resolve its partition.
275void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
276 SmallPtrSet<GlobalValue *, 8> &Used,
277 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000278 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000279 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
280
281 auto &GlobalRes = GlobalResolutions[Sym.getName()];
282 if (GV) {
283 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
284 if (Res.Prevailing)
285 GlobalRes.IRName = GV->getName();
286 }
287 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
288 (GlobalRes.Partition != GlobalResolution::Unknown &&
289 GlobalRes.Partition != Partition))
290 GlobalRes.Partition = GlobalResolution::External;
291 else
292 GlobalRes.Partition = Partition;
293}
294
Rafael Espindola7775c332016-08-26 20:19:35 +0000295static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
296 ArrayRef<SymbolResolution> Res) {
297 StringRef Path = Input->getMemoryBufferRef().getBufferIdentifier();
298 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000299 auto ResI = Res.begin();
300 for (const InputFile::Symbol &Sym : Input->symbols()) {
301 assert(ResI != Res.end());
302 SymbolResolution Res = *ResI++;
303
Rafael Espindola7775c332016-08-26 20:19:35 +0000304 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000305 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000306 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000307 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000308 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000309 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000310 OS << 'x';
311 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000312 }
313 assert(ResI == Res.end());
314}
315
316Error LTO::add(std::unique_ptr<InputFile> Input,
317 ArrayRef<SymbolResolution> Res) {
318 assert(!CalledGetMaxTasks);
319
320 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000321 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000322
Mehdi Amini9989f802016-08-19 15:35:44 +0000323 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000324 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000325 if (!Conf.OverrideTriple.empty())
326 M.setTargetTriple(Conf.OverrideTriple);
327 else if (M.getTargetTriple().empty())
328 M.setTargetTriple(Conf.DefaultTriple);
329
330 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000331 Expected<bool> HasThinLTOSummary = hasGlobalValueSummary(MBRef);
332 if (!HasThinLTOSummary)
333 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000334
Peter Collingbournecd513a42016-11-11 19:50:24 +0000335 if (*HasThinLTOSummary)
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000336 return addThinLTO(std::move(Input), Res);
337 else
338 return addRegularLTO(std::move(Input), Res);
339}
340
341// Add a regular LTO object to the link.
342Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
343 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000344 if (!RegularLTO.CombinedModule) {
345 RegularLTO.CombinedModule =
346 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
347 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
348 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000349 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
350 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
351 if (!ObjOrErr)
352 return errorCodeToError(ObjOrErr.getError());
353 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
354
355 Module &M = Obj->getModule();
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000356 if (Error Err = M.materializeMetadata())
357 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000358 UpgradeDebugInfo(M);
359
360 SmallPtrSet<GlobalValue *, 8> Used;
361 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
362
363 std::vector<GlobalValue *> Keep;
364
365 for (GlobalVariable &GV : M.globals())
366 if (GV.hasAppendingLinkage())
367 Keep.push_back(&GV);
368
369 auto ResI = Res.begin();
370 for (const InputFile::Symbol &Sym :
Rafael Espindola79121102016-10-25 12:02:03 +0000371 make_range(InputFile::symbol_iterator(Obj->symbol_begin(), nullptr),
372 InputFile::symbol_iterator(Obj->symbol_end(), nullptr))) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000373 assert(ResI != Res.end());
374 SymbolResolution Res = *ResI++;
375 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
376
377 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
Davide Italiano39ccd242016-09-13 18:45:13 +0000378 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
379 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380 if (Res.Prevailing && GV) {
381 Keep.push_back(GV);
382 switch (GV->getLinkage()) {
383 default:
384 break;
385 case GlobalValue::LinkOnceAnyLinkage:
386 GV->setLinkage(GlobalValue::WeakAnyLinkage);
387 break;
388 case GlobalValue::LinkOnceODRLinkage:
389 GV->setLinkage(GlobalValue::WeakODRLinkage);
390 break;
391 }
392 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000393 // Common resolution: collect the maximum size/alignment over all commons.
394 // We also record if we see an instance of a common as prevailing, so that
395 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000396 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
397 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
398 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
399 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000400 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000401 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000402
403 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
404 }
405 assert(ResI == Res.end());
406
Mehdi Aminie7494532016-08-23 18:39:12 +0000407 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000408 [](GlobalValue &, IRMover::ValueAdder) {},
409 /* LinkModuleInlineAsm */ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000410}
411
412// Add a ThinLTO object to the link.
413Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
414 ArrayRef<SymbolResolution> Res) {
415 Module &M = Input->Obj->getModule();
416 SmallPtrSet<GlobalValue *, 8> Used;
417 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
418
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000419 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000420 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
421 SummaryObjOrErr = object::ModuleSummaryIndexObjectFile::create(MBRef);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000422 if (!SummaryObjOrErr)
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000423 return SummaryObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000424 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
425 ThinLTO.ModuleMap.size());
426
427 auto ResI = Res.begin();
428 for (const InputFile::Symbol &Sym : Input->symbols()) {
429 assert(ResI != Res.end());
430 SymbolResolution Res = *ResI++;
431 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
432 ThinLTO.ModuleMap.size() + 1);
433
434 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
435 if (Res.Prevailing && GV)
436 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
437 MBRef.getBufferIdentifier();
438 }
439 assert(ResI == Res.end());
440
441 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
Mehdi Amini41af4302016-11-11 04:28:40 +0000442 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000443}
444
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000445unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000446 CalledGetMaxTasks = true;
447 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
448}
449
Peter Collingbourne80186a52016-09-23 21:33:43 +0000450Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000451 // Save the status of having a regularLTO combined module, as
452 // this is needed for generating the ThinLTO Task ID, and
453 // the CombinedModule will be moved at the end of runRegularLTO.
454 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000455 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000456 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000457 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000458 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000459 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000460}
461
Peter Collingbourne80186a52016-09-23 21:33:43 +0000462Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000463 // Make sure commons have the right size/alignment: we kept the largest from
464 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000465 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000466 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000467 if (!I.second.Prevailing)
468 // Don't do anything if no instance of this common was prevailing.
469 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000470 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000471 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000472 // Don't create a new global if the type is already correct, just make
473 // sure the alignment is correct.
474 OldGV->setAlignment(I.second.Align);
475 continue;
476 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000477 ArrayType *Ty =
478 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000479 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
480 GlobalValue::CommonLinkage,
481 ConstantAggregateZero::get(Ty), "");
482 GV->setAlignment(I.second.Align);
483 if (OldGV) {
484 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
485 GV->takeName(OldGV);
486 OldGV->eraseFromParent();
487 } else {
488 GV->setName(I.first);
489 }
490 }
491
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 if (Conf.PreOptModuleHook &&
493 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000494 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000495
Mehdi Aminid310b472016-08-22 06:25:41 +0000496 if (!Conf.CodeGenOnly) {
497 for (const auto &R : GlobalResolutions) {
498 if (R.second.IRName.empty())
499 continue;
500 if (R.second.Partition != 0 &&
501 R.second.Partition != GlobalResolution::External)
502 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000503
Mehdi Aminid310b472016-08-22 06:25:41 +0000504 GlobalValue *GV =
505 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
506 // Ignore symbols defined in other partitions.
507 if (!GV || GV->hasLocalLinkage())
508 continue;
509 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
510 : GlobalValue::UnnamedAddr::None);
511 if (R.second.Partition == 0)
512 GV->setLinkage(GlobalValue::InternalLinkage);
513 }
514
515 if (Conf.PostInternalizeModuleHook &&
516 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000517 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000518 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000519 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000520 std::move(RegularLTO.CombinedModule));
521}
522
523/// This class defines the interface to the ThinLTO backend.
524class lto::ThinBackendProc {
525protected:
526 Config &Conf;
527 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000528 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000529
530public:
531 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000532 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000533 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000534 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
535
536 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000537 virtual Error start(
538 unsigned Task, MemoryBufferRef MBRef,
539 const FunctionImporter::ImportMapTy &ImportList,
540 const FunctionImporter::ExportSetTy &ExportList,
541 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
542 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000543 virtual Error wait() = 0;
544};
545
546class InProcessThinBackend : public ThinBackendProc {
547 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000548 AddStreamFn AddStream;
549 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000550
551 Optional<Error> Err;
552 std::mutex ErrMu;
553
554public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000555 InProcessThinBackend(
556 Config &Conf, ModuleSummaryIndex &CombinedIndex,
557 unsigned ThinLTOParallelismLevel,
558 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000559 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000560 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
561 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000562 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000563
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000564 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000565 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
566 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000567 const FunctionImporter::ImportMapTy &ImportList,
568 const FunctionImporter::ExportSetTy &ExportList,
569 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
570 const GVSummaryMapTy &DefinedGlobals,
571 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000572 auto RunThinBackend = [&](AddStreamFn AddStream) {
573 LTOLLVMContext BackendContext(Conf);
574 ErrorOr<std::unique_ptr<Module>> MOrErr =
575 parseBitcodeFile(MBRef, BackendContext);
576 assert(MOrErr && "Unable to load module in thread?");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000577
Peter Collingbourne80186a52016-09-23 21:33:43 +0000578 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
579 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000580 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000581
Mehdi Amini00fa1402016-10-08 04:44:18 +0000582 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000583
584 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
585 all_of(CombinedIndex.getModuleHash(ModuleID),
586 [](uint32_t V) { return V == 0; }))
587 // Cache disabled or no entry for this module in the combined index or
588 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000589 return RunThinBackend(AddStream);
590
591 SmallString<40> Key;
592 // The module may be cached, this helps handling it.
Mehdi Amini00fa1402016-10-08 04:44:18 +0000593 computeCacheKey(Key, CombinedIndex, ModuleID, ImportList, ExportList,
594 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000595 if (AddStreamFn CacheAddStream = Cache(Task, Key))
596 return RunThinBackend(CacheAddStream);
597
Mehdi Amini41af4302016-11-11 04:28:40 +0000598 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000599 }
600
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000601 Error start(
602 unsigned Task, MemoryBufferRef MBRef,
603 const FunctionImporter::ImportMapTy &ImportList,
604 const FunctionImporter::ExportSetTy &ExportList,
605 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
606 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000607 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000608 assert(ModuleToDefinedGVSummaries.count(ModulePath));
609 const GVSummaryMapTy &DefinedGlobals =
610 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000611 BackendThreadPool.async(
612 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
613 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000614 const FunctionImporter::ExportSetTy &ExportList,
615 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
616 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000617 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000618 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000619 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000620 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
621 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000622 if (E) {
623 std::unique_lock<std::mutex> L(ErrMu);
624 if (Err)
625 Err = joinErrors(std::move(*Err), std::move(E));
626 else
627 Err = std::move(E);
628 }
629 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000630 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000631 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
632 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000633 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000634 }
635
636 Error wait() override {
637 BackendThreadPool.wait();
638 if (Err)
639 return std::move(*Err);
640 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000641 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000642 }
643};
644
645ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
646 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000647 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000648 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000649 return llvm::make_unique<InProcessThinBackend>(
650 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000651 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000652 };
653}
654
Teresa Johnson3f212b82016-09-21 19:12:05 +0000655// Given the original \p Path to an output file, replace any path
656// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
657// resulting directory if it does not yet exist.
658std::string lto::getThinLTOOutputFile(const std::string &Path,
659 const std::string &OldPrefix,
660 const std::string &NewPrefix) {
661 if (OldPrefix.empty() && NewPrefix.empty())
662 return Path;
663 SmallString<128> NewPath(Path);
664 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
665 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
666 if (!ParentPath.empty()) {
667 // Make sure the new directory exists, creating it if necessary.
668 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
669 llvm::errs() << "warning: could not create directory '" << ParentPath
670 << "': " << EC.message() << '\n';
671 }
672 return NewPath.str();
673}
674
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000675class WriteIndexesThinBackend : public ThinBackendProc {
676 std::string OldPrefix, NewPrefix;
677 bool ShouldEmitImportsFiles;
678
679 std::string LinkedObjectsFileName;
680 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
681
682public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000683 WriteIndexesThinBackend(
684 Config &Conf, ModuleSummaryIndex &CombinedIndex,
685 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
686 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
687 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000688 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000689 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
690 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
691 LinkedObjectsFileName(LinkedObjectsFileName) {}
692
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000693 Error start(
694 unsigned Task, MemoryBufferRef MBRef,
695 const FunctionImporter::ImportMapTy &ImportList,
696 const FunctionImporter::ExportSetTy &ExportList,
697 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
698 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000699 StringRef ModulePath = MBRef.getBufferIdentifier();
700 std::string NewModulePath =
701 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
702
703 std::error_code EC;
704 if (!LinkedObjectsFileName.empty()) {
705 if (!LinkedObjectsFile) {
706 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
707 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
708 if (EC)
709 return errorCodeToError(EC);
710 }
711 *LinkedObjectsFile << NewModulePath << '\n';
712 }
713
714 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
715 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000716 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000717
718 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
719 sys::fs::OpenFlags::F_None);
720 if (EC)
721 return errorCodeToError(EC);
722 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
723
724 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000725 return errorCodeToError(
726 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000727 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000728 }
729
Mehdi Amini41af4302016-11-11 04:28:40 +0000730 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000731};
732
733ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
734 std::string NewPrefix,
735 bool ShouldEmitImportsFiles,
736 std::string LinkedObjectsFile) {
737 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000738 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000739 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000740 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000741 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
742 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000743 };
744}
745
Peter Collingbourne80186a52016-09-23 21:33:43 +0000746Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
747 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000748 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000749 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000750
751 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000752 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000753
754 // Collect for each module the list of function it defines (GUID ->
755 // Summary).
756 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
757 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
758 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
759 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000760 // Create entries for any modules that didn't have any GV summaries
761 // (either they didn't have any GVs to start with, or we suppressed
762 // generation of the summaries because they e.g. had inline assembly
763 // uses that couldn't be promoted/renamed on export). This is so
764 // InProcessThinBackend::start can still launch a backend thread, which
765 // is passed the map of summaries for the module, without any special
766 // handling for this case.
767 for (auto &Mod : ThinLTO.ModuleMap)
768 if (!ModuleToDefinedGVSummaries.count(Mod.first))
769 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000770
771 StringMap<FunctionImporter::ImportMapTy> ImportLists(
772 ThinLTO.ModuleMap.size());
773 StringMap<FunctionImporter::ExportSetTy> ExportLists(
774 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000775 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000776
Teresa Johnson002af9b2016-10-31 22:12:21 +0000777 if (Conf.OptLevel > 0) {
778 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
779 ImportLists, ExportLists);
780
781 std::set<GlobalValue::GUID> ExportedGUIDs;
782 for (auto &Res : GlobalResolutions) {
783 if (!Res.second.IRName.empty() &&
784 Res.second.Partition == GlobalResolution::External)
785 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
786 }
787
788 auto isPrevailing = [&](GlobalValue::GUID GUID,
789 const GlobalValueSummary *S) {
790 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
791 };
792 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
793 const auto &ExportList = ExportLists.find(ModuleIdentifier);
794 return (ExportList != ExportLists.end() &&
795 ExportList->second.count(GUID)) ||
796 ExportedGUIDs.count(GUID);
797 };
798 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
799
800 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
801 GlobalValue::GUID GUID,
802 GlobalValue::LinkageTypes NewLinkage) {
803 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
804 };
805
806 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
807 recordNewLinkage);
808 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000809
Peter Collingbourne80186a52016-09-23 21:33:43 +0000810 std::unique_ptr<ThinBackendProc> BackendProc =
811 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
812 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000813
814 // Partition numbers for ThinLTO jobs start at 1 (see comments for
815 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000816 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
817 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
818 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000819 unsigned Task =
820 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000821 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000822
823 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000824 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000825 ExportLists[Mod.first],
826 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000827 return E;
828
829 ++Task;
830 ++Partition;
831 }
832
833 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000834}