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