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