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