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