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