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