xref: /llvm-project/llvm/lib/CodeGen/MachineBlockPlacement.cpp (revision 71ca9fcb8dc9ea0e1e3a4a47820edc78c398a85e)
1 //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements basic block placement transformations using the CFG
10 // structure and branch probability estimates.
11 //
12 // The pass strives to preserve the structure of the CFG (that is, retain
13 // a topological ordering of basic blocks) in the absence of a *strong* signal
14 // to the contrary from probabilities. However, within the CFG structure, it
15 // attempts to choose an ordering which favors placing more likely sequences of
16 // blocks adjacent to each other.
17 //
18 // The algorithm works from the inner-most loop within a function outward, and
19 // at each stage walks through the basic blocks, trying to coalesce them into
20 // sequential chains where allowed by the CFG (or demanded by heavy
21 // probabilities). Finally, it walks the blocks in topological order, and the
22 // first time it reaches a chain of basic blocks, it schedules them in the
23 // function in-order.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "BranchFolding.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SetVector.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/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/CodeGen/MBFIWrapper.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
40 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachinePostDominators.h"
45 #include "llvm/CodeGen/MachineSizeOpts.h"
46 #include "llvm/CodeGen/TailDuplicator.h"
47 #include "llvm/CodeGen/TargetInstrInfo.h"
48 #include "llvm/CodeGen/TargetLowering.h"
49 #include "llvm/CodeGen/TargetPassConfig.h"
50 #include "llvm/CodeGen/TargetSubtargetInfo.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/PrintPasses.h"
54 #include "llvm/InitializePasses.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Allocator.h"
57 #include "llvm/Support/BlockFrequency.h"
58 #include "llvm/Support/BranchProbability.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Transforms/Utils/CodeLayout.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <iterator>
70 #include <memory>
71 #include <string>
72 #include <tuple>
73 #include <utility>
74 #include <vector>
75 
76 using namespace llvm;
77 
78 #define DEBUG_TYPE "block-placement"
79 
80 STATISTIC(NumCondBranches, "Number of conditional branches");
81 STATISTIC(NumUncondBranches, "Number of unconditional branches");
82 STATISTIC(CondBranchTakenFreq,
83           "Potential frequency of taking conditional branches");
84 STATISTIC(UncondBranchTakenFreq,
85           "Potential frequency of taking unconditional branches");
86 
87 static cl::opt<unsigned> AlignAllBlock(
88     "align-all-blocks",
89     cl::desc("Force the alignment of all blocks in the function in log2 format "
90              "(e.g 4 means align on 16B boundaries)."),
91     cl::init(0), cl::Hidden);
92 
93 static cl::opt<unsigned> AlignAllNonFallThruBlocks(
94     "align-all-nofallthru-blocks",
95     cl::desc("Force the alignment of all blocks that have no fall-through "
96              "predecessors (i.e. don't add nops that are executed). In log2 "
97              "format (e.g 4 means align on 16B boundaries)."),
98     cl::init(0), cl::Hidden);
99 
100 static cl::opt<unsigned> MaxBytesForAlignmentOverride(
101     "max-bytes-for-alignment",
102     cl::desc("Forces the maximum bytes allowed to be emitted when padding for "
103              "alignment"),
104     cl::init(0), cl::Hidden);
105 
106 // FIXME: Find a good default for this flag and remove the flag.
107 static cl::opt<unsigned> ExitBlockBias(
108     "block-placement-exit-block-bias",
109     cl::desc("Block frequency percentage a loop exit block needs "
110              "over the original exit to be considered the new exit."),
111     cl::init(0), cl::Hidden);
112 
113 // Definition:
114 // - Outlining: placement of a basic block outside the chain or hot path.
115 
116 static cl::opt<unsigned> LoopToColdBlockRatio(
117     "loop-to-cold-block-ratio",
118     cl::desc("Outline loop blocks from loop chain if (frequency of loop) / "
119              "(frequency of block) is greater than this ratio"),
120     cl::init(5), cl::Hidden);
121 
122 static cl::opt<bool>
123     ForceLoopColdBlock("force-loop-cold-block",
124                        cl::desc("Force outlining cold blocks from loops."),
125                        cl::init(false), cl::Hidden);
126 
127 static cl::opt<bool>
128     PreciseRotationCost("precise-rotation-cost",
129                         cl::desc("Model the cost of loop rotation more "
130                                  "precisely by using profile data."),
131                         cl::init(false), cl::Hidden);
132 
133 static cl::opt<bool>
134     ForcePreciseRotationCost("force-precise-rotation-cost",
135                              cl::desc("Force the use of precise cost "
136                                       "loop rotation strategy."),
137                              cl::init(false), cl::Hidden);
138 
139 static cl::opt<unsigned> MisfetchCost(
140     "misfetch-cost",
141     cl::desc("Cost that models the probabilistic risk of an instruction "
142              "misfetch due to a jump comparing to falling through, whose cost "
143              "is zero."),
144     cl::init(1), cl::Hidden);
145 
146 static cl::opt<unsigned> JumpInstCost("jump-inst-cost",
147                                       cl::desc("Cost of jump instructions."),
148                                       cl::init(1), cl::Hidden);
149 static cl::opt<bool>
150     TailDupPlacement("tail-dup-placement",
151                      cl::desc("Perform tail duplication during placement. "
152                               "Creates more fallthrough opportunites in "
153                               "outline branches."),
154                      cl::init(true), cl::Hidden);
155 
156 static cl::opt<bool>
157     BranchFoldPlacement("branch-fold-placement",
158                         cl::desc("Perform branch folding during placement. "
159                                  "Reduces code size."),
160                         cl::init(true), cl::Hidden);
161 
162 // Heuristic for tail duplication.
163 static cl::opt<unsigned> TailDupPlacementThreshold(
164     "tail-dup-placement-threshold",
165     cl::desc("Instruction cutoff for tail duplication during layout. "
166              "Tail merging during layout is forced to have a threshold "
167              "that won't conflict."),
168     cl::init(2), cl::Hidden);
169 
170 // Heuristic for aggressive tail duplication.
171 static cl::opt<unsigned> TailDupPlacementAggressiveThreshold(
172     "tail-dup-placement-aggressive-threshold",
173     cl::desc("Instruction cutoff for aggressive tail duplication during "
174              "layout. Used at -O3. Tail merging during layout is forced to "
175              "have a threshold that won't conflict."),
176     cl::init(4), cl::Hidden);
177 
178 // Heuristic for tail duplication.
179 static cl::opt<unsigned> TailDupPlacementPenalty(
180     "tail-dup-placement-penalty",
181     cl::desc(
182         "Cost penalty for blocks that can avoid breaking CFG by copying. "
183         "Copying can increase fallthrough, but it also increases icache "
184         "pressure. This parameter controls the penalty to account for that. "
185         "Percent as integer."),
186     cl::init(2), cl::Hidden);
187 
188 // Heuristic for tail duplication if profile count is used in cost model.
189 static cl::opt<unsigned> TailDupProfilePercentThreshold(
190     "tail-dup-profile-percent-threshold",
191     cl::desc("If profile count information is used in tail duplication cost "
192              "model, the gained fall through number from tail duplication "
193              "should be at least this percent of hot count."),
194     cl::init(50), cl::Hidden);
195 
196 // Heuristic for triangle chains.
197 static cl::opt<unsigned> TriangleChainCount(
198     "triangle-chain-count",
199     cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the "
200              "triangle tail duplication heuristic to kick in. 0 to disable."),
201     cl::init(2), cl::Hidden);
202 
203 // Use case: When block layout is visualized after MBP pass, the basic blocks
204 // are labeled in layout order; meanwhile blocks could be numbered in a
205 // different order. It's hard to map between the graph and pass output.
206 // With this option on, the basic blocks are renumbered in function layout
207 // order. For debugging only.
208 static cl::opt<bool> RenumberBlocksBeforeView(
209     "renumber-blocks-before-view",
210     cl::desc(
211         "If true, basic blocks are re-numbered before MBP layout is printed "
212         "into a dot graph. Only used when a function is being printed."),
213     cl::init(false), cl::Hidden);
214 
215 static cl::opt<unsigned> ExtTspBlockPlacementMaxBlocks(
216     "ext-tsp-block-placement-max-blocks",
217     cl::desc("Maximum number of basic blocks in a function to run ext-TSP "
218              "block placement."),
219     cl::init(UINT_MAX), cl::Hidden);
220 
221 namespace llvm {
222 extern cl::opt<bool> EnableExtTspBlockPlacement;
223 extern cl::opt<bool> ApplyExtTspWithoutProfile;
224 extern cl::opt<unsigned> StaticLikelyProb;
225 extern cl::opt<unsigned> ProfileLikelyProb;
226 
227 // Internal option used to control BFI display only after MBP pass.
228 // Defined in CodeGen/MachineBlockFrequencyInfo.cpp:
229 // -view-block-layout-with-bfi=
230 extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI;
231 
232 // Command line option to specify the name of the function for CFG dump
233 // Defined in Analysis/BlockFrequencyInfo.cpp:  -view-bfi-func-name=
234 extern cl::opt<std::string> ViewBlockFreqFuncName;
235 } // namespace llvm
236 
237 namespace {
238 
239 class BlockChain;
240 
241 /// Type for our function-wide basic block -> block chain mapping.
242 using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>;
243 
244 /// A chain of blocks which will be laid out contiguously.
245 ///
246 /// This is the datastructure representing a chain of consecutive blocks that
247 /// are profitable to layout together in order to maximize fallthrough
248 /// probabilities and code locality. We also can use a block chain to represent
249 /// a sequence of basic blocks which have some external (correctness)
250 /// requirement for sequential layout.
251 ///
252 /// Chains can be built around a single basic block and can be merged to grow
253 /// them. They participate in a block-to-chain mapping, which is updated
254 /// automatically as chains are merged together.
255 class BlockChain {
256   /// The sequence of blocks belonging to this chain.
257   ///
258   /// This is the sequence of blocks for a particular chain. These will be laid
259   /// out in-order within the function.
260   SmallVector<MachineBasicBlock *, 4> Blocks;
261 
262   /// A handle to the function-wide basic block to block chain mapping.
263   ///
264   /// This is retained in each block chain to simplify the computation of child
265   /// block chains for SCC-formation and iteration. We store the edges to child
266   /// basic blocks, and map them back to their associated chains using this
267   /// structure.
268   BlockToChainMapType &BlockToChain;
269 
270 public:
271   /// Construct a new BlockChain.
272   ///
273   /// This builds a new block chain representing a single basic block in the
274   /// function. It also registers itself as the chain that block participates
275   /// in with the BlockToChain mapping.
276   BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB)
277       : Blocks(1, BB), BlockToChain(BlockToChain) {
278     assert(BB && "Cannot create a chain with a null basic block");
279     BlockToChain[BB] = this;
280   }
281 
282   /// Iterator over blocks within the chain.
283   using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
284   using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator;
285 
286   /// Beginning of blocks within the chain.
287   iterator begin() { return Blocks.begin(); }
288   const_iterator begin() const { return Blocks.begin(); }
289 
290   /// End of blocks within the chain.
291   iterator end() { return Blocks.end(); }
292   const_iterator end() const { return Blocks.end(); }
293 
294   bool remove(MachineBasicBlock *BB) {
295     for (iterator i = begin(); i != end(); ++i) {
296       if (*i == BB) {
297         Blocks.erase(i);
298         return true;
299       }
300     }
301     return false;
302   }
303 
304   /// Merge a block chain into this one.
305   ///
306   /// This routine merges a block chain into this one. It takes care of forming
307   /// a contiguous sequence of basic blocks, updating the edge list, and
308   /// updating the block -> chain mapping. It does not free or tear down the
309   /// old chain, but the old chain's block list is no longer valid.
310   void merge(MachineBasicBlock *BB, BlockChain *Chain) {
311     assert(BB && "Can't merge a null block.");
312     assert(!Blocks.empty() && "Can't merge into an empty chain.");
313 
314     // Fast path in case we don't have a chain already.
315     if (!Chain) {
316       assert(!BlockToChain[BB] &&
317              "Passed chain is null, but BB has entry in BlockToChain.");
318       Blocks.push_back(BB);
319       BlockToChain[BB] = this;
320       return;
321     }
322 
323     assert(BB == *Chain->begin() && "Passed BB is not head of Chain.");
324     assert(Chain->begin() != Chain->end());
325 
326     // Update the incoming blocks to point to this chain, and add them to the
327     // chain structure.
328     for (MachineBasicBlock *ChainBB : *Chain) {
329       Blocks.push_back(ChainBB);
330       assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain.");
331       BlockToChain[ChainBB] = this;
332     }
333   }
334 
335 #ifndef NDEBUG
336   /// Dump the blocks in this chain.
337   LLVM_DUMP_METHOD void dump() {
338     for (MachineBasicBlock *MBB : *this)
339       MBB->dump();
340   }
341 #endif // NDEBUG
342 
343   /// Count of predecessors of any block within the chain which have not
344   /// yet been scheduled.  In general, we will delay scheduling this chain
345   /// until those predecessors are scheduled (or we find a sufficiently good
346   /// reason to override this heuristic.)  Note that when forming loop chains,
347   /// blocks outside the loop are ignored and treated as if they were already
348   /// scheduled.
349   ///
350   /// Note: This field is reinitialized multiple times - once for each loop,
351   /// and then once for the function as a whole.
352   unsigned UnscheduledPredecessors = 0;
353 };
354 
355 class MachineBlockPlacement : public MachineFunctionPass {
356   /// A type for a block filter set.
357   using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
358 
359   /// Pair struct containing basic block and taildup profitability
360   struct BlockAndTailDupResult {
361     MachineBasicBlock *BB = nullptr;
362     bool ShouldTailDup;
363   };
364 
365   /// Triple struct containing edge weight and the edge.
366   struct WeightedEdge {
367     BlockFrequency Weight;
368     MachineBasicBlock *Src = nullptr;
369     MachineBasicBlock *Dest = nullptr;
370   };
371 
372   /// work lists of blocks that are ready to be laid out
373   SmallVector<MachineBasicBlock *, 16> BlockWorkList;
374   SmallVector<MachineBasicBlock *, 16> EHPadWorkList;
375 
376   /// Edges that have already been computed as optimal.
377   DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
378 
379   /// Machine Function
380   MachineFunction *F = nullptr;
381 
382   /// A handle to the branch probability pass.
383   const MachineBranchProbabilityInfo *MBPI = nullptr;
384 
385   /// A handle to the function-wide block frequency pass.
386   std::unique_ptr<MBFIWrapper> MBFI;
387 
388   /// A handle to the loop info.
389   MachineLoopInfo *MLI = nullptr;
390 
391   /// Preferred loop exit.
392   /// Member variable for convenience. It may be removed by duplication deep
393   /// in the call stack.
394   MachineBasicBlock *PreferredLoopExit = nullptr;
395 
396   /// A handle to the target's instruction info.
397   const TargetInstrInfo *TII = nullptr;
398 
399   /// A handle to the target's lowering info.
400   const TargetLoweringBase *TLI = nullptr;
401 
402   /// A handle to the post dominator tree.
403   MachinePostDominatorTree *MPDT = nullptr;
404 
405   ProfileSummaryInfo *PSI = nullptr;
406 
407   TargetPassConfig *PassConfig = nullptr;
408 
409   /// Duplicator used to duplicate tails during placement.
410   ///
411   /// Placement decisions can open up new tail duplication opportunities, but
412   /// since tail duplication affects placement decisions of later blocks, it
413   /// must be done inline.
414   TailDuplicator TailDup;
415 
416   /// Partial tail duplication threshold.
417   BlockFrequency DupThreshold;
418 
419   unsigned TailDupSize;
420 
421   /// True:  use block profile count to compute tail duplication cost.
422   /// False: use block frequency to compute tail duplication cost.
423   bool UseProfileCount = false;
424 
425   /// Allocator and owner of BlockChain structures.
426   ///
427   /// We build BlockChains lazily while processing the loop structure of
428   /// a function. To reduce malloc traffic, we allocate them using this
429   /// slab-like allocator, and destroy them after the pass completes. An
430   /// important guarantee is that this allocator produces stable pointers to
431   /// the chains.
432   SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
433 
434   /// Function wide BasicBlock to BlockChain mapping.
435   ///
436   /// This mapping allows efficiently moving from any given basic block to the
437   /// BlockChain it participates in, if any. We use it to, among other things,
438   /// allow implicitly defining edges between chains as the existing edges
439   /// between basic blocks.
440   DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
441 
442 #ifndef NDEBUG
443   /// The set of basic blocks that have terminators that cannot be fully
444   /// analyzed.  These basic blocks cannot be re-ordered safely by
445   /// MachineBlockPlacement, and we must preserve physical layout of these
446   /// blocks and their successors through the pass.
447   SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
448 #endif
449 
450   /// Get block profile count or frequency according to UseProfileCount.
451   /// The return value is used to model tail duplication cost.
452   BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) {
453     if (UseProfileCount) {
454       auto Count = MBFI->getBlockProfileCount(BB);
455       if (Count)
456         return BlockFrequency(*Count);
457       else
458         return BlockFrequency(0);
459     } else
460       return MBFI->getBlockFreq(BB);
461   }
462 
463   /// Scale the DupThreshold according to basic block size.
464   BlockFrequency scaleThreshold(MachineBasicBlock *BB);
465   void initTailDupThreshold();
466 
467   /// Decrease the UnscheduledPredecessors count for all blocks in chain, and
468   /// if the count goes to 0, add them to the appropriate work list.
469   void markChainSuccessors(const BlockChain &Chain,
470                            const MachineBasicBlock *LoopHeaderBB,
471                            const BlockFilterSet *BlockFilter = nullptr);
472 
473   /// Decrease the UnscheduledPredecessors count for a single block, and
474   /// if the count goes to 0, add them to the appropriate work list.
475   void markBlockSuccessors(const BlockChain &Chain, const MachineBasicBlock *BB,
476                            const MachineBasicBlock *LoopHeaderBB,
477                            const BlockFilterSet *BlockFilter = nullptr);
478 
479   BranchProbability
480   collectViableSuccessors(const MachineBasicBlock *BB, const BlockChain &Chain,
481                           const BlockFilterSet *BlockFilter,
482                           SmallVector<MachineBasicBlock *, 4> &Successors);
483   bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred,
484                        BlockFilterSet *BlockFilter);
485   void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates,
486                                MachineBasicBlock *BB,
487                                BlockFilterSet *BlockFilter);
488   bool repeatedlyTailDuplicateBlock(
489       MachineBasicBlock *BB, MachineBasicBlock *&LPred,
490       const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
491       BlockFilterSet *BlockFilter,
492       MachineFunction::iterator &PrevUnplacedBlockIt,
493       BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt);
494   bool
495   maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
496                           BlockChain &Chain, BlockFilterSet *BlockFilter,
497                           MachineFunction::iterator &PrevUnplacedBlockIt,
498                           BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
499                           bool &DuplicatedToLPred);
500   bool hasBetterLayoutPredecessor(const MachineBasicBlock *BB,
501                                   const MachineBasicBlock *Succ,
502                                   const BlockChain &SuccChain,
503                                   BranchProbability SuccProb,
504                                   BranchProbability RealSuccProb,
505                                   const BlockChain &Chain,
506                                   const BlockFilterSet *BlockFilter);
507   BlockAndTailDupResult selectBestSuccessor(const MachineBasicBlock *BB,
508                                             const BlockChain &Chain,
509                                             const BlockFilterSet *BlockFilter);
510   MachineBasicBlock *
511   selectBestCandidateBlock(const BlockChain &Chain,
512                            SmallVectorImpl<MachineBasicBlock *> &WorkList);
513   MachineBasicBlock *
514   getFirstUnplacedBlock(const BlockChain &PlacedChain,
515                         MachineFunction::iterator &PrevUnplacedBlockIt);
516   MachineBasicBlock *
517   getFirstUnplacedBlock(const BlockChain &PlacedChain,
518                         BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
519                         const BlockFilterSet *BlockFilter);
520 
521   /// Add a basic block to the work list if it is appropriate.
522   ///
523   /// If the optional parameter BlockFilter is provided, only MBB
524   /// present in the set will be added to the worklist. If nullptr
525   /// is provided, no filtering occurs.
526   void fillWorkLists(const MachineBasicBlock *MBB,
527                      SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
528                      const BlockFilterSet *BlockFilter);
529 
530   void buildChain(const MachineBasicBlock *BB, BlockChain &Chain,
531                   BlockFilterSet *BlockFilter = nullptr);
532   bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock,
533                                const MachineBasicBlock *OldTop);
534   bool hasViableTopFallthrough(const MachineBasicBlock *Top,
535                                const BlockFilterSet &LoopBlockSet);
536   BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top,
537                                     const BlockFilterSet &LoopBlockSet);
538   BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop,
539                                   const MachineBasicBlock *OldTop,
540                                   const MachineBasicBlock *ExitBB,
541                                   const BlockFilterSet &LoopBlockSet);
542   MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
543                                            const MachineLoop &L,
544                                            const BlockFilterSet &LoopBlockSet);
545   MachineBasicBlock *findBestLoopTop(const MachineLoop &L,
546                                      const BlockFilterSet &LoopBlockSet);
547   MachineBasicBlock *findBestLoopExit(const MachineLoop &L,
548                                       const BlockFilterSet &LoopBlockSet,
549                                       BlockFrequency &ExitFreq);
550   BlockFilterSet collectLoopBlockSet(const MachineLoop &L);
551   void buildLoopChains(const MachineLoop &L);
552   void rotateLoop(BlockChain &LoopChain, const MachineBasicBlock *ExitingBB,
553                   BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet);
554   void rotateLoopWithProfile(BlockChain &LoopChain, const MachineLoop &L,
555                              const BlockFilterSet &LoopBlockSet);
556   void buildCFGChains();
557   void optimizeBranches();
558   void alignBlocks();
559   /// Returns true if a block should be tail-duplicated to increase fallthrough
560   /// opportunities.
561   bool shouldTailDuplicate(MachineBasicBlock *BB);
562   /// Check the edge frequencies to see if tail duplication will increase
563   /// fallthroughs.
564   bool isProfitableToTailDup(const MachineBasicBlock *BB,
565                              const MachineBasicBlock *Succ,
566                              BranchProbability QProb, const BlockChain &Chain,
567                              const BlockFilterSet *BlockFilter);
568 
569   /// Check for a trellis layout.
570   bool isTrellis(const MachineBasicBlock *BB,
571                  const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
572                  const BlockChain &Chain, const BlockFilterSet *BlockFilter);
573 
574   /// Get the best successor given a trellis layout.
575   BlockAndTailDupResult getBestTrellisSuccessor(
576       const MachineBasicBlock *BB,
577       const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
578       BranchProbability AdjustedSumProb, const BlockChain &Chain,
579       const BlockFilterSet *BlockFilter);
580 
581   /// Get the best pair of non-conflicting edges.
582   static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
583       const MachineBasicBlock *BB,
584       MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges);
585 
586   /// Returns true if a block can tail duplicate into all unplaced
587   /// predecessors. Filters based on loop.
588   bool canTailDuplicateUnplacedPreds(const MachineBasicBlock *BB,
589                                      MachineBasicBlock *Succ,
590                                      const BlockChain &Chain,
591                                      const BlockFilterSet *BlockFilter);
592 
593   /// Find chains of triangles to tail-duplicate where a global analysis works,
594   /// but a local analysis would not find them.
595   void precomputeTriangleChains();
596 
597   /// Apply a post-processing step optimizing block placement.
598   void applyExtTsp();
599 
600   /// Modify the existing block placement in the function and adjust all jumps.
601   void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder);
602 
603   /// Create a single CFG chain from the current block order.
604   void createCFGChainExtTsp();
605 
606 public:
607   static char ID; // Pass identification, replacement for typeid
608 
609   MachineBlockPlacement() : MachineFunctionPass(ID) {
610     initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry());
611   }
612 
613   bool runOnMachineFunction(MachineFunction &F) override;
614 
615   bool allowTailDupPlacement() const {
616     assert(F);
617     return TailDupPlacement && !F->getTarget().requiresStructuredCFG();
618   }
619 
620   void getAnalysisUsage(AnalysisUsage &AU) const override {
621     AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
622     AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
623     if (TailDupPlacement)
624       AU.addRequired<MachinePostDominatorTreeWrapperPass>();
625     AU.addRequired<MachineLoopInfoWrapperPass>();
626     AU.addRequired<ProfileSummaryInfoWrapperPass>();
627     AU.addRequired<TargetPassConfig>();
628     MachineFunctionPass::getAnalysisUsage(AU);
629   }
630 };
631 
632 } // end anonymous namespace
633 
634 char MachineBlockPlacement::ID = 0;
635 
636 char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID;
637 
638 INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,
639                       "Branch Probability Basic Block Placement", false, false)
640 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
641 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
642 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTreeWrapperPass)
643 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass)
644 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
645 INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE,
646                     "Branch Probability Basic Block Placement", false, false)
647 
648 #ifndef NDEBUG
649 /// Helper to print the name of a MBB.
650 ///
651 /// Only used by debug logging.
652 static std::string getBlockName(const MachineBasicBlock *BB) {
653   std::string Result;
654   raw_string_ostream OS(Result);
655   OS << printMBBReference(*BB);
656   OS << " ('" << BB->getName() << "')";
657   OS.flush();
658   return Result;
659 }
660 #endif
661 
662 /// Mark a chain's successors as having one fewer preds.
663 ///
664 /// When a chain is being merged into the "placed" chain, this routine will
665 /// quickly walk the successors of each block in the chain and mark them as
666 /// having one fewer active predecessor. It also adds any successors of this
667 /// chain which reach the zero-predecessor state to the appropriate worklist.
668 void MachineBlockPlacement::markChainSuccessors(
669     const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB,
670     const BlockFilterSet *BlockFilter) {
671   // Walk all the blocks in this chain, marking their successors as having
672   // a predecessor placed.
673   for (MachineBasicBlock *MBB : Chain) {
674     markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
675   }
676 }
677 
678 /// Mark a single block's successors as having one fewer preds.
679 ///
680 /// Under normal circumstances, this is only called by markChainSuccessors,
681 /// but if a block that was to be placed is completely tail-duplicated away,
682 /// and was duplicated into the chain end, we need to redo markBlockSuccessors
683 /// for just that block.
684 void MachineBlockPlacement::markBlockSuccessors(
685     const BlockChain &Chain, const MachineBasicBlock *MBB,
686     const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) {
687   // Add any successors for which this is the only un-placed in-loop
688   // predecessor to the worklist as a viable candidate for CFG-neutral
689   // placement. No subsequent placement of this block will violate the CFG
690   // shape, so we get to use heuristics to choose a favorable placement.
691   for (MachineBasicBlock *Succ : MBB->successors()) {
692     if (BlockFilter && !BlockFilter->count(Succ))
693       continue;
694     BlockChain &SuccChain = *BlockToChain[Succ];
695     // Disregard edges within a fixed chain, or edges to the loop header.
696     if (&Chain == &SuccChain || Succ == LoopHeaderBB)
697       continue;
698 
699     // This is a cross-chain edge that is within the loop, so decrement the
700     // loop predecessor count of the destination chain.
701     if (SuccChain.UnscheduledPredecessors == 0 ||
702         --SuccChain.UnscheduledPredecessors > 0)
703       continue;
704 
705     auto *NewBB = *SuccChain.begin();
706     if (NewBB->isEHPad())
707       EHPadWorkList.push_back(NewBB);
708     else
709       BlockWorkList.push_back(NewBB);
710   }
711 }
712 
713 /// This helper function collects the set of successors of block
714 /// \p BB that are allowed to be its layout successors, and return
715 /// the total branch probability of edges from \p BB to those
716 /// blocks.
717 BranchProbability MachineBlockPlacement::collectViableSuccessors(
718     const MachineBasicBlock *BB, const BlockChain &Chain,
719     const BlockFilterSet *BlockFilter,
720     SmallVector<MachineBasicBlock *, 4> &Successors) {
721   // Adjust edge probabilities by excluding edges pointing to blocks that is
722   // either not in BlockFilter or is already in the current chain. Consider the
723   // following CFG:
724   //
725   //     --->A
726   //     |  / \
727   //     | B   C
728   //     |  \ / \
729   //     ----D   E
730   //
731   // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after
732   // A->C is chosen as a fall-through, D won't be selected as a successor of C
733   // due to CFG constraint (the probability of C->D is not greater than
734   // HotProb to break topo-order). If we exclude E that is not in BlockFilter
735   // when calculating the probability of C->D, D will be selected and we
736   // will get A C D B as the layout of this loop.
737   auto AdjustedSumProb = BranchProbability::getOne();
738   for (MachineBasicBlock *Succ : BB->successors()) {
739     bool SkipSucc = false;
740     if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
741       SkipSucc = true;
742     } else {
743       BlockChain *SuccChain = BlockToChain[Succ];
744       if (SuccChain == &Chain) {
745         SkipSucc = true;
746       } else if (Succ != *SuccChain->begin()) {
747         LLVM_DEBUG(dbgs() << "    " << getBlockName(Succ)
748                           << " -> Mid chain!\n");
749         continue;
750       }
751     }
752     if (SkipSucc)
753       AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
754     else
755       Successors.push_back(Succ);
756   }
757 
758   return AdjustedSumProb;
759 }
760 
761 /// The helper function returns the branch probability that is adjusted
762 /// or normalized over the new total \p AdjustedSumProb.
763 static BranchProbability
764 getAdjustedProbability(BranchProbability OrigProb,
765                        BranchProbability AdjustedSumProb) {
766   BranchProbability SuccProb;
767   uint32_t SuccProbN = OrigProb.getNumerator();
768   uint32_t SuccProbD = AdjustedSumProb.getNumerator();
769   if (SuccProbN >= SuccProbD)
770     SuccProb = BranchProbability::getOne();
771   else
772     SuccProb = BranchProbability(SuccProbN, SuccProbD);
773 
774   return SuccProb;
775 }
776 
777 /// Check if \p BB has exactly the successors in \p Successors.
778 static bool
779 hasSameSuccessors(MachineBasicBlock &BB,
780                   SmallPtrSetImpl<const MachineBasicBlock *> &Successors) {
781   if (BB.succ_size() != Successors.size())
782     return false;
783   // We don't want to count self-loops
784   if (Successors.count(&BB))
785     return false;
786   for (MachineBasicBlock *Succ : BB.successors())
787     if (!Successors.count(Succ))
788       return false;
789   return true;
790 }
791 
792 /// Check if a block should be tail duplicated to increase fallthrough
793 /// opportunities.
794 /// \p BB Block to check.
795 bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
796   // Blocks with single successors don't create additional fallthrough
797   // opportunities. Don't duplicate them. TODO: When conditional exits are
798   // analyzable, allow them to be duplicated.
799   bool IsSimple = TailDup.isSimpleBB(BB);
800 
801   if (BB->succ_size() == 1)
802     return false;
803   return TailDup.shouldTailDuplicate(IsSimple, *BB);
804 }
805 
806 /// Compare 2 BlockFrequency's with a small penalty for \p A.
807 /// In order to be conservative, we apply a X% penalty to account for
808 /// increased icache pressure and static heuristics. For small frequencies
809 /// we use only the numerators to improve accuracy. For simplicity, we assume
810 /// the penalty is less than 100%
811 /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere.
812 static bool greaterWithBias(BlockFrequency A, BlockFrequency B,
813                             BlockFrequency EntryFreq) {
814   BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
815   BlockFrequency Gain = A - B;
816   return (Gain / ThresholdProb) >= EntryFreq;
817 }
818 
819 /// Check the edge frequencies to see if tail duplication will increase
820 /// fallthroughs. It only makes sense to call this function when
821 /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is
822 /// always locally profitable if we would have picked \p Succ without
823 /// considering duplication.
824 bool MachineBlockPlacement::isProfitableToTailDup(
825     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
826     BranchProbability QProb, const BlockChain &Chain,
827     const BlockFilterSet *BlockFilter) {
828   // We need to do a probability calculation to make sure this is profitable.
829   // First: does succ have a successor that post-dominates? This affects the
830   // calculation. The 2 relevant cases are:
831   //    BB         BB
832   //    | \Qout    | \Qout
833   //   P|  C       |P C
834   //    =   C'     =   C'
835   //    |  /Qin    |  /Qin
836   //    | /        | /
837   //    Succ       Succ
838   //    / \        | \  V
839   //  U/   =V      |U \
840   //  /     \      =   D
841   //  D      E     |  /
842   //               | /
843   //               |/
844   //               PDom
845   //  '=' : Branch taken for that CFG edge
846   // In the second case, Placing Succ while duplicating it into C prevents the
847   // fallthrough of Succ into either D or PDom, because they now have C as an
848   // unplaced predecessor
849 
850   // Start by figuring out which case we fall into
851   MachineBasicBlock *PDom = nullptr;
852   SmallVector<MachineBasicBlock *, 4> SuccSuccs;
853   // Only scan the relevant successors
854   auto AdjustedSuccSumProb =
855       collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
856   BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ);
857   auto BBFreq = MBFI->getBlockFreq(BB);
858   auto SuccFreq = MBFI->getBlockFreq(Succ);
859   BlockFrequency P = BBFreq * PProb;
860   BlockFrequency Qout = BBFreq * QProb;
861   BlockFrequency EntryFreq = MBFI->getEntryFreq();
862   // If there are no more successors, it is profitable to copy, as it strictly
863   // increases fallthrough.
864   if (SuccSuccs.size() == 0)
865     return greaterWithBias(P, Qout, EntryFreq);
866 
867   auto BestSuccSucc = BranchProbability::getZero();
868   // Find the PDom or the best Succ if no PDom exists.
869   for (MachineBasicBlock *SuccSucc : SuccSuccs) {
870     auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
871     if (Prob > BestSuccSucc)
872       BestSuccSucc = Prob;
873     if (PDom == nullptr)
874       if (MPDT->dominates(SuccSucc, Succ)) {
875         PDom = SuccSucc;
876         break;
877       }
878   }
879   // For the comparisons, we need to know Succ's best incoming edge that isn't
880   // from BB.
881   auto SuccBestPred = BlockFrequency(0);
882   for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
883     if (SuccPred == Succ || SuccPred == BB ||
884         BlockToChain[SuccPred] == &Chain ||
885         (BlockFilter && !BlockFilter->count(SuccPred)))
886       continue;
887     auto Freq =
888         MBFI->getBlockFreq(SuccPred) * MBPI->getEdgeProbability(SuccPred, Succ);
889     if (Freq > SuccBestPred)
890       SuccBestPred = Freq;
891   }
892   // Qin is Succ's best unplaced incoming edge that isn't BB
893   BlockFrequency Qin = SuccBestPred;
894   // If it doesn't have a post-dominating successor, here is the calculation:
895   //    BB        BB
896   //    | \Qout   |  \
897   //   P|  C      |   =
898   //    =   C'    |    C
899   //    |  /Qin   |     |
900   //    | /       |     C' (+Succ)
901   //    Succ      Succ /|
902   //    / \       |  \/ |
903   //  U/   =V     |  == |
904   //  /     \     | /  \|
905   //  D      E    D     E
906   //  '=' : Branch taken for that CFG edge
907   //  Cost in the first case is: P + V
908   //  For this calculation, we always assume P > Qout. If Qout > P
909   //  The result of this function will be ignored at the caller.
910   //  Let F = SuccFreq - Qin
911   //  Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V
912 
913   if (PDom == nullptr || !Succ->isSuccessor(PDom)) {
914     BranchProbability UProb = BestSuccSucc;
915     BranchProbability VProb = AdjustedSuccSumProb - UProb;
916     BlockFrequency F = SuccFreq - Qin;
917     BlockFrequency V = SuccFreq * VProb;
918     BlockFrequency QinU = std::min(Qin, F) * UProb;
919     BlockFrequency BaseCost = P + V;
920     BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb;
921     return greaterWithBias(BaseCost, DupCost, EntryFreq);
922   }
923   BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom);
924   BranchProbability VProb = AdjustedSuccSumProb - UProb;
925   BlockFrequency U = SuccFreq * UProb;
926   BlockFrequency V = SuccFreq * VProb;
927   BlockFrequency F = SuccFreq - Qin;
928   // If there is a post-dominating successor, here is the calculation:
929   // BB         BB                 BB          BB
930   // | \Qout    |   \               | \Qout     |  \
931   // |P C       |    =              |P C        |   =
932   // =   C'     |P    C             =   C'      |P   C
933   // |  /Qin    |      |            |  /Qin     |     |
934   // | /        |      C' (+Succ)   | /         |     C' (+Succ)
935   // Succ       Succ  /|            Succ        Succ /|
936   // | \  V     |   \/ |            | \  V      |  \/ |
937   // |U \       |U  /\ =?           |U =        |U /\ |
938   // =   D      = =  =?|            |   D       | =  =|
939   // |  /       |/     D            |  /        |/    D
940   // | /        |     /             | =         |    /
941   // |/         |    /              |/          |   =
942   // Dom         Dom                Dom         Dom
943   //  '=' : Branch taken for that CFG edge
944   // The cost for taken branches in the first case is P + U
945   // Let F = SuccFreq - Qin
946   // The cost in the second case (assuming independence), given the layout:
947   // BB, Succ, (C+Succ), D, Dom or the layout:
948   // BB, Succ, D, Dom, (C+Succ)
949   // is Qout + max(F, Qin) * U + min(F, Qin)
950   // compare P + U vs Qout + P * U + Qin.
951   //
952   // The 3rd and 4th cases cover when Dom would be chosen to follow Succ.
953   //
954   // For the 3rd case, the cost is P + 2 * V
955   // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V
956   // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V
957   if (UProb > AdjustedSuccSumProb / 2 &&
958       !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
959                                   Chain, BlockFilter))
960     // Cases 3 & 4
961     return greaterWithBias(
962         (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
963         EntryFreq);
964   // Cases 1 & 2
965   return greaterWithBias((P + U),
966                          (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
967                           std::max(Qin, F) * UProb),
968                          EntryFreq);
969 }
970 
971 /// Check for a trellis layout. \p BB is the upper part of a trellis if its
972 /// successors form the lower part of a trellis. A successor set S forms the
973 /// lower part of a trellis if all of the predecessors of S are either in S or
974 /// have all of S as successors. We ignore trellises where BB doesn't have 2
975 /// successors because for fewer than 2, it's trivial, and for 3 or greater they
976 /// are very uncommon and complex to compute optimally. Allowing edges within S
977 /// is not strictly a trellis, but the same algorithm works, so we allow it.
978 bool MachineBlockPlacement::isTrellis(
979     const MachineBasicBlock *BB,
980     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
981     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
982   // Technically BB could form a trellis with branching factor higher than 2.
983   // But that's extremely uncommon.
984   if (BB->succ_size() != 2 || ViableSuccs.size() != 2)
985     return false;
986 
987   SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(),
988                                                        BB->succ_end());
989   // To avoid reviewing the same predecessors twice.
990   SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
991 
992   for (MachineBasicBlock *Succ : ViableSuccs) {
993     int PredCount = 0;
994     for (auto *SuccPred : Succ->predecessors()) {
995       // Allow triangle successors, but don't count them.
996       if (Successors.count(SuccPred)) {
997         // Make sure that it is actually a triangle.
998         for (MachineBasicBlock *CheckSucc : SuccPred->successors())
999           if (!Successors.count(CheckSucc))
1000             return false;
1001         continue;
1002       }
1003       const BlockChain *PredChain = BlockToChain[SuccPred];
1004       if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
1005           PredChain == &Chain || PredChain == BlockToChain[Succ])
1006         continue;
1007       ++PredCount;
1008       // Perform the successor check only once.
1009       if (!SeenPreds.insert(SuccPred).second)
1010         continue;
1011       if (!hasSameSuccessors(*SuccPred, Successors))
1012         return false;
1013     }
1014     // If one of the successors has only BB as a predecessor, it is not a
1015     // trellis.
1016     if (PredCount < 1)
1017       return false;
1018   }
1019   return true;
1020 }
1021 
1022 /// Pick the highest total weight pair of edges that can both be laid out.
1023 /// The edges in \p Edges[0] are assumed to have a different destination than
1024 /// the edges in \p Edges[1]. Simple counting shows that the best pair is either
1025 /// the individual highest weight edges to the 2 different destinations, or in
1026 /// case of a conflict, one of them should be replaced with a 2nd best edge.
1027 std::pair<MachineBlockPlacement::WeightedEdge,
1028           MachineBlockPlacement::WeightedEdge>
1029 MachineBlockPlacement::getBestNonConflictingEdges(
1030     const MachineBasicBlock *BB,
1031     MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>>
1032         Edges) {
1033   // Sort the edges, and then for each successor, find the best incoming
1034   // predecessor. If the best incoming predecessors aren't the same,
1035   // then that is clearly the best layout. If there is a conflict, one of the
1036   // successors will have to fallthrough from the second best predecessor. We
1037   // compare which combination is better overall.
1038 
1039   // Sort for highest frequency.
1040   auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; };
1041 
1042   llvm::stable_sort(Edges[0], Cmp);
1043   llvm::stable_sort(Edges[1], Cmp);
1044   auto BestA = Edges[0].begin();
1045   auto BestB = Edges[1].begin();
1046   // Arrange for the correct answer to be in BestA and BestB
1047   // If the 2 best edges don't conflict, the answer is already there.
1048   if (BestA->Src == BestB->Src) {
1049     // Compare the total fallthrough of (Best + Second Best) for both pairs
1050     auto SecondBestA = std::next(BestA);
1051     auto SecondBestB = std::next(BestB);
1052     BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
1053     BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
1054     if (BestAScore < BestBScore)
1055       BestA = SecondBestA;
1056     else
1057       BestB = SecondBestB;
1058   }
1059   // Arrange for the BB edge to be in BestA if it exists.
1060   if (BestB->Src == BB)
1061     std::swap(BestA, BestB);
1062   return std::make_pair(*BestA, *BestB);
1063 }
1064 
1065 /// Get the best successor from \p BB based on \p BB being part of a trellis.
1066 /// We only handle trellises with 2 successors, so the algorithm is
1067 /// straightforward: Find the best pair of edges that don't conflict. We find
1068 /// the best incoming edge for each successor in the trellis. If those conflict,
1069 /// we consider which of them should be replaced with the second best.
1070 /// Upon return the two best edges will be in \p BestEdges. If one of the edges
1071 /// comes from \p BB, it will be in \p BestEdges[0]
1072 MachineBlockPlacement::BlockAndTailDupResult
1073 MachineBlockPlacement::getBestTrellisSuccessor(
1074     const MachineBasicBlock *BB,
1075     const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1076     BranchProbability AdjustedSumProb, const BlockChain &Chain,
1077     const BlockFilterSet *BlockFilter) {
1078 
1079   BlockAndTailDupResult Result = {nullptr, false};
1080   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1081                                                        BB->succ_end());
1082 
1083   // We assume size 2 because it's common. For general n, we would have to do
1084   // the Hungarian algorithm, but it's not worth the complexity because more
1085   // than 2 successors is fairly uncommon, and a trellis even more so.
1086   if (Successors.size() != 2 || ViableSuccs.size() != 2)
1087     return Result;
1088 
1089   // Collect the edge frequencies of all edges that form the trellis.
1090   SmallVector<WeightedEdge, 8> Edges[2];
1091   int SuccIndex = 0;
1092   for (auto *Succ : ViableSuccs) {
1093     for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
1094       // Skip any placed predecessors that are not BB
1095       if (SuccPred != BB)
1096         if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
1097             BlockToChain[SuccPred] == &Chain ||
1098             BlockToChain[SuccPred] == BlockToChain[Succ])
1099           continue;
1100       BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1101                                 MBPI->getEdgeProbability(SuccPred, Succ);
1102       Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ});
1103     }
1104     ++SuccIndex;
1105   }
1106 
1107   // Pick the best combination of 2 edges from all the edges in the trellis.
1108   WeightedEdge BestA, BestB;
1109   std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1110 
1111   if (BestA.Src != BB) {
1112     // If we have a trellis, and BB doesn't have the best fallthrough edges,
1113     // we shouldn't choose any successor. We've already looked and there's a
1114     // better fallthrough edge for all the successors.
1115     LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n");
1116     return Result;
1117   }
1118 
1119   // Did we pick the triangle edge? If tail-duplication is profitable, do
1120   // that instead. Otherwise merge the triangle edge now while we know it is
1121   // optimal.
1122   if (BestA.Dest == BestB.Src) {
1123     // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2
1124     // would be better.
1125     MachineBasicBlock *Succ1 = BestA.Dest;
1126     MachineBasicBlock *Succ2 = BestB.Dest;
1127     // Check to see if tail-duplication would be profitable.
1128     if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
1129         canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1130         isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
1131                               Chain, BlockFilter)) {
1132       LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability(
1133                      MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
1134                  dbgs() << "    Selected: " << getBlockName(Succ2)
1135                         << ", probability: " << Succ2Prob
1136                         << " (Tail Duplicate)\n");
1137       Result.BB = Succ2;
1138       Result.ShouldTailDup = true;
1139       return Result;
1140     }
1141   }
1142   // We have already computed the optimal edge for the other side of the
1143   // trellis.
1144   ComputedEdges[BestB.Src] = {BestB.Dest, false};
1145 
1146   auto TrellisSucc = BestA.Dest;
1147   LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability(
1148                  MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1149              dbgs() << "    Selected: " << getBlockName(TrellisSucc)
1150                     << ", probability: " << SuccProb << " (Trellis)\n");
1151   Result.BB = TrellisSucc;
1152   return Result;
1153 }
1154 
1155 /// When the option allowTailDupPlacement() is on, this method checks if the
1156 /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated
1157 /// into all of its unplaced, unfiltered predecessors, that are not BB.
1158 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1159     const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1160     const BlockChain &Chain, const BlockFilterSet *BlockFilter) {
1161   if (!shouldTailDuplicate(Succ))
1162     return false;
1163 
1164   // The result of canTailDuplicate.
1165   bool Duplicate = true;
1166   // Number of possible duplication.
1167   unsigned int NumDup = 0;
1168 
1169   // For CFG checking.
1170   SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(),
1171                                                        BB->succ_end());
1172   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1173     // Make sure all unplaced and unfiltered predecessors can be
1174     // tail-duplicated into.
1175     // Skip any blocks that are already placed or not in this loop.
1176     if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) ||
1177         (BlockToChain[Pred] == &Chain && !Succ->succ_empty()))
1178       continue;
1179     if (!TailDup.canTailDuplicate(Succ, Pred)) {
1180       if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors))
1181         // This will result in a trellis after tail duplication, so we don't
1182         // need to copy Succ into this predecessor. In the presence
1183         // of a trellis tail duplication can continue to be profitable.
1184         // For example:
1185         // A            A
1186         // |\           |\
1187         // | \          | \
1188         // |  C         |  C+BB
1189         // | /          |  |
1190         // |/           |  |
1191         // BB    =>     BB |
1192         // |\           |\/|
1193         // | \          |/\|
1194         // |  D         |  D
1195         // | /          | /
1196         // |/           |/
1197         // Succ         Succ
1198         //
1199         // After BB was duplicated into C, the layout looks like the one on the
1200         // right. BB and C now have the same successors. When considering
1201         // whether Succ can be duplicated into all its unplaced predecessors, we
1202         // ignore C.
1203         // We can do this because C already has a profitable fallthrough, namely
1204         // D. TODO(iteratee): ignore sufficiently cold predecessors for
1205         // duplication and for this test.
1206         //
1207         // This allows trellises to be laid out in 2 separate chains
1208         // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic
1209         // because it allows the creation of 2 fallthrough paths with links
1210         // between them, and we correctly identify the best layout for these
1211         // CFGs. We want to extend trellises that the user created in addition
1212         // to trellises created by tail-duplication, so we just look for the
1213         // CFG.
1214         continue;
1215       Duplicate = false;
1216       continue;
1217     }
1218     NumDup++;
1219   }
1220 
1221   // No possible duplication in current filter set.
1222   if (NumDup == 0)
1223     return false;
1224 
1225   // If profile information is available, findDuplicateCandidates can do more
1226   // precise benefit analysis.
1227   if (F->getFunction().hasProfileData())
1228     return true;
1229 
1230   // This is mainly for function exit BB.
1231   // The integrated tail duplication is really designed for increasing
1232   // fallthrough from predecessors from Succ to its successors. We may need
1233   // other machanism to handle different cases.
1234   if (Succ->succ_empty())
1235     return true;
1236 
1237   // Plus the already placed predecessor.
1238   NumDup++;
1239 
1240   // If the duplication candidate has more unplaced predecessors than
1241   // successors, the extra duplication can't bring more fallthrough.
1242   //
1243   //     Pred1 Pred2 Pred3
1244   //         \   |   /
1245   //          \  |  /
1246   //           \ | /
1247   //            Dup
1248   //            / \
1249   //           /   \
1250   //       Succ1  Succ2
1251   //
1252   // In this example Dup has 2 successors and 3 predecessors, duplication of Dup
1253   // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2,
1254   // but the duplication into Pred3 can't increase fallthrough.
1255   //
1256   // A small number of extra duplication may not hurt too much. We need a better
1257   // heuristic to handle it.
1258   if ((NumDup > Succ->succ_size()) || !Duplicate)
1259     return false;
1260 
1261   return true;
1262 }
1263 
1264 /// Find chains of triangles where we believe it would be profitable to
1265 /// tail-duplicate them all, but a local analysis would not find them.
1266 /// There are 3 ways this can be profitable:
1267 /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with
1268 ///    longer chains)
1269 /// 2) The chains are statically correlated. Branch probabilities have a very
1270 ///    U-shaped distribution.
1271 ///    [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805]
1272 ///    If the branches in a chain are likely to be from the same side of the
1273 ///    distribution as their predecessor, but are independent at runtime, this
1274 ///    transformation is profitable. (Because the cost of being wrong is a small
1275 ///    fixed cost, unlike the standard triangle layout where the cost of being
1276 ///    wrong scales with the # of triangles.)
1277 /// 3) The chains are dynamically correlated. If the probability that a previous
1278 ///    branch was taken positively influences whether the next branch will be
1279 ///    taken
1280 /// We believe that 2 and 3 are common enough to justify the small margin in 1.
1281 void MachineBlockPlacement::precomputeTriangleChains() {
1282   struct TriangleChain {
1283     std::vector<MachineBasicBlock *> Edges;
1284 
1285     TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1286         : Edges({src, dst}) {}
1287 
1288     void append(MachineBasicBlock *dst) {
1289       assert(getKey()->isSuccessor(dst) &&
1290              "Attempting to append a block that is not a successor.");
1291       Edges.push_back(dst);
1292     }
1293 
1294     unsigned count() const { return Edges.size() - 1; }
1295 
1296     MachineBasicBlock *getKey() const { return Edges.back(); }
1297   };
1298 
1299   if (TriangleChainCount == 0)
1300     return;
1301 
1302   LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n");
1303   // Map from last block to the chain that contains it. This allows us to extend
1304   // chains as we find new triangles.
1305   DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1306   for (MachineBasicBlock &BB : *F) {
1307     // If BB doesn't have 2 successors, it doesn't start a triangle.
1308     if (BB.succ_size() != 2)
1309       continue;
1310     MachineBasicBlock *PDom = nullptr;
1311     for (MachineBasicBlock *Succ : BB.successors()) {
1312       if (!MPDT->dominates(Succ, &BB))
1313         continue;
1314       PDom = Succ;
1315       break;
1316     }
1317     // If BB doesn't have a post-dominating successor, it doesn't form a
1318     // triangle.
1319     if (PDom == nullptr)
1320       continue;
1321     // If PDom has a hint that it is low probability, skip this triangle.
1322     if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100))
1323       continue;
1324     // If PDom isn't eligible for duplication, this isn't the kind of triangle
1325     // we're looking for.
1326     if (!shouldTailDuplicate(PDom))
1327       continue;
1328     bool CanTailDuplicate = true;
1329     // If PDom can't tail-duplicate into it's non-BB predecessors, then this
1330     // isn't the kind of triangle we're looking for.
1331     for (MachineBasicBlock *Pred : PDom->predecessors()) {
1332       if (Pred == &BB)
1333         continue;
1334       if (!TailDup.canTailDuplicate(PDom, Pred)) {
1335         CanTailDuplicate = false;
1336         break;
1337       }
1338     }
1339     // If we can't tail-duplicate PDom to its predecessors, then skip this
1340     // triangle.
1341     if (!CanTailDuplicate)
1342       continue;
1343 
1344     // Now we have an interesting triangle. Insert it if it's not part of an
1345     // existing chain.
1346     // Note: This cannot be replaced with a call insert() or emplace() because
1347     // the find key is BB, but the insert/emplace key is PDom.
1348     auto Found = TriangleChainMap.find(&BB);
1349     // If it is, remove the chain from the map, grow it, and put it back in the
1350     // map with the end as the new key.
1351     if (Found != TriangleChainMap.end()) {
1352       TriangleChain Chain = std::move(Found->second);
1353       TriangleChainMap.erase(Found);
1354       Chain.append(PDom);
1355       TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1356     } else {
1357       auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom);
1358       assert(InsertResult.second && "Block seen twice.");
1359       (void)InsertResult;
1360     }
1361   }
1362 
1363   // Iterating over a DenseMap is safe here, because the only thing in the body
1364   // of the loop is inserting into another DenseMap (ComputedEdges).
1365   // ComputedEdges is never iterated, so this doesn't lead to non-determinism.
1366   for (auto &ChainPair : TriangleChainMap) {
1367     TriangleChain &Chain = ChainPair.second;
1368     // Benchmarking has shown that due to branch correlation duplicating 2 or
1369     // more triangles is profitable, despite the calculations assuming
1370     // independence.
1371     if (Chain.count() < TriangleChainCount)
1372       continue;
1373     MachineBasicBlock *dst = Chain.Edges.back();
1374     Chain.Edges.pop_back();
1375     for (MachineBasicBlock *src : reverse(Chain.Edges)) {
1376       LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->"
1377                         << getBlockName(dst)
1378                         << " as pre-computed based on triangles.\n");
1379 
1380       auto InsertResult = ComputedEdges.insert({src, {dst, true}});
1381       assert(InsertResult.second && "Block seen twice.");
1382       (void)InsertResult;
1383 
1384       dst = src;
1385     }
1386   }
1387 }
1388 
1389 // When profile is not present, return the StaticLikelyProb.
1390 // When profile is available, we need to handle the triangle-shape CFG.
1391 static BranchProbability
1392 getLayoutSuccessorProbThreshold(const MachineBasicBlock *BB) {
1393   if (!BB->getParent()->getFunction().hasProfileData())
1394     return BranchProbability(StaticLikelyProb, 100);
1395   if (BB->succ_size() == 2) {
1396     const MachineBasicBlock *Succ1 = *BB->succ_begin();
1397     const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1);
1398     if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) {
1399       /* See case 1 below for the cost analysis. For BB->Succ to
1400        * be taken with smaller cost, the following needs to hold:
1401        *   Prob(BB->Succ) > 2 * Prob(BB->Pred)
1402        *   So the threshold T in the calculation below
1403        *   (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred)
1404        *   So T / (1 - T) = 2, Yielding T = 2/3
1405        * Also adding user specified branch bias, we have
1406        *   T = (2/3)*(ProfileLikelyProb/50)
1407        *     = (2*ProfileLikelyProb)/150)
1408        */
1409       return BranchProbability(2 * ProfileLikelyProb, 150);
1410     }
1411   }
1412   return BranchProbability(ProfileLikelyProb, 100);
1413 }
1414 
1415 /// Checks to see if the layout candidate block \p Succ has a better layout
1416 /// predecessor than \c BB. If yes, returns true.
1417 /// \p SuccProb: The probability adjusted for only remaining blocks.
1418 ///   Only used for logging
1419 /// \p RealSuccProb: The un-adjusted probability.
1420 /// \p Chain: The chain that BB belongs to and Succ is being considered for.
1421 /// \p BlockFilter: if non-null, the set of blocks that make up the loop being
1422 ///    considered
1423 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1424     const MachineBasicBlock *BB, const MachineBasicBlock *Succ,
1425     const BlockChain &SuccChain, BranchProbability SuccProb,
1426     BranchProbability RealSuccProb, const BlockChain &Chain,
1427     const BlockFilterSet *BlockFilter) {
1428 
1429   // There isn't a better layout when there are no unscheduled predecessors.
1430   if (SuccChain.UnscheduledPredecessors == 0)
1431     return false;
1432 
1433   // There are two basic scenarios here:
1434   // -------------------------------------
1435   // Case 1: triangular shape CFG (if-then):
1436   //     BB
1437   //     | \
1438   //     |  \
1439   //     |   Pred
1440   //     |   /
1441   //     Succ
1442   // In this case, we are evaluating whether to select edge -> Succ, e.g.
1443   // set Succ as the layout successor of BB. Picking Succ as BB's
1444   // successor breaks the CFG constraints (FIXME: define these constraints).
1445   // With this layout, Pred BB
1446   // is forced to be outlined, so the overall cost will be cost of the
1447   // branch taken from BB to Pred, plus the cost of back taken branch
1448   // from Pred to Succ, as well as the additional cost associated
1449   // with the needed unconditional jump instruction from Pred To Succ.
1450 
1451   // The cost of the topological order layout is the taken branch cost
1452   // from BB to Succ, so to make BB->Succ a viable candidate, the following
1453   // must hold:
1454   //     2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost
1455   //      < freq(BB->Succ) *  taken_branch_cost.
1456   // Ignoring unconditional jump cost, we get
1457   //    freq(BB->Succ) > 2 * freq(BB->Pred), i.e.,
1458   //    prob(BB->Succ) > 2 * prob(BB->Pred)
1459   //
1460   // When real profile data is available, we can precisely compute the
1461   // probability threshold that is needed for edge BB->Succ to be considered.
1462   // Without profile data, the heuristic requires the branch bias to be
1463   // a lot larger to make sure the signal is very strong (e.g. 80% default).
1464   // -----------------------------------------------------------------
1465   // Case 2: diamond like CFG (if-then-else):
1466   //     S
1467   //    / \
1468   //   |   \
1469   //  BB    Pred
1470   //   \    /
1471   //    Succ
1472   //    ..
1473   //
1474   // The current block is BB and edge BB->Succ is now being evaluated.
1475   // Note that edge S->BB was previously already selected because
1476   // prob(S->BB) > prob(S->Pred).
1477   // At this point, 2 blocks can be placed after BB: Pred or Succ. If we
1478   // choose Pred, we will have a topological ordering as shown on the left
1479   // in the picture below. If we choose Succ, we have the solution as shown
1480   // on the right:
1481   //
1482   //   topo-order:
1483   //
1484   //       S-----                             ---S
1485   //       |    |                             |  |
1486   //    ---BB   |                             |  BB
1487   //    |       |                             |  |
1488   //    |  Pred--                             |  Succ--
1489   //    |  |                                  |       |
1490   //    ---Succ                               ---Pred--
1491   //
1492   // cost = freq(S->Pred) + freq(BB->Succ)    cost = 2 * freq (S->Pred)
1493   //      = freq(S->Pred) + freq(S->BB)
1494   //
1495   // If we have profile data (i.e, branch probabilities can be trusted), the
1496   // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 *
1497   // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB).
1498   // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which
1499   // means the cost of topological order is greater.
1500   // When profile data is not available, however, we need to be more
1501   // conservative. If the branch prediction is wrong, breaking the topo-order
1502   // will actually yield a layout with large cost. For this reason, we need
1503   // strong biased branch at block S with Prob(S->BB) in order to select
1504   // BB->Succ. This is equivalent to looking the CFG backward with backward
1505   // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without
1506   // profile data).
1507   // --------------------------------------------------------------------------
1508   // Case 3: forked diamond
1509   //       S
1510   //      / \
1511   //     /   \
1512   //   BB    Pred
1513   //   | \   / |
1514   //   |  \ /  |
1515   //   |   X   |
1516   //   |  / \  |
1517   //   | /   \ |
1518   //   S1     S2
1519   //
1520   // The current block is BB and edge BB->S1 is now being evaluated.
1521   // As above S->BB was already selected because
1522   // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2).
1523   //
1524   // topo-order:
1525   //
1526   //     S-------|                     ---S
1527   //     |       |                     |  |
1528   //  ---BB      |                     |  BB
1529   //  |          |                     |  |
1530   //  |  Pred----|                     |  S1----
1531   //  |  |                             |       |
1532   //  --(S1 or S2)                     ---Pred--
1533   //                                        |
1534   //                                       S2
1535   //
1536   // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2)
1537   //    + min(freq(Pred->S1), freq(Pred->S2))
1538   // Non-topo-order cost:
1539   // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2).
1540   // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2))
1541   // is 0. Then the non topo layout is better when
1542   // freq(S->Pred) < freq(BB->S1).
1543   // This is exactly what is checked below.
1544   // Note there are other shapes that apply (Pred may not be a single block,
1545   // but they all fit this general pattern.)
1546   BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB);
1547 
1548   // Make sure that a hot successor doesn't have a globally more
1549   // important predecessor.
1550   BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1551   bool BadCFGConflict = false;
1552 
1553   for (MachineBasicBlock *Pred : Succ->predecessors()) {
1554     BlockChain *PredChain = BlockToChain[Pred];
1555     if (Pred == Succ || PredChain == &SuccChain ||
1556         (BlockFilter && !BlockFilter->count(Pred)) || PredChain == &Chain ||
1557         Pred != *std::prev(PredChain->end()) ||
1558         // This check is redundant except for look ahead. This function is
1559         // called for lookahead by isProfitableToTailDup when BB hasn't been
1560         // placed yet.
1561         (Pred == BB))
1562       continue;
1563     // Do backward checking.
1564     // For all cases above, we need a backward checking to filter out edges that
1565     // are not 'strongly' biased.
1566     // BB  Pred
1567     //  \ /
1568     //  Succ
1569     // We select edge BB->Succ if
1570     //      freq(BB->Succ) > freq(Succ) * HotProb
1571     //      i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) *
1572     //      HotProb
1573     //      i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb
1574     // Case 1 is covered too, because the first equation reduces to:
1575     // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle)
1576     BlockFrequency PredEdgeFreq =
1577         MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1578     if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) {
1579       BadCFGConflict = true;
1580       break;
1581     }
1582   }
1583 
1584   if (BadCFGConflict) {
1585     LLVM_DEBUG(dbgs() << "    Not a candidate: " << getBlockName(Succ) << " -> "
1586                       << SuccProb << " (prob) (non-cold CFG conflict)\n");
1587     return true;
1588   }
1589 
1590   return false;
1591 }
1592 
1593 /// Select the best successor for a block.
1594 ///
1595 /// This looks across all successors of a particular block and attempts to
1596 /// select the "best" one to be the layout successor. It only considers direct
1597 /// successors which also pass the block filter. It will attempt to avoid
1598 /// breaking CFG structure, but cave and break such structures in the case of
1599 /// very hot successor edges.
1600 ///
1601 /// \returns The best successor block found, or null if none are viable, along
1602 /// with a boolean indicating if tail duplication is necessary.
1603 MachineBlockPlacement::BlockAndTailDupResult
1604 MachineBlockPlacement::selectBestSuccessor(const MachineBasicBlock *BB,
1605                                            const BlockChain &Chain,
1606                                            const BlockFilterSet *BlockFilter) {
1607   const BranchProbability HotProb(StaticLikelyProb, 100);
1608 
1609   BlockAndTailDupResult BestSucc = {nullptr, false};
1610   auto BestProb = BranchProbability::getZero();
1611 
1612   SmallVector<MachineBasicBlock *, 4> Successors;
1613   auto AdjustedSumProb =
1614       collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1615 
1616   LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB)
1617                     << "\n");
1618 
1619   // if we already precomputed the best successor for BB, return that if still
1620   // applicable.
1621   auto FoundEdge = ComputedEdges.find(BB);
1622   if (FoundEdge != ComputedEdges.end()) {
1623     MachineBasicBlock *Succ = FoundEdge->second.BB;
1624     ComputedEdges.erase(FoundEdge);
1625     BlockChain *SuccChain = BlockToChain[Succ];
1626     if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
1627         SuccChain != &Chain && Succ == *SuccChain->begin())
1628       return FoundEdge->second;
1629   }
1630 
1631   // if BB is part of a trellis, Use the trellis to determine the optimal
1632   // fallthrough edges
1633   if (isTrellis(BB, Successors, Chain, BlockFilter))
1634     return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1635                                    BlockFilter);
1636 
1637   // For blocks with CFG violations, we may be able to lay them out anyway with
1638   // tail-duplication. We keep this vector so we can perform the probability
1639   // calculations the minimum number of times.
1640   SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4>
1641       DupCandidates;
1642   for (MachineBasicBlock *Succ : Successors) {
1643     auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1644     BranchProbability SuccProb =
1645         getAdjustedProbability(RealSuccProb, AdjustedSumProb);
1646 
1647     BlockChain &SuccChain = *BlockToChain[Succ];
1648     // Skip the edge \c BB->Succ if block \c Succ has a better layout
1649     // predecessor that yields lower global cost.
1650     if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1651                                    Chain, BlockFilter)) {
1652       // If tail duplication would make Succ profitable, place it.
1653       if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
1654         DupCandidates.emplace_back(SuccProb, Succ);
1655       continue;
1656     }
1657 
1658     LLVM_DEBUG(
1659         dbgs() << "    Candidate: " << getBlockName(Succ)
1660                << ", probability: " << SuccProb
1661                << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "")
1662                << "\n");
1663 
1664     if (BestSucc.BB && BestProb >= SuccProb) {
1665       LLVM_DEBUG(dbgs() << "    Not the best candidate, continuing\n");
1666       continue;
1667     }
1668 
1669     LLVM_DEBUG(dbgs() << "    Setting it as best candidate\n");
1670     BestSucc.BB = Succ;
1671     BestProb = SuccProb;
1672   }
1673   // Handle the tail duplication candidates in order of decreasing probability.
1674   // Stop at the first one that is profitable. Also stop if they are less
1675   // profitable than BestSucc. Position is important because we preserve it and
1676   // prefer first best match. Here we aren't comparing in order, so we capture
1677   // the position instead.
1678   llvm::stable_sort(DupCandidates,
1679                     [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1680                        std::tuple<BranchProbability, MachineBasicBlock *> R) {
1681                       return std::get<0>(L) > std::get<0>(R);
1682                     });
1683   for (auto &Tup : DupCandidates) {
1684     BranchProbability DupProb;
1685     MachineBasicBlock *Succ;
1686     std::tie(DupProb, Succ) = Tup;
1687     if (DupProb < BestProb)
1688       break;
1689     if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) &&
1690         (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1691       LLVM_DEBUG(dbgs() << "    Candidate: " << getBlockName(Succ)
1692                         << ", probability: " << DupProb
1693                         << " (Tail Duplicate)\n");
1694       BestSucc.BB = Succ;
1695       BestSucc.ShouldTailDup = true;
1696       break;
1697     }
1698   }
1699 
1700   if (BestSucc.BB)
1701     LLVM_DEBUG(dbgs() << "    Selected: " << getBlockName(BestSucc.BB) << "\n");
1702 
1703   return BestSucc;
1704 }
1705 
1706 /// Select the best block from a worklist.
1707 ///
1708 /// This looks through the provided worklist as a list of candidate basic
1709 /// blocks and select the most profitable one to place. The definition of
1710 /// profitable only really makes sense in the context of a loop. This returns
1711 /// the most frequently visited block in the worklist, which in the case of
1712 /// a loop, is the one most desirable to be physically close to the rest of the
1713 /// loop body in order to improve i-cache behavior.
1714 ///
1715 /// \returns The best block found, or null if none are viable.
1716 MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
1717     const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1718   // Once we need to walk the worklist looking for a candidate, cleanup the
1719   // worklist of already placed entries.
1720   // FIXME: If this shows up on profiles, it could be folded (at the cost of
1721   // some code complexity) into the loop below.
1722   llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) {
1723     return BlockToChain.lookup(BB) == &Chain;
1724   });
1725 
1726   if (WorkList.empty())
1727     return nullptr;
1728 
1729   bool IsEHPad = WorkList[0]->isEHPad();
1730 
1731   MachineBasicBlock *BestBlock = nullptr;
1732   BlockFrequency BestFreq;
1733   for (MachineBasicBlock *MBB : WorkList) {
1734     assert(MBB->isEHPad() == IsEHPad &&
1735            "EHPad mismatch between block and work list.");
1736 
1737     BlockChain &SuccChain = *BlockToChain[MBB];
1738     if (&SuccChain == &Chain)
1739       continue;
1740 
1741     assert(SuccChain.UnscheduledPredecessors == 0 &&
1742            "Found CFG-violating block");
1743 
1744     BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB);
1745     LLVM_DEBUG(dbgs() << "    " << getBlockName(MBB) << " -> "
1746                       << printBlockFreq(MBFI->getMBFI(), CandidateFreq)
1747                       << " (freq)\n");
1748 
1749     // For ehpad, we layout the least probable first as to avoid jumping back
1750     // from least probable landingpads to more probable ones.
1751     //
1752     // FIXME: Using probability is probably (!) not the best way to achieve
1753     // this. We should probably have a more principled approach to layout
1754     // cleanup code.
1755     //
1756     // The goal is to get:
1757     //
1758     //                 +--------------------------+
1759     //                 |                          V
1760     // InnerLp -> InnerCleanup    OuterLp -> OuterCleanup -> Resume
1761     //
1762     // Rather than:
1763     //
1764     //                 +-------------------------------------+
1765     //                 V                                     |
1766     // OuterLp -> OuterCleanup -> Resume     InnerLp -> InnerCleanup
1767     if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1768       continue;
1769 
1770     BestBlock = MBB;
1771     BestFreq = CandidateFreq;
1772   }
1773 
1774   return BestBlock;
1775 }
1776 
1777 /// Retrieve the first unplaced basic block in the entire function.
1778 ///
1779 /// This routine is called when we are unable to use the CFG to walk through
1780 /// all of the basic blocks and form a chain due to unnatural loops in the CFG.
1781 /// We walk through the function's blocks in order, starting from the
1782 /// LastUnplacedBlockIt. We update this iterator on each call to avoid
1783 /// re-scanning the entire sequence on repeated calls to this routine.
1784 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1785     const BlockChain &PlacedChain,
1786     MachineFunction::iterator &PrevUnplacedBlockIt) {
1787 
1788   for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E;
1789        ++I) {
1790     if (BlockToChain[&*I] != &PlacedChain) {
1791       PrevUnplacedBlockIt = I;
1792       // Now select the head of the chain to which the unplaced block belongs
1793       // as the block to place. This will force the entire chain to be placed,
1794       // and satisfies the requirements of merging chains.
1795       return *BlockToChain[&*I]->begin();
1796     }
1797   }
1798   return nullptr;
1799 }
1800 
1801 /// Retrieve the first unplaced basic block among the blocks in BlockFilter.
1802 ///
1803 /// This is similar to getFirstUnplacedBlock for the entire function, but since
1804 /// the size of BlockFilter is typically far less than the number of blocks in
1805 /// the entire function, iterating through the BlockFilter is more efficient.
1806 /// When processing the entire funciton, using the version without BlockFilter
1807 /// has a complexity of #(loops in function) * #(blocks in function), while this
1808 /// version has a complexity of sum(#(loops in block) foreach block in function)
1809 /// which is always smaller. For long function mostly sequential in structure,
1810 /// the complexity is amortized to 1 * #(blocks in function).
1811 MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1812     const BlockChain &PlacedChain,
1813     BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
1814     const BlockFilterSet *BlockFilter) {
1815   assert(BlockFilter);
1816   for (; PrevUnplacedBlockInFilterIt != BlockFilter->end();
1817        ++PrevUnplacedBlockInFilterIt) {
1818     BlockChain *C = BlockToChain[*PrevUnplacedBlockInFilterIt];
1819     if (C != &PlacedChain) {
1820       return *C->begin();
1821     }
1822   }
1823   return nullptr;
1824 }
1825 
1826 void MachineBlockPlacement::fillWorkLists(
1827     const MachineBasicBlock *MBB, SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1828     const BlockFilterSet *BlockFilter = nullptr) {
1829   BlockChain &Chain = *BlockToChain[MBB];
1830   if (!UpdatedPreds.insert(&Chain).second)
1831     return;
1832 
1833   assert(
1834       Chain.UnscheduledPredecessors == 0 &&
1835       "Attempting to place block with unscheduled predecessors in worklist.");
1836   for (MachineBasicBlock *ChainBB : Chain) {
1837     assert(BlockToChain[ChainBB] == &Chain &&
1838            "Block in chain doesn't match BlockToChain map.");
1839     for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1840       if (BlockFilter && !BlockFilter->count(Pred))
1841         continue;
1842       if (BlockToChain[Pred] == &Chain)
1843         continue;
1844       ++Chain.UnscheduledPredecessors;
1845     }
1846   }
1847 
1848   if (Chain.UnscheduledPredecessors != 0)
1849     return;
1850 
1851   MachineBasicBlock *BB = *Chain.begin();
1852   if (BB->isEHPad())
1853     EHPadWorkList.push_back(BB);
1854   else
1855     BlockWorkList.push_back(BB);
1856 }
1857 
1858 void MachineBlockPlacement::buildChain(const MachineBasicBlock *HeadBB,
1859                                        BlockChain &Chain,
1860                                        BlockFilterSet *BlockFilter) {
1861   assert(HeadBB && "BB must not be null.\n");
1862   assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n");
1863   MachineFunction::iterator PrevUnplacedBlockIt = F->begin();
1864   BlockFilterSet::iterator PrevUnplacedBlockInFilterIt;
1865   if (BlockFilter)
1866     PrevUnplacedBlockInFilterIt = BlockFilter->begin();
1867 
1868   const MachineBasicBlock *LoopHeaderBB = HeadBB;
1869   markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1870   MachineBasicBlock *BB = *std::prev(Chain.end());
1871   while (true) {
1872     assert(BB && "null block found at end of chain in loop.");
1873     assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop.");
1874     assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain.");
1875 
1876     // Look for the best viable successor if there is one to place immediately
1877     // after this block.
1878     auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1879     MachineBasicBlock *BestSucc = Result.BB;
1880     bool ShouldTailDup = Result.ShouldTailDup;
1881     if (allowTailDupPlacement())
1882       ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(
1883                                         BB, BestSucc, Chain, BlockFilter));
1884 
1885     // If an immediate successor isn't available, look for the best viable
1886     // block among those we've identified as not violating the loop's CFG at
1887     // this point. This won't be a fallthrough, but it will increase locality.
1888     if (!BestSucc)
1889       BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1890     if (!BestSucc)
1891       BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1892 
1893     if (!BestSucc) {
1894       if (BlockFilter)
1895         BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockInFilterIt,
1896                                          BlockFilter);
1897       else
1898         BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt);
1899       if (!BestSucc)
1900         break;
1901 
1902       LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the "
1903                            "layout successor until the CFG reduces\n");
1904     }
1905 
1906     // Placement may have changed tail duplication opportunities.
1907     // Check for that now.
1908     if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
1909       repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1910                                    BlockFilter, PrevUnplacedBlockIt,
1911                                    PrevUnplacedBlockInFilterIt);
1912       // If the chosen successor was duplicated into BB, don't bother laying
1913       // it out, just go round the loop again with BB as the chain end.
1914       if (!BB->isSuccessor(BestSucc))
1915         continue;
1916     }
1917 
1918     // Place this block, updating the datastructures to reflect its placement.
1919     BlockChain &SuccChain = *BlockToChain[BestSucc];
1920     // Zero out UnscheduledPredecessors for the successor we're about to merge
1921     // in case we selected a successor that didn't fit naturally into the CFG.
1922     SuccChain.UnscheduledPredecessors = 0;
1923     LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to "
1924                       << getBlockName(BestSucc) << "\n");
1925     markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1926     Chain.merge(BestSucc, &SuccChain);
1927     BB = *std::prev(Chain.end());
1928   }
1929 
1930   LLVM_DEBUG(dbgs() << "Finished forming chain for header block "
1931                     << getBlockName(*Chain.begin()) << "\n");
1932 }
1933 
1934 // If bottom of block BB has only one successor OldTop, in most cases it is
1935 // profitable to move it before OldTop, except the following case:
1936 //
1937 //     -->OldTop<-
1938 //     |    .    |
1939 //     |    .    |
1940 //     |    .    |
1941 //     ---Pred   |
1942 //          |    |
1943 //         BB-----
1944 //
1945 // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't
1946 // layout the other successor below it, so it can't reduce taken branch.
1947 // In this case we keep its original layout.
1948 bool MachineBlockPlacement::canMoveBottomBlockToTop(
1949     const MachineBasicBlock *BottomBlock, const MachineBasicBlock *OldTop) {
1950   if (BottomBlock->pred_size() != 1)
1951     return true;
1952   MachineBasicBlock *Pred = *BottomBlock->pred_begin();
1953   if (Pred->succ_size() != 2)
1954     return true;
1955 
1956   MachineBasicBlock *OtherBB = *Pred->succ_begin();
1957   if (OtherBB == BottomBlock)
1958     OtherBB = *Pred->succ_rbegin();
1959   if (OtherBB == OldTop)
1960     return false;
1961 
1962   return true;
1963 }
1964 
1965 // Find out the possible fall through frequence to the top of a loop.
1966 BlockFrequency
1967 MachineBlockPlacement::TopFallThroughFreq(const MachineBasicBlock *Top,
1968                                           const BlockFilterSet &LoopBlockSet) {
1969   BlockFrequency MaxFreq = BlockFrequency(0);
1970   for (MachineBasicBlock *Pred : Top->predecessors()) {
1971     BlockChain *PredChain = BlockToChain[Pred];
1972     if (!LoopBlockSet.count(Pred) &&
1973         (!PredChain || Pred == *std::prev(PredChain->end()))) {
1974       // Found a Pred block can be placed before Top.
1975       // Check if Top is the best successor of Pred.
1976       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
1977       bool TopOK = true;
1978       for (MachineBasicBlock *Succ : Pred->successors()) {
1979         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
1980         BlockChain *SuccChain = BlockToChain[Succ];
1981         // Check if Succ can be placed after Pred.
1982         // Succ should not be in any chain, or it is the head of some chain.
1983         if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
1984             (!SuccChain || Succ == *SuccChain->begin())) {
1985           TopOK = false;
1986           break;
1987         }
1988       }
1989       if (TopOK) {
1990         BlockFrequency EdgeFreq =
1991             MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Top);
1992         if (EdgeFreq > MaxFreq)
1993           MaxFreq = EdgeFreq;
1994       }
1995     }
1996   }
1997   return MaxFreq;
1998 }
1999 
2000 // Compute the fall through gains when move NewTop before OldTop.
2001 //
2002 // In following diagram, edges marked as "-" are reduced fallthrough, edges
2003 // marked as "+" are increased fallthrough, this function computes
2004 //
2005 //      SUM(increased fallthrough) - SUM(decreased fallthrough)
2006 //
2007 //              |
2008 //              | -
2009 //              V
2010 //        --->OldTop
2011 //        |     .
2012 //        |     .
2013 //       +|     .    +
2014 //        |   Pred --->
2015 //        |     |-
2016 //        |     V
2017 //        --- NewTop <---
2018 //              |-
2019 //              V
2020 //
2021 BlockFrequency MachineBlockPlacement::FallThroughGains(
2022     const MachineBasicBlock *NewTop, const MachineBasicBlock *OldTop,
2023     const MachineBasicBlock *ExitBB, const BlockFilterSet &LoopBlockSet) {
2024   BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
2025   BlockFrequency FallThrough2Exit = BlockFrequency(0);
2026   if (ExitBB)
2027     FallThrough2Exit =
2028         MBFI->getBlockFreq(NewTop) * MBPI->getEdgeProbability(NewTop, ExitBB);
2029   BlockFrequency BackEdgeFreq =
2030       MBFI->getBlockFreq(NewTop) * MBPI->getEdgeProbability(NewTop, OldTop);
2031 
2032   // Find the best Pred of NewTop.
2033   MachineBasicBlock *BestPred = nullptr;
2034   BlockFrequency FallThroughFromPred = BlockFrequency(0);
2035   for (MachineBasicBlock *Pred : NewTop->predecessors()) {
2036     if (!LoopBlockSet.count(Pred))
2037       continue;
2038     BlockChain *PredChain = BlockToChain[Pred];
2039     if (!PredChain || Pred == *std::prev(PredChain->end())) {
2040       BlockFrequency EdgeFreq =
2041           MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, NewTop);
2042       if (EdgeFreq > FallThroughFromPred) {
2043         FallThroughFromPred = EdgeFreq;
2044         BestPred = Pred;
2045       }
2046     }
2047   }
2048 
2049   // If NewTop is not placed after Pred, another successor can be placed
2050   // after Pred.
2051   BlockFrequency NewFreq = BlockFrequency(0);
2052   if (BestPred) {
2053     for (MachineBasicBlock *Succ : BestPred->successors()) {
2054       if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
2055         continue;
2056       if (ComputedEdges.contains(Succ))
2057         continue;
2058       BlockChain *SuccChain = BlockToChain[Succ];
2059       if ((SuccChain && (Succ != *SuccChain->begin())) ||
2060           (SuccChain == BlockToChain[BestPred]))
2061         continue;
2062       BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
2063                                 MBPI->getEdgeProbability(BestPred, Succ);
2064       if (EdgeFreq > NewFreq)
2065         NewFreq = EdgeFreq;
2066     }
2067     BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
2068                                   MBPI->getEdgeProbability(BestPred, NewTop);
2069     if (NewFreq > OrigEdgeFreq) {
2070       // If NewTop is not the best successor of Pred, then Pred doesn't
2071       // fallthrough to NewTop. So there is no FallThroughFromPred and
2072       // NewFreq.
2073       NewFreq = BlockFrequency(0);
2074       FallThroughFromPred = BlockFrequency(0);
2075     }
2076   }
2077 
2078   BlockFrequency Result = BlockFrequency(0);
2079   BlockFrequency Gains = BackEdgeFreq + NewFreq;
2080   BlockFrequency Lost =
2081       FallThrough2Top + FallThrough2Exit + FallThroughFromPred;
2082   if (Gains > Lost)
2083     Result = Gains - Lost;
2084   return Result;
2085 }
2086 
2087 /// Helper function of findBestLoopTop. Find the best loop top block
2088 /// from predecessors of old top.
2089 ///
2090 /// Look for a block which is strictly better than the old top for laying
2091 /// out before the old top of the loop. This looks for only two patterns:
2092 ///
2093 ///     1. a block has only one successor, the old loop top
2094 ///
2095 ///        Because such a block will always result in an unconditional jump,
2096 ///        rotating it in front of the old top is always profitable.
2097 ///
2098 ///     2. a block has two successors, one is old top, another is exit
2099 ///        and it has more than one predecessors
2100 ///
2101 ///        If it is below one of its predecessors P, only P can fall through to
2102 ///        it, all other predecessors need a jump to it, and another conditional
2103 ///        jump to loop header. If it is moved before loop header, all its
2104 ///        predecessors jump to it, then fall through to loop header. So all its
2105 ///        predecessors except P can reduce one taken branch.
2106 ///        At the same time, move it before old top increases the taken branch
2107 ///        to loop exit block, so the reduced taken branch will be compared with
2108 ///        the increased taken branch to the loop exit block.
2109 MachineBasicBlock *MachineBlockPlacement::findBestLoopTopHelper(
2110     MachineBasicBlock *OldTop, const MachineLoop &L,
2111     const BlockFilterSet &LoopBlockSet) {
2112   // Check that the header hasn't been fused with a preheader block due to
2113   // crazy branches. If it has, we need to start with the header at the top to
2114   // prevent pulling the preheader into the loop body.
2115   BlockChain &HeaderChain = *BlockToChain[OldTop];
2116   if (!LoopBlockSet.count(*HeaderChain.begin()))
2117     return OldTop;
2118   if (OldTop != *HeaderChain.begin())
2119     return OldTop;
2120 
2121   LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop)
2122                     << "\n");
2123 
2124   BlockFrequency BestGains = BlockFrequency(0);
2125   MachineBasicBlock *BestPred = nullptr;
2126   for (MachineBasicBlock *Pred : OldTop->predecessors()) {
2127     if (!LoopBlockSet.count(Pred))
2128       continue;
2129     if (Pred == L.getHeader())
2130       continue;
2131     LLVM_DEBUG(dbgs() << "   old top pred: " << getBlockName(Pred) << ", has "
2132                       << Pred->succ_size() << " successors, "
2133                       << printBlockFreq(MBFI->getMBFI(), *Pred) << " freq\n");
2134     if (Pred->succ_size() > 2)
2135       continue;
2136 
2137     MachineBasicBlock *OtherBB = nullptr;
2138     if (Pred->succ_size() == 2) {
2139       OtherBB = *Pred->succ_begin();
2140       if (OtherBB == OldTop)
2141         OtherBB = *Pred->succ_rbegin();
2142     }
2143 
2144     if (!canMoveBottomBlockToTop(Pred, OldTop))
2145       continue;
2146 
2147     BlockFrequency Gains =
2148         FallThroughGains(Pred, OldTop, OtherBB, LoopBlockSet);
2149     if ((Gains > BlockFrequency(0)) &&
2150         (Gains > BestGains ||
2151          ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
2152       BestPred = Pred;
2153       BestGains = Gains;
2154     }
2155   }
2156 
2157   // If no direct predecessor is fine, just use the loop header.
2158   if (!BestPred) {
2159     LLVM_DEBUG(dbgs() << "    final top unchanged\n");
2160     return OldTop;
2161   }
2162 
2163   // Walk backwards through any straight line of predecessors.
2164   while (BestPred->pred_size() == 1 &&
2165          (*BestPred->pred_begin())->succ_size() == 1 &&
2166          *BestPred->pred_begin() != L.getHeader())
2167     BestPred = *BestPred->pred_begin();
2168 
2169   LLVM_DEBUG(dbgs() << "    final top: " << getBlockName(BestPred) << "\n");
2170   return BestPred;
2171 }
2172 
2173 /// Find the best loop top block for layout.
2174 ///
2175 /// This function iteratively calls findBestLoopTopHelper, until no new better
2176 /// BB can be found.
2177 MachineBasicBlock *
2178 MachineBlockPlacement::findBestLoopTop(const MachineLoop &L,
2179                                        const BlockFilterSet &LoopBlockSet) {
2180   // Placing the latch block before the header may introduce an extra branch
2181   // that skips this block the first time the loop is executed, which we want
2182   // to avoid when optimising for size.
2183   // FIXME: in theory there is a case that does not introduce a new branch,
2184   // i.e. when the layout predecessor does not fallthrough to the loop header.
2185   // In practice this never happens though: there always seems to be a preheader
2186   // that can fallthrough and that is also placed before the header.
2187   bool OptForSize = F->getFunction().hasOptSize() ||
2188                     llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get());
2189   if (OptForSize)
2190     return L.getHeader();
2191 
2192   MachineBasicBlock *OldTop = nullptr;
2193   MachineBasicBlock *NewTop = L.getHeader();
2194   while (NewTop != OldTop) {
2195     OldTop = NewTop;
2196     NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2197     if (NewTop != OldTop)
2198       ComputedEdges[NewTop] = {OldTop, false};
2199   }
2200   return NewTop;
2201 }
2202 
2203 /// Find the best loop exiting block for layout.
2204 ///
2205 /// This routine implements the logic to analyze the loop looking for the best
2206 /// block to layout at the top of the loop. Typically this is done to maximize
2207 /// fallthrough opportunities.
2208 MachineBasicBlock *
2209 MachineBlockPlacement::findBestLoopExit(const MachineLoop &L,
2210                                         const BlockFilterSet &LoopBlockSet,
2211                                         BlockFrequency &ExitFreq) {
2212   // We don't want to layout the loop linearly in all cases. If the loop header
2213   // is just a normal basic block in the loop, we want to look for what block
2214   // within the loop is the best one to layout at the top. However, if the loop
2215   // header has be pre-merged into a chain due to predecessors not having
2216   // analyzable branches, *and* the predecessor it is merged with is *not* part
2217   // of the loop, rotating the header into the middle of the loop will create
2218   // a non-contiguous range of blocks which is Very Bad. So start with the
2219   // header and only rotate if safe.
2220   BlockChain &HeaderChain = *BlockToChain[L.getHeader()];
2221   if (!LoopBlockSet.count(*HeaderChain.begin()))
2222     return nullptr;
2223 
2224   BlockFrequency BestExitEdgeFreq;
2225   unsigned BestExitLoopDepth = 0;
2226   MachineBasicBlock *ExitingBB = nullptr;
2227   // If there are exits to outer loops, loop rotation can severely limit
2228   // fallthrough opportunities unless it selects such an exit. Keep a set of
2229   // blocks where rotating to exit with that block will reach an outer loop.
2230   SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
2231 
2232   LLVM_DEBUG(dbgs() << "Finding best loop exit for: "
2233                     << getBlockName(L.getHeader()) << "\n");
2234   for (MachineBasicBlock *MBB : L.getBlocks()) {
2235     BlockChain &Chain = *BlockToChain[MBB];
2236     // Ensure that this block is at the end of a chain; otherwise it could be
2237     // mid-way through an inner loop or a successor of an unanalyzable branch.
2238     if (MBB != *std::prev(Chain.end()))
2239       continue;
2240 
2241     // Now walk the successors. We need to establish whether this has a viable
2242     // exiting successor and whether it has a viable non-exiting successor.
2243     // We store the old exiting state and restore it if a viable looping
2244     // successor isn't found.
2245     MachineBasicBlock *OldExitingBB = ExitingBB;
2246     BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2247     bool HasLoopingSucc = false;
2248     for (MachineBasicBlock *Succ : MBB->successors()) {
2249       if (Succ->isEHPad())
2250         continue;
2251       if (Succ == MBB)
2252         continue;
2253       BlockChain &SuccChain = *BlockToChain[Succ];
2254       // Don't split chains, either this chain or the successor's chain.
2255       if (&Chain == &SuccChain) {
2256         LLVM_DEBUG(dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
2257                           << getBlockName(Succ) << " (chain conflict)\n");
2258         continue;
2259       }
2260 
2261       auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
2262       if (LoopBlockSet.count(Succ)) {
2263         LLVM_DEBUG(dbgs() << "    looping: " << getBlockName(MBB) << " -> "
2264                           << getBlockName(Succ) << " (" << SuccProb << ")\n");
2265         HasLoopingSucc = true;
2266         continue;
2267       }
2268 
2269       unsigned SuccLoopDepth = 0;
2270       if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
2271         SuccLoopDepth = ExitLoop->getLoopDepth();
2272         if (ExitLoop->contains(&L))
2273           BlocksExitingToOuterLoop.insert(MBB);
2274       }
2275 
2276       BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
2277       LLVM_DEBUG(
2278           dbgs() << "    exiting: " << getBlockName(MBB) << " -> "
2279                  << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] ("
2280                  << printBlockFreq(MBFI->getMBFI(), ExitEdgeFreq) << ")\n");
2281       // Note that we bias this toward an existing layout successor to retain
2282       // incoming order in the absence of better information. The exit must have
2283       // a frequency higher than the current exit before we consider breaking
2284       // the layout.
2285       BranchProbability Bias(100 - ExitBlockBias, 100);
2286       if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2287           ExitEdgeFreq > BestExitEdgeFreq ||
2288           (MBB->isLayoutSuccessor(Succ) &&
2289            !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2290         BestExitEdgeFreq = ExitEdgeFreq;
2291         ExitingBB = MBB;
2292       }
2293     }
2294 
2295     if (!HasLoopingSucc) {
2296       // Restore the old exiting state, no viable looping successor was found.
2297       ExitingBB = OldExitingBB;
2298       BestExitEdgeFreq = OldBestExitEdgeFreq;
2299     }
2300   }
2301   // Without a candidate exiting block or with only a single block in the
2302   // loop, just use the loop header to layout the loop.
2303   if (!ExitingBB) {
2304     LLVM_DEBUG(
2305         dbgs() << "    No other candidate exit blocks, using loop header\n");
2306     return nullptr;
2307   }
2308   if (L.getNumBlocks() == 1) {
2309     LLVM_DEBUG(dbgs() << "    Loop has 1 block, using loop header as exit\n");
2310     return nullptr;
2311   }
2312 
2313   // Also, if we have exit blocks which lead to outer loops but didn't select
2314   // one of them as the exiting block we are rotating toward, disable loop
2315   // rotation altogether.
2316   if (!BlocksExitingToOuterLoop.empty() &&
2317       !BlocksExitingToOuterLoop.count(ExitingBB))
2318     return nullptr;
2319 
2320   LLVM_DEBUG(dbgs() << "  Best exiting block: " << getBlockName(ExitingBB)
2321                     << "\n");
2322   ExitFreq = BestExitEdgeFreq;
2323   return ExitingBB;
2324 }
2325 
2326 /// Check if there is a fallthrough to loop header Top.
2327 ///
2328 ///   1. Look for a Pred that can be layout before Top.
2329 ///   2. Check if Top is the most possible successor of Pred.
2330 bool MachineBlockPlacement::hasViableTopFallthrough(
2331     const MachineBasicBlock *Top, const BlockFilterSet &LoopBlockSet) {
2332   for (MachineBasicBlock *Pred : Top->predecessors()) {
2333     BlockChain *PredChain = BlockToChain[Pred];
2334     if (!LoopBlockSet.count(Pred) &&
2335         (!PredChain || Pred == *std::prev(PredChain->end()))) {
2336       // Found a Pred block can be placed before Top.
2337       // Check if Top is the best successor of Pred.
2338       auto TopProb = MBPI->getEdgeProbability(Pred, Top);
2339       bool TopOK = true;
2340       for (MachineBasicBlock *Succ : Pred->successors()) {
2341         auto SuccProb = MBPI->getEdgeProbability(Pred, Succ);
2342         BlockChain *SuccChain = BlockToChain[Succ];
2343         // Check if Succ can be placed after Pred.
2344         // Succ should not be in any chain, or it is the head of some chain.
2345         if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2346           TopOK = false;
2347           break;
2348         }
2349       }
2350       if (TopOK)
2351         return true;
2352     }
2353   }
2354   return false;
2355 }
2356 
2357 /// Attempt to rotate an exiting block to the bottom of the loop.
2358 ///
2359 /// Once we have built a chain, try to rotate it to line up the hot exit block
2360 /// with fallthrough out of the loop if doing so doesn't introduce unnecessary
2361 /// branches. For example, if the loop has fallthrough into its header and out
2362 /// of its bottom already, don't rotate it.
2363 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2364                                        const MachineBasicBlock *ExitingBB,
2365                                        BlockFrequency ExitFreq,
2366                                        const BlockFilterSet &LoopBlockSet) {
2367   if (!ExitingBB)
2368     return;
2369 
2370   MachineBasicBlock *Top = *LoopChain.begin();
2371   MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2372 
2373   // If ExitingBB is already the last one in a chain then nothing to do.
2374   if (Bottom == ExitingBB)
2375     return;
2376 
2377   // The entry block should always be the first BB in a function.
2378   if (Top->isEntryBlock())
2379     return;
2380 
2381   bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2382 
2383   // If the header has viable fallthrough, check whether the current loop
2384   // bottom is a viable exiting block. If so, bail out as rotating will
2385   // introduce an unnecessary branch.
2386   if (ViableTopFallthrough) {
2387     for (MachineBasicBlock *Succ : Bottom->successors()) {
2388       BlockChain *SuccChain = BlockToChain[Succ];
2389       if (!LoopBlockSet.count(Succ) &&
2390           (!SuccChain || Succ == *SuccChain->begin()))
2391         return;
2392     }
2393 
2394     // Rotate will destroy the top fallthrough, we need to ensure the new exit
2395     // frequency is larger than top fallthrough.
2396     BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2397     if (FallThrough2Top >= ExitFreq)
2398       return;
2399   }
2400 
2401   BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB);
2402   if (ExitIt == LoopChain.end())
2403     return;
2404 
2405   // Rotating a loop exit to the bottom when there is a fallthrough to top
2406   // trades the entry fallthrough for an exit fallthrough.
2407   // If there is no bottom->top edge, but the chosen exit block does have
2408   // a fallthrough, we break that fallthrough for nothing in return.
2409 
2410   // Let's consider an example. We have a built chain of basic blocks
2411   // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block.
2412   // By doing a rotation we get
2413   // Bk+1, ..., Bn, B1, ..., Bk
2414   // Break of fallthrough to B1 is compensated by a fallthrough from Bk.
2415   // If we had a fallthrough Bk -> Bk+1 it is broken now.
2416   // It might be compensated by fallthrough Bn -> B1.
2417   // So we have a condition to avoid creation of extra branch by loop rotation.
2418   // All below must be true to avoid loop rotation:
2419   //   If there is a fallthrough to top (B1)
2420   //   There was fallthrough from chosen exit block (Bk) to next one (Bk+1)
2421   //   There is no fallthrough from bottom (Bn) to top (B1).
2422   // Please note that there is no exit fallthrough from Bn because we checked it
2423   // above.
2424   if (ViableTopFallthrough) {
2425     assert(std::next(ExitIt) != LoopChain.end() &&
2426            "Exit should not be last BB");
2427     MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2428     if (ExitingBB->isSuccessor(NextBlockInChain))
2429       if (!Bottom->isSuccessor(Top))
2430         return;
2431   }
2432 
2433   LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB)
2434                     << " at bottom\n");
2435   std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2436 }
2437 
2438 /// Attempt to rotate a loop based on profile data to reduce branch cost.
2439 ///
2440 /// With profile data, we can determine the cost in terms of missed fall through
2441 /// opportunities when rotating a loop chain and select the best rotation.
2442 /// Basically, there are three kinds of cost to consider for each rotation:
2443 ///    1. The possibly missed fall through edge (if it exists) from BB out of
2444 ///    the loop to the loop header.
2445 ///    2. The possibly missed fall through edges (if they exist) from the loop
2446 ///    exits to BB out of the loop.
2447 ///    3. The missed fall through edge (if it exists) from the last BB to the
2448 ///    first BB in the loop chain.
2449 ///  Therefore, the cost for a given rotation is the sum of costs listed above.
2450 ///  We select the best rotation with the smallest cost.
2451 void MachineBlockPlacement::rotateLoopWithProfile(
2452     BlockChain &LoopChain, const MachineLoop &L,
2453     const BlockFilterSet &LoopBlockSet) {
2454   auto RotationPos = LoopChain.end();
2455   MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2456 
2457   // The entry block should always be the first BB in a function.
2458   if (ChainHeaderBB->isEntryBlock())
2459     return;
2460 
2461   BlockFrequency SmallestRotationCost = BlockFrequency::max();
2462 
2463   // A utility lambda that scales up a block frequency by dividing it by a
2464   // branch probability which is the reciprocal of the scale.
2465   auto ScaleBlockFrequency = [](BlockFrequency Freq,
2466                                 unsigned Scale) -> BlockFrequency {
2467     if (Scale == 0)
2468       return BlockFrequency(0);
2469     // Use operator / between BlockFrequency and BranchProbability to implement
2470     // saturating multiplication.
2471     return Freq / BranchProbability(1, Scale);
2472   };
2473 
2474   // Compute the cost of the missed fall-through edge to the loop header if the
2475   // chain head is not the loop header. As we only consider natural loops with
2476   // single header, this computation can be done only once.
2477   BlockFrequency HeaderFallThroughCost(0);
2478   for (auto *Pred : ChainHeaderBB->predecessors()) {
2479     BlockChain *PredChain = BlockToChain[Pred];
2480     if (!LoopBlockSet.count(Pred) &&
2481         (!PredChain || Pred == *std::prev(PredChain->end()))) {
2482       auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2483                       MBPI->getEdgeProbability(Pred, ChainHeaderBB);
2484       auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost);
2485       // If the predecessor has only an unconditional jump to the header, we
2486       // need to consider the cost of this jump.
2487       if (Pred->succ_size() == 1)
2488         FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost);
2489       HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2490     }
2491   }
2492 
2493   // Here we collect all exit blocks in the loop, and for each exit we find out
2494   // its hottest exit edge. For each loop rotation, we define the loop exit cost
2495   // as the sum of frequencies of exit edges we collect here, excluding the exit
2496   // edge from the tail of the loop chain.
2497   SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq;
2498   for (auto *BB : LoopChain) {
2499     auto LargestExitEdgeProb = BranchProbability::getZero();
2500     for (auto *Succ : BB->successors()) {
2501       BlockChain *SuccChain = BlockToChain[Succ];
2502       if (!LoopBlockSet.count(Succ) &&
2503           (!SuccChain || Succ == *SuccChain->begin())) {
2504         auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2505         LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2506       }
2507     }
2508     if (LargestExitEdgeProb > BranchProbability::getZero()) {
2509       auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2510       ExitsWithFreq.emplace_back(BB, ExitFreq);
2511     }
2512   }
2513 
2514   // In this loop we iterate every block in the loop chain and calculate the
2515   // cost assuming the block is the head of the loop chain. When the loop ends,
2516   // we should have found the best candidate as the loop chain's head.
2517   for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2518             EndIter = LoopChain.end();
2519        Iter != EndIter; Iter++, TailIter++) {
2520     // TailIter is used to track the tail of the loop chain if the block we are
2521     // checking (pointed by Iter) is the head of the chain.
2522     if (TailIter == LoopChain.end())
2523       TailIter = LoopChain.begin();
2524 
2525     auto TailBB = *TailIter;
2526 
2527     // Calculate the cost by putting this BB to the top.
2528     BlockFrequency Cost = BlockFrequency(0);
2529 
2530     // If the current BB is the loop header, we need to take into account the
2531     // cost of the missed fall through edge from outside of the loop to the
2532     // header.
2533     if (Iter != LoopChain.begin())
2534       Cost += HeaderFallThroughCost;
2535 
2536     // Collect the loop exit cost by summing up frequencies of all exit edges
2537     // except the one from the chain tail.
2538     for (auto &ExitWithFreq : ExitsWithFreq)
2539       if (TailBB != ExitWithFreq.first)
2540         Cost += ExitWithFreq.second;
2541 
2542     // The cost of breaking the once fall-through edge from the tail to the top
2543     // of the loop chain. Here we need to consider three cases:
2544     // 1. If the tail node has only one successor, then we will get an
2545     //    additional jmp instruction. So the cost here is (MisfetchCost +
2546     //    JumpInstCost) * tail node frequency.
2547     // 2. If the tail node has two successors, then we may still get an
2548     //    additional jmp instruction if the layout successor after the loop
2549     //    chain is not its CFG successor. Note that the more frequently executed
2550     //    jmp instruction will be put ahead of the other one. Assume the
2551     //    frequency of those two branches are x and y, where x is the frequency
2552     //    of the edge to the chain head, then the cost will be
2553     //    (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency.
2554     // 3. If the tail node has more than two successors (this rarely happens),
2555     //    we won't consider any additional cost.
2556     if (TailBB->isSuccessor(*Iter)) {
2557       auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2558       if (TailBB->succ_size() == 1)
2559         Cost += ScaleBlockFrequency(TailBBFreq, MisfetchCost + JumpInstCost);
2560       else if (TailBB->succ_size() == 2) {
2561         auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2562         auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2563         auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2564                                   ? TailBBFreq * TailToHeadProb.getCompl()
2565                                   : TailToHeadFreq;
2566         Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) +
2567                 ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost);
2568       }
2569     }
2570 
2571     LLVM_DEBUG(dbgs() << "The cost of loop rotation by making "
2572                       << getBlockName(*Iter) << " to the top: "
2573                       << printBlockFreq(MBFI->getMBFI(), Cost) << "\n");
2574 
2575     if (Cost < SmallestRotationCost) {
2576       SmallestRotationCost = Cost;
2577       RotationPos = Iter;
2578     }
2579   }
2580 
2581   if (RotationPos != LoopChain.end()) {
2582     LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos)
2583                       << " to the top\n");
2584     std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2585   }
2586 }
2587 
2588 /// Collect blocks in the given loop that are to be placed.
2589 ///
2590 /// When profile data is available, exclude cold blocks from the returned set;
2591 /// otherwise, collect all blocks in the loop.
2592 MachineBlockPlacement::BlockFilterSet
2593 MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) {
2594   // Collect the blocks in a set ordered by block number, as this gives the same
2595   // order as they appear in the function.
2596   struct MBBCompare {
2597     bool operator()(const MachineBasicBlock *X,
2598                     const MachineBasicBlock *Y) const {
2599       return X->getNumber() < Y->getNumber();
2600     }
2601   };
2602   std::set<const MachineBasicBlock *, MBBCompare> LoopBlockSet;
2603 
2604   // Filter cold blocks off from LoopBlockSet when profile data is available.
2605   // Collect the sum of frequencies of incoming edges to the loop header from
2606   // outside. If we treat the loop as a super block, this is the frequency of
2607   // the loop. Then for each block in the loop, we calculate the ratio between
2608   // its frequency and the frequency of the loop block. When it is too small,
2609   // don't add it to the loop chain. If there are outer loops, then this block
2610   // will be merged into the first outer loop chain for which this block is not
2611   // cold anymore. This needs precise profile data and we only do this when
2612   // profile data is available.
2613   if (F->getFunction().hasProfileData() || ForceLoopColdBlock) {
2614     BlockFrequency LoopFreq(0);
2615     for (auto *LoopPred : L.getHeader()->predecessors())
2616       if (!L.contains(LoopPred))
2617         LoopFreq += MBFI->getBlockFreq(LoopPred) *
2618                     MBPI->getEdgeProbability(LoopPred, L.getHeader());
2619 
2620     for (MachineBasicBlock *LoopBB : L.getBlocks()) {
2621       if (LoopBlockSet.count(LoopBB))
2622         continue;
2623       auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2624       if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio)
2625         continue;
2626       BlockChain *Chain = BlockToChain[LoopBB];
2627       for (MachineBasicBlock *ChainBB : *Chain)
2628         LoopBlockSet.insert(ChainBB);
2629     }
2630   } else
2631     LoopBlockSet.insert(L.block_begin(), L.block_end());
2632 
2633   // Copy the blocks into a BlockFilterSet, as iterating it is faster than
2634   // std::set. We will only remove blocks and never insert them, which will
2635   // preserve the ordering.
2636   BlockFilterSet Ret(LoopBlockSet.begin(), LoopBlockSet.end());
2637   return Ret;
2638 }
2639 
2640 /// Forms basic block chains from the natural loop structures.
2641 ///
2642 /// These chains are designed to preserve the existing *structure* of the code
2643 /// as much as possible. We can then stitch the chains together in a way which
2644 /// both preserves the topological structure and minimizes taken conditional
2645 /// branches.
2646 void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) {
2647   // First recurse through any nested loops, building chains for those inner
2648   // loops.
2649   for (const MachineLoop *InnerLoop : L)
2650     buildLoopChains(*InnerLoop);
2651 
2652   assert(BlockWorkList.empty() &&
2653          "BlockWorkList not empty when starting to build loop chains.");
2654   assert(EHPadWorkList.empty() &&
2655          "EHPadWorkList not empty when starting to build loop chains.");
2656   BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2657 
2658   // Check if we have profile data for this function. If yes, we will rotate
2659   // this loop by modeling costs more precisely which requires the profile data
2660   // for better layout.
2661   bool RotateLoopWithProfile =
2662       ForcePreciseRotationCost ||
2663       (PreciseRotationCost && F->getFunction().hasProfileData());
2664 
2665   // First check to see if there is an obviously preferable top block for the
2666   // loop. This will default to the header, but may end up as one of the
2667   // predecessors to the header if there is one which will result in strictly
2668   // fewer branches in the loop body.
2669   MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
2670 
2671   // If we selected just the header for the loop top, look for a potentially
2672   // profitable exit block in the event that rotating the loop can eliminate
2673   // branches by placing an exit edge at the bottom.
2674   //
2675   // Loops are processed innermost to uttermost, make sure we clear
2676   // PreferredLoopExit before processing a new loop.
2677   PreferredLoopExit = nullptr;
2678   BlockFrequency ExitFreq;
2679   if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2680     PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2681 
2682   BlockChain &LoopChain = *BlockToChain[LoopTop];
2683 
2684   // FIXME: This is a really lame way of walking the chains in the loop: we
2685   // walk the blocks, and use a set to prevent visiting a particular chain
2686   // twice.
2687   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2688   assert(LoopChain.UnscheduledPredecessors == 0 &&
2689          "LoopChain should not have unscheduled predecessors.");
2690   UpdatedPreds.insert(&LoopChain);
2691 
2692   for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2693     fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2694 
2695   buildChain(LoopTop, LoopChain, &LoopBlockSet);
2696 
2697   if (RotateLoopWithProfile)
2698     rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2699   else
2700     rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
2701 
2702   LLVM_DEBUG({
2703     // Crash at the end so we get all of the debugging output first.
2704     bool BadLoop = false;
2705     if (LoopChain.UnscheduledPredecessors) {
2706       BadLoop = true;
2707       dbgs() << "Loop chain contains a block without its preds placed!\n"
2708              << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2709              << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n";
2710     }
2711     for (MachineBasicBlock *ChainBB : LoopChain) {
2712       dbgs() << "          ... " << getBlockName(ChainBB) << "\n";
2713       if (!LoopBlockSet.remove(ChainBB)) {
2714         // We don't mark the loop as bad here because there are real situations
2715         // where this can occur. For example, with an unanalyzable fallthrough
2716         // from a loop block to a non-loop block or vice versa.
2717         dbgs() << "Loop chain contains a block not contained by the loop!\n"
2718                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2719                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2720                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2721       }
2722     }
2723 
2724     if (!LoopBlockSet.empty()) {
2725       BadLoop = true;
2726       for (const MachineBasicBlock *LoopBB : LoopBlockSet)
2727         dbgs() << "Loop contains blocks never placed into a chain!\n"
2728                << "  Loop header:  " << getBlockName(*L.block_begin()) << "\n"
2729                << "  Chain header: " << getBlockName(*LoopChain.begin()) << "\n"
2730                << "  Bad block:    " << getBlockName(LoopBB) << "\n";
2731     }
2732     assert(!BadLoop && "Detected problems with the placement of this loop.");
2733   });
2734 
2735   BlockWorkList.clear();
2736   EHPadWorkList.clear();
2737 }
2738 
2739 void MachineBlockPlacement::buildCFGChains() {
2740   // Ensure that every BB in the function has an associated chain to simplify
2741   // the assumptions of the remaining algorithm.
2742   SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
2743   for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE;
2744        ++FI) {
2745     MachineBasicBlock *BB = &*FI;
2746     BlockChain *Chain =
2747         new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2748     // Also, merge any blocks which we cannot reason about and must preserve
2749     // the exact fallthrough behavior for.
2750     while (true) {
2751       Cond.clear();
2752       MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2753       if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2754         break;
2755 
2756       MachineFunction::iterator NextFI = std::next(FI);
2757       MachineBasicBlock *NextBB = &*NextFI;
2758       // Ensure that the layout successor is a viable block, as we know that
2759       // fallthrough is a possibility.
2760       assert(NextFI != FE && "Can't fallthrough past the last block.");
2761       LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: "
2762                         << getBlockName(BB) << " -> " << getBlockName(NextBB)
2763                         << "\n");
2764       Chain->merge(NextBB, nullptr);
2765 #ifndef NDEBUG
2766       BlocksWithUnanalyzableExits.insert(&*BB);
2767 #endif
2768       FI = NextFI;
2769       BB = NextBB;
2770     }
2771   }
2772 
2773   // Build any loop-based chains.
2774   PreferredLoopExit = nullptr;
2775   for (MachineLoop *L : *MLI)
2776     buildLoopChains(*L);
2777 
2778   assert(BlockWorkList.empty() &&
2779          "BlockWorkList should be empty before building final chain.");
2780   assert(EHPadWorkList.empty() &&
2781          "EHPadWorkList should be empty before building final chain.");
2782 
2783   SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2784   for (MachineBasicBlock &MBB : *F)
2785     fillWorkLists(&MBB, UpdatedPreds);
2786 
2787   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2788   buildChain(&F->front(), FunctionChain);
2789 
2790 #ifndef NDEBUG
2791   using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
2792 #endif
2793   LLVM_DEBUG({
2794     // Crash at the end so we get all of the debugging output first.
2795     bool BadFunc = false;
2796     FunctionBlockSetType FunctionBlockSet;
2797     for (MachineBasicBlock &MBB : *F)
2798       FunctionBlockSet.insert(&MBB);
2799 
2800     for (MachineBasicBlock *ChainBB : FunctionChain)
2801       if (!FunctionBlockSet.erase(ChainBB)) {
2802         BadFunc = true;
2803         dbgs() << "Function chain contains a block not in the function!\n"
2804                << "  Bad block:    " << getBlockName(ChainBB) << "\n";
2805       }
2806 
2807     if (!FunctionBlockSet.empty()) {
2808       BadFunc = true;
2809       for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2810         dbgs() << "Function contains blocks never placed into a chain!\n"
2811                << "  Bad block:    " << getBlockName(RemainingBB) << "\n";
2812     }
2813     assert(!BadFunc && "Detected problems with the block placement.");
2814   });
2815 
2816   // Remember original layout ordering, so we can update terminators after
2817   // reordering to point to the original layout successor.
2818   SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
2819       F->getNumBlockIDs());
2820   {
2821     MachineBasicBlock *LastMBB = nullptr;
2822     for (auto &MBB : *F) {
2823       if (LastMBB != nullptr)
2824         OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB;
2825       LastMBB = &MBB;
2826     }
2827     OriginalLayoutSuccessors[F->back().getNumber()] = nullptr;
2828   }
2829 
2830   // Splice the blocks into place.
2831   MachineFunction::iterator InsertPos = F->begin();
2832   LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n");
2833   for (MachineBasicBlock *ChainBB : FunctionChain) {
2834     LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain "
2835                                                             : "          ... ")
2836                       << getBlockName(ChainBB) << "\n");
2837     if (InsertPos != MachineFunction::iterator(ChainBB))
2838       F->splice(InsertPos, ChainBB);
2839     else
2840       ++InsertPos;
2841 
2842     // Update the terminator of the previous block.
2843     if (ChainBB == *FunctionChain.begin())
2844       continue;
2845     MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB));
2846 
2847     // FIXME: It would be awesome of updateTerminator would just return rather
2848     // than assert when the branch cannot be analyzed in order to remove this
2849     // boiler plate.
2850     Cond.clear();
2851     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2852 
2853 #ifndef NDEBUG
2854     if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2855       // Given the exact block placement we chose, we may actually not _need_ to
2856       // be able to edit PrevBB's terminator sequence, but not being _able_ to
2857       // do that at this point is a bug.
2858       assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) ||
2859               !PrevBB->canFallThrough()) &&
2860              "Unexpected block with un-analyzable fallthrough!");
2861       Cond.clear();
2862       TBB = FBB = nullptr;
2863     }
2864 #endif
2865 
2866     // The "PrevBB" is not yet updated to reflect current code layout, so,
2867     //   o. it may fall-through to a block without explicit "goto" instruction
2868     //      before layout, and no longer fall-through it after layout; or
2869     //   o. just opposite.
2870     //
2871     // analyzeBranch() may return erroneous value for FBB when these two
2872     // situations take place. For the first scenario FBB is mistakenly set NULL;
2873     // for the 2nd scenario, the FBB, which is expected to be NULL, is
2874     // mistakenly pointing to "*BI".
2875     // Thus, if the future change needs to use FBB before the layout is set, it
2876     // has to correct FBB first by using the code similar to the following:
2877     //
2878     // if (!Cond.empty() && (!FBB || FBB == ChainBB)) {
2879     //   PrevBB->updateTerminator();
2880     //   Cond.clear();
2881     //   TBB = FBB = nullptr;
2882     //   if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2883     //     // FIXME: This should never take place.
2884     //     TBB = FBB = nullptr;
2885     //   }
2886     // }
2887     if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) {
2888       PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2889     }
2890   }
2891 
2892   // Fixup the last block.
2893   Cond.clear();
2894   MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2895   if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) {
2896     MachineBasicBlock *PrevBB = &F->back();
2897     PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]);
2898   }
2899 
2900   BlockWorkList.clear();
2901   EHPadWorkList.clear();
2902 }
2903 
2904 void MachineBlockPlacement::optimizeBranches() {
2905   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2906   SmallVector<MachineOperand, 4> Cond; // For analyzeBranch.
2907 
2908   // Now that all the basic blocks in the chain have the proper layout,
2909   // make a final call to analyzeBranch with AllowModify set.
2910   // Indeed, the target may be able to optimize the branches in a way we
2911   // cannot because all branches may not be analyzable.
2912   // E.g., the target may be able to remove an unconditional branch to
2913   // a fallthrough when it occurs after predicated terminators.
2914   for (MachineBasicBlock *ChainBB : FunctionChain) {
2915     Cond.clear();
2916     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2917     if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) {
2918       // If PrevBB has a two-way branch, try to re-order the branches
2919       // such that we branch to the successor with higher probability first.
2920       if (TBB && !Cond.empty() && FBB &&
2921           MBPI->getEdgeProbability(ChainBB, FBB) >
2922               MBPI->getEdgeProbability(ChainBB, TBB) &&
2923           !TII->reverseBranchCondition(Cond)) {
2924         LLVM_DEBUG(dbgs() << "Reverse order of the two branches: "
2925                           << getBlockName(ChainBB) << "\n");
2926         LLVM_DEBUG(dbgs() << "    Edge probability: "
2927                           << MBPI->getEdgeProbability(ChainBB, FBB) << " vs "
2928                           << MBPI->getEdgeProbability(ChainBB, TBB) << "\n");
2929         DebugLoc dl; // FIXME: this is nowhere
2930         TII->removeBranch(*ChainBB);
2931         TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl);
2932       }
2933     }
2934   }
2935 }
2936 
2937 void MachineBlockPlacement::alignBlocks() {
2938   // Walk through the backedges of the function now that we have fully laid out
2939   // the basic blocks and align the destination of each backedge. We don't rely
2940   // exclusively on the loop info here so that we can align backedges in
2941   // unnatural CFGs and backedges that were introduced purely because of the
2942   // loop rotations done during this layout pass.
2943   if (!AlignAllBlock && !AlignAllNonFallThruBlocks) {
2944     if (F->getFunction().hasMinSize() ||
2945         (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize()))
2946       return;
2947   }
2948 
2949   BlockChain &FunctionChain = *BlockToChain[&F->front()];
2950   // Empty chain.
2951   if (FunctionChain.begin() == FunctionChain.end())
2952     return;
2953 
2954   const BranchProbability ColdProb(1, 5); // 20%
2955   BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front());
2956   BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
2957   for (MachineBasicBlock *ChainBB : FunctionChain) {
2958     if (ChainBB == *FunctionChain.begin())
2959       continue;
2960 
2961     // Don't align non-looping basic blocks. These are unlikely to execute
2962     // enough times to matter in practice. Note that we'll still handle
2963     // unnatural CFGs inside of a natural outer loop (the common case) and
2964     // rotated loops.
2965     MachineLoop *L = MLI->getLoopFor(ChainBB);
2966     if (!L)
2967       continue;
2968 
2969     const Align TLIAlign = TLI->getPrefLoopAlignment(L);
2970     unsigned MDAlign = 1;
2971     MDNode *LoopID = L->getLoopID();
2972     if (LoopID) {
2973       for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) {
2974         MDNode *MD = dyn_cast<MDNode>(MDO);
2975         if (MD == nullptr)
2976           continue;
2977         MDString *S = dyn_cast<MDString>(MD->getOperand(0));
2978         if (S == nullptr)
2979           continue;
2980         if (S->getString() == "llvm.loop.align") {
2981           assert(MD->getNumOperands() == 2 &&
2982                  "per-loop align metadata should have two operands.");
2983           MDAlign =
2984               mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue();
2985           assert(MDAlign >= 1 && "per-loop align value must be positive.");
2986         }
2987       }
2988     }
2989 
2990     // Use max of the TLIAlign and MDAlign
2991     const Align LoopAlign = std::max(TLIAlign, Align(MDAlign));
2992     if (LoopAlign == 1)
2993       continue; // Don't care about loop alignment.
2994 
2995     // If the block is cold relative to the function entry don't waste space
2996     // aligning it.
2997     BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
2998     if (Freq < WeightedEntryFreq)
2999       continue;
3000 
3001     // If the block is cold relative to its loop header, don't align it
3002     // regardless of what edges into the block exist.
3003     MachineBasicBlock *LoopHeader = L->getHeader();
3004     BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
3005     if (Freq < (LoopHeaderFreq * ColdProb))
3006       continue;
3007 
3008     // If the global profiles indicates so, don't align it.
3009     if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) &&
3010         !TLI->alignLoopsWithOptSize())
3011       continue;
3012 
3013     // Check for the existence of a non-layout predecessor which would benefit
3014     // from aligning this block.
3015     MachineBasicBlock *LayoutPred =
3016         &*std::prev(MachineFunction::iterator(ChainBB));
3017 
3018     auto DetermineMaxAlignmentPadding = [&]() {
3019       // Set the maximum bytes allowed to be emitted for alignment.
3020       unsigned MaxBytes;
3021       if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0)
3022         MaxBytes = MaxBytesForAlignmentOverride;
3023       else
3024         MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB);
3025       ChainBB->setMaxBytesForAlignment(MaxBytes);
3026     };
3027 
3028     // Force alignment if all the predecessors are jumps. We already checked
3029     // that the block isn't cold above.
3030     if (!LayoutPred->isSuccessor(ChainBB)) {
3031       ChainBB->setAlignment(LoopAlign);
3032       DetermineMaxAlignmentPadding();
3033       continue;
3034     }
3035 
3036     // Align this block if the layout predecessor's edge into this block is
3037     // cold relative to the block. When this is true, other predecessors make up
3038     // all of the hot entries into the block and thus alignment is likely to be
3039     // important.
3040     BranchProbability LayoutProb =
3041         MBPI->getEdgeProbability(LayoutPred, ChainBB);
3042     BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
3043     if (LayoutEdgeFreq <= (Freq * ColdProb)) {
3044       ChainBB->setAlignment(LoopAlign);
3045       DetermineMaxAlignmentPadding();
3046     }
3047   }
3048 
3049   const bool HasMaxBytesOverride =
3050       MaxBytesForAlignmentOverride.getNumOccurrences() > 0;
3051 
3052   if (AlignAllBlock)
3053     // Align all of the blocks in the function to a specific alignment.
3054     for (MachineBasicBlock &MBB : *F) {
3055       if (HasMaxBytesOverride)
3056         MBB.setAlignment(Align(1ULL << AlignAllBlock),
3057                          MaxBytesForAlignmentOverride);
3058       else
3059         MBB.setAlignment(Align(1ULL << AlignAllBlock));
3060     }
3061   else if (AlignAllNonFallThruBlocks) {
3062     // Align all of the blocks that have no fall-through predecessors to a
3063     // specific alignment.
3064     for (auto MBI = std::next(F->begin()), MBE = F->end(); MBI != MBE; ++MBI) {
3065       auto LayoutPred = std::prev(MBI);
3066       if (!LayoutPred->isSuccessor(&*MBI)) {
3067         if (HasMaxBytesOverride)
3068           MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks),
3069                             MaxBytesForAlignmentOverride);
3070         else
3071           MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks));
3072       }
3073     }
3074   }
3075 }
3076 
3077 /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if
3078 /// it was duplicated into its chain predecessor and removed.
3079 /// \p BB    - Basic block that may be duplicated.
3080 ///
3081 /// \p LPred - Chosen layout predecessor of \p BB.
3082 ///            Updated to be the chain end if LPred is removed.
3083 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
3084 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
3085 ///                  Used to identify which blocks to update predecessor
3086 ///                  counts.
3087 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3088 ///                          chosen in the given order due to unnatural CFG
3089 ///                          only needed if \p BB is removed and
3090 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
3091 /// @return true if \p BB was removed.
3092 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
3093     MachineBasicBlock *BB, MachineBasicBlock *&LPred,
3094     const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
3095     BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt,
3096     BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt) {
3097   bool Removed, DuplicatedToLPred;
3098   bool DuplicatedToOriginalLPred;
3099   Removed = maybeTailDuplicateBlock(
3100       BB, LPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3101       PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3102   if (!Removed)
3103     return false;
3104   DuplicatedToOriginalLPred = DuplicatedToLPred;
3105   // Iteratively try to duplicate again. It can happen that a block that is
3106   // duplicated into is still small enough to be duplicated again.
3107   // No need to call markBlockSuccessors in this case, as the blocks being
3108   // duplicated from here on are already scheduled.
3109   while (DuplicatedToLPred && Removed) {
3110     MachineBasicBlock *DupBB, *DupPred;
3111     // The removal callback causes Chain.end() to be updated when a block is
3112     // removed. On the first pass through the loop, the chain end should be the
3113     // same as it was on function entry. On subsequent passes, because we are
3114     // duplicating the block at the end of the chain, if it is removed the
3115     // chain will have shrunk by one block.
3116     BlockChain::iterator ChainEnd = Chain.end();
3117     DupBB = *(--ChainEnd);
3118     // Now try to duplicate again.
3119     if (ChainEnd == Chain.begin())
3120       break;
3121     DupPred = *std::prev(ChainEnd);
3122     Removed = maybeTailDuplicateBlock(
3123         DupBB, DupPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3124         PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3125   }
3126   // If BB was duplicated into LPred, it is now scheduled. But because it was
3127   // removed, markChainSuccessors won't be called for its chain. Instead we
3128   // call markBlockSuccessors for LPred to achieve the same effect. This must go
3129   // at the end because repeating the tail duplication can increase the number
3130   // of unscheduled predecessors.
3131   LPred = *std::prev(Chain.end());
3132   if (DuplicatedToOriginalLPred)
3133     markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
3134   return true;
3135 }
3136 
3137 /// Tail duplicate \p BB into (some) predecessors if profitable.
3138 /// \p BB    - Basic block that may be duplicated
3139 /// \p LPred - Chosen layout predecessor of \p BB
3140 /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong.
3141 /// \p BlockFilter - Set of blocks that belong to the loop being laid out.
3142 ///                  Used to identify which blocks to update predecessor
3143 ///                  counts.
3144 /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was
3145 ///                          chosen in the given order due to unnatural CFG
3146 ///                          only needed if \p BB is removed and
3147 ///                          \p PrevUnplacedBlockIt pointed to \p BB.
3148 /// \p DuplicatedToLPred - True if the block was duplicated into LPred.
3149 /// \return  - True if the block was duplicated into all preds and removed.
3150 bool MachineBlockPlacement::maybeTailDuplicateBlock(
3151     MachineBasicBlock *BB, MachineBasicBlock *LPred, BlockChain &Chain,
3152     BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt,
3153     BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
3154     bool &DuplicatedToLPred) {
3155   DuplicatedToLPred = false;
3156   if (!shouldTailDuplicate(BB))
3157     return false;
3158 
3159   LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber()
3160                     << "\n");
3161 
3162   // This has to be a callback because none of it can be done after
3163   // BB is deleted.
3164   bool Removed = false;
3165   auto RemovalCallback = [&](MachineBasicBlock *RemBB) {
3166     // Signal to outer function
3167     Removed = true;
3168 
3169     // Conservative default.
3170     bool InWorkList = true;
3171     // Remove from the Chain and Chain Map
3172     if (BlockToChain.count(RemBB)) {
3173       BlockChain *Chain = BlockToChain[RemBB];
3174       InWorkList = Chain->UnscheduledPredecessors == 0;
3175       Chain->remove(RemBB);
3176       BlockToChain.erase(RemBB);
3177     }
3178 
3179     // Handle the unplaced block iterator
3180     if (&(*PrevUnplacedBlockIt) == RemBB) {
3181       PrevUnplacedBlockIt++;
3182     }
3183 
3184     // Handle the Work Lists
3185     if (InWorkList) {
3186       SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList;
3187       if (RemBB->isEHPad())
3188         RemoveList = EHPadWorkList;
3189       llvm::erase(RemoveList, RemBB);
3190     }
3191 
3192     // Handle the filter set
3193     if (BlockFilter) {
3194       auto It = llvm::find(*BlockFilter, RemBB);
3195       // Erase RemBB from BlockFilter, and keep PrevUnplacedBlockInFilterIt
3196       // pointing to the same element as before.
3197       if (It != BlockFilter->end()) {
3198         if (It < PrevUnplacedBlockInFilterIt) {
3199           const MachineBasicBlock *PrevBB = *PrevUnplacedBlockInFilterIt;
3200           // BlockFilter is a SmallVector so all elements after RemBB are
3201           // shifted to the front by 1 after its deletion.
3202           auto Distance = PrevUnplacedBlockInFilterIt - It - 1;
3203           PrevUnplacedBlockInFilterIt = BlockFilter->erase(It) + Distance;
3204           assert(*PrevUnplacedBlockInFilterIt == PrevBB);
3205           (void)PrevBB;
3206         } else if (It == PrevUnplacedBlockInFilterIt)
3207           // The block pointed by PrevUnplacedBlockInFilterIt is erased, we
3208           // have to set it to the next element.
3209           PrevUnplacedBlockInFilterIt = BlockFilter->erase(It);
3210         else
3211           BlockFilter->erase(It);
3212       }
3213     }
3214 
3215     // Remove the block from loop info.
3216     MLI->removeBlock(RemBB);
3217     if (RemBB == PreferredLoopExit)
3218       PreferredLoopExit = nullptr;
3219 
3220     LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: " << getBlockName(RemBB)
3221                       << "\n");
3222   };
3223   auto RemovalCallbackRef =
3224       function_ref<void(MachineBasicBlock *)>(RemovalCallback);
3225 
3226   SmallVector<MachineBasicBlock *, 8> DuplicatedPreds;
3227   bool IsSimple = TailDup.isSimpleBB(BB);
3228   SmallVector<MachineBasicBlock *, 8> CandidatePreds;
3229   SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr;
3230   if (F->getFunction().hasProfileData()) {
3231     // We can do partial duplication with precise profile information.
3232     findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
3233     if (CandidatePreds.size() == 0)
3234       return false;
3235     if (CandidatePreds.size() < BB->pred_size())
3236       CandidatePtr = &CandidatePreds;
3237   }
3238   TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds,
3239                                  &RemovalCallbackRef, CandidatePtr);
3240 
3241   // Update UnscheduledPredecessors to reflect tail-duplication.
3242   DuplicatedToLPred = false;
3243   for (MachineBasicBlock *Pred : DuplicatedPreds) {
3244     // We're only looking for unscheduled predecessors that match the filter.
3245     BlockChain *PredChain = BlockToChain[Pred];
3246     if (Pred == LPred)
3247       DuplicatedToLPred = true;
3248     if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) ||
3249         PredChain == &Chain)
3250       continue;
3251     for (MachineBasicBlock *NewSucc : Pred->successors()) {
3252       if (BlockFilter && !BlockFilter->count(NewSucc))
3253         continue;
3254       BlockChain *NewChain = BlockToChain[NewSucc];
3255       if (NewChain != &Chain && NewChain != PredChain)
3256         NewChain->UnscheduledPredecessors++;
3257     }
3258   }
3259   return Removed;
3260 }
3261 
3262 // Count the number of actual machine instructions.
3263 static uint64_t countMBBInstruction(MachineBasicBlock *MBB) {
3264   uint64_t InstrCount = 0;
3265   for (MachineInstr &MI : *MBB) {
3266     if (!MI.isPHI() && !MI.isMetaInstruction())
3267       InstrCount += 1;
3268   }
3269   return InstrCount;
3270 }
3271 
3272 // The size cost of duplication is the instruction size of the duplicated block.
3273 // So we should scale the threshold accordingly. But the instruction size is not
3274 // available on all targets, so we use the number of instructions instead.
3275 BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
3276   return BlockFrequency(DupThreshold.getFrequency() * countMBBInstruction(BB));
3277 }
3278 
3279 // Returns true if BB is Pred's best successor.
3280 bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
3281                                             MachineBasicBlock *Pred,
3282                                             BlockFilterSet *BlockFilter) {
3283   if (BB == Pred)
3284     return false;
3285   if (BlockFilter && !BlockFilter->count(Pred))
3286     return false;
3287   BlockChain *PredChain = BlockToChain[Pred];
3288   if (PredChain && (Pred != *std::prev(PredChain->end())))
3289     return false;
3290 
3291   // Find the successor with largest probability excluding BB.
3292   BranchProbability BestProb = BranchProbability::getZero();
3293   for (MachineBasicBlock *Succ : Pred->successors())
3294     if (Succ != BB) {
3295       if (BlockFilter && !BlockFilter->count(Succ))
3296         continue;
3297       BlockChain *SuccChain = BlockToChain[Succ];
3298       if (SuccChain && (Succ != *SuccChain->begin()))
3299         continue;
3300       BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ);
3301       if (SuccProb > BestProb)
3302         BestProb = SuccProb;
3303     }
3304 
3305   BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB);
3306   if (BBProb <= BestProb)
3307     return false;
3308 
3309   // Compute the number of reduced taken branches if Pred falls through to BB
3310   // instead of another successor. Then compare it with threshold.
3311   BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3312   BlockFrequency Gain = PredFreq * (BBProb - BestProb);
3313   return Gain > scaleThreshold(BB);
3314 }
3315 
3316 // Find out the predecessors of BB and BB can be beneficially duplicated into
3317 // them.
3318 void MachineBlockPlacement::findDuplicateCandidates(
3319     SmallVectorImpl<MachineBasicBlock *> &Candidates, MachineBasicBlock *BB,
3320     BlockFilterSet *BlockFilter) {
3321   MachineBasicBlock *Fallthrough = nullptr;
3322   BranchProbability DefaultBranchProb = BranchProbability::getZero();
3323   BlockFrequency BBDupThreshold(scaleThreshold(BB));
3324   SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors());
3325   SmallVector<MachineBasicBlock *, 8> Succs(BB->successors());
3326 
3327   // Sort for highest frequency.
3328   auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3329     return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B);
3330   };
3331   auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) {
3332     return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B);
3333   };
3334   llvm::stable_sort(Succs, CmpSucc);
3335   llvm::stable_sort(Preds, CmpPred);
3336 
3337   auto SuccIt = Succs.begin();
3338   if (SuccIt != Succs.end()) {
3339     DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl();
3340   }
3341 
3342   // For each predecessors of BB, compute the benefit of duplicating BB,
3343   // if it is larger than the threshold, add it into Candidates.
3344   //
3345   // If we have following control flow.
3346   //
3347   //     PB1 PB2 PB3 PB4
3348   //      \   |  /    /\
3349   //       \  | /    /  \
3350   //        \ |/    /    \
3351   //         BB----/     OB
3352   //         /\
3353   //        /  \
3354   //      SB1 SB2
3355   //
3356   // And it can be partially duplicated as
3357   //
3358   //   PB2+BB
3359   //      |  PB1 PB3 PB4
3360   //      |   |  /    /\
3361   //      |   | /    /  \
3362   //      |   |/    /    \
3363   //      |  BB----/     OB
3364   //      |\ /|
3365   //      | X |
3366   //      |/ \|
3367   //     SB2 SB1
3368   //
3369   // The benefit of duplicating into a predecessor is defined as
3370   //         Orig_taken_branch - Duplicated_taken_branch
3371   //
3372   // The Orig_taken_branch is computed with the assumption that predecessor
3373   // jumps to BB and the most possible successor is laid out after BB.
3374   //
3375   // The Duplicated_taken_branch is computed with the assumption that BB is
3376   // duplicated into PB, and one successor is layout after it (SB1 for PB1 and
3377   // SB2 for PB2 in our case). If there is no available successor, the combined
3378   // block jumps to all BB's successor, like PB3 in this example.
3379   //
3380   // If a predecessor has multiple successors, so BB can't be duplicated into
3381   // it. But it can beneficially fall through to BB, and duplicate BB into other
3382   // predecessors.
3383   for (MachineBasicBlock *Pred : Preds) {
3384     BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3385 
3386     if (!TailDup.canTailDuplicate(BB, Pred)) {
3387       // BB can't be duplicated into Pred, but it is possible to be layout
3388       // below Pred.
3389       if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) {
3390         Fallthrough = Pred;
3391         if (SuccIt != Succs.end())
3392           SuccIt++;
3393       }
3394       continue;
3395     }
3396 
3397     BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
3398     BlockFrequency DupCost;
3399     if (SuccIt == Succs.end()) {
3400       // Jump to all successors;
3401       if (Succs.size() > 0)
3402         DupCost += PredFreq;
3403     } else {
3404       // Fallthrough to *SuccIt, jump to all other successors;
3405       DupCost += PredFreq;
3406       DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt);
3407     }
3408 
3409     assert(OrigCost >= DupCost);
3410     OrigCost -= DupCost;
3411     if (OrigCost > BBDupThreshold) {
3412       Candidates.push_back(Pred);
3413       if (SuccIt != Succs.end())
3414         SuccIt++;
3415     }
3416   }
3417 
3418   // No predecessors can optimally fallthrough to BB.
3419   // So we can change one duplication into fallthrough.
3420   if (!Fallthrough) {
3421     if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) {
3422       Candidates[0] = Candidates.back();
3423       Candidates.pop_back();
3424     }
3425   }
3426 }
3427 
3428 void MachineBlockPlacement::initTailDupThreshold() {
3429   DupThreshold = BlockFrequency(0);
3430   if (F->getFunction().hasProfileData()) {
3431     // We prefer to use prifile count.
3432     uint64_t HotThreshold = PSI->getOrCompHotCountThreshold();
3433     if (HotThreshold != UINT64_MAX) {
3434       UseProfileCount = true;
3435       DupThreshold =
3436           BlockFrequency(HotThreshold * TailDupProfilePercentThreshold / 100);
3437     } else {
3438       // Profile count is not available, we can use block frequency instead.
3439       BlockFrequency MaxFreq = BlockFrequency(0);
3440       for (MachineBasicBlock &MBB : *F) {
3441         BlockFrequency Freq = MBFI->getBlockFreq(&MBB);
3442         if (Freq > MaxFreq)
3443           MaxFreq = Freq;
3444       }
3445 
3446       BranchProbability ThresholdProb(TailDupPlacementPenalty, 100);
3447       DupThreshold = BlockFrequency(MaxFreq * ThresholdProb);
3448       UseProfileCount = false;
3449     }
3450   }
3451 
3452   TailDupSize = TailDupPlacementThreshold;
3453   // If only the aggressive threshold is explicitly set, use it.
3454   if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 &&
3455       TailDupPlacementThreshold.getNumOccurrences() == 0)
3456     TailDupSize = TailDupPlacementAggressiveThreshold;
3457 
3458   // For aggressive optimization, we can adjust some thresholds to be less
3459   // conservative.
3460   if (PassConfig->getOptLevel() >= CodeGenOptLevel::Aggressive) {
3461     // At O3 we should be more willing to copy blocks for tail duplication. This
3462     // increases size pressure, so we only do it at O3
3463     // Do this unless only the regular threshold is explicitly set.
3464     if (TailDupPlacementThreshold.getNumOccurrences() == 0 ||
3465         TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0)
3466       TailDupSize = TailDupPlacementAggressiveThreshold;
3467   }
3468 
3469   // If there's no threshold provided through options, query the target
3470   // information for a threshold instead.
3471   if (TailDupPlacementThreshold.getNumOccurrences() == 0 &&
3472       (PassConfig->getOptLevel() < CodeGenOptLevel::Aggressive ||
3473        TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0))
3474     TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel());
3475 }
3476 
3477 bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) {
3478   if (skipFunction(MF.getFunction()))
3479     return false;
3480 
3481   // Check for single-block functions and skip them.
3482   if (std::next(MF.begin()) == MF.end())
3483     return false;
3484 
3485   F = &MF;
3486   MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
3487   MBFI = std::make_unique<MBFIWrapper>(
3488       getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
3489   MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
3490   TII = MF.getSubtarget().getInstrInfo();
3491   TLI = MF.getSubtarget().getTargetLowering();
3492   MPDT = nullptr;
3493   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3494   PassConfig = &getAnalysis<TargetPassConfig>();
3495 
3496   // Initialize PreferredLoopExit to nullptr here since it may never be set if
3497   // there are no MachineLoops.
3498   PreferredLoopExit = nullptr;
3499 
3500   assert(BlockToChain.empty() &&
3501          "BlockToChain map should be empty before starting placement.");
3502   assert(ComputedEdges.empty() &&
3503          "Computed Edge map should be empty before starting placement.");
3504 
3505   // Initialize tail duplication thresholds.
3506   initTailDupThreshold();
3507 
3508   // Apply tail duplication.
3509   if (allowTailDupPlacement()) {
3510     MPDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree();
3511     bool OptForSize = MF.getFunction().hasOptSize() ||
3512                       llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI());
3513     if (OptForSize)
3514       TailDupSize = 1;
3515     const bool PreRegAlloc = false;
3516     TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3517                    /* LayoutMode */ true, TailDupSize);
3518     precomputeTriangleChains();
3519   }
3520 
3521   buildCFGChains();
3522 
3523   // Changing the layout can create new tail merging opportunities.
3524   // TailMerge can create jump into if branches that make CFG irreducible for
3525   // HW that requires structured CFG.
3526   const bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
3527                                PassConfig->getEnableTailMerge() &&
3528                                BranchFoldPlacement && MF.size() > 3;
3529   // No tail merging opportunities if the block number is less than four.
3530   if (EnableTailMerge) {
3531     const unsigned TailMergeSize = TailDupSize + 1;
3532     BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false,
3533                     *MBFI, *MBPI, PSI, TailMergeSize);
3534 
3535     if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI,
3536                             /*AfterPlacement=*/true)) {
3537       // Redo the layout if tail merging creates/removes/moves blocks.
3538       BlockToChain.clear();
3539       ComputedEdges.clear();
3540       // Must redo the post-dominator tree if blocks were changed.
3541       if (MPDT)
3542         MPDT->recalculate(MF);
3543       ChainAllocator.DestroyAll();
3544       buildCFGChains();
3545     }
3546   }
3547 
3548   // Apply a post-processing optimizing block placement.
3549   if (MF.size() >= 3 && EnableExtTspBlockPlacement &&
3550       (ApplyExtTspWithoutProfile || MF.getFunction().hasProfileData()) &&
3551       MF.size() <= ExtTspBlockPlacementMaxBlocks) {
3552     // Find a new placement and modify the layout of the blocks in the function.
3553     applyExtTsp();
3554 
3555     // Re-create CFG chain so that we can optimizeBranches and alignBlocks.
3556     createCFGChainExtTsp();
3557   }
3558 
3559   optimizeBranches();
3560   alignBlocks();
3561 
3562   BlockToChain.clear();
3563   ComputedEdges.clear();
3564   ChainAllocator.DestroyAll();
3565 
3566   // View the function.
3567   if (ViewBlockLayoutWithBFI != GVDT_None &&
3568       (ViewBlockFreqFuncName.empty() ||
3569        F->getFunction().getName() == ViewBlockFreqFuncName)) {
3570     if (RenumberBlocksBeforeView)
3571       MF.RenumberBlocks();
3572     MBFI->view("MBP." + MF.getName(), false);
3573   }
3574 
3575   // We always return true as we have no way to track whether the final order
3576   // differs from the original order.
3577   return true;
3578 }
3579 
3580 void MachineBlockPlacement::applyExtTsp() {
3581   // Prepare data; blocks are indexed by their index in the current ordering.
3582   DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex;
3583   BlockIndex.reserve(F->size());
3584   std::vector<const MachineBasicBlock *> CurrentBlockOrder;
3585   CurrentBlockOrder.reserve(F->size());
3586   size_t NumBlocks = 0;
3587   for (const MachineBasicBlock &MBB : *F) {
3588     BlockIndex[&MBB] = NumBlocks++;
3589     CurrentBlockOrder.push_back(&MBB);
3590   }
3591 
3592   auto BlockSizes = std::vector<uint64_t>(F->size());
3593   auto BlockCounts = std::vector<uint64_t>(F->size());
3594   std::vector<codelayout::EdgeCount> JumpCounts;
3595   for (MachineBasicBlock &MBB : *F) {
3596     // Getting the block frequency.
3597     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3598     BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency();
3599     // Getting the block size:
3600     // - approximate the size of an instruction by 4 bytes, and
3601     // - ignore debug instructions.
3602     // Note: getting the exact size of each block is target-dependent and can be
3603     // done by extending the interface of MCCodeEmitter. Experimentally we do
3604     // not see a perf improvement with the exact block sizes.
3605     auto NonDbgInsts =
3606         instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end());
3607     int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
3608     BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts;
3609     // Getting jump frequencies.
3610     for (MachineBasicBlock *Succ : MBB.successors()) {
3611       auto EP = MBPI->getEdgeProbability(&MBB, Succ);
3612       BlockFrequency JumpFreq = BlockFreq * EP;
3613       JumpCounts.push_back(
3614           {BlockIndex[&MBB], BlockIndex[Succ], JumpFreq.getFrequency()});
3615     }
3616   }
3617 
3618   LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size()
3619                     << " with profile = " << F->getFunction().hasProfileData()
3620                     << " (" << F->getName().str() << ")"
3621                     << "\n");
3622   LLVM_DEBUG(
3623       dbgs() << format("  original  layout score: %0.2f\n",
3624                        calcExtTspScore(BlockSizes, BlockCounts, JumpCounts)));
3625 
3626   // Run the layout algorithm.
3627   auto NewOrder = computeExtTspLayout(BlockSizes, BlockCounts, JumpCounts);
3628   std::vector<const MachineBasicBlock *> NewBlockOrder;
3629   NewBlockOrder.reserve(F->size());
3630   for (uint64_t Node : NewOrder) {
3631     NewBlockOrder.push_back(CurrentBlockOrder[Node]);
3632   }
3633   LLVM_DEBUG(dbgs() << format("  optimized layout score: %0.2f\n",
3634                               calcExtTspScore(NewOrder, BlockSizes, BlockCounts,
3635                                               JumpCounts)));
3636 
3637   // Assign new block order.
3638   assignBlockOrder(NewBlockOrder);
3639 }
3640 
3641 void MachineBlockPlacement::assignBlockOrder(
3642     const std::vector<const MachineBasicBlock *> &NewBlockOrder) {
3643   assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order");
3644   F->RenumberBlocks();
3645   // At this point, we possibly removed blocks from the function, so we can't
3646   // renumber the domtree. At this point, we don't need it anymore, though.
3647   // TODO: move this to the point where the dominator tree is actually
3648   // invalidated (i.e., where blocks are removed without updating the domtree).
3649   MPDT = nullptr;
3650 
3651   bool HasChanges = false;
3652   for (size_t I = 0; I < NewBlockOrder.size(); I++) {
3653     if (NewBlockOrder[I] != F->getBlockNumbered(I)) {
3654       HasChanges = true;
3655       break;
3656     }
3657   }
3658   // Stop early if the new block order is identical to the existing one.
3659   if (!HasChanges)
3660     return;
3661 
3662   SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs());
3663   for (auto &MBB : *F) {
3664     PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
3665   }
3666 
3667   // Sort basic blocks in the function according to the computed order.
3668   DenseMap<const MachineBasicBlock *, size_t> NewIndex;
3669   for (const MachineBasicBlock *MBB : NewBlockOrder) {
3670     NewIndex[MBB] = NewIndex.size();
3671   }
3672   F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) {
3673     return NewIndex[&L] < NewIndex[&R];
3674   });
3675 
3676   // Update basic block branches by inserting explicit fallthrough branches
3677   // when required and re-optimize branches when possible.
3678   const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
3679   SmallVector<MachineOperand, 4> Cond;
3680   for (auto &MBB : *F) {
3681     MachineFunction::iterator NextMBB = std::next(MBB.getIterator());
3682     MachineFunction::iterator EndIt = MBB.getParent()->end();
3683     auto *FTMBB = PrevFallThroughs[MBB.getNumber()];
3684     // If this block had a fallthrough before we need an explicit unconditional
3685     // branch to that block if the fallthrough block is not adjacent to the
3686     // block in the new order.
3687     if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) {
3688       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
3689     }
3690 
3691     // It might be possible to optimize branches by flipping the condition.
3692     Cond.clear();
3693     MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
3694     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
3695       continue;
3696     MBB.updateTerminator(FTMBB);
3697   }
3698 
3699 #ifndef NDEBUG
3700   // Make sure we correctly constructed all branches.
3701   F->verify(this, "After optimized block reordering", &errs());
3702 #endif
3703 }
3704 
3705 void MachineBlockPlacement::createCFGChainExtTsp() {
3706   BlockToChain.clear();
3707   ComputedEdges.clear();
3708   ChainAllocator.DestroyAll();
3709 
3710   MachineBasicBlock *HeadBB = &F->front();
3711   BlockChain *FunctionChain =
3712       new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB);
3713 
3714   for (MachineBasicBlock &MBB : *F) {
3715     if (HeadBB == &MBB)
3716       continue; // Ignore head of the chain
3717     FunctionChain->merge(&MBB, nullptr);
3718   }
3719 }
3720 
3721 namespace {
3722 
3723 /// A pass to compute block placement statistics.
3724 ///
3725 /// A separate pass to compute interesting statistics for evaluating block
3726 /// placement. This is separate from the actual placement pass so that they can
3727 /// be computed in the absence of any placement transformations or when using
3728 /// alternative placement strategies.
3729 class MachineBlockPlacementStats : public MachineFunctionPass {
3730   /// A handle to the branch probability pass.
3731   const MachineBranchProbabilityInfo *MBPI;
3732 
3733   /// A handle to the function-wide block frequency pass.
3734   const MachineBlockFrequencyInfo *MBFI;
3735 
3736 public:
3737   static char ID; // Pass identification, replacement for typeid
3738 
3739   MachineBlockPlacementStats() : MachineFunctionPass(ID) {
3740     initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry());
3741   }
3742 
3743   bool runOnMachineFunction(MachineFunction &F) override;
3744 
3745   void getAnalysisUsage(AnalysisUsage &AU) const override {
3746     AU.addRequired<MachineBranchProbabilityInfoWrapperPass>();
3747     AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
3748     AU.setPreservesAll();
3749     MachineFunctionPass::getAnalysisUsage(AU);
3750   }
3751 };
3752 
3753 } // end anonymous namespace
3754 
3755 char MachineBlockPlacementStats::ID = 0;
3756 
3757 char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID;
3758 
3759 INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats",
3760                       "Basic Block Placement Stats", false, false)
3761 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass)
3762 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass)
3763 INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats",
3764                     "Basic Block Placement Stats", false, false)
3765 
3766 bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) {
3767   // Check for single-block functions and skip them.
3768   if (std::next(F.begin()) == F.end())
3769     return false;
3770 
3771   if (!isFunctionInPrintList(F.getName()))
3772     return false;
3773 
3774   MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
3775   MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
3776 
3777   for (MachineBasicBlock &MBB : F) {
3778     BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB);
3779     Statistic &NumBranches =
3780         (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3781     Statistic &BranchTakenFreq =
3782         (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
3783     for (MachineBasicBlock *Succ : MBB.successors()) {
3784       // Skip if this successor is a fallthrough.
3785       if (MBB.isLayoutSuccessor(Succ))
3786         continue;
3787 
3788       BlockFrequency EdgeFreq =
3789           BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
3790       ++NumBranches;
3791       BranchTakenFreq += EdgeFreq.getFrequency();
3792     }
3793   }
3794 
3795   return false;
3796 }
3797