BranchProbabilityInfo.h 19 KB

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