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