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