blob: 812fac0bb751d3566939417f03ce1c1d8e115c61 [file] [log] [blame]
Andrew Trick9e764222011-06-04 01:16:30 +00001//===-- BranchProbabilityInfo.cpp - 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// Loops should be simplified before this analysis.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Instructions.h"
15#include "llvm/Analysis/BranchProbabilityInfo.h"
Andrew Trickf289df22011-06-11 01:05:22 +000016#include "llvm/Support/Debug.h"
Andrew Trick9e764222011-06-04 01:16:30 +000017
18using namespace llvm;
19
20INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
21 "Branch Probability Analysis", false, true)
22INITIALIZE_PASS_DEPENDENCY(LoopInfo)
23INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
24 "Branch Probability Analysis", false, true)
25
26char BranchProbabilityInfo::ID = 0;
27
28
29// Please note that BranchProbabilityAnalysis is not a FunctionPass.
30// It is created by BranchProbabilityInfo (which is a FunctionPass), which
31// provides a clear interface. Thanks to that, all heuristics and other
32// private methods are hidden in the .cpp file.
33class BranchProbabilityAnalysis {
34
35 typedef std::pair<BasicBlock *, BasicBlock *> Edge;
36
Andrew Trickf289df22011-06-11 01:05:22 +000037 DenseMap<Edge, uint32_t> *Weights;
Andrew Trick9e764222011-06-04 01:16:30 +000038
39 BranchProbabilityInfo *BP;
40
41 LoopInfo *LI;
42
43
44 // Weights are for internal use only. They are used by heuristics to help to
45 // estimate edges' probability. Example:
46 //
47 // Using "Loop Branch Heuristics" we predict weights of edges for the
48 // block BB2.
49 // ...
50 // |
51 // V
52 // BB1<-+
53 // | |
54 // | | (Weight = 128)
55 // V |
56 // BB2--+
57 // |
58 // | (Weight = 4)
59 // V
60 // BB3
61 //
62 // Probability of the edge BB2->BB1 = 128 / (128 + 4) = 0.9696..
63 // Probability of the edge BB2->BB3 = 4 / (128 + 4) = 0.0303..
64
Andrew Trickf289df22011-06-11 01:05:22 +000065 static const uint32_t LBH_TAKEN_WEIGHT = 128;
66 static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick9e764222011-06-04 01:16:30 +000067
68 // Standard weight value. Used when none of the heuristics set weight for
69 // the edge.
Andrew Trickf289df22011-06-11 01:05:22 +000070 static const uint32_t NORMAL_WEIGHT = 16;
Andrew Trick9e764222011-06-04 01:16:30 +000071
72 // Minimum weight of an edge. Please note, that weight is NEVER 0.
Andrew Trickf289df22011-06-11 01:05:22 +000073 static const uint32_t MIN_WEIGHT = 1;
Andrew Trick9e764222011-06-04 01:16:30 +000074
75 // Return TRUE if BB leads directly to a Return Instruction.
76 static bool isReturningBlock(BasicBlock *BB) {
77 SmallPtrSet<BasicBlock *, 8> Visited;
78
79 while (true) {
80 TerminatorInst *TI = BB->getTerminator();
81 if (isa<ReturnInst>(TI))
82 return true;
83
84 if (TI->getNumSuccessors() > 1)
85 break;
86
87 // It is unreachable block which we can consider as a return instruction.
88 if (TI->getNumSuccessors() == 0)
89 return true;
90
91 Visited.insert(BB);
92 BB = TI->getSuccessor(0);
93
94 // Stop if cycle is detected.
95 if (Visited.count(BB))
96 return false;
97 }
98
99 return false;
100 }
101
102 // Multiply Edge Weight by two.
103 void incEdgeWeight(BasicBlock *Src, BasicBlock *Dst) {
Andrew Trickf289df22011-06-11 01:05:22 +0000104 uint32_t Weight = BP->getEdgeWeight(Src, Dst);
105 uint32_t MaxWeight = getMaxWeightFor(Src);
Andrew Trick9e764222011-06-04 01:16:30 +0000106
107 if (Weight * 2 > MaxWeight)
108 BP->setEdgeWeight(Src, Dst, MaxWeight);
109 else
110 BP->setEdgeWeight(Src, Dst, Weight * 2);
111 }
112
113 // Divide Edge Weight by two.
114 void decEdgeWeight(BasicBlock *Src, BasicBlock *Dst) {
Andrew Trickf289df22011-06-11 01:05:22 +0000115 uint32_t Weight = BP->getEdgeWeight(Src, Dst);
Andrew Trick9e764222011-06-04 01:16:30 +0000116
117 assert(Weight > 0);
118 if (Weight / 2 < MIN_WEIGHT)
119 BP->setEdgeWeight(Src, Dst, MIN_WEIGHT);
120 else
121 BP->setEdgeWeight(Src, Dst, Weight / 2);
122 }
123
124
Andrew Trickf289df22011-06-11 01:05:22 +0000125 uint32_t getMaxWeightFor(BasicBlock *BB) const {
126 return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
Andrew Trick9e764222011-06-04 01:16:30 +0000127 }
128
129public:
Andrew Trickf289df22011-06-11 01:05:22 +0000130 BranchProbabilityAnalysis(DenseMap<Edge, uint32_t> *W,
Andrew Trick9e764222011-06-04 01:16:30 +0000131 BranchProbabilityInfo *BP, LoopInfo *LI)
132 : Weights(W), BP(BP), LI(LI) {
133 }
134
135 // Return Heuristics
136 void calcReturnHeuristics(BasicBlock *BB);
137
138 // Pointer Heuristics
139 void calcPointerHeuristics(BasicBlock *BB);
140
141 // Loop Branch Heuristics
142 void calcLoopBranchHeuristics(BasicBlock *BB);
143
144 bool runOnFunction(Function &F);
145};
146
147// Calculate Edge Weights using "Return Heuristics". Predict a successor which
148// leads directly to Return Instruction will not be taken.
149void BranchProbabilityAnalysis::calcReturnHeuristics(BasicBlock *BB){
150 if (BB->getTerminator()->getNumSuccessors() == 1)
151 return;
152
153 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
154 BasicBlock *Succ = *I;
155 if (isReturningBlock(Succ)) {
156 decEdgeWeight(BB, Succ);
157 }
158 }
159}
160
161// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
162// between two pointer or pointer and NULL will fail.
163void BranchProbabilityAnalysis::calcPointerHeuristics(BasicBlock *BB) {
164 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
165 if (!BI || !BI->isConditional())
166 return;
167
168 Value *Cond = BI->getCondition();
169 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
170 if (!CI)
171 return;
172
173 Value *LHS = CI->getOperand(0);
Andrew Trick9e764222011-06-04 01:16:30 +0000174
175 if (!LHS->getType()->isPointerTy())
176 return;
177
Nick Lewycky404b53e2011-06-04 02:07:10 +0000178 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick9e764222011-06-04 01:16:30 +0000179
180 BasicBlock *Taken = BI->getSuccessor(0);
181 BasicBlock *NonTaken = BI->getSuccessor(1);
182
183 // p != 0 -> isProb = true
184 // p == 0 -> isProb = false
185 // p != q -> isProb = true
186 // p == q -> isProb = false;
187 bool isProb = !CI->isEquality();
188 if (!isProb)
189 std::swap(Taken, NonTaken);
190
191 incEdgeWeight(BB, Taken);
192 decEdgeWeight(BB, NonTaken);
193}
194
195// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
196// as taken, exiting edges as not-taken.
197void BranchProbabilityAnalysis::calcLoopBranchHeuristics(BasicBlock *BB) {
Andrew Trickf289df22011-06-11 01:05:22 +0000198 uint32_t numSuccs = BB->getTerminator()->getNumSuccessors();
Andrew Trick9e764222011-06-04 01:16:30 +0000199
200 Loop *L = LI->getLoopFor(BB);
201 if (!L)
202 return;
203
204 SmallVector<BasicBlock *, 8> BackEdges;
205 SmallVector<BasicBlock *, 8> ExitingEdges;
206
207 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
208 BasicBlock *Succ = *I;
209 Loop *SuccL = LI->getLoopFor(Succ);
210 if (SuccL != L)
211 ExitingEdges.push_back(Succ);
212 else if (Succ == L->getHeader())
213 BackEdges.push_back(Succ);
214 }
215
Andrew Trickf289df22011-06-11 01:05:22 +0000216 if (uint32_t numBackEdges = BackEdges.size()) {
217 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000218 if (backWeight < NORMAL_WEIGHT)
219 backWeight = NORMAL_WEIGHT;
220
221 for (SmallVector<BasicBlock *, 8>::iterator EI = BackEdges.begin(),
222 EE = BackEdges.end(); EI != EE; ++EI) {
223 BasicBlock *Back = *EI;
224 BP->setEdgeWeight(BB, Back, backWeight);
225 }
226 }
227
Andrew Trickf289df22011-06-11 01:05:22 +0000228 uint32_t numExitingEdges = ExitingEdges.size();
229 if (uint32_t numNonExitingEdges = numSuccs - numExitingEdges) {
230 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numNonExitingEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000231 if (exitWeight < MIN_WEIGHT)
232 exitWeight = MIN_WEIGHT;
233
234 for (SmallVector<BasicBlock *, 8>::iterator EI = ExitingEdges.begin(),
235 EE = ExitingEdges.end(); EI != EE; ++EI) {
236 BasicBlock *Exiting = *EI;
237 BP->setEdgeWeight(BB, Exiting, exitWeight);
238 }
239 }
240}
241
242bool BranchProbabilityAnalysis::runOnFunction(Function &F) {
243
244 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
245 BasicBlock *BB = I++;
246
247 // Only LBH uses setEdgeWeight method.
248 calcLoopBranchHeuristics(BB);
249
250 // PH and RH use only incEdgeWeight and decEwdgeWeight methods to
251 // not efface LBH results.
252 calcPointerHeuristics(BB);
253 calcReturnHeuristics(BB);
254 }
255
256 return false;
257}
258
259
260bool BranchProbabilityInfo::runOnFunction(Function &F) {
261 LoopInfo &LI = getAnalysis<LoopInfo>();
262 BranchProbabilityAnalysis BPA(&Weights, this, &LI);
Andrew Trickf289df22011-06-11 01:05:22 +0000263 return BPA.runOnFunction(F);
Andrew Trick9e764222011-06-04 01:16:30 +0000264}
265
Andrew Trickf289df22011-06-11 01:05:22 +0000266uint32_t BranchProbabilityInfo::getSumForBlock(BasicBlock *BB) const {
267 uint32_t Sum = 0;
268
269 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Andrew Trick9e764222011-06-04 01:16:30 +0000270 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000271 uint32_t Weight = getEdgeWeight(BB, Succ);
272 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000273
274 Sum += Weight;
275 assert(Sum > PrevSum); (void) PrevSum;
276 }
277
Andrew Trickf289df22011-06-11 01:05:22 +0000278 return Sum;
279}
280
281bool BranchProbabilityInfo::isEdgeHot(BasicBlock *Src, BasicBlock *Dst) const {
282 // Hot probability is at least 4/5 = 80%
283 uint32_t Weight = getEdgeWeight(Src, Dst);
284 uint32_t Sum = getSumForBlock(Src);
285
286 // FIXME: Implement BranchProbability::compare then change this code to
287 // compare this BranchProbability against a static "hot" BranchProbability.
288 return (uint64_t)Weight * 5 > (uint64_t)Sum * 4;
Andrew Trick9e764222011-06-04 01:16:30 +0000289}
290
291BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000292 uint32_t Sum = 0;
293 uint32_t MaxWeight = 0;
Andrew Trick9e764222011-06-04 01:16:30 +0000294 BasicBlock *MaxSucc = 0;
295
296 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
297 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000298 uint32_t Weight = getEdgeWeight(BB, Succ);
299 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000300
301 Sum += Weight;
302 assert(Sum > PrevSum); (void) PrevSum;
303
304 if (Weight > MaxWeight) {
305 MaxWeight = Weight;
306 MaxSucc = Succ;
307 }
308 }
309
Andrew Trickf289df22011-06-11 01:05:22 +0000310 // FIXME: Use BranchProbability::compare.
311 if ((uint64_t)MaxWeight * 5 > (uint64_t)Sum * 4)
Andrew Trick9e764222011-06-04 01:16:30 +0000312 return MaxSucc;
313
314 return 0;
315}
316
317// Return edge's weight. If can't find it, return DEFAULT_WEIGHT value.
Andrew Trickf289df22011-06-11 01:05:22 +0000318uint32_t
Andrew Trick9e764222011-06-04 01:16:30 +0000319BranchProbabilityInfo::getEdgeWeight(BasicBlock *Src, BasicBlock *Dst) const {
320 Edge E(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000321 DenseMap<Edge, uint32_t>::const_iterator I = Weights.find(E);
Andrew Trick9e764222011-06-04 01:16:30 +0000322
323 if (I != Weights.end())
324 return I->second;
325
326 return DEFAULT_WEIGHT;
327}
328
329void BranchProbabilityInfo::setEdgeWeight(BasicBlock *Src, BasicBlock *Dst,
Andrew Trickf289df22011-06-11 01:05:22 +0000330 uint32_t Weight) {
Andrew Trick9e764222011-06-04 01:16:30 +0000331 Weights[std::make_pair(Src, Dst)] = Weight;
Andrew Trickf289df22011-06-11 01:05:22 +0000332 DEBUG(dbgs() << "set edge " << Src->getNameStr() << " -> "
333 << Dst->getNameStr() << " weight to " << Weight
334 << (isEdgeHot(Src, Dst) ? " [is HOT now]\n" : "\n"));
335}
336
337
338BranchProbability BranchProbabilityInfo::
339getEdgeProbability(BasicBlock *Src, BasicBlock *Dst) const {
340
341 uint32_t N = getEdgeWeight(Src, Dst);
342 uint32_t D = getSumForBlock(Src);
343
344 return BranchProbability(N, D);
Andrew Trick9e764222011-06-04 01:16:30 +0000345}
346
347raw_ostream &
348BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS, BasicBlock *Src,
Andrew Trickf289df22011-06-11 01:05:22 +0000349 BasicBlock *Dst) const {
350 BranchProbability Prob = getEdgeProbability(Src, Dst);
Andrew Trick9e764222011-06-04 01:16:30 +0000351
Andrew Trickf289df22011-06-11 01:05:22 +0000352 OS << "edge " << Src->getNameStr() << " -> " << Dst->getNameStr()
353 << " probability is " << Prob
354 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick9e764222011-06-04 01:16:30 +0000355
356 return OS;
357}