BranchProbabilityInfo.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- BranchProbabilityInfo.h - Branch Probability Analysis ----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This pass is used to evaluate branch probabilties.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
  18. #define LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/DenseMapInfo.h"
  21. #include "llvm/ADT/DenseSet.h"
  22. #include "llvm/IR/BasicBlock.h"
  23. #include "llvm/IR/CFG.h"
  24. #include "llvm/IR/PassManager.h"
  25. #include "llvm/IR/ValueHandle.h"
  26. #include "llvm/Pass.h"
  27. #include "llvm/Support/BranchProbability.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cstdint>
  31. #include <memory>
  32. #include <utility>
  33. namespace llvm {
  34. class Function;
  35. class Loop;
  36. class LoopInfo;
  37. class raw_ostream;
  38. class DominatorTree;
  39. class PostDominatorTree;
  40. class TargetLibraryInfo;
  41. class Value;
  42. /// Analysis providing branch probability information.
  43. ///
  44. /// This is a function analysis which provides information on the relative
  45. /// probabilities of each "edge" in the function's CFG where such an edge is
  46. /// defined by a pair (PredBlock and an index in the successors). The
  47. /// probability of an edge from one block is always relative to the
  48. /// probabilities of other edges from the block. The probabilites of all edges
  49. /// from a block sum to exactly one (100%).
  50. /// We use a pair (PredBlock and an index in the successors) to uniquely
  51. /// identify an edge, since we can have multiple edges from Src to Dst.
  52. /// As an example, we can have a switch which jumps to Dst with value 0 and
  53. /// value 10.
  54. ///
  55. /// Process of computing branch probabilities can be logically viewed as three
  56. /// step process:
  57. ///
  58. /// First, if there is a profile information associated with the branch then
  59. /// it is trivially translated to branch probabilities. There is one exception
  60. /// from this rule though. Probabilities for edges leading to "unreachable"
  61. /// blocks (blocks with the estimated weight not greater than
  62. /// UNREACHABLE_WEIGHT) are evaluated according to static estimation and
  63. /// override profile information. If no branch probabilities were calculated
  64. /// on this step then take the next one.
  65. ///
  66. /// Second, estimate absolute execution weights for each block based on
  67. /// statically known information. Roots of such information are "cold",
  68. /// "unreachable", "noreturn" and "unwind" blocks. Those blocks get their
  69. /// weights set to BlockExecWeight::COLD, BlockExecWeight::UNREACHABLE,
  70. /// BlockExecWeight::NORETURN and BlockExecWeight::UNWIND respectively. Then the
  71. /// weights are propagated to the other blocks up the domination line. In
  72. /// addition, if all successors have estimated weights set then maximum of these
  73. /// weights assigned to the block itself (while this is not ideal heuristic in
  74. /// theory it's simple and works reasonably well in most cases) and the process
  75. /// repeats. Once the process of weights propagation converges branch
  76. /// probabilities are set for all such branches that have at least one successor
  77. /// with the weight set. Default execution weight (BlockExecWeight::DEFAULT) is
  78. /// used for any successors which doesn't have its weight set. For loop back
  79. /// branches we use their weights scaled by loop trip count equal to
  80. /// 'LBH_TAKEN_WEIGHT/LBH_NOTTAKEN_WEIGHT'.
  81. ///
  82. /// Here is a simple example demonstrating how the described algorithm works.
  83. ///
  84. /// BB1
  85. /// / \
  86. /// v v
  87. /// BB2 BB3
  88. /// / \
  89. /// v v
  90. /// ColdBB UnreachBB
  91. ///
  92. /// Initially, ColdBB is associated with COLD_WEIGHT and UnreachBB with
  93. /// UNREACHABLE_WEIGHT. COLD_WEIGHT is set to BB2 as maximum between its
  94. /// successors. BB1 and BB3 has no explicit estimated weights and assumed to
  95. /// have DEFAULT_WEIGHT. Based on assigned weights branches will have the
  96. /// following probabilities:
  97. /// P(BB1->BB2) = COLD_WEIGHT/(COLD_WEIGHT + DEFAULT_WEIGHT) =
  98. /// 0xffff / (0xffff + 0xfffff) = 0.0588(5.9%)
  99. /// P(BB1->BB3) = DEFAULT_WEIGHT_WEIGHT/(COLD_WEIGHT + DEFAULT_WEIGHT) =
  100. /// 0xfffff / (0xffff + 0xfffff) = 0.941(94.1%)
  101. /// P(BB2->ColdBB) = COLD_WEIGHT/(COLD_WEIGHT + UNREACHABLE_WEIGHT) = 1(100%)
  102. /// P(BB2->UnreachBB) =
  103. /// UNREACHABLE_WEIGHT/(COLD_WEIGHT+UNREACHABLE_WEIGHT) = 0(0%)
  104. ///
  105. /// If no branch probabilities were calculated on this step then take the next
  106. /// one.
  107. ///
  108. /// Third, apply different kinds of local heuristics for each individual
  109. /// branch until first match. For example probability of a pointer to be null is
  110. /// estimated as PH_TAKEN_WEIGHT/(PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT). If
  111. /// no local heuristic has been matched then branch is left with no explicit
  112. /// probability set and assumed to have default probability.
  113. class BranchProbabilityInfo {
  114. public:
  115. BranchProbabilityInfo() = default;
  116. BranchProbabilityInfo(const Function &F, const LoopInfo &LI,
  117. const TargetLibraryInfo *TLI = nullptr,
  118. DominatorTree *DT = nullptr,
  119. PostDominatorTree *PDT = nullptr) {
  120. calculate(F, LI, TLI, DT, PDT);
  121. }
  122. BranchProbabilityInfo(BranchProbabilityInfo &&Arg)
  123. : Probs(std::move(Arg.Probs)), LastF(Arg.LastF),
  124. EstimatedBlockWeight(std::move(Arg.EstimatedBlockWeight)) {}
  125. BranchProbabilityInfo(const BranchProbabilityInfo &) = delete;
  126. BranchProbabilityInfo &operator=(const BranchProbabilityInfo &) = delete;
  127. BranchProbabilityInfo &operator=(BranchProbabilityInfo &&RHS) {
  128. releaseMemory();
  129. Probs = std::move(RHS.Probs);
  130. EstimatedBlockWeight = std::move(RHS.EstimatedBlockWeight);
  131. return *this;
  132. }
  133. bool invalidate(Function &, const PreservedAnalyses &PA,
  134. FunctionAnalysisManager::Invalidator &);
  135. void releaseMemory();
  136. void print(raw_ostream &OS) const;
  137. /// Get an edge's probability, relative to other out-edges of the Src.
  138. ///
  139. /// This routine provides access to the fractional probability between zero
  140. /// (0%) and one (100%) of this edge executing, relative to other edges
  141. /// leaving the 'Src' block. The returned probability is never zero, and can
  142. /// only be one if the source block has only one successor.
  143. BranchProbability getEdgeProbability(const BasicBlock *Src,
  144. unsigned IndexInSuccessors) const;
  145. /// Get the probability of going from Src to Dst.
  146. ///
  147. /// It returns the sum of all probabilities for edges from Src to Dst.
  148. BranchProbability getEdgeProbability(const BasicBlock *Src,
  149. const BasicBlock *Dst) const;
  150. BranchProbability getEdgeProbability(const BasicBlock *Src,
  151. const_succ_iterator Dst) const;
  152. /// Test if an edge is hot relative to other out-edges of the Src.
  153. ///
  154. /// Check whether this edge out of the source block is 'hot'. We define hot
  155. /// as having a relative probability >= 80%.
  156. bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
  157. /// Print an edge's probability.
  158. ///
  159. /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
  160. /// then prints that probability to the provided stream. That stream is then
  161. /// returned.
  162. raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
  163. const BasicBlock *Dst) const;
  164. public:
  165. /// Set the raw probabilities for all edges from the given block.
  166. ///
  167. /// This allows a pass to explicitly set edge probabilities for a block. It
  168. /// can be used when updating the CFG to update the branch probability
  169. /// information.
  170. void setEdgeProbability(const BasicBlock *Src,
  171. const SmallVectorImpl<BranchProbability> &Probs);
  172. /// Copy outgoing edge probabilities from \p Src to \p Dst.
  173. ///
  174. /// This allows to keep probabilities unset for the destination if they were
  175. /// unset for source.
  176. void copyEdgeProbabilities(BasicBlock *Src, BasicBlock *Dst);
  177. static BranchProbability getBranchProbStackProtector(bool IsLikely) {
  178. static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
  179. return IsLikely ? LikelyProb : LikelyProb.getCompl();
  180. }
  181. void calculate(const Function &F, const LoopInfo &LI,
  182. const TargetLibraryInfo *TLI, DominatorTree *DT,
  183. PostDominatorTree *PDT);
  184. /// Forget analysis results for the given basic block.
  185. void eraseBlock(const BasicBlock *BB);
  186. // Data structure to track SCCs for handling irreducible loops.
  187. class SccInfo {
  188. // Enum of types to classify basic blocks in SCC. Basic block belonging to
  189. // SCC is 'Inner' until it is either 'Header' or 'Exiting'. Note that a
  190. // basic block can be 'Header' and 'Exiting' at the same time.
  191. enum SccBlockType {
  192. Inner = 0x0,
  193. Header = 0x1,
  194. Exiting = 0x2,
  195. };
  196. // Map of basic blocks to SCC IDs they belong to. If basic block doesn't
  197. // belong to any SCC it is not in the map.
  198. using SccMap = DenseMap<const BasicBlock *, int>;
  199. // Each basic block in SCC is attributed with one or several types from
  200. // SccBlockType. Map value has uint32_t type (instead of SccBlockType)
  201. // since basic block may be for example "Header" and "Exiting" at the same
  202. // time and we need to be able to keep more than one value from
  203. // SccBlockType.
  204. using SccBlockTypeMap = DenseMap<const BasicBlock *, uint32_t>;
  205. // Vector containing classification of basic blocks for all SCCs where i'th
  206. // vector element corresponds to SCC with ID equal to i.
  207. using SccBlockTypeMaps = std::vector<SccBlockTypeMap>;
  208. SccMap SccNums;
  209. SccBlockTypeMaps SccBlocks;
  210. public:
  211. explicit SccInfo(const Function &F);
  212. /// If \p BB belongs to some SCC then ID of that SCC is returned, otherwise
  213. /// -1 is returned. If \p BB belongs to more than one SCC at the same time
  214. /// result is undefined.
  215. int getSCCNum(const BasicBlock *BB) const;
  216. /// Returns true if \p BB is a 'header' block in SCC with \p SccNum ID,
  217. /// false otherwise.
  218. bool isSCCHeader(const BasicBlock *BB, int SccNum) const {
  219. return getSccBlockType(BB, SccNum) & Header;
  220. }
  221. /// Returns true if \p BB is an 'exiting' block in SCC with \p SccNum ID,
  222. /// false otherwise.
  223. bool isSCCExitingBlock(const BasicBlock *BB, int SccNum) const {
  224. return getSccBlockType(BB, SccNum) & Exiting;
  225. }
  226. /// Fills in \p Enters vector with all such blocks that don't belong to
  227. /// SCC with \p SccNum ID but there is an edge to a block belonging to the
  228. /// SCC.
  229. void getSccEnterBlocks(int SccNum,
  230. SmallVectorImpl<BasicBlock *> &Enters) const;
  231. /// Fills in \p Exits vector with all such blocks that don't belong to
  232. /// SCC with \p SccNum ID but there is an edge from a block belonging to the
  233. /// SCC.
  234. void getSccExitBlocks(int SccNum,
  235. SmallVectorImpl<BasicBlock *> &Exits) const;
  236. private:
  237. /// Returns \p BB's type according to classification given by SccBlockType
  238. /// enum. Please note that \p BB must belong to SSC with \p SccNum ID.
  239. uint32_t getSccBlockType(const BasicBlock *BB, int SccNum) const;
  240. /// Calculates \p BB's type and stores it in internal data structures for
  241. /// future use. Please note that \p BB must belong to SSC with \p SccNum ID.
  242. void calculateSccBlockType(const BasicBlock *BB, int SccNum);
  243. };
  244. private:
  245. // We need to store CallbackVH's in order to correctly handle basic block
  246. // removal.
  247. class BasicBlockCallbackVH final : public CallbackVH {
  248. BranchProbabilityInfo *BPI;
  249. void deleted() override {
  250. assert(BPI != nullptr);
  251. BPI->eraseBlock(cast<BasicBlock>(getValPtr()));
  252. }
  253. public:
  254. BasicBlockCallbackVH(const Value *V, BranchProbabilityInfo *BPI = nullptr)
  255. : CallbackVH(const_cast<Value *>(V)), BPI(BPI) {}
  256. };
  257. /// Pair of Loop and SCC ID number. Used to unify handling of normal and
  258. /// SCC based loop representations.
  259. using LoopData = std::pair<Loop *, int>;
  260. /// Helper class to keep basic block along with its loop data information.
  261. class LoopBlock {
  262. public:
  263. explicit LoopBlock(const BasicBlock *BB, const LoopInfo &LI,
  264. const SccInfo &SccI);
  265. const BasicBlock *getBlock() const { return BB; }
  266. BasicBlock *getBlock() { return const_cast<BasicBlock *>(BB); }
  267. LoopData getLoopData() const { return LD; }
  268. Loop *getLoop() const { return LD.first; }
  269. int getSccNum() const { return LD.second; }
  270. bool belongsToLoop() const { return getLoop() || getSccNum() != -1; }
  271. bool belongsToSameLoop(const LoopBlock &LB) const {
  272. return (LB.getLoop() && getLoop() == LB.getLoop()) ||
  273. (LB.getSccNum() != -1 && getSccNum() == LB.getSccNum());
  274. }
  275. private:
  276. const BasicBlock *const BB = nullptr;
  277. LoopData LD = {nullptr, -1};
  278. };
  279. // Pair of LoopBlocks representing an edge from first to second block.
  280. using LoopEdge = std::pair<const LoopBlock &, const LoopBlock &>;
  281. DenseSet<BasicBlockCallbackVH, DenseMapInfo<Value*>> Handles;
  282. // Since we allow duplicate edges from one basic block to another, we use
  283. // a pair (PredBlock and an index in the successors) to specify an edge.
  284. using Edge = std::pair<const BasicBlock *, unsigned>;
  285. DenseMap<Edge, BranchProbability> Probs;
  286. /// Track the last function we run over for printing.
  287. const Function *LastF = nullptr;
  288. const LoopInfo *LI = nullptr;
  289. /// Keeps information about all SCCs in a function.
  290. std::unique_ptr<const SccInfo> SccI;
  291. /// Keeps mapping of a basic block to its estimated weight.
  292. SmallDenseMap<const BasicBlock *, uint32_t> EstimatedBlockWeight;
  293. /// Keeps mapping of a loop to estimated weight to enter the loop.
  294. SmallDenseMap<LoopData, uint32_t> EstimatedLoopWeight;
  295. /// Helper to construct LoopBlock for \p BB.
  296. LoopBlock getLoopBlock(const BasicBlock *BB) const {
  297. return LoopBlock(BB, *LI, *SccI.get());
  298. }
  299. /// Returns true if destination block belongs to some loop and source block is
  300. /// either doesn't belong to any loop or belongs to a loop which is not inner
  301. /// relative to the destination block.
  302. bool isLoopEnteringEdge(const LoopEdge &Edge) const;
  303. /// Returns true if source block belongs to some loop and destination block is
  304. /// either doesn't belong to any loop or belongs to a loop which is not inner
  305. /// relative to the source block.
  306. bool isLoopExitingEdge(const LoopEdge &Edge) const;
  307. /// Returns true if \p Edge is either enters to or exits from some loop, false
  308. /// in all other cases.
  309. bool isLoopEnteringExitingEdge(const LoopEdge &Edge) const;
  310. /// Returns true if source and destination blocks belongs to the same loop and
  311. /// destination block is loop header.
  312. bool isLoopBackEdge(const LoopEdge &Edge) const;
  313. // Fills in \p Enters vector with all "enter" blocks to a loop \LB belongs to.
  314. void getLoopEnterBlocks(const LoopBlock &LB,
  315. SmallVectorImpl<BasicBlock *> &Enters) const;
  316. // Fills in \p Exits vector with all "exit" blocks from a loop \LB belongs to.
  317. void getLoopExitBlocks(const LoopBlock &LB,
  318. SmallVectorImpl<BasicBlock *> &Exits) const;
  319. /// Returns estimated weight for \p BB. std::nullopt if \p BB has no estimated
  320. /// weight.
  321. std::optional<uint32_t> getEstimatedBlockWeight(const BasicBlock *BB) const;
  322. /// Returns estimated weight to enter \p L. In other words it is weight of
  323. /// loop's header block not scaled by trip count. Returns std::nullopt if \p L
  324. /// has no no estimated weight.
  325. std::optional<uint32_t> getEstimatedLoopWeight(const LoopData &L) const;
  326. /// Return estimated weight for \p Edge. Returns std::nullopt if estimated
  327. /// weight is unknown.
  328. std::optional<uint32_t> getEstimatedEdgeWeight(const LoopEdge &Edge) const;
  329. /// Iterates over all edges leading from \p SrcBB to \p Successors and
  330. /// returns maximum of all estimated weights. If at least one edge has unknown
  331. /// estimated weight std::nullopt is returned.
  332. template <class IterT>
  333. std::optional<uint32_t>
  334. getMaxEstimatedEdgeWeight(const LoopBlock &SrcBB,
  335. iterator_range<IterT> Successors) const;
  336. /// If \p LoopBB has no estimated weight then set it to \p BBWeight and
  337. /// return true. Otherwise \p BB's weight remains unchanged and false is
  338. /// returned. In addition all blocks/loops that might need their weight to be
  339. /// re-estimated are put into BlockWorkList/LoopWorkList.
  340. bool updateEstimatedBlockWeight(LoopBlock &LoopBB, uint32_t BBWeight,
  341. SmallVectorImpl<BasicBlock *> &BlockWorkList,
  342. SmallVectorImpl<LoopBlock> &LoopWorkList);
  343. /// Starting from \p LoopBB (including \p LoopBB itself) propagate \p BBWeight
  344. /// up the domination tree.
  345. void propagateEstimatedBlockWeight(const LoopBlock &LoopBB, DominatorTree *DT,
  346. PostDominatorTree *PDT, uint32_t BBWeight,
  347. SmallVectorImpl<BasicBlock *> &WorkList,
  348. SmallVectorImpl<LoopBlock> &LoopWorkList);
  349. /// Returns block's weight encoded in the IR.
  350. std::optional<uint32_t> getInitialEstimatedBlockWeight(const BasicBlock *BB);
  351. // Computes estimated weights for all blocks in \p F.
  352. void computeEestimateBlockWeight(const Function &F, DominatorTree *DT,
  353. PostDominatorTree *PDT);
  354. /// Based on computed weights by \p computeEstimatedBlockWeight set
  355. /// probabilities on branches.
  356. bool calcEstimatedHeuristics(const BasicBlock *BB);
  357. bool calcMetadataWeights(const BasicBlock *BB);
  358. bool calcPointerHeuristics(const BasicBlock *BB);
  359. bool calcZeroHeuristics(const BasicBlock *BB, const TargetLibraryInfo *TLI);
  360. bool calcFloatingPointHeuristics(const BasicBlock *BB);
  361. };
  362. /// Analysis pass which computes \c BranchProbabilityInfo.
  363. class BranchProbabilityAnalysis
  364. : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
  365. friend AnalysisInfoMixin<BranchProbabilityAnalysis>;
  366. static AnalysisKey Key;
  367. public:
  368. /// Provide the result type for this analysis pass.
  369. using Result = BranchProbabilityInfo;
  370. /// Run the analysis pass over a function and produce BPI.
  371. BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM);
  372. };
  373. /// Printer pass for the \c BranchProbabilityAnalysis results.
  374. class BranchProbabilityPrinterPass
  375. : public PassInfoMixin<BranchProbabilityPrinterPass> {
  376. raw_ostream &OS;
  377. public:
  378. explicit BranchProbabilityPrinterPass(raw_ostream &OS) : OS(OS) {}
  379. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  380. };
  381. /// Legacy analysis pass which computes \c BranchProbabilityInfo.
  382. class BranchProbabilityInfoWrapperPass : public FunctionPass {
  383. BranchProbabilityInfo BPI;
  384. public:
  385. static char ID;
  386. BranchProbabilityInfoWrapperPass();
  387. BranchProbabilityInfo &getBPI() { return BPI; }
  388. const BranchProbabilityInfo &getBPI() const { return BPI; }
  389. void getAnalysisUsage(AnalysisUsage &AU) const override;
  390. bool runOnFunction(Function &F) override;
  391. void releaseMemory() override;
  392. void print(raw_ostream &OS, const Module *M = nullptr) const override;
  393. };
  394. } // end namespace llvm
  395. #endif // LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
  396. #ifdef __GNUC__
  397. #pragma GCC diagnostic pop
  398. #endif