LLVM 24.0.0git
BranchProbabilityInfo.cpp
Go to the documentation of this file.
1//===- BranchProbabilityInfo.cpp - Branch Probability Analysis ------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
14#include "AnalysisOptions.h"
16#include "llvm/ADT/STLExtras.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Metadata.h"
34#include "llvm/IR/PassManager.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/Value.h"
39#include "llvm/Pass.h"
42#include "llvm/Support/Debug.h"
44#include <cassert>
45#include <cstdint>
46#include <utility>
47
48using namespace llvm;
49
50#define DEBUG_TYPE "branch-prob"
51
53 "Branch Probability Analysis", false, true)
59 "Branch Probability Analysis", false, true)
60
63
65
66// 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;
88
89/// Unreachable-terminating branch taken probability.
90///
91/// This is the probability for a branch being taken to a block that terminates
92/// (eventually) in unreachable. These are predicted as unlikely as possible.
93/// All reachable probability will proportionally share the remaining part.
95
96/// Heuristics and lookup tables for non-loop branches:
97/// Pointer Heuristics (PH)
98static const uint32_t PH_TAKEN_WEIGHT = 20;
99static const uint32_t PH_NONTAKEN_WEIGHT = 12;
100static constexpr BranchProbability
102static constexpr BranchProbability
104
105/// Zero Heuristics (ZH)
106static const uint32_t ZH_TAKEN_WEIGHT = 20;
107static const uint32_t ZH_NONTAKEN_WEIGHT = 12;
108static constexpr BranchProbability
110static constexpr BranchProbability
112
113// Floating-Point Heuristics (FPH)
114static const uint32_t FPH_TAKEN_WEIGHT = 20;
116
117/// This is the probability for an ordered floating point comparison.
118static const uint32_t FPH_ORD_WEIGHT = 1024 * 1024 - 1;
119/// This is the probability for an unordered floating point comparison, it means
120/// one or two of the operands are NaN. Usually it is used to test for an
121/// exceptional case, so the result is unlikely.
122static const uint32_t FPH_UNO_WEIGHT = 1;
123
124static constexpr BranchProbability
126static constexpr BranchProbability
128static constexpr BranchProbability
130static constexpr BranchProbability
132
133/// Set of dedicated "absolute" execution weights for a block. These weights are
134/// meaningful relative to each other and their derivatives only.
135enum class BlockExecWeight : std::uint32_t {
136 /// Special weight used for cases with exact zero probability.
137 ZERO = 0x0,
138 /// Minimal possible non zero weight.
140 /// Weight to an 'unreachable' block.
142 /// Weight to a block containing non returning call.
144 /// Weight to 'unwind' block of an invoke instruction.
146 /// Weight to a 'cold' block. Cold blocks are the ones containing calls marked
147 /// with attribute 'cold'.
148 COLD = 0xffff,
149 /// Default weight is used in cases when there is no dedicated execution
150 /// weight set. It is not propagated through the domination line either.
151 DEFAULT = 0xfffff
152};
153
154namespace {
155class BPIConstruction {
156public:
157 BPIConstruction(BranchProbabilityInfo &BPI) : BPI(BPI) {}
158 void calculate(const Function &F, const CycleInfo &CI,
159 const TargetLibraryInfo *TLI, DominatorTree *DT,
160 PostDominatorTree *PDT);
161
162private:
163 // Pair representing an edge from first to second block.
164 using LoopEdge = std::pair<const BasicBlock *, const BasicBlock *>;
165
166 /// Returns true if destination block belongs to some loop and source block is
167 /// either doesn't belong to any loop or belongs to a loop which is not inner
168 /// relative to the destination block.
169 bool isLoopEnteringEdge(const LoopEdge &Edge) const;
170 /// Returns true if source block belongs to some loop and destination block is
171 /// either doesn't belong to any loop or belongs to a loop which is not inner
172 /// relative to the source block.
173 bool isLoopExitingEdge(const LoopEdge &Edge) const;
174 /// Returns true if \p Edge is either enters to or exits from some loop, false
175 /// in all other cases.
176 bool isLoopEnteringExitingEdge(const LoopEdge &Edge) const;
177 // Fills in \p Enters vector with all "enter" blocks to a loop \LB belongs to.
178 void getLoopEnterBlocks(const BasicBlock *LB,
179 SmallVectorImpl<const BasicBlock *> &Enters) const;
180
181 /// Returns estimated weight for \p BB. std::nullopt if \p BB has no estimated
182 /// weight.
183 std::optional<uint32_t> getEstimatedBlockWeight(const BasicBlock *BB) const;
184
185 /// Returns estimated weight to enter \p L. In other words it is weight of
186 /// loop's header block not scaled by trip count. Returns std::nullopt if \p C
187 /// has no no estimated weight.
188 std::optional<uint32_t> getEstimatedLoopWeight(CycleRef C) const;
189
190 /// Return estimated weight for \p Edge. Returns std::nullopt if estimated
191 /// weight is unknown.
192 std::optional<uint32_t> getEstimatedEdgeWeight(const LoopEdge &Edge) const;
193
194 /// Iterates over all edges leading from \p SrcBB to \p Successors and
195 /// returns maximum of all estimated weights. If at least one edge has unknown
196 /// estimated weight std::nullopt is returned.
197 template <class IterT>
198 std::optional<uint32_t>
199 getMaxEstimatedEdgeWeight(const BasicBlock *SrcBB,
200 iterator_range<IterT> Successors) const;
201
202 /// If \p LoopBB has no estimated weight then set it to \p BBWeight and
203 /// return true. Otherwise \p BB's weight remains unchanged and false is
204 /// returned. In addition all blocks/loops that might need their weight to be
205 /// re-estimated are put into BlockWorkList/LoopWorkList.
206 bool
207 updateEstimatedBlockWeight(const BasicBlock *BB, uint32_t BBWeight,
208 SmallVectorImpl<const BasicBlock *> &BlockWorkList,
209 SmallVectorImpl<const BasicBlock *> &LoopWorkList);
210
211 /// Starting from \p LoopBB (including \p LoopBB itself) propagate \p BBWeight
212 /// up the domination tree.
213 void propagateEstimatedBlockWeight(
214 const BasicBlock *BB, DominatorTree *DT, PostDominatorTree *PDT,
215 uint32_t BBWeight, SmallVectorImpl<const BasicBlock *> &WorkList,
216 SmallVectorImpl<const BasicBlock *> &LoopWorkList);
217
218 /// Returns block's weight encoded in the IR.
219 std::optional<uint32_t> getInitialEstimatedBlockWeight(const BasicBlock *BB);
220
221 // Computes estimated weights for all blocks in \p F.
222 void estimateBlockWeights(const Function &F, DominatorTree *DT,
223 PostDominatorTree *PDT);
224
225 /// Based on computed weights by \p computeEstimatedBlockWeight set
226 /// probabilities on branches.
227 bool calcEstimatedHeuristics(const BasicBlock *BB);
228 bool calcMetadataWeights(const BasicBlock *BB);
229 bool calcPointerHeuristics(const BasicBlock *BB);
230 bool calcZeroHeuristics(const BasicBlock *BB, const TargetLibraryInfo *TLI);
231 bool calcFloatingPointHeuristics(const BasicBlock *BB);
232
233 BranchProbabilityInfo &BPI;
234
235 const CycleInfo *CI = nullptr;
236
237 /// Keeps mapping of a basic block to its estimated weight.
238 SmallDenseMap<const BasicBlock *, uint32_t> EstimatedBlockWeight;
239
240 /// Keeps mapping of a loop to estimated weight to enter the loop.
241 SmallDenseMap<CycleRef, uint32_t> EstimatedLoopWeight;
242};
243
244bool BPIConstruction::isLoopEnteringEdge(const LoopEdge &Edge) const {
245 CycleRef SrcCycle = CI->getCycle(Edge.first);
246 CycleRef DstCycle = CI->getCycle(Edge.second);
247 if (!DstCycle) // Edge into no-cycle is not entering.
248 return false;
249 if (!SrcCycle) // Edge from no-cycle into cycle is entering.
250 return true;
251 return !CI->contains(DstCycle, SrcCycle);
252}
253
254bool BPIConstruction::isLoopExitingEdge(const LoopEdge &Edge) const {
255 return isLoopEnteringEdge({Edge.second, Edge.first});
256}
257
258bool BPIConstruction::isLoopEnteringExitingEdge(const LoopEdge &Edge) const {
259 return isLoopEnteringEdge(Edge) || isLoopExitingEdge(Edge);
260}
261
262void BPIConstruction::getLoopEnterBlocks(
263 const BasicBlock *BB, SmallVectorImpl<const BasicBlock *> &Enters) const {
264 CycleRef C = CI->getCycle(BB);
265 for (BasicBlock *Entry : CI->getEntries(C))
266 for (const auto *Pred : predecessors(Entry))
267 if (!CI->contains(C, Pred))
268 Enters.push_back(Pred);
269}
270
271// Propagate existing explicit probabilities from either profile data or
272// 'expect' intrinsic processing. Examine metadata against unreachable
273// heuristic. The probability of the edge coming to unreachable block is
274// set to min of metadata and unreachable heuristic.
275bool BPIConstruction::calcMetadataWeights(const BasicBlock *BB) {
276 const Instruction *TI = BB->getTerminator();
277 assert(TI->getNumSuccessors() > 1 && "expected more than one successor!");
278 if (!(isa<CondBrInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI) ||
280 return false;
281
282 MDNode *WeightsNode = getValidBranchWeightMDNode(*TI);
283 if (!WeightsNode)
284 return false;
285
286 // Check that the number of successors is manageable.
287 assert(TI->getNumSuccessors() < UINT32_MAX && "Too many successors");
288
290 SmallVector<unsigned, 2> UnreachableIdxs;
291 SmallVector<unsigned, 2> ReachableIdxs;
292
293 extractBranchWeights(WeightsNode, Weights);
294 auto Succs = succ_begin(TI);
295 for (unsigned I = 0, E = Weights.size(); I != E; ++I) {
296 auto EstimatedWeight = getEstimatedEdgeWeight({BB, *Succs++});
297 if (EstimatedWeight &&
298 *EstimatedWeight <= static_cast<uint32_t>(BlockExecWeight::UNREACHABLE))
299 UnreachableIdxs.push_back(I);
300 else
301 ReachableIdxs.push_back(I);
302 }
303 assert(Weights.size() == TI->getNumSuccessors() && "Checked above");
304
305 // If all successors are unreachable, all edges are equally likely.
306 if (ReachableIdxs.empty())
307 fill(Weights, 1);
308
309 // Set the probability.
312
313 // Examine the metadata against unreachable heuristic.
314 // If the unreachable heuristic is more strong then we use it for this edge.
315 if (UnreachableIdxs.size() == 0 || ReachableIdxs.size() == 0) {
316 BPI.setEdgeProbability(BB, BP);
317 return true;
318 }
319
320 auto UnreachableProb = UR_TAKEN_PROB;
321 for (auto I : UnreachableIdxs)
322 if (UnreachableProb < BP[I]) {
323 BP[I] = UnreachableProb;
324 }
325
326 // Sum of all edge probabilities must be 1.0. If we modified the probability
327 // of some edges then we must distribute the introduced difference over the
328 // reachable blocks.
329 //
330 // Proportional distribution: the relation between probabilities of the
331 // reachable edges is kept unchanged. That is for any reachable edges i and j:
332 // newBP[i] / newBP[j] == oldBP[i] / oldBP[j] =>
333 // newBP[i] / oldBP[i] == newBP[j] / oldBP[j] == K
334 // Where K is independent of i,j.
335 // newBP[i] == oldBP[i] * K
336 // We need to find K.
337 // Make sum of all reachables of the left and right parts:
338 // sum_of_reachable(newBP) == K * sum_of_reachable(oldBP)
339 // Sum of newBP must be equal to 1.0:
340 // sum_of_reachable(newBP) + sum_of_unreachable(newBP) == 1.0 =>
341 // sum_of_reachable(newBP) = 1.0 - sum_of_unreachable(newBP)
342 // Where sum_of_unreachable(newBP) is what has been just changed.
343 // Finally:
344 // K == sum_of_reachable(newBP) / sum_of_reachable(oldBP) =>
345 // K == (1.0 - sum_of_unreachable(newBP)) / sum_of_reachable(oldBP)
346 BranchProbability NewUnreachableSum = BranchProbability::getZero();
347 for (auto I : UnreachableIdxs)
348 NewUnreachableSum += BP[I];
349
350 BranchProbability NewReachableSum =
351 BranchProbability::getOne() - NewUnreachableSum;
352
353 BranchProbability OldReachableSum = BranchProbability::getZero();
354 for (auto I : ReachableIdxs)
355 OldReachableSum += BP[I];
356
357 if (OldReachableSum != NewReachableSum) { // Anything to dsitribute?
358 if (OldReachableSum.isZero()) {
359 // If all oldBP[i] are zeroes then the proportional distribution results
360 // in all zero probabilities and the error stays big. In this case we
361 // evenly spread NewReachableSum over the reachable edges.
362 BranchProbability PerEdge = NewReachableSum / ReachableIdxs.size();
363 for (auto I : ReachableIdxs)
364 BP[I] = PerEdge;
365 } else {
366 for (auto I : ReachableIdxs) {
367 // We use uint64_t to avoid double rounding error of the following
368 // calculation: BP[i] = BP[i] * NewReachableSum / OldReachableSum
369 // The formula is taken from the private constructor
370 // BranchProbability(uint32_t Numerator, uint32_t Denominator)
371 uint64_t Mul = static_cast<uint64_t>(NewReachableSum.getNumerator()) *
372 BP[I].getNumerator();
373 uint32_t Div = static_cast<uint32_t>(
374 divideNearest(Mul, OldReachableSum.getNumerator()));
376 }
377 }
378 }
379
380 BPI.setEdgeProbability(BB, BP);
381
382 return true;
383}
384
385// Calculate Edge Weights using "Pointer Heuristics". Predict a comparison
386// between two pointer or pointer and NULL will fail.
387bool BPIConstruction::calcPointerHeuristics(const BasicBlock *BB) {
388 const CondBrInst *BI = dyn_cast<CondBrInst>(BB->getTerminator());
389 if (!BI)
390 return false;
391
392 Value *Cond = BI->getCondition();
393 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
394 if (!CI || !CI->isEquality())
395 return false;
396
397 Value *LHS = CI->getOperand(0);
398
399 if (!LHS->getType()->isPointerTy())
400 return false;
401
402 assert(CI->getOperand(1)->getType()->isPointerTy());
403
404 switch (CI->getPredicate()) {
405 case ICmpInst::ICMP_NE: // p != q -> Likely
407 return true;
408 case ICmpInst::ICMP_EQ: // p == q -> Unlikely
410 return true;
411 default:
412 return false;
413 }
414}
415
416// Compute the unlikely successors to the block BB in the cycle C, specifically
417// those that are unlikely because this is a loop, and add them to the
418// UnlikelyBlocks set.
419static void
420computeUnlikelySuccessors(const BasicBlock *BB, const CycleInfo &CI, CycleRef C,
421 SmallPtrSetImpl<const BasicBlock *> &UnlikelyBlocks) {
422 // Sometimes in a loop we have a branch whose condition is made false by
423 // taking it. This is typically something like
424 // int n = 0;
425 // while (...) {
426 // if (++n >= MAX) {
427 // n = 0;
428 // }
429 // }
430 // In this sort of situation taking the branch means that at the very least it
431 // won't be taken again in the next iteration of the loop, so we should
432 // consider it less likely than a typical branch.
433 //
434 // We detect this by looking back through the graph of PHI nodes that sets the
435 // value that the condition depends on, and seeing if we can reach a successor
436 // block which can be determined to make the condition false.
437 //
438 // FIXME: We currently consider unlikely blocks to be half as likely as other
439 // blocks, but if we consider the example above the likelyhood is actually
440 // 1/MAX. We could therefore be more precise in how unlikely we consider
441 // blocks to be, but it would require more careful examination of the form
442 // of the comparison expression.
443 const CondBrInst *BI = dyn_cast<CondBrInst>(BB->getTerminator());
444 if (!BI)
445 return;
446
447 // Check if the branch is based on an instruction compared with a constant
448 CmpInst *Cmp = dyn_cast<CmpInst>(BI->getCondition());
449 if (!Cmp || !isa<Instruction>(Cmp->getOperand(0)) ||
450 !isa<Constant>(Cmp->getOperand(1)))
451 return;
452
453 // Either the instruction must be a PHI, or a chain of operations involving
454 // constants that ends in a PHI which we can then collapse into a single value
455 // if the PHI value is known.
456 Instruction *CmpLHS = dyn_cast<Instruction>(Cmp->getOperand(0));
457 PHINode *CmpPHI = dyn_cast<PHINode>(CmpLHS);
458 Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1));
459 // Collect the instructions until we hit a PHI
461 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
462 isa<Constant>(CmpLHS->getOperand(1))) {
463 // Stop if the chain extends outside of the loop
464 if (!CI.contains(C, CmpLHS->getParent()))
465 return;
466 InstChain.push_back(cast<BinaryOperator>(CmpLHS));
467 CmpLHS = dyn_cast<Instruction>(CmpLHS->getOperand(0));
468 if (CmpLHS)
469 CmpPHI = dyn_cast<PHINode>(CmpLHS);
470 }
471 if (!CmpPHI || !CI.contains(C, CmpPHI->getParent()))
472 return;
473
474 // Trace the phi node to find all values that come from successors of BB
475 SmallPtrSet<PHINode*, 8> VisitedInsts;
477 WorkList.push_back(CmpPHI);
478 VisitedInsts.insert(CmpPHI);
479 while (!WorkList.empty()) {
480 PHINode *P = WorkList.pop_back_val();
481 for (BasicBlock *B : P->blocks()) {
482 // Skip blocks that aren't part of the loop
483 if (!CI.contains(C, B))
484 continue;
485 Value *V = P->getIncomingValueForBlock(B);
486 // If the source is a PHI add it to the work list if we haven't
487 // already visited it.
488 if (PHINode *PN = dyn_cast<PHINode>(V)) {
489 if (VisitedInsts.insert(PN).second)
490 WorkList.push_back(PN);
491 continue;
492 }
493 // If this incoming value is a constant and B is a successor of BB, then
494 // we can constant-evaluate the compare to see if it makes the branch be
495 // taken or not.
496 Constant *CmpLHSConst = dyn_cast<Constant>(V);
497 if (!CmpLHSConst || !llvm::is_contained(successors(BB), B))
498 continue;
499 // First collapse InstChain
500 // Pass the Instruction when folding to access the denormal_fpenv.
501 const DataLayout &DL = BB->getDataLayout();
502 for (Instruction *I : llvm::reverse(InstChain)) {
503 CmpLHSConst = ConstantFoldInstOperands(
504 I, {CmpLHSConst, cast<Constant>(I->getOperand(1))}, DL);
505 if (!CmpLHSConst)
506 break;
507 }
508 if (!CmpLHSConst)
509 continue;
510 // Now constant-evaluate the compare
512 ConstantFoldInstOperands(Cmp, {CmpLHSConst, CmpConst}, DL);
513 // If the result means we don't branch to the block then that block is
514 // unlikely.
515 if (Result && ((Result->isNullValue() && B == BI->getSuccessor(0)) ||
516 (Result->isOneValue() && B == BI->getSuccessor(1))))
517 UnlikelyBlocks.insert(B);
518 }
519 }
520}
521
522std::optional<uint32_t>
523BPIConstruction::getEstimatedBlockWeight(const BasicBlock *BB) const {
524 auto WeightIt = EstimatedBlockWeight.find(BB);
525 if (WeightIt == EstimatedBlockWeight.end())
526 return std::nullopt;
527 return WeightIt->second;
528}
529
530std::optional<uint32_t>
531BPIConstruction::getEstimatedLoopWeight(CycleRef C) const {
532 auto WeightIt = EstimatedLoopWeight.find(C);
533 if (WeightIt == EstimatedLoopWeight.end())
534 return std::nullopt;
535 return WeightIt->second;
536}
537
538std::optional<uint32_t>
539BPIConstruction::getEstimatedEdgeWeight(const LoopEdge &Edge) const {
540 // For edges entering a loop take weight of a loop rather than an individual
541 // block in the loop.
542 return isLoopEnteringEdge(Edge)
543 ? getEstimatedLoopWeight(CI->getCycle(Edge.second))
544 : getEstimatedBlockWeight(Edge.second);
545}
546
547template <class IterT>
548std::optional<uint32_t> BPIConstruction::getMaxEstimatedEdgeWeight(
549 const BasicBlock *SrcBB, iterator_range<IterT> Successors) const {
550 std::optional<uint32_t> MaxWeight;
551 for (const BasicBlock *DstBB : Successors) {
552 auto Weight = getEstimatedEdgeWeight({SrcBB, DstBB});
553 if (!Weight)
554 return std::nullopt;
555 if (!MaxWeight || *MaxWeight < *Weight)
556 MaxWeight = Weight;
557 }
558
559 return MaxWeight;
560}
561
562// Updates \p LoopBB's weight and returns true. If \p LoopBB has already
563// an associated weight it is unchanged and false is returned.
564//
565// Please note by the algorithm the weight is not expected to change once set
566// thus 'false' status is used to track visited blocks.
567bool BPIConstruction::updateEstimatedBlockWeight(
568 const BasicBlock *BB, uint32_t BBWeight,
569 SmallVectorImpl<const BasicBlock *> &BlockWorkList,
570 SmallVectorImpl<const BasicBlock *> &LoopWorkList) {
571 // In general, weight is assigned to a block when it has final value and
572 // can't/shouldn't be changed. However, there are cases when a block
573 // inherently has several (possibly "contradicting") weights. For example,
574 // "unwind" block may also contain "cold" call. In that case the first
575 // set weight is favored and all consequent weights are ignored.
576 if (!EstimatedBlockWeight.insert({BB, BBWeight}).second)
577 return false;
578
579 for (const BasicBlock *PredBlock : predecessors(BB)) {
580 // Add affected block/loop to a working list.
581 if (isLoopExitingEdge({PredBlock, BB})) {
582 if (!EstimatedLoopWeight.count(CI->getCycle(PredBlock)))
583 LoopWorkList.push_back(PredBlock);
584 } else if (!EstimatedBlockWeight.count(PredBlock))
585 BlockWorkList.push_back(PredBlock);
586 }
587 return true;
588}
589
590// Starting from \p BB traverse through dominator blocks and assign \p BBWeight
591// to all such blocks that are post dominated by \BB. In other words to all
592// blocks that the one is executed if and only if another one is executed.
593// Importantly, we skip loops here for two reasons. First weights of blocks in
594// a loop should be scaled by trip count (yet possibly unknown). Second there is
595// no any value in doing that because that doesn't give any additional
596// information regarding distribution of probabilities inside the loop.
597// Exception is loop 'enter' and 'exit' edges that are handled in a special way
598// at calcEstimatedHeuristics.
599//
600// In addition, \p WorkList is populated with basic blocks if at leas one
601// successor has updated estimated weight.
602void BPIConstruction::propagateEstimatedBlockWeight(
603 const BasicBlock *BB, DominatorTree *DT, PostDominatorTree *PDT,
604 uint32_t BBWeight, SmallVectorImpl<const BasicBlock *> &BlockWorkList,
605 SmallVectorImpl<const BasicBlock *> &LoopWorkList) {
606 const auto *DTStartNode = DT->getNode(BB);
607 const auto *PDTStartNode = PDT->getNode(BB);
608
609 // TODO: Consider propagating weight down the domination line as well.
610 for (const auto *DTNode = DTStartNode; DTNode != nullptr;
611 DTNode = DTNode->getIDom()) {
612 auto *DomBB = DTNode->getBlock();
613 // Consider blocks which lie on one 'line'.
614 if (!PDT->dominates(PDTStartNode, PDT->getNode(DomBB)))
615 // If BB doesn't post dominate DomBB it will not post dominate dominators
616 // of DomBB as well.
617 break;
618
619 const LoopEdge Edge{DomBB, BB};
620 // Don't propagate weight to blocks belonging to different loops.
621 if (!isLoopEnteringExitingEdge(Edge)) {
622 if (!updateEstimatedBlockWeight(DomBB, BBWeight, BlockWorkList,
623 LoopWorkList))
624 // If DomBB has weight set then all it's predecessors are already
625 // processed (since we propagate weight up to the top of IR each time).
626 break;
627 } else if (isLoopExitingEdge(Edge)) {
628 LoopWorkList.push_back(DomBB);
629 }
630 }
631}
632
633std::optional<uint32_t>
634BPIConstruction::getInitialEstimatedBlockWeight(const BasicBlock *BB) {
635 // Returns true if \p BB has call marked with "NoReturn" attribute.
636 auto hasNoReturn = [&](const BasicBlock *BB) {
637 for (const auto &I : reverse(*BB))
638 if (const CallInst *CI = dyn_cast<CallInst>(&I))
639 if (CI->hasFnAttr(Attribute::NoReturn))
640 return true;
641
642 return false;
643 };
644
645 // Important note regarding the order of checks. They are ordered by weight
646 // from lowest to highest. Doing that allows to avoid "unstable" results
647 // when several conditions heuristics can be applied simultaneously.
649 // If this block is terminated by a call to
650 // @llvm.experimental.deoptimize then treat it like an unreachable
651 // since it is expected to practically never execute.
652 // TODO: Should we actually treat as never returning call?
654 return hasNoReturn(BB)
655 ? static_cast<uint32_t>(BlockExecWeight::NORETURN)
656 : static_cast<uint32_t>(BlockExecWeight::UNREACHABLE);
657
658 // Check if the block is an exception handling block.
659 if (BB->isEHPad())
660 return static_cast<uint32_t>(BlockExecWeight::UNWIND);
661
662 // Check if the block contains 'cold' call.
663 for (const auto &I : *BB)
664 if (const CallInst *CI = dyn_cast<CallInst>(&I))
665 if (CI->hasFnAttr(Attribute::Cold))
666 return static_cast<uint32_t>(BlockExecWeight::COLD);
667
668 return std::nullopt;
669}
670
671// Does RPO traversal over all blocks in \p F and assigns weights to
672// 'unreachable', 'noreturn', 'cold', 'unwind' blocks. In addition it does its
673// best to propagate the weight to up/down the IR.
674void BPIConstruction::estimateBlockWeights(const Function &F, DominatorTree *DT,
675 PostDominatorTree *PDT) {
676 SmallVector<const BasicBlock *, 8> BlockWorkList;
677 SmallVector<const BasicBlock *, 8> LoopWorkList;
678 SmallDenseMap<CycleRef, SmallVector<BasicBlock *, 4>> LoopExitBlocks;
679
680 // By doing RPO we make sure that all predecessors already have weights
681 // calculated before visiting theirs successors.
682 ReversePostOrderTraversal<const Function *> RPOT(&F);
683 for (const auto *BB : RPOT)
684 if (auto BBWeight = getInitialEstimatedBlockWeight(BB))
685 // If we were able to find estimated weight for the block set it to this
686 // block and propagate up the IR.
687 propagateEstimatedBlockWeight(BB, DT, PDT, *BBWeight, BlockWorkList,
688 LoopWorkList);
689
690 // BlockWorklist/LoopWorkList contains blocks/loops with at least one
691 // successor/exit having estimated weight. Try to propagate weight to such
692 // blocks/loops from successors/exits.
693 // Process loops and blocks. Order is not important.
694 do {
695 while (!LoopWorkList.empty()) {
696 const BasicBlock *LoopBB = LoopWorkList.pop_back_val();
697 CycleRef C = CI->getCycle(LoopBB);
698 if (EstimatedLoopWeight.count(C))
699 continue;
700
701 auto Res = LoopExitBlocks.try_emplace(C);
702 SmallVectorImpl<BasicBlock *> &Exits = Res.first->second;
703 if (Res.second)
704 CI->getExitBlocks(C, Exits);
705 auto LoopWeight = getMaxEstimatedEdgeWeight(
706 LoopBB, make_range(Exits.begin(), Exits.end()));
707
708 if (LoopWeight) {
709 // If we never exit the loop then we can enter it once at maximum.
710 if (LoopWeight <= static_cast<uint32_t>(BlockExecWeight::UNREACHABLE))
711 LoopWeight = static_cast<uint32_t>(BlockExecWeight::LOWEST_NON_ZERO);
712
713 EstimatedLoopWeight.insert({C, *LoopWeight});
714 // Add all blocks entering the loop into working list.
715 getLoopEnterBlocks(LoopBB, BlockWorkList);
716 }
717 }
718
719 while (!BlockWorkList.empty()) {
720 // We can reach here only if BlockWorkList is not empty.
721 const BasicBlock *BB = BlockWorkList.pop_back_val();
722 if (EstimatedBlockWeight.count(BB))
723 continue;
724
725 // We take maximum over all weights of successors. In other words we take
726 // weight of "hot" path. In theory we can probably find a better function
727 // which gives higher accuracy results (comparing to "maximum") but I
728 // can't
729 // think of any right now. And I doubt it will make any difference in
730 // practice.
731 auto MaxWeight = getMaxEstimatedEdgeWeight(BB, successors(BB));
732
733 if (MaxWeight)
734 propagateEstimatedBlockWeight(BB, DT, PDT, *MaxWeight, BlockWorkList,
735 LoopWorkList);
736 }
737 } while (!BlockWorkList.empty() || !LoopWorkList.empty());
738}
739
740// Calculate edge probabilities based on block's estimated weight.
741// Note that gathered weights were not scaled for loops. Thus edges entering
742// and exiting loops requires special processing.
743bool BPIConstruction::calcEstimatedHeuristics(const BasicBlock *BB) {
745 "expected more than one successor!");
746
747 CycleRef BBCycle = CI->getCycle(BB);
748
749 SmallPtrSet<const BasicBlock *, 8> UnlikelyBlocks;
751 if (BBCycle)
752 computeUnlikelySuccessors(BB, *CI, BBCycle, UnlikelyBlocks);
753
754 // Changed to 'true' if at least one successor has estimated weight.
755 bool FoundEstimatedWeight = false;
756 SmallVector<uint32_t, 4> SuccWeights;
757 uint64_t TotalWeight = 0;
758 // Go over all successors of BB and put their weights into SuccWeights.
759 for (const BasicBlock *SuccBB : successors(BB)) {
760 std::optional<uint32_t> Weight;
761 const LoopEdge Edge{BB, SuccBB};
762
763 Weight = getEstimatedEdgeWeight(Edge);
764
765 if (isLoopExitingEdge(Edge) &&
766 // Avoid adjustment of ZERO weight since it should remain unchanged.
767 Weight != static_cast<uint32_t>(BlockExecWeight::ZERO)) {
768 // Scale down loop exiting weight by trip count.
769 Weight = std::max(
770 static_cast<uint32_t>(BlockExecWeight::LOWEST_NON_ZERO),
771 Weight.value_or(static_cast<uint32_t>(BlockExecWeight::DEFAULT)) /
772 TC);
773 }
774 bool IsUnlikelyEdge = BBCycle && UnlikelyBlocks.contains(SuccBB);
775 if (IsUnlikelyEdge &&
776 // Avoid adjustment of ZERO weight since it should remain unchanged.
777 Weight != static_cast<uint32_t>(BlockExecWeight::ZERO)) {
778 // 'Unlikely' blocks have twice lower weight.
779 Weight = std::max(
780 static_cast<uint32_t>(BlockExecWeight::LOWEST_NON_ZERO),
781 Weight.value_or(static_cast<uint32_t>(BlockExecWeight::DEFAULT)) / 2);
782 }
783
784 if (Weight)
785 FoundEstimatedWeight = true;
786
787 auto WeightVal =
788 Weight.value_or(static_cast<uint32_t>(BlockExecWeight::DEFAULT));
789 TotalWeight += WeightVal;
790 SuccWeights.push_back(WeightVal);
791 }
792
793 // If non of blocks have estimated weight bail out.
794 // If TotalWeight is 0 that means weight of each successor is 0 as well and
795 // equally likely. Bail out early to not deal with devision by zero.
796 if (!FoundEstimatedWeight || TotalWeight == 0)
797 return false;
798
799 assert(SuccWeights.size() == succ_size(BB) && "Missed successor?");
800 const unsigned SuccCount = SuccWeights.size();
801
802 // If the sum of weights does not fit in 32 bits, scale every weight down
803 // accordingly.
804 if (TotalWeight > UINT32_MAX) {
805 uint64_t ScalingFactor = TotalWeight / UINT32_MAX + 1;
806 TotalWeight = 0;
807 for (unsigned Idx = 0; Idx < SuccCount; ++Idx) {
808 SuccWeights[Idx] /= ScalingFactor;
809 if (SuccWeights[Idx] == static_cast<uint32_t>(BlockExecWeight::ZERO))
810 SuccWeights[Idx] =
811 static_cast<uint32_t>(BlockExecWeight::LOWEST_NON_ZERO);
812 TotalWeight += SuccWeights[Idx];
813 }
814 assert(TotalWeight <= UINT32_MAX && "Total weight overflows");
815 }
816
817 // Finally set probabilities to edges according to estimated block weights.
818 SmallVector<BranchProbability, 4> EdgeProbabilities(
819 SuccCount, BranchProbability::getUnknown());
820
821 for (unsigned Idx = 0; Idx < SuccCount; ++Idx) {
822 EdgeProbabilities[Idx] =
823 BranchProbability(SuccWeights[Idx], (uint32_t)TotalWeight);
824 }
825 BPI.setEdgeProbability(BB, EdgeProbabilities);
826 return true;
827}
828
829bool BPIConstruction::calcZeroHeuristics(const BasicBlock *BB,
830 const TargetLibraryInfo *TLI) {
831 const CondBrInst *BI = dyn_cast<CondBrInst>(BB->getTerminator());
832 if (!BI)
833 return false;
834
835 Value *Cond = BI->getCondition();
836 ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
837 if (!CI)
838 return false;
839
840 auto GetConstantInt = [](Value *V) {
841 if (auto *I = dyn_cast<BitCastInst>(V))
842 return dyn_cast<ConstantInt>(I->getOperand(0));
843 return dyn_cast<ConstantInt>(V);
844 };
845
846 Value *RHS = CI->getOperand(1);
847 ConstantInt *CV = GetConstantInt(RHS);
848 if (!CV)
849 return false;
850
851 // If the LHS is the result of AND'ing a value with a single bit bitmask,
852 // we don't have information about probabilities.
853 if (Instruction *LHS = dyn_cast<Instruction>(CI->getOperand(0)))
854 if (LHS->getOpcode() == Instruction::And)
855 if (ConstantInt *AndRHS = GetConstantInt(LHS->getOperand(1)))
856 if (AndRHS->getValue().isPowerOf2())
857 return false;
858
859 // Check if the LHS is the return value of a library function
860 LibFunc Func = LibFunc::NotLibFunc;
861 if (TLI)
862 if (CallInst *Call = dyn_cast<CallInst>(CI->getOperand(0)))
863 if (Function *CalledFn = Call->getCalledFunction())
864 Func = TLI->getLibFunc(*CalledFn);
865
866 bool Likely;
867 if (Func == LibFunc_strcasecmp ||
868 Func == LibFunc_strcmp ||
869 Func == LibFunc_strncasecmp ||
870 Func == LibFunc_strncmp ||
871 Func == LibFunc_memcmp ||
872 Func == LibFunc_bcmp) {
873 /// strcmp and similar functions return zero, negative, or positive, if the
874 /// first string is equal, less, or greater than the second. We consider it
875 /// likely that the strings are not equal, so a comparison with zero is
876 /// probably false, but also a comparison with any other number is also
877 /// probably false given that what exactly is returned for nonzero values is
878 /// not specified. Any kind of comparison other than equality we know
879 /// nothing about.
880 // clang-format off
881 switch (CI->getPredicate()) {
882 case CmpInst::ICMP_EQ: Likely = false; break;
883 case CmpInst::ICMP_NE: Likely = true; break;
884 default: return false;
885 }
886 // clang-format on
887 } else if (CV->isZero()) {
888 // clang-format off
889 switch (CI->getPredicate()) {
890 case CmpInst::ICMP_EQ: Likely = false; break;
891 case CmpInst::ICMP_NE: Likely = true; break;
892 case CmpInst::ICMP_SLT: Likely = false; break;
893 case CmpInst::ICMP_SGT: Likely = true; break;
894 default: return false;
895 }
896 // clang-format on
897 } else if (CV->isOne()) {
898 // clang-format off
899 switch (CI->getPredicate()) {
900 case CmpInst::ICMP_SLT: Likely = false; break;
901 default: return false;
902 }
903 // clang-format on
904 } else if (CV->isMinusOne()) {
905 // clang-format off
906 switch (CI->getPredicate()) {
907 case CmpInst::ICMP_EQ: Likely = false; break;
908 case CmpInst::ICMP_NE: Likely = true; break;
909 // InstCombine canonicalizes X >= 0 into X > -1
910 case CmpInst::ICMP_SGT: Likely = true; break;
911 default: return false;
912 }
913 // clang-format on
914 } else {
915 return false;
916 }
917
918 if (Likely)
920 else
922 return true;
923}
924
925bool BPIConstruction::calcFloatingPointHeuristics(const BasicBlock *BB) {
926 const CondBrInst *BI = dyn_cast<CondBrInst>(BB->getTerminator());
927 if (!BI)
928 return false;
929
930 Value *Cond = BI->getCondition();
931 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cond);
932 if (!FCmp)
933 return false;
934
935 if (FCmp->isEquality()) {
936 if (!FCmp->isTrueWhenEqual()) // f1 == f2 -> Unlikely
938 else // f1 != f2 -> Likely
940 } else if (FCmp->getPredicate() == FCmpInst::FCMP_ORD) {
942 BB, {FPOrdTakenProb, FPOrdUntakenProb}); // !isnan -> Likely
943 } else if (FCmp->getPredicate() == FCmpInst::FCMP_UNO) {
945 BB, {FPOrdUntakenProb, FPOrdTakenProb}); // isnan -> Unlikely
946 } else {
947 return false;
948 }
949 return true;
950}
951void BPIConstruction::calculate(const Function &F, const CycleInfo &CycleI,
952 const TargetLibraryInfo *TLI, DominatorTree *DT,
953 PostDominatorTree *PDT) {
954 CI = &CycleI;
955
956 std::unique_ptr<DominatorTree> DTPtr;
957 std::unique_ptr<PostDominatorTree> PDTPtr;
958
959 if (!DT) {
960 DTPtr = std::make_unique<DominatorTree>(const_cast<Function &>(F));
961 DT = DTPtr.get();
962 }
963
964 if (!PDT) {
965 PDTPtr = std::make_unique<PostDominatorTree>(const_cast<Function &>(F));
966 PDT = PDTPtr.get();
967 }
968
969 estimateBlockWeights(F, DT, PDT);
970
971 // Walk the basic blocks in post-order so that we can build up state about
972 // the successors of a block iteratively.
973 for (const auto *BB : post_order(&F.getEntryBlock())) {
974 LLVM_DEBUG(dbgs() << "Computing probabilities for " << BB->getName()
975 << "\n");
976 // If there is no at least two successors, no sense to set probability.
977 if (BB->getTerminator()->getNumSuccessors() < 2)
978 continue;
979 if (calcMetadataWeights(BB))
980 continue;
981 if (calcEstimatedHeuristics(BB))
982 continue;
983 if (calcPointerHeuristics(BB))
984 continue;
985 if (calcZeroHeuristics(BB, TLI))
986 continue;
987 if (calcFloatingPointHeuristics(BB))
988 continue;
989 }
990}
991
992} // end anonymous namespace
993
995BranchProbabilityInfo::allocEdges(const BasicBlock *BB) {
996 assert(BB->getParent() == LastF);
997 assert(BlockNumberEpoch == LastF->getBlockNumberEpoch());
998 unsigned NumSuccs = succ_size(BB);
999 if (NumSuccs == 0) {
1000 eraseBlock(BB);
1001 return {};
1002 }
1003 if (EdgeStarts.size() <= BB->getNumber())
1004 EdgeStarts.resize(LastF->getMaxBlockNumber(), 0);
1005 unsigned EdgeStart = Probs.size();
1006 EdgeStarts[BB->getNumber()] = EdgeStart + 1; // 0 = no edges.
1007 Probs.append(NumSuccs, {});
1008 return MutableArrayRef(&Probs[EdgeStart], NumSuccs);
1009}
1010
1012BranchProbabilityInfo::getEdges(const BasicBlock *BB) const {
1013 assert(BB->getParent() == LastF);
1014 assert(BlockNumberEpoch == LastF->getBlockNumberEpoch());
1015 if (EdgeStarts.size() <= BB->getNumber())
1016 return {};
1017 if (unsigned EdgeStart = EdgeStarts[BB->getNumber()]) {
1018 const BranchProbability *Start = &Probs[EdgeStart - 1]; // 0 = no edges.
1019 size_t Count = SIZE_MAX; // Avoid querying num successors in release builds.
1020#ifndef NDEBUG
1021 Count = succ_size(BB);
1022#endif
1023 return ArrayRef(Start, Count);
1024 }
1025 return {};
1026}
1027
1029 FunctionAnalysisManager::Invalidator &) {
1030 // Check whether the analysis, all analyses on functions, or the function's
1031 // CFG have been preserved.
1032 auto PAC = PA.getChecker<BranchProbabilityAnalysis>();
1033 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1034 PAC.preservedSet<CFGAnalyses>());
1035}
1036
1038 OS << "---- Branch Probabilities ----\n";
1039 // We print the probabilities from the last function the analysis ran over,
1040 // or the function it is currently running over.
1041 assert(LastF && "Cannot print prior to running over a function");
1042 for (const auto &BI : *LastF) {
1043 for (const BasicBlock *Succ : successors(&BI))
1044 printEdgeProbability(OS << " ", &BI, Succ);
1045 }
1046}
1047
1049isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const {
1050 // Hot probability is at least 4/5 = 80%
1051 // FIXME: Compare against a static "hot" BranchProbability.
1052 return getEdgeProbability(Src, Dst) > BranchProbability(4, 5);
1053}
1054
1055/// Get the raw edge probability for the edge. If can't find it, return a
1056/// default probability 1/N where N is the number of successors. Here an edge is
1057/// specified using PredBlock and an
1058/// index to the successors.
1061 unsigned IndexInSuccessors) const {
1062 if (ArrayRef<BranchProbability> P = getEdges(Src); !P.empty())
1063 return P[IndexInSuccessors];
1064 return {1, static_cast<uint32_t>(succ_size(Src))};
1065}
1066
1067/// Get the raw edge probability calculated for the block pair. This returns the
1068/// sum of all raw edge probabilities from Src to Dst.
1071 const BasicBlock *Dst) const {
1072 ArrayRef<BranchProbability> P = getEdges(Src);
1073 if (P.empty())
1074 return BranchProbability(llvm::count(successors(Src), Dst), succ_size(Src));
1075
1076 auto Prob = BranchProbability::getZero();
1077 for (auto It : enumerate(successors(Src)))
1078 if (It.value() == Dst)
1079 Prob += P[It.index()];
1080
1081 return Prob;
1082}
1083
1086 ArrayRef<uint32_t> Weights) {
1087 // If the sum of weights does not fit in 32 bits, scale every weight down
1088 // accordingly.
1089 SmallVector<uint32_t> ScaledWeights(Weights);
1090 uint64_t WeightSum = sum_of(ScaledWeights, uint64_t(0));
1091 if (WeightSum > UINT32_MAX) {
1092 uint64_t ScalingFactor = WeightSum / UINT32_MAX + 1;
1093 for (uint32_t &Weight : ScaledWeights)
1094 Weight /= ScalingFactor;
1095 WeightSum = sum_of(ScaledWeights, uint64_t(0));
1096 }
1097
1098 assert(WeightSum <= UINT32_MAX &&
1099 "Expected weights to scale down to 32 bits");
1100
1101 if (WeightSum == 0) {
1102 fill(ScaledWeights, 1);
1103 WeightSum = ScaledWeights.size();
1104 }
1105
1106 return map_to_vector(ScaledWeights, [WeightSum](uint32_t Weight) {
1107 return BranchProbability(Weight, static_cast<uint32_t>(WeightSum));
1108 });
1109}
1110
1111/// Set the edge probability for all edges at once.
1113 const BasicBlock *Src, ArrayRef<BranchProbability> Probs) {
1114 assert(Src->getTerminator()->getNumSuccessors() == Probs.size());
1115 MutableArrayRef<BranchProbability> P = allocEdges(Src);
1116 uint64_t TotalNumerator = 0;
1117 for (unsigned SuccIdx = 0; SuccIdx < Probs.size(); ++SuccIdx) {
1118 P[SuccIdx] = Probs[SuccIdx];
1119 LLVM_DEBUG(dbgs() << "set edge " << Src->getName() << " -> " << SuccIdx
1120 << " successor probability to " << Probs[SuccIdx]
1121 << "\n");
1122 TotalNumerator += Probs[SuccIdx].getNumerator();
1123 }
1124
1125 // Because of rounding errors the total probability cannot be checked to be
1126 // 1.0 exactly. That is TotalNumerator == BranchProbability::getDenominator.
1127 // Instead, every single probability in Probs must be as accurate as possible.
1128 // This results in error 1/denominator at most, thus the total absolute error
1129 // should be within Probs.size / BranchProbability::getDenominator.
1130 if (P.empty())
1131 return; // If we store no probabilities, TotalNumerator is zero.
1132 assert(TotalNumerator <= BranchProbability::getDenominator() + Probs.size());
1133 assert(TotalNumerator >= BranchProbability::getDenominator() - Probs.size());
1134 (void)TotalNumerator;
1135}
1136
1138 BasicBlock *Dst) {
1139 assert(succ_size(Src) == succ_size(Dst));
1140 // allocEdges can reallocate and must be called first.
1141 MutableArrayRef<BranchProbability> DstP = allocEdges(Dst);
1142 ArrayRef<BranchProbability> SrcP = getEdges(Src);
1143 if (SrcP.empty()) {
1144 // Nothing to copy from, erase again.
1145 eraseBlock(Dst);
1146 return;
1147 }
1148 for (unsigned i = 0; i != DstP.size(); ++i) {
1149 DstP[i] = SrcP[i];
1150 LLVM_DEBUG(dbgs() << "set edge " << Dst->getName() << " -> " << i
1151 << " successor probability to " << SrcP[i] << "\n");
1152 }
1153}
1154
1156 assert(Src->getTerminator()->getNumSuccessors() == 2);
1157 ArrayRef<BranchProbability> P = getEdges(Src);
1158 if (P.empty())
1159 return;
1161 const_cast<BranchProbability *>(P.data()), P.size());
1162 std::swap(MP[0], MP[1]);
1163}
1164
1167 const BasicBlock *Src,
1168 const BasicBlock *Dst) const {
1169 const BranchProbability Prob = getEdgeProbability(Src, Dst);
1170 OS << "edge ";
1171 Src->printAsOperand(OS, false, Src->getModule());
1172 OS << " -> ";
1173 Dst->printAsOperand(OS, false, Dst->getModule());
1174 OS << " probability is " << Prob
1175 << (isEdgeHot(Src, Dst) ? " [HOT edge]\n" : "\n");
1176
1177 return OS;
1178}
1179
1181 LLVM_DEBUG(dbgs() << "eraseBlock " << BB->getName() << "\n");
1182 assert(BB->getParent() == LastF);
1183 assert(BlockNumberEpoch == LastF->getBlockNumberEpoch());
1184 if (EdgeStarts.size() > BB->getNumber())
1185 EdgeStarts[BB->getNumber()] = 0;
1186}
1187
1189 const CycleInfo &CycleI,
1190 const TargetLibraryInfo *TLI,
1191 DominatorTree *DT,
1192 PostDominatorTree *PDT) {
1193 LLVM_DEBUG(dbgs() << "---- Branch Probability Info : " << F.getName()
1194 << " ----\n\n");
1195 LastF = &F; // Store the last function we ran on for printing.
1196 BlockNumberEpoch = F.getBlockNumberEpoch();
1197 Probs.clear();
1198 EdgeStarts.clear();
1199 BPIConstruction(*this).calculate(F, CycleI, TLI, DT, PDT);
1200
1201 const AnalysisOptions &Opts = getAnalysisOptions(F);
1202 if (Opts.print_bpi && (Opts.print_bpi_func_name.empty() ||
1203 F.getName() == Opts.print_bpi_func_name)) {
1204 print(dbgs());
1205 }
1206}
1207
1209 AnalysisUsage &AU) const {
1210 // We require DT so it's available when LI is available. The LI updating code
1211 // asserts that DT is also present so if we don't make sure that we have DT
1212 // here, that assert will trigger.
1218 AU.setPreservesAll();
1219}
1220
1222 const CycleInfo &CI = getAnalysis<CycleInfoWrapperPass>().getResult();
1223 const TargetLibraryInfo &TLI =
1226 PostDominatorTree &PDT =
1228 BPI.calculate(F, CI, &TLI, &DT, &PDT);
1229 return false;
1230}
1231
1233 const Module *) const {
1234 BPI.print(OS);
1235}
1236
1237AnalysisKey BranchProbabilityAnalysis::Key;
1240 auto &CI = AM.getResult<CycleAnalysis>(F);
1241 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1242 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1243 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1245 BPI.calculate(F, CI, &TLI, &DT, &PDT);
1246 return BPI;
1247}
1248
1251 OS << "Printing analysis 'Branch Probability Analysis' for function '"
1252 << F.getName() << "':\n";
1254 return PreservedAnalyses::all();
1255}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockExecWeight
Set of dedicated "absolute" execution weights for a block.
@ NORETURN
Weight to a block containing non returning call.
@ UNWIND
Weight to 'unwind' block of an invoke instruction.
@ COLD
Weight to a 'cold' block.
@ ZERO
Special weight used for cases with exact zero probability.
@ UNREACHABLE
Weight to an 'unreachable' block.
@ DEFAULT
Default weight is used in cases when there is no dedicated execution weight set.
@ LOWEST_NON_ZERO
Minimal possible non zero weight.
static constexpr BranchProbability FPTakenProb(FPH_TAKEN_WEIGHT, FPH_TAKEN_WEIGHT+FPH_NONTAKEN_WEIGHT)
static const uint32_t FPH_TAKEN_WEIGHT
static const uint32_t LBH_TAKEN_WEIGHT
static const uint32_t ZH_NONTAKEN_WEIGHT
static const uint32_t PH_NONTAKEN_WEIGHT
static constexpr BranchProbability UR_TAKEN_PROB
Unreachable-terminating branch taken probability.
static const uint32_t PH_TAKEN_WEIGHT
Heuristics and lookup tables for non-loop branches: Pointer Heuristics (PH)
static constexpr BranchProbability FPUntakenProb(FPH_NONTAKEN_WEIGHT, FPH_TAKEN_WEIGHT+FPH_NONTAKEN_WEIGHT)
static constexpr BranchProbability PtrTakenProb(PH_TAKEN_WEIGHT, PH_TAKEN_WEIGHT+PH_NONTAKEN_WEIGHT)
static constexpr BranchProbability PtrUntakenProb(PH_NONTAKEN_WEIGHT, PH_TAKEN_WEIGHT+PH_NONTAKEN_WEIGHT)
static const uint32_t ZH_TAKEN_WEIGHT
Zero Heuristics (ZH)
static const uint32_t FPH_NONTAKEN_WEIGHT
static constexpr BranchProbability ZeroTakenProb(ZH_TAKEN_WEIGHT, ZH_TAKEN_WEIGHT+ZH_NONTAKEN_WEIGHT)
static const uint32_t LBH_NONTAKEN_WEIGHT
static constexpr BranchProbability ZeroUntakenProb(ZH_NONTAKEN_WEIGHT, ZH_TAKEN_WEIGHT+ZH_NONTAKEN_WEIGHT)
static const uint32_t FPH_ORD_WEIGHT
This is the probability for an ordered floating point comparison.
static const uint32_t FPH_UNO_WEIGHT
This is the probability for an unordered floating point comparison, it means one or two of the operan...
static constexpr BranchProbability FPOrdTakenProb(FPH_ORD_WEIGHT, FPH_ORD_WEIGHT+FPH_UNO_WEIGHT)
static constexpr BranchProbability FPOrdUntakenProb(FPH_UNO_WEIGHT, FPH_ORD_WEIGHT+FPH_UNO_WEIGHT)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
SmallVector< MachineOperand, 4 > Cond
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
static void eraseBlock(MachineBasicBlock *MBB, LiveIntervals &LIS, MachineDomTreeUpdater &MDTU)
#define P(N)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines less commonly used SmallVector utilities.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
BinaryOperator * Mul
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
LLVM Basic Block Representation.
Definition BasicBlock.h:61
unsigned getNumber() const
Definition BasicBlock.h:94
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:682
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
Analysis pass which computes BranchProbabilityInfo.
LLVM_ABI BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BPI.
Legacy analysis pass which computes BranchProbabilityInfo.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
Analysis providing branch probability information.
static LLVM_ABI SmallVector< BranchProbability > getEdgeProbabilitiesFromWeights(ArrayRef< uint32_t > Weights)
Returns the probabilities of edges with branch weights Weights.
LLVM_ABI void eraseBlock(const BasicBlock *BB)
Forget analysis results for the given basic block.
LLVM_ABI void calculate(const Function &F, const CycleInfo &CI, const TargetLibraryInfo *TLI, DominatorTree *DT, PostDominatorTree *PDT)
LLVM_ABI bool invalidate(Function &, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
LLVM_ABI void setEdgeProbability(const BasicBlock *Src, ArrayRef< BranchProbability > Probs)
Set the raw probabilities for all edges from the given block.
LLVM_ABI bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
LLVM_ABI void swapSuccEdgesProbabilities(const BasicBlock *Src)
Swap outgoing edges probabilities for Src with branch terminator.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI raw_ostream & printEdgeProbability(raw_ostream &OS, const BasicBlock *Src, const BasicBlock *Dst) const
Print an edge's probability.
LLVM_ABI void copyEdgeProbabilities(BasicBlock *Src, BasicBlock *Dst)
Copy outgoing edge probabilities from Src to Dst.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static constexpr BranchProbability getOne()
static uint32_t getDenominator()
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
static constexpr BranchProbability getRaw(uint32_t N)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_NE
not equal
Definition InstrTypes.h:762
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
Analysis pass which computes a CycleInfo.
Legacy analysis pass which computes a CycleInfo.
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static bool isEquality(Predicate Pred)
FunctionPass(char &pid)
Definition Pass.h:314
ArrayRef< BlockT * > getEntries(CycleRef C) const
bool contains(CycleRef Outer, CycleRef Inner) const
Returns true iff Outer contains Inner. O(1). Non-strict.
void getExitBlocks(CycleRef C, SmallVectorImpl< BlockT * > &TmpStorage) const
Return all of the successor blocks of C: the blocks outside of C which are branched to from within it...
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
LLVM_ABI bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
Value * getOperand(unsigned i) const
Definition User.h:207
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
const ParentTy * getParent() const
Definition ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
auto map_to_vector(ContainerTy &&C, FuncTy &&F)
Map a range to a SmallVector with element types deduced from the mapping.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition MathExtras.h:453
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto succ_size(const MachineBasicBlock *BB)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto post_order(const T &G)
Post-order traversal of a graph.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29