blob: 23d5a887c34af7aed76633b77c1fb9bf23284696 [file] [log] [blame]
Bill Wendlinge1c54262012-08-15 12:22:35 +00001//===-- BranchProbabilityInfo.cpp - Branch Probability Analysis -----------===//
Andrew Trick49371f32011-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
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/Analysis/BranchProbabilityInfo.h"
15#include "llvm/ADT/PostOrderIterator.h"
16#include "llvm/Analysis/LoopInfo.h"
John Brawnda4a68a2017-06-08 09:44:40 +000017#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000018#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/LLVMContext.h"
23#include "llvm/IR/Metadata.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000024#include "llvm/Support/Debug.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000025#include "llvm/Support/raw_ostream.h"
Andrew Trick49371f32011-06-04 01:16:30 +000026
27using namespace llvm;
28
Chandler Carruthf1221bd2014-04-22 02:48:03 +000029#define DEBUG_TYPE "branch-prob"
30
Cong Houab23bfb2015-07-15 22:48:29 +000031INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000032 "Branch Probability Analysis", false, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000033INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
John Brawnda4a68a2017-06-08 09:44:40 +000034INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000035INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000036 "Branch Probability Analysis", false, true)
37
Cong Houab23bfb2015-07-15 22:48:29 +000038char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000039
Chandler Carruth7a0094a2011-10-24 01:40:45 +000040// Weights are for internal use only. They are used by heuristics to help to
41// estimate edges' probability. Example:
42//
43// Using "Loop Branch Heuristics" we predict weights of edges for the
44// block BB2.
45// ...
46// |
47// V
48// BB1<-+
49// | |
50// | | (Weight = 124)
51// V |
52// BB2--+
53// |
54// | (Weight = 4)
55// V
56// BB3
57//
58// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
59// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
60static const uint32_t LBH_TAKEN_WEIGHT = 124;
61static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
Andrew Trick49371f32011-06-04 01:16:30 +000062
Serguei Katkovba831f72017-05-18 06:11:56 +000063/// \brief Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +000064///
Serguei Katkovba831f72017-05-18 06:11:56 +000065/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +000066/// (eventually) in unreachable. These are predicted as unlikely as possible.
Serguei Katkovba831f72017-05-18 06:11:56 +000067/// All reachable probability will equally share the remaining part.
68static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +000069
Diego Novilloc6399532013-05-24 12:26:52 +000070/// \brief Weight for a branch taken going into a cold block.
71///
72/// This is the weight for a branch taken toward a block marked
73/// cold. A block is marked cold if it's postdominated by a
74/// block containing a call to a cold function. Cold functions
75/// are those marked with attribute 'cold'.
76static const uint32_t CC_TAKEN_WEIGHT = 4;
77
78/// \brief Weight for a branch not-taken into a cold block.
79///
80/// This is the weight for a branch not taken toward a block marked
81/// cold.
82static const uint32_t CC_NONTAKEN_WEIGHT = 64;
83
Chandler Carruth7a0094a2011-10-24 01:40:45 +000084static const uint32_t PH_TAKEN_WEIGHT = 20;
85static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +000086
Chandler Carruth7a0094a2011-10-24 01:40:45 +000087static const uint32_t ZH_TAKEN_WEIGHT = 20;
88static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +000089
Chandler Carruth7a0094a2011-10-24 01:40:45 +000090static const uint32_t FPH_TAKEN_WEIGHT = 20;
91static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +000092
Bill Wendlinge1c54262012-08-15 12:22:35 +000093/// \brief Invoke-terminating normal branch taken weight
94///
95/// This is the weight for branching to the normal destination of an invoke
96/// instruction. We expect this to happen most of the time. Set the weight to an
97/// absurdly high value so that nested loops subsume it.
98static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
99
100/// \brief Invoke-terminating normal branch not-taken weight.
101///
102/// This is the weight for branching to the unwind destination of an invoke
103/// instruction. This is essentially never taken.
104static const uint32_t IH_NONTAKEN_WEIGHT = 1;
105
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000106/// \brief Add \p BB to PostDominatedByUnreachable set if applicable.
107void
108BranchProbabilityInfo::updatePostDominatedByUnreachable(const BasicBlock *BB) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000109 const TerminatorInst *TI = BB->getTerminator();
Chandler Carruth7111f452011-10-24 12:01:08 +0000110 if (TI->getNumSuccessors() == 0) {
Sanjoy Das432c1c32016-04-18 19:01:28 +0000111 if (isa<UnreachableInst>(TI) ||
112 // If this block is terminated by a call to
113 // @llvm.experimental.deoptimize then treat it like an unreachable since
114 // the @llvm.experimental.deoptimize call is expected to practically
115 // never execute.
116 BB->getTerminatingDeoptimizeCall())
Chandler Carruth7111f452011-10-24 12:01:08 +0000117 PostDominatedByUnreachable.insert(BB);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000118 return;
Chandler Carruth7111f452011-10-24 12:01:08 +0000119 }
120
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000121 // If the terminator is an InvokeInst, check only the normal destination block
122 // as the unwind edge of InvokeInst is also very unlikely taken.
123 if (auto *II = dyn_cast<InvokeInst>(TI)) {
124 if (PostDominatedByUnreachable.count(II->getNormalDest()))
125 PostDominatedByUnreachable.insert(BB);
126 return;
127 }
128
129 for (auto *I : successors(BB))
130 // If any of successor is not post dominated then BB is also not.
131 if (!PostDominatedByUnreachable.count(I))
132 return;
133
134 PostDominatedByUnreachable.insert(BB);
135}
136
137/// \brief Add \p BB to PostDominatedByColdCall set if applicable.
138void
139BranchProbabilityInfo::updatePostDominatedByColdCall(const BasicBlock *BB) {
140 assert(!PostDominatedByColdCall.count(BB));
141 const TerminatorInst *TI = BB->getTerminator();
142 if (TI->getNumSuccessors() == 0)
143 return;
144
145 // If all of successor are post dominated then BB is also done.
146 if (llvm::all_of(successors(BB), [&](const BasicBlock *SuccBB) {
147 return PostDominatedByColdCall.count(SuccBB);
148 })) {
149 PostDominatedByColdCall.insert(BB);
150 return;
151 }
152
153 // If the terminator is an InvokeInst, check only the normal destination
154 // block as the unwind edge of InvokeInst is also very unlikely taken.
155 if (auto *II = dyn_cast<InvokeInst>(TI))
156 if (PostDominatedByColdCall.count(II->getNormalDest())) {
157 PostDominatedByColdCall.insert(BB);
158 return;
159 }
160
161 // Otherwise, if the block itself contains a cold function, add it to the
162 // set of blocks post-dominated by a cold call.
163 for (auto &I : *BB)
164 if (const CallInst *CI = dyn_cast<CallInst>(&I))
165 if (CI->hasFnAttr(Attribute::Cold)) {
166 PostDominatedByColdCall.insert(BB);
167 return;
168 }
169}
170
171/// \brief Calculate edge weights for successors lead to unreachable.
172///
173/// Predict that a successor which leads necessarily to an
174/// unreachable-terminated block as extremely unlikely.
175bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
176 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000177 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
178
179 // Return false here so that edge weights for InvokeInst could be decided
180 // in calcInvokeHeuristics().
181 if (isa<InvokeInst>(TI))
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000182 return false;
183
Manman Rencf104462012-08-24 18:14:27 +0000184 SmallVector<unsigned, 4> UnreachableEdges;
185 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000186
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000187 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000188 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000189 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000190 else
Manman Rencf104462012-08-24 18:14:27 +0000191 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000192
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000193 // Skip probabilities if all were reachable.
194 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000195 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000196
Cong Houe93b8e12015-12-22 18:56:14 +0000197 if (ReachableEdges.empty()) {
198 BranchProbability Prob(1, UnreachableEdges.size());
199 for (unsigned SuccIdx : UnreachableEdges)
200 setEdgeProbability(BB, SuccIdx, Prob);
Chandler Carruth7111f452011-10-24 12:01:08 +0000201 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000202 }
203
Serguei Katkovba831f72017-05-18 06:11:56 +0000204 auto UnreachableProb = UR_TAKEN_PROB;
205 auto ReachableProb =
206 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
207 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000208
209 for (unsigned SuccIdx : UnreachableEdges)
210 setEdgeProbability(BB, SuccIdx, UnreachableProb);
211 for (unsigned SuccIdx : ReachableEdges)
212 setEdgeProbability(BB, SuccIdx, ReachableProb);
Chandler Carruth7111f452011-10-24 12:01:08 +0000213
214 return true;
215}
216
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000217// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000218// 'expect' intrinsic processing. Examine metadata against unreachable
219// heuristic. The probability of the edge coming to unreachable block is
220// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000221bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
222 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000223 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000224 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000225 return false;
226
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000227 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000228 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000229 return false;
230
Diego Novillode5b8012015-05-07 17:22:06 +0000231 // Check that the number of successors is manageable.
232 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
233
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000234 // Ensure there are weights for all of the successors. Note that the first
235 // operand to the metadata node is a name, not a weight.
236 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000237 return false;
238
Diego Novillode5b8012015-05-07 17:22:06 +0000239 // Build up the final weights that will be used in a temporary buffer.
240 // Compute the sum of all weights to later decide whether they need to
241 // be scaled to fit in 32 bits.
242 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000243 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000244 SmallVector<unsigned, 2> UnreachableIdxs;
245 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000246 Weights.reserve(TI->getNumSuccessors());
247 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000248 ConstantInt *Weight =
249 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000250 if (!Weight)
251 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000252 assert(Weight->getValue().getActiveBits() <= 32 &&
253 "Too many bits for uint32_t");
254 Weights.push_back(Weight->getZExtValue());
255 WeightSum += Weights.back();
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000256 if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
257 UnreachableIdxs.push_back(i - 1);
258 else
259 ReachableIdxs.push_back(i - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000260 }
261 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000262
263 // If the sum of weights does not fit in 32 bits, scale every weight down
264 // accordingly.
265 uint64_t ScalingFactor =
266 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
267
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000268 if (ScalingFactor > 1) {
269 WeightSum = 0;
270 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
271 Weights[i] /= ScalingFactor;
272 WeightSum += Weights[i];
273 }
Diego Novillode5b8012015-05-07 17:22:06 +0000274 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000275 assert(WeightSum <= UINT32_MAX &&
276 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000277
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000278 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Cong Hou6a2c71a2015-12-22 23:45:55 +0000279 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000280 Weights[i] = 1;
281 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000282 }
Cong Houe93b8e12015-12-22 18:56:14 +0000283
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000284 // Set the probability.
285 SmallVector<BranchProbability, 2> BP;
286 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
287 BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
288
289 // Examine the metadata against unreachable heuristic.
290 // If the unreachable heuristic is more strong then we use it for this edge.
291 if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
292 auto ToDistribute = BranchProbability::getZero();
Serguei Katkovba831f72017-05-18 06:11:56 +0000293 auto UnreachableProb = UR_TAKEN_PROB;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000294 for (auto i : UnreachableIdxs)
295 if (UnreachableProb < BP[i]) {
296 ToDistribute += BP[i] - UnreachableProb;
297 BP[i] = UnreachableProb;
298 }
299
300 // If we modified the probability of some edges then we must distribute
301 // the difference between reachable blocks.
302 if (ToDistribute > BranchProbability::getZero()) {
303 BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
Serguei Katkov63c9c812017-05-12 07:50:06 +0000304 for (auto i : ReachableIdxs)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000305 BP[i] += PerEdge;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000306 }
307 }
308
309 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
310 setEdgeProbability(BB, i, BP[i]);
311
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000312 return true;
313}
314
Diego Novilloc6399532013-05-24 12:26:52 +0000315/// \brief Calculate edge weights for edges leading to cold blocks.
316///
317/// A cold block is one post-dominated by a block with a call to a
318/// cold function. Those edges are unlikely to be taken, so we give
319/// them relatively low weight.
320///
321/// Return true if we could compute the weights for cold edges.
322/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000323bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
324 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000325 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
326
327 // Return false here so that edge weights for InvokeInst could be decided
328 // in calcInvokeHeuristics().
329 if (isa<InvokeInst>(TI))
Diego Novilloc6399532013-05-24 12:26:52 +0000330 return false;
331
332 // Determine which successors are post-dominated by a cold block.
333 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000334 SmallVector<unsigned, 4> NormalEdges;
Mehdi Aminia7978772016-04-07 21:59:28 +0000335 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000336 if (PostDominatedByColdCall.count(*I))
337 ColdEdges.push_back(I.getSuccessorIndex());
338 else
339 NormalEdges.push_back(I.getSuccessorIndex());
340
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000341 // Skip probabilities if no cold edges.
342 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000343 return false;
344
Cong Houe93b8e12015-12-22 18:56:14 +0000345 if (NormalEdges.empty()) {
346 BranchProbability Prob(1, ColdEdges.size());
347 for (unsigned SuccIdx : ColdEdges)
348 setEdgeProbability(BB, SuccIdx, Prob);
Diego Novilloc6399532013-05-24 12:26:52 +0000349 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000350 }
351
Vedant Kumara4bd1462016-12-17 01:02:08 +0000352 auto ColdProb = BranchProbability::getBranchProbability(
353 CC_TAKEN_WEIGHT,
354 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
355 auto NormalProb = BranchProbability::getBranchProbability(
356 CC_NONTAKEN_WEIGHT,
357 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000358
359 for (unsigned SuccIdx : ColdEdges)
360 setEdgeProbability(BB, SuccIdx, ColdProb);
361 for (unsigned SuccIdx : NormalEdges)
362 setEdgeProbability(BB, SuccIdx, NormalProb);
Diego Novilloc6399532013-05-24 12:26:52 +0000363
364 return true;
365}
366
Andrew Trick49371f32011-06-04 01:16:30 +0000367// Calculate Edge Weights using "Pointer Heuristics". Predict a comparsion
368// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000369bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
370 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000371 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000372 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000373
374 Value *Cond = BI->getCondition();
375 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000376 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000377 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000378
379 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000380
381 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000382 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000383
Nick Lewycky75b20532011-06-04 02:07:10 +0000384 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000385
Andrew Trick49371f32011-06-04 01:16:30 +0000386 // p != 0 -> isProb = true
387 // p == 0 -> isProb = false
388 // p != q -> isProb = true
389 // p == q -> isProb = false;
Manman Rencf104462012-08-24 18:14:27 +0000390 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000391 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000392 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000393 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick49371f32011-06-04 01:16:30 +0000394
Cong Houe93b8e12015-12-22 18:56:14 +0000395 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
396 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
397 setEdgeProbability(BB, TakenIdx, TakenProb);
398 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000399 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000400}
401
402// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
403// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000404bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Cong Houab23bfb2015-07-15 22:48:29 +0000405 const LoopInfo &LI) {
406 Loop *L = LI.getLoopFor(BB);
Andrew Trick49371f32011-06-04 01:16:30 +0000407 if (!L)
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000408 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000409
Manman Rencf104462012-08-24 18:14:27 +0000410 SmallVector<unsigned, 8> BackEdges;
411 SmallVector<unsigned, 8> ExitingEdges;
412 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000413
Mehdi Aminia7978772016-04-07 21:59:28 +0000414 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Chandler Carruth32f46e72011-10-25 09:47:41 +0000415 if (!L->contains(*I))
Manman Rencf104462012-08-24 18:14:27 +0000416 ExitingEdges.push_back(I.getSuccessorIndex());
Chandler Carruth32f46e72011-10-25 09:47:41 +0000417 else if (L->getHeader() == *I)
Manman Rencf104462012-08-24 18:14:27 +0000418 BackEdges.push_back(I.getSuccessorIndex());
Chandler Carruth32f46e72011-10-25 09:47:41 +0000419 else
Manman Rencf104462012-08-24 18:14:27 +0000420 InEdges.push_back(I.getSuccessorIndex());
Andrew Trick49371f32011-06-04 01:16:30 +0000421 }
422
Akira Hatanaka5638b892014-04-14 16:56:19 +0000423 if (BackEdges.empty() && ExitingEdges.empty())
424 return false;
425
Cong Houe93b8e12015-12-22 18:56:14 +0000426 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
427 // normalize them so that they sum up to one.
Benjamin Kramer1d67ac52016-06-17 13:15:10 +0000428 BranchProbability Probs[] = {BranchProbability::getZero(),
429 BranchProbability::getZero(),
430 BranchProbability::getZero()};
Cong Houe93b8e12015-12-22 18:56:14 +0000431 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
432 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
433 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
434 if (!BackEdges.empty())
435 Probs[0] = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
436 if (!InEdges.empty())
437 Probs[1] = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
438 if (!ExitingEdges.empty())
439 Probs[2] = BranchProbability(LBH_NONTAKEN_WEIGHT, Denom);
Andrew Trick49371f32011-06-04 01:16:30 +0000440
Cong Houe93b8e12015-12-22 18:56:14 +0000441 if (uint32_t numBackEdges = BackEdges.size()) {
442 auto Prob = Probs[0] / numBackEdges;
443 for (unsigned SuccIdx : BackEdges)
444 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000445 }
446
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000447 if (uint32_t numInEdges = InEdges.size()) {
Cong Houe93b8e12015-12-22 18:56:14 +0000448 auto Prob = Probs[1] / numInEdges;
449 for (unsigned SuccIdx : InEdges)
450 setEdgeProbability(BB, SuccIdx, Prob);
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000451 }
452
Chandler Carruth32f46e72011-10-25 09:47:41 +0000453 if (uint32_t numExitingEdges = ExitingEdges.size()) {
Cong Houe93b8e12015-12-22 18:56:14 +0000454 auto Prob = Probs[2] / numExitingEdges;
455 for (unsigned SuccIdx : ExitingEdges)
456 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000457 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000458
459 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000460}
461
John Brawnda4a68a2017-06-08 09:44:40 +0000462bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
463 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000464 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000465 if (!BI || !BI->isConditional())
466 return false;
467
468 Value *Cond = BI->getCondition();
469 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
470 if (!CI)
471 return false;
472
Jakub Staszak17af66a2011-07-31 03:27:24 +0000473 Value *RHS = CI->getOperand(1);
Jakub Staszakbfb1ae22011-07-31 04:47:20 +0000474 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000475 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000476 return false;
477
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000478 // If the LHS is the result of AND'ing a value with a single bit bitmask,
479 // we don't have information about probabilities.
480 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
481 if (LHS->getOpcode() == Instruction::And)
482 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
483 if (AndRHS->getUniqueInteger().isPowerOf2())
484 return false;
485
John Brawnda4a68a2017-06-08 09:44:40 +0000486 // Check if the LHS is the return value of a library function
487 LibFunc Func = NumLibFuncs;
488 if (TLI)
489 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
490 if (Function *CalledFn = Call->getCalledFunction())
491 TLI->getLibFunc(*CalledFn, Func);
492
Jakub Staszak17af66a2011-07-31 03:27:24 +0000493 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000494 if (Func == LibFunc_strcasecmp ||
495 Func == LibFunc_strcmp ||
496 Func == LibFunc_strncasecmp ||
497 Func == LibFunc_strncmp ||
498 Func == LibFunc_memcmp) {
499 // strcmp and similar functions return zero, negative, or positive, if the
500 // first string is equal, less, or greater than the second. We consider it
501 // likely that the strings are not equal, so a comparison with zero is
502 // probably false, but also a comparison with any other number is also
503 // probably false given that what exactly is returned for nonzero values is
504 // not specified. Any kind of comparison other than equality we know
505 // nothing about.
506 switch (CI->getPredicate()) {
507 case CmpInst::ICMP_EQ:
508 isProb = false;
509 break;
510 case CmpInst::ICMP_NE:
511 isProb = true;
512 break;
513 default:
514 return false;
515 }
516 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000517 switch (CI->getPredicate()) {
518 case CmpInst::ICMP_EQ:
519 // X == 0 -> Unlikely
520 isProb = false;
521 break;
522 case CmpInst::ICMP_NE:
523 // X != 0 -> Likely
524 isProb = true;
525 break;
526 case CmpInst::ICMP_SLT:
527 // X < 0 -> Unlikely
528 isProb = false;
529 break;
530 case CmpInst::ICMP_SGT:
531 // X > 0 -> Likely
532 isProb = true;
533 break;
534 default:
535 return false;
536 }
537 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
538 // InstCombine canonicalizes X <= 0 into X < 1.
539 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000540 isProb = false;
Hal Finkel4d949302013-11-01 10:58:22 +0000541 } else if (CV->isAllOnesValue()) {
542 switch (CI->getPredicate()) {
543 case CmpInst::ICMP_EQ:
544 // X == -1 -> Unlikely
545 isProb = false;
546 break;
547 case CmpInst::ICMP_NE:
548 // X != -1 -> Likely
549 isProb = true;
550 break;
551 case CmpInst::ICMP_SGT:
552 // InstCombine canonicalizes X >= 0 into X > -1.
553 // X >= 0 -> Likely
554 isProb = true;
555 break;
556 default:
557 return false;
558 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000559 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000560 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000561 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000562
Manman Rencf104462012-08-24 18:14:27 +0000563 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000564
565 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000566 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000567
Cong Houe93b8e12015-12-22 18:56:14 +0000568 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
569 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
570 setEdgeProbability(BB, TakenIdx, TakenProb);
571 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000572 return true;
573}
574
Mehdi Aminia7978772016-04-07 21:59:28 +0000575bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
576 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000577 if (!BI || !BI->isConditional())
578 return false;
579
580 Value *Cond = BI->getCondition();
581 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000582 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000583 return false;
584
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000585 bool isProb;
586 if (FCmp->isEquality()) {
587 // f1 == f2 -> Unlikely
588 // f1 != f2 -> Likely
589 isProb = !FCmp->isTrueWhenEqual();
590 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
591 // !isnan -> Likely
592 isProb = true;
593 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
594 // isnan -> Unlikely
595 isProb = false;
596 } else {
597 return false;
598 }
599
Manman Rencf104462012-08-24 18:14:27 +0000600 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000601
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000602 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000603 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000604
Cong Houe93b8e12015-12-22 18:56:14 +0000605 BranchProbability TakenProb(FPH_TAKEN_WEIGHT,
606 FPH_TAKEN_WEIGHT + FPH_NONTAKEN_WEIGHT);
607 setEdgeProbability(BB, TakenIdx, TakenProb);
608 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000609 return true;
610}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000611
Mehdi Aminia7978772016-04-07 21:59:28 +0000612bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
613 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000614 if (!II)
615 return false;
616
Cong Houe93b8e12015-12-22 18:56:14 +0000617 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
618 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
619 setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
620 setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000621 return true;
622}
623
Pete Cooperb9d2e342015-05-28 19:43:06 +0000624void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +0000625 Probs.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +0000626}
627
Cong Houab23bfb2015-07-15 22:48:29 +0000628void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000629 OS << "---- Branch Probabilities ----\n";
630 // We print the probabilities from the last function the analysis ran over,
631 // or the function it is currently running over.
632 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000633 for (const auto &BI : *LastF) {
634 for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
635 ++SI) {
636 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000637 }
638 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000639}
640
Jakub Staszakefd94c82011-07-29 19:30:00 +0000641bool BranchProbabilityInfo::
642isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000643 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000644 // FIXME: Compare against a static "hot" BranchProbability.
645 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000646}
647
Mehdi Aminia7978772016-04-07 21:59:28 +0000648const BasicBlock *
649BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +0000650 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +0000651 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000652
Mehdi Aminia7978772016-04-07 21:59:28 +0000653 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
654 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +0000655 auto Prob = getEdgeProbability(BB, Succ);
656 if (Prob > MaxProb) {
657 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000658 MaxSucc = Succ;
659 }
660 }
661
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000662 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +0000663 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000664 return MaxSucc;
665
Craig Topper9f008862014-04-15 04:59:12 +0000666 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000667}
668
Cong Houe93b8e12015-12-22 18:56:14 +0000669/// Get the raw edge probability for the edge. If can't find it, return a
670/// default probability 1/N where N is the number of successors. Here an edge is
671/// specified using PredBlock and an
672/// index to the successors.
673BranchProbability
674BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
675 unsigned IndexInSuccessors) const {
676 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000677
Cong Houe93b8e12015-12-22 18:56:14 +0000678 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +0000679 return I->second;
680
Cong Houe93b8e12015-12-22 18:56:14 +0000681 return {1,
682 static_cast<uint32_t>(std::distance(succ_begin(Src), succ_end(Src)))};
Andrew Trick49371f32011-06-04 01:16:30 +0000683}
684
Cong Houd97c1002015-12-01 05:29:22 +0000685BranchProbability
686BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
687 succ_const_iterator Dst) const {
688 return getEdgeProbability(Src, Dst.getSuccessorIndex());
689}
690
Cong Houe93b8e12015-12-22 18:56:14 +0000691/// Get the raw edge probability calculated for the block pair. This returns the
692/// sum of all raw edge probabilities from Src to Dst.
693BranchProbability
694BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
695 const BasicBlock *Dst) const {
696 auto Prob = BranchProbability::getZero();
697 bool FoundProb = false;
698 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
699 if (*I == Dst) {
700 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
701 if (MapI != Probs.end()) {
702 FoundProb = true;
703 Prob += MapI->second;
704 }
705 }
706 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
707 return FoundProb ? Prob : BranchProbability(1, succ_num);
708}
709
710/// Set the edge probability for a given edge specified by PredBlock and an
711/// index to the successors.
712void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
713 unsigned IndexInSuccessors,
714 BranchProbability Prob) {
715 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000716 Handles.insert(BasicBlockCallbackVH(Src, this));
Cong Houe93b8e12015-12-22 18:56:14 +0000717 DEBUG(dbgs() << "set edge " << Src->getName() << " -> " << IndexInSuccessors
718 << " successor probability to " << Prob << "\n");
719}
720
Andrew Trick49371f32011-06-04 01:16:30 +0000721raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000722BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
723 const BasicBlock *Src,
724 const BasicBlock *Dst) const {
Andrew Trick49371f32011-06-04 01:16:30 +0000725
Jakub Staszak12a43bd2011-06-16 20:22:37 +0000726 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000727 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000728 << " probability is " << Prob
729 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +0000730
731 return OS;
732}
Cong Houab23bfb2015-07-15 22:48:29 +0000733
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000734void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
735 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
736 auto Key = I->first;
737 if (Key.first == BB)
738 Probs.erase(Key);
739 }
740}
741
John Brawnda4a68a2017-06-08 09:44:40 +0000742void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
743 const TargetLibraryInfo *TLI) {
Cong Houab23bfb2015-07-15 22:48:29 +0000744 DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
745 << " ----\n\n");
746 LastF = &F; // Store the last function we ran on for printing.
747 assert(PostDominatedByUnreachable.empty());
748 assert(PostDominatedByColdCall.empty());
749
750 // Walk the basic blocks in post-order so that we can build up state about
751 // the successors of a block iteratively.
752 for (auto BB : post_order(&F.getEntryBlock())) {
753 DEBUG(dbgs() << "Computing probabilities for " << BB->getName() << "\n");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000754 updatePostDominatedByUnreachable(BB);
755 updatePostDominatedByColdCall(BB);
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000756 // If there is no at least two successors, no sense to set probability.
757 if (BB->getTerminator()->getNumSuccessors() < 2)
758 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000759 if (calcMetadataWeights(BB))
760 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000761 if (calcUnreachableHeuristics(BB))
762 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000763 if (calcColdCallHeuristics(BB))
764 continue;
765 if (calcLoopBranchHeuristics(BB, LI))
766 continue;
767 if (calcPointerHeuristics(BB))
768 continue;
John Brawnda4a68a2017-06-08 09:44:40 +0000769 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +0000770 continue;
771 if (calcFloatingPointHeuristics(BB))
772 continue;
773 calcInvokeHeuristics(BB);
774 }
775
776 PostDominatedByUnreachable.clear();
777 PostDominatedByColdCall.clear();
778}
779
780void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
781 AnalysisUsage &AU) const {
782 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +0000783 AU.addRequired<TargetLibraryInfoWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +0000784 AU.setPreservesAll();
785}
786
787bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
788 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
John Brawnda4a68a2017-06-08 09:44:40 +0000789 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
790 BPI.calculate(F, LI, &TLI);
Cong Houab23bfb2015-07-15 22:48:29 +0000791 return false;
792}
793
794void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
795
796void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
797 const Module *) const {
798 BPI.print(OS);
799}
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000800
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000801AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000802BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +0000803BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000804 BranchProbabilityInfo BPI;
John Brawnda4a68a2017-06-08 09:44:40 +0000805 BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000806 return BPI;
807}
808
809PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +0000810BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +0000811 OS << "Printing analysis results of BPI for function "
812 << "'" << F.getName() << "':"
813 << "\n";
814 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
815 return PreservedAnalyses::all();
816}