20 #include "llvm/Config/llvm-config.h" 42 #include "llvm/Support/VCSRevision.h" 58 #define DEBUG_TYPE "lto" 62 cl::desc(
"Dump the SCCs in the ThinLTO index's callgraph"));
67 cl::desc(
"Enable global value internalization in LTO"));
76 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
78 const std::set<GlobalValue::GUID> &CfiFunctionDefs,
79 const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
87 Hasher.
update(LLVM_VERSION_STRING);
89 Hasher.
update(LLVM_REVISION);
97 auto AddUnsigned = [&](
unsigned I) {
105 auto AddUint64 = [&](uint64_t
I) {
126 for (
auto &A : Conf.
MAttrs)
150 for (
const auto &
VI : ExportList) {
151 auto GUID =
VI.getGUID();
159 for (
auto &
Entry : ImportList) {
163 AddUint64(
Entry.second.size());
164 for (
auto &Fn :
Entry.second)
169 for (
auto &
Entry : ResolvedODR) {
178 std::set<GlobalValue::GUID> UsedCfiDefs;
179 std::set<GlobalValue::GUID> UsedCfiDecls;
182 std::set<GlobalValue::GUID> UsedTypeIds;
185 if (CfiFunctionDefs.count(ValueGUID))
186 UsedCfiDefs.insert(ValueGUID);
187 if (CfiFunctionDecls.count(ValueGUID))
188 UsedCfiDecls.insert(ValueGUID);
193 AddUnsigned(
GS->isLive());
194 AddUnsigned(
GS->canAutoHide());
196 AddUnsigned(
VI.isDSOLocal());
197 AddUsedCfiGlobal(
VI.getGUID());
199 if (
auto *GVS = dyn_cast<GlobalVarSummary>(
GS)) {
200 AddUnsigned(GVS->maybeReadOnly());
201 AddUnsigned(GVS->maybeWriteOnly());
203 if (
auto *
FS = dyn_cast<FunctionSummary>(
GS)) {
204 for (
auto &
TT :
FS->type_tests())
205 UsedTypeIds.insert(
TT);
206 for (
auto &
TT :
FS->type_test_assume_vcalls())
207 UsedTypeIds.insert(
TT.GUID);
208 for (
auto &
TT :
FS->type_checked_load_vcalls())
209 UsedTypeIds.insert(
TT.GUID);
210 for (
auto &
TT :
FS->type_test_assume_const_vcalls())
211 UsedTypeIds.insert(
TT.VFunc.GUID);
212 for (
auto &
TT :
FS->type_checked_load_const_vcalls())
213 UsedTypeIds.insert(
TT.VFunc.GUID);
214 for (
auto &ET :
FS->calls()) {
215 AddUnsigned(ET.first.isDSOLocal());
216 AddUsedCfiGlobal(ET.first.getGUID());
223 for (
auto &
GS : DefinedGlobals) {
227 AddUsedCfiGlobal(
GS.first);
228 AddUsedThings(
GS.second);
233 for (
auto &ImpM : ImportList)
234 for (
auto &ImpF : ImpM.second) {
239 if (
auto *AS = dyn_cast_or_null<AliasSummary>(S))
240 AddUsedThings(AS->getBaseObject());
246 AddUnsigned(S.TTRes.TheKind);
247 AddUnsigned(S.TTRes.SizeM1BitWidth);
249 AddUint64(S.TTRes.AlignLog2);
250 AddUint64(S.TTRes.SizeM1);
251 AddUint64(S.TTRes.BitMask);
252 AddUint64(S.TTRes.InlineBits);
254 AddUint64(S.WPDRes.size());
255 for (
auto &WPD : S.WPDRes) {
256 AddUnsigned(WPD.first);
257 AddUnsigned(WPD.second.TheKind);
258 AddString(WPD.second.SingleImplName);
260 AddUint64(WPD.second.ResByArg.size());
261 for (
auto &ByArg : WPD.second.ResByArg) {
262 AddUint64(ByArg.first.size());
263 for (uint64_t
Arg : ByArg.first)
265 AddUnsigned(ByArg.second.TheKind);
266 AddUint64(ByArg.second.Info);
267 AddUnsigned(ByArg.second.Byte);
268 AddUnsigned(ByArg.second.Bit);
275 auto TidIter = Index.
typeIds().equal_range(TId);
276 for (
auto It = TidIter.first; It != TidIter.second; ++It)
277 AddTypeIdSummary(It->second.first, It->second.second);
280 AddUnsigned(UsedCfiDefs.size());
281 for (
auto &V : UsedCfiDefs)
284 AddUnsigned(UsedCfiDecls.size());
285 for (
auto &V : UsedCfiDecls)
291 Hasher.
update(FileOrErr.get()->getBuffer());
296 Hasher.
update(FileOrErr.get()->getBuffer());
326 if (isPrevailing(VI.
getGUID(), S.get())) {
344 else if (!isa<AliasSummary>(S.get()) &&
345 !GlobalInvolvedWithAlias.
count(S.get()))
347 if (S->linkage() != OriginalLinkage)
348 recordNewLinkage(S->modulePath(), VI.
getGUID(), S->linkage());
369 for (
auto &
I : Index)
370 for (
auto &S :
I.second.SummaryList)
371 if (
auto AS = dyn_cast<AliasSummary>(S.get()))
372 GlobalInvolvedWithAlias.
insert(&AS->getAliasee());
374 for (
auto &
I : Index)
376 isPrevailing, recordNewLinkage,
377 GUIDPreservedSymbols);
381 if (
auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->
getBaseObject()))
382 return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
393 if (isExported(S->modulePath(),
VI)) {
401 isPrevailing(VI.
getGUID(), S.get())) &&
423 for (
auto &
I : Index)
438 File->TargetTriple = FOrErr->TheReader.getTargetTriple();
439 File->SourceFileName = FOrErr->TheReader.getSourceFileName();
440 File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
441 File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
442 File->ComdatTable = FOrErr->TheReader.getComdatTable();
444 for (
unsigned I = 0;
I != FOrErr->Mods.size(); ++
I) {
445 size_t Begin = File->Symbols.size();
447 FOrErr->TheReader.module_symbols(
I))
450 if (Sym.isGlobal() && !Sym.isFormatSpecific())
451 File->Symbols.push_back(Sym);
452 File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
455 File->Mods = FOrErr->Mods;
456 File->Strtab = std::move(FOrErr->Strtab);
457 return std::move(File);
461 return Mods[0].getModuleIdentifier();
465 assert(Mods.size() == 1 &&
"Expect only one bitcode module");
469 LTO::RegularLTOState::RegularLTOState(
unsigned ParallelCodeGenParallelismLevel,
471 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
472 Ctx(Conf), CombinedModule(std::make_unique<Module>(
"ld-temp.o", Ctx)),
473 Mover(std::make_unique<IRMover>(*CombinedModule)) {}
475 LTO::ThinLTOState::ThinLTOState(
ThinBackend Backend)
476 : Backend(Backend), CombinedIndex(
false) {
483 unsigned ParallelCodeGenParallelismLevel)
484 : Conf(
std::move(Conf)),
485 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
486 ThinLTO(
std::move(Backend)) {}
495 unsigned Partition,
bool InSummary) {
496 auto *ResI = Res.
begin();
497 auto *ResE = Res.
end();
504 Triple TT(RegularLTO.CombinedModule->getTargetTriple());
508 if (
TT.isOSBinFormatCOFF() && Name.
startswith(
"__imp_"))
509 Name = Name.
substr(strlen(
"__imp_"));
510 auto &GlobalRes = GlobalResolutions[
Name];
511 GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
513 assert(!GlobalRes.Prevailing &&
514 "Multiple prevailing defs are not allowed");
515 GlobalRes.Prevailing =
true;
516 GlobalRes.IRName = Sym.getIRName();
517 }
else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
524 GlobalRes.IRName = Sym.getIRName();
533 GlobalRes.Partition != Partition)) {
534 GlobalRes.Partition = GlobalResolution::External;
537 GlobalRes.Partition = Partition;
541 GlobalRes.VisibleOutsideSummary |=
550 auto ResI = Res.
begin();
555 OS <<
"-r=" << Path <<
',' << Sym.getName() <<
',';
558 if (Res.FinalDefinitionInLinkageUnit)
560 if (Res.VisibleToRegularObj)
562 if (Res.LinkerRedefined)
572 assert(!CalledGetMaxTasks);
577 if (RegularLTO.CombinedModule->getTargetTriple().empty())
578 RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
581 for (
unsigned I = 0;
I != Input->Mods.size(); ++
I)
582 if (
Error Err = addModule(*Input,
I, ResI, Res.
end()))
596 if (EnableSplitLTOUnit.
hasValue()) {
600 if (EnableSplitLTOUnit.
getValue() != LTOInfo->EnableSplitLTOUnit)
601 ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
603 EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
606 auto ModSyms = Input.module_symbols(ModI);
607 addModuleToGlobalRes(ModSyms, {ResI, ResE},
608 LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
609 LTOInfo->HasSummary);
611 if (LTOInfo->IsThinLTO)
612 return addThinLTO(BM, ModSyms, ResI, ResE);
615 addRegularLTO(BM, ModSyms, ResI, ResE);
619 if (!LTOInfo->HasSummary)
620 return linkRegularLTO(std::move(*ModOrErr),
false);
626 RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
642 std::set<const Comdat *> &NonPrevailingComdats) {
647 if (!NonPrevailingComdats.count(C))
656 if (
auto GO = dyn_cast<GlobalObject>(&GV))
657 GO->setComdat(
nullptr);
667 RegularLTOState::AddedModule
Mod;
674 Mod.M = std::move(*MOrErr);
677 return std::move(Err);
684 if (GV.hasAppendingLinkage())
685 Mod.Keep.push_back(&GV);
690 AliasedGlobals.
insert(GO);
699 auto MsymI = SymTab.
symbols().begin(), MsymE = SymTab.
symbols().end();
701 while (MsymI != MsymE) {
711 std::set<const Comdat *> NonPrevailingComdats;
722 if (Sym.isUndefined())
724 Mod.Keep.push_back(GV);
735 }
else if (isa<GlobalObject>(GV) &&
736 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
737 GV->hasAvailableExternallyLinkage()) &&
738 !AliasedGlobals.
count(cast<GlobalObject>(GV))) {
744 Mod.Keep.push_back(GV);
747 NonPrevailingComdats.insert(GV->getComdat());
748 cast<GlobalObject>(GV)->setComdat(
nullptr);
753 GV->setDSOLocal(
true);
754 if (GV->hasDLLImportStorageClass())
756 DefaultStorageClass);
762 if (Sym.isCommon()) {
765 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
766 CommonRes.Size =
std::max(CommonRes.Size, Sym.getCommonSize());
777 return std::move(Mod);
780 Error LTO::linkRegularLTO(RegularLTOState::AddedModule
Mod,
781 bool LivenessFromIndex) {
782 std::vector<GlobalValue *> Keep;
784 if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->
getGUID()))
795 RegularLTO.CombinedModule->getNamedValue(GV->
getName());
802 return RegularLTO.Mover->move(std::move(Mod.M), Keep,
813 ThinLTO.ModuleMap.size()))
820 if (!Sym.getIRName().empty()) {
831 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(
839 if (
auto S = ThinLTO.CombinedIndex.findSummaryInModule(
841 S->setDSOLocal(
true);
847 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
848 return make_error<StringError>(
849 "Expected at most one ThinLTO module per bitcode file",
856 CalledGetMaxTasks =
true;
857 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
862 Error LTO::checkPartiallySplit() {
863 if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
866 Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
868 Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
873 if ((TypeTestFunc && !TypeTestFunc->
use_empty()) ||
874 (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->
use_empty()))
875 return make_error<StringError>(
876 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
881 for (
auto &
P : ThinLTO.CombinedIndex) {
882 for (
auto &S :
P.second.SummaryList) {
886 if (!
FS->type_test_assume_vcalls().empty() ||
887 !
FS->type_checked_load_vcalls().empty() ||
888 !
FS->type_test_assume_const_vcalls().empty() ||
889 !
FS->type_checked_load_const_vcalls().empty() ||
890 !
FS->type_tests().empty())
891 return make_error<StringError>(
892 "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
903 for (
auto &Res : GlobalResolutions) {
906 if (Res.second.IRName.
empty())
912 if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
913 GUIDPreservedSymbols.
insert(GUID);
915 GUIDPrevailingResolutions[GUID] =
920 auto It = GUIDPrevailingResolutions.
find(
G);
921 if (It == GUIDPrevailingResolutions.
end())
931 return StatsFileOrErr.takeError();
932 std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
936 for (
auto &M : RegularLTO.ModsWithSummaries)
937 if (
Error Err = linkRegularLTO(std::move(M),
942 if (
Error Err = checkPartiallySplit())
945 Error Result = runRegularLTO(AddStream);
947 Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
958 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
959 for (
auto &
I : RegularLTO.Commons) {
960 if (!
I.second.Prevailing)
963 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(
I.first);
972 auto *GV =
new GlobalVariable(*RegularLTO.CombinedModule, Ty,
false,
975 GV->setAlignment(
I.second.Align);
981 GV->setName(
I.first);
990 for (
const auto &R : GlobalResolutions) {
991 if (!R.second.isPrevailingIRSymbol())
993 if (R.second.Partition != 0 &&
994 R.second.Partition != GlobalResolution::External)
998 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1009 RegularLTO.CombinedModule->addModuleFlag(
Module::Error,
"LTOPostLink", 1);
1015 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1016 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
1020 #define HANDLE_LIBCALL(code, name) name, 1021 #include "llvm/IR/RuntimeLibcalls.def" 1022 #undef HANDLE_LIBCALL 1039 : Conf(Conf), CombinedIndex(CombinedIndex),
1040 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
1043 virtual Error start(
1047 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1049 virtual Error wait() = 0;
1057 std::set<GlobalValue::GUID> CfiFunctionDefs;
1058 std::set<GlobalValue::GUID> CfiFunctionDecls;
1064 InProcessThinBackend(
1066 unsigned ThinLTOParallelismLevel,
1070 BackendThreadPool(ThinLTOParallelismLevel),
1071 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
1073 CfiFunctionDefs.insert(
1076 CfiFunctionDecls.insert(
1080 Error runThinLTOBackendThread(
1085 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1088 auto RunThinBackend = [&](
AddStreamFn AddStream) {
1094 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1095 ImportList, DefinedGlobals, ModuleMap);
1102 [](
uint32_t V) {
return V == 0; }))
1105 return RunThinBackend(AddStream);
1110 ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1112 if (
AddStreamFn CacheAddStream = Cache(Task, Key))
1113 return RunThinBackend(CacheAddStream);
1122 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1125 assert(ModuleToDefinedGVSummaries.
count(ModulePath));
1127 ModuleToDefinedGVSummaries.
find(ModulePath)->second;
1128 BackendThreadPool.
async(
1132 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1136 Error E = runThinLTOBackendThread(
1137 AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1138 ResolvedODR, DefinedGlobals, ModuleMap);
1140 std::unique_lock<std::mutex> L(ErrMu);
1142 Err =
joinErrors(std::move(*Err), std::move(E));
1147 BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1148 std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1152 Error wait()
override {
1153 BackendThreadPool.
wait();
1155 return std::move(*Err);
1166 return std::make_unique<InProcessThinBackend>(
1167 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
1176 const std::string &OldPrefix,
1177 const std::string &NewPrefix) {
1178 if (OldPrefix.empty() && NewPrefix.empty())
1183 if (!ParentPath.
empty()) {
1186 llvm::errs() <<
"warning: could not create directory '" << ParentPath
1187 <<
"': " << EC.message() <<
'\n';
1189 return NewPath.
str();
1194 std::string OldPrefix, NewPrefix;
1195 bool ShouldEmitImportsFiles;
1200 WriteIndexesThinBackend(
1203 std::string OldPrefix, std::string NewPrefix,
bool ShouldEmitImportsFiles,
1206 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1207 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
1208 LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
1214 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1217 std::string NewModulePath =
1220 if (LinkedObjectsFile)
1221 *LinkedObjectsFile << NewModulePath <<
'\n';
1223 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1225 ImportList, ModuleToSummariesForIndex);
1234 if (ShouldEmitImportsFiles) {
1236 ModuleToSummariesForIndex);
1242 OnWrite(ModulePath);
1251 std::string OldPrefix, std::string NewPrefix,
bool ShouldEmitImportsFiles,
1256 return std::make_unique<WriteIndexesThinBackend>(
1257 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1258 ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1264 if (ThinLTO.ModuleMap.empty())
1274 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1275 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1276 ModuleToDefinedGVSummaries);
1284 for (
auto &Mod : ThinLTO.ModuleMap)
1285 if (!ModuleToDefinedGVSummaries.count(Mod.first))
1286 ModuleToDefinedGVSummaries.
try_emplace(Mod.first);
1292 ThinLTO.ModuleMap.size());
1294 ThinLTO.ModuleMap.size());
1298 ThinLTO.CombinedIndex.dumpSCCs(
outs());
1300 std::set<GlobalValue::GUID> ExportedGUIDs;
1305 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1307 LocalWPDTargetsMap);
1311 ImportLists, ExportLists);
1317 for (
auto &Res : GlobalResolutions) {
1320 if (Res.second.Partition != GlobalResolution::External ||
1321 !Res.second.isPrevailingIRSymbol())
1326 if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1327 ExportedGUIDs.insert(GUID);
1332 for (
auto &
Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1333 ExportedGUIDs.insert(
1337 const auto &ExportList = ExportLists.find(ModuleIdentifier);
1338 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1339 ExportedGUIDs.count(VI.
getGUID());
1345 LocalWPDTargetsMap);
1349 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1354 auto recordNewLinkage = [&](
StringRef ModuleIdentifier,
1357 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1360 recordNewLinkage, GUIDPreservedSymbols);
1362 std::unique_ptr<ThinBackendProc> BackendProc =
1363 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1368 unsigned Task = RegularLTO.ParallelCodeGenParallelismLevel;
1369 for (
auto &Mod : ThinLTO.ModuleMap) {
1370 if (
Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1371 ExportLists[Mod.first],
1372 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1377 return BackendProc->wait();
1387 if (!Filename.empty() && Count != -1)
1393 Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness);
1394 if (
Error E = ResultOrErr.takeError())
1395 return std::move(
E);
1398 (*ResultOrErr)->keep();
1406 if (StatsFilename.
empty())
1417 return std::move(StatsFile);
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time...
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
A parsed version of the target data layout string in and methods for querying it. ...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
This class defines the interface to the ThinLTO backend.
bool hasLocalLinkage() const
Special purpose, only applies to global arrays.
uint32_t getSymbolFlags(Symbol S) const
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
unsigned Prevailing
The linker has chosen this definition of the symbol.
CodeGenOpt::Level CGOptLevel
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
This class represents lattice values for constants.
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
A Module instance is used to store all the information related to an LLVM module. ...
Same, but only replaced by something equivalent.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Implements a dense probed hash-table based set.
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
Available for inspection, not emission.
unsigned DataSections
Emit data into separate sections.
static ConstantAggregateZero * get(Type *Ty)
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
bool hasAvailableExternallyLinkage() const
unsigned LinkerRedefined
Linker redefined version of the symbol which appeared in -wrap or -defsym linker option.
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
An efficient, type-erasing, non-owning reference to a callable.
iterator find(StringRef Key)
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
Externally visible function.
The resolution for a symbol.
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
const StringMap< GVSummaryMapTy > & ModuleToDefinedGVSummaries
A class that wrap the SHA1 algorithm.
Error takeError()
Take ownership of the stored error.
static void thinLTOResolvePrevailingGUID(ValueInfo VI, DenseSet< GlobalValueSummary *> &GlobalInvolvedWithAlias, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
std::function< void(const std::string &)> IndexWriteCallback
This ThinBackend writes individual module indexes to files, instead of running the individual backend...
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
StringRef getModuleIdentifier() const
ThinBackend createWriteIndexesThinBackend(std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite)
static bool isLocalLinkage(LinkageTypes Linkage)
static bool isLinkOnceLinkage(LinkageTypes Linkage)
CombinedIndexHookFn CombinedIndexHook
static void thinLTOInternalizeAndPromoteGUID(ValueInfo VI, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
T dyn_cast() const
Returns the current pointer if it is of the specified pointer type, otherwises returns null...
GlobalValue::GUID getGUID() const
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Represents a module in a bitcode file.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
std::string DwoDir
The directory to store .dwo files.
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module's symbol table for COMDATs (constant).
std::vector< std::string > MAttrs
void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary >> &LocalWPDTargetsMap)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
std::string ProfileRemapping
Name remapping file for profile data.
ModuleSummaryIndex & CombinedIndex
const TypeIdSummaryMapTy & typeIds() const
ArrayRef< Symbol > symbols() const
Tagged union holding either a T or a Error.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
StringRef result()
Return a reference to the current raw 160-bits SHA1 for the digested data since the last call to init...
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
void addModule(Module *M)
static bool isLinkOnceODRLinkage(LinkageTypes Linkage)
StringRef str() const
Explicit conversion to StringRef.
Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
constexpr Align()=default
Default is byte-aligned.
const T & getValue() const LLVM_LVALUE_FUNCTION
ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries)
Class to represent array types.
std::string SampleProfile
Sample PGO profile path.
bool canAutoHide() const
Checks if all copies are eligible for auto-hiding (have flag set).
unsigned FunctionSections
Emit functions into separate sections.
Optional< CodeModel::Model > CodeModel
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
A ThreadPool for asynchronous parallel execution on a defined number of threads.
static bool isAppendingLinkage(LinkageTypes Linkage)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static ArrayRef< const char * > getRuntimeLibcallSymbols()
Static method that returns a list of libcall symbols that can be generated by LTO but might not be vi...
std::pair< iterator, bool > try_emplace(StringRef Key, ArgsTy &&... Args)
Emplace a new element for the specified key into the map if the key isn't already in the map...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
Expected< std::unique_ptr< ToolOutputFile > > setupStatsFile(StringRef StatsFilename)
Setups the output file for saving statistics.
void update(ArrayRef< uint8_t > Data)
Digest more data.
iterator find(const_arg_type_t< KeyT > Val)
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Ephemeral symbols produced by Reader::symbols() and Reader::module_symbols().
Error add(std::unique_ptr< InputFile > Obj, ArrayRef< SymbolResolution > Res)
Add an input file to the LTO link, using the provided symbol resolutions.
std::function< std::unique_ptr< ThinBackendProc >(const Config &C, ModuleSummaryIndex &CombinedIndex, StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, AddStreamFn AddStream, NativeObjectCache Cache)> ThinBackend
A ThinBackend defines what happens after the thin-link phase during ThinLTO.
DebuggerKind DebuggerTuning
Which debugger to tune for.
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
Same, but only replaced by something equivalent.
initializer< Ty > init(const Ty &Val)
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
Emits an error if two values disagree, otherwise the resulting value is that of the operands...
static cl::opt< bool > DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden, cl::desc("Dump the SCCs in the ThinLTO index's callgraph"))
void gatherImportedSummariesForModule(StringRef ModulePath, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary >> &LocalWPDTargetsMap)
Perform index-based whole program devirtualization on the Summary index.
This is an important class for using LLVM in a threaded context.
Instrumentation for Order File
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
std::pair< iterator, bool > insert(const ValueT &V)
bool UseNewPM
Use the new pass manager.
Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::function< AddStreamFn(unsigned Task, StringRef Key)> NativeObjectCache
This is the type of a native object cache.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
DLLStorageClassTypes
Storage classes of global values for PE targets.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
void thinLTOResolvePrevailingInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
bool replace_path_prefix(SmallVectorImpl< char > &Path, const StringRef &OldPrefix, const StringRef &NewPrefix, Style style=Style::native, bool strict=false)
Replace matching path prefix with another path.
Function and variable summary information to aid decisions and implementation of importing.
static GUID getGUID(StringRef GlobalName)
Return a 64-bit global unique ID constructed from global value name (i.e.
std::string StatsFile
Statistics output file path.
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS)
std::function< std::unique_ptr< NativeObjectStream >(unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
Triple - Helper class for working with autoconf configuration names.
static LinkageTypes getWeakLinkage(bool ODR)
Struct that holds a reference to a particular GUID in a global value summary.
static void writeToResolutionFile(raw_ostream &OS, InputFile *Input, ArrayRef< SymbolResolution > Res)
void computeSyntheticCounts(ModuleSummaryIndex &Index)
Compute synthetic function entry counts.
void PrintStatisticsJSON(raw_ostream &OS)
Print statistics in JSON format.
static ErrorSuccess success()
Create a success value.
GlobalValueSummary * getBaseObject()
If this is an alias summary, returns the summary of the aliased object (a global variable or function...
Align max(MaybeAlign Lhs, Align Rhs)
unsigned getMaxTasks() const
Returns an upper bound on the number of tasks that the client may expect.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
void computeLTOCacheKey(SmallString< 40 > &Key, const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const std::set< GlobalValue::GUID > &CfiFunctionDefs={}, const std::set< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
virtual ~ThinBackendProc()
Optional< Reloc::Model > RelocModel
std::string utostr(uint64_t X, bool isNeg=false)
void setLinkage(LinkageTypes LT)
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
const Comdat * getComdat() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
CodeGenFileType CGFileType
LinkageTypes
An enumeration for the kinds of linkage for global values.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
unsigned RelaxELFRelocations
ThinBackend createInProcessThinBackend(unsigned ParallelismLevel)
This ThinBackend runs the individual backend jobs in-process.
static const char * libcallRoutineNames[]
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, unsigned RemarksHotnessThreshold=0)
Setup optimization remarks that output to a file.
std::set< std::string > & cfiFunctionDefs()
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, StringMap< FunctionImporter::ImportMapTy > &ImportLists, StringMap< FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
void setAlignment(MaybeAlign Align)
A raw_ostream that writes to a file descriptor.
LTO(Config Conf, ThinBackend Backend=nullptr, unsigned ParallelCodeGenParallelismLevel=1)
Create an LTO object.
void setUnnamedAddr(UnnamedAddr Val)
Linkage
Describes symbol linkage.
static void handleNonPrevailingComdat(GlobalValue &GV, std::set< const Comdat *> &NonPrevailingComdats)
Error joinErrors(Error E1, Error E2)
Concatenate errors.
StringRef getName() const
Return a constant reference to the value's name.
Error run(AddStreamFn AddStream, NativeObjectCache Cache=nullptr)
Runs the LTO pipeline.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
Keep one copy of named function when linking (weak)
Rename collisions when linking (static functions).
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
Function summary information to aid decisions and implementation of importing.
unsigned VisibleToRegularObj
The definition of this symbol is visible outside of the LTO unit.
cl::opt< bool > EnableLTOInternalization("enable-lto-internalization", cl::init(true), cl::Hidden, cl::desc("Enable global value internalization in LTO"))
Enable global value internalization in LTO.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
const GlobalObject * getBaseObject() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::set< std::string > & cfiFunctionDecls()
std::function< void(GlobalValue &)> ValueAdder
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
Lightweight error class with error context and mandatory checking.
void EnableStatistics(bool DoPrintOnExit=true)
Enable the collection and printing of statistics.
This class implements an extremely fast bulk output stream that can only output to a stream...
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
iterator_range< global_iterator > globals()
A derived class of LLVMContext that initializes itself according to a given Config object...
StringRef - Represent a constant reference to a string, i.e.
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target...
unsigned FinalDefinitionInLinkageUnit
The definition of this symbol is unpreemptable at runtime and is known to be in this linkage unit...
Expected< IRSymtabFile > readIRSymtab(MemoryBufferRef MBRef)
Reads a bitcode file, creating its irsymtab if necessary.
std::string toHex(StringRef Input, bool LowerCase=false)
Convert buffer Input to its hexadecimal representation.
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
llvm::Error materializeMetadata()
static IntegerType * getInt8Ty(LLVMContext &C)
PointerType * getType() const
Global values are always pointers.
std::string getThinLTOOutputFile(const std::string &Path, const std::string &OldPrefix, const std::string &NewPrefix)
Given the original Path to an output file, replace any path prefix matching OldPrefix with NewPrefix...
bool empty() const
empty - Check if the array is empty.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
iterator_range< alias_iterator > aliases()
iterator_range< global_value_iterator > global_values()