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-placement2"
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>
66 ExitBlockBias("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);
79 /// \brief Type for our function-wide basic block -> block chain mapping.
80 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
84 /// \brief A chain of blocks which will be laid out contiguously.
86 /// This is the datastructure representing a chain of consecutive blocks that
87 /// are profitable to layout together in order to maximize fallthrough
88 /// probabilities and code locality. We also can use a block chain to represent
89 /// a sequence of basic blocks which have some external (correctness)
90 /// requirement for sequential layout.
92 /// Chains can be built around a single basic block and can be merged to grow
93 /// them. They participate in a block-to-chain mapping, which is updated
94 /// automatically as chains are merged together.
96 /// \brief The sequence of blocks belonging to this chain.
98 /// This is the sequence of blocks for a particular chain. These will be laid
99 /// out in-order within the function.
100 SmallVector<MachineBasicBlock *, 4> Blocks;
102 /// \brief A handle to the function-wide basic block to block chain mapping.
104 /// This is retained in each block chain to simplify the computation of child
105 /// block chains for SCC-formation and iteration. We store the edges to child
106 /// basic blocks, and map them back to their associated chains using this
108 BlockToChainMapType &BlockToChain;
111 /// \brief Construct a new BlockChain.
113 /// This builds a new block chain representing a single basic block in the
114 /// function. It also registers itself as the chain that block participates
115 /// in with the BlockToChain mapping.
116 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
117 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
118 assert(BB && "Cannot create a chain with a null basic block");
119 BlockToChain[BB] = this;
122 /// \brief Iterator over blocks within the chain.
123 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
125 /// \brief Beginning of blocks within the chain.
126 iterator begin() { return Blocks.begin(); }
128 /// \brief End of blocks within the chain.
129 iterator end() { return Blocks.end(); }
131 /// \brief Merge a block chain into this one.
133 /// This routine merges a block chain into this one. It takes care of forming
134 /// a contiguous sequence of basic blocks, updating the edge list, and
135 /// updating the block -> chain mapping. It does not free or tear down the
136 /// old chain, but the old chain's block list is no longer valid.
137 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
139 assert(!Blocks.empty());
141 // Fast path in case we don't have a chain already.
143 assert(!BlockToChain[BB]);
144 Blocks.push_back(BB);
145 BlockToChain[BB] = this;
149 assert(BB == *Chain->begin());
150 assert(Chain->begin() != Chain->end());
152 // Update the incoming blocks to point to this chain, and add them to the
154 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
156 Blocks.push_back(*BI);
157 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
158 BlockToChain[*BI] = this;
163 /// \brief Dump the blocks in this chain.
164 LLVM_DUMP_METHOD void dump() {
165 for (iterator I = begin(), E = end(); I != E; ++I)
170 /// \brief Count of predecessors within the loop currently being processed.
172 /// This count is updated at each loop we process to represent the number of
173 /// in-loop predecessors of this chain.
174 unsigned LoopPredecessors;
179 class MachineBlockPlacement : public MachineFunctionPass {
180 /// \brief A typedef for a block filter set.
181 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
183 /// \brief A handle to the branch probability pass.
184 const MachineBranchProbabilityInfo *MBPI;
186 /// \brief A handle to the function-wide block frequency pass.
187 const MachineBlockFrequencyInfo *MBFI;
189 /// \brief A handle to the loop info.
190 const MachineLoopInfo *MLI;
192 /// \brief A handle to the target's instruction info.
193 const TargetInstrInfo *TII;
195 /// \brief A handle to the target's lowering info.
196 const TargetLoweringBase *TLI;
198 /// \brief A handle to the post dominator tree.
199 MachineDominatorTree *MDT;
201 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
202 /// all terminators of the MachineFunction.
203 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
205 /// \brief Allocator and owner of BlockChain structures.
207 /// We build BlockChains lazily while processing the loop structure of
208 /// a function. To reduce malloc traffic, we allocate them using this
209 /// slab-like allocator, and destroy them after the pass completes. An
210 /// important guarantee is that this allocator produces stable pointers to
212 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
214 /// \brief Function wide BasicBlock to BlockChain mapping.
216 /// This mapping allows efficiently moving from any given basic block to the
217 /// BlockChain it participates in, if any. We use it to, among other things,
218 /// allow implicitly defining edges between chains as the existing edges
219 /// between basic blocks.
220 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
222 void markChainSuccessors(BlockChain &Chain,
223 MachineBasicBlock *LoopHeaderBB,
224 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
225 const BlockFilterSet *BlockFilter = nullptr);
226 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
228 const BlockFilterSet *BlockFilter);
229 MachineBasicBlock *selectBestCandidateBlock(
230 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
231 const BlockFilterSet *BlockFilter);
232 MachineBasicBlock *getFirstUnplacedBlock(
234 const BlockChain &PlacedChain,
235 MachineFunction::iterator &PrevUnplacedBlockIt,
236 const BlockFilterSet *BlockFilter);
237 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
238 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
239 const BlockFilterSet *BlockFilter = nullptr);
240 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
241 const BlockFilterSet &LoopBlockSet);
242 MachineBasicBlock *findBestLoopExit(MachineFunction &F,
244 const BlockFilterSet &LoopBlockSet);
245 void buildLoopChains(MachineFunction &F, MachineLoop &L);
246 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
247 const BlockFilterSet &LoopBlockSet);
248 void buildCFGChains(MachineFunction &F);
251 static char ID; // Pass identification, replacement for typeid
252 MachineBlockPlacement() : MachineFunctionPass(ID) {
253 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
256 bool runOnMachineFunction(MachineFunction &F) override;
258 void getAnalysisUsage(AnalysisUsage &AU) const override {
259 AU.addRequired<MachineBranchProbabilityInfo>();
260 AU.addRequired<MachineBlockFrequencyInfo>();
261 AU.addRequired<MachineDominatorTree>();
262 AU.addRequired<MachineLoopInfo>();
263 MachineFunctionPass::getAnalysisUsage(AU);
268 char MachineBlockPlacement::ID = 0;
269 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
270 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
271 "Branch Probability Basic Block Placement", false, false)
272 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
273 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
274 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
275 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
276 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
277 "Branch Probability Basic Block Placement", false, false)
280 /// \brief Helper to print the name of a MBB.
282 /// Only used by debug logging.
283 static std::string getBlockName(MachineBasicBlock *BB) {
285 raw_string_ostream OS(Result);
286 OS << "BB#" << BB->getNumber()
287 << " (derived from LLVM BB '" << BB->getName() << "')";
292 /// \brief Helper to print the number of a MBB.
294 /// Only used by debug logging.
295 static std::string getBlockNum(MachineBasicBlock *BB) {
297 raw_string_ostream OS(Result);
298 OS << "BB#" << BB->getNumber();
304 /// \brief Mark a chain's successors as having one fewer preds.
306 /// When a chain is being merged into the "placed" chain, this routine will
307 /// quickly walk the successors of each block in the chain and mark them as
308 /// having one fewer active predecessor. It also adds any successors of this
309 /// chain which reach the zero-predecessor state to the worklist passed in.
310 void MachineBlockPlacement::markChainSuccessors(
312 MachineBasicBlock *LoopHeaderBB,
313 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
314 const BlockFilterSet *BlockFilter) {
315 // Walk all the blocks in this chain, marking their successors as having
316 // a predecessor placed.
317 for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
319 // Add any successors for which this is the only un-placed in-loop
320 // predecessor to the worklist as a viable candidate for CFG-neutral
321 // placement. No subsequent placement of this block will violate the CFG
322 // shape, so we get to use heuristics to choose a favorable placement.
323 for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
324 SE = (*CBI)->succ_end();
326 if (BlockFilter && !BlockFilter->count(*SI))
328 BlockChain &SuccChain = *BlockToChain[*SI];
329 // Disregard edges within a fixed chain, or edges to the loop header.
330 if (&Chain == &SuccChain || *SI == LoopHeaderBB)
333 // This is a cross-chain edge that is within the loop, so decrement the
334 // loop predecessor count of the destination chain.
335 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
336 BlockWorkList.push_back(*SuccChain.begin());
341 /// \brief Select the best successor for a block.
343 /// This looks across all successors of a particular block and attempts to
344 /// select the "best" one to be the layout successor. It only considers direct
345 /// successors which also pass the block filter. It will attempt to avoid
346 /// breaking CFG structure, but cave and break such structures in the case of
347 /// very hot successor edges.
349 /// \returns The best successor block found, or null if none are viable.
350 MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
351 MachineBasicBlock *BB, BlockChain &Chain,
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)
389 // Only consider successors which are either "hot", or wouldn't violate
390 // any CFG constraints.
391 if (SuccChain.LoopPredecessors != 0) {
392 if (SuccProb < HotProb) {
393 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
394 << " (prob) (CFG conflict)\n");
398 // Make sure that a hot successor doesn't have a globally more
399 // important predecessor.
400 BlockFrequency CandidateEdgeFreq =
401 MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
402 bool BadCFGConflict = false;
403 for (MachineBasicBlock *Pred : Succ->predecessors()) {
404 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
405 BlockToChain[Pred] == &Chain)
407 BlockFrequency PredEdgeFreq =
408 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
409 if (PredEdgeFreq >= CandidateEdgeFreq) {
410 BadCFGConflict = true;
414 if (BadCFGConflict) {
415 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
416 << " (prob) (non-cold CFG conflict)\n");
421 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
423 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
425 if (BestSucc && BestWeight >= SuccWeight)
428 BestWeight = SuccWeight;
433 /// \brief Select the best block from a worklist.
435 /// This looks through the provided worklist as a list of candidate basic
436 /// blocks and select the most profitable one to place. The definition of
437 /// profitable only really makes sense in the context of a loop. This returns
438 /// the most frequently visited block in the worklist, which in the case of
439 /// a loop, is the one most desirable to be physically close to the rest of the
440 /// loop body in order to improve icache behavior.
442 /// \returns The best block found, or null if none are viable.
443 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
444 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
445 const BlockFilterSet *BlockFilter) {
446 // Once we need to walk the worklist looking for a candidate, cleanup the
447 // worklist of already placed entries.
448 // FIXME: If this shows up on profiles, it could be folded (at the cost of
449 // some code complexity) into the loop below.
450 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
451 [&](MachineBasicBlock *BB) {
452 return BlockToChain.lookup(BB) == &Chain;
456 MachineBasicBlock *BestBlock = nullptr;
457 BlockFrequency BestFreq;
458 for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
459 WBE = WorkList.end();
461 BlockChain &SuccChain = *BlockToChain[*WBI];
462 if (&SuccChain == &Chain) {
463 DEBUG(dbgs() << " " << getBlockName(*WBI)
464 << " -> Already merged!\n");
467 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
469 BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
470 DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> ";
471 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
472 if (BestBlock && BestFreq >= CandidateFreq)
475 BestFreq = CandidateFreq;
480 /// \brief Retrieve the first unplaced basic block.
482 /// This routine is called when we are unable to use the CFG to walk through
483 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
484 /// We walk through the function's blocks in order, starting from the
485 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
486 /// re-scanning the entire sequence on repeated calls to this routine.
487 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
488 MachineFunction &F, const BlockChain &PlacedChain,
489 MachineFunction::iterator &PrevUnplacedBlockIt,
490 const BlockFilterSet *BlockFilter) {
491 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
493 if (BlockFilter && !BlockFilter->count(I))
495 if (BlockToChain[I] != &PlacedChain) {
496 PrevUnplacedBlockIt = I;
497 // Now select the head of the chain to which the unplaced block belongs
498 // as the block to place. This will force the entire chain to be placed,
499 // and satisfies the requirements of merging chains.
500 return *BlockToChain[I]->begin();
506 void MachineBlockPlacement::buildChain(
507 MachineBasicBlock *BB, BlockChain &Chain,
508 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
509 const BlockFilterSet *BlockFilter) {
511 assert(BlockToChain[BB] == &Chain);
512 MachineFunction &F = *BB->getParent();
513 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
515 MachineBasicBlock *LoopHeaderBB = BB;
516 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
517 BB = *std::prev(Chain.end());
520 assert(BlockToChain[BB] == &Chain);
521 assert(*std::prev(Chain.end()) == BB);
523 // Look for the best viable successor if there is one to place immediately
525 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
527 // If an immediate successor isn't available, look for the best viable
528 // block among those we've identified as not violating the loop's CFG at
529 // this point. This won't be a fallthrough, but it will increase locality.
531 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
534 BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
539 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
540 "layout successor until the CFG reduces\n");
543 // Place this block, updating the datastructures to reflect its placement.
544 BlockChain &SuccChain = *BlockToChain[BestSucc];
545 // Zero out LoopPredecessors for the successor we're about to merge in case
546 // we selected a successor that didn't fit naturally into the CFG.
547 SuccChain.LoopPredecessors = 0;
548 DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
549 << " to " << getBlockNum(BestSucc) << "\n");
550 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
551 Chain.merge(BestSucc, &SuccChain);
552 BB = *std::prev(Chain.end());
555 DEBUG(dbgs() << "Finished forming chain for header block "
556 << getBlockNum(*Chain.begin()) << "\n");
559 /// \brief Find the best loop top block for layout.
561 /// Look for a block which is strictly better than the loop header for laying
562 /// out at the top of the loop. This looks for one and only one pattern:
563 /// a latch block with no conditional exit. This block will cause a conditional
564 /// jump around it or will be the bottom of the loop if we lay it out in place,
565 /// but if it it doesn't end up at the bottom of the loop for any reason,
566 /// rotation alone won't fix it. Because such a block will always result in an
567 /// unconditional jump (for the backedge) rotating it in front of the loop
568 /// header is always profitable.
570 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
571 const BlockFilterSet &LoopBlockSet) {
572 // Check that the header hasn't been fused with a preheader block due to
573 // crazy branches. If it has, we need to start with the header at the top to
574 // prevent pulling the preheader into the loop body.
575 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
576 if (!LoopBlockSet.count(*HeaderChain.begin()))
577 return L.getHeader();
579 DEBUG(dbgs() << "Finding best loop top for: "
580 << getBlockName(L.getHeader()) << "\n");
582 BlockFrequency BestPredFreq;
583 MachineBasicBlock *BestPred = nullptr;
584 for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
585 PE = L.getHeader()->pred_end();
587 MachineBasicBlock *Pred = *PI;
588 if (!LoopBlockSet.count(Pred))
590 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
591 << Pred->succ_size() << " successors, ";
592 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
593 if (Pred->succ_size() > 1)
596 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
597 if (!BestPred || PredFreq > BestPredFreq ||
598 (!(PredFreq < BestPredFreq) &&
599 Pred->isLayoutSuccessor(L.getHeader()))) {
601 BestPredFreq = PredFreq;
605 // If no direct predecessor is fine, just use the loop header.
607 return L.getHeader();
609 // Walk backwards through any straight line of predecessors.
610 while (BestPred->pred_size() == 1 &&
611 (*BestPred->pred_begin())->succ_size() == 1 &&
612 *BestPred->pred_begin() != L.getHeader())
613 BestPred = *BestPred->pred_begin();
615 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
620 /// \brief Find the best loop exiting block for layout.
622 /// This routine implements the logic to analyze the loop looking for the best
623 /// block to layout at the top of the loop. Typically this is done to maximize
624 /// fallthrough opportunities.
626 MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
628 const BlockFilterSet &LoopBlockSet) {
629 // We don't want to layout the loop linearly in all cases. If the loop header
630 // is just a normal basic block in the loop, we want to look for what block
631 // within the loop is the best one to layout at the top. However, if the loop
632 // header has be pre-merged into a chain due to predecessors not having
633 // analyzable branches, *and* the predecessor it is merged with is *not* part
634 // of the loop, rotating the header into the middle of the loop will create
635 // a non-contiguous range of blocks which is Very Bad. So start with the
636 // header and only rotate if safe.
637 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
638 if (!LoopBlockSet.count(*HeaderChain.begin()))
641 BlockFrequency BestExitEdgeFreq;
642 unsigned BestExitLoopDepth = 0;
643 MachineBasicBlock *ExitingBB = nullptr;
644 // If there are exits to outer loops, loop rotation can severely limit
645 // fallthrough opportunites unless it selects such an exit. Keep a set of
646 // blocks where rotating to exit with that block will reach an outer loop.
647 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
649 DEBUG(dbgs() << "Finding best loop exit for: "
650 << getBlockName(L.getHeader()) << "\n");
651 for (MachineLoop::block_iterator I = L.block_begin(),
654 BlockChain &Chain = *BlockToChain[*I];
655 // Ensure that this block is at the end of a chain; otherwise it could be
656 // mid-way through an inner loop or a successor of an analyzable branch.
657 if (*I != *std::prev(Chain.end()))
660 // Now walk the successors. We need to establish whether this has a viable
661 // exiting successor and whether it has a viable non-exiting successor.
662 // We store the old exiting state and restore it if a viable looping
663 // successor isn't found.
664 MachineBasicBlock *OldExitingBB = ExitingBB;
665 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
666 bool HasLoopingSucc = false;
667 // FIXME: Due to the performance of the probability and weight routines in
668 // the MBPI analysis, we use the internal weights and manually compute the
669 // probabilities to avoid quadratic behavior.
670 uint32_t WeightScale = 0;
671 uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
672 for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
673 SE = (*I)->succ_end();
675 if ((*SI)->isLandingPad())
679 BlockChain &SuccChain = *BlockToChain[*SI];
680 // Don't split chains, either this chain or the successor's chain.
681 if (&Chain == &SuccChain) {
682 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
683 << getBlockName(*SI) << " (chain conflict)\n");
687 uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
688 if (LoopBlockSet.count(*SI)) {
689 DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> "
690 << getBlockName(*SI) << " (" << SuccWeight << ")\n");
691 HasLoopingSucc = true;
695 unsigned SuccLoopDepth = 0;
696 if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
697 SuccLoopDepth = ExitLoop->getLoopDepth();
698 if (ExitLoop->contains(&L))
699 BlocksExitingToOuterLoop.insert(*I);
702 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
703 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
704 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
705 << getBlockName(*SI) << " [L:" << SuccLoopDepth
707 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
708 // Note that we bias this toward an existing layout successor to retain
709 // incoming order in the absence of better information. The exit must have
710 // a frequency higher than the current exit before we consider breaking
712 BranchProbability Bias(100 - ExitBlockBias, 100);
713 if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
714 ExitEdgeFreq > BestExitEdgeFreq ||
715 ((*I)->isLayoutSuccessor(*SI) &&
716 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
717 BestExitEdgeFreq = ExitEdgeFreq;
722 // Restore the old exiting state, no viable looping successor was found.
723 if (!HasLoopingSucc) {
724 ExitingBB = OldExitingBB;
725 BestExitEdgeFreq = OldBestExitEdgeFreq;
729 // Without a candidate exiting block or with only a single block in the
730 // loop, just use the loop header to layout the loop.
731 if (!ExitingBB || L.getNumBlocks() == 1)
734 // Also, if we have exit blocks which lead to outer loops but didn't select
735 // one of them as the exiting block we are rotating toward, disable loop
736 // rotation altogether.
737 if (!BlocksExitingToOuterLoop.empty() &&
738 !BlocksExitingToOuterLoop.count(ExitingBB))
741 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
745 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
747 /// Once we have built a chain, try to rotate it to line up the hot exit block
748 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
749 /// branches. For example, if the loop has fallthrough into its header and out
750 /// of its bottom already, don't rotate it.
751 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
752 MachineBasicBlock *ExitingBB,
753 const BlockFilterSet &LoopBlockSet) {
757 MachineBasicBlock *Top = *LoopChain.begin();
758 bool ViableTopFallthrough = false;
759 for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
760 PE = Top->pred_end();
762 BlockChain *PredChain = BlockToChain[*PI];
763 if (!LoopBlockSet.count(*PI) &&
764 (!PredChain || *PI == *std::prev(PredChain->end()))) {
765 ViableTopFallthrough = true;
770 // If the header has viable fallthrough, check whether the current loop
771 // bottom is a viable exiting block. If so, bail out as rotating will
772 // introduce an unnecessary branch.
773 if (ViableTopFallthrough) {
774 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
775 for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
776 SE = Bottom->succ_end();
778 BlockChain *SuccChain = BlockToChain[*SI];
779 if (!LoopBlockSet.count(*SI) &&
780 (!SuccChain || *SI == *SuccChain->begin()))
785 BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
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::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
804 buildLoopChains(F, **LI);
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 (MachineLoop::block_iterator BI = L.block_begin(),
833 BlockChain &Chain = *BlockToChain[*BI];
834 if (!UpdatedPreds.insert(&Chain).second)
837 assert(Chain.LoopPredecessors == 0);
838 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
840 assert(BlockToChain[*BCI] == &Chain);
841 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
842 PE = (*BCI)->pred_end();
844 if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
846 ++Chain.LoopPredecessors;
850 if (Chain.LoopPredecessors == 0)
851 BlockWorkList.push_back(*Chain.begin());
854 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
855 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
858 // Crash at the end so we get all of the debugging output first.
859 bool BadLoop = false;
860 if (LoopChain.LoopPredecessors) {
862 dbgs() << "Loop chain contains a block without its preds placed!\n"
863 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
864 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
866 for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
868 dbgs() << " ... " << getBlockName(*BCI) << "\n";
869 if (!LoopBlockSet.erase(*BCI)) {
870 // We don't mark the loop as bad here because there are real situations
871 // where this can occur. For example, with an unanalyzable fallthrough
872 // from a loop block to a non-loop block or vice versa.
873 dbgs() << "Loop chain contains a block not contained by the loop!\n"
874 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
875 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
876 << " Bad block: " << getBlockName(*BCI) << "\n";
880 if (!LoopBlockSet.empty()) {
882 for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
883 LBE = LoopBlockSet.end();
885 dbgs() << "Loop contains blocks never placed into a chain!\n"
886 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
887 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
888 << " Bad block: " << getBlockName(*LBI) << "\n";
890 assert(!BadLoop && "Detected problems with the placement of this loop.");
894 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
895 // Ensure that every BB in the function has an associated chain to simplify
896 // the assumptions of the remaining algorithm.
897 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
898 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
899 MachineBasicBlock *BB = FI;
901 = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
902 // Also, merge any blocks which we cannot reason about and must preserve
903 // the exact fallthrough behavior for.
906 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
907 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
910 MachineFunction::iterator NextFI(std::next(FI));
911 MachineBasicBlock *NextBB = NextFI;
912 // Ensure that the layout successor is a viable block, as we know that
913 // fallthrough is a possibility.
914 assert(NextFI != FE && "Can't fallthrough past the last block.");
915 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
916 << getBlockName(BB) << " -> " << getBlockName(NextBB)
918 Chain->merge(NextBB, nullptr);
924 if (OutlineOptionalBranches) {
925 // Find the nearest common dominator of all of F's terminators.
926 MachineBasicBlock *Terminator = nullptr;
927 for (MachineBasicBlock &MBB : F) {
928 if (MBB.succ_size() == 0) {
929 if (Terminator == nullptr)
932 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
936 // MBBs dominating this common dominator are unavoidable.
937 UnavoidableBlocks.clear();
938 for (MachineBasicBlock &MBB : F) {
939 if (MDT->dominates(&MBB, Terminator)) {
940 UnavoidableBlocks.insert(&MBB);
945 // Build any loop-based chains.
946 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
948 buildLoopChains(F, **LI);
950 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
952 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
953 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
954 MachineBasicBlock *BB = &*FI;
955 BlockChain &Chain = *BlockToChain[BB];
956 if (!UpdatedPreds.insert(&Chain).second)
959 assert(Chain.LoopPredecessors == 0);
960 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
962 assert(BlockToChain[*BCI] == &Chain);
963 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
964 PE = (*BCI)->pred_end();
966 if (BlockToChain[*PI] == &Chain)
968 ++Chain.LoopPredecessors;
972 if (Chain.LoopPredecessors == 0)
973 BlockWorkList.push_back(*Chain.begin());
976 BlockChain &FunctionChain = *BlockToChain[&F.front()];
977 buildChain(&F.front(), FunctionChain, BlockWorkList);
980 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
983 // Crash at the end so we get all of the debugging output first.
984 bool BadFunc = false;
985 FunctionBlockSetType FunctionBlockSet;
986 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
987 FunctionBlockSet.insert(FI);
989 for (BlockChain::iterator BCI = FunctionChain.begin(),
990 BCE = FunctionChain.end();
992 if (!FunctionBlockSet.erase(*BCI)) {
994 dbgs() << "Function chain contains a block not in the function!\n"
995 << " Bad block: " << getBlockName(*BCI) << "\n";
998 if (!FunctionBlockSet.empty()) {
1000 for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
1001 FBE = FunctionBlockSet.end();
1003 dbgs() << "Function contains blocks never placed into a chain!\n"
1004 << " Bad block: " << getBlockName(*FBI) << "\n";
1006 assert(!BadFunc && "Detected problems with the block placement.");
1009 // Splice the blocks into place.
1010 MachineFunction::iterator InsertPos = F.begin();
1011 for (BlockChain::iterator BI = FunctionChain.begin(),
1012 BE = FunctionChain.end();
1014 DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
1016 << getBlockName(*BI) << "\n");
1017 if (InsertPos != MachineFunction::iterator(*BI))
1018 F.splice(InsertPos, *BI);
1022 // Update the terminator of the previous block.
1023 if (BI == FunctionChain.begin())
1025 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
1027 // FIXME: It would be awesome of updateTerminator would just return rather
1028 // than assert when the branch cannot be analyzed in order to remove this
1031 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1032 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1033 // The "PrevBB" is not yet updated to reflect current code layout, so,
1034 // o. it may fall-through to a block without explict "goto" instruction
1035 // before layout, and no longer fall-through it after layout; or
1036 // o. just opposite.
1038 // AnalyzeBranch() may return erroneous value for FBB when these two
1039 // situations take place. For the first scenario FBB is mistakenly set
1040 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1041 // is mistakenly pointing to "*BI".
1043 bool needUpdateBr = true;
1044 if (!Cond.empty() && (!FBB || FBB == *BI)) {
1045 PrevBB->updateTerminator();
1046 needUpdateBr = false;
1048 TBB = FBB = nullptr;
1049 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1050 // FIXME: This should never take place.
1051 TBB = FBB = nullptr;
1055 // If PrevBB has a two-way branch, try to re-order the branches
1056 // such that we branch to the successor with higher weight first.
1057 if (TBB && !Cond.empty() && FBB &&
1058 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1059 !TII->ReverseBranchCondition(Cond)) {
1060 DEBUG(dbgs() << "Reverse order of the two branches: "
1061 << getBlockName(PrevBB) << "\n");
1062 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1063 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1064 DebugLoc dl; // FIXME: this is nowhere
1065 TII->RemoveBranch(*PrevBB);
1066 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1067 needUpdateBr = true;
1070 PrevBB->updateTerminator();
1074 // Fixup the last block.
1076 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1077 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1078 F.back().updateTerminator();
1080 // Walk through the backedges of the function now that we have fully laid out
1081 // the basic blocks and align the destination of each backedge. We don't rely
1082 // exclusively on the loop info here so that we can align backedges in
1083 // unnatural CFGs and backedges that were introduced purely because of the
1084 // loop rotations done during this layout pass.
1085 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1087 if (FunctionChain.begin() == FunctionChain.end())
1088 return; // Empty chain.
1090 const BranchProbability ColdProb(1, 5); // 20%
1091 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1092 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1093 for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
1094 BE = FunctionChain.end();
1096 // Don't align non-looping basic blocks. These are unlikely to execute
1097 // enough times to matter in practice. Note that we'll still handle
1098 // unnatural CFGs inside of a natural outer loop (the common case) and
1100 MachineLoop *L = MLI->getLoopFor(*BI);
1104 unsigned Align = TLI->getPrefLoopAlignment(L);
1106 continue; // Don't care about loop alignment.
1108 // If the block is cold relative to the function entry don't waste space
1110 BlockFrequency Freq = MBFI->getBlockFreq(*BI);
1111 if (Freq < WeightedEntryFreq)
1114 // If the block is cold relative to its loop header, don't align it
1115 // regardless of what edges into the block exist.
1116 MachineBasicBlock *LoopHeader = L->getHeader();
1117 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1118 if (Freq < (LoopHeaderFreq * ColdProb))
1121 // Check for the existence of a non-layout predecessor which would benefit
1122 // from aligning this block.
1123 MachineBasicBlock *LayoutPred = *std::prev(BI);
1125 // Force alignment if all the predecessors are jumps. We already checked
1126 // that the block isn't cold above.
1127 if (!LayoutPred->isSuccessor(*BI)) {
1128 (*BI)->setAlignment(Align);
1132 // Align this block if the layout predecessor's edge into this block is
1133 // cold relative to the block. When this is true, other predecessors make up
1134 // all of the hot entries into the block and thus alignment is likely to be
1136 BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
1137 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1138 if (LayoutEdgeFreq <= (Freq * ColdProb))
1139 (*BI)->setAlignment(Align);
1143 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1144 // Check for single-block functions and skip them.
1145 if (std::next(F.begin()) == F.end())
1148 if (skipOptnoneFunction(*F.getFunction()))
1151 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1152 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1153 MLI = &getAnalysis<MachineLoopInfo>();
1154 TII = F.getSubtarget().getInstrInfo();
1155 TLI = F.getSubtarget().getTargetLowering();
1156 MDT = &getAnalysis<MachineDominatorTree>();
1157 assert(BlockToChain.empty());
1161 BlockToChain.clear();
1162 ChainAllocator.DestroyAll();
1165 // Align all of the blocks in the function to a specific alignment.
1166 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
1168 FI->setAlignment(AlignAllBlock);
1170 // We always return true as we have no way to track whether the final order
1171 // differs from the original order.
1176 /// \brief A pass to compute block placement statistics.
1178 /// A separate pass to compute interesting statistics for evaluating block
1179 /// placement. This is separate from the actual placement pass so that they can
1180 /// be computed in the absence of any placement transformations or when using
1181 /// alternative placement strategies.
1182 class MachineBlockPlacementStats : public MachineFunctionPass {
1183 /// \brief A handle to the branch probability pass.
1184 const MachineBranchProbabilityInfo *MBPI;
1186 /// \brief A handle to the function-wide block frequency pass.
1187 const MachineBlockFrequencyInfo *MBFI;
1190 static char ID; // Pass identification, replacement for typeid
1191 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1192 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1195 bool runOnMachineFunction(MachineFunction &F) override;
1197 void getAnalysisUsage(AnalysisUsage &AU) const override {
1198 AU.addRequired<MachineBranchProbabilityInfo>();
1199 AU.addRequired<MachineBlockFrequencyInfo>();
1200 AU.setPreservesAll();
1201 MachineFunctionPass::getAnalysisUsage(AU);
1206 char MachineBlockPlacementStats::ID = 0;
1207 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1208 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1209 "Basic Block Placement Stats", false, false)
1210 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1211 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1212 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1213 "Basic Block Placement Stats", false, false)
1215 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1216 // Check for single-block functions and skip them.
1217 if (std::next(F.begin()) == F.end())
1220 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1221 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1223 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1224 BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
1225 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
1226 : NumUncondBranches;
1227 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
1228 : UncondBranchTakenFreq;
1229 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
1232 // Skip if this successor is a fallthrough.
1233 if (I->isLayoutSuccessor(*SI))
1236 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
1238 BranchTakenFreq += EdgeFreq.getFrequency();