LLVM 24.0.0git
BranchProbabilityInfo.h
Go to the documentation of this file.
1//===- BranchProbabilityInfo.h - Branch Probability Analysis ----*- 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 pass is used to evaluate branch probabilties.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
14#define LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
15
16#include "llvm/IR/BasicBlock.h"
17#include "llvm/IR/CFG.h"
18#include "llvm/IR/PassManager.h"
19#include "llvm/Pass.h"
22#include <cassert>
23#include <cstdint>
24#include <memory>
25#include <utility>
26
27namespace llvm {
28
29class Function;
30class CycleInfo;
31class raw_ostream;
32class DominatorTree;
35
36/// Analysis providing branch probability information.
37///
38/// This is a function analysis which provides information on the relative
39/// probabilities of each "edge" in the function's CFG where such an edge is
40/// defined by a pair (PredBlock and an index in the successors). The
41/// probability of an edge from one block is always relative to the
42/// probabilities of other edges from the block. The probabilites of all edges
43/// from a block sum to exactly one (100%).
44/// We use a pair (PredBlock and an index in the successors) to uniquely
45/// identify an edge, since we can have multiple edges from Src to Dst.
46/// As an example, we can have a switch which jumps to Dst with value 0 and
47/// value 10.
48///
49/// Process of computing branch probabilities can be logically viewed as three
50/// step process:
51///
52/// First, if there is a profile information associated with the branch then
53/// it is trivially translated to branch probabilities. There is one exception
54/// from this rule though. Probabilities for edges leading to "unreachable"
55/// blocks (blocks with the estimated weight not greater than
56/// UNREACHABLE_WEIGHT) are evaluated according to static estimation and
57/// override profile information. If no branch probabilities were calculated
58/// on this step then take the next one.
59///
60/// Second, estimate absolute execution weights for each block based on
61/// statically known information. Roots of such information are "cold",
62/// "unreachable", "noreturn" and "unwind" blocks. Those blocks get their
63/// weights set to BlockExecWeight::COLD, BlockExecWeight::UNREACHABLE,
64/// BlockExecWeight::NORETURN and BlockExecWeight::UNWIND respectively. Then the
65/// weights are propagated to the other blocks up the domination line. In
66/// addition, if all successors have estimated weights set then maximum of these
67/// weights assigned to the block itself (while this is not ideal heuristic in
68/// theory it's simple and works reasonably well in most cases) and the process
69/// repeats. Once the process of weights propagation converges branch
70/// probabilities are set for all such branches that have at least one successor
71/// with the weight set. Default execution weight (BlockExecWeight::DEFAULT) is
72/// used for any successors which doesn't have its weight set. For loop back
73/// branches we use their weights scaled by loop trip count equal to
74/// 'LBH_TAKEN_WEIGHT/LBH_NOTTAKEN_WEIGHT'.
75///
76/// Here is a simple example demonstrating how the described algorithm works.
77///
78/// BB1
79/// / \
80/// v v
81/// BB2 BB3
82/// / \
83/// v v
84/// ColdBB UnreachBB
85///
86/// Initially, ColdBB is associated with COLD_WEIGHT and UnreachBB with
87/// UNREACHABLE_WEIGHT. COLD_WEIGHT is set to BB2 as maximum between its
88/// successors. BB1 and BB3 has no explicit estimated weights and assumed to
89/// have DEFAULT_WEIGHT. Based on assigned weights branches will have the
90/// following probabilities:
91/// P(BB1->BB2) = COLD_WEIGHT/(COLD_WEIGHT + DEFAULT_WEIGHT) =
92/// 0xffff / (0xffff + 0xfffff) = 0.0588(5.9%)
93/// P(BB1->BB3) = DEFAULT_WEIGHT_WEIGHT/(COLD_WEIGHT + DEFAULT_WEIGHT) =
94/// 0xfffff / (0xffff + 0xfffff) = 0.941(94.1%)
95/// P(BB2->ColdBB) = COLD_WEIGHT/(COLD_WEIGHT + UNREACHABLE_WEIGHT) = 1(100%)
96/// P(BB2->UnreachBB) =
97/// UNREACHABLE_WEIGHT/(COLD_WEIGHT+UNREACHABLE_WEIGHT) = 0(0%)
98///
99/// If no branch probabilities were calculated on this step then take the next
100/// one.
101///
102/// Third, apply different kinds of local heuristics for each individual
103/// branch until first match. For example probability of a pointer to be null is
104/// estimated as PH_TAKEN_WEIGHT/(PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT). If
105/// no local heuristic has been matched then branch is left with no explicit
106/// probability set and assumed to have default probability.
108public:
110
112 const TargetLibraryInfo *TLI = nullptr,
113 DominatorTree *DT = nullptr,
114 PostDominatorTree *PDT = nullptr) {
115 calculate(F, CI, TLI, DT, PDT);
116 }
117
119 FunctionAnalysisManager::Invalidator &);
120
121 LLVM_ABI void print(raw_ostream &OS) const;
122
123 /// Get an edge's probability, relative to other out-edges of the Src.
124 ///
125 /// This routine provides access to the fractional probability between zero
126 /// (0%) and one (100%) of this edge executing, relative to other edges
127 /// leaving the 'Src' block. The returned probability is never zero, and can
128 /// only be one if the source block has only one successor.
130 getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const;
131
132 /// Get the probability of going from Src to Dst.
133 ///
134 /// It returns the sum of all probabilities for edges from Src to Dst.
136 const BasicBlock *Dst) const;
137
138 /// Test if an edge is hot relative to other out-edges of the Src.
139 ///
140 /// Check whether this edge out of the source block is 'hot'. We define hot
141 /// as having a relative probability > 80%.
142 LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
143
144 /// Print an edge's probability.
145 ///
146 /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
147 /// then prints that probability to the provided stream. That stream is then
148 /// returned.
150 const BasicBlock *Src,
151 const BasicBlock *Dst) const;
152
153 /// Set the raw probabilities for all edges from the given block.
154 ///
155 /// This allows a pass to explicitly set edge probabilities for a block. It
156 /// can be used when updating the CFG to update the branch probability
157 /// information.
158 LLVM_ABI void setEdgeProbability(const BasicBlock *Src,
160
161 /// Copy outgoing edge probabilities from \p Src to \p Dst.
162 ///
163 /// This allows to keep probabilities unset for the destination if they were
164 /// unset for source.
166
167 /// Swap outgoing edges probabilities for \p Src with branch terminator
169
170 /// Returns the probabilities of edges with branch weights \p Weights.
171 /// Weights whose sum does not fit in 32 bits are scaled down, and if all
172 /// weights are zero, all edges are equally likely.
175
177 static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
178 return IsLikely ? LikelyProb : LikelyProb.getCompl();
179 }
180
181 LLVM_ABI void calculate(const Function &F, const CycleInfo &CI,
183 PostDominatorTree *PDT);
184
185 /// Forget analysis results for the given basic block.
186 LLVM_ABI void eraseBlock(const BasicBlock *BB);
187
188private:
190 ArrayRef<BranchProbability> getEdges(const BasicBlock *BB) const;
191
192 // Storage for branch probabilities.
194 // Map from block number to first edge.
195 SmallVector<unsigned> EdgeStarts;
196
197 /// Track the last function we run over for printing.
198 const Function *LastF = nullptr;
199 unsigned BlockNumberEpoch;
200};
201
202/// Analysis pass which computes \c BranchProbabilityInfo.
204 : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
206
207 LLVM_ABI static AnalysisKey Key;
208
209public:
210 /// Provide the result type for this analysis pass.
212
213 /// Run the analysis pass over a function and produce BPI.
215};
216
217/// Printer pass for the \c BranchProbabilityAnalysis results.
219 : public RequiredPassInfoMixin<BranchProbabilityPrinterPass> {
220 raw_ostream &OS;
221
222public:
224
226};
227
228/// Legacy analysis pass which computes \c BranchProbabilityInfo.
231
232public:
233 static char ID;
234
236
237 BranchProbabilityInfo &getBPI() { return BPI; }
238 const BranchProbabilityInfo &getBPI() const { return BPI; }
239
240 void getAnalysisUsage(AnalysisUsage &AU) const override;
241 bool runOnFunction(Function &F) override;
242 void print(raw_ostream &OS, const Module *M = nullptr) const override;
243};
244
245} // end namespace llvm
246
247#endif // LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
const TargetLowering & TLI
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define LLVM_ABI
Definition Compiler.h:211
static bool runOnFunction(Function &F, bool PostInlining)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
Represent the analysis usage information of a pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:61
Analysis pass which computes BranchProbabilityInfo.
LLVM_ABI BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BPI.
BranchProbabilityInfo Result
Provide the result type for this analysis pass.
const BranchProbabilityInfo & getBPI() const
Analysis providing branch probability information.
static LLVM_ABI SmallVector< BranchProbability > getEdgeProbabilitiesFromWeights(ArrayRef< uint32_t > Weights)
Returns the probabilities of edges with branch weights Weights.
LLVM_ABI void eraseBlock(const BasicBlock *BB)
Forget analysis results for the given basic block.
LLVM_ABI void calculate(const Function &F, const CycleInfo &CI, const TargetLibraryInfo *TLI, DominatorTree *DT, PostDominatorTree *PDT)
LLVM_ABI bool invalidate(Function &, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
static BranchProbability getBranchProbStackProtector(bool IsLikely)
LLVM_ABI void setEdgeProbability(const BasicBlock *Src, ArrayRef< BranchProbability > Probs)
Set the raw probabilities for all edges from the given block.
LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
LLVM_ABI void swapSuccEdgesProbabilities(const BasicBlock *Src)
Swap outgoing edges probabilities for Src with branch terminator.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI raw_ostream & printEdgeProbability(raw_ostream &OS, const BasicBlock *Src, const BasicBlock *Dst) const
Print an edge's probability.
LLVM_ABI void copyEdgeProbabilities(BasicBlock *Src, BasicBlock *Dst)
Copy outgoing edge probabilities from Src to Dst.
BranchProbabilityInfo(const Function &F, const CycleInfo &CI, const TargetLibraryInfo *TLI=nullptr, DominatorTree *DT=nullptr, PostDominatorTree *PDT=nullptr)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
BranchProbability getCompl() const
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
FunctionPass(char &pid)
Definition Pass.h:314
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Provides information about what library functions are available for the current target.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
A CRTP mix-in that provides informational APIs needed for analysis passes.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
A CRTP mix-in for passes that should not be skipped.