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/Support/Error.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/SHA1.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/ThreadPool.h"
36 #include "llvm/Support/Threading.h"
37 #include "llvm/Support/VCSRevision.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Transforms/IPO.h"
42 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
43 #include "llvm/Transforms/Utils/SplitModule.h"
49 using namespace object;
51 #define DEBUG_TYPE "lto"
53 // The values are (type identifier, summary) pairs.
56 TinyPtrVector<const std::pair<const std::string, TypeIdSummary> *>>
57 TypeIdSummariesByGuidTy;
59 // Returns a unique hash for the Module considering the current list of
60 // export/import and other global analysis results.
61 // The hash is produced in \p Key.
62 static void computeCacheKey(
63 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
64 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
65 const FunctionImporter::ExportSetTy &ExportList,
66 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
67 const GVSummaryMapTy &DefinedGlobals,
68 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
69 // Compute the unique hash for this entry.
70 // This is based on the current compiler version, the module itself, the
71 // export list, the hash for every single module in the import list, the
72 // list of ResolvedODR for the module, and the list of preserved symbols.
75 // Start with the compiler revision
76 Hasher.update(LLVM_VERSION_STRING);
78 Hasher.update(LLVM_REVISION);
81 // Include the parts of the LTO configuration that affect code generation.
82 auto AddString = [&](StringRef Str) {
84 Hasher.update(ArrayRef<uint8_t>{0});
86 auto AddUnsigned = [&](unsigned I) {
92 Hasher.update(ArrayRef<uint8_t>{Data, 4});
94 auto AddUint64 = [&](uint64_t I) {
104 Hasher.update(ArrayRef<uint8_t>{Data, 8});
107 // FIXME: Hash more of Options. For now all clients initialize Options from
108 // command-line flags (which is unsupported in production), but may set
109 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
110 // DataSections and DebuggerTuning via command line flags.
111 AddUnsigned(Conf.Options.RelaxELFRelocations);
112 AddUnsigned(Conf.Options.FunctionSections);
113 AddUnsigned(Conf.Options.DataSections);
114 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
115 for (auto &A : Conf.MAttrs)
117 AddUnsigned(Conf.RelocModel);
118 AddUnsigned(Conf.CodeModel);
119 AddUnsigned(Conf.CGOptLevel);
120 AddUnsigned(Conf.CGFileType);
121 AddUnsigned(Conf.OptLevel);
122 AddString(Conf.OptPipeline);
123 AddString(Conf.AAPipeline);
124 AddString(Conf.OverrideTriple);
125 AddString(Conf.DefaultTriple);
127 // Include the hash for the current module
128 auto ModHash = Index.getModuleHash(ModuleID);
129 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
130 for (auto F : ExportList)
131 // The export list can impact the internalization, be conservative here
132 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
134 // Include the hash for every module we import functions from. The set of
135 // imported symbols for each module may affect code generation and is
136 // sensitive to link order, so include that as well.
137 for (auto &Entry : ImportList) {
138 auto ModHash = Index.getModuleHash(Entry.first());
139 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
141 AddUint64(Entry.second.size());
142 for (auto &Fn : Entry.second)
146 // Include the hash for the resolved ODR.
147 for (auto &Entry : ResolvedODR) {
148 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
149 sizeof(GlobalValue::GUID)));
150 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
151 sizeof(GlobalValue::LinkageTypes)));
154 std::set<GlobalValue::GUID> UsedTypeIds;
156 auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
157 auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
160 for (auto &TT : FS->type_tests())
161 UsedTypeIds.insert(TT);
162 for (auto &TT : FS->type_test_assume_vcalls())
163 UsedTypeIds.insert(TT.GUID);
164 for (auto &TT : FS->type_checked_load_vcalls())
165 UsedTypeIds.insert(TT.GUID);
166 for (auto &TT : FS->type_test_assume_const_vcalls())
167 UsedTypeIds.insert(TT.VFunc.GUID);
168 for (auto &TT : FS->type_checked_load_const_vcalls())
169 UsedTypeIds.insert(TT.VFunc.GUID);
172 // Include the hash for the linkage type to reflect internalization and weak
173 // resolution, and collect any used type identifier resolutions.
174 for (auto &GS : DefinedGlobals) {
175 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
177 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
178 AddUsedTypeIds(GS.second);
181 // Imported functions may introduce new uses of type identifier resolutions,
182 // so we need to collect their used resolutions as well.
183 for (auto &ImpM : ImportList)
184 for (auto &ImpF : ImpM.second)
185 AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
187 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
190 AddUnsigned(S.TTRes.TheKind);
191 AddUnsigned(S.TTRes.SizeM1BitWidth);
193 AddUint64(S.WPDRes.size());
194 for (auto &WPD : S.WPDRes) {
195 AddUnsigned(WPD.first);
196 AddUnsigned(WPD.second.TheKind);
197 AddString(WPD.second.SingleImplName);
199 AddUint64(WPD.second.ResByArg.size());
200 for (auto &ByArg : WPD.second.ResByArg) {
201 AddUint64(ByArg.first.size());
202 for (uint64_t Arg : ByArg.first)
204 AddUnsigned(ByArg.second.TheKind);
205 AddUint64(ByArg.second.Info);
210 // Include the hash for all type identifiers used by this module.
211 for (GlobalValue::GUID TId : UsedTypeIds) {
212 auto SummariesI = TypeIdSummariesByGuid.find(TId);
213 if (SummariesI != TypeIdSummariesByGuid.end())
214 for (auto *Summary : SummariesI->second)
215 AddTypeIdSummary(Summary->first, Summary->second);
218 if (!Conf.SampleProfile.empty()) {
219 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
221 Hasher.update(FileOrErr.get()->getBuffer());
224 Key = toHex(Hasher.result());
227 static void thinLTOResolveWeakForLinkerGUID(
228 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
229 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
230 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
232 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
234 for (auto &S : GVSummaryList) {
235 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
236 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
238 // We need to emit only one of these. The prevailing module will keep it,
239 // but turned into a weak, while the others will drop it when possible.
240 // This is both a compile-time optimization and a correctness
241 // transformation. This is necessary for correctness when we have exported
242 // a reference - we need to convert the linkonce to weak to
243 // ensure a copy is kept to satisfy the exported reference.
244 // FIXME: We may want to split the compile time and correctness
245 // aspects into separate routines.
246 if (isPrevailing(GUID, S.get())) {
247 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
248 S->setLinkage(GlobalValue::getWeakLinkage(
249 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
251 // Alias and aliasee can't be turned into available_externally.
252 else if (!isa<AliasSummary>(S.get()) &&
253 !GlobalInvolvedWithAlias.count(S.get()))
254 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
255 if (S->linkage() != OriginalLinkage)
256 recordNewLinkage(S->modulePath(), GUID, S->linkage());
260 // Resolve Weak and LinkOnce values in the \p Index.
262 // We'd like to drop these functions if they are no longer referenced in the
263 // current module. However there is a chance that another module is still
264 // referencing them because of the import. We make sure we always emit at least
266 void llvm::thinLTOResolveWeakForLinkerInIndex(
267 ModuleSummaryIndex &Index,
268 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
270 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
272 // We won't optimize the globals that are referenced by an alias for now
273 // Ideally we should turn the alias into a global and duplicate the definition
275 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
276 for (auto &I : Index)
277 for (auto &S : I.second.SummaryList)
278 if (auto AS = dyn_cast<AliasSummary>(S.get()))
279 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
281 for (auto &I : Index)
282 thinLTOResolveWeakForLinkerGUID(I.second.SummaryList, I.first,
283 GlobalInvolvedWithAlias, isPrevailing,
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.SummaryList, 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) {
596 BM.readSummary(ThinLTO.CombinedIndex, ThinLTO.ModuleMap.size()))
599 for (const InputFile::Symbol &Sym : Syms) {
600 assert(ResI != ResE);
601 SymbolResolution Res = *ResI++;
602 addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
604 if (Res.Prevailing) {
605 if (!Sym.getIRName().empty()) {
606 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
607 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
608 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
613 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
614 return make_error<StringError>(
615 "Expected at most one ThinLTO module per bitcode file",
616 inconvertibleErrorCode());
618 return Error::success();
621 unsigned LTO::getMaxTasks() const {
622 CalledGetMaxTasks = true;
623 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
626 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
627 // Save the status of having a regularLTO combined module, as
628 // this is needed for generating the ThinLTO Task ID, and
629 // the CombinedModule will be moved at the end of runRegularLTO.
630 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
631 // Invoke regular LTO if there was a regular LTO module to start with.
633 if (auto E = runRegularLTO(AddStream))
635 return runThinLTO(AddStream, Cache, HasRegularLTO);
638 Error LTO::runRegularLTO(AddStreamFn AddStream) {
639 // Make sure commons have the right size/alignment: we kept the largest from
640 // all the prevailing when adding the inputs, and we apply it here.
641 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
642 for (auto &I : RegularLTO.Commons) {
643 if (!I.second.Prevailing)
644 // Don't do anything if no instance of this common was prevailing.
646 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
647 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
648 // Don't create a new global if the type is already correct, just make
649 // sure the alignment is correct.
650 OldGV->setAlignment(I.second.Align);
654 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
655 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
656 GlobalValue::CommonLinkage,
657 ConstantAggregateZero::get(Ty), "");
658 GV->setAlignment(I.second.Align);
660 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
662 OldGV->eraseFromParent();
664 GV->setName(I.first);
668 if (Conf.PreOptModuleHook &&
669 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
670 return Error::success();
672 if (!Conf.CodeGenOnly) {
673 for (const auto &R : GlobalResolutions) {
674 if (R.second.IRName.empty())
676 if (R.second.Partition != 0 &&
677 R.second.Partition != GlobalResolution::External)
681 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
682 // Ignore symbols defined in other partitions.
683 if (!GV || GV->hasLocalLinkage())
685 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
686 : GlobalValue::UnnamedAddr::None);
687 if (R.second.Partition == 0)
688 GV->setLinkage(GlobalValue::InternalLinkage);
691 if (Conf.PostInternalizeModuleHook &&
692 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
693 return Error::success();
695 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
696 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
699 /// This class defines the interface to the ThinLTO backend.
700 class lto::ThinBackendProc {
703 ModuleSummaryIndex &CombinedIndex;
704 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
707 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
708 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
709 : Conf(Conf), CombinedIndex(CombinedIndex),
710 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
712 virtual ~ThinBackendProc() {}
714 unsigned Task, BitcodeModule BM,
715 const FunctionImporter::ImportMapTy &ImportList,
716 const FunctionImporter::ExportSetTy &ExportList,
717 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
718 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
719 virtual Error wait() = 0;
723 class InProcessThinBackend : public ThinBackendProc {
724 ThreadPool BackendThreadPool;
725 AddStreamFn AddStream;
726 NativeObjectCache Cache;
727 TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
733 InProcessThinBackend(
734 Config &Conf, ModuleSummaryIndex &CombinedIndex,
735 unsigned ThinLTOParallelismLevel,
736 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
737 AddStreamFn AddStream, NativeObjectCache Cache)
738 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
739 BackendThreadPool(ThinLTOParallelismLevel),
740 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
741 // Create a mapping from type identifier GUIDs to type identifier summaries.
742 // This allows backends to use the type identifier GUIDs stored in the
743 // function summaries to determine which type identifier summaries affect
744 // each function without needing to compute GUIDs in each backend.
745 for (auto &TId : CombinedIndex.typeIds())
746 TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
749 Error runThinLTOBackendThread(
750 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
751 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
752 const FunctionImporter::ImportMapTy &ImportList,
753 const FunctionImporter::ExportSetTy &ExportList,
754 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
755 const GVSummaryMapTy &DefinedGlobals,
756 MapVector<StringRef, BitcodeModule> &ModuleMap,
757 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
758 auto RunThinBackend = [&](AddStreamFn AddStream) {
759 LTOLLVMContext BackendContext(Conf);
760 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
762 return MOrErr.takeError();
764 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
765 ImportList, DefinedGlobals, ModuleMap);
768 auto ModuleID = BM.getModuleIdentifier();
770 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
771 all_of(CombinedIndex.getModuleHash(ModuleID),
772 [](uint32_t V) { return V == 0; }))
773 // Cache disabled or no entry for this module in the combined index or
775 return RunThinBackend(AddStream);
778 // The module may be cached, this helps handling it.
779 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
780 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
781 if (AddStreamFn CacheAddStream = Cache(Task, Key))
782 return RunThinBackend(CacheAddStream);
784 return Error::success();
788 unsigned Task, BitcodeModule BM,
789 const FunctionImporter::ImportMapTy &ImportList,
790 const FunctionImporter::ExportSetTy &ExportList,
791 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
792 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
793 StringRef ModulePath = BM.getModuleIdentifier();
794 assert(ModuleToDefinedGVSummaries.count(ModulePath));
795 const GVSummaryMapTy &DefinedGlobals =
796 ModuleToDefinedGVSummaries.find(ModulePath)->second;
797 BackendThreadPool.async(
798 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
799 const FunctionImporter::ImportMapTy &ImportList,
800 const FunctionImporter::ExportSetTy &ExportList,
801 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
803 const GVSummaryMapTy &DefinedGlobals,
804 MapVector<StringRef, BitcodeModule> &ModuleMap,
805 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
806 Error E = runThinLTOBackendThread(
807 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
808 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
810 std::unique_lock<std::mutex> L(ErrMu);
812 Err = joinErrors(std::move(*Err), std::move(E));
817 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
818 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
819 std::ref(TypeIdSummariesByGuid));
820 return Error::success();
823 Error wait() override {
824 BackendThreadPool.wait();
826 return std::move(*Err);
828 return Error::success();
831 } // end anonymous namespace
833 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
834 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
835 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
836 AddStreamFn AddStream, NativeObjectCache Cache) {
837 return llvm::make_unique<InProcessThinBackend>(
838 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
843 // Given the original \p Path to an output file, replace any path
844 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
845 // resulting directory if it does not yet exist.
846 std::string lto::getThinLTOOutputFile(const std::string &Path,
847 const std::string &OldPrefix,
848 const std::string &NewPrefix) {
849 if (OldPrefix.empty() && NewPrefix.empty())
851 SmallString<128> NewPath(Path);
852 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
853 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
854 if (!ParentPath.empty()) {
855 // Make sure the new directory exists, creating it if necessary.
856 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
857 llvm::errs() << "warning: could not create directory '" << ParentPath
858 << "': " << EC.message() << '\n';
860 return NewPath.str();
864 class WriteIndexesThinBackend : public ThinBackendProc {
865 std::string OldPrefix, NewPrefix;
866 bool ShouldEmitImportsFiles;
868 std::string LinkedObjectsFileName;
869 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
872 WriteIndexesThinBackend(
873 Config &Conf, ModuleSummaryIndex &CombinedIndex,
874 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
875 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
876 std::string LinkedObjectsFileName)
877 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
878 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
879 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
880 LinkedObjectsFileName(LinkedObjectsFileName) {}
883 unsigned Task, BitcodeModule BM,
884 const FunctionImporter::ImportMapTy &ImportList,
885 const FunctionImporter::ExportSetTy &ExportList,
886 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
887 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
888 StringRef ModulePath = BM.getModuleIdentifier();
889 std::string NewModulePath =
890 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
893 if (!LinkedObjectsFileName.empty()) {
894 if (!LinkedObjectsFile) {
895 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
896 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
898 return errorCodeToError(EC);
900 *LinkedObjectsFile << NewModulePath << '\n';
903 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
904 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
905 ImportList, ModuleToSummariesForIndex);
907 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
908 sys::fs::OpenFlags::F_None);
910 return errorCodeToError(EC);
911 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
913 if (ShouldEmitImportsFiles)
914 return errorCodeToError(
915 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
916 return Error::success();
919 Error wait() override { return Error::success(); }
921 } // end anonymous namespace
923 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
924 std::string NewPrefix,
925 bool ShouldEmitImportsFiles,
926 std::string LinkedObjectsFile) {
927 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
928 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
929 AddStreamFn AddStream, NativeObjectCache Cache) {
930 return llvm::make_unique<WriteIndexesThinBackend>(
931 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
932 ShouldEmitImportsFiles, LinkedObjectsFile);
936 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
937 bool HasRegularLTO) {
938 if (ThinLTO.ModuleMap.empty())
939 return Error::success();
941 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
942 return Error::success();
944 // Collect for each module the list of function it defines (GUID ->
946 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
947 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
948 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
949 ModuleToDefinedGVSummaries);
950 // Create entries for any modules that didn't have any GV summaries
951 // (either they didn't have any GVs to start with, or we suppressed
952 // generation of the summaries because they e.g. had inline assembly
953 // uses that couldn't be promoted/renamed on export). This is so
954 // InProcessThinBackend::start can still launch a backend thread, which
955 // is passed the map of summaries for the module, without any special
956 // handling for this case.
957 for (auto &Mod : ThinLTO.ModuleMap)
958 if (!ModuleToDefinedGVSummaries.count(Mod.first))
959 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
961 StringMap<FunctionImporter::ImportMapTy> ImportLists(
962 ThinLTO.ModuleMap.size());
963 StringMap<FunctionImporter::ExportSetTy> ExportLists(
964 ThinLTO.ModuleMap.size());
965 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
967 if (Conf.OptLevel > 0) {
968 // Compute "dead" symbols, we don't want to import/export these!
969 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
970 for (auto &Res : GlobalResolutions) {
971 if (Res.second.VisibleOutsideThinLTO &&
972 // IRName will be defined if we have seen the prevailing copy of
973 // this value. If not, no need to preserve any ThinLTO copies.
974 !Res.second.IRName.empty())
975 GUIDPreservedSymbols.insert(GlobalValue::getGUID(
976 GlobalValue::dropLLVMManglingEscape(Res.second.IRName)));
980 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
982 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
983 ImportLists, ExportLists, &DeadSymbols);
985 std::set<GlobalValue::GUID> ExportedGUIDs;
986 for (auto &Res : GlobalResolutions) {
987 // First check if the symbol was flagged as having external references.
988 if (Res.second.Partition != GlobalResolution::External)
990 // IRName will be defined if we have seen the prevailing copy of
991 // this value. If not, no need to mark as exported from a ThinLTO
992 // partition (and we can't get the GUID).
993 if (Res.second.IRName.empty())
995 auto GUID = GlobalValue::getGUID(
996 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
997 // Mark exported unless index-based analysis determined it to be dead.
998 if (!DeadSymbols.count(GUID))
999 ExportedGUIDs.insert(GUID);
1002 auto isPrevailing = [&](GlobalValue::GUID GUID,
1003 const GlobalValueSummary *S) {
1004 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1006 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1007 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1008 return (ExportList != ExportLists.end() &&
1009 ExportList->second.count(GUID)) ||
1010 ExportedGUIDs.count(GUID);
1012 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1014 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1015 GlobalValue::GUID GUID,
1016 GlobalValue::LinkageTypes NewLinkage) {
1017 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1020 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1024 std::unique_ptr<ThinBackendProc> BackendProc =
1025 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1028 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1029 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1030 // are reserved for parallel code generation partitions.
1032 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
1033 for (auto &Mod : ThinLTO.ModuleMap) {
1034 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1035 ExportLists[Mod.first],
1036 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1041 return BackendProc->wait();
1044 Expected<std::unique_ptr<tool_output_file>>
1045 lto::setupOptimizationRemarks(LLVMContext &Context,
1046 StringRef LTORemarksFilename,
1047 bool LTOPassRemarksWithHotness, int Count) {
1048 if (LTORemarksFilename.empty())
1051 std::string Filename = LTORemarksFilename;
1053 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1056 auto DiagnosticFile =
1057 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1059 return errorCodeToError(EC);
1060 Context.setDiagnosticsOutputFile(
1061 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1062 if (LTOPassRemarksWithHotness)
1063 Context.setDiagnosticHotnessRequested(true);
1064 DiagnosticFile->keep();
1065 return std::move(DiagnosticFile);