SyntheticCountsPropagation.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. //=- SyntheticCountsPropagation.cpp - Propagate function counts --*- C++ -*-=//
  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 implements a transformation that synthesizes entry counts for
  10. // functions and attaches !prof metadata to functions with the synthesized
  11. // counts. The presence of !prof metadata with counter name set to
  12. // 'synthesized_function_entry_count' indicate that the value of the counter is
  13. // an estimation of the likely execution count of the function. This transform
  14. // is applied only in non PGO mode as functions get 'real' profile-based
  15. // function entry counts in the PGO mode.
  16. //
  17. // The transformation works by first assigning some initial values to the entry
  18. // counts of all functions and then doing a top-down traversal of the
  19. // callgraph-scc to propagate the counts. For each function the set of callsites
  20. // and their relative block frequency is gathered. The relative block frequency
  21. // multiplied by the entry count of the caller and added to the callee's entry
  22. // count. For non-trivial SCCs, the new counts are computed from the previous
  23. // counts and updated in one shot.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
  27. #include "llvm/Analysis/BlockFrequencyInfo.h"
  28. #include "llvm/Analysis/CallGraph.h"
  29. #include "llvm/Analysis/SyntheticCountsUtils.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/Support/CommandLine.h"
  34. using namespace llvm;
  35. using Scaled64 = ScaledNumber<uint64_t>;
  36. using ProfileCount = Function::ProfileCount;
  37. #define DEBUG_TYPE "synthetic-counts-propagation"
  38. namespace llvm {
  39. cl::opt<int>
  40. InitialSyntheticCount("initial-synthetic-count", cl::Hidden, cl::init(10),
  41. cl::desc("Initial value of synthetic entry count"));
  42. } // namespace llvm
  43. /// Initial synthetic count assigned to inline functions.
  44. static cl::opt<int> InlineSyntheticCount(
  45. "inline-synthetic-count", cl::Hidden, cl::init(15),
  46. cl::desc("Initial synthetic entry count for inline functions."));
  47. /// Initial synthetic count assigned to cold functions.
  48. static cl::opt<int> ColdSyntheticCount(
  49. "cold-synthetic-count", cl::Hidden, cl::init(5),
  50. cl::desc("Initial synthetic entry count for cold functions."));
  51. // Assign initial synthetic entry counts to functions.
  52. static void
  53. initializeCounts(Module &M, function_ref<void(Function *, uint64_t)> SetCount) {
  54. auto MayHaveIndirectCalls = [](Function &F) {
  55. for (auto *U : F.users()) {
  56. if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
  57. return true;
  58. }
  59. return false;
  60. };
  61. for (Function &F : M) {
  62. uint64_t InitialCount = InitialSyntheticCount;
  63. if (F.isDeclaration())
  64. continue;
  65. if (F.hasFnAttribute(Attribute::AlwaysInline) ||
  66. F.hasFnAttribute(Attribute::InlineHint)) {
  67. // Use a higher value for inline functions to account for the fact that
  68. // these are usually beneficial to inline.
  69. InitialCount = InlineSyntheticCount;
  70. } else if (F.hasLocalLinkage() && !MayHaveIndirectCalls(F)) {
  71. // Local functions without inline hints get counts only through
  72. // propagation.
  73. InitialCount = 0;
  74. } else if (F.hasFnAttribute(Attribute::Cold) ||
  75. F.hasFnAttribute(Attribute::NoInline)) {
  76. // Use a lower value for noinline and cold functions.
  77. InitialCount = ColdSyntheticCount;
  78. }
  79. SetCount(&F, InitialCount);
  80. }
  81. }
  82. PreservedAnalyses SyntheticCountsPropagation::run(Module &M,
  83. ModuleAnalysisManager &MAM) {
  84. FunctionAnalysisManager &FAM =
  85. MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  86. DenseMap<Function *, Scaled64> Counts;
  87. // Set initial entry counts.
  88. initializeCounts(
  89. M, [&](Function *F, uint64_t Count) { Counts[F] = Scaled64(Count, 0); });
  90. // Edge includes information about the source. Hence ignore the first
  91. // parameter.
  92. auto GetCallSiteProfCount = [&](const CallGraphNode *,
  93. const CallGraphNode::CallRecord &Edge) {
  94. std::optional<Scaled64> Res;
  95. if (!Edge.first)
  96. return Res;
  97. CallBase &CB = *cast<CallBase>(*Edge.first);
  98. Function *Caller = CB.getCaller();
  99. auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(*Caller);
  100. // Now compute the callsite count from relative frequency and
  101. // entry count:
  102. BasicBlock *CSBB = CB.getParent();
  103. Scaled64 EntryFreq(BFI.getEntryFreq(), 0);
  104. Scaled64 BBCount(BFI.getBlockFreq(CSBB).getFrequency(), 0);
  105. BBCount /= EntryFreq;
  106. BBCount *= Counts[Caller];
  107. return std::optional<Scaled64>(BBCount);
  108. };
  109. CallGraph CG(M);
  110. // Propgate the entry counts on the callgraph.
  111. SyntheticCountsUtils<const CallGraph *>::propagate(
  112. &CG, GetCallSiteProfCount, [&](const CallGraphNode *N, Scaled64 New) {
  113. auto F = N->getFunction();
  114. if (!F || F->isDeclaration())
  115. return;
  116. Counts[F] += New;
  117. });
  118. // Set the counts as metadata.
  119. for (auto Entry : Counts) {
  120. Entry.first->setEntryCount(ProfileCount(
  121. Entry.second.template toInt<uint64_t>(), Function::PCT_Synthetic));
  122. }
  123. return PreservedAnalyses::all();
  124. }