blob: 654b86a0dfd57f13352103bfc13e4566963a571a [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 Johnsondf6edc52016-05-23 22:54:06 +000017#include "llvm/Bitcode/ReaderWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000018#include "llvm/CodeGen/Analysis.h"
19#include "llvm/IR/AutoUpgrade.h"
20#include "llvm/IR/DiagnosticPrinter.h"
21#include "llvm/IR/LegacyPassManager.h"
22#include "llvm/LTO/LTOBackend.h"
23#include "llvm/Linker/IRMover.h"
24#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
25#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000026#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000027#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000028#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000029#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000030#include "llvm/Support/TargetRegistry.h"
31#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000032#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000033#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000034#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
36#include "llvm/Transforms/IPO.h"
37#include "llvm/Transforms/IPO/PassManagerBuilder.h"
38#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000039
Teresa Johnson9ba95f92016-08-11 14:58:12 +000040#include <set>
41
42using namespace llvm;
43using namespace lto;
44using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000045
Mehdi Aminiadc0e262016-08-23 21:30:12 +000046#define DEBUG_TYPE "lto"
47
48// Returns a unique hash for the Module considering the current list of
49// export/import and other global analysis results.
50// The hash is produced in \p Key.
51static void computeCacheKey(
52 SmallString<40> &Key, const ModuleSummaryIndex &Index, StringRef ModuleID,
53 const FunctionImporter::ImportMapTy &ImportList,
54 const FunctionImporter::ExportSetTy &ExportList,
55 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
56 const GVSummaryMapTy &DefinedGlobals) {
57 // Compute the unique hash for this entry.
58 // This is based on the current compiler version, the module itself, the
59 // export list, the hash for every single module in the import list, the
60 // list of ResolvedODR for the module, and the list of preserved symbols.
61 SHA1 Hasher;
62
63 // Start with the compiler revision
64 Hasher.update(LLVM_VERSION_STRING);
65#ifdef HAVE_LLVM_REVISION
66 Hasher.update(LLVM_REVISION);
67#endif
68
69 // Include the hash for the current module
70 auto ModHash = Index.getModuleHash(ModuleID);
71 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
72 for (auto F : ExportList)
73 // The export list can impact the internalization, be conservative here
74 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
75
76 // Include the hash for every module we import functions from
77 for (auto &Entry : ImportList) {
78 auto ModHash = Index.getModuleHash(Entry.first());
79 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
80 }
81
82 // Include the hash for the resolved ODR.
83 for (auto &Entry : ResolvedODR) {
84 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
85 sizeof(GlobalValue::GUID)));
86 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
87 sizeof(GlobalValue::LinkageTypes)));
88 }
89
90 // Include the hash for the linkage type to reflect internalization and weak
91 // resolution.
92 for (auto &GS : DefinedGlobals) {
93 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
94 Hasher.update(
95 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
96 }
97
98 Key = toHex(Hasher.result());
99}
100
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000101// Simple helper to load a module from bitcode
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000102std::unique_ptr<Module>
103llvm::loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
104 bool Lazy) {
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000105 SMDiagnostic Err;
106 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
107 if (Lazy) {
108 ModuleOrErr =
109 getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context,
110 /* ShouldLazyLoadMetadata */ Lazy);
111 } 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();
331 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
332
333 if (HasThinLTOSummary)
334 return addThinLTO(std::move(Input), Res);
335 else
336 return addRegularLTO(std::move(Input), Res);
337}
338
339// Add a regular LTO object to the link.
340Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
341 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000342 if (!RegularLTO.CombinedModule) {
343 RegularLTO.CombinedModule =
344 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
345 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
346 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
348 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
349 if (!ObjOrErr)
350 return errorCodeToError(ObjOrErr.getError());
351 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
352
353 Module &M = Obj->getModule();
354 M.materializeMetadata();
355 UpgradeDebugInfo(M);
356
357 SmallPtrSet<GlobalValue *, 8> Used;
358 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
359
360 std::vector<GlobalValue *> Keep;
361
362 for (GlobalVariable &GV : M.globals())
363 if (GV.hasAppendingLinkage())
364 Keep.push_back(&GV);
365
366 auto ResI = Res.begin();
367 for (const InputFile::Symbol &Sym :
Rafael Espindola79121102016-10-25 12:02:03 +0000368 make_range(InputFile::symbol_iterator(Obj->symbol_begin(), nullptr),
369 InputFile::symbol_iterator(Obj->symbol_end(), nullptr))) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000370 assert(ResI != Res.end());
371 SymbolResolution Res = *ResI++;
372 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
373
374 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
Davide Italiano39ccd242016-09-13 18:45:13 +0000375 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
376 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000377 if (Res.Prevailing && GV) {
378 Keep.push_back(GV);
379 switch (GV->getLinkage()) {
380 default:
381 break;
382 case GlobalValue::LinkOnceAnyLinkage:
383 GV->setLinkage(GlobalValue::WeakAnyLinkage);
384 break;
385 case GlobalValue::LinkOnceODRLinkage:
386 GV->setLinkage(GlobalValue::WeakODRLinkage);
387 break;
388 }
389 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000390 // Common resolution: collect the maximum size/alignment over all commons.
391 // We also record if we see an instance of a common as prevailing, so that
392 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000393 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
394 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
395 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
396 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000397 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000398 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000399
400 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
401 }
402 assert(ResI == Res.end());
403
Mehdi Aminie7494532016-08-23 18:39:12 +0000404 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000405 [](GlobalValue &, IRMover::ValueAdder) {},
406 /* LinkModuleInlineAsm */ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000407}
408
409// Add a ThinLTO object to the link.
410Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
411 ArrayRef<SymbolResolution> Res) {
412 Module &M = Input->Obj->getModule();
413 SmallPtrSet<GlobalValue *, 8> Used;
414 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
415
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
417 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
418 SummaryObjOrErr =
419 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
420 if (!SummaryObjOrErr)
421 return errorCodeToError(SummaryObjOrErr.getError());
422 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
423 ThinLTO.ModuleMap.size());
424
425 auto ResI = Res.begin();
426 for (const InputFile::Symbol &Sym : Input->symbols()) {
427 assert(ResI != Res.end());
428 SymbolResolution Res = *ResI++;
429 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
430 ThinLTO.ModuleMap.size() + 1);
431
432 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
433 if (Res.Prevailing && GV)
434 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
435 MBRef.getBufferIdentifier();
436 }
437 assert(ResI == Res.end());
438
439 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
440 return Error();
441}
442
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000443unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444 CalledGetMaxTasks = true;
445 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
446}
447
Peter Collingbourne80186a52016-09-23 21:33:43 +0000448Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000449 // Save the status of having a regularLTO combined module, as
450 // this is needed for generating the ThinLTO Task ID, and
451 // the CombinedModule will be moved at the end of runRegularLTO.
452 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000453 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000454 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000455 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000456 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000457 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000458}
459
Peter Collingbourne80186a52016-09-23 21:33:43 +0000460Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000461 // Make sure commons have the right size/alignment: we kept the largest from
462 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000463 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000464 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000465 if (!I.second.Prevailing)
466 // Don't do anything if no instance of this common was prevailing.
467 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000468 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000469 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000470 // Don't create a new global if the type is already correct, just make
471 // sure the alignment is correct.
472 OldGV->setAlignment(I.second.Align);
473 continue;
474 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000475 ArrayType *Ty =
476 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000477 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
478 GlobalValue::CommonLinkage,
479 ConstantAggregateZero::get(Ty), "");
480 GV->setAlignment(I.second.Align);
481 if (OldGV) {
482 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
483 GV->takeName(OldGV);
484 OldGV->eraseFromParent();
485 } else {
486 GV->setName(I.first);
487 }
488 }
489
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000490 if (Conf.PreOptModuleHook &&
491 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
492 return Error();
493
Mehdi Aminid310b472016-08-22 06:25:41 +0000494 if (!Conf.CodeGenOnly) {
495 for (const auto &R : GlobalResolutions) {
496 if (R.second.IRName.empty())
497 continue;
498 if (R.second.Partition != 0 &&
499 R.second.Partition != GlobalResolution::External)
500 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000501
Mehdi Aminid310b472016-08-22 06:25:41 +0000502 GlobalValue *GV =
503 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
504 // Ignore symbols defined in other partitions.
505 if (!GV || GV->hasLocalLinkage())
506 continue;
507 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
508 : GlobalValue::UnnamedAddr::None);
509 if (R.second.Partition == 0)
510 GV->setLinkage(GlobalValue::InternalLinkage);
511 }
512
513 if (Conf.PostInternalizeModuleHook &&
514 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
515 return Error();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000516 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000517 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000518 std::move(RegularLTO.CombinedModule));
519}
520
521/// This class defines the interface to the ThinLTO backend.
522class lto::ThinBackendProc {
523protected:
524 Config &Conf;
525 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000526 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527
528public:
529 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000530 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000531 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
533
534 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000535 virtual Error start(
536 unsigned Task, MemoryBufferRef MBRef,
537 const FunctionImporter::ImportMapTy &ImportList,
538 const FunctionImporter::ExportSetTy &ExportList,
539 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
540 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000541 virtual Error wait() = 0;
542};
543
544class InProcessThinBackend : public ThinBackendProc {
545 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000546 AddStreamFn AddStream;
547 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000548
549 Optional<Error> Err;
550 std::mutex ErrMu;
551
552public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000553 InProcessThinBackend(
554 Config &Conf, ModuleSummaryIndex &CombinedIndex,
555 unsigned ThinLTOParallelismLevel,
556 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000557 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000558 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
559 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000560 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000561
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000562 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000563 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
564 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000565 const FunctionImporter::ImportMapTy &ImportList,
566 const FunctionImporter::ExportSetTy &ExportList,
567 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
568 const GVSummaryMapTy &DefinedGlobals,
569 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000570 auto RunThinBackend = [&](AddStreamFn AddStream) {
571 LTOLLVMContext BackendContext(Conf);
572 ErrorOr<std::unique_ptr<Module>> MOrErr =
573 parseBitcodeFile(MBRef, BackendContext);
574 assert(MOrErr && "Unable to load module in thread?");
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000575
Peter Collingbourne80186a52016-09-23 21:33:43 +0000576 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
577 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000578 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000579
Mehdi Amini00fa1402016-10-08 04:44:18 +0000580 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000581
582 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
583 all_of(CombinedIndex.getModuleHash(ModuleID),
584 [](uint32_t V) { return V == 0; }))
585 // Cache disabled or no entry for this module in the combined index or
586 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000587 return RunThinBackend(AddStream);
588
589 SmallString<40> Key;
590 // The module may be cached, this helps handling it.
Mehdi Amini00fa1402016-10-08 04:44:18 +0000591 computeCacheKey(Key, CombinedIndex, ModuleID, ImportList, ExportList,
592 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000593 if (AddStreamFn CacheAddStream = Cache(Task, Key))
594 return RunThinBackend(CacheAddStream);
595
596 return Error();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000597 }
598
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000599 Error start(
600 unsigned Task, MemoryBufferRef MBRef,
601 const FunctionImporter::ImportMapTy &ImportList,
602 const FunctionImporter::ExportSetTy &ExportList,
603 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
604 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000605 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000606 assert(ModuleToDefinedGVSummaries.count(ModulePath));
607 const GVSummaryMapTy &DefinedGlobals =
608 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000609 BackendThreadPool.async(
610 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
611 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000612 const FunctionImporter::ExportSetTy &ExportList,
613 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
614 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000615 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000616 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000617 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000618 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
619 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000620 if (E) {
621 std::unique_lock<std::mutex> L(ErrMu);
622 if (Err)
623 Err = joinErrors(std::move(*Err), std::move(E));
624 else
625 Err = std::move(E);
626 }
627 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000628 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000629 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
630 std::ref(ModuleMap));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000631 return Error();
632 }
633
634 Error wait() override {
635 BackendThreadPool.wait();
636 if (Err)
637 return std::move(*Err);
638 else
639 return Error();
640 }
641};
642
643ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
644 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000645 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000646 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000647 return llvm::make_unique<InProcessThinBackend>(
648 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000649 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000650 };
651}
652
Teresa Johnson3f212b82016-09-21 19:12:05 +0000653// Given the original \p Path to an output file, replace any path
654// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
655// resulting directory if it does not yet exist.
656std::string lto::getThinLTOOutputFile(const std::string &Path,
657 const std::string &OldPrefix,
658 const std::string &NewPrefix) {
659 if (OldPrefix.empty() && NewPrefix.empty())
660 return Path;
661 SmallString<128> NewPath(Path);
662 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
663 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
664 if (!ParentPath.empty()) {
665 // Make sure the new directory exists, creating it if necessary.
666 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
667 llvm::errs() << "warning: could not create directory '" << ParentPath
668 << "': " << EC.message() << '\n';
669 }
670 return NewPath.str();
671}
672
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000673class WriteIndexesThinBackend : public ThinBackendProc {
674 std::string OldPrefix, NewPrefix;
675 bool ShouldEmitImportsFiles;
676
677 std::string LinkedObjectsFileName;
678 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
679
680public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000681 WriteIndexesThinBackend(
682 Config &Conf, ModuleSummaryIndex &CombinedIndex,
683 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
684 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
685 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000686 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000687 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
688 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
689 LinkedObjectsFileName(LinkedObjectsFileName) {}
690
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000691 Error start(
692 unsigned Task, MemoryBufferRef MBRef,
693 const FunctionImporter::ImportMapTy &ImportList,
694 const FunctionImporter::ExportSetTy &ExportList,
695 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
696 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000697 StringRef ModulePath = MBRef.getBufferIdentifier();
698 std::string NewModulePath =
699 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
700
701 std::error_code EC;
702 if (!LinkedObjectsFileName.empty()) {
703 if (!LinkedObjectsFile) {
704 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
705 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
706 if (EC)
707 return errorCodeToError(EC);
708 }
709 *LinkedObjectsFile << NewModulePath << '\n';
710 }
711
712 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
713 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000714 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000715
716 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
717 sys::fs::OpenFlags::F_None);
718 if (EC)
719 return errorCodeToError(EC);
720 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
721
722 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000723 return errorCodeToError(
724 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000725 return Error();
726 }
727
728 Error wait() override { return Error(); }
729};
730
731ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
732 std::string NewPrefix,
733 bool ShouldEmitImportsFiles,
734 std::string LinkedObjectsFile) {
735 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000736 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000737 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000738 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000739 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
740 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000741 };
742}
743
Peter Collingbourne80186a52016-09-23 21:33:43 +0000744Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
745 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000746 if (ThinLTO.ModuleMap.empty())
747 return Error();
748
749 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
750 return Error();
751
752 // Collect for each module the list of function it defines (GUID ->
753 // Summary).
754 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
755 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
756 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
757 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000758 // Create entries for any modules that didn't have any GV summaries
759 // (either they didn't have any GVs to start with, or we suppressed
760 // generation of the summaries because they e.g. had inline assembly
761 // uses that couldn't be promoted/renamed on export). This is so
762 // InProcessThinBackend::start can still launch a backend thread, which
763 // is passed the map of summaries for the module, without any special
764 // handling for this case.
765 for (auto &Mod : ThinLTO.ModuleMap)
766 if (!ModuleToDefinedGVSummaries.count(Mod.first))
767 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000768
769 StringMap<FunctionImporter::ImportMapTy> ImportLists(
770 ThinLTO.ModuleMap.size());
771 StringMap<FunctionImporter::ExportSetTy> ExportLists(
772 ThinLTO.ModuleMap.size());
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, const GlobalValueSummary *S) {
784 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
785 };
786 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
787 const auto &ExportList = ExportLists.find(ModuleIdentifier);
788 return (ExportList != ExportLists.end() &&
789 ExportList->second.count(GUID)) ||
790 ExportedGUIDs.count(GUID);
791 };
792 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000793
794 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
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);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000803
Peter Collingbourne80186a52016-09-23 21:33:43 +0000804 std::unique_ptr<ThinBackendProc> BackendProc =
805 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
806 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000807
808 // Partition numbers for ThinLTO jobs start at 1 (see comments for
809 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000810 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
811 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
812 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000813 unsigned Task =
814 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000815 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000816
817 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000818 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000819 ExportLists[Mod.first],
820 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000821 return E;
822
823 ++Task;
824 ++Partition;
825 }
826
827 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000828}