1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements basic block placement transformations using the CFG
11 // structure and branch probability estimates.
13 // The pass strives to preserve the structure of the CFG (that is, retain
14 // a topological ordering of basic blocks) in the absence of a *strong* signal
15 // to the contrary from probabilities. However, within the CFG structure, it
16 // attempts to choose an ordering which favors placing more likely sequences of
17 // blocks adjacent to each other.
19 // The algorithm works from the inner-most loop within a function outward, and
20 // at each stage walks through the basic blocks, trying to coalesce them into
21 // sequential chains where allowed by the CFG (or demanded by heavy
22 // probabilities). Finally, it walks the blocks in topological order, and the
23 // first time it reaches a chain of basic blocks, it schedules them in the
26 //===----------------------------------------------------------------------===//
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/TargetPassConfig.h"
30 #include "BranchFolding.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
37 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
38 #include "llvm/CodeGen/MachineDominators.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineLoopInfo.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
53 #define DEBUG_TYPE "block-placement"
55 STATISTIC(NumCondBranches, "Number of conditional branches");
56 STATISTIC(NumUncondBranches, "Number of unconditional branches");
57 STATISTIC(CondBranchTakenFreq,
58 "Potential frequency of taking conditional branches");
59 STATISTIC(UncondBranchTakenFreq,
60 "Potential frequency of taking unconditional branches");
62 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
63 cl::desc("Force the alignment of all "
64 "blocks in the function."),
65 cl::init(0), cl::Hidden);
67 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
68 "align-all-nofallthru-blocks",
69 cl::desc("Force the alignment of all "
70 "blocks that have no fall-through predecessors (i.e. don't add "
71 "nops that are executed)."),
72 cl::init(0), cl::Hidden);
74 // FIXME: Find a good default for this flag and remove the flag.
75 static cl::opt<unsigned> ExitBlockBias(
76 "block-placement-exit-block-bias",
77 cl::desc("Block frequency percentage a loop exit block needs "
78 "over the original exit to be considered the new exit."),
79 cl::init(0), cl::Hidden);
81 static cl::opt<bool> OutlineOptionalBranches(
82 "outline-optional-branches",
83 cl::desc("Put completely optional branches, i.e. branches with a common "
84 "post dominator, out of line."),
85 cl::init(false), cl::Hidden);
87 static cl::opt<unsigned> OutlineOptionalThreshold(
88 "outline-optional-threshold",
89 cl::desc("Don't outline optional branches that are a single block with an "
90 "instruction count below this threshold"),
91 cl::init(4), cl::Hidden);
93 static cl::opt<unsigned> LoopToColdBlockRatio(
94 "loop-to-cold-block-ratio",
95 cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
96 "(frequency of block) is greater than this ratio"),
97 cl::init(5), cl::Hidden);
100 PreciseRotationCost("precise-rotation-cost",
101 cl::desc("Model the cost of loop rotation more "
102 "precisely by using profile data."),
103 cl::init(false), cl::Hidden);
105 ForcePreciseRotationCost("force-precise-rotation-cost",
106 cl::desc("Force the use of precise cost "
107 "loop rotation strategy."),
108 cl::init(false), cl::Hidden);
110 static cl::opt<unsigned> MisfetchCost(
112 cl::desc("Cost that models the probabilistic risk of an instruction "
113 "misfetch due to a jump comparing to falling through, whose cost "
115 cl::init(1), cl::Hidden);
117 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
118 cl::desc("Cost of jump instructions."),
119 cl::init(1), cl::Hidden);
122 BranchFoldPlacement("branch-fold-placement",
123 cl::desc("Perform branch folding during placement. "
124 "Reduces code size."),
125 cl::init(true), cl::Hidden);
127 extern cl::opt<unsigned> StaticLikelyProb;
128 extern cl::opt<unsigned> ProfileLikelyProb;
132 /// \brief Type for our function-wide basic block -> block chain mapping.
133 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
137 /// \brief A chain of blocks which will be laid out contiguously.
139 /// This is the datastructure representing a chain of consecutive blocks that
140 /// are profitable to layout together in order to maximize fallthrough
141 /// probabilities and code locality. We also can use a block chain to represent
142 /// a sequence of basic blocks which have some external (correctness)
143 /// requirement for sequential layout.
145 /// Chains can be built around a single basic block and can be merged to grow
146 /// them. They participate in a block-to-chain mapping, which is updated
147 /// automatically as chains are merged together.
149 /// \brief The sequence of blocks belonging to this chain.
151 /// This is the sequence of blocks for a particular chain. These will be laid
152 /// out in-order within the function.
153 SmallVector<MachineBasicBlock *, 4> Blocks;
155 /// \brief A handle to the function-wide basic block to block chain mapping.
157 /// This is retained in each block chain to simplify the computation of child
158 /// block chains for SCC-formation and iteration. We store the edges to child
159 /// basic blocks, and map them back to their associated chains using this
161 BlockToChainMapType &BlockToChain;
164 /// \brief Construct a new BlockChain.
166 /// This builds a new block chain representing a single basic block in the
167 /// function. It also registers itself as the chain that block participates
168 /// in with the BlockToChain mapping.
169 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
170 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
171 assert(BB && "Cannot create a chain with a null basic block");
172 BlockToChain[BB] = this;
175 /// \brief Iterator over blocks within the chain.
176 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
178 /// \brief Beginning of blocks within the chain.
179 iterator begin() { return Blocks.begin(); }
181 /// \brief End of blocks within the chain.
182 iterator end() { return Blocks.end(); }
184 /// \brief Merge a block chain into this one.
186 /// This routine merges a block chain into this one. It takes care of forming
187 /// a contiguous sequence of basic blocks, updating the edge list, and
188 /// updating the block -> chain mapping. It does not free or tear down the
189 /// old chain, but the old chain's block list is no longer valid.
190 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
192 assert(!Blocks.empty());
194 // Fast path in case we don't have a chain already.
196 assert(!BlockToChain[BB]);
197 Blocks.push_back(BB);
198 BlockToChain[BB] = this;
202 assert(BB == *Chain->begin());
203 assert(Chain->begin() != Chain->end());
205 // Update the incoming blocks to point to this chain, and add them to the
207 for (MachineBasicBlock *ChainBB : *Chain) {
208 Blocks.push_back(ChainBB);
209 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
210 BlockToChain[ChainBB] = this;
215 /// \brief Dump the blocks in this chain.
216 LLVM_DUMP_METHOD void dump() {
217 for (MachineBasicBlock *MBB : *this)
222 /// \brief Count of predecessors of any block within the chain which have not
223 /// yet been scheduled. In general, we will delay scheduling this chain
224 /// until those predecessors are scheduled (or we find a sufficiently good
225 /// reason to override this heuristic.) Note that when forming loop chains,
226 /// blocks outside the loop are ignored and treated as if they were already
229 /// Note: This field is reinitialized multiple times - once for each loop,
230 /// and then once for the function as a whole.
231 unsigned UnscheduledPredecessors;
236 class MachineBlockPlacement : public MachineFunctionPass {
237 /// \brief A typedef for a block filter set.
238 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
240 /// \brief work lists of blocks that are ready to be laid out
241 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
242 SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
244 /// \brief Machine Function
247 /// \brief A handle to the branch probability pass.
248 const MachineBranchProbabilityInfo *MBPI;
250 /// \brief A handle to the function-wide block frequency pass.
251 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
253 /// \brief A handle to the loop info.
254 MachineLoopInfo *MLI;
256 /// \brief A handle to the target's instruction info.
257 const TargetInstrInfo *TII;
259 /// \brief A handle to the target's lowering info.
260 const TargetLoweringBase *TLI;
262 /// \brief A handle to the post dominator tree.
263 MachineDominatorTree *MDT;
265 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
266 /// all terminators of the MachineFunction.
267 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
269 /// \brief Allocator and owner of BlockChain structures.
271 /// We build BlockChains lazily while processing the loop structure of
272 /// a function. To reduce malloc traffic, we allocate them using this
273 /// slab-like allocator, and destroy them after the pass completes. An
274 /// important guarantee is that this allocator produces stable pointers to
276 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
278 /// \brief Function wide BasicBlock to BlockChain mapping.
280 /// This mapping allows efficiently moving from any given basic block to the
281 /// BlockChain it participates in, if any. We use it to, among other things,
282 /// allow implicitly defining edges between chains as the existing edges
283 /// between basic blocks.
284 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
286 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
287 const BlockFilterSet *BlockFilter = nullptr);
289 collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
290 const BlockFilterSet *BlockFilter,
291 SmallVector<MachineBasicBlock *, 4> &Successors);
292 bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
294 const BlockFilterSet *BlockFilter,
295 BranchProbability SuccProb,
296 BranchProbability HotProb);
298 hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
299 BlockChain &SuccChain, BranchProbability SuccProb,
300 BranchProbability RealSuccProb, BlockChain &Chain,
301 const BlockFilterSet *BlockFilter);
302 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
304 const BlockFilterSet *BlockFilter);
306 selectBestCandidateBlock(BlockChain &Chain,
307 SmallVectorImpl<MachineBasicBlock *> &WorkList);
309 getFirstUnplacedBlock(const BlockChain &PlacedChain,
310 MachineFunction::iterator &PrevUnplacedBlockIt,
311 const BlockFilterSet *BlockFilter);
313 /// \brief Add a basic block to the work list if it is appropriate.
315 /// If the optional parameter BlockFilter is provided, only MBB
316 /// present in the set will be added to the worklist. If nullptr
317 /// is provided, no filtering occurs.
318 void fillWorkLists(MachineBasicBlock *MBB,
319 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
320 const BlockFilterSet *BlockFilter);
321 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
322 const BlockFilterSet *BlockFilter = nullptr);
323 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
324 const BlockFilterSet &LoopBlockSet);
325 MachineBasicBlock *findBestLoopExit(MachineLoop &L,
326 const BlockFilterSet &LoopBlockSet);
327 BlockFilterSet collectLoopBlockSet(MachineLoop &L);
328 void buildLoopChains(MachineLoop &L);
329 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
330 const BlockFilterSet &LoopBlockSet);
331 void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
332 const BlockFilterSet &LoopBlockSet);
333 void collectMustExecuteBBs();
334 void buildCFGChains();
335 void optimizeBranches();
339 static char ID; // Pass identification, replacement for typeid
340 MachineBlockPlacement() : MachineFunctionPass(ID) {
341 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
344 bool runOnMachineFunction(MachineFunction &F) override;
346 void getAnalysisUsage(AnalysisUsage &AU) const override {
347 AU.addRequired<MachineBranchProbabilityInfo>();
348 AU.addRequired<MachineBlockFrequencyInfo>();
349 AU.addRequired<MachineDominatorTree>();
350 AU.addRequired<MachineLoopInfo>();
351 AU.addRequired<TargetPassConfig>();
352 MachineFunctionPass::getAnalysisUsage(AU);
357 char MachineBlockPlacement::ID = 0;
358 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
359 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
360 "Branch Probability Basic Block Placement", false, false)
361 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
362 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
363 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
364 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
365 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
366 "Branch Probability Basic Block Placement", false, false)
369 /// \brief Helper to print the name of a MBB.
371 /// Only used by debug logging.
372 static std::string getBlockName(MachineBasicBlock *BB) {
374 raw_string_ostream OS(Result);
375 OS << "BB#" << BB->getNumber();
376 OS << " ('" << BB->getName() << "')";
382 /// \brief Mark a chain's successors as having one fewer preds.
384 /// When a chain is being merged into the "placed" chain, this routine will
385 /// quickly walk the successors of each block in the chain and mark them as
386 /// having one fewer active predecessor. It also adds any successors of this
387 /// chain which reach the zero-predecessor state to the worklist passed in.
388 void MachineBlockPlacement::markChainSuccessors(
389 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
390 const BlockFilterSet *BlockFilter) {
391 // Walk all the blocks in this chain, marking their successors as having
392 // a predecessor placed.
393 for (MachineBasicBlock *MBB : Chain) {
394 // Add any successors for which this is the only un-placed in-loop
395 // predecessor to the worklist as a viable candidate for CFG-neutral
396 // placement. No subsequent placement of this block will violate the CFG
397 // shape, so we get to use heuristics to choose a favorable placement.
398 for (MachineBasicBlock *Succ : MBB->successors()) {
399 if (BlockFilter && !BlockFilter->count(Succ))
401 BlockChain &SuccChain = *BlockToChain[Succ];
402 // Disregard edges within a fixed chain, or edges to the loop header.
403 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
406 // This is a cross-chain edge that is within the loop, so decrement the
407 // loop predecessor count of the destination chain.
408 if (SuccChain.UnscheduledPredecessors == 0 ||
409 --SuccChain.UnscheduledPredecessors > 0)
412 auto *MBB = *SuccChain.begin();
414 EHPadWorkList.push_back(MBB);
416 BlockWorkList.push_back(MBB);
421 /// This helper function collects the set of successors of block
422 /// \p BB that are allowed to be its layout successors, and return
423 /// the total branch probability of edges from \p BB to those
425 BranchProbability MachineBlockPlacement::collectViableSuccessors(
426 MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
427 SmallVector<MachineBasicBlock *, 4> &Successors) {
428 // Adjust edge probabilities by excluding edges pointing to blocks that is
429 // either not in BlockFilter or is already in the current chain. Consider the
438 // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
439 // A->C is chosen as a fall-through, D won't be selected as a successor of C
440 // due to CFG constraint (the probability of C->D is not greater than
441 // HotProb to break top-order). If we exclude E that is not in BlockFilter
442 // when calculating the probability of C->D, D will be selected and we
443 // will get A C D B as the layout of this loop.
444 auto AdjustedSumProb = BranchProbability::getOne();
445 for (MachineBasicBlock *Succ : BB->successors()) {
446 bool SkipSucc = false;
447 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
450 BlockChain *SuccChain = BlockToChain[Succ];
451 if (SuccChain == &Chain) {
453 } else if (Succ != *SuccChain->begin()) {
454 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
459 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
461 Successors.push_back(Succ);
464 return AdjustedSumProb;
467 /// The helper function returns the branch probability that is adjusted
468 /// or normalized over the new total \p AdjustedSumProb.
469 static BranchProbability
470 getAdjustedProbability(BranchProbability OrigProb,
471 BranchProbability AdjustedSumProb) {
472 BranchProbability SuccProb;
473 uint32_t SuccProbN = OrigProb.getNumerator();
474 uint32_t SuccProbD = AdjustedSumProb.getNumerator();
475 if (SuccProbN >= SuccProbD)
476 SuccProb = BranchProbability::getOne();
478 SuccProb = BranchProbability(SuccProbN, SuccProbD);
483 /// When the option OutlineOptionalBranches is on, this method
484 /// checks if the fallthrough candidate block \p Succ (of block
485 /// \p BB) also has other unscheduled predecessor blocks which
486 /// are also successors of \p BB (forming triangular shape CFG).
487 /// If none of such predecessors are small, it returns true.
488 /// The caller can choose to select \p Succ as the layout successors
489 /// so that \p Succ's predecessors (optional branches) can be
491 /// FIXME: fold this with more general layout cost analysis.
492 bool MachineBlockPlacement::shouldPredBlockBeOutlined(
493 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
494 const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
495 BranchProbability HotProb) {
496 if (!OutlineOptionalBranches)
498 // If we outline optional branches, look whether Succ is unavoidable, i.e.
499 // dominates all terminators of the MachineFunction. If it does, other
500 // successors must be optional. Don't do this for cold branches.
501 if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
502 for (MachineBasicBlock *Pred : Succ->predecessors()) {
503 // Check whether there is an unplaced optional branch.
504 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
505 BlockToChain[Pred] == &Chain)
507 // Check whether the optional branch has exactly one BB.
508 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
510 // Check whether the optional branch is small.
511 if (Pred->size() < OutlineOptionalThreshold)
519 // When profile is not present, return the StaticLikelyProb.
520 // When profile is available, we need to handle the triangle-shape CFG.
521 static BranchProbability getLayoutSuccessorProbThreshold(
522 MachineBasicBlock *BB) {
523 if (!BB->getParent()->getFunction()->getEntryCount())
524 return BranchProbability(StaticLikelyProb, 100);
525 if (BB->succ_size() == 2) {
526 const MachineBasicBlock *Succ1 = *BB->succ_begin();
527 const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
528 if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
529 /* See case 1 below for the cost analysis. For BB->Succ to
530 * be taken with smaller cost, the following needs to hold:
531 * Prob(BB->Succ) > 2* Prob(BB->Pred)
533 * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1,
534 * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified
535 * branch bias, we have
536 * T = (2/3)*(ProfileLikelyProb/50)
537 * = (2*ProfileLikelyProb)/150)
539 return BranchProbability(2 * ProfileLikelyProb, 150);
542 return BranchProbability(ProfileLikelyProb, 100);
545 /// Checks to see if the layout candidate block \p Succ has a better layout
546 /// predecessor than \c BB. If yes, returns true.
547 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
548 MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
549 BranchProbability SuccProb, BranchProbability RealSuccProb,
550 BlockChain &Chain, const BlockFilterSet *BlockFilter) {
552 // There isn't a better layout when there are no unscheduled predecessors.
553 if (SuccChain.UnscheduledPredecessors == 0)
556 // There are two basic scenarios here:
557 // -------------------------------------
558 // Case 1: triangular shape CFG (if-then):
565 // In this case, we are evaluating whether to select edge -> Succ, e.g.
566 // set Succ as the layout successor of BB. Picking Succ as BB's
567 // successor breaks the CFG constraints (FIXME: define these constraints).
568 // With this layout, Pred BB
569 // is forced to be outlined, so the overall cost will be cost of the
570 // branch taken from BB to Pred, plus the cost of back taken branch
571 // from Pred to Succ, as well as the additional cost associated
572 // with the needed unconditional jump instruction from Pred To Succ.
574 // The cost of the topological order layout is the taken branch cost
575 // from BB to Succ, so to make BB->Succ a viable candidate, the following
577 // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
578 // < freq(BB->Succ) * taken_branch_cost.
579 // Ignoring unconditional jump cost, we get
580 // freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
581 // prob(BB->Succ) > 2 * prob(BB->Pred)
583 // When real profile data is available, we can precisely compute the
584 // probability threshold that is needed for edge BB->Succ to be considered.
585 // Without profile data, the heuristic requires the branch bias to be
586 // a lot larger to make sure the signal is very strong (e.g. 80% default).
587 // -----------------------------------------------------------------
588 // Case 2: diamond like CFG (if-then-else):
597 // The current block is BB and edge BB->Succ is now being evaluated.
598 // Note that edge S->BB was previously already selected because
599 // prob(S->BB) > prob(S->Pred).
600 // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
601 // choose Pred, we will have a topological ordering as shown on the left
602 // in the picture below. If we choose Succ, we have the solution as shown
615 // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred)
616 // = freq(S->Pred) + freq(S->BB)
618 // If we have profile data (i.e, branch probabilities can be trusted), the
619 // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
620 // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
621 // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
622 // means the cost of topological order is greater.
623 // When profile data is not available, however, we need to be more
624 // conservative. If the branch prediction is wrong, breaking the topo-order
625 // will actually yield a layout with large cost. For this reason, we need
626 // strong biased branch at block S with Prob(S->BB) in order to select
627 // BB->Succ. This is equivalent to looking the CFG backward with backward
628 // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
631 BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
633 // Forward checking. For case 2, SuccProb will be 1.
634 if (SuccProb < HotProb) {
635 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
636 << " (prob) (CFG conflict)\n");
640 // Make sure that a hot successor doesn't have a globally more
641 // important predecessor.
642 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
643 bool BadCFGConflict = false;
645 for (MachineBasicBlock *Pred : Succ->predecessors()) {
646 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
647 (BlockFilter && !BlockFilter->count(Pred)) ||
648 BlockToChain[Pred] == &Chain)
650 // Do backward checking. For case 1, it is actually redundant check. For
651 // case 2 above, we need a backward checking to filter out edges that are
652 // not 'strongly' biased. With profile data available, the check is mostly
653 // redundant too (when threshold prob is set at 50%) unless S has more than
658 // We select edge BB->Succ if
659 // freq(BB->Succ) > freq(Succ) * HotProb
660 // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
662 // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
663 BlockFrequency PredEdgeFreq =
664 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
665 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
666 BadCFGConflict = true;
671 if (BadCFGConflict) {
672 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
673 << " (prob) (non-cold CFG conflict)\n");
680 /// \brief Select the best successor for a block.
682 /// This looks across all successors of a particular block and attempts to
683 /// select the "best" one to be the layout successor. It only considers direct
684 /// successors which also pass the block filter. It will attempt to avoid
685 /// breaking CFG structure, but cave and break such structures in the case of
686 /// very hot successor edges.
688 /// \returns The best successor block found, or null if none are viable.
690 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
692 const BlockFilterSet *BlockFilter) {
693 const BranchProbability HotProb(StaticLikelyProb, 100);
695 MachineBasicBlock *BestSucc = nullptr;
696 auto BestProb = BranchProbability::getZero();
698 SmallVector<MachineBasicBlock *, 4> Successors;
699 auto AdjustedSumProb =
700 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
702 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
703 for (MachineBasicBlock *Succ : Successors) {
704 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
705 BranchProbability SuccProb =
706 getAdjustedProbability(RealSuccProb, AdjustedSumProb);
708 // This heuristic is off by default.
709 if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
713 BlockChain &SuccChain = *BlockToChain[Succ];
714 // Skip the edge \c BB->Succ if block \c Succ has a better layout
715 // predecessor that yields lower global cost.
716 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
721 dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
723 << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
725 if (BestSucc && BestProb >= SuccProb)
733 /// \brief Select the best block from a worklist.
735 /// This looks through the provided worklist as a list of candidate basic
736 /// blocks and select the most profitable one to place. The definition of
737 /// profitable only really makes sense in the context of a loop. This returns
738 /// the most frequently visited block in the worklist, which in the case of
739 /// a loop, is the one most desirable to be physically close to the rest of the
740 /// loop body in order to improve i-cache behavior.
742 /// \returns The best block found, or null if none are viable.
743 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
744 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
745 // Once we need to walk the worklist looking for a candidate, cleanup the
746 // worklist of already placed entries.
747 // FIXME: If this shows up on profiles, it could be folded (at the cost of
748 // some code complexity) into the loop below.
749 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
750 [&](MachineBasicBlock *BB) {
751 return BlockToChain.lookup(BB) == &Chain;
755 if (WorkList.empty())
758 bool IsEHPad = WorkList[0]->isEHPad();
760 MachineBasicBlock *BestBlock = nullptr;
761 BlockFrequency BestFreq;
762 for (MachineBasicBlock *MBB : WorkList) {
763 assert(MBB->isEHPad() == IsEHPad);
765 BlockChain &SuccChain = *BlockToChain[MBB];
766 if (&SuccChain == &Chain)
769 assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
771 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
772 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
773 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
775 // For ehpad, we layout the least probable first as to avoid jumping back
776 // from least probable landingpads to more probable ones.
778 // FIXME: Using probability is probably (!) not the best way to achieve
779 // this. We should probably have a more principled approach to layout
782 // The goal is to get:
784 // +--------------------------+
786 // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume
790 // +-------------------------------------+
792 // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup
793 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
797 BestFreq = CandidateFreq;
803 /// \brief Retrieve the first unplaced basic block.
805 /// This routine is called when we are unable to use the CFG to walk through
806 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
807 /// We walk through the function's blocks in order, starting from the
808 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
809 /// re-scanning the entire sequence on repeated calls to this routine.
810 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
811 const BlockChain &PlacedChain,
812 MachineFunction::iterator &PrevUnplacedBlockIt,
813 const BlockFilterSet *BlockFilter) {
814 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
816 if (BlockFilter && !BlockFilter->count(&*I))
818 if (BlockToChain[&*I] != &PlacedChain) {
819 PrevUnplacedBlockIt = I;
820 // Now select the head of the chain to which the unplaced block belongs
821 // as the block to place. This will force the entire chain to be placed,
822 // and satisfies the requirements of merging chains.
823 return *BlockToChain[&*I]->begin();
829 void MachineBlockPlacement::fillWorkLists(
830 MachineBasicBlock *MBB,
831 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
832 const BlockFilterSet *BlockFilter = nullptr) {
833 BlockChain &Chain = *BlockToChain[MBB];
834 if (!UpdatedPreds.insert(&Chain).second)
837 assert(Chain.UnscheduledPredecessors == 0);
838 for (MachineBasicBlock *ChainBB : Chain) {
839 assert(BlockToChain[ChainBB] == &Chain);
840 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
841 if (BlockFilter && !BlockFilter->count(Pred))
843 if (BlockToChain[Pred] == &Chain)
845 ++Chain.UnscheduledPredecessors;
849 if (Chain.UnscheduledPredecessors != 0)
852 MBB = *Chain.begin();
854 EHPadWorkList.push_back(MBB);
856 BlockWorkList.push_back(MBB);
859 void MachineBlockPlacement::buildChain(
860 MachineBasicBlock *BB, BlockChain &Chain,
861 const BlockFilterSet *BlockFilter) {
862 assert(BB && "BB must not be null.\n");
863 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
864 MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
866 MachineBasicBlock *LoopHeaderBB = BB;
867 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
868 BB = *std::prev(Chain.end());
870 assert(BB && "null block found at end of chain in loop.");
871 assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
872 assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
875 // Look for the best viable successor if there is one to place immediately
877 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
879 // If an immediate successor isn't available, look for the best viable
880 // block among those we've identified as not violating the loop's CFG at
881 // this point. This won't be a fallthrough, but it will increase locality.
883 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
885 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
888 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
892 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
893 "layout successor until the CFG reduces\n");
896 // Place this block, updating the datastructures to reflect its placement.
897 BlockChain &SuccChain = *BlockToChain[BestSucc];
898 // Zero out UnscheduledPredecessors for the successor we're about to merge in case
899 // we selected a successor that didn't fit naturally into the CFG.
900 SuccChain.UnscheduledPredecessors = 0;
901 DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
902 << getBlockName(BestSucc) << "\n");
903 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
904 Chain.merge(BestSucc, &SuccChain);
905 BB = *std::prev(Chain.end());
908 DEBUG(dbgs() << "Finished forming chain for header block "
909 << getBlockName(*Chain.begin()) << "\n");
912 /// \brief Find the best loop top block for layout.
914 /// Look for a block which is strictly better than the loop header for laying
915 /// out at the top of the loop. This looks for one and only one pattern:
916 /// a latch block with no conditional exit. This block will cause a conditional
917 /// jump around it or will be the bottom of the loop if we lay it out in place,
918 /// but if it it doesn't end up at the bottom of the loop for any reason,
919 /// rotation alone won't fix it. Because such a block will always result in an
920 /// unconditional jump (for the backedge) rotating it in front of the loop
921 /// header is always profitable.
923 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
924 const BlockFilterSet &LoopBlockSet) {
925 // Check that the header hasn't been fused with a preheader block due to
926 // crazy branches. If it has, we need to start with the header at the top to
927 // prevent pulling the preheader into the loop body.
928 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
929 if (!LoopBlockSet.count(*HeaderChain.begin()))
930 return L.getHeader();
932 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
935 BlockFrequency BestPredFreq;
936 MachineBasicBlock *BestPred = nullptr;
937 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
938 if (!LoopBlockSet.count(Pred))
940 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
941 << Pred->succ_size() << " successors, ";
942 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
943 if (Pred->succ_size() > 1)
946 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
947 if (!BestPred || PredFreq > BestPredFreq ||
948 (!(PredFreq < BestPredFreq) &&
949 Pred->isLayoutSuccessor(L.getHeader()))) {
951 BestPredFreq = PredFreq;
955 // If no direct predecessor is fine, just use the loop header.
957 DEBUG(dbgs() << " final top unchanged\n");
958 return L.getHeader();
961 // Walk backwards through any straight line of predecessors.
962 while (BestPred->pred_size() == 1 &&
963 (*BestPred->pred_begin())->succ_size() == 1 &&
964 *BestPred->pred_begin() != L.getHeader())
965 BestPred = *BestPred->pred_begin();
967 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
971 /// \brief Find the best loop exiting block for layout.
973 /// This routine implements the logic to analyze the loop looking for the best
974 /// block to layout at the top of the loop. Typically this is done to maximize
975 /// fallthrough opportunities.
977 MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
978 const BlockFilterSet &LoopBlockSet) {
979 // We don't want to layout the loop linearly in all cases. If the loop header
980 // is just a normal basic block in the loop, we want to look for what block
981 // within the loop is the best one to layout at the top. However, if the loop
982 // header has be pre-merged into a chain due to predecessors not having
983 // analyzable branches, *and* the predecessor it is merged with is *not* part
984 // of the loop, rotating the header into the middle of the loop will create
985 // a non-contiguous range of blocks which is Very Bad. So start with the
986 // header and only rotate if safe.
987 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
988 if (!LoopBlockSet.count(*HeaderChain.begin()))
991 BlockFrequency BestExitEdgeFreq;
992 unsigned BestExitLoopDepth = 0;
993 MachineBasicBlock *ExitingBB = nullptr;
994 // If there are exits to outer loops, loop rotation can severely limit
995 // fallthrough opportunities unless it selects such an exit. Keep a set of
996 // blocks where rotating to exit with that block will reach an outer loop.
997 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
999 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1001 for (MachineBasicBlock *MBB : L.getBlocks()) {
1002 BlockChain &Chain = *BlockToChain[MBB];
1003 // Ensure that this block is at the end of a chain; otherwise it could be
1004 // mid-way through an inner loop or a successor of an unanalyzable branch.
1005 if (MBB != *std::prev(Chain.end()))
1008 // Now walk the successors. We need to establish whether this has a viable
1009 // exiting successor and whether it has a viable non-exiting successor.
1010 // We store the old exiting state and restore it if a viable looping
1011 // successor isn't found.
1012 MachineBasicBlock *OldExitingBB = ExitingBB;
1013 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
1014 bool HasLoopingSucc = false;
1015 for (MachineBasicBlock *Succ : MBB->successors()) {
1016 if (Succ->isEHPad())
1020 BlockChain &SuccChain = *BlockToChain[Succ];
1021 // Don't split chains, either this chain or the successor's chain.
1022 if (&Chain == &SuccChain) {
1023 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1024 << getBlockName(Succ) << " (chain conflict)\n");
1028 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
1029 if (LoopBlockSet.count(Succ)) {
1030 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
1031 << getBlockName(Succ) << " (" << SuccProb << ")\n");
1032 HasLoopingSucc = true;
1036 unsigned SuccLoopDepth = 0;
1037 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
1038 SuccLoopDepth = ExitLoop->getLoopDepth();
1039 if (ExitLoop->contains(&L))
1040 BlocksExitingToOuterLoop.insert(MBB);
1043 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1044 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
1045 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
1046 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
1047 // Note that we bias this toward an existing layout successor to retain
1048 // incoming order in the absence of better information. The exit must have
1049 // a frequency higher than the current exit before we consider breaking
1051 BranchProbability Bias(100 - ExitBlockBias, 100);
1052 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
1053 ExitEdgeFreq > BestExitEdgeFreq ||
1054 (MBB->isLayoutSuccessor(Succ) &&
1055 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
1056 BestExitEdgeFreq = ExitEdgeFreq;
1061 if (!HasLoopingSucc) {
1062 // Restore the old exiting state, no viable looping successor was found.
1063 ExitingBB = OldExitingBB;
1064 BestExitEdgeFreq = OldBestExitEdgeFreq;
1067 // Without a candidate exiting block or with only a single block in the
1068 // loop, just use the loop header to layout the loop.
1069 if (!ExitingBB || L.getNumBlocks() == 1)
1072 // Also, if we have exit blocks which lead to outer loops but didn't select
1073 // one of them as the exiting block we are rotating toward, disable loop
1074 // rotation altogether.
1075 if (!BlocksExitingToOuterLoop.empty() &&
1076 !BlocksExitingToOuterLoop.count(ExitingBB))
1079 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
1083 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
1085 /// Once we have built a chain, try to rotate it to line up the hot exit block
1086 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1087 /// branches. For example, if the loop has fallthrough into its header and out
1088 /// of its bottom already, don't rotate it.
1089 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1090 MachineBasicBlock *ExitingBB,
1091 const BlockFilterSet &LoopBlockSet) {
1095 MachineBasicBlock *Top = *LoopChain.begin();
1096 bool ViableTopFallthrough = false;
1097 for (MachineBasicBlock *Pred : Top->predecessors()) {
1098 BlockChain *PredChain = BlockToChain[Pred];
1099 if (!LoopBlockSet.count(Pred) &&
1100 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1101 ViableTopFallthrough = true;
1106 // If the header has viable fallthrough, check whether the current loop
1107 // bottom is a viable exiting block. If so, bail out as rotating will
1108 // introduce an unnecessary branch.
1109 if (ViableTopFallthrough) {
1110 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
1111 for (MachineBasicBlock *Succ : Bottom->successors()) {
1112 BlockChain *SuccChain = BlockToChain[Succ];
1113 if (!LoopBlockSet.count(Succ) &&
1114 (!SuccChain || Succ == *SuccChain->begin()))
1119 BlockChain::iterator ExitIt =
1120 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
1121 if (ExitIt == LoopChain.end())
1124 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
1127 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1129 /// With profile data, we can determine the cost in terms of missed fall through
1130 /// opportunities when rotating a loop chain and select the best rotation.
1131 /// Basically, there are three kinds of cost to consider for each rotation:
1132 /// 1. The possibly missed fall through edge (if it exists) from BB out of
1133 /// the loop to the loop header.
1134 /// 2. The possibly missed fall through edges (if they exist) from the loop
1135 /// exits to BB out of the loop.
1136 /// 3. The missed fall through edge (if it exists) from the last BB to the
1137 /// first BB in the loop chain.
1138 /// Therefore, the cost for a given rotation is the sum of costs listed above.
1139 /// We select the best rotation with the smallest cost.
1140 void MachineBlockPlacement::rotateLoopWithProfile(
1141 BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1142 auto HeaderBB = L.getHeader();
1143 auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
1144 auto RotationPos = LoopChain.end();
1146 BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1148 // A utility lambda that scales up a block frequency by dividing it by a
1149 // branch probability which is the reciprocal of the scale.
1150 auto ScaleBlockFrequency = [](BlockFrequency Freq,
1151 unsigned Scale) -> BlockFrequency {
1154 // Use operator / between BlockFrequency and BranchProbability to implement
1155 // saturating multiplication.
1156 return Freq / BranchProbability(1, Scale);
1159 // Compute the cost of the missed fall-through edge to the loop header if the
1160 // chain head is not the loop header. As we only consider natural loops with
1161 // single header, this computation can be done only once.
1162 BlockFrequency HeaderFallThroughCost(0);
1163 for (auto *Pred : HeaderBB->predecessors()) {
1164 BlockChain *PredChain = BlockToChain[Pred];
1165 if (!LoopBlockSet.count(Pred) &&
1166 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1168 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1169 auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1170 // If the predecessor has only an unconditional jump to the header, we
1171 // need to consider the cost of this jump.
1172 if (Pred->succ_size() == 1)
1173 FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1174 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1178 // Here we collect all exit blocks in the loop, and for each exit we find out
1179 // its hottest exit edge. For each loop rotation, we define the loop exit cost
1180 // as the sum of frequencies of exit edges we collect here, excluding the exit
1181 // edge from the tail of the loop chain.
1182 SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1183 for (auto BB : LoopChain) {
1184 auto LargestExitEdgeProb = BranchProbability::getZero();
1185 for (auto *Succ : BB->successors()) {
1186 BlockChain *SuccChain = BlockToChain[Succ];
1187 if (!LoopBlockSet.count(Succ) &&
1188 (!SuccChain || Succ == *SuccChain->begin())) {
1189 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1190 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
1193 if (LargestExitEdgeProb > BranchProbability::getZero()) {
1194 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
1195 ExitsWithFreq.emplace_back(BB, ExitFreq);
1199 // In this loop we iterate every block in the loop chain and calculate the
1200 // cost assuming the block is the head of the loop chain. When the loop ends,
1201 // we should have found the best candidate as the loop chain's head.
1202 for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1203 EndIter = LoopChain.end();
1204 Iter != EndIter; Iter++, TailIter++) {
1205 // TailIter is used to track the tail of the loop chain if the block we are
1206 // checking (pointed by Iter) is the head of the chain.
1207 if (TailIter == LoopChain.end())
1208 TailIter = LoopChain.begin();
1210 auto TailBB = *TailIter;
1212 // Calculate the cost by putting this BB to the top.
1213 BlockFrequency Cost = 0;
1215 // If the current BB is the loop header, we need to take into account the
1216 // cost of the missed fall through edge from outside of the loop to the
1218 if (Iter != HeaderIter)
1219 Cost += HeaderFallThroughCost;
1221 // Collect the loop exit cost by summing up frequencies of all exit edges
1222 // except the one from the chain tail.
1223 for (auto &ExitWithFreq : ExitsWithFreq)
1224 if (TailBB != ExitWithFreq.first)
1225 Cost += ExitWithFreq.second;
1227 // The cost of breaking the once fall-through edge from the tail to the top
1228 // of the loop chain. Here we need to consider three cases:
1229 // 1. If the tail node has only one successor, then we will get an
1230 // additional jmp instruction. So the cost here is (MisfetchCost +
1231 // JumpInstCost) * tail node frequency.
1232 // 2. If the tail node has two successors, then we may still get an
1233 // additional jmp instruction if the layout successor after the loop
1234 // chain is not its CFG successor. Note that the more frequently executed
1235 // jmp instruction will be put ahead of the other one. Assume the
1236 // frequency of those two branches are x and y, where x is the frequency
1237 // of the edge to the chain head, then the cost will be
1238 // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1239 // 3. If the tail node has more than two successors (this rarely happens),
1240 // we won't consider any additional cost.
1241 if (TailBB->isSuccessor(*Iter)) {
1242 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1243 if (TailBB->succ_size() == 1)
1244 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1245 MisfetchCost + JumpInstCost);
1246 else if (TailBB->succ_size() == 2) {
1247 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1248 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1249 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1250 ? TailBBFreq * TailToHeadProb.getCompl()
1252 Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1253 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1257 DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
1258 << " to the top: " << Cost.getFrequency() << "\n");
1260 if (Cost < SmallestRotationCost) {
1261 SmallestRotationCost = Cost;
1266 if (RotationPos != LoopChain.end()) {
1267 DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
1268 << " to the top\n");
1269 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1273 /// \brief Collect blocks in the given loop that are to be placed.
1275 /// When profile data is available, exclude cold blocks from the returned set;
1276 /// otherwise, collect all blocks in the loop.
1277 MachineBlockPlacement::BlockFilterSet
1278 MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
1279 BlockFilterSet LoopBlockSet;
1281 // Filter cold blocks off from LoopBlockSet when profile data is available.
1282 // Collect the sum of frequencies of incoming edges to the loop header from
1283 // outside. If we treat the loop as a super block, this is the frequency of
1284 // the loop. Then for each block in the loop, we calculate the ratio between
1285 // its frequency and the frequency of the loop block. When it is too small,
1286 // don't add it to the loop chain. If there are outer loops, then this block
1287 // will be merged into the first outer loop chain for which this block is not
1288 // cold anymore. This needs precise profile data and we only do this when
1289 // profile data is available.
1290 if (F->getFunction()->getEntryCount()) {
1291 BlockFrequency LoopFreq(0);
1292 for (auto LoopPred : L.getHeader()->predecessors())
1293 if (!L.contains(LoopPred))
1294 LoopFreq += MBFI->getBlockFreq(LoopPred) *
1295 MBPI->getEdgeProbability(LoopPred, L.getHeader());
1297 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1298 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1299 if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1301 LoopBlockSet.insert(LoopBB);
1304 LoopBlockSet.insert(L.block_begin(), L.block_end());
1306 return LoopBlockSet;
1309 /// \brief Forms basic block chains from the natural loop structures.
1311 /// These chains are designed to preserve the existing *structure* of the code
1312 /// as much as possible. We can then stitch the chains together in a way which
1313 /// both preserves the topological structure and minimizes taken conditional
1315 void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
1316 // First recurse through any nested loops, building chains for those inner
1318 for (MachineLoop *InnerLoop : L)
1319 buildLoopChains(*InnerLoop);
1321 assert(BlockWorkList.empty());
1322 assert(EHPadWorkList.empty());
1323 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
1325 // Check if we have profile data for this function. If yes, we will rotate
1326 // this loop by modeling costs more precisely which requires the profile data
1327 // for better layout.
1328 bool RotateLoopWithProfile =
1329 ForcePreciseRotationCost ||
1330 (PreciseRotationCost && F->getFunction()->getEntryCount());
1332 // First check to see if there is an obviously preferable top block for the
1333 // loop. This will default to the header, but may end up as one of the
1334 // predecessors to the header if there is one which will result in strictly
1335 // fewer branches in the loop body.
1336 // When we use profile data to rotate the loop, this is unnecessary.
1337 MachineBasicBlock *LoopTop =
1338 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1340 // If we selected just the header for the loop top, look for a potentially
1341 // profitable exit block in the event that rotating the loop can eliminate
1342 // branches by placing an exit edge at the bottom.
1343 MachineBasicBlock *ExitingBB = nullptr;
1344 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1345 ExitingBB = findBestLoopExit(L, LoopBlockSet);
1347 BlockChain &LoopChain = *BlockToChain[LoopTop];
1349 // FIXME: This is a really lame way of walking the chains in the loop: we
1350 // walk the blocks, and use a set to prevent visiting a particular chain
1352 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1353 assert(LoopChain.UnscheduledPredecessors == 0);
1354 UpdatedPreds.insert(&LoopChain);
1356 for (MachineBasicBlock *LoopBB : LoopBlockSet)
1357 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
1359 buildChain(LoopTop, LoopChain, &LoopBlockSet);
1361 if (RotateLoopWithProfile)
1362 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1364 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1367 // Crash at the end so we get all of the debugging output first.
1368 bool BadLoop = false;
1369 if (LoopChain.UnscheduledPredecessors) {
1371 dbgs() << "Loop chain contains a block without its preds placed!\n"
1372 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1373 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1375 for (MachineBasicBlock *ChainBB : LoopChain) {
1376 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
1377 if (!LoopBlockSet.erase(ChainBB)) {
1378 // We don't mark the loop as bad here because there are real situations
1379 // where this can occur. For example, with an unanalyzable fallthrough
1380 // from a loop block to a non-loop block or vice versa.
1381 dbgs() << "Loop chain contains a block not contained by the loop!\n"
1382 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1383 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1384 << " Bad block: " << getBlockName(ChainBB) << "\n";
1388 if (!LoopBlockSet.empty()) {
1390 for (MachineBasicBlock *LoopBB : LoopBlockSet)
1391 dbgs() << "Loop contains blocks never placed into a chain!\n"
1392 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
1393 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1394 << " Bad block: " << getBlockName(LoopBB) << "\n";
1396 assert(!BadLoop && "Detected problems with the placement of this loop.");
1399 BlockWorkList.clear();
1400 EHPadWorkList.clear();
1403 /// When OutlineOpitonalBranches is on, this method collects BBs that
1404 /// dominates all terminator blocks of the function \p F.
1405 void MachineBlockPlacement::collectMustExecuteBBs() {
1406 if (OutlineOptionalBranches) {
1407 // Find the nearest common dominator of all of F's terminators.
1408 MachineBasicBlock *Terminator = nullptr;
1409 for (MachineBasicBlock &MBB : *F) {
1410 if (MBB.succ_size() == 0) {
1411 if (Terminator == nullptr)
1414 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1418 // MBBs dominating this common dominator are unavoidable.
1419 UnavoidableBlocks.clear();
1420 for (MachineBasicBlock &MBB : *F) {
1421 if (MDT->dominates(&MBB, Terminator)) {
1422 UnavoidableBlocks.insert(&MBB);
1428 void MachineBlockPlacement::buildCFGChains() {
1429 // Ensure that every BB in the function has an associated chain to simplify
1430 // the assumptions of the remaining algorithm.
1431 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1432 for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1434 MachineBasicBlock *BB = &*FI;
1436 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1437 // Also, merge any blocks which we cannot reason about and must preserve
1438 // the exact fallthrough behavior for.
1441 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1442 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1445 MachineFunction::iterator NextFI = std::next(FI);
1446 MachineBasicBlock *NextBB = &*NextFI;
1447 // Ensure that the layout successor is a viable block, as we know that
1448 // fallthrough is a possibility.
1449 assert(NextFI != FE && "Can't fallthrough past the last block.");
1450 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1451 << getBlockName(BB) << " -> " << getBlockName(NextBB)
1453 Chain->merge(NextBB, nullptr);
1459 // Turned on with OutlineOptionalBranches option
1460 collectMustExecuteBBs();
1462 // Build any loop-based chains.
1463 for (MachineLoop *L : *MLI)
1464 buildLoopChains(*L);
1466 assert(BlockWorkList.empty());
1467 assert(EHPadWorkList.empty());
1469 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1470 for (MachineBasicBlock &MBB : *F)
1471 fillWorkLists(&MBB, UpdatedPreds);
1473 BlockChain &FunctionChain = *BlockToChain[&F->front()];
1474 buildChain(&F->front(), FunctionChain);
1477 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1480 // Crash at the end so we get all of the debugging output first.
1481 bool BadFunc = false;
1482 FunctionBlockSetType FunctionBlockSet;
1483 for (MachineBasicBlock &MBB : *F)
1484 FunctionBlockSet.insert(&MBB);
1486 for (MachineBasicBlock *ChainBB : FunctionChain)
1487 if (!FunctionBlockSet.erase(ChainBB)) {
1489 dbgs() << "Function chain contains a block not in the function!\n"
1490 << " Bad block: " << getBlockName(ChainBB) << "\n";
1493 if (!FunctionBlockSet.empty()) {
1495 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1496 dbgs() << "Function contains blocks never placed into a chain!\n"
1497 << " Bad block: " << getBlockName(RemainingBB) << "\n";
1499 assert(!BadFunc && "Detected problems with the block placement.");
1502 // Splice the blocks into place.
1503 MachineFunction::iterator InsertPos = F->begin();
1504 DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
1505 for (MachineBasicBlock *ChainBB : FunctionChain) {
1506 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1508 << getBlockName(ChainBB) << "\n");
1509 if (InsertPos != MachineFunction::iterator(ChainBB))
1510 F->splice(InsertPos, ChainBB);
1514 // Update the terminator of the previous block.
1515 if (ChainBB == *FunctionChain.begin())
1517 MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1519 // FIXME: It would be awesome of updateTerminator would just return rather
1520 // than assert when the branch cannot be analyzed in order to remove this
1523 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1525 // The "PrevBB" is not yet updated to reflect current code layout, so,
1526 // o. it may fall-through to a block without explicit "goto" instruction
1527 // before layout, and no longer fall-through it after layout; or
1528 // o. just opposite.
1530 // analyzeBranch() may return erroneous value for FBB when these two
1531 // situations take place. For the first scenario FBB is mistakenly set NULL;
1532 // for the 2nd scenario, the FBB, which is expected to be NULL, is
1533 // mistakenly pointing to "*BI".
1534 // Thus, if the future change needs to use FBB before the layout is set, it
1535 // has to correct FBB first by using the code similar to the following:
1537 // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1538 // PrevBB->updateTerminator();
1540 // TBB = FBB = nullptr;
1541 // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1542 // // FIXME: This should never take place.
1543 // TBB = FBB = nullptr;
1546 if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
1547 PrevBB->updateTerminator();
1550 // Fixup the last block.
1552 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1553 if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
1554 F->back().updateTerminator();
1556 BlockWorkList.clear();
1557 EHPadWorkList.clear();
1560 void MachineBlockPlacement::optimizeBranches() {
1561 BlockChain &FunctionChain = *BlockToChain[&F->front()];
1562 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1564 // Now that all the basic blocks in the chain have the proper layout,
1565 // make a final call to AnalyzeBranch with AllowModify set.
1566 // Indeed, the target may be able to optimize the branches in a way we
1567 // cannot because all branches may not be analyzable.
1568 // E.g., the target may be able to remove an unconditional branch to
1569 // a fallthrough when it occurs after predicated terminators.
1570 for (MachineBasicBlock *ChainBB : FunctionChain) {
1572 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1573 if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1574 // If PrevBB has a two-way branch, try to re-order the branches
1575 // such that we branch to the successor with higher probability first.
1576 if (TBB && !Cond.empty() && FBB &&
1577 MBPI->getEdgeProbability(ChainBB, FBB) >
1578 MBPI->getEdgeProbability(ChainBB, TBB) &&
1579 !TII->ReverseBranchCondition(Cond)) {
1580 DEBUG(dbgs() << "Reverse order of the two branches: "
1581 << getBlockName(ChainBB) << "\n");
1582 DEBUG(dbgs() << " Edge probability: "
1583 << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1584 << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1585 DebugLoc dl; // FIXME: this is nowhere
1586 TII->RemoveBranch(*ChainBB);
1587 TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1588 ChainBB->updateTerminator();
1594 void MachineBlockPlacement::alignBlocks() {
1595 // Walk through the backedges of the function now that we have fully laid out
1596 // the basic blocks and align the destination of each backedge. We don't rely
1597 // exclusively on the loop info here so that we can align backedges in
1598 // unnatural CFGs and backedges that were introduced purely because of the
1599 // loop rotations done during this layout pass.
1600 if (F->getFunction()->optForSize())
1602 BlockChain &FunctionChain = *BlockToChain[&F->front()];
1603 if (FunctionChain.begin() == FunctionChain.end())
1604 return; // Empty chain.
1606 const BranchProbability ColdProb(1, 5); // 20%
1607 BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
1608 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1609 for (MachineBasicBlock *ChainBB : FunctionChain) {
1610 if (ChainBB == *FunctionChain.begin())
1613 // Don't align non-looping basic blocks. These are unlikely to execute
1614 // enough times to matter in practice. Note that we'll still handle
1615 // unnatural CFGs inside of a natural outer loop (the common case) and
1617 MachineLoop *L = MLI->getLoopFor(ChainBB);
1621 unsigned Align = TLI->getPrefLoopAlignment(L);
1623 continue; // Don't care about loop alignment.
1625 // If the block is cold relative to the function entry don't waste space
1627 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1628 if (Freq < WeightedEntryFreq)
1631 // If the block is cold relative to its loop header, don't align it
1632 // regardless of what edges into the block exist.
1633 MachineBasicBlock *LoopHeader = L->getHeader();
1634 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1635 if (Freq < (LoopHeaderFreq * ColdProb))
1638 // Check for the existence of a non-layout predecessor which would benefit
1639 // from aligning this block.
1640 MachineBasicBlock *LayoutPred =
1641 &*std::prev(MachineFunction::iterator(ChainBB));
1643 // Force alignment if all the predecessors are jumps. We already checked
1644 // that the block isn't cold above.
1645 if (!LayoutPred->isSuccessor(ChainBB)) {
1646 ChainBB->setAlignment(Align);
1650 // Align this block if the layout predecessor's edge into this block is
1651 // cold relative to the block. When this is true, other predecessors make up
1652 // all of the hot entries into the block and thus alignment is likely to be
1654 BranchProbability LayoutProb =
1655 MBPI->getEdgeProbability(LayoutPred, ChainBB);
1656 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1657 if (LayoutEdgeFreq <= (Freq * ColdProb))
1658 ChainBB->setAlignment(Align);
1662 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
1663 if (skipFunction(*MF.getFunction()))
1666 // Check for single-block functions and skip them.
1667 if (std::next(MF.begin()) == MF.end())
1671 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1672 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1673 getAnalysis<MachineBlockFrequencyInfo>());
1674 MLI = &getAnalysis<MachineLoopInfo>();
1675 TII = MF.getSubtarget().getInstrInfo();
1676 TLI = MF.getSubtarget().getTargetLowering();
1677 MDT = &getAnalysis<MachineDominatorTree>();
1678 assert(BlockToChain.empty());
1682 // Changing the layout can create new tail merging opportunities.
1683 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1684 // TailMerge can create jump into if branches that make CFG irreducible for
1685 // HW that requires structured CFG.
1686 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
1687 PassConfig->getEnableTailMerge() &&
1688 BranchFoldPlacement;
1689 // No tail merging opportunities if the block number is less than four.
1690 if (MF.size() > 3 && EnableTailMerge) {
1691 BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
1694 if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
1695 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
1696 /*AfterBlockPlacement=*/true)) {
1697 // Redo the layout if tail merging creates/removes/moves blocks.
1698 BlockToChain.clear();
1699 ChainAllocator.DestroyAll();
1707 BlockToChain.clear();
1708 ChainAllocator.DestroyAll();
1711 // Align all of the blocks in the function to a specific alignment.
1712 for (MachineBasicBlock &MBB : MF)
1713 MBB.setAlignment(AlignAllBlock);
1714 else if (AlignAllNonFallThruBlocks) {
1715 // Align all of the blocks that have no fall-through predecessors to a
1716 // specific alignment.
1717 for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
1718 auto LayoutPred = std::prev(MBI);
1719 if (!LayoutPred->isSuccessor(&*MBI))
1720 MBI->setAlignment(AlignAllNonFallThruBlocks);
1724 // We always return true as we have no way to track whether the final order
1725 // differs from the original order.
1730 /// \brief A pass to compute block placement statistics.
1732 /// A separate pass to compute interesting statistics for evaluating block
1733 /// placement. This is separate from the actual placement pass so that they can
1734 /// be computed in the absence of any placement transformations or when using
1735 /// alternative placement strategies.
1736 class MachineBlockPlacementStats : public MachineFunctionPass {
1737 /// \brief A handle to the branch probability pass.
1738 const MachineBranchProbabilityInfo *MBPI;
1740 /// \brief A handle to the function-wide block frequency pass.
1741 const MachineBlockFrequencyInfo *MBFI;
1744 static char ID; // Pass identification, replacement for typeid
1745 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1746 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1749 bool runOnMachineFunction(MachineFunction &F) override;
1751 void getAnalysisUsage(AnalysisUsage &AU) const override {
1752 AU.addRequired<MachineBranchProbabilityInfo>();
1753 AU.addRequired<MachineBlockFrequencyInfo>();
1754 AU.setPreservesAll();
1755 MachineFunctionPass::getAnalysisUsage(AU);
1760 char MachineBlockPlacementStats::ID = 0;
1761 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1762 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1763 "Basic Block Placement Stats", false, false)
1764 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1765 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1766 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1767 "Basic Block Placement Stats", false, false)
1769 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1770 // Check for single-block functions and skip them.
1771 if (std::next(F.begin()) == F.end())
1774 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1775 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1777 for (MachineBasicBlock &MBB : F) {
1778 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1779 Statistic &NumBranches =
1780 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1781 Statistic &BranchTakenFreq =
1782 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1783 for (MachineBasicBlock *Succ : MBB.successors()) {
1784 // Skip if this successor is a fallthrough.
1785 if (MBB.isLayoutSuccessor(Succ))
1788 BlockFrequency EdgeFreq =
1789 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1791 BranchTakenFreq += EdgeFreq.getFrequency();