xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/BranchProbabilityInfo.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
10b57cec5SDimitry Andric //===- BranchProbabilityInfo.cpp - Branch Probability Analysis ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Loops should be simplified before this analysis.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
140b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SCCIterator.h"
160b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
19*480093f4SDimitry Andric #include "llvm/Analysis/PostDominators.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
210b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
220b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
230b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
240b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
250b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
260b57cec5SDimitry Andric #include "llvm/IR/Function.h"
270b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
280b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
290b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
300b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
310b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
320b57cec5SDimitry Andric #include "llvm/IR/PassManager.h"
330b57cec5SDimitry Andric #include "llvm/IR/Type.h"
340b57cec5SDimitry Andric #include "llvm/IR/Value.h"
35*480093f4SDimitry Andric #include "llvm/InitializePasses.h"
360b57cec5SDimitry Andric #include "llvm/Pass.h"
370b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
380b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
39*480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
400b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
410b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
420b57cec5SDimitry Andric #include <cassert>
430b57cec5SDimitry Andric #include <cstdint>
440b57cec5SDimitry Andric #include <iterator>
450b57cec5SDimitry Andric #include <utility>
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric using namespace llvm;
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric #define DEBUG_TYPE "branch-prob"
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric static cl::opt<bool> PrintBranchProb(
520b57cec5SDimitry Andric     "print-bpi", cl::init(false), cl::Hidden,
530b57cec5SDimitry Andric     cl::desc("Print the branch probability info."));
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric cl::opt<std::string> PrintBranchProbFuncName(
560b57cec5SDimitry Andric     "print-bpi-func-name", cl::Hidden,
570b57cec5SDimitry Andric     cl::desc("The option to specify the name of the function "
580b57cec5SDimitry Andric              "whose branch probability info is printed."));
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
610b57cec5SDimitry Andric                       "Branch Probability Analysis", false, true)
620b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
630b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
640b57cec5SDimitry Andric INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
650b57cec5SDimitry Andric                     "Branch Probability Analysis", false, true)
660b57cec5SDimitry Andric 
67*480093f4SDimitry Andric BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass()
68*480093f4SDimitry Andric     : FunctionPass(ID) {
69*480093f4SDimitry Andric   initializeBranchProbabilityInfoWrapperPassPass(
70*480093f4SDimitry Andric       *PassRegistry::getPassRegistry());
71*480093f4SDimitry Andric }
72*480093f4SDimitry Andric 
730b57cec5SDimitry Andric char BranchProbabilityInfoWrapperPass::ID = 0;
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric // Weights are for internal use only. They are used by heuristics to help to
760b57cec5SDimitry Andric // estimate edges' probability. Example:
770b57cec5SDimitry Andric //
780b57cec5SDimitry Andric // Using "Loop Branch Heuristics" we predict weights of edges for the
790b57cec5SDimitry Andric // block BB2.
800b57cec5SDimitry Andric //         ...
810b57cec5SDimitry Andric //          |
820b57cec5SDimitry Andric //          V
830b57cec5SDimitry Andric //         BB1<-+
840b57cec5SDimitry Andric //          |   |
850b57cec5SDimitry Andric //          |   | (Weight = 124)
860b57cec5SDimitry Andric //          V   |
870b57cec5SDimitry Andric //         BB2--+
880b57cec5SDimitry Andric //          |
890b57cec5SDimitry Andric //          | (Weight = 4)
900b57cec5SDimitry Andric //          V
910b57cec5SDimitry Andric //         BB3
920b57cec5SDimitry Andric //
930b57cec5SDimitry Andric // Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
940b57cec5SDimitry Andric // Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
950b57cec5SDimitry Andric static const uint32_t LBH_TAKEN_WEIGHT = 124;
960b57cec5SDimitry Andric static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
970b57cec5SDimitry Andric // Unlikely edges within a loop are half as likely as other edges
980b57cec5SDimitry Andric static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
990b57cec5SDimitry Andric 
1000b57cec5SDimitry Andric /// Unreachable-terminating branch taken probability.
1010b57cec5SDimitry Andric ///
1020b57cec5SDimitry Andric /// This is the probability for a branch being taken to a block that terminates
1030b57cec5SDimitry Andric /// (eventually) in unreachable. These are predicted as unlikely as possible.
1040b57cec5SDimitry Andric /// All reachable probability will equally share the remaining part.
1050b57cec5SDimitry Andric static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric /// Weight for a branch taken going into a cold block.
1080b57cec5SDimitry Andric ///
1090b57cec5SDimitry Andric /// This is the weight for a branch taken toward a block marked
1100b57cec5SDimitry Andric /// cold.  A block is marked cold if it's postdominated by a
1110b57cec5SDimitry Andric /// block containing a call to a cold function.  Cold functions
1120b57cec5SDimitry Andric /// are those marked with attribute 'cold'.
1130b57cec5SDimitry Andric static const uint32_t CC_TAKEN_WEIGHT = 4;
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric /// Weight for a branch not-taken into a cold block.
1160b57cec5SDimitry Andric ///
1170b57cec5SDimitry Andric /// This is the weight for a branch not taken toward a block marked
1180b57cec5SDimitry Andric /// cold.
1190b57cec5SDimitry Andric static const uint32_t CC_NONTAKEN_WEIGHT = 64;
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric static const uint32_t PH_TAKEN_WEIGHT = 20;
1220b57cec5SDimitry Andric static const uint32_t PH_NONTAKEN_WEIGHT = 12;
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric static const uint32_t ZH_TAKEN_WEIGHT = 20;
1250b57cec5SDimitry Andric static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric static const uint32_t FPH_TAKEN_WEIGHT = 20;
1280b57cec5SDimitry Andric static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
1290b57cec5SDimitry Andric 
1308bcb0991SDimitry Andric /// This is the probability for an ordered floating point comparison.
1318bcb0991SDimitry Andric static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1;
1328bcb0991SDimitry Andric /// This is the probability for an unordered floating point comparison, it means
1338bcb0991SDimitry Andric /// one or two of the operands are NaN. Usually it is used to test for an
1348bcb0991SDimitry Andric /// exceptional case, so the result is unlikely.
1358bcb0991SDimitry Andric static const uint32_t FPH_UNO_WEIGHT = 1;
1368bcb0991SDimitry Andric 
1370b57cec5SDimitry Andric /// Invoke-terminating normal branch taken weight
1380b57cec5SDimitry Andric ///
1390b57cec5SDimitry Andric /// This is the weight for branching to the normal destination of an invoke
1400b57cec5SDimitry Andric /// instruction. We expect this to happen most of the time. Set the weight to an
1410b57cec5SDimitry Andric /// absurdly high value so that nested loops subsume it.
1420b57cec5SDimitry Andric static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric /// Invoke-terminating normal branch not-taken weight.
1450b57cec5SDimitry Andric ///
1460b57cec5SDimitry Andric /// This is the weight for branching to the unwind destination of an invoke
1470b57cec5SDimitry Andric /// instruction. This is essentially never taken.
1480b57cec5SDimitry Andric static const uint32_t IH_NONTAKEN_WEIGHT = 1;
1490b57cec5SDimitry Andric 
150*480093f4SDimitry Andric static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT,
151*480093f4SDimitry Andric                               SmallVectorImpl<const BasicBlock *> &WorkList,
152*480093f4SDimitry Andric                               SmallPtrSetImpl<const BasicBlock *> &TargetSet) {
153*480093f4SDimitry Andric   SmallVector<BasicBlock *, 8> Descendants;
154*480093f4SDimitry Andric   SmallPtrSet<const BasicBlock *, 16> NewItems;
155*480093f4SDimitry Andric 
156*480093f4SDimitry Andric   PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants);
157*480093f4SDimitry Andric   for (auto *BB : Descendants)
158*480093f4SDimitry Andric     if (TargetSet.insert(BB).second)
159*480093f4SDimitry Andric       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
160*480093f4SDimitry Andric         if (!TargetSet.count(*PI))
161*480093f4SDimitry Andric           NewItems.insert(*PI);
162*480093f4SDimitry Andric   WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end());
163*480093f4SDimitry Andric }
164*480093f4SDimitry Andric 
165*480093f4SDimitry Andric /// Compute a set of basic blocks that are post-dominated by unreachables.
166*480093f4SDimitry Andric void BranchProbabilityInfo::computePostDominatedByUnreachable(
167*480093f4SDimitry Andric     const Function &F, PostDominatorTree *PDT) {
168*480093f4SDimitry Andric   SmallVector<const BasicBlock *, 8> WorkList;
169*480093f4SDimitry Andric   for (auto &BB : F) {
170*480093f4SDimitry Andric     const Instruction *TI = BB.getTerminator();
1710b57cec5SDimitry Andric     if (TI->getNumSuccessors() == 0) {
1720b57cec5SDimitry Andric       if (isa<UnreachableInst>(TI) ||
1730b57cec5SDimitry Andric           // If this block is terminated by a call to
174*480093f4SDimitry Andric           // @llvm.experimental.deoptimize then treat it like an unreachable
175*480093f4SDimitry Andric           // since the @llvm.experimental.deoptimize call is expected to
176*480093f4SDimitry Andric           // practically never execute.
177*480093f4SDimitry Andric           BB.getTerminatingDeoptimizeCall())
178*480093f4SDimitry Andric         UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable);
179*480093f4SDimitry Andric     }
1800b57cec5SDimitry Andric   }
1810b57cec5SDimitry Andric 
182*480093f4SDimitry Andric   while (!WorkList.empty()) {
183*480093f4SDimitry Andric     const BasicBlock *BB = WorkList.pop_back_val();
184*480093f4SDimitry Andric     if (PostDominatedByUnreachable.count(BB))
185*480093f4SDimitry Andric       continue;
186*480093f4SDimitry Andric     // If the terminator is an InvokeInst, check only the normal destination
187*480093f4SDimitry Andric     // block as the unwind edge of InvokeInst is also very unlikely taken.
188*480093f4SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
1890b57cec5SDimitry Andric       if (PostDominatedByUnreachable.count(II->getNormalDest()))
190*480093f4SDimitry Andric         UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
191*480093f4SDimitry Andric     }
192*480093f4SDimitry Andric     // If all the successors are unreachable, BB is unreachable as well.
193*480093f4SDimitry Andric     else if (!successors(BB).empty() &&
194*480093f4SDimitry Andric              llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
195*480093f4SDimitry Andric                return PostDominatedByUnreachable.count(Succ);
196*480093f4SDimitry Andric              }))
197*480093f4SDimitry Andric       UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
198*480093f4SDimitry Andric   }
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric 
201*480093f4SDimitry Andric /// compute a set of basic blocks that are post-dominated by ColdCalls.
202*480093f4SDimitry Andric void BranchProbabilityInfo::computePostDominatedByColdCall(
203*480093f4SDimitry Andric     const Function &F, PostDominatorTree *PDT) {
204*480093f4SDimitry Andric   SmallVector<const BasicBlock *, 8> WorkList;
205*480093f4SDimitry Andric   for (auto &BB : F)
206*480093f4SDimitry Andric     for (auto &I : BB)
207*480093f4SDimitry Andric       if (const CallInst *CI = dyn_cast<CallInst>(&I))
208*480093f4SDimitry Andric         if (CI->hasFnAttr(Attribute::Cold))
209*480093f4SDimitry Andric           UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall);
2100b57cec5SDimitry Andric 
211*480093f4SDimitry Andric   while (!WorkList.empty()) {
212*480093f4SDimitry Andric     const BasicBlock *BB = WorkList.pop_back_val();
2130b57cec5SDimitry Andric 
2140b57cec5SDimitry Andric     // If the terminator is an InvokeInst, check only the normal destination
2150b57cec5SDimitry Andric     // block as the unwind edge of InvokeInst is also very unlikely taken.
216*480093f4SDimitry Andric     if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
217*480093f4SDimitry Andric       if (PostDominatedByColdCall.count(II->getNormalDest()))
218*480093f4SDimitry Andric         UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
2190b57cec5SDimitry Andric     }
220*480093f4SDimitry Andric     // If all of successor are post dominated then BB is also done.
221*480093f4SDimitry Andric     else if (!successors(BB).empty() &&
222*480093f4SDimitry Andric              llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
223*480093f4SDimitry Andric                return PostDominatedByColdCall.count(Succ);
224*480093f4SDimitry Andric              }))
225*480093f4SDimitry Andric       UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric /// Calculate edge weights for successors lead to unreachable.
2300b57cec5SDimitry Andric ///
2310b57cec5SDimitry Andric /// Predict that a successor which leads necessarily to an
2320b57cec5SDimitry Andric /// unreachable-terminated block as extremely unlikely.
2330b57cec5SDimitry Andric bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
2340b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
2350b57cec5SDimitry Andric   (void) TI;
2360b57cec5SDimitry Andric   assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
2370b57cec5SDimitry Andric   assert(!isa<InvokeInst>(TI) &&
2380b57cec5SDimitry Andric          "Invokes should have already been handled by calcInvokeHeuristics");
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   SmallVector<unsigned, 4> UnreachableEdges;
2410b57cec5SDimitry Andric   SmallVector<unsigned, 4> ReachableEdges;
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
2440b57cec5SDimitry Andric     if (PostDominatedByUnreachable.count(*I))
2450b57cec5SDimitry Andric       UnreachableEdges.push_back(I.getSuccessorIndex());
2460b57cec5SDimitry Andric     else
2470b57cec5SDimitry Andric       ReachableEdges.push_back(I.getSuccessorIndex());
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   // Skip probabilities if all were reachable.
2500b57cec5SDimitry Andric   if (UnreachableEdges.empty())
2510b57cec5SDimitry Andric     return false;
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric   if (ReachableEdges.empty()) {
2540b57cec5SDimitry Andric     BranchProbability Prob(1, UnreachableEdges.size());
2550b57cec5SDimitry Andric     for (unsigned SuccIdx : UnreachableEdges)
2560b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
2570b57cec5SDimitry Andric     return true;
2580b57cec5SDimitry Andric   }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   auto UnreachableProb = UR_TAKEN_PROB;
2610b57cec5SDimitry Andric   auto ReachableProb =
2620b57cec5SDimitry Andric       (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
2630b57cec5SDimitry Andric       ReachableEdges.size();
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   for (unsigned SuccIdx : UnreachableEdges)
2660b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, UnreachableProb);
2670b57cec5SDimitry Andric   for (unsigned SuccIdx : ReachableEdges)
2680b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, ReachableProb);
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric   return true;
2710b57cec5SDimitry Andric }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric // Propagate existing explicit probabilities from either profile data or
2740b57cec5SDimitry Andric // 'expect' intrinsic processing. Examine metadata against unreachable
2750b57cec5SDimitry Andric // heuristic. The probability of the edge coming to unreachable block is
2760b57cec5SDimitry Andric // set to min of metadata and unreachable heuristic.
2770b57cec5SDimitry Andric bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
2780b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
2790b57cec5SDimitry Andric   assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
2800b57cec5SDimitry Andric   if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
2810b57cec5SDimitry Andric     return false;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
2840b57cec5SDimitry Andric   if (!WeightsNode)
2850b57cec5SDimitry Andric     return false;
2860b57cec5SDimitry Andric 
2870b57cec5SDimitry Andric   // Check that the number of successors is manageable.
2880b57cec5SDimitry Andric   assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   // Ensure there are weights for all of the successors. Note that the first
2910b57cec5SDimitry Andric   // operand to the metadata node is a name, not a weight.
2920b57cec5SDimitry Andric   if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
2930b57cec5SDimitry Andric     return false;
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   // Build up the final weights that will be used in a temporary buffer.
2960b57cec5SDimitry Andric   // Compute the sum of all weights to later decide whether they need to
2970b57cec5SDimitry Andric   // be scaled to fit in 32 bits.
2980b57cec5SDimitry Andric   uint64_t WeightSum = 0;
2990b57cec5SDimitry Andric   SmallVector<uint32_t, 2> Weights;
3000b57cec5SDimitry Andric   SmallVector<unsigned, 2> UnreachableIdxs;
3010b57cec5SDimitry Andric   SmallVector<unsigned, 2> ReachableIdxs;
3020b57cec5SDimitry Andric   Weights.reserve(TI->getNumSuccessors());
3030b57cec5SDimitry Andric   for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
3040b57cec5SDimitry Andric     ConstantInt *Weight =
3050b57cec5SDimitry Andric         mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
3060b57cec5SDimitry Andric     if (!Weight)
3070b57cec5SDimitry Andric       return false;
3080b57cec5SDimitry Andric     assert(Weight->getValue().getActiveBits() <= 32 &&
3090b57cec5SDimitry Andric            "Too many bits for uint32_t");
3100b57cec5SDimitry Andric     Weights.push_back(Weight->getZExtValue());
3110b57cec5SDimitry Andric     WeightSum += Weights.back();
3120b57cec5SDimitry Andric     if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
3130b57cec5SDimitry Andric       UnreachableIdxs.push_back(i - 1);
3140b57cec5SDimitry Andric     else
3150b57cec5SDimitry Andric       ReachableIdxs.push_back(i - 1);
3160b57cec5SDimitry Andric   }
3170b57cec5SDimitry Andric   assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric   // If the sum of weights does not fit in 32 bits, scale every weight down
3200b57cec5SDimitry Andric   // accordingly.
3210b57cec5SDimitry Andric   uint64_t ScalingFactor =
3220b57cec5SDimitry Andric       (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   if (ScalingFactor > 1) {
3250b57cec5SDimitry Andric     WeightSum = 0;
3260b57cec5SDimitry Andric     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
3270b57cec5SDimitry Andric       Weights[i] /= ScalingFactor;
3280b57cec5SDimitry Andric       WeightSum += Weights[i];
3290b57cec5SDimitry Andric     }
3300b57cec5SDimitry Andric   }
3310b57cec5SDimitry Andric   assert(WeightSum <= UINT32_MAX &&
3320b57cec5SDimitry Andric          "Expected weights to scale down to 32 bits");
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   if (WeightSum == 0 || ReachableIdxs.size() == 0) {
3350b57cec5SDimitry Andric     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3360b57cec5SDimitry Andric       Weights[i] = 1;
3370b57cec5SDimitry Andric     WeightSum = TI->getNumSuccessors();
3380b57cec5SDimitry Andric   }
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric   // Set the probability.
3410b57cec5SDimitry Andric   SmallVector<BranchProbability, 2> BP;
3420b57cec5SDimitry Andric   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3430b57cec5SDimitry Andric     BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   // Examine the metadata against unreachable heuristic.
3460b57cec5SDimitry Andric   // If the unreachable heuristic is more strong then we use it for this edge.
3470b57cec5SDimitry Andric   if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
3480b57cec5SDimitry Andric     auto ToDistribute = BranchProbability::getZero();
3490b57cec5SDimitry Andric     auto UnreachableProb = UR_TAKEN_PROB;
3500b57cec5SDimitry Andric     for (auto i : UnreachableIdxs)
3510b57cec5SDimitry Andric       if (UnreachableProb < BP[i]) {
3520b57cec5SDimitry Andric         ToDistribute += BP[i] - UnreachableProb;
3530b57cec5SDimitry Andric         BP[i] = UnreachableProb;
3540b57cec5SDimitry Andric       }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric     // If we modified the probability of some edges then we must distribute
3570b57cec5SDimitry Andric     // the difference between reachable blocks.
3580b57cec5SDimitry Andric     if (ToDistribute > BranchProbability::getZero()) {
3590b57cec5SDimitry Andric       BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
3600b57cec5SDimitry Andric       for (auto i : ReachableIdxs)
3610b57cec5SDimitry Andric         BP[i] += PerEdge;
3620b57cec5SDimitry Andric     }
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
3660b57cec5SDimitry Andric     setEdgeProbability(BB, i, BP[i]);
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   return true;
3690b57cec5SDimitry Andric }
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric /// Calculate edge weights for edges leading to cold blocks.
3720b57cec5SDimitry Andric ///
3730b57cec5SDimitry Andric /// A cold block is one post-dominated by  a block with a call to a
3740b57cec5SDimitry Andric /// cold function.  Those edges are unlikely to be taken, so we give
3750b57cec5SDimitry Andric /// them relatively low weight.
3760b57cec5SDimitry Andric ///
3770b57cec5SDimitry Andric /// Return true if we could compute the weights for cold edges.
3780b57cec5SDimitry Andric /// Return false, otherwise.
3790b57cec5SDimitry Andric bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
3800b57cec5SDimitry Andric   const Instruction *TI = BB->getTerminator();
3810b57cec5SDimitry Andric   (void) TI;
3820b57cec5SDimitry Andric   assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
3830b57cec5SDimitry Andric   assert(!isa<InvokeInst>(TI) &&
3840b57cec5SDimitry Andric          "Invokes should have already been handled by calcInvokeHeuristics");
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric   // Determine which successors are post-dominated by a cold block.
3870b57cec5SDimitry Andric   SmallVector<unsigned, 4> ColdEdges;
3880b57cec5SDimitry Andric   SmallVector<unsigned, 4> NormalEdges;
3890b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
3900b57cec5SDimitry Andric     if (PostDominatedByColdCall.count(*I))
3910b57cec5SDimitry Andric       ColdEdges.push_back(I.getSuccessorIndex());
3920b57cec5SDimitry Andric     else
3930b57cec5SDimitry Andric       NormalEdges.push_back(I.getSuccessorIndex());
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric   // Skip probabilities if no cold edges.
3960b57cec5SDimitry Andric   if (ColdEdges.empty())
3970b57cec5SDimitry Andric     return false;
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   if (NormalEdges.empty()) {
4000b57cec5SDimitry Andric     BranchProbability Prob(1, ColdEdges.size());
4010b57cec5SDimitry Andric     for (unsigned SuccIdx : ColdEdges)
4020b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
4030b57cec5SDimitry Andric     return true;
4040b57cec5SDimitry Andric   }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   auto ColdProb = BranchProbability::getBranchProbability(
4070b57cec5SDimitry Andric       CC_TAKEN_WEIGHT,
4080b57cec5SDimitry Andric       (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
4090b57cec5SDimitry Andric   auto NormalProb = BranchProbability::getBranchProbability(
4100b57cec5SDimitry Andric       CC_NONTAKEN_WEIGHT,
4110b57cec5SDimitry Andric       (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   for (unsigned SuccIdx : ColdEdges)
4140b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, ColdProb);
4150b57cec5SDimitry Andric   for (unsigned SuccIdx : NormalEdges)
4160b57cec5SDimitry Andric     setEdgeProbability(BB, SuccIdx, NormalProb);
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   return true;
4190b57cec5SDimitry Andric }
4200b57cec5SDimitry Andric 
4210b57cec5SDimitry Andric // Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
4220b57cec5SDimitry Andric // between two pointer or pointer and NULL will fail.
4230b57cec5SDimitry Andric bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
4240b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
4250b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
4260b57cec5SDimitry Andric     return false;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   Value *Cond = BI->getCondition();
4290b57cec5SDimitry Andric   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
4300b57cec5SDimitry Andric   if (!CI || !CI->isEquality())
4310b57cec5SDimitry Andric     return false;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   Value *LHS = CI->getOperand(0);
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   if (!LHS->getType()->isPointerTy())
4360b57cec5SDimitry Andric     return false;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   assert(CI->getOperand(1)->getType()->isPointerTy());
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   // p != 0   ->   isProb = true
4410b57cec5SDimitry Andric   // p == 0   ->   isProb = false
4420b57cec5SDimitry Andric   // p != q   ->   isProb = true
4430b57cec5SDimitry Andric   // p == q   ->   isProb = false;
4440b57cec5SDimitry Andric   unsigned TakenIdx = 0, NonTakenIdx = 1;
4450b57cec5SDimitry Andric   bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
4460b57cec5SDimitry Andric   if (!isProb)
4470b57cec5SDimitry Andric     std::swap(TakenIdx, NonTakenIdx);
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric   BranchProbability TakenProb(PH_TAKEN_WEIGHT,
4500b57cec5SDimitry Andric                               PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
4510b57cec5SDimitry Andric   setEdgeProbability(BB, TakenIdx, TakenProb);
4520b57cec5SDimitry Andric   setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
4530b57cec5SDimitry Andric   return true;
4540b57cec5SDimitry Andric }
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric static int getSCCNum(const BasicBlock *BB,
4570b57cec5SDimitry Andric                      const BranchProbabilityInfo::SccInfo &SccI) {
4580b57cec5SDimitry Andric   auto SccIt = SccI.SccNums.find(BB);
4590b57cec5SDimitry Andric   if (SccIt == SccI.SccNums.end())
4600b57cec5SDimitry Andric     return -1;
4610b57cec5SDimitry Andric   return SccIt->second;
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric // Consider any block that is an entry point to the SCC as a header.
4650b57cec5SDimitry Andric static bool isSCCHeader(const BasicBlock *BB, int SccNum,
4660b57cec5SDimitry Andric                         BranchProbabilityInfo::SccInfo &SccI) {
4670b57cec5SDimitry Andric   assert(getSCCNum(BB, SccI) == SccNum);
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   // Lazily compute the set of headers for a given SCC and cache the results
4700b57cec5SDimitry Andric   // in the SccHeaderMap.
4710b57cec5SDimitry Andric   if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum))
4720b57cec5SDimitry Andric     SccI.SccHeaders.resize(SccNum + 1);
4730b57cec5SDimitry Andric   auto &HeaderMap = SccI.SccHeaders[SccNum];
4740b57cec5SDimitry Andric   bool Inserted;
4750b57cec5SDimitry Andric   BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt;
4760b57cec5SDimitry Andric   std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false));
4770b57cec5SDimitry Andric   if (Inserted) {
4780b57cec5SDimitry Andric     bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
4790b57cec5SDimitry Andric                                  [&](const BasicBlock *Pred) {
4800b57cec5SDimitry Andric                                    return getSCCNum(Pred, SccI) != SccNum;
4810b57cec5SDimitry Andric                                  });
4820b57cec5SDimitry Andric     HeaderMapIt->second = IsHeader;
4830b57cec5SDimitry Andric     return IsHeader;
4840b57cec5SDimitry Andric   } else
4850b57cec5SDimitry Andric     return HeaderMapIt->second;
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric // Compute the unlikely successors to the block BB in the loop L, specifically
4890b57cec5SDimitry Andric // those that are unlikely because this is a loop, and add them to the
4900b57cec5SDimitry Andric // UnlikelyBlocks set.
4910b57cec5SDimitry Andric static void
4920b57cec5SDimitry Andric computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
4930b57cec5SDimitry Andric                           SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
4940b57cec5SDimitry Andric   // Sometimes in a loop we have a branch whose condition is made false by
4950b57cec5SDimitry Andric   // taking it. This is typically something like
4960b57cec5SDimitry Andric   //  int n = 0;
4970b57cec5SDimitry Andric   //  while (...) {
4980b57cec5SDimitry Andric   //    if (++n >= MAX) {
4990b57cec5SDimitry Andric   //      n = 0;
5000b57cec5SDimitry Andric   //    }
5010b57cec5SDimitry Andric   //  }
5020b57cec5SDimitry Andric   // In this sort of situation taking the branch means that at the very least it
5030b57cec5SDimitry Andric   // won't be taken again in the next iteration of the loop, so we should
5040b57cec5SDimitry Andric   // consider it less likely than a typical branch.
5050b57cec5SDimitry Andric   //
5060b57cec5SDimitry Andric   // We detect this by looking back through the graph of PHI nodes that sets the
5070b57cec5SDimitry Andric   // value that the condition depends on, and seeing if we can reach a successor
5080b57cec5SDimitry Andric   // block which can be determined to make the condition false.
5090b57cec5SDimitry Andric   //
5100b57cec5SDimitry Andric   // FIXME: We currently consider unlikely blocks to be half as likely as other
5110b57cec5SDimitry Andric   // blocks, but if we consider the example above the likelyhood is actually
5120b57cec5SDimitry Andric   // 1/MAX. We could therefore be more precise in how unlikely we consider
5130b57cec5SDimitry Andric   // blocks to be, but it would require more careful examination of the form
5140b57cec5SDimitry Andric   // of the comparison expression.
5150b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
5160b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
5170b57cec5SDimitry Andric     return;
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // Check if the branch is based on an instruction compared with a constant
5200b57cec5SDimitry Andric   CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
5210b57cec5SDimitry Andric   if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
5220b57cec5SDimitry Andric       !isa<Constant>(CI->getOperand(1)))
5230b57cec5SDimitry Andric     return;
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   // Either the instruction must be a PHI, or a chain of operations involving
5260b57cec5SDimitry Andric   // constants that ends in a PHI which we can then collapse into a single value
5270b57cec5SDimitry Andric   // if the PHI value is known.
5280b57cec5SDimitry Andric   Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
5290b57cec5SDimitry Andric   PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
5300b57cec5SDimitry Andric   Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
5310b57cec5SDimitry Andric   // Collect the instructions until we hit a PHI
5320b57cec5SDimitry Andric   SmallVector<BinaryOperator *, 1> InstChain;
5330b57cec5SDimitry Andric   while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
5340b57cec5SDimitry Andric          isa<Constant>(CmpLHS->getOperand(1))) {
5350b57cec5SDimitry Andric     // Stop if the chain extends outside of the loop
5360b57cec5SDimitry Andric     if (!L->contains(CmpLHS))
5370b57cec5SDimitry Andric       return;
5380b57cec5SDimitry Andric     InstChain.push_back(cast<BinaryOperator>(CmpLHS));
5390b57cec5SDimitry Andric     CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
5400b57cec5SDimitry Andric     if (CmpLHS)
5410b57cec5SDimitry Andric       CmpPHI = dyn_cast<PHINode>(CmpLHS);
5420b57cec5SDimitry Andric   }
5430b57cec5SDimitry Andric   if (!CmpPHI || !L->contains(CmpPHI))
5440b57cec5SDimitry Andric     return;
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric   // Trace the phi node to find all values that come from successors of BB
5470b57cec5SDimitry Andric   SmallPtrSet<PHINode*, 8> VisitedInsts;
5480b57cec5SDimitry Andric   SmallVector<PHINode*, 8> WorkList;
5490b57cec5SDimitry Andric   WorkList.push_back(CmpPHI);
5500b57cec5SDimitry Andric   VisitedInsts.insert(CmpPHI);
5510b57cec5SDimitry Andric   while (!WorkList.empty()) {
5520b57cec5SDimitry Andric     PHINode *P = WorkList.back();
5530b57cec5SDimitry Andric     WorkList.pop_back();
5540b57cec5SDimitry Andric     for (BasicBlock *B : P->blocks()) {
5550b57cec5SDimitry Andric       // Skip blocks that aren't part of the loop
5560b57cec5SDimitry Andric       if (!L->contains(B))
5570b57cec5SDimitry Andric         continue;
5580b57cec5SDimitry Andric       Value *V = P->getIncomingValueForBlock(B);
5590b57cec5SDimitry Andric       // If the source is a PHI add it to the work list if we haven't
5600b57cec5SDimitry Andric       // already visited it.
5610b57cec5SDimitry Andric       if (PHINode *PN = dyn_cast<PHINode>(V)) {
5620b57cec5SDimitry Andric         if (VisitedInsts.insert(PN).second)
5630b57cec5SDimitry Andric           WorkList.push_back(PN);
5640b57cec5SDimitry Andric         continue;
5650b57cec5SDimitry Andric       }
5660b57cec5SDimitry Andric       // If this incoming value is a constant and B is a successor of BB, then
5670b57cec5SDimitry Andric       // we can constant-evaluate the compare to see if it makes the branch be
5680b57cec5SDimitry Andric       // taken or not.
5690b57cec5SDimitry Andric       Constant *CmpLHSConst = dyn_cast<Constant>(V);
5700b57cec5SDimitry Andric       if (!CmpLHSConst ||
5710b57cec5SDimitry Andric           std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB))
5720b57cec5SDimitry Andric         continue;
5730b57cec5SDimitry Andric       // First collapse InstChain
5740b57cec5SDimitry Andric       for (Instruction *I : llvm::reverse(InstChain)) {
5750b57cec5SDimitry Andric         CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
5760b57cec5SDimitry Andric                                         cast<Constant>(I->getOperand(1)), true);
5770b57cec5SDimitry Andric         if (!CmpLHSConst)
5780b57cec5SDimitry Andric           break;
5790b57cec5SDimitry Andric       }
5800b57cec5SDimitry Andric       if (!CmpLHSConst)
5810b57cec5SDimitry Andric         continue;
5820b57cec5SDimitry Andric       // Now constant-evaluate the compare
5830b57cec5SDimitry Andric       Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
5840b57cec5SDimitry Andric                                                   CmpLHSConst, CmpConst, true);
5850b57cec5SDimitry Andric       // If the result means we don't branch to the block then that block is
5860b57cec5SDimitry Andric       // unlikely.
5870b57cec5SDimitry Andric       if (Result &&
5880b57cec5SDimitry Andric           ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
5890b57cec5SDimitry Andric            (Result->isOneValue() && B == BI->getSuccessor(1))))
5900b57cec5SDimitry Andric         UnlikelyBlocks.insert(B);
5910b57cec5SDimitry Andric     }
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric }
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric // Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
5960b57cec5SDimitry Andric // as taken, exiting edges as not-taken.
5970b57cec5SDimitry Andric bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
5980b57cec5SDimitry Andric                                                      const LoopInfo &LI,
5990b57cec5SDimitry Andric                                                      SccInfo &SccI) {
6000b57cec5SDimitry Andric   int SccNum;
6010b57cec5SDimitry Andric   Loop *L = LI.getLoopFor(BB);
6020b57cec5SDimitry Andric   if (!L) {
6030b57cec5SDimitry Andric     SccNum = getSCCNum(BB, SccI);
6040b57cec5SDimitry Andric     if (SccNum < 0)
6050b57cec5SDimitry Andric       return false;
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
6090b57cec5SDimitry Andric   if (L)
6100b57cec5SDimitry Andric     computeUnlikelySuccessors(BB, L, UnlikelyBlocks);
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric   SmallVector<unsigned, 8> BackEdges;
6130b57cec5SDimitry Andric   SmallVector<unsigned, 8> ExitingEdges;
6140b57cec5SDimitry Andric   SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
6150b57cec5SDimitry Andric   SmallVector<unsigned, 8> UnlikelyEdges;
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
6180b57cec5SDimitry Andric     // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch
6190b57cec5SDimitry Andric     // irreducible loops.
6200b57cec5SDimitry Andric     if (L) {
6210b57cec5SDimitry Andric       if (UnlikelyBlocks.count(*I) != 0)
6220b57cec5SDimitry Andric         UnlikelyEdges.push_back(I.getSuccessorIndex());
6230b57cec5SDimitry Andric       else if (!L->contains(*I))
6240b57cec5SDimitry Andric         ExitingEdges.push_back(I.getSuccessorIndex());
6250b57cec5SDimitry Andric       else if (L->getHeader() == *I)
6260b57cec5SDimitry Andric         BackEdges.push_back(I.getSuccessorIndex());
6270b57cec5SDimitry Andric       else
6280b57cec5SDimitry Andric         InEdges.push_back(I.getSuccessorIndex());
6290b57cec5SDimitry Andric     } else {
6300b57cec5SDimitry Andric       if (getSCCNum(*I, SccI) != SccNum)
6310b57cec5SDimitry Andric         ExitingEdges.push_back(I.getSuccessorIndex());
6320b57cec5SDimitry Andric       else if (isSCCHeader(*I, SccNum, SccI))
6330b57cec5SDimitry Andric         BackEdges.push_back(I.getSuccessorIndex());
6340b57cec5SDimitry Andric       else
6350b57cec5SDimitry Andric         InEdges.push_back(I.getSuccessorIndex());
6360b57cec5SDimitry Andric     }
6370b57cec5SDimitry Andric   }
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric   if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
6400b57cec5SDimitry Andric     return false;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
6430b57cec5SDimitry Andric   // normalize them so that they sum up to one.
6440b57cec5SDimitry Andric   unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
6450b57cec5SDimitry Andric                    (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
6460b57cec5SDimitry Andric                    (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
6470b57cec5SDimitry Andric                    (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   if (uint32_t numBackEdges = BackEdges.size()) {
6500b57cec5SDimitry Andric     BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
6510b57cec5SDimitry Andric     auto Prob = TakenProb / numBackEdges;
6520b57cec5SDimitry Andric     for (unsigned SuccIdx : BackEdges)
6530b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6540b57cec5SDimitry Andric   }
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric   if (uint32_t numInEdges = InEdges.size()) {
6570b57cec5SDimitry Andric     BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
6580b57cec5SDimitry Andric     auto Prob = TakenProb / numInEdges;
6590b57cec5SDimitry Andric     for (unsigned SuccIdx : InEdges)
6600b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6610b57cec5SDimitry Andric   }
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric   if (uint32_t numExitingEdges = ExitingEdges.size()) {
6640b57cec5SDimitry Andric     BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
6650b57cec5SDimitry Andric                                                        Denom);
6660b57cec5SDimitry Andric     auto Prob = NotTakenProb / numExitingEdges;
6670b57cec5SDimitry Andric     for (unsigned SuccIdx : ExitingEdges)
6680b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6690b57cec5SDimitry Andric   }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric   if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
6720b57cec5SDimitry Andric     BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
6730b57cec5SDimitry Andric                                                        Denom);
6740b57cec5SDimitry Andric     auto Prob = UnlikelyProb / numUnlikelyEdges;
6750b57cec5SDimitry Andric     for (unsigned SuccIdx : UnlikelyEdges)
6760b57cec5SDimitry Andric       setEdgeProbability(BB, SuccIdx, Prob);
6770b57cec5SDimitry Andric   }
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   return true;
6800b57cec5SDimitry Andric }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
6830b57cec5SDimitry Andric                                                const TargetLibraryInfo *TLI) {
6840b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
6850b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
6860b57cec5SDimitry Andric     return false;
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric   Value *Cond = BI->getCondition();
6890b57cec5SDimitry Andric   ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
6900b57cec5SDimitry Andric   if (!CI)
6910b57cec5SDimitry Andric     return false;
6920b57cec5SDimitry Andric 
6930b57cec5SDimitry Andric   auto GetConstantInt = [](Value *V) {
6940b57cec5SDimitry Andric     if (auto *I = dyn_cast<BitCastInst>(V))
6950b57cec5SDimitry Andric       return dyn_cast<ConstantInt>(I->getOperand(0));
6960b57cec5SDimitry Andric     return dyn_cast<ConstantInt>(V);
6970b57cec5SDimitry Andric   };
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   Value *RHS = CI->getOperand(1);
7000b57cec5SDimitry Andric   ConstantInt *CV = GetConstantInt(RHS);
7010b57cec5SDimitry Andric   if (!CV)
7020b57cec5SDimitry Andric     return false;
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   // If the LHS is the result of AND'ing a value with a single bit bitmask,
7050b57cec5SDimitry Andric   // we don't have information about probabilities.
7060b57cec5SDimitry Andric   if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
7070b57cec5SDimitry Andric     if (LHS->getOpcode() == Instruction::And)
7080b57cec5SDimitry Andric       if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
7090b57cec5SDimitry Andric         if (AndRHS->getValue().isPowerOf2())
7100b57cec5SDimitry Andric           return false;
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   // Check if the LHS is the return value of a library function
7130b57cec5SDimitry Andric   LibFunc Func = NumLibFuncs;
7140b57cec5SDimitry Andric   if (TLI)
7150b57cec5SDimitry Andric     if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
7160b57cec5SDimitry Andric       if (Function *CalledFn = Call->getCalledFunction())
7170b57cec5SDimitry Andric         TLI->getLibFunc(*CalledFn, Func);
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   bool isProb;
7200b57cec5SDimitry Andric   if (Func == LibFunc_strcasecmp ||
7210b57cec5SDimitry Andric       Func == LibFunc_strcmp ||
7220b57cec5SDimitry Andric       Func == LibFunc_strncasecmp ||
7230b57cec5SDimitry Andric       Func == LibFunc_strncmp ||
7240b57cec5SDimitry Andric       Func == LibFunc_memcmp) {
7250b57cec5SDimitry Andric     // strcmp and similar functions return zero, negative, or positive, if the
7260b57cec5SDimitry Andric     // first string is equal, less, or greater than the second. We consider it
7270b57cec5SDimitry Andric     // likely that the strings are not equal, so a comparison with zero is
7280b57cec5SDimitry Andric     // probably false, but also a comparison with any other number is also
7290b57cec5SDimitry Andric     // probably false given that what exactly is returned for nonzero values is
7300b57cec5SDimitry Andric     // not specified. Any kind of comparison other than equality we know
7310b57cec5SDimitry Andric     // nothing about.
7320b57cec5SDimitry Andric     switch (CI->getPredicate()) {
7330b57cec5SDimitry Andric     case CmpInst::ICMP_EQ:
7340b57cec5SDimitry Andric       isProb = false;
7350b57cec5SDimitry Andric       break;
7360b57cec5SDimitry Andric     case CmpInst::ICMP_NE:
7370b57cec5SDimitry Andric       isProb = true;
7380b57cec5SDimitry Andric       break;
7390b57cec5SDimitry Andric     default:
7400b57cec5SDimitry Andric       return false;
7410b57cec5SDimitry Andric     }
7420b57cec5SDimitry Andric   } else if (CV->isZero()) {
7430b57cec5SDimitry Andric     switch (CI->getPredicate()) {
7440b57cec5SDimitry Andric     case CmpInst::ICMP_EQ:
7450b57cec5SDimitry Andric       // X == 0   ->  Unlikely
7460b57cec5SDimitry Andric       isProb = false;
7470b57cec5SDimitry Andric       break;
7480b57cec5SDimitry Andric     case CmpInst::ICMP_NE:
7490b57cec5SDimitry Andric       // X != 0   ->  Likely
7500b57cec5SDimitry Andric       isProb = true;
7510b57cec5SDimitry Andric       break;
7520b57cec5SDimitry Andric     case CmpInst::ICMP_SLT:
7530b57cec5SDimitry Andric       // X < 0   ->  Unlikely
7540b57cec5SDimitry Andric       isProb = false;
7550b57cec5SDimitry Andric       break;
7560b57cec5SDimitry Andric     case CmpInst::ICMP_SGT:
7570b57cec5SDimitry Andric       // X > 0   ->  Likely
7580b57cec5SDimitry Andric       isProb = true;
7590b57cec5SDimitry Andric       break;
7600b57cec5SDimitry Andric     default:
7610b57cec5SDimitry Andric       return false;
7620b57cec5SDimitry Andric     }
7630b57cec5SDimitry Andric   } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
7640b57cec5SDimitry Andric     // InstCombine canonicalizes X <= 0 into X < 1.
7650b57cec5SDimitry Andric     // X <= 0   ->  Unlikely
7660b57cec5SDimitry Andric     isProb = false;
7670b57cec5SDimitry Andric   } else if (CV->isMinusOne()) {
7680b57cec5SDimitry Andric     switch (CI->getPredicate()) {
7690b57cec5SDimitry Andric     case CmpInst::ICMP_EQ:
7700b57cec5SDimitry Andric       // X == -1  ->  Unlikely
7710b57cec5SDimitry Andric       isProb = false;
7720b57cec5SDimitry Andric       break;
7730b57cec5SDimitry Andric     case CmpInst::ICMP_NE:
7740b57cec5SDimitry Andric       // X != -1  ->  Likely
7750b57cec5SDimitry Andric       isProb = true;
7760b57cec5SDimitry Andric       break;
7770b57cec5SDimitry Andric     case CmpInst::ICMP_SGT:
7780b57cec5SDimitry Andric       // InstCombine canonicalizes X >= 0 into X > -1.
7790b57cec5SDimitry Andric       // X >= 0   ->  Likely
7800b57cec5SDimitry Andric       isProb = true;
7810b57cec5SDimitry Andric       break;
7820b57cec5SDimitry Andric     default:
7830b57cec5SDimitry Andric       return false;
7840b57cec5SDimitry Andric     }
7850b57cec5SDimitry Andric   } else {
7860b57cec5SDimitry Andric     return false;
7870b57cec5SDimitry Andric   }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   unsigned TakenIdx = 0, NonTakenIdx = 1;
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   if (!isProb)
7920b57cec5SDimitry Andric     std::swap(TakenIdx, NonTakenIdx);
7930b57cec5SDimitry Andric 
7940b57cec5SDimitry Andric   BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
7950b57cec5SDimitry Andric                               ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
7960b57cec5SDimitry Andric   setEdgeProbability(BB, TakenIdx, TakenProb);
7970b57cec5SDimitry Andric   setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
7980b57cec5SDimitry Andric   return true;
7990b57cec5SDimitry Andric }
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
8020b57cec5SDimitry Andric   const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
8030b57cec5SDimitry Andric   if (!BI || !BI->isConditional())
8040b57cec5SDimitry Andric     return false;
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   Value *Cond = BI->getCondition();
8070b57cec5SDimitry Andric   FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
8080b57cec5SDimitry Andric   if (!FCmp)
8090b57cec5SDimitry Andric     return false;
8100b57cec5SDimitry Andric 
8118bcb0991SDimitry Andric   uint32_t TakenWeight = FPH_TAKEN_WEIGHT;
8128bcb0991SDimitry Andric   uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT;
8130b57cec5SDimitry Andric   bool isProb;
8140b57cec5SDimitry Andric   if (FCmp->isEquality()) {
8150b57cec5SDimitry Andric     // f1 == f2 -> Unlikely
8160b57cec5SDimitry Andric     // f1 != f2 -> Likely
8170b57cec5SDimitry Andric     isProb = !FCmp->isTrueWhenEqual();
8180b57cec5SDimitry Andric   } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
8190b57cec5SDimitry Andric     // !isnan -> Likely
8200b57cec5SDimitry Andric     isProb = true;
8218bcb0991SDimitry Andric     TakenWeight = FPH_ORD_WEIGHT;
8228bcb0991SDimitry Andric     NontakenWeight = FPH_UNO_WEIGHT;
8230b57cec5SDimitry Andric   } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
8240b57cec5SDimitry Andric     // isnan -> Unlikely
8250b57cec5SDimitry Andric     isProb = false;
8268bcb0991SDimitry Andric     TakenWeight = FPH_ORD_WEIGHT;
8278bcb0991SDimitry Andric     NontakenWeight = FPH_UNO_WEIGHT;
8280b57cec5SDimitry Andric   } else {
8290b57cec5SDimitry Andric     return false;
8300b57cec5SDimitry Andric   }
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   unsigned TakenIdx = 0, NonTakenIdx = 1;
8330b57cec5SDimitry Andric 
8340b57cec5SDimitry Andric   if (!isProb)
8350b57cec5SDimitry Andric     std::swap(TakenIdx, NonTakenIdx);
8360b57cec5SDimitry Andric 
8378bcb0991SDimitry Andric   BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight);
8380b57cec5SDimitry Andric   setEdgeProbability(BB, TakenIdx, TakenProb);
8390b57cec5SDimitry Andric   setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
8400b57cec5SDimitry Andric   return true;
8410b57cec5SDimitry Andric }
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
8440b57cec5SDimitry Andric   const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
8450b57cec5SDimitry Andric   if (!II)
8460b57cec5SDimitry Andric     return false;
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   BranchProbability TakenProb(IH_TAKEN_WEIGHT,
8490b57cec5SDimitry Andric                               IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
8500b57cec5SDimitry Andric   setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
8510b57cec5SDimitry Andric   setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
8520b57cec5SDimitry Andric   return true;
8530b57cec5SDimitry Andric }
8540b57cec5SDimitry Andric 
8550b57cec5SDimitry Andric void BranchProbabilityInfo::releaseMemory() {
8560b57cec5SDimitry Andric   Probs.clear();
8570b57cec5SDimitry Andric }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric void BranchProbabilityInfo::print(raw_ostream &OS) const {
8600b57cec5SDimitry Andric   OS << "---- Branch Probabilities ----\n";
8610b57cec5SDimitry Andric   // We print the probabilities from the last function the analysis ran over,
8620b57cec5SDimitry Andric   // or the function it is currently running over.
8630b57cec5SDimitry Andric   assert(LastF && "Cannot print prior to running over a function");
8640b57cec5SDimitry Andric   for (const auto &BI : *LastF) {
8650b57cec5SDimitry Andric     for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
8660b57cec5SDimitry Andric          ++SI) {
8670b57cec5SDimitry Andric       printEdgeProbability(OS << "  ", &BI, *SI);
8680b57cec5SDimitry Andric     }
8690b57cec5SDimitry Andric   }
8700b57cec5SDimitry Andric }
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric bool BranchProbabilityInfo::
8730b57cec5SDimitry Andric isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
8740b57cec5SDimitry Andric   // Hot probability is at least 4/5 = 80%
8750b57cec5SDimitry Andric   // FIXME: Compare against a static "hot" BranchProbability.
8760b57cec5SDimitry Andric   return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
8770b57cec5SDimitry Andric }
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric const BasicBlock *
8800b57cec5SDimitry Andric BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
8810b57cec5SDimitry Andric   auto MaxProb = BranchProbability::getZero();
8820b57cec5SDimitry Andric   const BasicBlock *MaxSucc = nullptr;
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
8850b57cec5SDimitry Andric     const BasicBlock *Succ = *I;
8860b57cec5SDimitry Andric     auto Prob = getEdgeProbability(BB, Succ);
8870b57cec5SDimitry Andric     if (Prob > MaxProb) {
8880b57cec5SDimitry Andric       MaxProb = Prob;
8890b57cec5SDimitry Andric       MaxSucc = Succ;
8900b57cec5SDimitry Andric     }
8910b57cec5SDimitry Andric   }
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric   // Hot probability is at least 4/5 = 80%
8940b57cec5SDimitry Andric   if (MaxProb > BranchProbability(4, 5))
8950b57cec5SDimitry Andric     return MaxSucc;
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   return nullptr;
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric /// Get the raw edge probability for the edge. If can't find it, return a
9010b57cec5SDimitry Andric /// default probability 1/N where N is the number of successors. Here an edge is
9020b57cec5SDimitry Andric /// specified using PredBlock and an
9030b57cec5SDimitry Andric /// index to the successors.
9040b57cec5SDimitry Andric BranchProbability
9050b57cec5SDimitry Andric BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
9060b57cec5SDimitry Andric                                           unsigned IndexInSuccessors) const {
9070b57cec5SDimitry Andric   auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric   if (I != Probs.end())
9100b57cec5SDimitry Andric     return I->second;
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   return {1, static_cast<uint32_t>(succ_size(Src))};
9130b57cec5SDimitry Andric }
9140b57cec5SDimitry Andric 
9150b57cec5SDimitry Andric BranchProbability
9160b57cec5SDimitry Andric BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
9170b57cec5SDimitry Andric                                           succ_const_iterator Dst) const {
9180b57cec5SDimitry Andric   return getEdgeProbability(Src, Dst.getSuccessorIndex());
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric /// Get the raw edge probability calculated for the block pair. This returns the
9220b57cec5SDimitry Andric /// sum of all raw edge probabilities from Src to Dst.
9230b57cec5SDimitry Andric BranchProbability
9240b57cec5SDimitry Andric BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
9250b57cec5SDimitry Andric                                           const BasicBlock *Dst) const {
9260b57cec5SDimitry Andric   auto Prob = BranchProbability::getZero();
9270b57cec5SDimitry Andric   bool FoundProb = false;
9280b57cec5SDimitry Andric   for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
9290b57cec5SDimitry Andric     if (*I == Dst) {
9300b57cec5SDimitry Andric       auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
9310b57cec5SDimitry Andric       if (MapI != Probs.end()) {
9320b57cec5SDimitry Andric         FoundProb = true;
9330b57cec5SDimitry Andric         Prob += MapI->second;
9340b57cec5SDimitry Andric       }
9350b57cec5SDimitry Andric     }
9360b57cec5SDimitry Andric   uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
9370b57cec5SDimitry Andric   return FoundProb ? Prob : BranchProbability(1, succ_num);
9380b57cec5SDimitry Andric }
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric /// Set the edge probability for a given edge specified by PredBlock and an
9410b57cec5SDimitry Andric /// index to the successors.
9420b57cec5SDimitry Andric void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
9430b57cec5SDimitry Andric                                                unsigned IndexInSuccessors,
9440b57cec5SDimitry Andric                                                BranchProbability Prob) {
9450b57cec5SDimitry Andric   Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
9460b57cec5SDimitry Andric   Handles.insert(BasicBlockCallbackVH(Src, this));
9470b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
9480b57cec5SDimitry Andric                     << IndexInSuccessors << " successor probability to " << Prob
9490b57cec5SDimitry Andric                     << "\n");
9500b57cec5SDimitry Andric }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric raw_ostream &
9530b57cec5SDimitry Andric BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
9540b57cec5SDimitry Andric                                             const BasicBlock *Src,
9550b57cec5SDimitry Andric                                             const BasicBlock *Dst) const {
9560b57cec5SDimitry Andric   const BranchProbability Prob = getEdgeProbability(Src, Dst);
9570b57cec5SDimitry Andric   OS << "edge " << Src->getName() << " -> " << Dst->getName()
9580b57cec5SDimitry Andric      << " probability is " << Prob
9590b57cec5SDimitry Andric      << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   return OS;
9620b57cec5SDimitry Andric }
9630b57cec5SDimitry Andric 
9640b57cec5SDimitry Andric void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
9650b57cec5SDimitry Andric   for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
9660b57cec5SDimitry Andric     auto Key = I->first;
9670b57cec5SDimitry Andric     if (Key.first == BB)
9680b57cec5SDimitry Andric       Probs.erase(Key);
9690b57cec5SDimitry Andric   }
9700b57cec5SDimitry Andric }
9710b57cec5SDimitry Andric 
9720b57cec5SDimitry Andric void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
9730b57cec5SDimitry Andric                                       const TargetLibraryInfo *TLI) {
9740b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
9750b57cec5SDimitry Andric                     << " ----\n\n");
9760b57cec5SDimitry Andric   LastF = &F; // Store the last function we ran on for printing.
9770b57cec5SDimitry Andric   assert(PostDominatedByUnreachable.empty());
9780b57cec5SDimitry Andric   assert(PostDominatedByColdCall.empty());
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   // Record SCC numbers of blocks in the CFG to identify irreducible loops.
9810b57cec5SDimitry Andric   // FIXME: We could only calculate this if the CFG is known to be irreducible
9820b57cec5SDimitry Andric   // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
9830b57cec5SDimitry Andric   int SccNum = 0;
9840b57cec5SDimitry Andric   SccInfo SccI;
9850b57cec5SDimitry Andric   for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
9860b57cec5SDimitry Andric        ++It, ++SccNum) {
9870b57cec5SDimitry Andric     // Ignore single-block SCCs since they either aren't loops or LoopInfo will
9880b57cec5SDimitry Andric     // catch them.
9890b57cec5SDimitry Andric     const std::vector<const BasicBlock *> &Scc = *It;
9900b57cec5SDimitry Andric     if (Scc.size() == 1)
9910b57cec5SDimitry Andric       continue;
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
9940b57cec5SDimitry Andric     for (auto *BB : Scc) {
9950b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " " << BB->getName());
9960b57cec5SDimitry Andric       SccI.SccNums[BB] = SccNum;
9970b57cec5SDimitry Andric     }
9980b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric 
1001*480093f4SDimitry Andric   std::unique_ptr<PostDominatorTree> PDT =
1002*480093f4SDimitry Andric       std::make_unique<PostDominatorTree>(const_cast<Function &>(F));
1003*480093f4SDimitry Andric   computePostDominatedByUnreachable(F, PDT.get());
1004*480093f4SDimitry Andric   computePostDominatedByColdCall(F, PDT.get());
1005*480093f4SDimitry Andric 
10060b57cec5SDimitry Andric   // Walk the basic blocks in post-order so that we can build up state about
10070b57cec5SDimitry Andric   // the successors of a block iteratively.
10080b57cec5SDimitry Andric   for (auto BB : post_order(&F.getEntryBlock())) {
10090b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
10100b57cec5SDimitry Andric                       << "\n");
10110b57cec5SDimitry Andric     // If there is no at least two successors, no sense to set probability.
10120b57cec5SDimitry Andric     if (BB->getTerminator()->getNumSuccessors() < 2)
10130b57cec5SDimitry Andric       continue;
10140b57cec5SDimitry Andric     if (calcMetadataWeights(BB))
10150b57cec5SDimitry Andric       continue;
10160b57cec5SDimitry Andric     if (calcInvokeHeuristics(BB))
10170b57cec5SDimitry Andric       continue;
10180b57cec5SDimitry Andric     if (calcUnreachableHeuristics(BB))
10190b57cec5SDimitry Andric       continue;
10200b57cec5SDimitry Andric     if (calcColdCallHeuristics(BB))
10210b57cec5SDimitry Andric       continue;
10220b57cec5SDimitry Andric     if (calcLoopBranchHeuristics(BB, LI, SccI))
10230b57cec5SDimitry Andric       continue;
10240b57cec5SDimitry Andric     if (calcPointerHeuristics(BB))
10250b57cec5SDimitry Andric       continue;
10260b57cec5SDimitry Andric     if (calcZeroHeuristics(BB, TLI))
10270b57cec5SDimitry Andric       continue;
10280b57cec5SDimitry Andric     if (calcFloatingPointHeuristics(BB))
10290b57cec5SDimitry Andric       continue;
10300b57cec5SDimitry Andric   }
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric   PostDominatedByUnreachable.clear();
10330b57cec5SDimitry Andric   PostDominatedByColdCall.clear();
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   if (PrintBranchProb &&
10360b57cec5SDimitry Andric       (PrintBranchProbFuncName.empty() ||
10370b57cec5SDimitry Andric        F.getName().equals(PrintBranchProbFuncName))) {
10380b57cec5SDimitry Andric     print(dbgs());
10390b57cec5SDimitry Andric   }
10400b57cec5SDimitry Andric }
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
10430b57cec5SDimitry Andric     AnalysisUsage &AU) const {
10440b57cec5SDimitry Andric   // We require DT so it's available when LI is available. The LI updating code
10450b57cec5SDimitry Andric   // asserts that DT is also present so if we don't make sure that we have DT
10460b57cec5SDimitry Andric   // here, that assert will trigger.
10470b57cec5SDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
10480b57cec5SDimitry Andric   AU.addRequired<LoopInfoWrapperPass>();
10490b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
10500b57cec5SDimitry Andric   AU.setPreservesAll();
10510b57cec5SDimitry Andric }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
10540b57cec5SDimitry Andric   const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
10558bcb0991SDimitry Andric   const TargetLibraryInfo &TLI =
10568bcb0991SDimitry Andric       getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
10570b57cec5SDimitry Andric   BPI.calculate(F, LI, &TLI);
10580b57cec5SDimitry Andric   return false;
10590b57cec5SDimitry Andric }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
10640b57cec5SDimitry Andric                                              const Module *) const {
10650b57cec5SDimitry Andric   BPI.print(OS);
10660b57cec5SDimitry Andric }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric AnalysisKey BranchProbabilityAnalysis::Key;
10690b57cec5SDimitry Andric BranchProbabilityInfo
10700b57cec5SDimitry Andric BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
10710b57cec5SDimitry Andric   BranchProbabilityInfo BPI;
10720b57cec5SDimitry Andric   BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
10730b57cec5SDimitry Andric   return BPI;
10740b57cec5SDimitry Andric }
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric PreservedAnalyses
10770b57cec5SDimitry Andric BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
10780b57cec5SDimitry Andric   OS << "Printing analysis results of BPI for function "
10790b57cec5SDimitry Andric      << "'" << F.getName() << "':"
10800b57cec5SDimitry Andric      << "\n";
10810b57cec5SDimitry Andric   AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
10820b57cec5SDimitry Andric   return PreservedAnalyses::all();
10830b57cec5SDimitry Andric }
1084