xref: /llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision 5b458cc1f6b41d65067ba61f2a345f52a77c060b)
1 //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements basic block placement transformations using the CFG
11 // structure and branch probability estimates.
12 //
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.
18 //
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
24 // function in-order.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/TargetPassConfig.h"
30 #include "BranchFolding.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
37 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
38 #include "llvm/CodeGen/MachineDominators.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineFunctionPass.h"
41 #include "llvm/CodeGen/MachineLoopInfo.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
50 #include <algorithm>
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "block-placement"
54 
55 STATISTIC(NumCondBranches, "Number of conditional branches");
56 STATISTIC(NumUncondBranches, "Number of unconditional branches");
57 STATISTIC(CondBranchTakenFreq,
58           "Potential frequency of taking conditional branches");
59 STATISTIC(UncondBranchTakenFreq,
60           "Potential frequency of taking unconditional branches");
61 
62 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
63                                        cl::desc("Force the alignment of all "
64                                                 "blocks in the function."),
65                                        cl::init(0), cl::Hidden);
66 
67 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
68     "align-all-nofallthru-blocks",
69     cl::desc("Force the alignment of all "
70              "blocks that have no fall-through predecessors (i.e. don't add "
71              "nops that are executed)."),
72     cl::init(0), cl::Hidden);
73 
74 // FIXME: Find a good default for this flag and remove the flag.
75 static cl::opt<unsigned> ExitBlockBias(
76     "block-placement-exit-block-bias",
77     cl::desc("Block frequency percentage a loop exit block needs "
78              "over the original exit to be considered the new exit."),
79     cl::init(0), cl::Hidden);
80 
81 static cl::opt<bool> OutlineOptionalBranches(
82     "outline-optional-branches",
83     cl::desc("Put completely optional branches, i.e. branches with a common "
84              "post dominator, out of line."),
85     cl::init(false), cl::Hidden);
86 
87 static cl::opt<unsigned> OutlineOptionalThreshold(
88     "outline-optional-threshold",
89     cl::desc("Don't outline optional branches that are a single block with an "
90              "instruction count below this threshold"),
91     cl::init(4), cl::Hidden);
92 
93 static cl::opt<unsigned> LoopToColdBlockRatio(
94     "loop-to-cold-block-ratio",
95     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
96              "(frequency of block) is greater than this ratio"),
97     cl::init(5), cl::Hidden);
98 
99 static cl::opt<bool>
100     PreciseRotationCost("precise-rotation-cost",
101                         cl::desc("Model the cost of loop rotation more "
102                                  "precisely by using profile data."),
103                         cl::init(false), cl::Hidden);
104 static cl::opt<bool>
105     ForcePreciseRotationCost("force-precise-rotation-cost",
106                              cl::desc("Force the use of precise cost "
107                                       "loop rotation strategy."),
108                              cl::init(false), cl::Hidden);
109 
110 static cl::opt<unsigned> MisfetchCost(
111     "misfetch-cost",
112     cl::desc("Cost that models the probablistic risk of an instruction "
113              "misfetch due to a jump comparing to falling through, whose cost "
114              "is zero."),
115     cl::init(1), cl::Hidden);
116 
117 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
118                                       cl::desc("Cost of jump instructions."),
119                                       cl::init(1), cl::Hidden);
120 
121 static cl::opt<bool>
122 BranchFoldPlacement("branch-fold-placement",
123               cl::desc("Perform branch folding during placement. "
124                        "Reduces code size."),
125               cl::init(true), cl::Hidden);
126 
127 extern cl::opt<unsigned> StaticLikelyProb;
128 
129 namespace {
130 class BlockChain;
131 /// \brief Type for our function-wide basic block -> block chain mapping.
132 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
133 }
134 
135 namespace {
136 /// \brief A chain of blocks which will be laid out contiguously.
137 ///
138 /// This is the datastructure representing a chain of consecutive blocks that
139 /// are profitable to layout together in order to maximize fallthrough
140 /// probabilities and code locality. We also can use a block chain to represent
141 /// a sequence of basic blocks which have some external (correctness)
142 /// requirement for sequential layout.
143 ///
144 /// Chains can be built around a single basic block and can be merged to grow
145 /// them. They participate in a block-to-chain mapping, which is updated
146 /// automatically as chains are merged together.
147 class BlockChain {
148   /// \brief The sequence of blocks belonging to this chain.
149   ///
150   /// This is the sequence of blocks for a particular chain. These will be laid
151   /// out in-order within the function.
152   SmallVector<MachineBasicBlock *, 4> Blocks;
153 
154   /// \brief A handle to the function-wide basic block to block chain mapping.
155   ///
156   /// This is retained in each block chain to simplify the computation of child
157   /// block chains for SCC-formation and iteration. We store the edges to child
158   /// basic blocks, and map them back to their associated chains using this
159   /// structure.
160   BlockToChainMapType &BlockToChain;
161 
162 public:
163   /// \brief Construct a new BlockChain.
164   ///
165   /// This builds a new block chain representing a single basic block in the
166   /// function. It also registers itself as the chain that block participates
167   /// in with the BlockToChain mapping.
168   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
169       : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
170     assert(BB && "Cannot create a chain with a null basic block");
171     BlockToChain[BB] = this;
172   }
173 
174   /// \brief Iterator over blocks within the chain.
175   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
176 
177   /// \brief Beginning of blocks within the chain.
178   iterator begin() { return Blocks.begin(); }
179 
180   /// \brief End of blocks within the chain.
181   iterator end() { return Blocks.end(); }
182 
183   /// \brief Merge a block chain into this one.
184   ///
185   /// This routine merges a block chain into this one. It takes care of forming
186   /// a contiguous sequence of basic blocks, updating the edge list, and
187   /// updating the block -> chain mapping. It does not free or tear down the
188   /// old chain, but the old chain's block list is no longer valid.
189   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
190     assert(BB);
191     assert(!Blocks.empty());
192 
193     // Fast path in case we don't have a chain already.
194     if (!Chain) {
195       assert(!BlockToChain[BB]);
196       Blocks.push_back(BB);
197       BlockToChain[BB] = this;
198       return;
199     }
200 
201     assert(BB == *Chain->begin());
202     assert(Chain->begin() != Chain->end());
203 
204     // Update the incoming blocks to point to this chain, and add them to the
205     // chain structure.
206     for (MachineBasicBlock *ChainBB : *Chain) {
207       Blocks.push_back(ChainBB);
208       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
209       BlockToChain[ChainBB] = this;
210     }
211   }
212 
213 #ifndef NDEBUG
214   /// \brief Dump the blocks in this chain.
215   LLVM_DUMP_METHOD void dump() {
216     for (MachineBasicBlock *MBB : *this)
217       MBB->dump();
218   }
219 #endif // NDEBUG
220 
221   /// \brief Count of predecessors of any block within the chain which have not
222   /// yet been scheduled.  In general, we will delay scheduling this chain
223   /// until those predecessors are scheduled (or we find a sufficiently good
224   /// reason to override this heuristic.)  Note that when forming loop chains,
225   /// blocks outside the loop are ignored and treated as if they were already
226   /// scheduled.
227   ///
228   /// Note: This field is reinitialized multiple times - once for each loop,
229   /// and then once for the function as a whole.
230   unsigned UnscheduledPredecessors;
231 };
232 }
233 
234 namespace {
235 class MachineBlockPlacement : public MachineFunctionPass {
236   /// \brief A typedef for a block filter set.
237   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
238 
239   /// \brief A handle to the branch probability pass.
240   const MachineBranchProbabilityInfo *MBPI;
241 
242   /// \brief A handle to the function-wide block frequency pass.
243   std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
244 
245   /// \brief A handle to the loop info.
246   MachineLoopInfo *MLI;
247 
248   /// \brief A handle to the target's instruction info.
249   const TargetInstrInfo *TII;
250 
251   /// \brief A handle to the target's lowering info.
252   const TargetLoweringBase *TLI;
253 
254   /// \brief A handle to the post dominator tree.
255   MachineDominatorTree *MDT;
256 
257   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
258   /// all terminators of the MachineFunction.
259   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
260 
261   /// \brief Allocator and owner of BlockChain structures.
262   ///
263   /// We build BlockChains lazily while processing the loop structure of
264   /// a function. To reduce malloc traffic, we allocate them using this
265   /// slab-like allocator, and destroy them after the pass completes. An
266   /// important guarantee is that this allocator produces stable pointers to
267   /// the chains.
268   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
269 
270   /// \brief Function wide BasicBlock to BlockChain mapping.
271   ///
272   /// This mapping allows efficiently moving from any given basic block to the
273   /// BlockChain it participates in, if any. We use it to, among other things,
274   /// allow implicitly defining edges between chains as the existing edges
275   /// between basic blocks.
276   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
277 
278   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
279                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
280                            SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
281                            const BlockFilterSet *BlockFilter = nullptr);
282   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
283                                          BlockChain &Chain,
284                                          const BlockFilterSet *BlockFilter);
285   MachineBasicBlock *
286   selectBestCandidateBlock(BlockChain &Chain,
287                            SmallVectorImpl<MachineBasicBlock *> &WorkList);
288   MachineBasicBlock *
289   getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
290                         MachineFunction::iterator &PrevUnplacedBlockIt,
291                         const BlockFilterSet *BlockFilter);
292 
293   /// \brief Add a basic block to the work list if it is apropriate.
294   ///
295   /// If the optional parameter BlockFilter is provided, only MBB
296   /// present in the set will be added to the worklist. If nullptr
297   /// is provided, no filtering occurs.
298   void fillWorkLists(MachineBasicBlock *MBB,
299                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
300                      SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
301                      SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
302                      const BlockFilterSet *BlockFilter);
303   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
304                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
305                   SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
306                   const BlockFilterSet *BlockFilter = nullptr);
307   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
308                                      const BlockFilterSet &LoopBlockSet);
309   MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
310                                       const BlockFilterSet &LoopBlockSet);
311   BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
312   void buildLoopChains(MachineFunction &F, MachineLoop &L);
313   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
314                   const BlockFilterSet &LoopBlockSet);
315   void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
316                              const BlockFilterSet &LoopBlockSet);
317   void buildCFGChains(MachineFunction &F);
318   void optimizeBranches(MachineFunction &F);
319   void alignBlocks(MachineFunction &F);
320 
321 public:
322   static char ID; // Pass identification, replacement for typeid
323   MachineBlockPlacement() : MachineFunctionPass(ID) {
324     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
325   }
326 
327   bool runOnMachineFunction(MachineFunction &F) override;
328 
329   void getAnalysisUsage(AnalysisUsage &AU) const override {
330     AU.addRequired<MachineBranchProbabilityInfo>();
331     AU.addRequired<MachineBlockFrequencyInfo>();
332     AU.addRequired<MachineDominatorTree>();
333     AU.addRequired<MachineLoopInfo>();
334     AU.addRequired<TargetPassConfig>();
335     MachineFunctionPass::getAnalysisUsage(AU);
336   }
337 };
338 }
339 
340 char MachineBlockPlacement::ID = 0;
341 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
342 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
343                       "Branch Probability Basic Block Placement", false, false)
344 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
345 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
346 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
347 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
348 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
349                     "Branch Probability Basic Block Placement", false, false)
350 
351 #ifndef NDEBUG
352 /// \brief Helper to print the name of a MBB.
353 ///
354 /// Only used by debug logging.
355 static std::string getBlockName(MachineBasicBlock *BB) {
356   std::string Result;
357   raw_string_ostream OS(Result);
358   OS << "BB#" << BB->getNumber();
359   OS << " ('" << BB->getName() << "')";
360   OS.flush();
361   return Result;
362 }
363 #endif
364 
365 /// \brief Mark a chain's successors as having one fewer preds.
366 ///
367 /// When a chain is being merged into the "placed" chain, this routine will
368 /// quickly walk the successors of each block in the chain and mark them as
369 /// having one fewer active predecessor. It also adds any successors of this
370 /// chain which reach the zero-predecessor state to the worklist passed in.
371 void MachineBlockPlacement::markChainSuccessors(
372     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
373     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
374     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
375     const BlockFilterSet *BlockFilter) {
376   // Walk all the blocks in this chain, marking their successors as having
377   // a predecessor placed.
378   for (MachineBasicBlock *MBB : Chain) {
379     // Add any successors for which this is the only un-placed in-loop
380     // predecessor to the worklist as a viable candidate for CFG-neutral
381     // placement. No subsequent placement of this block will violate the CFG
382     // shape, so we get to use heuristics to choose a favorable placement.
383     for (MachineBasicBlock *Succ : MBB->successors()) {
384       if (BlockFilter && !BlockFilter->count(Succ))
385         continue;
386       BlockChain &SuccChain = *BlockToChain[Succ];
387       // Disregard edges within a fixed chain, or edges to the loop header.
388       if (&Chain == &SuccChain || Succ == LoopHeaderBB)
389         continue;
390 
391       // This is a cross-chain edge that is within the loop, so decrement the
392       // loop predecessor count of the destination chain.
393       if (SuccChain.UnscheduledPredecessors == 0 ||
394           --SuccChain.UnscheduledPredecessors > 0)
395         continue;
396 
397       auto *MBB = *SuccChain.begin();
398       if (MBB->isEHPad())
399         EHPadWorkList.push_back(MBB);
400       else
401         BlockWorkList.push_back(MBB);
402     }
403   }
404 }
405 
406 /// \brief Select the best successor for a block.
407 ///
408 /// This looks across all successors of a particular block and attempts to
409 /// select the "best" one to be the layout successor. It only considers direct
410 /// successors which also pass the block filter. It will attempt to avoid
411 /// breaking CFG structure, but cave and break such structures in the case of
412 /// very hot successor edges.
413 ///
414 /// \returns The best successor block found, or null if none are viable.
415 MachineBasicBlock *
416 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
417                                            BlockChain &Chain,
418                                            const BlockFilterSet *BlockFilter) {
419   const BranchProbability HotProb(StaticLikelyProb, 100);
420 
421   MachineBasicBlock *BestSucc = nullptr;
422   auto BestProb = BranchProbability::getZero();
423 
424   // Adjust edge probabilities by excluding edges pointing to blocks that is
425   // either not in BlockFilter or is already in the current chain. Consider the
426   // following CFG:
427   //
428   //     --->A
429   //     |  / \
430   //     | B   C
431   //     |  \ / \
432   //     ----D   E
433   //
434   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
435   // A->C is chosen as a fall-through, D won't be selected as a successor of C
436   // due to CFG constraint (the probability of C->D is not greater than
437   // HotProb). If we exclude E that is not in BlockFilter when calculating the
438   // probability of C->D, D will be selected and we will get A C D B as the
439   // layout of this loop.
440   auto AdjustedSumProb = BranchProbability::getOne();
441   SmallVector<MachineBasicBlock *, 4> Successors;
442   for (MachineBasicBlock *Succ : BB->successors()) {
443     bool SkipSucc = false;
444     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
445       SkipSucc = true;
446     } else {
447       BlockChain *SuccChain = BlockToChain[Succ];
448       if (SuccChain == &Chain) {
449         SkipSucc = true;
450       } else if (Succ != *SuccChain->begin()) {
451         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
452         continue;
453       }
454     }
455     if (SkipSucc)
456       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
457     else
458       Successors.push_back(Succ);
459   }
460 
461   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
462   for (MachineBasicBlock *Succ : Successors) {
463     BranchProbability SuccProb;
464     uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
465     uint32_t SuccProbD = AdjustedSumProb.getNumerator();
466     if (SuccProbN >= SuccProbD)
467       SuccProb = BranchProbability::getOne();
468     else
469       SuccProb = BranchProbability(SuccProbN, SuccProbD);
470 
471     // If we outline optional branches, look whether Succ is unavoidable, i.e.
472     // dominates all terminators of the MachineFunction. If it does, other
473     // successors must be optional. Don't do this for cold branches.
474     if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
475         UnavoidableBlocks.count(Succ) > 0) {
476       auto HasShortOptionalBranch = [&]() {
477         for (MachineBasicBlock *Pred : Succ->predecessors()) {
478           // Check whether there is an unplaced optional branch.
479           if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
480               BlockToChain[Pred] == &Chain)
481             continue;
482           // Check whether the optional branch has exactly one BB.
483           if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
484             continue;
485           // Check whether the optional branch is small.
486           if (Pred->size() < OutlineOptionalThreshold)
487             return true;
488         }
489         return false;
490       };
491       if (!HasShortOptionalBranch())
492         return Succ;
493     }
494 
495     // Only consider successors which are either "hot", or wouldn't violate
496     // any CFG constraints.
497     BlockChain &SuccChain = *BlockToChain[Succ];
498     if (SuccChain.UnscheduledPredecessors != 0) {
499       if (SuccProb < HotProb) {
500         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
501                      << " (prob) (CFG conflict)\n");
502         continue;
503       }
504 
505       // Make sure that a hot successor doesn't have a globally more
506       // important predecessor.
507       auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
508       BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
509       bool BadCFGConflict = false;
510       for (MachineBasicBlock *Pred : Succ->predecessors()) {
511         if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
512             (BlockFilter && !BlockFilter->count(Pred)) ||
513             BlockToChain[Pred] == &Chain)
514           continue;
515         BlockFrequency PredEdgeFreq =
516             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
517         // A   B
518         //  \ /
519         //   C
520         // We layout ACB iff  A.freq > C.freq * HotProb
521         //               i.e. A.freq > A.freq * HotProb + B.freq * HotProb
522         //               i.e. A.freq * (1 - HotProb) > B.freq * HotProb
523         // A: CandidateEdge
524         // B: PredEdge
525         if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
526           BadCFGConflict = true;
527           break;
528         }
529       }
530       if (BadCFGConflict) {
531         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
532                      << " (prob) (non-cold CFG conflict)\n");
533         continue;
534       }
535     }
536 
537     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
538                  << " (prob)"
539                  << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
540                  << "\n");
541     if (BestSucc && BestProb >= SuccProb)
542       continue;
543     BestSucc = Succ;
544     BestProb = SuccProb;
545   }
546   return BestSucc;
547 }
548 
549 /// \brief Select the best block from a worklist.
550 ///
551 /// This looks through the provided worklist as a list of candidate basic
552 /// blocks and select the most profitable one to place. The definition of
553 /// profitable only really makes sense in the context of a loop. This returns
554 /// the most frequently visited block in the worklist, which in the case of
555 /// a loop, is the one most desirable to be physically close to the rest of the
556 /// loop body in order to improve icache behavior.
557 ///
558 /// \returns The best block found, or null if none are viable.
559 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
560     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
561   // Once we need to walk the worklist looking for a candidate, cleanup the
562   // worklist of already placed entries.
563   // FIXME: If this shows up on profiles, it could be folded (at the cost of
564   // some code complexity) into the loop below.
565   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
566                                 [&](MachineBasicBlock *BB) {
567                                   return BlockToChain.lookup(BB) == &Chain;
568                                 }),
569                  WorkList.end());
570 
571   if (WorkList.empty())
572     return nullptr;
573 
574   bool IsEHPad = WorkList[0]->isEHPad();
575 
576   MachineBasicBlock *BestBlock = nullptr;
577   BlockFrequency BestFreq;
578   for (MachineBasicBlock *MBB : WorkList) {
579     assert(MBB->isEHPad() == IsEHPad);
580 
581     BlockChain &SuccChain = *BlockToChain[MBB];
582     if (&SuccChain == &Chain)
583       continue;
584 
585     assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
586 
587     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
588     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
589           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
590 
591     // For ehpad, we layout the least probable first as to avoid jumping back
592     // from least probable landingpads to more probable ones.
593     //
594     // FIXME: Using probability is probably (!) not the best way to achieve
595     // this. We should probably have a more principled approach to layout
596     // cleanup code.
597     //
598     // The goal is to get:
599     //
600     //                 +--------------------------+
601     //                 |                          V
602     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
603     //
604     // Rather than:
605     //
606     //                 +-------------------------------------+
607     //                 V                                     |
608     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
609     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
610       continue;
611 
612     BestBlock = MBB;
613     BestFreq = CandidateFreq;
614   }
615 
616   return BestBlock;
617 }
618 
619 /// \brief Retrieve the first unplaced basic block.
620 ///
621 /// This routine is called when we are unable to use the CFG to walk through
622 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
623 /// We walk through the function's blocks in order, starting from the
624 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
625 /// re-scanning the entire sequence on repeated calls to this routine.
626 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
627     MachineFunction &F, const BlockChain &PlacedChain,
628     MachineFunction::iterator &PrevUnplacedBlockIt,
629     const BlockFilterSet *BlockFilter) {
630   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
631        ++I) {
632     if (BlockFilter && !BlockFilter->count(&*I))
633       continue;
634     if (BlockToChain[&*I] != &PlacedChain) {
635       PrevUnplacedBlockIt = I;
636       // Now select the head of the chain to which the unplaced block belongs
637       // as the block to place. This will force the entire chain to be placed,
638       // and satisfies the requirements of merging chains.
639       return *BlockToChain[&*I]->begin();
640     }
641   }
642   return nullptr;
643 }
644 
645 void MachineBlockPlacement::fillWorkLists(
646     MachineBasicBlock *MBB,
647     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
648     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
649     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
650     const BlockFilterSet *BlockFilter = nullptr) {
651   BlockChain &Chain = *BlockToChain[MBB];
652   if (!UpdatedPreds.insert(&Chain).second)
653     return;
654 
655   assert(Chain.UnscheduledPredecessors == 0);
656   for (MachineBasicBlock *ChainBB : Chain) {
657     assert(BlockToChain[ChainBB] == &Chain);
658     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
659       if (BlockFilter && !BlockFilter->count(Pred))
660         continue;
661       if (BlockToChain[Pred] == &Chain)
662         continue;
663       ++Chain.UnscheduledPredecessors;
664     }
665   }
666 
667   if (Chain.UnscheduledPredecessors != 0)
668     return;
669 
670   MBB = *Chain.begin();
671   if (MBB->isEHPad())
672     EHPadWorkList.push_back(MBB);
673   else
674     BlockWorkList.push_back(MBB);
675 }
676 
677 void MachineBlockPlacement::buildChain(
678     MachineBasicBlock *BB, BlockChain &Chain,
679     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
680     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
681     const BlockFilterSet *BlockFilter) {
682   assert(BB);
683   assert(BlockToChain[BB] == &Chain);
684   MachineFunction &F = *BB->getParent();
685   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
686 
687   MachineBasicBlock *LoopHeaderBB = BB;
688   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
689                       BlockFilter);
690   BB = *std::prev(Chain.end());
691   for (;;) {
692     assert(BB);
693     assert(BlockToChain[BB] == &Chain);
694     assert(*std::prev(Chain.end()) == BB);
695 
696     // Look for the best viable successor if there is one to place immediately
697     // after this block.
698     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
699 
700     // If an immediate successor isn't available, look for the best viable
701     // block among those we've identified as not violating the loop's CFG at
702     // this point. This won't be a fallthrough, but it will increase locality.
703     if (!BestSucc)
704       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
705     if (!BestSucc)
706       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
707 
708     if (!BestSucc) {
709       BestSucc =
710           getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
711       if (!BestSucc)
712         break;
713 
714       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
715                       "layout successor until the CFG reduces\n");
716     }
717 
718     // Place this block, updating the datastructures to reflect its placement.
719     BlockChain &SuccChain = *BlockToChain[BestSucc];
720     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
721     // we selected a successor that didn't fit naturally into the CFG.
722     SuccChain.UnscheduledPredecessors = 0;
723     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
724                  << getBlockName(BestSucc) << "\n");
725     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
726                         BlockFilter);
727     Chain.merge(BestSucc, &SuccChain);
728     BB = *std::prev(Chain.end());
729   }
730 
731   DEBUG(dbgs() << "Finished forming chain for header block "
732                << getBlockName(*Chain.begin()) << "\n");
733 }
734 
735 /// \brief Find the best loop top block for layout.
736 ///
737 /// Look for a block which is strictly better than the loop header for laying
738 /// out at the top of the loop. This looks for one and only one pattern:
739 /// a latch block with no conditional exit. This block will cause a conditional
740 /// jump around it or will be the bottom of the loop if we lay it out in place,
741 /// but if it it doesn't end up at the bottom of the loop for any reason,
742 /// rotation alone won't fix it. Because such a block will always result in an
743 /// unconditional jump (for the backedge) rotating it in front of the loop
744 /// header is always profitable.
745 MachineBasicBlock *
746 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
747                                        const BlockFilterSet &LoopBlockSet) {
748   // Check that the header hasn't been fused with a preheader block due to
749   // crazy branches. If it has, we need to start with the header at the top to
750   // prevent pulling the preheader into the loop body.
751   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
752   if (!LoopBlockSet.count(*HeaderChain.begin()))
753     return L.getHeader();
754 
755   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
756                << "\n");
757 
758   BlockFrequency BestPredFreq;
759   MachineBasicBlock *BestPred = nullptr;
760   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
761     if (!LoopBlockSet.count(Pred))
762       continue;
763     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
764                  << Pred->succ_size() << " successors, ";
765           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
766     if (Pred->succ_size() > 1)
767       continue;
768 
769     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
770     if (!BestPred || PredFreq > BestPredFreq ||
771         (!(PredFreq < BestPredFreq) &&
772          Pred->isLayoutSuccessor(L.getHeader()))) {
773       BestPred = Pred;
774       BestPredFreq = PredFreq;
775     }
776   }
777 
778   // If no direct predecessor is fine, just use the loop header.
779   if (!BestPred) {
780     DEBUG(dbgs() << "    final top unchanged\n");
781     return L.getHeader();
782   }
783 
784   // Walk backwards through any straight line of predecessors.
785   while (BestPred->pred_size() == 1 &&
786          (*BestPred->pred_begin())->succ_size() == 1 &&
787          *BestPred->pred_begin() != L.getHeader())
788     BestPred = *BestPred->pred_begin();
789 
790   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
791   return BestPred;
792 }
793 
794 /// \brief Find the best loop exiting block for layout.
795 ///
796 /// This routine implements the logic to analyze the loop looking for the best
797 /// block to layout at the top of the loop. Typically this is done to maximize
798 /// fallthrough opportunities.
799 MachineBasicBlock *
800 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
801                                         const BlockFilterSet &LoopBlockSet) {
802   // We don't want to layout the loop linearly in all cases. If the loop header
803   // is just a normal basic block in the loop, we want to look for what block
804   // within the loop is the best one to layout at the top. However, if the loop
805   // header has be pre-merged into a chain due to predecessors not having
806   // analyzable branches, *and* the predecessor it is merged with is *not* part
807   // of the loop, rotating the header into the middle of the loop will create
808   // a non-contiguous range of blocks which is Very Bad. So start with the
809   // header and only rotate if safe.
810   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
811   if (!LoopBlockSet.count(*HeaderChain.begin()))
812     return nullptr;
813 
814   BlockFrequency BestExitEdgeFreq;
815   unsigned BestExitLoopDepth = 0;
816   MachineBasicBlock *ExitingBB = nullptr;
817   // If there are exits to outer loops, loop rotation can severely limit
818   // fallthrough opportunites unless it selects such an exit. Keep a set of
819   // blocks where rotating to exit with that block will reach an outer loop.
820   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
821 
822   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
823                << "\n");
824   for (MachineBasicBlock *MBB : L.getBlocks()) {
825     BlockChain &Chain = *BlockToChain[MBB];
826     // Ensure that this block is at the end of a chain; otherwise it could be
827     // mid-way through an inner loop or a successor of an unanalyzable branch.
828     if (MBB != *std::prev(Chain.end()))
829       continue;
830 
831     // Now walk the successors. We need to establish whether this has a viable
832     // exiting successor and whether it has a viable non-exiting successor.
833     // We store the old exiting state and restore it if a viable looping
834     // successor isn't found.
835     MachineBasicBlock *OldExitingBB = ExitingBB;
836     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
837     bool HasLoopingSucc = false;
838     for (MachineBasicBlock *Succ : MBB->successors()) {
839       if (Succ->isEHPad())
840         continue;
841       if (Succ == MBB)
842         continue;
843       BlockChain &SuccChain = *BlockToChain[Succ];
844       // Don't split chains, either this chain or the successor's chain.
845       if (&Chain == &SuccChain) {
846         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
847                      << getBlockName(Succ) << " (chain conflict)\n");
848         continue;
849       }
850 
851       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
852       if (LoopBlockSet.count(Succ)) {
853         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
854                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
855         HasLoopingSucc = true;
856         continue;
857       }
858 
859       unsigned SuccLoopDepth = 0;
860       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
861         SuccLoopDepth = ExitLoop->getLoopDepth();
862         if (ExitLoop->contains(&L))
863           BlocksExitingToOuterLoop.insert(MBB);
864       }
865 
866       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
867       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
868                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
869             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
870       // Note that we bias this toward an existing layout successor to retain
871       // incoming order in the absence of better information. The exit must have
872       // a frequency higher than the current exit before we consider breaking
873       // the layout.
874       BranchProbability Bias(100 - ExitBlockBias, 100);
875       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
876           ExitEdgeFreq > BestExitEdgeFreq ||
877           (MBB->isLayoutSuccessor(Succ) &&
878            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
879         BestExitEdgeFreq = ExitEdgeFreq;
880         ExitingBB = MBB;
881       }
882     }
883 
884     if (!HasLoopingSucc) {
885       // Restore the old exiting state, no viable looping successor was found.
886       ExitingBB = OldExitingBB;
887       BestExitEdgeFreq = OldBestExitEdgeFreq;
888     }
889   }
890   // Without a candidate exiting block or with only a single block in the
891   // loop, just use the loop header to layout the loop.
892   if (!ExitingBB || L.getNumBlocks() == 1)
893     return nullptr;
894 
895   // Also, if we have exit blocks which lead to outer loops but didn't select
896   // one of them as the exiting block we are rotating toward, disable loop
897   // rotation altogether.
898   if (!BlocksExitingToOuterLoop.empty() &&
899       !BlocksExitingToOuterLoop.count(ExitingBB))
900     return nullptr;
901 
902   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
903   return ExitingBB;
904 }
905 
906 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
907 ///
908 /// Once we have built a chain, try to rotate it to line up the hot exit block
909 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
910 /// branches. For example, if the loop has fallthrough into its header and out
911 /// of its bottom already, don't rotate it.
912 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
913                                        MachineBasicBlock *ExitingBB,
914                                        const BlockFilterSet &LoopBlockSet) {
915   if (!ExitingBB)
916     return;
917 
918   MachineBasicBlock *Top = *LoopChain.begin();
919   bool ViableTopFallthrough = false;
920   for (MachineBasicBlock *Pred : Top->predecessors()) {
921     BlockChain *PredChain = BlockToChain[Pred];
922     if (!LoopBlockSet.count(Pred) &&
923         (!PredChain || Pred == *std::prev(PredChain->end()))) {
924       ViableTopFallthrough = true;
925       break;
926     }
927   }
928 
929   // If the header has viable fallthrough, check whether the current loop
930   // bottom is a viable exiting block. If so, bail out as rotating will
931   // introduce an unnecessary branch.
932   if (ViableTopFallthrough) {
933     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
934     for (MachineBasicBlock *Succ : Bottom->successors()) {
935       BlockChain *SuccChain = BlockToChain[Succ];
936       if (!LoopBlockSet.count(Succ) &&
937           (!SuccChain || Succ == *SuccChain->begin()))
938         return;
939     }
940   }
941 
942   BlockChain::iterator ExitIt =
943       std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
944   if (ExitIt == LoopChain.end())
945     return;
946 
947   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
948 }
949 
950 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
951 ///
952 /// With profile data, we can determine the cost in terms of missed fall through
953 /// opportunities when rotating a loop chain and select the best rotation.
954 /// Basically, there are three kinds of cost to consider for each rotation:
955 ///    1. The possibly missed fall through edge (if it exists) from BB out of
956 ///    the loop to the loop header.
957 ///    2. The possibly missed fall through edges (if they exist) from the loop
958 ///    exits to BB out of the loop.
959 ///    3. The missed fall through edge (if it exists) from the last BB to the
960 ///    first BB in the loop chain.
961 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
962 ///  We select the best rotation with the smallest cost.
963 void MachineBlockPlacement::rotateLoopWithProfile(
964     BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
965   auto HeaderBB = L.getHeader();
966   auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
967   auto RotationPos = LoopChain.end();
968 
969   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
970 
971   // A utility lambda that scales up a block frequency by dividing it by a
972   // branch probability which is the reciprocal of the scale.
973   auto ScaleBlockFrequency = [](BlockFrequency Freq,
974                                 unsigned Scale) -> BlockFrequency {
975     if (Scale == 0)
976       return 0;
977     // Use operator / between BlockFrequency and BranchProbability to implement
978     // saturating multiplication.
979     return Freq / BranchProbability(1, Scale);
980   };
981 
982   // Compute the cost of the missed fall-through edge to the loop header if the
983   // chain head is not the loop header. As we only consider natural loops with
984   // single header, this computation can be done only once.
985   BlockFrequency HeaderFallThroughCost(0);
986   for (auto *Pred : HeaderBB->predecessors()) {
987     BlockChain *PredChain = BlockToChain[Pred];
988     if (!LoopBlockSet.count(Pred) &&
989         (!PredChain || Pred == *std::prev(PredChain->end()))) {
990       auto EdgeFreq =
991           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
992       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
993       // If the predecessor has only an unconditional jump to the header, we
994       // need to consider the cost of this jump.
995       if (Pred->succ_size() == 1)
996         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
997       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
998     }
999   }
1000 
1001   // Here we collect all exit blocks in the loop, and for each exit we find out
1002   // its hottest exit edge. For each loop rotation, we define the loop exit cost
1003   // as the sum of frequencies of exit edges we collect here, excluding the exit
1004   // edge from the tail of the loop chain.
1005   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1006   for (auto BB : LoopChain) {
1007     auto LargestExitEdgeProb = BranchProbability::getZero();
1008     for (auto *Succ : BB->successors()) {
1009       BlockChain *SuccChain = BlockToChain[Succ];
1010       if (!LoopBlockSet.count(Succ) &&
1011           (!SuccChain || Succ == *SuccChain->begin())) {
1012         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1013         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
1014       }
1015     }
1016     if (LargestExitEdgeProb > BranchProbability::getZero()) {
1017       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
1018       ExitsWithFreq.emplace_back(BB, ExitFreq);
1019     }
1020   }
1021 
1022   // In this loop we iterate every block in the loop chain and calculate the
1023   // cost assuming the block is the head of the loop chain. When the loop ends,
1024   // we should have found the best candidate as the loop chain's head.
1025   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1026             EndIter = LoopChain.end();
1027        Iter != EndIter; Iter++, TailIter++) {
1028     // TailIter is used to track the tail of the loop chain if the block we are
1029     // checking (pointed by Iter) is the head of the chain.
1030     if (TailIter == LoopChain.end())
1031       TailIter = LoopChain.begin();
1032 
1033     auto TailBB = *TailIter;
1034 
1035     // Calculate the cost by putting this BB to the top.
1036     BlockFrequency Cost = 0;
1037 
1038     // If the current BB is the loop header, we need to take into account the
1039     // cost of the missed fall through edge from outside of the loop to the
1040     // header.
1041     if (Iter != HeaderIter)
1042       Cost += HeaderFallThroughCost;
1043 
1044     // Collect the loop exit cost by summing up frequencies of all exit edges
1045     // except the one from the chain tail.
1046     for (auto &ExitWithFreq : ExitsWithFreq)
1047       if (TailBB != ExitWithFreq.first)
1048         Cost += ExitWithFreq.second;
1049 
1050     // The cost of breaking the once fall-through edge from the tail to the top
1051     // of the loop chain. Here we need to consider three cases:
1052     // 1. If the tail node has only one successor, then we will get an
1053     //    additional jmp instruction. So the cost here is (MisfetchCost +
1054     //    JumpInstCost) * tail node frequency.
1055     // 2. If the tail node has two successors, then we may still get an
1056     //    additional jmp instruction if the layout successor after the loop
1057     //    chain is not its CFG successor. Note that the more frequently executed
1058     //    jmp instruction will be put ahead of the other one. Assume the
1059     //    frequency of those two branches are x and y, where x is the frequency
1060     //    of the edge to the chain head, then the cost will be
1061     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1062     // 3. If the tail node has more than two successors (this rarely happens),
1063     //    we won't consider any additional cost.
1064     if (TailBB->isSuccessor(*Iter)) {
1065       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1066       if (TailBB->succ_size() == 1)
1067         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1068                                     MisfetchCost + JumpInstCost);
1069       else if (TailBB->succ_size() == 2) {
1070         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1071         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1072         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1073                                   ? TailBBFreq * TailToHeadProb.getCompl()
1074                                   : TailToHeadFreq;
1075         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1076                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1077       }
1078     }
1079 
1080     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
1081                  << " to the top: " << Cost.getFrequency() << "\n");
1082 
1083     if (Cost < SmallestRotationCost) {
1084       SmallestRotationCost = Cost;
1085       RotationPos = Iter;
1086     }
1087   }
1088 
1089   if (RotationPos != LoopChain.end()) {
1090     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
1091                  << " to the top\n");
1092     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1093   }
1094 }
1095 
1096 /// \brief Collect blocks in the given loop that are to be placed.
1097 ///
1098 /// When profile data is available, exclude cold blocks from the returned set;
1099 /// otherwise, collect all blocks in the loop.
1100 MachineBlockPlacement::BlockFilterSet
1101 MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1102   BlockFilterSet LoopBlockSet;
1103 
1104   // Filter cold blocks off from LoopBlockSet when profile data is available.
1105   // Collect the sum of frequencies of incoming edges to the loop header from
1106   // outside. If we treat the loop as a super block, this is the frequency of
1107   // the loop. Then for each block in the loop, we calculate the ratio between
1108   // its frequency and the frequency of the loop block. When it is too small,
1109   // don't add it to the loop chain. If there are outer loops, then this block
1110   // will be merged into the first outer loop chain for which this block is not
1111   // cold anymore. This needs precise profile data and we only do this when
1112   // profile data is available.
1113   if (F.getFunction()->getEntryCount()) {
1114     BlockFrequency LoopFreq(0);
1115     for (auto LoopPred : L.getHeader()->predecessors())
1116       if (!L.contains(LoopPred))
1117         LoopFreq += MBFI->getBlockFreq(LoopPred) *
1118                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
1119 
1120     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1121       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1122       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1123         continue;
1124       LoopBlockSet.insert(LoopBB);
1125     }
1126   } else
1127     LoopBlockSet.insert(L.block_begin(), L.block_end());
1128 
1129   return LoopBlockSet;
1130 }
1131 
1132 /// \brief Forms basic block chains from the natural loop structures.
1133 ///
1134 /// These chains are designed to preserve the existing *structure* of the code
1135 /// as much as possible. We can then stitch the chains together in a way which
1136 /// both preserves the topological structure and minimizes taken conditional
1137 /// branches.
1138 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
1139                                             MachineLoop &L) {
1140   // First recurse through any nested loops, building chains for those inner
1141   // loops.
1142   for (MachineLoop *InnerLoop : L)
1143     buildLoopChains(F, *InnerLoop);
1144 
1145   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1146   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
1147   BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
1148 
1149   // Check if we have profile data for this function. If yes, we will rotate
1150   // this loop by modeling costs more precisely which requires the profile data
1151   // for better layout.
1152   bool RotateLoopWithProfile =
1153       ForcePreciseRotationCost ||
1154       (PreciseRotationCost && F.getFunction()->getEntryCount());
1155 
1156   // First check to see if there is an obviously preferable top block for the
1157   // loop. This will default to the header, but may end up as one of the
1158   // predecessors to the header if there is one which will result in strictly
1159   // fewer branches in the loop body.
1160   // When we use profile data to rotate the loop, this is unnecessary.
1161   MachineBasicBlock *LoopTop =
1162       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1163 
1164   // If we selected just the header for the loop top, look for a potentially
1165   // profitable exit block in the event that rotating the loop can eliminate
1166   // branches by placing an exit edge at the bottom.
1167   MachineBasicBlock *ExitingBB = nullptr;
1168   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1169     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1170 
1171   BlockChain &LoopChain = *BlockToChain[LoopTop];
1172 
1173   // FIXME: This is a really lame way of walking the chains in the loop: we
1174   // walk the blocks, and use a set to prevent visiting a particular chain
1175   // twice.
1176   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1177   assert(LoopChain.UnscheduledPredecessors == 0);
1178   UpdatedPreds.insert(&LoopChain);
1179 
1180   for (MachineBasicBlock *LoopBB : LoopBlockSet)
1181     fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, EHPadWorkList,
1182                   &LoopBlockSet);
1183 
1184   buildChain(LoopTop, LoopChain, BlockWorkList, EHPadWorkList, &LoopBlockSet);
1185 
1186   if (RotateLoopWithProfile)
1187     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1188   else
1189     rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1190 
1191   DEBUG({
1192     // Crash at the end so we get all of the debugging output first.
1193     bool BadLoop = false;
1194     if (LoopChain.UnscheduledPredecessors) {
1195       BadLoop = true;
1196       dbgs() << "Loop chain contains a block without its preds placed!\n"
1197              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1198              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1199     }
1200     for (MachineBasicBlock *ChainBB : LoopChain) {
1201       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
1202       if (!LoopBlockSet.erase(ChainBB)) {
1203         // We don't mark the loop as bad here because there are real situations
1204         // where this can occur. For example, with an unanalyzable fallthrough
1205         // from a loop block to a non-loop block or vice versa.
1206         dbgs() << "Loop chain contains a block not contained by the loop!\n"
1207                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1208                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1209                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1210       }
1211     }
1212 
1213     if (!LoopBlockSet.empty()) {
1214       BadLoop = true;
1215       for (MachineBasicBlock *LoopBB : LoopBlockSet)
1216         dbgs() << "Loop contains blocks never placed into a chain!\n"
1217                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1218                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1219                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
1220     }
1221     assert(!BadLoop && "Detected problems with the placement of this loop.");
1222   });
1223 }
1224 
1225 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
1226   // Ensure that every BB in the function has an associated chain to simplify
1227   // the assumptions of the remaining algorithm.
1228   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1229   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1230     MachineBasicBlock *BB = &*FI;
1231     BlockChain *Chain =
1232         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1233     // Also, merge any blocks which we cannot reason about and must preserve
1234     // the exact fallthrough behavior for.
1235     for (;;) {
1236       Cond.clear();
1237       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1238       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1239         break;
1240 
1241       MachineFunction::iterator NextFI = std::next(FI);
1242       MachineBasicBlock *NextBB = &*NextFI;
1243       // Ensure that the layout successor is a viable block, as we know that
1244       // fallthrough is a possibility.
1245       assert(NextFI != FE && "Can't fallthrough past the last block.");
1246       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1247                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
1248                    << "\n");
1249       Chain->merge(NextBB, nullptr);
1250       FI = NextFI;
1251       BB = NextBB;
1252     }
1253   }
1254 
1255   if (OutlineOptionalBranches) {
1256     // Find the nearest common dominator of all of F's terminators.
1257     MachineBasicBlock *Terminator = nullptr;
1258     for (MachineBasicBlock &MBB : F) {
1259       if (MBB.succ_size() == 0) {
1260         if (Terminator == nullptr)
1261           Terminator = &MBB;
1262         else
1263           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1264       }
1265     }
1266 
1267     // MBBs dominating this common dominator are unavoidable.
1268     UnavoidableBlocks.clear();
1269     for (MachineBasicBlock &MBB : F) {
1270       if (MDT->dominates(&MBB, Terminator)) {
1271         UnavoidableBlocks.insert(&MBB);
1272       }
1273     }
1274   }
1275 
1276   // Build any loop-based chains.
1277   for (MachineLoop *L : *MLI)
1278     buildLoopChains(F, *L);
1279 
1280   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1281   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
1282 
1283   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1284   for (MachineBasicBlock &MBB : F)
1285     fillWorkLists(&MBB, UpdatedPreds, BlockWorkList, EHPadWorkList);
1286 
1287   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1288   buildChain(&F.front(), FunctionChain, BlockWorkList, EHPadWorkList);
1289 
1290 #ifndef NDEBUG
1291   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1292 #endif
1293   DEBUG({
1294     // Crash at the end so we get all of the debugging output first.
1295     bool BadFunc = false;
1296     FunctionBlockSetType FunctionBlockSet;
1297     for (MachineBasicBlock &MBB : F)
1298       FunctionBlockSet.insert(&MBB);
1299 
1300     for (MachineBasicBlock *ChainBB : FunctionChain)
1301       if (!FunctionBlockSet.erase(ChainBB)) {
1302         BadFunc = true;
1303         dbgs() << "Function chain contains a block not in the function!\n"
1304                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1305       }
1306 
1307     if (!FunctionBlockSet.empty()) {
1308       BadFunc = true;
1309       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1310         dbgs() << "Function contains blocks never placed into a chain!\n"
1311                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
1312     }
1313     assert(!BadFunc && "Detected problems with the block placement.");
1314   });
1315 
1316   // Splice the blocks into place.
1317   MachineFunction::iterator InsertPos = F.begin();
1318   for (MachineBasicBlock *ChainBB : FunctionChain) {
1319     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1320                                                        : "          ... ")
1321                  << getBlockName(ChainBB) << "\n");
1322     if (InsertPos != MachineFunction::iterator(ChainBB))
1323       F.splice(InsertPos, ChainBB);
1324     else
1325       ++InsertPos;
1326 
1327     // Update the terminator of the previous block.
1328     if (ChainBB == *FunctionChain.begin())
1329       continue;
1330     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1331 
1332     // FIXME: It would be awesome of updateTerminator would just return rather
1333     // than assert when the branch cannot be analyzed in order to remove this
1334     // boiler plate.
1335     Cond.clear();
1336     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1337 
1338     // The "PrevBB" is not yet updated to reflect current code layout, so,
1339     //   o. it may fall-through to a block without explict "goto" instruction
1340     //      before layout, and no longer fall-through it after layout; or
1341     //   o. just opposite.
1342     //
1343     // AnalyzeBranch() may return erroneous value for FBB when these two
1344     // situations take place. For the first scenario FBB is mistakenly set NULL;
1345     // for the 2nd scenario, the FBB, which is expected to be NULL, is
1346     // mistakenly pointing to "*BI".
1347     // Thus, if the future change needs to use FBB before the layout is set, it
1348     // has to correct FBB first by using the code similar to the following:
1349     //
1350     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1351     //   PrevBB->updateTerminator();
1352     //   Cond.clear();
1353     //   TBB = FBB = nullptr;
1354     //   if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1355     //     // FIXME: This should never take place.
1356     //     TBB = FBB = nullptr;
1357     //   }
1358     // }
1359     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond))
1360       PrevBB->updateTerminator();
1361   }
1362 
1363   // Fixup the last block.
1364   Cond.clear();
1365   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1366   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1367     F.back().updateTerminator();
1368 }
1369 
1370 void MachineBlockPlacement::optimizeBranches(MachineFunction &F) {
1371   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1372   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1373 
1374   // Now that all the basic blocks in the chain have the proper layout,
1375   // make a final call to AnalyzeBranch with AllowModify set.
1376   // Indeed, the target may be able to optimize the branches in a way we
1377   // cannot because all branches may not be analyzable.
1378   // E.g., the target may be able to remove an unconditional branch to
1379   // a fallthrough when it occurs after predicated terminators.
1380   for (MachineBasicBlock *ChainBB : FunctionChain) {
1381     Cond.clear();
1382     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1383     if (!TII->AnalyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1384       // If PrevBB has a two-way branch, try to re-order the branches
1385       // such that we branch to the successor with higher probability first.
1386       if (TBB && !Cond.empty() && FBB &&
1387           MBPI->getEdgeProbability(ChainBB, FBB) >
1388               MBPI->getEdgeProbability(ChainBB, TBB) &&
1389           !TII->ReverseBranchCondition(Cond)) {
1390         DEBUG(dbgs() << "Reverse order of the two branches: "
1391                      << getBlockName(ChainBB) << "\n");
1392         DEBUG(dbgs() << "    Edge probability: "
1393                      << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1394                      << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1395         DebugLoc dl; // FIXME: this is nowhere
1396         TII->RemoveBranch(*ChainBB);
1397         TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1398         ChainBB->updateTerminator();
1399       }
1400     }
1401   }
1402 }
1403 
1404 void MachineBlockPlacement::alignBlocks(MachineFunction &F) {
1405   // Walk through the backedges of the function now that we have fully laid out
1406   // the basic blocks and align the destination of each backedge. We don't rely
1407   // exclusively on the loop info here so that we can align backedges in
1408   // unnatural CFGs and backedges that were introduced purely because of the
1409   // loop rotations done during this layout pass.
1410   if (F.getFunction()->optForSize())
1411     return;
1412   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1413   if (FunctionChain.begin() == FunctionChain.end())
1414     return; // Empty chain.
1415 
1416   const BranchProbability ColdProb(1, 5); // 20%
1417   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
1418   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1419   for (MachineBasicBlock *ChainBB : FunctionChain) {
1420     if (ChainBB == *FunctionChain.begin())
1421       continue;
1422 
1423     // Don't align non-looping basic blocks. These are unlikely to execute
1424     // enough times to matter in practice. Note that we'll still handle
1425     // unnatural CFGs inside of a natural outer loop (the common case) and
1426     // rotated loops.
1427     MachineLoop *L = MLI->getLoopFor(ChainBB);
1428     if (!L)
1429       continue;
1430 
1431     unsigned Align = TLI->getPrefLoopAlignment(L);
1432     if (!Align)
1433       continue; // Don't care about loop alignment.
1434 
1435     // If the block is cold relative to the function entry don't waste space
1436     // aligning it.
1437     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1438     if (Freq < WeightedEntryFreq)
1439       continue;
1440 
1441     // If the block is cold relative to its loop header, don't align it
1442     // regardless of what edges into the block exist.
1443     MachineBasicBlock *LoopHeader = L->getHeader();
1444     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1445     if (Freq < (LoopHeaderFreq * ColdProb))
1446       continue;
1447 
1448     // Check for the existence of a non-layout predecessor which would benefit
1449     // from aligning this block.
1450     MachineBasicBlock *LayoutPred =
1451         &*std::prev(MachineFunction::iterator(ChainBB));
1452 
1453     // Force alignment if all the predecessors are jumps. We already checked
1454     // that the block isn't cold above.
1455     if (!LayoutPred->isSuccessor(ChainBB)) {
1456       ChainBB->setAlignment(Align);
1457       continue;
1458     }
1459 
1460     // Align this block if the layout predecessor's edge into this block is
1461     // cold relative to the block. When this is true, other predecessors make up
1462     // all of the hot entries into the block and thus alignment is likely to be
1463     // important.
1464     BranchProbability LayoutProb =
1465         MBPI->getEdgeProbability(LayoutPred, ChainBB);
1466     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1467     if (LayoutEdgeFreq <= (Freq * ColdProb))
1468       ChainBB->setAlignment(Align);
1469   }
1470 }
1471 
1472 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1473   if (skipFunction(*F.getFunction()))
1474     return false;
1475 
1476   // Check for single-block functions and skip them.
1477   if (std::next(F.begin()) == F.end())
1478     return false;
1479 
1480   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1481   MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1482       getAnalysis<MachineBlockFrequencyInfo>());
1483   MLI = &getAnalysis<MachineLoopInfo>();
1484   TII = F.getSubtarget().getInstrInfo();
1485   TLI = F.getSubtarget().getTargetLowering();
1486   MDT = &getAnalysis<MachineDominatorTree>();
1487   assert(BlockToChain.empty());
1488 
1489   buildCFGChains(F);
1490 
1491   // Changing the layout can create new tail merging opportunities.
1492   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1493   // TailMerge can create jump into if branches that make CFG irreducible for
1494   // HW that requires structurized CFG.
1495   bool EnableTailMerge = !F.getTarget().requiresStructuredCFG() &&
1496                          PassConfig->getEnableTailMerge() &&
1497                          BranchFoldPlacement;
1498   // No tail merging opportunities if the block number is less than four.
1499   if (F.size() > 3 && EnableTailMerge) {
1500     BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
1501                     *MBPI);
1502 
1503     if (BF.OptimizeFunction(F, TII, F.getSubtarget().getRegisterInfo(),
1504                             getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
1505                             /*AfterBlockPlacement=*/true)) {
1506       // Redo the layout if tail merging creates/removes/moves blocks.
1507       BlockToChain.clear();
1508       ChainAllocator.DestroyAll();
1509       buildCFGChains(F);
1510     }
1511   }
1512 
1513   optimizeBranches(F);
1514   alignBlocks(F);
1515 
1516   BlockToChain.clear();
1517   ChainAllocator.DestroyAll();
1518 
1519   if (AlignAllBlock)
1520     // Align all of the blocks in the function to a specific alignment.
1521     for (MachineBasicBlock &MBB : F)
1522       MBB.setAlignment(AlignAllBlock);
1523   else if (AlignAllNonFallThruBlocks) {
1524     // Align all of the blocks that have no fall-through predecessors to a
1525     // specific alignment.
1526     for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1527       auto LayoutPred = std::prev(MBI);
1528       if (!LayoutPred->isSuccessor(&*MBI))
1529         MBI->setAlignment(AlignAllNonFallThruBlocks);
1530     }
1531   }
1532 
1533   // We always return true as we have no way to track whether the final order
1534   // differs from the original order.
1535   return true;
1536 }
1537 
1538 namespace {
1539 /// \brief A pass to compute block placement statistics.
1540 ///
1541 /// A separate pass to compute interesting statistics for evaluating block
1542 /// placement. This is separate from the actual placement pass so that they can
1543 /// be computed in the absence of any placement transformations or when using
1544 /// alternative placement strategies.
1545 class MachineBlockPlacementStats : public MachineFunctionPass {
1546   /// \brief A handle to the branch probability pass.
1547   const MachineBranchProbabilityInfo *MBPI;
1548 
1549   /// \brief A handle to the function-wide block frequency pass.
1550   const MachineBlockFrequencyInfo *MBFI;
1551 
1552 public:
1553   static char ID; // Pass identification, replacement for typeid
1554   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1555     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1556   }
1557 
1558   bool runOnMachineFunction(MachineFunction &F) override;
1559 
1560   void getAnalysisUsage(AnalysisUsage &AU) const override {
1561     AU.addRequired<MachineBranchProbabilityInfo>();
1562     AU.addRequired<MachineBlockFrequencyInfo>();
1563     AU.setPreservesAll();
1564     MachineFunctionPass::getAnalysisUsage(AU);
1565   }
1566 };
1567 }
1568 
1569 char MachineBlockPlacementStats::ID = 0;
1570 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1571 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1572                       "Basic Block Placement Stats", false, false)
1573 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1574 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1575 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1576                     "Basic Block Placement Stats", false, false)
1577 
1578 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1579   // Check for single-block functions and skip them.
1580   if (std::next(F.begin()) == F.end())
1581     return false;
1582 
1583   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1584   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1585 
1586   for (MachineBasicBlock &MBB : F) {
1587     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1588     Statistic &NumBranches =
1589         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1590     Statistic &BranchTakenFreq =
1591         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1592     for (MachineBasicBlock *Succ : MBB.successors()) {
1593       // Skip if this successor is a fallthrough.
1594       if (MBB.isLayoutSuccessor(Succ))
1595         continue;
1596 
1597       BlockFrequency EdgeFreq =
1598           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1599       ++NumBranches;
1600       BranchTakenFreq += EdgeFreq.getFrequency();
1601     }
1602   }
1603 
1604   return false;
1605 }
1606