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 "llvm/Analysis/BlockFrequencyInfo.h"
16 #include "llvm/IR/BasicBlock.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Metadata.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/ProfileSummary.h"
21 #include "llvm/InitializePasses.h"
22 #include "llvm/Support/CommandLine.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 
33 static cl::opt<int> ProfileSummaryCutoffHot(
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 
38 static cl::opt<int> ProfileSummaryCutoffCold(
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 
43 static cl::opt<unsigned> ProfileSummaryHugeWorkingSetSizeThreshold(
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 
50 static cl::opt<unsigned> ProfileSummaryLargeWorkingSetSizeThreshold(
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.
59 static cl::opt<int> ProfileSummaryHotCount(
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 
64 static cl::opt<int> ProfileSummaryColdCount(
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 static cl::opt<bool> PartialProfile(
70     "partial-profile", cl::Hidden, cl::init(false),
71     cl::desc("Specify the current profile is used as a partial profile."));
72 
73 cl::opt<bool> ScalePartialSampleProfileWorkingSetSize(
74     "scale-partial-sample-profile-working-set-size", cl::Hidden,
75     cl::init(false),
76     cl::desc(
77         "If true, scale the working set size of the partial sample profile "
78         "by the partial profile ratio to reflect the size of the program "
79         "being compiled."));
80 
81 static cl::opt<double> PartialSampleProfileWorkingSetSizeScaleFactor(
82     "partial-sample-profile-working-set-size-scale-factor", cl::Hidden,
83     cl::init(0.008),
84     cl::desc("The scale factor used to scale the working set size of the "
85              "partial sample profile along with the partial profile ratio. "
86              "This includes the factor of the profile counter per block "
87              "and the factor to scale the working set size to use the same "
88              "shared thresholds as PGO."));
89 
90 // Find the summary entry for a desired percentile of counts.
91 static const ProfileSummaryEntry &getEntryForPercentile(SummaryEntryVector &DS,
92                                                         uint64_t Percentile) {
93   auto It = partition_point(DS, [=](const ProfileSummaryEntry &Entry) {
94     return Entry.Cutoff < Percentile;
95   });
96   // The required percentile has to be <= one of the percentiles in the
97   // detailed summary.
98   if (It == DS.end())
99     report_fatal_error("Desired percentile exceeds the maximum cutoff");
100   return *It;
101 }
102 
103 // The profile summary metadata may be attached either by the frontend or by
104 // any backend passes (IR level instrumentation, for example). This method
105 // checks if the Summary is null and if so checks if the summary metadata is now
106 // available in the module and parses it to get the Summary object.
107 void ProfileSummaryInfo::refresh() {
108   if (hasProfileSummary())
109     return;
110   // First try to get context sensitive ProfileSummary.
111   auto *SummaryMD = M.getProfileSummary(/* IsCS */ true);
112   if (SummaryMD)
113     Summary.reset(ProfileSummary::getFromMD(SummaryMD));
114 
115   if (!hasProfileSummary()) {
116     // This will actually return PSK_Instr or PSK_Sample summary.
117     SummaryMD = M.getProfileSummary(/* IsCS */ false);
118     if (SummaryMD)
119       Summary.reset(ProfileSummary::getFromMD(SummaryMD));
120   }
121   if (!hasProfileSummary())
122     return;
123   computeThresholds();
124 }
125 
126 Optional<uint64_t> ProfileSummaryInfo::getProfileCount(
127     const CallBase &Call, BlockFrequencyInfo *BFI, bool AllowSynthetic) const {
128   assert((isa<CallInst>(Call) || isa<InvokeInst>(Call)) &&
129          "We can only get profile count for call/invoke instruction.");
130   if (hasSampleProfile()) {
131     // In sample PGO mode, check if there is a profile metadata on the
132     // instruction. If it is present, determine hotness solely based on that,
133     // since the sampled entry count may not be accurate. If there is no
134     // annotated on the instruction, return None.
135     uint64_t TotalCount;
136     if (Call.extractProfTotalWeight(TotalCount))
137       return TotalCount;
138     return None;
139   }
140   if (BFI)
141     return BFI->getBlockProfileCount(Call.getParent(), AllowSynthetic);
142   return None;
143 }
144 
145 /// Returns true if the function's entry is hot. If it returns false, it
146 /// either means it is not hot or it is unknown whether it is hot or not (for
147 /// example, no profile data is available).
148 bool ProfileSummaryInfo::isFunctionEntryHot(const Function *F) const {
149   if (!F || !hasProfileSummary())
150     return false;
151   auto FunctionCount = F->getEntryCount();
152   // FIXME: The heuristic used below for determining hotness is based on
153   // preliminary SPEC tuning for inliner. This will eventually be a
154   // convenience method that calls isHotCount.
155   return FunctionCount && isHotCount(FunctionCount.getCount());
156 }
157 
158 /// Returns true if the function contains hot code. This can include a hot
159 /// function entry count, hot basic block, or (in the case of Sample PGO)
160 /// hot total call edge count.
161 /// If it returns false, it either means it is not hot or it is unknown
162 /// (for example, no profile data is available).
163 bool ProfileSummaryInfo::isFunctionHotInCallGraph(
164     const Function *F, BlockFrequencyInfo &BFI) const {
165   if (!F || !hasProfileSummary())
166     return false;
167   if (auto FunctionCount = F->getEntryCount())
168     if (isHotCount(FunctionCount.getCount()))
169       return true;
170 
171   if (hasSampleProfile()) {
172     uint64_t TotalCallCount = 0;
173     for (const auto &BB : *F)
174       for (const auto &I : BB)
175         if (isa<CallInst>(I) || isa<InvokeInst>(I))
176           if (auto CallCount = getProfileCount(cast<CallBase>(I), nullptr))
177             TotalCallCount += CallCount.getValue();
178     if (isHotCount(TotalCallCount))
179       return true;
180   }
181   for (const auto &BB : *F)
182     if (isHotBlock(&BB, &BFI))
183       return true;
184   return false;
185 }
186 
187 /// Returns true if the function only contains cold code. This means that
188 /// the function entry and blocks are all cold, and (in the case of Sample PGO)
189 /// the total call edge count is cold.
190 /// If it returns false, it either means it is not cold or it is unknown
191 /// (for example, no profile data is available).
192 bool ProfileSummaryInfo::isFunctionColdInCallGraph(
193     const Function *F, BlockFrequencyInfo &BFI) const {
194   if (!F || !hasProfileSummary())
195     return false;
196   if (auto FunctionCount = F->getEntryCount())
197     if (!isColdCount(FunctionCount.getCount()))
198       return false;
199 
200   if (hasSampleProfile()) {
201     uint64_t TotalCallCount = 0;
202     for (const auto &BB : *F)
203       for (const auto &I : BB)
204         if (isa<CallInst>(I) || isa<InvokeInst>(I))
205           if (auto CallCount = getProfileCount(cast<CallBase>(I), nullptr))
206             TotalCallCount += CallCount.getValue();
207     if (!isColdCount(TotalCallCount))
208       return false;
209   }
210   for (const auto &BB : *F)
211     if (!isColdBlock(&BB, &BFI))
212       return false;
213   return true;
214 }
215 
216 bool ProfileSummaryInfo::isFunctionHotnessUnknown(const Function &F) const {
217   assert(hasPartialSampleProfile() && "Expect partial sample profile");
218   return !F.getEntryCount().hasValue();
219 }
220 
221 template <bool isHot>
222 bool ProfileSummaryInfo::isFunctionHotOrColdInCallGraphNthPercentile(
223     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) const {
224   if (!F || !hasProfileSummary())
225     return false;
226   if (auto FunctionCount = F->getEntryCount()) {
227     if (isHot &&
228         isHotCountNthPercentile(PercentileCutoff, FunctionCount.getCount()))
229       return true;
230     if (!isHot &&
231         !isColdCountNthPercentile(PercentileCutoff, FunctionCount.getCount()))
232       return false;
233   }
234   if (hasSampleProfile()) {
235     uint64_t TotalCallCount = 0;
236     for (const auto &BB : *F)
237       for (const auto &I : BB)
238         if (isa<CallInst>(I) || isa<InvokeInst>(I))
239           if (auto CallCount = getProfileCount(cast<CallBase>(I), nullptr))
240             TotalCallCount += CallCount.getValue();
241     if (isHot && isHotCountNthPercentile(PercentileCutoff, TotalCallCount))
242       return true;
243     if (!isHot && !isColdCountNthPercentile(PercentileCutoff, TotalCallCount))
244       return false;
245   }
246   for (const auto &BB : *F) {
247     if (isHot && isHotBlockNthPercentile(PercentileCutoff, &BB, &BFI))
248       return true;
249     if (!isHot && !isColdBlockNthPercentile(PercentileCutoff, &BB, &BFI))
250       return false;
251   }
252   return !isHot;
253 }
254 
255 // Like isFunctionHotInCallGraph but for a given cutoff.
256 bool ProfileSummaryInfo::isFunctionHotInCallGraphNthPercentile(
257     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) const {
258   return isFunctionHotOrColdInCallGraphNthPercentile<true>(
259       PercentileCutoff, F, BFI);
260 }
261 
262 bool ProfileSummaryInfo::isFunctionColdInCallGraphNthPercentile(
263     int PercentileCutoff, const Function *F, BlockFrequencyInfo &BFI) const {
264   return isFunctionHotOrColdInCallGraphNthPercentile<false>(
265       PercentileCutoff, F, BFI);
266 }
267 
268 /// Returns true if the function's entry is a cold. If it returns false, it
269 /// either means it is not cold or it is unknown whether it is cold or not (for
270 /// example, no profile data is available).
271 bool ProfileSummaryInfo::isFunctionEntryCold(const Function *F) const {
272   if (!F)
273     return false;
274   if (F->hasFnAttribute(Attribute::Cold))
275     return true;
276   if (!hasProfileSummary())
277     return false;
278   auto FunctionCount = F->getEntryCount();
279   // FIXME: The heuristic used below for determining coldness is based on
280   // preliminary SPEC tuning for inliner. This will eventually be a
281   // convenience method that calls isHotCount.
282   return FunctionCount && isColdCount(FunctionCount.getCount());
283 }
284 
285 /// Compute the hot and cold thresholds.
286 void ProfileSummaryInfo::computeThresholds() {
287   auto &DetailedSummary = Summary->getDetailedSummary();
288   auto &HotEntry =
289       getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffHot);
290   HotCountThreshold = HotEntry.MinCount;
291   if (ProfileSummaryHotCount.getNumOccurrences() > 0)
292     HotCountThreshold = ProfileSummaryHotCount;
293   auto &ColdEntry =
294       getEntryForPercentile(DetailedSummary, ProfileSummaryCutoffCold);
295   ColdCountThreshold = ColdEntry.MinCount;
296   if (ProfileSummaryColdCount.getNumOccurrences() > 0)
297     ColdCountThreshold = ProfileSummaryColdCount;
298   assert(ColdCountThreshold <= HotCountThreshold &&
299          "Cold count threshold cannot exceed hot count threshold!");
300   if (!hasPartialSampleProfile() || !ScalePartialSampleProfileWorkingSetSize) {
301     HasHugeWorkingSetSize =
302         HotEntry.NumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
303     HasLargeWorkingSetSize =
304         HotEntry.NumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
305   } else {
306     // Scale the working set size of the partial sample profile to reflect the
307     // size of the program being compiled.
308     double PartialProfileRatio = Summary->getPartialProfileRatio();
309     uint64_t ScaledHotEntryNumCounts =
310         static_cast<uint64_t>(HotEntry.NumCounts * PartialProfileRatio *
311                               PartialSampleProfileWorkingSetSizeScaleFactor);
312     HasHugeWorkingSetSize =
313         ScaledHotEntryNumCounts > ProfileSummaryHugeWorkingSetSizeThreshold;
314     HasLargeWorkingSetSize =
315         ScaledHotEntryNumCounts > ProfileSummaryLargeWorkingSetSizeThreshold;
316   }
317 }
318 
319 Optional<uint64_t>
320 ProfileSummaryInfo::computeThreshold(int PercentileCutoff) const {
321   if (!hasProfileSummary())
322     return None;
323   auto iter = ThresholdCache.find(PercentileCutoff);
324   if (iter != ThresholdCache.end()) {
325     return iter->second;
326   }
327   auto &DetailedSummary = Summary->getDetailedSummary();
328   auto &Entry =
329       getEntryForPercentile(DetailedSummary, PercentileCutoff);
330   uint64_t CountThreshold = Entry.MinCount;
331   ThresholdCache[PercentileCutoff] = CountThreshold;
332   return CountThreshold;
333 }
334 
335 bool ProfileSummaryInfo::hasHugeWorkingSetSize() const {
336   return HasHugeWorkingSetSize && HasHugeWorkingSetSize.getValue();
337 }
338 
339 bool ProfileSummaryInfo::hasLargeWorkingSetSize() const {
340   return HasLargeWorkingSetSize && HasLargeWorkingSetSize.getValue();
341 }
342 
343 bool ProfileSummaryInfo::isHotCount(uint64_t C) const {
344   return HotCountThreshold && C >= HotCountThreshold.getValue();
345 }
346 
347 bool ProfileSummaryInfo::isColdCount(uint64_t C) const {
348   return ColdCountThreshold && C <= ColdCountThreshold.getValue();
349 }
350 
351 template <bool isHot>
352 bool ProfileSummaryInfo::isHotOrColdCountNthPercentile(int PercentileCutoff,
353                                                        uint64_t C) const {
354   auto CountThreshold = computeThreshold(PercentileCutoff);
355   if (isHot)
356     return CountThreshold && C >= CountThreshold.getValue();
357   else
358     return CountThreshold && C <= CountThreshold.getValue();
359 }
360 
361 bool ProfileSummaryInfo::isHotCountNthPercentile(int PercentileCutoff,
362                                                  uint64_t C) const {
363   return isHotOrColdCountNthPercentile<true>(PercentileCutoff, C);
364 }
365 
366 bool ProfileSummaryInfo::isColdCountNthPercentile(int PercentileCutoff,
367                                                   uint64_t C) const {
368   return isHotOrColdCountNthPercentile<false>(PercentileCutoff, C);
369 }
370 
371 uint64_t ProfileSummaryInfo::getOrCompHotCountThreshold() const {
372   return HotCountThreshold ? HotCountThreshold.getValue() : UINT64_MAX;
373 }
374 
375 uint64_t ProfileSummaryInfo::getOrCompColdCountThreshold() const {
376   return ColdCountThreshold ? ColdCountThreshold.getValue() : 0;
377 }
378 
379 bool ProfileSummaryInfo::isHotBlock(const BasicBlock *BB,
380                                     BlockFrequencyInfo *BFI) const {
381   auto Count = BFI->getBlockProfileCount(BB);
382   return Count && isHotCount(*Count);
383 }
384 
385 bool ProfileSummaryInfo::isColdBlock(const BasicBlock *BB,
386                                      BlockFrequencyInfo *BFI) const {
387   auto Count = BFI->getBlockProfileCount(BB);
388   return Count && isColdCount(*Count);
389 }
390 
391 template <bool isHot>
392 bool ProfileSummaryInfo::isHotOrColdBlockNthPercentile(
393     int PercentileCutoff, const BasicBlock *BB, BlockFrequencyInfo *BFI) const {
394   auto Count = BFI->getBlockProfileCount(BB);
395   if (isHot)
396     return Count && isHotCountNthPercentile(PercentileCutoff, *Count);
397   else
398     return Count && isColdCountNthPercentile(PercentileCutoff, *Count);
399 }
400 
401 bool ProfileSummaryInfo::isHotBlockNthPercentile(
402     int PercentileCutoff, const BasicBlock *BB, BlockFrequencyInfo *BFI) const {
403   return isHotOrColdBlockNthPercentile<true>(PercentileCutoff, BB, BFI);
404 }
405 
406 bool ProfileSummaryInfo::isColdBlockNthPercentile(
407     int PercentileCutoff, const BasicBlock *BB, BlockFrequencyInfo *BFI) const {
408   return isHotOrColdBlockNthPercentile<false>(PercentileCutoff, BB, BFI);
409 }
410 
411 bool ProfileSummaryInfo::isHotCallSite(const CallBase &CB,
412                                        BlockFrequencyInfo *BFI) const {
413   auto C = getProfileCount(CB, BFI);
414   return C && isHotCount(*C);
415 }
416 
417 bool ProfileSummaryInfo::isColdCallSite(const CallBase &CB,
418                                         BlockFrequencyInfo *BFI) const {
419   auto C = getProfileCount(CB, BFI);
420   if (C)
421     return isColdCount(*C);
422 
423   // In SamplePGO, if the caller has been sampled, and there is no profile
424   // annotated on the callsite, we consider the callsite as cold.
425   return hasSampleProfile() && CB.getCaller()->hasProfileData();
426 }
427 
428 bool ProfileSummaryInfo::hasPartialSampleProfile() const {
429   return hasProfileSummary() &&
430          Summary->getKind() == ProfileSummary::PSK_Sample &&
431          (PartialProfile || Summary->isPartialProfile());
432 }
433 
434 INITIALIZE_PASS(ProfileSummaryInfoWrapperPass, "profile-summary-info",
435                 "Profile summary info", false, true)
436 
437 ProfileSummaryInfoWrapperPass::ProfileSummaryInfoWrapperPass()
438     : ImmutablePass(ID) {
439   initializeProfileSummaryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
440 }
441 
442 bool ProfileSummaryInfoWrapperPass::doInitialization(Module &M) {
443   PSI.reset(new ProfileSummaryInfo(M));
444   return false;
445 }
446 
447 bool ProfileSummaryInfoWrapperPass::doFinalization(Module &M) {
448   PSI.reset();
449   return false;
450 }
451 
452 AnalysisKey ProfileSummaryAnalysis::Key;
453 ProfileSummaryInfo ProfileSummaryAnalysis::run(Module &M,
454                                                ModuleAnalysisManager &) {
455   return ProfileSummaryInfo(M);
456 }
457 
458 PreservedAnalyses ProfileSummaryPrinterPass::run(Module &M,
459                                                  ModuleAnalysisManager &AM) {
460   ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
461 
462   OS << "Functions in " << M.getName() << " with hot/cold annotations: \n";
463   for (auto &F : M) {
464     OS << F.getName();
465     if (PSI.isFunctionEntryHot(&F))
466       OS << " :hot entry ";
467     else if (PSI.isFunctionEntryCold(&F))
468       OS << " :cold entry ";
469     OS << "\n";
470   }
471   return PreservedAnalyses::all();
472 }
473 
474 char ProfileSummaryInfoWrapperPass::ID = 0;
475