blob: 108b5a42d75e58126bfa1d65b5b17bfd69571197 [file] [log] [blame]
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements functions and classes used to support LTO.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000015#include "llvm/Analysis/TargetLibraryInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000017#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000019#include "llvm/CodeGen/Analysis.h"
20#include "llvm/IR/AutoUpgrade.h"
21#include "llvm/IR/DiagnosticPrinter.h"
22#include "llvm/IR/LegacyPassManager.h"
23#include "llvm/LTO/LTOBackend.h"
24#include "llvm/Linker/IRMover.h"
25#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
26#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000027#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000028#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000029#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000030#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000031#include "llvm/Support/TargetRegistry.h"
32#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000033#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000035#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
37#include "llvm/Transforms/IPO.h"
38#include "llvm/Transforms/IPO/PassManagerBuilder.h"
39#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000040
Teresa Johnson9ba95f92016-08-11 14:58:12 +000041#include <set>
42
43using namespace llvm;
44using namespace lto;
45using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000046
Mehdi Aminiadc0e262016-08-23 21:30:12 +000047#define DEBUG_TYPE "lto"
48
49// Returns a unique hash for the Module considering the current list of
50// export/import and other global analysis results.
51// The hash is produced in \p Key.
52static void computeCacheKey(
Peter Collingbournef4257522016-12-08 05:28:30 +000053 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
54 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +000055 const FunctionImporter::ExportSetTy &ExportList,
56 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
57 const GVSummaryMapTy &DefinedGlobals) {
58 // Compute the unique hash for this entry.
59 // This is based on the current compiler version, the module itself, the
60 // export list, the hash for every single module in the import list, the
61 // list of ResolvedODR for the module, and the list of preserved symbols.
62 SHA1 Hasher;
63
64 // Start with the compiler revision
65 Hasher.update(LLVM_VERSION_STRING);
66#ifdef HAVE_LLVM_REVISION
67 Hasher.update(LLVM_REVISION);
68#endif
69
Peter Collingbournef4257522016-12-08 05:28:30 +000070 // Include the parts of the LTO configuration that affect code generation.
71 auto AddString = [&](StringRef Str) {
72 Hasher.update(Str);
73 Hasher.update(ArrayRef<uint8_t>{0});
74 };
75 auto AddUnsigned = [&](unsigned I) {
76 uint8_t Data[4];
77 Data[0] = I;
78 Data[1] = I >> 8;
79 Data[2] = I >> 16;
80 Data[3] = I >> 24;
81 Hasher.update(ArrayRef<uint8_t>{Data, 4});
82 };
83 AddString(Conf.CPU);
84 // FIXME: Hash more of Options. For now all clients initialize Options from
85 // command-line flags (which is unsupported in production), but may set
86 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
87 // DataSections and DebuggerTuning via command line flags.
88 AddUnsigned(Conf.Options.RelaxELFRelocations);
89 AddUnsigned(Conf.Options.FunctionSections);
90 AddUnsigned(Conf.Options.DataSections);
91 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
92 for (auto &A : Conf.MAttrs)
93 AddString(A);
94 AddUnsigned(Conf.RelocModel);
95 AddUnsigned(Conf.CodeModel);
96 AddUnsigned(Conf.CGOptLevel);
97 AddUnsigned(Conf.OptLevel);
98 AddString(Conf.OptPipeline);
99 AddString(Conf.AAPipeline);
100 AddString(Conf.OverrideTriple);
101 AddString(Conf.DefaultTriple);
102
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000103 // Include the hash for the current module
104 auto ModHash = Index.getModuleHash(ModuleID);
105 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
106 for (auto F : ExportList)
107 // The export list can impact the internalization, be conservative here
108 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
109
110 // Include the hash for every module we import functions from
111 for (auto &Entry : ImportList) {
112 auto ModHash = Index.getModuleHash(Entry.first());
113 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
114 }
115
116 // Include the hash for the resolved ODR.
117 for (auto &Entry : ResolvedODR) {
118 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
119 sizeof(GlobalValue::GUID)));
120 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
121 sizeof(GlobalValue::LinkageTypes)));
122 }
123
124 // Include the hash for the linkage type to reflect internalization and weak
125 // resolution.
126 for (auto &GS : DefinedGlobals) {
127 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
128 Hasher.update(
129 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
130 }
131
132 Key = toHex(Hasher.result());
133}
134
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000135static void thinLTOResolveWeakForLinkerGUID(
136 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
137 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000138 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000139 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000140 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000141 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000142 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000143 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
144 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
145 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000146 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000147 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000148 // This is both a compile-time optimization and a correctness
149 // transformation. This is necessary for correctness when we have exported
150 // a reference - we need to convert the linkonce to weak to
151 // ensure a copy is kept to satisfy the exported reference.
152 // FIXME: We may want to split the compile time and correctness
153 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000154 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000155 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
156 S->setLinkage(GlobalValue::getWeakLinkage(
157 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000158 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000159 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000160 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000161 !GlobalInvolvedWithAlias.count(S.get()) &&
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000162 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
163 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
164 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
165 if (S->linkage() != OriginalLinkage)
166 recordNewLinkage(S->modulePath(), GUID, S->linkage());
167 }
168}
169
170// Resolve Weak and LinkOnce values in the \p Index.
171//
172// We'd like to drop these functions if they are no longer referenced in the
173// current module. However there is a chance that another module is still
174// referencing them because of the import. We make sure we always emit at least
175// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000176void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000177 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000178 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000179 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000180 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000181 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000182 // We won't optimize the globals that are referenced by an alias for now
183 // Ideally we should turn the alias into a global and duplicate the definition
184 // when needed.
185 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
186 for (auto &I : Index)
187 for (auto &S : I.second)
188 if (auto AS = dyn_cast<AliasSummary>(S.get()))
189 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
190
191 for (auto &I : Index)
192 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000193 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000194}
195
196static void thinLTOInternalizeAndPromoteGUID(
197 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000198 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000199 for (auto &S : GVSummaryList) {
200 if (isExported(S->modulePath(), GUID)) {
201 if (GlobalValue::isLocalLinkage(S->linkage()))
202 S->setLinkage(GlobalValue::ExternalLinkage);
203 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
204 S->setLinkage(GlobalValue::InternalLinkage);
205 }
206}
207
208// Update the linkages in the given \p Index to mark exported values
209// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000210void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000211 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000212 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000213 for (auto &I : Index)
214 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
215}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000216
217Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
218 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000219
Peter Collingbourned9445c42016-11-13 07:00:17 +0000220 Expected<std::unique_ptr<object::IRObjectFile>> IRObj =
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000221 IRObjectFile::create(Object, File->Ctx);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000222 if (!IRObj)
Peter Collingbourned9445c42016-11-13 07:00:17 +0000223 return IRObj.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000224 File->Obj = std::move(*IRObj);
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 }
Peter Collingbourned9445c42016-11-13 07:00:17 +0000349 Expected<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000350 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
351 if (!ObjOrErr)
Peter Collingbourned9445c42016-11-13 07:00:17 +0000352 return ObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000353 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) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000397 // FIXME: We should figure out what to do about commons defined by asm.
398 // For now they aren't reported correctly by ModuleSymbolTable.
399 assert(GV);
400 auto &CommonRes = RegularLTO.Commons[GV->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000401 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
402 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000403 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000404 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405
406 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
407 }
408 assert(ResI == Res.end());
409
Mehdi Aminie7494532016-08-23 18:39:12 +0000410 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000411 [](GlobalValue &, IRMover::ValueAdder) {},
412 /* LinkModuleInlineAsm */ true);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413}
414
415// Add a ThinLTO object to the link.
416Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
417 ArrayRef<SymbolResolution> Res) {
418 Module &M = Input->Obj->getModule();
419 SmallPtrSet<GlobalValue *, 8> Used;
420 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
421
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000422 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000423 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
424 SummaryObjOrErr = object::ModuleSummaryIndexObjectFile::create(MBRef);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000425 if (!SummaryObjOrErr)
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000426 return SummaryObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000427 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
428 ThinLTO.ModuleMap.size());
429
430 auto ResI = Res.begin();
431 for (const InputFile::Symbol &Sym : Input->symbols()) {
432 assert(ResI != Res.end());
433 SymbolResolution Res = *ResI++;
434 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
435 ThinLTO.ModuleMap.size() + 1);
436
437 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
438 if (Res.Prevailing && GV)
439 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
440 MBRef.getBufferIdentifier();
441 }
442 assert(ResI == Res.end());
443
444 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
Mehdi Amini41af4302016-11-11 04:28:40 +0000445 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000446}
447
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000448unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000449 CalledGetMaxTasks = true;
450 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
451}
452
Peter Collingbourne80186a52016-09-23 21:33:43 +0000453Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000454 // Save the status of having a regularLTO combined module, as
455 // this is needed for generating the ThinLTO Task ID, and
456 // the CombinedModule will be moved at the end of runRegularLTO.
457 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000458 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000459 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000460 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000461 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000462 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000463}
464
Peter Collingbourne80186a52016-09-23 21:33:43 +0000465Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000466 // Make sure commons have the right size/alignment: we kept the largest from
467 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000468 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000469 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000470 if (!I.second.Prevailing)
471 // Don't do anything if no instance of this common was prevailing.
472 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000473 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000474 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000475 // Don't create a new global if the type is already correct, just make
476 // sure the alignment is correct.
477 OldGV->setAlignment(I.second.Align);
478 continue;
479 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000480 ArrayType *Ty =
481 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000482 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
483 GlobalValue::CommonLinkage,
484 ConstantAggregateZero::get(Ty), "");
485 GV->setAlignment(I.second.Align);
486 if (OldGV) {
487 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
488 GV->takeName(OldGV);
489 OldGV->eraseFromParent();
490 } else {
491 GV->setName(I.first);
492 }
493 }
494
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000495 if (Conf.PreOptModuleHook &&
496 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000497 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000498
Mehdi Aminid310b472016-08-22 06:25:41 +0000499 if (!Conf.CodeGenOnly) {
500 for (const auto &R : GlobalResolutions) {
501 if (R.second.IRName.empty())
502 continue;
503 if (R.second.Partition != 0 &&
504 R.second.Partition != GlobalResolution::External)
505 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000506
Mehdi Aminid310b472016-08-22 06:25:41 +0000507 GlobalValue *GV =
508 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
509 // Ignore symbols defined in other partitions.
510 if (!GV || GV->hasLocalLinkage())
511 continue;
512 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
513 : GlobalValue::UnnamedAddr::None);
514 if (R.second.Partition == 0)
515 GV->setLinkage(GlobalValue::InternalLinkage);
516 }
517
518 if (Conf.PostInternalizeModuleHook &&
519 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000520 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000521 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000522 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000523 std::move(RegularLTO.CombinedModule));
524}
525
526/// This class defines the interface to the ThinLTO backend.
527class lto::ThinBackendProc {
528protected:
529 Config &Conf;
530 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000531 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000532
533public:
534 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000535 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000536 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000537 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
538
539 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000540 virtual Error start(
541 unsigned Task, MemoryBufferRef MBRef,
542 const FunctionImporter::ImportMapTy &ImportList,
543 const FunctionImporter::ExportSetTy &ExportList,
544 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
545 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000546 virtual Error wait() = 0;
547};
548
Benjamin Kramerffd37152016-11-19 20:44:26 +0000549namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000550class InProcessThinBackend : public ThinBackendProc {
551 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000552 AddStreamFn AddStream;
553 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000554
555 Optional<Error> Err;
556 std::mutex ErrMu;
557
558public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000559 InProcessThinBackend(
560 Config &Conf, ModuleSummaryIndex &CombinedIndex,
561 unsigned ThinLTOParallelismLevel,
562 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000563 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000564 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
565 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000566 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000567
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000568 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000569 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
570 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000571 const FunctionImporter::ImportMapTy &ImportList,
572 const FunctionImporter::ExportSetTy &ExportList,
573 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
574 const GVSummaryMapTy &DefinedGlobals,
575 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000576 auto RunThinBackend = [&](AddStreamFn AddStream) {
577 LTOLLVMContext BackendContext(Conf);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000578 Expected<std::unique_ptr<Module>> MOrErr =
Peter Collingbourne80186a52016-09-23 21:33:43 +0000579 parseBitcodeFile(MBRef, BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000580 if (!MOrErr)
581 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000582
Peter Collingbourne80186a52016-09-23 21:33:43 +0000583 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
584 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000585 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000586
Mehdi Amini00fa1402016-10-08 04:44:18 +0000587 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000588
589 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
590 all_of(CombinedIndex.getModuleHash(ModuleID),
591 [](uint32_t V) { return V == 0; }))
592 // Cache disabled or no entry for this module in the combined index or
593 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000594 return RunThinBackend(AddStream);
595
596 SmallString<40> Key;
597 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000598 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000599 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000600 if (AddStreamFn CacheAddStream = Cache(Task, Key))
601 return RunThinBackend(CacheAddStream);
602
Mehdi Amini41af4302016-11-11 04:28:40 +0000603 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000604 }
605
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000606 Error start(
607 unsigned Task, MemoryBufferRef MBRef,
608 const FunctionImporter::ImportMapTy &ImportList,
609 const FunctionImporter::ExportSetTy &ExportList,
610 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
611 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000612 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000613 assert(ModuleToDefinedGVSummaries.count(ModulePath));
614 const GVSummaryMapTy &DefinedGlobals =
615 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000616 BackendThreadPool.async(
617 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
618 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000619 const FunctionImporter::ExportSetTy &ExportList,
620 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
621 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000622 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000623 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000624 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000625 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
626 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000627 if (E) {
628 std::unique_lock<std::mutex> L(ErrMu);
629 if (Err)
630 Err = joinErrors(std::move(*Err), std::move(E));
631 else
632 Err = std::move(E);
633 }
634 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000635 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000636 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
637 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000638 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000639 }
640
641 Error wait() override {
642 BackendThreadPool.wait();
643 if (Err)
644 return std::move(*Err);
645 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000646 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000647 }
648};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000649} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000650
651ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
652 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000653 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000654 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000655 return llvm::make_unique<InProcessThinBackend>(
656 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000657 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000658 };
659}
660
Teresa Johnson3f212b82016-09-21 19:12:05 +0000661// Given the original \p Path to an output file, replace any path
662// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
663// resulting directory if it does not yet exist.
664std::string lto::getThinLTOOutputFile(const std::string &Path,
665 const std::string &OldPrefix,
666 const std::string &NewPrefix) {
667 if (OldPrefix.empty() && NewPrefix.empty())
668 return Path;
669 SmallString<128> NewPath(Path);
670 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
671 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
672 if (!ParentPath.empty()) {
673 // Make sure the new directory exists, creating it if necessary.
674 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
675 llvm::errs() << "warning: could not create directory '" << ParentPath
676 << "': " << EC.message() << '\n';
677 }
678 return NewPath.str();
679}
680
Benjamin Kramerffd37152016-11-19 20:44:26 +0000681namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000682class WriteIndexesThinBackend : public ThinBackendProc {
683 std::string OldPrefix, NewPrefix;
684 bool ShouldEmitImportsFiles;
685
686 std::string LinkedObjectsFileName;
687 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
688
689public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000690 WriteIndexesThinBackend(
691 Config &Conf, ModuleSummaryIndex &CombinedIndex,
692 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
693 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
694 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000695 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000696 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
697 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
698 LinkedObjectsFileName(LinkedObjectsFileName) {}
699
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000700 Error start(
701 unsigned Task, MemoryBufferRef MBRef,
702 const FunctionImporter::ImportMapTy &ImportList,
703 const FunctionImporter::ExportSetTy &ExportList,
704 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
705 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000706 StringRef ModulePath = MBRef.getBufferIdentifier();
707 std::string NewModulePath =
708 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
709
710 std::error_code EC;
711 if (!LinkedObjectsFileName.empty()) {
712 if (!LinkedObjectsFile) {
713 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
714 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
715 if (EC)
716 return errorCodeToError(EC);
717 }
718 *LinkedObjectsFile << NewModulePath << '\n';
719 }
720
721 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
722 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000723 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000724
725 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
726 sys::fs::OpenFlags::F_None);
727 if (EC)
728 return errorCodeToError(EC);
729 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
730
731 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000732 return errorCodeToError(
733 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000734 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000735 }
736
Mehdi Amini41af4302016-11-11 04:28:40 +0000737 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000738};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000739} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000740
741ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
742 std::string NewPrefix,
743 bool ShouldEmitImportsFiles,
744 std::string LinkedObjectsFile) {
745 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000746 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000747 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000748 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000749 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
750 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000751 };
752}
753
Peter Collingbourne80186a52016-09-23 21:33:43 +0000754Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
755 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000756 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000757 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000758
759 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000760 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000761
762 // Collect for each module the list of function it defines (GUID ->
763 // Summary).
764 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
765 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
766 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
767 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000768 // Create entries for any modules that didn't have any GV summaries
769 // (either they didn't have any GVs to start with, or we suppressed
770 // generation of the summaries because they e.g. had inline assembly
771 // uses that couldn't be promoted/renamed on export). This is so
772 // InProcessThinBackend::start can still launch a backend thread, which
773 // is passed the map of summaries for the module, without any special
774 // handling for this case.
775 for (auto &Mod : ThinLTO.ModuleMap)
776 if (!ModuleToDefinedGVSummaries.count(Mod.first))
777 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000778
779 StringMap<FunctionImporter::ImportMapTy> ImportLists(
780 ThinLTO.ModuleMap.size());
781 StringMap<FunctionImporter::ExportSetTy> ExportLists(
782 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000783 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000784
Teresa Johnson002af9b2016-10-31 22:12:21 +0000785 if (Conf.OptLevel > 0) {
786 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
787 ImportLists, ExportLists);
788
789 std::set<GlobalValue::GUID> ExportedGUIDs;
790 for (auto &Res : GlobalResolutions) {
791 if (!Res.second.IRName.empty() &&
792 Res.second.Partition == GlobalResolution::External)
793 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
794 }
795
796 auto isPrevailing = [&](GlobalValue::GUID GUID,
797 const GlobalValueSummary *S) {
798 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
799 };
800 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
801 const auto &ExportList = ExportLists.find(ModuleIdentifier);
802 return (ExportList != ExportLists.end() &&
803 ExportList->second.count(GUID)) ||
804 ExportedGUIDs.count(GUID);
805 };
806 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
807
808 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
809 GlobalValue::GUID GUID,
810 GlobalValue::LinkageTypes NewLinkage) {
811 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
812 };
813
814 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
815 recordNewLinkage);
816 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000817
Peter Collingbourne80186a52016-09-23 21:33:43 +0000818 std::unique_ptr<ThinBackendProc> BackendProc =
819 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
820 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000821
822 // Partition numbers for ThinLTO jobs start at 1 (see comments for
823 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000824 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
825 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
826 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000827 unsigned Task =
828 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000829 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000830
831 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000832 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000833 ExportLists[Mod.first],
834 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000835 return E;
836
837 ++Task;
838 ++Partition;
839 }
840
841 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000842}