blob: 1fd2ccf7deb0f4237d7e8af7c2ab9ae3bd297a48 [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) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000412 /* LinkModuleInlineAsm */ true,
413 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000414}
415
416// Add a ThinLTO object to the link.
417Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
418 ArrayRef<SymbolResolution> Res) {
419 Module &M = Input->Obj->getModule();
420 SmallPtrSet<GlobalValue *, 8> Used;
421 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
422
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000423 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000424 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
425 SummaryObjOrErr = object::ModuleSummaryIndexObjectFile::create(MBRef);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000426 if (!SummaryObjOrErr)
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000427 return SummaryObjOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000428 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
429 ThinLTO.ModuleMap.size());
430
431 auto ResI = Res.begin();
432 for (const InputFile::Symbol &Sym : Input->symbols()) {
433 assert(ResI != Res.end());
434 SymbolResolution Res = *ResI++;
435 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
436 ThinLTO.ModuleMap.size() + 1);
437
438 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
439 if (Res.Prevailing && GV)
440 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
441 MBRef.getBufferIdentifier();
442 }
443 assert(ResI == Res.end());
444
445 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
Mehdi Amini41af4302016-11-11 04:28:40 +0000446 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000447}
448
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000449unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000450 CalledGetMaxTasks = true;
451 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
452}
453
Peter Collingbourne80186a52016-09-23 21:33:43 +0000454Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000455 // Save the status of having a regularLTO combined module, as
456 // this is needed for generating the ThinLTO Task ID, and
457 // the CombinedModule will be moved at the end of runRegularLTO.
458 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000459 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000460 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000461 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000463 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000464}
465
Peter Collingbourne80186a52016-09-23 21:33:43 +0000466Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000467 // Make sure commons have the right size/alignment: we kept the largest from
468 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000469 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000470 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000471 if (!I.second.Prevailing)
472 // Don't do anything if no instance of this common was prevailing.
473 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000474 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000475 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000476 // Don't create a new global if the type is already correct, just make
477 // sure the alignment is correct.
478 OldGV->setAlignment(I.second.Align);
479 continue;
480 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000481 ArrayType *Ty =
482 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000483 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
484 GlobalValue::CommonLinkage,
485 ConstantAggregateZero::get(Ty), "");
486 GV->setAlignment(I.second.Align);
487 if (OldGV) {
488 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
489 GV->takeName(OldGV);
490 OldGV->eraseFromParent();
491 } else {
492 GV->setName(I.first);
493 }
494 }
495
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000496 if (Conf.PreOptModuleHook &&
497 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000498 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000499
Mehdi Aminid310b472016-08-22 06:25:41 +0000500 if (!Conf.CodeGenOnly) {
501 for (const auto &R : GlobalResolutions) {
502 if (R.second.IRName.empty())
503 continue;
504 if (R.second.Partition != 0 &&
505 R.second.Partition != GlobalResolution::External)
506 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000507
Mehdi Aminid310b472016-08-22 06:25:41 +0000508 GlobalValue *GV =
509 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
510 // Ignore symbols defined in other partitions.
511 if (!GV || GV->hasLocalLinkage())
512 continue;
513 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
514 : GlobalValue::UnnamedAddr::None);
515 if (R.second.Partition == 0)
516 GV->setLinkage(GlobalValue::InternalLinkage);
517 }
518
519 if (Conf.PostInternalizeModuleHook &&
520 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000521 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000522 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000523 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000524 std::move(RegularLTO.CombinedModule));
525}
526
527/// This class defines the interface to the ThinLTO backend.
528class lto::ThinBackendProc {
529protected:
530 Config &Conf;
531 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000532 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000533
534public:
535 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000536 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000537 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000538 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
539
540 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000541 virtual Error start(
542 unsigned Task, MemoryBufferRef MBRef,
543 const FunctionImporter::ImportMapTy &ImportList,
544 const FunctionImporter::ExportSetTy &ExportList,
545 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
546 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000547 virtual Error wait() = 0;
548};
549
Benjamin Kramerffd37152016-11-19 20:44:26 +0000550namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000551class InProcessThinBackend : public ThinBackendProc {
552 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000553 AddStreamFn AddStream;
554 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000555
556 Optional<Error> Err;
557 std::mutex ErrMu;
558
559public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000560 InProcessThinBackend(
561 Config &Conf, ModuleSummaryIndex &CombinedIndex,
562 unsigned ThinLTOParallelismLevel,
563 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000564 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000565 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
566 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000567 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000568
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000569 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000570 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
571 MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000572 const FunctionImporter::ImportMapTy &ImportList,
573 const FunctionImporter::ExportSetTy &ExportList,
574 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
575 const GVSummaryMapTy &DefinedGlobals,
576 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000577 auto RunThinBackend = [&](AddStreamFn AddStream) {
578 LTOLLVMContext BackendContext(Conf);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000579 Expected<std::unique_ptr<Module>> MOrErr =
Peter Collingbourne80186a52016-09-23 21:33:43 +0000580 parseBitcodeFile(MBRef, BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000581 if (!MOrErr)
582 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000583
Peter Collingbourne80186a52016-09-23 21:33:43 +0000584 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
585 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000586 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000587
Mehdi Amini00fa1402016-10-08 04:44:18 +0000588 auto ModuleID = MBRef.getBufferIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000589
590 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
591 all_of(CombinedIndex.getModuleHash(ModuleID),
592 [](uint32_t V) { return V == 0; }))
593 // Cache disabled or no entry for this module in the combined index or
594 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000595 return RunThinBackend(AddStream);
596
597 SmallString<40> Key;
598 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000599 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000600 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000601 if (AddStreamFn CacheAddStream = Cache(Task, Key))
602 return RunThinBackend(CacheAddStream);
603
Mehdi Amini41af4302016-11-11 04:28:40 +0000604 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000605 }
606
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000607 Error start(
608 unsigned Task, MemoryBufferRef MBRef,
609 const FunctionImporter::ImportMapTy &ImportList,
610 const FunctionImporter::ExportSetTy &ExportList,
611 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
612 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000613 StringRef ModulePath = MBRef.getBufferIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000614 assert(ModuleToDefinedGVSummaries.count(ModulePath));
615 const GVSummaryMapTy &DefinedGlobals =
616 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000617 BackendThreadPool.async(
618 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
619 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000620 const FunctionImporter::ExportSetTy &ExportList,
621 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
622 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000623 const GVSummaryMapTy &DefinedGlobals,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000624 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000625 Error E = runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000626 AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
627 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000628 if (E) {
629 std::unique_lock<std::mutex> L(ErrMu);
630 if (Err)
631 Err = joinErrors(std::move(*Err), std::move(E));
632 else
633 Err = std::move(E);
634 }
635 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000636 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000637 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
638 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000639 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000640 }
641
642 Error wait() override {
643 BackendThreadPool.wait();
644 if (Err)
645 return std::move(*Err);
646 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000647 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000648 }
649};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000650} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000651
652ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
653 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000654 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000655 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000656 return llvm::make_unique<InProcessThinBackend>(
657 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000658 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000659 };
660}
661
Teresa Johnson3f212b82016-09-21 19:12:05 +0000662// Given the original \p Path to an output file, replace any path
663// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
664// resulting directory if it does not yet exist.
665std::string lto::getThinLTOOutputFile(const std::string &Path,
666 const std::string &OldPrefix,
667 const std::string &NewPrefix) {
668 if (OldPrefix.empty() && NewPrefix.empty())
669 return Path;
670 SmallString<128> NewPath(Path);
671 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
672 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
673 if (!ParentPath.empty()) {
674 // Make sure the new directory exists, creating it if necessary.
675 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
676 llvm::errs() << "warning: could not create directory '" << ParentPath
677 << "': " << EC.message() << '\n';
678 }
679 return NewPath.str();
680}
681
Benjamin Kramerffd37152016-11-19 20:44:26 +0000682namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000683class WriteIndexesThinBackend : public ThinBackendProc {
684 std::string OldPrefix, NewPrefix;
685 bool ShouldEmitImportsFiles;
686
687 std::string LinkedObjectsFileName;
688 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
689
690public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000691 WriteIndexesThinBackend(
692 Config &Conf, ModuleSummaryIndex &CombinedIndex,
693 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
694 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
695 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000696 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000697 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
698 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
699 LinkedObjectsFileName(LinkedObjectsFileName) {}
700
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000701 Error start(
702 unsigned Task, MemoryBufferRef MBRef,
703 const FunctionImporter::ImportMapTy &ImportList,
704 const FunctionImporter::ExportSetTy &ExportList,
705 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
706 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000707 StringRef ModulePath = MBRef.getBufferIdentifier();
708 std::string NewModulePath =
709 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
710
711 std::error_code EC;
712 if (!LinkedObjectsFileName.empty()) {
713 if (!LinkedObjectsFile) {
714 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
715 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
716 if (EC)
717 return errorCodeToError(EC);
718 }
719 *LinkedObjectsFile << NewModulePath << '\n';
720 }
721
722 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
723 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000724 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000725
726 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
727 sys::fs::OpenFlags::F_None);
728 if (EC)
729 return errorCodeToError(EC);
730 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
731
732 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000733 return errorCodeToError(
734 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000735 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000736 }
737
Mehdi Amini41af4302016-11-11 04:28:40 +0000738 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000739};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000740} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000741
742ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
743 std::string NewPrefix,
744 bool ShouldEmitImportsFiles,
745 std::string LinkedObjectsFile) {
746 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000747 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000748 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000749 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000750 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
751 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000752 };
753}
754
Peter Collingbourne80186a52016-09-23 21:33:43 +0000755Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
756 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000757 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000758 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000759
760 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000761 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000762
763 // Collect for each module the list of function it defines (GUID ->
764 // Summary).
765 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
766 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
767 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
768 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000769 // Create entries for any modules that didn't have any GV summaries
770 // (either they didn't have any GVs to start with, or we suppressed
771 // generation of the summaries because they e.g. had inline assembly
772 // uses that couldn't be promoted/renamed on export). This is so
773 // InProcessThinBackend::start can still launch a backend thread, which
774 // is passed the map of summaries for the module, without any special
775 // handling for this case.
776 for (auto &Mod : ThinLTO.ModuleMap)
777 if (!ModuleToDefinedGVSummaries.count(Mod.first))
778 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000779
780 StringMap<FunctionImporter::ImportMapTy> ImportLists(
781 ThinLTO.ModuleMap.size());
782 StringMap<FunctionImporter::ExportSetTy> ExportLists(
783 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000784 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000785
Teresa Johnson002af9b2016-10-31 22:12:21 +0000786 if (Conf.OptLevel > 0) {
787 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
788 ImportLists, ExportLists);
789
790 std::set<GlobalValue::GUID> ExportedGUIDs;
791 for (auto &Res : GlobalResolutions) {
792 if (!Res.second.IRName.empty() &&
793 Res.second.Partition == GlobalResolution::External)
794 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
795 }
796
797 auto isPrevailing = [&](GlobalValue::GUID GUID,
798 const GlobalValueSummary *S) {
799 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
800 };
801 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
802 const auto &ExportList = ExportLists.find(ModuleIdentifier);
803 return (ExportList != ExportLists.end() &&
804 ExportList->second.count(GUID)) ||
805 ExportedGUIDs.count(GUID);
806 };
807 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
808
809 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
810 GlobalValue::GUID GUID,
811 GlobalValue::LinkageTypes NewLinkage) {
812 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
813 };
814
815 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
816 recordNewLinkage);
817 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000818
Peter Collingbourne80186a52016-09-23 21:33:43 +0000819 std::unique_ptr<ThinBackendProc> BackendProc =
820 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
821 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000822
823 // Partition numbers for ThinLTO jobs start at 1 (see comments for
824 // GlobalResolution in LTO.h). Task numbers, however, start at
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000825 // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
826 // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
827 // generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000828 unsigned Task =
829 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000830 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000831
832 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000833 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000834 ExportLists[Mod.first],
835 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000836 return E;
837
838 ++Task;
839 ++Partition;
840 }
841
842 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000843}