LLVM  10.0.0
ProfileSummaryInfo.cpp
Go to the documentation of this file.
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 
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/Metadata.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/ProfileSummary.h"
21 #include "llvm/InitializePasses.h"
23 using namespace llvm;
24 
25 // The following two parameters determine the threshold for a count to be
26 // considered hot/cold. These two parameters are percentile values (multiplied
27 // by 10000). If the counts are sorted in descending order, the minimum count to
28 // reach ProfileSummaryCutoffHot gives the threshold to determine a hot count.
29 // Similarly, the minimum count to reach ProfileSummaryCutoffCold gives the
30 // threshold for determining cold count (everything <= this threshold is
31 // considered cold).
32 
34  "profile-summary-cutoff-hot", cl::Hidden, cl::init(990000), cl::ZeroOrMore,
35  cl::desc("A count is hot if it exceeds the minimum count to"
36  " reach this percentile of total counts."));
37 
39  "profile-summary-cutoff-cold", cl::Hidden, cl::init(999999), cl::ZeroOrMore,
40  cl::desc("A count is cold if it is below the minimum count"
41  " to reach this percentile of total counts."));
42 
44  "profile-summary-huge-working-set-size-threshold", cl::Hidden,
45  cl::init(15000), cl::ZeroOrMore,
46  cl::desc("The code working set size is considered huge if the number of"
47  " blocks required to reach the -profile-summary-cutoff-hot"
48  " percentile exceeds this count."));
49 
51  "profile-summary-large-working-set-size-threshold", cl::Hidden,
52  cl::init(12500), cl::ZeroOrMore,
53  cl::desc("The code working set size is considered large if the number of"
54  " blocks required to reach the -profile-summary-cutoff-hot"
55  " percentile exceeds this count."));
56 
57 // The next two options override the counts derived from summary computation and
58 // are useful for debugging purposes.
60  "profile-summary-hot-count", cl::ReallyHidden, cl::ZeroOrMore,
61  cl::desc("A fixed hot count that overrides the count derived from"
62  " profile-summary-cutoff-hot"));
63 
65  "profile-summary-cold-count", cl::ReallyHidden, cl::ZeroOrMore,
66  cl::desc("A fixed cold count that overrides the count derived from"
67  " profile-summary-cutoff-cold"));
68 
69 // Find the summary entry for a desired percentile of counts.
71  uint64_t Percentile) {
72  auto It = partition_point(DS, [=](const ProfileSummaryEntry &Entry) {
73  return Entry.Cutoff < Percentile;
74  });
75  // The required percentile has to be <= one of the percentiles in the
76  // detailed summary.
77  if (It == DS.end())
78  report_fatal_error("Desired percentile exceeds the maximum cutoff");
79  return *It;
80 }
81 
82 // The profile summary metadata may be attached either by the frontend or by
83 // any backend passes (IR level instrumentation, for example). This method
84 // checks if the Summary is null and if so checks if the summary metadata is now
85 // available in the module and parses it to get the Summary object. Returns true
86 // if a valid Summary is available.
87 bool ProfileSummaryInfo::computeSummary() {
88  if (Summary)
89  return true;
90  // First try to get context sensitive ProfileSummary.
91  auto *SummaryMD = M.getProfileSummary(/* IsCS */ true);
92  if (SummaryMD) {
93  Summary.reset(ProfileSummary::getFromMD(SummaryMD));
94  return true;
95  }
96  // This will actually return PSK_Instr or PSK_Sample summary.
97  SummaryMD = M.getProfileSummary(/* IsCS */ false);
98  if (!SummaryMD)
99  return false;
100  Summary.reset(ProfileSummary::getFromMD(SummaryMD));
101  return true;
102 }
103 
107  bool AllowSynthetic) {
108  if (!Inst)
109  return None;
110  assert((isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) &&
111  "We can only get profile count for call/invoke instruction.");
112  if (hasSampleProfile()) {
113  // In sample PGO mode, check if there is a profile metadata on the
114  // instruction. If it is present, determine hotness solely based on that,
115  // since the sampled entry count may not be accurate. If there is no
116  // annotated on the instruction, return None.
117  uint64_t TotalCount;
118  if (Inst->extractProfTotalWeight(TotalCount))
119  return TotalCount;
120  return None;
121  }
122  if (BFI)
123  return BFI->getBlockProfileCount(Inst->getParent(), AllowSynthetic);
124  return None;
125 }
126 
127 /// Returns true if the function's entry is hot. If it returns false, it
128 /// either means it is not hot or it is unknown whether it is hot or not (for
129 /// example, no profile data is available).
131  if (!F || !computeSummary())
132  return false;
133  auto FunctionCount = F->getEntryCount();
134  // FIXME: The heuristic used below for determining hotness is based on
135  // preliminary SPEC tuning for inliner. This will eventually be a
136  // convenience method that calls isHotCount.
137  return FunctionCount && isHotCount(FunctionCount.getCount());
138 }
139 
140 /// Returns true if the function contains hot code. This can include a hot
141 /// function entry count, hot basic block, or (in the case of Sample PGO)
142 /// hot total call edge count.
143 /// If it returns false, it either means it is not hot or it is unknown
144 /// (for example, no profile data is available).
147  if (!F || !computeSummary())
148  return false;
149  if (auto FunctionCount = F->getEntryCount())
150  if (isHotCount(FunctionCount.getCount()))
151  return true;
152 
153  if (hasSampleProfile()) {
154  uint64_t TotalCallCount = 0;
155  for (const auto &BB : *F)
156  for (const auto &I : BB)
157  if (isa<CallInst>(I) || isa<InvokeInst>(I))
158  if (auto CallCount = getProfileCount(&I, nullptr))
159  TotalCallCount += CallCount.getValue();
160  if (isHotCount(TotalCallCount))
161  return true;
162  }
163  for (const auto &BB : *F)
164  if (isHotBlock(&BB, &BFI))
165  return true;
166  return false;
167 }
168 
169 /// Returns true if the function only contains cold code. This means that
170 /// the function entry and blocks are all cold, and (in the case of Sample PGO)
171 /// the total call edge count is cold.
172 /// If it returns false, it either means it is not cold or it is unknown
173 /// (for example, no profile data is available).
176  if (!F || !computeSummary())
177  return false;
178  if (auto FunctionCount = F->getEntryCount())
179  if (!isColdCount(FunctionCount.getCount()))
180  return false;
181 
182  if (hasSampleProfile()) {
183  uint64_t TotalCallCount = 0;
184  for (const auto &BB : *F)
185  for (const auto &I : BB)
186  if (isa<CallInst>(I) || isa<InvokeInst>(I))
187  if (auto CallCount = getProfileCount(&I, nullptr))
188  TotalCallCount += CallCount.getValue();
189  if (!isColdCount(TotalCallCount))
190  return false;
191  }
192  for (const auto &BB : *F)
193  if (!isColdBlock(&BB, &BFI))
194  return false;
195  return true;
196 }
197 
198 // Like isFunctionHotInCallGraph but for a given cutoff.
200  int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) {
201  if (!F || !computeSummary())
202  return false;
203  if (auto FunctionCount = F->getEntryCount())
204  if (isHotCountNthPercentile(PercentileCutoff, FunctionCount.getCount()))
205  return true;
206 
207  if (hasSampleProfile()) {
208  uint64_t TotalCallCount = 0;
209  for (const auto &BB : *F)
210  for (const auto &I : BB)
211  if (isa<CallInst>(I) || isa<InvokeInst>(I))
212  if (auto CallCount = getProfileCount(&I, nullptr))
213  TotalCallCount += CallCount.getValue();
214  if (isHotCountNthPercentile(PercentileCutoff, TotalCallCount))
215  return true;
216  }
217  for (const auto &BB : *F)
218  if (isHotBlockNthPercentile(PercentileCutoff, &BB, &BFI))
219  return true;
220  return false;
221 }
222 
223 /// Returns true if the function's entry is a cold. If it returns false, it
224 /// either means it is not cold or it is unknown whether it is cold or not (for
225 /// example, no profile data is available).
227  if (!F)
228  return false;
230  return true;
231  if (!computeSummary())
232  return false;
233  auto FunctionCount = F->getEntryCount();
234  // FIXME: The heuristic used below for determining coldness is based on
235  // preliminary SPEC tuning for inliner. This will eventually be a
236  // convenience method that calls isHotCount.
237  return FunctionCount && isColdCount(FunctionCount.getCount());
238 }
239 
240 /// Compute the hot and cold thresholds.
241 void ProfileSummaryInfo::computeThresholds() {
242  if (!computeSummary())
243  return;
244  auto &DetailedSummary = Summary->getDetailedSummary();
245  auto &HotEntry =
247  HotCountThreshold = HotEntry.MinCount;
248  if (ProfileSummaryHotCount.getNumOccurrences() > 0)
249  HotCountThreshold = ProfileSummaryHotCount;
250  auto &ColdEntry =
252  ColdCountThreshold = ColdEntry.MinCount;
253  if (ProfileSummaryColdCount.getNumOccurrences() > 0)
254  ColdCountThreshold = ProfileSummaryColdCount;
255  assert(ColdCountThreshold <= HotCountThreshold &&
256  "Cold count threshold cannot exceed hot count threshold!");
257  HasHugeWorkingSetSize =
258  HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
259  HasLargeWorkingSetSize =
260  HotEntry.NumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
261 }
262 
263 Optional<uint64_t> ProfileSummaryInfo::computeThreshold(int PercentileCutoff) {
264  if (!computeSummary())
265  return None;
266  auto iter = ThresholdCache.find(PercentileCutoff);
267  if (iter != ThresholdCache.end()) {
268  return iter->second;
269  }
270  auto &DetailedSummary = Summary->getDetailedSummary();
271  auto &Entry =
272  getEntryForPercentile(DetailedSummary, PercentileCutoff);
273  uint64_t CountThreshold = Entry.MinCount;
274  ThresholdCache[PercentileCutoff] = CountThreshold;
275  return CountThreshold;
276 }
277 
279  if (!HasHugeWorkingSetSize)
280  computeThresholds();
281  return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue();
282 }
283 
285  if (!HasLargeWorkingSetSize)
286  computeThresholds();
287  return HasLargeWorkingSetSize && HasLargeWorkingSetSize.getValue();
288 }
289 
291  if (!HotCountThreshold)
292  computeThresholds();
293  return HotCountThreshold && C >= HotCountThreshold.getValue();
294 }
295 
297  if (!ColdCountThreshold)
298  computeThresholds();
299  return ColdCountThreshold && C <= ColdCountThreshold.getValue();
300 }
301 
302 bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff, uint64_t C) {
303  auto CountThreshold = computeThreshold(PercentileCutoff);
304  return CountThreshold && C >= CountThreshold.getValue();
305 }
306 
308  if (!HotCountThreshold)
309  computeThresholds();
310  return HotCountThreshold ? HotCountThreshold.getValue() : UINT64_MAX;
311 }
312 
314  if (!ColdCountThreshold)
315  computeThresholds();
316  return ColdCountThreshold ? ColdCountThreshold.getValue() : 0;
317 }
318 
320  auto Count = BFI->getBlockProfileCount(BB);
321  return Count && isHotCount(*Count);
322 }
323 
326  auto Count = BFI->getBlockProfileCount(BB);
327  return Count && isColdCount(*Count);
328 }
329 
331  const BasicBlock *BB,
333  auto Count = BFI->getBlockProfileCount(BB);
334  return Count && isHotCountNthPercentile(PercentileCutoff, *Count);
335 }
336 
339  auto C = getProfileCount(CS.getInstruction(), BFI);
340  return C && isHotCount(*C);
341 }
342 
345  auto C = getProfileCount(CS.getInstruction(), BFI);
346  if (C)
347  return isColdCount(*C);
348 
349  // In SamplePGO, if the caller has been sampled, and there is no profile
350  // annotated on the callsite, we consider the callsite as cold.
351  return hasSampleProfile() && CS.getCaller()->hasProfileData();
352 }
353 
355  "Profile summary info", false, true)
356 
358  : ImmutablePass(ID) {
360 }
361 
363  PSI.reset(new ProfileSummaryInfo(M));
364  return false;
365 }
366 
368  PSI.reset();
369  return false;
370 }
371 
372 AnalysisKey ProfileSummaryAnalysis::Key;
375  return ProfileSummaryInfo(M);
376 }
377 
379  ModuleAnalysisManager &AM) {
381 
382  OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
383  for (auto &F : M) {
384  OS << F.getName();
385  if (PSI.isFunctionEntryHot(&F))
386  OS << " :hot entry ";
387  else if (PSI.isFunctionEntryCold(&F))
388  OS << " :cold entry ";
389  OS << "\n";
390  }
391  return PreservedAnalyses::all();
392 }
393 
uint64_t CallInst * C
Optional< uint64_t > getBlockProfileCount(const BasicBlock *BB, bool AllowSynthetic=false) const
Returns the estimated profile count of BB.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint32_t Cutoff
The required percentile of counts.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
bool isColdCount(uint64_t C)
Returns true if count C is considered cold.
Analysis providing profile information.
This file contains the declarations for metadata subclasses.
Metadata * getProfileSummary(bool IsCS)
Returns profile summary metadata.
Definition: Module.cpp:557
bool isFunctionHotInCallGraphNthPercentile(int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI)
Returns true if F contains hot code with regard to a given hot percentile cutoff value.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.h:323
StringRef getName() const
Get a short "name" for the module.
Definition: Module.h:228
F(f)
uint64_t getOrCompHotCountThreshold()
Returns HotCountThreshold if set.
static cl::opt< unsigned > ProfileSummaryHugeWorkingSetSizeThreshold("profile-summary-huge-working-set-size-threshold", cl::Hidden, cl::init(15000), cl::ZeroOrMore, cl::desc("The code working set size is considered huge if the number of" " blocks required to reach the -profile-summary-cutoff-hot" " percentile exceeds this count."))
bool isHotCount(uint64_t C)
Returns true if count C is considered hot.
bool isFunctionEntryCold(const Function *F)
Returns true if F has cold function entry.
bool isHotCallSite(const CallSite &CS, BlockFrequencyInfo *BFI)
Returns true if CallSite CS is considered hot.
static cl::opt< int > ProfileSummaryHotCount("profile-summary-hot-count", cl::ReallyHidden, cl::ZeroOrMore, cl::desc("A fixed hot count that overrides the count derived from" " profile-summary-cutoff-hot"))
uint64_t getOrCompColdCountThreshold()
Returns ColdCountThreshold if set.
Result run(Module &M, ModuleAnalysisManager &)
bool isFunctionHotInCallGraph(const Function *F, BlockFrequencyInfo &BFI)
Returns true if F contains hot code.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
InstrTy * getInstruction() const
Definition: CallSite.h:96
auto partition_point(R &&Range, Predicate P) -> decltype(adl_begin(Range))
Binary search for the first iterator in a range where a predicate is false.
Definition: STLExtras.h:1319
bool isColdBlock(const BasicBlock *BB, BlockFrequencyInfo *BFI)
Returns true if BasicBlock BB is considered cold.
#define UINT64_MAX
Definition: DataTypes.h:83
bool hasLargeWorkingSetSize()
Returns true if the working set size of the code is considered large.
static cl::opt< unsigned > CountThreshold("hexagon-cext-threshold", cl::init(3), cl::Hidden, cl::ZeroOrMore, cl::desc("Minimum number of extenders to trigger replacement"))
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:255
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
Definition: Metadata.cpp:1339
bool doInitialization(Module &M) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
bool hasSampleProfile()
Returns true if module M has sample profile.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
ProfileCount getEntryCount(bool AllowSynthetic=false) const
Get the entry count for this function.
Definition: Function.cpp:1571
bool isHotCountNthPercentile(int PercentileCutoff, uint64_t C)
Returns true if count C is considered hot with regard to a given hot percentile cutoff value...
INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info", "Profile summary info", false, true) ProfileSummaryInfoWrapperPass
bool isHotBlockNthPercentile(int PercentileCutoff, const BasicBlock *BB, BlockFrequencyInfo *BFI)
Returns true if BasicBlock BB is considered hot with regard to a given hot percentile cutoff value...
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
Definition: Function.h:308
bool doFinalization(Module &M) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
Optional< uint64_t > getProfileCount(const Instruction *CallInst, BlockFrequencyInfo *BFI, bool AllowSynthetic=false)
Returns the profile count for CallInst.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:253
Module.h This file contains the declarations for the Module class.
void initializeProfileSummaryInfoWrapperPassPass(PassRegistry &)
bool isFunctionColdInCallGraph(const Function *F, BlockFrequencyInfo &BFI)
Returns true if F contains only cold code.
static ProfileSummary * getFromMD(Metadata *MD)
Construct profile summary from metdata.
static cl::opt< int > ProfileSummaryCutoffHot("profile-summary-cutoff-hot", cl::Hidden, cl::init(990000), cl::ZeroOrMore, cl::desc("A count is hot if it exceeds the minimum count to" " reach this percentile of total counts."))
bool isFunctionEntryHot(const Function *F)
Returns true if F has hot function entry.
static cl::opt< unsigned > ProfileSummaryLargeWorkingSetSizeThreshold("profile-summary-large-working-set-size-threshold", cl::Hidden, cl::init(12500), cl::ZeroOrMore, cl::desc("The code working set size is considered large if the number of" " blocks required to reach the -profile-summary-cutoff-hot" " percentile exceeds this count."))
#define I(x, y, z)
Definition: MD5.cpp:58
iterator end()
Definition: DenseMap.h:82
bool isHotBlock(const BasicBlock *BB, BlockFrequencyInfo *BFI)
Returns true if BasicBlock BB is considered hot.
bool isColdCallSite(const CallSite &CS, BlockFrequencyInfo *BFI)
Returns true if Callsite CS is considered cold.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasHugeWorkingSetSize()
Returns true if the working set size of the code is considered huge.
static cl::opt< int > ProfileSummaryCutoffCold("profile-summary-cutoff-cold", cl::Hidden, cl::init(999999), cl::ZeroOrMore, cl::desc("A count is cold if it is below the minimum count" " to reach this percentile of total counts."))
A container for analyses that lazily runs them and caches their results.
std::vector< ProfileSummaryEntry > SummaryEntryVector
static cl::opt< int > ProfileSummaryColdCount("profile-summary-cold-count", cl::ReallyHidden, cl::ZeroOrMore, cl::desc("A fixed cold count that overrides the count derived from" " profile-summary-cutoff-cold"))
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:71
static const ProfileSummaryEntry & getEntryForPercentile(SummaryEntryVector &DS, uint64_t Percentile)
const BasicBlock * getParent() const
Definition: Instruction.h:66
FunTy * getCaller() const
Return the caller function for this call site.
Definition: CallSite.h:275