1//===- ProfileSummaryInfo.cpp - Global profile summary information --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass that provides access to the global profile summary
10// information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/ProfileSummaryInfo.h"
15#include "AnalysisOptions.h"
16#include "llvm/Analysis/BlockFrequencyInfo.h"
17#include "llvm/IR/BasicBlock.h"
18#include "llvm/IR/Instructions.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/ProfileSummary.h"
21#include "llvm/InitializePasses.h"
22#include "llvm/ProfileData/ProfileCommon.h"
23#include <optional>
24using namespace llvm;
25
26ProfileSummaryInfo::ProfileSummaryInfo(const Module &M)
27 : Opts(getAnalysisOptions(M)), M(&M) {
28 refresh();
29}
30
31// The profile summary metadata may be attached either by the frontend or by
32// any backend passes (IR level instrumentation, for example). This method
33// checks if the Summary is null and if so checks if the summary metadata is now
34// available in the module and parses it to get the Summary object.
35void ProfileSummaryInfo::refresh(std::unique_ptr<ProfileSummary> &&Other) {
36 if (Other) {
37 Summary.swap(u&: Other);
38 return;
39 }
40 if (hasProfileSummary())
41 return;
42 // First try to get context sensitive ProfileSummary.
43 auto *SummaryMD = M->getProfileSummary(/* IsCS */ true);
44 if (SummaryMD)
45 Summary.reset(p: ProfileSummary::getFromMD(MD: SummaryMD));
46
47 if (!hasProfileSummary()) {
48 // This will actually return PSK_Instr or PSK_Sample summary.
49 SummaryMD = M->getProfileSummary(/* IsCS */ false);
50 if (SummaryMD)
51 Summary.reset(p: ProfileSummary::getFromMD(MD: SummaryMD));
52 }
53 if (!hasProfileSummary())
54 return;
55 computeThresholds();
56}
57
58std::optional<uint64_t>
59ProfileSummaryInfo::getProfileCount(const CallBase &Call,
60 BlockFrequencyInfo *BFI) const {
61 assert((isa<CallInst>(Call) || isa<InvokeInst>(Call)) &&
62 "We can only get profile count for call/invoke instruction.");
63 if (hasSampleProfile()) {
64 // In sample PGO mode, check if there is a profile metadata on the
65 // instruction. If it is present, determine hotness solely based on that,
66 // since the sampled entry count may not be accurate. If there is no
67 // annotated on the instruction, return std::nullopt.
68 uint64_t TotalCount;
69 if (Call.extractProfTotalWeight(TotalVal&: TotalCount))
70 return TotalCount;
71 return std::nullopt;
72 }
73 if (BFI)
74 return BFI->getBlockProfileCount(BB: Call.getParent());
75 return std::nullopt;
76}
77
78bool ProfileSummaryInfo::isFunctionHotnessUnknown(const Function &F) const {
79 assert(hasPartialSampleProfile() && "Expect partial sample profile");
80 return !F.getEntryCount();
81}
82
83/// Returns true if the function's entry is a cold. If it returns false, it
84/// either means it is not cold or it is unknown whether it is cold or not (for
85/// example, no profile data is available).
86bool ProfileSummaryInfo::isFunctionEntryCold(const Function *F) const {
87 if (!F)
88 return false;
89 // The hot attribute is a manual alternative to profile data, and takes
90 // precedence over it.
91 if (hasHotAttr(F))
92 return false;
93 if (F->hasFnAttribute(Kind: Attribute::Cold))
94 return true;
95 if (!hasProfileSummary())
96 return false;
97 auto FunctionCount = F->getEntryCount();
98 // FIXME: The heuristic used below for determining coldness is based on
99 // preliminary SPEC tuning for inliner. This will eventually be a
100 // convenience method that calls isHotCount.
101 return FunctionCount && isColdCount(C: *FunctionCount);
102}
103
104/// Compute the hot and cold thresholds.
105void ProfileSummaryInfo::computeThresholds() {
106 auto &DetailedSummary = Summary->getDetailedSummary();
107 auto &HotEntry = ProfileSummaryBuilder::getEntryForPercentile(
108 DS: DetailedSummary, Percentile: ProfileSummaryCutoffHot);
109 HotCountThreshold =
110 ProfileSummaryBuilder::getHotCountThreshold(DS: DetailedSummary);
111 ColdCountThreshold =
112 ProfileSummaryBuilder::getColdCountThreshold(DS: DetailedSummary);
113 // When the hot and cold thresholds are identical, we would classify
114 // a count value as both hot and cold since we are doing an inclusive check
115 // (see ::is{Hot|Cold}Count(). To avoid this undesirable overlap, ensure the
116 // thresholds are distinct.
117 if (HotCountThreshold == ColdCountThreshold) {
118 if (ColdCountThreshold > 0)
119 (*ColdCountThreshold)--;
120 else
121 (*HotCountThreshold)++;
122 }
123 assert(ColdCountThreshold < HotCountThreshold &&
124 "Cold count threshold should be less than hot count threshold!");
125 if (!hasPartialSampleProfile() ||
126 !Opts.scale_partial_sample_profile_working_set_size) {
127 HasHugeWorkingSetSize =
128 HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
129 HasLargeWorkingSetSize =
130 HotEntry.NumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
131 } else {
132 // Scale the working set size of the partial sample profile to reflect the
133 // size of the program being compiled.
134 double PartialProfileRatio = Summary->getPartialProfileRatio();
135 uint64_t ScaledHotEntryNumCounts = static_cast<uint64_t>(
136 HotEntry.NumCounts * PartialProfileRatio *
137 Opts.partial_sample_profile_working_set_size_scale_factor);
138 HasHugeWorkingSetSize =
139 ScaledHotEntryNumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
140 HasLargeWorkingSetSize =
141 ScaledHotEntryNumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
142 }
143}
144
145std::optional<uint64_t>
146ProfileSummaryInfo::computeThreshold(int PercentileCutoff) const {
147 if (!hasProfileSummary())
148 return std::nullopt;
149 auto [Iter, Inserted] = ThresholdCache.try_emplace(Key: PercentileCutoff);
150 if (!Inserted)
151 return Iter->second;
152 auto &DetailedSummary = Summary->getDetailedSummary();
153 auto &Entry = ProfileSummaryBuilder::getEntryForPercentile(DS: DetailedSummary,
154 Percentile: PercentileCutoff);
155 uint64_t CountThreshold = Entry.MinCount;
156 Iter->second = CountThreshold;
157 return CountThreshold;
158}
159
160bool ProfileSummaryInfo::hasHugeWorkingSetSize() const {
161 return HasHugeWorkingSetSize && *HasHugeWorkingSetSize;
162}
163
164bool ProfileSummaryInfo::hasLargeWorkingSetSize() const {
165 return HasLargeWorkingSetSize && *HasLargeWorkingSetSize;
166}
167
168bool ProfileSummaryInfo::isHotCount(uint64_t C) const {
169 return HotCountThreshold && C >= *HotCountThreshold;
170}
171
172bool ProfileSummaryInfo::isColdCount(uint64_t C) const {
173 return ColdCountThreshold && C <= *ColdCountThreshold;
174}
175
176template <bool isHot>
177bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff,
178 uint64_t C) const {
179 auto CountThreshold = computeThreshold(PercentileCutoff);
180 if (isHot)
181 return CountThreshold && C >= *CountThreshold;
182 else
183 return CountThreshold && C <= *CountThreshold;
184}
185
186bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff,
187 uint64_t C) const {
188 return isHotOrColdCountNthPercentile<true>(PercentileCutoff, C);
189}
190
191bool ProfileSummaryInfo::isColdCountNthPercentile(int PercentileCutoff,
192 uint64_t C) const {
193 return isHotOrColdCountNthPercentile<false>(PercentileCutoff, C);
194}
195
196uint64_t ProfileSummaryInfo::getOrCompHotCountThreshold() const {
197 return HotCountThreshold.value_or(UINT64_MAX);
198}
199
200uint64_t ProfileSummaryInfo::getOrCompColdCountThreshold() const {
201 return ColdCountThreshold.value_or(u: 0);
202}
203
204bool ProfileSummaryInfo::isHotCallSite(const CallBase &CB,
205 BlockFrequencyInfo *BFI) const {
206 auto C = getProfileCount(Call: CB, BFI);
207 return C && isHotCount(C: *C);
208}
209
210bool ProfileSummaryInfo::isColdCallSite(const CallBase &CB,
211 BlockFrequencyInfo *BFI) const {
212 auto C = getProfileCount(Call: CB, BFI);
213 if (C)
214 return isColdCount(C: *C);
215
216 // In SamplePGO, if the caller has been sampled, and there is no profile
217 // annotated on the callsite, we consider the callsite as cold.
218 return hasSampleProfile() && CB.getCaller()->hasProfileData();
219}
220
221bool ProfileSummaryInfo::hasPartialSampleProfile() const {
222 return hasProfileSummary() &&
223 Summary->getKind() == ProfileSummary::PSK_Sample &&
224 (Opts.partial_profile || Summary->isPartialProfile());
225}
226
227INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info",
228 "Profile summary info", false, true)
229
230ProfileSummaryInfoWrapperPass::ProfileSummaryInfoWrapperPass()
231 : ImmutablePass(ID) {}
232
233bool ProfileSummaryInfoWrapperPass::doInitialization(Module &M) {
234 PSI.reset(p: new ProfileSummaryInfo(M));
235 return false;
236}
237
238bool ProfileSummaryInfoWrapperPass::doFinalization(Module &M) {
239 PSI.reset();
240 return false;
241}
242
243AnalysisKey ProfileSummaryAnalysis::Key;
244ProfileSummaryInfo ProfileSummaryAnalysis::run(Module &M,
245 ModuleAnalysisManager &) {
246 return ProfileSummaryInfo(M);
247}
248
249PreservedAnalyses ProfileSummaryPrinterPass::run(Module &M,
250 ModuleAnalysisManager &AM) {
251 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(IR&: M);
252
253 OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
254 for (auto &F : M) {
255 OS << F.getName();
256 if (PSI.isFunctionEntryHot(F: &F))
257 OS << " :hot entry ";
258 else if (PSI.isFunctionEntryCold(F: &F))
259 OS << " :cold entry ";
260 OS << "\n";
261 }
262 return PreservedAnalyses::all();
263}
264
265char ProfileSummaryInfoWrapperPass::ID = 0;
266