ProfileSummaryInfo.cpp 16 KB

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