blob: 51b7e7d13c75e7e6afb93fd559a40f161cf6185f [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
Dehao Chen27978002016-12-16 16:48:46 +0000132 if (!Conf.SampleProfile.empty()) {
133 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
134 if (FileOrErr)
135 Hasher.update(FileOrErr.get()->getBuffer());
136 }
137
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000138 Key = toHex(Hasher.result());
139}
140
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000141static void thinLTOResolveWeakForLinkerGUID(
142 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
143 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000144 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000145 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000146 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000147 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000148 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000149 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
150 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
151 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000152 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000153 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000154 // This is both a compile-time optimization and a correctness
155 // transformation. This is necessary for correctness when we have exported
156 // a reference - we need to convert the linkonce to weak to
157 // ensure a copy is kept to satisfy the exported reference.
158 // FIXME: We may want to split the compile time and correctness
159 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000160 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000161 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
162 S->setLinkage(GlobalValue::getWeakLinkage(
163 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000164 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000165 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000166 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000167 !GlobalInvolvedWithAlias.count(S.get()))
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
169 if (S->linkage() != OriginalLinkage)
170 recordNewLinkage(S->modulePath(), GUID, S->linkage());
171 }
172}
173
174// Resolve Weak and LinkOnce values in the \p Index.
175//
176// We'd like to drop these functions if they are no longer referenced in the
177// current module. However there is a chance that another module is still
178// referencing them because of the import. We make sure we always emit at least
179// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000180void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000181 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000182 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000183 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000184 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000185 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000186 // We won't optimize the globals that are referenced by an alias for now
187 // Ideally we should turn the alias into a global and duplicate the definition
188 // when needed.
189 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
190 for (auto &I : Index)
191 for (auto &S : I.second)
192 if (auto AS = dyn_cast<AliasSummary>(S.get()))
193 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
194
195 for (auto &I : Index)
196 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000197 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000198}
199
200static void thinLTOInternalizeAndPromoteGUID(
201 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Mehdi Amini97624fb2017-02-02 18:31:35 +0000202 function_ref<SummaryResolution(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000203 for (auto &S : GVSummaryList) {
Mehdi Amini97624fb2017-02-02 18:31:35 +0000204 auto ExportResolution = isExported(S->modulePath(), GUID);
205 if (ExportResolution != Internal) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000206 if (GlobalValue::isLocalLinkage(S->linkage()))
207 S->setLinkage(GlobalValue::ExternalLinkage);
Mehdi Amini97624fb2017-02-02 18:31:35 +0000208 if (ExportResolution == Hidden)
209 S->setAutoHide();
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000210 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
211 S->setLinkage(GlobalValue::InternalLinkage);
212 }
213}
214
215// Update the linkages in the given \p Index to mark exported values
216// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000217void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000218 ModuleSummaryIndex &Index,
Mehdi Amini97624fb2017-02-02 18:31:35 +0000219 function_ref<SummaryResolution(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000220 for (auto &I : Index)
221 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
222}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000223
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000224struct InputFile::InputModule {
225 BitcodeModule BM;
226 std::unique_ptr<Module> Mod;
227
228 // The range of ModuleSymbolTable entries for this input module.
229 size_t SymBegin, SymEnd;
230};
231
232// Requires a destructor for std::vector<InputModule>.
233InputFile::~InputFile() = default;
234
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000235Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
236 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000237
Peter Collingbournead903692016-12-13 19:43:49 +0000238 ErrorOr<MemoryBufferRef> BCOrErr =
239 IRObjectFile::findBitcodeInMemBuffer(Object);
240 if (!BCOrErr)
241 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000242
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000243 Expected<std::vector<BitcodeModule>> BMsOrErr =
244 getBitcodeModuleList(*BCOrErr);
245 if (!BMsOrErr)
246 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000247
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000248 if (BMsOrErr->empty())
249 return make_error<StringError>("Bitcode file does not contain any modules",
250 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000251
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000252 // Create an InputModule for each module in the InputFile, and add it to the
253 // ModuleSymbolTable.
254 for (auto BM : *BMsOrErr) {
255 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000256 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
257 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000258 if (!MOrErr)
259 return MOrErr.takeError();
260
261 size_t SymBegin = File->SymTab.symbols().size();
262 File->SymTab.addModule(MOrErr->get());
263 size_t SymEnd = File->SymTab.symbols().size();
264
265 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
266 auto P = File->ComdatMap.insert(
267 std::make_pair(&C.second, File->Comdats.size()));
268 assert(P.second);
269 (void)P;
270 File->Comdats.push_back(C.first());
271 }
272
273 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000274 }
275
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000276 return std::move(File);
277}
278
Rafael Espindola79121102016-10-25 12:02:03 +0000279Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000280 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000281 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000282 const GlobalObject *GO = getGV()->getBaseObject();
283 if (!GO)
284 return make_error<StringError>("Unable to determine comdat of alias!",
285 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000286 if (const Comdat *C = GO->getComdat()) {
287 auto I = File->ComdatMap.find(C);
288 assert(I != File->ComdatMap.end());
289 return I->second;
290 }
291 return -1;
292}
293
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000294StringRef InputFile::getName() const {
295 return Mods[0].BM.getModuleIdentifier();
296}
297
298StringRef InputFile::getSourceFileName() const {
299 return Mods[0].Mod->getSourceFileName();
300}
301
302iterator_range<InputFile::symbol_iterator>
303InputFile::module_symbols(InputModule &IM) {
304 return llvm::make_range(
305 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
306 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
307}
308
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000309LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
310 Config &Conf)
311 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000312 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000313
314LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
315 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000316 this->Backend =
317 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000318}
319
320LTO::LTO(Config Conf, ThinBackend Backend,
321 unsigned ParallelCodeGenParallelismLevel)
322 : Conf(std::move(Conf)),
323 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000324 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000325
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000326// Requires a destructor for MapVector<BitcodeModule>.
327LTO::~LTO() = default;
328
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000329// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000330void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000331 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000332 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000333 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000334
335 auto &GlobalRes = GlobalResolutions[Sym.getName()];
336 if (GV) {
337 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
338 if (Res.Prevailing)
339 GlobalRes.IRName = GV->getName();
340 }
Teresa Johnson6c475a72017-01-05 21:34:18 +0000341 // Set the partition to external if we know it is used elsewhere, e.g.
342 // it is visible to a regular object, is referenced from llvm.compiler_used,
343 // or was already recorded as being referenced from a different partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000344 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
345 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000346 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000347 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000348 } else
349 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000350 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000351
352 // Flag as visible outside of ThinLTO if visible from a regular object or
353 // if this is a reference in the regular LTO partition.
354 GlobalRes.VisibleOutsideThinLTO |=
355 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000356}
357
Rafael Espindola7775c332016-08-26 20:19:35 +0000358static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
359 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000360 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000361 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000362 auto ResI = Res.begin();
363 for (const InputFile::Symbol &Sym : Input->symbols()) {
364 assert(ResI != Res.end());
365 SymbolResolution Res = *ResI++;
366
Rafael Espindola7775c332016-08-26 20:19:35 +0000367 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000368 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000369 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000370 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000371 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000372 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000373 OS << 'x';
374 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000375 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000376 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000377 assert(ResI == Res.end());
378}
379
380Error LTO::add(std::unique_ptr<InputFile> Input,
381 ArrayRef<SymbolResolution> Res) {
382 assert(!CalledGetMaxTasks);
383
384 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000385 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000386
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000387 const SymbolResolution *ResI = Res.begin();
388 for (InputFile::InputModule &IM : Input->Mods)
389 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
390 return Err;
391
392 assert(ResI == Res.end());
393 return Error::success();
394}
395
396Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
397 const SymbolResolution *&ResI,
398 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000399 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000400 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000401
402 if (M.getDataLayoutStr().empty())
403 return make_error<StringError>("input module has no datalayout",
404 inconvertibleErrorCode());
405
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000406 if (!Conf.OverrideTriple.empty())
407 M.setTargetTriple(Conf.OverrideTriple);
408 else if (M.getTargetTriple().empty())
409 M.setTargetTriple(Conf.DefaultTriple);
410
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000411 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000412 if (!HasThinLTOSummary)
413 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000414
Peter Collingbournecd513a42016-11-11 19:50:24 +0000415 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000416 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000417 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000418 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000419}
420
421// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000422Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
423 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000424 if (!RegularLTO.CombinedModule) {
425 RegularLTO.CombinedModule =
426 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
427 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
428 }
Peter Collingbournead903692016-12-13 19:43:49 +0000429 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000430 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
431 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000432 if (!MOrErr)
433 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000434
Peter Collingbournead903692016-12-13 19:43:49 +0000435 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000436 if (Error Err = M.materializeMetadata())
437 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000438 UpgradeDebugInfo(M);
439
Peter Collingbournead903692016-12-13 19:43:49 +0000440 ModuleSymbolTable SymTab;
441 SymTab.addModule(&M);
442
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000443 SmallPtrSet<GlobalValue *, 8> Used;
444 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
445
446 std::vector<GlobalValue *> Keep;
447
448 for (GlobalVariable &GV : M.globals())
449 if (GV.hasAppendingLinkage())
450 Keep.push_back(&GV);
451
Peter Collingbourne46136262017-02-02 05:22:42 +0000452 DenseSet<GlobalObject *> AliasedGlobals;
453 for (auto &GA : M.aliases())
454 if (GlobalObject *GO = GA.getBaseObject())
455 AliasedGlobals.insert(GO);
456
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000457 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000458 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
459 nullptr),
460 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
461 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000462 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000463 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000464 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465
Peter Collingbournec387e702017-02-02 05:12:15 +0000466 if (Sym.isGV()) {
Peter Collingbournead903692016-12-13 19:43:49 +0000467 GlobalValue *GV = Sym.getGV();
Peter Collingbournec387e702017-02-02 05:12:15 +0000468 if (Res.Prevailing) {
469 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
470 continue;
471 Keep.push_back(GV);
472 switch (GV->getLinkage()) {
473 default:
474 break;
475 case GlobalValue::LinkOnceAnyLinkage:
476 GV->setLinkage(GlobalValue::WeakAnyLinkage);
477 break;
478 case GlobalValue::LinkOnceODRLinkage:
479 GV->setLinkage(GlobalValue::WeakODRLinkage);
480 break;
481 }
Peter Collingbourne46136262017-02-02 05:22:42 +0000482 } else if (isa<GlobalObject>(GV) &&
483 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
484 GV->hasAvailableExternallyLinkage()) &&
485 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
486 // Either of the above three types of linkage indicates that the
487 // chosen prevailing symbol will have the same semantics as this copy of
488 // the symbol, so we can link it with available_externally linkage. We
489 // only need to do this if the symbol is undefined.
Peter Collingbournec387e702017-02-02 05:12:15 +0000490 GlobalValue *CombinedGV =
491 RegularLTO.CombinedModule->getNamedValue(GV->getName());
Peter Collingbourne46136262017-02-02 05:22:42 +0000492 if (!CombinedGV || CombinedGV->isDeclaration()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000493 Keep.push_back(GV);
Peter Collingbourne46136262017-02-02 05:22:42 +0000494 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
495 cast<GlobalObject>(GV)->setComdat(nullptr);
496 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000497 }
498 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000499 // Common resolution: collect the maximum size/alignment over all commons.
500 // We also record if we see an instance of a common as prevailing, so that
501 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000502 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000503 // FIXME: We should figure out what to do about commons defined by asm.
504 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000505 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000506 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
507 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000508 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000509 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000510
511 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
512 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000513
Peter Collingbournead903692016-12-13 19:43:49 +0000514 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000515 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000516 /* LinkModuleInlineAsm */ true,
517 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000518}
519
520// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000521// FIXME: This function should not need to take as many parameters once we have
522// a bitcode symbol table.
523Error LTO::addThinLTO(BitcodeModule BM, Module &M,
524 iterator_range<InputFile::symbol_iterator> Syms,
525 const SymbolResolution *&ResI,
526 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527 SmallPtrSet<GlobalValue *, 8> Used;
528 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
529
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000530 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
531 if (!SummaryOrErr)
532 return SummaryOrErr.takeError();
533 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000534 ThinLTO.ModuleMap.size());
535
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000536 for (const InputFile::Symbol &Sym : Syms) {
537 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000538 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000539 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000540
Peter Collingbournead903692016-12-13 19:43:49 +0000541 if (Res.Prevailing && Sym.isGV())
542 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000543 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000544 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000545
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000546 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
547 return make_error<StringError>(
548 "Expected at most one ThinLTO module per bitcode file",
549 inconvertibleErrorCode());
550
Mehdi Amini41af4302016-11-11 04:28:40 +0000551 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000552}
553
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000554unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000555 CalledGetMaxTasks = true;
556 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
557}
558
Peter Collingbourne80186a52016-09-23 21:33:43 +0000559Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000560 // Save the status of having a regularLTO combined module, as
561 // this is needed for generating the ThinLTO Task ID, and
562 // the CombinedModule will be moved at the end of runRegularLTO.
563 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000564 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000565 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000566 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000567 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000568 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000569}
570
Peter Collingbourne80186a52016-09-23 21:33:43 +0000571Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000572 // Make sure commons have the right size/alignment: we kept the largest from
573 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000574 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000575 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000576 if (!I.second.Prevailing)
577 // Don't do anything if no instance of this common was prevailing.
578 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000579 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000580 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000581 // Don't create a new global if the type is already correct, just make
582 // sure the alignment is correct.
583 OldGV->setAlignment(I.second.Align);
584 continue;
585 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000586 ArrayType *Ty =
587 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000588 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
589 GlobalValue::CommonLinkage,
590 ConstantAggregateZero::get(Ty), "");
591 GV->setAlignment(I.second.Align);
592 if (OldGV) {
593 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
594 GV->takeName(OldGV);
595 OldGV->eraseFromParent();
596 } else {
597 GV->setName(I.first);
598 }
599 }
600
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000601 if (Conf.PreOptModuleHook &&
602 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000603 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000604
Mehdi Aminid310b472016-08-22 06:25:41 +0000605 if (!Conf.CodeGenOnly) {
606 for (const auto &R : GlobalResolutions) {
607 if (R.second.IRName.empty())
608 continue;
609 if (R.second.Partition != 0 &&
610 R.second.Partition != GlobalResolution::External)
611 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000612
Mehdi Aminid310b472016-08-22 06:25:41 +0000613 GlobalValue *GV =
614 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
615 // Ignore symbols defined in other partitions.
616 if (!GV || GV->hasLocalLinkage())
617 continue;
618 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
619 : GlobalValue::UnnamedAddr::None);
620 if (R.second.Partition == 0)
621 GV->setLinkage(GlobalValue::InternalLinkage);
622 }
623
624 if (Conf.PostInternalizeModuleHook &&
625 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000626 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000627 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000628 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000629 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000630}
631
632/// This class defines the interface to the ThinLTO backend.
633class lto::ThinBackendProc {
634protected:
635 Config &Conf;
636 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000637 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000638
639public:
640 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000641 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000642 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000643 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
644
645 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000646 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000647 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000648 const FunctionImporter::ImportMapTy &ImportList,
649 const FunctionImporter::ExportSetTy &ExportList,
650 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000651 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000652 virtual Error wait() = 0;
653};
654
Benjamin Kramerffd37152016-11-19 20:44:26 +0000655namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000656class InProcessThinBackend : public ThinBackendProc {
657 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000658 AddStreamFn AddStream;
659 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000660
661 Optional<Error> Err;
662 std::mutex ErrMu;
663
664public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000665 InProcessThinBackend(
666 Config &Conf, ModuleSummaryIndex &CombinedIndex,
667 unsigned ThinLTOParallelismLevel,
668 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000669 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000670 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
671 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000672 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000673
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000674 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000675 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000676 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000677 const FunctionImporter::ImportMapTy &ImportList,
678 const FunctionImporter::ExportSetTy &ExportList,
679 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
680 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000681 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000682 auto RunThinBackend = [&](AddStreamFn AddStream) {
683 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000684 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000685 if (!MOrErr)
686 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000687
Peter Collingbourne80186a52016-09-23 21:33:43 +0000688 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
689 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000690 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000691
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000692 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000693
694 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
695 all_of(CombinedIndex.getModuleHash(ModuleID),
696 [](uint32_t V) { return V == 0; }))
697 // Cache disabled or no entry for this module in the combined index or
698 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000699 return RunThinBackend(AddStream);
700
701 SmallString<40> Key;
702 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000703 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000704 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000705 if (AddStreamFn CacheAddStream = Cache(Task, Key))
706 return RunThinBackend(CacheAddStream);
707
Mehdi Amini41af4302016-11-11 04:28:40 +0000708 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000709 }
710
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000711 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000712 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000713 const FunctionImporter::ImportMapTy &ImportList,
714 const FunctionImporter::ExportSetTy &ExportList,
715 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000716 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
717 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000718 assert(ModuleToDefinedGVSummaries.count(ModulePath));
719 const GVSummaryMapTy &DefinedGlobals =
720 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000721 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000722 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000723 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000724 const FunctionImporter::ExportSetTy &ExportList,
725 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
726 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000727 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000728 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000729 Error E = runThinLTOBackendThread(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000730 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000731 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000732 if (E) {
733 std::unique_lock<std::mutex> L(ErrMu);
734 if (Err)
735 Err = joinErrors(std::move(*Err), std::move(E));
736 else
737 Err = std::move(E);
738 }
739 },
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000740 BM, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000741 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
742 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000743 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000744 }
745
746 Error wait() override {
747 BackendThreadPool.wait();
748 if (Err)
749 return std::move(*Err);
750 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000751 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000752 }
753};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000754} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000755
756ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
757 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000758 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000759 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000760 return llvm::make_unique<InProcessThinBackend>(
761 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000762 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000763 };
764}
765
Teresa Johnson3f212b82016-09-21 19:12:05 +0000766// Given the original \p Path to an output file, replace any path
767// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
768// resulting directory if it does not yet exist.
769std::string lto::getThinLTOOutputFile(const std::string &Path,
770 const std::string &OldPrefix,
771 const std::string &NewPrefix) {
772 if (OldPrefix.empty() && NewPrefix.empty())
773 return Path;
774 SmallString<128> NewPath(Path);
775 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
776 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
777 if (!ParentPath.empty()) {
778 // Make sure the new directory exists, creating it if necessary.
779 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
780 llvm::errs() << "warning: could not create directory '" << ParentPath
781 << "': " << EC.message() << '\n';
782 }
783 return NewPath.str();
784}
785
Benjamin Kramerffd37152016-11-19 20:44:26 +0000786namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000787class WriteIndexesThinBackend : public ThinBackendProc {
788 std::string OldPrefix, NewPrefix;
789 bool ShouldEmitImportsFiles;
790
791 std::string LinkedObjectsFileName;
792 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
793
794public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000795 WriteIndexesThinBackend(
796 Config &Conf, ModuleSummaryIndex &CombinedIndex,
797 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
798 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
799 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000800 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000801 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
802 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
803 LinkedObjectsFileName(LinkedObjectsFileName) {}
804
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000805 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000806 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000807 const FunctionImporter::ImportMapTy &ImportList,
808 const FunctionImporter::ExportSetTy &ExportList,
809 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000810 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
811 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000812 std::string NewModulePath =
813 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
814
815 std::error_code EC;
816 if (!LinkedObjectsFileName.empty()) {
817 if (!LinkedObjectsFile) {
818 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
819 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
820 if (EC)
821 return errorCodeToError(EC);
822 }
823 *LinkedObjectsFile << NewModulePath << '\n';
824 }
825
826 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
827 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000828 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000829
830 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
831 sys::fs::OpenFlags::F_None);
832 if (EC)
833 return errorCodeToError(EC);
834 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
835
836 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000837 return errorCodeToError(
838 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000839 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000840 }
841
Mehdi Amini41af4302016-11-11 04:28:40 +0000842 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000843};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000844} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000845
846ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
847 std::string NewPrefix,
848 bool ShouldEmitImportsFiles,
849 std::string LinkedObjectsFile) {
850 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000851 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000852 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000853 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000854 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
855 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000856 };
857}
858
Peter Collingbourne80186a52016-09-23 21:33:43 +0000859Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
860 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000861 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000862 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000863
864 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000865 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000866
867 // Collect for each module the list of function it defines (GUID ->
868 // Summary).
869 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
870 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
871 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
872 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000873 // Create entries for any modules that didn't have any GV summaries
874 // (either they didn't have any GVs to start with, or we suppressed
875 // generation of the summaries because they e.g. had inline assembly
876 // uses that couldn't be promoted/renamed on export). This is so
877 // InProcessThinBackend::start can still launch a backend thread, which
878 // is passed the map of summaries for the module, without any special
879 // handling for this case.
880 for (auto &Mod : ThinLTO.ModuleMap)
881 if (!ModuleToDefinedGVSummaries.count(Mod.first))
882 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000883
884 StringMap<FunctionImporter::ImportMapTy> ImportLists(
885 ThinLTO.ModuleMap.size());
886 StringMap<FunctionImporter::ExportSetTy> ExportLists(
887 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000888 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000889
Teresa Johnson002af9b2016-10-31 22:12:21 +0000890 if (Conf.OptLevel > 0) {
Mehdi Aminif39ce992017-01-20 23:34:12 +0000891 // Compute "dead" symbols, we don't want to import/export these!
892 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
893 for (auto &Res : GlobalResolutions) {
894 if (Res.second.VisibleOutsideThinLTO &&
895 // IRName will be defined if we have seen the prevailing copy of
896 // this value. If not, no need to preserve any ThinLTO copies.
897 !Res.second.IRName.empty())
898 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
899 }
900
901 auto DeadSymbols =
902 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
903
Teresa Johnson002af9b2016-10-31 22:12:21 +0000904 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000905 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000906
907 std::set<GlobalValue::GUID> ExportedGUIDs;
908 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000909 // First check if the symbol was flagged as having external references.
910 if (Res.second.Partition != GlobalResolution::External)
911 continue;
912 // IRName will be defined if we have seen the prevailing copy of
913 // this value. If not, no need to mark as exported from a ThinLTO
914 // partition (and we can't get the GUID).
915 if (Res.second.IRName.empty())
916 continue;
917 auto GUID = GlobalValue::getGUID(Res.second.IRName);
918 // Mark exported unless index-based analysis determined it to be dead.
919 if (!DeadSymbols.count(GUID))
Teresa Johnson002af9b2016-10-31 22:12:21 +0000920 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
921 }
922
923 auto isPrevailing = [&](GlobalValue::GUID GUID,
924 const GlobalValueSummary *S) {
925 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
926 };
Mehdi Amini97624fb2017-02-02 18:31:35 +0000927 auto isExported = [&](StringRef ModuleIdentifier,
928 GlobalValue::GUID GUID) -> SummaryResolution {
Teresa Johnson002af9b2016-10-31 22:12:21 +0000929 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini97624fb2017-02-02 18:31:35 +0000930 if ((ExportList != ExportLists.end() && ExportList->second.count(GUID)) ||
931 ExportedGUIDs.count(GUID)) {
932 // We could do better by hiding when a symbol is in
933 // GUIDPreservedSymbols because it is only referenced from regular LTO
934 // or from native files and not outside the final binary, but that's
935 // something the native linker could do as gwell.
936 if (GUIDPreservedSymbols.count(GUID))
937 return Exported;
938 return Hidden;
939 }
940 return Internal;
Teresa Johnson002af9b2016-10-31 22:12:21 +0000941 };
942 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
943
944 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
945 GlobalValue::GUID GUID,
946 GlobalValue::LinkageTypes NewLinkage) {
947 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
948 };
949
950 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
951 recordNewLinkage);
952 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000953
Peter Collingbourne80186a52016-09-23 21:33:43 +0000954 std::unique_ptr<ThinBackendProc> BackendProc =
955 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
956 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000957
Davide Italiano63098952017-01-04 20:37:57 +0000958 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
959 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
960 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000961 unsigned Task =
962 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000963 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000964 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000965 ExportLists[Mod.first],
966 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000967 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000968 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000969 }
970
971 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000972}