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