blob: b255ce6dba5162aaa8e02ce6fef7f800c2759fc6 [file] [log] [blame]
Bill Wendling0c34ae82012-08-15 12:22:35 +00001//===-- BranchProbabilityInfo.cpp - Branch Probability Analysis -----------===//
Andrew Trick9e764222011-06-04 01:16:30 +00002//
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
Jakub Staszaka5dd5502011-07-31 03:27:24 +000014#include "llvm/Constants.h"
Chandler Carruth14edd312011-10-23 21:21:50 +000015#include "llvm/Function.h"
Andrew Trick9e764222011-06-04 01:16:30 +000016#include "llvm/Instructions.h"
Chandler Carruth99d01c52011-10-19 10:30:30 +000017#include "llvm/LLVMContext.h"
18#include "llvm/Metadata.h"
Andrew Trick9e764222011-06-04 01:16:30 +000019#include "llvm/Analysis/BranchProbabilityInfo.h"
Jakub Staszak12af93a2011-07-16 20:31:15 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthde1c9bb2011-10-24 12:01:08 +000021#include "llvm/ADT/PostOrderIterator.h"
Chandler Carruth14edd312011-10-23 21:21:50 +000022#include "llvm/Support/CFG.h"
Andrew Trickf289df22011-06-11 01:05:22 +000023#include "llvm/Support/Debug.h"
Andrew Trick9e764222011-06-04 01:16:30 +000024
25using namespace llvm;
26
27INITIALIZE_PASS_BEGIN(BranchProbabilityInfo, "branch-prob",
28 "Branch Probability Analysis", false, true)
29INITIALIZE_PASS_DEPENDENCY(LoopInfo)
30INITIALIZE_PASS_END(BranchProbabilityInfo, "branch-prob",
31 "Branch Probability Analysis", false, true)
32
33char BranchProbabilityInfo::ID = 0;
34
Chandler Carruthb068bbba2011-10-24 01:40:45 +000035// Weights are for internal use only. They are used by heuristics to help to
36// estimate edges' probability. Example:
37//
38// Using "Loop Branch Heuristics" we predict weights of edges for the
39// block BB2.
40// ...
41// |
42// V
43// BB1<-+
44// | |
45// | | (Weight = 124)
46// V |
47// BB2--+
48// |
49// | (Weight = 4)
50// V
51// BB3
52//
53// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
54// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
55static const uint32_t LBH_TAKEN_WEIGHT = 124;
56static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick9e764222011-06-04 01:16:30 +000057
Chandler Carruthde1c9bb2011-10-24 12:01:08 +000058/// \brief Unreachable-terminating branch taken weight.
59///
60/// This is the weight for a branch being taken to a block that terminates
61/// (eventually) in unreachable. These are predicted as unlikely as possible.
62static const uint32_t UR_TAKEN_WEIGHT = 1;
63
64/// \brief Unreachable-terminating branch not-taken weight.
65///
66/// This is the weight for a branch not being taken toward a block that
67/// terminates (eventually) in unreachable. Such a branch is essentially never
Chandler Carruth51f40a72011-12-22 09:26:37 +000068/// taken. Set the weight to an absurdly high value so that nested loops don't
69/// easily subsume it.
70static const uint32_t UR_NONTAKEN_WEIGHT = 1024*1024 - 1;
Andrew Trick9e764222011-06-04 01:16:30 +000071
Chandler Carruthb068bbba2011-10-24 01:40:45 +000072static const uint32_t PH_TAKEN_WEIGHT = 20;
73static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick9e764222011-06-04 01:16:30 +000074
Chandler Carruthb068bbba2011-10-24 01:40:45 +000075static const uint32_t ZH_TAKEN_WEIGHT = 20;
76static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick9e764222011-06-04 01:16:30 +000077
Chandler Carruthb068bbba2011-10-24 01:40:45 +000078static const uint32_t FPH_TAKEN_WEIGHT = 20;
79static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick9e764222011-06-04 01:16:30 +000080
Bill Wendling0c34ae82012-08-15 12:22:35 +000081/// \brief Invoke-terminating normal branch taken weight
82///
83/// This is the weight for branching to the normal destination of an invoke
84/// instruction. We expect this to happen most of the time. Set the weight to an
85/// absurdly high value so that nested loops subsume it.
86static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
87
88/// \brief Invoke-terminating normal branch not-taken weight.
89///
90/// This is the weight for branching to the unwind destination of an invoke
91/// instruction. This is essentially never taken.
92static const uint32_t IH_NONTAKEN_WEIGHT = 1;
93
Chandler Carruthb068bbba2011-10-24 01:40:45 +000094// Standard weight value. Used when none of the heuristics set weight for
95// the edge.
96static const uint32_t NORMAL_WEIGHT = 16;
Andrew Trick9e764222011-06-04 01:16:30 +000097
Chandler Carruthb068bbba2011-10-24 01:40:45 +000098// Minimum weight of an edge. Please note, that weight is NEVER 0.
99static const uint32_t MIN_WEIGHT = 1;
Andrew Trick9e764222011-06-04 01:16:30 +0000100
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000101static uint32_t getMaxWeightFor(BasicBlock *BB) {
102 return UINT32_MAX / BB->getTerminator()->getNumSuccessors();
103}
Andrew Trick9e764222011-06-04 01:16:30 +0000104
Andrew Trick9e764222011-06-04 01:16:30 +0000105
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000106/// \brief Calculate edge weights for successors lead to unreachable.
107///
108/// Predict that a successor which leads necessarily to an
109/// unreachable-terminated block as extremely unlikely.
110bool BranchProbabilityInfo::calcUnreachableHeuristics(BasicBlock *BB) {
111 TerminatorInst *TI = BB->getTerminator();
112 if (TI->getNumSuccessors() == 0) {
113 if (isa<UnreachableInst>(TI))
114 PostDominatedByUnreachable.insert(BB);
115 return false;
116 }
117
118 SmallPtrSet<BasicBlock *, 4> UnreachableEdges;
119 SmallPtrSet<BasicBlock *, 4> ReachableEdges;
120
121 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
122 if (PostDominatedByUnreachable.count(*I))
123 UnreachableEdges.insert(*I);
124 else
125 ReachableEdges.insert(*I);
126 }
127
128 // If all successors are in the set of blocks post-dominated by unreachable,
129 // this block is too.
130 if (UnreachableEdges.size() == TI->getNumSuccessors())
131 PostDominatedByUnreachable.insert(BB);
132
133 // Skip probabilities if this block has a single successor or if all were
134 // reachable.
135 if (TI->getNumSuccessors() == 1 || UnreachableEdges.empty())
136 return false;
137
138 uint32_t UnreachableWeight =
139 std::max(UR_TAKEN_WEIGHT / UnreachableEdges.size(), MIN_WEIGHT);
140 for (SmallPtrSet<BasicBlock *, 4>::iterator I = UnreachableEdges.begin(),
141 E = UnreachableEdges.end();
142 I != E; ++I)
143 setEdgeWeight(BB, *I, UnreachableWeight);
144
145 if (ReachableEdges.empty())
146 return true;
147 uint32_t ReachableWeight =
148 std::max(UR_NONTAKEN_WEIGHT / ReachableEdges.size(), NORMAL_WEIGHT);
149 for (SmallPtrSet<BasicBlock *, 4>::iterator I = ReachableEdges.begin(),
150 E = ReachableEdges.end();
151 I != E; ++I)
152 setEdgeWeight(BB, *I, ReachableWeight);
153
154 return true;
155}
156
Chandler Carruth99d01c52011-10-19 10:30:30 +0000157// Propagate existing explicit probabilities from either profile data or
158// 'expect' intrinsic processing.
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000159bool BranchProbabilityInfo::calcMetadataWeights(BasicBlock *BB) {
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000160 TerminatorInst *TI = BB->getTerminator();
161 if (TI->getNumSuccessors() == 1)
162 return false;
163 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
Chandler Carruth99d01c52011-10-19 10:30:30 +0000164 return false;
165
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000166 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
167 if (!WeightsNode)
Chandler Carruth99d01c52011-10-19 10:30:30 +0000168 return false;
169
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000170 // Ensure there are weights for all of the successors. Note that the first
171 // operand to the metadata node is a name, not a weight.
172 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruth99d01c52011-10-19 10:30:30 +0000173 return false;
174
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000175 // Build up the final weights that will be used in a temporary buffer, but
176 // don't add them until all weihts are present. Each weight value is clamped
177 // to [1, getMaxWeightFor(BB)].
Chandler Carruth99d01c52011-10-19 10:30:30 +0000178 uint32_t WeightLimit = getMaxWeightFor(BB);
Chandler Carruth941aa7b2011-10-19 10:32:19 +0000179 SmallVector<uint32_t, 2> Weights;
180 Weights.reserve(TI->getNumSuccessors());
181 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
182 ConstantInt *Weight = dyn_cast<ConstantInt>(WeightsNode->getOperand(i));
183 if (!Weight)
184 return false;
185 Weights.push_back(
186 std::max<uint32_t>(1, Weight->getLimitedValue(WeightLimit)));
187 }
188 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
189 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000190 setEdgeWeight(BB, TI->getSuccessor(i), Weights[i]);
Chandler Carruth99d01c52011-10-19 10:30:30 +0000191
192 return true;
193}
194
Andrew Trick9e764222011-06-04 01:16:30 +0000195// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
196// between two pointer or pointer and NULL will fail.
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000197bool BranchProbabilityInfo::calcPointerHeuristics(BasicBlock *BB) {
Andrew Trick9e764222011-06-04 01:16:30 +0000198 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
199 if (!BI || !BI->isConditional())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000200 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000201
202 Value *Cond = BI->getCondition();
203 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000204 if (!CI || !CI->isEquality())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000205 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000206
207 Value *LHS = CI->getOperand(0);
Andrew Trick9e764222011-06-04 01:16:30 +0000208
209 if (!LHS->getType()->isPointerTy())
Jakub Staszak7241caf2011-07-28 21:45:07 +0000210 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000211
Nick Lewycky404b53e2011-06-04 02:07:10 +0000212 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick9e764222011-06-04 01:16:30 +0000213
214 BasicBlock *Taken = BI->getSuccessor(0);
215 BasicBlock *NonTaken = BI->getSuccessor(1);
216
217 // p != 0 -> isProb = true
218 // p == 0 -> isProb = false
219 // p != q -> isProb = true
220 // p == q -> isProb = false;
Jakub Staszakd7932ca2011-07-15 20:51:06 +0000221 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick9e764222011-06-04 01:16:30 +0000222 if (!isProb)
223 std::swap(Taken, NonTaken);
224
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000225 setEdgeWeight(BB, Taken, PH_TAKEN_WEIGHT);
226 setEdgeWeight(BB, NonTaken, PH_NONTAKEN_WEIGHT);
Jakub Staszak7241caf2011-07-28 21:45:07 +0000227 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000228}
229
230// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
231// as taken, exiting edges as not-taken.
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000232bool BranchProbabilityInfo::calcLoopBranchHeuristics(BasicBlock *BB) {
Andrew Trick9e764222011-06-04 01:16:30 +0000233 Loop *L = LI->getLoopFor(BB);
234 if (!L)
Jakub Staszak7241caf2011-07-28 21:45:07 +0000235 return false;
Andrew Trick9e764222011-06-04 01:16:30 +0000236
Jakub Staszakb137f162011-08-01 19:16:26 +0000237 SmallPtrSet<BasicBlock *, 8> BackEdges;
238 SmallPtrSet<BasicBlock *, 8> ExitingEdges;
239 SmallPtrSet<BasicBlock *, 8> InEdges; // Edges from header to the loop.
Jakub Staszakfa447252011-07-28 21:33:46 +0000240
Andrew Trick9e764222011-06-04 01:16:30 +0000241 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Chandler Carruth45baf6b2011-10-25 09:47:41 +0000242 if (!L->contains(*I))
243 ExitingEdges.insert(*I);
244 else if (L->getHeader() == *I)
245 BackEdges.insert(*I);
246 else
247 InEdges.insert(*I);
Andrew Trick9e764222011-06-04 01:16:30 +0000248 }
249
Andrew Trickf289df22011-06-11 01:05:22 +0000250 if (uint32_t numBackEdges = BackEdges.size()) {
251 uint32_t backWeight = LBH_TAKEN_WEIGHT / numBackEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000252 if (backWeight < NORMAL_WEIGHT)
253 backWeight = NORMAL_WEIGHT;
254
Jakub Staszakb137f162011-08-01 19:16:26 +0000255 for (SmallPtrSet<BasicBlock *, 8>::iterator EI = BackEdges.begin(),
Andrew Trick9e764222011-06-04 01:16:30 +0000256 EE = BackEdges.end(); EI != EE; ++EI) {
257 BasicBlock *Back = *EI;
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000258 setEdgeWeight(BB, Back, backWeight);
Andrew Trick9e764222011-06-04 01:16:30 +0000259 }
260 }
261
Jakub Staszakfa447252011-07-28 21:33:46 +0000262 if (uint32_t numInEdges = InEdges.size()) {
263 uint32_t inWeight = LBH_TAKEN_WEIGHT / numInEdges;
264 if (inWeight < NORMAL_WEIGHT)
265 inWeight = NORMAL_WEIGHT;
266
Jakub Staszakb137f162011-08-01 19:16:26 +0000267 for (SmallPtrSet<BasicBlock *, 8>::iterator EI = InEdges.begin(),
Jakub Staszakfa447252011-07-28 21:33:46 +0000268 EE = InEdges.end(); EI != EE; ++EI) {
269 BasicBlock *Back = *EI;
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000270 setEdgeWeight(BB, Back, inWeight);
Jakub Staszakfa447252011-07-28 21:33:46 +0000271 }
272 }
273
Chandler Carruth45baf6b2011-10-25 09:47:41 +0000274 if (uint32_t numExitingEdges = ExitingEdges.size()) {
275 uint32_t exitWeight = LBH_NONTAKEN_WEIGHT / numExitingEdges;
Andrew Trick9e764222011-06-04 01:16:30 +0000276 if (exitWeight < MIN_WEIGHT)
277 exitWeight = MIN_WEIGHT;
278
Jakub Staszakb137f162011-08-01 19:16:26 +0000279 for (SmallPtrSet<BasicBlock *, 8>::iterator EI = ExitingEdges.begin(),
Andrew Trick9e764222011-06-04 01:16:30 +0000280 EE = ExitingEdges.end(); EI != EE; ++EI) {
281 BasicBlock *Exiting = *EI;
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000282 setEdgeWeight(BB, Exiting, exitWeight);
Andrew Trick9e764222011-06-04 01:16:30 +0000283 }
284 }
Jakub Staszak7241caf2011-07-28 21:45:07 +0000285
286 return true;
Andrew Trick9e764222011-06-04 01:16:30 +0000287}
288
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000289bool BranchProbabilityInfo::calcZeroHeuristics(BasicBlock *BB) {
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000290 BranchInst * BI = dyn_cast<BranchInst>(BB->getTerminator());
291 if (!BI || !BI->isConditional())
292 return false;
293
294 Value *Cond = BI->getCondition();
295 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
296 if (!CI)
297 return false;
298
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000299 Value *RHS = CI->getOperand(1);
Jakub Staszaka385c202011-07-31 04:47:20 +0000300 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000301 if (!CV)
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000302 return false;
303
304 bool isProb;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000305 if (CV->isZero()) {
306 switch (CI->getPredicate()) {
307 case CmpInst::ICMP_EQ:
308 // X == 0 -> Unlikely
309 isProb = false;
310 break;
311 case CmpInst::ICMP_NE:
312 // X != 0 -> Likely
313 isProb = true;
314 break;
315 case CmpInst::ICMP_SLT:
316 // X < 0 -> Unlikely
317 isProb = false;
318 break;
319 case CmpInst::ICMP_SGT:
320 // X > 0 -> Likely
321 isProb = true;
322 break;
323 default:
324 return false;
325 }
326 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
327 // InstCombine canonicalizes X <= 0 into X < 1.
328 // X <= 0 -> Unlikely
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000329 isProb = false;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000330 } else if (CV->isAllOnesValue() && CI->getPredicate() == CmpInst::ICMP_SGT) {
331 // InstCombine canonicalizes X >= 0 into X > -1.
332 // X >= 0 -> Likely
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000333 isProb = true;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000334 } else {
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000335 return false;
Benjamin Kramer26eb8702011-09-04 23:53:04 +0000336 }
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000337
338 BasicBlock *Taken = BI->getSuccessor(0);
339 BasicBlock *NonTaken = BI->getSuccessor(1);
340
341 if (!isProb)
342 std::swap(Taken, NonTaken);
343
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000344 setEdgeWeight(BB, Taken, ZH_TAKEN_WEIGHT);
345 setEdgeWeight(BB, NonTaken, ZH_NONTAKEN_WEIGHT);
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000346
347 return true;
348}
349
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000350bool BranchProbabilityInfo::calcFloatingPointHeuristics(BasicBlock *BB) {
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000351 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
352 if (!BI || !BI->isConditional())
353 return false;
354
355 Value *Cond = BI->getCondition();
356 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000357 if (!FCmp)
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000358 return false;
359
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000360 bool isProb;
361 if (FCmp->isEquality()) {
362 // f1 == f2 -> Unlikely
363 // f1 != f2 -> Likely
364 isProb = !FCmp->isTrueWhenEqual();
365 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
366 // !isnan -> Likely
367 isProb = true;
368 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
369 // isnan -> Unlikely
370 isProb = false;
371 } else {
372 return false;
373 }
374
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000375 BasicBlock *Taken = BI->getSuccessor(0);
376 BasicBlock *NonTaken = BI->getSuccessor(1);
377
Benjamin Kramer675c02b2011-10-21 21:13:47 +0000378 if (!isProb)
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000379 std::swap(Taken, NonTaken);
380
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000381 setEdgeWeight(BB, Taken, FPH_TAKEN_WEIGHT);
382 setEdgeWeight(BB, NonTaken, FPH_NONTAKEN_WEIGHT);
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000383
384 return true;
385}
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000386
Bill Wendling0c34ae82012-08-15 12:22:35 +0000387bool BranchProbabilityInfo::calcInvokeHeuristics(BasicBlock *BB) {
388 InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
389 if (!II)
390 return false;
391
392 BasicBlock *Normal = II->getNormalDest();
393 BasicBlock *Unwind = II->getUnwindDest();
394
395 setEdgeWeight(BB, Normal, IH_TAKEN_WEIGHT);
396 setEdgeWeight(BB, Unwind, IH_NONTAKEN_WEIGHT);
397 return true;
398}
399
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000400void BranchProbabilityInfo::getAnalysisUsage(AnalysisUsage &AU) const {
401 AU.addRequired<LoopInfo>();
402 AU.setPreservesAll();
403}
404
405bool BranchProbabilityInfo::runOnFunction(Function &F) {
406 LastF = &F; // Store the last function we ran on for printing.
407 LI = &getAnalysis<LoopInfo>();
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000408 assert(PostDominatedByUnreachable.empty());
Chandler Carruthb068bbba2011-10-24 01:40:45 +0000409
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000410 // Walk the basic blocks in post-order so that we can build up state about
411 // the successors of a block iteratively.
412 for (po_iterator<BasicBlock *> I = po_begin(&F.getEntryBlock()),
413 E = po_end(&F.getEntryBlock());
414 I != E; ++I) {
415 DEBUG(dbgs() << "Computing probabilities for " << I->getName() << "\n");
416 if (calcUnreachableHeuristics(*I))
Chandler Carruth99d01c52011-10-19 10:30:30 +0000417 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000418 if (calcMetadataWeights(*I))
Jakub Staszak7241caf2011-07-28 21:45:07 +0000419 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000420 if (calcLoopBranchHeuristics(*I))
Jakub Staszak7241caf2011-07-28 21:45:07 +0000421 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000422 if (calcPointerHeuristics(*I))
Jakub Staszaka5dd5502011-07-31 03:27:24 +0000423 continue;
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000424 if (calcZeroHeuristics(*I))
Benjamin Kramerc888aa42011-10-21 20:12:47 +0000425 continue;
Bill Wendling0c34ae82012-08-15 12:22:35 +0000426 if (calcFloatingPointHeuristics(*I))
427 continue;
428 calcInvokeHeuristics(*I);
Andrew Trick9e764222011-06-04 01:16:30 +0000429 }
Chandler Carruthde1c9bb2011-10-24 12:01:08 +0000430
431 PostDominatedByUnreachable.clear();
Andrew Trick9e764222011-06-04 01:16:30 +0000432 return false;
433}
434
Chandler Carruth14edd312011-10-23 21:21:50 +0000435void BranchProbabilityInfo::print(raw_ostream &OS, const Module *) const {
436 OS << "---- Branch Probabilities ----\n";
437 // We print the probabilities from the last function the analysis ran over,
438 // or the function it is currently running over.
439 assert(LastF && "Cannot print prior to running over a function");
440 for (Function::const_iterator BI = LastF->begin(), BE = LastF->end();
441 BI != BE; ++BI) {
442 for (succ_const_iterator SI = succ_begin(BI), SE = succ_end(BI);
443 SI != SE; ++SI) {
444 printEdgeProbability(OS << " ", BI, *SI);
445 }
446 }
447}
448
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000449uint32_t BranchProbabilityInfo::getSumForBlock(const BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000450 uint32_t Sum = 0;
451
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000452 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
453 const BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000454 uint32_t Weight = getEdgeWeight(BB, Succ);
455 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000456
457 Sum += Weight;
458 assert(Sum > PrevSum); (void) PrevSum;
459 }
460
Andrew Trickf289df22011-06-11 01:05:22 +0000461 return Sum;
462}
463
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000464bool BranchProbabilityInfo::
465isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000466 // Hot probability is at least 4/5 = 80%
Benjamin Kramer341473c2011-10-23 11:19:14 +0000467 // FIXME: Compare against a static "hot" BranchProbability.
468 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick9e764222011-06-04 01:16:30 +0000469}
470
471BasicBlock *BranchProbabilityInfo::getHotSucc(BasicBlock *BB) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000472 uint32_t Sum = 0;
473 uint32_t MaxWeight = 0;
Andrew Trick9e764222011-06-04 01:16:30 +0000474 BasicBlock *MaxSucc = 0;
475
476 for (succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
477 BasicBlock *Succ = *I;
Andrew Trickf289df22011-06-11 01:05:22 +0000478 uint32_t Weight = getEdgeWeight(BB, Succ);
479 uint32_t PrevSum = Sum;
Andrew Trick9e764222011-06-04 01:16:30 +0000480
481 Sum += Weight;
482 assert(Sum > PrevSum); (void) PrevSum;
483
484 if (Weight > MaxWeight) {
485 MaxWeight = Weight;
486 MaxSucc = Succ;
487 }
488 }
489
Benjamin Kramer341473c2011-10-23 11:19:14 +0000490 // Hot probability is at least 4/5 = 80%
491 if (BranchProbability(MaxWeight, Sum) > BranchProbability(4, 5))
Andrew Trick9e764222011-06-04 01:16:30 +0000492 return MaxSucc;
493
494 return 0;
495}
496
497// Return edge's weight. If can't find it, return DEFAULT_WEIGHT value.
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000498uint32_t BranchProbabilityInfo::
499getEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick9e764222011-06-04 01:16:30 +0000500 Edge E(Src, Dst);
Andrew Trickf289df22011-06-11 01:05:22 +0000501 DenseMap<Edge, uint32_t>::const_iterator I = Weights.find(E);
Andrew Trick9e764222011-06-04 01:16:30 +0000502
503 if (I != Weights.end())
504 return I->second;
505
506 return DEFAULT_WEIGHT;
507}
508
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000509void BranchProbabilityInfo::
510setEdgeWeight(const BasicBlock *Src, const BasicBlock *Dst, uint32_t Weight) {
Andrew Trick9e764222011-06-04 01:16:30 +0000511 Weights[std::make_pair(Src, Dst)] = Weight;
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000512 DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
513 << Dst->getName() << " weight to " << Weight
Andrew Trickf289df22011-06-11 01:05:22 +0000514 << (isEdgeHot(Src, Dst) ? " [is HOT now]\n" : "\n"));
515}
516
517
518BranchProbability BranchProbabilityInfo::
Jakub Staszak6f6baf12011-07-29 19:30:00 +0000519getEdgeProbability(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trickf289df22011-06-11 01:05:22 +0000520
521 uint32_t N = getEdgeWeight(Src, Dst);
522 uint32_t D = getSumForBlock(Src);
523
524 return BranchProbability(N, D);
Andrew Trick9e764222011-06-04 01:16:30 +0000525}
526
527raw_ostream &
Chandler Carruth14edd312011-10-23 21:21:50 +0000528BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
529 const BasicBlock *Src,
530 const BasicBlock *Dst) const {
Andrew Trick9e764222011-06-04 01:16:30 +0000531
Jakub Staszak7cc2b072011-06-16 20:22:37 +0000532 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000533 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trickf289df22011-06-11 01:05:22 +0000534 << " probability is " << Prob
535 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick9e764222011-06-04 01:16:30 +0000536
537 return OS;
538}