1 //===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements functions and classes used to support LTO.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/LTO/LTO.h"
15 #include "llvm/Analysis/TargetLibraryInfo.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/Bitcode/BitcodeReader.h"
18 #include "llvm/Bitcode/BitcodeWriter.h"
19 #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/IR/Mangler.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/LTO/LTOBackend.h"
26 #include "llvm/Linker/IRMover.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/SHA1.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/ThreadPool.h"
37 #include "llvm/Support/Threading.h"
38 #include "llvm/Support/VCSRevision.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Utils/SplitModule.h"
50 using namespace object;
52 #define DEBUG_TYPE "lto"
54 // The values are (type identifier, summary) pairs.
57 TinyPtrVector<const std::pair<const std::string, TypeIdSummary> *>>
58 TypeIdSummariesByGuidTy;
60 // Returns a unique hash for the Module considering the current list of
61 // export/import and other global analysis results.
62 // The hash is produced in \p Key.
63 static void computeCacheKey(
64 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
65 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
66 const FunctionImporter::ExportSetTy &ExportList,
67 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
68 const GVSummaryMapTy &DefinedGlobals,
69 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
70 // Compute the unique hash for this entry.
71 // This is based on the current compiler version, the module itself, the
72 // export list, the hash for every single module in the import list, the
73 // list of ResolvedODR for the module, and the list of preserved symbols.
76 // Start with the compiler revision
77 Hasher.update(LLVM_VERSION_STRING);
79 Hasher.update(LLVM_REVISION);
82 // Include the parts of the LTO configuration that affect code generation.
83 auto AddString = [&](StringRef Str) {
85 Hasher.update(ArrayRef<uint8_t>{0});
87 auto AddUnsigned = [&](unsigned I) {
93 Hasher.update(ArrayRef<uint8_t>{Data, 4});
95 auto AddUint64 = [&](uint64_t I) {
105 Hasher.update(ArrayRef<uint8_t>{Data, 8});
108 // FIXME: Hash more of Options. For now all clients initialize Options from
109 // command-line flags (which is unsupported in production), but may set
110 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
111 // DataSections and DebuggerTuning via command line flags.
112 AddUnsigned(Conf.Options.RelaxELFRelocations);
113 AddUnsigned(Conf.Options.FunctionSections);
114 AddUnsigned(Conf.Options.DataSections);
115 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
116 for (auto &A : Conf.MAttrs)
118 AddUnsigned(Conf.RelocModel);
119 AddUnsigned(Conf.CodeModel);
120 AddUnsigned(Conf.CGOptLevel);
121 AddUnsigned(Conf.CGFileType);
122 AddUnsigned(Conf.OptLevel);
123 AddString(Conf.OptPipeline);
124 AddString(Conf.AAPipeline);
125 AddString(Conf.OverrideTriple);
126 AddString(Conf.DefaultTriple);
128 // Include the hash for the current module
129 auto ModHash = Index.getModuleHash(ModuleID);
130 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
131 for (auto F : ExportList)
132 // The export list can impact the internalization, be conservative here
133 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
135 // Include the hash for every module we import functions from. The set of
136 // imported symbols for each module may affect code generation and is
137 // sensitive to link order, so include that as well.
138 for (auto &Entry : ImportList) {
139 auto ModHash = Index.getModuleHash(Entry.first());
140 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
142 AddUint64(Entry.second.size());
143 for (auto &Fn : Entry.second)
147 // Include the hash for the resolved ODR.
148 for (auto &Entry : ResolvedODR) {
149 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
150 sizeof(GlobalValue::GUID)));
151 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
152 sizeof(GlobalValue::LinkageTypes)));
155 std::set<GlobalValue::GUID> UsedTypeIds;
157 auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
158 auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
161 for (auto &TT : FS->type_tests())
162 UsedTypeIds.insert(TT);
163 for (auto &TT : FS->type_test_assume_vcalls())
164 UsedTypeIds.insert(TT.GUID);
165 for (auto &TT : FS->type_checked_load_vcalls())
166 UsedTypeIds.insert(TT.GUID);
167 for (auto &TT : FS->type_test_assume_const_vcalls())
168 UsedTypeIds.insert(TT.VFunc.GUID);
169 for (auto &TT : FS->type_checked_load_const_vcalls())
170 UsedTypeIds.insert(TT.VFunc.GUID);
173 // Include the hash for the linkage type to reflect internalization and weak
174 // resolution, and collect any used type identifier resolutions.
175 for (auto &GS : DefinedGlobals) {
176 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
178 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
179 AddUsedTypeIds(GS.second);
182 // Imported functions may introduce new uses of type identifier resolutions,
183 // so we need to collect their used resolutions as well.
184 for (auto &ImpM : ImportList)
185 for (auto &ImpF : ImpM.second)
186 AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
188 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
191 AddUnsigned(S.TTRes.TheKind);
192 AddUnsigned(S.TTRes.SizeM1BitWidth);
194 AddUint64(S.WPDRes.size());
195 for (auto &WPD : S.WPDRes) {
196 AddUnsigned(WPD.first);
197 AddUnsigned(WPD.second.TheKind);
198 AddString(WPD.second.SingleImplName);
200 AddUint64(WPD.second.ResByArg.size());
201 for (auto &ByArg : WPD.second.ResByArg) {
202 AddUint64(ByArg.first.size());
203 for (uint64_t Arg : ByArg.first)
205 AddUnsigned(ByArg.second.TheKind);
206 AddUint64(ByArg.second.Info);
211 // Include the hash for all type identifiers used by this module.
212 for (GlobalValue::GUID TId : UsedTypeIds) {
213 auto SummariesI = TypeIdSummariesByGuid.find(TId);
214 if (SummariesI != TypeIdSummariesByGuid.end())
215 for (auto *Summary : SummariesI->second)
216 AddTypeIdSummary(Summary->first, Summary->second);
219 if (!Conf.SampleProfile.empty()) {
220 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
222 Hasher.update(FileOrErr.get()->getBuffer());
225 Key = toHex(Hasher.result());
228 static void thinLTOResolveWeakForLinkerGUID(
229 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
230 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
231 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
233 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
235 for (auto &S : GVSummaryList) {
236 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
237 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
239 // We need to emit only one of these. The prevailing module will keep it,
240 // but turned into a weak, while the others will drop it when possible.
241 // This is both a compile-time optimization and a correctness
242 // transformation. This is necessary for correctness when we have exported
243 // a reference - we need to convert the linkonce to weak to
244 // ensure a copy is kept to satisfy the exported reference.
245 // FIXME: We may want to split the compile time and correctness
246 // aspects into separate routines.
247 if (isPrevailing(GUID, S.get())) {
248 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
249 S->setLinkage(GlobalValue::getWeakLinkage(
250 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
252 // Alias and aliasee can't be turned into available_externally.
253 else if (!isa<AliasSummary>(S.get()) &&
254 !GlobalInvolvedWithAlias.count(S.get()))
255 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
256 if (S->linkage() != OriginalLinkage)
257 recordNewLinkage(S->modulePath(), GUID, S->linkage());
261 // Resolve Weak and LinkOnce values in the \p Index.
263 // We'd like to drop these functions if they are no longer referenced in the
264 // current module. However there is a chance that another module is still
265 // referencing them because of the import. We make sure we always emit at least
267 void llvm::thinLTOResolveWeakForLinkerInIndex(
268 ModuleSummaryIndex &Index,
269 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
271 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
273 // We won't optimize the globals that are referenced by an alias for now
274 // Ideally we should turn the alias into a global and duplicate the definition
276 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
277 for (auto &I : Index)
278 for (auto &S : I.second)
279 if (auto AS = dyn_cast<AliasSummary>(S.get()))
280 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
282 for (auto &I : Index)
283 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
284 isPrevailing, recordNewLinkage);
287 static void thinLTOInternalizeAndPromoteGUID(
288 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
289 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
290 for (auto &S : GVSummaryList) {
291 if (isExported(S->modulePath(), GUID)) {
292 if (GlobalValue::isLocalLinkage(S->linkage()))
293 S->setLinkage(GlobalValue::ExternalLinkage);
294 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
295 S->setLinkage(GlobalValue::InternalLinkage);
299 // Update the linkages in the given \p Index to mark exported values
300 // as external and non-exported values as internal.
301 void llvm::thinLTOInternalizeAndPromoteInIndex(
302 ModuleSummaryIndex &Index,
303 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
304 for (auto &I : Index)
305 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
308 // Requires a destructor for std::vector<InputModule>.
309 InputFile::~InputFile() = default;
311 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
312 std::unique_ptr<InputFile> File(new InputFile);
314 ErrorOr<MemoryBufferRef> BCOrErr =
315 IRObjectFile::findBitcodeInMemBuffer(Object);
317 return errorCodeToError(BCOrErr.getError());
319 Expected<std::vector<BitcodeModule>> BMsOrErr =
320 getBitcodeModuleList(*BCOrErr);
322 return BMsOrErr.takeError();
324 if (BMsOrErr->empty())
325 return make_error<StringError>("Bitcode file does not contain any modules",
326 inconvertibleErrorCode());
328 File->Mods = *BMsOrErr;
331 std::vector<Module *> Mods;
332 std::vector<std::unique_ptr<Module>> OwnedMods;
333 for (auto BM : *BMsOrErr) {
334 Expected<std::unique_ptr<Module>> MOrErr =
335 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
336 /*IsImporting*/ false);
338 return MOrErr.takeError();
340 if ((*MOrErr)->getDataLayoutStr().empty())
341 return make_error<StringError>("input module has no datalayout",
342 inconvertibleErrorCode());
344 Mods.push_back(MOrErr->get());
345 OwnedMods.push_back(std::move(*MOrErr));
348 SmallVector<char, 0> Symtab;
349 if (Error E = irsymtab::build(Mods, Symtab, File->Strtab))
352 irsymtab::Reader R({Symtab.data(), Symtab.size()},
353 {File->Strtab.data(), File->Strtab.size()});
354 File->TargetTriple = R.getTargetTriple();
355 File->SourceFileName = R.getSourceFileName();
356 File->COFFLinkerOpts = R.getCOFFLinkerOpts();
357 File->ComdatTable = R.getComdatTable();
359 for (unsigned I = 0; I != Mods.size(); ++I) {
360 size_t Begin = File->Symbols.size();
361 for (const irsymtab::Reader::SymbolRef &Sym : R.module_symbols(I))
362 // Skip symbols that are irrelevant to LTO. Note that this condition needs
363 // to match the one in Skip() in LTO::addRegularLTO().
364 if (Sym.isGlobal() && !Sym.isFormatSpecific())
365 File->Symbols.push_back(Sym);
366 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
369 return std::move(File);
372 StringRef InputFile::getName() const {
373 return Mods[0].getModuleIdentifier();
376 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
378 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
381 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
384 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
387 LTO::LTO(Config Conf, ThinBackend Backend,
388 unsigned ParallelCodeGenParallelismLevel)
389 : Conf(std::move(Conf)),
390 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
391 ThinLTO(std::move(Backend)) {}
393 // Requires a destructor for MapVector<BitcodeModule>.
394 LTO::~LTO() = default;
396 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
397 void LTO::addSymbolToGlobalRes(const InputFile::Symbol &Sym,
398 SymbolResolution Res, unsigned Partition) {
399 auto &GlobalRes = GlobalResolutions[Sym.getName()];
400 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
402 GlobalRes.IRName = Sym.getIRName();
404 // Set the partition to external if we know it is used elsewhere, e.g.
405 // it is visible to a regular object, is referenced from llvm.compiler_used,
406 // or was already recorded as being referenced from a different partition.
407 if (Res.VisibleToRegularObj || Sym.isUsed() ||
408 (GlobalRes.Partition != GlobalResolution::Unknown &&
409 GlobalRes.Partition != Partition)) {
410 GlobalRes.Partition = GlobalResolution::External;
412 // First recorded reference, save the current partition.
413 GlobalRes.Partition = Partition;
415 // Flag as visible outside of ThinLTO if visible from a regular object or
416 // if this is a reference in the regular LTO partition.
417 GlobalRes.VisibleOutsideThinLTO |=
418 (Res.VisibleToRegularObj || Sym.isUsed() ||
419 Partition == GlobalResolution::RegularLTO);
422 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
423 ArrayRef<SymbolResolution> Res) {
424 StringRef Path = Input->getName();
426 auto ResI = Res.begin();
427 for (const InputFile::Symbol &Sym : Input->symbols()) {
428 assert(ResI != Res.end());
429 SymbolResolution Res = *ResI++;
431 OS << "-r=" << Path << ',' << Sym.getName() << ',';
434 if (Res.FinalDefinitionInLinkageUnit)
436 if (Res.VisibleToRegularObj)
441 assert(ResI == Res.end());
444 Error LTO::add(std::unique_ptr<InputFile> Input,
445 ArrayRef<SymbolResolution> Res) {
446 assert(!CalledGetMaxTasks);
448 if (Conf.ResolutionFile)
449 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
451 const SymbolResolution *ResI = Res.begin();
452 for (unsigned I = 0; I != Input->Mods.size(); ++I)
453 if (Error Err = addModule(*Input, I, ResI, Res.end()))
456 assert(ResI == Res.end());
457 return Error::success();
460 Error LTO::addModule(InputFile &Input, unsigned ModI,
461 const SymbolResolution *&ResI,
462 const SymbolResolution *ResE) {
463 Expected<bool> HasThinLTOSummary = Input.Mods[ModI].hasSummary();
464 if (!HasThinLTOSummary)
465 return HasThinLTOSummary.takeError();
467 auto ModSyms = Input.module_symbols(ModI);
468 if (*HasThinLTOSummary)
469 return addThinLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
471 return addRegularLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
474 // Add a regular LTO object to the link.
475 Error LTO::addRegularLTO(BitcodeModule BM,
476 ArrayRef<InputFile::Symbol> Syms,
477 const SymbolResolution *&ResI,
478 const SymbolResolution *ResE) {
479 if (!RegularLTO.CombinedModule) {
480 RegularLTO.CombinedModule =
481 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
482 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
484 Expected<std::unique_ptr<Module>> MOrErr =
485 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
486 /*IsImporting*/ false);
488 return MOrErr.takeError();
490 Module &M = **MOrErr;
491 if (Error Err = M.materializeMetadata())
495 ModuleSymbolTable SymTab;
496 SymTab.addModule(&M);
498 std::vector<GlobalValue *> Keep;
500 for (GlobalVariable &GV : M.globals())
501 if (GV.hasAppendingLinkage())
504 DenseSet<GlobalObject *> AliasedGlobals;
505 for (auto &GA : M.aliases())
506 if (GlobalObject *GO = GA.getBaseObject())
507 AliasedGlobals.insert(GO);
509 // In this function we need IR GlobalValues matching the symbols in Syms
510 // (which is not backed by a module), so we need to enumerate them in the same
511 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
512 // matches the order of an irsymtab, but when we read the irsymtab in
513 // InputFile::create we omit some symbols that are irrelevant to LTO. The
514 // Skip() function skips the same symbols from the module as InputFile does
515 // from the symbol table.
516 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
518 while (MsymI != MsymE) {
519 auto Flags = SymTab.getSymbolFlags(*MsymI);
520 if ((Flags & object::BasicSymbolRef::SF_Global) &&
521 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
528 for (const InputFile::Symbol &Sym : Syms) {
529 assert(ResI != ResE);
530 SymbolResolution Res = *ResI++;
531 addSymbolToGlobalRes(Sym, Res, 0);
533 assert(MsymI != MsymE);
534 ModuleSymbolTable::Symbol Msym = *MsymI++;
537 if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
538 if (Res.Prevailing) {
539 if (Sym.isUndefined())
542 switch (GV->getLinkage()) {
545 case GlobalValue::LinkOnceAnyLinkage:
546 GV->setLinkage(GlobalValue::WeakAnyLinkage);
548 case GlobalValue::LinkOnceODRLinkage:
549 GV->setLinkage(GlobalValue::WeakODRLinkage);
552 } else if (isa<GlobalObject>(GV) &&
553 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
554 GV->hasAvailableExternallyLinkage()) &&
555 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
556 // Either of the above three types of linkage indicates that the
557 // chosen prevailing symbol will have the same semantics as this copy of
558 // the symbol, so we can link it with available_externally linkage. We
559 // only need to do this if the symbol is undefined.
560 GlobalValue *CombinedGV =
561 RegularLTO.CombinedModule->getNamedValue(GV->getName());
562 if (!CombinedGV || CombinedGV->isDeclaration()) {
564 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
565 cast<GlobalObject>(GV)->setComdat(nullptr);
569 // Common resolution: collect the maximum size/alignment over all commons.
570 // We also record if we see an instance of a common as prevailing, so that
571 // if none is prevailing we can ignore it later.
572 if (Sym.isCommon()) {
573 // FIXME: We should figure out what to do about commons defined by asm.
574 // For now they aren't reported correctly by ModuleSymbolTable.
575 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
576 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
577 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
578 CommonRes.Prevailing |= Res.Prevailing;
581 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
583 assert(MsymI == MsymE);
585 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
586 [](GlobalValue &, IRMover::ValueAdder) {},
587 /* IsPerformingImport */ false);
590 // Add a ThinLTO object to the link.
591 Error LTO::addThinLTO(BitcodeModule BM,
592 ArrayRef<InputFile::Symbol> Syms,
593 const SymbolResolution *&ResI,
594 const SymbolResolution *ResE) {
595 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
597 return SummaryOrErr.takeError();
598 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
599 ThinLTO.ModuleMap.size());
601 for (const InputFile::Symbol &Sym : Syms) {
602 assert(ResI != ResE);
603 SymbolResolution Res = *ResI++;
604 addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
606 if (Res.Prevailing) {
607 if (!Sym.getIRName().empty()) {
608 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
609 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
610 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
615 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
616 return make_error<StringError>(
617 "Expected at most one ThinLTO module per bitcode file",
618 inconvertibleErrorCode());
620 return Error::success();
623 unsigned LTO::getMaxTasks() const {
624 CalledGetMaxTasks = true;
625 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
628 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
629 // Save the status of having a regularLTO combined module, as
630 // this is needed for generating the ThinLTO Task ID, and
631 // the CombinedModule will be moved at the end of runRegularLTO.
632 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
633 // Invoke regular LTO if there was a regular LTO module to start with.
635 if (auto E = runRegularLTO(AddStream))
637 return runThinLTO(AddStream, Cache, HasRegularLTO);
640 Error LTO::runRegularLTO(AddStreamFn AddStream) {
641 // Make sure commons have the right size/alignment: we kept the largest from
642 // all the prevailing when adding the inputs, and we apply it here.
643 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
644 for (auto &I : RegularLTO.Commons) {
645 if (!I.second.Prevailing)
646 // Don't do anything if no instance of this common was prevailing.
648 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
649 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
650 // Don't create a new global if the type is already correct, just make
651 // sure the alignment is correct.
652 OldGV->setAlignment(I.second.Align);
656 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
657 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
658 GlobalValue::CommonLinkage,
659 ConstantAggregateZero::get(Ty), "");
660 GV->setAlignment(I.second.Align);
662 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
664 OldGV->eraseFromParent();
666 GV->setName(I.first);
670 if (Conf.PreOptModuleHook &&
671 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
672 return Error::success();
674 if (!Conf.CodeGenOnly) {
675 for (const auto &R : GlobalResolutions) {
676 if (R.second.IRName.empty())
678 if (R.second.Partition != 0 &&
679 R.second.Partition != GlobalResolution::External)
683 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
684 // Ignore symbols defined in other partitions.
685 if (!GV || GV->hasLocalLinkage())
687 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
688 : GlobalValue::UnnamedAddr::None);
689 if (R.second.Partition == 0)
690 GV->setLinkage(GlobalValue::InternalLinkage);
693 if (Conf.PostInternalizeModuleHook &&
694 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
695 return Error::success();
697 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
698 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
701 /// This class defines the interface to the ThinLTO backend.
702 class lto::ThinBackendProc {
705 ModuleSummaryIndex &CombinedIndex;
706 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
709 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
710 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
711 : Conf(Conf), CombinedIndex(CombinedIndex),
712 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
714 virtual ~ThinBackendProc() {}
716 unsigned Task, BitcodeModule BM,
717 const FunctionImporter::ImportMapTy &ImportList,
718 const FunctionImporter::ExportSetTy &ExportList,
719 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
720 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
721 virtual Error wait() = 0;
725 class InProcessThinBackend : public ThinBackendProc {
726 ThreadPool BackendThreadPool;
727 AddStreamFn AddStream;
728 NativeObjectCache Cache;
729 TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
735 InProcessThinBackend(
736 Config &Conf, ModuleSummaryIndex &CombinedIndex,
737 unsigned ThinLTOParallelismLevel,
738 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
739 AddStreamFn AddStream, NativeObjectCache Cache)
740 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
741 BackendThreadPool(ThinLTOParallelismLevel),
742 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
743 // Create a mapping from type identifier GUIDs to type identifier summaries.
744 // This allows backends to use the type identifier GUIDs stored in the
745 // function summaries to determine which type identifier summaries affect
746 // each function without needing to compute GUIDs in each backend.
747 for (auto &TId : CombinedIndex.typeIds())
748 TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
751 Error runThinLTOBackendThread(
752 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
753 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
754 const FunctionImporter::ImportMapTy &ImportList,
755 const FunctionImporter::ExportSetTy &ExportList,
756 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
757 const GVSummaryMapTy &DefinedGlobals,
758 MapVector<StringRef, BitcodeModule> &ModuleMap,
759 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
760 auto RunThinBackend = [&](AddStreamFn AddStream) {
761 LTOLLVMContext BackendContext(Conf);
762 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
764 return MOrErr.takeError();
766 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
767 ImportList, DefinedGlobals, ModuleMap);
770 auto ModuleID = BM.getModuleIdentifier();
772 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
773 all_of(CombinedIndex.getModuleHash(ModuleID),
774 [](uint32_t V) { return V == 0; }))
775 // Cache disabled or no entry for this module in the combined index or
777 return RunThinBackend(AddStream);
780 // The module may be cached, this helps handling it.
781 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
782 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
783 if (AddStreamFn CacheAddStream = Cache(Task, Key))
784 return RunThinBackend(CacheAddStream);
786 return Error::success();
790 unsigned Task, BitcodeModule BM,
791 const FunctionImporter::ImportMapTy &ImportList,
792 const FunctionImporter::ExportSetTy &ExportList,
793 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
794 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
795 StringRef ModulePath = BM.getModuleIdentifier();
796 assert(ModuleToDefinedGVSummaries.count(ModulePath));
797 const GVSummaryMapTy &DefinedGlobals =
798 ModuleToDefinedGVSummaries.find(ModulePath)->second;
799 BackendThreadPool.async(
800 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
801 const FunctionImporter::ImportMapTy &ImportList,
802 const FunctionImporter::ExportSetTy &ExportList,
803 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
805 const GVSummaryMapTy &DefinedGlobals,
806 MapVector<StringRef, BitcodeModule> &ModuleMap,
807 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
808 Error E = runThinLTOBackendThread(
809 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
810 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
812 std::unique_lock<std::mutex> L(ErrMu);
814 Err = joinErrors(std::move(*Err), std::move(E));
819 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
820 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
821 std::ref(TypeIdSummariesByGuid));
822 return Error::success();
825 Error wait() override {
826 BackendThreadPool.wait();
828 return std::move(*Err);
830 return Error::success();
833 } // end anonymous namespace
835 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
836 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
837 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
838 AddStreamFn AddStream, NativeObjectCache Cache) {
839 return llvm::make_unique<InProcessThinBackend>(
840 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
845 // Given the original \p Path to an output file, replace any path
846 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
847 // resulting directory if it does not yet exist.
848 std::string lto::getThinLTOOutputFile(const std::string &Path,
849 const std::string &OldPrefix,
850 const std::string &NewPrefix) {
851 if (OldPrefix.empty() && NewPrefix.empty())
853 SmallString<128> NewPath(Path);
854 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
855 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
856 if (!ParentPath.empty()) {
857 // Make sure the new directory exists, creating it if necessary.
858 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
859 llvm::errs() << "warning: could not create directory '" << ParentPath
860 << "': " << EC.message() << '\n';
862 return NewPath.str();
866 class WriteIndexesThinBackend : public ThinBackendProc {
867 std::string OldPrefix, NewPrefix;
868 bool ShouldEmitImportsFiles;
870 std::string LinkedObjectsFileName;
871 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
874 WriteIndexesThinBackend(
875 Config &Conf, ModuleSummaryIndex &CombinedIndex,
876 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
877 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
878 std::string LinkedObjectsFileName)
879 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
880 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
881 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
882 LinkedObjectsFileName(LinkedObjectsFileName) {}
885 unsigned Task, BitcodeModule BM,
886 const FunctionImporter::ImportMapTy &ImportList,
887 const FunctionImporter::ExportSetTy &ExportList,
888 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
889 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
890 StringRef ModulePath = BM.getModuleIdentifier();
891 std::string NewModulePath =
892 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
895 if (!LinkedObjectsFileName.empty()) {
896 if (!LinkedObjectsFile) {
897 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
898 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
900 return errorCodeToError(EC);
902 *LinkedObjectsFile << NewModulePath << '\n';
905 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
906 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
907 ImportList, ModuleToSummariesForIndex);
909 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
910 sys::fs::OpenFlags::F_None);
912 return errorCodeToError(EC);
913 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
915 if (ShouldEmitImportsFiles)
916 return errorCodeToError(
917 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
918 return Error::success();
921 Error wait() override { return Error::success(); }
923 } // end anonymous namespace
925 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
926 std::string NewPrefix,
927 bool ShouldEmitImportsFiles,
928 std::string LinkedObjectsFile) {
929 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
930 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
931 AddStreamFn AddStream, NativeObjectCache Cache) {
932 return llvm::make_unique<WriteIndexesThinBackend>(
933 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
934 ShouldEmitImportsFiles, LinkedObjectsFile);
938 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
939 bool HasRegularLTO) {
940 if (ThinLTO.ModuleMap.empty())
941 return Error::success();
943 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
944 return Error::success();
946 // Collect for each module the list of function it defines (GUID ->
948 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
949 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
950 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
951 ModuleToDefinedGVSummaries);
952 // Create entries for any modules that didn't have any GV summaries
953 // (either they didn't have any GVs to start with, or we suppressed
954 // generation of the summaries because they e.g. had inline assembly
955 // uses that couldn't be promoted/renamed on export). This is so
956 // InProcessThinBackend::start can still launch a backend thread, which
957 // is passed the map of summaries for the module, without any special
958 // handling for this case.
959 for (auto &Mod : ThinLTO.ModuleMap)
960 if (!ModuleToDefinedGVSummaries.count(Mod.first))
961 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
963 StringMap<FunctionImporter::ImportMapTy> ImportLists(
964 ThinLTO.ModuleMap.size());
965 StringMap<FunctionImporter::ExportSetTy> ExportLists(
966 ThinLTO.ModuleMap.size());
967 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
969 if (Conf.OptLevel > 0) {
970 // Compute "dead" symbols, we don't want to import/export these!
971 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
972 for (auto &Res : GlobalResolutions) {
973 if (Res.second.VisibleOutsideThinLTO &&
974 // IRName will be defined if we have seen the prevailing copy of
975 // this value. If not, no need to preserve any ThinLTO copies.
976 !Res.second.IRName.empty())
977 GUIDPreservedSymbols.insert(GlobalValue::getGUID(
978 GlobalValue::getRealLinkageName(Res.second.IRName)));
982 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
984 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
985 ImportLists, ExportLists, &DeadSymbols);
987 std::set<GlobalValue::GUID> ExportedGUIDs;
988 for (auto &Res : GlobalResolutions) {
989 // First check if the symbol was flagged as having external references.
990 if (Res.second.Partition != GlobalResolution::External)
992 // IRName will be defined if we have seen the prevailing copy of
993 // this value. If not, no need to mark as exported from a ThinLTO
994 // partition (and we can't get the GUID).
995 if (Res.second.IRName.empty())
997 auto GUID = GlobalValue::getGUID(
998 GlobalValue::getRealLinkageName(Res.second.IRName));
999 // Mark exported unless index-based analysis determined it to be dead.
1000 if (!DeadSymbols.count(GUID))
1001 ExportedGUIDs.insert(GUID);
1004 auto isPrevailing = [&](GlobalValue::GUID GUID,
1005 const GlobalValueSummary *S) {
1006 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1008 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1009 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1010 return (ExportList != ExportLists.end() &&
1011 ExportList->second.count(GUID)) ||
1012 ExportedGUIDs.count(GUID);
1014 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1016 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1017 GlobalValue::GUID GUID,
1018 GlobalValue::LinkageTypes NewLinkage) {
1019 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1022 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1026 std::unique_ptr<ThinBackendProc> BackendProc =
1027 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1030 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1031 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1032 // are reserved for parallel code generation partitions.
1034 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
1035 for (auto &Mod : ThinLTO.ModuleMap) {
1036 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1037 ExportLists[Mod.first],
1038 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1043 return BackendProc->wait();
1046 Expected<std::unique_ptr<tool_output_file>>
1047 lto::setupOptimizationRemarks(LLVMContext &Context,
1048 StringRef LTORemarksFilename,
1049 bool LTOPassRemarksWithHotness, int Count) {
1050 if (LTORemarksFilename.empty())
1053 std::string Filename = LTORemarksFilename;
1055 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1058 auto DiagnosticFile =
1059 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1061 return errorCodeToError(EC);
1062 Context.setDiagnosticsOutputFile(
1063 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1064 if (LTOPassRemarksWithHotness)
1065 Context.setDiagnosticHotnessRequested(true);
1066 DiagnosticFile->keep();
1067 return std::move(DiagnosticFile);