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