//===----------------------------------------------------------------------===//
#include "llvm/Constants.h"
+#include "llvm/Function.h"
#include "llvm/Instructions.h"
+#include "llvm/LLVMContext.h"
+#include "llvm/Metadata.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/LoopInfo.h"
+#include "llvm/Support/CFG.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
typedef std::pair<const BasicBlock *, const BasicBlock *> Edge;
- DenseMap<Edge, uint32_t> *Weights;
-
BranchProbabilityInfo *BP;
LoopInfo *LI;
static const uint32_t ZH_TAKEN_WEIGHT = 20;
static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
+ static const uint32_t FPH_TAKEN_WEIGHT = 20;
+ static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
+
// Standard weight value. Used when none of the heuristics set weight for
// the edge.
static const uint32_t NORMAL_WEIGHT = 16;
}
public:
- BranchProbabilityAnalysis(DenseMap<Edge, uint32_t> *W,
- BranchProbabilityInfo *BP, LoopInfo *LI)
- : Weights(W), BP(BP), LI(LI) {
+ BranchProbabilityAnalysis(BranchProbabilityInfo *BP, LoopInfo *LI)
+ : BP(BP), LI(LI) {
}
+ // Metadata Weights
+ bool calcMetadataWeights(BasicBlock *BB);
+
// Return Heuristics
bool calcReturnHeuristics(BasicBlock *BB);
// Loop Branch Heuristics
bool calcLoopBranchHeuristics(BasicBlock *BB);
- // Zero Heurestics
+ // Zero Heuristics
bool calcZeroHeuristics(BasicBlock *BB);
+ // Floating Point Heuristics
+ bool calcFloatingPointHeuristics(BasicBlock *BB);
+
bool runOnFunction(Function &F);
};
} // end anonymous namespace
+// Propagate existing explicit probabilities from either profile data or
+// 'expect' intrinsic processing.
+bool BranchProbabilityAnalysis::calcMetadataWeights(BasicBlock *BB) {
+ TerminatorInst *TI = BB->getTerminator();
+ if (TI->getNumSuccessors() == 1)
+ return false;
+ if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
+ return false;
+
+ MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
+ if (!WeightsNode)
+ return false;
+
+ // Ensure there are weights for all of the successors. Note that the first
+ // operand to the metadata node is a name, not a weight.
+ if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
+ return false;
+
+ // Build up the final weights that will be used in a temporary buffer, but
+ // don't add them until all weihts are present. Each weight value is clamped
+ // to [1, getMaxWeightFor(BB)].
+ uint32_t WeightLimit = getMaxWeightFor(BB);
+ SmallVector<uint32_t, 2> Weights;
+ Weights.reserve(TI->getNumSuccessors());
+ for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
+ ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i));
+ if (!Weight)
+ return false;
+ Weights.push_back(
+ std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit)));
+ }
+ assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
+ for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
+ BP->setEdgeWeight(BB, TI->getSuccessor(i), Weights[i]);
+
+ return true;
+}
+
// Calculate Edge Weights using "Return Heuristics". Predict a successor which
// leads directly to Return Instruction will not be taken.
bool BranchProbabilityAnalysis::calcReturnHeuristics(BasicBlock *BB){
if (BB->getTerminator()->getNumSuccessors() == 1)
return false;
- SmallVector<BasicBlock *, 4> ReturningEdges;
- SmallVector<BasicBlock *, 4> StayEdges;
+ SmallPtrSet<BasicBlock *, 4> ReturningEdges;
+ SmallPtrSet<BasicBlock *, 4> StayEdges;
for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
BasicBlock *Succ = *I;
if (isReturningBlock(Succ))
- ReturningEdges.push_back(Succ);
+ ReturningEdges.insert(Succ);
else
- StayEdges.push_back(Succ);
+ StayEdges.insert(Succ);
}
if (uint32_t numStayEdges = StayEdges.size()) {
if (stayWeight < NORMAL_WEIGHT)
stayWeight = NORMAL_WEIGHT;
- for (SmallVector<BasicBlock *, 4>::iterator I = StayEdges.begin(),
+ for (SmallPtrSet<BasicBlock *, 4>::iterator I = StayEdges.begin(),
E = StayEdges.end(); I != E; ++I)
BP->setEdgeWeight(BB, *I, stayWeight);
}
uint32_t retWeight = RH_NONTAKEN_WEIGHT / numRetEdges;
if (retWeight < MIN_WEIGHT)
retWeight = MIN_WEIGHT;
- for (SmallVector<BasicBlock *, 4>::iterator I = ReturningEdges.begin(),
+ for (SmallPtrSet<BasicBlock *, 4>::iterator I = ReturningEdges.begin(),
E = ReturningEdges.end(); I != E; ++I) {
BP->setEdgeWeight(BB, *I, retWeight);
}
if (!L)
return false;
- SmallVector<BasicBlock *, 8> BackEdges;
- SmallVector<BasicBlock *, 8> ExitingEdges;
- SmallVector<BasicBlock *, 8> InEdges; // Edges from header to the loop.
+ SmallPtrSet<BasicBlock *, 8> BackEdges;
+ SmallPtrSet<BasicBlock *, 8> ExitingEdges;
+ SmallPtrSet<BasicBlock *, 8> InEdges; // Edges from header to the loop.
bool isHeader = BB == L->getHeader();
BasicBlock *Succ = *I;
Loop *SuccL = LI->getLoopFor(Succ);
if (SuccL != L)
- ExitingEdges.push_back(Succ);
+ ExitingEdges.insert(Succ);
else if (Succ == L->getHeader())
- BackEdges.push_back(Succ);
+ BackEdges.insert(Succ);
else if (isHeader)
- InEdges.push_back(Succ);
+ InEdges.insert(Succ);
}
if (uint32_t numBackEdges = BackEdges.size()) {
if (backWeight < NORMAL_WEIGHT)
backWeight = NORMAL_WEIGHT;
- for (SmallVector<BasicBlock *, 8>::iterator EI = BackEdges.begin(),
+ for (SmallPtrSet<BasicBlock *, 8>::iterator EI = BackEdges.begin(),
EE = BackEdges.end(); EI != EE; ++EI) {
BasicBlock *Back = *EI;
BP->setEdgeWeight(BB, Back, backWeight);
if (inWeight < NORMAL_WEIGHT)
inWeight = NORMAL_WEIGHT;
- for (SmallVector<BasicBlock *, 8>::iterator EI = InEdges.begin(),
+ for (SmallPtrSet<BasicBlock *, 8>::iterator EI = InEdges.begin(),
EE = InEdges.end(); EI != EE; ++EI) {
BasicBlock *Back = *EI;
BP->setEdgeWeight(BB, Back, inWeight);
if (exitWeight < MIN_WEIGHT)
exitWeight = MIN_WEIGHT;
- for (SmallVector<BasicBlock *, 8>::iterator EI = ExitingEdges.begin(),
+ for (SmallPtrSet<BasicBlock *, 8>::iterator EI = ExitingEdges.begin(),
EE = ExitingEdges.end(); EI != EE; ++EI) {
BasicBlock *Exiting = *EI;
BP->setEdgeWeight(BB, Exiting, exitWeight);
if (!CI)
return false;
- Value *LHS = CI->getOperand(0);
Value *RHS = CI->getOperand(1);
-
- bool hasZero = false;
- bool lhsZero = false;
- if (ConstantInt *CI = dyn_cast<ConstantInt>(LHS)) {
- hasZero = CI->isZero();
- lhsZero = true;
- }
-
- if (!hasZero)
- if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
- hasZero = CI->isZero();
-
- if (!hasZero)
+ ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
+ if (!CV)
return false;
bool isProb;
- switch (CI->getPredicate()) {
- case CmpInst::ICMP_EQ:
- // Equal to zero is not expected to be taken.
+ if (CV->isZero()) {
+ switch (CI->getPredicate()) {
+ case CmpInst::ICMP_EQ:
+ // X == 0 -> Unlikely
+ isProb = false;
+ break;
+ case CmpInst::ICMP_NE:
+ // X != 0 -> Likely
+ isProb = true;
+ break;
+ case CmpInst::ICMP_SLT:
+ // X < 0 -> Unlikely
+ isProb = false;
+ break;
+ case CmpInst::ICMP_SGT:
+ // X > 0 -> Likely
+ isProb = true;
+ break;
+ default:
+ return false;
+ }
+ } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
+ // InstCombine canonicalizes X <= 0 into X < 1.
+ // X <= 0 -> Unlikely
isProb = false;
- break;
-
- case CmpInst::ICMP_NE:
- // Not equal to zero is expected.
+ } else if (CV->isAllOnesValue() && CI->getPredicate() == CmpInst::ICMP_SGT) {
+ // InstCombine canonicalizes X >= 0 into X > -1.
+ // X >= 0 -> Likely
isProb = true;
- break;
-
- case CmpInst::ICMP_ULT:
- case CmpInst::ICMP_ULE:
- case CmpInst::ICMP_SLT:
- case CmpInst::ICMP_SLE:
- // Less or equal to zero is not expected.
- // 0 < X -> isProb = true
- // 0 <= X -> isProb = true
- // X < 0 -> isProb = false
- // X <= 0 -> isProb = false
- isProb = lhsZero;
- break;
-
- case CmpInst::ICMP_UGT:
- case CmpInst::ICMP_UGE:
- case CmpInst::ICMP_SGT:
- case CmpInst::ICMP_SGE:
- // Greater or equal to zero is expected.
- // 0 > X -> isProb = false
- // 0 >= X -> isProb = false
- // X > 0 -> isProb = true
- // X >= 0 -> isProb = true
- isProb = !lhsZero;
- break;
-
- default:
+ } else {
return false;
- };
+ }
BasicBlock *Taken = BI->getSuccessor(0);
BasicBlock *NonTaken = BI->getSuccessor(1);
return true;
}
+bool BranchProbabilityAnalysis::calcFloatingPointHeuristics(BasicBlock *BB) {
+ BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
+ if (!BI || !BI->isConditional())
+ return false;
-bool BranchProbabilityAnalysis::runOnFunction(Function &F) {
+ Value *Cond = BI->getCondition();
+ FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
+ if (!FCmp)
+ return false;
- for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
- BasicBlock *BB = I++;
+ bool isProb;
+ if (FCmp->isEquality()) {
+ // f1 == f2 -> Unlikely
+ // f1 != f2 -> Likely
+ isProb = !FCmp->isTrueWhenEqual();
+ } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
+ // !isnan -> Likely
+ isProb = true;
+ } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
+ // isnan -> Unlikely
+ isProb = false;
+ } else {
+ return false;
+ }
- // Only LBH uses setEdgeWeight method.
- if (calcLoopBranchHeuristics(BB))
- continue;
+ BasicBlock *Taken = BI->getSuccessor(0);
+ BasicBlock *NonTaken = BI->getSuccessor(1);
- // PH and RH use only incEdgeWeight and decEwdgeWeight methods to
- // not efface LBH results.
- if (calcReturnHeuristics(BB))
- continue;
+ if (!isProb)
+ std::swap(Taken, NonTaken);
- if (calcPointerHeuristics(BB))
- continue;
+ BP->setEdgeWeight(BB, Taken, FPH_TAKEN_WEIGHT);
+ BP->setEdgeWeight(BB, NonTaken, FPH_NONTAKEN_WEIGHT);
- calcZeroHeuristics(BB);
- }
+ return true;
+}
+bool BranchProbabilityAnalysis::runOnFunction(Function &F) {
+ for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
+ if (calcMetadataWeights(I))
+ continue;
+ if (calcLoopBranchHeuristics(I))
+ continue;
+ if (calcReturnHeuristics(I))
+ continue;
+ if (calcPointerHeuristics(I))
+ continue;
+ if (calcZeroHeuristics(I))
+ continue;
+ calcFloatingPointHeuristics(I);
+ }
return false;
}
void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
- AU.addRequired<LoopInfo>();
- AU.setPreservesAll();
+ AU.addRequired<LoopInfo>();
+ AU.setPreservesAll();
}
bool BranchProbabilityInfo::runOnFunction(Function &F) {
+ LastF = &F; // Store the last function we ran on for printing.
LoopInfo &LI = getAnalysis<LoopInfo>();
- BranchProbabilityAnalysis BPA(&Weights, this, &LI);
+ BranchProbabilityAnalysis BPA(this, &LI);
return BPA.runOnFunction(F);
}
+void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const {
+ OS << "---- Branch Probabilities ----\n";
+ // We print the probabilities from the last function the analysis ran over,
+ // or the function it is currently running over.
+ assert(LastF && "Cannot print prior to running over a function");
+ for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
+ BI != BE; ++BI) {
+ for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
+ SI != SE; ++SI) {
+ printEdgeProbability(OS << " ", BI, *SI);
+ }
+ }
+}
+
uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const {
uint32_t Sum = 0;
bool BranchProbabilityInfo::
isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
// Hot probability is at least 4/5 = 80%
- uint32_t Weight = getEdgeWeight(Src, Dst);
- uint32_t Sum = getSumForBlock(Src);
-
- // FIXME: Implement BranchProbability::compare then change this code to
- // compare this BranchProbability against a static "hot" BranchProbability.
- return (uint64_t)Weight * 5 > (uint64_t)Sum * 4;
+ // FIXME: Compare against a static "hot" BranchProbability.
+ return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
}
BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
}
}
- // FIXME: Use BranchProbability::compare.
- if ((uint64_t)MaxWeight * 5 > (uint64_t)Sum * 4)
+ // Hot probability is at least 4/5 = 80%
+ if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
return MaxSucc;
return 0;
}
raw_ostream &
-BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, BasicBlock *Src,
- BasicBlock *Dst) const {
+BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
+ const BasicBlock *Src,
+ const BasicBlock *Dst) const {
const BranchProbability Prob = getEdgeProbability(Src, Dst);
OS << "edge " << Src->getNameStr() << " -> " << Dst->getNameStr()