1 //===--- BranchProbabilityInfo.h - Branch Probability Analysis --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is used to evaluate branch probabilties.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
15 #define LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/PassManager.h"
22 #include "llvm/IR/ValueHandle.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/BranchProbability.h"
31 /// \brief Analysis providing branch probability information.
33 /// This is a function analysis which provides information on the relative
34 /// probabilities of each "edge" in the function's CFG where such an edge is
35 /// defined by a pair (PredBlock and an index in the successors). The
36 /// probability of an edge from one block is always relative to the
37 /// probabilities of other edges from the block. The probabilites of all edges
38 /// from a block sum to exactly one (100%).
39 /// We use a pair (PredBlock and an index in the successors) to uniquely
40 /// identify an edge, since we can have multiple edges from Src to Dst.
41 /// As an example, we can have a switch which jumps to Dst with value 0 and
43 class BranchProbabilityInfo {
45 BranchProbabilityInfo() {}
46 BranchProbabilityInfo(const Function &F, const LoopInfo &LI) {
50 BranchProbabilityInfo(BranchProbabilityInfo &&Arg)
51 : Probs(std::move(Arg.Probs)), LastF(Arg.LastF),
52 PostDominatedByUnreachable(std::move(Arg.PostDominatedByUnreachable)),
53 PostDominatedByColdCall(std::move(Arg.PostDominatedByColdCall)) {}
55 BranchProbabilityInfo &operator=(BranchProbabilityInfo &&RHS) {
57 Probs = std::move(RHS.Probs);
58 PostDominatedByColdCall = std::move(RHS.PostDominatedByColdCall);
59 PostDominatedByUnreachable = std::move(RHS.PostDominatedByUnreachable);
65 void print(raw_ostream &OS) const;
67 /// \brief Get an edge's probability, relative to other out-edges of the Src.
69 /// This routine provides access to the fractional probability between zero
70 /// (0%) and one (100%) of this edge executing, relative to other edges
71 /// leaving the 'Src' block. The returned probability is never zero, and can
72 /// only be one if the source block has only one successor.
73 BranchProbability getEdgeProbability(const BasicBlock *Src,
74 unsigned IndexInSuccessors) const;
76 /// \brief Get the probability of going from Src to Dst.
78 /// It returns the sum of all probabilities for edges from Src to Dst.
79 BranchProbability getEdgeProbability(const BasicBlock *Src,
80 const BasicBlock *Dst) const;
82 BranchProbability getEdgeProbability(const BasicBlock *Src,
83 succ_const_iterator Dst) const;
85 /// \brief Test if an edge is hot relative to other out-edges of the Src.
87 /// Check whether this edge out of the source block is 'hot'. We define hot
88 /// as having a relative probability >= 80%.
89 bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
91 /// \brief Retrieve the hot successor of a block if one exists.
93 /// Given a basic block, look through its successors and if one exists for
94 /// which \see isEdgeHot would return true, return that successor block.
95 const BasicBlock *getHotSucc(const BasicBlock *BB) const;
97 /// \brief Print an edge's probability.
99 /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
100 /// then prints that probability to the provided stream. That stream is then
102 raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
103 const BasicBlock *Dst) const;
105 /// \brief Set the raw edge probability for the given edge.
107 /// This allows a pass to explicitly set the edge probability for an edge. It
108 /// can be used when updating the CFG to update and preserve the branch
109 /// probability information. Read the implementation of how these edge
110 /// probabilities are calculated carefully before using!
111 void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors,
112 BranchProbability Prob);
114 static BranchProbability getBranchProbStackProtector(bool IsLikely) {
115 static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
116 return IsLikely ? LikelyProb : LikelyProb.getCompl();
119 void calculate(const Function &F, const LoopInfo &LI);
121 /// Forget analysis results for the given basic block.
122 void eraseBlock(const BasicBlock *BB);
125 void operator=(const BranchProbabilityInfo &) = delete;
126 BranchProbabilityInfo(const BranchProbabilityInfo &) = delete;
128 // We need to store CallbackVH's in order to correctly handle basic block
130 class BasicBlockCallbackVH final : public CallbackVH {
131 BranchProbabilityInfo *BPI;
132 void deleted() override {
133 assert(BPI != nullptr);
134 BPI->eraseBlock(cast<BasicBlock>(getValPtr()));
135 BPI->Handles.erase(*this);
139 BasicBlockCallbackVH(const Value *V, BranchProbabilityInfo *BPI=nullptr)
140 : CallbackVH(const_cast<Value *>(V)), BPI(BPI) {}
142 DenseSet<BasicBlockCallbackVH, DenseMapInfo<Value*>> Handles;
144 // Since we allow duplicate edges from one basic block to another, we use
145 // a pair (PredBlock and an index in the successors) to specify an edge.
146 typedef std::pair<const BasicBlock *, unsigned> Edge;
148 // Default weight value. Used when we don't have information about the edge.
149 // TODO: DEFAULT_WEIGHT makes sense during static predication, when none of
150 // the successors have a weight yet. But it doesn't make sense when providing
151 // weight to an edge that may have siblings with non-zero weights. This can
152 // be handled various ways, but it's probably fine for an edge with unknown
153 // weight to just "inherit" the non-zero weight of an adjacent successor.
154 static const uint32_t DEFAULT_WEIGHT = 16;
156 DenseMap<Edge, BranchProbability> Probs;
158 /// \brief Track the last function we run over for printing.
159 const Function *LastF;
161 /// \brief Track the set of blocks directly succeeded by a returning block.
162 SmallPtrSet<const BasicBlock *, 16> PostDominatedByUnreachable;
164 /// \brief Track the set of blocks that always lead to a cold call.
165 SmallPtrSet<const BasicBlock *, 16> PostDominatedByColdCall;
167 void updatePostDominatedByUnreachable(const BasicBlock *BB);
168 void updatePostDominatedByColdCall(const BasicBlock *BB);
169 bool calcUnreachableHeuristics(const BasicBlock *BB);
170 bool calcMetadataWeights(const BasicBlock *BB);
171 bool calcColdCallHeuristics(const BasicBlock *BB);
172 bool calcPointerHeuristics(const BasicBlock *BB);
173 bool calcLoopBranchHeuristics(const BasicBlock *BB, const LoopInfo &LI);
174 bool calcZeroHeuristics(const BasicBlock *BB);
175 bool calcFloatingPointHeuristics(const BasicBlock *BB);
176 bool calcInvokeHeuristics(const BasicBlock *BB);
179 /// \brief Analysis pass which computes \c BranchProbabilityInfo.
180 class BranchProbabilityAnalysis
181 : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
182 friend AnalysisInfoMixin<BranchProbabilityAnalysis>;
183 static AnalysisKey Key;
186 /// \brief Provide the result typedef for this analysis pass.
187 typedef BranchProbabilityInfo Result;
189 /// \brief Run the analysis pass over a function and produce BPI.
190 BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM);
193 /// \brief Printer pass for the \c BranchProbabilityAnalysis results.
194 class BranchProbabilityPrinterPass
195 : public PassInfoMixin<BranchProbabilityPrinterPass> {
199 explicit BranchProbabilityPrinterPass(raw_ostream &OS) : OS(OS) {}
200 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
203 /// \brief Legacy analysis pass which computes \c BranchProbabilityInfo.
204 class BranchProbabilityInfoWrapperPass : public FunctionPass {
205 BranchProbabilityInfo BPI;
210 BranchProbabilityInfoWrapperPass() : FunctionPass(ID) {
211 initializeBranchProbabilityInfoWrapperPassPass(
212 *PassRegistry::getPassRegistry());
215 BranchProbabilityInfo &getBPI() { return BPI; }
216 const BranchProbabilityInfo &getBPI() const { return BPI; }
218 void getAnalysisUsage(AnalysisUsage &AU) const override;
219 bool runOnFunction(Function &F) override;
220 void releaseMemory() override;
221 void print(raw_ostream &OS, const Module *M = nullptr) const override;