92#include <system_error>
99#define DEBUG_TYPE "sample-profile"
100#define CSINLINE_DEBUG DEBUG_TYPE "-inline"
103 "Number of functions inlined with context sensitive profile");
105 "Number of functions not inlined with context sensitive profile");
107 "Number of functions with CFG mismatched profile");
108STATISTIC(NumMatchedProfile,
"Number of functions with CFG matched profile");
110 "Number of inlined callsites with a partial distribution factor");
113 "Number of functions with FDO inline stopped due to min size limit");
115 "Number of functions with FDO inline stopped due to max size limit");
117 NumCSInlinedHitGrowthLimit,
118 "Number of functions with FDO inline stopped due to growth size limit");
128using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
132class GUIDToFuncNameMapper {
137 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
141 for (
const auto &
F : CurrentModule) {
143 CurrentGUIDToFuncNameMap.insert(
154 if (CanonName != OrigName)
155 CurrentGUIDToFuncNameMap.insert(
160 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
163 ~GUIDToFuncNameMapper() {
167 CurrentGUIDToFuncNameMap.clear();
171 SetGUIDToFuncNameMapForAll(
nullptr);
176 std::queue<FunctionSamples *> FSToUpdate;
178 FSToUpdate.push(&IFS.second);
181 while (!FSToUpdate.empty()) {
184 FS->GUIDToFuncNameMap = Map;
185 for (
const auto &ICS : FS->getCallsiteSamples()) {
187 for (
const auto &IFS : FSMap) {
189 FSToUpdate.push(&FS);
201struct InlineCandidate {
203 const FunctionSamples *CalleeSamples;
211 float CallsiteDistribution;
215struct CandidateComparer {
216 bool operator()(
const InlineCandidate &
LHS,
const InlineCandidate &
RHS) {
217 if (
LHS.CallsiteCount !=
RHS.CallsiteCount)
218 return LHS.CallsiteCount <
RHS.CallsiteCount;
220 const FunctionSamples *LCS =
LHS.CalleeSamples;
221 const FunctionSamples *RCS =
RHS.CalleeSamples;
236using CandidateQueue =
248 const IPOOptions &Opts, StringRef Name, StringRef RemapName,
250 std::function<AssumptionCache &(
Function &)> GetAssumptionCache,
251 std::function<TargetTransformInfo &(
Function &)> GetTargetTransformInfo,
252 std::function<
const TargetLibraryInfo &(
Function &)> GetTLI,
253 LazyCallGraph &CG,
bool DisableSampleProfileInlining,
254 bool UseFlattenedProfile)
257 Opts(Opts), ProfileMergeInlinee(Opts.sample_profile_merge_inlinee),
258 ProfileSizeInline(
valueOr(Opts.sample_profile_inline_size,
false)),
259 CallsitePrioritizedInline(
260 valueOr(Opts.sample_profile_prioritized_inline,
false)),
261 AllowRecursiveInline(
263 UsePreInlinerDecision(
265 SalvageStaleProfile(
valueOr(Opts.salvage_stale_profile,
false)),
266 SalvageUnusedProfile(
valueOr(Opts.salvage_unused_profile,
false)),
267 GetAC(std::
move(GetAssumptionCache)),
268 GetTTI(std::
move(GetTargetTransformInfo)), GetTLI(std::
move(GetTLI)),
269 CG(CG), LTOPhase(LTOPhase),
270 AnnotatedPassName(Opts.annotate_sample_profile_inline_phase
274 DisableSampleProfileInlining(DisableSampleProfileInlining),
275 UseFlattenedProfile(UseFlattenedProfile) {}
279 ProfileSummaryInfo *_PSI);
282 const IPOOptions &Opts;
284 bool ProfileMergeInlinee;
285 bool ProfileSizeInline;
286 bool CallsitePrioritizedInline;
287 bool AllowRecursiveInline;
288 bool UsePreInlinerDecision;
289 bool SalvageStaleProfile;
290 bool SalvageUnusedProfile;
291 SampleProfileInlineOptions InlineOpts;
295 ErrorOr<uint64_t> getInstWeight(
const Instruction &
I)
override;
296 const FunctionSamples *findCalleeFunctionSamples(
const CallBase &
I)
const;
297 const FunctionSamples *
298 findFunctionSamples(
const Instruction &
I)
const override;
299 std::vector<const FunctionSamples *>
300 findIndirectCallFunctionSamples(
const Instruction &
I,
uint64_t &Sum)
const;
301 void findExternalInlineCandidate(CallBase *CB,
const FunctionSamples *Samples,
302 DenseSet<GlobalValue::GUID> &InlinedGUIDs,
305 bool tryPromoteAndInlineCandidate(
310 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
311 std::optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
312 bool getExternalInlineAdvisorShouldInline(CallBase &CB);
313 InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
314 bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
316 tryInlineCandidate(InlineCandidate &Candidate,
319 inlineHotFunctionsWithPriority(
Function &
F,
320 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
322 bool shouldInlineColdCallee(CallBase &CallInst);
323 void emitOptimizationRemarksForInlineCandidates(
324 const SmallVectorImpl<CallBase *> &Candidates,
const Function &
F,
326 void promoteMergeNotInlinedContextSamples(
327 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
329 std::vector<Function *> buildFunctionOrder(
Module &M, LazyCallGraph &CG);
330 std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(
Module &M);
331 void generateMDProfMetadata(
Function &
F);
332 bool rejectHighStalenessProfile(
Module &M, ProfileSummaryInfo *PSI,
333 const SampleProfileMap &Profiles);
334 void removePseudoProbeInstsDiscriminator(
Module &M);
340 HashKeyMap<DenseMap, FunctionId, Function *> SymbolMap;
347 HashKeyMap<DenseMap, FunctionId, SmallVector<Function *, 1>> MemProfClones;
351 HashKeyMap<DenseMap, FunctionId, FunctionId> FuncNameToProfNameMap;
353 std::function<AssumptionCache &(
Function &)> GetAC;
354 std::function<TargetTransformInfo &(
Function &)> GetTTI;
355 std::function<
const TargetLibraryInfo &(
Function &)> GetTLI;
359 std::unique_ptr<SampleContextTracker> ContextTracker;
367 const std::string AnnotatedPassName;
371 std::shared_ptr<ProfileSymbolList> PSL;
376 struct NotInlinedProfileInfo {
379 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
383 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
390 bool ProfAccForSymsInList;
392 bool DisableSampleProfileInlining;
394 bool UseFlattenedProfile;
397 std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
400 std::unique_ptr<SampleProfileMatcher> MatchingManager;
403 const char *getAnnotatedRemarkPassName()
const {
404 return AnnotatedPassName.c_str();
411inline bool SampleProfileInference<Function>::isExit(
const BasicBlock *BB) {
416inline void SampleProfileInference<Function>::findUnlikelyJumps(
417 const std::vector<const BasicBlockT *> &BasicBlocks,
419 for (
auto &Jump :
Func.Jumps) {
420 const auto *BB = BasicBlocks[Jump.Source];
421 const auto *Succ = BasicBlocks[Jump.Target];
425 const auto &Succs = Successors[BB];
426 if (Succs.size() == 2 && Succs.back() == Succ) {
428 Jump.IsUnlikely =
true;
435 Jump.IsUnlikely =
true;
456 return getProbeWeight(Inst);
460 return std::error_code();
466 return std::error_code();
476 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
479 return getInstWeightImpl(Inst);
494const FunctionSamples *
495SampleProfileLoader::findCalleeFunctionSamples(
const CallBase &Inst)
const {
501 StringRef CalleeName;
503 CalleeName =
Callee->getName();
506 return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
508 const FunctionSamples *
FS = findFunctionSamples(Inst);
513 CalleeName, Reader->getRemapper(),
514 &FuncNameToProfNameMap);
520std::vector<const FunctionSamples *>
521SampleProfileLoader::findIndirectCallFunctionSamples(
522 const Instruction &Inst,
uint64_t &Sum)
const {
524 std::vector<const FunctionSamples *>
R;
530 auto FSCompare = [](
const FunctionSamples *
L,
const FunctionSamples *
R) {
531 assert(L && R &&
"Expect non-null FunctionSamples");
532 if (
L->getHeadSamplesEstimate() !=
R->getHeadSamplesEstimate())
533 return L->getHeadSamplesEstimate() >
R->getHeadSamplesEstimate();
534 return L->getGUID() <
R->getGUID();
539 ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
540 if (CalleeSamples.empty())
546 for (
const auto *
const FS : CalleeSamples) {
547 Sum +=
FS->getHeadSamplesEstimate();
554 const FunctionSamples *
FS = findFunctionSamples(Inst);
560 if (
auto T =
FS->findCallTargetMapAt(CallSite))
561 for (
const auto &T_C : *
T)
566 for (
const auto &NameFS : *M) {
567 Sum += NameFS.second.getHeadSamplesEstimate();
568 R.push_back(&NameFS.second);
575const FunctionSamples *
576SampleProfileLoader::findFunctionSamples(
const Instruction &Inst)
const {
587 auto it = DILocation2SampleMap.try_emplace(DIL,
nullptr);
590 it.first->second = ContextTracker->getContextSamplesFor(DIL);
592 it.first->second = Samples->findFunctionSamples(
593 DIL, Reader->getRemapper(), &FuncNameToProfNameMap);
595 return it.first->second;
609 Opts.sample_profile_icp_max_prom,
613 if (ValueData.empty())
616 unsigned NumPromoted = 0;
617 for (
const auto &
V : ValueData) {
628 if (NumPromoted == Opts.sample_profile_icp_max_prom)
648 if (Opts.sample_profile_icp_max_prom == 0)
654 Opts.sample_profile_icp_max_prom, OldSum,
true);
660 "If sum is 0, assume only one element in CallTargets "
661 "with count being NOMORE_ICP_MAGICNUM");
663 for (
const auto &
V : ValueData)
664 ValueCountMap[
V.Value] =
V.Count;
670 OldSum -= Pair.first->second;
677 for (
const auto &
V : ValueData) {
679 ValueCountMap[
V.Value] =
V.Count;
682 for (
const auto &
Data : CallTargets) {
689 assert(Sum >=
Data.Count &&
"Sum should never be less than Data.Count");
695 for (
const auto &ValueCount : ValueCountMap) {
697 InstrProfValueData{ValueCount.first, ValueCount.second});
701 [](
const InstrProfValueData &L,
const InstrProfValueData &R) {
702 return std::tie(L.Count, L.Value) > std::tie(R.Count, R.Value);
706 std::min(NewCallTargets.
size(),
707 static_cast<size_t>(Opts.sample_profile_icp_max_prom));
709 NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
722bool SampleProfileLoader::tryPromoteAndInlineCandidate(
726 if (DisableSampleProfileInlining)
731 if (Opts.sample_profile_icp_max_prom == 0)
733 auto CalleeFunctionName = Candidate.CalleeSamples->
getFunction();
734 auto R = SymbolMap.find(CalleeFunctionName);
735 if (R == SymbolMap.end() || !
R->second)
738 auto &CI = *Candidate.CallInstr;
742 const char *Reason =
"Callee function not available";
749 if (!
R->second->isDeclaration() &&
R->second->getSubprogram() &&
750 R->second->hasFnAttribute(
"use-sample-profile") &&
755 Function::getGUIDAssumingExternalLinkage(
R->second->getName()),
760 CI,
R->second, Candidate.CallsiteCount, Sum,
false, ORE);
762 Sum -= Candidate.CallsiteCount;
775 Candidate.CallInstr = DI;
777 bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
782 *DI,
static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
790 Candidate.CallInstr->
getName())<<
" because "
796bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
797 if (!ProfileSizeInline)
805 GetTTI(*CallInst.
getCaller()), GetAC, GetTLI);
816void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
817 const SmallVectorImpl<CallBase *> &Candidates,
const Function &
F,
819 for (
auto *
I : Candidates) {
820 Function *CalledFunction =
I->getCalledFunction();
821 if (CalledFunction) {
822 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
823 "InlineAttempt",
I->getDebugLoc(),
825 <<
"previous inlining reattempted for "
826 << (
Hot ?
"hotness: '" :
"size: '")
827 <<
ore::NV(
"Callee", CalledFunction) <<
"' into '"
833void SampleProfileLoader::findExternalInlineCandidate(
834 CallBase *CB,
const FunctionSamples *Samples,
835 DenseSet<GlobalValue::GUID> &InlinedGUIDs,
uint64_t Threshold) {
840 bool IncludeLocalTargets = Opts.sample_profile_preserve_deferred_inlines &&
845 if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
849 InlinedGUIDs.
insert(Function::getGUIDAssumingExternalLinkage(
869 if (UsePreInlinerDecision)
872 IncludeLocalTargets);
876 ContextTrieNode *
Caller = ContextTracker->getContextNodeForProfile(Samples);
877 std::queue<ContextTrieNode *> CalleeList;
878 CalleeList.push(Caller);
879 while (!CalleeList.empty()) {
880 ContextTrieNode *
Node = CalleeList.front();
882 FunctionSamples *CalleeSample =
Node->getFunctionSamples();
891 UsePreInlinerDecision &&
899 InlinedGUIDs, SymbolMap, CalleeSample->
getFunction(),
905 for (
const auto &TS : BS.second.getCallTargets())
906 if (TS.second > Threshold)
908 IncludeLocalTargets);
914 for (
auto &Child :
Node->getAllChildContext()) {
915 ContextTrieNode *CalleeNode = &Child.second;
916 CalleeList.push(CalleeNode);
943bool SampleProfileLoader::inlineHotFunctions(
944 Function &
F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
947 assert((!ProfAccForSymsInList ||
948 (!Opts.profile_sample_accurate &&
949 !
F.hasFnAttribute(
"profile-sample-accurate"))) &&
950 "ProfAccForSymsInList should be false when profile-sample-accurate "
953 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
955 bool LocalChanged =
true;
956 while (LocalChanged) {
957 LocalChanged =
false;
964 const FunctionSamples *
FS =
nullptr;
967 if ((FS = findCalleeFunctionSamples(*CB))) {
969 "GUIDToFuncNameMap has to be populated");
971 if (
FS->getHeadSamplesEstimate() > 0 ||
973 LocalNotInlinedCallSites.
insert({CB,
FS});
976 else if (shouldInlineColdCallee(*CB))
978 }
else if (getExternalInlineAdvisorShouldInline(*CB)) {
984 if (
Hot || ExternalInlineAdvisor) {
986 emitOptimizationRemarksForInlineCandidates(AllCandidates,
F,
true);
989 emitOptimizationRemarksForInlineCandidates(ColdCandidates,
F,
false);
992 for (CallBase *
I : CIS) {
993 Function *CalledFunction =
I->getCalledFunction();
994 InlineCandidate Candidate = {
I, LocalNotInlinedCallSites.
lookup(
I),
998 if (CalledFunction == &
F)
1000 if (
I->isIndirectCall()) {
1002 for (
const auto *FS : findIndirectCallFunctionSamples(*
I, Sum)) {
1004 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1005 findExternalInlineCandidate(
I, FS, InlinedGUIDs,
1006 PSI->getOrCompHotCountThreshold());
1012 Candidate = {
I,
FS,
FS->getHeadSamplesEstimate(), 1.0};
1013 if (tryPromoteAndInlineCandidate(
F, Candidate, SumOrigin, Sum)) {
1014 LocalNotInlinedCallSites.
erase(
I);
1015 LocalChanged =
true;
1018 }
else if (CalledFunction && CalledFunction->
getSubprogram() &&
1020 if (tryInlineCandidate(Candidate)) {
1021 LocalNotInlinedCallSites.
erase(
I);
1022 LocalChanged =
true;
1024 }
else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1025 findExternalInlineCandidate(
I, findCalleeFunctionSamples(*
I),
1027 PSI->getOrCompHotCountThreshold());
1036 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites,
F);
1040bool SampleProfileLoader::tryInlineCandidate(
1044 if (DisableSampleProfileInlining)
1047 CallBase &CB = *Candidate.CallInstr;
1049 assert(CalledFunction &&
"Expect a callee with definition");
1053 InlineCost
Cost = shouldInlineCandidate(Candidate);
1054 if (
Cost.isNever()) {
1055 ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1056 "InlineFail", DLoc, BB)
1057 <<
"incompatible inlining");
1064 InlineFunctionInfo IFI(GetAC);
1065 IFI.UpdateProfile =
false;
1068 if (!
IR.isSuccess())
1073 Cost,
true, getAnnotatedRemarkPassName());
1076 if (InlinedCallSites) {
1077 InlinedCallSites->
clear();
1082 ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1092 if (Candidate.CallsiteDistribution < 1) {
1093 for (
auto &
I : IFI.InlinedCallSites) {
1096 Candidate.CallsiteDistribution);
1098 NumDuplicatedInlinesite++;
1104bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1106 assert(CB &&
"Expect non-null call instruction");
1112 const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1115 if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
1119 if (std::optional<PseudoProbe> Probe =
extractProbe(*CB))
1120 Factor = Probe->Factor;
1124 *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1128std::optional<InlineCost>
1129SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
1130 std::unique_ptr<InlineAdvice> Advice =
nullptr;
1131 if (ExternalInlineAdvisor) {
1132 Advice = ExternalInlineAdvisor->getAdvice(CB);
1134 if (!Advice->isInliningRecommended()) {
1135 Advice->recordUnattemptedInlining();
1138 Advice->recordInlining();
1146bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
1147 std::optional<InlineCost>
Cost = getExternalInlineAdvisorCost(CB);
1152SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1153 if (std::optional<InlineCost> ReplayCost =
1154 getExternalInlineAdvisorCost(*Candidate.CallInstr))
1159 if (CallsitePrioritizedInline) {
1160 if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1162 else if (!ProfileSizeInline)
1168 assert(Callee &&
"Expect a definition for inline candidate of direct call");
1181 GetTTI(*Caller), GetAC, GetTLI);
1184 if (
Cost.isNever() ||
Cost.isAlways())
1196 if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1209 if (!CallsitePrioritizedInline) {
1218bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1219 Function &
F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1222 assert((!ProfAccForSymsInList ||
1223 (!Opts.profile_sample_accurate &&
1224 !
F.hasFnAttribute(
"profile-sample-accurate"))) &&
1225 "ProfAccForSymsInList should be false when profile-sample-accurate "
1230 CandidateQueue CQueue;
1231 InlineCandidate NewCandidate;
1232 for (
auto &BB :
F) {
1234 if (getInlineCandidate(&NewCandidate, &CB))
1235 CQueue.push(NewCandidate);
1244 "Max inline size limit should not be smaller than min inline size "
1246 unsigned SizeLimit =
F.getInstructionCount() * InlineOpts.
GrowthLimit;
1247 SizeLimit = std::min(SizeLimit, InlineOpts.
LimitMax);
1248 SizeLimit = std::max(SizeLimit, InlineOpts.
LimitMin);
1249 if (ExternalInlineAdvisor)
1250 SizeLimit = std::numeric_limits<unsigned>::max();
1252 MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1256 while (!CQueue.empty() &&
F.getInstructionCount() < SizeLimit) {
1257 InlineCandidate Candidate = CQueue.top();
1259 CallBase *
I = Candidate.CallInstr;
1260 Function *CalledFunction =
I->getCalledFunction();
1262 if (CalledFunction == &
F)
1264 if (
I->isIndirectCall()) {
1266 auto CalleeSamples = findIndirectCallFunctionSamples(*
I, Sum);
1268 Sum *= Candidate.CallsiteDistribution;
1269 unsigned ICPCount = 0;
1270 for (
const auto *FS : CalleeSamples) {
1272 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1273 findExternalInlineCandidate(
I, FS, InlinedGUIDs,
1274 PSI->getOrCompHotCountThreshold());
1278 FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
1283 if (ICPCount >= Opts.sample_profile_icp_relative_hotness_skip &&
1284 EntryCountDistributed * 100 <
1285 SumOrigin * Opts.sample_profile_icp_relative_hotness)
1294 if (!PSI->isHotCount(EntryCountDistributed))
1299 Candidate = {
I,
FS, EntryCountDistributed,
1300 Candidate.CallsiteDistribution};
1301 if (tryPromoteAndInlineCandidate(
F, Candidate, SumOrigin, Sum,
1302 &InlinedCallSites)) {
1303 for (
auto *CB : InlinedCallSites) {
1304 if (getInlineCandidate(&NewCandidate, CB))
1305 CQueue.emplace(NewCandidate);
1309 }
else if (!ContextTracker) {
1310 LocalNotInlinedCallSites.
insert({
I,
FS});
1313 }
else if (CalledFunction && CalledFunction->
getSubprogram() &&
1316 if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1317 for (
auto *CB : InlinedCallSites) {
1318 if (getInlineCandidate(&NewCandidate, CB))
1319 CQueue.emplace(NewCandidate);
1322 }
else if (!ContextTracker) {
1323 LocalNotInlinedCallSites.
insert({
I, Candidate.CalleeSamples});
1325 }
else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1326 findExternalInlineCandidate(
I, findCalleeFunctionSamples(*
I),
1328 PSI->getOrCompHotCountThreshold());
1332 if (!CQueue.empty()) {
1333 if (SizeLimit == InlineOpts.
LimitMax)
1334 ++NumCSInlinedHitMaxLimit;
1335 else if (SizeLimit == InlineOpts.
LimitMin)
1336 ++NumCSInlinedHitMinLimit;
1338 ++NumCSInlinedHitGrowthLimit;
1344 promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites,
F);
1348void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1349 MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
1352 for (
const auto &Pair : NonInlinedCallSites) {
1353 CallBase *
I = Pair.first;
1355 if (!Callee ||
Callee->isDeclaration())
1359 OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
"NotInline",
1360 I->getDebugLoc(),
I->getParent())
1361 <<
"previous inlining not repeated: '" <<
ore::NV(
"Callee", Callee)
1362 <<
"' into '" <<
ore::NV(
"Caller", &
F) <<
"'");
1365 const FunctionSamples *
FS = Pair.second;
1366 if (
FS->getTotalSamples() == 0 &&
FS->getHeadSamplesEstimate() == 0) {
1374 if (ProfileMergeInlinee) {
1380 if (
FS->getHeadSamples() == 0) {
1383 const_cast<FunctionSamples *
>(
FS)->addHeadSamples(
1384 FS->getHeadSamplesEstimate());
1389 FunctionSamples *OutlineFS = Reader->getSamplesFor(*Callee);
1393 OutlineFS = &OutlineFunctionSamples[
1395 OutlineFS->
merge(*FS, 1);
1401 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1402 pair.first->second.entryCount +=
FS->getHeadSamplesEstimate();
1413 InstrProfValueData{
I.first.getHashCode(),
I.second});
1420void SampleProfileLoader::generateMDProfMetadata(
Function &
F) {
1423 LLVM_DEBUG(
dbgs() <<
"\nPropagation complete. Setting branch weights\n");
1424 LLVMContext &Ctx =
F.getContext();
1426 for (
auto &BI :
F) {
1429 if (BlockWeights[BB]) {
1430 for (
auto &
I : *BB) {
1437 const DILocation *DIL = DLoc;
1438 const FunctionSamples *
FS = findFunctionSamples(
I);
1442 ErrorOr<SampleRecord::CallTargetMap>
T =
1443 FS->findCallTargetMapAt(CallSite);
1444 if (!
T ||
T.get().empty())
1451 if (Probe->Factor < 1)
1458 for (
const auto &
C :
T.get())
1465 FS->findFunctionSamplesMapAt(CallSite)) {
1466 for (
const auto &NameFS : *M)
1467 Sum += NameFS.second.getHeadSamplesEstimate();
1472 else if (Opts.overwrite_existing_weights)
1473 I.setMetadata(LLVMContext::MD_prof,
nullptr);
1476 I, ArrayRef<uint32_t>{
static_cast<uint32_t
>(BlockWeights[BB])},
1480 }
else if (Opts.overwrite_existing_weights ||
1481 Opts.profile_sample_block_accurate) {
1484 for (
auto &
I : *BB) {
1487 I.setMetadata(LLVMContext::MD_prof,
nullptr);
1505 << ((BranchLoc) ? Twine(BranchLoc.
getLine())
1506 : Twine(
"<UNKNOWN LOCATION>"))
1508 SmallVector<uint32_t, 4> Weights;
1509 uint32_t MaxWeight = 0;
1514 DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
1515 std::vector<uint64_t> EdgeIndex;
1520 EdgeIndex[
I] = EdgeMultiplicity[Succ];
1521 EdgeMultiplicity[Succ]++;
1526 Edge E = std::make_pair(BB, Succ);
1532 if (Weight > std::numeric_limits<uint32_t>::max()) {
1534 Weight = std::numeric_limits<uint32_t>::max();
1539 Weights.
push_back(
static_cast<uint32_t
>(
1540 Weight == std::numeric_limits<uint32_t>::max() ? Weight
1545 uint64_t W = Weight / EdgeMultiplicity[Succ];
1547 if (EdgeIndex[
I] < Weight % EdgeMultiplicity[Succ])
1549 Weights.
push_back(
static_cast<uint32_t
>(W));
1552 if (Weight > MaxWeight) {
1554 MaxDestInst = &*Succ->getFirstNonPHIOrLifetime();
1571 Opts.overwrite_existing_weights)) {
1575 return OptimizationRemark(
DEBUG_TYPE,
"PopularDest", MaxDestInst)
1576 <<
"most popular destination for conditional branches at "
1577 <<
ore::NV(
"CondBranchesLoc", BranchLoc);
1580 if (Opts.overwrite_existing_weights) {
1596bool SampleProfileLoader::emitAnnotations(
Function &
F) {
1601 if (!ProbeManager->getDesc(
F))
1602 dbgs() <<
"Probe descriptor missing for Function " <<
F.getName()
1606 if (ProbeManager->profileIsValid(
F, *Samples)) {
1607 ++NumMatchedProfile;
1609 ++NumMismatchedProfile;
1611 dbgs() <<
"Profile is invalid due to CFG mismatch for Function "
1612 <<
F.getName() <<
"\n");
1613 if (!SalvageStaleProfile)
1617 if (getFunctionLoc(
F) == 0)
1621 <<
F.getName() <<
": " << getFunctionLoc(
F) <<
"\n");
1624 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1625 if (CallsitePrioritizedInline)
1626 Changed |= inlineHotFunctionsWithPriority(
F, InlinedGUIDs);
1628 Changed |= inlineHotFunctions(
F, InlinedGUIDs);
1630 Changed |= computeAndPropagateWeights(
F, InlinedGUIDs);
1633 generateMDProfMetadata(
F);
1635 emitCoverageRemarks(
F);
1639std::unique_ptr<ProfiledCallGraph>
1640SampleProfileLoader::buildProfiledCallGraph(
Module &M) {
1641 std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1643 ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1645 ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1653 ProfiledCG->addProfiledFunction(
1660std::vector<Function *>
1661SampleProfileLoader::buildFunctionOrder(
Module &M, LazyCallGraph &CG) {
1662 std::vector<Function *> FunctionOrderList;
1663 FunctionOrderList.reserve(
M.size());
1665 if (!Opts.sample_profile_top_down_load && Opts.use_profiled_call_graph)
1666 errs() <<
"WARNING: -use-profiled-call-graph ignored, should be used "
1667 "together with -sample-profile-top-down-load.\n";
1669 if (!Opts.sample_profile_top_down_load) {
1670 if (ProfileMergeInlinee) {
1676 ProfileMergeInlinee =
false;
1681 FunctionOrderList.push_back(&
F);
1682 return FunctionOrderList;
1685 if (Opts.use_profiled_call_graph) {
1734 std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(M);
1735 scc_iterator<ProfiledCallGraph *> CGI =
scc_begin(ProfiledCG.get());
1740 scc_member_iterator<ProfiledCallGraph *>
SI(*CGI);
1743 for (
auto *Node :
Range) {
1748 if (
auto It = MemProfClones.find(
Node->Name); It != MemProfClones.end())
1750 FunctionOrderList.push_back(Clone);
1753 FunctionOrderList.push_back(
F);
1757 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1762 dbgs() <<
"Function processing order:\n";
1763 for (
auto F : FunctionOrderList) {
1764 dbgs() <<
F->getName() <<
"\n";
1768 return FunctionOrderList;
1771bool SampleProfileLoader::doInitialization(
Module &M,
1773 auto &Ctx =
M.getContext();
1778 Filename, Ctx, *FS, FSDiscriminatorPass::Base, RemappingFilename);
1779 if (std::error_code EC = ReaderOrErr.getError()) {
1780 std::string
Msg =
"Could not open profile: " +
EC.message();
1784 Reader = std::move(ReaderOrErr.get());
1785 Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1788 Reader->setModule(&M);
1789 if (std::error_code EC = Reader->read()) {
1790 std::string
Msg =
"profile reading failed: " +
EC.message();
1795 PSL = Reader->getProfileSymbolList();
1797 DisableSampleProfileInlining =
1798 !
valueOr(Opts.sample_loader_inlining, !DisableSampleProfileInlining);
1800 if (UseFlattenedProfile)
1802 Reader->profileIsCS());
1805 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL &&
1806 !Opts.profile_sample_accurate;
1807 if (ProfAccForSymsInList)
1808 CoverageTracker.setProfAccForSymsInList(
true);
1810 if (
FAM && !Opts.sample_profile_inline_replay.
empty()) {
1812 M, *
FAM, Ctx,
nullptr,
1813 ReplayInlinerSettings{Opts.sample_profile_inline_replay,
1814 Opts.sample_profile_inline_replay_scope,
1815 Opts.sample_profile_inline_replay_fallback,
1816 {Opts.sample_profile_inline_replay_format}},
1818 InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
1822 if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
1823 Reader->profileIsProbeBased()) {
1831 ProfileSizeInline =
valueOr(Opts.sample_profile_inline_size,
true);
1832 CallsitePrioritizedInline =
1833 valueOr(Opts.sample_profile_prioritized_inline,
true);
1835 AllowRecursiveInline =
valueOr(Opts.sample_profile_recursive_inline,
true);
1837 if (Reader->profileIsPreInlined())
1838 UsePreInlinerDecision =
valueOr(Opts.sample_profile_use_preinliner,
true);
1845 if (Reader->profileIsProbeBased()) {
1846 SalvageStaleProfile =
valueOr(Opts.salvage_stale_profile,
true);
1847 SalvageUnusedProfile =
valueOr(Opts.salvage_unused_profile,
true);
1850 if (!Reader->profileIsCS()) {
1855 InlineOpts.
LimitMin = Opts.sample_profile_inline_limit_min.value_or(
1856 std::numeric_limits<unsigned>::max());
1858 std::max(Opts.sample_profile_inline_limit_max.value_or(
1859 std::numeric_limits<unsigned>::max()),
1864 if (Reader->profileIsCS()) {
1866 ContextTracker = std::make_unique<SampleContextTracker>(
1867 Reader->getProfiles(), &GUIDToFuncNameMap);
1871 if (Reader->profileIsProbeBased()) {
1872 ProbeManager = std::make_unique<PseudoProbeManager>(M);
1873 if (!ProbeManager->moduleIsProbed(M)) {
1875 "Pseudo-probe-based profile requires SampleProfileProbePass";
1876 Ctx.
diagnose(DiagnosticInfoSampleProfile(
M.getModuleIdentifier(),
Msg,
1882 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
1883 SalvageStaleProfile) {
1884 MatchingManager = std::make_unique<SampleProfileMatcher>(
1885 Opts, M, *Reader, CG, ProbeManager.get(), LTOPhase, SymbolMap, PSL,
1886 FuncNameToProfNameMap, SalvageStaleProfile, SalvageUnusedProfile);
1902bool SampleProfileLoader::rejectHighStalenessProfile(
1903 Module &M, ProfileSummaryInfo *PSI,
const SampleProfileMap &Profiles) {
1905 "Only support for probe-based profile");
1908 for (
const auto &
I : Profiles) {
1909 const auto &
FS =
I.second;
1910 const auto *FuncDesc = ProbeManager->getDesc(
FS.getGUID());
1916 FS.getTotalSamples()))
1920 if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS) &&
1921 !ProbeManager->probeFromWeakSymbol(
FS.getGUID()))
1922 NumMismatchedFunc++;
1926 if (TotalHotFunc < Opts.min_functions_for_staleness_error)
1930 if (NumMismatchedFunc * 100 >=
1931 TotalHotFunc * Opts.percent_mismatch_for_staleness_error) {
1932 auto &Ctx =
M.getContext();
1934 "The input profile significantly mismatches current source code. "
1935 "Please recollect profile to avoid performance regression.";
1936 Ctx.
diagnose(DiagnosticInfoSampleProfile(
M.getModuleIdentifier(),
Msg));
1942void SampleProfileLoader::removePseudoProbeInstsDiscriminator(
Module &M) {
1944 std::vector<Instruction *> InstsToDel;
1945 for (
auto &BB :
F) {
1946 for (
auto &
I : BB) {
1948 InstsToDel.push_back(&
I);
1950 if (
const DILocation *DIL =
I.getDebugLoc().get()) {
1954 std::optional<uint32_t> DwarfDiscriminator =
1963 for (
auto *
I : InstsToDel)
1964 I->eraseFromParent();
1969 ProfileSummaryInfo *_PSI) {
1970 GUIDToFuncNameMapper
Mapper(M, *Reader, GUIDToFuncNameMap);
1973 if (
M.getProfileSummary(
false) ==
nullptr) {
1974 M.setProfileSummary(Reader->getSummary().getMD(
M.getContext()),
1980 rejectHighStalenessProfile(M, PSI, Reader->getProfiles()))
1983 auto Remapper = Reader->getRemapper();
1985 for (
const auto &N_F :
M.getValueSymbolTable()) {
1986 StringRef OrigName = N_F.getKey();
1988 if (
F ==
nullptr || OrigName.
empty())
1990 SymbolMap[FunctionId(OrigName)] =
F;
1997 if (OrigName != NewName && !NewName.
empty()) {
1998 auto r = SymbolMap.emplace(FunctionId(NewName),
F);
2004 r.first->second =
nullptr;
2009 if (
auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2010 if (*MapName != OrigName && !MapName->empty())
2011 SymbolMap.emplace(FunctionId(*MapName),
F);
2024 if (
Name.empty() || Name ==
F.getName())
2027 if (
auto MapName = Remapper->lookUpNameInProfile(Name)) {
2028 if (!MapName->empty())
2032 MemProfClones[FunctionId(Name)].push_back(&
F);
2036 if (Opts.report_profile_staleness || Opts.persist_profile_staleness ||
2037 SalvageStaleProfile) {
2038 MatchingManager->runOnModule();
2039 MatchingManager->clearMatchingData();
2041 assert(SymbolMap.count(FunctionId()) == 0 &&
2042 "No empty StringRef should be added in SymbolMap");
2043 assert((SalvageUnusedProfile || FuncNameToProfNameMap.empty()) &&
2044 "FuncNameToProfNameMap is not empty when --salvage-unused-profile is "
2047 bool retval =
false;
2048 for (
auto *
F : buildFunctionOrder(M, CG)) {
2050 clearFunctionData();
2056 for (
const auto &[Fn, Info] : notInlinedCallInfo)
2059 if (Opts.sample_profile_remove_probe &&
2061 removePseudoProbeInstsDiscriminator(M);
2063 M.eraseNamedMetadata(FuncInfo);
2069bool SampleProfileLoader::runOnFunction(
Function &
F,
2071 LLVM_DEBUG(
dbgs() <<
"\n\nProcessing Function " <<
F.getName() <<
"\n");
2072 DILocation2SampleMap.clear();
2079 ProfAccForSymsInList = Opts.profile_accurate_for_symsinlist && PSL;
2080 if (Opts.profile_sample_accurate ||
2081 F.hasFnAttribute(
"profile-sample-accurate")) {
2084 initialEntryCount = 0;
2087 ProfAccForSymsInList =
false;
2089 CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
2095 if (ProfAccForSymsInList) {
2097 if (PSL->contains(
F.getName()))
2098 initialEntryCount = 0;
2113 Function::getGUIDAssumingExternalLinkage(CanonName))
2114 : Reader->contains(CanonName))
2115 initialEntryCount = -1;
2120 if (!
F.getEntryCount())
2121 F.setEntryCount(initialEntryCount);
2127 Samples = ContextTracker->getBaseSamplesFor(
F);
2129 Samples = Reader->getSamplesFor(
F);
2134 auto It = OutlineFunctionSamples.find(FunctionId(CanonName));
2135 if (It != OutlineFunctionSamples.end()) {
2136 Samples = &It->second;
2137 }
else if (
auto Remapper = Reader->getRemapper()) {
2138 if (
auto RemppedName = Remapper->lookUpNameInProfile(CanonName)) {
2139 It = OutlineFunctionSamples.find(FunctionId(*RemppedName));
2140 if (It != OutlineFunctionSamples.end())
2141 Samples = &It->second;
2147 if (Samples && !Samples->
empty())
2148 return emitAnnotations(
F);
2158 const auto &Opts =
C.get<IPOOptions>();
2160 Opts.sample_profile_hot_inline_threshold.value_or(
2163 Opts.sample_profile_cold_inline_threshold.value_or(
2166 Opts.sample_profile_inline_growth_limit.value_or(Defaults.
GrowthLimit);
2168 Opts.sample_profile_inline_limit_min.value_or(Defaults.
LimitMin);
2170 Opts.sample_profile_inline_limit_max.value_or(Defaults.
LimitMax);
2179 bool UseFlattenedProfile)
2180 : ProfileFileName(File), ProfileRemappingFileName(RemappingFile),
2181 LTOPhase(LTOPhase), FS(
std::
move(FS)),
2182 DisableSampleProfileInlining(DisableSampleProfileInlining),
2183 UseFlattenedProfile(UseFlattenedProfile) {}
2205 SampleProfileLoader SampleLoader(
2207 ProfileFileName.empty() ? Opts.sample_profile_file
2209 ProfileRemappingFileName.
empty() ? Opts.sample_profile_remapping_file
2211 LTOPhase, FS, GetAssumptionCache, GetTTI, GetTLI, CG,
2212 DisableSampleProfileInlining, UseFlattenedProfile);
2213 if (!SampleLoader.doInitialization(M, &
FAM))
2217 if (!SampleLoader.runOnModule(M, AM, PSI))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static bool runOnFunction(Function &F, bool PostInlining)
Provides ErrorOr<T> smart pointer.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static LVReader * CurrentReader
Implements a lazy call graph analysis and related passes for the new pass manager.
Legalize the Machine IR a function s Machine IR
Machine Check Debug Module
static const Function * getCalledFunction(const MachineInstr &MI)
This file implements a map that provides insertion order iteration.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
static constexpr StringLiteral Filename
FunctionAnalysisManager FAM
This file defines the PriorityQueue class.
This file contains the declarations for profiling metadata utility functions.
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
std::pair< BasicBlock *, BasicBlock * > Edge
This file provides the interface for context-sensitive profile tracker used by CSSPGO.
This file provides the interface for the sampled PGO profile loader base implementation.
This file provides the utility functions for the sampled PGO loader base implementation.
This file provides the interface for SampleProfileMatcher.
This file provides the interface for the pseudo probe implementation for AutoFDO.
static void updateIDTMetaData(const IPOOptions &Opts, Instruction &Inst, const SmallVectorImpl< InstrProfValueData > &CallTargets, uint64_t Sum)
Update indirect call target profile metadata for Inst.
static bool doesHistoryAllowICP(const IPOOptions &Opts, const Instruction &Inst, StringRef Candidate)
Check whether the indirect call promotion history of Inst allows the promotion for Candidate.
static SmallVector< InstrProfValueData, 2 > GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M)
Returns the sorted CallTargetMap M by count in descending order.
This file provides the interface for the sampled PGO loader pass.
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)
Defines the virtual file system interface vfs::FileSystem.
bool empty() const
Returns true if the analysis manager has an empty results cache.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
const Function * getParent() const
Return the enclosing method, or null if none.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
static bool isPseudoProbeDiscriminator(unsigned Discriminator)
const DILocation * cloneWithDiscriminator(unsigned Discriminator) const
Returns a new DILocation with updated Discriminator.
LLVM_ABI unsigned getLine() const
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Represents either an error or a value T.
DISubprogram * getSubprogram() const
Get the attached subprogram.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
static InlineCost getNever(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
static InlineCost getAlways(const char *Reason, std::optional< CostBenefitPair > CostBenefit=std::nullopt)
static InlineCost get(int Cost, int Threshold, int StaticBonus=0)
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is an important class for using LLVM in a threaded context.
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
An analysis pass which computes the call graph for a module.
A lazily constructed view of the call graph of a module.
ValueT lookup(const KeyT &Key) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
A Module instance is used to store all the information related to an LLVM module.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
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.
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI void refresh(std::unique_ptr< ProfileSummary > &&Other=nullptr)
If a summary is provided as argument, use that.
LLVM_ABI bool isHotCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered hot with regard to a given hot percentile cutoff value.
void computeDominanceAndLoopInfo(FunctionT &F)
PostDominatorTreePtrT PDT
static LLVM_ABI SampleProfileInlineOptions getInlineOptions(const cl::LibraryOptionsContext &C, SampleProfileInlineOptions Defaults)
Return Defaults overridden by the inliner options given in C.
static LLVM_ABI StringRef getSampleProfileFile(const LLVMContext &C)
Return -sample-profile-file.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI SampleProfileLoaderPass(std::string File="", std::string RemappingFile="", ThinOrFullLTOPhase LTOPhase=ThinOrFullLTOPhase::None, IntrusiveRefCntPtr< vfs::FileSystem > FS=nullptr, bool DisableSampleProfileInlining=false, bool UseFlattenedProfile=false)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LLVM Value Representation.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
int getNumOccurrences() const
std::pair< iterator, bool > insert(const ValueT &V)
const ParentTy * getParent() const
Representation of the samples collected for a function.
void findInlinedFunctions(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, uint64_t Threshold, bool IncludeLocalTargets=false) const
Recursively collect import GUIDs from contexts with total samples greater than Threshold,...
static LLVM_ABI std::atomic< bool > UseMD5
Whether the profile uses MD5 to represent string.
FunctionId getFunction() const
Return the function name.
SampleContext & getContext() const LLVM_LIFETIME_BOUND
static StringRef getCanonicalFnName(const Function &F)
Return the canonical name for a function, taking into account suffix elision policy attributes.
static void addImportGUID(DenseSet< GlobalValue::GUID > &S, const HashKeyMap< DenseMap, FunctionId, Function * > &SymbolMap, FunctionId Name, bool IncludeLocal)
Add the import GUID of profiled function Name to S.
void setContextSynthetic()
static LLVM_ABI std::atomic< bool > ProfileIsProbeBased
const BodySampleMap & getBodySamples() const LLVM_LIFETIME_BOUND
Return all the samples collected in the body of the function.
uint64_t getTotalSamples() const
Return the total number of samples collected inside the function.
sampleprof_error merge(const FunctionSamples &Other, uint64_t Weight=1)
Merge the samples in Other into this one.
static LLVM_ABI std::atomic< bool > ProfileIsCS
static LLVM_ABI LineLocation getCallSiteIdentifier(const DILocation *DIL, bool ProfileIsFS=false)
Returns a unique call site identifier for a given debug location of a call instruction.
uint64_t getHeadSamplesEstimate() const
Return an estimate of the sample count of the function entry basic block.
uint64_t getGUID() const
Return the GUID of the context's name.
static void flattenProfile(SampleProfileMap &ProfileMap, bool ProfileIsCS=false)
bool hasAttribute(ContextAttributeMask A)
static LLVM_ABI ErrorOr< std::unique_ptr< SampleProfileReader > > create(StringRef Filename, LLVMContext &C, vfs::FileSystem &FS, FSDiscriminatorPass P=FSDiscriminatorPass::Base, StringRef RemapFilename="")
Create a sample profile reader appropriate to the file format.
static SortedCallTargetSet sortCallTargets(const CallTargetMap &Targets)
Sort call targets in descending order of call frequency.
static const CallTargetMap adjustCallTargets(const CallTargetMap &Targets, float DistributionFactor)
Prorate call targets by a distribution factor.
SortedVectorMap< FunctionId, uint64_t, 0 > CallTargetMap
bool isAtEnd() const
Direct loop termination test which is more efficient than comparison with end().
@ BasicBlock
Various leaf nodes.
LLVM_ABI void checkExpectAnnotations(const Instruction &I, ArrayRef< uint32_t > ExistingWeights, bool IsFrontend)
checkExpectAnnotations - compares PGO counters to the thresholds used for llvm.expect and warns if th...
DiagnosticInfoOptimizationBase::Argument NV
LLVM_ABI CallBase & promoteIndirectCall(CallBase &CB, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
NodeAddr< NodeBase * > Node
NodeAddr< FuncNode * > Func
static FunctionId getRepInFormat(StringRef Name)
Get the proper representation of a string according to whether the current Format uses MD5 to represe...
@ ContextDuplicatedIntoBase
std::map< FunctionId, FunctionSamples > FunctionSamplesMap
LLVM_ABI bool callsiteIsHot(const FunctionSamples *CallsiteFS, ProfileSummaryInfo *PSI, bool ProfAccForSymsInList)
Return true if the given callsite is hot wrt to hot cutoff threshold.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
static bool isIndirectCall(const MachineInstr &MI)
LLVM_ABI bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
bool succ_empty(const Instruction *I)
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
LLVM_ABI InlineParams getInlineParams(const LLVMContext &C)
Generate the parameters to tune the inline cost analysis based only on the commandline options.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
static void buildTopDownFuncOrder(LazyCallGraph &CG, std::vector< Function * > &FunctionOrderList)
LLVM_ABI InlineResult InlineFunction(CallBase &CB, InlineFunctionInfo &IFI, bool MergeAttributes=false, AAResults *CalleeAAR=nullptr, bool InsertLifetime=true, bool TrackInlineHistory=false, Function *ForwardVarArgsTo=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
This function inlines the called function into the basic block of the caller.
LLVM_ABI void setProbeDistributionFactor(Instruction &Inst, float Factor)
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
LLVM_ABI std::string AnnotateInlinePassName(InlineContext IC)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
LLVM_ABI cl::opt< bool > SampleProfileUseProfi
const IPOOptions & getIPOOptions(const LLVMContext &C)
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI llvm::cl::opt< bool > UseIterativeBFIInference
LLVM_ABI std::optional< PseudoProbe > extractProbe(const Instruction &Inst)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void emitInlinedIntoBasedOnCost(OptimizationRemarkEmitter &ORE, DebugLoc DLoc, const BasicBlock *Block, const Function &Callee, const Function &Caller, const InlineCost &IC, bool ForProfileContext=false, const char *PassName=nullptr)
Emit ORE message based in cost (default heuristic).
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI std::unique_ptr< InlineAdvisor > getReplayInlineAdvisor(Module &M, FunctionAnalysisManager &FAM, LLVMContext &Context, std::unique_ptr< InlineAdvisor > OriginalAdvisor, const ReplayInlinerSettings &ReplaySettings, bool EmitRemarks, InlineContext IC)
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_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void updateProfileCallee(Function *Callee, int64_t EntryDelta, const ValueMap< const Value *, WeakTrackingVH > *VMap=nullptr)
Updates profile information by adjusting the entry count by adding EntryDelta then scaling callsite i...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
bool isMemProfClone(const GlobalValue &GV)
Returns true if GV is a MemProf context-disambiguated clone.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
static bool skipProfileForFunction(const Function &F)
constexpr bool valueOr(BoolOrDefault X, bool Default)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
cl::opt< bool > EnableExtTspBlockPlacement
const uint64_t NOMORE_ICP_MAGICNUM
Magic number in the value profile metadata showing a target has been promoted for the instruction and...
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
constexpr const char * PseudoProbeDescMetadataName
Implement std::hash so that hash_code can be used in STL containers.
A wrapper of binary function with basic blocks and jumps.
std::optional< bool > AllowRecursiveCall
Indicate whether we allow inlining for recursive call.
std::optional< bool > ComputeFullInlineCost
Compute inline cost even when the cost has exceeded the threshold.
static std::optional< uint32_t > extractDwarfBaseDiscriminator(uint32_t Value)
The thresholds of the priority-based sample profile loader inliner.
int ColdCallSiteThreshold