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