]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/MachineBlockPlacement.cpp
Merge ^/head r318380 through r318559.
[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/Analysis/BlockFrequencyInfoImpl.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
38 #include "llvm/CodeGen/MachineBranchProbabilityInfo.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/CodeGen/MachinePostDominators.h"
44 #include "llvm/CodeGen/TailDuplicator.h"
45 #include "llvm/Support/Allocator.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetLowering.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include <algorithm>
53 #include <functional>
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "block-placement"
58
59 STATISTIC(NumCondBranches, "Number of conditional branches");
60 STATISTIC(NumUncondBranches, "Number of unconditional branches");
61 STATISTIC(CondBranchTakenFreq,
62           "Potential frequency of taking conditional branches");
63 STATISTIC(UncondBranchTakenFreq,
64           "Potential frequency of taking unconditional branches");
65
66 static cl::opt<unsigned> AlignAllBlock("align-all-blocks",
67                                        cl::desc("Force the alignment of all "
68                                                 "blocks in the function."),
69                                        cl::init(0), cl::Hidden);
70
71 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
72     "align-all-nofallthru-blocks",
73     cl::desc("Force the alignment of all "
74              "blocks that have no fall-through predecessors (i.e. don't add "
75              "nops that are executed)."),
76     cl::init(0), cl::Hidden);
77
78 // FIXME: Find a good default for this flag and remove the flag.
79 static cl::opt<unsigned> ExitBlockBias(
80     "block-placement-exit-block-bias",
81     cl::desc("Block frequency percentage a loop exit block needs "
82              "over the original exit to be considered the new exit."),
83     cl::init(0), cl::Hidden);
84
85 // Definition:
86 // - Outlining: placement of a basic block outside the chain or hot path.
87
88 static cl::opt<unsigned> LoopToColdBlockRatio(
89     "loop-to-cold-block-ratio",
90     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
91              "(frequency of block) is greater than this ratio"),
92     cl::init(5), cl::Hidden);
93
94 static cl::opt<bool>
95     PreciseRotationCost("precise-rotation-cost",
96                         cl::desc("Model the cost of loop rotation more "
97                                  "precisely by using profile data."),
98                         cl::init(false), cl::Hidden);
99 static cl::opt<bool>
100     ForcePreciseRotationCost("force-precise-rotation-cost",
101                              cl::desc("Force the use of precise cost "
102                                       "loop rotation strategy."),
103                              cl::init(false), cl::Hidden);
104
105 static cl::opt<unsigned> MisfetchCost(
106     "misfetch-cost",
107     cl::desc("Cost that models the probabilistic risk of an instruction "
108              "misfetch due to a jump comparing to falling through, whose cost "
109              "is zero."),
110     cl::init(1), cl::Hidden);
111
112 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
113                                       cl::desc("Cost of jump instructions."),
114                                       cl::init(1), cl::Hidden);
115 static cl::opt<bool>
116 TailDupPlacement("tail-dup-placement",
117               cl::desc("Perform tail duplication during placement. "
118                        "Creates more fallthrough opportunites in "
119                        "outline branches."),
120               cl::init(true), cl::Hidden);
121
122 static cl::opt<bool>
123 BranchFoldPlacement("branch-fold-placement",
124               cl::desc("Perform branch folding during placement. "
125                        "Reduces code size."),
126               cl::init(true), cl::Hidden);
127
128 // Heuristic for tail duplication.
129 static cl::opt<unsigned> TailDupPlacementThreshold(
130     "tail-dup-placement-threshold",
131     cl::desc("Instruction cutoff for tail duplication during layout. "
132              "Tail merging during layout is forced to have a threshold "
133              "that won't conflict."), cl::init(2),
134     cl::Hidden);
135
136 // Heuristic for aggressive tail duplication.
137 static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
138     "tail-dup-placement-aggressive-threshold",
139     cl::desc("Instruction cutoff for aggressive tail duplication during "
140              "layout. Used at -O3. Tail merging during layout is forced to "
141              "have a threshold that won't conflict."), cl::init(3),
142     cl::Hidden);
143
144 // Heuristic for tail duplication.
145 static cl::opt<unsigned> TailDupPlacementPenalty(
146     "tail-dup-placement-penalty",
147     cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. "
148              "Copying can increase fallthrough, but it also increases icache "
149              "pressure. This parameter controls the penalty to account for that. "
150              "Percent as integer."),
151     cl::init(2),
152     cl::Hidden);
153
154 // Heuristic for triangle chains.
155 static cl::opt<unsigned> TriangleChainCount(
156     "triangle-chain-count",
157     cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
158              "triangle tail duplication heuristic to kick in. 0 to disable."),
159     cl::init(2),
160     cl::Hidden);
161
162 extern cl::opt<unsigned> StaticLikelyProb;
163 extern cl::opt<unsigned> ProfileLikelyProb;
164
165 // Internal option used to control BFI display only after MBP pass.
166 // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
167 // -view-block-layout-with-bfi=
168 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
169
170 // Command line option to specify the name of the function for CFG dump
171 // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
172 extern cl::opt<std::string> ViewBlockFreqFuncName;
173
174 namespace {
175 class BlockChain;
176 /// \brief Type for our function-wide basic block -> block chain mapping.
177 typedef DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChainMapType;
178 }
179
180 namespace {
181 /// \brief A chain of blocks which will be laid out contiguously.
182 ///
183 /// This is the datastructure representing a chain of consecutive blocks that
184 /// are profitable to layout together in order to maximize fallthrough
185 /// probabilities and code locality. We also can use a block chain to represent
186 /// a sequence of basic blocks which have some external (correctness)
187 /// requirement for sequential layout.
188 ///
189 /// Chains can be built around a single basic block and can be merged to grow
190 /// them. They participate in a block-to-chain mapping, which is updated
191 /// automatically as chains are merged together.
192 class BlockChain {
193   /// \brief The sequence of blocks belonging to this chain.
194   ///
195   /// This is the sequence of blocks for a particular chain. These will be laid
196   /// out in-order within the function.
197   SmallVector<MachineBasicBlock *, 4> Blocks;
198
199   /// \brief A handle to the function-wide basic block to block chain mapping.
200   ///
201   /// This is retained in each block chain to simplify the computation of child
202   /// block chains for SCC-formation and iteration. We store the edges to child
203   /// basic blocks, and map them back to their associated chains using this
204   /// structure.
205   BlockToChainMapType &BlockToChain;
206
207 public:
208   /// \brief Construct a new BlockChain.
209   ///
210   /// This builds a new block chain representing a single basic block in the
211   /// function. It also registers itself as the chain that block participates
212   /// in with the BlockToChain mapping.
213   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
214       : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
215     assert(BB && "Cannot create a chain with a null basic block");
216     BlockToChain[BB] = this;
217   }
218
219   /// \brief Iterator over blocks within the chain.
220   typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator;
221   typedef SmallVectorImpl<MachineBasicBlock *>::const_iterator const_iterator;
222
223   /// \brief Beginning of blocks within the chain.
224   iterator begin() { return Blocks.begin(); }
225   const_iterator begin() const { return Blocks.begin(); }
226
227   /// \brief End of blocks within the chain.
228   iterator end() { return Blocks.end(); }
229   const_iterator end() const { return Blocks.end(); }
230
231   bool remove(MachineBasicBlock* BB) {
232     for(iterator i = begin(); i != end(); ++i) {
233       if (*i == BB) {
234         Blocks.erase(i);
235         return true;
236       }
237     }
238     return false;
239   }
240
241   /// \brief Merge a block chain into this one.
242   ///
243   /// This routine merges a block chain into this one. It takes care of forming
244   /// a contiguous sequence of basic blocks, updating the edge list, and
245   /// updating the block -> chain mapping. It does not free or tear down the
246   /// old chain, but the old chain's block list is no longer valid.
247   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
248     assert(BB);
249     assert(!Blocks.empty());
250
251     // Fast path in case we don't have a chain already.
252     if (!Chain) {
253       assert(!BlockToChain[BB]);
254       Blocks.push_back(BB);
255       BlockToChain[BB] = this;
256       return;
257     }
258
259     assert(BB == *Chain->begin());
260     assert(Chain->begin() != Chain->end());
261
262     // Update the incoming blocks to point to this chain, and add them to the
263     // chain structure.
264     for (MachineBasicBlock *ChainBB : *Chain) {
265       Blocks.push_back(ChainBB);
266       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain");
267       BlockToChain[ChainBB] = this;
268     }
269   }
270
271 #ifndef NDEBUG
272   /// \brief Dump the blocks in this chain.
273   LLVM_DUMP_METHOD void dump() {
274     for (MachineBasicBlock *MBB : *this)
275       MBB->dump();
276   }
277 #endif // NDEBUG
278
279   /// \brief Count of predecessors of any block within the chain which have not
280   /// yet been scheduled.  In general, we will delay scheduling this chain
281   /// until those predecessors are scheduled (or we find a sufficiently good
282   /// reason to override this heuristic.)  Note that when forming loop chains,
283   /// blocks outside the loop are ignored and treated as if they were already
284   /// scheduled.
285   ///
286   /// Note: This field is reinitialized multiple times - once for each loop,
287   /// and then once for the function as a whole.
288   unsigned UnscheduledPredecessors;
289 };
290 }
291
292 namespace {
293 class MachineBlockPlacement : public MachineFunctionPass {
294   /// \brief A typedef for a block filter set.
295   typedef SmallSetVector<const MachineBasicBlock *, 16> BlockFilterSet;
296
297   /// Pair struct containing basic block and taildup profitiability
298   struct BlockAndTailDupResult {
299     MachineBasicBlock *BB;
300     bool ShouldTailDup;
301   };
302
303   /// Triple struct containing edge weight and the edge.
304   struct WeightedEdge {
305     BlockFrequency Weight;
306     MachineBasicBlock *Src;
307     MachineBasicBlock *Dest;
308   };
309
310   /// \brief work lists of blocks that are ready to be laid out
311   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
312   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
313
314   /// Edges that have already been computed as optimal.
315   DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
316
317   /// \brief Machine Function
318   MachineFunction *F;
319
320   /// \brief A handle to the branch probability pass.
321   const MachineBranchProbabilityInfo *MBPI;
322
323   /// \brief A handle to the function-wide block frequency pass.
324   std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
325
326   /// \brief A handle to the loop info.
327   MachineLoopInfo *MLI;
328
329   /// \brief Preferred loop exit.
330   /// Member variable for convenience. It may be removed by duplication deep
331   /// in the call stack.
332   MachineBasicBlock *PreferredLoopExit;
333
334   /// \brief A handle to the target's instruction info.
335   const TargetInstrInfo *TII;
336
337   /// \brief A handle to the target's lowering info.
338   const TargetLoweringBase *TLI;
339
340   /// \brief A handle to the post dominator tree.
341   MachinePostDominatorTree *MPDT;
342
343   /// \brief Duplicator used to duplicate tails during placement.
344   ///
345   /// Placement decisions can open up new tail duplication opportunities, but
346   /// since tail duplication affects placement decisions of later blocks, it
347   /// must be done inline.
348   TailDuplicator TailDup;
349
350   /// \brief Allocator and owner of BlockChain structures.
351   ///
352   /// We build BlockChains lazily while processing the loop structure of
353   /// a function. To reduce malloc traffic, we allocate them using this
354   /// slab-like allocator, and destroy them after the pass completes. An
355   /// important guarantee is that this allocator produces stable pointers to
356   /// the chains.
357   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
358
359   /// \brief Function wide BasicBlock to BlockChain mapping.
360   ///
361   /// This mapping allows efficiently moving from any given basic block to the
362   /// BlockChain it participates in, if any. We use it to, among other things,
363   /// allow implicitly defining edges between chains as the existing edges
364   /// between basic blocks.
365   DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
366
367 #ifndef NDEBUG
368   /// The set of basic blocks that have terminators that cannot be fully
369   /// analyzed.  These basic blocks cannot be re-ordered safely by
370   /// MachineBlockPlacement, and we must preserve physical layout of these
371   /// blocks and their successors through the pass.
372   SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
373 #endif
374
375   /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
376   /// if the count goes to 0, add them to the appropriate work list.
377   void markChainSuccessors(
378       const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
379       const BlockFilterSet *BlockFilter = nullptr);
380
381   /// Decrease the UnscheduledPredecessors count for a single block, and
382   /// if the count goes to 0, add them to the appropriate work list.
383   void markBlockSuccessors(
384       const BlockChain &Chain, const MachineBasicBlock *BB,
385       const MachineBasicBlock *LoopHeaderBB,
386       const BlockFilterSet *BlockFilter = nullptr);
387
388   BranchProbability
389   collectViableSuccessors(
390       const MachineBasicBlock *BB, const BlockChain &Chain,
391       const BlockFilterSet *BlockFilter,
392       SmallVector<MachineBasicBlock *, 4> &Successors);
393   bool shouldPredBlockBeOutlined(
394       const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
395       const BlockChain &Chain, const BlockFilterSet *BlockFilter,
396       BranchProbability SuccProb, BranchProbability HotProb);
397   bool repeatedlyTailDuplicateBlock(
398       MachineBasicBlock *BB, MachineBasicBlock *&LPred,
399       const MachineBasicBlock *LoopHeaderBB,
400       BlockChain &Chain, BlockFilterSet *BlockFilter,
401       MachineFunction::iterator &PrevUnplacedBlockIt);
402   bool maybeTailDuplicateBlock(
403       MachineBasicBlock *BB, MachineBasicBlock *LPred,
404       BlockChain &Chain, BlockFilterSet *BlockFilter,
405       MachineFunction::iterator &PrevUnplacedBlockIt,
406       bool &DuplicatedToPred);
407   bool hasBetterLayoutPredecessor(
408       const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
409       const BlockChain &SuccChain, BranchProbability SuccProb,
410       BranchProbability RealSuccProb, const BlockChain &Chain,
411       const BlockFilterSet *BlockFilter);
412   BlockAndTailDupResult selectBestSuccessor(
413       const MachineBasicBlock *BB, const BlockChain &Chain,
414       const BlockFilterSet *BlockFilter);
415   MachineBasicBlock *selectBestCandidateBlock(
416       const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList);
417   MachineBasicBlock *getFirstUnplacedBlock(
418       const BlockChain &PlacedChain,
419       MachineFunction::iterator &PrevUnplacedBlockIt,
420       const BlockFilterSet *BlockFilter);
421
422   /// \brief Add a basic block to the work list if it is appropriate.
423   ///
424   /// If the optional parameter BlockFilter is provided, only MBB
425   /// present in the set will be added to the worklist. If nullptr
426   /// is provided, no filtering occurs.
427   void fillWorkLists(const MachineBasicBlock *MBB,
428                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
429                      const BlockFilterSet *BlockFilter);
430   void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
431                   BlockFilterSet *BlockFilter = nullptr);
432   MachineBasicBlock *findBestLoopTop(
433       const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
434   MachineBasicBlock *findBestLoopExit(
435       const MachineLoop &L, const BlockFilterSet &LoopBlockSet);
436   BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
437   void buildLoopChains(const MachineLoop &L);
438   void rotateLoop(
439       BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
440       const BlockFilterSet &LoopBlockSet);
441   void rotateLoopWithProfile(
442       BlockChain &LoopChain, const MachineLoop &L,
443       const BlockFilterSet &LoopBlockSet);
444   void buildCFGChains();
445   void optimizeBranches();
446   void alignBlocks();
447   /// Returns true if a block should be tail-duplicated to increase fallthrough
448   /// opportunities.
449   bool shouldTailDuplicate(MachineBasicBlock *BB);
450   /// Check the edge frequencies to see if tail duplication will increase
451   /// fallthroughs.
452   bool isProfitableToTailDup(
453     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
454     BranchProbability AdjustedSumProb,
455     const BlockChain &Chain, const BlockFilterSet *BlockFilter);
456   /// Check for a trellis layout.
457   bool isTrellis(const MachineBasicBlock *BB,
458                  const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
459                  const BlockChain &Chain, const BlockFilterSet *BlockFilter);
460   /// Get the best successor given a trellis layout.
461   BlockAndTailDupResult getBestTrellisSuccessor(
462       const MachineBasicBlock *BB,
463       const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
464       BranchProbability AdjustedSumProb, const BlockChain &Chain,
465       const BlockFilterSet *BlockFilter);
466   /// Get the best pair of non-conflicting edges.
467   static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
468       const MachineBasicBlock *BB,
469       MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
470   /// Returns true if a block can tail duplicate into all unplaced
471   /// predecessors. Filters based on loop.
472   bool canTailDuplicateUnplacedPreds(
473       const MachineBasicBlock *BB, MachineBasicBlock *Succ,
474       const BlockChain &Chain, const BlockFilterSet *BlockFilter);
475   /// Find chains of triangles to tail-duplicate where a global analysis works,
476   /// but a local analysis would not find them.
477   void precomputeTriangleChains();
478
479 public:
480   static char ID; // Pass identification, replacement for typeid
481   MachineBlockPlacement() : MachineFunctionPass(ID) {
482     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
483   }
484
485   bool runOnMachineFunction(MachineFunction &F) override;
486
487   void getAnalysisUsage(AnalysisUsage &AU) const override {
488     AU.addRequired<MachineBranchProbabilityInfo>();
489     AU.addRequired<MachineBlockFrequencyInfo>();
490     if (TailDupPlacement)
491       AU.addRequired<MachinePostDominatorTree>();
492     AU.addRequired<MachineLoopInfo>();
493     AU.addRequired<TargetPassConfig>();
494     MachineFunctionPass::getAnalysisUsage(AU);
495   }
496 };
497 }
498
499 char MachineBlockPlacement::ID = 0;
500 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
501 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement",
502                       "Branch Probability Basic Block Placement", false, false)
503 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
504 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
505 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
506 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
507 INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement",
508                     "Branch Probability Basic Block Placement", false, false)
509
510 #ifndef NDEBUG
511 /// \brief Helper to print the name of a MBB.
512 ///
513 /// Only used by debug logging.
514 static std::string getBlockName(const MachineBasicBlock *BB) {
515   std::string Result;
516   raw_string_ostream OS(Result);
517   OS << "BB#" << BB->getNumber();
518   OS << " ('" << BB->getName() << "')";
519   OS.flush();
520   return Result;
521 }
522 #endif
523
524 /// \brief Mark a chain's successors as having one fewer preds.
525 ///
526 /// When a chain is being merged into the "placed" chain, this routine will
527 /// quickly walk the successors of each block in the chain and mark them as
528 /// having one fewer active predecessor. It also adds any successors of this
529 /// chain which reach the zero-predecessor state to the appropriate worklist.
530 void MachineBlockPlacement::markChainSuccessors(
531     const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
532     const BlockFilterSet *BlockFilter) {
533   // Walk all the blocks in this chain, marking their successors as having
534   // a predecessor placed.
535   for (MachineBasicBlock *MBB : Chain) {
536     markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
537   }
538 }
539
540 /// \brief Mark a single block's successors as having one fewer preds.
541 ///
542 /// Under normal circumstances, this is only called by markChainSuccessors,
543 /// but if a block that was to be placed is completely tail-duplicated away,
544 /// and was duplicated into the chain end, we need to redo markBlockSuccessors
545 /// for just that block.
546 void MachineBlockPlacement::markBlockSuccessors(
547     const BlockChain &Chain, const MachineBasicBlock *MBB,
548     const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
549   // Add any successors for which this is the only un-placed in-loop
550   // predecessor to the worklist as a viable candidate for CFG-neutral
551   // placement. No subsequent placement of this block will violate the CFG
552   // shape, so we get to use heuristics to choose a favorable placement.
553   for (MachineBasicBlock *Succ : MBB->successors()) {
554     if (BlockFilter && !BlockFilter->count(Succ))
555       continue;
556     BlockChain &SuccChain = *BlockToChain[Succ];
557     // Disregard edges within a fixed chain, or edges to the loop header.
558     if (&Chain == &SuccChain || Succ == LoopHeaderBB)
559       continue;
560
561     // This is a cross-chain edge that is within the loop, so decrement the
562     // loop predecessor count of the destination chain.
563     if (SuccChain.UnscheduledPredecessors == 0 ||
564         --SuccChain.UnscheduledPredecessors > 0)
565       continue;
566
567     auto *NewBB = *SuccChain.begin();
568     if (NewBB->isEHPad())
569       EHPadWorkList.push_back(NewBB);
570     else
571       BlockWorkList.push_back(NewBB);
572   }
573 }
574
575 /// This helper function collects the set of successors of block
576 /// \p BB that are allowed to be its layout successors, and return
577 /// the total branch probability of edges from \p BB to those
578 /// blocks.
579 BranchProbability MachineBlockPlacement::collectViableSuccessors(
580     const MachineBasicBlock *BB, const BlockChain &Chain,
581     const BlockFilterSet *BlockFilter,
582     SmallVector<MachineBasicBlock *, 4> &Successors) {
583   // Adjust edge probabilities by excluding edges pointing to blocks that is
584   // either not in BlockFilter or is already in the current chain. Consider the
585   // following CFG:
586   //
587   //     --->A
588   //     |  / \
589   //     | B   C
590   //     |  \ / \
591   //     ----D   E
592   //
593   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
594   // A->C is chosen as a fall-through, D won't be selected as a successor of C
595   // due to CFG constraint (the probability of C->D is not greater than
596   // HotProb to break top-order). If we exclude E that is not in BlockFilter
597   // when calculating the  probability of C->D, D will be selected and we
598   // will get A C D B as the layout of this loop.
599   auto AdjustedSumProb = BranchProbability::getOne();
600   for (MachineBasicBlock *Succ : BB->successors()) {
601     bool SkipSucc = false;
602     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
603       SkipSucc = true;
604     } else {
605       BlockChain *SuccChain = BlockToChain[Succ];
606       if (SuccChain == &Chain) {
607         SkipSucc = true;
608       } else if (Succ != *SuccChain->begin()) {
609         DEBUG(dbgs() << "    " << getBlockName(Succ) << " -> Mid chain!\n");
610         continue;
611       }
612     }
613     if (SkipSucc)
614       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
615     else
616       Successors.push_back(Succ);
617   }
618
619   return AdjustedSumProb;
620 }
621
622 /// The helper function returns the branch probability that is adjusted
623 /// or normalized over the new total \p AdjustedSumProb.
624 static BranchProbability
625 getAdjustedProbability(BranchProbability OrigProb,
626                        BranchProbability AdjustedSumProb) {
627   BranchProbability SuccProb;
628   uint32_t SuccProbN = OrigProb.getNumerator();
629   uint32_t SuccProbD = AdjustedSumProb.getNumerator();
630   if (SuccProbN >= SuccProbD)
631     SuccProb = BranchProbability::getOne();
632   else
633     SuccProb = BranchProbability(SuccProbN, SuccProbD);
634
635   return SuccProb;
636 }
637
638 /// Check if \p BB has exactly the successors in \p Successors.
639 static bool
640 hasSameSuccessors(MachineBasicBlock &BB,
641                   SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
642   if (BB.succ_size() != Successors.size())
643     return false;
644   // We don't want to count self-loops
645   if (Successors.count(&BB))
646     return false;
647   for (MachineBasicBlock *Succ : BB.successors())
648     if (!Successors.count(Succ))
649       return false;
650   return true;
651 }
652
653 /// Check if a block should be tail duplicated to increase fallthrough
654 /// opportunities.
655 /// \p BB Block to check.
656 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
657   // Blocks with single successors don't create additional fallthrough
658   // opportunities. Don't duplicate them. TODO: When conditional exits are
659   // analyzable, allow them to be duplicated.
660   bool IsSimple = TailDup.isSimpleBB(BB);
661
662   if (BB->succ_size() == 1)
663     return false;
664   return TailDup.shouldTailDuplicate(IsSimple, *BB);
665 }
666
667 /// Compare 2 BlockFrequency's with a small penalty for \p A.
668 /// In order to be conservative, we apply a X% penalty to account for
669 /// increased icache pressure and static heuristics. For small frequencies
670 /// we use only the numerators to improve accuracy. For simplicity, we assume the
671 /// penalty is less than 100%
672 /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
673 static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
674                             uint64_t EntryFreq) {
675   BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
676   BlockFrequency Gain = A - B;
677   return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
678 }
679
680 /// Check the edge frequencies to see if tail duplication will increase
681 /// fallthroughs. It only makes sense to call this function when
682 /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
683 /// always locally profitable if we would have picked \p Succ without
684 /// considering duplication.
685 bool MachineBlockPlacement::isProfitableToTailDup(
686     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
687     BranchProbability QProb,
688     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
689   // We need to do a probability calculation to make sure this is profitable.
690   // First: does succ have a successor that post-dominates? This affects the
691   // calculation. The 2 relevant cases are:
692   //    BB         BB
693   //    | \Qout    | \Qout
694   //   P|  C       |P C
695   //    =   C'     =   C'
696   //    |  /Qin    |  /Qin
697   //    | /        | /
698   //    Succ       Succ
699   //    / \        | \  V
700   //  U/   =V      |U \
701   //  /     \      =   D
702   //  D      E     |  /
703   //               | /
704   //               |/
705   //               PDom
706   //  '=' : Branch taken for that CFG edge
707   // In the second case, Placing Succ while duplicating it into C prevents the
708   // fallthrough of Succ into either D or PDom, because they now have C as an
709   // unplaced predecessor
710
711   // Start by figuring out which case we fall into
712   MachineBasicBlock *PDom = nullptr;
713   SmallVector<MachineBasicBlock *, 4> SuccSuccs;
714   // Only scan the relevant successors
715   auto AdjustedSuccSumProb =
716       collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
717   BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
718   auto BBFreq = MBFI->getBlockFreq(BB);
719   auto SuccFreq = MBFI->getBlockFreq(Succ);
720   BlockFrequency P = BBFreq * PProb;
721   BlockFrequency Qout = BBFreq * QProb;
722   uint64_t EntryFreq = MBFI->getEntryFreq();
723   // If there are no more successors, it is profitable to copy, as it strictly
724   // increases fallthrough.
725   if (SuccSuccs.size() == 0)
726     return greaterWithBias(P, Qout, EntryFreq);
727
728   auto BestSuccSucc = BranchProbability::getZero();
729   // Find the PDom or the best Succ if no PDom exists.
730   for (MachineBasicBlock *SuccSucc : SuccSuccs) {
731     auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
732     if (Prob > BestSuccSucc)
733       BestSuccSucc = Prob;
734     if (PDom == nullptr)
735       if (MPDT->dominates(SuccSucc, Succ)) {
736         PDom = SuccSucc;
737         break;
738       }
739   }
740   // For the comparisons, we need to know Succ's best incoming edge that isn't
741   // from BB.
742   auto SuccBestPred = BlockFrequency(0);
743   for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
744     if (SuccPred == Succ || SuccPred == BB
745         || BlockToChain[SuccPred] == &Chain
746         || (BlockFilter && !BlockFilter->count(SuccPred)))
747       continue;
748     auto Freq = MBFI->getBlockFreq(SuccPred)
749         * MBPI->getEdgeProbability(SuccPred, Succ);
750     if (Freq > SuccBestPred)
751       SuccBestPred = Freq;
752   }
753   // Qin is Succ's best unplaced incoming edge that isn't BB
754   BlockFrequency Qin = SuccBestPred;
755   // If it doesn't have a post-dominating successor, here is the calculation:
756   //    BB        BB
757   //    | \Qout   |  \
758   //   P|  C      |   =
759   //    =   C'    |    C
760   //    |  /Qin   |     |
761   //    | /       |     C' (+Succ)
762   //    Succ      Succ /|
763   //    / \       |  \/ |
764   //  U/   =V     |  == |
765   //  /     \     | /  \|
766   //  D      E    D     E
767   //  '=' : Branch taken for that CFG edge
768   //  Cost in the first case is: P + V
769   //  For this calculation, we always assume P > Qout. If Qout > P
770   //  The result of this function will be ignored at the caller.
771   //  Let F = SuccFreq - Qin
772   //  Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
773
774   if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
775     BranchProbability UProb = BestSuccSucc;
776     BranchProbability VProb = AdjustedSuccSumProb - UProb;
777     BlockFrequency F = SuccFreq - Qin;
778     BlockFrequency V = SuccFreq * VProb;
779     BlockFrequency QinU = std::min(Qin, F) * UProb;
780     BlockFrequency BaseCost = P + V;
781     BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
782     return greaterWithBias(BaseCost, DupCost, EntryFreq);
783   }
784   BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
785   BranchProbability VProb = AdjustedSuccSumProb - UProb;
786   BlockFrequency U = SuccFreq * UProb;
787   BlockFrequency V = SuccFreq * VProb;
788   BlockFrequency F = SuccFreq - Qin;
789   // If there is a post-dominating successor, here is the calculation:
790   // BB         BB                 BB          BB
791   // | \Qout    |   \               | \Qout     |  \
792   // |P C       |    =              |P C        |   =
793   // =   C'     |P    C             =   C'      |P   C
794   // |  /Qin    |      |            |  /Qin     |     |
795   // | /        |      C' (+Succ)   | /         |     C' (+Succ)
796   // Succ       Succ  /|            Succ        Succ /|
797   // | \  V     |   \/ |            | \  V      |  \/ |
798   // |U \       |U  /\ =?           |U =        |U /\ |
799   // =   D      = =  =?|            |   D       | =  =|
800   // |  /       |/     D            |  /        |/    D
801   // | /        |     /             | =         |    /
802   // |/         |    /              |/          |   =
803   // Dom         Dom                Dom         Dom
804   //  '=' : Branch taken for that CFG edge
805   // The cost for taken branches in the first case is P + U
806   // Let F = SuccFreq - Qin
807   // The cost in the second case (assuming independence), given the layout:
808   // BB, Succ, (C+Succ), D, Dom or the layout:
809   // BB, Succ, D, Dom, (C+Succ)
810   // is Qout + max(F, Qin) * U + min(F, Qin)
811   // compare P + U vs Qout + P * U + Qin.
812   //
813   // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
814   //
815   // For the 3rd case, the cost is P + 2 * V
816   // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
817   // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
818   if (UProb > AdjustedSuccSumProb / 2 &&
819       !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
820                                   Chain, BlockFilter))
821     // Cases 3 & 4
822     return greaterWithBias(
823         (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
824         EntryFreq);
825   // Cases 1 & 2
826   return greaterWithBias((P + U),
827                          (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
828                           std::max(Qin, F) * UProb),
829                          EntryFreq);
830 }
831
832 /// Check for a trellis layout. \p BB is the upper part of a trellis if its
833 /// successors form the lower part of a trellis. A successor set S forms the
834 /// lower part of a trellis if all of the predecessors of S are either in S or
835 /// have all of S as successors. We ignore trellises where BB doesn't have 2
836 /// successors because for fewer than 2, it's trivial, and for 3 or greater they
837 /// are very uncommon and complex to compute optimally. Allowing edges within S
838 /// is not strictly a trellis, but the same algorithm works, so we allow it.
839 bool MachineBlockPlacement::isTrellis(
840     const MachineBasicBlock *BB,
841     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
842     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
843   // Technically BB could form a trellis with branching factor higher than 2.
844   // But that's extremely uncommon.
845   if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
846     return false;
847
848   SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
849                                                        BB->succ_end());
850   // To avoid reviewing the same predecessors twice.
851   SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
852
853   for (MachineBasicBlock *Succ : ViableSuccs) {
854     int PredCount = 0;
855     for (auto SuccPred : Succ->predecessors()) {
856       // Allow triangle successors, but don't count them.
857       if (Successors.count(SuccPred)) {
858         // Make sure that it is actually a triangle.
859         for (MachineBasicBlock *CheckSucc : SuccPred->successors())
860           if (!Successors.count(CheckSucc))
861             return false;
862         continue;
863       }
864       const BlockChain *PredChain = BlockToChain[SuccPred];
865       if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
866           PredChain == &Chain || PredChain == BlockToChain[Succ])
867         continue;
868       ++PredCount;
869       // Perform the successor check only once.
870       if (!SeenPreds.insert(SuccPred).second)
871         continue;
872       if (!hasSameSuccessors(*SuccPred, Successors))
873         return false;
874     }
875     // If one of the successors has only BB as a predecessor, it is not a
876     // trellis.
877     if (PredCount < 1)
878       return false;
879   }
880   return true;
881 }
882
883 /// Pick the highest total weight pair of edges that can both be laid out.
884 /// The edges in \p Edges[0] are assumed to have a different destination than
885 /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
886 /// the individual highest weight edges to the 2 different destinations, or in
887 /// case of a conflict, one of them should be replaced with a 2nd best edge.
888 std::pair<MachineBlockPlacement::WeightedEdge,
889           MachineBlockPlacement::WeightedEdge>
890 MachineBlockPlacement::getBestNonConflictingEdges(
891     const MachineBasicBlock *BB,
892     MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
893         Edges) {
894   // Sort the edges, and then for each successor, find the best incoming
895   // predecessor. If the best incoming predecessors aren't the same,
896   // then that is clearly the best layout. If there is a conflict, one of the
897   // successors will have to fallthrough from the second best predecessor. We
898   // compare which combination is better overall.
899
900   // Sort for highest frequency.
901   auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
902
903   std::stable_sort(Edges[0].begin(), Edges[0].end(), Cmp);
904   std::stable_sort(Edges[1].begin(), Edges[1].end(), Cmp);
905   auto BestA = Edges[0].begin();
906   auto BestB = Edges[1].begin();
907   // Arrange for the correct answer to be in BestA and BestB
908   // If the 2 best edges don't conflict, the answer is already there.
909   if (BestA->Src == BestB->Src) {
910     // Compare the total fallthrough of (Best + Second Best) for both pairs
911     auto SecondBestA = std::next(BestA);
912     auto SecondBestB = std::next(BestB);
913     BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
914     BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
915     if (BestAScore < BestBScore)
916       BestA = SecondBestA;
917     else
918       BestB = SecondBestB;
919   }
920   // Arrange for the BB edge to be in BestA if it exists.
921   if (BestB->Src == BB)
922     std::swap(BestA, BestB);
923   return std::make_pair(*BestA, *BestB);
924 }
925
926 /// Get the best successor from \p BB based on \p BB being part of a trellis.
927 /// We only handle trellises with 2 successors, so the algorithm is
928 /// straightforward: Find the best pair of edges that don't conflict. We find
929 /// the best incoming edge for each successor in the trellis. If those conflict,
930 /// we consider which of them should be replaced with the second best.
931 /// Upon return the two best edges will be in \p BestEdges. If one of the edges
932 /// comes from \p BB, it will be in \p BestEdges[0]
933 MachineBlockPlacement::BlockAndTailDupResult
934 MachineBlockPlacement::getBestTrellisSuccessor(
935     const MachineBasicBlock *BB,
936     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
937     BranchProbability AdjustedSumProb, const BlockChain &Chain,
938     const BlockFilterSet *BlockFilter) {
939
940   BlockAndTailDupResult Result = {nullptr, false};
941   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
942                                                        BB->succ_end());
943
944   // We assume size 2 because it's common. For general n, we would have to do
945   // the Hungarian algorithm, but it's not worth the complexity because more
946   // than 2 successors is fairly uncommon, and a trellis even more so.
947   if (Successors.size() != 2 || ViableSuccs.size() != 2)
948     return Result;
949
950   // Collect the edge frequencies of all edges that form the trellis.
951   SmallVector<WeightedEdge, 8> Edges[2];
952   int SuccIndex = 0;
953   for (auto Succ : ViableSuccs) {
954     for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
955       // Skip any placed predecessors that are not BB
956       if (SuccPred != BB)
957         if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
958             BlockToChain[SuccPred] == &Chain ||
959             BlockToChain[SuccPred] == BlockToChain[Succ])
960           continue;
961       BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
962                                 MBPI->getEdgeProbability(SuccPred, Succ);
963       Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
964     }
965     ++SuccIndex;
966   }
967
968   // Pick the best combination of 2 edges from all the edges in the trellis.
969   WeightedEdge BestA, BestB;
970   std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
971
972   if (BestA.Src != BB) {
973     // If we have a trellis, and BB doesn't have the best fallthrough edges,
974     // we shouldn't choose any successor. We've already looked and there's a
975     // better fallthrough edge for all the successors.
976     DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
977     return Result;
978   }
979
980   // Did we pick the triangle edge? If tail-duplication is profitable, do
981   // that instead. Otherwise merge the triangle edge now while we know it is
982   // optimal.
983   if (BestA.Dest == BestB.Src) {
984     // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
985     // would be better.
986     MachineBasicBlock *Succ1 = BestA.Dest;
987     MachineBasicBlock *Succ2 = BestB.Dest;
988     // Check to see if tail-duplication would be profitable.
989     if (TailDupPlacement && shouldTailDuplicate(Succ2) &&
990         canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
991         isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
992                               Chain, BlockFilter)) {
993       DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
994                 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
995             dbgs() << "    Selected: " << getBlockName(Succ2)
996                    << ", probability: " << Succ2Prob << " (Tail Duplicate)\n");
997       Result.BB = Succ2;
998       Result.ShouldTailDup = true;
999       return Result;
1000     }
1001   }
1002   // We have already computed the optimal edge for the other side of the
1003   // trellis.
1004   ComputedEdges[BestB.Src] = { BestB.Dest, false };
1005
1006   auto TrellisSucc = BestA.Dest;
1007   DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1008             MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1009         dbgs() << "    Selected: " << getBlockName(TrellisSucc)
1010                << ", probability: " << SuccProb << " (Trellis)\n");
1011   Result.BB = TrellisSucc;
1012   return Result;
1013 }
1014
1015 /// When the option TailDupPlacement is on, this method checks if the
1016 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1017 /// into all of its unplaced, unfiltered predecessors, that are not BB.
1018 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1019     const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1020     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
1021   if (!shouldTailDuplicate(Succ))
1022     return false;
1023
1024   // For CFG checking.
1025   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1026                                                        BB->succ_end());
1027   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1028     // Make sure all unplaced and unfiltered predecessors can be
1029     // tail-duplicated into.
1030     // Skip any blocks that are already placed or not in this loop.
1031     if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1032         || BlockToChain[Pred] == &Chain)
1033       continue;
1034     if (!TailDup.canTailDuplicate(Succ, Pred)) {
1035       if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1036         // This will result in a trellis after tail duplication, so we don't
1037         // need to copy Succ into this predecessor. In the presence
1038         // of a trellis tail duplication can continue to be profitable.
1039         // For example:
1040         // A            A
1041         // |\           |\
1042         // | \          | \
1043         // |  C         |  C+BB
1044         // | /          |  |
1045         // |/           |  |
1046         // BB    =>     BB |
1047         // |\           |\/|
1048         // | \          |/\|
1049         // |  D         |  D
1050         // | /          | /
1051         // |/           |/
1052         // Succ         Succ
1053         //
1054         // After BB was duplicated into C, the layout looks like the one on the
1055         // right. BB and C now have the same successors. When considering
1056         // whether Succ can be duplicated into all its unplaced predecessors, we
1057         // ignore C.
1058         // We can do this because C already has a profitable fallthrough, namely
1059         // D. TODO(iteratee): ignore sufficiently cold predecessors for
1060         // duplication and for this test.
1061         //
1062         // This allows trellises to be laid out in 2 separate chains
1063         // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1064         // because it allows the creation of 2 fallthrough paths with links
1065         // between them, and we correctly identify the best layout for these
1066         // CFGs. We want to extend trellises that the user created in addition
1067         // to trellises created by tail-duplication, so we just look for the
1068         // CFG.
1069         continue;
1070       return false;
1071     }
1072   }
1073   return true;
1074 }
1075
1076 /// Find chains of triangles where we believe it would be profitable to
1077 /// tail-duplicate them all, but a local analysis would not find them.
1078 /// There are 3 ways this can be profitable:
1079 /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1080 ///    longer chains)
1081 /// 2) The chains are statically correlated. Branch probabilities have a very
1082 ///    U-shaped distribution.
1083 ///    [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1084 ///    If the branches in a chain are likely to be from the same side of the
1085 ///    distribution as their predecessor, but are independent at runtime, this
1086 ///    transformation is profitable. (Because the cost of being wrong is a small
1087 ///    fixed cost, unlike the standard triangle layout where the cost of being
1088 ///    wrong scales with the # of triangles.)
1089 /// 3) The chains are dynamically correlated. If the probability that a previous
1090 ///    branch was taken positively influences whether the next branch will be
1091 ///    taken
1092 /// We believe that 2 and 3 are common enough to justify the small margin in 1.
1093 void MachineBlockPlacement::precomputeTriangleChains() {
1094   struct TriangleChain {
1095     std::vector<MachineBasicBlock *> Edges;
1096     TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1097         : Edges({src, dst}) {}
1098
1099     void append(MachineBasicBlock *dst) {
1100       assert(getKey()->isSuccessor(dst) &&
1101              "Attempting to append a block that is not a successor.");
1102       Edges.push_back(dst);
1103     }
1104
1105     unsigned count() const { return Edges.size() - 1; }
1106
1107     MachineBasicBlock *getKey() const {
1108       return Edges.back();
1109     }
1110   };
1111
1112   if (TriangleChainCount == 0)
1113     return;
1114
1115   DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1116   // Map from last block to the chain that contains it. This allows us to extend
1117   // chains as we find new triangles.
1118   DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1119   for (MachineBasicBlock &BB : *F) {
1120     // If BB doesn't have 2 successors, it doesn't start a triangle.
1121     if (BB.succ_size() != 2)
1122       continue;
1123     MachineBasicBlock *PDom = nullptr;
1124     for (MachineBasicBlock *Succ : BB.successors()) {
1125       if (!MPDT->dominates(Succ, &BB))
1126         continue;
1127       PDom = Succ;
1128       break;
1129     }
1130     // If BB doesn't have a post-dominating successor, it doesn't form a
1131     // triangle.
1132     if (PDom == nullptr)
1133       continue;
1134     // If PDom has a hint that it is low probability, skip this triangle.
1135     if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1136       continue;
1137     // If PDom isn't eligible for duplication, this isn't the kind of triangle
1138     // we're looking for.
1139     if (!shouldTailDuplicate(PDom))
1140       continue;
1141     bool CanTailDuplicate = true;
1142     // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1143     // isn't the kind of triangle we're looking for.
1144     for (MachineBasicBlock* Pred : PDom->predecessors()) {
1145       if (Pred == &BB)
1146         continue;
1147       if (!TailDup.canTailDuplicate(PDom, Pred)) {
1148         CanTailDuplicate = false;
1149         break;
1150       }
1151     }
1152     // If we can't tail-duplicate PDom to its predecessors, then skip this
1153     // triangle.
1154     if (!CanTailDuplicate)
1155       continue;
1156
1157     // Now we have an interesting triangle. Insert it if it's not part of an
1158     // existing chain
1159     // Note: This cannot be replaced with a call insert() or emplace() because
1160     // the find key is BB, but the insert/emplace key is PDom.
1161     auto Found = TriangleChainMap.find(&BB);
1162     // If it is, remove the chain from the map, grow it, and put it back in the
1163     // map with the end as the new key.
1164     if (Found != TriangleChainMap.end()) {
1165       TriangleChain Chain = std::move(Found->second);
1166       TriangleChainMap.erase(Found);
1167       Chain.append(PDom);
1168       TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1169     } else {
1170       auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
1171       assert(InsertResult.second && "Block seen twice.");
1172       (void)InsertResult;
1173     }
1174   }
1175
1176   // Iterating over a DenseMap is safe here, because the only thing in the body
1177   // of the loop is inserting into another DenseMap (ComputedEdges).
1178   // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
1179   for (auto &ChainPair : TriangleChainMap) {
1180     TriangleChain &Chain = ChainPair.second;
1181     // Benchmarking has shown that due to branch correlation duplicating 2 or
1182     // more triangles is profitable, despite the calculations assuming
1183     // independence.
1184     if (Chain.count() < TriangleChainCount)
1185       continue;
1186     MachineBasicBlock *dst = Chain.Edges.back();
1187     Chain.Edges.pop_back();
1188     for (MachineBasicBlock *src : reverse(Chain.Edges)) {
1189       DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" <<
1190             getBlockName(dst) << " as pre-computed based on triangles.\n");
1191
1192       auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1193       assert(InsertResult.second && "Block seen twice.");
1194       (void)InsertResult;
1195
1196       dst = src;
1197     }
1198   }
1199 }
1200
1201 // When profile is not present, return the StaticLikelyProb.
1202 // When profile is available, we need to handle the triangle-shape CFG.
1203 static BranchProbability getLayoutSuccessorProbThreshold(
1204       const MachineBasicBlock *BB) {
1205   if (!BB->getParent()->getFunction()->getEntryCount())
1206     return BranchProbability(StaticLikelyProb, 100);
1207   if (BB->succ_size() == 2) {
1208     const MachineBasicBlock *Succ1 = *BB->succ_begin();
1209     const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
1210     if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1211       /* See case 1 below for the cost analysis. For BB->Succ to
1212        * be taken with smaller cost, the following needs to hold:
1213        *   Prob(BB->Succ) > 2 * Prob(BB->Pred)
1214        *   So the threshold T in the calculation below
1215        *   (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1216        *   So T / (1 - T) = 2, Yielding T = 2/3
1217        * Also adding user specified branch bias, we have
1218        *   T = (2/3)*(ProfileLikelyProb/50)
1219        *     = (2*ProfileLikelyProb)/150)
1220        */
1221       return BranchProbability(2 * ProfileLikelyProb, 150);
1222     }
1223   }
1224   return BranchProbability(ProfileLikelyProb, 100);
1225 }
1226
1227 /// Checks to see if the layout candidate block \p Succ has a better layout
1228 /// predecessor than \c BB. If yes, returns true.
1229 /// \p SuccProb: The probability adjusted for only remaining blocks.
1230 ///   Only used for logging
1231 /// \p RealSuccProb: The un-adjusted probability.
1232 /// \p Chain: The chain that BB belongs to and Succ is being considered for.
1233 /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1234 ///    considered
1235 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1236     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1237     const BlockChain &SuccChain, BranchProbability SuccProb,
1238     BranchProbability RealSuccProb, const BlockChain &Chain,
1239     const BlockFilterSet *BlockFilter) {
1240
1241   // There isn't a better layout when there are no unscheduled predecessors.
1242   if (SuccChain.UnscheduledPredecessors == 0)
1243     return false;
1244
1245   // There are two basic scenarios here:
1246   // -------------------------------------
1247   // Case 1: triangular shape CFG (if-then):
1248   //     BB
1249   //     | \
1250   //     |  \
1251   //     |   Pred
1252   //     |   /
1253   //     Succ
1254   // In this case, we are evaluating whether to select edge -> Succ, e.g.
1255   // set Succ as the layout successor of BB. Picking Succ as BB's
1256   // successor breaks the CFG constraints (FIXME: define these constraints).
1257   // With this layout, Pred BB
1258   // is forced to be outlined, so the overall cost will be cost of the
1259   // branch taken from BB to Pred, plus the cost of back taken branch
1260   // from Pred to Succ, as well as the additional cost associated
1261   // with the needed unconditional jump instruction from Pred To Succ.
1262
1263   // The cost of the topological order layout is the taken branch cost
1264   // from BB to Succ, so to make BB->Succ a viable candidate, the following
1265   // must hold:
1266   //     2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1267   //      < freq(BB->Succ) *  taken_branch_cost.
1268   // Ignoring unconditional jump cost, we get
1269   //    freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1270   //    prob(BB->Succ) > 2 * prob(BB->Pred)
1271   //
1272   // When real profile data is available, we can precisely compute the
1273   // probability threshold that is needed for edge BB->Succ to be considered.
1274   // Without profile data, the heuristic requires the branch bias to be
1275   // a lot larger to make sure the signal is very strong (e.g. 80% default).
1276   // -----------------------------------------------------------------
1277   // Case 2: diamond like CFG (if-then-else):
1278   //     S
1279   //    / \
1280   //   |   \
1281   //  BB    Pred
1282   //   \    /
1283   //    Succ
1284   //    ..
1285   //
1286   // The current block is BB and edge BB->Succ is now being evaluated.
1287   // Note that edge S->BB was previously already selected because
1288   // prob(S->BB) > prob(S->Pred).
1289   // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1290   // choose Pred, we will have a topological ordering as shown on the left
1291   // in the picture below. If we choose Succ, we have the solution as shown
1292   // on the right:
1293   //
1294   //   topo-order:
1295   //
1296   //       S-----                             ---S
1297   //       |    |                             |  |
1298   //    ---BB   |                             |  BB
1299   //    |       |                             |  |
1300   //    |  pred--                             |  Succ--
1301   //    |  |                                  |       |
1302   //    ---succ                               ---pred--
1303   //
1304   // cost = freq(S->Pred) + freq(BB->Succ)    cost = 2 * freq (S->Pred)
1305   //      = freq(S->Pred) + freq(S->BB)
1306   //
1307   // If we have profile data (i.e, branch probabilities can be trusted), the
1308   // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1309   // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1310   // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1311   // means the cost of topological order is greater.
1312   // When profile data is not available, however, we need to be more
1313   // conservative. If the branch prediction is wrong, breaking the topo-order
1314   // will actually yield a layout with large cost. For this reason, we need
1315   // strong biased branch at block S with Prob(S->BB) in order to select
1316   // BB->Succ. This is equivalent to looking the CFG backward with backward
1317   // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1318   // profile data).
1319   // --------------------------------------------------------------------------
1320   // Case 3: forked diamond
1321   //       S
1322   //      / \
1323   //     /   \
1324   //   BB    Pred
1325   //   | \   / |
1326   //   |  \ /  |
1327   //   |   X   |
1328   //   |  / \  |
1329   //   | /   \ |
1330   //   S1     S2
1331   //
1332   // The current block is BB and edge BB->S1 is now being evaluated.
1333   // As above S->BB was already selected because
1334   // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1335   //
1336   // topo-order:
1337   //
1338   //     S-------|                     ---S
1339   //     |       |                     |  |
1340   //  ---BB      |                     |  BB
1341   //  |          |                     |  |
1342   //  |  Pred----|                     |  S1----
1343   //  |  |                             |       |
1344   //  --(S1 or S2)                     ---Pred--
1345   //                                        |
1346   //                                       S2
1347   //
1348   // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1349   //    + min(freq(Pred->S1), freq(Pred->S2))
1350   // Non-topo-order cost:
1351   // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1352   // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1353   // is 0. Then the non topo layout is better when
1354   // freq(S->Pred) < freq(BB->S1).
1355   // This is exactly what is checked below.
1356   // Note there are other shapes that apply (Pred may not be a single block,
1357   // but they all fit this general pattern.)
1358   BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
1359
1360   // Make sure that a hot successor doesn't have a globally more
1361   // important predecessor.
1362   BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1363   bool BadCFGConflict = false;
1364
1365   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1366     if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1367         (BlockFilter && !BlockFilter->count(Pred)) ||
1368         BlockToChain[Pred] == &Chain ||
1369         // This check is redundant except for look ahead. This function is
1370         // called for lookahead by isProfitableToTailDup when BB hasn't been
1371         // placed yet.
1372         (Pred == BB))
1373       continue;
1374     // Do backward checking.
1375     // For all cases above, we need a backward checking to filter out edges that
1376     // are not 'strongly' biased.
1377     // BB  Pred
1378     //  \ /
1379     //  Succ
1380     // We select edge BB->Succ if
1381     //      freq(BB->Succ) > freq(Succ) * HotProb
1382     //      i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1383     //      HotProb
1384     //      i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1385     // Case 1 is covered too, because the first equation reduces to:
1386     // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
1387     BlockFrequency PredEdgeFreq =
1388         MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1389     if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1390       BadCFGConflict = true;
1391       break;
1392     }
1393   }
1394
1395   if (BadCFGConflict) {
1396     DEBUG(dbgs() << "    Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb
1397                  << " (prob) (non-cold CFG conflict)\n");
1398     return true;
1399   }
1400
1401   return false;
1402 }
1403
1404 /// \brief Select the best successor for a block.
1405 ///
1406 /// This looks across all successors of a particular block and attempts to
1407 /// select the "best" one to be the layout successor. It only considers direct
1408 /// successors which also pass the block filter. It will attempt to avoid
1409 /// breaking CFG structure, but cave and break such structures in the case of
1410 /// very hot successor edges.
1411 ///
1412 /// \returns The best successor block found, or null if none are viable, along
1413 /// with a boolean indicating if tail duplication is necessary.
1414 MachineBlockPlacement::BlockAndTailDupResult
1415 MachineBlockPlacement::selectBestSuccessor(
1416     const MachineBasicBlock *BB, const BlockChain &Chain,
1417     const BlockFilterSet *BlockFilter) {
1418   const BranchProbability HotProb(StaticLikelyProb, 100);
1419
1420   BlockAndTailDupResult BestSucc = { nullptr, false };
1421   auto BestProb = BranchProbability::getZero();
1422
1423   SmallVector<MachineBasicBlock *, 4> Successors;
1424   auto AdjustedSumProb =
1425       collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1426
1427   DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n");
1428
1429   // if we already precomputed the best successor for BB, return that if still
1430   // applicable.
1431   auto FoundEdge = ComputedEdges.find(BB);
1432   if (FoundEdge != ComputedEdges.end()) {
1433     MachineBasicBlock *Succ = FoundEdge->second.BB;
1434     ComputedEdges.erase(FoundEdge);
1435     BlockChain *SuccChain = BlockToChain[Succ];
1436     if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
1437         SuccChain != &Chain && Succ == *SuccChain->begin())
1438       return FoundEdge->second;
1439   }
1440
1441   // if BB is part of a trellis, Use the trellis to determine the optimal
1442   // fallthrough edges
1443   if (isTrellis(BB, Successors, Chain, BlockFilter))
1444     return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1445                                    BlockFilter);
1446
1447   // For blocks with CFG violations, we may be able to lay them out anyway with
1448   // tail-duplication. We keep this vector so we can perform the probability
1449   // calculations the minimum number of times.
1450   SmallVector<std::tuple<BranchProbability, MachineBasicBlock *>, 4>
1451       DupCandidates;
1452   for (MachineBasicBlock *Succ : Successors) {
1453     auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1454     BranchProbability SuccProb =
1455         getAdjustedProbability(RealSuccProb, AdjustedSumProb);
1456
1457     BlockChain &SuccChain = *BlockToChain[Succ];
1458     // Skip the edge \c BB->Succ if block \c Succ has a better layout
1459     // predecessor that yields lower global cost.
1460     if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1461                                    Chain, BlockFilter)) {
1462       // If tail duplication would make Succ profitable, place it.
1463       if (TailDupPlacement && shouldTailDuplicate(Succ))
1464         DupCandidates.push_back(std::make_tuple(SuccProb, Succ));
1465       continue;
1466     }
1467
1468     DEBUG(
1469         dbgs() << "    Candidate: " << getBlockName(Succ) << ", probability: "
1470                << SuccProb
1471                << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1472                << "\n");
1473
1474     if (BestSucc.BB && BestProb >= SuccProb) {
1475       DEBUG(dbgs() << "    Not the best candidate, continuing\n");
1476       continue;
1477     }
1478
1479     DEBUG(dbgs() << "    Setting it as best candidate\n");
1480     BestSucc.BB = Succ;
1481     BestProb = SuccProb;
1482   }
1483   // Handle the tail duplication candidates in order of decreasing probability.
1484   // Stop at the first one that is profitable. Also stop if they are less
1485   // profitable than BestSucc. Position is important because we preserve it and
1486   // prefer first best match. Here we aren't comparing in order, so we capture
1487   // the position instead.
1488   if (DupCandidates.size() != 0) {
1489     auto cmp =
1490         [](const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1491            const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1492           return std::get<0>(a) > std::get<0>(b);
1493         };
1494     std::stable_sort(DupCandidates.begin(), DupCandidates.end(), cmp);
1495   }
1496   for(auto &Tup : DupCandidates) {
1497     BranchProbability DupProb;
1498     MachineBasicBlock *Succ;
1499     std::tie(DupProb, Succ) = Tup;
1500     if (DupProb < BestProb)
1501       break;
1502     if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1503         && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1504       DEBUG(
1505           dbgs() << "    Candidate: " << getBlockName(Succ) << ", probability: "
1506                  << DupProb
1507                  << " (Tail Duplicate)\n");
1508       BestSucc.BB = Succ;
1509       BestSucc.ShouldTailDup = true;
1510       break;
1511     }
1512   }
1513
1514   if (BestSucc.BB)
1515     DEBUG(dbgs() << "    Selected: " << getBlockName(BestSucc.BB) << "\n");
1516
1517   return BestSucc;
1518 }
1519
1520 /// \brief Select the best block from a worklist.
1521 ///
1522 /// This looks through the provided worklist as a list of candidate basic
1523 /// blocks and select the most profitable one to place. The definition of
1524 /// profitable only really makes sense in the context of a loop. This returns
1525 /// the most frequently visited block in the worklist, which in the case of
1526 /// a loop, is the one most desirable to be physically close to the rest of the
1527 /// loop body in order to improve i-cache behavior.
1528 ///
1529 /// \returns The best block found, or null if none are viable.
1530 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
1531     const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1532   // Once we need to walk the worklist looking for a candidate, cleanup the
1533   // worklist of already placed entries.
1534   // FIXME: If this shows up on profiles, it could be folded (at the cost of
1535   // some code complexity) into the loop below.
1536   WorkList.erase(remove_if(WorkList,
1537                            [&](MachineBasicBlock *BB) {
1538                              return BlockToChain.lookup(BB) == &Chain;
1539                            }),
1540                  WorkList.end());
1541
1542   if (WorkList.empty())
1543     return nullptr;
1544
1545   bool IsEHPad = WorkList[0]->isEHPad();
1546
1547   MachineBasicBlock *BestBlock = nullptr;
1548   BlockFrequency BestFreq;
1549   for (MachineBasicBlock *MBB : WorkList) {
1550     assert(MBB->isEHPad() == IsEHPad);
1551
1552     BlockChain &SuccChain = *BlockToChain[MBB];
1553     if (&SuccChain == &Chain)
1554       continue;
1555
1556     assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block");
1557
1558     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1559     DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> ";
1560           MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n");
1561
1562     // For ehpad, we layout the least probable first as to avoid jumping back
1563     // from least probable landingpads to more probable ones.
1564     //
1565     // FIXME: Using probability is probably (!) not the best way to achieve
1566     // this. We should probably have a more principled approach to layout
1567     // cleanup code.
1568     //
1569     // The goal is to get:
1570     //
1571     //                 +--------------------------+
1572     //                 |                          V
1573     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
1574     //
1575     // Rather than:
1576     //
1577     //                 +-------------------------------------+
1578     //                 V                                     |
1579     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
1580     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1581       continue;
1582
1583     BestBlock = MBB;
1584     BestFreq = CandidateFreq;
1585   }
1586
1587   return BestBlock;
1588 }
1589
1590 /// \brief Retrieve the first unplaced basic block.
1591 ///
1592 /// This routine is called when we are unable to use the CFG to walk through
1593 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1594 /// We walk through the function's blocks in order, starting from the
1595 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
1596 /// re-scanning the entire sequence on repeated calls to this routine.
1597 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1598     const BlockChain &PlacedChain,
1599     MachineFunction::iterator &PrevUnplacedBlockIt,
1600     const BlockFilterSet *BlockFilter) {
1601   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1602        ++I) {
1603     if (BlockFilter && !BlockFilter->count(&*I))
1604       continue;
1605     if (BlockToChain[&*I] != &PlacedChain) {
1606       PrevUnplacedBlockIt = I;
1607       // Now select the head of the chain to which the unplaced block belongs
1608       // as the block to place. This will force the entire chain to be placed,
1609       // and satisfies the requirements of merging chains.
1610       return *BlockToChain[&*I]->begin();
1611     }
1612   }
1613   return nullptr;
1614 }
1615
1616 void MachineBlockPlacement::fillWorkLists(
1617     const MachineBasicBlock *MBB,
1618     SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1619     const BlockFilterSet *BlockFilter = nullptr) {
1620   BlockChain &Chain = *BlockToChain[MBB];
1621   if (!UpdatedPreds.insert(&Chain).second)
1622     return;
1623
1624   assert(Chain.UnscheduledPredecessors == 0);
1625   for (MachineBasicBlock *ChainBB : Chain) {
1626     assert(BlockToChain[ChainBB] == &Chain);
1627     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1628       if (BlockFilter && !BlockFilter->count(Pred))
1629         continue;
1630       if (BlockToChain[Pred] == &Chain)
1631         continue;
1632       ++Chain.UnscheduledPredecessors;
1633     }
1634   }
1635
1636   if (Chain.UnscheduledPredecessors != 0)
1637     return;
1638
1639   MachineBasicBlock *BB = *Chain.begin();
1640   if (BB->isEHPad())
1641     EHPadWorkList.push_back(BB);
1642   else
1643     BlockWorkList.push_back(BB);
1644 }
1645
1646 void MachineBlockPlacement::buildChain(
1647     const MachineBasicBlock *HeadBB, BlockChain &Chain,
1648     BlockFilterSet *BlockFilter) {
1649   assert(HeadBB && "BB must not be null.\n");
1650   assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
1651   MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1652
1653   const MachineBasicBlock *LoopHeaderBB = HeadBB;
1654   markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1655   MachineBasicBlock *BB = *std::prev(Chain.end());
1656   for (;;) {
1657     assert(BB && "null block found at end of chain in loop.");
1658     assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1659     assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1660
1661
1662     // Look for the best viable successor if there is one to place immediately
1663     // after this block.
1664     auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1665     MachineBasicBlock* BestSucc = Result.BB;
1666     bool ShouldTailDup = Result.ShouldTailDup;
1667     if (TailDupPlacement)
1668       ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
1669
1670     // If an immediate successor isn't available, look for the best viable
1671     // block among those we've identified as not violating the loop's CFG at
1672     // this point. This won't be a fallthrough, but it will increase locality.
1673     if (!BestSucc)
1674       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1675     if (!BestSucc)
1676       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1677
1678     if (!BestSucc) {
1679       BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1680       if (!BestSucc)
1681         break;
1682
1683       DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1684                       "layout successor until the CFG reduces\n");
1685     }
1686
1687     // Placement may have changed tail duplication opportunities.
1688     // Check for that now.
1689     if (TailDupPlacement && BestSucc && ShouldTailDup) {
1690       // If the chosen successor was duplicated into all its predecessors,
1691       // don't bother laying it out, just go round the loop again with BB as
1692       // the chain end.
1693       if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1694                                        BlockFilter, PrevUnplacedBlockIt))
1695         continue;
1696     }
1697
1698     // Place this block, updating the datastructures to reflect its placement.
1699     BlockChain &SuccChain = *BlockToChain[BestSucc];
1700     // Zero out UnscheduledPredecessors for the successor we're about to merge in case
1701     // we selected a successor that didn't fit naturally into the CFG.
1702     SuccChain.UnscheduledPredecessors = 0;
1703     DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1704                  << getBlockName(BestSucc) << "\n");
1705     markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1706     Chain.merge(BestSucc, &SuccChain);
1707     BB = *std::prev(Chain.end());
1708   }
1709
1710   DEBUG(dbgs() << "Finished forming chain for header block "
1711                << getBlockName(*Chain.begin()) << "\n");
1712 }
1713
1714 /// \brief Find the best loop top block for layout.
1715 ///
1716 /// Look for a block which is strictly better than the loop header for laying
1717 /// out at the top of the loop. This looks for one and only one pattern:
1718 /// a latch block with no conditional exit. This block will cause a conditional
1719 /// jump around it or will be the bottom of the loop if we lay it out in place,
1720 /// but if it it doesn't end up at the bottom of the loop for any reason,
1721 /// rotation alone won't fix it. Because such a block will always result in an
1722 /// unconditional jump (for the backedge) rotating it in front of the loop
1723 /// header is always profitable.
1724 MachineBasicBlock *
1725 MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
1726                                        const BlockFilterSet &LoopBlockSet) {
1727   // Placing the latch block before the header may introduce an extra branch
1728   // that skips this block the first time the loop is executed, which we want
1729   // to avoid when optimising for size.
1730   // FIXME: in theory there is a case that does not introduce a new branch,
1731   // i.e. when the layout predecessor does not fallthrough to the loop header.
1732   // In practice this never happens though: there always seems to be a preheader
1733   // that can fallthrough and that is also placed before the header.
1734   if (F->getFunction()->optForSize())
1735     return L.getHeader();
1736
1737   // Check that the header hasn't been fused with a preheader block due to
1738   // crazy branches. If it has, we need to start with the header at the top to
1739   // prevent pulling the preheader into the loop body.
1740   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1741   if (!LoopBlockSet.count(*HeaderChain.begin()))
1742     return L.getHeader();
1743
1744   DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader())
1745                << "\n");
1746
1747   BlockFrequency BestPredFreq;
1748   MachineBasicBlock *BestPred = nullptr;
1749   for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) {
1750     if (!LoopBlockSet.count(Pred))
1751       continue;
1752     DEBUG(dbgs() << "    header pred: " << getBlockName(Pred) << ", has "
1753                  << Pred->succ_size() << " successors, ";
1754           MBFI->printBlockFreq(dbgs(), Pred) << " freq\n");
1755     if (Pred->succ_size() > 1)
1756       continue;
1757
1758     BlockFrequency PredFreq = MBFI->getBlockFreq(Pred);
1759     if (!BestPred || PredFreq > BestPredFreq ||
1760         (!(PredFreq < BestPredFreq) &&
1761          Pred->isLayoutSuccessor(L.getHeader()))) {
1762       BestPred = Pred;
1763       BestPredFreq = PredFreq;
1764     }
1765   }
1766
1767   // If no direct predecessor is fine, just use the loop header.
1768   if (!BestPred) {
1769     DEBUG(dbgs() << "    final top unchanged\n");
1770     return L.getHeader();
1771   }
1772
1773   // Walk backwards through any straight line of predecessors.
1774   while (BestPred->pred_size() == 1 &&
1775          (*BestPred->pred_begin())->succ_size() == 1 &&
1776          *BestPred->pred_begin() != L.getHeader())
1777     BestPred = *BestPred->pred_begin();
1778
1779   DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
1780   return BestPred;
1781 }
1782
1783 /// \brief Find the best loop exiting block for layout.
1784 ///
1785 /// This routine implements the logic to analyze the loop looking for the best
1786 /// block to layout at the top of the loop. Typically this is done to maximize
1787 /// fallthrough opportunities.
1788 MachineBasicBlock *
1789 MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
1790                                         const BlockFilterSet &LoopBlockSet) {
1791   // We don't want to layout the loop linearly in all cases. If the loop header
1792   // is just a normal basic block in the loop, we want to look for what block
1793   // within the loop is the best one to layout at the top. However, if the loop
1794   // header has be pre-merged into a chain due to predecessors not having
1795   // analyzable branches, *and* the predecessor it is merged with is *not* part
1796   // of the loop, rotating the header into the middle of the loop will create
1797   // a non-contiguous range of blocks which is Very Bad. So start with the
1798   // header and only rotate if safe.
1799   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
1800   if (!LoopBlockSet.count(*HeaderChain.begin()))
1801     return nullptr;
1802
1803   BlockFrequency BestExitEdgeFreq;
1804   unsigned BestExitLoopDepth = 0;
1805   MachineBasicBlock *ExitingBB = nullptr;
1806   // If there are exits to outer loops, loop rotation can severely limit
1807   // fallthrough opportunities unless it selects such an exit. Keep a set of
1808   // blocks where rotating to exit with that block will reach an outer loop.
1809   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
1810
1811   DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader())
1812                << "\n");
1813   for (MachineBasicBlock *MBB : L.getBlocks()) {
1814     BlockChain &Chain = *BlockToChain[MBB];
1815     // Ensure that this block is at the end of a chain; otherwise it could be
1816     // mid-way through an inner loop or a successor of an unanalyzable branch.
1817     if (MBB != *std::prev(Chain.end()))
1818       continue;
1819
1820     // Now walk the successors. We need to establish whether this has a viable
1821     // exiting successor and whether it has a viable non-exiting successor.
1822     // We store the old exiting state and restore it if a viable looping
1823     // successor isn't found.
1824     MachineBasicBlock *OldExitingBB = ExitingBB;
1825     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
1826     bool HasLoopingSucc = false;
1827     for (MachineBasicBlock *Succ : MBB->successors()) {
1828       if (Succ->isEHPad())
1829         continue;
1830       if (Succ == MBB)
1831         continue;
1832       BlockChain &SuccChain = *BlockToChain[Succ];
1833       // Don't split chains, either this chain or the successor's chain.
1834       if (&Chain == &SuccChain) {
1835         DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
1836                      << getBlockName(Succ) << " (chain conflict)\n");
1837         continue;
1838       }
1839
1840       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
1841       if (LoopBlockSet.count(Succ)) {
1842         DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
1843                      << getBlockName(Succ) << " (" << SuccProb << ")\n");
1844         HasLoopingSucc = true;
1845         continue;
1846       }
1847
1848       unsigned SuccLoopDepth = 0;
1849       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
1850         SuccLoopDepth = ExitLoop->getLoopDepth();
1851         if (ExitLoop->contains(&L))
1852           BlocksExitingToOuterLoop.insert(MBB);
1853       }
1854
1855       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1856       DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
1857                    << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (";
1858             MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n");
1859       // Note that we bias this toward an existing layout successor to retain
1860       // incoming order in the absence of better information. The exit must have
1861       // a frequency higher than the current exit before we consider breaking
1862       // the layout.
1863       BranchProbability Bias(100 - ExitBlockBias, 100);
1864       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
1865           ExitEdgeFreq > BestExitEdgeFreq ||
1866           (MBB->isLayoutSuccessor(Succ) &&
1867            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
1868         BestExitEdgeFreq = ExitEdgeFreq;
1869         ExitingBB = MBB;
1870       }
1871     }
1872
1873     if (!HasLoopingSucc) {
1874       // Restore the old exiting state, no viable looping successor was found.
1875       ExitingBB = OldExitingBB;
1876       BestExitEdgeFreq = OldBestExitEdgeFreq;
1877     }
1878   }
1879   // Without a candidate exiting block or with only a single block in the
1880   // loop, just use the loop header to layout the loop.
1881   if (!ExitingBB) {
1882     DEBUG(dbgs() << "    No other candidate exit blocks, using loop header\n");
1883     return nullptr;
1884   }
1885   if (L.getNumBlocks() == 1) {
1886     DEBUG(dbgs() << "    Loop has 1 block, using loop header as exit\n");
1887     return nullptr;
1888   }
1889
1890   // Also, if we have exit blocks which lead to outer loops but didn't select
1891   // one of them as the exiting block we are rotating toward, disable loop
1892   // rotation altogether.
1893   if (!BlocksExitingToOuterLoop.empty() &&
1894       !BlocksExitingToOuterLoop.count(ExitingBB))
1895     return nullptr;
1896
1897   DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB) << "\n");
1898   return ExitingBB;
1899 }
1900
1901 /// \brief Attempt to rotate an exiting block to the bottom of the loop.
1902 ///
1903 /// Once we have built a chain, try to rotate it to line up the hot exit block
1904 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
1905 /// branches. For example, if the loop has fallthrough into its header and out
1906 /// of its bottom already, don't rotate it.
1907 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1908                                        const MachineBasicBlock *ExitingBB,
1909                                        const BlockFilterSet &LoopBlockSet) {
1910   if (!ExitingBB)
1911     return;
1912
1913   MachineBasicBlock *Top = *LoopChain.begin();
1914   bool ViableTopFallthrough = false;
1915   for (MachineBasicBlock *Pred : Top->predecessors()) {
1916     BlockChain *PredChain = BlockToChain[Pred];
1917     if (!LoopBlockSet.count(Pred) &&
1918         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1919       ViableTopFallthrough = true;
1920       break;
1921     }
1922   }
1923
1924   // If the header has viable fallthrough, check whether the current loop
1925   // bottom is a viable exiting block. If so, bail out as rotating will
1926   // introduce an unnecessary branch.
1927   if (ViableTopFallthrough) {
1928     MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
1929     for (MachineBasicBlock *Succ : Bottom->successors()) {
1930       BlockChain *SuccChain = BlockToChain[Succ];
1931       if (!LoopBlockSet.count(Succ) &&
1932           (!SuccChain || Succ == *SuccChain->begin()))
1933         return;
1934     }
1935   }
1936
1937   BlockChain::iterator ExitIt = find(LoopChain, ExitingBB);
1938   if (ExitIt == LoopChain.end())
1939     return;
1940
1941   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
1942 }
1943
1944 /// \brief Attempt to rotate a loop based on profile data to reduce branch cost.
1945 ///
1946 /// With profile data, we can determine the cost in terms of missed fall through
1947 /// opportunities when rotating a loop chain and select the best rotation.
1948 /// Basically, there are three kinds of cost to consider for each rotation:
1949 ///    1. The possibly missed fall through edge (if it exists) from BB out of
1950 ///    the loop to the loop header.
1951 ///    2. The possibly missed fall through edges (if they exist) from the loop
1952 ///    exits to BB out of the loop.
1953 ///    3. The missed fall through edge (if it exists) from the last BB to the
1954 ///    first BB in the loop chain.
1955 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
1956 ///  We select the best rotation with the smallest cost.
1957 void MachineBlockPlacement::rotateLoopWithProfile(
1958     BlockChain &LoopChain, const MachineLoop &L,
1959     const BlockFilterSet &LoopBlockSet) {
1960   auto HeaderBB = L.getHeader();
1961   auto HeaderIter = find(LoopChain, HeaderBB);
1962   auto RotationPos = LoopChain.end();
1963
1964   BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency();
1965
1966   // A utility lambda that scales up a block frequency by dividing it by a
1967   // branch probability which is the reciprocal of the scale.
1968   auto ScaleBlockFrequency = [](BlockFrequency Freq,
1969                                 unsigned Scale) -> BlockFrequency {
1970     if (Scale == 0)
1971       return 0;
1972     // Use operator / between BlockFrequency and BranchProbability to implement
1973     // saturating multiplication.
1974     return Freq / BranchProbability(1, Scale);
1975   };
1976
1977   // Compute the cost of the missed fall-through edge to the loop header if the
1978   // chain head is not the loop header. As we only consider natural loops with
1979   // single header, this computation can be done only once.
1980   BlockFrequency HeaderFallThroughCost(0);
1981   for (auto *Pred : HeaderBB->predecessors()) {
1982     BlockChain *PredChain = BlockToChain[Pred];
1983     if (!LoopBlockSet.count(Pred) &&
1984         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1985       auto EdgeFreq =
1986           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
1987       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
1988       // If the predecessor has only an unconditional jump to the header, we
1989       // need to consider the cost of this jump.
1990       if (Pred->succ_size() == 1)
1991         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
1992       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
1993     }
1994   }
1995
1996   // Here we collect all exit blocks in the loop, and for each exit we find out
1997   // its hottest exit edge. For each loop rotation, we define the loop exit cost
1998   // as the sum of frequencies of exit edges we collect here, excluding the exit
1999   // edge from the tail of the loop chain.
2000   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2001   for (auto BB : LoopChain) {
2002     auto LargestExitEdgeProb = BranchProbability::getZero();
2003     for (auto *Succ : BB->successors()) {
2004       BlockChain *SuccChain = BlockToChain[Succ];
2005       if (!LoopBlockSet.count(Succ) &&
2006           (!SuccChain || Succ == *SuccChain->begin())) {
2007         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2008         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2009       }
2010     }
2011     if (LargestExitEdgeProb > BranchProbability::getZero()) {
2012       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2013       ExitsWithFreq.emplace_back(BB, ExitFreq);
2014     }
2015   }
2016
2017   // In this loop we iterate every block in the loop chain and calculate the
2018   // cost assuming the block is the head of the loop chain. When the loop ends,
2019   // we should have found the best candidate as the loop chain's head.
2020   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2021             EndIter = LoopChain.end();
2022        Iter != EndIter; Iter++, TailIter++) {
2023     // TailIter is used to track the tail of the loop chain if the block we are
2024     // checking (pointed by Iter) is the head of the chain.
2025     if (TailIter == LoopChain.end())
2026       TailIter = LoopChain.begin();
2027
2028     auto TailBB = *TailIter;
2029
2030     // Calculate the cost by putting this BB to the top.
2031     BlockFrequency Cost = 0;
2032
2033     // If the current BB is the loop header, we need to take into account the
2034     // cost of the missed fall through edge from outside of the loop to the
2035     // header.
2036     if (Iter != HeaderIter)
2037       Cost += HeaderFallThroughCost;
2038
2039     // Collect the loop exit cost by summing up frequencies of all exit edges
2040     // except the one from the chain tail.
2041     for (auto &ExitWithFreq : ExitsWithFreq)
2042       if (TailBB != ExitWithFreq.first)
2043         Cost += ExitWithFreq.second;
2044
2045     // The cost of breaking the once fall-through edge from the tail to the top
2046     // of the loop chain. Here we need to consider three cases:
2047     // 1. If the tail node has only one successor, then we will get an
2048     //    additional jmp instruction. So the cost here is (MisfetchCost +
2049     //    JumpInstCost) * tail node frequency.
2050     // 2. If the tail node has two successors, then we may still get an
2051     //    additional jmp instruction if the layout successor after the loop
2052     //    chain is not its CFG successor. Note that the more frequently executed
2053     //    jmp instruction will be put ahead of the other one. Assume the
2054     //    frequency of those two branches are x and y, where x is the frequency
2055     //    of the edge to the chain head, then the cost will be
2056     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2057     // 3. If the tail node has more than two successors (this rarely happens),
2058     //    we won't consider any additional cost.
2059     if (TailBB->isSuccessor(*Iter)) {
2060       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2061       if (TailBB->succ_size() == 1)
2062         Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2063                                     MisfetchCost + JumpInstCost);
2064       else if (TailBB->succ_size() == 2) {
2065         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2066         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2067         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2068                                   ? TailBBFreq * TailToHeadProb.getCompl()
2069                                   : TailToHeadFreq;
2070         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2071                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2072       }
2073     }
2074
2075     DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter)
2076                  << " to the top: " << Cost.getFrequency() << "\n");
2077
2078     if (Cost < SmallestRotationCost) {
2079       SmallestRotationCost = Cost;
2080       RotationPos = Iter;
2081     }
2082   }
2083
2084   if (RotationPos != LoopChain.end()) {
2085     DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2086                  << " to the top\n");
2087     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2088   }
2089 }
2090
2091 /// \brief Collect blocks in the given loop that are to be placed.
2092 ///
2093 /// When profile data is available, exclude cold blocks from the returned set;
2094 /// otherwise, collect all blocks in the loop.
2095 MachineBlockPlacement::BlockFilterSet
2096 MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
2097   BlockFilterSet LoopBlockSet;
2098
2099   // Filter cold blocks off from LoopBlockSet when profile data is available.
2100   // Collect the sum of frequencies of incoming edges to the loop header from
2101   // outside. If we treat the loop as a super block, this is the frequency of
2102   // the loop. Then for each block in the loop, we calculate the ratio between
2103   // its frequency and the frequency of the loop block. When it is too small,
2104   // don't add it to the loop chain. If there are outer loops, then this block
2105   // will be merged into the first outer loop chain for which this block is not
2106   // cold anymore. This needs precise profile data and we only do this when
2107   // profile data is available.
2108   if (F->getFunction()->getEntryCount()) {
2109     BlockFrequency LoopFreq(0);
2110     for (auto LoopPred : L.getHeader()->predecessors())
2111       if (!L.contains(LoopPred))
2112         LoopFreq += MBFI->getBlockFreq(LoopPred) *
2113                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
2114
2115     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2116       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2117       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2118         continue;
2119       LoopBlockSet.insert(LoopBB);
2120     }
2121   } else
2122     LoopBlockSet.insert(L.block_begin(), L.block_end());
2123
2124   return LoopBlockSet;
2125 }
2126
2127 /// \brief Forms basic block chains from the natural loop structures.
2128 ///
2129 /// These chains are designed to preserve the existing *structure* of the code
2130 /// as much as possible. We can then stitch the chains together in a way which
2131 /// both preserves the topological structure and minimizes taken conditional
2132 /// branches.
2133 void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
2134   // First recurse through any nested loops, building chains for those inner
2135   // loops.
2136   for (const MachineLoop *InnerLoop : L)
2137     buildLoopChains(*InnerLoop);
2138
2139   assert(BlockWorkList.empty());
2140   assert(EHPadWorkList.empty());
2141   BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2142
2143   // Check if we have profile data for this function. If yes, we will rotate
2144   // this loop by modeling costs more precisely which requires the profile data
2145   // for better layout.
2146   bool RotateLoopWithProfile =
2147       ForcePreciseRotationCost ||
2148       (PreciseRotationCost && F->getFunction()->getEntryCount());
2149
2150   // First check to see if there is an obviously preferable top block for the
2151   // loop. This will default to the header, but may end up as one of the
2152   // predecessors to the header if there is one which will result in strictly
2153   // fewer branches in the loop body.
2154   // When we use profile data to rotate the loop, this is unnecessary.
2155   MachineBasicBlock *LoopTop =
2156       RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
2157
2158   // If we selected just the header for the loop top, look for a potentially
2159   // profitable exit block in the event that rotating the loop can eliminate
2160   // branches by placing an exit edge at the bottom.
2161   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2162     PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
2163
2164   BlockChain &LoopChain = *BlockToChain[LoopTop];
2165
2166   // FIXME: This is a really lame way of walking the chains in the loop: we
2167   // walk the blocks, and use a set to prevent visiting a particular chain
2168   // twice.
2169   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2170   assert(LoopChain.UnscheduledPredecessors == 0);
2171   UpdatedPreds.insert(&LoopChain);
2172
2173   for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2174     fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2175
2176   buildChain(LoopTop, LoopChain, &LoopBlockSet);
2177
2178   if (RotateLoopWithProfile)
2179     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2180   else
2181     rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
2182
2183   DEBUG({
2184     // Crash at the end so we get all of the debugging output first.
2185     bool BadLoop = false;
2186     if (LoopChain.UnscheduledPredecessors) {
2187       BadLoop = true;
2188       dbgs() << "Loop chain contains a block without its preds placed!\n"
2189              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2190              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
2191     }
2192     for (MachineBasicBlock *ChainBB : LoopChain) {
2193       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
2194       if (!LoopBlockSet.remove(ChainBB)) {
2195         // We don't mark the loop as bad here because there are real situations
2196         // where this can occur. For example, with an unanalyzable fallthrough
2197         // from a loop block to a non-loop block or vice versa.
2198         dbgs() << "Loop chain contains a block not contained by the loop!\n"
2199                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2200                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2201                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2202       }
2203     }
2204
2205     if (!LoopBlockSet.empty()) {
2206       BadLoop = true;
2207       for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2208         dbgs() << "Loop contains blocks never placed into a chain!\n"
2209                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2210                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2211                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
2212     }
2213     assert(!BadLoop && "Detected problems with the placement of this loop.");
2214   });
2215
2216   BlockWorkList.clear();
2217   EHPadWorkList.clear();
2218 }
2219
2220 void MachineBlockPlacement::buildCFGChains() {
2221   // Ensure that every BB in the function has an associated chain to simplify
2222   // the assumptions of the remaining algorithm.
2223   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
2224   for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2225        ++FI) {
2226     MachineBasicBlock *BB = &*FI;
2227     BlockChain *Chain =
2228         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2229     // Also, merge any blocks which we cannot reason about and must preserve
2230     // the exact fallthrough behavior for.
2231     for (;;) {
2232       Cond.clear();
2233       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2234       if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2235         break;
2236
2237       MachineFunction::iterator NextFI = std::next(FI);
2238       MachineBasicBlock *NextBB = &*NextFI;
2239       // Ensure that the layout successor is a viable block, as we know that
2240       // fallthrough is a possibility.
2241       assert(NextFI != FE && "Can't fallthrough past the last block.");
2242       DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2243                    << getBlockName(BB) << " -> " << getBlockName(NextBB)
2244                    << "\n");
2245       Chain->merge(NextBB, nullptr);
2246 #ifndef NDEBUG
2247       BlocksWithUnanalyzableExits.insert(&*BB);
2248 #endif
2249       FI = NextFI;
2250       BB = NextBB;
2251     }
2252   }
2253
2254   // Build any loop-based chains.
2255   PreferredLoopExit = nullptr;
2256   for (MachineLoop *L : *MLI)
2257     buildLoopChains(*L);
2258
2259   assert(BlockWorkList.empty());
2260   assert(EHPadWorkList.empty());
2261
2262   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2263   for (MachineBasicBlock &MBB : *F)
2264     fillWorkLists(&MBB, UpdatedPreds);
2265
2266   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2267   buildChain(&F->front(), FunctionChain);
2268
2269 #ifndef NDEBUG
2270   typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType;
2271 #endif
2272   DEBUG({
2273     // Crash at the end so we get all of the debugging output first.
2274     bool BadFunc = false;
2275     FunctionBlockSetType FunctionBlockSet;
2276     for (MachineBasicBlock &MBB : *F)
2277       FunctionBlockSet.insert(&MBB);
2278
2279     for (MachineBasicBlock *ChainBB : FunctionChain)
2280       if (!FunctionBlockSet.erase(ChainBB)) {
2281         BadFunc = true;
2282         dbgs() << "Function chain contains a block not in the function!\n"
2283                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2284       }
2285
2286     if (!FunctionBlockSet.empty()) {
2287       BadFunc = true;
2288       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2289         dbgs() << "Function contains blocks never placed into a chain!\n"
2290                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
2291     }
2292     assert(!BadFunc && "Detected problems with the block placement.");
2293   });
2294
2295   // Splice the blocks into place.
2296   MachineFunction::iterator InsertPos = F->begin();
2297   DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n");
2298   for (MachineBasicBlock *ChainBB : FunctionChain) {
2299     DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2300                                                        : "          ... ")
2301                  << getBlockName(ChainBB) << "\n");
2302     if (InsertPos != MachineFunction::iterator(ChainBB))
2303       F->splice(InsertPos, ChainBB);
2304     else
2305       ++InsertPos;
2306
2307     // Update the terminator of the previous block.
2308     if (ChainBB == *FunctionChain.begin())
2309       continue;
2310     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
2311
2312     // FIXME: It would be awesome of updateTerminator would just return rather
2313     // than assert when the branch cannot be analyzed in order to remove this
2314     // boiler plate.
2315     Cond.clear();
2316     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2317
2318 #ifndef NDEBUG
2319     if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2320       // Given the exact block placement we chose, we may actually not _need_ to
2321       // be able to edit PrevBB's terminator sequence, but not being _able_ to
2322       // do that at this point is a bug.
2323       assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2324               !PrevBB->canFallThrough()) &&
2325              "Unexpected block with un-analyzable fallthrough!");
2326       Cond.clear();
2327       TBB = FBB = nullptr;
2328     }
2329 #endif
2330
2331     // The "PrevBB" is not yet updated to reflect current code layout, so,
2332     //   o. it may fall-through to a block without explicit "goto" instruction
2333     //      before layout, and no longer fall-through it after layout; or
2334     //   o. just opposite.
2335     //
2336     // analyzeBranch() may return erroneous value for FBB when these two
2337     // situations take place. For the first scenario FBB is mistakenly set NULL;
2338     // for the 2nd scenario, the FBB, which is expected to be NULL, is
2339     // mistakenly pointing to "*BI".
2340     // Thus, if the future change needs to use FBB before the layout is set, it
2341     // has to correct FBB first by using the code similar to the following:
2342     //
2343     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2344     //   PrevBB->updateTerminator();
2345     //   Cond.clear();
2346     //   TBB = FBB = nullptr;
2347     //   if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2348     //     // FIXME: This should never take place.
2349     //     TBB = FBB = nullptr;
2350     //   }
2351     // }
2352     if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond))
2353       PrevBB->updateTerminator();
2354   }
2355
2356   // Fixup the last block.
2357   Cond.clear();
2358   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2359   if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond))
2360     F->back().updateTerminator();
2361
2362   BlockWorkList.clear();
2363   EHPadWorkList.clear();
2364 }
2365
2366 void MachineBlockPlacement::optimizeBranches() {
2367   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2368   SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch.
2369
2370   // Now that all the basic blocks in the chain have the proper layout,
2371   // make a final call to AnalyzeBranch with AllowModify set.
2372   // Indeed, the target may be able to optimize the branches in a way we
2373   // cannot because all branches may not be analyzable.
2374   // E.g., the target may be able to remove an unconditional branch to
2375   // a fallthrough when it occurs after predicated terminators.
2376   for (MachineBasicBlock *ChainBB : FunctionChain) {
2377     Cond.clear();
2378     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch.
2379     if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
2380       // If PrevBB has a two-way branch, try to re-order the branches
2381       // such that we branch to the successor with higher probability first.
2382       if (TBB && !Cond.empty() && FBB &&
2383           MBPI->getEdgeProbability(ChainBB, FBB) >
2384               MBPI->getEdgeProbability(ChainBB, TBB) &&
2385           !TII->reverseBranchCondition(Cond)) {
2386         DEBUG(dbgs() << "Reverse order of the two branches: "
2387                      << getBlockName(ChainBB) << "\n");
2388         DEBUG(dbgs() << "    Edge probability: "
2389                      << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2390                      << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2391         DebugLoc dl; // FIXME: this is nowhere
2392         TII->removeBranch(*ChainBB);
2393         TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
2394         ChainBB->updateTerminator();
2395       }
2396     }
2397   }
2398 }
2399
2400 void MachineBlockPlacement::alignBlocks() {
2401   // Walk through the backedges of the function now that we have fully laid out
2402   // the basic blocks and align the destination of each backedge. We don't rely
2403   // exclusively on the loop info here so that we can align backedges in
2404   // unnatural CFGs and backedges that were introduced purely because of the
2405   // loop rotations done during this layout pass.
2406   if (F->getFunction()->optForSize())
2407     return;
2408   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2409   if (FunctionChain.begin() == FunctionChain.end())
2410     return; // Empty chain.
2411
2412   const BranchProbability ColdProb(1, 5); // 20%
2413   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
2414   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
2415   for (MachineBasicBlock *ChainBB : FunctionChain) {
2416     if (ChainBB == *FunctionChain.begin())
2417       continue;
2418
2419     // Don't align non-looping basic blocks. These are unlikely to execute
2420     // enough times to matter in practice. Note that we'll still handle
2421     // unnatural CFGs inside of a natural outer loop (the common case) and
2422     // rotated loops.
2423     MachineLoop *L = MLI->getLoopFor(ChainBB);
2424     if (!L)
2425       continue;
2426
2427     unsigned Align = TLI->getPrefLoopAlignment(L);
2428     if (!Align)
2429       continue; // Don't care about loop alignment.
2430
2431     // If the block is cold relative to the function entry don't waste space
2432     // aligning it.
2433     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
2434     if (Freq < WeightedEntryFreq)
2435       continue;
2436
2437     // If the block is cold relative to its loop header, don't align it
2438     // regardless of what edges into the block exist.
2439     MachineBasicBlock *LoopHeader = L->getHeader();
2440     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
2441     if (Freq < (LoopHeaderFreq * ColdProb))
2442       continue;
2443
2444     // Check for the existence of a non-layout predecessor which would benefit
2445     // from aligning this block.
2446     MachineBasicBlock *LayoutPred =
2447         &*std::prev(MachineFunction::iterator(ChainBB));
2448
2449     // Force alignment if all the predecessors are jumps. We already checked
2450     // that the block isn't cold above.
2451     if (!LayoutPred->isSuccessor(ChainBB)) {
2452       ChainBB->setAlignment(Align);
2453       continue;
2454     }
2455
2456     // Align this block if the layout predecessor's edge into this block is
2457     // cold relative to the block. When this is true, other predecessors make up
2458     // all of the hot entries into the block and thus alignment is likely to be
2459     // important.
2460     BranchProbability LayoutProb =
2461         MBPI->getEdgeProbability(LayoutPred, ChainBB);
2462     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2463     if (LayoutEdgeFreq <= (Freq * ColdProb))
2464       ChainBB->setAlignment(Align);
2465   }
2466 }
2467
2468 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
2469 /// it was duplicated into its chain predecessor and removed.
2470 /// \p BB    - Basic block that may be duplicated.
2471 ///
2472 /// \p LPred - Chosen layout predecessor of \p BB.
2473 ///            Updated to be the chain end if LPred is removed.
2474 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2475 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2476 ///                  Used to identify which blocks to update predecessor
2477 ///                  counts.
2478 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2479 ///                          chosen in the given order due to unnatural CFG
2480 ///                          only needed if \p BB is removed and
2481 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
2482 /// @return true if \p BB was removed.
2483 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2484     MachineBasicBlock *BB, MachineBasicBlock *&LPred,
2485     const MachineBasicBlock *LoopHeaderBB,
2486     BlockChain &Chain, BlockFilterSet *BlockFilter,
2487     MachineFunction::iterator &PrevUnplacedBlockIt) {
2488   bool Removed, DuplicatedToLPred;
2489   bool DuplicatedToOriginalLPred;
2490   Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2491                                     PrevUnplacedBlockIt,
2492                                     DuplicatedToLPred);
2493   if (!Removed)
2494     return false;
2495   DuplicatedToOriginalLPred = DuplicatedToLPred;
2496   // Iteratively try to duplicate again. It can happen that a block that is
2497   // duplicated into is still small enough to be duplicated again.
2498   // No need to call markBlockSuccessors in this case, as the blocks being
2499   // duplicated from here on are already scheduled.
2500   // Note that DuplicatedToLPred always implies Removed.
2501   while (DuplicatedToLPred) {
2502     assert (Removed && "Block must have been removed to be duplicated into its "
2503             "layout predecessor.");
2504     MachineBasicBlock *DupBB, *DupPred;
2505     // The removal callback causes Chain.end() to be updated when a block is
2506     // removed. On the first pass through the loop, the chain end should be the
2507     // same as it was on function entry. On subsequent passes, because we are
2508     // duplicating the block at the end of the chain, if it is removed the
2509     // chain will have shrunk by one block.
2510     BlockChain::iterator ChainEnd = Chain.end();
2511     DupBB = *(--ChainEnd);
2512     // Now try to duplicate again.
2513     if (ChainEnd == Chain.begin())
2514       break;
2515     DupPred = *std::prev(ChainEnd);
2516     Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2517                                       PrevUnplacedBlockIt,
2518                                       DuplicatedToLPred);
2519   }
2520   // If BB was duplicated into LPred, it is now scheduled. But because it was
2521   // removed, markChainSuccessors won't be called for its chain. Instead we
2522   // call markBlockSuccessors for LPred to achieve the same effect. This must go
2523   // at the end because repeating the tail duplication can increase the number
2524   // of unscheduled predecessors.
2525   LPred = *std::prev(Chain.end());
2526   if (DuplicatedToOriginalLPred)
2527     markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2528   return true;
2529 }
2530
2531 /// Tail duplicate \p BB into (some) predecessors if profitable.
2532 /// \p BB    - Basic block that may be duplicated
2533 /// \p LPred - Chosen layout predecessor of \p BB
2534 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
2535 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
2536 ///                  Used to identify which blocks to update predecessor
2537 ///                  counts.
2538 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
2539 ///                          chosen in the given order due to unnatural CFG
2540 ///                          only needed if \p BB is removed and
2541 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
2542 /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will
2543 ///                        only be true if the block was removed.
2544 /// \return  - True if the block was duplicated into all preds and removed.
2545 bool MachineBlockPlacement::maybeTailDuplicateBlock(
2546     MachineBasicBlock *BB, MachineBasicBlock *LPred,
2547     BlockChain &Chain, BlockFilterSet *BlockFilter,
2548     MachineFunction::iterator &PrevUnplacedBlockIt,
2549     bool &DuplicatedToLPred) {
2550   DuplicatedToLPred = false;
2551   if (!shouldTailDuplicate(BB))
2552     return false;
2553
2554   DEBUG(dbgs() << "Redoing tail duplication for Succ#"
2555         << BB->getNumber() << "\n");
2556
2557   // This has to be a callback because none of it can be done after
2558   // BB is deleted.
2559   bool Removed = false;
2560   auto RemovalCallback =
2561       [&](MachineBasicBlock *RemBB) {
2562         // Signal to outer function
2563         Removed = true;
2564
2565         // Conservative default.
2566         bool InWorkList = true;
2567         // Remove from the Chain and Chain Map
2568         if (BlockToChain.count(RemBB)) {
2569           BlockChain *Chain = BlockToChain[RemBB];
2570           InWorkList = Chain->UnscheduledPredecessors == 0;
2571           Chain->remove(RemBB);
2572           BlockToChain.erase(RemBB);
2573         }
2574
2575         // Handle the unplaced block iterator
2576         if (&(*PrevUnplacedBlockIt) == RemBB) {
2577           PrevUnplacedBlockIt++;
2578         }
2579
2580         // Handle the Work Lists
2581         if (InWorkList) {
2582           SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
2583           if (RemBB->isEHPad())
2584             RemoveList = EHPadWorkList;
2585           RemoveList.erase(
2586               remove_if(RemoveList,
2587                         [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}),
2588               RemoveList.end());
2589         }
2590
2591         // Handle the filter set
2592         if (BlockFilter) {
2593           BlockFilter->remove(RemBB);
2594         }
2595
2596         // Remove the block from loop info.
2597         MLI->removeBlock(RemBB);
2598         if (RemBB == PreferredLoopExit)
2599           PreferredLoopExit = nullptr;
2600
2601         DEBUG(dbgs() << "TailDuplicator deleted block: "
2602               << getBlockName(RemBB) << "\n");
2603       };
2604   auto RemovalCallbackRef =
2605       llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback);
2606
2607   SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
2608   bool IsSimple = TailDup.isSimpleBB(BB);
2609   TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2610                                  &DuplicatedPreds, &RemovalCallbackRef);
2611
2612   // Update UnscheduledPredecessors to reflect tail-duplication.
2613   DuplicatedToLPred = false;
2614   for (MachineBasicBlock *Pred : DuplicatedPreds) {
2615     // We're only looking for unscheduled predecessors that match the filter.
2616     BlockChain* PredChain = BlockToChain[Pred];
2617     if (Pred == LPred)
2618       DuplicatedToLPred = true;
2619     if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2620         || PredChain == &Chain)
2621       continue;
2622     for (MachineBasicBlock *NewSucc : Pred->successors()) {
2623       if (BlockFilter && !BlockFilter->count(NewSucc))
2624         continue;
2625       BlockChain *NewChain = BlockToChain[NewSucc];
2626       if (NewChain != &Chain && NewChain != PredChain)
2627         NewChain->UnscheduledPredecessors++;
2628     }
2629   }
2630   return Removed;
2631 }
2632
2633 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
2634   if (skipFunction(*MF.getFunction()))
2635     return false;
2636
2637   // Check for single-block functions and skip them.
2638   if (std::next(MF.begin()) == MF.end())
2639     return false;
2640
2641   F = &MF;
2642   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2643   MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2644       getAnalysis<MachineBlockFrequencyInfo>());
2645   MLI = &getAnalysis<MachineLoopInfo>();
2646   TII = MF.getSubtarget().getInstrInfo();
2647   TLI = MF.getSubtarget().getTargetLowering();
2648   MPDT = nullptr;
2649
2650   // Initialize PreferredLoopExit to nullptr here since it may never be set if
2651   // there are no MachineLoops.
2652   PreferredLoopExit = nullptr;
2653
2654   assert(BlockToChain.empty());
2655   assert(ComputedEdges.empty());
2656
2657   unsigned TailDupSize = TailDupPlacementThreshold;
2658   // If only the aggressive threshold is explicitly set, use it.
2659   if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
2660       TailDupPlacementThreshold.getNumOccurrences() == 0)
2661     TailDupSize = TailDupPlacementAggressiveThreshold;
2662
2663   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
2664   // For agressive optimization, we can adjust some thresholds to be less
2665   // conservative.
2666   if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) {
2667     // At O3 we should be more willing to copy blocks for tail duplication. This
2668     // increases size pressure, so we only do it at O3
2669     // Do this unless only the regular threshold is explicitly set.
2670     if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
2671         TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
2672       TailDupSize = TailDupPlacementAggressiveThreshold;
2673   }
2674
2675   if (TailDupPlacement) {
2676     MPDT = &getAnalysis<MachinePostDominatorTree>();
2677     if (MF.getFunction()->optForSize())
2678       TailDupSize = 1;
2679     TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize);
2680     precomputeTriangleChains();
2681   }
2682
2683   buildCFGChains();
2684
2685   // Changing the layout can create new tail merging opportunities.
2686   // TailMerge can create jump into if branches that make CFG irreducible for
2687   // HW that requires structured CFG.
2688   bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
2689                          PassConfig->getEnableTailMerge() &&
2690                          BranchFoldPlacement;
2691   // No tail merging opportunities if the block number is less than four.
2692   if (MF.size() > 3 && EnableTailMerge) {
2693     unsigned TailMergeSize = TailDupSize + 1;
2694     BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI,
2695                     *MBPI, TailMergeSize);
2696
2697     if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(),
2698                             getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2699                             /*AfterBlockPlacement=*/true)) {
2700       // Redo the layout if tail merging creates/removes/moves blocks.
2701       BlockToChain.clear();
2702       ComputedEdges.clear();
2703       // Must redo the post-dominator tree if blocks were changed.
2704       if (MPDT)
2705         MPDT->runOnMachineFunction(MF);
2706       ChainAllocator.DestroyAll();
2707       buildCFGChains();
2708     }
2709   }
2710
2711   optimizeBranches();
2712   alignBlocks();
2713
2714   BlockToChain.clear();
2715   ComputedEdges.clear();
2716   ChainAllocator.DestroyAll();
2717
2718   if (AlignAllBlock)
2719     // Align all of the blocks in the function to a specific alignment.
2720     for (MachineBasicBlock &MBB : MF)
2721       MBB.setAlignment(AlignAllBlock);
2722   else if (AlignAllNonFallThruBlocks) {
2723     // Align all of the blocks that have no fall-through predecessors to a
2724     // specific alignment.
2725     for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
2726       auto LayoutPred = std::prev(MBI);
2727       if (!LayoutPred->isSuccessor(&*MBI))
2728         MBI->setAlignment(AlignAllNonFallThruBlocks);
2729     }
2730   }
2731   if (ViewBlockLayoutWithBFI != GVDT_None &&
2732       (ViewBlockFreqFuncName.empty() ||
2733        F->getFunction()->getName().equals(ViewBlockFreqFuncName))) {
2734     MBFI->view("MBP." + MF.getName(), false);
2735   }
2736
2737
2738   // We always return true as we have no way to track whether the final order
2739   // differs from the original order.
2740   return true;
2741 }
2742
2743 namespace {
2744 /// \brief A pass to compute block placement statistics.
2745 ///
2746 /// A separate pass to compute interesting statistics for evaluating block
2747 /// placement. This is separate from the actual placement pass so that they can
2748 /// be computed in the absence of any placement transformations or when using
2749 /// alternative placement strategies.
2750 class MachineBlockPlacementStats : public MachineFunctionPass {
2751   /// \brief A handle to the branch probability pass.
2752   const MachineBranchProbabilityInfo *MBPI;
2753
2754   /// \brief A handle to the function-wide block frequency pass.
2755   const MachineBlockFrequencyInfo *MBFI;
2756
2757 public:
2758   static char ID; // Pass identification, replacement for typeid
2759   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
2760     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
2761   }
2762
2763   bool runOnMachineFunction(MachineFunction &F) override;
2764
2765   void getAnalysisUsage(AnalysisUsage &AU) const override {
2766     AU.addRequired<MachineBranchProbabilityInfo>();
2767     AU.addRequired<MachineBlockFrequencyInfo>();
2768     AU.setPreservesAll();
2769     MachineFunctionPass::getAnalysisUsage(AU);
2770   }
2771 };
2772 }
2773
2774 char MachineBlockPlacementStats::ID = 0;
2775 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
2776 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
2777                       "Basic Block Placement Stats", false, false)
2778 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
2779 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo)
2780 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
2781                     "Basic Block Placement Stats", false, false)
2782
2783 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
2784   // Check for single-block functions and skip them.
2785   if (std::next(F.begin()) == F.end())
2786     return false;
2787
2788   MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2789   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2790
2791   for (MachineBasicBlock &MBB : F) {
2792     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
2793     Statistic &NumBranches =
2794         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
2795     Statistic &BranchTakenFreq =
2796         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2797     for (MachineBasicBlock *Succ : MBB.successors()) {
2798       // Skip if this successor is a fallthrough.
2799       if (MBB.isLayoutSuccessor(Succ))
2800         continue;
2801
2802       BlockFrequency EdgeFreq =
2803           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
2804       ++NumBranches;
2805       BranchTakenFreq += EdgeFreq.getFrequency();
2806     }
2807   }
2808
2809   return false;
2810 }