1 //===--- BranchProbabilityInfo.h - Branch Probability Analysis --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is used to evaluate branch probabilties.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
15 #define LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/IR/CFG.h"
20 #include "llvm/InitializePasses.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Support/BranchProbability.h"
23 
24 namespace llvm {
25 class LoopInfo;
26 class raw_ostream;
27 
28 /// \brief Analysis providing branch probability information.
29 ///
30 /// This is a function analysis which provides information on the relative
31 /// probabilities of each "edge" in the function's CFG where such an edge is
32 /// defined by a pair (PredBlock and an index in the successors). The
33 /// probability of an edge from one block is always relative to the
34 /// probabilities of other edges from the block. The probabilites of all edges
35 /// from a block sum to exactly one (100%).
36 /// We use a pair (PredBlock and an index in the successors) to uniquely
37 /// identify an edge, since we can have multiple edges from Src to Dst.
38 /// As an example, we can have a switch which jumps to Dst with value 0 and
39 /// value 10.
40 class BranchProbabilityInfo {
41 public:
BranchProbabilityInfo()42   BranchProbabilityInfo() {}
BranchProbabilityInfo(Function & F,const LoopInfo & LI)43   BranchProbabilityInfo(Function &F, const LoopInfo &LI) { calculate(F, LI); }
44 
45   void releaseMemory();
46 
47   void print(raw_ostream &OS) const;
48 
49   /// \brief Get an edge's probability, relative to other out-edges of the Src.
50   ///
51   /// This routine provides access to the fractional probability between zero
52   /// (0%) and one (100%) of this edge executing, relative to other edges
53   /// leaving the 'Src' block. The returned probability is never zero, and can
54   /// only be one if the source block has only one successor.
55   BranchProbability getEdgeProbability(const BasicBlock *Src,
56                                        unsigned IndexInSuccessors) const;
57 
58   /// \brief Get the probability of going from Src to Dst.
59   ///
60   /// It returns the sum of all probabilities for edges from Src to Dst.
61   BranchProbability getEdgeProbability(const BasicBlock *Src,
62                                        const BasicBlock *Dst) const;
63 
64   BranchProbability getEdgeProbability(const BasicBlock *Src,
65                                        succ_const_iterator Dst) const;
66 
67   /// \brief Test if an edge is hot relative to other out-edges of the Src.
68   ///
69   /// Check whether this edge out of the source block is 'hot'. We define hot
70   /// as having a relative probability >= 80%.
71   bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
72 
73   /// \brief Retrieve the hot successor of a block if one exists.
74   ///
75   /// Given a basic block, look through its successors and if one exists for
76   /// which \see isEdgeHot would return true, return that successor block.
77   BasicBlock *getHotSucc(BasicBlock *BB) const;
78 
79   /// \brief Print an edge's probability.
80   ///
81   /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
82   /// then prints that probability to the provided stream. That stream is then
83   /// returned.
84   raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
85                                     const BasicBlock *Dst) const;
86 
87   /// \brief Get the raw edge weight calculated for the edge.
88   ///
89   /// This returns the raw edge weight. It is guaranteed to fall between 1 and
90   /// UINT32_MAX. Note that the raw edge weight is not meaningful in isolation.
91   /// This interface should be very carefully, and primarily by routines that
92   /// are updating the analysis by later calling setEdgeWeight.
93   uint32_t getEdgeWeight(const BasicBlock *Src,
94                          unsigned IndexInSuccessors) const;
95 
96   /// \brief Get the raw edge weight calculated for the block pair.
97   ///
98   /// This returns the sum of all raw edge weights from Src to Dst.
99   /// It is guaranteed to fall between 1 and UINT32_MAX.
100   uint32_t getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const;
101 
102   uint32_t getEdgeWeight(const BasicBlock *Src,
103                          succ_const_iterator Dst) const;
104 
105   /// \brief Set the raw edge weight for a given edge.
106   ///
107   /// This allows a pass to explicitly set the edge weight for an edge. It can
108   /// be used when updating the CFG to update and preserve the branch
109   /// probability information. Read the implementation of how these edge
110   /// weights are calculated carefully before using!
111   void setEdgeWeight(const BasicBlock *Src, unsigned IndexInSuccessors,
112                      uint32_t Weight);
113 
getBranchWeightStackProtector(bool IsLikely)114   static uint32_t getBranchWeightStackProtector(bool IsLikely) {
115     return IsLikely ? (1u << 20) - 1 : 1;
116   }
117 
getBranchProbStackProtector(bool IsLikely)118   static BranchProbability getBranchProbStackProtector(bool IsLikely) {
119     static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
120     return IsLikely ? LikelyProb : LikelyProb.getCompl();
121   }
122 
123   void calculate(Function &F, const LoopInfo& LI);
124 
125 private:
126   // Since we allow duplicate edges from one basic block to another, we use
127   // a pair (PredBlock and an index in the successors) to specify an edge.
128   typedef std::pair<const BasicBlock *, unsigned> Edge;
129 
130   // Default weight value. Used when we don't have information about the edge.
131   // TODO: DEFAULT_WEIGHT makes sense during static predication, when none of
132   // the successors have a weight yet. But it doesn't make sense when providing
133   // weight to an edge that may have siblings with non-zero weights. This can
134   // be handled various ways, but it's probably fine for an edge with unknown
135   // weight to just "inherit" the non-zero weight of an adjacent successor.
136   static const uint32_t DEFAULT_WEIGHT = 16;
137 
138   DenseMap<Edge, uint32_t> Weights;
139 
140   /// \brief Track the last function we run over for printing.
141   Function *LastF;
142 
143   /// \brief Track the set of blocks directly succeeded by a returning block.
144   SmallPtrSet<BasicBlock *, 16> PostDominatedByUnreachable;
145 
146   /// \brief Track the set of blocks that always lead to a cold call.
147   SmallPtrSet<BasicBlock *, 16> PostDominatedByColdCall;
148 
149   /// \brief Get sum of the block successors' weights.
150   uint32_t getSumForBlock(const BasicBlock *BB) const;
151 
152   bool calcUnreachableHeuristics(BasicBlock *BB);
153   bool calcMetadataWeights(BasicBlock *BB);
154   bool calcColdCallHeuristics(BasicBlock *BB);
155   bool calcPointerHeuristics(BasicBlock *BB);
156   bool calcLoopBranchHeuristics(BasicBlock *BB, const LoopInfo &LI);
157   bool calcZeroHeuristics(BasicBlock *BB);
158   bool calcFloatingPointHeuristics(BasicBlock *BB);
159   bool calcInvokeHeuristics(BasicBlock *BB);
160 };
161 
162 /// \brief Legacy analysis pass which computes \c BranchProbabilityInfo.
163 class BranchProbabilityInfoWrapperPass : public FunctionPass {
164   BranchProbabilityInfo BPI;
165 
166 public:
167   static char ID;
168 
BranchProbabilityInfoWrapperPass()169   BranchProbabilityInfoWrapperPass() : FunctionPass(ID) {
170     initializeBranchProbabilityInfoWrapperPassPass(
171         *PassRegistry::getPassRegistry());
172   }
173 
getBPI()174   BranchProbabilityInfo &getBPI() { return BPI; }
getBPI()175   const BranchProbabilityInfo &getBPI() const { return BPI; }
176 
177   void getAnalysisUsage(AnalysisUsage &AU) const override;
178   bool runOnFunction(Function &F) override;
179   void releaseMemory() override;
180   void print(raw_ostream &OS, const Module *M = nullptr) const override;
181 };
182 
183 }
184 
185 #endif
186