57#include <system_error>
63#define DEBUG_TYPE "function-import"
66 "Number of functions thin link decided to import");
68 "Number of hot functions thin link decided to import");
70 "Number of critical functions thin link decided to import");
72 "Number of global variables thin link decided to import");
73STATISTIC(NumImportedFunctions,
"Number of functions imported in backend");
75 "Number of function declarations thin link decided to import because "
76 "the callee is required in the caller's module (e.g. for MemProf "
79 "Number of function declarations imported in backend");
81 "Number of global variables imported in backend");
82STATISTIC(NumImportedModules,
"Number of modules imported from");
83STATISTIC(NumDeadSymbols,
"Number of dead stripped symbols in index");
84STATISTIC(NumLiveSymbols,
"Number of live symbols in index");
95static std::unique_ptr<Module>
loadFile(
const std::string &FileName,
101 std::unique_ptr<Module> Result =
105 Err.print(
"function-import",
errs());
134 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
138 [&Index, CalleeSummaryList,
139 CallerModulePath](
const std::unique_ptr<GlobalValueSummary> &SummaryPtr)
142 auto *GVSummary = SummaryPtr.get();
143 if (!Index.isGlobalValueLive(GVSummary))
180 if (Summary->notEligibleToImport())
205 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
206 unsigned Threshold,
StringRef CallerModulePath,
210 TooLargeOrNoInlineSummary =
nullptr;
211 auto QualifiedCandidates =
213 for (
auto QualifiedValue : QualifiedCandidates) {
214 Reason = QualifiedValue.first;
223 if ((Summary->instCount() > Threshold) && !Summary->fflags().AlwaysInline &&
224 !Opts.force_import_all) {
225 TooLargeOrNoInlineSummary = Summary;
231 if (Summary->fflags().NoInline && !Opts.force_import_all) {
232 TooLargeOrNoInlineSummary = Summary;
251 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
252 if (!Imports.insert(Def).second)
264 auto [Def, Decl] = IDs.createImportIDs(FromModule, GUID);
267 if (!Imports.contains(Def))
268 Imports.insert(Decl);
274 for (
const auto &[SrcMod, GUID, ImportType] : *
this)
281std::optional<GlobalValueSummary::ImportKind>
284 if (
auto IDPair = IDs.getImportIDs(FromModule, GUID)) {
285 auto [Def, Decl] = *IDPair;
286 if (Imports.contains(Def))
288 if (Imports.contains(Decl))
297 const IPOOptions &Opts;
306 const auto &GVS = DefinedGVSummaries.
find(VI.getGUID());
307 if (GVS == DefinedGVSummaries.end())
324 if (VI.getSummaryList().size() > 1 &&
326 !IsPrevailing(VI.getGUID(), GVS->second))
335 for (
const auto &VI : Summary.refs()) {
336 if (!shouldImportGlobal(VI, Summary.modulePath())) {
338 dbgs() <<
"Ref ignored! Target already in destination module.\n");
344 for (
const auto &RefSummary : VI.getSummaryList()) {
362 bool CanImportDecl =
false;
364 Summary.modulePath()) ||
365 !Index.canImportGlobalVar(GVS,
true,
367 if (Opts.import_declaration && CanImportDecl)
368 ImportList.maybeAddDeclaration(RefSummary->modulePath(),
376 if (ImportList.addDefinition(RefSummary->modulePath(), VI.getGUID()) !=
382 NumImportedGlobalVarsThinLink++;
387 (*ExportLists)[RefSummary->modulePath()].insert(VI);
391 if (!Index.isWriteOnly(GVS))
406 : Opts(Opts), Index(Index), DefinedGVSummaries(DefinedGVSummaries),
407 IsPrevailing(IsPrevailing), ImportList(ImportList),
408 ExportLists(ExportLists) {}
412 onImportingSummaryImpl(Summary, Worklist);
413 while (!Worklist.
empty())
414 onImportingSummaryImpl(*Worklist.
pop_back_val(), Worklist);
422 void computeImportForFunction(
443 const IPOOptions &
Opts,
470 void addRequiredDeclaration(
ValueInfo VI,
491 static std::unique_ptr<ModuleImportsManager>
492 create(
const IPOOptions &Opts,
519 if (
Opts.thinlto_move_ctxprof_trees) {
526 if (SetIter == Workloads.end()) {
528 <<
" does not contain the root of any context.\n");
530 ModName, ImportList);
533 <<
" contains the root(s) of context(s).\n");
537 auto &ValueInfos = SetIter->second;
539 auto It = DefinedGVSummaries.
find(VI.getGUID());
540 if (It != DefinedGVSummaries.
end() &&
543 dbgs() <<
"[Workload] " << VI.name()
544 <<
" has the prevailing variant already in the module "
545 << ModName <<
". No need to import\n");
555 [&](
const auto &Candidate) {
557 <<
" from " << Candidate.second->modulePath()
558 <<
" ImportFailureReason: "
560 return Candidate.first ==
563 [](
const auto &Candidate) {
return Candidate.second; });
564 if (PotentialCandidates.empty()) {
566 <<
" because can't find eligible Callee. Guid is: "
567 << VI.getGUID() <<
"\n");
585 PotentialCandidates, [&](
const auto *Candidate) {
588 if (PrevailingCandidates.empty()) {
589 GVS = *PotentialCandidates.begin();
594 <<
"[Workload] Found multiple non-prevailing candidates for "
596 <<
". This is unexpected. Are module paths passed to the "
597 "compiler unique for the modules passed to the linker?");
606 GVS = *PrevailingCandidates.begin();
613 if (ExportingModule == ModName) {
615 <<
" because its defining module is the same as the "
619 LLVM_DEBUG(
dbgs() <<
"[Workload][Including]" << VI.name() <<
" from "
620 << ExportingModule <<
" : " << VI.getGUID() <<
"\n");
624 (*ExportLists)[ExportingModule].insert(VI);
629 void loadFromJson() {
636 if (!NameToValueInfo.
insert(std::make_pair(VI.name(), VI)).second)
639 auto DbgReportIfAmbiguous = [&](
StringRef Name) {
641 dbgs() <<
"[Workload] Function name " << Name
642 <<
" present in the workload definition is ambiguous. Consider "
643 "compiling with -funique-internal-linkage-names.";
648 if (std::error_code EC = BufferOrErr.getError()) {
652 auto Buffer = std::move(BufferOrErr.get());
653 std::map<std::string, std::vector<std::string>> WorkloadDefs;
666 for (
const auto &Workload : WorkloadDefs) {
667 const auto &Root = Workload.first;
668 DbgReportIfAmbiguous(Root);
670 const auto &AllCallees = Workload.second;
671 auto RootIt = NameToValueInfo.
find(Root);
672 if (RootIt == NameToValueInfo.
end()) {
674 <<
" not found in this linkage unit.\n");
677 auto RootVI = RootIt->second;
678 if (RootVI.getSummaryList().size() != 1) {
680 <<
" should have exactly one summary, but has "
681 << RootVI.getSummaryList().size() <<
". Skipping.\n");
685 RootVI.getSummaryList().
front()->modulePath();
686 LLVM_DEBUG(
dbgs() <<
"[Workload] Root defining module for " << Root
687 <<
" is : " << RootDefiningModule <<
"\n");
688 auto &Set = Workloads[RootDefiningModule];
689 for (
const auto &Callee : AllCallees) {
691 DbgReportIfAmbiguous(Callee);
692 auto ElemIt = NameToValueInfo.
find(Callee);
693 if (ElemIt == NameToValueInfo.
end()) {
697 Set.insert(ElemIt->second);
702 void loadFromCtxProf() {
705 if (std::error_code EC = BufferOrErr.getError()) {
709 auto Buffer = std::move(BufferOrErr.get());
717 const auto &CtxMap = Ctx->Contexts;
719 for (
const auto &[RootGuid, Root] : CtxMap) {
722 ContainedGUIDs.
clear();
724 auto RootVI =
Index.getValueInfo(RootGuid);
727 <<
" not found in this linkage unit.\n");
730 if (RootVI.getSummaryList().size() != 1) {
732 <<
" should have exactly one summary, but has "
733 << RootVI.getSummaryList().size() <<
". Skipping.\n");
736 std::string RootDefiningModule =
737 RootVI.getSummaryList().front()->modulePath().str();
738 if (
Opts.thinlto_move_ctxprof_trees) {
739 RootDefiningModule = std::to_string(RootGuid);
741 dbgs() <<
"[Workload] Moving " << RootGuid
742 <<
" to a module with the filename without extension : "
743 << RootDefiningModule <<
"\n");
745 LLVM_DEBUG(
dbgs() <<
"[Workload] Root defining module for " << RootGuid
746 <<
" is : " << RootDefiningModule <<
"\n");
748 auto &Set = Workloads[RootDefiningModule];
749 Root.getContainedGuids(ContainedGUIDs);
750 Roots.insert(RootVI);
751 for (
auto Guid : ContainedGUIDs)
761 const IPOOptions &
Opts,
769 "Pass only one of: -thinlto-pgo-ctx-prof or -thinlto-workload-def");
777 for (
const auto &[Root, Set] : Workloads) {
778 dbgs() <<
"[Workload] Root: " << Root <<
" we have " << Set.size()
779 <<
" distinct callees.\n";
780 for (
const auto &VI : Set) {
781 dbgs() <<
"[Workload] Root: " << Root
782 <<
" Would include: " << VI.getGUID() <<
"\n";
790 const IPOOptions &
Opts,
796 LLVM_DEBUG(
dbgs() <<
"[Workload] Using the regular imports manager.\n");
797 return std::unique_ptr<ModuleImportsManager>(
800 LLVM_DEBUG(
dbgs() <<
"[Workload] Using the contextual imports manager.\n");
817 return "InterposableLinkage";
819 return "LocalLinkageNotInModule";
821 return "NotEligible";
831void ModuleImportsManager::computeImportForFunction(
832 const FunctionSummary &Summary,
const unsigned Threshold,
834 SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
835 FunctionImporter::ImportMapTy &ImportList,
838 static int ImportCount = 0;
840 ValueInfo
VI =
Edge.first;
841 LLVM_DEBUG(
dbgs() <<
" edge -> " << VI <<
" Threshold:" << Threshold
858 const bool RequiresDeclImport =
859 Edge.second.requiresDeclImport() ||
860 (
Edge.second.hasIndirectCall() &&
861 (Opts.import_declaration ||
862 (Opts.import_declaration_for_indirect_calls &&
863 Edge.second.getHotness() >=
864 Opts.import_declaration_for_indirect_calls_min_hotness)));
866 if (Opts.import_cutoff >= 0 && ImportCount >= Opts.import_cutoff) {
868 << Opts.import_cutoff <<
" reached.\n");
871 if (RequiresDeclImport && !DefinedGVSummaries.
count(
VI.getGUID()))
872 importRequiredDeclaration(VI,
Summary.modulePath(), ImportList);
876 if (DefinedGVSummaries.
count(
VI.getGUID())) {
880 LLVM_DEBUG(
dbgs() <<
"ignored! Target already in destination module.\n");
884 if (!canImport(VI)) {
886 dbgs() <<
"Skipping over " <<
VI.getGUID()
887 <<
" because its import is handled in a different module.");
888 assert(
VI.getSummaryList().size() == 1 &&
889 "The root was expected to be an external symbol");
895 return Opts.import_hot_multiplier;
897 return Opts.import_cold_multiplier;
899 return Opts.import_critical_multiplier;
903 const auto NewThreshold =
904 Threshold * GetBonusMultiplier(
Edge.second.getHotness());
906 auto IT = ImportThresholds.insert(std::make_pair(
907 VI.getGUID(), std::make_tuple(NewThreshold,
nullptr,
nullptr)));
908 bool PreviouslyVisited = !IT.second;
909 auto &ProcessedThreshold = std::get<0>(IT.first->second);
910 auto &CalleeSummary = std::get<1>(IT.first->second);
911 auto &FailureInfo = std::get<2>(IT.first->second);
915 bool IsCriticalCallsite =
918 const FunctionSummary *ResolvedCalleeSummary =
nullptr;
920 assert(PreviouslyVisited);
925 if (NewThreshold <= ProcessedThreshold) {
927 dbgs() <<
"ignored! Target was already imported with Threshold "
928 << ProcessedThreshold <<
"\n");
932 ProcessedThreshold = NewThreshold;
937 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
939 dbgs() <<
"ignored! Target was already rejected with Threshold "
940 << ProcessedThreshold <<
"\n");
941 if (Opts.print_import_failures) {
943 "Expected FailureInfo for previously rejected candidate");
944 FailureInfo->Attempts++;
949 if (RequiresDeclImport)
950 importRequiredDeclaration(VI,
Summary.modulePath(), ImportList);
957 const GlobalValueSummary *SummaryForDeclImport =
nullptr;
960 Summary.modulePath(), SummaryForDeclImport, Reason);
961 if (!CalleeSummary) {
964 if (SummaryForDeclImport) {
965 if (RequiresDeclImport)
967 addRequiredDeclaration(VI, SummaryForDeclImport, ImportList);
968 else if (Opts.import_declaration)
976 if (PreviouslyVisited) {
977 ProcessedThreshold = NewThreshold;
978 if (Opts.print_import_failures) {
980 "Expected FailureInfo for previously rejected candidate");
981 FailureInfo->Reason = Reason;
982 FailureInfo->Attempts++;
983 FailureInfo->MaxHotness =
984 std::max(FailureInfo->MaxHotness,
Edge.second.getHotness());
986 }
else if (Opts.print_import_failures) {
988 "Expected no FailureInfo for newly rejected candidate");
989 FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
990 VI,
Edge.second.getHotness(), Reason, 1);
992 if (Opts.force_import_all) {
993 std::string
Msg = std::string(
"Failed to import function ") +
994 VI.name().str() +
" due to " +
999 "Error importing module: ");
1003 <<
"ignored! No qualifying callee with summary found.\n");
1009 CalleeSummary = CalleeSummary->getBaseObject();
1013 Opts.force_import_all ||
1014 (ResolvedCalleeSummary->
instCount() <= NewThreshold)) &&
1015 "selectCallee() didn't honor the threshold");
1017 auto ExportModulePath = ResolvedCalleeSummary->
modulePath();
1023 NumImportedFunctionsThinLink++;
1025 NumImportedHotFunctionsThinLink++;
1026 if (IsCriticalCallsite)
1027 NumImportedCriticalFunctionsThinLink++;
1034 (*ExportLists)[ExportModulePath].insert(VI);
1037 auto GetAdjustedThreshold = [&](
unsigned Threshold,
bool IsHotCallsite) {
1042 return Threshold * Opts.import_hot_evolution_factor;
1043 return Threshold * Opts.import_instr_evolution_factor;
1046 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
1051 Worklist.
emplace_back(ResolvedCalleeSummary, AdjThreshold);
1067 for (
const auto &GVSummary : DefinedGVSummaries) {
1071 auto VI =
Index.getValueInfo(GVSummary.first);
1073 if (!
Index.isGlobalValueLive(GVSummary.second)) {
1083 computeImportForFunction(*FuncSummary,
Opts.import_instr_limit,
1084 DefinedGVSummaries, Worklist, GVI, ImportList,
1089 while (!Worklist.
empty()) {
1091 auto *Summary = std::get<0>(GVInfo);
1092 auto Threshold = std::get<1>(GVInfo);
1094 computeImportForFunction(*Summary, Threshold, DefinedGVSummaries, Worklist,
1095 GVI, ImportList, ImportThresholds);
1100 if (
Opts.print_import_failures) {
1101 dbgs() <<
"Missed imports into module " << ModName <<
"\n";
1102 for (
auto &
I : ImportThresholds) {
1103 auto &ProcessedThreshold = std::get<0>(
I.second);
1104 auto &CalleeSummary = std::get<1>(
I.second);
1105 auto &FailureInfo = std::get<2>(
I.second);
1110 if (!FailureInfo->VI.getSummaryList().empty())
1112 FailureInfo->VI.getSummaryList()[0]->getBaseObject());
1113 dbgs() << FailureInfo->VI
1115 <<
", Threshold = " << ProcessedThreshold
1116 <<
", Size = " << (FS ? (int)FS->instCount() : -1)
1118 <<
", Attempts = " << FailureInfo->Attempts <<
"\n";
1132 for (
auto [Reason, CandidateSummary] :
1136 "Expected only legality checks in qualifyCalleeCandidates");
1148 auto ExistingImportType = ImportList.
getImportType(SrcModule, VI.getGUID());
1153 if (!ExistingImportType) {
1155 NumRequiredDeclsThinLink++;
1168 auto SL = VI.getSummaryList();
1176 if (
const auto &VI = Index.getValueInfo(
G))
1185 unsigned NumGVS = 0;
1186 for (
auto &VI : ExportSet)
1204 for (
const auto &[FromModule, GUID,
Type] : ImportList) {
1223 for (
const auto &ImportPerModule : ImportLists)
1224 for (
const auto &[FromModule, GUID, ImportType] : ImportPerModule.second)
1225 FlattenedImports.
insert(GUID);
1233 auto IsReadOrWriteOnlyVarNeedingImporting = [&](
StringRef ModulePath,
1236 Index.findSummaryInModule(VI, ModulePath));
1237 return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
1243 for (
auto &ExportPerModule : ExportLists)
1244 for (
auto &VI : ExportPerModule.second)
1245 if (!FlattenedImports.
count(VI.getGUID()) &&
1246 IsReadOrWriteOnlyVarNeedingImporting(ExportPerModule.first, VI))
1263 isPrevailing, Index, &ExportLists);
1265 for (
const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
1266 auto &ImportList = ImportLists[DefinedGVSummaries.first];
1268 << DefinedGVSummaries.first <<
"'\n");
1269 MIS->computeImportForModule(DefinedGVSummaries.second,
1270 DefinedGVSummaries.first, ImportList);
1278 for (
auto &ELI : ExportLists) {
1282 const auto &DefinedGVSummaries =
1283 ModuleToDefinedGVSummaries.
lookup(ELI.first);
1284 for (
auto &EI : ELI.second) {
1291 auto DS = DefinedGVSummaries.
find(EI.getGUID());
1295 auto *S = DS->getSecond();
1296 S = S->getBaseObject();
1302 if (!Index.isWriteOnly(GVS))
1315 [&](
ValueInfo VI) {
return !DefinedGVSummaries.
count(VI.getGUID()); });
1316 ELI.second.insert_range(NewExports);
1322 for (
auto &[ModPath, RequiredExports] : MIS->requiredDeclExports())
1329 for (
const auto &ModuleImports : ImportLists) {
1330 auto ModName = ModuleImports.first;
1331 auto &Exports = ExportLists[ModName];
1336 << Exports.
size() - NumGVS <<
" functions and " << NumGVS
1337 <<
" vars. Imports from " << Histogram.
size()
1339 for (
const auto &[SrcModName,
Stats] : Histogram) {
1341 <<
" function definitions and "
1343 <<
" function declarations imported from " << SrcModName
1346 <<
" global vars imported from " << SrcModName <<
"\n");
1358 LLVM_DEBUG(
dbgs() <<
"* Module " << ModulePath <<
" imports from "
1359 << Histogram.
size() <<
" modules.\n");
1360 for (
const auto &[SrcModName,
Stats] : Histogram) {
1362 <<
" function definitions and "
1364 <<
" function declarations imported from " << SrcModName
1367 << SrcModName <<
"\n");
1381 const IPOOptions &Opts,
StringRef ModulePath,
1389 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
1392 LLVM_DEBUG(
dbgs() <<
"Computing import for Module '" << ModulePath <<
"'\n");
1394 MIS->computeImportForModule(FunctionSummaryMap, ModulePath, ImportList);
1409 for (
const auto &GlobalList : Index) {
1411 if (GlobalList.second.getSummaryList().empty())
1414 auto GUID = GlobalList.first;
1415 assert(GlobalList.second.getSummaryList().size() == 1 &&
1416 "Expected individual combined index to have one summary per GUID");
1417 auto &Summary = GlobalList.second.getSummaryList()[0];
1420 if (Summary->modulePath() == ModulePath)
1423 ImportList.
addGUID(Summary->modulePath(), GUID, Summary->importType());
1439 if (!CalleeVI || !CalleeVI.getSummaryList().empty())
1441 auto GUID = Index.getGUIDFromOriginalID(CalleeVI.getGUID());
1444 auto VI = Index.getValueInfo(GUID);
1446 VI.getSummaryList(),
1447 [&](
const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1457 return SummaryPtr->getSummaryKind() ==
1458 GlobalValueSummary::GlobalVarKind;
1464 for (
auto &EI : FS->mutableCalls()) {
1466 if (
auto VI = GetUpdatedCallee(EI.first))
1477 if (FS->callsites().empty())
1479 for (
auto &CI : FS->mutableCallsites()) {
1480 if (
auto VI = GetUpdatedCallee(CI.Callee))
1486 for (
const auto &Entry : Index) {
1487 for (
const auto &S : Entry.second.getSummaryList()) {
1498 assert(!Index.withGlobalValueDeadStripping());
1499 if (!LibraryOptions.
get<IPOOptions>().compute_dead ||
1501 GUIDPreservedSymbols.
empty()) {
1506 unsigned LiveSymbols = 0;
1508 Worklist.
reserve(GUIDPreservedSymbols.
size() * 2);
1509 for (
auto GUID : GUIDPreservedSymbols) {
1510 ValueInfo VI = Index.getValueInfo(GUID);
1513 for (
const auto &S : VI.getSummaryList())
1518 for (
const auto &Entry : Index) {
1519 auto VI = Index.getValueInfo(Entry);
1520 for (
const auto &S : Entry.second.getSummaryList()) {
1544 [](
const std::unique_ptr<llvm::GlobalValueSummary> &S) {
1555 bool KeepAliveLinkage =
false;
1556 bool Interposable =
false;
1557 for (
const auto &S : VI.getSummaryList()) {
1561 KeepAliveLinkage =
true;
1563 Interposable =
true;
1567 if (!KeepAliveLinkage)
1572 "Interposable and available_externally/linkonce_odr/weak_odr "
1577 for (
const auto &S : VI.getSummaryList())
1583 while (!Worklist.
empty()) {
1585 for (
const auto &Summary : VI.getSummaryList()) {
1590 visit(AS->getAliaseeVI(),
true);
1593 for (
auto Ref : Summary->refs())
1596 for (
auto Call : FS->calls())
1600 Index.setWithGlobalValueDeadStripping();
1602 unsigned DeadSymbols = Index.size() - LiveSymbols;
1603 LLVM_DEBUG(
dbgs() << LiveSymbols <<
" symbols Live, and " << DeadSymbols
1604 <<
" symbols Dead \n");
1605 NumDeadSymbols += DeadSymbols;
1606 NumLiveSymbols += LiveSymbols;
1614 bool ImportEnabled) {
1617 GUIDPreservedSymbols, isPrevailing);
1619 Index.propagateAttributes(GUIDPreservedSymbols);
1631 ModuleToSummariesForIndex[std::string(ModulePath)] =
1632 ModuleToDefinedGVSummaries.
lookup(ModulePath);
1641 auto It = Map.find(
Key);
1642 if (It == Map.end())
1643 std::tie(It, std::ignore) =
1649 for (
const auto &[FromModule, GUID, ImportType] : ImportList) {
1650 auto &SummariesForIndex =
1651 LookupOrCreate(ModuleToSummariesForIndex, FromModule);
1653 const auto &DefinedGVSummaries = ModuleToDefinedGVSummaries.
at(FromModule);
1654 const auto &DS = DefinedGVSummaries.
find(GUID);
1655 assert(DS != DefinedGVSummaries.
end() &&
1656 "Expected a defined summary for imported global value");
1658 DecSummaries.
insert(DS->second);
1660 SummariesForIndex[GUID] = DS->second;
1676 for (
auto &[ModPath, SummariesForIndex] : ModuleToSummariesForIndex) {
1677 if (ModPath == ModulePath)
1679 auto It = ModuleToDefinedGVSummaries.
find(ModPath);
1680 if (It == ModuleToDefinedGVSummaries.
end())
1682 for (
const auto &[GUID, Summary] : It->second) {
1683 if (Summary->noRenameOnPromotion()) {
1684 DecSummaries.
insert(Summary);
1685 SummariesForIndex.try_emplace(GUID, Summary);
1702 [&](
StringRef M) { ImportsOS << M <<
"\n"; });
1712 for (
const auto &ILI : ModuleToSummariesForIndex)
1716 if (ILI.first != ModulePath)
1725 UniqueID = GO->getMetadata(LLVMContext::MD_guid);
1731 F->setMetadata(LLVMContext::MD_guid,
UniqueID);
1732 F->setComdat(
nullptr);
1734 V->setInitializer(
nullptr);
1738 V->setMetadata(LLVMContext::MD_guid,
UniqueID);
1739 V->setComdat(
nullptr);
1770 IFuncResolvers.
insert(
I.getResolverFunction());
1771 auto FinalizeInModule = [&](
GlobalValue &GV,
bool Propagate =
false) {
1774 if (GS == DefinedGlobals.
end())
1781 if (FS->fflags().ReadNone && !
F->doesNotAccessMemory())
1782 F->setDoesNotAccessMemory();
1784 if (FS->fflags().ReadOnly && !
F->onlyReadsMemory())
1785 F->setOnlyReadsMemory();
1787 if (FS->fflags().NoRecurse && !
F->doesNotRecurse())
1788 F->setDoesNotRecurse();
1790 if (FS->fflags().NoUnwind && !
F->doesNotThrow())
1791 F->setDoesNotThrow();
1795 auto NewLinkage = GS->second->linkage();
1840 GS->second->canAutoHide()) {
1846 <<
"` from " << GV.
getLinkage() <<
" to " << NewLinkage
1854 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
1855 if (GO->getComdat()->getName() == GO->getName())
1856 NonPrevailingComdats.
insert(GO->getComdat());
1857 GO->setComdat(
nullptr);
1862 for (
auto &GV : TheModule)
1864 for (
auto &GV : TheModule.
globals())
1865 FinalizeInModule(GV);
1866 for (
auto &GV : TheModule.
aliases())
1867 FinalizeInModule(GV);
1871 if (NonPrevailingComdats.
empty())
1874 if (
auto *
C = GO.getComdat();
C && NonPrevailingComdats.
count(
C)) {
1875 GO.setComdat(
nullptr);
1888 for (
auto &GA : TheModule.
aliases()) {
1889 if (GA.hasAvailableExternallyLinkage())
1892 assert(Obj &&
"aliasee without an base object is unimplemented");
1893 if (Obj->hasAvailableExternallyLinkage()) {
1907 auto MustPreserveGV = [&](
const GlobalValue &GV) ->
bool {
1917 auto GS = DefinedGlobals.
find(GV.getGUIDOrFallback());
1918 if (GS == DefinedGlobals.
end()) {
1929 GS = DefinedGlobals.
find(
1931 if (GS == DefinedGlobals.
end()) {
1938 GS = DefinedGlobals.
find(
1969 for (
auto &GV : M.globals())
1972 if (!GV.isDeclaration() && GV.hasAttribute(
"thinlto-internalize")) {
1986 if (!
F.hasAvailableExternallyLinkage() ||
1987 !
F.hasMetadata(LLVMContext::MD_implicit_ref))
1990 F.getMetadata(LLVMContext::MD_implicit_ref, MDs);
1992 auto *
Op = MD->getOperand(0).get();
1997 if (GV->hasAvailableExternallyLinkage() && Seen.
insert(GV).second)
2001 if (!ToProtect.
empty())
2006 return C.get<IPOOptions>().force_import_all;
2016 unsigned ImportedCount = 0, ImportedGVCount = 0;
2023 for (
auto &
F : DestModule)
2024 if (!
F.isDeclaration() && MoveSymbolGUIDSet.
contains(
F.getGUIDOrFallback()))
2036 SourceModules.
emplace_back(Index.getModuleHash(ModName), ModName);
2040 for (
const auto &[ModHash, ModName] : SourceModules) {
2044 if (!SrcModuleOrErr)
2046 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
2048 "Context mismatch");
2052 if (
Error Err = SrcModule->materializeMetadata())
2053 return std::move(Err);
2065 auto GUID =
F.getGUIDOrFallback();
2066 auto MaybeImportType = ImportList.
getImportType(ModName, GUID);
2067 bool ImportDefinition =
2071 <<
" importing function"
2072 << (ImportDefinition
2074 : (MaybeImportType ?
" declaration " :
" "))
2075 << GUID <<
" " <<
F.getName() <<
" from "
2076 << SrcModule->getSourceFileName() <<
"\n");
2077 if (ImportDefinition) {
2078 if (
Error Err =
F.materialize())
2079 return std::move(Err);
2082 if (Opts.enable_import_metadata ||
2083 Opts.memprof_context_disambiguation) {
2087 "thinlto_src_module",
2089 {MDString::get(DestModule.getContext(),
2090 SrcModule->getModuleIdentifier())}));
2094 {MDString::get(DestModule.getContext(),
2095 SrcModule->getSourceFileName())}));
2098 }
else if (MaybeImportType) {
2109 auto GUID = GV.getGUIDOrFallback();
2110 auto MaybeImportType = ImportList.
getImportType(ModName, GUID);
2111 bool ImportDefinition =
2115 <<
" importing global"
2116 << (ImportDefinition
2118 : (MaybeImportType ?
" declaration " :
" "))
2119 << GUID <<
" " << GV.getName() <<
" from "
2120 << SrcModule->getSourceFileName() <<
"\n");
2121 if (ImportDefinition) {
2122 if (
Error Err = GV.materialize())
2123 return std::move(Err);
2124 ImportedGVCount += GlobalsToImport.
insert(&GV);
2133 auto GUID = GA.getGUIDOrFallback();
2134 auto MaybeImportType = ImportList.
getImportType(ModName, GUID);
2135 bool ImportDefinition =
2139 <<
" importing alias"
2140 << (ImportDefinition
2142 : (MaybeImportType ?
" declaration " :
" "))
2143 << GUID <<
" " << GA.getName() <<
" from "
2144 << SrcModule->getSourceFileName() <<
"\n");
2145 if (ImportDefinition) {
2146 if (
Error Err = GA.materialize())
2147 return std::move(Err);
2151 return std::move(Err);
2157 <<
" " << GO->
getName() <<
" from "
2158 << SrcModule->getSourceFileName() <<
"\n");
2159 if (Opts.enable_import_metadata ||
2160 Opts.memprof_context_disambiguation) {
2166 "thinlto_src_module",
2168 Ctx, SrcModule->getModuleIdentifier())}));
2172 Ctx, {
MDString::get(Ctx, SrcModule->getSourceFileName())}));
2174 "thinlto_alias_guid",
2178 GlobalsToImport.
insert(Fn);
2179 }
else if (MaybeImportType) {
2195 SrcModule->setPartialSampleProfileRatio(Index);
2215 for (
auto [GV, GUID] : DeclsToImport) {
2216 assert(!GV->hasLocalLinkage() &&
2217 "Expected imported declaration to be promoted");
2224 DeclInfos.
push_back({GV->getName().str(),
F->getFunctionType(),
2225 F->getAddressSpace(),
F->getCallingConv(),
2226 F->getAttributes(), GV->getVisibility(),
2227 GV->isDSOLocal(), GUID});
2230 if (Opts.print_imports) {
2231 for (
const auto *GV : GlobalsToImport)
2233 <<
" from " << SrcModule->getSourceFileName() <<
"\n";
2236 if (
Error Err = Mover.
move(std::move(SrcModule),
2240 Twine(
"Function Import: link error: ") +
2243 ImportedCount += GlobalsToImport.
size();
2244 NumImportedModules++;
2258 for (
auto &DI : DeclInfos) {
2264 LLVMContext::MD_guid,
2267 {ConstantAsMetadata::get(ConstantInt::get(
2268 Type::getInt64Ty(DestModule.getContext()), DI.GUID))}));
2279 ExistingF && ExistingF->isDeclaration() &&
2280 !ExistingF->getMetadata(LLVMContext::MD_guid))
2285 DI.AddrSpace, DI.Name, &DestModule);
2286 F->setCallingConv(DI.CC);
2287 F->setAttributes(DI.Attrs);
2290 F->setVisibility(DI.Visibility);
2291 F->setDSOLocal(DI.DSOLocal);
2293 NumImportedFunctionDecls++;
2301 if (ImportedGVCount > 0)
2304 NumImportedFunctions += (ImportedCount - ImportedGVCount);
2305 NumImportedGlobalVars += ImportedGVCount;
2308 LLVM_DEBUG(
dbgs() <<
"Imported " << ImportedCount - ImportedGVCount
2309 <<
" functions for Module "
2312 <<
" global variables for Module "
2314 return ImportedCount;
2321 if (Opts.summary_file.empty())
2325 if (!IndexPtrOrErr) {
2327 "Error loading file '" + Opts.summary_file +
"': ");
2330 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
2338 if (Opts.import_all_index)
2340 *Index, ImportList);
2343 isPrevailing, *Index, ImportList);
2349 for (
auto &
I : *Index) {
2350 for (
auto &S :
I.second.getSummaryList()) {
2352 S->setExternalLinkageForTest();
2362 auto ModuleLoader = [&M](
StringRef Identifier) {
2363 return loadFile(std::string(Identifier), M.getContext());
2372 "Error importing module: ");
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
static auto qualifyCalleeCandidates(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, StringRef CallerModulePath)
Given a list of possible callee implementation for a call site, qualify the legality of importing eac...
static DenseMap< StringRef, ImportStatistics > collectImportStatistics(const ModuleSummaryIndex &Index, const FunctionImporter::ImportMapTy &ImportList)
static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, FunctionImporter::ExportSetTy &ExportSet)
static bool checkVariableImport(const ModuleSummaryIndex &Index, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
static bool doImportingForModuleForTest(Module &M, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
static const char * getFailureName(FunctionImporter::ImportFailureReason Reason)
static void internalizeGVsAfterImport(Module &M)
void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index, FunctionSummary *FS)
static std::unique_ptr< Module > loadFile(const std::string &FileName, LLVMContext &Context)
static bool shouldSkipLocalInAnotherModule(const GlobalValueSummary *RefSummary, size_t NumDefs, StringRef ImporterModule)
static const GlobalValueSummary * selectCallee(const IPOOptions &Opts, const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary > > CalleeSummaryList, unsigned Threshold, StringRef CallerModulePath, const GlobalValueSummary *&TooLargeOrNoInlineSummary, FunctionImporter::ImportFailureReason &Reason)
Given a list of possible callee implementation for a call site, select one that fits the Threshold fo...
static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI)
static Function * replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA)
Make alias a clone of its aliasee.
static void protectImplicitRefGlobals(Module &M)
When a function carrying !implicit.ref is imported via ThinLTO, the referenced global arrives as avai...
static void dumpImportListForModule(const ModuleSummaryIndex &Index, StringRef ModulePath, FunctionImporter::ImportMapTy &ImportList)
static void ComputeCrossModuleImportForModuleForTest(const IPOOptions &Opts, StringRef ModulePath, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Compute all the imports for the given module using the Index.
static void ComputeCrossModuleImportForModuleFromIndexForTest(StringRef ModulePath, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Mark all external summaries in Index for import into the given module.
Module.h This file contains the declarations for the Module class.
This file supports working with JSON data.
block placement Basic Block Placement Stats
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
static cl::opt< bool > PropagateAttrs("propagate-attrs", cl::init(true), cl::Hidden, cl::desc("Propagate attributes in index"))
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static constexpr StringLiteral Filename
Reader for contextual iFDO profile, which comes in bitstream format.
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
std::pair< BasicBlock *, BasicBlock * > Edge
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Import globals referenced by a function or other globals that are being imported, if importing such g...
void onImportingSummary(const GlobalValueSummary &Summary)
GlobalsImporter(const IPOOptions &Opts, const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, FunctionImporter::ImportMapTy &ImportList, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
virtual bool canImport(ValueInfo VI)
void importRequiredDeclaration(ValueInfo VI, StringRef CallerModulePath, FunctionImporter::ImportMapTy &ImportList)
Import a declaration of the callee VI of a call edge requiring a declaration import (see RequiresDecl...
DenseMap< StringRef, FunctionImporter::ExportSetTy > *const ExportLists
void addRequiredDeclaration(ValueInfo VI, const GlobalValueSummary *DeclSummary, FunctionImporter::ImportMapTy &ImportList)
Import a declaration of the callee VI from the module containing DeclSummary, which must be a candida...
ModuleImportsManager(const IPOOptions &Opts, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
virtual ~ModuleImportsManager()=default
function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing
const ModuleSummaryIndex & Index
static std::unique_ptr< ModuleImportsManager > create(const IPOOptions &Opts, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists=nullptr)
DenseMap< StringRef, FunctionImporter::ExportSetTy > RequiredDeclExports
DenseMap< StringRef, FunctionImporter::ExportSetTy > & requiredDeclExports()
Values that must be exported from their defining modules because declarations of them are required in...
virtual void computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName, FunctionImporter::ImportMapTy &ImportList)
Given the list of globals defined in a module, compute the list of imports as well as the list of "ex...
WorkloadImportsManager(const IPOOptions &Opts, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> IsPrevailing, const ModuleSummaryIndex &Index, DenseMap< StringRef, FunctionImporter::ExportSetTy > *ExportLists)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
void insert_range(Range &&R)
Inserts a range of 'std::pair<KeyT, ValueT>' values into the map.
ValueT & at(const_arg_type_t< KeyT > Val)
Return the entry for the specified key, or abort if no such entry exists.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Implements a dense probed hash-table based set.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
The map maintains the list of imports.
LLVM_ABI AddDefinitionStatus addDefinition(StringRef FromModule, GlobalValue::GUID GUID)
void addGUID(StringRef FromModule, GlobalValue::GUID GUID, GlobalValueSummary::ImportKind ImportKind)
LLVM_ABI SmallVector< StringRef, 0 > getSourceModules() const
LLVM_ABI std::optional< GlobalValueSummary::ImportKind > getImportType(StringRef FromModule, GlobalValue::GUID GUID) const
LLVM_ABI void maybeAddDeclaration(StringRef FromModule, GlobalValue::GUID GUID)
The function importer is automatically importing function from other modules based on the provided su...
LLVM_ABI Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
DenseMap< GlobalValue::GUID, std::tuple< unsigned, const GlobalValueSummary *, std::unique_ptr< ImportFailureInfo > > > ImportThresholdsTy
Map of callee GUID considered for import into a given module to a pair consisting of the largest thre...
static LLVM_ABI bool forceImportAll(const cl::LibraryOptionsContext &C)
ImportFailureReason
The different reasons selectCallee will chose not to import a candidate.
@ LocalLinkageNotInModule
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function summary information to aid decisions and implementation of importing.
unsigned instCount() const
Get the instruction count recorded for this function.
FFlags fflags() const
Get function summary flags.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
LLVM_ABI const GlobalObject * getAliaseeObject() const
Function and variable summary information to aid decisions and implementation of importing.
StringRef modulePath() const
Get the path to the module containing this function.
GlobalValue::LinkageTypes linkage() const
Return linkage type recorded for this global value.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
VisibilityTypes getVisibility() const
bool isImplicitDSOLocal() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
LinkageTypes getLinkage() const
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
ThreadLocalMode getThreadLocalMode() const
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
void setLinkage(LinkageTypes LT)
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time.
LLVM_ABI Error materialize()
Make sure this GlobalValue is fully read.
LLVM_ABI bool canBeOmittedFromSymbolTable() const
True if GV can be left out of the object symbol table.
@ InternalLinkage
Rename collisions when linking (static functions).
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Type * getValueType() const
LLVM_ABI Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
This is an important class for using LLVM in a threaded context.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
A Module instance is used to store all the information related to an LLVM module.
LLVMContext & getContext() const
Get the global data context.
iterator_range< ifunc_iterator > ifuncs()
const std::string & getSourceFileName() const
Get the module's original source file name.
iterator_range< alias_iterator > aliases()
iterator_range< global_iterator > globals()
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
iterator_range< global_object_iterator > global_objects()
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
LLVM_ABI Expected< PGOCtxProfile > loadProfiles()
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
A vector that has set insertion semantics.
ArrayRef< value_type > getArrayRef() const
size_type size() const
Determine the number of elements in the SetVector.
Vector takeVector()
Clear the SetVector and return the underlying vector.
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
void clear()
Completely clear the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Represent a constant reference to a string, i.e.
constexpr size_t size() const
Get the string size.
char front() const
Get the first character in the string.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
StringSet - A wrapper for StringMap that provides set-like functionality.
std::pair< typename Base::iterator, bool > insert(StringRef key)
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
bool isFunctionTy() const
True if this is an instance of FunctionType.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool remove_if(Predicate Pred)
Remove all elements for which Pred returns true.
An efficient, type-erasing, non-owning reference to a callable.
The root is the trivial Path to the root value.
A raw_ostream that writes to a file descriptor.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
LLVM_ABI llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
bool fromJSON(const Value &E, std::string &Out, Path P)
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
LLVM_ABI void computeDeadSymbolsWithConstProp(const cl::LibraryOptionsContext &LibraryOptions, 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.
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV)
Helper function to internalize functions and variables in a Module.
std::error_code make_error_code(BitcodeError E)
cl::list< GlobalValue::GUID > MoveSymbolGUID
const char * getHotnessName(CalleeInfo::HotnessType HT)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
LLVM_ABI void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
const IPOOptions & getIPOOptions(const LLVMContext &C)
void sort(IteratorTy Start, IteratorTy End)
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void computeDeadSymbolsAndUpdateIndirectCalls(const cl::LibraryOptionsContext &LibraryOptions, ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of the...
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
LLVM_ABI void ComputeCrossModuleImport(const cl::LibraryOptionsContext &LibraryOptions, const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI void updateIndirectCalls(ModuleSummaryIndex &Index)
Update call edges for indirect calls to local functions added from SamplePGO when needed.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
LLVM_ABI std::unique_ptr< Module > getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given file holds a bitcode image, return a Module for it which does lazy deserialization of fu...
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
DWARFExpression::Operation Op
LLVM_ABI void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI void processImportsFiles(StringRef ModulePath, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, function_ref< void(const std::string &)> F)
Call F passing each of the files module ModulePath will import from.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
PrevailingType
PrevailingType enum used as a return type of callback passed to computeDeadSymbolsAndUpdateIndirectCa...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
LLVM_ABI Error EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
Struct that holds a reference to a particular GUID in a global value summary.