blob: f4aea51d301cde905f00a2d2fde3abc6c3371eb4 [file] [log] [blame]
Eugene Zelenko38c02bc2017-07-21 21:37:46 +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"
Geoff Berryeed65312017-11-01 15:16:50 +000016#include "llvm/ADT/SCCIterator.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000017#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/LoopInfo.h"
John Brawnda4a68a2017-06-08 09:44:40 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000021#include "llvm/IR/Attributes.h"
22#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/Function.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000026#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Metadata.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000031#include "llvm/IR/PassManager.h"
32#include "llvm/IR/Type.h"
33#include "llvm/IR/Value.h"
34#include "llvm/Pass.h"
35#include "llvm/Support/BranchProbability.h"
36#include "llvm/Support/Casting.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000037#include "llvm/Support/Debug.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000038#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000039#include <cassert>
40#include <cstdint>
41#include <iterator>
42#include <utility>
Andrew Trick49371f32011-06-04 01:16:30 +000043
44using namespace llvm;
45
Chandler Carruthf1221bd2014-04-22 02:48:03 +000046#define DEBUG_TYPE "branch-prob"
47
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +000048static cl::opt<bool> PrintBranchProb(
49 "print-bpi", cl::init(false), cl::Hidden,
50 cl::desc("Print the branch probability info."));
51
52cl::opt<std::string> PrintBranchProbFuncName(
53 "print-bpi-func-name", cl::Hidden,
54 cl::desc("The option to specify the name of the function "
55 "whose branch probability info is printed."));
56
Cong Houab23bfb2015-07-15 22:48:29 +000057INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000058 "Branch Probability Analysis", false, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000059INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
John Brawnda4a68a2017-06-08 09:44:40 +000060INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000061INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000062 "Branch Probability Analysis", false, true)
63
Cong Houab23bfb2015-07-15 22:48:29 +000064char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000065
Chandler Carruth7a0094a2011-10-24 01:40:45 +000066// Weights are for internal use only. They are used by heuristics to help to
67// estimate edges' probability. Example:
68//
69// Using "Loop Branch Heuristics" we predict weights of edges for the
70// block BB2.
71// ...
72// |
73// V
74// BB1<-+
75// | |
76// | | (Weight = 124)
77// V |
78// BB2--+
79// |
80// | (Weight = 4)
81// V
82// BB3
83//
84// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
85// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
86static const uint32_t LBH_TAKEN_WEIGHT = 124;
87static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
John Brawn29bbed32018-02-23 17:17:31 +000088// Unlikely edges within a loop are half as likely as other edges
89static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
Andrew Trick49371f32011-06-04 01:16:30 +000090
Serguei Katkovba831f72017-05-18 06:11:56 +000091/// \brief Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +000092///
Serguei Katkovba831f72017-05-18 06:11:56 +000093/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +000094/// (eventually) in unreachable. These are predicted as unlikely as possible.
Serguei Katkovba831f72017-05-18 06:11:56 +000095/// All reachable probability will equally share the remaining part.
96static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +000097
Diego Novilloc6399532013-05-24 12:26:52 +000098/// \brief Weight for a branch taken going into a cold block.
99///
100/// This is the weight for a branch taken toward a block marked
101/// cold. A block is marked cold if it's postdominated by a
102/// block containing a call to a cold function. Cold functions
103/// are those marked with attribute 'cold'.
104static const uint32_t CC_TAKEN_WEIGHT = 4;
105
106/// \brief Weight for a branch not-taken into a cold block.
107///
108/// This is the weight for a branch not taken toward a block marked
109/// cold.
110static const uint32_t CC_NONTAKEN_WEIGHT = 64;
111
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000112static const uint32_t PH_TAKEN_WEIGHT = 20;
113static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000114
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000115static const uint32_t ZH_TAKEN_WEIGHT = 20;
116static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000117
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000118static const uint32_t FPH_TAKEN_WEIGHT = 20;
119static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000120
Bill Wendlinge1c54262012-08-15 12:22:35 +0000121/// \brief Invoke-terminating normal branch taken weight
122///
123/// This is the weight for branching to the normal destination of an invoke
124/// instruction. We expect this to happen most of the time. Set the weight to an
125/// absurdly high value so that nested loops subsume it.
126static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
127
128/// \brief Invoke-terminating normal branch not-taken weight.
129///
130/// This is the weight for branching to the unwind destination of an invoke
131/// instruction. This is essentially never taken.
132static const uint32_t IH_NONTAKEN_WEIGHT = 1;
133
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000134/// \brief Add \p BB to PostDominatedByUnreachable set if applicable.
135void
136BranchProbabilityInfo::updatePostDominatedByUnreachable(const BasicBlock *BB) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000137 const TerminatorInst *TI = BB->getTerminator();
Chandler Carruth7111f452011-10-24 12:01:08 +0000138 if (TI->getNumSuccessors() == 0) {
Sanjoy Das432c1c32016-04-18 19:01:28 +0000139 if (isa<UnreachableInst>(TI) ||
140 // If this block is terminated by a call to
141 // @llvm.experimental.deoptimize then treat it like an unreachable since
142 // the @llvm.experimental.deoptimize call is expected to practically
143 // never execute.
144 BB->getTerminatingDeoptimizeCall())
Chandler Carruth7111f452011-10-24 12:01:08 +0000145 PostDominatedByUnreachable.insert(BB);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000146 return;
Chandler Carruth7111f452011-10-24 12:01:08 +0000147 }
148
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000149 // If the terminator is an InvokeInst, check only the normal destination block
150 // as the unwind edge of InvokeInst is also very unlikely taken.
151 if (auto *II = dyn_cast<InvokeInst>(TI)) {
152 if (PostDominatedByUnreachable.count(II->getNormalDest()))
153 PostDominatedByUnreachable.insert(BB);
154 return;
155 }
156
157 for (auto *I : successors(BB))
158 // If any of successor is not post dominated then BB is also not.
159 if (!PostDominatedByUnreachable.count(I))
160 return;
161
162 PostDominatedByUnreachable.insert(BB);
163}
164
165/// \brief Add \p BB to PostDominatedByColdCall set if applicable.
166void
167BranchProbabilityInfo::updatePostDominatedByColdCall(const BasicBlock *BB) {
168 assert(!PostDominatedByColdCall.count(BB));
169 const TerminatorInst *TI = BB->getTerminator();
170 if (TI->getNumSuccessors() == 0)
171 return;
172
173 // If all of successor are post dominated then BB is also done.
174 if (llvm::all_of(successors(BB), [&](const BasicBlock *SuccBB) {
175 return PostDominatedByColdCall.count(SuccBB);
176 })) {
177 PostDominatedByColdCall.insert(BB);
178 return;
179 }
180
181 // If the terminator is an InvokeInst, check only the normal destination
182 // block as the unwind edge of InvokeInst is also very unlikely taken.
183 if (auto *II = dyn_cast<InvokeInst>(TI))
184 if (PostDominatedByColdCall.count(II->getNormalDest())) {
185 PostDominatedByColdCall.insert(BB);
186 return;
187 }
188
189 // Otherwise, if the block itself contains a cold function, add it to the
190 // set of blocks post-dominated by a cold call.
191 for (auto &I : *BB)
192 if (const CallInst *CI = dyn_cast<CallInst>(&I))
193 if (CI->hasFnAttr(Attribute::Cold)) {
194 PostDominatedByColdCall.insert(BB);
195 return;
196 }
197}
198
199/// \brief Calculate edge weights for successors lead to unreachable.
200///
201/// Predict that a successor which leads necessarily to an
202/// unreachable-terminated block as extremely unlikely.
203bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
204 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000205 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
206
207 // Return false here so that edge weights for InvokeInst could be decided
208 // in calcInvokeHeuristics().
209 if (isa<InvokeInst>(TI))
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000210 return false;
211
Manman Rencf104462012-08-24 18:14:27 +0000212 SmallVector<unsigned, 4> UnreachableEdges;
213 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000214
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000215 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000216 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000217 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000218 else
Manman Rencf104462012-08-24 18:14:27 +0000219 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000220
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000221 // Skip probabilities if all were reachable.
222 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000223 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000224
Cong Houe93b8e12015-12-22 18:56:14 +0000225 if (ReachableEdges.empty()) {
226 BranchProbability Prob(1, UnreachableEdges.size());
227 for (unsigned SuccIdx : UnreachableEdges)
228 setEdgeProbability(BB, SuccIdx, Prob);
Chandler Carruth7111f452011-10-24 12:01:08 +0000229 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000230 }
231
Serguei Katkovba831f72017-05-18 06:11:56 +0000232 auto UnreachableProb = UR_TAKEN_PROB;
233 auto ReachableProb =
234 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
235 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000236
237 for (unsigned SuccIdx : UnreachableEdges)
238 setEdgeProbability(BB, SuccIdx, UnreachableProb);
239 for (unsigned SuccIdx : ReachableEdges)
240 setEdgeProbability(BB, SuccIdx, ReachableProb);
Chandler Carruth7111f452011-10-24 12:01:08 +0000241
242 return true;
243}
244
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000245// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000246// 'expect' intrinsic processing. Examine metadata against unreachable
247// heuristic. The probability of the edge coming to unreachable block is
248// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000249bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
250 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000251 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Rong Xu15848e52017-08-23 21:36:02 +0000252 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000253 return false;
254
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000255 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000256 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000257 return false;
258
Diego Novillode5b8012015-05-07 17:22:06 +0000259 // Check that the number of successors is manageable.
260 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
261
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000262 // Ensure there are weights for all of the successors. Note that the first
263 // operand to the metadata node is a name, not a weight.
264 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000265 return false;
266
Diego Novillode5b8012015-05-07 17:22:06 +0000267 // Build up the final weights that will be used in a temporary buffer.
268 // Compute the sum of all weights to later decide whether they need to
269 // be scaled to fit in 32 bits.
270 uint64_t WeightSum = 0;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000271 SmallVector<uint32_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000272 SmallVector<unsigned, 2> UnreachableIdxs;
273 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000274 Weights.reserve(TI->getNumSuccessors());
275 for (unsigned i = 1, e = WeightsNode->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000276 ConstantInt *Weight =
277 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(i));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000278 if (!Weight)
279 return false;
Diego Novillode5b8012015-05-07 17:22:06 +0000280 assert(Weight->getValue().getActiveBits() <= 32 &&
281 "Too many bits for uint32_t");
282 Weights.push_back(Weight->getZExtValue());
283 WeightSum += Weights.back();
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000284 if (PostDominatedByUnreachable.count(TI->getSuccessor(i - 1)))
285 UnreachableIdxs.push_back(i - 1);
286 else
287 ReachableIdxs.push_back(i - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000288 }
289 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000290
291 // If the sum of weights does not fit in 32 bits, scale every weight down
292 // accordingly.
293 uint64_t ScalingFactor =
294 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
295
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000296 if (ScalingFactor > 1) {
297 WeightSum = 0;
298 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
299 Weights[i] /= ScalingFactor;
300 WeightSum += Weights[i];
301 }
Diego Novillode5b8012015-05-07 17:22:06 +0000302 }
Serguei Katkov63c9c812017-05-12 07:50:06 +0000303 assert(WeightSum <= UINT32_MAX &&
304 "Expected weights to scale down to 32 bits");
Cong Hou6a2c71a2015-12-22 23:45:55 +0000305
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000306 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Cong Hou6a2c71a2015-12-22 23:45:55 +0000307 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000308 Weights[i] = 1;
309 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000310 }
Cong Houe93b8e12015-12-22 18:56:14 +0000311
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000312 // Set the probability.
313 SmallVector<BranchProbability, 2> BP;
314 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
315 BP.push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
316
317 // Examine the metadata against unreachable heuristic.
318 // If the unreachable heuristic is more strong then we use it for this edge.
319 if (UnreachableIdxs.size() > 0 && ReachableIdxs.size() > 0) {
320 auto ToDistribute = BranchProbability::getZero();
Serguei Katkovba831f72017-05-18 06:11:56 +0000321 auto UnreachableProb = UR_TAKEN_PROB;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000322 for (auto i : UnreachableIdxs)
323 if (UnreachableProb < BP[i]) {
324 ToDistribute += BP[i] - UnreachableProb;
325 BP[i] = UnreachableProb;
326 }
327
328 // If we modified the probability of some edges then we must distribute
329 // the difference between reachable blocks.
330 if (ToDistribute > BranchProbability::getZero()) {
331 BranchProbability PerEdge = ToDistribute / ReachableIdxs.size();
Serguei Katkov63c9c812017-05-12 07:50:06 +0000332 for (auto i : ReachableIdxs)
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000333 BP[i] += PerEdge;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000334 }
335 }
336
337 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
338 setEdgeProbability(BB, i, BP[i]);
339
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000340 return true;
341}
342
Diego Novilloc6399532013-05-24 12:26:52 +0000343/// \brief Calculate edge weights for edges leading to cold blocks.
344///
345/// A cold block is one post-dominated by a block with a call to a
346/// cold function. Those edges are unlikely to be taken, so we give
347/// them relatively low weight.
348///
349/// Return true if we could compute the weights for cold edges.
350/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000351bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
352 const TerminatorInst *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000353 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
354
355 // Return false here so that edge weights for InvokeInst could be decided
356 // in calcInvokeHeuristics().
357 if (isa<InvokeInst>(TI))
Diego Novilloc6399532013-05-24 12:26:52 +0000358 return false;
359
360 // Determine which successors are post-dominated by a cold block.
361 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000362 SmallVector<unsigned, 4> NormalEdges;
Mehdi Aminia7978772016-04-07 21:59:28 +0000363 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000364 if (PostDominatedByColdCall.count(*I))
365 ColdEdges.push_back(I.getSuccessorIndex());
366 else
367 NormalEdges.push_back(I.getSuccessorIndex());
368
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000369 // Skip probabilities if no cold edges.
370 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000371 return false;
372
Cong Houe93b8e12015-12-22 18:56:14 +0000373 if (NormalEdges.empty()) {
374 BranchProbability Prob(1, ColdEdges.size());
375 for (unsigned SuccIdx : ColdEdges)
376 setEdgeProbability(BB, SuccIdx, Prob);
Diego Novilloc6399532013-05-24 12:26:52 +0000377 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000378 }
379
Vedant Kumara4bd1462016-12-17 01:02:08 +0000380 auto ColdProb = BranchProbability::getBranchProbability(
381 CC_TAKEN_WEIGHT,
382 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
383 auto NormalProb = BranchProbability::getBranchProbability(
384 CC_NONTAKEN_WEIGHT,
385 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000386
387 for (unsigned SuccIdx : ColdEdges)
388 setEdgeProbability(BB, SuccIdx, ColdProb);
389 for (unsigned SuccIdx : NormalEdges)
390 setEdgeProbability(BB, SuccIdx, NormalProb);
Diego Novilloc6399532013-05-24 12:26:52 +0000391
392 return true;
393}
394
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000395// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000396// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000397bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
398 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000399 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000400 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000401
402 Value *Cond = BI->getCondition();
403 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000404 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000405 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000406
407 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000408
409 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000410 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000411
Nick Lewycky75b20532011-06-04 02:07:10 +0000412 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000413
Andrew Trick49371f32011-06-04 01:16:30 +0000414 // p != 0 -> isProb = true
415 // p == 0 -> isProb = false
416 // p != q -> isProb = true
417 // p == q -> isProb = false;
Manman Rencf104462012-08-24 18:14:27 +0000418 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000419 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000420 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000421 std::swap(TakenIdx, NonTakenIdx);
Andrew Trick49371f32011-06-04 01:16:30 +0000422
Cong Houe93b8e12015-12-22 18:56:14 +0000423 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
424 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
425 setEdgeProbability(BB, TakenIdx, TakenProb);
426 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000427 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000428}
429
Geoff Berryeed65312017-11-01 15:16:50 +0000430static int getSCCNum(const BasicBlock *BB,
431 const BranchProbabilityInfo::SccInfo &SccI) {
432 auto SccIt = SccI.SccNums.find(BB);
433 if (SccIt == SccI.SccNums.end())
434 return -1;
435 return SccIt->second;
436}
437
438// Consider any block that is an entry point to the SCC as a header.
439static bool isSCCHeader(const BasicBlock *BB, int SccNum,
440 BranchProbabilityInfo::SccInfo &SccI) {
441 assert(getSCCNum(BB, SccI) == SccNum);
442
443 // Lazily compute the set of headers for a given SCC and cache the results
444 // in the SccHeaderMap.
445 if (SccI.SccHeaders.size() <= static_cast<unsigned>(SccNum))
446 SccI.SccHeaders.resize(SccNum + 1);
447 auto &HeaderMap = SccI.SccHeaders[SccNum];
448 bool Inserted;
449 BranchProbabilityInfo::SccHeaderMap::iterator HeaderMapIt;
450 std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB, false));
451 if (Inserted) {
452 bool IsHeader = llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
453 [&](const BasicBlock *Pred) {
454 return getSCCNum(Pred, SccI) != SccNum;
455 });
456 HeaderMapIt->second = IsHeader;
457 return IsHeader;
458 } else
459 return HeaderMapIt->second;
460}
461
John Brawn29bbed32018-02-23 17:17:31 +0000462// Compute the unlikely successors to the block BB in the loop L, specifically
463// those that are unlikely because this is a loop, and add them to the
464// UnlikelyBlocks set.
465static void
466computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
467 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
468 // Sometimes in a loop we have a branch whose condition is made false by
469 // taking it. This is typically something like
470 // int n = 0;
471 // while (...) {
472 // if (++n >= MAX) {
473 // n = 0;
474 // }
475 // }
476 // In this sort of situation taking the branch means that at the very least it
477 // won't be taken again in the next iteration of the loop, so we should
478 // consider it less likely than a typical branch.
479 //
480 // We detect this by looking back through the graph of PHI nodes that sets the
481 // value that the condition depends on, and seeing if we can reach a successor
482 // block which can be determined to make the condition false.
483 //
484 // FIXME: We currently consider unlikely blocks to be half as likely as other
485 // blocks, but if we consider the example above the likelyhood is actually
486 // 1/MAX. We could therefore be more precise in how unlikely we consider
487 // blocks to be, but it would require more careful examination of the form
488 // of the comparison expression.
489 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
490 if (!BI || !BI->isConditional())
491 return;
492
493 // Check if the branch is based on an instruction compared with a constant
494 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
495 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
496 !isa<Constant>(CI->getOperand(1)))
497 return;
498
499 // Either the instruction must be a PHI, or a chain of operations involving
500 // constants that ends in a PHI which we can then collapse into a single value
501 // if the PHI value is known.
502 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
503 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
504 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
505 // Collect the instructions until we hit a PHI
506 std::list<BinaryOperator*> InstChain;
507 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
508 isa<Constant>(CmpLHS->getOperand(1))) {
509 // Stop if the chain extends outside of the loop
510 if (!L->contains(CmpLHS))
511 return;
512 InstChain.push_front(dyn_cast<BinaryOperator>(CmpLHS));
513 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
514 if (CmpLHS)
515 CmpPHI = dyn_cast<PHINode>(CmpLHS);
516 }
517 if (!CmpPHI || !L->contains(CmpPHI))
518 return;
519
520 // Trace the phi node to find all values that come from successors of BB
521 SmallPtrSet<PHINode*, 8> VisitedInsts;
522 SmallVector<PHINode*, 8> WorkList;
523 WorkList.push_back(CmpPHI);
524 VisitedInsts.insert(CmpPHI);
525 while (!WorkList.empty()) {
526 PHINode *P = WorkList.back();
527 WorkList.pop_back();
528 for (BasicBlock *B : P->blocks()) {
529 // Skip blocks that aren't part of the loop
530 if (!L->contains(B))
531 continue;
532 Value *V = P->getIncomingValueForBlock(B);
533 // If the source is a PHI add it to the work list if we haven't
534 // already visited it.
535 if (PHINode *PN = dyn_cast<PHINode>(V)) {
536 if (VisitedInsts.insert(PN).second)
537 WorkList.push_back(PN);
538 continue;
539 }
540 // If this incoming value is a constant and B is a successor of BB, then
541 // we can constant-evaluate the compare to see if it makes the branch be
542 // taken or not.
543 Constant *CmpLHSConst = dyn_cast<Constant>(V);
544 if (!CmpLHSConst ||
545 std::find(succ_begin(BB), succ_end(BB), B) == succ_end(BB))
546 continue;
547 // First collapse InstChain
548 for (Instruction *I : InstChain) {
549 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
550 dyn_cast<Constant>(I->getOperand(1)),
551 true);
552 if (!CmpLHSConst)
553 break;
554 }
555 if (!CmpLHSConst)
556 continue;
557 // Now constant-evaluate the compare
558 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
559 CmpLHSConst, CmpConst, true);
560 // If the result means we don't branch to the block then that block is
561 // unlikely.
562 if (Result &&
563 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
564 (Result->isOneValue() && B == BI->getSuccessor(1))))
565 UnlikelyBlocks.insert(B);
566 }
567 }
568}
569
Andrew Trick49371f32011-06-04 01:16:30 +0000570// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
571// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000572bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Geoff Berryeed65312017-11-01 15:16:50 +0000573 const LoopInfo &LI,
574 SccInfo &SccI) {
575 int SccNum;
Cong Houab23bfb2015-07-15 22:48:29 +0000576 Loop *L = LI.getLoopFor(BB);
Geoff Berryeed65312017-11-01 15:16:50 +0000577 if (!L) {
578 SccNum = getSCCNum(BB, SccI);
579 if (SccNum < 0)
580 return false;
581 }
Andrew Trick49371f32011-06-04 01:16:30 +0000582
John Brawn29bbed32018-02-23 17:17:31 +0000583 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
584 if (L)
585 computeUnlikelySuccessors(BB, L, UnlikelyBlocks);
586
Manman Rencf104462012-08-24 18:14:27 +0000587 SmallVector<unsigned, 8> BackEdges;
588 SmallVector<unsigned, 8> ExitingEdges;
589 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000590 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000591
Mehdi Aminia7978772016-04-07 21:59:28 +0000592 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Geoff Berryeed65312017-11-01 15:16:50 +0000593 // Use LoopInfo if we have it, otherwise fall-back to SCC info to catch
594 // irreducible loops.
595 if (L) {
John Brawn29bbed32018-02-23 17:17:31 +0000596 if (UnlikelyBlocks.count(*I) != 0)
597 UnlikelyEdges.push_back(I.getSuccessorIndex());
598 else if (!L->contains(*I))
Geoff Berryeed65312017-11-01 15:16:50 +0000599 ExitingEdges.push_back(I.getSuccessorIndex());
600 else if (L->getHeader() == *I)
601 BackEdges.push_back(I.getSuccessorIndex());
602 else
603 InEdges.push_back(I.getSuccessorIndex());
604 } else {
605 if (getSCCNum(*I, SccI) != SccNum)
606 ExitingEdges.push_back(I.getSuccessorIndex());
607 else if (isSCCHeader(*I, SccNum, SccI))
608 BackEdges.push_back(I.getSuccessorIndex());
609 else
610 InEdges.push_back(I.getSuccessorIndex());
611 }
Andrew Trick49371f32011-06-04 01:16:30 +0000612 }
613
John Brawn29bbed32018-02-23 17:17:31 +0000614 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000615 return false;
616
Cong Houe93b8e12015-12-22 18:56:14 +0000617 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
618 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000619 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
620 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000621 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000622 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000623
Cong Houe93b8e12015-12-22 18:56:14 +0000624 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000625 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
626 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000627 for (unsigned SuccIdx : BackEdges)
628 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000629 }
630
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000631 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000632 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
633 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000634 for (unsigned SuccIdx : InEdges)
635 setEdgeProbability(BB, SuccIdx, Prob);
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000636 }
637
Chandler Carruth32f46e72011-10-25 09:47:41 +0000638 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000639 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
640 Denom);
641 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000642 for (unsigned SuccIdx : ExitingEdges)
643 setEdgeProbability(BB, SuccIdx, Prob);
Andrew Trick49371f32011-06-04 01:16:30 +0000644 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000645
John Brawn29bbed32018-02-23 17:17:31 +0000646 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
647 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
648 Denom);
649 auto Prob = UnlikelyProb / numUnlikelyEdges;
650 for (unsigned SuccIdx : UnlikelyEdges)
651 setEdgeProbability(BB, SuccIdx, Prob);
652 }
653
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000654 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000655}
656
John Brawnda4a68a2017-06-08 09:44:40 +0000657bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
658 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000659 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000660 if (!BI || !BI->isConditional())
661 return false;
662
663 Value *Cond = BI->getCondition();
664 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
665 if (!CI)
666 return false;
667
Jakub Staszak17af66a2011-07-31 03:27:24 +0000668 Value *RHS = CI->getOperand(1);
Jakub Staszakbfb1ae22011-07-31 04:47:20 +0000669 ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000670 if (!CV)
Jakub Staszak17af66a2011-07-31 03:27:24 +0000671 return false;
672
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000673 // If the LHS is the result of AND'ing a value with a single bit bitmask,
674 // we don't have information about probabilities.
675 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
676 if (LHS->getOpcode() == Instruction::And)
677 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000678 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000679 return false;
680
John Brawnda4a68a2017-06-08 09:44:40 +0000681 // Check if the LHS is the return value of a library function
682 LibFunc Func = NumLibFuncs;
683 if (TLI)
684 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
685 if (Function *CalledFn = Call->getCalledFunction())
686 TLI->getLibFunc(*CalledFn, Func);
687
Jakub Staszak17af66a2011-07-31 03:27:24 +0000688 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000689 if (Func == LibFunc_strcasecmp ||
690 Func == LibFunc_strcmp ||
691 Func == LibFunc_strncasecmp ||
692 Func == LibFunc_strncmp ||
693 Func == LibFunc_memcmp) {
694 // strcmp and similar functions return zero, negative, or positive, if the
695 // first string is equal, less, or greater than the second. We consider it
696 // likely that the strings are not equal, so a comparison with zero is
697 // probably false, but also a comparison with any other number is also
698 // probably false given that what exactly is returned for nonzero values is
699 // not specified. Any kind of comparison other than equality we know
700 // nothing about.
701 switch (CI->getPredicate()) {
702 case CmpInst::ICMP_EQ:
703 isProb = false;
704 break;
705 case CmpInst::ICMP_NE:
706 isProb = true;
707 break;
708 default:
709 return false;
710 }
711 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000712 switch (CI->getPredicate()) {
713 case CmpInst::ICMP_EQ:
714 // X == 0 -> Unlikely
715 isProb = false;
716 break;
717 case CmpInst::ICMP_NE:
718 // X != 0 -> Likely
719 isProb = true;
720 break;
721 case CmpInst::ICMP_SLT:
722 // X < 0 -> Unlikely
723 isProb = false;
724 break;
725 case CmpInst::ICMP_SGT:
726 // X > 0 -> Likely
727 isProb = true;
728 break;
729 default:
730 return false;
731 }
732 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
733 // InstCombine canonicalizes X <= 0 into X < 1.
734 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000735 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000736 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000737 switch (CI->getPredicate()) {
738 case CmpInst::ICMP_EQ:
739 // X == -1 -> Unlikely
740 isProb = false;
741 break;
742 case CmpInst::ICMP_NE:
743 // X != -1 -> Likely
744 isProb = true;
745 break;
746 case CmpInst::ICMP_SGT:
747 // InstCombine canonicalizes X >= 0 into X > -1.
748 // X >= 0 -> Likely
749 isProb = true;
750 break;
751 default:
752 return false;
753 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000754 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000755 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000756 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000757
Manman Rencf104462012-08-24 18:14:27 +0000758 unsigned TakenIdx = 0, NonTakenIdx = 1;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000759
760 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000761 std::swap(TakenIdx, NonTakenIdx);
Jakub Staszak17af66a2011-07-31 03:27:24 +0000762
Cong Houe93b8e12015-12-22 18:56:14 +0000763 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
764 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
765 setEdgeProbability(BB, TakenIdx, TakenProb);
766 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000767 return true;
768}
769
Mehdi Aminia7978772016-04-07 21:59:28 +0000770bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
771 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000772 if (!BI || !BI->isConditional())
773 return false;
774
775 Value *Cond = BI->getCondition();
776 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000777 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000778 return false;
779
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000780 bool isProb;
781 if (FCmp->isEquality()) {
782 // f1 == f2 -> Unlikely
783 // f1 != f2 -> Likely
784 isProb = !FCmp->isTrueWhenEqual();
785 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
786 // !isnan -> Likely
787 isProb = true;
788 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
789 // isnan -> Unlikely
790 isProb = false;
791 } else {
792 return false;
793 }
794
Manman Rencf104462012-08-24 18:14:27 +0000795 unsigned TakenIdx = 0, NonTakenIdx = 1;
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000796
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000797 if (!isProb)
Manman Rencf104462012-08-24 18:14:27 +0000798 std::swap(TakenIdx, NonTakenIdx);
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000799
Cong Houe93b8e12015-12-22 18:56:14 +0000800 BranchProbability TakenProb(FPH_TAKEN_WEIGHT,
801 FPH_TAKEN_WEIGHT + FPH_NONTAKEN_WEIGHT);
802 setEdgeProbability(BB, TakenIdx, TakenProb);
803 setEdgeProbability(BB, NonTakenIdx, TakenProb.getCompl());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000804 return true;
805}
Jakub Staszak17af66a2011-07-31 03:27:24 +0000806
Mehdi Aminia7978772016-04-07 21:59:28 +0000807bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
808 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000809 if (!II)
810 return false;
811
Cong Houe93b8e12015-12-22 18:56:14 +0000812 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
813 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
814 setEdgeProbability(BB, 0 /*Index for Normal*/, TakenProb);
815 setEdgeProbability(BB, 1 /*Index for Unwind*/, TakenProb.getCompl());
Bill Wendlinge1c54262012-08-15 12:22:35 +0000816 return true;
817}
818
Pete Cooperb9d2e342015-05-28 19:43:06 +0000819void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +0000820 Probs.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +0000821}
822
Cong Houab23bfb2015-07-15 22:48:29 +0000823void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000824 OS << "---- Branch Probabilities ----\n";
825 // We print the probabilities from the last function the analysis ran over,
826 // or the function it is currently running over.
827 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000828 for (const auto &BI : *LastF) {
829 for (succ_const_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
830 ++SI) {
831 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000832 }
833 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000834}
835
Jakub Staszakefd94c82011-07-29 19:30:00 +0000836bool BranchProbabilityInfo::
837isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000838 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000839 // FIXME: Compare against a static "hot" BranchProbability.
840 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +0000841}
842
Mehdi Aminia7978772016-04-07 21:59:28 +0000843const BasicBlock *
844BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +0000845 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +0000846 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000847
Mehdi Aminia7978772016-04-07 21:59:28 +0000848 for (succ_const_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
849 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +0000850 auto Prob = getEdgeProbability(BB, Succ);
851 if (Prob > MaxProb) {
852 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000853 MaxSucc = Succ;
854 }
855 }
856
Benjamin Kramer929f53f2011-10-23 11:19:14 +0000857 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +0000858 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +0000859 return MaxSucc;
860
Craig Topper9f008862014-04-15 04:59:12 +0000861 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +0000862}
863
Cong Houe93b8e12015-12-22 18:56:14 +0000864/// Get the raw edge probability for the edge. If can't find it, return a
865/// default probability 1/N where N is the number of successors. Here an edge is
866/// specified using PredBlock and an
867/// index to the successors.
868BranchProbability
869BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
870 unsigned IndexInSuccessors) const {
871 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +0000872
Cong Houe93b8e12015-12-22 18:56:14 +0000873 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +0000874 return I->second;
875
Cong Houe93b8e12015-12-22 18:56:14 +0000876 return {1,
877 static_cast<uint32_t>(std::distance(succ_begin(Src), succ_end(Src)))};
Andrew Trick49371f32011-06-04 01:16:30 +0000878}
879
Cong Houd97c1002015-12-01 05:29:22 +0000880BranchProbability
881BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
882 succ_const_iterator Dst) const {
883 return getEdgeProbability(Src, Dst.getSuccessorIndex());
884}
885
Cong Houe93b8e12015-12-22 18:56:14 +0000886/// Get the raw edge probability calculated for the block pair. This returns the
887/// sum of all raw edge probabilities from Src to Dst.
888BranchProbability
889BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
890 const BasicBlock *Dst) const {
891 auto Prob = BranchProbability::getZero();
892 bool FoundProb = false;
893 for (succ_const_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
894 if (*I == Dst) {
895 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
896 if (MapI != Probs.end()) {
897 FoundProb = true;
898 Prob += MapI->second;
899 }
900 }
901 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
902 return FoundProb ? Prob : BranchProbability(1, succ_num);
903}
904
905/// Set the edge probability for a given edge specified by PredBlock and an
906/// index to the successors.
907void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
908 unsigned IndexInSuccessors,
909 BranchProbability Prob) {
910 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000911 Handles.insert(BasicBlockCallbackVH(Src, this));
Cong Houe93b8e12015-12-22 18:56:14 +0000912 DEBUG(dbgs() << "set edge " << Src->getName() << " -> " << IndexInSuccessors
913 << " successor probability to " << Prob << "\n");
914}
915
Andrew Trick49371f32011-06-04 01:16:30 +0000916raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +0000917BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
918 const BasicBlock *Src,
919 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +0000920 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000921 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +0000922 << " probability is " << Prob
923 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +0000924
925 return OS;
926}
Cong Houab23bfb2015-07-15 22:48:29 +0000927
Igor Laevskyee40d1e2016-07-15 14:31:16 +0000928void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
929 for (auto I = Probs.begin(), E = Probs.end(); I != E; ++I) {
930 auto Key = I->first;
931 if (Key.first == BB)
932 Probs.erase(Key);
933 }
934}
935
John Brawnda4a68a2017-06-08 09:44:40 +0000936void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
937 const TargetLibraryInfo *TLI) {
Cong Houab23bfb2015-07-15 22:48:29 +0000938 DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
939 << " ----\n\n");
940 LastF = &F; // Store the last function we ran on for printing.
941 assert(PostDominatedByUnreachable.empty());
942 assert(PostDominatedByColdCall.empty());
943
Geoff Berryeed65312017-11-01 15:16:50 +0000944 // Record SCC numbers of blocks in the CFG to identify irreducible loops.
945 // FIXME: We could only calculate this if the CFG is known to be irreducible
946 // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
947 int SccNum = 0;
948 SccInfo SccI;
949 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
950 ++It, ++SccNum) {
951 // Ignore single-block SCCs since they either aren't loops or LoopInfo will
952 // catch them.
953 const std::vector<const BasicBlock *> &Scc = *It;
954 if (Scc.size() == 1)
955 continue;
956
957 DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
958 for (auto *BB : Scc) {
959 DEBUG(dbgs() << " " << BB->getName());
960 SccI.SccNums[BB] = SccNum;
961 }
962 DEBUG(dbgs() << "\n");
963 }
964
Cong Houab23bfb2015-07-15 22:48:29 +0000965 // Walk the basic blocks in post-order so that we can build up state about
966 // the successors of a block iteratively.
967 for (auto BB : post_order(&F.getEntryBlock())) {
968 DEBUG(dbgs() << "Computing probabilities for " << BB->getName() << "\n");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000969 updatePostDominatedByUnreachable(BB);
970 updatePostDominatedByColdCall(BB);
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000971 // If there is no at least two successors, no sense to set probability.
972 if (BB->getTerminator()->getNumSuccessors() < 2)
973 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000974 if (calcMetadataWeights(BB))
975 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000976 if (calcUnreachableHeuristics(BB))
977 continue;
Cong Houab23bfb2015-07-15 22:48:29 +0000978 if (calcColdCallHeuristics(BB))
979 continue;
Geoff Berryeed65312017-11-01 15:16:50 +0000980 if (calcLoopBranchHeuristics(BB, LI, SccI))
Cong Houab23bfb2015-07-15 22:48:29 +0000981 continue;
982 if (calcPointerHeuristics(BB))
983 continue;
John Brawnda4a68a2017-06-08 09:44:40 +0000984 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +0000985 continue;
986 if (calcFloatingPointHeuristics(BB))
987 continue;
988 calcInvokeHeuristics(BB);
989 }
990
991 PostDominatedByUnreachable.clear();
992 PostDominatedByColdCall.clear();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +0000993
994 if (PrintBranchProb &&
995 (PrintBranchProbFuncName.empty() ||
996 F.getName().equals(PrintBranchProbFuncName))) {
997 print(dbgs());
998 }
Cong Houab23bfb2015-07-15 22:48:29 +0000999}
1000
1001void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1002 AnalysisUsage &AU) const {
1003 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001004 AU.addRequired<TargetLibraryInfoWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001005 AU.setPreservesAll();
1006}
1007
1008bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1009 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
John Brawnda4a68a2017-06-08 09:44:40 +00001010 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1011 BPI.calculate(F, LI, &TLI);
Cong Houab23bfb2015-07-15 22:48:29 +00001012 return false;
1013}
1014
1015void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1016
1017void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1018 const Module *) const {
1019 BPI.print(OS);
1020}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001021
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001022AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001023BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001024BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001025 BranchProbabilityInfo BPI;
John Brawnda4a68a2017-06-08 09:44:40 +00001026 BPI.calculate(F, AM.getResult<LoopAnalysis>(F), &AM.getResult<TargetLibraryAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001027 return BPI;
1028}
1029
1030PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001031BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001032 OS << "Printing analysis results of BPI for function "
1033 << "'" << F.getName() << "':"
1034 << "\n";
1035 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1036 return PreservedAnalyses::all();
1037}