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