ProfileSummaryInfo.cpp 16 KB

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