xref: /llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision 77ea344786abf9e96805641868dcd04f59e452ad)
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 =
509           MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
510       bool BadCFGConflict = false;
511       for (MachineBasicBlock *Pred : Succ->predecessors()) {
512         if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
513             (BlockFilter && !BlockFilter->count(Pred)) ||
514             BlockToChain[Pred] == &Chain)
515           continue;
516         BlockFrequency PredEdgeFreq =
517             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
518         if (PredEdgeFreq >= CandidateEdgeFreq) {
519           BadCFGConflict = true;
520           break;
521         }
522       }
523       if (BadCFGConflict) {
524         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
525                      << " (prob) (non-cold CFG conflict)\n");
526         continue;
527       }
528     }
529 
530     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
531                  << " (prob)"
532                  << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
533                  << "\n");
534     if (BestSucc && BestProb >= SuccProb)
535       continue;
536     BestSucc = Succ;
537     BestProb = SuccProb;
538   }
539   return BestSucc;
540 }
541 
542 /// \brief Select the best block from a worklist.
543 ///
544 /// This looks through the provided worklist as a list of candidate basic
545 /// blocks and select the most profitable one to place. The definition of
546 /// profitable only really makes sense in the context of a loop. This returns
547 /// the most frequently visited block in the worklist, which in the case of
548 /// a loop, is the one most desirable to be physically close to the rest of the
549 /// loop body in order to improve icache behavior.
550 ///
551 /// \returns The best block found, or null if none are viable.
552 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
553     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
554   // Once we need to walk the worklist looking for a candidate, cleanup the
555   // worklist of already placed entries.
556   // FIXME: If this shows up on profiles, it could be folded (at the cost of
557   // some code complexity) into the loop below.
558   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
559                                 [&](MachineBasicBlock *BB) {
560                                   return BlockToChain.lookup(BB) == &Chain;
561                                 }),
562                  WorkList.end());
563 
564   if (WorkList.empty())
565     return nullptr;
566 
567   bool IsEHPad = WorkList[0]->isEHPad();
568 
569   MachineBasicBlock *BestBlock = nullptr;
570   BlockFrequency BestFreq;
571   for (MachineBasicBlock *MBB : WorkList) {
572     assert(MBB->isEHPad() == IsEHPad);
573 
574     BlockChain &SuccChain = *BlockToChain[MBB];
575     if (&SuccChain == &Chain)
576       continue;
577 
578     assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
579 
580     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
581     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
582           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
583 
584     // For ehpad, we layout the least probable first as to avoid jumping back
585     // from least probable landingpads to more probable ones.
586     //
587     // FIXME: Using probability is probably (!) not the best way to achieve
588     // this. We should probably have a more principled approach to layout
589     // cleanup code.
590     //
591     // The goal is to get:
592     //
593     //                 +--------------------------+
594     //                 |                          V
595     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
596     //
597     // Rather than:
598     //
599     //                 +-------------------------------------+
600     //                 V                                     |
601     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
602     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
603       continue;
604 
605     BestBlock = MBB;
606     BestFreq = CandidateFreq;
607   }
608 
609   return BestBlock;
610 }
611 
612 /// \brief Retrieve the first unplaced basic block.
613 ///
614 /// This routine is called when we are unable to use the CFG to walk through
615 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
616 /// We walk through the function's blocks in order, starting from the
617 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
618 /// re-scanning the entire sequence on repeated calls to this routine.
619 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
620     MachineFunction &F, const BlockChain &PlacedChain,
621     MachineFunction::iterator &PrevUnplacedBlockIt,
622     const BlockFilterSet *BlockFilter) {
623   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
624        ++I) {
625     if (BlockFilter && !BlockFilter->count(&*I))
626       continue;
627     if (BlockToChain[&*I] != &PlacedChain) {
628       PrevUnplacedBlockIt = I;
629       // Now select the head of the chain to which the unplaced block belongs
630       // as the block to place. This will force the entire chain to be placed,
631       // and satisfies the requirements of merging chains.
632       return *BlockToChain[&*I]->begin();
633     }
634   }
635   return nullptr;
636 }
637 
638 void MachineBlockPlacement::fillWorkLists(
639     MachineBasicBlock *MBB,
640     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
641     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
642     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
643     const BlockFilterSet *BlockFilter = nullptr) {
644   BlockChain &Chain = *BlockToChain[MBB];
645   if (!UpdatedPreds.insert(&Chain).second)
646     return;
647 
648   assert(Chain.UnscheduledPredecessors == 0);
649   for (MachineBasicBlock *ChainBB : Chain) {
650     assert(BlockToChain[ChainBB] == &Chain);
651     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
652       if (BlockFilter && !BlockFilter->count(Pred))
653         continue;
654       if (BlockToChain[Pred] == &Chain)
655         continue;
656       ++Chain.UnscheduledPredecessors;
657     }
658   }
659 
660   if (Chain.UnscheduledPredecessors != 0)
661     return;
662 
663   MBB = *Chain.begin();
664   if (MBB->isEHPad())
665     EHPadWorkList.push_back(MBB);
666   else
667     BlockWorkList.push_back(MBB);
668 }
669 
670 void MachineBlockPlacement::buildChain(
671     MachineBasicBlock *BB, BlockChain &Chain,
672     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
673     SmallVectorImpl<MachineBasicBlock *> &EHPadWorkList,
674     const BlockFilterSet *BlockFilter) {
675   assert(BB);
676   assert(BlockToChain[BB] == &Chain);
677   MachineFunction &F = *BB->getParent();
678   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
679 
680   MachineBasicBlock *LoopHeaderBB = BB;
681   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
682                       BlockFilter);
683   BB = *std::prev(Chain.end());
684   for (;;) {
685     assert(BB);
686     assert(BlockToChain[BB] == &Chain);
687     assert(*std::prev(Chain.end()) == BB);
688 
689     // Look for the best viable successor if there is one to place immediately
690     // after this block.
691     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
692 
693     // If an immediate successor isn't available, look for the best viable
694     // block among those we've identified as not violating the loop's CFG at
695     // this point. This won't be a fallthrough, but it will increase locality.
696     if (!BestSucc)
697       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
698     if (!BestSucc)
699       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
700 
701     if (!BestSucc) {
702       BestSucc =
703           getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
704       if (!BestSucc)
705         break;
706 
707       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
708                       "layout successor until the CFG reduces\n");
709     }
710 
711     // Place this block, updating the datastructures to reflect its placement.
712     BlockChain &SuccChain = *BlockToChain[BestSucc];
713     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
714     // we selected a successor that didn't fit naturally into the CFG.
715     SuccChain.UnscheduledPredecessors = 0;
716     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
717                  << getBlockName(BestSucc) << "\n");
718     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, EHPadWorkList,
719                         BlockFilter);
720     Chain.merge(BestSucc, &SuccChain);
721     BB = *std::prev(Chain.end());
722   }
723 
724   DEBUG(dbgs() << "Finished forming chain for header block "
725                << getBlockName(*Chain.begin()) << "\n");
726 }
727 
728 /// \brief Find the best loop top block for layout.
729 ///
730 /// Look for a block which is strictly better than the loop header for laying
731 /// out at the top of the loop. This looks for one and only one pattern:
732 /// a latch block with no conditional exit. This block will cause a conditional
733 /// jump around it or will be the bottom of the loop if we lay it out in place,
734 /// but if it it doesn't end up at the bottom of the loop for any reason,
735 /// rotation alone won't fix it. Because such a block will always result in an
736 /// unconditional jump (for the backedge) rotating it in front of the loop
737 /// header is always profitable.
738 MachineBasicBlock *
739 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
740                                        const BlockFilterSet &LoopBlockSet) {
741   // Check that the header hasn't been fused with a preheader block due to
742   // crazy branches. If it has, we need to start with the header at the top to
743   // prevent pulling the preheader into the loop body.
744   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
745   if (!LoopBlockSet.count(*HeaderChain.begin()))
746     return L.getHeader();
747 
748   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
749                << "\n");
750 
751   BlockFrequency BestPredFreq;
752   MachineBasicBlock *BestPred = nullptr;
753   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
754     if (!LoopBlockSet.count(Pred))
755       continue;
756     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
757                  << Pred->succ_size() << " successors, ";
758           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
759     if (Pred->succ_size() > 1)
760       continue;
761 
762     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
763     if (!BestPred || PredFreq > BestPredFreq ||
764         (!(PredFreq < BestPredFreq) &&
765          Pred->isLayoutSuccessor(L.getHeader()))) {
766       BestPred = Pred;
767       BestPredFreq = PredFreq;
768     }
769   }
770 
771   // If no direct predecessor is fine, just use the loop header.
772   if (!BestPred) {
773     DEBUG(dbgs() << "    final top unchanged\n");
774     return L.getHeader();
775   }
776 
777   // Walk backwards through any straight line of predecessors.
778   while (BestPred->pred_size() == 1 &&
779          (*BestPred->pred_begin())->succ_size() == 1 &&
780          *BestPred->pred_begin() != L.getHeader())
781     BestPred = *BestPred->pred_begin();
782 
783   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
784   return BestPred;
785 }
786 
787 /// \brief Find the best loop exiting block for layout.
788 ///
789 /// This routine implements the logic to analyze the loop looking for the best
790 /// block to layout at the top of the loop. Typically this is done to maximize
791 /// fallthrough opportunities.
792 MachineBasicBlock *
793 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
794                                         const BlockFilterSet &LoopBlockSet) {
795   // We don't want to layout the loop linearly in all cases. If the loop header
796   // is just a normal basic block in the loop, we want to look for what block
797   // within the loop is the best one to layout at the top. However, if the loop
798   // header has be pre-merged into a chain due to predecessors not having
799   // analyzable branches, *and* the predecessor it is merged with is *not* part
800   // of the loop, rotating the header into the middle of the loop will create
801   // a non-contiguous range of blocks which is Very Bad. So start with the
802   // header and only rotate if safe.
803   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
804   if (!LoopBlockSet.count(*HeaderChain.begin()))
805     return nullptr;
806 
807   BlockFrequency BestExitEdgeFreq;
808   unsigned BestExitLoopDepth = 0;
809   MachineBasicBlock *ExitingBB = nullptr;
810   // If there are exits to outer loops, loop rotation can severely limit
811   // fallthrough opportunites unless it selects such an exit. Keep a set of
812   // blocks where rotating to exit with that block will reach an outer loop.
813   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
814 
815   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
816                << "\n");
817   for (MachineBasicBlock *MBB : L.getBlocks()) {
818     BlockChain &Chain = *BlockToChain[MBB];
819     // Ensure that this block is at the end of a chain; otherwise it could be
820     // mid-way through an inner loop or a successor of an unanalyzable branch.
821     if (MBB != *std::prev(Chain.end()))
822       continue;
823 
824     // Now walk the successors. We need to establish whether this has a viable
825     // exiting successor and whether it has a viable non-exiting successor.
826     // We store the old exiting state and restore it if a viable looping
827     // successor isn't found.
828     MachineBasicBlock *OldExitingBB = ExitingBB;
829     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
830     bool HasLoopingSucc = false;
831     for (MachineBasicBlock *Succ : MBB->successors()) {
832       if (Succ->isEHPad())
833         continue;
834       if (Succ == MBB)
835         continue;
836       BlockChain &SuccChain = *BlockToChain[Succ];
837       // Don't split chains, either this chain or the successor's chain.
838       if (&Chain == &SuccChain) {
839         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
840                      << getBlockName(Succ) << " (chain conflict)\n");
841         continue;
842       }
843 
844       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
845       if (LoopBlockSet.count(Succ)) {
846         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
847                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
848         HasLoopingSucc = true;
849         continue;
850       }
851 
852       unsigned SuccLoopDepth = 0;
853       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
854         SuccLoopDepth = ExitLoop->getLoopDepth();
855         if (ExitLoop->contains(&L))
856           BlocksExitingToOuterLoop.insert(MBB);
857       }
858 
859       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
860       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
861                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
862             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
863       // Note that we bias this toward an existing layout successor to retain
864       // incoming order in the absence of better information. The exit must have
865       // a frequency higher than the current exit before we consider breaking
866       // the layout.
867       BranchProbability Bias(100 - ExitBlockBias, 100);
868       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
869           ExitEdgeFreq > BestExitEdgeFreq ||
870           (MBB->isLayoutSuccessor(Succ) &&
871            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
872         BestExitEdgeFreq = ExitEdgeFreq;
873         ExitingBB = MBB;
874       }
875     }
876 
877     if (!HasLoopingSucc) {
878       // Restore the old exiting state, no viable looping successor was found.
879       ExitingBB = OldExitingBB;
880       BestExitEdgeFreq = OldBestExitEdgeFreq;
881     }
882   }
883   // Without a candidate exiting block or with only a single block in the
884   // loop, just use the loop header to layout the loop.
885   if (!ExitingBB || L.getNumBlocks() == 1)
886     return nullptr;
887 
888   // Also, if we have exit blocks which lead to outer loops but didn't select
889   // one of them as the exiting block we are rotating toward, disable loop
890   // rotation altogether.
891   if (!BlocksExitingToOuterLoop.empty() &&
892       !BlocksExitingToOuterLoop.count(ExitingBB))
893     return nullptr;
894 
895   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
896   return ExitingBB;
897 }
898 
899 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
900 ///
901 /// Once we have built a chain, try to rotate it to line up the hot exit block
902 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
903 /// branches. For example, if the loop has fallthrough into its header and out
904 /// of its bottom already, don't rotate it.
905 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
906                                        MachineBasicBlock *ExitingBB,
907                                        const BlockFilterSet &LoopBlockSet) {
908   if (!ExitingBB)
909     return;
910 
911   MachineBasicBlock *Top = *LoopChain.begin();
912   bool ViableTopFallthrough = false;
913   for (MachineBasicBlock *Pred : Top->predecessors()) {
914     BlockChain *PredChain = BlockToChain[Pred];
915     if (!LoopBlockSet.count(Pred) &&
916         (!PredChain || Pred == *std::prev(PredChain->end()))) {
917       ViableTopFallthrough = true;
918       break;
919     }
920   }
921 
922   // If the header has viable fallthrough, check whether the current loop
923   // bottom is a viable exiting block. If so, bail out as rotating will
924   // introduce an unnecessary branch.
925   if (ViableTopFallthrough) {
926     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
927     for (MachineBasicBlock *Succ : Bottom->successors()) {
928       BlockChain *SuccChain = BlockToChain[Succ];
929       if (!LoopBlockSet.count(Succ) &&
930           (!SuccChain || Succ == *SuccChain->begin()))
931         return;
932     }
933   }
934 
935   BlockChain::iterator ExitIt =
936       std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
937   if (ExitIt == LoopChain.end())
938     return;
939 
940   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
941 }
942 
943 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
944 ///
945 /// With profile data, we can determine the cost in terms of missed fall through
946 /// opportunities when rotating a loop chain and select the best rotation.
947 /// Basically, there are three kinds of cost to consider for each rotation:
948 ///    1. The possibly missed fall through edge (if it exists) from BB out of
949 ///    the loop to the loop header.
950 ///    2. The possibly missed fall through edges (if they exist) from the loop
951 ///    exits to BB out of the loop.
952 ///    3. The missed fall through edge (if it exists) from the last BB to the
953 ///    first BB in the loop chain.
954 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
955 ///  We select the best rotation with the smallest cost.
956 void MachineBlockPlacement::rotateLoopWithProfile(
957     BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
958   auto HeaderBB = L.getHeader();
959   auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
960   auto RotationPos = LoopChain.end();
961 
962   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
963 
964   // A utility lambda that scales up a block frequency by dividing it by a
965   // branch probability which is the reciprocal of the scale.
966   auto ScaleBlockFrequency = [](BlockFrequency Freq,
967                                 unsigned Scale) -> BlockFrequency {
968     if (Scale == 0)
969       return 0;
970     // Use operator / between BlockFrequency and BranchProbability to implement
971     // saturating multiplication.
972     return Freq / BranchProbability(1, Scale);
973   };
974 
975   // Compute the cost of the missed fall-through edge to the loop header if the
976   // chain head is not the loop header. As we only consider natural loops with
977   // single header, this computation can be done only once.
978   BlockFrequency HeaderFallThroughCost(0);
979   for (auto *Pred : HeaderBB->predecessors()) {
980     BlockChain *PredChain = BlockToChain[Pred];
981     if (!LoopBlockSet.count(Pred) &&
982         (!PredChain || Pred == *std::prev(PredChain->end()))) {
983       auto EdgeFreq =
984           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
985       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
986       // If the predecessor has only an unconditional jump to the header, we
987       // need to consider the cost of this jump.
988       if (Pred->succ_size() == 1)
989         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
990       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
991     }
992   }
993 
994   // Here we collect all exit blocks in the loop, and for each exit we find out
995   // its hottest exit edge. For each loop rotation, we define the loop exit cost
996   // as the sum of frequencies of exit edges we collect here, excluding the exit
997   // edge from the tail of the loop chain.
998   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
999   for (auto BB : LoopChain) {
1000     auto LargestExitEdgeProb = BranchProbability::getZero();
1001     for (auto *Succ : BB->successors()) {
1002       BlockChain *SuccChain = BlockToChain[Succ];
1003       if (!LoopBlockSet.count(Succ) &&
1004           (!SuccChain || Succ == *SuccChain->begin())) {
1005         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1006         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
1007       }
1008     }
1009     if (LargestExitEdgeProb > BranchProbability::getZero()) {
1010       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
1011       ExitsWithFreq.emplace_back(BB, ExitFreq);
1012     }
1013   }
1014 
1015   // In this loop we iterate every block in the loop chain and calculate the
1016   // cost assuming the block is the head of the loop chain. When the loop ends,
1017   // we should have found the best candidate as the loop chain's head.
1018   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1019             EndIter = LoopChain.end();
1020        Iter != EndIter; Iter++, TailIter++) {
1021     // TailIter is used to track the tail of the loop chain if the block we are
1022     // checking (pointed by Iter) is the head of the chain.
1023     if (TailIter == LoopChain.end())
1024       TailIter = LoopChain.begin();
1025 
1026     auto TailBB = *TailIter;
1027 
1028     // Calculate the cost by putting this BB to the top.
1029     BlockFrequency Cost = 0;
1030 
1031     // If the current BB is the loop header, we need to take into account the
1032     // cost of the missed fall through edge from outside of the loop to the
1033     // header.
1034     if (Iter != HeaderIter)
1035       Cost += HeaderFallThroughCost;
1036 
1037     // Collect the loop exit cost by summing up frequencies of all exit edges
1038     // except the one from the chain tail.
1039     for (auto &ExitWithFreq : ExitsWithFreq)
1040       if (TailBB != ExitWithFreq.first)
1041         Cost += ExitWithFreq.second;
1042 
1043     // The cost of breaking the once fall-through edge from the tail to the top
1044     // of the loop chain. Here we need to consider three cases:
1045     // 1. If the tail node has only one successor, then we will get an
1046     //    additional jmp instruction. So the cost here is (MisfetchCost +
1047     //    JumpInstCost) * tail node frequency.
1048     // 2. If the tail node has two successors, then we may still get an
1049     //    additional jmp instruction if the layout successor after the loop
1050     //    chain is not its CFG successor. Note that the more frequently executed
1051     //    jmp instruction will be put ahead of the other one. Assume the
1052     //    frequency of those two branches are x and y, where x is the frequency
1053     //    of the edge to the chain head, then the cost will be
1054     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1055     // 3. If the tail node has more than two successors (this rarely happens),
1056     //    we won't consider any additional cost.
1057     if (TailBB->isSuccessor(*Iter)) {
1058       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1059       if (TailBB->succ_size() == 1)
1060         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1061                                     MisfetchCost + JumpInstCost);
1062       else if (TailBB->succ_size() == 2) {
1063         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1064         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1065         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1066                                   ? TailBBFreq * TailToHeadProb.getCompl()
1067                                   : TailToHeadFreq;
1068         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1069                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1070       }
1071     }
1072 
1073     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
1074                  << " to the top: " << Cost.getFrequency() << "\n");
1075 
1076     if (Cost < SmallestRotationCost) {
1077       SmallestRotationCost = Cost;
1078       RotationPos = Iter;
1079     }
1080   }
1081 
1082   if (RotationPos != LoopChain.end()) {
1083     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
1084                  << " to the top\n");
1085     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1086   }
1087 }
1088 
1089 /// \brief Collect blocks in the given loop that are to be placed.
1090 ///
1091 /// When profile data is available, exclude cold blocks from the returned set;
1092 /// otherwise, collect all blocks in the loop.
1093 MachineBlockPlacement::BlockFilterSet
1094 MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
1095   BlockFilterSet LoopBlockSet;
1096 
1097   // Filter cold blocks off from LoopBlockSet when profile data is available.
1098   // Collect the sum of frequencies of incoming edges to the loop header from
1099   // outside. If we treat the loop as a super block, this is the frequency of
1100   // the loop. Then for each block in the loop, we calculate the ratio between
1101   // its frequency and the frequency of the loop block. When it is too small,
1102   // don't add it to the loop chain. If there are outer loops, then this block
1103   // will be merged into the first outer loop chain for which this block is not
1104   // cold anymore. This needs precise profile data and we only do this when
1105   // profile data is available.
1106   if (F.getFunction()->getEntryCount()) {
1107     BlockFrequency LoopFreq(0);
1108     for (auto LoopPred : L.getHeader()->predecessors())
1109       if (!L.contains(LoopPred))
1110         LoopFreq += MBFI->getBlockFreq(LoopPred) *
1111                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
1112 
1113     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1114       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1115       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1116         continue;
1117       LoopBlockSet.insert(LoopBB);
1118     }
1119   } else
1120     LoopBlockSet.insert(L.block_begin(), L.block_end());
1121 
1122   return LoopBlockSet;
1123 }
1124 
1125 /// \brief Forms basic block chains from the natural loop structures.
1126 ///
1127 /// These chains are designed to preserve the existing *structure* of the code
1128 /// as much as possible. We can then stitch the chains together in a way which
1129 /// both preserves the topological structure and minimizes taken conditional
1130 /// branches.
1131 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
1132                                             MachineLoop &L) {
1133   // First recurse through any nested loops, building chains for those inner
1134   // loops.
1135   for (MachineLoop *InnerLoop : L)
1136     buildLoopChains(F, *InnerLoop);
1137 
1138   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1139   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
1140   BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
1141 
1142   // Check if we have profile data for this function. If yes, we will rotate
1143   // this loop by modeling costs more precisely which requires the profile data
1144   // for better layout.
1145   bool RotateLoopWithProfile =
1146       ForcePreciseRotationCost ||
1147       (PreciseRotationCost && F.getFunction()->getEntryCount());
1148 
1149   // First check to see if there is an obviously preferable top block for the
1150   // loop. This will default to the header, but may end up as one of the
1151   // predecessors to the header if there is one which will result in strictly
1152   // fewer branches in the loop body.
1153   // When we use profile data to rotate the loop, this is unnecessary.
1154   MachineBasicBlock *LoopTop =
1155       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1156 
1157   // If we selected just the header for the loop top, look for a potentially
1158   // profitable exit block in the event that rotating the loop can eliminate
1159   // branches by placing an exit edge at the bottom.
1160   MachineBasicBlock *ExitingBB = nullptr;
1161   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1162     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1163 
1164   BlockChain &LoopChain = *BlockToChain[LoopTop];
1165 
1166   // FIXME: This is a really lame way of walking the chains in the loop: we
1167   // walk the blocks, and use a set to prevent visiting a particular chain
1168   // twice.
1169   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1170   assert(LoopChain.UnscheduledPredecessors == 0);
1171   UpdatedPreds.insert(&LoopChain);
1172 
1173   for (MachineBasicBlock *LoopBB : LoopBlockSet)
1174     fillWorkLists(LoopBB, UpdatedPreds, BlockWorkList, EHPadWorkList,
1175                   &LoopBlockSet);
1176 
1177   buildChain(LoopTop, LoopChain, BlockWorkList, EHPadWorkList, &LoopBlockSet);
1178 
1179   if (RotateLoopWithProfile)
1180     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1181   else
1182     rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1183 
1184   DEBUG({
1185     // Crash at the end so we get all of the debugging output first.
1186     bool BadLoop = false;
1187     if (LoopChain.UnscheduledPredecessors) {
1188       BadLoop = true;
1189       dbgs() << "Loop chain contains a block without its preds placed!\n"
1190              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1191              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1192     }
1193     for (MachineBasicBlock *ChainBB : LoopChain) {
1194       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
1195       if (!LoopBlockSet.erase(ChainBB)) {
1196         // We don't mark the loop as bad here because there are real situations
1197         // where this can occur. For example, with an unanalyzable fallthrough
1198         // from a loop block to a non-loop block or vice versa.
1199         dbgs() << "Loop chain contains a block not contained by the loop!\n"
1200                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1201                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1202                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1203       }
1204     }
1205 
1206     if (!LoopBlockSet.empty()) {
1207       BadLoop = true;
1208       for (MachineBasicBlock *LoopBB : LoopBlockSet)
1209         dbgs() << "Loop contains blocks never placed into a chain!\n"
1210                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1211                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1212                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
1213     }
1214     assert(!BadLoop && "Detected problems with the placement of this loop.");
1215   });
1216 }
1217 
1218 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
1219   // Ensure that every BB in the function has an associated chain to simplify
1220   // the assumptions of the remaining algorithm.
1221   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1222   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1223     MachineBasicBlock *BB = &*FI;
1224     BlockChain *Chain =
1225         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1226     // Also, merge any blocks which we cannot reason about and must preserve
1227     // the exact fallthrough behavior for.
1228     for (;;) {
1229       Cond.clear();
1230       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1231       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1232         break;
1233 
1234       MachineFunction::iterator NextFI = std::next(FI);
1235       MachineBasicBlock *NextBB = &*NextFI;
1236       // Ensure that the layout successor is a viable block, as we know that
1237       // fallthrough is a possibility.
1238       assert(NextFI != FE && "Can't fallthrough past the last block.");
1239       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1240                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
1241                    << "\n");
1242       Chain->merge(NextBB, nullptr);
1243       FI = NextFI;
1244       BB = NextBB;
1245     }
1246   }
1247 
1248   if (OutlineOptionalBranches) {
1249     // Find the nearest common dominator of all of F's terminators.
1250     MachineBasicBlock *Terminator = nullptr;
1251     for (MachineBasicBlock &MBB : F) {
1252       if (MBB.succ_size() == 0) {
1253         if (Terminator == nullptr)
1254           Terminator = &MBB;
1255         else
1256           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1257       }
1258     }
1259 
1260     // MBBs dominating this common dominator are unavoidable.
1261     UnavoidableBlocks.clear();
1262     for (MachineBasicBlock &MBB : F) {
1263       if (MDT->dominates(&MBB, Terminator)) {
1264         UnavoidableBlocks.insert(&MBB);
1265       }
1266     }
1267   }
1268 
1269   // Build any loop-based chains.
1270   for (MachineLoop *L : *MLI)
1271     buildLoopChains(F, *L);
1272 
1273   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1274   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
1275 
1276   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1277   for (MachineBasicBlock &MBB : F)
1278     fillWorkLists(&MBB, UpdatedPreds, BlockWorkList, EHPadWorkList);
1279 
1280   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1281   buildChain(&F.front(), FunctionChain, BlockWorkList, EHPadWorkList);
1282 
1283 #ifndef NDEBUG
1284   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1285 #endif
1286   DEBUG({
1287     // Crash at the end so we get all of the debugging output first.
1288     bool BadFunc = false;
1289     FunctionBlockSetType FunctionBlockSet;
1290     for (MachineBasicBlock &MBB : F)
1291       FunctionBlockSet.insert(&MBB);
1292 
1293     for (MachineBasicBlock *ChainBB : FunctionChain)
1294       if (!FunctionBlockSet.erase(ChainBB)) {
1295         BadFunc = true;
1296         dbgs() << "Function chain contains a block not in the function!\n"
1297                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1298       }
1299 
1300     if (!FunctionBlockSet.empty()) {
1301       BadFunc = true;
1302       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1303         dbgs() << "Function contains blocks never placed into a chain!\n"
1304                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
1305     }
1306     assert(!BadFunc && "Detected problems with the block placement.");
1307   });
1308 
1309   // Splice the blocks into place.
1310   MachineFunction::iterator InsertPos = F.begin();
1311   for (MachineBasicBlock *ChainBB : FunctionChain) {
1312     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1313                                                        : "          ... ")
1314                  << getBlockName(ChainBB) << "\n");
1315     if (InsertPos != MachineFunction::iterator(ChainBB))
1316       F.splice(InsertPos, ChainBB);
1317     else
1318       ++InsertPos;
1319 
1320     // Update the terminator of the previous block.
1321     if (ChainBB == *FunctionChain.begin())
1322       continue;
1323     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1324 
1325     // FIXME: It would be awesome of updateTerminator would just return rather
1326     // than assert when the branch cannot be analyzed in order to remove this
1327     // boiler plate.
1328     Cond.clear();
1329     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1330 
1331     // The "PrevBB" is not yet updated to reflect current code layout, so,
1332     //   o. it may fall-through to a block without explict "goto" instruction
1333     //      before layout, and no longer fall-through it after layout; or
1334     //   o. just opposite.
1335     //
1336     // AnalyzeBranch() may return erroneous value for FBB when these two
1337     // situations take place. For the first scenario FBB is mistakenly set NULL;
1338     // for the 2nd scenario, the FBB, which is expected to be NULL, is
1339     // mistakenly pointing to "*BI".
1340     // Thus, if the future change needs to use FBB before the layout is set, it
1341     // has to correct FBB first by using the code similar to the following:
1342     //
1343     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1344     //   PrevBB->updateTerminator();
1345     //   Cond.clear();
1346     //   TBB = FBB = nullptr;
1347     //   if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1348     //     // FIXME: This should never take place.
1349     //     TBB = FBB = nullptr;
1350     //   }
1351     // }
1352     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond))
1353       PrevBB->updateTerminator();
1354   }
1355 
1356   // Fixup the last block.
1357   Cond.clear();
1358   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1359   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1360     F.back().updateTerminator();
1361 }
1362 
1363 void MachineBlockPlacement::optimizeBranches(MachineFunction &F) {
1364   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1365   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1366 
1367   // Now that all the basic blocks in the chain have the proper layout,
1368   // make a final call to AnalyzeBranch with AllowModify set.
1369   // Indeed, the target may be able to optimize the branches in a way we
1370   // cannot because all branches may not be analyzable.
1371   // E.g., the target may be able to remove an unconditional branch to
1372   // a fallthrough when it occurs after predicated terminators.
1373   for (MachineBasicBlock *ChainBB : FunctionChain) {
1374     Cond.clear();
1375     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1376     if (!TII->AnalyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
1377       // If PrevBB has a two-way branch, try to re-order the branches
1378       // such that we branch to the successor with higher probability first.
1379       if (TBB && !Cond.empty() && FBB &&
1380           MBPI->getEdgeProbability(ChainBB, FBB) >
1381               MBPI->getEdgeProbability(ChainBB, TBB) &&
1382           !TII->ReverseBranchCondition(Cond)) {
1383         DEBUG(dbgs() << "Reverse order of the two branches: "
1384                      << getBlockName(ChainBB) << "\n");
1385         DEBUG(dbgs() << "    Edge probability: "
1386                      << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
1387                      << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
1388         DebugLoc dl; // FIXME: this is nowhere
1389         TII->RemoveBranch(*ChainBB);
1390         TII->InsertBranch(*ChainBB, FBB, TBB, Cond, dl);
1391         ChainBB->updateTerminator();
1392       }
1393     }
1394   }
1395 }
1396 
1397 void MachineBlockPlacement::alignBlocks(MachineFunction &F) {
1398   // Walk through the backedges of the function now that we have fully laid out
1399   // the basic blocks and align the destination of each backedge. We don't rely
1400   // exclusively on the loop info here so that we can align backedges in
1401   // unnatural CFGs and backedges that were introduced purely because of the
1402   // loop rotations done during this layout pass.
1403   if (F.getFunction()->optForSize())
1404     return;
1405   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1406   if (FunctionChain.begin() == FunctionChain.end())
1407     return; // Empty chain.
1408 
1409   const BranchProbability ColdProb(1, 5); // 20%
1410   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
1411   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1412   for (MachineBasicBlock *ChainBB : FunctionChain) {
1413     if (ChainBB == *FunctionChain.begin())
1414       continue;
1415 
1416     // Don't align non-looping basic blocks. These are unlikely to execute
1417     // enough times to matter in practice. Note that we'll still handle
1418     // unnatural CFGs inside of a natural outer loop (the common case) and
1419     // rotated loops.
1420     MachineLoop *L = MLI->getLoopFor(ChainBB);
1421     if (!L)
1422       continue;
1423 
1424     unsigned Align = TLI->getPrefLoopAlignment(L);
1425     if (!Align)
1426       continue; // Don't care about loop alignment.
1427 
1428     // If the block is cold relative to the function entry don't waste space
1429     // aligning it.
1430     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1431     if (Freq < WeightedEntryFreq)
1432       continue;
1433 
1434     // If the block is cold relative to its loop header, don't align it
1435     // regardless of what edges into the block exist.
1436     MachineBasicBlock *LoopHeader = L->getHeader();
1437     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1438     if (Freq < (LoopHeaderFreq * ColdProb))
1439       continue;
1440 
1441     // Check for the existence of a non-layout predecessor which would benefit
1442     // from aligning this block.
1443     MachineBasicBlock *LayoutPred =
1444         &*std::prev(MachineFunction::iterator(ChainBB));
1445 
1446     // Force alignment if all the predecessors are jumps. We already checked
1447     // that the block isn't cold above.
1448     if (!LayoutPred->isSuccessor(ChainBB)) {
1449       ChainBB->setAlignment(Align);
1450       continue;
1451     }
1452 
1453     // Align this block if the layout predecessor's edge into this block is
1454     // cold relative to the block. When this is true, other predecessors make up
1455     // all of the hot entries into the block and thus alignment is likely to be
1456     // important.
1457     BranchProbability LayoutProb =
1458         MBPI->getEdgeProbability(LayoutPred, ChainBB);
1459     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1460     if (LayoutEdgeFreq <= (Freq * ColdProb))
1461       ChainBB->setAlignment(Align);
1462   }
1463 }
1464 
1465 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1466   if (skipFunction(*F.getFunction()))
1467     return false;
1468 
1469   // Check for single-block functions and skip them.
1470   if (std::next(F.begin()) == F.end())
1471     return false;
1472 
1473   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1474   MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
1475       getAnalysis<MachineBlockFrequencyInfo>());
1476   MLI = &getAnalysis<MachineLoopInfo>();
1477   TII = F.getSubtarget().getInstrInfo();
1478   TLI = F.getSubtarget().getTargetLowering();
1479   MDT = &getAnalysis<MachineDominatorTree>();
1480   assert(BlockToChain.empty());
1481 
1482   buildCFGChains(F);
1483 
1484   // Changing the layout can create new tail merging opportunities.
1485   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
1486   // TailMerge can create jump into if branches that make CFG irreducible for
1487   // HW that requires structurized CFG.
1488   bool EnableTailMerge = !F.getTarget().requiresStructuredCFG() &&
1489                          PassConfig->getEnableTailMerge() &&
1490                          BranchFoldPlacement;
1491   // No tail merging opportunities if the block number is less than four.
1492   if (F.size() > 3 && EnableTailMerge) {
1493     BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
1494                     *MBPI);
1495 
1496     if (BF.OptimizeFunction(F, TII, F.getSubtarget().getRegisterInfo(),
1497                             getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
1498                             /*AfterBlockPlacement=*/true)) {
1499       // Redo the layout if tail merging creates/removes/moves blocks.
1500       BlockToChain.clear();
1501       ChainAllocator.DestroyAll();
1502       buildCFGChains(F);
1503     }
1504   }
1505 
1506   optimizeBranches(F);
1507   alignBlocks(F);
1508 
1509   BlockToChain.clear();
1510   ChainAllocator.DestroyAll();
1511 
1512   if (AlignAllBlock)
1513     // Align all of the blocks in the function to a specific alignment.
1514     for (MachineBasicBlock &MBB : F)
1515       MBB.setAlignment(AlignAllBlock);
1516   else if (AlignAllNonFallThruBlocks) {
1517     // Align all of the blocks that have no fall-through predecessors to a
1518     // specific alignment.
1519     for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1520       auto LayoutPred = std::prev(MBI);
1521       if (!LayoutPred->isSuccessor(&*MBI))
1522         MBI->setAlignment(AlignAllNonFallThruBlocks);
1523     }
1524   }
1525 
1526   // We always return true as we have no way to track whether the final order
1527   // differs from the original order.
1528   return true;
1529 }
1530 
1531 namespace {
1532 /// \brief A pass to compute block placement statistics.
1533 ///
1534 /// A separate pass to compute interesting statistics for evaluating block
1535 /// placement. This is separate from the actual placement pass so that they can
1536 /// be computed in the absence of any placement transformations or when using
1537 /// alternative placement strategies.
1538 class MachineBlockPlacementStats : public MachineFunctionPass {
1539   /// \brief A handle to the branch probability pass.
1540   const MachineBranchProbabilityInfo *MBPI;
1541 
1542   /// \brief A handle to the function-wide block frequency pass.
1543   const MachineBlockFrequencyInfo *MBFI;
1544 
1545 public:
1546   static char ID; // Pass identification, replacement for typeid
1547   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1548     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1549   }
1550 
1551   bool runOnMachineFunction(MachineFunction &F) override;
1552 
1553   void getAnalysisUsage(AnalysisUsage &AU) const override {
1554     AU.addRequired<MachineBranchProbabilityInfo>();
1555     AU.addRequired<MachineBlockFrequencyInfo>();
1556     AU.setPreservesAll();
1557     MachineFunctionPass::getAnalysisUsage(AU);
1558   }
1559 };
1560 }
1561 
1562 char MachineBlockPlacementStats::ID = 0;
1563 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1564 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1565                       "Basic Block Placement Stats", false, false)
1566 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1567 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1568 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1569                     "Basic Block Placement Stats", false, false)
1570 
1571 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1572   // Check for single-block functions and skip them.
1573   if (std::next(F.begin()) == F.end())
1574     return false;
1575 
1576   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1577   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1578 
1579   for (MachineBasicBlock &MBB : F) {
1580     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1581     Statistic &NumBranches =
1582         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1583     Statistic &BranchTakenFreq =
1584         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1585     for (MachineBasicBlock *Succ : MBB.successors()) {
1586       // Skip if this successor is a fallthrough.
1587       if (MBB.isLayoutSuccessor(Succ))
1588         continue;
1589 
1590       BlockFrequency EdgeFreq =
1591           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1592       ++NumBranches;
1593       BranchTakenFreq += EdgeFreq.getFrequency();
1594     }
1595   }
1596 
1597   return false;
1598 }
1599