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)
118 AddUnsigned(*Conf.RelocModel);
121 AddUnsigned(Conf.CodeModel);
122 AddUnsigned(Conf.CGOptLevel);
123 AddUnsigned(Conf.CGFileType);
124 AddUnsigned(Conf.OptLevel);
125 AddString(Conf.OptPipeline);
126 AddString(Conf.AAPipeline);
127 AddString(Conf.OverrideTriple);
128 AddString(Conf.DefaultTriple);
130 // Include the hash for the current module
131 auto ModHash = Index.getModuleHash(ModuleID);
132 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
133 for (auto F : ExportList)
134 // The export list can impact the internalization, be conservative here
135 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
137 // Include the hash for every module we import functions from. The set of
138 // imported symbols for each module may affect code generation and is
139 // sensitive to link order, so include that as well.
140 for (auto &Entry : ImportList) {
141 auto ModHash = Index.getModuleHash(Entry.first());
142 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
144 AddUint64(Entry.second.size());
145 for (auto &Fn : Entry.second)
149 // Include the hash for the resolved ODR.
150 for (auto &Entry : ResolvedODR) {
151 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
152 sizeof(GlobalValue::GUID)));
153 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
154 sizeof(GlobalValue::LinkageTypes)));
157 std::set<GlobalValue::GUID> UsedTypeIds;
159 auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
160 auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
163 for (auto &TT : FS->type_tests())
164 UsedTypeIds.insert(TT);
165 for (auto &TT : FS->type_test_assume_vcalls())
166 UsedTypeIds.insert(TT.GUID);
167 for (auto &TT : FS->type_checked_load_vcalls())
168 UsedTypeIds.insert(TT.GUID);
169 for (auto &TT : FS->type_test_assume_const_vcalls())
170 UsedTypeIds.insert(TT.VFunc.GUID);
171 for (auto &TT : FS->type_checked_load_const_vcalls())
172 UsedTypeIds.insert(TT.VFunc.GUID);
175 // Include the hash for the linkage type to reflect internalization and weak
176 // resolution, and collect any used type identifier resolutions.
177 for (auto &GS : DefinedGlobals) {
178 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
180 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
181 AddUsedTypeIds(GS.second);
184 // Imported functions may introduce new uses of type identifier resolutions,
185 // so we need to collect their used resolutions as well.
186 for (auto &ImpM : ImportList)
187 for (auto &ImpF : ImpM.second)
188 AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
190 auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
193 AddUnsigned(S.TTRes.TheKind);
194 AddUnsigned(S.TTRes.SizeM1BitWidth);
196 AddUint64(S.WPDRes.size());
197 for (auto &WPD : S.WPDRes) {
198 AddUnsigned(WPD.first);
199 AddUnsigned(WPD.second.TheKind);
200 AddString(WPD.second.SingleImplName);
202 AddUint64(WPD.second.ResByArg.size());
203 for (auto &ByArg : WPD.second.ResByArg) {
204 AddUint64(ByArg.first.size());
205 for (uint64_t Arg : ByArg.first)
207 AddUnsigned(ByArg.second.TheKind);
208 AddUint64(ByArg.second.Info);
213 // Include the hash for all type identifiers used by this module.
214 for (GlobalValue::GUID TId : UsedTypeIds) {
215 auto SummariesI = TypeIdSummariesByGuid.find(TId);
216 if (SummariesI != TypeIdSummariesByGuid.end())
217 for (auto *Summary : SummariesI->second)
218 AddTypeIdSummary(Summary->first, Summary->second);
221 if (!Conf.SampleProfile.empty()) {
222 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
224 Hasher.update(FileOrErr.get()->getBuffer());
227 Key = toHex(Hasher.result());
230 static void thinLTOResolveWeakForLinkerGUID(
231 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
232 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
233 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
235 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
237 for (auto &S : GVSummaryList) {
238 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
239 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
241 // We need to emit only one of these. The prevailing module will keep it,
242 // but turned into a weak, while the others will drop it when possible.
243 // This is both a compile-time optimization and a correctness
244 // transformation. This is necessary for correctness when we have exported
245 // a reference - we need to convert the linkonce to weak to
246 // ensure a copy is kept to satisfy the exported reference.
247 // FIXME: We may want to split the compile time and correctness
248 // aspects into separate routines.
249 if (isPrevailing(GUID, S.get())) {
250 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
251 S->setLinkage(GlobalValue::getWeakLinkage(
252 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
254 // Alias and aliasee can't be turned into available_externally.
255 else if (!isa<AliasSummary>(S.get()) &&
256 !GlobalInvolvedWithAlias.count(S.get()))
257 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
258 if (S->linkage() != OriginalLinkage)
259 recordNewLinkage(S->modulePath(), GUID, S->linkage());
263 // Resolve Weak and LinkOnce values in the \p Index.
265 // We'd like to drop these functions if they are no longer referenced in the
266 // current module. However there is a chance that another module is still
267 // referencing them because of the import. We make sure we always emit at least
269 void llvm::thinLTOResolveWeakForLinkerInIndex(
270 ModuleSummaryIndex &Index,
271 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
273 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
275 // We won't optimize the globals that are referenced by an alias for now
276 // Ideally we should turn the alias into a global and duplicate the definition
278 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
279 for (auto &I : Index)
280 for (auto &S : I.second.SummaryList)
281 if (auto AS = dyn_cast<AliasSummary>(S.get()))
282 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
284 for (auto &I : Index)
285 thinLTOResolveWeakForLinkerGUID(I.second.SummaryList, I.first,
286 GlobalInvolvedWithAlias, isPrevailing,
290 static void thinLTOInternalizeAndPromoteGUID(
291 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
292 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
293 for (auto &S : GVSummaryList) {
294 if (isExported(S->modulePath(), GUID)) {
295 if (GlobalValue::isLocalLinkage(S->linkage()))
296 S->setLinkage(GlobalValue::ExternalLinkage);
297 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
298 S->setLinkage(GlobalValue::InternalLinkage);
302 // Update the linkages in the given \p Index to mark exported values
303 // as external and non-exported values as internal.
304 void llvm::thinLTOInternalizeAndPromoteInIndex(
305 ModuleSummaryIndex &Index,
306 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
307 for (auto &I : Index)
308 thinLTOInternalizeAndPromoteGUID(I.second.SummaryList, I.first, isExported);
311 // Requires a destructor for std::vector<InputModule>.
312 InputFile::~InputFile() = default;
314 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
315 std::unique_ptr<InputFile> File(new InputFile);
317 ErrorOr<MemoryBufferRef> BCOrErr =
318 IRObjectFile::findBitcodeInMemBuffer(Object);
320 return errorCodeToError(BCOrErr.getError());
322 Expected<std::vector<BitcodeModule>> BMsOrErr =
323 getBitcodeModuleList(*BCOrErr);
325 return BMsOrErr.takeError();
327 if (BMsOrErr->empty())
328 return make_error<StringError>("Bitcode file does not contain any modules",
329 inconvertibleErrorCode());
331 File->Mods = *BMsOrErr;
334 std::vector<Module *> Mods;
335 std::vector<std::unique_ptr<Module>> OwnedMods;
336 for (auto BM : *BMsOrErr) {
337 Expected<std::unique_ptr<Module>> MOrErr =
338 BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
339 /*IsImporting*/ false);
341 return MOrErr.takeError();
343 if ((*MOrErr)->getDataLayoutStr().empty())
344 return make_error<StringError>("input module has no datalayout",
345 inconvertibleErrorCode());
347 Mods.push_back(MOrErr->get());
348 OwnedMods.push_back(std::move(*MOrErr));
351 SmallVector<char, 0> Symtab;
352 if (Error E = irsymtab::build(Mods, Symtab, File->Strtab))
355 irsymtab::Reader R({Symtab.data(), Symtab.size()},
356 {File->Strtab.data(), File->Strtab.size()});
357 File->TargetTriple = R.getTargetTriple();
358 File->SourceFileName = R.getSourceFileName();
359 File->COFFLinkerOpts = R.getCOFFLinkerOpts();
360 File->ComdatTable = R.getComdatTable();
362 for (unsigned I = 0; I != Mods.size(); ++I) {
363 size_t Begin = File->Symbols.size();
364 for (const irsymtab::Reader::SymbolRef &Sym : R.module_symbols(I))
365 // Skip symbols that are irrelevant to LTO. Note that this condition needs
366 // to match the one in Skip() in LTO::addRegularLTO().
367 if (Sym.isGlobal() && !Sym.isFormatSpecific())
368 File->Symbols.push_back(Sym);
369 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
372 return std::move(File);
375 StringRef InputFile::getName() const {
376 return Mods[0].getModuleIdentifier();
379 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
381 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
384 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
387 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
390 LTO::LTO(Config Conf, ThinBackend Backend,
391 unsigned ParallelCodeGenParallelismLevel)
392 : Conf(std::move(Conf)),
393 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
394 ThinLTO(std::move(Backend)) {}
396 // Requires a destructor for MapVector<BitcodeModule>.
397 LTO::~LTO() = default;
399 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
400 void LTO::addSymbolToGlobalRes(const InputFile::Symbol &Sym,
401 SymbolResolution Res, unsigned Partition) {
402 auto &GlobalRes = GlobalResolutions[Sym.getName()];
403 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
405 GlobalRes.IRName = Sym.getIRName();
407 // Set the partition to external if we know it is used elsewhere, e.g.
408 // it is visible to a regular object, is referenced from llvm.compiler_used,
409 // or was already recorded as being referenced from a different partition.
410 if (Res.VisibleToRegularObj || Sym.isUsed() ||
411 (GlobalRes.Partition != GlobalResolution::Unknown &&
412 GlobalRes.Partition != Partition)) {
413 GlobalRes.Partition = GlobalResolution::External;
415 // First recorded reference, save the current partition.
416 GlobalRes.Partition = Partition;
418 // Flag as visible outside of ThinLTO if visible from a regular object or
419 // if this is a reference in the regular LTO partition.
420 GlobalRes.VisibleOutsideThinLTO |=
421 (Res.VisibleToRegularObj || Sym.isUsed() ||
422 Partition == GlobalResolution::RegularLTO);
425 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
426 ArrayRef<SymbolResolution> Res) {
427 StringRef Path = Input->getName();
429 auto ResI = Res.begin();
430 for (const InputFile::Symbol &Sym : Input->symbols()) {
431 assert(ResI != Res.end());
432 SymbolResolution Res = *ResI++;
434 OS << "-r=" << Path << ',' << Sym.getName() << ',';
437 if (Res.FinalDefinitionInLinkageUnit)
439 if (Res.VisibleToRegularObj)
444 assert(ResI == Res.end());
447 Error LTO::add(std::unique_ptr<InputFile> Input,
448 ArrayRef<SymbolResolution> Res) {
449 assert(!CalledGetMaxTasks);
451 if (Conf.ResolutionFile)
452 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
454 const SymbolResolution *ResI = Res.begin();
455 for (unsigned I = 0; I != Input->Mods.size(); ++I)
456 if (Error Err = addModule(*Input, I, ResI, Res.end()))
459 assert(ResI == Res.end());
460 return Error::success();
463 Error LTO::addModule(InputFile &Input, unsigned ModI,
464 const SymbolResolution *&ResI,
465 const SymbolResolution *ResE) {
466 Expected<bool> HasThinLTOSummary = Input.Mods[ModI].hasSummary();
467 if (!HasThinLTOSummary)
468 return HasThinLTOSummary.takeError();
470 auto ModSyms = Input.module_symbols(ModI);
471 if (*HasThinLTOSummary)
472 return addThinLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
474 return addRegularLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
477 // Add a regular LTO object to the link.
478 Error LTO::addRegularLTO(BitcodeModule BM,
479 ArrayRef<InputFile::Symbol> Syms,
480 const SymbolResolution *&ResI,
481 const SymbolResolution *ResE) {
482 if (!RegularLTO.CombinedModule) {
483 RegularLTO.CombinedModule =
484 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
485 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
487 Expected<std::unique_ptr<Module>> MOrErr =
488 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
489 /*IsImporting*/ false);
491 return MOrErr.takeError();
493 Module &M = **MOrErr;
494 if (Error Err = M.materializeMetadata())
498 ModuleSymbolTable SymTab;
499 SymTab.addModule(&M);
501 std::vector<GlobalValue *> Keep;
503 for (GlobalVariable &GV : M.globals())
504 if (GV.hasAppendingLinkage())
507 DenseSet<GlobalObject *> AliasedGlobals;
508 for (auto &GA : M.aliases())
509 if (GlobalObject *GO = GA.getBaseObject())
510 AliasedGlobals.insert(GO);
512 // In this function we need IR GlobalValues matching the symbols in Syms
513 // (which is not backed by a module), so we need to enumerate them in the same
514 // order. The symbol enumeration order of a ModuleSymbolTable intentionally
515 // matches the order of an irsymtab, but when we read the irsymtab in
516 // InputFile::create we omit some symbols that are irrelevant to LTO. The
517 // Skip() function skips the same symbols from the module as InputFile does
518 // from the symbol table.
519 auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
521 while (MsymI != MsymE) {
522 auto Flags = SymTab.getSymbolFlags(*MsymI);
523 if ((Flags & object::BasicSymbolRef::SF_Global) &&
524 !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
531 for (const InputFile::Symbol &Sym : Syms) {
532 assert(ResI != ResE);
533 SymbolResolution Res = *ResI++;
534 addSymbolToGlobalRes(Sym, Res, 0);
536 assert(MsymI != MsymE);
537 ModuleSymbolTable::Symbol Msym = *MsymI++;
540 if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
541 if (Res.Prevailing) {
542 if (Sym.isUndefined())
545 GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
546 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
547 GV->setLinkage(GlobalValue::getWeakLinkage(
548 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
549 } else if (isa<GlobalObject>(GV) &&
550 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
551 GV->hasAvailableExternallyLinkage()) &&
552 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
553 // Either of the above three types of linkage indicates that the
554 // chosen prevailing symbol will have the same semantics as this copy of
555 // the symbol, so we can link it with available_externally linkage. We
556 // only need to do this if the symbol is undefined.
557 GlobalValue *CombinedGV =
558 RegularLTO.CombinedModule->getNamedValue(GV->getName());
559 if (!CombinedGV || CombinedGV->isDeclaration()) {
561 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
562 cast<GlobalObject>(GV)->setComdat(nullptr);
566 // Common resolution: collect the maximum size/alignment over all commons.
567 // We also record if we see an instance of a common as prevailing, so that
568 // if none is prevailing we can ignore it later.
569 if (Sym.isCommon()) {
570 // FIXME: We should figure out what to do about commons defined by asm.
571 // For now they aren't reported correctly by ModuleSymbolTable.
572 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
573 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
574 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
575 CommonRes.Prevailing |= Res.Prevailing;
578 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
580 assert(MsymI == MsymE);
582 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
583 [](GlobalValue &, IRMover::ValueAdder) {},
584 /* IsPerformingImport */ false);
587 // Add a ThinLTO object to the link.
588 Error LTO::addThinLTO(BitcodeModule BM,
589 ArrayRef<InputFile::Symbol> Syms,
590 const SymbolResolution *&ResI,
591 const SymbolResolution *ResE) {
593 BM.readSummary(ThinLTO.CombinedIndex, ThinLTO.ModuleMap.size()))
596 for (const InputFile::Symbol &Sym : Syms) {
597 assert(ResI != ResE);
598 SymbolResolution Res = *ResI++;
599 addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
601 if (Res.Prevailing) {
602 if (!Sym.getIRName().empty()) {
603 auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
604 Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
605 ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
610 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
611 return make_error<StringError>(
612 "Expected at most one ThinLTO module per bitcode file",
613 inconvertibleErrorCode());
615 return Error::success();
618 unsigned LTO::getMaxTasks() const {
619 CalledGetMaxTasks = true;
620 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
623 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
624 // Save the status of having a regularLTO combined module, as
625 // this is needed for generating the ThinLTO Task ID, and
626 // the CombinedModule will be moved at the end of runRegularLTO.
627 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
628 // Invoke regular LTO if there was a regular LTO module to start with.
630 if (auto E = runRegularLTO(AddStream))
632 return runThinLTO(AddStream, Cache, HasRegularLTO);
635 Error LTO::runRegularLTO(AddStreamFn AddStream) {
636 // Make sure commons have the right size/alignment: we kept the largest from
637 // all the prevailing when adding the inputs, and we apply it here.
638 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
639 for (auto &I : RegularLTO.Commons) {
640 if (!I.second.Prevailing)
641 // Don't do anything if no instance of this common was prevailing.
643 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
644 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
645 // Don't create a new global if the type is already correct, just make
646 // sure the alignment is correct.
647 OldGV->setAlignment(I.second.Align);
651 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
652 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
653 GlobalValue::CommonLinkage,
654 ConstantAggregateZero::get(Ty), "");
655 GV->setAlignment(I.second.Align);
657 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
659 OldGV->eraseFromParent();
661 GV->setName(I.first);
665 if (Conf.PreOptModuleHook &&
666 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
667 return Error::success();
669 if (!Conf.CodeGenOnly) {
670 for (const auto &R : GlobalResolutions) {
671 if (R.second.IRName.empty())
673 if (R.second.Partition != 0 &&
674 R.second.Partition != GlobalResolution::External)
678 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
679 // Ignore symbols defined in other partitions.
680 if (!GV || GV->hasLocalLinkage())
682 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
683 : GlobalValue::UnnamedAddr::None);
684 if (R.second.Partition == 0)
685 GV->setLinkage(GlobalValue::InternalLinkage);
688 if (Conf.PostInternalizeModuleHook &&
689 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
690 return Error::success();
692 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
693 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
696 /// This class defines the interface to the ThinLTO backend.
697 class lto::ThinBackendProc {
700 ModuleSummaryIndex &CombinedIndex;
701 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
704 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
705 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
706 : Conf(Conf), CombinedIndex(CombinedIndex),
707 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
709 virtual ~ThinBackendProc() {}
711 unsigned Task, BitcodeModule BM,
712 const FunctionImporter::ImportMapTy &ImportList,
713 const FunctionImporter::ExportSetTy &ExportList,
714 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
715 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
716 virtual Error wait() = 0;
720 class InProcessThinBackend : public ThinBackendProc {
721 ThreadPool BackendThreadPool;
722 AddStreamFn AddStream;
723 NativeObjectCache Cache;
724 TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
730 InProcessThinBackend(
731 Config &Conf, ModuleSummaryIndex &CombinedIndex,
732 unsigned ThinLTOParallelismLevel,
733 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
734 AddStreamFn AddStream, NativeObjectCache Cache)
735 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
736 BackendThreadPool(ThinLTOParallelismLevel),
737 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
738 // Create a mapping from type identifier GUIDs to type identifier summaries.
739 // This allows backends to use the type identifier GUIDs stored in the
740 // function summaries to determine which type identifier summaries affect
741 // each function without needing to compute GUIDs in each backend.
742 for (auto &TId : CombinedIndex.typeIds())
743 TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
746 Error runThinLTOBackendThread(
747 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
748 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
749 const FunctionImporter::ImportMapTy &ImportList,
750 const FunctionImporter::ExportSetTy &ExportList,
751 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
752 const GVSummaryMapTy &DefinedGlobals,
753 MapVector<StringRef, BitcodeModule> &ModuleMap,
754 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
755 auto RunThinBackend = [&](AddStreamFn AddStream) {
756 LTOLLVMContext BackendContext(Conf);
757 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
759 return MOrErr.takeError();
761 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
762 ImportList, DefinedGlobals, ModuleMap);
765 auto ModuleID = BM.getModuleIdentifier();
767 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
768 all_of(CombinedIndex.getModuleHash(ModuleID),
769 [](uint32_t V) { return V == 0; }))
770 // Cache disabled or no entry for this module in the combined index or
772 return RunThinBackend(AddStream);
775 // The module may be cached, this helps handling it.
776 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
777 ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
778 if (AddStreamFn CacheAddStream = Cache(Task, Key))
779 return RunThinBackend(CacheAddStream);
781 return Error::success();
785 unsigned Task, BitcodeModule BM,
786 const FunctionImporter::ImportMapTy &ImportList,
787 const FunctionImporter::ExportSetTy &ExportList,
788 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
789 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
790 StringRef ModulePath = BM.getModuleIdentifier();
791 assert(ModuleToDefinedGVSummaries.count(ModulePath));
792 const GVSummaryMapTy &DefinedGlobals =
793 ModuleToDefinedGVSummaries.find(ModulePath)->second;
794 BackendThreadPool.async(
795 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
796 const FunctionImporter::ImportMapTy &ImportList,
797 const FunctionImporter::ExportSetTy &ExportList,
798 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
800 const GVSummaryMapTy &DefinedGlobals,
801 MapVector<StringRef, BitcodeModule> &ModuleMap,
802 const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
803 Error E = runThinLTOBackendThread(
804 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
805 ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
807 std::unique_lock<std::mutex> L(ErrMu);
809 Err = joinErrors(std::move(*Err), std::move(E));
814 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
815 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
816 std::ref(TypeIdSummariesByGuid));
817 return Error::success();
820 Error wait() override {
821 BackendThreadPool.wait();
823 return std::move(*Err);
825 return Error::success();
828 } // end anonymous namespace
830 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
831 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
832 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
833 AddStreamFn AddStream, NativeObjectCache Cache) {
834 return llvm::make_unique<InProcessThinBackend>(
835 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
840 // Given the original \p Path to an output file, replace any path
841 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
842 // resulting directory if it does not yet exist.
843 std::string lto::getThinLTOOutputFile(const std::string &Path,
844 const std::string &OldPrefix,
845 const std::string &NewPrefix) {
846 if (OldPrefix.empty() && NewPrefix.empty())
848 SmallString<128> NewPath(Path);
849 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
850 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
851 if (!ParentPath.empty()) {
852 // Make sure the new directory exists, creating it if necessary.
853 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
854 llvm::errs() << "warning: could not create directory '" << ParentPath
855 << "': " << EC.message() << '\n';
857 return NewPath.str();
861 class WriteIndexesThinBackend : public ThinBackendProc {
862 std::string OldPrefix, NewPrefix;
863 bool ShouldEmitImportsFiles;
865 std::string LinkedObjectsFileName;
866 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
869 WriteIndexesThinBackend(
870 Config &Conf, ModuleSummaryIndex &CombinedIndex,
871 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
872 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
873 std::string LinkedObjectsFileName)
874 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
875 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
876 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
877 LinkedObjectsFileName(LinkedObjectsFileName) {}
880 unsigned Task, BitcodeModule BM,
881 const FunctionImporter::ImportMapTy &ImportList,
882 const FunctionImporter::ExportSetTy &ExportList,
883 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
884 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
885 StringRef ModulePath = BM.getModuleIdentifier();
886 std::string NewModulePath =
887 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
890 if (!LinkedObjectsFileName.empty()) {
891 if (!LinkedObjectsFile) {
892 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
893 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
895 return errorCodeToError(EC);
897 *LinkedObjectsFile << NewModulePath << '\n';
900 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
901 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
902 ImportList, ModuleToSummariesForIndex);
904 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
905 sys::fs::OpenFlags::F_None);
907 return errorCodeToError(EC);
908 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
910 if (ShouldEmitImportsFiles)
911 return errorCodeToError(
912 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
913 return Error::success();
916 Error wait() override { return Error::success(); }
918 } // end anonymous namespace
920 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
921 std::string NewPrefix,
922 bool ShouldEmitImportsFiles,
923 std::string LinkedObjectsFile) {
924 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
925 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
926 AddStreamFn AddStream, NativeObjectCache Cache) {
927 return llvm::make_unique<WriteIndexesThinBackend>(
928 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
929 ShouldEmitImportsFiles, LinkedObjectsFile);
933 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
934 bool HasRegularLTO) {
935 if (ThinLTO.ModuleMap.empty())
936 return Error::success();
938 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
939 return Error::success();
941 // Collect for each module the list of function it defines (GUID ->
943 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
944 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
945 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
946 ModuleToDefinedGVSummaries);
947 // Create entries for any modules that didn't have any GV summaries
948 // (either they didn't have any GVs to start with, or we suppressed
949 // generation of the summaries because they e.g. had inline assembly
950 // uses that couldn't be promoted/renamed on export). This is so
951 // InProcessThinBackend::start can still launch a backend thread, which
952 // is passed the map of summaries for the module, without any special
953 // handling for this case.
954 for (auto &Mod : ThinLTO.ModuleMap)
955 if (!ModuleToDefinedGVSummaries.count(Mod.first))
956 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
958 StringMap<FunctionImporter::ImportMapTy> ImportLists(
959 ThinLTO.ModuleMap.size());
960 StringMap<FunctionImporter::ExportSetTy> ExportLists(
961 ThinLTO.ModuleMap.size());
962 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
964 if (Conf.OptLevel > 0) {
965 // Compute "dead" symbols, we don't want to import/export these!
966 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
967 for (auto &Res : GlobalResolutions) {
968 if (Res.second.VisibleOutsideThinLTO &&
969 // IRName will be defined if we have seen the prevailing copy of
970 // this value. If not, no need to preserve any ThinLTO copies.
971 !Res.second.IRName.empty())
972 GUIDPreservedSymbols.insert(GlobalValue::getGUID(
973 GlobalValue::dropLLVMManglingEscape(Res.second.IRName)));
977 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
979 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
980 ImportLists, ExportLists, &DeadSymbols);
982 std::set<GlobalValue::GUID> ExportedGUIDs;
983 for (auto &Res : GlobalResolutions) {
984 // First check if the symbol was flagged as having external references.
985 if (Res.second.Partition != GlobalResolution::External)
987 // IRName will be defined if we have seen the prevailing copy of
988 // this value. If not, no need to mark as exported from a ThinLTO
989 // partition (and we can't get the GUID).
990 if (Res.second.IRName.empty())
992 auto GUID = GlobalValue::getGUID(
993 GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
994 // Mark exported unless index-based analysis determined it to be dead.
995 if (!DeadSymbols.count(GUID))
996 ExportedGUIDs.insert(GUID);
999 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1000 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1001 return (ExportList != ExportLists.end() &&
1002 ExportList->second.count(GUID)) ||
1003 ExportedGUIDs.count(GUID);
1005 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1008 auto isPrevailing = [&](GlobalValue::GUID GUID,
1009 const GlobalValueSummary *S) {
1010 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1012 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1013 GlobalValue::GUID GUID,
1014 GlobalValue::LinkageTypes NewLinkage) {
1015 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1017 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1020 std::unique_ptr<ThinBackendProc> BackendProc =
1021 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1024 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1025 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1026 // are reserved for parallel code generation partitions.
1028 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
1029 for (auto &Mod : ThinLTO.ModuleMap) {
1030 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1031 ExportLists[Mod.first],
1032 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1037 return BackendProc->wait();
1040 Expected<std::unique_ptr<tool_output_file>>
1041 lto::setupOptimizationRemarks(LLVMContext &Context,
1042 StringRef LTORemarksFilename,
1043 bool LTOPassRemarksWithHotness, int Count) {
1044 if (LTORemarksFilename.empty())
1047 std::string Filename = LTORemarksFilename;
1049 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1052 auto DiagnosticFile =
1053 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1055 return errorCodeToError(EC);
1056 Context.setDiagnosticsOutputFile(
1057 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1058 if (LTOPassRemarksWithHotness)
1059 Context.setDiagnosticHotnessRequested(true);
1060 DiagnosticFile->keep();
1061 return std::move(DiagnosticFile);