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;
35class Value;
36
37/// Analysis providing branch probability information.
38///
39/// This is a function analysis which provides information on the relative
40/// probabilities of each "edge" in the function's CFG where such an edge is
41/// defined by a pair (PredBlock and an index in the successors). The
42/// probability of an edge from one block is always relative to the
43/// probabilities of other edges from the block. The probabilites of all edges
44/// from a block sum to exactly one (100%).
45/// We use a pair (PredBlock and an index in the successors) to uniquely
46/// identify an edge, since we can have multiple edges from Src to Dst.
47/// As an example, we can have a switch which jumps to Dst with value 0 and
48/// value 10.
49///
50/// Process of computing branch probabilities can be logically viewed as three
51/// step process:
52///
53/// First, if there is a profile information associated with the branch then
54/// it is trivially translated to branch probabilities. There is one exception
55/// from this rule though. Probabilities for edges leading to "unreachable"
56/// blocks (blocks with the estimated weight not greater than
57/// UNREACHABLE_WEIGHT) are evaluated according to static estimation and
58/// override profile information. If no branch probabilities were calculated
59/// on this step then take the next one.
60///
61/// Second, estimate absolute execution weights for each block based on
62/// statically known information. Roots of such information are "cold",
63/// "unreachable", "noreturn" and "unwind" blocks. Those blocks get their
64/// weights set to BlockExecWeight::COLD, BlockExecWeight::UNREACHABLE,
65/// BlockExecWeight::NORETURN and BlockExecWeight::UNWIND respectively. Then the
66/// weights are propagated to the other blocks up the domination line. In
67/// addition, if all successors have estimated weights set then maximum of these
68/// weights assigned to the block itself (while this is not ideal heuristic in
69/// theory it's simple and works reasonably well in most cases) and the process
70/// repeats. Once the process of weights propagation converges branch
71/// probabilities are set for all such branches that have at least one successor
72/// with the weight set. Default execution weight (BlockExecWeight::DEFAULT) is
73/// used for any successors which doesn't have its weight set. For loop back
74/// branches we use their weights scaled by loop trip count equal to
75/// 'LBH_TAKEN_WEIGHT/LBH_NOTTAKEN_WEIGHT'.
76///
77/// Here is a simple example demonstrating how the described algorithm works.
78///
79/// BB1
80/// / \
81/// v v
82/// BB2 BB3
83/// / \
84/// v v
85/// ColdBB UnreachBB
86///
87/// Initially, ColdBB is associated with COLD_WEIGHT and UnreachBB with
88/// UNREACHABLE_WEIGHT. COLD_WEIGHT is set to BB2 as maximum between its
89/// successors. BB1 and BB3 has no explicit estimated weights and assumed to
90/// have DEFAULT_WEIGHT. Based on assigned weights branches will have the
91/// following probabilities:
92/// P(BB1->BB2) = COLD_WEIGHT/(COLD_WEIGHT + DEFAULT_WEIGHT) =
93/// 0xffff / (0xffff + 0xfffff) = 0.0588(5.9%)
94/// P(BB1->BB3) = DEFAULT_WEIGHT_WEIGHT/(COLD_WEIGHT + DEFAULT_WEIGHT) =
95/// 0xfffff / (0xffff + 0xfffff) = 0.941(94.1%)
96/// P(BB2->ColdBB) = COLD_WEIGHT/(COLD_WEIGHT + UNREACHABLE_WEIGHT) = 1(100%)
97/// P(BB2->UnreachBB) =
98/// UNREACHABLE_WEIGHT/(COLD_WEIGHT+UNREACHABLE_WEIGHT) = 0(0%)
99///
100/// If no branch probabilities were calculated on this step then take the next
101/// one.
102///
103/// Third, apply different kinds of local heuristics for each individual
104/// branch until first match. For example probability of a pointer to be null is
105/// estimated as PH_TAKEN_WEIGHT/(PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT). If
106/// no local heuristic has been matched then branch is left with no explicit
107/// probability set and assumed to have default probability.
109public:
111
113 const TargetLibraryInfo *TLI = nullptr,
114 DominatorTree *DT = nullptr,
115 PostDominatorTree *PDT = nullptr) {
116 calculate(F, CI, TLI, DT, PDT);
117 }
118
120 FunctionAnalysisManager::Invalidator &);
121
122 LLVM_ABI void print(raw_ostream &OS) const;
123
124 /// Get an edge's probability, relative to other out-edges of the Src.
125 ///
126 /// This routine provides access to the fractional probability between zero
127 /// (0%) and one (100%) of this edge executing, relative to other edges
128 /// leaving the 'Src' block. The returned probability is never zero, and can
129 /// only be one if the source block has only one successor.
131 getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const;
132
133 /// Get the probability of going from Src to Dst.
134 ///
135 /// It returns the sum of all probabilities for edges from Src to Dst.
137 const BasicBlock *Dst) const;
138
139 /// Test if an edge is hot relative to other out-edges of the Src.
140 ///
141 /// Check whether this edge out of the source block is 'hot'. We define hot
142 /// as having a relative probability > 80%.
143 LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
144
145 /// Print an edge's probability.
146 ///
147 /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
148 /// then prints that probability to the provided stream. That stream is then
149 /// returned.
151 const BasicBlock *Src,
152 const BasicBlock *Dst) const;
153
154 /// Set the raw probabilities for all edges from the given block.
155 ///
156 /// This allows a pass to explicitly set edge probabilities for a block. It
157 /// can be used when updating the CFG to update the branch probability
158 /// information.
159 LLVM_ABI void setEdgeProbability(const BasicBlock *Src,
161
162 /// Copy outgoing edge probabilities from \p Src to \p Dst.
163 ///
164 /// This allows to keep probabilities unset for the destination if they were
165 /// unset for source.
167
168 /// Swap outgoing edges probabilities for \p Src with branch terminator
170
172 static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
173 return IsLikely ? LikelyProb : LikelyProb.getCompl();
174 }
175
176 LLVM_ABI void calculate(const Function &F, const CycleInfo &CI,
177 const TargetLibraryInfo *TLI, DominatorTree *DT,
178 PostDominatorTree *PDT);
179
180 /// Forget analysis results for the given basic block.
181 LLVM_ABI void eraseBlock(const BasicBlock *BB);
182
183private:
185 ArrayRef<BranchProbability> getEdges(const BasicBlock *BB) const;
186
187 // Storage for branch probabilities.
189 // Map from block number to first edge.
190 SmallVector<unsigned> EdgeStarts;
191
192 /// Track the last function we run over for printing.
193 const Function *LastF = nullptr;
194 unsigned BlockNumberEpoch;
195};
196
197/// Analysis pass which computes \c BranchProbabilityInfo.
199 : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
201
202 LLVM_ABI static AnalysisKey Key;
203
204public:
205 /// Provide the result type for this analysis pass.
207
208 /// Run the analysis pass over a function and produce BPI.
210};
211
212/// Printer pass for the \c BranchProbabilityAnalysis results.
214 : public RequiredPassInfoMixin<BranchProbabilityPrinterPass> {
215 raw_ostream &OS;
216
217public:
219
221};
222
223/// Legacy analysis pass which computes \c BranchProbabilityInfo.
226
227public:
228 static char ID;
229
231
232 BranchProbabilityInfo &getBPI() { return BPI; }
233 const BranchProbabilityInfo &getBPI() const { return BPI; }
234
235 void getAnalysisUsage(AnalysisUsage &AU) const override;
236 bool runOnFunction(Function &F) override;
237 void print(raw_ostream &OS, const Module *M = nullptr) const override;
238};
239
240} // end namespace llvm
241
242#endif // LLVM_ANALYSIS_BRANCHPROBABILITYINFO_H
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define LLVM_ABI
Definition Compiler.h:215
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:62
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.
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:151
FunctionPass(char &pid)
Definition Pass.h:316
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
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.
LLVM Value Representation.
Definition Value.h:75
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.