blob: 3249468fe942bda1eb266006b8887556d48a1065 [file] [log] [blame]
Eugene Zelenko38c02bc2017-07-21 21:37:46 +00001//===- BranchProbabilityInfo.cpp - Branch Probability Analysis ------------===//
Andrew Trick49371f32011-06-04 01:16:30 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Trick49371f32011-06-04 01:16:30 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carruthed0881b2012-12-03 16:50:05 +000013#include "llvm/Analysis/BranchProbabilityInfo.h"
14#include "llvm/ADT/PostOrderIterator.h"
Geoff Berryeed65312017-11-01 15:16:50 +000015#include "llvm/ADT/SCCIterator.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Analysis/LoopInfo.h"
Taewook Oh2da205d2019-12-02 10:15:22 -080019#include "llvm/Analysis/PostDominators.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"
Mikael Holmen2ca16892018-05-17 09:05:40 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Function.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000027#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000032#include "llvm/IR/PassManager.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080035#include "llvm/InitializePasses.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000036#include "llvm/Pass.h"
37#include "llvm/Support/BranchProbability.h"
38#include "llvm/Support/Casting.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080039#include "llvm/Support/CommandLine.h"
Andrew Trick3d4e64b2011-06-11 01:05:22 +000040#include "llvm/Support/Debug.h"
Arthur Eubanks10f2a0d2020-09-30 12:11:46 -070041#include "llvm/Support/MathExtras.h"
Benjamin Kramer16132e62015-03-23 18:07:13 +000042#include "llvm/Support/raw_ostream.h"
Eugene Zelenko38c02bc2017-07-21 21:37:46 +000043#include <cassert>
44#include <cstdint>
45#include <iterator>
46#include <utility>
Andrew Trick49371f32011-06-04 01:16:30 +000047
48using namespace llvm;
49
Chandler Carruthf1221bd2014-04-22 02:48:03 +000050#define DEBUG_TYPE "branch-prob"
51
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +000052static cl::opt<bool> PrintBranchProb(
53 "print-bpi", cl::init(false), cl::Hidden,
54 cl::desc("Print the branch probability info."));
55
56cl::opt<std::string> PrintBranchProbFuncName(
57 "print-bpi-func-name", cl::Hidden,
58 cl::desc("The option to specify the name of the function "
59 "whose branch probability info is printed."));
60
Cong Houab23bfb2015-07-15 22:48:29 +000061INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000062 "Branch Probability Analysis", false, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +000063INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
John Brawnda4a68a2017-06-08 09:44:40 +000064INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +070065INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Cong Houab23bfb2015-07-15 22:48:29 +000066INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass, "branch-prob",
Andrew Trick49371f32011-06-04 01:16:30 +000067 "Branch Probability Analysis", false, true)
68
Reid Kleckner05da2fe2019-11-13 13:15:01 -080069BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass()
70 : FunctionPass(ID) {
71 initializeBranchProbabilityInfoWrapperPassPass(
72 *PassRegistry::getPassRegistry());
73}
74
Cong Houab23bfb2015-07-15 22:48:29 +000075char BranchProbabilityInfoWrapperPass::ID = 0;
Andrew Trick49371f32011-06-04 01:16:30 +000076
Chandler Carruth7a0094a2011-10-24 01:40:45 +000077// Weights are for internal use only. They are used by heuristics to help to
78// estimate edges' probability. Example:
79//
80// Using "Loop Branch Heuristics" we predict weights of edges for the
81// block BB2.
82// ...
83// |
84// V
85// BB1<-+
86// | |
87// | | (Weight = 124)
88// V |
89// BB2--+
90// |
91// | (Weight = 4)
92// V
93// BB3
94//
95// Probability of the edge BB2->BB1 = 124 / (124 + 4) = 0.96875
96// Probability of the edge BB2->BB3 = 4 / (124 + 4) = 0.03125
97static const uint32_t LBH_TAKEN_WEIGHT = 124;
98static const uint32_t LBH_NONTAKEN_WEIGHT = 4;
John Brawn29bbed32018-02-23 17:17:31 +000099// Unlikely edges within a loop are half as likely as other edges
100static const uint32_t LBH_UNLIKELY_WEIGHT = 62;
Andrew Trick49371f32011-06-04 01:16:30 +0000101
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000102/// Unreachable-terminating branch taken probability.
Chandler Carruth7111f452011-10-24 12:01:08 +0000103///
Serguei Katkovba831f72017-05-18 06:11:56 +0000104/// This is the probability for a branch being taken to a block that terminates
Chandler Carruth7111f452011-10-24 12:01:08 +0000105/// (eventually) in unreachable. These are predicted as unlikely as possible.
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700106/// All reachable probability will proportionally share the remaining part.
Serguei Katkovba831f72017-05-18 06:11:56 +0000107static const BranchProbability UR_TAKEN_PROB = BranchProbability::getRaw(1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000108
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000109/// Weight for a branch taken going into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000110///
111/// This is the weight for a branch taken toward a block marked
112/// cold. A block is marked cold if it's postdominated by a
113/// block containing a call to a cold function. Cold functions
114/// are those marked with attribute 'cold'.
115static const uint32_t CC_TAKEN_WEIGHT = 4;
116
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000117/// Weight for a branch not-taken into a cold block.
Diego Novilloc6399532013-05-24 12:26:52 +0000118///
119/// This is the weight for a branch not taken toward a block marked
120/// cold.
121static const uint32_t CC_NONTAKEN_WEIGHT = 64;
122
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000123static const uint32_t PH_TAKEN_WEIGHT = 20;
124static const uint32_t PH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000125
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200126static const uint32_t ZH_TAKEN_WEIGHT = 20;
127static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000128
Chandler Carruth7a0094a2011-10-24 01:40:45 +0000129static const uint32_t FPH_TAKEN_WEIGHT = 20;
130static const uint32_t FPH_NONTAKEN_WEIGHT = 12;
Andrew Trick49371f32011-06-04 01:16:30 +0000131
Guozhi Weib329e072019-09-10 17:25:11 +0000132/// This is the probability for an ordered floating point comparison.
133static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1;
134/// This is the probability for an unordered floating point comparison, it means
135/// one or two of the operands are NaN. Usually it is used to test for an
136/// exceptional case, so the result is unlikely.
137static const uint32_t FPH_UNO_WEIGHT = 1;
138
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000139/// Invoke-terminating normal branch taken weight
Bill Wendlinge1c54262012-08-15 12:22:35 +0000140///
141/// This is the weight for branching to the normal destination of an invoke
142/// instruction. We expect this to happen most of the time. Set the weight to an
143/// absurdly high value so that nested loops subsume it.
144static const uint32_t IH_TAKEN_WEIGHT = 1024 * 1024 - 1;
145
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000146/// Invoke-terminating normal branch not-taken weight.
Bill Wendlinge1c54262012-08-15 12:22:35 +0000147///
148/// This is the weight for branching to the unwind destination of an invoke
149/// instruction. This is essentially never taken.
150static const uint32_t IH_NONTAKEN_WEIGHT = 1;
151
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +0700152BranchProbabilityInfo::SccInfo::SccInfo(const Function &F) {
153 // Record SCC numbers of blocks in the CFG to identify irreducible loops.
154 // FIXME: We could only calculate this if the CFG is known to be irreducible
155 // (perhaps cache this info in LoopInfo if we can easily calculate it there?).
156 int SccNum = 0;
157 for (scc_iterator<const Function *> It = scc_begin(&F); !It.isAtEnd();
158 ++It, ++SccNum) {
159 // Ignore single-block SCCs since they either aren't loops or LoopInfo will
160 // catch them.
161 const std::vector<const BasicBlock *> &Scc = *It;
162 if (Scc.size() == 1)
163 continue;
164
165 LLVM_DEBUG(dbgs() << "BPI: SCC " << SccNum << ":");
166 for (const auto *BB : Scc) {
167 LLVM_DEBUG(dbgs() << " " << BB->getName());
168 SccNums[BB] = SccNum;
169 calculateSccBlockType(BB, SccNum);
170 }
171 LLVM_DEBUG(dbgs() << "\n");
172 }
173}
174
175int BranchProbabilityInfo::SccInfo::getSCCNum(const BasicBlock *BB) const {
176 auto SccIt = SccNums.find(BB);
177 if (SccIt == SccNums.end())
178 return -1;
179 return SccIt->second;
180}
181
182void BranchProbabilityInfo::SccInfo::getSccEnterBlocks(
183 int SccNum, SmallVectorImpl<BasicBlock *> &Enters) const {
184
185 for (auto MapIt : SccBlocks[SccNum]) {
186 const auto *BB = MapIt.first;
187 if (isSCCHeader(BB, SccNum))
188 for (const auto *Pred : predecessors(BB))
189 if (getSCCNum(Pred) != SccNum)
190 Enters.push_back(const_cast<BasicBlock *>(BB));
191 }
192}
193
194void BranchProbabilityInfo::SccInfo::getSccExitBlocks(
195 int SccNum, SmallVectorImpl<BasicBlock *> &Exits) const {
196 for (auto MapIt : SccBlocks[SccNum]) {
197 const auto *BB = MapIt.first;
198 if (isSCCExitingBlock(BB, SccNum))
199 for (const auto *Succ : successors(BB))
200 if (getSCCNum(Succ) != SccNum)
201 Exits.push_back(const_cast<BasicBlock *>(BB));
202 }
203}
204
205uint32_t BranchProbabilityInfo::SccInfo::getSccBlockType(const BasicBlock *BB,
206 int SccNum) const {
207 assert(getSCCNum(BB) == SccNum);
208
209 assert(SccBlocks.size() > static_cast<unsigned>(SccNum) && "Unknown SCC");
210 const auto &SccBlockTypes = SccBlocks[SccNum];
211
212 auto It = SccBlockTypes.find(BB);
213 if (It != SccBlockTypes.end()) {
214 return It->second;
215 }
216 return Inner;
217}
218
219void BranchProbabilityInfo::SccInfo::calculateSccBlockType(const BasicBlock *BB,
220 int SccNum) {
221 assert(getSCCNum(BB) == SccNum);
222 uint32_t BlockType = Inner;
223
224 if (llvm::any_of(make_range(pred_begin(BB), pred_end(BB)),
225 [&](const BasicBlock *Pred) {
226 // Consider any block that is an entry point to the SCC as
227 // a header.
228 return getSCCNum(Pred) != SccNum;
229 }))
230 BlockType |= Header;
231
232 if (llvm::any_of(
233 make_range(succ_begin(BB), succ_end(BB)),
234 [&](const BasicBlock *Succ) { return getSCCNum(Succ) != SccNum; }))
235 BlockType |= Exiting;
236
237 // Lazily compute the set of headers for a given SCC and cache the results
238 // in the SccHeaderMap.
239 if (SccBlocks.size() <= static_cast<unsigned>(SccNum))
240 SccBlocks.resize(SccNum + 1);
241 auto &SccBlockTypes = SccBlocks[SccNum];
242
243 if (BlockType != Inner) {
244 bool IsInserted;
245 std::tie(std::ignore, IsInserted) =
246 SccBlockTypes.insert(std::make_pair(BB, BlockType));
247 assert(IsInserted && "Duplicated block in SCC");
248 }
249}
250
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700251BranchProbabilityInfo::LoopBlock::LoopBlock(const BasicBlock *BB,
252 const LoopInfo &LI,
253 const SccInfo &SccI)
254 : BB(BB) {
255 LD.first = LI.getLoopFor(BB);
256 if (!LD.first) {
257 LD.second = SccI.getSCCNum(BB);
258 }
259}
260
261bool BranchProbabilityInfo::isLoopEnteringEdge(const LoopEdge &Edge) const {
262 const auto &SrcBlock = Edge.first;
263 const auto &DstBlock = Edge.second;
264 return (DstBlock.getLoop() &&
265 !DstBlock.getLoop()->contains(SrcBlock.getLoop())) ||
266 // Assume that SCCs can't be nested.
267 (DstBlock.getSccNum() != -1 &&
268 SrcBlock.getSccNum() != DstBlock.getSccNum());
269}
270
271bool BranchProbabilityInfo::isLoopExitingEdge(const LoopEdge &Edge) const {
272 return isLoopEnteringEdge({Edge.second, Edge.first});
273}
274
275bool BranchProbabilityInfo::isLoopEnteringExitingEdge(
276 const LoopEdge &Edge) const {
277 return isLoopEnteringEdge(Edge) || isLoopExitingEdge(Edge);
278}
279
280bool BranchProbabilityInfo::isLoopBackEdge(const LoopEdge &Edge) const {
281 const auto &SrcBlock = Edge.first;
282 const auto &DstBlock = Edge.second;
283 return SrcBlock.belongsToSameLoop(DstBlock) &&
284 ((DstBlock.getLoop() &&
285 DstBlock.getLoop()->getHeader() == DstBlock.getBlock()) ||
286 (DstBlock.getSccNum() != -1 &&
287 SccI->isSCCHeader(DstBlock.getBlock(), DstBlock.getSccNum())));
288}
289
290void BranchProbabilityInfo::getLoopEnterBlocks(
291 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Enters) const {
292 if (LB.getLoop()) {
293 auto *Header = LB.getLoop()->getHeader();
294 Enters.append(pred_begin(Header), pred_end(Header));
295 } else {
296 assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?");
297 SccI->getSccEnterBlocks(LB.getSccNum(), Enters);
298 }
299}
300
301void BranchProbabilityInfo::getLoopExitBlocks(
302 const LoopBlock &LB, SmallVectorImpl<BasicBlock *> &Exits) const {
303 if (LB.getLoop()) {
304 LB.getLoop()->getExitBlocks(Exits);
305 } else {
306 assert(LB.getSccNum() != -1 && "LB doesn't belong to any loop?");
307 SccI->getSccExitBlocks(LB.getSccNum(), Exits);
308 }
309}
310
Taewook Oh2da205d2019-12-02 10:15:22 -0800311static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT,
312 SmallVectorImpl<const BasicBlock *> &WorkList,
313 SmallPtrSetImpl<const BasicBlock *> &TargetSet) {
314 SmallVector<BasicBlock *, 8> Descendants;
315 SmallPtrSet<const BasicBlock *, 16> NewItems;
Chandler Carruth7111f452011-10-24 12:01:08 +0000316
Taewook Oh2da205d2019-12-02 10:15:22 -0800317 PDT->getDescendants(const_cast<BasicBlock *>(BB), Descendants);
318 for (auto *BB : Descendants)
319 if (TargetSet.insert(BB).second)
320 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
321 if (!TargetSet.count(*PI))
322 NewItems.insert(*PI);
323 WorkList.insert(WorkList.end(), NewItems.begin(), NewItems.end());
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000324}
325
Taewook Oh2da205d2019-12-02 10:15:22 -0800326/// Compute a set of basic blocks that are post-dominated by unreachables.
327void BranchProbabilityInfo::computePostDominatedByUnreachable(
328 const Function &F, PostDominatorTree *PDT) {
329 SmallVector<const BasicBlock *, 8> WorkList;
330 for (auto &BB : F) {
331 const Instruction *TI = BB.getTerminator();
332 if (TI->getNumSuccessors() == 0) {
333 if (isa<UnreachableInst>(TI) ||
334 // If this block is terminated by a call to
335 // @llvm.experimental.deoptimize then treat it like an unreachable
336 // since the @llvm.experimental.deoptimize call is expected to
337 // practically never execute.
338 BB.getTerminatingDeoptimizeCall())
339 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByUnreachable);
340 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000341 }
342
Taewook Oh2da205d2019-12-02 10:15:22 -0800343 while (!WorkList.empty()) {
344 const BasicBlock *BB = WorkList.pop_back_val();
345 if (PostDominatedByUnreachable.count(BB))
346 continue;
347 // If the terminator is an InvokeInst, check only the normal destination
348 // block as the unwind edge of InvokeInst is also very unlikely taken.
349 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
350 if (PostDominatedByUnreachable.count(II->getNormalDest()))
351 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000352 }
Taewook Oh2da205d2019-12-02 10:15:22 -0800353 // If all the successors are unreachable, BB is unreachable as well.
354 else if (!successors(BB).empty() &&
355 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
356 return PostDominatedByUnreachable.count(Succ);
357 }))
358 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByUnreachable);
359 }
360}
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000361
Taewook Oh2da205d2019-12-02 10:15:22 -0800362/// compute a set of basic blocks that are post-dominated by ColdCalls.
363void BranchProbabilityInfo::computePostDominatedByColdCall(
364 const Function &F, PostDominatorTree *PDT) {
365 SmallVector<const BasicBlock *, 8> WorkList;
366 for (auto &BB : F)
367 for (auto &I : BB)
368 if (const CallInst *CI = dyn_cast<CallInst>(&I))
369 if (CI->hasFnAttr(Attribute::Cold))
370 UpdatePDTWorklist(&BB, PDT, WorkList, PostDominatedByColdCall);
371
372 while (!WorkList.empty()) {
373 const BasicBlock *BB = WorkList.pop_back_val();
374
375 // If the terminator is an InvokeInst, check only the normal destination
376 // block as the unwind edge of InvokeInst is also very unlikely taken.
377 if (auto *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
378 if (PostDominatedByColdCall.count(II->getNormalDest()))
379 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
380 }
381 // If all of successor are post dominated then BB is also done.
382 else if (!successors(BB).empty() &&
383 llvm::all_of(successors(BB), [this](const BasicBlock *Succ) {
384 return PostDominatedByColdCall.count(Succ);
385 }))
386 UpdatePDTWorklist(BB, PDT, WorkList, PostDominatedByColdCall);
387 }
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000388}
389
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000390/// Calculate edge weights for successors lead to unreachable.
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000391///
392/// Predict that a successor which leads necessarily to an
393/// unreachable-terminated block as extremely unlikely.
394bool BranchProbabilityInfo::calcUnreachableHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000395 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000396 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000397 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000398 assert(!isa<InvokeInst>(TI) &&
399 "Invokes should have already been handled by calcInvokeHeuristics");
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000400
Manman Rencf104462012-08-24 18:14:27 +0000401 SmallVector<unsigned, 4> UnreachableEdges;
402 SmallVector<unsigned, 4> ReachableEdges;
Chandler Carruth7111f452011-10-24 12:01:08 +0000403
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700404 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Chandler Carruth7111f452011-10-24 12:01:08 +0000405 if (PostDominatedByUnreachable.count(*I))
Manman Rencf104462012-08-24 18:14:27 +0000406 UnreachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000407 else
Manman Rencf104462012-08-24 18:14:27 +0000408 ReachableEdges.push_back(I.getSuccessorIndex());
Chandler Carruth7111f452011-10-24 12:01:08 +0000409
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000410 // Skip probabilities if all were reachable.
411 if (UnreachableEdges.empty())
Serguei Katkovecebc3d2017-04-12 05:42:14 +0000412 return false;
Jun Bum Lima23e5f72015-12-21 22:00:51 +0000413
Yevgeny Rouban81384872020-05-21 11:49:11 +0700414 SmallVector<BranchProbability, 4> EdgeProbabilities(
415 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000416 if (ReachableEdges.empty()) {
417 BranchProbability Prob(1, UnreachableEdges.size());
418 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700419 EdgeProbabilities[SuccIdx] = Prob;
420 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000421 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000422 }
423
Serguei Katkovba831f72017-05-18 06:11:56 +0000424 auto UnreachableProb = UR_TAKEN_PROB;
425 auto ReachableProb =
426 (BranchProbability::getOne() - UR_TAKEN_PROB * UnreachableEdges.size()) /
427 ReachableEdges.size();
Cong Houe93b8e12015-12-22 18:56:14 +0000428
429 for (unsigned SuccIdx : UnreachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700430 EdgeProbabilities[SuccIdx] = UnreachableProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000431 for (unsigned SuccIdx : ReachableEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700432 EdgeProbabilities[SuccIdx] = ReachableProb;
Chandler Carruth7111f452011-10-24 12:01:08 +0000433
Yevgeny Rouban81384872020-05-21 11:49:11 +0700434 setEdgeProbability(BB, EdgeProbabilities);
Chandler Carruth7111f452011-10-24 12:01:08 +0000435 return true;
436}
437
Arthur Eubanks10f2a0d2020-09-30 12:11:46 -0700438// Scales all values in Weights so that the total fits in 64 bits. Returns the
439// total.
440// FIXME: only scale by the minimum necessary to fit the total within 64 bits.
441static uint64_t ScaleWeights(MutableArrayRef<uint64_t> Weights) {
442 uint64_t Total = 0;
443 bool Overflowed = false;
444 for (uint64_t W : Weights) {
445 Total = SaturatingAdd(Total, W, &Overflowed);
446 if (Overflowed)
447 break;
448 }
449 if (Overflowed) {
450 uint64_t ScaledTotal = 0;
451 for (uint64_t &W : Weights) {
452 W /= UINT32_MAX;
453 ScaledTotal += W;
454 }
455 return ScaledTotal;
456 }
457 return Total;
458}
459
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000460// Propagate existing explicit probabilities from either profile data or
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000461// 'expect' intrinsic processing. Examine metadata against unreachable
462// heuristic. The probability of the edge coming to unreachable block is
463// set to min of metadata and unreachable heuristic.
Mehdi Aminia7978772016-04-07 21:59:28 +0000464bool BranchProbabilityInfo::calcMetadataWeights(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000465 const Instruction *TI = BB->getTerminator();
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000466 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Yevgeny Roubandcfa78a2020-06-04 15:34:14 +0700467 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI) ||
468 isa<InvokeInst>(TI)))
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000469 return false;
470
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000471 MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000472 if (!WeightsNode)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000473 return false;
474
Diego Novillode5b8012015-05-07 17:22:06 +0000475 // Check that the number of successors is manageable.
476 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
477
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000478 // Ensure there are weights for all of the successors. Note that the first
479 // operand to the metadata node is a name, not a weight.
480 if (WeightsNode->getNumOperands() != TI->getNumSuccessors() + 1)
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000481 return false;
482
Diego Novillode5b8012015-05-07 17:22:06 +0000483 // Build up the final weights that will be used in a temporary buffer.
Arthur Eubanks10f2a0d2020-09-30 12:11:46 -0700484 SmallVector<uint64_t, 2> Weights;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000485 SmallVector<unsigned, 2> UnreachableIdxs;
486 SmallVector<unsigned, 2> ReachableIdxs;
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000487 Weights.reserve(TI->getNumSuccessors());
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700488 for (unsigned I = 1, E = WeightsNode->getNumOperands(); I != E; ++I) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000489 ConstantInt *Weight =
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700490 mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(I));
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000491 if (!Weight)
492 return false;
Arthur Eubanks10f2a0d2020-09-30 12:11:46 -0700493 // TODO: remove scaling by UINT32_MAX and use full uint64_t range.
494 uint64_t WeightVal = Weight->getZExtValue();
495 Weights.push_back(WeightVal);
496 // WeightSum += WeightVal;
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700497 if (PostDominatedByUnreachable.count(TI->getSuccessor(I - 1)))
498 UnreachableIdxs.push_back(I - 1);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000499 else
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700500 ReachableIdxs.push_back(I - 1);
Chandler Carruthdeac50c2011-10-19 10:32:19 +0000501 }
502 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
Diego Novillode5b8012015-05-07 17:22:06 +0000503
Arthur Eubanks10f2a0d2020-09-30 12:11:46 -0700504 uint64_t WeightSum = ScaleWeights(Weights);
Cong Hou6a2c71a2015-12-22 23:45:55 +0000505
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000506 if (WeightSum == 0 || ReachableIdxs.size() == 0) {
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700507 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
508 Weights[I] = 1;
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000509 WeightSum = TI->getNumSuccessors();
Cong Hou6a2c71a2015-12-22 23:45:55 +0000510 }
Cong Houe93b8e12015-12-22 18:56:14 +0000511
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000512 // Set the probability.
513 SmallVector<BranchProbability, 2> BP;
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700514 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I)
Arthur Eubanks10f2a0d2020-09-30 12:11:46 -0700515 BP.push_back(
516 BranchProbability::getBranchProbability(Weights[I], WeightSum));
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000517
518 // Examine the metadata against unreachable heuristic.
519 // If the unreachable heuristic is more strong then we use it for this edge.
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700520 if (UnreachableIdxs.size() == 0 || ReachableIdxs.size() == 0) {
521 setEdgeProbability(BB, BP);
522 return true;
523 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000524
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700525 auto UnreachableProb = UR_TAKEN_PROB;
526 for (auto I : UnreachableIdxs)
527 if (UnreachableProb < BP[I]) {
528 BP[I] = UnreachableProb;
529 }
Yevgeny Rouban81384872020-05-21 11:49:11 +0700530
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700531 // Sum of all edge probabilities must be 1.0. If we modified the probability
532 // of some edges then we must distribute the introduced difference over the
533 // reachable blocks.
534 //
535 // Proportional distribution: the relation between probabilities of the
536 // reachable edges is kept unchanged. That is for any reachable edges i and j:
537 // newBP[i] / newBP[j] == oldBP[i] / oldBP[j] =>
538 // newBP[i] / oldBP[i] == newBP[j] / oldBP[j] == K
539 // Where K is independent of i,j.
540 // newBP[i] == oldBP[i] * K
541 // We need to find K.
542 // Make sum of all reachables of the left and right parts:
543 // sum_of_reachable(newBP) == K * sum_of_reachable(oldBP)
544 // Sum of newBP must be equal to 1.0:
545 // sum_of_reachable(newBP) + sum_of_unreachable(newBP) == 1.0 =>
546 // sum_of_reachable(newBP) = 1.0 - sum_of_unreachable(newBP)
547 // Where sum_of_unreachable(newBP) is what has been just changed.
548 // Finally:
549 // K == sum_of_reachable(newBP) / sum_of_reachable(oldBP) =>
550 // K == (1.0 - sum_of_unreachable(newBP)) / sum_of_reachable(oldBP)
551 BranchProbability NewUnreachableSum = BranchProbability::getZero();
552 for (auto I : UnreachableIdxs)
553 NewUnreachableSum += BP[I];
554
555 BranchProbability NewReachableSum =
556 BranchProbability::getOne() - NewUnreachableSum;
557
558 BranchProbability OldReachableSum = BranchProbability::getZero();
559 for (auto I : ReachableIdxs)
560 OldReachableSum += BP[I];
561
562 if (OldReachableSum != NewReachableSum) { // Anything to dsitribute?
563 if (OldReachableSum.isZero()) {
564 // If all oldBP[i] are zeroes then the proportional distribution results
565 // in all zero probabilities and the error stays big. In this case we
566 // evenly spread NewReachableSum over the reachable edges.
567 BranchProbability PerEdge = NewReachableSum / ReachableIdxs.size();
Yevgeny Rouban3bb0d952020-06-02 10:55:27 +0700568 for (auto I : ReachableIdxs)
Yevgeny Rouban07239c72020-06-02 11:28:12 +0700569 BP[I] = PerEdge;
570 } else {
571 for (auto I : ReachableIdxs) {
572 // We use uint64_t to avoid double rounding error of the following
573 // calculation: BP[i] = BP[i] * NewReachableSum / OldReachableSum
574 // The formula is taken from the private constructor
575 // BranchProbability(uint32_t Numerator, uint32_t Denominator)
576 uint64_t Mul = static_cast<uint64_t>(NewReachableSum.getNumerator()) *
577 BP[I].getNumerator();
578 uint32_t Div = static_cast<uint32_t>(
579 divideNearest(Mul, OldReachableSum.getNumerator()));
580 BP[I] = BranchProbability::getRaw(Div);
581 }
582 }
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000583 }
584
Yevgeny Rouban81384872020-05-21 11:49:11 +0700585 setEdgeProbability(BB, BP);
Serguei Katkov2616bbb2017-04-17 04:33:04 +0000586
Chandler Carruthd27a7a92011-10-19 10:30:30 +0000587 return true;
588}
589
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000590/// Calculate edge weights for edges leading to cold blocks.
Diego Novilloc6399532013-05-24 12:26:52 +0000591///
592/// A cold block is one post-dominated by a block with a call to a
593/// cold function. Those edges are unlikely to be taken, so we give
594/// them relatively low weight.
595///
596/// Return true if we could compute the weights for cold edges.
597/// Return false, otherwise.
Mehdi Aminia7978772016-04-07 21:59:28 +0000598bool BranchProbabilityInfo::calcColdCallHeuristics(const BasicBlock *BB) {
Chandler Carruthedb12a82018-10-15 10:04:59 +0000599 const Instruction *TI = BB->getTerminator();
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000600 (void) TI;
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000601 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
Artur Pilipenko4d063e72018-06-08 13:03:21 +0000602 assert(!isa<InvokeInst>(TI) &&
603 "Invokes should have already been handled by calcInvokeHeuristics");
Diego Novilloc6399532013-05-24 12:26:52 +0000604
605 // Determine which successors are post-dominated by a cold block.
606 SmallVector<unsigned, 4> ColdEdges;
Diego Novilloc6399532013-05-24 12:26:52 +0000607 SmallVector<unsigned, 4> NormalEdges;
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700608 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I)
Diego Novilloc6399532013-05-24 12:26:52 +0000609 if (PostDominatedByColdCall.count(*I))
610 ColdEdges.push_back(I.getSuccessorIndex());
611 else
612 NormalEdges.push_back(I.getSuccessorIndex());
613
Serguei Katkov11d9c4f2017-04-17 06:39:47 +0000614 // Skip probabilities if no cold edges.
615 if (ColdEdges.empty())
Diego Novilloc6399532013-05-24 12:26:52 +0000616 return false;
617
Yevgeny Rouban81384872020-05-21 11:49:11 +0700618 SmallVector<BranchProbability, 4> EdgeProbabilities(
619 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000620 if (NormalEdges.empty()) {
621 BranchProbability Prob(1, ColdEdges.size());
622 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700623 EdgeProbabilities[SuccIdx] = Prob;
624 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000625 return true;
Cong Houe93b8e12015-12-22 18:56:14 +0000626 }
627
Vedant Kumara4bd1462016-12-17 01:02:08 +0000628 auto ColdProb = BranchProbability::getBranchProbability(
629 CC_TAKEN_WEIGHT,
630 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.size()));
631 auto NormalProb = BranchProbability::getBranchProbability(
632 CC_NONTAKEN_WEIGHT,
633 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.size()));
Cong Houe93b8e12015-12-22 18:56:14 +0000634
635 for (unsigned SuccIdx : ColdEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700636 EdgeProbabilities[SuccIdx] = ColdProb;
Cong Houe93b8e12015-12-22 18:56:14 +0000637 for (unsigned SuccIdx : NormalEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700638 EdgeProbabilities[SuccIdx] = NormalProb;
Diego Novilloc6399532013-05-24 12:26:52 +0000639
Yevgeny Rouban81384872020-05-21 11:49:11 +0700640 setEdgeProbability(BB, EdgeProbabilities);
Diego Novilloc6399532013-05-24 12:26:52 +0000641 return true;
642}
643
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000644// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
Andrew Trick49371f32011-06-04 01:16:30 +0000645// between two pointer or pointer and NULL will fail.
Mehdi Aminia7978772016-04-07 21:59:28 +0000646bool BranchProbabilityInfo::calcPointerHeuristics(const BasicBlock *BB) {
647 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Andrew Trick49371f32011-06-04 01:16:30 +0000648 if (!BI || !BI->isConditional())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000649 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000650
651 Value *Cond = BI->getCondition();
652 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
Jakub Staszakabb236f2011-07-15 20:51:06 +0000653 if (!CI || !CI->isEquality())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000654 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000655
656 Value *LHS = CI->getOperand(0);
Andrew Trick49371f32011-06-04 01:16:30 +0000657
658 if (!LHS->getType()->isPointerTy())
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000659 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000660
Nick Lewycky75b20532011-06-04 02:07:10 +0000661 assert(CI->getOperand(1)->getType()->isPointerTy());
Andrew Trick49371f32011-06-04 01:16:30 +0000662
Yevgeny Rouban81384872020-05-21 11:49:11 +0700663 BranchProbability TakenProb(PH_TAKEN_WEIGHT,
664 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
665 BranchProbability UntakenProb(PH_NONTAKEN_WEIGHT,
666 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
667
Andrew Trick49371f32011-06-04 01:16:30 +0000668 // p != 0 -> isProb = true
669 // p == 0 -> isProb = false
670 // p != q -> isProb = true
671 // p == q -> isProb = false;
Jakub Staszakabb236f2011-07-15 20:51:06 +0000672 bool isProb = CI->getPredicate() == ICmpInst::ICMP_NE;
Andrew Trick49371f32011-06-04 01:16:30 +0000673 if (!isProb)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700674 std::swap(TakenProb, UntakenProb);
Andrew Trick49371f32011-06-04 01:16:30 +0000675
Yevgeny Rouban81384872020-05-21 11:49:11 +0700676 setEdgeProbability(
677 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000678 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000679}
680
John Brawn29bbed32018-02-23 17:17:31 +0000681// Compute the unlikely successors to the block BB in the loop L, specifically
682// those that are unlikely because this is a loop, and add them to the
683// UnlikelyBlocks set.
684static void
685computeUnlikelySuccessors(const BasicBlock *BB, Loop *L,
686 SmallPtrSetImpl<const BasicBlock*> &UnlikelyBlocks) {
687 // Sometimes in a loop we have a branch whose condition is made false by
688 // taking it. This is typically something like
689 // int n = 0;
690 // while (...) {
691 // if (++n >= MAX) {
692 // n = 0;
693 // }
694 // }
695 // In this sort of situation taking the branch means that at the very least it
696 // won't be taken again in the next iteration of the loop, so we should
697 // consider it less likely than a typical branch.
698 //
699 // We detect this by looking back through the graph of PHI nodes that sets the
700 // value that the condition depends on, and seeing if we can reach a successor
701 // block which can be determined to make the condition false.
702 //
703 // FIXME: We currently consider unlikely blocks to be half as likely as other
704 // blocks, but if we consider the example above the likelyhood is actually
705 // 1/MAX. We could therefore be more precise in how unlikely we consider
706 // blocks to be, but it would require more careful examination of the form
707 // of the comparison expression.
708 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
709 if (!BI || !BI->isConditional())
710 return;
711
712 // Check if the branch is based on an instruction compared with a constant
713 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
714 if (!CI || !isa<Instruction>(CI->getOperand(0)) ||
715 !isa<Constant>(CI->getOperand(1)))
716 return;
717
718 // Either the instruction must be a PHI, or a chain of operations involving
719 // constants that ends in a PHI which we can then collapse into a single value
720 // if the PHI value is known.
721 Instruction *CmpLHS = dyn_cast<Instruction>(CI->getOperand(0));
722 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
723 Constant *CmpConst = dyn_cast<Constant>(CI->getOperand(1));
724 // Collect the instructions until we hit a PHI
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000725 SmallVector<BinaryOperator *, 1> InstChain;
John Brawn29bbed32018-02-23 17:17:31 +0000726 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
727 isa<Constant>(CmpLHS->getOperand(1))) {
728 // Stop if the chain extends outside of the loop
729 if (!L->contains(CmpLHS))
730 return;
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000731 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
John Brawn29bbed32018-02-23 17:17:31 +0000732 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
733 if (CmpLHS)
734 CmpPHI = dyn_cast<PHINode>(CmpLHS);
735 }
736 if (!CmpPHI || !L->contains(CmpPHI))
737 return;
738
739 // Trace the phi node to find all values that come from successors of BB
740 SmallPtrSet<PHINode*, 8> VisitedInsts;
741 SmallVector<PHINode*, 8> WorkList;
742 WorkList.push_back(CmpPHI);
743 VisitedInsts.insert(CmpPHI);
744 while (!WorkList.empty()) {
745 PHINode *P = WorkList.back();
746 WorkList.pop_back();
747 for (BasicBlock *B : P->blocks()) {
748 // Skip blocks that aren't part of the loop
749 if (!L->contains(B))
750 continue;
751 Value *V = P->getIncomingValueForBlock(B);
752 // If the source is a PHI add it to the work list if we haven't
753 // already visited it.
754 if (PHINode *PN = dyn_cast<PHINode>(V)) {
755 if (VisitedInsts.insert(PN).second)
756 WorkList.push_back(PN);
757 continue;
758 }
759 // If this incoming value is a constant and B is a successor of BB, then
760 // we can constant-evaluate the compare to see if it makes the branch be
761 // taken or not.
762 Constant *CmpLHSConst = dyn_cast<Constant>(V);
Kazu Hirata60434982020-08-01 21:49:38 -0700763 if (!CmpLHSConst || !llvm::is_contained(successors(BB), B))
John Brawn29bbed32018-02-23 17:17:31 +0000764 continue;
765 // First collapse InstChain
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000766 for (Instruction *I : llvm::reverse(InstChain)) {
John Brawn29bbed32018-02-23 17:17:31 +0000767 CmpLHSConst = ConstantExpr::get(I->getOpcode(), CmpLHSConst,
Benjamin Kramer7f68a302018-06-15 21:06:43 +0000768 cast<Constant>(I->getOperand(1)), true);
John Brawn29bbed32018-02-23 17:17:31 +0000769 if (!CmpLHSConst)
770 break;
771 }
772 if (!CmpLHSConst)
773 continue;
774 // Now constant-evaluate the compare
775 Constant *Result = ConstantExpr::getCompare(CI->getPredicate(),
776 CmpLHSConst, CmpConst, true);
777 // If the result means we don't branch to the block then that block is
778 // unlikely.
779 if (Result &&
780 ((Result->isZeroValue() && B == BI->getSuccessor(0)) ||
781 (Result->isOneValue() && B == BI->getSuccessor(1))))
782 UnlikelyBlocks.insert(B);
783 }
784 }
785}
786
Andrew Trick49371f32011-06-04 01:16:30 +0000787// Calculate Edge Weights using "Loop Branch Heuristics". Predict backedges
788// as taken, exiting edges as not-taken.
Mehdi Aminia7978772016-04-07 21:59:28 +0000789bool BranchProbabilityInfo::calcLoopBranchHeuristics(const BasicBlock *BB,
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +0700790 const LoopInfo &LI) {
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700791 LoopBlock LB(BB, LI, *SccI.get());
792 if (!LB.belongsToLoop())
793 return false;
Andrew Trick49371f32011-06-04 01:16:30 +0000794
John Brawn29bbed32018-02-23 17:17:31 +0000795 SmallPtrSet<const BasicBlock*, 8> UnlikelyBlocks;
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700796 if (LB.getLoop())
797 computeUnlikelySuccessors(BB, LB.getLoop(), UnlikelyBlocks);
John Brawn29bbed32018-02-23 17:17:31 +0000798
Manman Rencf104462012-08-24 18:14:27 +0000799 SmallVector<unsigned, 8> BackEdges;
800 SmallVector<unsigned, 8> ExitingEdges;
801 SmallVector<unsigned, 8> InEdges; // Edges from header to the loop.
John Brawn29bbed32018-02-23 17:17:31 +0000802 SmallVector<unsigned, 8> UnlikelyEdges;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000803
Alina Sbirlea3abcbf92020-03-10 11:33:02 -0700804 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Evgeniy Brevnov02a629d2020-07-29 19:19:00 +0700805 LoopBlock SuccLB(*I, LI, *SccI.get());
806 LoopEdge Edge(LB, SuccLB);
807 bool IsUnlikelyEdge =
808 LB.getLoop() && (UnlikelyBlocks.find(*I) != UnlikelyBlocks.end());
809
810 if (IsUnlikelyEdge)
811 UnlikelyEdges.push_back(I.getSuccessorIndex());
812 else if (isLoopExitingEdge(Edge))
813 ExitingEdges.push_back(I.getSuccessorIndex());
814 else if (isLoopBackEdge(Edge))
815 BackEdges.push_back(I.getSuccessorIndex());
816 else {
817 InEdges.push_back(I.getSuccessorIndex());
Geoff Berryeed65312017-11-01 15:16:50 +0000818 }
Andrew Trick49371f32011-06-04 01:16:30 +0000819 }
820
John Brawn29bbed32018-02-23 17:17:31 +0000821 if (BackEdges.empty() && ExitingEdges.empty() && UnlikelyEdges.empty())
Akira Hatanaka5638b892014-04-14 16:56:19 +0000822 return false;
823
Cong Houe93b8e12015-12-22 18:56:14 +0000824 // Collect the sum of probabilities of back-edges/in-edges/exiting-edges, and
825 // normalize them so that they sum up to one.
Cong Houe93b8e12015-12-22 18:56:14 +0000826 unsigned Denom = (BackEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
827 (InEdges.empty() ? 0 : LBH_TAKEN_WEIGHT) +
John Brawn29bbed32018-02-23 17:17:31 +0000828 (UnlikelyEdges.empty() ? 0 : LBH_UNLIKELY_WEIGHT) +
Cong Houe93b8e12015-12-22 18:56:14 +0000829 (ExitingEdges.empty() ? 0 : LBH_NONTAKEN_WEIGHT);
Andrew Trick49371f32011-06-04 01:16:30 +0000830
Yevgeny Rouban81384872020-05-21 11:49:11 +0700831 SmallVector<BranchProbability, 4> EdgeProbabilities(
832 BB->getTerminator()->getNumSuccessors(), BranchProbability::getUnknown());
Cong Houe93b8e12015-12-22 18:56:14 +0000833 if (uint32_t numBackEdges = BackEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000834 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
835 auto Prob = TakenProb / numBackEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000836 for (unsigned SuccIdx : BackEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700837 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000838 }
839
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000840 if (uint32_t numInEdges = InEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000841 BranchProbability TakenProb = BranchProbability(LBH_TAKEN_WEIGHT, Denom);
842 auto Prob = TakenProb / numInEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000843 for (unsigned SuccIdx : InEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700844 EdgeProbabilities[SuccIdx] = Prob;
Jakub Staszakbcb3c652011-07-28 21:33:46 +0000845 }
846
Chandler Carruth32f46e72011-10-25 09:47:41 +0000847 if (uint32_t numExitingEdges = ExitingEdges.size()) {
John Brawn29bbed32018-02-23 17:17:31 +0000848 BranchProbability NotTakenProb = BranchProbability(LBH_NONTAKEN_WEIGHT,
849 Denom);
850 auto Prob = NotTakenProb / numExitingEdges;
Cong Houe93b8e12015-12-22 18:56:14 +0000851 for (unsigned SuccIdx : ExitingEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700852 EdgeProbabilities[SuccIdx] = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +0000853 }
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000854
John Brawn29bbed32018-02-23 17:17:31 +0000855 if (uint32_t numUnlikelyEdges = UnlikelyEdges.size()) {
856 BranchProbability UnlikelyProb = BranchProbability(LBH_UNLIKELY_WEIGHT,
857 Denom);
858 auto Prob = UnlikelyProb / numUnlikelyEdges;
859 for (unsigned SuccIdx : UnlikelyEdges)
Yevgeny Rouban81384872020-05-21 11:49:11 +0700860 EdgeProbabilities[SuccIdx] = Prob;
John Brawn29bbed32018-02-23 17:17:31 +0000861 }
862
Yevgeny Rouban81384872020-05-21 11:49:11 +0700863 setEdgeProbability(BB, EdgeProbabilities);
Jakub Staszakd07b2e12011-07-28 21:45:07 +0000864 return true;
Andrew Trick49371f32011-06-04 01:16:30 +0000865}
866
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200867bool BranchProbabilityInfo::calcZeroHeuristics(const BasicBlock *BB,
John Brawnda4a68a2017-06-08 09:44:40 +0000868 const TargetLibraryInfo *TLI) {
Mehdi Aminia7978772016-04-07 21:59:28 +0000869 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Jakub Staszak17af66a2011-07-31 03:27:24 +0000870 if (!BI || !BI->isConditional())
871 return false;
872
873 Value *Cond = BI->getCondition();
874 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
875 if (!CI)
876 return false;
877
Sam Parker0b53e842019-02-15 11:50:21 +0000878 auto GetConstantInt = [](Value *V) {
879 if (auto *I = dyn_cast<BitCastInst>(V))
880 return dyn_cast<ConstantInt>(I->getOperand(0));
881 return dyn_cast<ConstantInt>(V);
882 };
883
Jakub Staszak17af66a2011-07-31 03:27:24 +0000884 Value *RHS = CI->getOperand(1);
Sam Parker0b53e842019-02-15 11:50:21 +0000885 ConstantInt *CV = GetConstantInt(RHS);
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200886 if (!CV)
887 return false;
Jakub Staszak17af66a2011-07-31 03:27:24 +0000888
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000889 // If the LHS is the result of AND'ing a value with a single bit bitmask,
890 // we don't have information about probabilities.
891 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
892 if (LHS->getOpcode() == Instruction::And)
893 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
Craig Topper4e22ee62017-08-04 16:59:29 +0000894 if (AndRHS->getValue().isPowerOf2())
Daniel Jaspera73f3d52015-04-15 06:24:07 +0000895 return false;
896
John Brawnda4a68a2017-06-08 09:44:40 +0000897 // Check if the LHS is the return value of a library function
898 LibFunc Func = NumLibFuncs;
899 if (TLI)
900 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
901 if (Function *CalledFn = Call->getCalledFunction())
902 TLI->getLibFunc(*CalledFn, Func);
903
Jakub Staszak17af66a2011-07-31 03:27:24 +0000904 bool isProb;
John Brawnda4a68a2017-06-08 09:44:40 +0000905 if (Func == LibFunc_strcasecmp ||
906 Func == LibFunc_strcmp ||
907 Func == LibFunc_strncasecmp ||
908 Func == LibFunc_strncmp ||
Dávid Bolvanskýd68a2852020-08-11 20:42:58 +0200909 Func == LibFunc_memcmp ||
910 Func == LibFunc_bcmp) {
John Brawnda4a68a2017-06-08 09:44:40 +0000911 // strcmp and similar functions return zero, negative, or positive, if the
912 // first string is equal, less, or greater than the second. We consider it
913 // likely that the strings are not equal, so a comparison with zero is
914 // probably false, but also a comparison with any other number is also
915 // probably false given that what exactly is returned for nonzero values is
916 // not specified. Any kind of comparison other than equality we know
917 // nothing about.
918 switch (CI->getPredicate()) {
919 case CmpInst::ICMP_EQ:
920 isProb = false;
921 break;
922 case CmpInst::ICMP_NE:
923 isProb = true;
924 break;
925 default:
926 return false;
927 }
928 } else if (CV->isZero()) {
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000929 switch (CI->getPredicate()) {
930 case CmpInst::ICMP_EQ:
931 // X == 0 -> Unlikely
932 isProb = false;
933 break;
934 case CmpInst::ICMP_NE:
935 // X != 0 -> Likely
936 isProb = true;
937 break;
938 case CmpInst::ICMP_SLT:
939 // X < 0 -> Unlikely
940 isProb = false;
941 break;
942 case CmpInst::ICMP_SGT:
943 // X > 0 -> Likely
944 isProb = true;
945 break;
946 default:
947 return false;
948 }
949 } else if (CV->isOne() && CI->getPredicate() == CmpInst::ICMP_SLT) {
950 // InstCombine canonicalizes X <= 0 into X < 1.
951 // X <= 0 -> Unlikely
Jakub Staszak17af66a2011-07-31 03:27:24 +0000952 isProb = false;
Craig Topper79ab6432017-07-06 18:39:47 +0000953 } else if (CV->isMinusOne()) {
Hal Finkel4d949302013-11-01 10:58:22 +0000954 switch (CI->getPredicate()) {
955 case CmpInst::ICMP_EQ:
956 // X == -1 -> Unlikely
957 isProb = false;
958 break;
959 case CmpInst::ICMP_NE:
960 // X != -1 -> Likely
961 isProb = true;
962 break;
963 case CmpInst::ICMP_SGT:
964 // InstCombine canonicalizes X >= 0 into X > -1.
965 // X >= 0 -> Likely
966 isProb = true;
967 break;
968 default:
969 return false;
970 }
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000971 } else {
Jakub Staszak17af66a2011-07-31 03:27:24 +0000972 return false;
Benjamin Kramer0ca1ad02011-09-04 23:53:04 +0000973 }
Jakub Staszak17af66a2011-07-31 03:27:24 +0000974
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +0200975 BranchProbability TakenProb(ZH_TAKEN_WEIGHT,
976 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
977 BranchProbability UntakenProb(ZH_NONTAKEN_WEIGHT,
978 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
Yevgeny Rouban81384872020-05-21 11:49:11 +0700979 if (!isProb)
980 std::swap(TakenProb, UntakenProb);
981
982 setEdgeProbability(
983 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Jakub Staszak17af66a2011-07-31 03:27:24 +0000984 return true;
985}
986
Mehdi Aminia7978772016-04-07 21:59:28 +0000987bool BranchProbabilityInfo::calcFloatingPointHeuristics(const BasicBlock *BB) {
988 const BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000989 if (!BI || !BI->isConditional())
990 return false;
991
992 Value *Cond = BI->getCondition();
993 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000994 if (!FCmp)
Benjamin Kramer1e731a12011-10-21 20:12:47 +0000995 return false;
996
Guozhi Weib329e072019-09-10 17:25:11 +0000997 uint32_t TakenWeight = FPH_TAKEN_WEIGHT;
998 uint32_t NontakenWeight = FPH_NONTAKEN_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +0000999 bool isProb;
1000 if (FCmp->isEquality()) {
1001 // f1 == f2 -> Unlikely
1002 // f1 != f2 -> Likely
1003 isProb = !FCmp->isTrueWhenEqual();
1004 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
1005 // !isnan -> Likely
1006 isProb = true;
Guozhi Weib329e072019-09-10 17:25:11 +00001007 TakenWeight = FPH_ORD_WEIGHT;
1008 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +00001009 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
1010 // isnan -> Unlikely
1011 isProb = false;
Guozhi Weib329e072019-09-10 17:25:11 +00001012 TakenWeight = FPH_ORD_WEIGHT;
1013 NontakenWeight = FPH_UNO_WEIGHT;
Benjamin Kramer606a50a2011-10-21 21:13:47 +00001014 } else {
1015 return false;
1016 }
1017
Reid Kleckner13707572020-05-13 08:23:09 -07001018 BranchProbability TakenProb(TakenWeight, TakenWeight + NontakenWeight);
Yevgeny Rouban81384872020-05-21 11:49:11 +07001019 BranchProbability UntakenProb(NontakenWeight, TakenWeight + NontakenWeight);
1020 if (!isProb)
1021 std::swap(TakenProb, UntakenProb);
1022
1023 setEdgeProbability(
1024 BB, SmallVector<BranchProbability, 2>({TakenProb, UntakenProb}));
Benjamin Kramer1e731a12011-10-21 20:12:47 +00001025 return true;
1026}
Jakub Staszak17af66a2011-07-31 03:27:24 +00001027
Mehdi Aminia7978772016-04-07 21:59:28 +00001028bool BranchProbabilityInfo::calcInvokeHeuristics(const BasicBlock *BB) {
1029 const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator());
Bill Wendlinge1c54262012-08-15 12:22:35 +00001030 if (!II)
1031 return false;
1032
Cong Houe93b8e12015-12-22 18:56:14 +00001033 BranchProbability TakenProb(IH_TAKEN_WEIGHT,
1034 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
Yevgeny Rouban81384872020-05-21 11:49:11 +07001035 setEdgeProbability(
1036 BB, SmallVector<BranchProbability, 2>({TakenProb, TakenProb.getCompl()}));
Bill Wendlinge1c54262012-08-15 12:22:35 +00001037 return true;
1038}
1039
Pete Cooperb9d2e342015-05-28 19:43:06 +00001040void BranchProbabilityInfo::releaseMemory() {
Cong Houe93b8e12015-12-22 18:56:14 +00001041 Probs.clear();
Kazu Hirataa7b662d2020-10-27 16:14:25 -07001042 MaxSuccIdx.clear();
Nikita Popovfe8abbf2020-04-07 21:21:30 +02001043 Handles.clear();
Pete Cooperb9d2e342015-05-28 19:43:06 +00001044}
1045
Alina Sbirlea62a50a92020-01-15 14:02:33 -08001046bool BranchProbabilityInfo::invalidate(Function &, const PreservedAnalyses &PA,
1047 FunctionAnalysisManager::Invalidator &) {
1048 // Check whether the analysis, all analyses on functions, or the function's
1049 // CFG have been preserved.
1050 auto PAC = PA.getChecker<BranchProbabilityAnalysis>();
1051 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1052 PAC.preservedSet<CFGAnalyses>());
1053}
1054
Cong Houab23bfb2015-07-15 22:48:29 +00001055void BranchProbabilityInfo::print(raw_ostream &OS) const {
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001056 OS << "---- Branch Probabilities ----\n";
1057 // We print the probabilities from the last function the analysis ran over,
1058 // or the function it is currently running over.
1059 assert(LastF && "Cannot print prior to running over a function");
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001060 for (const auto &BI : *LastF) {
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001061 for (const_succ_iterator SI = succ_begin(&BI), SE = succ_end(&BI); SI != SE;
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +00001062 ++SI) {
1063 printEdgeProbability(OS << " ", &BI, *SI);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001064 }
1065 }
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001066}
1067
Jakub Staszakefd94c82011-07-29 19:30:00 +00001068bool BranchProbabilityInfo::
1069isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
Andrew Trick3d4e64b2011-06-11 01:05:22 +00001070 // Hot probability is at least 4/5 = 80%
Benjamin Kramer929f53f2011-10-23 11:19:14 +00001071 // FIXME: Compare against a static "hot" BranchProbability.
1072 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
Andrew Trick49371f32011-06-04 01:16:30 +00001073}
1074
Mehdi Aminia7978772016-04-07 21:59:28 +00001075const BasicBlock *
1076BranchProbabilityInfo::getHotSucc(const BasicBlock *BB) const {
Cong Houe93b8e12015-12-22 18:56:14 +00001077 auto MaxProb = BranchProbability::getZero();
Mehdi Aminia7978772016-04-07 21:59:28 +00001078 const BasicBlock *MaxSucc = nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +00001079
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001080 for (const_succ_iterator I = succ_begin(BB), E = succ_end(BB); I != E; ++I) {
Mehdi Aminia7978772016-04-07 21:59:28 +00001081 const BasicBlock *Succ = *I;
Cong Houe93b8e12015-12-22 18:56:14 +00001082 auto Prob = getEdgeProbability(BB, Succ);
1083 if (Prob > MaxProb) {
1084 MaxProb = Prob;
Andrew Trick49371f32011-06-04 01:16:30 +00001085 MaxSucc = Succ;
1086 }
1087 }
1088
Benjamin Kramer929f53f2011-10-23 11:19:14 +00001089 // Hot probability is at least 4/5 = 80%
Cong Houe93b8e12015-12-22 18:56:14 +00001090 if (MaxProb > BranchProbability(4, 5))
Andrew Trick49371f32011-06-04 01:16:30 +00001091 return MaxSucc;
1092
Craig Topper9f008862014-04-15 04:59:12 +00001093 return nullptr;
Andrew Trick49371f32011-06-04 01:16:30 +00001094}
1095
Cong Houe93b8e12015-12-22 18:56:14 +00001096/// Get the raw edge probability for the edge. If can't find it, return a
1097/// default probability 1/N where N is the number of successors. Here an edge is
1098/// specified using PredBlock and an
1099/// index to the successors.
1100BranchProbability
1101BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
1102 unsigned IndexInSuccessors) const {
1103 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
Andrew Trick49371f32011-06-04 01:16:30 +00001104
Cong Houe93b8e12015-12-22 18:56:14 +00001105 if (I != Probs.end())
Andrew Trick49371f32011-06-04 01:16:30 +00001106 return I->second;
1107
Vedant Kumare0b5f862018-05-10 23:01:54 +00001108 return {1, static_cast<uint32_t>(succ_size(Src))};
Andrew Trick49371f32011-06-04 01:16:30 +00001109}
1110
Cong Houd97c1002015-12-01 05:29:22 +00001111BranchProbability
1112BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001113 const_succ_iterator Dst) const {
Cong Houd97c1002015-12-01 05:29:22 +00001114 return getEdgeProbability(Src, Dst.getSuccessorIndex());
1115}
1116
Cong Houe93b8e12015-12-22 18:56:14 +00001117/// Get the raw edge probability calculated for the block pair. This returns the
1118/// sum of all raw edge probabilities from Src to Dst.
1119BranchProbability
1120BranchProbabilityInfo::getEdgeProbability(const BasicBlock *Src,
1121 const BasicBlock *Dst) const {
1122 auto Prob = BranchProbability::getZero();
1123 bool FoundProb = false;
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001124 uint32_t EdgeCount = 0;
Alina Sbirlea3abcbf92020-03-10 11:33:02 -07001125 for (const_succ_iterator I = succ_begin(Src), E = succ_end(Src); I != E; ++I)
Cong Houe93b8e12015-12-22 18:56:14 +00001126 if (*I == Dst) {
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001127 ++EdgeCount;
Cong Houe93b8e12015-12-22 18:56:14 +00001128 auto MapI = Probs.find(std::make_pair(Src, I.getSuccessorIndex()));
1129 if (MapI != Probs.end()) {
1130 FoundProb = true;
1131 Prob += MapI->second;
1132 }
1133 }
1134 uint32_t succ_num = std::distance(succ_begin(Src), succ_end(Src));
Evgeniy Brevnovbb0842a2020-04-29 14:08:01 +07001135 return FoundProb ? Prob : BranchProbability(EdgeCount, succ_num);
Cong Houe93b8e12015-12-22 18:56:14 +00001136}
1137
1138/// Set the edge probability for a given edge specified by PredBlock and an
1139/// index to the successors.
1140void BranchProbabilityInfo::setEdgeProbability(const BasicBlock *Src,
1141 unsigned IndexInSuccessors,
1142 BranchProbability Prob) {
1143 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001144 Handles.insert(BasicBlockCallbackVH(Src, this));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001145 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> "
1146 << IndexInSuccessors << " successor probability to " << Prob
1147 << "\n");
Kazu Hirataa7b662d2020-10-27 16:14:25 -07001148
Fangrui Songd69ada32020-10-27 16:29:10 -07001149 unsigned &SuccIdx = MaxSuccIdx[Src];
1150 SuccIdx = std::max(SuccIdx, IndexInSuccessors);
Cong Houe93b8e12015-12-22 18:56:14 +00001151}
1152
Yevgeny Rouban81384872020-05-21 11:49:11 +07001153/// Set the edge probability for all edges at once.
1154void BranchProbabilityInfo::setEdgeProbability(
1155 const BasicBlock *Src, const SmallVectorImpl<BranchProbability> &Probs) {
1156 assert(Src->getTerminator()->getNumSuccessors() == Probs.size());
1157 if (Probs.size() == 0)
1158 return; // Nothing to set.
1159
1160 uint64_t TotalNumerator = 0;
1161 for (unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) {
1162 setEdgeProbability(Src, SuccIdx, Probs[SuccIdx]);
1163 TotalNumerator += Probs[SuccIdx].getNumerator();
1164 }
1165
1166 // Because of rounding errors the total probability cannot be checked to be
1167 // 1.0 exactly. That is TotalNumerator == BranchProbability::getDenominator.
1168 // Instead, every single probability in Probs must be as accurate as possible.
1169 // This results in error 1/denominator at most, thus the total absolute error
1170 // should be within Probs.size / BranchProbability::getDenominator.
1171 assert(TotalNumerator <= BranchProbability::getDenominator() + Probs.size());
1172 assert(TotalNumerator >= BranchProbability::getDenominator() - Probs.size());
1173}
1174
Andrew Trick49371f32011-06-04 01:16:30 +00001175raw_ostream &
Chandler Carruth1c8ace02011-10-23 21:21:50 +00001176BranchProbabilityInfo::printEdgeProbability(raw_ostream &OS,
1177 const BasicBlock *Src,
1178 const BasicBlock *Dst) const {
Jakub Staszak12a43bd2011-06-16 20:22:37 +00001179 const BranchProbability Prob = getEdgeProbability(Src, Dst);
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +00001180 OS << "edge " << Src->getName() << " -> " << Dst->getName()
Andrew Trick3d4e64b2011-06-11 01:05:22 +00001181 << " probability is " << Prob
1182 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
Andrew Trick49371f32011-06-04 01:16:30 +00001183
1184 return OS;
1185}
Cong Houab23bfb2015-07-15 22:48:29 +00001186
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001187void BranchProbabilityInfo::eraseBlock(const BasicBlock *BB) {
Fangrui Songd69ada32020-10-27 16:29:10 -07001188 // Note that we cannot use successors of BB because the terminator of BB may
1189 // have changed when eraseBlock is called as a BasicBlockCallbackVH callback.
Kazu Hirataa7b662d2020-10-27 16:14:25 -07001190 auto It = MaxSuccIdx.find(BB);
1191 if (It == MaxSuccIdx.end())
1192 return;
1193
1194 for (unsigned I = 0, E = It->second; I <= E; ++I) {
1195 auto MapI = Probs.find(std::make_pair(BB, I));
Teresa Johnson3e5173d2020-07-10 15:25:27 -07001196 if (MapI != Probs.end())
1197 Probs.erase(MapI);
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001198 }
Kazu Hirataa7b662d2020-10-27 16:14:25 -07001199 MaxSuccIdx.erase(BB);
Igor Laevskyee40d1e2016-07-15 14:31:16 +00001200}
1201
John Brawnda4a68a2017-06-08 09:44:40 +00001202void BranchProbabilityInfo::calculate(const Function &F, const LoopInfo &LI,
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001203 const TargetLibraryInfo *TLI,
1204 PostDominatorTree *PDT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001205 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
1206 << " ----\n\n");
Cong Houab23bfb2015-07-15 22:48:29 +00001207 LastF = &F; // Store the last function we ran on for printing.
1208 assert(PostDominatedByUnreachable.empty());
1209 assert(PostDominatedByColdCall.empty());
1210
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +07001211 SccI = std::make_unique<SccInfo>(F);
Geoff Berryeed65312017-11-01 15:16:50 +00001212
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001213 std::unique_ptr<PostDominatorTree> PDTPtr;
1214
1215 if (!PDT) {
1216 PDTPtr = std::make_unique<PostDominatorTree>(const_cast<Function &>(F));
1217 PDT = PDTPtr.get();
1218 }
1219
1220 computePostDominatedByUnreachable(F, PDT);
1221 computePostDominatedByColdCall(F, PDT);
Taewook Oh2da205d2019-12-02 10:15:22 -08001222
Cong Houab23bfb2015-07-15 22:48:29 +00001223 // Walk the basic blocks in post-order so that we can build up state about
1224 // the successors of a block iteratively.
1225 for (auto BB : post_order(&F.getEntryBlock())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001226 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
1227 << "\n");
Serguei Katkov11d9c4f2017-04-17 06:39:47 +00001228 // If there is no at least two successors, no sense to set probability.
1229 if (BB->getTerminator()->getNumSuccessors() < 2)
1230 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001231 if (calcMetadataWeights(BB))
1232 continue;
Artur Pilipenko4d063e72018-06-08 13:03:21 +00001233 if (calcInvokeHeuristics(BB))
1234 continue;
Serguei Katkov2616bbb2017-04-17 04:33:04 +00001235 if (calcUnreachableHeuristics(BB))
1236 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001237 if (calcColdCallHeuristics(BB))
1238 continue;
Evgeniy Brevnov3a2b05f2020-07-24 18:57:10 +07001239 if (calcLoopBranchHeuristics(BB, LI))
Cong Houab23bfb2015-07-15 22:48:29 +00001240 continue;
1241 if (calcPointerHeuristics(BB))
1242 continue;
Dávid Bolvanský0f14b2e2020-08-17 20:42:57 +02001243 if (calcZeroHeuristics(BB, TLI))
Cong Houab23bfb2015-07-15 22:48:29 +00001244 continue;
1245 if (calcFloatingPointHeuristics(BB))
1246 continue;
Cong Houab23bfb2015-07-15 22:48:29 +00001247 }
1248
1249 PostDominatedByUnreachable.clear();
1250 PostDominatedByColdCall.clear();
Evgeniy Brevnov412b3932020-07-28 19:50:40 +07001251 SccI.reset();
Hiroshi Yamauchi63e17eb2017-08-26 00:31:00 +00001252
1253 if (PrintBranchProb &&
1254 (PrintBranchProbFuncName.empty() ||
1255 F.getName().equals(PrintBranchProbFuncName))) {
1256 print(dbgs());
1257 }
Cong Houab23bfb2015-07-15 22:48:29 +00001258}
1259
1260void BranchProbabilityInfoWrapperPass::getAnalysisUsage(
1261 AnalysisUsage &AU) const {
Mikael Holmen2ca16892018-05-17 09:05:40 +00001262 // We require DT so it's available when LI is available. The LI updating code
1263 // asserts that DT is also present so if we don't make sure that we have DT
1264 // here, that assert will trigger.
1265 AU.addRequired<DominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001266 AU.addRequired<LoopInfoWrapperPass>();
John Brawnda4a68a2017-06-08 09:44:40 +00001267 AU.addRequired<TargetLibraryInfoWrapperPass>();
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001268 AU.addRequired<PostDominatorTreeWrapperPass>();
Cong Houab23bfb2015-07-15 22:48:29 +00001269 AU.setPreservesAll();
1270}
1271
1272bool BranchProbabilityInfoWrapperPass::runOnFunction(Function &F) {
1273 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnson9c27b592019-09-07 03:09:36 +00001274 const TargetLibraryInfo &TLI =
1275 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001276 PostDominatorTree &PDT =
1277 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1278 BPI.calculate(F, LI, &TLI, &PDT);
Cong Houab23bfb2015-07-15 22:48:29 +00001279 return false;
1280}
1281
1282void BranchProbabilityInfoWrapperPass::releaseMemory() { BPI.releaseMemory(); }
1283
1284void BranchProbabilityInfoWrapperPass::print(raw_ostream &OS,
1285 const Module *) const {
1286 BPI.print(OS);
1287}
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001288
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001289AnalysisKey BranchProbabilityAnalysis::Key;
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001290BranchProbabilityInfo
Sean Silva36e0d012016-08-09 00:28:15 +00001291BranchProbabilityAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001292 BranchProbabilityInfo BPI;
Evgeniy Brevnov3e68a6672020-04-28 16:31:20 +07001293 BPI.calculate(F, AM.getResult<LoopAnalysis>(F),
1294 &AM.getResult<TargetLibraryAnalysis>(F),
1295 &AM.getResult<PostDominatorTreeAnalysis>(F));
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001296 return BPI;
1297}
1298
1299PreservedAnalyses
Sean Silva36e0d012016-08-09 00:28:15 +00001300BranchProbabilityPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
Xinliang David Li6e5dd412016-05-05 02:59:57 +00001301 OS << "Printing analysis results of BPI for function "
1302 << "'" << F.getName() << "':"
1303 << "\n";
1304 AM.getResult<BranchProbabilityAnalysis>(F).print(OS);
1305 return PreservedAnalyses::all();
1306}