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/Analysis/BlockFrequencyInfoImpl.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
39 #include "llvm/CodeGen/MachineDominators.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineFunctionPass.h"
42 #include "llvm/CodeGen/MachineLoopInfo.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/MachinePostDominators.h"
45 #include "llvm/CodeGen/TailDuplicator.h"
46 #include "llvm/Support/Allocator.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetInstrInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include <algorithm>
54 #include <functional>
55 #include <utility>
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "block-placement"
59 
60 STATISTIC(NumCondBranches, "Number of conditional branches");
61 STATISTIC(NumUncondBranches, "Number of unconditional branches");
62 STATISTIC(CondBranchTakenFreq,
63           "Potential frequency of taking conditional branches");
64 STATISTIC(UncondBranchTakenFreq,
65           "Potential frequency of taking unconditional branches");
66 
67 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
68                                        cl::desc("Force the alignment of all "
69                                                 "blocks in the function."),
70                                        cl::init(0), cl::Hidden);
71 
72 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
73     "align-all-nofallthru-blocks",
74     cl::desc("Force the alignment of all "
75              "blocks that have no fall-through predecessors (i.e. don't add "
76              "nops that are executed)."),
77     cl::init(0), cl::Hidden);
78 
79 // FIXME: Find a good default for this flag and remove the flag.
80 static cl::opt<unsigned> ExitBlockBias(
81     "block-placement-exit-block-bias",
82     cl::desc("Block frequency percentage a loop exit block needs "
83              "over the original exit to be considered the new exit."),
84     cl::init(0), cl::Hidden);
85 
86 // Definition:
87 // - Outlining: placement of a basic block outside the chain or hot path.
88 
89 static cl::opt<bool> OutlineOptionalBranches(
90     "outline-optional-branches",
91     cl::desc("Outlining optional branches will place blocks that are optional "
92               "branches, i.e. branches with a common post dominator, outside "
93               "the hot path or chain"),
94     cl::init(false), cl::Hidden);
95 
96 static cl::opt<unsigned> OutlineOptionalThreshold(
97     "outline-optional-threshold",
98     cl::desc("Don't outline optional branches that are a single block with an "
99              "instruction count below this threshold"),
100     cl::init(4), cl::Hidden);
101 
102 static cl::opt<unsigned> LoopToColdBlockRatio(
103     "loop-to-cold-block-ratio",
104     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
105              "(frequency of block) is greater than this ratio"),
106     cl::init(5), cl::Hidden);
107 
108 static cl::opt<bool>
109     PreciseRotationCost("precise-rotation-cost",
110                         cl::desc("Model the cost of loop rotation more "
111                                  "precisely by using profile data."),
112                         cl::init(false), cl::Hidden);
113 static cl::opt<bool>
114     ForcePreciseRotationCost("force-precise-rotation-cost",
115                              cl::desc("Force the use of precise cost "
116                                       "loop rotation strategy."),
117                              cl::init(false), cl::Hidden);
118 
119 static cl::opt<unsigned> MisfetchCost(
120     "misfetch-cost",
121     cl::desc("Cost that models the probabilistic risk of an instruction "
122              "misfetch due to a jump comparing to falling through, whose cost "
123              "is zero."),
124     cl::init(1), cl::Hidden);
125 
126 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
127                                       cl::desc("Cost of jump instructions."),
128                                       cl::init(1), cl::Hidden);
129 static cl::opt<bool>
130 TailDupPlacement("tail-dup-placement",
131               cl::desc("Perform tail duplication during placement. "
132                        "Creates more fallthrough opportunites in "
133                        "outline branches."),
134               cl::init(true), cl::Hidden);
135 
136 static cl::opt<bool>
137 BranchFoldPlacement("branch-fold-placement",
138               cl::desc("Perform branch folding during placement. "
139                        "Reduces code size."),
140               cl::init(true), cl::Hidden);
141 
142 // Heuristic for tail duplication.
143 static cl::opt<unsigned> TailDupPlacementThreshold(
144     "tail-dup-placement-threshold",
145     cl::desc("Instruction cutoff for tail duplication during layout. "
146              "Tail merging during layout is forced to have a threshold "
147              "that won't conflict."), cl::init(2),
148     cl::Hidden);
149 
150 // Heuristic for tail duplication.
151 static cl::opt<unsigned> TailDupPlacementPenalty(
152     "tail-dup-placement-penalty",
153     cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
154              "Copying can increase fallthrough, but it also increases icache "
155              "pressure. This parameter controls the penalty to account for that. "
156              "Percent as integer."),
157     cl::init(2),
158     cl::Hidden);
159 
160 extern cl::opt<unsigned> StaticLikelyProb;
161 extern cl::opt<unsigned> ProfileLikelyProb;
162 
163 #ifndef NDEBUG
164 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
165 extern cl::opt<std::string> ViewBlockFreqFuncName;
166 #endif
167 
168 namespace {
169 class BlockChain;
170 /// \brief Type for our function-wide basic block -> block chain mapping.
171 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
172 }
173 
174 namespace {
175 /// \brief A chain of blocks which will be laid out contiguously.
176 ///
177 /// This is the datastructure representing a chain of consecutive blocks that
178 /// are profitable to layout together in order to maximize fallthrough
179 /// probabilities and code locality. We also can use a block chain to represent
180 /// a sequence of basic blocks which have some external (correctness)
181 /// requirement for sequential layout.
182 ///
183 /// Chains can be built around a single basic block and can be merged to grow
184 /// them. They participate in a block-to-chain mapping, which is updated
185 /// automatically as chains are merged together.
186 class BlockChain {
187   /// \brief The sequence of blocks belonging to this chain.
188   ///
189   /// This is the sequence of blocks for a particular chain. These will be laid
190   /// out in-order within the function.
191   SmallVector<MachineBasicBlock *, 4> Blocks;
192 
193   /// \brief A handle to the function-wide basic block to block chain mapping.
194   ///
195   /// This is retained in each block chain to simplify the computation of child
196   /// block chains for SCC-formation and iteration. We store the edges to child
197   /// basic blocks, and map them back to their associated chains using this
198   /// structure.
199   BlockToChainMapType &BlockToChain;
200 
201 public:
202   /// \brief Construct a new BlockChain.
203   ///
204   /// This builds a new block chain representing a single basic block in the
205   /// function. It also registers itself as the chain that block participates
206   /// in with the BlockToChain mapping.
207   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
208       : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
209     assert(BB && "Cannot create a chain with a null basic block");
210     BlockToChain[BB] = this;
211   }
212 
213   /// \brief Iterator over blocks within the chain.
214   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
215 
216   /// \brief Beginning of blocks within the chain.
217   iterator begin() { return Blocks.begin(); }
218 
219   /// \brief End of blocks within the chain.
220   iterator end() { return Blocks.end(); }
221 
222   bool remove(MachineBasicBlock* BB) {
223     for(iterator i = begin(); i != end(); ++i) {
224       if (*i == BB) {
225         Blocks.erase(i);
226         return true;
227       }
228     }
229     return false;
230   }
231 
232   /// \brief Merge a block chain into this one.
233   ///
234   /// This routine merges a block chain into this one. It takes care of forming
235   /// a contiguous sequence of basic blocks, updating the edge list, and
236   /// updating the block -> chain mapping. It does not free or tear down the
237   /// old chain, but the old chain's block list is no longer valid.
238   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
239     assert(BB);
240     assert(!Blocks.empty());
241 
242     // Fast path in case we don't have a chain already.
243     if (!Chain) {
244       assert(!BlockToChain[BB]);
245       Blocks.push_back(BB);
246       BlockToChain[BB] = this;
247       return;
248     }
249 
250     assert(BB == *Chain->begin());
251     assert(Chain->begin() != Chain->end());
252 
253     // Update the incoming blocks to point to this chain, and add them to the
254     // chain structure.
255     for (MachineBasicBlock *ChainBB : *Chain) {
256       Blocks.push_back(ChainBB);
257       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
258       BlockToChain[ChainBB] = this;
259     }
260   }
261 
262 #ifndef NDEBUG
263   /// \brief Dump the blocks in this chain.
264   LLVM_DUMP_METHOD void dump() {
265     for (MachineBasicBlock *MBB : *this)
266       MBB->dump();
267   }
268 #endif // NDEBUG
269 
270   /// \brief Count of predecessors of any block within the chain which have not
271   /// yet been scheduled.  In general, we will delay scheduling this chain
272   /// until those predecessors are scheduled (or we find a sufficiently good
273   /// reason to override this heuristic.)  Note that when forming loop chains,
274   /// blocks outside the loop are ignored and treated as if they were already
275   /// scheduled.
276   ///
277   /// Note: This field is reinitialized multiple times - once for each loop,
278   /// and then once for the function as a whole.
279   unsigned UnscheduledPredecessors;
280 };
281 }
282 
283 namespace {
284 class MachineBlockPlacement : public MachineFunctionPass {
285   /// \brief A typedef for a block filter set.
286   typedef SmallSetVector<MachineBasicBlock *, 16> BlockFilterSet;
287 
288   /// Pair struct containing basic block and taildup profitiability
289   struct BlockAndTailDupResult {
290     MachineBasicBlock * BB;
291     bool ShouldTailDup;
292   };
293 
294   /// \brief work lists of blocks that are ready to be laid out
295   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
296   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
297 
298   /// \brief Machine Function
299   MachineFunction *F;
300 
301   /// \brief A handle to the branch probability pass.
302   const MachineBranchProbabilityInfo *MBPI;
303 
304   /// \brief A handle to the function-wide block frequency pass.
305   std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
306 
307   /// \brief A handle to the loop info.
308   MachineLoopInfo *MLI;
309 
310   /// \brief Preferred loop exit.
311   /// Member variable for convenience. It may be removed by duplication deep
312   /// in the call stack.
313   MachineBasicBlock *PreferredLoopExit;
314 
315   /// \brief A handle to the target's instruction info.
316   const TargetInstrInfo *TII;
317 
318   /// \brief A handle to the target's lowering info.
319   const TargetLoweringBase *TLI;
320 
321   /// \brief A handle to the dominator tree.
322   MachineDominatorTree *MDT;
323 
324   /// \brief A handle to the post dominator tree.
325   MachinePostDominatorTree *MPDT;
326 
327   /// \brief Duplicator used to duplicate tails during placement.
328   ///
329   /// Placement decisions can open up new tail duplication opportunities, but
330   /// since tail duplication affects placement decisions of later blocks, it
331   /// must be done inline.
332   TailDuplicator TailDup;
333 
334   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
335   /// all terminators of the MachineFunction.
336   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
337 
338   /// \brief Allocator and owner of BlockChain structures.
339   ///
340   /// We build BlockChains lazily while processing the loop structure of
341   /// a function. To reduce malloc traffic, we allocate them using this
342   /// slab-like allocator, and destroy them after the pass completes. An
343   /// important guarantee is that this allocator produces stable pointers to
344   /// the chains.
345   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
346 
347   /// \brief Function wide BasicBlock to BlockChain mapping.
348   ///
349   /// This mapping allows efficiently moving from any given basic block to the
350   /// BlockChain it participates in, if any. We use it to, among other things,
351   /// allow implicitly defining edges between chains as the existing edges
352   /// between basic blocks.
353   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
354 
355 #ifndef NDEBUG
356   /// The set of basic blocks that have terminators that cannot be fully
357   /// analyzed.  These basic blocks cannot be re-ordered safely by
358   /// MachineBlockPlacement, and we must preserve physical layout of these
359   /// blocks and their successors through the pass.
360   SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
361 #endif
362 
363   /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
364   /// if the count goes to 0, add them to the appropriate work list.
365   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
366                            const BlockFilterSet *BlockFilter = nullptr);
367 
368   /// Decrease the UnscheduledPredecessors count for a single block, and
369   /// if the count goes to 0, add them to the appropriate work list.
370   void markBlockSuccessors(
371       BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB,
372       const BlockFilterSet *BlockFilter = nullptr);
373 
374 
375   BranchProbability
376   collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain,
377                           const BlockFilterSet *BlockFilter,
378                           SmallVector<MachineBasicBlock *, 4> &Successors);
379   bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ,
380                                  BlockChain &Chain,
381                                  const BlockFilterSet *BlockFilter,
382                                  BranchProbability SuccProb,
383                                  BranchProbability HotProb);
384   bool repeatedlyTailDuplicateBlock(
385       MachineBasicBlock *BB, MachineBasicBlock *&LPred,
386       MachineBasicBlock *LoopHeaderBB,
387       BlockChain &Chain, BlockFilterSet *BlockFilter,
388       MachineFunction::iterator &PrevUnplacedBlockIt);
389   bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
390                                const BlockChain &Chain,
391                                BlockFilterSet *BlockFilter,
392                                MachineFunction::iterator &PrevUnplacedBlockIt,
393                                bool &DuplicatedToPred);
394   bool
395   hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ,
396                              BlockChain &SuccChain, BranchProbability SuccProb,
397                              BranchProbability RealSuccProb, BlockChain &Chain,
398                              const BlockFilterSet *BlockFilter);
399   BlockAndTailDupResult selectBestSuccessor(MachineBasicBlock *BB,
400                                             BlockChain &Chain,
401                                             const BlockFilterSet *BlockFilter);
402   MachineBasicBlock *
403   selectBestCandidateBlock(BlockChain &Chain,
404                            SmallVectorImpl<MachineBasicBlock *> &WorkList);
405   MachineBasicBlock *
406   getFirstUnplacedBlock(const BlockChain &PlacedChain,
407                         MachineFunction::iterator &PrevUnplacedBlockIt,
408                         const BlockFilterSet *BlockFilter);
409 
410   /// \brief Add a basic block to the work list if it is appropriate.
411   ///
412   /// If the optional parameter BlockFilter is provided, only MBB
413   /// present in the set will be added to the worklist. If nullptr
414   /// is provided, no filtering occurs.
415   void fillWorkLists(MachineBasicBlock *MBB,
416                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
417                      const BlockFilterSet *BlockFilter);
418   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
419                   BlockFilterSet *BlockFilter = nullptr);
420   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
421                                      const BlockFilterSet &LoopBlockSet);
422   MachineBasicBlock *findBestLoopExit(MachineLoop &L,
423                                       const BlockFilterSet &LoopBlockSet);
424   BlockFilterSet collectLoopBlockSet(MachineLoop &L);
425   void buildLoopChains(MachineLoop &L);
426   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
427                   const BlockFilterSet &LoopBlockSet);
428   void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
429                              const BlockFilterSet &LoopBlockSet);
430   void collectMustExecuteBBs();
431   void buildCFGChains();
432   void optimizeBranches();
433   void alignBlocks();
434   bool shouldTailDuplicate(MachineBasicBlock *BB);
435   /// Check the edge frequencies to see if tail duplication will increase
436   /// fallthroughs.
437   bool isProfitableToTailDup(
438     MachineBasicBlock *BB, MachineBasicBlock *Succ,
439     BranchProbability AdjustedSumProb,
440     BlockChain &Chain, const BlockFilterSet *BlockFilter);
441   /// Returns true if a block can tail duplicate into all unplaced
442   /// predecessors. Filters based on loop.
443   bool canTailDuplicateUnplacedPreds(
444       MachineBasicBlock *BB, MachineBasicBlock *Succ,
445       BlockChain &Chain, const BlockFilterSet *BlockFilter);
446 
447 public:
448   static char ID; // Pass identification, replacement for typeid
449   MachineBlockPlacement() : MachineFunctionPass(ID) {
450     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
451   }
452 
453   bool runOnMachineFunction(MachineFunction &F) override;
454 
455   void getAnalysisUsage(AnalysisUsage &AU) const override {
456     AU.addRequired<MachineBranchProbabilityInfo>();
457     AU.addRequired<MachineBlockFrequencyInfo>();
458     AU.addRequired<MachineDominatorTree>();
459     if (TailDupPlacement)
460       AU.addRequired<MachinePostDominatorTree>();
461     AU.addRequired<MachineLoopInfo>();
462     AU.addRequired<TargetPassConfig>();
463     MachineFunctionPass::getAnalysisUsage(AU);
464   }
465 };
466 }
467 
468 char MachineBlockPlacement::ID = 0;
469 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
470 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
471                       "Branch Probability Basic Block Placement", false, false)
472 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
473 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
474 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
475 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
476 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
477 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
478                     "Branch Probability Basic Block Placement", false, false)
479 
480 #ifndef NDEBUG
481 /// \brief Helper to print the name of a MBB.
482 ///
483 /// Only used by debug logging.
484 static std::string getBlockName(MachineBasicBlock *BB) {
485   std::string Result;
486   raw_string_ostream OS(Result);
487   OS << "BB#" << BB->getNumber();
488   OS << " ('" << BB->getName() << "')";
489   OS.flush();
490   return Result;
491 }
492 #endif
493 
494 /// \brief Mark a chain's successors as having one fewer preds.
495 ///
496 /// When a chain is being merged into the "placed" chain, this routine will
497 /// quickly walk the successors of each block in the chain and mark them as
498 /// having one fewer active predecessor. It also adds any successors of this
499 /// chain which reach the zero-predecessor state to the appropriate worklist.
500 void MachineBlockPlacement::markChainSuccessors(
501     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
502     const BlockFilterSet *BlockFilter) {
503   // Walk all the blocks in this chain, marking their successors as having
504   // a predecessor placed.
505   for (MachineBasicBlock *MBB : Chain) {
506     markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
507   }
508 }
509 
510 /// \brief Mark a single block's successors as having one fewer preds.
511 ///
512 /// Under normal circumstances, this is only called by markChainSuccessors,
513 /// but if a block that was to be placed is completely tail-duplicated away,
514 /// and was duplicated into the chain end, we need to redo markBlockSuccessors
515 /// for just that block.
516 void MachineBlockPlacement::markBlockSuccessors(
517     BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB,
518     const BlockFilterSet *BlockFilter) {
519   // Add any successors for which this is the only un-placed in-loop
520   // predecessor to the worklist as a viable candidate for CFG-neutral
521   // placement. No subsequent placement of this block will violate the CFG
522   // shape, so we get to use heuristics to choose a favorable placement.
523   for (MachineBasicBlock *Succ : MBB->successors()) {
524     if (BlockFilter && !BlockFilter->count(Succ))
525       continue;
526     BlockChain &SuccChain = *BlockToChain[Succ];
527     // Disregard edges within a fixed chain, or edges to the loop header.
528     if (&Chain == &SuccChain || Succ == LoopHeaderBB)
529       continue;
530 
531     // This is a cross-chain edge that is within the loop, so decrement the
532     // loop predecessor count of the destination chain.
533     if (SuccChain.UnscheduledPredecessors == 0 ||
534         --SuccChain.UnscheduledPredecessors > 0)
535       continue;
536 
537     auto *NewBB = *SuccChain.begin();
538     if (NewBB->isEHPad())
539       EHPadWorkList.push_back(NewBB);
540     else
541       BlockWorkList.push_back(NewBB);
542   }
543 }
544 
545 /// This helper function collects the set of successors of block
546 /// \p BB that are allowed to be its layout successors, and return
547 /// the total branch probability of edges from \p BB to those
548 /// blocks.
549 BranchProbability MachineBlockPlacement::collectViableSuccessors(
550     MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter,
551     SmallVector<MachineBasicBlock *, 4> &Successors) {
552   // Adjust edge probabilities by excluding edges pointing to blocks that is
553   // either not in BlockFilter or is already in the current chain. Consider the
554   // following CFG:
555   //
556   //     --->A
557   //     |  / \
558   //     | B   C
559   //     |  \ / \
560   //     ----D   E
561   //
562   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
563   // A->C is chosen as a fall-through, D won't be selected as a successor of C
564   // due to CFG constraint (the probability of C->D is not greater than
565   // HotProb to break top-order). If we exclude E that is not in BlockFilter
566   // when calculating the  probability of C->D, D will be selected and we
567   // will get A C D B as the layout of this loop.
568   auto AdjustedSumProb = BranchProbability::getOne();
569   for (MachineBasicBlock *Succ : BB->successors()) {
570     bool SkipSucc = false;
571     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
572       SkipSucc = true;
573     } else {
574       BlockChain *SuccChain = BlockToChain[Succ];
575       if (SuccChain == &Chain) {
576         SkipSucc = true;
577       } else if (Succ != *SuccChain->begin()) {
578         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
579         continue;
580       }
581     }
582     if (SkipSucc)
583       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
584     else
585       Successors.push_back(Succ);
586   }
587 
588   return AdjustedSumProb;
589 }
590 
591 /// The helper function returns the branch probability that is adjusted
592 /// or normalized over the new total \p AdjustedSumProb.
593 static BranchProbability
594 getAdjustedProbability(BranchProbability OrigProb,
595                        BranchProbability AdjustedSumProb) {
596   BranchProbability SuccProb;
597   uint32_t SuccProbN = OrigProb.getNumerator();
598   uint32_t SuccProbD = AdjustedSumProb.getNumerator();
599   if (SuccProbN >= SuccProbD)
600     SuccProb = BranchProbability::getOne();
601   else
602     SuccProb = BranchProbability(SuccProbN, SuccProbD);
603 
604   return SuccProb;
605 }
606 
607 /// Check if a block should be tail duplicated.
608 /// \p BB Block to check.
609 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
610   // Blocks with single successors don't create additional fallthrough
611   // opportunities. Don't duplicate them. TODO: When conditional exits are
612   // analyzable, allow them to be duplicated.
613   bool IsSimple = TailDup.isSimpleBB(BB);
614 
615   if (BB->succ_size() == 1)
616     return false;
617   return TailDup.shouldTailDuplicate(IsSimple, *BB);
618 }
619 
620 /// Compare 2 BlockFrequency's with a small penalty for \p A.
621 /// In order to be conservative, we apply a X% penalty to account for
622 /// increased icache pressure and static heuristics. For small frequencies
623 /// we use only the numerators to improve accuracy. For simplicity, we assume the
624 /// penalty is less than 100%
625 /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
626 static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
627                             uint64_t EntryFreq) {
628   BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
629   BlockFrequency Gain = A - B;
630   return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
631 }
632 
633 /// Check the edge frequencies to see if tail duplication will increase
634 /// fallthroughs. It only makes sense to call this function when
635 /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
636 /// always locally profitable if we would have picked \p Succ without
637 /// considering duplication.
638 bool MachineBlockPlacement::isProfitableToTailDup(
639     MachineBasicBlock *BB, MachineBasicBlock *Succ,
640     BranchProbability QProb,
641     BlockChain &Chain, const BlockFilterSet *BlockFilter) {
642   // We need to do a probability calculation to make sure this is profitable.
643   // First: does succ have a successor that post-dominates? This affects the
644   // calculation. The 2 relevant cases are:
645   //    BB         BB
646   //    | \Qout    | \Qout
647   //   P|  C       |P C
648   //    =   C'     =   C'
649   //    |  /Qin    |  /Qin
650   //    | /        | /
651   //    Succ       Succ
652   //    / \        | \  V
653   //  U/   =V      |U \
654   //  /     \      =   D
655   //  D      E     |  /
656   //               | /
657   //               |/
658   //               PDom
659   //  '=' : Branch taken for that CFG edge
660   // In the second case, Placing Succ while duplicating it into C prevents the
661   // fallthrough of Succ into either D or PDom, because they now have C as an
662   // unplaced predecessor
663 
664   // Start by figuring out which case we fall into
665   MachineBasicBlock *PDom = nullptr;
666   SmallVector<MachineBasicBlock *, 4> SuccSuccs;
667   // Only scan the relevant successors
668   auto AdjustedSuccSumProb =
669       collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
670   BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
671   auto BBFreq = MBFI->getBlockFreq(BB);
672   auto SuccFreq = MBFI->getBlockFreq(Succ);
673   BlockFrequency P = BBFreq * PProb;
674   BlockFrequency Qout = BBFreq * QProb;
675   uint64_t EntryFreq = MBFI->getEntryFreq();
676   // If there are no more successors, it is profitable to copy, as it strictly
677   // increases fallthrough.
678   if (SuccSuccs.size() == 0)
679     return greaterWithBias(P, Qout, EntryFreq);
680 
681   auto BestSuccSucc = BranchProbability::getZero();
682   // Find the PDom or the best Succ if no PDom exists.
683   for (MachineBasicBlock *SuccSucc : SuccSuccs) {
684     auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
685     if (Prob > BestSuccSucc)
686       BestSuccSucc = Prob;
687     if (PDom == nullptr)
688       if (MPDT->dominates(SuccSucc, Succ)) {
689         PDom = SuccSucc;
690         break;
691       }
692   }
693   // For the comparisons, we need to know Succ's best incoming edge that isn't
694   // from BB.
695   auto SuccBestPred = BlockFrequency(0);
696   for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
697     if (SuccPred == Succ || SuccPred == BB
698         || BlockToChain[SuccPred] == &Chain
699         || (BlockFilter && !BlockFilter->count(SuccPred)))
700       continue;
701     auto Freq = MBFI->getBlockFreq(SuccPred)
702         * MBPI->getEdgeProbability(SuccPred, Succ);
703     if (Freq > SuccBestPred)
704       SuccBestPred = Freq;
705   }
706   // Qin is Succ's best unplaced incoming edge that isn't BB
707   BlockFrequency Qin = SuccBestPred;
708   // If it doesn't have a post-dominating successor, here is the calculation:
709   //    BB        BB
710   //    | \Qout   |  \
711   //   P|  C      |   =
712   //    =   C'    |    C
713   //    |  /Qin   |     |
714   //    | /       |     C' (+Succ)
715   //    Succ      Succ /|
716   //    / \       |  \/ |
717   //  U/   =V     =  /= =
718   //  /     \     | /  \|
719   //  D      E    D     E
720   //  '=' : Branch taken for that CFG edge
721   //  Cost in the first case is: P + V
722   //  For this calculation, we always assume P > Qout. If Qout > P
723   //  The result of this function will be ignored at the caller.
724   //  Cost in the second case is: Qout + Qin * V + P * U + P * V
725   //  TODO(iteratee): If we lay out D after Succ, the P * U term
726   //  goes away. This logic is coming in D28522.
727 
728   if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
729     BranchProbability UProb = BestSuccSucc;
730     BranchProbability VProb = AdjustedSuccSumProb - UProb;
731     BlockFrequency V = SuccFreq * VProb;
732     BlockFrequency QinV = Qin * VProb;
733     BlockFrequency BaseCost = P + V;
734     BlockFrequency DupCost = Qout + QinV + P * AdjustedSuccSumProb;
735     return greaterWithBias(BaseCost, DupCost, EntryFreq);
736   }
737   BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
738   BranchProbability VProb = AdjustedSuccSumProb - UProb;
739   BlockFrequency U = SuccFreq * UProb;
740   BlockFrequency V = SuccFreq * VProb;
741   // If there is a post-dominating successor, here is the calculation:
742   // BB         BB                 BB          BB
743   // | \Qout    |  \               | \Qout     |  \
744   // |P C       |   =              |P C        |   =
745   // =   C'     |P   C             =   C'      |P   C
746   // |  /Qin    |     |            |  /Qin     |     |
747   // | /        |     C' (+Succ)   | /         |     C' (+Succ)
748   // Succ       Succ /|            Succ        Succ /|
749   // | \  V     |  \/ |            | \  V      |  \/ |
750   // |U \       |U /\ |            |U =        |U /\ |
751   // =   D      = =  =|            |   D       | =  =|
752   // |  /       |/    D            |  /        |/    D
753   // | /        |    /             | =         |    /
754   // |/         |   /              |/          |   =
755   // Dom        Dom                Dom         Dom
756   //  '=' : Branch taken for that CFG edge
757   // The cost for taken branches in the first case is P + U
758   // The cost in the second case (assuming independence), given the layout:
759   // BB, Succ, (C+Succ), D, Dom
760   // is Qout + P * V + Qin * U
761   // compare P + U vs Qout + P + Qin * U.
762   //
763   // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
764   //
765   // For the 3rd case, the cost is P + 2 * V
766   // For the 4th case, the cost is Qout + Qin * U + P * V + V
767   // We choose 4 over 3 when (P + V) > Qout + Qin * U + P * V
768   if (UProb > AdjustedSuccSumProb / 2
769       && !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom],
770                                      UProb, UProb, Chain, BlockFilter)) {
771     // Cases 3 & 4
772     return greaterWithBias((P + V), (Qout + Qin * UProb + P * VProb),
773                            EntryFreq);
774   }
775   // Cases 1 & 2
776   return greaterWithBias(
777       (P + U), (Qout + Qin * UProb + P * AdjustedSuccSumProb), EntryFreq);
778 }
779 
780 
781 /// When the option TailDupPlacement is on, this method checks if the
782 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
783 /// into all of its unplaced, unfiltered predecessors, that are not BB.
784 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
785     MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
786     const BlockFilterSet *BlockFilter) {
787   if (!shouldTailDuplicate(Succ))
788     return false;
789 
790   for (MachineBasicBlock *Pred : Succ->predecessors()) {
791     // Make sure all unplaced and unfiltered predecessors can be
792     // tail-duplicated into.
793     if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
794         || BlockToChain[Pred] == &Chain)
795       continue;
796     if (!TailDup.canTailDuplicate(Succ, Pred))
797       return false;
798   }
799   return true;
800 }
801 
802 /// When the option OutlineOptionalBranches is on, this method
803 /// checks if the fallthrough candidate block \p Succ (of block
804 /// \p BB) also has other unscheduled predecessor blocks which
805 /// are also successors of \p BB (forming triangular shape CFG).
806 /// If none of such predecessors are small, it returns true.
807 /// The caller can choose to select \p Succ as the layout successors
808 /// so that \p Succ's predecessors (optional branches) can be
809 /// outlined.
810 /// FIXME: fold this with more general layout cost analysis.
811 bool MachineBlockPlacement::shouldPredBlockBeOutlined(
812     MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain,
813     const BlockFilterSet *BlockFilter, BranchProbability SuccProb,
814     BranchProbability HotProb) {
815   if (!OutlineOptionalBranches)
816     return false;
817   // If we outline optional branches, look whether Succ is unavoidable, i.e.
818   // dominates all terminators of the MachineFunction. If it does, other
819   // successors must be optional. Don't do this for cold branches.
820   if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) {
821     for (MachineBasicBlock *Pred : Succ->predecessors()) {
822       // Check whether there is an unplaced optional branch.
823       if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
824           BlockToChain[Pred] == &Chain)
825         continue;
826       // Check whether the optional branch has exactly one BB.
827       if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
828         continue;
829       // Check whether the optional branch is small.
830       if (Pred->size() < OutlineOptionalThreshold)
831         return false;
832     }
833     return true;
834   } else
835     return false;
836 }
837 
838 // When profile is not present, return the StaticLikelyProb.
839 // When profile is available, we need to handle the triangle-shape CFG.
840 static BranchProbability getLayoutSuccessorProbThreshold(
841       MachineBasicBlock *BB) {
842   if (!BB->getParent()->getFunction()->getEntryCount())
843     return BranchProbability(StaticLikelyProb, 100);
844   if (BB->succ_size() == 2) {
845     const MachineBasicBlock *Succ1 = *BB->succ_begin();
846     const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
847     if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
848       /* See case 1 below for the cost analysis. For BB->Succ to
849        * be taken with smaller cost, the following needs to hold:
850        *   Prob(BB->Succ) > 2 * Prob(BB->Pred)
851        *   So the threshold T in the calculation below
852        *   (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
853        *   So T / (1 - T) = 2, Yielding T = 2/3
854        * Also adding user specified branch bias, we have
855        *   T = (2/3)*(ProfileLikelyProb/50)
856        *     = (2*ProfileLikelyProb)/150)
857        */
858       return BranchProbability(2 * ProfileLikelyProb, 150);
859     }
860   }
861   return BranchProbability(ProfileLikelyProb, 100);
862 }
863 
864 /// Checks to see if the layout candidate block \p Succ has a better layout
865 /// predecessor than \c BB. If yes, returns true.
866 /// \p SuccProb: The probability adjusted for only remaining blocks.
867 ///   Only used for logging
868 /// \p RealSuccProb: The un-adjusted probability.
869 /// \p Chain: The chain that BB belongs to and Succ is being considered for.
870 /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
871 ///    considered
872 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
873     MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain,
874     BranchProbability SuccProb, BranchProbability RealSuccProb,
875     BlockChain &Chain, const BlockFilterSet *BlockFilter) {
876 
877   // There isn't a better layout when there are no unscheduled predecessors.
878   if (SuccChain.UnscheduledPredecessors == 0)
879     return false;
880 
881   // There are two basic scenarios here:
882   // -------------------------------------
883   // Case 1: triangular shape CFG (if-then):
884   //     BB
885   //     | \
886   //     |  \
887   //     |   Pred
888   //     |   /
889   //     Succ
890   // In this case, we are evaluating whether to select edge -> Succ, e.g.
891   // set Succ as the layout successor of BB. Picking Succ as BB's
892   // successor breaks the CFG constraints (FIXME: define these constraints).
893   // With this layout, Pred BB
894   // is forced to be outlined, so the overall cost will be cost of the
895   // branch taken from BB to Pred, plus the cost of back taken branch
896   // from Pred to Succ, as well as the additional cost associated
897   // with the needed unconditional jump instruction from Pred To Succ.
898 
899   // The cost of the topological order layout is the taken branch cost
900   // from BB to Succ, so to make BB->Succ a viable candidate, the following
901   // must hold:
902   //     2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
903   //      < freq(BB->Succ) *  taken_branch_cost.
904   // Ignoring unconditional jump cost, we get
905   //    freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
906   //    prob(BB->Succ) > 2 * prob(BB->Pred)
907   //
908   // When real profile data is available, we can precisely compute the
909   // probability threshold that is needed for edge BB->Succ to be considered.
910   // Without profile data, the heuristic requires the branch bias to be
911   // a lot larger to make sure the signal is very strong (e.g. 80% default).
912   // -----------------------------------------------------------------
913   // Case 2: diamond like CFG (if-then-else):
914   //     S
915   //    / \
916   //   |   \
917   //  BB    Pred
918   //   \    /
919   //    Succ
920   //    ..
921   //
922   // The current block is BB and edge BB->Succ is now being evaluated.
923   // Note that edge S->BB was previously already selected because
924   // prob(S->BB) > prob(S->Pred).
925   // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
926   // choose Pred, we will have a topological ordering as shown on the left
927   // in the picture below. If we choose Succ, we have the solution as shown
928   // on the right:
929   //
930   //   topo-order:
931   //
932   //       S-----                             ---S
933   //       |    |                             |  |
934   //    ---BB   |                             |  BB
935   //    |       |                             |  |
936   //    |  pred--                             |  Succ--
937   //    |  |                                  |       |
938   //    ---succ                               ---pred--
939   //
940   // cost = freq(S->Pred) + freq(BB->Succ)    cost = 2 * freq (S->Pred)
941   //      = freq(S->Pred) + freq(S->BB)
942   //
943   // If we have profile data (i.e, branch probabilities can be trusted), the
944   // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
945   // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
946   // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
947   // means the cost of topological order is greater.
948   // When profile data is not available, however, we need to be more
949   // conservative. If the branch prediction is wrong, breaking the topo-order
950   // will actually yield a layout with large cost. For this reason, we need
951   // strong biased branch at block S with Prob(S->BB) in order to select
952   // BB->Succ. This is equivalent to looking the CFG backward with backward
953   // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
954   // profile data).
955   // --------------------------------------------------------------------------
956   // Case 3: forked diamond
957   //       S
958   //      / \
959   //     /   \
960   //   BB    Pred
961   //   | \   / |
962   //   |  \ /  |
963   //   |   X   |
964   //   |  / \  |
965   //   | /   \ |
966   //   S1     S2
967   //
968   // The current block is BB and edge BB->S1 is now being evaluated.
969   // As above S->BB was already selected because
970   // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
971   //
972   // topo-order:
973   //
974   //     S-------|                     ---S
975   //     |       |                     |  |
976   //  ---BB      |                     |  BB
977   //  |          |                     |  |
978   //  |  Pred----|                     |  S1----
979   //  |  |                             |       |
980   //  --(S1 or S2)                     ---Pred--
981   //
982   // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
983   //    + min(freq(Pred->S1), freq(Pred->S2))
984   // Non-topo-order cost:
985   // In the worst case, S2 will not get laid out after Pred.
986   // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
987   // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
988   // is 0. Then the non topo layout is better when
989   // freq(S->Pred) < freq(BB->S1).
990   // This is exactly what is checked below.
991   // Note there are other shapes that apply (Pred may not be a single block,
992   // but they all fit this general pattern.)
993   BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
994 
995   // Make sure that a hot successor doesn't have a globally more
996   // important predecessor.
997   BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
998   bool BadCFGConflict = false;
999 
1000   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1001     if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1002         (BlockFilter && !BlockFilter->count(Pred)) ||
1003         BlockToChain[Pred] == &Chain ||
1004         // This check is redundant except for look ahead. This function is
1005         // called for lookahead by isProfitableToTailDup when BB hasn't been
1006         // placed yet.
1007         (Pred == BB))
1008       continue;
1009     // Do backward checking.
1010     // For all cases above, we need a backward checking to filter out edges that
1011     // are not 'strongly' biased.
1012     // BB  Pred
1013     //  \ /
1014     //  Succ
1015     // We select edge BB->Succ if
1016     //      freq(BB->Succ) > freq(Succ) * HotProb
1017     //      i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1018     //      HotProb
1019     //      i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1020     // Case 1 is covered too, because the first equation reduces to:
1021     // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
1022     BlockFrequency PredEdgeFreq =
1023         MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1024     if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1025       BadCFGConflict = true;
1026       break;
1027     }
1028   }
1029 
1030   if (BadCFGConflict) {
1031     DEBUG(dbgs() << "    Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
1032                  << " (prob) (non-cold CFG conflict)\n");
1033     return true;
1034   }
1035 
1036   return false;
1037 }
1038 
1039 /// \brief Select the best successor for a block.
1040 ///
1041 /// This looks across all successors of a particular block and attempts to
1042 /// select the "best" one to be the layout successor. It only considers direct
1043 /// successors which also pass the block filter. It will attempt to avoid
1044 /// breaking CFG structure, but cave and break such structures in the case of
1045 /// very hot successor edges.
1046 ///
1047 /// \returns The best successor block found, or null if none are viable, along
1048 /// with a boolean indicating if tail duplication is necessary.
1049 MachineBlockPlacement::BlockAndTailDupResult
1050 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
1051                                            BlockChain &Chain,
1052                                            const BlockFilterSet *BlockFilter) {
1053   const BranchProbability HotProb(StaticLikelyProb, 100);
1054 
1055   BlockAndTailDupResult BestSucc = { nullptr, false };
1056   auto BestProb = BranchProbability::getZero();
1057 
1058   SmallVector<MachineBasicBlock *, 4> Successors;
1059   auto AdjustedSumProb =
1060       collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1061 
1062   DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
1063 
1064   // For blocks with CFG violations, we may be able to lay them out anyway with
1065   // tail-duplication. We keep this vector so we can perform the probability
1066   // calculations the minimum number of times.
1067   SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1068       DupCandidates;
1069   for (MachineBasicBlock *Succ : Successors) {
1070     auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1071     BranchProbability SuccProb =
1072         getAdjustedProbability(RealSuccProb, AdjustedSumProb);
1073 
1074     // This heuristic is off by default.
1075     if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb,
1076                                   HotProb)) {
1077       BestSucc.BB = Succ;
1078       return BestSucc;
1079     }
1080 
1081     BlockChain &SuccChain = *BlockToChain[Succ];
1082     // Skip the edge \c BB->Succ if block \c Succ has a better layout
1083     // predecessor that yields lower global cost.
1084     if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1085                                    Chain, BlockFilter)) {
1086       // If tail duplication would make Succ profitable, place it.
1087       if (TailDupPlacement && shouldTailDuplicate(Succ))
1088         DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
1089       continue;
1090     }
1091 
1092     DEBUG(
1093         dbgs() << "    Candidate: " << getBlockName(Succ) << ", probability: "
1094                << SuccProb
1095                << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1096                << "\n");
1097 
1098     if (BestSucc.BB && BestProb >= SuccProb) {
1099       DEBUG(dbgs() << "    Not the best candidate, continuing\n");
1100       continue;
1101     }
1102 
1103     DEBUG(dbgs() << "    Setting it as best candidate\n");
1104     BestSucc.BB = Succ;
1105     BestProb = SuccProb;
1106   }
1107   // Handle the tail duplication candidates in order of decreasing probability.
1108   // Stop at the first one that is profitable. Also stop if they are less
1109   // profitable than BestSucc. Position is important because we preserve it and
1110   // prefer first best match. Here we aren't comparing in order, so we capture
1111   // the position instead.
1112   if (DupCandidates.size() != 0) {
1113     auto cmp =
1114         [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1115            const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1116           return std::get<0>(a) > std::get<0>(b);
1117         };
1118     std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1119   }
1120   for(auto &Tup : DupCandidates) {
1121     BranchProbability DupProb;
1122     MachineBasicBlock *Succ;
1123     std::tie(DupProb, Succ) = Tup;
1124     if (DupProb < BestProb)
1125       break;
1126     if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1127         // If tail duplication gives us fallthrough when we otherwise wouldn't
1128         // have it, that is a strict gain.
1129         && (BestSucc.BB == nullptr
1130             || isProfitableToTailDup(BB, Succ, BestProb, Chain,
1131                                      BlockFilter))) {
1132       DEBUG(
1133           dbgs() << "    Candidate: " << getBlockName(Succ) << ", probability: "
1134                  << DupProb
1135                  << " (Tail Duplicate)\n");
1136       BestSucc.BB = Succ;
1137       BestSucc.ShouldTailDup = true;
1138       break;
1139     }
1140   }
1141 
1142   if (BestSucc.BB)
1143     DEBUG(dbgs() << "    Selected: " << getBlockName(BestSucc.BB) << "\n");
1144 
1145   return BestSucc;
1146 }
1147 
1148 /// \brief Select the best block from a worklist.
1149 ///
1150 /// This looks through the provided worklist as a list of candidate basic
1151 /// blocks and select the most profitable one to place. The definition of
1152 /// profitable only really makes sense in the context of a loop. This returns
1153 /// the most frequently visited block in the worklist, which in the case of
1154 /// a loop, is the one most desirable to be physically close to the rest of the
1155 /// loop body in order to improve i-cache behavior.
1156 ///
1157 /// \returns The best block found, or null if none are viable.
1158 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
1159     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1160   // Once we need to walk the worklist looking for a candidate, cleanup the
1161   // worklist of already placed entries.
1162   // FIXME: If this shows up on profiles, it could be folded (at the cost of
1163   // some code complexity) into the loop below.
1164   WorkList.erase(remove_if(WorkList,
1165                            [&](MachineBasicBlock *BB) {
1166                              return BlockToChain.lookup(BB) == &Chain;
1167                            }),
1168                  WorkList.end());
1169 
1170   if (WorkList.empty())
1171     return nullptr;
1172 
1173   bool IsEHPad = WorkList[0]->isEHPad();
1174 
1175   MachineBasicBlock *BestBlock = nullptr;
1176   BlockFrequency BestFreq;
1177   for (MachineBasicBlock *MBB : WorkList) {
1178     assert(MBB->isEHPad() == IsEHPad);
1179 
1180     BlockChain &SuccChain = *BlockToChain[MBB];
1181     if (&SuccChain == &Chain)
1182       continue;
1183 
1184     assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
1185 
1186     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1187     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
1188           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
1189 
1190     // For ehpad, we layout the least probable first as to avoid jumping back
1191     // from least probable landingpads to more probable ones.
1192     //
1193     // FIXME: Using probability is probably (!) not the best way to achieve
1194     // this. We should probably have a more principled approach to layout
1195     // cleanup code.
1196     //
1197     // The goal is to get:
1198     //
1199     //                 +--------------------------+
1200     //                 |                          V
1201     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
1202     //
1203     // Rather than:
1204     //
1205     //                 +-------------------------------------+
1206     //                 V                                     |
1207     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
1208     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1209       continue;
1210 
1211     BestBlock = MBB;
1212     BestFreq = CandidateFreq;
1213   }
1214 
1215   return BestBlock;
1216 }
1217 
1218 /// \brief Retrieve the first unplaced basic block.
1219 ///
1220 /// This routine is called when we are unable to use the CFG to walk through
1221 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1222 /// We walk through the function's blocks in order, starting from the
1223 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
1224 /// re-scanning the entire sequence on repeated calls to this routine.
1225 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1226     const BlockChain &PlacedChain,
1227     MachineFunction::iterator &PrevUnplacedBlockIt,
1228     const BlockFilterSet *BlockFilter) {
1229   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1230        ++I) {
1231     if (BlockFilter && !BlockFilter->count(&*I))
1232       continue;
1233     if (BlockToChain[&*I] != &PlacedChain) {
1234       PrevUnplacedBlockIt = I;
1235       // Now select the head of the chain to which the unplaced block belongs
1236       // as the block to place. This will force the entire chain to be placed,
1237       // and satisfies the requirements of merging chains.
1238       return *BlockToChain[&*I]->begin();
1239     }
1240   }
1241   return nullptr;
1242 }
1243 
1244 void MachineBlockPlacement::fillWorkLists(
1245     MachineBasicBlock *MBB,
1246     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1247     const BlockFilterSet *BlockFilter = nullptr) {
1248   BlockChain &Chain = *BlockToChain[MBB];
1249   if (!UpdatedPreds.insert(&Chain).second)
1250     return;
1251 
1252   assert(Chain.UnscheduledPredecessors == 0);
1253   for (MachineBasicBlock *ChainBB : Chain) {
1254     assert(BlockToChain[ChainBB] == &Chain);
1255     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1256       if (BlockFilter && !BlockFilter->count(Pred))
1257         continue;
1258       if (BlockToChain[Pred] == &Chain)
1259         continue;
1260       ++Chain.UnscheduledPredecessors;
1261     }
1262   }
1263 
1264   if (Chain.UnscheduledPredecessors != 0)
1265     return;
1266 
1267   MBB = *Chain.begin();
1268   if (MBB->isEHPad())
1269     EHPadWorkList.push_back(MBB);
1270   else
1271     BlockWorkList.push_back(MBB);
1272 }
1273 
1274 void MachineBlockPlacement::buildChain(
1275     MachineBasicBlock *BB, BlockChain &Chain,
1276     BlockFilterSet *BlockFilter) {
1277   assert(BB && "BB must not be null.\n");
1278   assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n");
1279   MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1280 
1281   MachineBasicBlock *LoopHeaderBB = BB;
1282   markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1283   BB = *std::prev(Chain.end());
1284   for (;;) {
1285     assert(BB && "null block found at end of chain in loop.");
1286     assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1287     assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1288 
1289 
1290     // Look for the best viable successor if there is one to place immediately
1291     // after this block.
1292     auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1293     MachineBasicBlock* BestSucc = Result.BB;
1294     bool ShouldTailDup = Result.ShouldTailDup;
1295     if (TailDupPlacement)
1296       ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
1297 
1298     // If an immediate successor isn't available, look for the best viable
1299     // block among those we've identified as not violating the loop's CFG at
1300     // this point. This won't be a fallthrough, but it will increase locality.
1301     if (!BestSucc)
1302       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1303     if (!BestSucc)
1304       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1305 
1306     if (!BestSucc) {
1307       BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1308       if (!BestSucc)
1309         break;
1310 
1311       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1312                       "layout successor until the CFG reduces\n");
1313     }
1314 
1315     // Placement may have changed tail duplication opportunities.
1316     // Check for that now.
1317     if (TailDupPlacement && BestSucc && ShouldTailDup) {
1318       // If the chosen successor was duplicated into all its predecessors,
1319       // don't bother laying it out, just go round the loop again with BB as
1320       // the chain end.
1321       if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1322                                        BlockFilter, PrevUnplacedBlockIt))
1323         continue;
1324     }
1325 
1326     // Place this block, updating the datastructures to reflect its placement.
1327     BlockChain &SuccChain = *BlockToChain[BestSucc];
1328     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
1329     // we selected a successor that didn't fit naturally into the CFG.
1330     SuccChain.UnscheduledPredecessors = 0;
1331     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1332                  << getBlockName(BestSucc) << "\n");
1333     markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1334     Chain.merge(BestSucc, &SuccChain);
1335     BB = *std::prev(Chain.end());
1336   }
1337 
1338   DEBUG(dbgs() << "Finished forming chain for header block "
1339                << getBlockName(*Chain.begin()) << "\n");
1340 }
1341 
1342 /// \brief Find the best loop top block for layout.
1343 ///
1344 /// Look for a block which is strictly better than the loop header for laying
1345 /// out at the top of the loop. This looks for one and only one pattern:
1346 /// a latch block with no conditional exit. This block will cause a conditional
1347 /// jump around it or will be the bottom of the loop if we lay it out in place,
1348 /// but if it it doesn't end up at the bottom of the loop for any reason,
1349 /// rotation alone won't fix it. Because such a block will always result in an
1350 /// unconditional jump (for the backedge) rotating it in front of the loop
1351 /// header is always profitable.
1352 MachineBasicBlock *
1353 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
1354                                        const BlockFilterSet &LoopBlockSet) {
1355   // Placing the latch block before the header may introduce an extra branch
1356   // that skips this block the first time the loop is executed, which we want
1357   // to avoid when optimising for size.
1358   // FIXME: in theory there is a case that does not introduce a new branch,
1359   // i.e. when the layout predecessor does not fallthrough to the loop header.
1360   // In practice this never happens though: there always seems to be a preheader
1361   // that can fallthrough and that is also placed before the header.
1362   if (F->getFunction()->optForSize())
1363     return L.getHeader();
1364 
1365   // Check that the header hasn't been fused with a preheader block due to
1366   // crazy branches. If it has, we need to start with the header at the top to
1367   // prevent pulling the preheader into the loop body.
1368   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1369   if (!LoopBlockSet.count(*HeaderChain.begin()))
1370     return L.getHeader();
1371 
1372   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1373                << "\n");
1374 
1375   BlockFrequency BestPredFreq;
1376   MachineBasicBlock *BestPred = nullptr;
1377   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
1378     if (!LoopBlockSet.count(Pred))
1379       continue;
1380     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", has "
1381                  << Pred->succ_size() << " successors, ";
1382           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
1383     if (Pred->succ_size() > 1)
1384       continue;
1385 
1386     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1387     if (!BestPred || PredFreq > BestPredFreq ||
1388         (!(PredFreq < BestPredFreq) &&
1389          Pred->isLayoutSuccessor(L.getHeader()))) {
1390       BestPred = Pred;
1391       BestPredFreq = PredFreq;
1392     }
1393   }
1394 
1395   // If no direct predecessor is fine, just use the loop header.
1396   if (!BestPred) {
1397     DEBUG(dbgs() << "    final top unchanged\n");
1398     return L.getHeader();
1399   }
1400 
1401   // Walk backwards through any straight line of predecessors.
1402   while (BestPred->pred_size() == 1 &&
1403          (*BestPred->pred_begin())->succ_size() == 1 &&
1404          *BestPred->pred_begin() != L.getHeader())
1405     BestPred = *BestPred->pred_begin();
1406 
1407   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
1408   return BestPred;
1409 }
1410 
1411 /// \brief Find the best loop exiting block for layout.
1412 ///
1413 /// This routine implements the logic to analyze the loop looking for the best
1414 /// block to layout at the top of the loop. Typically this is done to maximize
1415 /// fallthrough opportunities.
1416 MachineBasicBlock *
1417 MachineBlockPlacement::findBestLoopExit(MachineLoop &L,
1418                                         const BlockFilterSet &LoopBlockSet) {
1419   // We don't want to layout the loop linearly in all cases. If the loop header
1420   // is just a normal basic block in the loop, we want to look for what block
1421   // within the loop is the best one to layout at the top. However, if the loop
1422   // header has be pre-merged into a chain due to predecessors not having
1423   // analyzable branches, *and* the predecessor it is merged with is *not* part
1424   // of the loop, rotating the header into the middle of the loop will create
1425   // a non-contiguous range of blocks which is Very Bad. So start with the
1426   // header and only rotate if safe.
1427   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1428   if (!LoopBlockSet.count(*HeaderChain.begin()))
1429     return nullptr;
1430 
1431   BlockFrequency BestExitEdgeFreq;
1432   unsigned BestExitLoopDepth = 0;
1433   MachineBasicBlock *ExitingBB = nullptr;
1434   // If there are exits to outer loops, loop rotation can severely limit
1435   // fallthrough opportunities unless it selects such an exit. Keep a set of
1436   // blocks where rotating to exit with that block will reach an outer loop.
1437   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1438 
1439   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1440                << "\n");
1441   for (MachineBasicBlock *MBB : L.getBlocks()) {
1442     BlockChain &Chain = *BlockToChain[MBB];
1443     // Ensure that this block is at the end of a chain; otherwise it could be
1444     // mid-way through an inner loop or a successor of an unanalyzable branch.
1445     if (MBB != *std::prev(Chain.end()))
1446       continue;
1447 
1448     // Now walk the successors. We need to establish whether this has a viable
1449     // exiting successor and whether it has a viable non-exiting successor.
1450     // We store the old exiting state and restore it if a viable looping
1451     // successor isn't found.
1452     MachineBasicBlock *OldExitingBB = ExitingBB;
1453     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
1454     bool HasLoopingSucc = false;
1455     for (MachineBasicBlock *Succ : MBB->successors()) {
1456       if (Succ->isEHPad())
1457         continue;
1458       if (Succ == MBB)
1459         continue;
1460       BlockChain &SuccChain = *BlockToChain[Succ];
1461       // Don't split chains, either this chain or the successor's chain.
1462       if (&Chain == &SuccChain) {
1463         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
1464                      << getBlockName(Succ) << " (chain conflict)\n");
1465         continue;
1466       }
1467 
1468       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
1469       if (LoopBlockSet.count(Succ)) {
1470         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
1471                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
1472         HasLoopingSucc = true;
1473         continue;
1474       }
1475 
1476       unsigned SuccLoopDepth = 0;
1477       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
1478         SuccLoopDepth = ExitLoop->getLoopDepth();
1479         if (ExitLoop->contains(&L))
1480           BlocksExitingToOuterLoop.insert(MBB);
1481       }
1482 
1483       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1484       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
1485                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
1486             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
1487       // Note that we bias this toward an existing layout successor to retain
1488       // incoming order in the absence of better information. The exit must have
1489       // a frequency higher than the current exit before we consider breaking
1490       // the layout.
1491       BranchProbability Bias(100 - ExitBlockBias, 100);
1492       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
1493           ExitEdgeFreq > BestExitEdgeFreq ||
1494           (MBB->isLayoutSuccessor(Succ) &&
1495            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
1496         BestExitEdgeFreq = ExitEdgeFreq;
1497         ExitingBB = MBB;
1498       }
1499     }
1500 
1501     if (!HasLoopingSucc) {
1502       // Restore the old exiting state, no viable looping successor was found.
1503       ExitingBB = OldExitingBB;
1504       BestExitEdgeFreq = OldBestExitEdgeFreq;
1505     }
1506   }
1507   // Without a candidate exiting block or with only a single block in the
1508   // loop, just use the loop header to layout the loop.
1509   if (!ExitingBB) {
1510     DEBUG(dbgs() << "    No other candidate exit blocks, using loop header\n");
1511     return nullptr;
1512   }
1513   if (L.getNumBlocks() == 1) {
1514     DEBUG(dbgs() << "    Loop has 1 block, using loop header as exit\n");
1515     return nullptr;
1516   }
1517 
1518   // Also, if we have exit blocks which lead to outer loops but didn't select
1519   // one of them as the exiting block we are rotating toward, disable loop
1520   // rotation altogether.
1521   if (!BlocksExitingToOuterLoop.empty() &&
1522       !BlocksExitingToOuterLoop.count(ExitingBB))
1523     return nullptr;
1524 
1525   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
1526   return ExitingBB;
1527 }
1528 
1529 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
1530 ///
1531 /// Once we have built a chain, try to rotate it to line up the hot exit block
1532 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1533 /// branches. For example, if the loop has fallthrough into its header and out
1534 /// of its bottom already, don't rotate it.
1535 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1536                                        MachineBasicBlock *ExitingBB,
1537                                        const BlockFilterSet &LoopBlockSet) {
1538   if (!ExitingBB)
1539     return;
1540 
1541   MachineBasicBlock *Top = *LoopChain.begin();
1542   bool ViableTopFallthrough = false;
1543   for (MachineBasicBlock *Pred : Top->predecessors()) {
1544     BlockChain *PredChain = BlockToChain[Pred];
1545     if (!LoopBlockSet.count(Pred) &&
1546         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1547       ViableTopFallthrough = true;
1548       break;
1549     }
1550   }
1551 
1552   // If the header has viable fallthrough, check whether the current loop
1553   // bottom is a viable exiting block. If so, bail out as rotating will
1554   // introduce an unnecessary branch.
1555   if (ViableTopFallthrough) {
1556     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
1557     for (MachineBasicBlock *Succ : Bottom->successors()) {
1558       BlockChain *SuccChain = BlockToChain[Succ];
1559       if (!LoopBlockSet.count(Succ) &&
1560           (!SuccChain || Succ == *SuccChain->begin()))
1561         return;
1562     }
1563   }
1564 
1565   BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
1566   if (ExitIt == LoopChain.end())
1567     return;
1568 
1569   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
1570 }
1571 
1572 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1573 ///
1574 /// With profile data, we can determine the cost in terms of missed fall through
1575 /// opportunities when rotating a loop chain and select the best rotation.
1576 /// Basically, there are three kinds of cost to consider for each rotation:
1577 ///    1. The possibly missed fall through edge (if it exists) from BB out of
1578 ///    the loop to the loop header.
1579 ///    2. The possibly missed fall through edges (if they exist) from the loop
1580 ///    exits to BB out of the loop.
1581 ///    3. The missed fall through edge (if it exists) from the last BB to the
1582 ///    first BB in the loop chain.
1583 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
1584 ///  We select the best rotation with the smallest cost.
1585 void MachineBlockPlacement::rotateLoopWithProfile(
1586     BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
1587   auto HeaderBB = L.getHeader();
1588   auto HeaderIter = find(LoopChain, HeaderBB);
1589   auto RotationPos = LoopChain.end();
1590 
1591   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1592 
1593   // A utility lambda that scales up a block frequency by dividing it by a
1594   // branch probability which is the reciprocal of the scale.
1595   auto ScaleBlockFrequency = [](BlockFrequency Freq,
1596                                 unsigned Scale) -> BlockFrequency {
1597     if (Scale == 0)
1598       return 0;
1599     // Use operator / between BlockFrequency and BranchProbability to implement
1600     // saturating multiplication.
1601     return Freq / BranchProbability(1, Scale);
1602   };
1603 
1604   // Compute the cost of the missed fall-through edge to the loop header if the
1605   // chain head is not the loop header. As we only consider natural loops with
1606   // single header, this computation can be done only once.
1607   BlockFrequency HeaderFallThroughCost(0);
1608   for (auto *Pred : HeaderBB->predecessors()) {
1609     BlockChain *PredChain = BlockToChain[Pred];
1610     if (!LoopBlockSet.count(Pred) &&
1611         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1612       auto EdgeFreq =
1613           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1614       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1615       // If the predecessor has only an unconditional jump to the header, we
1616       // need to consider the cost of this jump.
1617       if (Pred->succ_size() == 1)
1618         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1619       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1620     }
1621   }
1622 
1623   // Here we collect all exit blocks in the loop, and for each exit we find out
1624   // its hottest exit edge. For each loop rotation, we define the loop exit cost
1625   // as the sum of frequencies of exit edges we collect here, excluding the exit
1626   // edge from the tail of the loop chain.
1627   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
1628   for (auto BB : LoopChain) {
1629     auto LargestExitEdgeProb = BranchProbability::getZero();
1630     for (auto *Succ : BB->successors()) {
1631       BlockChain *SuccChain = BlockToChain[Succ];
1632       if (!LoopBlockSet.count(Succ) &&
1633           (!SuccChain || Succ == *SuccChain->begin())) {
1634         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
1635         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
1636       }
1637     }
1638     if (LargestExitEdgeProb > BranchProbability::getZero()) {
1639       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
1640       ExitsWithFreq.emplace_back(BB, ExitFreq);
1641     }
1642   }
1643 
1644   // In this loop we iterate every block in the loop chain and calculate the
1645   // cost assuming the block is the head of the loop chain. When the loop ends,
1646   // we should have found the best candidate as the loop chain's head.
1647   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
1648             EndIter = LoopChain.end();
1649        Iter != EndIter; Iter++, TailIter++) {
1650     // TailIter is used to track the tail of the loop chain if the block we are
1651     // checking (pointed by Iter) is the head of the chain.
1652     if (TailIter == LoopChain.end())
1653       TailIter = LoopChain.begin();
1654 
1655     auto TailBB = *TailIter;
1656 
1657     // Calculate the cost by putting this BB to the top.
1658     BlockFrequency Cost = 0;
1659 
1660     // If the current BB is the loop header, we need to take into account the
1661     // cost of the missed fall through edge from outside of the loop to the
1662     // header.
1663     if (Iter != HeaderIter)
1664       Cost += HeaderFallThroughCost;
1665 
1666     // Collect the loop exit cost by summing up frequencies of all exit edges
1667     // except the one from the chain tail.
1668     for (auto &ExitWithFreq : ExitsWithFreq)
1669       if (TailBB != ExitWithFreq.first)
1670         Cost += ExitWithFreq.second;
1671 
1672     // The cost of breaking the once fall-through edge from the tail to the top
1673     // of the loop chain. Here we need to consider three cases:
1674     // 1. If the tail node has only one successor, then we will get an
1675     //    additional jmp instruction. So the cost here is (MisfetchCost +
1676     //    JumpInstCost) * tail node frequency.
1677     // 2. If the tail node has two successors, then we may still get an
1678     //    additional jmp instruction if the layout successor after the loop
1679     //    chain is not its CFG successor. Note that the more frequently executed
1680     //    jmp instruction will be put ahead of the other one. Assume the
1681     //    frequency of those two branches are x and y, where x is the frequency
1682     //    of the edge to the chain head, then the cost will be
1683     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
1684     // 3. If the tail node has more than two successors (this rarely happens),
1685     //    we won't consider any additional cost.
1686     if (TailBB->isSuccessor(*Iter)) {
1687       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
1688       if (TailBB->succ_size() == 1)
1689         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
1690                                     MisfetchCost + JumpInstCost);
1691       else if (TailBB->succ_size() == 2) {
1692         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
1693         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
1694         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
1695                                   ? TailBBFreq * TailToHeadProb.getCompl()
1696                                   : TailToHeadFreq;
1697         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
1698                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
1699       }
1700     }
1701 
1702     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
1703                  << " to the top: " << Cost.getFrequency() << "\n");
1704 
1705     if (Cost < SmallestRotationCost) {
1706       SmallestRotationCost = Cost;
1707       RotationPos = Iter;
1708     }
1709   }
1710 
1711   if (RotationPos != LoopChain.end()) {
1712     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
1713                  << " to the top\n");
1714     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
1715   }
1716 }
1717 
1718 /// \brief Collect blocks in the given loop that are to be placed.
1719 ///
1720 /// When profile data is available, exclude cold blocks from the returned set;
1721 /// otherwise, collect all blocks in the loop.
1722 MachineBlockPlacement::BlockFilterSet
1723 MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) {
1724   BlockFilterSet LoopBlockSet;
1725 
1726   // Filter cold blocks off from LoopBlockSet when profile data is available.
1727   // Collect the sum of frequencies of incoming edges to the loop header from
1728   // outside. If we treat the loop as a super block, this is the frequency of
1729   // the loop. Then for each block in the loop, we calculate the ratio between
1730   // its frequency and the frequency of the loop block. When it is too small,
1731   // don't add it to the loop chain. If there are outer loops, then this block
1732   // will be merged into the first outer loop chain for which this block is not
1733   // cold anymore. This needs precise profile data and we only do this when
1734   // profile data is available.
1735   if (F->getFunction()->getEntryCount()) {
1736     BlockFrequency LoopFreq(0);
1737     for (auto LoopPred : L.getHeader()->predecessors())
1738       if (!L.contains(LoopPred))
1739         LoopFreq += MBFI->getBlockFreq(LoopPred) *
1740                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
1741 
1742     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1743       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1744       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1745         continue;
1746       LoopBlockSet.insert(LoopBB);
1747     }
1748   } else
1749     LoopBlockSet.insert(L.block_begin(), L.block_end());
1750 
1751   return LoopBlockSet;
1752 }
1753 
1754 /// \brief Forms basic block chains from the natural loop structures.
1755 ///
1756 /// These chains are designed to preserve the existing *structure* of the code
1757 /// as much as possible. We can then stitch the chains together in a way which
1758 /// both preserves the topological structure and minimizes taken conditional
1759 /// branches.
1760 void MachineBlockPlacement::buildLoopChains(MachineLoop &L) {
1761   // First recurse through any nested loops, building chains for those inner
1762   // loops.
1763   for (MachineLoop *InnerLoop : L)
1764     buildLoopChains(*InnerLoop);
1765 
1766   assert(BlockWorkList.empty());
1767   assert(EHPadWorkList.empty());
1768   BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
1769 
1770   // Check if we have profile data for this function. If yes, we will rotate
1771   // this loop by modeling costs more precisely which requires the profile data
1772   // for better layout.
1773   bool RotateLoopWithProfile =
1774       ForcePreciseRotationCost ||
1775       (PreciseRotationCost && F->getFunction()->getEntryCount());
1776 
1777   // First check to see if there is an obviously preferable top block for the
1778   // loop. This will default to the header, but may end up as one of the
1779   // predecessors to the header if there is one which will result in strictly
1780   // fewer branches in the loop body.
1781   // When we use profile data to rotate the loop, this is unnecessary.
1782   MachineBasicBlock *LoopTop =
1783       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1784 
1785   // If we selected just the header for the loop top, look for a potentially
1786   // profitable exit block in the event that rotating the loop can eliminate
1787   // branches by placing an exit edge at the bottom.
1788   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1789     PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
1790 
1791   BlockChain &LoopChain = *BlockToChain[LoopTop];
1792 
1793   // FIXME: This is a really lame way of walking the chains in the loop: we
1794   // walk the blocks, and use a set to prevent visiting a particular chain
1795   // twice.
1796   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1797   assert(LoopChain.UnscheduledPredecessors == 0);
1798   UpdatedPreds.insert(&LoopChain);
1799 
1800   for (MachineBasicBlock *LoopBB : LoopBlockSet)
1801     fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
1802 
1803   buildChain(LoopTop, LoopChain, &LoopBlockSet);
1804 
1805   if (RotateLoopWithProfile)
1806     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1807   else
1808     rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
1809 
1810   DEBUG({
1811     // Crash at the end so we get all of the debugging output first.
1812     bool BadLoop = false;
1813     if (LoopChain.UnscheduledPredecessors) {
1814       BadLoop = true;
1815       dbgs() << "Loop chain contains a block without its preds placed!\n"
1816              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1817              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1818     }
1819     for (MachineBasicBlock *ChainBB : LoopChain) {
1820       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
1821       if (!LoopBlockSet.remove(ChainBB)) {
1822         // We don't mark the loop as bad here because there are real situations
1823         // where this can occur. For example, with an unanalyzable fallthrough
1824         // from a loop block to a non-loop block or vice versa.
1825         dbgs() << "Loop chain contains a block not contained by the loop!\n"
1826                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1827                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1828                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1829       }
1830     }
1831 
1832     if (!LoopBlockSet.empty()) {
1833       BadLoop = true;
1834       for (MachineBasicBlock *LoopBB : LoopBlockSet)
1835         dbgs() << "Loop contains blocks never placed into a chain!\n"
1836                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1837                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1838                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
1839     }
1840     assert(!BadLoop && "Detected problems with the placement of this loop.");
1841   });
1842 
1843   BlockWorkList.clear();
1844   EHPadWorkList.clear();
1845 }
1846 
1847 /// When OutlineOpitonalBranches is on, this method collects BBs that
1848 /// dominates all terminator blocks of the function \p F.
1849 void MachineBlockPlacement::collectMustExecuteBBs() {
1850   if (OutlineOptionalBranches) {
1851     // Find the nearest common dominator of all of F's terminators.
1852     MachineBasicBlock *Terminator = nullptr;
1853     for (MachineBasicBlock &MBB : *F) {
1854       if (MBB.succ_size() == 0) {
1855         if (Terminator == nullptr)
1856           Terminator = &MBB;
1857         else
1858           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1859       }
1860     }
1861 
1862     // MBBs dominating this common dominator are unavoidable.
1863     UnavoidableBlocks.clear();
1864     for (MachineBasicBlock &MBB : *F) {
1865       if (MDT->dominates(&MBB, Terminator)) {
1866         UnavoidableBlocks.insert(&MBB);
1867       }
1868     }
1869   }
1870 }
1871 
1872 void MachineBlockPlacement::buildCFGChains() {
1873   // Ensure that every BB in the function has an associated chain to simplify
1874   // the assumptions of the remaining algorithm.
1875   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1876   for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
1877        ++FI) {
1878     MachineBasicBlock *BB = &*FI;
1879     BlockChain *Chain =
1880         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1881     // Also, merge any blocks which we cannot reason about and must preserve
1882     // the exact fallthrough behavior for.
1883     for (;;) {
1884       Cond.clear();
1885       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1886       if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1887         break;
1888 
1889       MachineFunction::iterator NextFI = std::next(FI);
1890       MachineBasicBlock *NextBB = &*NextFI;
1891       // Ensure that the layout successor is a viable block, as we know that
1892       // fallthrough is a possibility.
1893       assert(NextFI != FE && "Can't fallthrough past the last block.");
1894       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1895                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
1896                    << "\n");
1897       Chain->merge(NextBB, nullptr);
1898 #ifndef NDEBUG
1899       BlocksWithUnanalyzableExits.insert(&*BB);
1900 #endif
1901       FI = NextFI;
1902       BB = NextBB;
1903     }
1904   }
1905 
1906   // Turned on with OutlineOptionalBranches option
1907   collectMustExecuteBBs();
1908 
1909   // Build any loop-based chains.
1910   PreferredLoopExit = nullptr;
1911   for (MachineLoop *L : *MLI)
1912     buildLoopChains(*L);
1913 
1914   assert(BlockWorkList.empty());
1915   assert(EHPadWorkList.empty());
1916 
1917   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1918   for (MachineBasicBlock &MBB : *F)
1919     fillWorkLists(&MBB, UpdatedPreds);
1920 
1921   BlockChain &FunctionChain = *BlockToChain[&F->front()];
1922   buildChain(&F->front(), FunctionChain);
1923 
1924 #ifndef NDEBUG
1925   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1926 #endif
1927   DEBUG({
1928     // Crash at the end so we get all of the debugging output first.
1929     bool BadFunc = false;
1930     FunctionBlockSetType FunctionBlockSet;
1931     for (MachineBasicBlock &MBB : *F)
1932       FunctionBlockSet.insert(&MBB);
1933 
1934     for (MachineBasicBlock *ChainBB : FunctionChain)
1935       if (!FunctionBlockSet.erase(ChainBB)) {
1936         BadFunc = true;
1937         dbgs() << "Function chain contains a block not in the function!\n"
1938                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1939       }
1940 
1941     if (!FunctionBlockSet.empty()) {
1942       BadFunc = true;
1943       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1944         dbgs() << "Function contains blocks never placed into a chain!\n"
1945                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
1946     }
1947     assert(!BadFunc && "Detected problems with the block placement.");
1948   });
1949 
1950   // Splice the blocks into place.
1951   MachineFunction::iterator InsertPos = F->begin();
1952   DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
1953   for (MachineBasicBlock *ChainBB : FunctionChain) {
1954     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1955                                                        : "          ... ")
1956                  << getBlockName(ChainBB) << "\n");
1957     if (InsertPos != MachineFunction::iterator(ChainBB))
1958       F->splice(InsertPos, ChainBB);
1959     else
1960       ++InsertPos;
1961 
1962     // Update the terminator of the previous block.
1963     if (ChainBB == *FunctionChain.begin())
1964       continue;
1965     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1966 
1967     // FIXME: It would be awesome of updateTerminator would just return rather
1968     // than assert when the branch cannot be analyzed in order to remove this
1969     // boiler plate.
1970     Cond.clear();
1971     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1972 
1973 #ifndef NDEBUG
1974     if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
1975       // Given the exact block placement we chose, we may actually not _need_ to
1976       // be able to edit PrevBB's terminator sequence, but not being _able_ to
1977       // do that at this point is a bug.
1978       assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
1979               !PrevBB->canFallThrough()) &&
1980              "Unexpected block with un-analyzable fallthrough!");
1981       Cond.clear();
1982       TBB = FBB = nullptr;
1983     }
1984 #endif
1985 
1986     // The "PrevBB" is not yet updated to reflect current code layout, so,
1987     //   o. it may fall-through to a block without explicit "goto" instruction
1988     //      before layout, and no longer fall-through it after layout; or
1989     //   o. just opposite.
1990     //
1991     // analyzeBranch() may return erroneous value for FBB when these two
1992     // situations take place. For the first scenario FBB is mistakenly set NULL;
1993     // for the 2nd scenario, the FBB, which is expected to be NULL, is
1994     // mistakenly pointing to "*BI".
1995     // Thus, if the future change needs to use FBB before the layout is set, it
1996     // has to correct FBB first by using the code similar to the following:
1997     //
1998     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1999     //   PrevBB->updateTerminator();
2000     //   Cond.clear();
2001     //   TBB = FBB = nullptr;
2002     //   if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2003     //     // FIXME: This should never take place.
2004     //     TBB = FBB = nullptr;
2005     //   }
2006     // }
2007     if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
2008       PrevBB->updateTerminator();
2009   }
2010 
2011   // Fixup the last block.
2012   Cond.clear();
2013   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2014   if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
2015     F->back().updateTerminator();
2016 
2017   BlockWorkList.clear();
2018   EHPadWorkList.clear();
2019 }
2020 
2021 void MachineBlockPlacement::optimizeBranches() {
2022   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2023   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
2024 
2025   // Now that all the basic blocks in the chain have the proper layout,
2026   // make a final call to AnalyzeBranch with AllowModify set.
2027   // Indeed, the target may be able to optimize the branches in a way we
2028   // cannot because all branches may not be analyzable.
2029   // E.g., the target may be able to remove an unconditional branch to
2030   // a fallthrough when it occurs after predicated terminators.
2031   for (MachineBasicBlock *ChainBB : FunctionChain) {
2032     Cond.clear();
2033     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2034     if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
2035       // If PrevBB has a two-way branch, try to re-order the branches
2036       // such that we branch to the successor with higher probability first.
2037       if (TBB && !Cond.empty() && FBB &&
2038           MBPI->getEdgeProbability(ChainBB, FBB) >
2039               MBPI->getEdgeProbability(ChainBB, TBB) &&
2040           !TII->reverseBranchCondition(Cond)) {
2041         DEBUG(dbgs() << "Reverse order of the two branches: "
2042                      << getBlockName(ChainBB) << "\n");
2043         DEBUG(dbgs() << "    Edge probability: "
2044                      << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2045                      << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2046         DebugLoc dl; // FIXME: this is nowhere
2047         TII->removeBranch(*ChainBB);
2048         TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
2049         ChainBB->updateTerminator();
2050       }
2051     }
2052   }
2053 }
2054 
2055 void MachineBlockPlacement::alignBlocks() {
2056   // Walk through the backedges of the function now that we have fully laid out
2057   // the basic blocks and align the destination of each backedge. We don't rely
2058   // exclusively on the loop info here so that we can align backedges in
2059   // unnatural CFGs and backedges that were introduced purely because of the
2060   // loop rotations done during this layout pass.
2061   if (F->getFunction()->optForSize())
2062     return;
2063   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2064   if (FunctionChain.begin() == FunctionChain.end())
2065     return; // Empty chain.
2066 
2067   const BranchProbability ColdProb(1, 5); // 20%
2068   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
2069   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
2070   for (MachineBasicBlock *ChainBB : FunctionChain) {
2071     if (ChainBB == *FunctionChain.begin())
2072       continue;
2073 
2074     // Don't align non-looping basic blocks. These are unlikely to execute
2075     // enough times to matter in practice. Note that we'll still handle
2076     // unnatural CFGs inside of a natural outer loop (the common case) and
2077     // rotated loops.
2078     MachineLoop *L = MLI->getLoopFor(ChainBB);
2079     if (!L)
2080       continue;
2081 
2082     unsigned Align = TLI->getPrefLoopAlignment(L);
2083     if (!Align)
2084       continue; // Don't care about loop alignment.
2085 
2086     // If the block is cold relative to the function entry don't waste space
2087     // aligning it.
2088     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
2089     if (Freq < WeightedEntryFreq)
2090       continue;
2091 
2092     // If the block is cold relative to its loop header, don't align it
2093     // regardless of what edges into the block exist.
2094     MachineBasicBlock *LoopHeader = L->getHeader();
2095     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2096     if (Freq < (LoopHeaderFreq * ColdProb))
2097       continue;
2098 
2099     // Check for the existence of a non-layout predecessor which would benefit
2100     // from aligning this block.
2101     MachineBasicBlock *LayoutPred =
2102         &*std::prev(MachineFunction::iterator(ChainBB));
2103 
2104     // Force alignment if all the predecessors are jumps. We already checked
2105     // that the block isn't cold above.
2106     if (!LayoutPred->isSuccessor(ChainBB)) {
2107       ChainBB->setAlignment(Align);
2108       continue;
2109     }
2110 
2111     // Align this block if the layout predecessor's edge into this block is
2112     // cold relative to the block. When this is true, other predecessors make up
2113     // all of the hot entries into the block and thus alignment is likely to be
2114     // important.
2115     BranchProbability LayoutProb =
2116         MBPI->getEdgeProbability(LayoutPred, ChainBB);
2117     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2118     if (LayoutEdgeFreq <= (Freq * ColdProb))
2119       ChainBB->setAlignment(Align);
2120   }
2121 }
2122 
2123 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2124 /// it was duplicated into its chain predecessor and removed.
2125 /// \p BB    - Basic block that may be duplicated.
2126 ///
2127 /// \p LPred - Chosen layout predecessor of \p BB.
2128 ///            Updated to be the chain end if LPred is removed.
2129 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2130 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2131 ///                  Used to identify which blocks to update predecessor
2132 ///                  counts.
2133 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2134 ///                          chosen in the given order due to unnatural CFG
2135 ///                          only needed if \p BB is removed and
2136 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
2137 /// @return true if \p BB was removed.
2138 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2139     MachineBasicBlock *BB, MachineBasicBlock *&LPred,
2140     MachineBasicBlock *LoopHeaderBB,
2141     BlockChain &Chain, BlockFilterSet *BlockFilter,
2142     MachineFunction::iterator &PrevUnplacedBlockIt) {
2143   bool Removed, DuplicatedToLPred;
2144   bool DuplicatedToOriginalLPred;
2145   Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2146                                     PrevUnplacedBlockIt,
2147                                     DuplicatedToLPred);
2148   if (!Removed)
2149     return false;
2150   DuplicatedToOriginalLPred = DuplicatedToLPred;
2151   // Iteratively try to duplicate again. It can happen that a block that is
2152   // duplicated into is still small enough to be duplicated again.
2153   // No need to call markBlockSuccessors in this case, as the blocks being
2154   // duplicated from here on are already scheduled.
2155   // Note that DuplicatedToLPred always implies Removed.
2156   while (DuplicatedToLPred) {
2157     assert (Removed && "Block must have been removed to be duplicated into its "
2158             "layout predecessor.");
2159     MachineBasicBlock *DupBB, *DupPred;
2160     // The removal callback causes Chain.end() to be updated when a block is
2161     // removed. On the first pass through the loop, the chain end should be the
2162     // same as it was on function entry. On subsequent passes, because we are
2163     // duplicating the block at the end of the chain, if it is removed the
2164     // chain will have shrunk by one block.
2165     BlockChain::iterator ChainEnd = Chain.end();
2166     DupBB = *(--ChainEnd);
2167     // Now try to duplicate again.
2168     if (ChainEnd == Chain.begin())
2169       break;
2170     DupPred = *std::prev(ChainEnd);
2171     Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2172                                       PrevUnplacedBlockIt,
2173                                       DuplicatedToLPred);
2174   }
2175   // If BB was duplicated into LPred, it is now scheduled. But because it was
2176   // removed, markChainSuccessors won't be called for its chain. Instead we
2177   // call markBlockSuccessors for LPred to achieve the same effect. This must go
2178   // at the end because repeating the tail duplication can increase the number
2179   // of unscheduled predecessors.
2180   LPred = *std::prev(Chain.end());
2181   if (DuplicatedToOriginalLPred)
2182     markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2183   return true;
2184 }
2185 
2186 /// Tail duplicate \p BB into (some) predecessors if profitable.
2187 /// \p BB    - Basic block that may be duplicated
2188 /// \p LPred - Chosen layout predecessor of \p BB
2189 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2190 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2191 ///                  Used to identify which blocks to update predecessor
2192 ///                  counts.
2193 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2194 ///                          chosen in the given order due to unnatural CFG
2195 ///                          only needed if \p BB is removed and
2196 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
2197 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2198 ///                        only be true if the block was removed.
2199 /// \return  - True if the block was duplicated into all preds and removed.
2200 bool MachineBlockPlacement::maybeTailDuplicateBlock(
2201     MachineBasicBlock *BB, MachineBasicBlock *LPred,
2202     const BlockChain &Chain, BlockFilterSet *BlockFilter,
2203     MachineFunction::iterator &PrevUnplacedBlockIt,
2204     bool &DuplicatedToLPred) {
2205 
2206   DuplicatedToLPred = false;
2207   DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2208         << BB->getNumber() << "\n");
2209 
2210   if (!shouldTailDuplicate(BB))
2211     return false;
2212   // This has to be a callback because none of it can be done after
2213   // BB is deleted.
2214   bool Removed = false;
2215   auto RemovalCallback =
2216       [&](MachineBasicBlock *RemBB) {
2217         // Signal to outer function
2218         Removed = true;
2219 
2220         // Conservative default.
2221         bool InWorkList = true;
2222         // Remove from the Chain and Chain Map
2223         if (BlockToChain.count(RemBB)) {
2224           BlockChain *Chain = BlockToChain[RemBB];
2225           InWorkList = Chain->UnscheduledPredecessors == 0;
2226           Chain->remove(RemBB);
2227           BlockToChain.erase(RemBB);
2228         }
2229 
2230         // Handle the unplaced block iterator
2231         if (&(*PrevUnplacedBlockIt) == RemBB) {
2232           PrevUnplacedBlockIt++;
2233         }
2234 
2235         // Handle the Work Lists
2236         if (InWorkList) {
2237           SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2238           if (RemBB->isEHPad())
2239             RemoveList = EHPadWorkList;
2240           RemoveList.erase(
2241               remove_if(RemoveList,
2242                         [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
2243               RemoveList.end());
2244         }
2245 
2246         // Handle the filter set
2247         if (BlockFilter) {
2248           BlockFilter->remove(RemBB);
2249         }
2250 
2251         // Remove the block from loop info.
2252         MLI->removeBlock(RemBB);
2253         if (RemBB == PreferredLoopExit)
2254           PreferredLoopExit = nullptr;
2255 
2256         DEBUG(dbgs() << "TailDuplicator deleted block: "
2257               << getBlockName(RemBB) << "\n");
2258       };
2259   auto RemovalCallbackRef =
2260       llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2261 
2262   SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
2263   bool IsSimple = TailDup.isSimpleBB(BB);
2264   TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2265                                  &DuplicatedPreds, &RemovalCallbackRef);
2266 
2267   // Update UnscheduledPredecessors to reflect tail-duplication.
2268   DuplicatedToLPred = false;
2269   for (MachineBasicBlock *Pred : DuplicatedPreds) {
2270     // We're only looking for unscheduled predecessors that match the filter.
2271     BlockChain* PredChain = BlockToChain[Pred];
2272     if (Pred == LPred)
2273       DuplicatedToLPred = true;
2274     if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2275         || PredChain == &Chain)
2276       continue;
2277     for (MachineBasicBlock *NewSucc : Pred->successors()) {
2278       if (BlockFilter && !BlockFilter->count(NewSucc))
2279         continue;
2280       BlockChain *NewChain = BlockToChain[NewSucc];
2281       if (NewChain != &Chain && NewChain != PredChain)
2282         NewChain->UnscheduledPredecessors++;
2283     }
2284   }
2285   return Removed;
2286 }
2287 
2288 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2289   if (skipFunction(*MF.getFunction()))
2290     return false;
2291 
2292   // Check for single-block functions and skip them.
2293   if (std::next(MF.begin()) == MF.end())
2294     return false;
2295 
2296   F = &MF;
2297   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2298   MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2299       getAnalysis<MachineBlockFrequencyInfo>());
2300   MLI = &getAnalysis<MachineLoopInfo>();
2301   TII = MF.getSubtarget().getInstrInfo();
2302   TLI = MF.getSubtarget().getTargetLowering();
2303   MDT = &getAnalysis<MachineDominatorTree>();
2304   MPDT = nullptr;
2305 
2306   // Initialize PreferredLoopExit to nullptr here since it may never be set if
2307   // there are no MachineLoops.
2308   PreferredLoopExit = nullptr;
2309 
2310   if (TailDupPlacement) {
2311     MPDT = &getAnalysis<MachinePostDominatorTree>();
2312     unsigned TailDupSize = TailDupPlacementThreshold;
2313     if (MF.getFunction()->optForSize())
2314       TailDupSize = 1;
2315     TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
2316   }
2317 
2318   assert(BlockToChain.empty());
2319 
2320   buildCFGChains();
2321 
2322   // Changing the layout can create new tail merging opportunities.
2323   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2324   // TailMerge can create jump into if branches that make CFG irreducible for
2325   // HW that requires structured CFG.
2326   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
2327                          PassConfig->getEnableTailMerge() &&
2328                          BranchFoldPlacement;
2329   // No tail merging opportunities if the block number is less than four.
2330   if (MF.size() > 3 && EnableTailMerge) {
2331     unsigned TailMergeSize = TailDupPlacementThreshold + 1;
2332     BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
2333                     *MBPI, TailMergeSize);
2334 
2335     if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
2336                             getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2337                             /*AfterBlockPlacement=*/true)) {
2338       // Redo the layout if tail merging creates/removes/moves blocks.
2339       BlockToChain.clear();
2340       // Must redo the dominator tree if blocks were changed.
2341       MDT->runOnMachineFunction(MF);
2342       if (MPDT)
2343         MPDT->runOnMachineFunction(MF);
2344       ChainAllocator.DestroyAll();
2345       buildCFGChains();
2346     }
2347   }
2348 
2349   optimizeBranches();
2350   alignBlocks();
2351 
2352   BlockToChain.clear();
2353   ChainAllocator.DestroyAll();
2354 
2355   if (AlignAllBlock)
2356     // Align all of the blocks in the function to a specific alignment.
2357     for (MachineBasicBlock &MBB : MF)
2358       MBB.setAlignment(AlignAllBlock);
2359   else if (AlignAllNonFallThruBlocks) {
2360     // Align all of the blocks that have no fall-through predecessors to a
2361     // specific alignment.
2362     for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
2363       auto LayoutPred = std::prev(MBI);
2364       if (!LayoutPred->isSuccessor(&*MBI))
2365         MBI->setAlignment(AlignAllNonFallThruBlocks);
2366     }
2367   }
2368 #ifndef NDEBUG
2369   if (ViewBlockLayoutWithBFI != GVDT_None &&
2370       (ViewBlockFreqFuncName.empty() ||
2371        F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
2372     MBFI->view(false);
2373   }
2374 #endif
2375 
2376 
2377   // We always return true as we have no way to track whether the final order
2378   // differs from the original order.
2379   return true;
2380 }
2381 
2382 namespace {
2383 /// \brief A pass to compute block placement statistics.
2384 ///
2385 /// A separate pass to compute interesting statistics for evaluating block
2386 /// placement. This is separate from the actual placement pass so that they can
2387 /// be computed in the absence of any placement transformations or when using
2388 /// alternative placement strategies.
2389 class MachineBlockPlacementStats : public MachineFunctionPass {
2390   /// \brief A handle to the branch probability pass.
2391   const MachineBranchProbabilityInfo *MBPI;
2392 
2393   /// \brief A handle to the function-wide block frequency pass.
2394   const MachineBlockFrequencyInfo *MBFI;
2395 
2396 public:
2397   static char ID; // Pass identification, replacement for typeid
2398   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2399     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2400   }
2401 
2402   bool runOnMachineFunction(MachineFunction &F) override;
2403 
2404   void getAnalysisUsage(AnalysisUsage &AU) const override {
2405     AU.addRequired<MachineBranchProbabilityInfo>();
2406     AU.addRequired<MachineBlockFrequencyInfo>();
2407     AU.setPreservesAll();
2408     MachineFunctionPass::getAnalysisUsage(AU);
2409   }
2410 };
2411 }
2412 
2413 char MachineBlockPlacementStats::ID = 0;
2414 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
2415 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2416                       "Basic Block Placement Stats", false, false)
2417 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2418 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2419 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2420                     "Basic Block Placement Stats", false, false)
2421 
2422 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2423   // Check for single-block functions and skip them.
2424   if (std::next(F.begin()) == F.end())
2425     return false;
2426 
2427   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2428   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2429 
2430   for (MachineBasicBlock &MBB : F) {
2431     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
2432     Statistic &NumBranches =
2433         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
2434     Statistic &BranchTakenFreq =
2435         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2436     for (MachineBasicBlock *Succ : MBB.successors()) {
2437       // Skip if this successor is a fallthrough.
2438       if (MBB.isLayoutSuccessor(Succ))
2439         continue;
2440 
2441       BlockFrequency EdgeFreq =
2442           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
2443       ++NumBranches;
2444       BranchTakenFreq += EdgeFreq.getFrequency();
2445     }
2446   }
2447 
2448   return false;
2449 }
2450