blob: 12de8445568df1e9267636c799d7354ee9877193 [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) {
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000108 ModuleOrErr = getLazyBitcodeModule(Buffer, Context,
109 /* ShouldLazyLoadMetadata */ Lazy);
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000110 } else {
111 ModuleOrErr = parseBitcodeFile(Buffer, Context);
112 }
113 if (std::error_code EC = ModuleOrErr.getError()) {
114 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
115 EC.message());
116 Err.print("ThinLTO", errs());
117 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);
206 std::string Msg;
207 auto DiagHandler = [](const DiagnosticInfo &DI, void *MsgP) {
208 auto *Msg = reinterpret_cast<std::string *>(MsgP);
209 raw_string_ostream OS(*Msg);
210 DiagnosticPrinterRawOStream DP(OS);
211 DI.print(DP);
212 };
213 File->Ctx.setDiagnosticHandler(DiagHandler, static_cast<void *>(&Msg));
214
215 ErrorOr<std::unique_ptr<object::IRObjectFile>> IRObj =
216 IRObjectFile::create(Object, File->Ctx);
217 if (!Msg.empty())
218 return make_error<StringError>(Msg, inconvertibleErrorCode());
219 if (!IRObj)
220 return errorCodeToError(IRObj.getError());
221 File->Obj = std::move(*IRObj);
222
223 File->Ctx.setDiagnosticHandler(nullptr, nullptr);
224
Rafael Espindola79121102016-10-25 12:02:03 +0000225 for (const auto &C : File->Obj->getModule().getComdatSymbolTable()) {
226 auto P =
227 File->ComdatMap.insert(std::make_pair(&C.second, File->Comdats.size()));
228 assert(P.second);
Rafael Espindola20aa1772016-10-25 12:28:26 +0000229 (void)P;
Rafael Espindola79121102016-10-25 12:02:03 +0000230 File->Comdats.push_back(C.first());
231 }
232
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000233 return std::move(File);
234}
235
Rafael Espindola79121102016-10-25 12:02:03 +0000236Expected<int> InputFile::Symbol::getComdatIndex() const {
237 if (!GV)
238 return -1;
239 const GlobalObject *GO;
240 if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
241 GO = GA->getBaseObject();
242 if (!GO)
243 return make_error<StringError>("Unable to determine comdat of alias!",
244 inconvertibleErrorCode());
245 } else {
246 GO = cast<GlobalObject>(GV);
247 }
248 if (const Comdat *C = GO->getComdat()) {
249 auto I = File->ComdatMap.find(C);
250 assert(I != File->ComdatMap.end());
251 return I->second;
252 }
253 return -1;
254}
255
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000256LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
257 Config &Conf)
258 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000259 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000260
261LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
262 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000263 this->Backend =
264 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000265}
266
267LTO::LTO(Config Conf, ThinBackend Backend,
268 unsigned ParallelCodeGenParallelismLevel)
269 : Conf(std::move(Conf)),
270 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000271 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000272
273// Add the given symbol to the GlobalResolutions map, and resolve its partition.
274void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
275 SmallPtrSet<GlobalValue *, 8> &Used,
276 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000277 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000278 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
279
280 auto &GlobalRes = GlobalResolutions[Sym.getName()];
281 if (GV) {
282 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
283 if (Res.Prevailing)
284 GlobalRes.IRName = GV->getName();
285 }
286 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
287 (GlobalRes.Partition != GlobalResolution::Unknown &&
288 GlobalRes.Partition != Partition))
289 GlobalRes.Partition = GlobalResolution::External;
290 else
291 GlobalRes.Partition = Partition;
292}
293
Rafael Espindola7775c332016-08-26 20:19:35 +0000294static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
295 ArrayRef<SymbolResolution> Res) {
296 StringRef Path = Input->getMemoryBufferRef().getBufferIdentifier();
297 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000298 auto ResI = Res.begin();
299 for (const InputFile::Symbol &Sym : Input->symbols()) {
300 assert(ResI != Res.end());
301 SymbolResolution Res = *ResI++;
302
Rafael Espindola7775c332016-08-26 20:19:35 +0000303 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000304 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000305 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000306 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000307 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000308 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000309 OS << 'x';
310 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000311 }
312 assert(ResI == Res.end());
313}
314
315Error LTO::add(std::unique_ptr<InputFile> Input,
316 ArrayRef<SymbolResolution> Res) {
317 assert(!CalledGetMaxTasks);
318
319 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000320 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000321
Mehdi Amini9989f802016-08-19 15:35:44 +0000322 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000323 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000324 if (!Conf.OverrideTriple.empty())
325 M.setTargetTriple(Conf.OverrideTriple);
326 else if (M.getTargetTriple().empty())
327 M.setTargetTriple(Conf.DefaultTriple);
328
329 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
330 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
331
332 if (HasThinLTOSummary)
333 return addThinLTO(std::move(Input), Res);
334 else
335 return addRegularLTO(std::move(Input), Res);
336}
337
338// Add a regular LTO object to the link.
339Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
340 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000341 if (!RegularLTO.CombinedModule) {
342 RegularLTO.CombinedModule =
343 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
344 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
345 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000346 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
347 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
348 if (!ObjOrErr)
349 return errorCodeToError(ObjOrErr.getError());
350 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
351
352 Module &M = Obj->getModule();
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000353 if (Error Err = M.materializeMetadata())
354 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000355 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;
Mehdi Amini41af4302016-11-11 04:28:40 +0000440 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000441}
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))
Mehdi Amini41af4302016-11-11 04:28:40 +0000492 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493
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))
Mehdi Amini41af4302016-11-11 04:28:40 +0000515 return Error::success();
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
Mehdi Amini41af4302016-11-11 04:28:40 +0000596 return Error::success();
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));
Mehdi Amini41af4302016-11-11 04:28:40 +0000631 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000632 }
633
634 Error wait() override {
635 BackendThreadPool.wait();
636 if (Err)
637 return std::move(*Err);
638 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000639 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000640 }
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));
Mehdi Amini41af4302016-11-11 04:28:40 +0000725 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000726 }
727
Mehdi Amini41af4302016-11-11 04:28:40 +0000728 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000729};
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())
Mehdi Amini41af4302016-11-11 04:28:40 +0000747 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000748
749 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000750 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000751
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());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000773 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000774
Teresa Johnson002af9b2016-10-31 22:12:21 +0000775 if (Conf.OptLevel > 0) {
776 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
777 ImportLists, ExportLists);
778
779 std::set<GlobalValue::GUID> ExportedGUIDs;
780 for (auto &Res : GlobalResolutions) {
781 if (!Res.second.IRName.empty() &&
782 Res.second.Partition == GlobalResolution::External)
783 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
784 }
785
786 auto isPrevailing = [&](GlobalValue::GUID GUID,
787 const GlobalValueSummary *S) {
788 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
789 };
790 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
791 const auto &ExportList = ExportLists.find(ModuleIdentifier);
792 return (ExportList != ExportLists.end() &&
793 ExportList->second.count(GUID)) ||
794 ExportedGUIDs.count(GUID);
795 };
796 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
797
798 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
799 GlobalValue::GUID GUID,
800 GlobalValue::LinkageTypes NewLinkage) {
801 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
802 };
803
804 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
805 recordNewLinkage);
806 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000807
Peter Collingbourne80186a52016-09-23 21:33:43 +0000808 std::unique_ptr<ThinBackendProc> BackendProc =
809 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
810 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000811
812 // Partition numbers for ThinLTO jobs start at 1 (see comments for
813 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000814 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
815 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
816 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000817 unsigned Task =
818 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000819 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000820
821 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000822 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000823 ExportLists[Mod.first],
824 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000825 return E;
826
827 ++Task;
828 ++Partition;
829 }
830
831 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000832}