Home | History | Annotate | Download | only in Analysis
      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/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"
     26 
     27 namespace llvm {
     28 class LoopInfo;
     29 class TargetLibraryInfo;
     30 class raw_ostream;
     31 
     32 /// \brief Analysis providing branch probability information.
     33 ///
     34 /// This is a function analysis which provides information on the relative
     35 /// probabilities of each "edge" in the function's CFG where such an edge is
     36 /// defined by a pair (PredBlock and an index in the successors). The
     37 /// probability of an edge from one block is always relative to the
     38 /// probabilities of other edges from the block. The probabilites of all edges
     39 /// from a block sum to exactly one (100%).
     40 /// We use a pair (PredBlock and an index in the successors) to uniquely
     41 /// identify an edge, since we can have multiple edges from Src to Dst.
     42 /// As an example, we can have a switch which jumps to Dst with value 0 and
     43 /// value 10.
     44 class BranchProbabilityInfo {
     45 public:
     46   BranchProbabilityInfo() {}
     47   BranchProbabilityInfo(const Function &F, const LoopInfo &LI,
     48                         const TargetLibraryInfo *TLI = nullptr) {
     49     calculate(F, LI, TLI);
     50   }
     51 
     52   BranchProbabilityInfo(BranchProbabilityInfo &&Arg)
     53       : Probs(std::move(Arg.Probs)), LastF(Arg.LastF),
     54         PostDominatedByUnreachable(std::move(Arg.PostDominatedByUnreachable)),
     55         PostDominatedByColdCall(std::move(Arg.PostDominatedByColdCall)) {}
     56 
     57   BranchProbabilityInfo &operator=(BranchProbabilityInfo &&RHS) {
     58     releaseMemory();
     59     Probs = std::move(RHS.Probs);
     60     PostDominatedByColdCall = std::move(RHS.PostDominatedByColdCall);
     61     PostDominatedByUnreachable = std::move(RHS.PostDominatedByUnreachable);
     62     return *this;
     63   }
     64 
     65   void releaseMemory();
     66 
     67   void print(raw_ostream &OS) const;
     68 
     69   /// \brief Get an edge's probability, relative to other out-edges of the Src.
     70   ///
     71   /// This routine provides access to the fractional probability between zero
     72   /// (0%) and one (100%) of this edge executing, relative to other edges
     73   /// leaving the 'Src' block. The returned probability is never zero, and can
     74   /// only be one if the source block has only one successor.
     75   BranchProbability getEdgeProbability(const BasicBlock *Src,
     76                                        unsigned IndexInSuccessors) const;
     77 
     78   /// \brief Get the probability of going from Src to Dst.
     79   ///
     80   /// It returns the sum of all probabilities for edges from Src to Dst.
     81   BranchProbability getEdgeProbability(const BasicBlock *Src,
     82                                        const BasicBlock *Dst) const;
     83 
     84   BranchProbability getEdgeProbability(const BasicBlock *Src,
     85                                        succ_const_iterator Dst) const;
     86 
     87   /// \brief Test if an edge is hot relative to other out-edges of the Src.
     88   ///
     89   /// Check whether this edge out of the source block is 'hot'. We define hot
     90   /// as having a relative probability >= 80%.
     91   bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const;
     92 
     93   /// \brief Retrieve the hot successor of a block if one exists.
     94   ///
     95   /// Given a basic block, look through its successors and if one exists for
     96   /// which \see isEdgeHot would return true, return that successor block.
     97   const BasicBlock *getHotSucc(const BasicBlock *BB) const;
     98 
     99   /// \brief Print an edge's probability.
    100   ///
    101   /// Retrieves an edge's probability similarly to \see getEdgeProbability, but
    102   /// then prints that probability to the provided stream. That stream is then
    103   /// returned.
    104   raw_ostream &printEdgeProbability(raw_ostream &OS, const BasicBlock *Src,
    105                                     const BasicBlock *Dst) const;
    106 
    107   /// \brief Set the raw edge probability for the given edge.
    108   ///
    109   /// This allows a pass to explicitly set the edge probability for an edge. It
    110   /// can be used when updating the CFG to update and preserve the branch
    111   /// probability information. Read the implementation of how these edge
    112   /// probabilities are calculated carefully before using!
    113   void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors,
    114                           BranchProbability Prob);
    115 
    116   static BranchProbability getBranchProbStackProtector(bool IsLikely) {
    117     static const BranchProbability LikelyProb((1u << 20) - 1, 1u << 20);
    118     return IsLikely ? LikelyProb : LikelyProb.getCompl();
    119   }
    120 
    121   void calculate(const Function &F, const LoopInfo &LI,
    122                  const TargetLibraryInfo *TLI = nullptr);
    123 
    124   /// Forget analysis results for the given basic block.
    125   void eraseBlock(const BasicBlock *BB);
    126 
    127 private:
    128   void operator=(const BranchProbabilityInfo &) = delete;
    129   BranchProbabilityInfo(const BranchProbabilityInfo &) = delete;
    130 
    131   // We need to store CallbackVH's in order to correctly handle basic block
    132   // removal.
    133   class BasicBlockCallbackVH final : public CallbackVH {
    134     BranchProbabilityInfo *BPI;
    135     void deleted() override {
    136       assert(BPI != nullptr);
    137       BPI->eraseBlock(cast<BasicBlock>(getValPtr()));
    138       BPI->Handles.erase(*this);
    139     }
    140 
    141   public:
    142     BasicBlockCallbackVH(const Value *V, BranchProbabilityInfo *BPI=nullptr)
    143         : CallbackVH(const_cast<Value *>(V)), BPI(BPI) {}
    144   };
    145   DenseSet<BasicBlockCallbackVH, DenseMapInfo<Value*>> Handles;
    146 
    147   // Since we allow duplicate edges from one basic block to another, we use
    148   // a pair (PredBlock and an index in the successors) to specify an edge.
    149   typedef std::pair<const BasicBlock *, unsigned> Edge;
    150 
    151   // Default weight value. Used when we don't have information about the edge.
    152   // TODO: DEFAULT_WEIGHT makes sense during static predication, when none of
    153   // the successors have a weight yet. But it doesn't make sense when providing
    154   // weight to an edge that may have siblings with non-zero weights. This can
    155   // be handled various ways, but it's probably fine for an edge with unknown
    156   // weight to just "inherit" the non-zero weight of an adjacent successor.
    157   static const uint32_t DEFAULT_WEIGHT = 16;
    158 
    159   DenseMap<Edge, BranchProbability> Probs;
    160 
    161   /// \brief Track the last function we run over for printing.
    162   const Function *LastF;
    163 
    164   /// \brief Track the set of blocks directly succeeded by a returning block.
    165   SmallPtrSet<const BasicBlock *, 16> PostDominatedByUnreachable;
    166 
    167   /// \brief Track the set of blocks that always lead to a cold call.
    168   SmallPtrSet<const BasicBlock *, 16> PostDominatedByColdCall;
    169 
    170   void updatePostDominatedByUnreachable(const BasicBlock *BB);
    171   void updatePostDominatedByColdCall(const BasicBlock *BB);
    172   bool calcUnreachableHeuristics(const BasicBlock *BB);
    173   bool calcMetadataWeights(const BasicBlock *BB);
    174   bool calcColdCallHeuristics(const BasicBlock *BB);
    175   bool calcPointerHeuristics(const BasicBlock *BB);
    176   bool calcLoopBranchHeuristics(const BasicBlock *BB, const LoopInfo &LI);
    177   bool calcZeroHeuristics(const BasicBlock *BB, const TargetLibraryInfo *TLI);
    178   bool calcFloatingPointHeuristics(const BasicBlock *BB);
    179   bool calcInvokeHeuristics(const BasicBlock *BB);
    180 };
    181 
    182 /// \brief Analysis pass which computes \c BranchProbabilityInfo.
    183 class BranchProbabilityAnalysis
    184     : public AnalysisInfoMixin<BranchProbabilityAnalysis> {
    185   friend AnalysisInfoMixin<BranchProbabilityAnalysis>;
    186   static AnalysisKey Key;
    187 
    188 public:
    189   /// \brief Provide the result typedef for this analysis pass.
    190   typedef BranchProbabilityInfo Result;
    191 
    192   /// \brief Run the analysis pass over a function and produce BPI.
    193   BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM);
    194 };
    195 
    196 /// \brief Printer pass for the \c BranchProbabilityAnalysis results.
    197 class BranchProbabilityPrinterPass
    198     : public PassInfoMixin<BranchProbabilityPrinterPass> {
    199   raw_ostream &OS;
    200 
    201 public:
    202   explicit BranchProbabilityPrinterPass(raw_ostream &OS) : OS(OS) {}
    203   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
    204 };
    205 
    206 /// \brief Legacy analysis pass which computes \c BranchProbabilityInfo.
    207 class BranchProbabilityInfoWrapperPass : public FunctionPass {
    208   BranchProbabilityInfo BPI;
    209 
    210 public:
    211   static char ID;
    212 
    213   BranchProbabilityInfoWrapperPass() : FunctionPass(ID) {
    214     initializeBranchProbabilityInfoWrapperPassPass(
    215         *PassRegistry::getPassRegistry());
    216   }
    217 
    218   BranchProbabilityInfo &getBPI() { return BPI; }
    219   const BranchProbabilityInfo &getBPI() const { return BPI; }
    220 
    221   void getAnalysisUsage(AnalysisUsage &AU) const override;
    222   bool runOnFunction(Function &F) override;
    223   void releaseMemory() override;
    224   void print(raw_ostream &OS, const Module *M = nullptr) const override;
    225 };
    226 
    227 }
    228 
    229 #endif
    230