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