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/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
35 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
36 #include "llvm/CodeGen/MachineDominators.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineLoopInfo.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
48 #include <algorithm>
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "block-placement"
52 
53 STATISTIC(NumCondBranches, "Number of conditional branches");
54 STATISTIC(NumUncondBranches, "Number of unconditional branches");
55 STATISTIC(CondBranchTakenFreq,
56           "Potential frequency of taking conditional branches");
57 STATISTIC(UncondBranchTakenFreq,
58           "Potential frequency of taking unconditional branches");
59 
60 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
61                                        cl::desc("Force the alignment of all "
62                                                 "blocks in the function."),
63                                        cl::init(0), cl::Hidden);
64 
65 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
66     "align-all-nofallthru-blocks",
67     cl::desc("Force the alignment of all "
68              "blocks that have no fall-through predecessors (i.e. don't add "
69              "nops that are executed)."),
70     cl::init(0), cl::Hidden);
71 
72 // FIXME: Find a good default for this flag and remove the flag.
73 static cl::opt<unsigned> ExitBlockBias(
74     "block-placement-exit-block-bias",
75     cl::desc("Block frequency percentage a loop exit block needs "
76              "over the original exit to be considered the new exit."),
77     cl::init(0), cl::Hidden);
78 
79 static cl::opt<bool> OutlineOptionalBranches(
80     "outline-optional-branches",
81     cl::desc("Put completely optional branches, i.e. branches with a common "
82              "post dominator, out of line."),
83     cl::init(false), cl::Hidden);
84 
85 static cl::opt<unsigned> OutlineOptionalThreshold(
86     "outline-optional-threshold",
87     cl::desc("Don't outline optional branches that are a single block with an "
88              "instruction count below this threshold"),
89     cl::init(4), cl::Hidden);
90 
91 static cl::opt<unsigned> LoopToColdBlockRatio(
92     "loop-to-cold-block-ratio",
93     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
94              "(frequency of block) is greater than this ratio"),
95     cl::init(5), cl::Hidden);
96 
97 static cl::opt<bool>
98     PreciseRotationCost("precise-rotation-cost",
99                         cl::desc("Model the cost of loop rotation more "
100                                  "precisely by using profile data."),
101                         cl::init(false), cl::Hidden);
102 
103 static cl::opt<unsigned> MisfetchCost(
104     "misfetch-cost",
105     cl::desc("Cost that models the probablistic risk of an instruction "
106              "misfetch due to a jump comparing to falling through, whose cost "
107              "is zero."),
108     cl::init(1), cl::Hidden);
109 
110 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
111                                       cl::desc("Cost of jump instructions."),
112                                       cl::init(1), cl::Hidden);
113 
114 namespace {
115 class BlockChain;
116 /// \brief Type for our function-wide basic block -> block chain mapping.
117 typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType;
118 }
119 
120 namespace {
121 /// \brief A chain of blocks which will be laid out contiguously.
122 ///
123 /// This is the datastructure representing a chain of consecutive blocks that
124 /// are profitable to layout together in order to maximize fallthrough
125 /// probabilities and code locality. We also can use a block chain to represent
126 /// a sequence of basic blocks which have some external (correctness)
127 /// requirement for sequential layout.
128 ///
129 /// Chains can be built around a single basic block and can be merged to grow
130 /// them. They participate in a block-to-chain mapping, which is updated
131 /// automatically as chains are merged together.
132 class BlockChain {
133   /// \brief The sequence of blocks belonging to this chain.
134   ///
135   /// This is the sequence of blocks for a particular chain. These will be laid
136   /// out in-order within the function.
137   SmallVector<MachineBasicBlock *, 4> Blocks;
138 
139   /// \brief A handle to the function-wide basic block to block chain mapping.
140   ///
141   /// This is retained in each block chain to simplify the computation of child
142   /// block chains for SCC-formation and iteration. We store the edges to child
143   /// basic blocks, and map them back to their associated chains using this
144   /// structure.
145   BlockToChainMapType &BlockToChain;
146 
147 public:
148   /// \brief Construct a new BlockChain.
149   ///
150   /// This builds a new block chain representing a single basic block in the
151   /// function. It also registers itself as the chain that block participates
152   /// in with the BlockToChain mapping.
153   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
154       : Blocks(1, BB), BlockToChain(BlockToChain), LoopPredecessors(0) {
155     assert(BB && "Cannot create a chain with a null basic block");
156     BlockToChain[BB] = this;
157   }
158 
159   /// \brief Iterator over blocks within the chain.
160   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
161 
162   /// \brief Beginning of blocks within the chain.
163   iterator begin() { return Blocks.begin(); }
164 
165   /// \brief End of blocks within the chain.
166   iterator end() { return Blocks.end(); }
167 
168   /// \brief Merge a block chain into this one.
169   ///
170   /// This routine merges a block chain into this one. It takes care of forming
171   /// a contiguous sequence of basic blocks, updating the edge list, and
172   /// updating the block -> chain mapping. It does not free or tear down the
173   /// old chain, but the old chain's block list is no longer valid.
174   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
175     assert(BB);
176     assert(!Blocks.empty());
177 
178     // Fast path in case we don't have a chain already.
179     if (!Chain) {
180       assert(!BlockToChain[BB]);
181       Blocks.push_back(BB);
182       BlockToChain[BB] = this;
183       return;
184     }
185 
186     assert(BB == *Chain->begin());
187     assert(Chain->begin() != Chain->end());
188 
189     // Update the incoming blocks to point to this chain, and add them to the
190     // chain structure.
191     for (MachineBasicBlock *ChainBB : *Chain) {
192       Blocks.push_back(ChainBB);
193       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
194       BlockToChain[ChainBB] = this;
195     }
196   }
197 
198 #ifndef NDEBUG
199   /// \brief Dump the blocks in this chain.
200   LLVM_DUMP_METHOD void dump() {
201     for (MachineBasicBlock *MBB : *this)
202       MBB->dump();
203   }
204 #endif // NDEBUG
205 
206   /// \brief Count of predecessors within the loop currently being processed.
207   ///
208   /// This count is updated at each loop we process to represent the number of
209   /// in-loop predecessors of this chain.
210   unsigned LoopPredecessors;
211 };
212 }
213 
214 namespace {
215 class MachineBlockPlacement : public MachineFunctionPass {
216   /// \brief A typedef for a block filter set.
217   typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet;
218 
219   /// \brief A handle to the branch probability pass.
220   const MachineBranchProbabilityInfo *MBPI;
221 
222   /// \brief A handle to the function-wide block frequency pass.
223   const MachineBlockFrequencyInfo *MBFI;
224 
225   /// \brief A handle to the loop info.
226   const MachineLoopInfo *MLI;
227 
228   /// \brief A handle to the target's instruction info.
229   const TargetInstrInfo *TII;
230 
231   /// \brief A handle to the target's lowering info.
232   const TargetLoweringBase *TLI;
233 
234   /// \brief A handle to the post dominator tree.
235   MachineDominatorTree *MDT;
236 
237   /// \brief A set of blocks that are unavoidably execute, i.e. they dominate
238   /// all terminators of the MachineFunction.
239   SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks;
240 
241   /// \brief Allocator and owner of BlockChain structures.
242   ///
243   /// We build BlockChains lazily while processing the loop structure of
244   /// a function. To reduce malloc traffic, we allocate them using this
245   /// slab-like allocator, and destroy them after the pass completes. An
246   /// important guarantee is that this allocator produces stable pointers to
247   /// the chains.
248   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
249 
250   /// \brief Function wide BasicBlock to BlockChain mapping.
251   ///
252   /// This mapping allows efficiently moving from any given basic block to the
253   /// BlockChain it participates in, if any. We use it to, among other things,
254   /// allow implicitly defining edges between chains as the existing edges
255   /// between basic blocks.
256   DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain;
257 
258   void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
259                            SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
260                            const BlockFilterSet *BlockFilter = nullptr);
261   MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB,
262                                          BlockChain &Chain,
263                                          const BlockFilterSet *BlockFilter);
264   MachineBasicBlock *
265   selectBestCandidateBlock(BlockChain &Chain,
266                            SmallVectorImpl<MachineBasicBlock *> &WorkList,
267                            const BlockFilterSet *BlockFilter);
268   MachineBasicBlock *
269   getFirstUnplacedBlock(MachineFunction &F, const BlockChain &PlacedChain,
270                         MachineFunction::iterator &PrevUnplacedBlockIt,
271                         const BlockFilterSet *BlockFilter);
272   void buildChain(MachineBasicBlock *BB, BlockChain &Chain,
273                   SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
274                   const BlockFilterSet *BlockFilter = nullptr);
275   MachineBasicBlock *findBestLoopTop(MachineLoop &L,
276                                      const BlockFilterSet &LoopBlockSet);
277   MachineBasicBlock *findBestLoopExit(MachineFunction &F, MachineLoop &L,
278                                       const BlockFilterSet &LoopBlockSet);
279   BlockFilterSet collectLoopBlockSet(MachineFunction &F, MachineLoop &L);
280   void buildLoopChains(MachineFunction &F, MachineLoop &L);
281   void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB,
282                   const BlockFilterSet &LoopBlockSet);
283   void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L,
284                              const BlockFilterSet &LoopBlockSet);
285   void buildCFGChains(MachineFunction &F);
286 
287 public:
288   static char ID; // Pass identification, replacement for typeid
289   MachineBlockPlacement() : MachineFunctionPass(ID) {
290     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
291   }
292 
293   bool runOnMachineFunction(MachineFunction &F) override;
294 
295   void getAnalysisUsage(AnalysisUsage &AU) const override {
296     AU.addRequired<MachineBranchProbabilityInfo>();
297     AU.addRequired<MachineBlockFrequencyInfo>();
298     AU.addRequired<MachineDominatorTree>();
299     AU.addRequired<MachineLoopInfo>();
300     MachineFunctionPass::getAnalysisUsage(AU);
301   }
302 };
303 }
304 
305 char MachineBlockPlacement::ID = 0;
306 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
307 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
308                       "Branch Probability Basic Block Placement", false, false)
309 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
310 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
311 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
312 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
313 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
314                     "Branch Probability Basic Block Placement", false, false)
315 
316 #ifndef NDEBUG
317 /// \brief Helper to print the name of a MBB.
318 ///
319 /// Only used by debug logging.
320 static std::string getBlockName(MachineBasicBlock *BB) {
321   std::string Result;
322   raw_string_ostream OS(Result);
323   OS << "BB#" << BB->getNumber();
324   OS << " ('" << BB->getName() << "')";
325   OS.flush();
326   return Result;
327 }
328 #endif
329 
330 /// \brief Mark a chain's successors as having one fewer preds.
331 ///
332 /// When a chain is being merged into the "placed" chain, this routine will
333 /// quickly walk the successors of each block in the chain and mark them as
334 /// having one fewer active predecessor. It also adds any successors of this
335 /// chain which reach the zero-predecessor state to the worklist passed in.
336 void MachineBlockPlacement::markChainSuccessors(
337     BlockChain &Chain, MachineBasicBlock *LoopHeaderBB,
338     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
339     const BlockFilterSet *BlockFilter) {
340   // Walk all the blocks in this chain, marking their successors as having
341   // a predecessor placed.
342   for (MachineBasicBlock *MBB : Chain) {
343     // Add any successors for which this is the only un-placed in-loop
344     // predecessor to the worklist as a viable candidate for CFG-neutral
345     // placement. No subsequent placement of this block will violate the CFG
346     // shape, so we get to use heuristics to choose a favorable placement.
347     for (MachineBasicBlock *Succ : MBB->successors()) {
348       if (BlockFilter && !BlockFilter->count(Succ))
349         continue;
350       BlockChain &SuccChain = *BlockToChain[Succ];
351       // Disregard edges within a fixed chain, or edges to the loop header.
352       if (&Chain == &SuccChain || Succ == LoopHeaderBB)
353         continue;
354 
355       // This is a cross-chain edge that is within the loop, so decrement the
356       // loop predecessor count of the destination chain.
357       if (SuccChain.LoopPredecessors > 0 && --SuccChain.LoopPredecessors == 0)
358         BlockWorkList.push_back(*SuccChain.begin());
359     }
360   }
361 }
362 
363 /// \brief Select the best successor for a block.
364 ///
365 /// This looks across all successors of a particular block and attempts to
366 /// select the "best" one to be the layout successor. It only considers direct
367 /// successors which also pass the block filter. It will attempt to avoid
368 /// breaking CFG structure, but cave and break such structures in the case of
369 /// very hot successor edges.
370 ///
371 /// \returns The best successor block found, or null if none are viable.
372 MachineBasicBlock *
373 MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB,
374                                            BlockChain &Chain,
375                                            const BlockFilterSet *BlockFilter) {
376   const BranchProbability HotProb(4, 5); // 80%
377 
378   MachineBasicBlock *BestSucc = nullptr;
379   auto BestProb = BranchProbability::getZero();
380 
381   // Adjust edge probabilities by excluding edges pointing to blocks that is
382   // either not in BlockFilter or is already in the current chain. Consider the
383   // following CFG:
384   //
385   //     --->A
386   //     |  / \
387   //     | B   C
388   //     |  \ / \
389   //     ----D   E
390   //
391   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
392   // A->C is chosen as a fall-through, D won't be selected as a successor of C
393   // due to CFG constraint (the probability of C->D is not greater than
394   // HotProb). If we exclude E that is not in BlockFilter when calculating the
395   // probability of C->D, D will be selected and we will get A C D B as the
396   // layout of this loop.
397   auto AdjustedSumProb = BranchProbability::getOne();
398   SmallVector<MachineBasicBlock *, 4> Successors;
399   for (MachineBasicBlock *Succ : BB->successors()) {
400     bool SkipSucc = false;
401     if (BlockFilter && !BlockFilter->count(Succ)) {
402       SkipSucc = true;
403     } else {
404       BlockChain *SuccChain = BlockToChain[Succ];
405       if (SuccChain == &Chain) {
406         SkipSucc = true;
407       } else if (Succ != *SuccChain->begin()) {
408         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
409         continue;
410       }
411     }
412     if (SkipSucc)
413       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
414     else
415       Successors.push_back(Succ);
416   }
417 
418   DEBUG(dbgs() << "Attempting merge from: " << getBlockName(BB) << "\n");
419   for (MachineBasicBlock *Succ : Successors) {
420     BranchProbability SuccProb;
421     uint32_t SuccProbN = MBPI->getEdgeProbability(BB, Succ).getNumerator();
422     uint32_t SuccProbD = AdjustedSumProb.getNumerator();
423     if (SuccProbN >= SuccProbD)
424       SuccProb = BranchProbability::getOne();
425     else
426       SuccProb = BranchProbability(SuccProbN, SuccProbD);
427 
428     // If we outline optional branches, look whether Succ is unavoidable, i.e.
429     // dominates all terminators of the MachineFunction. If it does, other
430     // successors must be optional. Don't do this for cold branches.
431     if (OutlineOptionalBranches && SuccProb > HotProb.getCompl() &&
432         UnavoidableBlocks.count(Succ) > 0) {
433       auto HasShortOptionalBranch = [&]() {
434         for (MachineBasicBlock *Pred : Succ->predecessors()) {
435           // Check whether there is an unplaced optional branch.
436           if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) ||
437               BlockToChain[Pred] == &Chain)
438             continue;
439           // Check whether the optional branch has exactly one BB.
440           if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB)
441             continue;
442           // Check whether the optional branch is small.
443           if (Pred->size() < OutlineOptionalThreshold)
444             return true;
445         }
446         return false;
447       };
448       if (!HasShortOptionalBranch())
449         return Succ;
450     }
451 
452     // Only consider successors which are either "hot", or wouldn't violate
453     // any CFG constraints.
454     BlockChain &SuccChain = *BlockToChain[Succ];
455     if (SuccChain.LoopPredecessors != 0) {
456       if (SuccProb < HotProb) {
457         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
458                      << " (prob) (CFG conflict)\n");
459         continue;
460       }
461 
462       // Make sure that a hot successor doesn't have a globally more
463       // important predecessor.
464       auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
465       BlockFrequency CandidateEdgeFreq =
466           MBFI->getBlockFreq(BB) * RealSuccProb * HotProb.getCompl();
467       bool BadCFGConflict = false;
468       for (MachineBasicBlock *Pred : Succ->predecessors()) {
469         if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
470             (BlockFilter && !BlockFilter->count(Pred)) ||
471             BlockToChain[Pred] == &Chain)
472           continue;
473         BlockFrequency PredEdgeFreq =
474             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
475         if (PredEdgeFreq >= CandidateEdgeFreq) {
476           BadCFGConflict = true;
477           break;
478         }
479       }
480       if (BadCFGConflict) {
481         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
482                      << " (prob) (non-cold CFG conflict)\n");
483         continue;
484       }
485     }
486 
487     DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> " << SuccProb
488                  << " (prob)"
489                  << (SuccChain.LoopPredecessors != 0 ? " (CFG break)" : "")
490                  << "\n");
491     if (BestSucc && BestProb >= SuccProb)
492       continue;
493     BestSucc = Succ;
494     BestProb = SuccProb;
495   }
496   return BestSucc;
497 }
498 
499 /// \brief Select the best block from a worklist.
500 ///
501 /// This looks through the provided worklist as a list of candidate basic
502 /// blocks and select the most profitable one to place. The definition of
503 /// profitable only really makes sense in the context of a loop. This returns
504 /// the most frequently visited block in the worklist, which in the case of
505 /// a loop, is the one most desirable to be physically close to the rest of the
506 /// loop body in order to improve icache behavior.
507 ///
508 /// \returns The best block found, or null if none are viable.
509 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
510     BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList,
511     const BlockFilterSet *BlockFilter) {
512   // Once we need to walk the worklist looking for a candidate, cleanup the
513   // worklist of already placed entries.
514   // FIXME: If this shows up on profiles, it could be folded (at the cost of
515   // some code complexity) into the loop below.
516   WorkList.erase(std::remove_if(WorkList.begin(), WorkList.end(),
517                                 [&](MachineBasicBlock *BB) {
518                                   return BlockToChain.lookup(BB) == &Chain;
519                                 }),
520                  WorkList.end());
521 
522   MachineBasicBlock *BestBlock = nullptr;
523   BlockFrequency BestFreq;
524   for (MachineBasicBlock *MBB : WorkList) {
525     BlockChain &SuccChain = *BlockToChain[MBB];
526     if (&SuccChain == &Chain)
527       continue;
528 
529     assert(SuccChain.LoopPredecessors == 0 && "Found CFG-violating block");
530 
531     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
532     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
533           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
534     if (BestBlock && BestFreq >= CandidateFreq)
535       continue;
536     BestBlock = MBB;
537     BestFreq = CandidateFreq;
538   }
539   return BestBlock;
540 }
541 
542 /// \brief Retrieve the first unplaced basic block.
543 ///
544 /// This routine is called when we are unable to use the CFG to walk through
545 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
546 /// We walk through the function's blocks in order, starting from the
547 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
548 /// re-scanning the entire sequence on repeated calls to this routine.
549 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
550     MachineFunction &F, const BlockChain &PlacedChain,
551     MachineFunction::iterator &PrevUnplacedBlockIt,
552     const BlockFilterSet *BlockFilter) {
553   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F.end(); I != E;
554        ++I) {
555     if (BlockFilter && !BlockFilter->count(&*I))
556       continue;
557     if (BlockToChain[&*I] != &PlacedChain) {
558       PrevUnplacedBlockIt = I;
559       // Now select the head of the chain to which the unplaced block belongs
560       // as the block to place. This will force the entire chain to be placed,
561       // and satisfies the requirements of merging chains.
562       return *BlockToChain[&*I]->begin();
563     }
564   }
565   return nullptr;
566 }
567 
568 void MachineBlockPlacement::buildChain(
569     MachineBasicBlock *BB, BlockChain &Chain,
570     SmallVectorImpl<MachineBasicBlock *> &BlockWorkList,
571     const BlockFilterSet *BlockFilter) {
572   assert(BB);
573   assert(BlockToChain[BB] == &Chain);
574   MachineFunction &F = *BB->getParent();
575   MachineFunction::iterator PrevUnplacedBlockIt = F.begin();
576 
577   MachineBasicBlock *LoopHeaderBB = BB;
578   markChainSuccessors(Chain, LoopHeaderBB, BlockWorkList, BlockFilter);
579   BB = *std::prev(Chain.end());
580   for (;;) {
581     assert(BB);
582     assert(BlockToChain[BB] == &Chain);
583     assert(*std::prev(Chain.end()) == BB);
584 
585     // Look for the best viable successor if there is one to place immediately
586     // after this block.
587     MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter);
588 
589     // If an immediate successor isn't available, look for the best viable
590     // block among those we've identified as not violating the loop's CFG at
591     // this point. This won't be a fallthrough, but it will increase locality.
592     if (!BestSucc)
593       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList, BlockFilter);
594 
595     if (!BestSucc) {
596       BestSucc =
597           getFirstUnplacedBlock(F, Chain, PrevUnplacedBlockIt, BlockFilter);
598       if (!BestSucc)
599         break;
600 
601       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
602                       "layout successor until the CFG reduces\n");
603     }
604 
605     // Place this block, updating the datastructures to reflect its placement.
606     BlockChain &SuccChain = *BlockToChain[BestSucc];
607     // Zero out LoopPredecessors for the successor we're about to merge in case
608     // we selected a successor that didn't fit naturally into the CFG.
609     SuccChain.LoopPredecessors = 0;
610     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
611                  << getBlockName(BestSucc) << "\n");
612     markChainSuccessors(SuccChain, LoopHeaderBB, BlockWorkList, BlockFilter);
613     Chain.merge(BestSucc, &SuccChain);
614     BB = *std::prev(Chain.end());
615   }
616 
617   DEBUG(dbgs() << "Finished forming chain for header block "
618                << getBlockName(*Chain.begin()) << "\n");
619 }
620 
621 /// \brief Find the best loop top block for layout.
622 ///
623 /// Look for a block which is strictly better than the loop header for laying
624 /// out at the top of the loop. This looks for one and only one pattern:
625 /// a latch block with no conditional exit. This block will cause a conditional
626 /// jump around it or will be the bottom of the loop if we lay it out in place,
627 /// but if it it doesn't end up at the bottom of the loop for any reason,
628 /// rotation alone won't fix it. Because such a block will always result in an
629 /// unconditional jump (for the backedge) rotating it in front of the loop
630 /// header is always profitable.
631 MachineBasicBlock *
632 MachineBlockPlacement::findBestLoopTop(MachineLoop &L,
633                                        const BlockFilterSet &LoopBlockSet) {
634   // Check that the header hasn't been fused with a preheader block due to
635   // crazy branches. If it has, we need to start with the header at the top to
636   // prevent pulling the preheader into the loop body.
637   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
638   if (!LoopBlockSet.count(*HeaderChain.begin()))
639     return L.getHeader();
640 
641   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
642                << "\n");
643 
644   BlockFrequency BestPredFreq;
645   MachineBasicBlock *BestPred = nullptr;
646   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
647     if (!LoopBlockSet.count(Pred))
648       continue;
649     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", "
650                  << Pred->succ_size() << " successors, ";
651           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
652     if (Pred->succ_size() > 1)
653       continue;
654 
655     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
656     if (!BestPred || PredFreq > BestPredFreq ||
657         (!(PredFreq < BestPredFreq) &&
658          Pred->isLayoutSuccessor(L.getHeader()))) {
659       BestPred = Pred;
660       BestPredFreq = PredFreq;
661     }
662   }
663 
664   // If no direct predecessor is fine, just use the loop header.
665   if (!BestPred) {
666     DEBUG(dbgs() << "    final top unchanged\n");
667     return L.getHeader();
668   }
669 
670   // Walk backwards through any straight line of predecessors.
671   while (BestPred->pred_size() == 1 &&
672          (*BestPred->pred_begin())->succ_size() == 1 &&
673          *BestPred->pred_begin() != L.getHeader())
674     BestPred = *BestPred->pred_begin();
675 
676   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
677   return BestPred;
678 }
679 
680 /// \brief Find the best loop exiting block for layout.
681 ///
682 /// This routine implements the logic to analyze the loop looking for the best
683 /// block to layout at the top of the loop. Typically this is done to maximize
684 /// fallthrough opportunities.
685 MachineBasicBlock *
686 MachineBlockPlacement::findBestLoopExit(MachineFunction &F, MachineLoop &L,
687                                         const BlockFilterSet &LoopBlockSet) {
688   // We don't want to layout the loop linearly in all cases. If the loop header
689   // is just a normal basic block in the loop, we want to look for what block
690   // within the loop is the best one to layout at the top. However, if the loop
691   // header has be pre-merged into a chain due to predecessors not having
692   // analyzable branches, *and* the predecessor it is merged with is *not* part
693   // of the loop, rotating the header into the middle of the loop will create
694   // a non-contiguous range of blocks which is Very Bad. So start with the
695   // header and only rotate if safe.
696   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
697   if (!LoopBlockSet.count(*HeaderChain.begin()))
698     return nullptr;
699 
700   BlockFrequency BestExitEdgeFreq;
701   unsigned BestExitLoopDepth = 0;
702   MachineBasicBlock *ExitingBB = nullptr;
703   // If there are exits to outer loops, loop rotation can severely limit
704   // fallthrough opportunites unless it selects such an exit. Keep a set of
705   // blocks where rotating to exit with that block will reach an outer loop.
706   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
707 
708   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
709                << "\n");
710   for (MachineBasicBlock *MBB : L.getBlocks()) {
711     BlockChain &Chain = *BlockToChain[MBB];
712     // Ensure that this block is at the end of a chain; otherwise it could be
713     // mid-way through an inner loop or a successor of an unanalyzable branch.
714     if (MBB != *std::prev(Chain.end()))
715       continue;
716 
717     // Now walk the successors. We need to establish whether this has a viable
718     // exiting successor and whether it has a viable non-exiting successor.
719     // We store the old exiting state and restore it if a viable looping
720     // successor isn't found.
721     MachineBasicBlock *OldExitingBB = ExitingBB;
722     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
723     bool HasLoopingSucc = false;
724     for (MachineBasicBlock *Succ : MBB->successors()) {
725       if (Succ->isEHPad())
726         continue;
727       if (Succ == MBB)
728         continue;
729       BlockChain &SuccChain = *BlockToChain[Succ];
730       // Don't split chains, either this chain or the successor's chain.
731       if (&Chain == &SuccChain) {
732         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
733                      << getBlockName(Succ) << " (chain conflict)\n");
734         continue;
735       }
736 
737       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
738       if (LoopBlockSet.count(Succ)) {
739         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
740                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
741         HasLoopingSucc = true;
742         continue;
743       }
744 
745       unsigned SuccLoopDepth = 0;
746       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
747         SuccLoopDepth = ExitLoop->getLoopDepth();
748         if (ExitLoop->contains(&L))
749           BlocksExitingToOuterLoop.insert(MBB);
750       }
751 
752       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
753       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
754                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
755             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
756       // Note that we bias this toward an existing layout successor to retain
757       // incoming order in the absence of better information. The exit must have
758       // a frequency higher than the current exit before we consider breaking
759       // the layout.
760       BranchProbability Bias(100 - ExitBlockBias, 100);
761       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
762           ExitEdgeFreq > BestExitEdgeFreq ||
763           (MBB->isLayoutSuccessor(Succ) &&
764            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
765         BestExitEdgeFreq = ExitEdgeFreq;
766         ExitingBB = MBB;
767       }
768     }
769 
770     if (!HasLoopingSucc) {
771       // Restore the old exiting state, no viable looping successor was found.
772       ExitingBB = OldExitingBB;
773       BestExitEdgeFreq = OldBestExitEdgeFreq;
774       continue;
775     }
776   }
777   // Without a candidate exiting block or with only a single block in the
778   // loop, just use the loop header to layout the loop.
779   if (!ExitingBB || L.getNumBlocks() == 1)
780     return nullptr;
781 
782   // Also, if we have exit blocks which lead to outer loops but didn't select
783   // one of them as the exiting block we are rotating toward, disable loop
784   // rotation altogether.
785   if (!BlocksExitingToOuterLoop.empty() &&
786       !BlocksExitingToOuterLoop.count(ExitingBB))
787     return nullptr;
788 
789   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
790   return ExitingBB;
791 }
792 
793 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
794 ///
795 /// Once we have built a chain, try to rotate it to line up the hot exit block
796 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
797 /// branches. For example, if the loop has fallthrough into its header and out
798 /// of its bottom already, don't rotate it.
799 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
800                                        MachineBasicBlock *ExitingBB,
801                                        const BlockFilterSet &LoopBlockSet) {
802   if (!ExitingBB)
803     return;
804 
805   MachineBasicBlock *Top = *LoopChain.begin();
806   bool ViableTopFallthrough = false;
807   for (MachineBasicBlock *Pred : Top->predecessors()) {
808     BlockChain *PredChain = BlockToChain[Pred];
809     if (!LoopBlockSet.count(Pred) &&
810         (!PredChain || Pred == *std::prev(PredChain->end()))) {
811       ViableTopFallthrough = true;
812       break;
813     }
814   }
815 
816   // If the header has viable fallthrough, check whether the current loop
817   // bottom is a viable exiting block. If so, bail out as rotating will
818   // introduce an unnecessary branch.
819   if (ViableTopFallthrough) {
820     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
821     for (MachineBasicBlock *Succ : Bottom->successors()) {
822       BlockChain *SuccChain = BlockToChain[Succ];
823       if (!LoopBlockSet.count(Succ) &&
824           (!SuccChain || Succ == *SuccChain->begin()))
825         return;
826     }
827   }
828 
829   BlockChain::iterator ExitIt =
830       std::find(LoopChain.begin(), LoopChain.end(), ExitingBB);
831   if (ExitIt == LoopChain.end())
832     return;
833 
834   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
835 }
836 
837 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
838 ///
839 /// With profile data, we can determine the cost in terms of missed fall through
840 /// opportunities when rotating a loop chain and select the best rotation.
841 /// Basically, there are three kinds of cost to consider for each rotation:
842 ///    1. The possibly missed fall through edge (if it exists) from BB out of
843 ///    the loop to the loop header.
844 ///    2. The possibly missed fall through edges (if they exist) from the loop
845 ///    exits to BB out of the loop.
846 ///    3. The missed fall through edge (if it exists) from the last BB to the
847 ///    first BB in the loop chain.
848 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
849 ///  We select the best rotation with the smallest cost.
850 void MachineBlockPlacement::rotateLoopWithProfile(
851     BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) {
852   auto HeaderBB = L.getHeader();
853   auto HeaderIter = std::find(LoopChain.begin(), LoopChain.end(), HeaderBB);
854   auto RotationPos = LoopChain.end();
855 
856   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
857 
858   // A utility lambda that scales up a block frequency by dividing it by a
859   // branch probability which is the reciprocal of the scale.
860   auto ScaleBlockFrequency = [](BlockFrequency Freq,
861                                 unsigned Scale) -> BlockFrequency {
862     if (Scale == 0)
863       return 0;
864     // Use operator / between BlockFrequency and BranchProbability to implement
865     // saturating multiplication.
866     return Freq / BranchProbability(1, Scale);
867   };
868 
869   // Compute the cost of the missed fall-through edge to the loop header if the
870   // chain head is not the loop header. As we only consider natural loops with
871   // single header, this computation can be done only once.
872   BlockFrequency HeaderFallThroughCost(0);
873   for (auto *Pred : HeaderBB->predecessors()) {
874     BlockChain *PredChain = BlockToChain[Pred];
875     if (!LoopBlockSet.count(Pred) &&
876         (!PredChain || Pred == *std::prev(PredChain->end()))) {
877       auto EdgeFreq =
878           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
879       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
880       // If the predecessor has only an unconditional jump to the header, we
881       // need to consider the cost of this jump.
882       if (Pred->succ_size() == 1)
883         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
884       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
885     }
886   }
887 
888   // Here we collect all exit blocks in the loop, and for each exit we find out
889   // its hottest exit edge. For each loop rotation, we define the loop exit cost
890   // as the sum of frequencies of exit edges we collect here, excluding the exit
891   // edge from the tail of the loop chain.
892   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
893   for (auto BB : LoopChain) {
894     auto LargestExitEdgeProb = BranchProbability::getZero();
895     for (auto *Succ : BB->successors()) {
896       BlockChain *SuccChain = BlockToChain[Succ];
897       if (!LoopBlockSet.count(Succ) &&
898           (!SuccChain || Succ == *SuccChain->begin())) {
899         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
900         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
901       }
902     }
903     if (LargestExitEdgeProb > BranchProbability::getZero()) {
904       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
905       ExitsWithFreq.emplace_back(BB, ExitFreq);
906     }
907   }
908 
909   // In this loop we iterate every block in the loop chain and calculate the
910   // cost assuming the block is the head of the loop chain. When the loop ends,
911   // we should have found the best candidate as the loop chain's head.
912   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
913             EndIter = LoopChain.end();
914        Iter != EndIter; Iter++, TailIter++) {
915     // TailIter is used to track the tail of the loop chain if the block we are
916     // checking (pointed by Iter) is the head of the chain.
917     if (TailIter == LoopChain.end())
918       TailIter = LoopChain.begin();
919 
920     auto TailBB = *TailIter;
921 
922     // Calculate the cost by putting this BB to the top.
923     BlockFrequency Cost = 0;
924 
925     // If the current BB is the loop header, we need to take into account the
926     // cost of the missed fall through edge from outside of the loop to the
927     // header.
928     if (Iter != HeaderIter)
929       Cost += HeaderFallThroughCost;
930 
931     // Collect the loop exit cost by summing up frequencies of all exit edges
932     // except the one from the chain tail.
933     for (auto &ExitWithFreq : ExitsWithFreq)
934       if (TailBB != ExitWithFreq.first)
935         Cost += ExitWithFreq.second;
936 
937     // The cost of breaking the once fall-through edge from the tail to the top
938     // of the loop chain. Here we need to consider three cases:
939     // 1. If the tail node has only one successor, then we will get an
940     //    additional jmp instruction. So the cost here is (MisfetchCost +
941     //    JumpInstCost) * tail node frequency.
942     // 2. If the tail node has two successors, then we may still get an
943     //    additional jmp instruction if the layout successor after the loop
944     //    chain is not its CFG successor. Note that the more frequently executed
945     //    jmp instruction will be put ahead of the other one. Assume the
946     //    frequency of those two branches are x and y, where x is the frequency
947     //    of the edge to the chain head, then the cost will be
948     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
949     // 3. If the tail node has more than two successors (this rarely happens),
950     //    we won't consider any additional cost.
951     if (TailBB->isSuccessor(*Iter)) {
952       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
953       if (TailBB->succ_size() == 1)
954         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
955                                     MisfetchCost + JumpInstCost);
956       else if (TailBB->succ_size() == 2) {
957         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
958         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
959         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
960                                   ? TailBBFreq * TailToHeadProb.getCompl()
961                                   : TailToHeadFreq;
962         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
963                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
964       }
965     }
966 
967     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
968                  << " to the top: " << Cost.getFrequency() << "\n");
969 
970     if (Cost < SmallestRotationCost) {
971       SmallestRotationCost = Cost;
972       RotationPos = Iter;
973     }
974   }
975 
976   if (RotationPos != LoopChain.end()) {
977     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
978                  << " to the top\n");
979     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
980   }
981 }
982 
983 /// \brief Collect blocks in the given loop that are to be placed.
984 ///
985 /// When profile data is available, exclude cold blocks from the returned set;
986 /// otherwise, collect all blocks in the loop.
987 MachineBlockPlacement::BlockFilterSet
988 MachineBlockPlacement::collectLoopBlockSet(MachineFunction &F, MachineLoop &L) {
989   BlockFilterSet LoopBlockSet;
990 
991   // Filter cold blocks off from LoopBlockSet when profile data is available.
992   // Collect the sum of frequencies of incoming edges to the loop header from
993   // outside. If we treat the loop as a super block, this is the frequency of
994   // the loop. Then for each block in the loop, we calculate the ratio between
995   // its frequency and the frequency of the loop block. When it is too small,
996   // don't add it to the loop chain. If there are outer loops, then this block
997   // will be merged into the first outer loop chain for which this block is not
998   // cold anymore. This needs precise profile data and we only do this when
999   // profile data is available.
1000   if (F.getFunction()->getEntryCount()) {
1001     BlockFrequency LoopFreq(0);
1002     for (auto LoopPred : L.getHeader()->predecessors())
1003       if (!L.contains(LoopPred))
1004         LoopFreq += MBFI->getBlockFreq(LoopPred) *
1005                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
1006 
1007     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
1008       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
1009       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
1010         continue;
1011       LoopBlockSet.insert(LoopBB);
1012     }
1013   } else
1014     LoopBlockSet.insert(L.block_begin(), L.block_end());
1015 
1016   return LoopBlockSet;
1017 }
1018 
1019 /// \brief Forms basic block chains from the natural loop structures.
1020 ///
1021 /// These chains are designed to preserve the existing *structure* of the code
1022 /// as much as possible. We can then stitch the chains together in a way which
1023 /// both preserves the topological structure and minimizes taken conditional
1024 /// branches.
1025 void MachineBlockPlacement::buildLoopChains(MachineFunction &F,
1026                                             MachineLoop &L) {
1027   // First recurse through any nested loops, building chains for those inner
1028   // loops.
1029   for (MachineLoop *InnerLoop : L)
1030     buildLoopChains(F, *InnerLoop);
1031 
1032   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1033   BlockFilterSet LoopBlockSet = collectLoopBlockSet(F, L);
1034 
1035   // Check if we have profile data for this function. If yes, we will rotate
1036   // this loop by modeling costs more precisely which requires the profile data
1037   // for better layout.
1038   bool RotateLoopWithProfile =
1039       PreciseRotationCost && F.getFunction()->getEntryCount();
1040 
1041   // First check to see if there is an obviously preferable top block for the
1042   // loop. This will default to the header, but may end up as one of the
1043   // predecessors to the header if there is one which will result in strictly
1044   // fewer branches in the loop body.
1045   // When we use profile data to rotate the loop, this is unnecessary.
1046   MachineBasicBlock *LoopTop =
1047       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
1048 
1049   // If we selected just the header for the loop top, look for a potentially
1050   // profitable exit block in the event that rotating the loop can eliminate
1051   // branches by placing an exit edge at the bottom.
1052   MachineBasicBlock *ExitingBB = nullptr;
1053   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
1054     ExitingBB = findBestLoopExit(F, L, LoopBlockSet);
1055 
1056   BlockChain &LoopChain = *BlockToChain[LoopTop];
1057 
1058   // FIXME: This is a really lame way of walking the chains in the loop: we
1059   // walk the blocks, and use a set to prevent visiting a particular chain
1060   // twice.
1061   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1062   assert(LoopChain.LoopPredecessors == 0);
1063   UpdatedPreds.insert(&LoopChain);
1064 
1065   for (MachineBasicBlock *LoopBB : LoopBlockSet) {
1066     BlockChain &Chain = *BlockToChain[LoopBB];
1067     if (!UpdatedPreds.insert(&Chain).second)
1068       continue;
1069 
1070     assert(Chain.LoopPredecessors == 0);
1071     for (MachineBasicBlock *ChainBB : Chain) {
1072       assert(BlockToChain[ChainBB] == &Chain);
1073       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1074         if (BlockToChain[Pred] == &Chain || !LoopBlockSet.count(Pred))
1075           continue;
1076         ++Chain.LoopPredecessors;
1077       }
1078     }
1079 
1080     if (Chain.LoopPredecessors == 0)
1081       BlockWorkList.push_back(*Chain.begin());
1082   }
1083 
1084   buildChain(LoopTop, LoopChain, BlockWorkList, &LoopBlockSet);
1085 
1086   if (RotateLoopWithProfile)
1087     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
1088   else
1089     rotateLoop(LoopChain, ExitingBB, LoopBlockSet);
1090 
1091   DEBUG({
1092     // Crash at the end so we get all of the debugging output first.
1093     bool BadLoop = false;
1094     if (LoopChain.LoopPredecessors) {
1095       BadLoop = true;
1096       dbgs() << "Loop chain contains a block without its preds placed!\n"
1097              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1098              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
1099     }
1100     for (MachineBasicBlock *ChainBB : LoopChain) {
1101       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
1102       if (!LoopBlockSet.erase(ChainBB)) {
1103         // We don't mark the loop as bad here because there are real situations
1104         // where this can occur. For example, with an unanalyzable fallthrough
1105         // from a loop block to a non-loop block or vice versa.
1106         dbgs() << "Loop chain contains a block not contained by the loop!\n"
1107                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1108                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1109                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1110       }
1111     }
1112 
1113     if (!LoopBlockSet.empty()) {
1114       BadLoop = true;
1115       for (MachineBasicBlock *LoopBB : LoopBlockSet)
1116         dbgs() << "Loop contains blocks never placed into a chain!\n"
1117                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
1118                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
1119                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
1120     }
1121     assert(!BadLoop && "Detected problems with the placement of this loop.");
1122   });
1123 }
1124 
1125 void MachineBlockPlacement::buildCFGChains(MachineFunction &F) {
1126   // Ensure that every BB in the function has an associated chain to simplify
1127   // the assumptions of the remaining algorithm.
1128   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
1129   for (MachineFunction::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
1130     MachineBasicBlock *BB = &*FI;
1131     BlockChain *Chain =
1132         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
1133     // Also, merge any blocks which we cannot reason about and must preserve
1134     // the exact fallthrough behavior for.
1135     for (;;) {
1136       Cond.clear();
1137       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1138       if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
1139         break;
1140 
1141       MachineFunction::iterator NextFI = std::next(FI);
1142       MachineBasicBlock *NextBB = &*NextFI;
1143       // Ensure that the layout successor is a viable block, as we know that
1144       // fallthrough is a possibility.
1145       assert(NextFI != FE && "Can't fallthrough past the last block.");
1146       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
1147                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
1148                    << "\n");
1149       Chain->merge(NextBB, nullptr);
1150       FI = NextFI;
1151       BB = NextBB;
1152     }
1153   }
1154 
1155   if (OutlineOptionalBranches) {
1156     // Find the nearest common dominator of all of F's terminators.
1157     MachineBasicBlock *Terminator = nullptr;
1158     for (MachineBasicBlock &MBB : F) {
1159       if (MBB.succ_size() == 0) {
1160         if (Terminator == nullptr)
1161           Terminator = &MBB;
1162         else
1163           Terminator = MDT->findNearestCommonDominator(Terminator, &MBB);
1164       }
1165     }
1166 
1167     // MBBs dominating this common dominator are unavoidable.
1168     UnavoidableBlocks.clear();
1169     for (MachineBasicBlock &MBB : F) {
1170       if (MDT->dominates(&MBB, Terminator)) {
1171         UnavoidableBlocks.insert(&MBB);
1172       }
1173     }
1174   }
1175 
1176   // Build any loop-based chains.
1177   for (MachineLoop *L : *MLI)
1178     buildLoopChains(F, *L);
1179 
1180   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
1181 
1182   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
1183   for (MachineBasicBlock &MBB : F) {
1184     BlockChain &Chain = *BlockToChain[&MBB];
1185     if (!UpdatedPreds.insert(&Chain).second)
1186       continue;
1187 
1188     assert(Chain.LoopPredecessors == 0);
1189     for (MachineBasicBlock *ChainBB : Chain) {
1190       assert(BlockToChain[ChainBB] == &Chain);
1191       for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1192         if (BlockToChain[Pred] == &Chain)
1193           continue;
1194         ++Chain.LoopPredecessors;
1195       }
1196     }
1197 
1198     if (Chain.LoopPredecessors == 0)
1199       BlockWorkList.push_back(*Chain.begin());
1200   }
1201 
1202   BlockChain &FunctionChain = *BlockToChain[&F.front()];
1203   buildChain(&F.front(), FunctionChain, BlockWorkList);
1204 
1205 #ifndef NDEBUG
1206   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
1207 #endif
1208   DEBUG({
1209     // Crash at the end so we get all of the debugging output first.
1210     bool BadFunc = false;
1211     FunctionBlockSetType FunctionBlockSet;
1212     for (MachineBasicBlock &MBB : F)
1213       FunctionBlockSet.insert(&MBB);
1214 
1215     for (MachineBasicBlock *ChainBB : FunctionChain)
1216       if (!FunctionBlockSet.erase(ChainBB)) {
1217         BadFunc = true;
1218         dbgs() << "Function chain contains a block not in the function!\n"
1219                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
1220       }
1221 
1222     if (!FunctionBlockSet.empty()) {
1223       BadFunc = true;
1224       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
1225         dbgs() << "Function contains blocks never placed into a chain!\n"
1226                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
1227     }
1228     assert(!BadFunc && "Detected problems with the block placement.");
1229   });
1230 
1231   // Splice the blocks into place.
1232   MachineFunction::iterator InsertPos = F.begin();
1233   for (MachineBasicBlock *ChainBB : FunctionChain) {
1234     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
1235                                                        : "          ... ")
1236                  << getBlockName(ChainBB) << "\n");
1237     if (InsertPos != MachineFunction::iterator(ChainBB))
1238       F.splice(InsertPos, ChainBB);
1239     else
1240       ++InsertPos;
1241 
1242     // Update the terminator of the previous block.
1243     if (ChainBB == *FunctionChain.begin())
1244       continue;
1245     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
1246 
1247     // FIXME: It would be awesome of updateTerminator would just return rather
1248     // than assert when the branch cannot be analyzed in order to remove this
1249     // boiler plate.
1250     Cond.clear();
1251     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1252     if (!TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1253       // The "PrevBB" is not yet updated to reflect current code layout, so,
1254       //   o. it may fall-through to a block without explict "goto" instruction
1255       //      before layout, and no longer fall-through it after layout; or
1256       //   o. just opposite.
1257       //
1258       // AnalyzeBranch() may return erroneous value for FBB when these two
1259       // situations take place. For the first scenario FBB is mistakenly set
1260       // NULL; for the 2nd scenario, the FBB, which is expected to be NULL,
1261       // is mistakenly pointing to "*BI".
1262       //
1263       bool needUpdateBr = true;
1264       if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
1265         PrevBB->updateTerminator();
1266         needUpdateBr = false;
1267         Cond.clear();
1268         TBB = FBB = nullptr;
1269         if (TII->AnalyzeBranch(*PrevBB, TBB, FBB, Cond)) {
1270           // FIXME: This should never take place.
1271           TBB = FBB = nullptr;
1272         }
1273       }
1274 
1275       // If PrevBB has a two-way branch, try to re-order the branches
1276       // such that we branch to the successor with higher probability first.
1277       if (TBB && !Cond.empty() && FBB &&
1278           MBPI->getEdgeProbability(PrevBB, FBB) >
1279               MBPI->getEdgeProbability(PrevBB, TBB) &&
1280           !TII->ReverseBranchCondition(Cond)) {
1281         DEBUG(dbgs() << "Reverse order of the two branches: "
1282                      << getBlockName(PrevBB) << "\n");
1283         DEBUG(dbgs() << "    Edge probability: "
1284                      << MBPI->getEdgeProbability(PrevBB, FBB) << " vs "
1285                      << MBPI->getEdgeProbability(PrevBB, TBB) << "\n");
1286         DebugLoc dl; // FIXME: this is nowhere
1287         TII->RemoveBranch(*PrevBB);
1288         TII->InsertBranch(*PrevBB, FBB, TBB, Cond, dl);
1289         needUpdateBr = true;
1290       }
1291       if (needUpdateBr)
1292         PrevBB->updateTerminator();
1293     }
1294   }
1295 
1296   // Fixup the last block.
1297   Cond.clear();
1298   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
1299   if (!TII->AnalyzeBranch(F.back(), TBB, FBB, Cond))
1300     F.back().updateTerminator();
1301 
1302   // Walk through the backedges of the function now that we have fully laid out
1303   // the basic blocks and align the destination of each backedge. We don't rely
1304   // exclusively on the loop info here so that we can align backedges in
1305   // unnatural CFGs and backedges that were introduced purely because of the
1306   // loop rotations done during this layout pass.
1307   // FIXME: Use Function::optForSize().
1308   if (F.getFunction()->hasFnAttribute(Attribute::OptimizeForSize))
1309     return;
1310   if (FunctionChain.begin() == FunctionChain.end())
1311     return; // Empty chain.
1312 
1313   const BranchProbability ColdProb(1, 5); // 20%
1314   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F.front());
1315   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
1316   for (MachineBasicBlock *ChainBB : FunctionChain) {
1317     if (ChainBB == *FunctionChain.begin())
1318       continue;
1319 
1320     // Don't align non-looping basic blocks. These are unlikely to execute
1321     // enough times to matter in practice. Note that we'll still handle
1322     // unnatural CFGs inside of a natural outer loop (the common case) and
1323     // rotated loops.
1324     MachineLoop *L = MLI->getLoopFor(ChainBB);
1325     if (!L)
1326       continue;
1327 
1328     unsigned Align = TLI->getPrefLoopAlignment(L);
1329     if (!Align)
1330       continue; // Don't care about loop alignment.
1331 
1332     // If the block is cold relative to the function entry don't waste space
1333     // aligning it.
1334     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
1335     if (Freq < WeightedEntryFreq)
1336       continue;
1337 
1338     // If the block is cold relative to its loop header, don't align it
1339     // regardless of what edges into the block exist.
1340     MachineBasicBlock *LoopHeader = L->getHeader();
1341     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
1342     if (Freq < (LoopHeaderFreq * ColdProb))
1343       continue;
1344 
1345     // Check for the existence of a non-layout predecessor which would benefit
1346     // from aligning this block.
1347     MachineBasicBlock *LayoutPred =
1348         &*std::prev(MachineFunction::iterator(ChainBB));
1349 
1350     // Force alignment if all the predecessors are jumps. We already checked
1351     // that the block isn't cold above.
1352     if (!LayoutPred->isSuccessor(ChainBB)) {
1353       ChainBB->setAlignment(Align);
1354       continue;
1355     }
1356 
1357     // Align this block if the layout predecessor's edge into this block is
1358     // cold relative to the block. When this is true, other predecessors make up
1359     // all of the hot entries into the block and thus alignment is likely to be
1360     // important.
1361     BranchProbability LayoutProb =
1362         MBPI->getEdgeProbability(LayoutPred, ChainBB);
1363     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
1364     if (LayoutEdgeFreq <= (Freq * ColdProb))
1365       ChainBB->setAlignment(Align);
1366   }
1367 }
1368 
1369 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &F) {
1370   // Check for single-block functions and skip them.
1371   if (std::next(F.begin()) == F.end())
1372     return false;
1373 
1374   if (skipOptnoneFunction(*F.getFunction()))
1375     return false;
1376 
1377   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1378   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1379   MLI = &getAnalysis<MachineLoopInfo>();
1380   TII = F.getSubtarget().getInstrInfo();
1381   TLI = F.getSubtarget().getTargetLowering();
1382   MDT = &getAnalysis<MachineDominatorTree>();
1383   assert(BlockToChain.empty());
1384 
1385   buildCFGChains(F);
1386 
1387   BlockToChain.clear();
1388   ChainAllocator.DestroyAll();
1389 
1390   if (AlignAllBlock)
1391     // Align all of the blocks in the function to a specific alignment.
1392     for (MachineBasicBlock &MBB : F)
1393       MBB.setAlignment(AlignAllBlock);
1394   else if (AlignAllNonFallThruBlocks) {
1395     // Align all of the blocks that have no fall-through predecessors to a
1396     // specific alignment.
1397     for (auto MBI = std::next(F.begin()), MBE = F.end(); MBI != MBE; ++MBI) {
1398       auto LayoutPred = std::prev(MBI);
1399       if (!LayoutPred->isSuccessor(&*MBI))
1400         MBI->setAlignment(AlignAllNonFallThruBlocks);
1401     }
1402   }
1403 
1404   // We always return true as we have no way to track whether the final order
1405   // differs from the original order.
1406   return true;
1407 }
1408 
1409 namespace {
1410 /// \brief A pass to compute block placement statistics.
1411 ///
1412 /// A separate pass to compute interesting statistics for evaluating block
1413 /// placement. This is separate from the actual placement pass so that they can
1414 /// be computed in the absence of any placement transformations or when using
1415 /// alternative placement strategies.
1416 class MachineBlockPlacementStats : public MachineFunctionPass {
1417   /// \brief A handle to the branch probability pass.
1418   const MachineBranchProbabilityInfo *MBPI;
1419 
1420   /// \brief A handle to the function-wide block frequency pass.
1421   const MachineBlockFrequencyInfo *MBFI;
1422 
1423 public:
1424   static char ID; // Pass identification, replacement for typeid
1425   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
1426     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
1427   }
1428 
1429   bool runOnMachineFunction(MachineFunction &F) override;
1430 
1431   void getAnalysisUsage(AnalysisUsage &AU) const override {
1432     AU.addRequired<MachineBranchProbabilityInfo>();
1433     AU.addRequired<MachineBlockFrequencyInfo>();
1434     AU.setPreservesAll();
1435     MachineFunctionPass::getAnalysisUsage(AU);
1436   }
1437 };
1438 }
1439 
1440 char MachineBlockPlacementStats::ID = 0;
1441 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
1442 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
1443                       "Basic Block Placement Stats", false, false)
1444 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
1445 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
1446 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
1447                     "Basic Block Placement Stats", false, false)
1448 
1449 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
1450   // Check for single-block functions and skip them.
1451   if (std::next(F.begin()) == F.end())
1452     return false;
1453 
1454   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
1455   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1456 
1457   for (MachineBasicBlock &MBB : F) {
1458     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
1459     Statistic &NumBranches =
1460         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
1461     Statistic &BranchTakenFreq =
1462         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
1463     for (MachineBasicBlock *Succ : MBB.successors()) {
1464       // Skip if this successor is a fallthrough.
1465       if (MBB.isLayoutSuccessor(Succ))
1466         continue;
1467 
1468       BlockFrequency EdgeFreq =
1469           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
1470       ++NumBranches;
1471       BranchTakenFreq += EdgeFreq.getFrequency();
1472     }
1473   }
1474 
1475   return false;
1476 }
1477