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/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
36 #include "llvm/CodeGen/MachineDominators.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineLoopInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetSubtargetInfo.h"
50 #define DEBUG_TYPE "block-placement"
52 STATISTIC(NumCondBranches, "Number of conditional branches");
53 STATISTIC(NumUncondBranches, "Number of uncondittional branches");
54 STATISTIC(CondBranchTakenFreq,
55 "Potential frequency of taking conditional branches");
56 STATISTIC(UncondBranchTakenFreq,
57 "Potential frequency of taking unconditional branches");
59 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
60 cl::desc("Force the alignment of all "
61 "blocks in the function."),
62 cl::init(0), cl::Hidden);
64 // FIXME: Find a good default for this flag and remove the flag.
65 static cl::opt<unsigned> ExitBlockBias(
66 "block-placement-exit-block-bias",
67 cl::desc("Block frequency percentage a loop exit block needs "
68 "over the original exit to be considered the new exit."),
69 cl::init(0), cl::Hidden);
71 static cl::opt<bool> OutlineOptionalBranches(
72 "outline-optional-branches",
73 cl::desc("Put completely optional branches, i.e. branches with a common "
74 "post dominator, out of line."),
75 cl::init(false), cl::Hidden);
77 static cl::opt<unsigned> OutlineOptionalThreshold(
78 "outline-optional-threshold",
79 cl::desc("Don't outline optional branches that are a single block with an "
80 "instruction count below this threshold"),
81 cl::init(4), cl::Hidden);
85 /// \brief Type for our function-wide basic block -> block chain mapping.
86 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
90 /// \brief A chain of blocks which will be laid out contiguously.
92 /// This is the datastructure representing a chain of consecutive blocks that
93 /// are profitable to layout together in order to maximize fallthrough
94 /// probabilities and code locality. We also can use a block chain to represent
95 /// a sequence of basic blocks which have some external (correctness)
96 /// requirement for sequential layout.
98 /// Chains can be built around a single basic block and can be merged to grow
99 /// them. They participate in a block-to-chain mapping, which is updated
100 /// automatically as chains are merged together.
102 /// \brief The sequence of blocks belonging to this chain.
104 /// This is the sequence of blocks for a particular chain. These will be laid
105 /// out in-order within the function.
106 SmallVector<MachineBasicBlock *, 4> Blocks;
108 /// \brief A handle to the function-wide basic block to block chain mapping.
110 /// This is retained in each block chain to simplify the computation of child
111 /// block chains for SCC-formation and iteration. We store the edges to child
112 /// basic blocks, and map them back to their associated chains using this
114 BlockToChainMapType &BlockToChain;
117 /// \brief Construct a new BlockChain.
119 /// This builds a new block chain representing a single basic block in the
120 /// function. It also registers itself as the chain that block participates
121 /// in with the BlockToChain mapping.
122 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
123 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
124 assert(BB && "Cannot create a chain with a null basic block");
125 BlockToChain[BB] = this;
128 /// \brief Iterator over blocks within the chain.
129 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
131 /// \brief Beginning of blocks within the chain.
132 iterator begin() { return Blocks.begin(); }
134 /// \brief End of blocks within the chain.
135 iterator end() { return Blocks.end(); }
137 /// \brief Merge a block chain into this one.
139 /// This routine merges a block chain into this one. It takes care of forming
140 /// a contiguous sequence of basic blocks, updating the edge list, and
141 /// updating the block -> chain mapping. It does not free or tear down the
142 /// old chain, but the old chain's block list is no longer valid.
143 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
145 assert(!Blocks.empty());
147 // Fast path in case we don't have a chain already.
149 assert(!BlockToChain[BB]);
150 Blocks.push_back(BB);
151 BlockToChain[BB] = this;
155 assert(BB == *Chain->begin());
156 assert(Chain->begin() != Chain->end());
158 // Update the incoming blocks to point to this chain, and add them to the
160 for (MachineBasicBlock *ChainBB : *Chain) {
161 Blocks.push_back(ChainBB);
162 assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
163 BlockToChain[ChainBB] = this;
168 /// \brief Dump the blocks in this chain.
169 LLVM_DUMP_METHOD void dump() {
170 for (MachineBasicBlock *MBB : *this)
175 /// \brief Count of predecessors within the loop currently being processed.
177 /// This count is updated at each loop we process to represent the number of
178 /// in-loop predecessors of this chain.
179 unsigned LoopPredecessors;
184 class MachineBlockPlacement : public MachineFunctionPass {
185 /// \brief A typedef for a block filter set.
186 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
188 /// \brief A handle to the branch probability pass.
189 const MachineBranchProbabilityInfo *MBPI;
191 /// \brief A handle to the function-wide block frequency pass.
192 const MachineBlockFrequencyInfo *MBFI;
194 /// \brief A handle to the loop info.
195 const MachineLoopInfo *MLI;
197 /// \brief A handle to the target's instruction info.
198 const TargetInstrInfo *TII;
200 /// \brief A handle to the target's lowering info.
201 const TargetLoweringBase *TLI;
203 /// \brief A handle to the post dominator tree.
204 MachineDominatorTree *MDT;
206 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
207 /// all terminators of the MachineFunction.
208 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
210 /// \brief Allocator and owner of BlockChain structures.
212 /// We build BlockChains lazily while processing the loop structure of
213 /// a function. To reduce malloc traffic, we allocate them using this
214 /// slab-like allocator, and destroy them after the pass completes. An
215 /// important guarantee is that this allocator produces stable pointers to
217 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
219 /// \brief Function wide BasicBlock to BlockChain mapping.
221 /// This mapping allows efficiently moving from any given basic block to the
222 /// BlockChain it participates in, if any. We use it to, among other things,
223 /// allow implicitly defining edges between chains as the existing edges
224 /// between basic blocks.
225 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
227 void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
228 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
229 const BlockFilterSet *BlockFilter = nullptr);
230 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
232 const BlockFilterSet *BlockFilter);
234 selectBestCandidateBlock(BlockChain &Chain,
235 SmallVectorImpl<MachineBasicBlock *> &WorkList,
236 const BlockFilterSet *BlockFilter);
238 getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
239 MachineFunction::iterator &PrevUnplacedBlockIt,
240 const BlockFilterSet *BlockFilter);
241 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
242 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
243 const BlockFilterSet *BlockFilter = nullptr);
244 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
245 const BlockFilterSet &LoopBlockSet);
246 MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
247 const BlockFilterSet &LoopBlockSet);
248 void buildLoopChains(MachineFunction &F, MachineLoop &L);
249 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
250 const BlockFilterSet &LoopBlockSet);
251 void buildCFGChains(MachineFunction &F);
254 static char ID; // Pass identification, replacement for typeid
255 MachineBlockPlacement() : MachineFunctionPass(ID) {
256 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
259 bool runOnMachineFunction(MachineFunction &F) override;
261 void getAnalysisUsage(AnalysisUsage &AU) const override {
262 AU.addRequired<MachineBranchProbabilityInfo>();
263 AU.addRequired<MachineBlockFrequencyInfo>();
264 AU.addRequired<MachineDominatorTree>();
265 AU.addRequired<MachineLoopInfo>();
266 MachineFunctionPass::getAnalysisUsage(AU);
271 char MachineBlockPlacement::ID = 0;
272 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
273 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
274 "Branch Probability Basic Block Placement", false, false)
275 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
276 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
277 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
278 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
279 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
280 "Branch Probability Basic Block Placement", false, false)
283 /// \brief Helper to print the name of a MBB.
285 /// Only used by debug logging.
286 static std::string getBlockName(MachineBasicBlock *BB) {
288 raw_string_ostream OS(Result);
289 OS << "BB#" << BB->getNumber();
290 OS << " (derived from LLVM BB '" << BB->getName() << "')";
295 /// \brief Helper to print the number of a MBB.
297 /// Only used by debug logging.
298 static std::string getBlockNum(MachineBasicBlock *BB) {
300 raw_string_ostream OS(Result);
301 OS << "BB#" << BB->getNumber();
307 /// \brief Mark a chain's successors as having one fewer preds.
309 /// When a chain is being merged into the "placed" chain, this routine will
310 /// quickly walk the successors of each block in the chain and mark them as
311 /// having one fewer active predecessor. It also adds any successors of this
312 /// chain which reach the zero-predecessor state to the worklist passed in.
313 void MachineBlockPlacement::markChainSuccessors(
314 BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
315 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
316 const BlockFilterSet *BlockFilter) {
317 // Walk all the blocks in this chain, marking their successors as having
318 // a predecessor placed.
319 for (MachineBasicBlock *MBB : Chain) {
320 // Add any successors for which this is the only un-placed in-loop
321 // predecessor to the worklist as a viable candidate for CFG-neutral
322 // placement. No subsequent placement of this block will violate the CFG
323 // shape, so we get to use heuristics to choose a favorable placement.
324 for (MachineBasicBlock *Succ : MBB->successors()) {
325 if (BlockFilter && !BlockFilter->count(Succ))
327 BlockChain &SuccChain = *BlockToChain[Succ];
328 // Disregard edges within a fixed chain, or edges to the loop header.
329 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
332 // This is a cross-chain edge that is within the loop, so decrement the
333 // loop predecessor count of the destination chain.
334 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
335 BlockWorkList.push_back(*SuccChain.begin());
340 /// \brief Select the best successor for a block.
342 /// This looks across all successors of a particular block and attempts to
343 /// select the "best" one to be the layout successor. It only considers direct
344 /// successors which also pass the block filter. It will attempt to avoid
345 /// breaking CFG structure, but cave and break such structures in the case of
346 /// very hot successor edges.
348 /// \returns The best successor block found, or null if none are viable.
350 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
352 const BlockFilterSet *BlockFilter) {
353 const BranchProbability HotProb(4, 5); // 80%
355 MachineBasicBlock *BestSucc = nullptr;
356 // FIXME: Due to the performance of the probability and weight routines in
357 // the MBPI analysis, we manually compute probabilities using the edge
358 // weights. This is suboptimal as it means that the somewhat subtle
359 // definition of edge weight semantics is encoded here as well. We should
360 // improve the MBPI interface to efficiently support query patterns such as
362 uint32_t BestWeight = 0;
363 uint32_t WeightScale = 0;
364 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
365 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
366 for (MachineBasicBlock *Succ : BB->successors()) {
367 if (BlockFilter && !BlockFilter->count(Succ))
369 BlockChain &SuccChain = *BlockToChain[Succ];
370 if (&SuccChain == &Chain) {
371 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Already merged!\n");
374 if (Succ != *SuccChain.begin()) {
375 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
379 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
380 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
382 // If we outline optional branches, look whether Succ is unavoidable, i.e.
383 // dominates all terminators of the MachineFunction. If it does, other
384 // successors must be optional. Don't do this for cold branches.
385 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
386 UnavoidableBlocks.count(Succ) > 0) {
387 auto HasShortOptionalBranch = [&]() {
388 for (MachineBasicBlock *Pred : Succ->predecessors()) {
389 // Check whether there is an unplaced optional branch.
390 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
391 BlockToChain[Pred] == &Chain)
393 // Check whether the optional branch has exactly one BB.
394 if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
396 // Check whether the optional branch is small.
397 if (Pred->size() < OutlineOptionalThreshold)
402 if (!HasShortOptionalBranch())
406 // Only consider successors which are either "hot", or wouldn't violate
407 // any CFG constraints.
408 if (SuccChain.LoopPredecessors != 0) {
409 if (SuccProb < HotProb) {
410 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
411 << " (prob) (CFG conflict)\n");
415 // Make sure that a hot successor doesn't have a globally more
416 // important predecessor.
417 BlockFrequency CandidateEdgeFreq =
418 MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
419 bool BadCFGConflict = false;
420 for (MachineBasicBlock *Pred : Succ->predecessors()) {
421 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
422 BlockToChain[Pred] == &Chain)
424 BlockFrequency PredEdgeFreq =
425 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
426 if (PredEdgeFreq >= CandidateEdgeFreq) {
427 BadCFGConflict = true;
431 if (BadCFGConflict) {
432 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
433 << " (prob) (non-cold CFG conflict)\n");
438 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
440 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
442 if (BestSucc && BestWeight >= SuccWeight)
445 BestWeight = SuccWeight;
450 /// \brief Select the best block from a worklist.
452 /// This looks through the provided worklist as a list of candidate basic
453 /// blocks and select the most profitable one to place. The definition of
454 /// profitable only really makes sense in the context of a loop. This returns
455 /// the most frequently visited block in the worklist, which in the case of
456 /// a loop, is the one most desirable to be physically close to the rest of the
457 /// loop body in order to improve icache behavior.
459 /// \returns The best block found, or null if none are viable.
460 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
461 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
462 const BlockFilterSet *BlockFilter) {
463 // Once we need to walk the worklist looking for a candidate, cleanup the
464 // worklist of already placed entries.
465 // FIXME: If this shows up on profiles, it could be folded (at the cost of
466 // some code complexity) into the loop below.
467 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
468 [&](MachineBasicBlock *BB) {
469 return BlockToChain.lookup(BB) == &Chain;
473 MachineBasicBlock *BestBlock = nullptr;
474 BlockFrequency BestFreq;
475 for (MachineBasicBlock *MBB : WorkList) {
476 BlockChain &SuccChain = *BlockToChain[MBB];
477 if (&SuccChain == &Chain) {
478 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> Already merged!\n");
481 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
483 BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
484 DEBUG(dbgs() << " " << getBlockName(MBB) << " -> ";
485 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
486 if (BestBlock && BestFreq >= CandidateFreq)
489 BestFreq = CandidateFreq;
494 /// \brief Retrieve the first unplaced basic block.
496 /// This routine is called when we are unable to use the CFG to walk through
497 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
498 /// We walk through the function's blocks in order, starting from the
499 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
500 /// re-scanning the entire sequence on repeated calls to this routine.
501 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
502 MachineFunction &F, const BlockChain &PlacedChain,
503 MachineFunction::iterator &PrevUnplacedBlockIt,
504 const BlockFilterSet *BlockFilter) {
505 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
507 if (BlockFilter && !BlockFilter->count(I))
509 if (BlockToChain[I] != &PlacedChain) {
510 PrevUnplacedBlockIt = I;
511 // Now select the head of the chain to which the unplaced block belongs
512 // as the block to place. This will force the entire chain to be placed,
513 // and satisfies the requirements of merging chains.
514 return *BlockToChain[I]->begin();
520 void MachineBlockPlacement::buildChain(
521 MachineBasicBlock *BB, BlockChain &Chain,
522 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
523 const BlockFilterSet *BlockFilter) {
525 assert(BlockToChain[BB] == &Chain);
526 MachineFunction &F = *BB->getParent();
527 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
529 MachineBasicBlock *LoopHeaderBB = BB;
530 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
531 BB = *std::prev(Chain.end());
534 assert(BlockToChain[BB] == &Chain);
535 assert(*std::prev(Chain.end()) == BB);
537 // Look for the best viable successor if there is one to place immediately
539 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
541 // If an immediate successor isn't available, look for the best viable
542 // block among those we've identified as not violating the loop's CFG at
543 // this point. This won't be a fallthrough, but it will increase locality.
545 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
549 getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
553 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
554 "layout successor until the CFG reduces\n");
557 // Place this block, updating the datastructures to reflect its placement.
558 BlockChain &SuccChain = *BlockToChain[BestSucc];
559 // Zero out LoopPredecessors for the successor we're about to merge in case
560 // we selected a successor that didn't fit naturally into the CFG.
561 SuccChain.LoopPredecessors = 0;
562 DEBUG(dbgs() << "Merging from " << getBlockNum(BB) << " to "
563 << getBlockNum(BestSucc) << "\n");
564 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
565 Chain.merge(BestSucc, &SuccChain);
566 BB = *std::prev(Chain.end());
569 DEBUG(dbgs() << "Finished forming chain for header block "
570 << getBlockNum(*Chain.begin()) << "\n");
573 /// \brief Find the best loop top block for layout.
575 /// Look for a block which is strictly better than the loop header for laying
576 /// out at the top of the loop. This looks for one and only one pattern:
577 /// a latch block with no conditional exit. This block will cause a conditional
578 /// jump around it or will be the bottom of the loop if we lay it out in place,
579 /// but if it it doesn't end up at the bottom of the loop for any reason,
580 /// rotation alone won't fix it. Because such a block will always result in an
581 /// unconditional jump (for the backedge) rotating it in front of the loop
582 /// header is always profitable.
584 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
585 const BlockFilterSet &LoopBlockSet) {
586 // Check that the header hasn't been fused with a preheader block due to
587 // crazy branches. If it has, we need to start with the header at the top to
588 // prevent pulling the preheader into the loop body.
589 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
590 if (!LoopBlockSet.count(*HeaderChain.begin()))
591 return L.getHeader();
593 DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
596 BlockFrequency BestPredFreq;
597 MachineBasicBlock *BestPred = nullptr;
598 for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
599 if (!LoopBlockSet.count(Pred))
601 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
602 << Pred->succ_size() << " successors, ";
603 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
604 if (Pred->succ_size() > 1)
607 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
608 if (!BestPred || PredFreq > BestPredFreq ||
609 (!(PredFreq < BestPredFreq) &&
610 Pred->isLayoutSuccessor(L.getHeader()))) {
612 BestPredFreq = PredFreq;
616 // If no direct predecessor is fine, just use the loop header.
618 return L.getHeader();
620 // Walk backwards through any straight line of predecessors.
621 while (BestPred->pred_size() == 1 &&
622 (*BestPred->pred_begin())->succ_size() == 1 &&
623 *BestPred->pred_begin() != L.getHeader())
624 BestPred = *BestPred->pred_begin();
626 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
630 /// \brief Find the best loop exiting block for layout.
632 /// This routine implements the logic to analyze the loop looking for the best
633 /// block to layout at the top of the loop. Typically this is done to maximize
634 /// fallthrough opportunities.
636 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
637 const BlockFilterSet &LoopBlockSet) {
638 // We don't want to layout the loop linearly in all cases. If the loop header
639 // is just a normal basic block in the loop, we want to look for what block
640 // within the loop is the best one to layout at the top. However, if the loop
641 // header has be pre-merged into a chain due to predecessors not having
642 // analyzable branches, *and* the predecessor it is merged with is *not* part
643 // of the loop, rotating the header into the middle of the loop will create
644 // a non-contiguous range of blocks which is Very Bad. So start with the
645 // header and only rotate if safe.
646 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
647 if (!LoopBlockSet.count(*HeaderChain.begin()))
650 BlockFrequency BestExitEdgeFreq;
651 unsigned BestExitLoopDepth = 0;
652 MachineBasicBlock *ExitingBB = nullptr;
653 // If there are exits to outer loops, loop rotation can severely limit
654 // fallthrough opportunites unless it selects such an exit. Keep a set of
655 // blocks where rotating to exit with that block will reach an outer loop.
656 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
658 DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
660 for (MachineBasicBlock *MBB : L.getBlocks()) {
661 BlockChain &Chain = *BlockToChain[MBB];
662 // Ensure that this block is at the end of a chain; otherwise it could be
663 // mid-way through an inner loop or a successor of an analyzable branch.
664 if (MBB != *std::prev(Chain.end()))
667 // Now walk the successors. We need to establish whether this has a viable
668 // exiting successor and whether it has a viable non-exiting successor.
669 // We store the old exiting state and restore it if a viable looping
670 // successor isn't found.
671 MachineBasicBlock *OldExitingBB = ExitingBB;
672 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
673 bool HasLoopingSucc = false;
674 // FIXME: Due to the performance of the probability and weight routines in
675 // the MBPI analysis, we use the internal weights and manually compute the
676 // probabilities to avoid quadratic behavior.
677 uint32_t WeightScale = 0;
678 uint32_t SumWeight = MBPI->getSumForBlock(MBB, WeightScale);
679 for (MachineBasicBlock *Succ : MBB->successors()) {
680 if (Succ->isLandingPad())
684 BlockChain &SuccChain = *BlockToChain[Succ];
685 // Don't split chains, either this chain or the successor's chain.
686 if (&Chain == &SuccChain) {
687 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
688 << getBlockName(Succ) << " (chain conflict)\n");
692 uint32_t SuccWeight = MBPI->getEdgeWeight(MBB, Succ);
693 if (LoopBlockSet.count(Succ)) {
694 DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> "
695 << getBlockName(Succ) << " (" << SuccWeight << ")\n");
696 HasLoopingSucc = true;
700 unsigned SuccLoopDepth = 0;
701 if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
702 SuccLoopDepth = ExitLoop->getLoopDepth();
703 if (ExitLoop->contains(&L))
704 BlocksExitingToOuterLoop.insert(MBB);
707 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
708 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
709 DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> "
710 << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
711 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
712 // Note that we bias this toward an existing layout successor to retain
713 // incoming order in the absence of better information. The exit must have
714 // a frequency higher than the current exit before we consider breaking
716 BranchProbability Bias(100 - ExitBlockBias, 100);
717 if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
718 ExitEdgeFreq > BestExitEdgeFreq ||
719 (MBB->isLayoutSuccessor(Succ) &&
720 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
721 BestExitEdgeFreq = ExitEdgeFreq;
726 // Restore the old exiting state, no viable looping successor was found.
727 if (!HasLoopingSucc) {
728 ExitingBB = OldExitingBB;
729 BestExitEdgeFreq = OldBestExitEdgeFreq;
733 // Without a candidate exiting block or with only a single block in the
734 // loop, just use the loop header to layout the loop.
735 if (!ExitingBB || L.getNumBlocks() == 1)
738 // Also, if we have exit blocks which lead to outer loops but didn't select
739 // one of them as the exiting block we are rotating toward, disable loop
740 // rotation altogether.
741 if (!BlocksExitingToOuterLoop.empty() &&
742 !BlocksExitingToOuterLoop.count(ExitingBB))
745 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
749 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
751 /// Once we have built a chain, try to rotate it to line up the hot exit block
752 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
753 /// branches. For example, if the loop has fallthrough into its header and out
754 /// of its bottom already, don't rotate it.
755 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
756 MachineBasicBlock *ExitingBB,
757 const BlockFilterSet &LoopBlockSet) {
761 MachineBasicBlock *Top = *LoopChain.begin();
762 bool ViableTopFallthrough = false;
763 for (MachineBasicBlock *Pred : Top->predecessors()) {
764 BlockChain *PredChain = BlockToChain[Pred];
765 if (!LoopBlockSet.count(Pred) &&
766 (!PredChain || Pred == *std::prev(PredChain->end()))) {
767 ViableTopFallthrough = true;
772 // If the header has viable fallthrough, check whether the current loop
773 // bottom is a viable exiting block. If so, bail out as rotating will
774 // introduce an unnecessary branch.
775 if (ViableTopFallthrough) {
776 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
777 for (MachineBasicBlock *Succ : Bottom->successors()) {
778 BlockChain *SuccChain = BlockToChain[Succ];
779 if (!LoopBlockSet.count(Succ) &&
780 (!SuccChain || Succ == *SuccChain->begin()))
785 BlockChain::iterator ExitIt =
786 std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
787 if (ExitIt == LoopChain.end())
790 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
793 /// \brief Forms basic block chains from the natural loop structures.
795 /// These chains are designed to preserve the existing *structure* of the code
796 /// as much as possible. We can then stitch the chains together in a way which
797 /// both preserves the topological structure and minimizes taken conditional
799 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
801 // First recurse through any nested loops, building chains for those inner
803 for (MachineLoop *InnerLoop : L)
804 buildLoopChains(F, *InnerLoop);
806 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
807 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
809 // First check to see if there is an obviously preferable top block for the
810 // loop. This will default to the header, but may end up as one of the
811 // predecessors to the header if there is one which will result in strictly
812 // fewer branches in the loop body.
813 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
815 // If we selected just the header for the loop top, look for a potentially
816 // profitable exit block in the event that rotating the loop can eliminate
817 // branches by placing an exit edge at the bottom.
818 MachineBasicBlock *ExitingBB = nullptr;
819 if (LoopTop == L.getHeader())
820 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
822 BlockChain &LoopChain = *BlockToChain[LoopTop];
824 // FIXME: This is a really lame way of walking the chains in the loop: we
825 // walk the blocks, and use a set to prevent visiting a particular chain
827 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
828 assert(LoopChain.LoopPredecessors == 0);
829 UpdatedPreds.insert(&LoopChain);
830 for (MachineBasicBlock *LoopBB : L.getBlocks()) {
831 BlockChain &Chain = *BlockToChain[LoopBB];
832 if (!UpdatedPreds.insert(&Chain).second)
835 assert(Chain.LoopPredecessors == 0);
836 for (MachineBasicBlock *ChainBB : Chain) {
837 assert(BlockToChain[ChainBB] == &Chain);
838 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
839 if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
841 ++Chain.LoopPredecessors;
845 if (Chain.LoopPredecessors == 0)
846 BlockWorkList.push_back(*Chain.begin());
849 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
850 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
853 // Crash at the end so we get all of the debugging output first.
854 bool BadLoop = false;
855 if (LoopChain.LoopPredecessors) {
857 dbgs() << "Loop chain contains a block without its preds placed!\n"
858 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
859 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
861 for (MachineBasicBlock *ChainBB : LoopChain) {
862 dbgs() << " ... " << getBlockName(ChainBB) << "\n";
863 if (!LoopBlockSet.erase(ChainBB)) {
864 // We don't mark the loop as bad here because there are real situations
865 // where this can occur. For example, with an unanalyzable fallthrough
866 // from a loop block to a non-loop block or vice versa.
867 dbgs() << "Loop chain contains a block not contained by the loop!\n"
868 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
869 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
870 << " Bad block: " << getBlockName(ChainBB) << "\n";
874 if (!LoopBlockSet.empty()) {
876 for (MachineBasicBlock *LoopBB : LoopBlockSet)
877 dbgs() << "Loop contains blocks never placed into a chain!\n"
878 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
879 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
880 << " Bad block: " << getBlockName(LoopBB) << "\n";
882 assert(!BadLoop && "Detected problems with the placement of this loop.");
886 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
887 // Ensure that every BB in the function has an associated chain to simplify
888 // the assumptions of the remaining algorithm.
889 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
890 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
891 MachineBasicBlock *BB = FI;
893 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
894 // Also, merge any blocks which we cannot reason about and must preserve
895 // the exact fallthrough behavior for.
898 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
899 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
902 MachineFunction::iterator NextFI(std::next(FI));
903 MachineBasicBlock *NextBB = NextFI;
904 // Ensure that the layout successor is a viable block, as we know that
905 // fallthrough is a possibility.
906 assert(NextFI != FE && "Can't fallthrough past the last block.");
907 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
908 << getBlockName(BB) << " -> " << getBlockName(NextBB)
910 Chain->merge(NextBB, nullptr);
916 if (OutlineOptionalBranches) {
917 // Find the nearest common dominator of all of F's terminators.
918 MachineBasicBlock *Terminator = nullptr;
919 for (MachineBasicBlock &MBB : F) {
920 if (MBB.succ_size() == 0) {
921 if (Terminator == nullptr)
924 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
928 // MBBs dominating this common dominator are unavoidable.
929 UnavoidableBlocks.clear();
930 for (MachineBasicBlock &MBB : F) {
931 if (MDT->dominates(&MBB, Terminator)) {
932 UnavoidableBlocks.insert(&MBB);
937 // Build any loop-based chains.
938 for (MachineLoop *L : *MLI)
939 buildLoopChains(F, *L);
941 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
943 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
944 for (MachineBasicBlock &MBB : F) {
945 BlockChain &Chain = *BlockToChain[&MBB];
946 if (!UpdatedPreds.insert(&Chain).second)
949 assert(Chain.LoopPredecessors == 0);
950 for (MachineBasicBlock *ChainBB : Chain) {
951 assert(BlockToChain[ChainBB] == &Chain);
952 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
953 if (BlockToChain[Pred] == &Chain)
955 ++Chain.LoopPredecessors;
959 if (Chain.LoopPredecessors == 0)
960 BlockWorkList.push_back(*Chain.begin());
963 BlockChain &FunctionChain = *BlockToChain[&F.front()];
964 buildChain(&F.front(), FunctionChain, BlockWorkList);
967 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
970 // Crash at the end so we get all of the debugging output first.
971 bool BadFunc = false;
972 FunctionBlockSetType FunctionBlockSet;
973 for (MachineBasicBlock &MBB : F)
974 FunctionBlockSet.insert(&MBB);
976 for (MachineBasicBlock *ChainBB : FunctionChain)
977 if (!FunctionBlockSet.erase(ChainBB)) {
979 dbgs() << "Function chain contains a block not in the function!\n"
980 << " Bad block: " << getBlockName(ChainBB) << "\n";
983 if (!FunctionBlockSet.empty()) {
985 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
986 dbgs() << "Function contains blocks never placed into a chain!\n"
987 << " Bad block: " << getBlockName(RemainingBB) << "\n";
989 assert(!BadFunc && "Detected problems with the block placement.");
992 // Splice the blocks into place.
993 MachineFunction::iterator InsertPos = F.begin();
994 for (MachineBasicBlock *ChainBB : FunctionChain) {
995 DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
997 << getBlockName(ChainBB) << "\n");
998 if (InsertPos != MachineFunction::iterator(ChainBB))
999 F.splice(InsertPos, ChainBB);
1003 // Update the terminator of the previous block.
1004 if (ChainBB == *FunctionChain.begin())
1006 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(ChainBB));
1008 // FIXME: It would be awesome of updateTerminator would just return rather
1009 // than assert when the branch cannot be analyzed in order to remove this
1012 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1013 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1014 // The "PrevBB" is not yet updated to reflect current code layout, so,
1015 // o. it may fall-through to a block without explict "goto" instruction
1016 // before layout, and no longer fall-through it after layout; or
1017 // o. just opposite.
1019 // AnalyzeBranch() may return erroneous value for FBB when these two
1020 // situations take place. For the first scenario FBB is mistakenly set
1021 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1022 // is mistakenly pointing to "*BI".
1024 bool needUpdateBr = true;
1025 if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1026 PrevBB->updateTerminator();
1027 needUpdateBr = false;
1029 TBB = FBB = nullptr;
1030 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1031 // FIXME: This should never take place.
1032 TBB = FBB = nullptr;
1036 // If PrevBB has a two-way branch, try to re-order the branches
1037 // such that we branch to the successor with higher weight first.
1038 if (TBB && !Cond.empty() && FBB &&
1039 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1040 !TII->ReverseBranchCondition(Cond)) {
1041 DEBUG(dbgs() << "Reverse order of the two branches: "
1042 << getBlockName(PrevBB) << "\n");
1043 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1044 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1045 DebugLoc dl; // FIXME: this is nowhere
1046 TII->RemoveBranch(*PrevBB);
1047 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1048 needUpdateBr = true;
1051 PrevBB->updateTerminator();
1055 // Fixup the last block.
1057 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1058 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1059 F.back().updateTerminator();
1061 // Walk through the backedges of the function now that we have fully laid out
1062 // the basic blocks and align the destination of each backedge. We don't rely
1063 // exclusively on the loop info here so that we can align backedges in
1064 // unnatural CFGs and backedges that were introduced purely because of the
1065 // loop rotations done during this layout pass.
1066 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1068 if (FunctionChain.begin() == FunctionChain.end())
1069 return; // Empty chain.
1071 const BranchProbability ColdProb(1, 5); // 20%
1072 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1073 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1074 for (MachineBasicBlock *ChainBB : FunctionChain) {
1075 if (ChainBB == *FunctionChain.begin())
1078 // Don't align non-looping basic blocks. These are unlikely to execute
1079 // enough times to matter in practice. Note that we'll still handle
1080 // unnatural CFGs inside of a natural outer loop (the common case) and
1082 MachineLoop *L = MLI->getLoopFor(ChainBB);
1086 unsigned Align = TLI->getPrefLoopAlignment(L);
1088 continue; // Don't care about loop alignment.
1090 // If the block is cold relative to the function entry don't waste space
1092 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1093 if (Freq < WeightedEntryFreq)
1096 // If the block is cold relative to its loop header, don't align it
1097 // regardless of what edges into the block exist.
1098 MachineBasicBlock *LoopHeader = L->getHeader();
1099 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1100 if (Freq < (LoopHeaderFreq * ColdProb))
1103 // Check for the existence of a non-layout predecessor which would benefit
1104 // from aligning this block.
1105 MachineBasicBlock *LayoutPred =
1106 &*std::prev(MachineFunction::iterator(ChainBB));
1108 // Force alignment if all the predecessors are jumps. We already checked
1109 // that the block isn't cold above.
1110 if (!LayoutPred->isSuccessor(ChainBB)) {
1111 ChainBB->setAlignment(Align);
1115 // Align this block if the layout predecessor's edge into this block is
1116 // cold relative to the block. When this is true, other predecessors make up
1117 // all of the hot entries into the block and thus alignment is likely to be
1119 BranchProbability LayoutProb =
1120 MBPI->getEdgeProbability(LayoutPred, ChainBB);
1121 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1122 if (LayoutEdgeFreq <= (Freq * ColdProb))
1123 ChainBB->setAlignment(Align);
1127 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1128 // Check for single-block functions and skip them.
1129 if (std::next(F.begin()) == F.end())
1132 if (skipOptnoneFunction(*F.getFunction()))
1135 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1136 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1137 MLI = &getAnalysis<MachineLoopInfo>();
1138 TII = F.getSubtarget().getInstrInfo();
1139 TLI = F.getSubtarget().getTargetLowering();
1140 MDT = &getAnalysis<MachineDominatorTree>();
1141 assert(BlockToChain.empty());
1145 BlockToChain.clear();
1146 ChainAllocator.DestroyAll();
1149 // Align all of the blocks in the function to a specific alignment.
1150 for (MachineBasicBlock &MBB : F)
1151 MBB.setAlignment(AlignAllBlock);
1153 // We always return true as we have no way to track whether the final order
1154 // differs from the original order.
1159 /// \brief A pass to compute block placement statistics.
1161 /// A separate pass to compute interesting statistics for evaluating block
1162 /// placement. This is separate from the actual placement pass so that they can
1163 /// be computed in the absence of any placement transformations or when using
1164 /// alternative placement strategies.
1165 class MachineBlockPlacementStats : public MachineFunctionPass {
1166 /// \brief A handle to the branch probability pass.
1167 const MachineBranchProbabilityInfo *MBPI;
1169 /// \brief A handle to the function-wide block frequency pass.
1170 const MachineBlockFrequencyInfo *MBFI;
1173 static char ID; // Pass identification, replacement for typeid
1174 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1175 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1178 bool runOnMachineFunction(MachineFunction &F) override;
1180 void getAnalysisUsage(AnalysisUsage &AU) const override {
1181 AU.addRequired<MachineBranchProbabilityInfo>();
1182 AU.addRequired<MachineBlockFrequencyInfo>();
1183 AU.setPreservesAll();
1184 MachineFunctionPass::getAnalysisUsage(AU);
1189 char MachineBlockPlacementStats::ID = 0;
1190 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1191 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1192 "Basic Block Placement Stats", false, false)
1193 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1194 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1195 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1196 "Basic Block Placement Stats", false, false)
1198 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1199 // Check for single-block functions and skip them.
1200 if (std::next(F.begin()) == F.end())
1203 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1204 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1206 for (MachineBasicBlock &MBB : F) {
1207 BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1208 Statistic &NumBranches =
1209 (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1210 Statistic &BranchTakenFreq =
1211 (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1212 for (MachineBasicBlock *Succ : MBB.successors()) {
1213 // Skip if this successor is a fallthrough.
1214 if (MBB.isLayoutSuccessor(Succ))
1217 BlockFrequency EdgeFreq =
1218 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1220 BranchTakenFreq += EdgeFreq.getFrequency();