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> PlaceLastSuccessor(
72 "place-last-successor",
73 cl::desc("When selecting a non-successor block, choose the last block to "
74 "have been a successor. This represents the block whose "
75 "predecessor was most recently placed."),
76 cl::init(false), cl::Hidden);
78 static cl::opt<bool> OutlineOptionalBranches(
79 "outline-optional-branches",
80 cl::desc("Put completely optional branches, i.e. branches with a common "
81 "post dominator, out of line."),
82 cl::init(false), cl::Hidden);
86 /// \brief Type for our function-wide basic block -> block chain mapping.
87 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
91 /// \brief A chain of blocks which will be laid out contiguously.
93 /// This is the datastructure representing a chain of consecutive blocks that
94 /// are profitable to layout together in order to maximize fallthrough
95 /// probabilities and code locality. We also can use a block chain to represent
96 /// a sequence of basic blocks which have some external (correctness)
97 /// requirement for sequential layout.
99 /// Chains can be built around a single basic block and can be merged to grow
100 /// them. They participate in a block-to-chain mapping, which is updated
101 /// automatically as chains are merged together.
103 /// \brief The sequence of blocks belonging to this chain.
105 /// This is the sequence of blocks for a particular chain. These will be laid
106 /// out in-order within the function.
107 SmallVector<MachineBasicBlock *, 4> Blocks;
109 /// \brief A handle to the function-wide basic block to block chain mapping.
111 /// This is retained in each block chain to simplify the computation of child
112 /// block chains for SCC-formation and iteration. We store the edges to child
113 /// basic blocks, and map them back to their associated chains using this
115 BlockToChainMapType &BlockToChain;
118 /// \brief Construct a new BlockChain.
120 /// This builds a new block chain representing a single basic block in the
121 /// function. It also registers itself as the chain that block participates
122 /// in with the BlockToChain mapping.
123 BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
124 : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
125 assert(BB && "Cannot create a chain with a null basic block");
126 BlockToChain[BB] = this;
129 /// \brief Iterator over blocks within the chain.
130 typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
132 /// \brief Beginning of blocks within the chain.
133 iterator begin() { return Blocks.begin(); }
135 /// \brief End of blocks within the chain.
136 iterator end() { return Blocks.end(); }
138 /// \brief Merge a block chain into this one.
140 /// This routine merges a block chain into this one. It takes care of forming
141 /// a contiguous sequence of basic blocks, updating the edge list, and
142 /// updating the block -> chain mapping. It does not free or tear down the
143 /// old chain, but the old chain's block list is no longer valid.
144 void merge(MachineBasicBlock *BB, BlockChain *Chain) {
146 assert(!Blocks.empty());
148 // Fast path in case we don't have a chain already.
150 assert(!BlockToChain[BB]);
151 Blocks.push_back(BB);
152 BlockToChain[BB] = this;
156 assert(BB == *Chain->begin());
157 assert(Chain->begin() != Chain->end());
159 // Update the incoming blocks to point to this chain, and add them to the
161 for (BlockChain::iterator BI = Chain->begin(), BE = Chain->end();
163 Blocks.push_back(*BI);
164 assert(BlockToChain[*BI] == Chain && "Incoming blocks not in chain");
165 BlockToChain[*BI] = this;
170 /// \brief Dump the blocks in this chain.
171 LLVM_DUMP_METHOD void dump() {
172 for (iterator I = begin(), E = end(); I != E; ++I)
177 /// \brief Count of predecessors within the loop currently being processed.
179 /// This count is updated at each loop we process to represent the number of
180 /// in-loop predecessors of this chain.
181 unsigned LoopPredecessors;
186 class MachineBlockPlacement : public MachineFunctionPass {
187 /// \brief A typedef for a block filter set.
188 typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
190 /// \brief A handle to the branch probability pass.
191 const MachineBranchProbabilityInfo *MBPI;
193 /// \brief A handle to the function-wide block frequency pass.
194 const MachineBlockFrequencyInfo *MBFI;
196 /// \brief A handle to the loop info.
197 const MachineLoopInfo *MLI;
199 /// \brief A handle to the target's instruction info.
200 const TargetInstrInfo *TII;
202 /// \brief A handle to the target's lowering info.
203 const TargetLoweringBase *TLI;
205 /// \brief A handle to the post dominator tree.
206 MachineDominatorTree *MDT;
208 /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
209 /// all terminators of the MachineFunction.
210 SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
212 /// \brief Allocator and owner of BlockChain structures.
214 /// We build BlockChains lazily while processing the loop structure of
215 /// a function. To reduce malloc traffic, we allocate them using this
216 /// slab-like allocator, and destroy them after the pass completes. An
217 /// important guarantee is that this allocator produces stable pointers to
219 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
221 /// \brief Function wide BasicBlock to BlockChain mapping.
223 /// This mapping allows efficiently moving from any given basic block to the
224 /// BlockChain it participates in, if any. We use it to, among other things,
225 /// allow implicitly defining edges between chains as the existing edges
226 /// between basic blocks.
227 DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
229 void markChainSuccessors(BlockChain &Chain,
230 MachineBasicBlock *LoopHeaderBB,
231 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
232 const BlockFilterSet *BlockFilter = nullptr);
233 MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
235 const BlockFilterSet *BlockFilter);
236 MachineBasicBlock *selectBestCandidateBlock(
237 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
238 const BlockFilterSet *BlockFilter);
239 MachineBasicBlock *getFirstUnplacedBlock(
241 const BlockChain &PlacedChain,
242 MachineFunction::iterator &PrevUnplacedBlockIt,
243 const BlockFilterSet *BlockFilter);
244 void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
245 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
246 const BlockFilterSet *BlockFilter = nullptr);
247 MachineBasicBlock *findBestLoopTop(MachineLoop &L,
248 const BlockFilterSet &LoopBlockSet);
249 MachineBasicBlock *findBestLoopExit(MachineFunction &F,
251 const BlockFilterSet &LoopBlockSet);
252 void buildLoopChains(MachineFunction &F, MachineLoop &L);
253 void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
254 const BlockFilterSet &LoopBlockSet);
255 void buildCFGChains(MachineFunction &F);
258 static char ID; // Pass identification, replacement for typeid
259 MachineBlockPlacement() : MachineFunctionPass(ID) {
260 initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
263 bool runOnMachineFunction(MachineFunction &F) override;
265 void getAnalysisUsage(AnalysisUsage &AU) const override {
266 AU.addRequired<MachineBranchProbabilityInfo>();
267 AU.addRequired<MachineBlockFrequencyInfo>();
268 AU.addRequired<MachineDominatorTree>();
269 AU.addRequired<MachineLoopInfo>();
270 MachineFunctionPass::getAnalysisUsage(AU);
275 char MachineBlockPlacement::ID = 0;
276 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
277 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement2",
278 "Branch Probability Basic Block Placement", false, false)
279 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
280 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
281 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
282 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
283 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement2",
284 "Branch Probability Basic Block Placement", false, false)
287 /// \brief Helper to print the name of a MBB.
289 /// Only used by debug logging.
290 static std::string getBlockName(MachineBasicBlock *BB) {
292 raw_string_ostream OS(Result);
293 OS << "BB#" << BB->getNumber()
294 << " (derived from LLVM BB '" << BB->getName() << "')";
299 /// \brief Helper to print the number of a MBB.
301 /// Only used by debug logging.
302 static std::string getBlockNum(MachineBasicBlock *BB) {
304 raw_string_ostream OS(Result);
305 OS << "BB#" << BB->getNumber();
311 /// \brief Mark a chain's successors as having one fewer preds.
313 /// When a chain is being merged into the "placed" chain, this routine will
314 /// quickly walk the successors of each block in the chain and mark them as
315 /// having one fewer active predecessor. It also adds any successors of this
316 /// chain which reach the zero-predecessor state to the worklist passed in.
317 void MachineBlockPlacement::markChainSuccessors(
319 MachineBasicBlock *LoopHeaderBB,
320 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
321 const BlockFilterSet *BlockFilter) {
322 // Walk all the blocks in this chain, marking their successors as having
323 // a predecessor placed.
324 for (BlockChain::iterator CBI = Chain.begin(), CBE = Chain.end();
326 // Add any successors for which this is the only un-placed in-loop
327 // predecessor to the worklist as a viable candidate for CFG-neutral
328 // placement. No subsequent placement of this block will violate the CFG
329 // shape, so we get to use heuristics to choose a favorable placement.
330 for (MachineBasicBlock::succ_iterator SI = (*CBI)->succ_begin(),
331 SE = (*CBI)->succ_end();
333 if (BlockFilter && !BlockFilter->count(*SI))
335 BlockChain &SuccChain = *BlockToChain[*SI];
336 // Disregard edges within a fixed chain, or edges to the loop header.
337 if (&Chain == &SuccChain || *SI == LoopHeaderBB)
340 // This is a cross-chain edge that is within the loop, so decrement the
341 // loop predecessor count of the destination chain.
342 if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
343 BlockWorkList.push_back(*SuccChain.begin());
348 /// \brief Select the best successor for a block.
350 /// This looks across all successors of a particular block and attempts to
351 /// select the "best" one to be the layout successor. It only considers direct
352 /// successors which also pass the block filter. It will attempt to avoid
353 /// breaking CFG structure, but cave and break such structures in the case of
354 /// very hot successor edges.
356 /// \returns The best successor block found, or null if none are viable.
357 MachineBasicBlock *MachineBlockPlacement::selectBestSuccessor(
358 MachineBasicBlock *BB, BlockChain &Chain,
359 const BlockFilterSet *BlockFilter) {
360 const BranchProbability HotProb(4, 5); // 80%
362 MachineBasicBlock *BestSucc = nullptr;
363 // FIXME: Due to the performance of the probability and weight routines in
364 // the MBPI analysis, we manually compute probabilities using the edge
365 // weights. This is suboptimal as it means that the somewhat subtle
366 // definition of edge weight semantics is encoded here as well. We should
367 // improve the MBPI interface to efficiently support query patterns such as
369 uint32_t BestWeight = 0;
370 uint32_t WeightScale = 0;
371 uint32_t SumWeight = MBPI->getSumForBlock(BB, WeightScale);
372 DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
373 for (MachineBasicBlock *Succ : BB->successors()) {
374 if (BlockFilter && !BlockFilter->count(Succ))
376 BlockChain &SuccChain = *BlockToChain[Succ];
377 if (&SuccChain == &Chain) {
378 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Already merged!\n");
381 if (Succ != *SuccChain.begin()) {
382 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n");
386 uint32_t SuccWeight = MBPI->getEdgeWeight(BB, Succ);
387 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
389 // If we outline optional branches, look whether Succ is unavoidable, i.e.
390 // dominates all terminators of the MachineFunction. If it does, other
391 // successors must be optional. Don't do this for cold branches.
392 if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
393 UnavoidableBlocks.count(Succ) > 0)
396 // Only consider successors which are either "hot", or wouldn't violate
397 // any CFG constraints.
398 if (SuccChain.LoopPredecessors != 0) {
399 if (SuccProb < HotProb) {
400 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
401 << " (prob) (CFG conflict)\n");
405 // Make sure that a hot successor doesn't have a globally more
406 // important predecessor.
407 BlockFrequency CandidateEdgeFreq =
408 MBFI->getBlockFreq(BB) * SuccProb * HotProb.getCompl();
409 bool BadCFGConflict = false;
410 for (MachineBasicBlock *Pred : Succ->predecessors()) {
411 if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
412 BlockToChain[Pred] == &Chain)
414 BlockFrequency PredEdgeFreq =
415 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
416 if (PredEdgeFreq >= CandidateEdgeFreq) {
417 BadCFGConflict = true;
421 if (BadCFGConflict) {
422 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
423 << " (prob) (non-cold CFG conflict)\n");
428 DEBUG(dbgs() << " " << getBlockName(Succ) << " -> " << SuccProb
430 << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
432 if (BestSucc && BestWeight >= SuccWeight)
435 BestWeight = SuccWeight;
440 /// \brief Select the best block from a worklist.
442 /// This looks through the provided worklist as a list of candidate basic
443 /// blocks and select the most profitable one to place. The definition of
444 /// profitable only really makes sense in the context of a loop. This returns
445 /// the most frequently visited block in the worklist, which in the case of
446 /// a loop, is the one most desirable to be physically close to the rest of the
447 /// loop body in order to improve icache behavior.
449 /// \returns The best block found, or null if none are viable.
450 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
451 BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
452 const BlockFilterSet *BlockFilter) {
453 if (PlaceLastSuccessor) {
454 // If we're just placing the last successor as the best candidate, the
455 // logic is super simple. We skip the already placed entries on the
456 // worklist and return the most recently added entry that isn't placed.
457 while (!WorkList.empty()) {
458 MachineBasicBlock *SuccBB = WorkList.pop_back_val();
459 BlockChain &SuccChain = *BlockToChain.lookup(SuccBB);
460 if (&SuccChain == &Chain) {
461 DEBUG(dbgs() << " " << getBlockName(SuccBB)
462 << " -> Already merged!\n");
465 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
472 // Once we need to walk the worklist looking for a candidate, cleanup the
473 // worklist of already placed entries.
474 // FIXME: If this shows up on profiles, it could be folded (at the cost of
475 // some code complexity) into the loop below.
476 WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
477 [&](MachineBasicBlock *BB) {
478 return BlockToChain.lookup(BB) == &Chain;
482 MachineBasicBlock *BestBlock = nullptr;
483 BlockFrequency BestFreq;
484 for (SmallVectorImpl<MachineBasicBlock *>::iterator WBI = WorkList.begin(),
485 WBE = WorkList.end();
487 BlockChain &SuccChain = *BlockToChain[*WBI];
488 if (&SuccChain == &Chain) {
489 DEBUG(dbgs() << " " << getBlockName(*WBI)
490 << " -> Already merged!\n");
493 assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
495 BlockFrequency CandidateFreq = MBFI->getBlockFreq(*WBI);
496 DEBUG(dbgs() << " " << getBlockName(*WBI) << " -> ";
497 MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
498 if (BestBlock && BestFreq >= CandidateFreq)
501 BestFreq = CandidateFreq;
506 /// \brief Retrieve the first unplaced basic block.
508 /// This routine is called when we are unable to use the CFG to walk through
509 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
510 /// We walk through the function's blocks in order, starting from the
511 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
512 /// re-scanning the entire sequence on repeated calls to this routine.
513 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
514 MachineFunction &F, const BlockChain &PlacedChain,
515 MachineFunction::iterator &PrevUnplacedBlockIt,
516 const BlockFilterSet *BlockFilter) {
517 for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
519 if (BlockFilter && !BlockFilter->count(I))
521 if (BlockToChain[I] != &PlacedChain) {
522 PrevUnplacedBlockIt = I;
523 // Now select the head of the chain to which the unplaced block belongs
524 // as the block to place. This will force the entire chain to be placed,
525 // and satisfies the requirements of merging chains.
526 return *BlockToChain[I]->begin();
532 void MachineBlockPlacement::buildChain(
533 MachineBasicBlock *BB, BlockChain &Chain,
534 SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
535 const BlockFilterSet *BlockFilter) {
537 assert(BlockToChain[BB] == &Chain);
538 MachineFunction &F = *BB->getParent();
539 MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
541 MachineBasicBlock *LoopHeaderBB = BB;
542 markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
543 BB = *std::prev(Chain.end());
546 assert(BlockToChain[BB] == &Chain);
547 assert(*std::prev(Chain.end()) == BB);
549 // Look for the best viable successor if there is one to place immediately
551 MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
553 // If an immediate successor isn't available, look for the best viable
554 // block among those we've identified as not violating the loop's CFG at
555 // this point. This won't be a fallthrough, but it will increase locality.
557 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
560 BestSucc = getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt,
565 DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
566 "layout successor until the CFG reduces\n");
569 // Place this block, updating the datastructures to reflect its placement.
570 BlockChain &SuccChain = *BlockToChain[BestSucc];
571 // Zero out LoopPredecessors for the successor we're about to merge in case
572 // we selected a successor that didn't fit naturally into the CFG.
573 SuccChain.LoopPredecessors = 0;
574 DEBUG(dbgs() << "Merging from " << getBlockNum(BB)
575 << " to " << getBlockNum(BestSucc) << "\n");
576 markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
577 Chain.merge(BestSucc, &SuccChain);
578 BB = *std::prev(Chain.end());
581 DEBUG(dbgs() << "Finished forming chain for header block "
582 << getBlockNum(*Chain.begin()) << "\n");
585 /// \brief Find the best loop top block for layout.
587 /// Look for a block which is strictly better than the loop header for laying
588 /// out at the top of the loop. This looks for one and only one pattern:
589 /// a latch block with no conditional exit. This block will cause a conditional
590 /// jump around it or will be the bottom of the loop if we lay it out in place,
591 /// but if it it doesn't end up at the bottom of the loop for any reason,
592 /// rotation alone won't fix it. Because such a block will always result in an
593 /// unconditional jump (for the backedge) rotating it in front of the loop
594 /// header is always profitable.
596 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
597 const BlockFilterSet &LoopBlockSet) {
598 // Check that the header hasn't been fused with a preheader block due to
599 // crazy branches. If it has, we need to start with the header at the top to
600 // prevent pulling the preheader into the loop body.
601 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
602 if (!LoopBlockSet.count(*HeaderChain.begin()))
603 return L.getHeader();
605 DEBUG(dbgs() << "Finding best loop top for: "
606 << getBlockName(L.getHeader()) << "\n");
608 BlockFrequency BestPredFreq;
609 MachineBasicBlock *BestPred = nullptr;
610 for (MachineBasicBlock::pred_iterator PI = L.getHeader()->pred_begin(),
611 PE = L.getHeader()->pred_end();
613 MachineBasicBlock *Pred = *PI;
614 if (!LoopBlockSet.count(Pred))
616 DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", "
617 << Pred->succ_size() << " successors, ";
618 MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
619 if (Pred->succ_size() > 1)
622 BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
623 if (!BestPred || PredFreq > BestPredFreq ||
624 (!(PredFreq < BestPredFreq) &&
625 Pred->isLayoutSuccessor(L.getHeader()))) {
627 BestPredFreq = PredFreq;
631 // If no direct predecessor is fine, just use the loop header.
633 return L.getHeader();
635 // Walk backwards through any straight line of predecessors.
636 while (BestPred->pred_size() == 1 &&
637 (*BestPred->pred_begin())->succ_size() == 1 &&
638 *BestPred->pred_begin() != L.getHeader())
639 BestPred = *BestPred->pred_begin();
641 DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n");
646 /// \brief Find the best loop exiting block for layout.
648 /// This routine implements the logic to analyze the loop looking for the best
649 /// block to layout at the top of the loop. Typically this is done to maximize
650 /// fallthrough opportunities.
652 MachineBlockPlacement::findBestLoopExit(MachineFunction &F,
654 const BlockFilterSet &LoopBlockSet) {
655 // We don't want to layout the loop linearly in all cases. If the loop header
656 // is just a normal basic block in the loop, we want to look for what block
657 // within the loop is the best one to layout at the top. However, if the loop
658 // header has be pre-merged into a chain due to predecessors not having
659 // analyzable branches, *and* the predecessor it is merged with is *not* part
660 // of the loop, rotating the header into the middle of the loop will create
661 // a non-contiguous range of blocks which is Very Bad. So start with the
662 // header and only rotate if safe.
663 BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
664 if (!LoopBlockSet.count(*HeaderChain.begin()))
667 BlockFrequency BestExitEdgeFreq;
668 unsigned BestExitLoopDepth = 0;
669 MachineBasicBlock *ExitingBB = nullptr;
670 // If there are exits to outer loops, loop rotation can severely limit
671 // fallthrough opportunites unless it selects such an exit. Keep a set of
672 // blocks where rotating to exit with that block will reach an outer loop.
673 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
675 DEBUG(dbgs() << "Finding best loop exit for: "
676 << getBlockName(L.getHeader()) << "\n");
677 for (MachineLoop::block_iterator I = L.block_begin(),
680 BlockChain &Chain = *BlockToChain[*I];
681 // Ensure that this block is at the end of a chain; otherwise it could be
682 // mid-way through an inner loop or a successor of an analyzable branch.
683 if (*I != *std::prev(Chain.end()))
686 // Now walk the successors. We need to establish whether this has a viable
687 // exiting successor and whether it has a viable non-exiting successor.
688 // We store the old exiting state and restore it if a viable looping
689 // successor isn't found.
690 MachineBasicBlock *OldExitingBB = ExitingBB;
691 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
692 bool HasLoopingSucc = false;
693 // FIXME: Due to the performance of the probability and weight routines in
694 // the MBPI analysis, we use the internal weights and manually compute the
695 // probabilities to avoid quadratic behavior.
696 uint32_t WeightScale = 0;
697 uint32_t SumWeight = MBPI->getSumForBlock(*I, WeightScale);
698 for (MachineBasicBlock::succ_iterator SI = (*I)->succ_begin(),
699 SE = (*I)->succ_end();
701 if ((*SI)->isLandingPad())
705 BlockChain &SuccChain = *BlockToChain[*SI];
706 // Don't split chains, either this chain or the successor's chain.
707 if (&Chain == &SuccChain) {
708 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
709 << getBlockName(*SI) << " (chain conflict)\n");
713 uint32_t SuccWeight = MBPI->getEdgeWeight(*I, *SI);
714 if (LoopBlockSet.count(*SI)) {
715 DEBUG(dbgs() << " looping: " << getBlockName(*I) << " -> "
716 << getBlockName(*SI) << " (" << SuccWeight << ")\n");
717 HasLoopingSucc = true;
721 unsigned SuccLoopDepth = 0;
722 if (MachineLoop *ExitLoop = MLI->getLoopFor(*SI)) {
723 SuccLoopDepth = ExitLoop->getLoopDepth();
724 if (ExitLoop->contains(&L))
725 BlocksExitingToOuterLoop.insert(*I);
728 BranchProbability SuccProb(SuccWeight / WeightScale, SumWeight);
729 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(*I) * SuccProb;
730 DEBUG(dbgs() << " exiting: " << getBlockName(*I) << " -> "
731 << getBlockName(*SI) << " [L:" << SuccLoopDepth
733 MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
734 // Note that we bias this toward an existing layout successor to retain
735 // incoming order in the absence of better information. The exit must have
736 // a frequency higher than the current exit before we consider breaking
738 BranchProbability Bias(100 - ExitBlockBias, 100);
739 if (!ExitingBB || BestExitLoopDepth < SuccLoopDepth ||
740 ExitEdgeFreq > BestExitEdgeFreq ||
741 ((*I)->isLayoutSuccessor(*SI) &&
742 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
743 BestExitEdgeFreq = ExitEdgeFreq;
748 // Restore the old exiting state, no viable looping successor was found.
749 if (!HasLoopingSucc) {
750 ExitingBB = OldExitingBB;
751 BestExitEdgeFreq = OldBestExitEdgeFreq;
755 // Without a candidate exiting block or with only a single block in the
756 // loop, just use the loop header to layout the loop.
757 if (!ExitingBB || L.getNumBlocks() == 1)
760 // Also, if we have exit blocks which lead to outer loops but didn't select
761 // one of them as the exiting block we are rotating toward, disable loop
762 // rotation altogether.
763 if (!BlocksExitingToOuterLoop.empty() &&
764 !BlocksExitingToOuterLoop.count(ExitingBB))
767 DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n");
771 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
773 /// Once we have built a chain, try to rotate it to line up the hot exit block
774 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
775 /// branches. For example, if the loop has fallthrough into its header and out
776 /// of its bottom already, don't rotate it.
777 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
778 MachineBasicBlock *ExitingBB,
779 const BlockFilterSet &LoopBlockSet) {
783 MachineBasicBlock *Top = *LoopChain.begin();
784 bool ViableTopFallthrough = false;
785 for (MachineBasicBlock::pred_iterator PI = Top->pred_begin(),
786 PE = Top->pred_end();
788 BlockChain *PredChain = BlockToChain[*PI];
789 if (!LoopBlockSet.count(*PI) &&
790 (!PredChain || *PI == *std::prev(PredChain->end()))) {
791 ViableTopFallthrough = true;
796 // If the header has viable fallthrough, check whether the current loop
797 // bottom is a viable exiting block. If so, bail out as rotating will
798 // introduce an unnecessary branch.
799 if (ViableTopFallthrough) {
800 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
801 for (MachineBasicBlock::succ_iterator SI = Bottom->succ_begin(),
802 SE = Bottom->succ_end();
804 BlockChain *SuccChain = BlockToChain[*SI];
805 if (!LoopBlockSet.count(*SI) &&
806 (!SuccChain || *SI == *SuccChain->begin()))
811 BlockChain::iterator ExitIt = std::find(LoopChain.begin(), LoopChain.end(),
813 if (ExitIt == LoopChain.end())
816 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
819 /// \brief Forms basic block chains from the natural loop structures.
821 /// These chains are designed to preserve the existing *structure* of the code
822 /// as much as possible. We can then stitch the chains together in a way which
823 /// both preserves the topological structure and minimizes taken conditional
825 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
827 // First recurse through any nested loops, building chains for those inner
829 for (MachineLoop::iterator LI = L.begin(), LE = L.end(); LI != LE; ++LI)
830 buildLoopChains(F, **LI);
832 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
833 BlockFilterSet LoopBlockSet(L.block_begin(), L.block_end());
835 // First check to see if there is an obviously preferable top block for the
836 // loop. This will default to the header, but may end up as one of the
837 // predecessors to the header if there is one which will result in strictly
838 // fewer branches in the loop body.
839 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
841 // If we selected just the header for the loop top, look for a potentially
842 // profitable exit block in the event that rotating the loop can eliminate
843 // branches by placing an exit edge at the bottom.
844 MachineBasicBlock *ExitingBB = nullptr;
845 if (LoopTop == L.getHeader())
846 ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
848 BlockChain &LoopChain = *BlockToChain[LoopTop];
850 // FIXME: This is a really lame way of walking the chains in the loop: we
851 // walk the blocks, and use a set to prevent visiting a particular chain
853 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
854 assert(LoopChain.LoopPredecessors == 0);
855 UpdatedPreds.insert(&LoopChain);
856 for (MachineLoop::block_iterator BI = L.block_begin(),
859 BlockChain &Chain = *BlockToChain[*BI];
860 if (!UpdatedPreds.insert(&Chain).second)
863 assert(Chain.LoopPredecessors == 0);
864 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
866 assert(BlockToChain[*BCI] == &Chain);
867 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
868 PE = (*BCI)->pred_end();
870 if (BlockToChain[*PI] == &Chain || !LoopBlockSet.count(*PI))
872 ++Chain.LoopPredecessors;
876 if (Chain.LoopPredecessors == 0)
877 BlockWorkList.push_back(*Chain.begin());
880 buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
881 rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
884 // Crash at the end so we get all of the debugging output first.
885 bool BadLoop = false;
886 if (LoopChain.LoopPredecessors) {
888 dbgs() << "Loop chain contains a block without its preds placed!\n"
889 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
890 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
892 for (BlockChain::iterator BCI = LoopChain.begin(), BCE = LoopChain.end();
894 dbgs() << " ... " << getBlockName(*BCI) << "\n";
895 if (!LoopBlockSet.erase(*BCI)) {
896 // We don't mark the loop as bad here because there are real situations
897 // where this can occur. For example, with an unanalyzable fallthrough
898 // from a loop block to a non-loop block or vice versa.
899 dbgs() << "Loop chain contains a block not contained by the loop!\n"
900 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
901 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
902 << " Bad block: " << getBlockName(*BCI) << "\n";
906 if (!LoopBlockSet.empty()) {
908 for (BlockFilterSet::iterator LBI = LoopBlockSet.begin(),
909 LBE = LoopBlockSet.end();
911 dbgs() << "Loop contains blocks never placed into a chain!\n"
912 << " Loop header: " << getBlockName(*L.block_begin()) << "\n"
913 << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
914 << " Bad block: " << getBlockName(*LBI) << "\n";
916 assert(!BadLoop && "Detected problems with the placement of this loop.");
920 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
921 // Ensure that every BB in the function has an associated chain to simplify
922 // the assumptions of the remaining algorithm.
923 SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
924 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
925 MachineBasicBlock *BB = FI;
927 = new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
928 // Also, merge any blocks which we cannot reason about and must preserve
929 // the exact fallthrough behavior for.
932 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
933 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
936 MachineFunction::iterator NextFI(std::next(FI));
937 MachineBasicBlock *NextBB = NextFI;
938 // Ensure that the layout successor is a viable block, as we know that
939 // fallthrough is a possibility.
940 assert(NextFI != FE && "Can't fallthrough past the last block.");
941 DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
942 << getBlockName(BB) << " -> " << getBlockName(NextBB)
944 Chain->merge(NextBB, nullptr);
950 if (OutlineOptionalBranches) {
951 // Find the nearest common dominator of all of F's terminators.
952 MachineBasicBlock *Terminator = nullptr;
953 for (MachineBasicBlock &MBB : F) {
954 if (MBB.succ_size() == 0) {
955 if (Terminator == nullptr)
958 Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
962 // MBBs dominating this common dominator are unavoidable.
963 UnavoidableBlocks.clear();
964 for (MachineBasicBlock &MBB : F) {
965 if (MDT->dominates(&MBB, Terminator)) {
966 UnavoidableBlocks.insert(&MBB);
971 // Build any loop-based chains.
972 for (MachineLoopInfo::iterator LI = MLI->begin(), LE = MLI->end(); LI != LE;
974 buildLoopChains(F, **LI);
976 SmallVector<MachineBasicBlock *, 16> BlockWorkList;
978 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
979 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
980 MachineBasicBlock *BB = &*FI;
981 BlockChain &Chain = *BlockToChain[BB];
982 if (!UpdatedPreds.insert(&Chain).second)
985 assert(Chain.LoopPredecessors == 0);
986 for (BlockChain::iterator BCI = Chain.begin(), BCE = Chain.end();
988 assert(BlockToChain[*BCI] == &Chain);
989 for (MachineBasicBlock::pred_iterator PI = (*BCI)->pred_begin(),
990 PE = (*BCI)->pred_end();
992 if (BlockToChain[*PI] == &Chain)
994 ++Chain.LoopPredecessors;
998 if (Chain.LoopPredecessors == 0)
999 BlockWorkList.push_back(*Chain.begin());
1002 BlockChain &FunctionChain = *BlockToChain[&F.front()];
1003 buildChain(&F.front(), FunctionChain, BlockWorkList);
1006 typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1009 // Crash at the end so we get all of the debugging output first.
1010 bool BadFunc = false;
1011 FunctionBlockSetType FunctionBlockSet;
1012 for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
1013 FunctionBlockSet.insert(FI);
1015 for (BlockChain::iterator BCI = FunctionChain.begin(),
1016 BCE = FunctionChain.end();
1018 if (!FunctionBlockSet.erase(*BCI)) {
1020 dbgs() << "Function chain contains a block not in the function!\n"
1021 << " Bad block: " << getBlockName(*BCI) << "\n";
1024 if (!FunctionBlockSet.empty()) {
1026 for (FunctionBlockSetType::iterator FBI = FunctionBlockSet.begin(),
1027 FBE = FunctionBlockSet.end();
1029 dbgs() << "Function contains blocks never placed into a chain!\n"
1030 << " Bad block: " << getBlockName(*FBI) << "\n";
1032 assert(!BadFunc && "Detected problems with the block placement.");
1035 // Splice the blocks into place.
1036 MachineFunction::iterator InsertPos = F.begin();
1037 for (BlockChain::iterator BI = FunctionChain.begin(),
1038 BE = FunctionChain.end();
1040 DEBUG(dbgs() << (BI == FunctionChain.begin() ? "Placing chain "
1042 << getBlockName(*BI) << "\n");
1043 if (InsertPos != MachineFunction::iterator(*BI))
1044 F.splice(InsertPos, *BI);
1048 // Update the terminator of the previous block.
1049 if (BI == FunctionChain.begin())
1051 MachineBasicBlock *PrevBB = std::prev(MachineFunction::iterator(*BI));
1053 // FIXME: It would be awesome of updateTerminator would just return rather
1054 // than assert when the branch cannot be analyzed in order to remove this
1057 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1058 if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1059 // The "PrevBB" is not yet updated to reflect current code layout, so,
1060 // o. it may fall-through to a block without explict "goto" instruction
1061 // before layout, and no longer fall-through it after layout; or
1062 // o. just opposite.
1064 // AnalyzeBranch() may return erroneous value for FBB when these two
1065 // situations take place. For the first scenario FBB is mistakenly set
1066 // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1067 // is mistakenly pointing to "*BI".
1069 bool needUpdateBr = true;
1070 if (!Cond.empty() && (!FBB || FBB == *BI)) {
1071 PrevBB->updateTerminator();
1072 needUpdateBr = false;
1074 TBB = FBB = nullptr;
1075 if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1076 // FIXME: This should never take place.
1077 TBB = FBB = nullptr;
1081 // If PrevBB has a two-way branch, try to re-order the branches
1082 // such that we branch to the successor with higher weight first.
1083 if (TBB && !Cond.empty() && FBB &&
1084 MBPI->getEdgeWeight(PrevBB, FBB) > MBPI->getEdgeWeight(PrevBB, TBB) &&
1085 !TII->ReverseBranchCondition(Cond)) {
1086 DEBUG(dbgs() << "Reverse order of the two branches: "
1087 << getBlockName(PrevBB) << "\n");
1088 DEBUG(dbgs() << " Edge weight: " << MBPI->getEdgeWeight(PrevBB, FBB)
1089 << " vs " << MBPI->getEdgeWeight(PrevBB, TBB) << "\n");
1090 DebugLoc dl; // FIXME: this is nowhere
1091 TII->RemoveBranch(*PrevBB);
1092 TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1093 needUpdateBr = true;
1096 PrevBB->updateTerminator();
1100 // Fixup the last block.
1102 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1103 if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1104 F.back().updateTerminator();
1106 // Walk through the backedges of the function now that we have fully laid out
1107 // the basic blocks and align the destination of each backedge. We don't rely
1108 // exclusively on the loop info here so that we can align backedges in
1109 // unnatural CFGs and backedges that were introduced purely because of the
1110 // loop rotations done during this layout pass.
1111 if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1113 if (FunctionChain.begin() == FunctionChain.end())
1114 return; // Empty chain.
1116 const BranchProbability ColdProb(1, 5); // 20%
1117 BlockFrequency EntryFreq = MBFI->getBlockFreq(F.begin());
1118 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1119 for (BlockChain::iterator BI = std::next(FunctionChain.begin()),
1120 BE = FunctionChain.end();
1122 // Don't align non-looping basic blocks. These are unlikely to execute
1123 // enough times to matter in practice. Note that we'll still handle
1124 // unnatural CFGs inside of a natural outer loop (the common case) and
1126 MachineLoop *L = MLI->getLoopFor(*BI);
1130 unsigned Align = TLI->getPrefLoopAlignment(L);
1132 continue; // Don't care about loop alignment.
1134 // If the block is cold relative to the function entry don't waste space
1136 BlockFrequency Freq = MBFI->getBlockFreq(*BI);
1137 if (Freq < WeightedEntryFreq)
1140 // If the block is cold relative to its loop header, don't align it
1141 // regardless of what edges into the block exist.
1142 MachineBasicBlock *LoopHeader = L->getHeader();
1143 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1144 if (Freq < (LoopHeaderFreq * ColdProb))
1147 // Check for the existence of a non-layout predecessor which would benefit
1148 // from aligning this block.
1149 MachineBasicBlock *LayoutPred = *std::prev(BI);
1151 // Force alignment if all the predecessors are jumps. We already checked
1152 // that the block isn't cold above.
1153 if (!LayoutPred->isSuccessor(*BI)) {
1154 (*BI)->setAlignment(Align);
1158 // Align this block if the layout predecessor's edge into this block is
1159 // cold relative to the block. When this is true, other predecessors make up
1160 // all of the hot entries into the block and thus alignment is likely to be
1162 BranchProbability LayoutProb = MBPI->getEdgeProbability(LayoutPred, *BI);
1163 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1164 if (LayoutEdgeFreq <= (Freq * ColdProb))
1165 (*BI)->setAlignment(Align);
1169 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1170 // Check for single-block functions and skip them.
1171 if (std::next(F.begin()) == F.end())
1174 if (skipOptnoneFunction(*F.getFunction()))
1177 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1178 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1179 MLI = &getAnalysis<MachineLoopInfo>();
1180 TII = F.getSubtarget().getInstrInfo();
1181 TLI = F.getSubtarget().getTargetLowering();
1182 MDT = &getAnalysis<MachineDominatorTree>();
1183 assert(BlockToChain.empty());
1187 BlockToChain.clear();
1188 ChainAllocator.DestroyAll();
1191 // Align all of the blocks in the function to a specific alignment.
1192 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
1194 FI->setAlignment(AlignAllBlock);
1196 // We always return true as we have no way to track whether the final order
1197 // differs from the original order.
1202 /// \brief A pass to compute block placement statistics.
1204 /// A separate pass to compute interesting statistics for evaluating block
1205 /// placement. This is separate from the actual placement pass so that they can
1206 /// be computed in the absence of any placement transformations or when using
1207 /// alternative placement strategies.
1208 class MachineBlockPlacementStats : public MachineFunctionPass {
1209 /// \brief A handle to the branch probability pass.
1210 const MachineBranchProbabilityInfo *MBPI;
1212 /// \brief A handle to the function-wide block frequency pass.
1213 const MachineBlockFrequencyInfo *MBFI;
1216 static char ID; // Pass identification, replacement for typeid
1217 MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1218 initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1221 bool runOnMachineFunction(MachineFunction &F) override;
1223 void getAnalysisUsage(AnalysisUsage &AU) const override {
1224 AU.addRequired<MachineBranchProbabilityInfo>();
1225 AU.addRequired<MachineBlockFrequencyInfo>();
1226 AU.setPreservesAll();
1227 MachineFunctionPass::getAnalysisUsage(AU);
1232 char MachineBlockPlacementStats::ID = 0;
1233 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1234 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1235 "Basic Block Placement Stats", false, false)
1236 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1237 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1238 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1239 "Basic Block Placement Stats", false, false)
1241 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1242 // Check for single-block functions and skip them.
1243 if (std::next(F.begin()) == F.end())
1246 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1247 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1249 for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1250 BlockFrequency BlockFreq = MBFI->getBlockFreq(I);
1251 Statistic &NumBranches = (I->succ_size() > 1) ? NumCondBranches
1252 : NumUncondBranches;
1253 Statistic &BranchTakenFreq = (I->succ_size() > 1) ? CondBranchTakenFreq
1254 : UncondBranchTakenFreq;
1255 for (MachineBasicBlock::succ_iterator SI = I->succ_begin(),
1258 // Skip if this successor is a fallthrough.
1259 if (I->isLayoutSuccessor(*SI))
1262 BlockFrequency EdgeFreq = BlockFreq * MBPI->getEdgeProbability(I, *SI);
1264 BranchTakenFreq += EdgeFreq.getFrequency();