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