10b57cec5SDimitry Andric //===- MachineBlockPlacement.cpp - Basic Block Code Layout optimization ---===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements basic block placement transformations using the CFG 100b57cec5SDimitry Andric // structure and branch probability estimates. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric // The pass strives to preserve the structure of the CFG (that is, retain 130b57cec5SDimitry Andric // a topological ordering of basic blocks) in the absence of a *strong* signal 140b57cec5SDimitry Andric // to the contrary from probabilities. However, within the CFG structure, it 150b57cec5SDimitry Andric // attempts to choose an ordering which favors placing more likely sequences of 160b57cec5SDimitry Andric // blocks adjacent to each other. 170b57cec5SDimitry Andric // 180b57cec5SDimitry Andric // The algorithm works from the inner-most loop within a function outward, and 190b57cec5SDimitry Andric // at each stage walks through the basic blocks, trying to coalesce them into 200b57cec5SDimitry Andric // sequential chains where allowed by the CFG (or demanded by heavy 210b57cec5SDimitry Andric // probabilities). Finally, it walks the blocks in topological order, and the 220b57cec5SDimitry Andric // first time it reaches a chain of basic blocks, it schedules them in the 230b57cec5SDimitry Andric // function in-order. 240b57cec5SDimitry Andric // 250b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 260b57cec5SDimitry Andric 270b57cec5SDimitry Andric #include "BranchFolding.h" 280b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h" 290b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 300b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 310b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h" 320b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 330b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 340b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 350b57cec5SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h" 36480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h" 3781ad6265SDimitry Andric #include "llvm/CodeGen/MBFIWrapper.h" 380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h" 440b57cec5SDimitry Andric #include "llvm/CodeGen/MachinePostDominators.h" 45480093f4SDimitry Andric #include "llvm/CodeGen/MachineSizeOpts.h" 460b57cec5SDimitry Andric #include "llvm/CodeGen/TailDuplicator.h" 470b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h" 480b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h" 490b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 500b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 510b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h" 520b57cec5SDimitry Andric #include "llvm/IR/Function.h" 5381ad6265SDimitry Andric #include "llvm/IR/PrintPasses.h" 54480093f4SDimitry Andric #include "llvm/InitializePasses.h" 550b57cec5SDimitry Andric #include "llvm/Pass.h" 560b57cec5SDimitry Andric #include "llvm/Support/Allocator.h" 570b57cec5SDimitry Andric #include "llvm/Support/BlockFrequency.h" 580b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h" 590b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 600b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 610b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 620b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 630b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 640b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h" 650eae32dcSDimitry Andric #include "llvm/Transforms/Utils/CodeLayout.h" 660b57cec5SDimitry Andric #include <algorithm> 670b57cec5SDimitry Andric #include <cassert> 680b57cec5SDimitry Andric #include <cstdint> 690b57cec5SDimitry Andric #include <iterator> 700b57cec5SDimitry Andric #include <memory> 710b57cec5SDimitry Andric #include <string> 720b57cec5SDimitry Andric #include <tuple> 730b57cec5SDimitry Andric #include <utility> 740b57cec5SDimitry Andric #include <vector> 750b57cec5SDimitry Andric 760b57cec5SDimitry Andric using namespace llvm; 770b57cec5SDimitry Andric 780b57cec5SDimitry Andric #define DEBUG_TYPE "block-placement" 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric STATISTIC(NumCondBranches, "Number of conditional branches"); 810b57cec5SDimitry Andric STATISTIC(NumUncondBranches, "Number of unconditional branches"); 820b57cec5SDimitry Andric STATISTIC(CondBranchTakenFreq, 830b57cec5SDimitry Andric "Potential frequency of taking conditional branches"); 840b57cec5SDimitry Andric STATISTIC(UncondBranchTakenFreq, 850b57cec5SDimitry Andric "Potential frequency of taking unconditional branches"); 860b57cec5SDimitry Andric 878bcb0991SDimitry Andric static cl::opt<unsigned> AlignAllBlock( 888bcb0991SDimitry Andric "align-all-blocks", 898bcb0991SDimitry Andric cl::desc("Force the alignment of all blocks in the function in log2 format " 908bcb0991SDimitry Andric "(e.g 4 means align on 16B boundaries)."), 910b57cec5SDimitry Andric cl::init(0), cl::Hidden); 920b57cec5SDimitry Andric 930b57cec5SDimitry Andric static cl::opt<unsigned> AlignAllNonFallThruBlocks( 940b57cec5SDimitry Andric "align-all-nofallthru-blocks", 958bcb0991SDimitry Andric cl::desc("Force the alignment of all blocks that have no fall-through " 968bcb0991SDimitry Andric "predecessors (i.e. don't add nops that are executed). In log2 " 978bcb0991SDimitry Andric "format (e.g 4 means align on 16B boundaries)."), 980b57cec5SDimitry Andric cl::init(0), cl::Hidden); 990b57cec5SDimitry Andric 10004eeddc0SDimitry Andric static cl::opt<unsigned> MaxBytesForAlignmentOverride( 10104eeddc0SDimitry Andric "max-bytes-for-alignment", 10204eeddc0SDimitry Andric cl::desc("Forces the maximum bytes allowed to be emitted when padding for " 10304eeddc0SDimitry Andric "alignment"), 10404eeddc0SDimitry Andric cl::init(0), cl::Hidden); 10504eeddc0SDimitry Andric 1060b57cec5SDimitry Andric // FIXME: Find a good default for this flag and remove the flag. 1070b57cec5SDimitry Andric static cl::opt<unsigned> ExitBlockBias( 1080b57cec5SDimitry Andric "block-placement-exit-block-bias", 1090b57cec5SDimitry Andric cl::desc("Block frequency percentage a loop exit block needs " 1100b57cec5SDimitry Andric "over the original exit to be considered the new exit."), 1110b57cec5SDimitry Andric cl::init(0), cl::Hidden); 1120b57cec5SDimitry Andric 1130b57cec5SDimitry Andric // Definition: 1140b57cec5SDimitry Andric // - Outlining: placement of a basic block outside the chain or hot path. 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric static cl::opt<unsigned> LoopToColdBlockRatio( 1170b57cec5SDimitry Andric "loop-to-cold-block-ratio", 1180b57cec5SDimitry Andric cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " 1190b57cec5SDimitry Andric "(frequency of block) is greater than this ratio"), 1200b57cec5SDimitry Andric cl::init(5), cl::Hidden); 1210b57cec5SDimitry Andric 1220b57cec5SDimitry Andric static cl::opt<bool> ForceLoopColdBlock( 1230b57cec5SDimitry Andric "force-loop-cold-block", 1240b57cec5SDimitry Andric cl::desc("Force outlining cold blocks from loops."), 1250b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric static cl::opt<bool> 1280b57cec5SDimitry Andric PreciseRotationCost("precise-rotation-cost", 1290b57cec5SDimitry Andric cl::desc("Model the cost of loop rotation more " 1300b57cec5SDimitry Andric "precisely by using profile data."), 1310b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric static cl::opt<bool> 1340b57cec5SDimitry Andric ForcePreciseRotationCost("force-precise-rotation-cost", 1350b57cec5SDimitry Andric cl::desc("Force the use of precise cost " 1360b57cec5SDimitry Andric "loop rotation strategy."), 1370b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1380b57cec5SDimitry Andric 1390b57cec5SDimitry Andric static cl::opt<unsigned> MisfetchCost( 1400b57cec5SDimitry Andric "misfetch-cost", 1410b57cec5SDimitry Andric cl::desc("Cost that models the probabilistic risk of an instruction " 1420b57cec5SDimitry Andric "misfetch due to a jump comparing to falling through, whose cost " 1430b57cec5SDimitry Andric "is zero."), 1440b57cec5SDimitry Andric cl::init(1), cl::Hidden); 1450b57cec5SDimitry Andric 1460b57cec5SDimitry Andric static cl::opt<unsigned> JumpInstCost("jump-inst-cost", 1470b57cec5SDimitry Andric cl::desc("Cost of jump instructions."), 1480b57cec5SDimitry Andric cl::init(1), cl::Hidden); 1490b57cec5SDimitry Andric static cl::opt<bool> 1500b57cec5SDimitry Andric TailDupPlacement("tail-dup-placement", 1510b57cec5SDimitry Andric cl::desc("Perform tail duplication during placement. " 1520b57cec5SDimitry Andric "Creates more fallthrough opportunites in " 1530b57cec5SDimitry Andric "outline branches."), 1540b57cec5SDimitry Andric cl::init(true), cl::Hidden); 1550b57cec5SDimitry Andric 1560b57cec5SDimitry Andric static cl::opt<bool> 1570b57cec5SDimitry Andric BranchFoldPlacement("branch-fold-placement", 1580b57cec5SDimitry Andric cl::desc("Perform branch folding during placement. " 1590b57cec5SDimitry Andric "Reduces code size."), 1600b57cec5SDimitry Andric cl::init(true), cl::Hidden); 1610b57cec5SDimitry Andric 1620b57cec5SDimitry Andric // Heuristic for tail duplication. 1630b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementThreshold( 1640b57cec5SDimitry Andric "tail-dup-placement-threshold", 1650b57cec5SDimitry Andric cl::desc("Instruction cutoff for tail duplication during layout. " 1660b57cec5SDimitry Andric "Tail merging during layout is forced to have a threshold " 1670b57cec5SDimitry Andric "that won't conflict."), cl::init(2), 1680b57cec5SDimitry Andric cl::Hidden); 1690b57cec5SDimitry Andric 1700b57cec5SDimitry Andric // Heuristic for aggressive tail duplication. 1710b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementAggressiveThreshold( 1720b57cec5SDimitry Andric "tail-dup-placement-aggressive-threshold", 1730b57cec5SDimitry Andric cl::desc("Instruction cutoff for aggressive tail duplication during " 1740b57cec5SDimitry Andric "layout. Used at -O3. Tail merging during layout is forced to " 1750b57cec5SDimitry Andric "have a threshold that won't conflict."), cl::init(4), 1760b57cec5SDimitry Andric cl::Hidden); 1770b57cec5SDimitry Andric 1780b57cec5SDimitry Andric // Heuristic for tail duplication. 1790b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementPenalty( 1800b57cec5SDimitry Andric "tail-dup-placement-penalty", 1810b57cec5SDimitry Andric cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. " 1820b57cec5SDimitry Andric "Copying can increase fallthrough, but it also increases icache " 1830b57cec5SDimitry Andric "pressure. This parameter controls the penalty to account for that. " 1840b57cec5SDimitry Andric "Percent as integer."), 1850b57cec5SDimitry Andric cl::init(2), 1860b57cec5SDimitry Andric cl::Hidden); 1870b57cec5SDimitry Andric 188e8d8bef9SDimitry Andric // Heuristic for tail duplication if profile count is used in cost model. 189e8d8bef9SDimitry Andric static cl::opt<unsigned> TailDupProfilePercentThreshold( 190e8d8bef9SDimitry Andric "tail-dup-profile-percent-threshold", 191e8d8bef9SDimitry Andric cl::desc("If profile count information is used in tail duplication cost " 192e8d8bef9SDimitry Andric "model, the gained fall through number from tail duplication " 193e8d8bef9SDimitry Andric "should be at least this percent of hot count."), 194e8d8bef9SDimitry Andric cl::init(50), cl::Hidden); 195e8d8bef9SDimitry Andric 1960b57cec5SDimitry Andric // Heuristic for triangle chains. 1970b57cec5SDimitry Andric static cl::opt<unsigned> TriangleChainCount( 1980b57cec5SDimitry Andric "triangle-chain-count", 1990b57cec5SDimitry Andric cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the " 2000b57cec5SDimitry Andric "triangle tail duplication heuristic to kick in. 0 to disable."), 2010b57cec5SDimitry Andric cl::init(2), 2020b57cec5SDimitry Andric cl::Hidden); 2030b57cec5SDimitry Andric 204*bdd1243dSDimitry Andric // Use case: When block layout is visualized after MBP pass, the basic blocks 205*bdd1243dSDimitry Andric // are labeled in layout order; meanwhile blocks could be numbered in a 206*bdd1243dSDimitry Andric // different order. It's hard to map between the graph and pass output. 207*bdd1243dSDimitry Andric // With this option on, the basic blocks are renumbered in function layout 208*bdd1243dSDimitry Andric // order. For debugging only. 209*bdd1243dSDimitry Andric static cl::opt<bool> RenumberBlocksBeforeView( 210*bdd1243dSDimitry Andric "renumber-blocks-before-view", 211*bdd1243dSDimitry Andric cl::desc( 212*bdd1243dSDimitry Andric "If true, basic blocks are re-numbered before MBP layout is printed " 213*bdd1243dSDimitry Andric "into a dot graph. Only used when a function is being printed."), 214*bdd1243dSDimitry Andric cl::init(false), cl::Hidden); 215*bdd1243dSDimitry Andric 21681ad6265SDimitry Andric extern cl::opt<bool> EnableExtTspBlockPlacement; 21781ad6265SDimitry Andric extern cl::opt<bool> ApplyExtTspWithoutProfile; 2180eae32dcSDimitry Andric 219fe6060f1SDimitry Andric namespace llvm { 2200b57cec5SDimitry Andric extern cl::opt<unsigned> StaticLikelyProb; 2210b57cec5SDimitry Andric extern cl::opt<unsigned> ProfileLikelyProb; 2220b57cec5SDimitry Andric 2230b57cec5SDimitry Andric // Internal option used to control BFI display only after MBP pass. 2240b57cec5SDimitry Andric // Defined in CodeGen/MachineBlockFrequencyInfo.cpp: 2250b57cec5SDimitry Andric // -view-block-layout-with-bfi= 2260b57cec5SDimitry Andric extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI; 2270b57cec5SDimitry Andric 2280b57cec5SDimitry Andric // Command line option to specify the name of the function for CFG dump 2290b57cec5SDimitry Andric // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 2300b57cec5SDimitry Andric extern cl::opt<std::string> ViewBlockFreqFuncName; 231fe6060f1SDimitry Andric } // namespace llvm 2320b57cec5SDimitry Andric 2330b57cec5SDimitry Andric namespace { 2340b57cec5SDimitry Andric 2350b57cec5SDimitry Andric class BlockChain; 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric /// Type for our function-wide basic block -> block chain mapping. 2380b57cec5SDimitry Andric using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>; 2390b57cec5SDimitry Andric 2400b57cec5SDimitry Andric /// A chain of blocks which will be laid out contiguously. 2410b57cec5SDimitry Andric /// 2420b57cec5SDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that 2430b57cec5SDimitry Andric /// are profitable to layout together in order to maximize fallthrough 2440b57cec5SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent 2450b57cec5SDimitry Andric /// a sequence of basic blocks which have some external (correctness) 2460b57cec5SDimitry Andric /// requirement for sequential layout. 2470b57cec5SDimitry Andric /// 2480b57cec5SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow 2490b57cec5SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated 2500b57cec5SDimitry Andric /// automatically as chains are merged together. 2510b57cec5SDimitry Andric class BlockChain { 2520b57cec5SDimitry Andric /// The sequence of blocks belonging to this chain. 2530b57cec5SDimitry Andric /// 2540b57cec5SDimitry Andric /// This is the sequence of blocks for a particular chain. These will be laid 2550b57cec5SDimitry Andric /// out in-order within the function. 2560b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> Blocks; 2570b57cec5SDimitry Andric 2580b57cec5SDimitry Andric /// A handle to the function-wide basic block to block chain mapping. 2590b57cec5SDimitry Andric /// 2600b57cec5SDimitry Andric /// This is retained in each block chain to simplify the computation of child 2610b57cec5SDimitry Andric /// block chains for SCC-formation and iteration. We store the edges to child 2620b57cec5SDimitry Andric /// basic blocks, and map them back to their associated chains using this 2630b57cec5SDimitry Andric /// structure. 2640b57cec5SDimitry Andric BlockToChainMapType &BlockToChain; 2650b57cec5SDimitry Andric 2660b57cec5SDimitry Andric public: 2670b57cec5SDimitry Andric /// Construct a new BlockChain. 2680b57cec5SDimitry Andric /// 2690b57cec5SDimitry Andric /// This builds a new block chain representing a single basic block in the 2700b57cec5SDimitry Andric /// function. It also registers itself as the chain that block participates 2710b57cec5SDimitry Andric /// in with the BlockToChain mapping. 2720b57cec5SDimitry Andric BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 2730b57cec5SDimitry Andric : Blocks(1, BB), BlockToChain(BlockToChain) { 2740b57cec5SDimitry Andric assert(BB && "Cannot create a chain with a null basic block"); 2750b57cec5SDimitry Andric BlockToChain[BB] = this; 2760b57cec5SDimitry Andric } 2770b57cec5SDimitry Andric 2780b57cec5SDimitry Andric /// Iterator over blocks within the chain. 2790b57cec5SDimitry Andric using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator; 2800b57cec5SDimitry Andric using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator; 2810b57cec5SDimitry Andric 2820b57cec5SDimitry Andric /// Beginning of blocks within the chain. 2830b57cec5SDimitry Andric iterator begin() { return Blocks.begin(); } 2840b57cec5SDimitry Andric const_iterator begin() const { return Blocks.begin(); } 2850b57cec5SDimitry Andric 2860b57cec5SDimitry Andric /// End of blocks within the chain. 2870b57cec5SDimitry Andric iterator end() { return Blocks.end(); } 2880b57cec5SDimitry Andric const_iterator end() const { return Blocks.end(); } 2890b57cec5SDimitry Andric 2900b57cec5SDimitry Andric bool remove(MachineBasicBlock* BB) { 2910b57cec5SDimitry Andric for(iterator i = begin(); i != end(); ++i) { 2920b57cec5SDimitry Andric if (*i == BB) { 2930b57cec5SDimitry Andric Blocks.erase(i); 2940b57cec5SDimitry Andric return true; 2950b57cec5SDimitry Andric } 2960b57cec5SDimitry Andric } 2970b57cec5SDimitry Andric return false; 2980b57cec5SDimitry Andric } 2990b57cec5SDimitry Andric 3000b57cec5SDimitry Andric /// Merge a block chain into this one. 3010b57cec5SDimitry Andric /// 3020b57cec5SDimitry Andric /// This routine merges a block chain into this one. It takes care of forming 3030b57cec5SDimitry Andric /// a contiguous sequence of basic blocks, updating the edge list, and 3040b57cec5SDimitry Andric /// updating the block -> chain mapping. It does not free or tear down the 3050b57cec5SDimitry Andric /// old chain, but the old chain's block list is no longer valid. 3060b57cec5SDimitry Andric void merge(MachineBasicBlock *BB, BlockChain *Chain) { 3070b57cec5SDimitry Andric assert(BB && "Can't merge a null block."); 3080b57cec5SDimitry Andric assert(!Blocks.empty() && "Can't merge into an empty chain."); 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric // Fast path in case we don't have a chain already. 3110b57cec5SDimitry Andric if (!Chain) { 3120b57cec5SDimitry Andric assert(!BlockToChain[BB] && 3130b57cec5SDimitry Andric "Passed chain is null, but BB has entry in BlockToChain."); 3140b57cec5SDimitry Andric Blocks.push_back(BB); 3150b57cec5SDimitry Andric BlockToChain[BB] = this; 3160b57cec5SDimitry Andric return; 3170b57cec5SDimitry Andric } 3180b57cec5SDimitry Andric 3190b57cec5SDimitry Andric assert(BB == *Chain->begin() && "Passed BB is not head of Chain."); 3200b57cec5SDimitry Andric assert(Chain->begin() != Chain->end()); 3210b57cec5SDimitry Andric 3220b57cec5SDimitry Andric // Update the incoming blocks to point to this chain, and add them to the 3230b57cec5SDimitry Andric // chain structure. 3240b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) { 3250b57cec5SDimitry Andric Blocks.push_back(ChainBB); 3260b57cec5SDimitry Andric assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain."); 3270b57cec5SDimitry Andric BlockToChain[ChainBB] = this; 3280b57cec5SDimitry Andric } 3290b57cec5SDimitry Andric } 3300b57cec5SDimitry Andric 3310b57cec5SDimitry Andric #ifndef NDEBUG 3320b57cec5SDimitry Andric /// Dump the blocks in this chain. 3330b57cec5SDimitry Andric LLVM_DUMP_METHOD void dump() { 3340b57cec5SDimitry Andric for (MachineBasicBlock *MBB : *this) 3350b57cec5SDimitry Andric MBB->dump(); 3360b57cec5SDimitry Andric } 3370b57cec5SDimitry Andric #endif // NDEBUG 3380b57cec5SDimitry Andric 3390b57cec5SDimitry Andric /// Count of predecessors of any block within the chain which have not 3400b57cec5SDimitry Andric /// yet been scheduled. In general, we will delay scheduling this chain 3410b57cec5SDimitry Andric /// until those predecessors are scheduled (or we find a sufficiently good 3420b57cec5SDimitry Andric /// reason to override this heuristic.) Note that when forming loop chains, 3430b57cec5SDimitry Andric /// blocks outside the loop are ignored and treated as if they were already 3440b57cec5SDimitry Andric /// scheduled. 3450b57cec5SDimitry Andric /// 3460b57cec5SDimitry Andric /// Note: This field is reinitialized multiple times - once for each loop, 3470b57cec5SDimitry Andric /// and then once for the function as a whole. 3480b57cec5SDimitry Andric unsigned UnscheduledPredecessors = 0; 3490b57cec5SDimitry Andric }; 3500b57cec5SDimitry Andric 3510b57cec5SDimitry Andric class MachineBlockPlacement : public MachineFunctionPass { 3520b57cec5SDimitry Andric /// A type for a block filter set. 3530b57cec5SDimitry Andric using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>; 3540b57cec5SDimitry Andric 3550b57cec5SDimitry Andric /// Pair struct containing basic block and taildup profitability 3560b57cec5SDimitry Andric struct BlockAndTailDupResult { 3570b57cec5SDimitry Andric MachineBasicBlock *BB; 3580b57cec5SDimitry Andric bool ShouldTailDup; 3590b57cec5SDimitry Andric }; 3600b57cec5SDimitry Andric 3610b57cec5SDimitry Andric /// Triple struct containing edge weight and the edge. 3620b57cec5SDimitry Andric struct WeightedEdge { 3630b57cec5SDimitry Andric BlockFrequency Weight; 3640b57cec5SDimitry Andric MachineBasicBlock *Src; 3650b57cec5SDimitry Andric MachineBasicBlock *Dest; 3660b57cec5SDimitry Andric }; 3670b57cec5SDimitry Andric 3680b57cec5SDimitry Andric /// work lists of blocks that are ready to be laid out 3690b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 16> BlockWorkList; 3700b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 3710b57cec5SDimitry Andric 3720b57cec5SDimitry Andric /// Edges that have already been computed as optimal. 3730b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges; 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric /// Machine Function 3760b57cec5SDimitry Andric MachineFunction *F; 3770b57cec5SDimitry Andric 3780b57cec5SDimitry Andric /// A handle to the branch probability pass. 3790b57cec5SDimitry Andric const MachineBranchProbabilityInfo *MBPI; 3800b57cec5SDimitry Andric 3810b57cec5SDimitry Andric /// A handle to the function-wide block frequency pass. 3825ffd83dbSDimitry Andric std::unique_ptr<MBFIWrapper> MBFI; 3830b57cec5SDimitry Andric 3840b57cec5SDimitry Andric /// A handle to the loop info. 3850b57cec5SDimitry Andric MachineLoopInfo *MLI; 3860b57cec5SDimitry Andric 3870b57cec5SDimitry Andric /// Preferred loop exit. 3880b57cec5SDimitry Andric /// Member variable for convenience. It may be removed by duplication deep 3890b57cec5SDimitry Andric /// in the call stack. 3900b57cec5SDimitry Andric MachineBasicBlock *PreferredLoopExit; 3910b57cec5SDimitry Andric 3920b57cec5SDimitry Andric /// A handle to the target's instruction info. 3930b57cec5SDimitry Andric const TargetInstrInfo *TII; 3940b57cec5SDimitry Andric 3950b57cec5SDimitry Andric /// A handle to the target's lowering info. 3960b57cec5SDimitry Andric const TargetLoweringBase *TLI; 3970b57cec5SDimitry Andric 3980b57cec5SDimitry Andric /// A handle to the post dominator tree. 3990b57cec5SDimitry Andric MachinePostDominatorTree *MPDT; 4000b57cec5SDimitry Andric 401480093f4SDimitry Andric ProfileSummaryInfo *PSI; 402480093f4SDimitry Andric 4030b57cec5SDimitry Andric /// Duplicator used to duplicate tails during placement. 4040b57cec5SDimitry Andric /// 4050b57cec5SDimitry Andric /// Placement decisions can open up new tail duplication opportunities, but 4060b57cec5SDimitry Andric /// since tail duplication affects placement decisions of later blocks, it 4070b57cec5SDimitry Andric /// must be done inline. 4080b57cec5SDimitry Andric TailDuplicator TailDup; 4090b57cec5SDimitry Andric 4105ffd83dbSDimitry Andric /// Partial tail duplication threshold. 4115ffd83dbSDimitry Andric BlockFrequency DupThreshold; 4125ffd83dbSDimitry Andric 413e8d8bef9SDimitry Andric /// True: use block profile count to compute tail duplication cost. 414e8d8bef9SDimitry Andric /// False: use block frequency to compute tail duplication cost. 415e8d8bef9SDimitry Andric bool UseProfileCount; 416e8d8bef9SDimitry Andric 4170b57cec5SDimitry Andric /// Allocator and owner of BlockChain structures. 4180b57cec5SDimitry Andric /// 4190b57cec5SDimitry Andric /// We build BlockChains lazily while processing the loop structure of 4200b57cec5SDimitry Andric /// a function. To reduce malloc traffic, we allocate them using this 4210b57cec5SDimitry Andric /// slab-like allocator, and destroy them after the pass completes. An 4220b57cec5SDimitry Andric /// important guarantee is that this allocator produces stable pointers to 4230b57cec5SDimitry Andric /// the chains. 4240b57cec5SDimitry Andric SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 4250b57cec5SDimitry Andric 4260b57cec5SDimitry Andric /// Function wide BasicBlock to BlockChain mapping. 4270b57cec5SDimitry Andric /// 4280b57cec5SDimitry Andric /// This mapping allows efficiently moving from any given basic block to the 4290b57cec5SDimitry Andric /// BlockChain it participates in, if any. We use it to, among other things, 4300b57cec5SDimitry Andric /// allow implicitly defining edges between chains as the existing edges 4310b57cec5SDimitry Andric /// between basic blocks. 4320b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain; 4330b57cec5SDimitry Andric 4340b57cec5SDimitry Andric #ifndef NDEBUG 4350b57cec5SDimitry Andric /// The set of basic blocks that have terminators that cannot be fully 4360b57cec5SDimitry Andric /// analyzed. These basic blocks cannot be re-ordered safely by 4370b57cec5SDimitry Andric /// MachineBlockPlacement, and we must preserve physical layout of these 4380b57cec5SDimitry Andric /// blocks and their successors through the pass. 4390b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits; 4400b57cec5SDimitry Andric #endif 4410b57cec5SDimitry Andric 442e8d8bef9SDimitry Andric /// Get block profile count or frequency according to UseProfileCount. 443e8d8bef9SDimitry Andric /// The return value is used to model tail duplication cost. 444e8d8bef9SDimitry Andric BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) { 445e8d8bef9SDimitry Andric if (UseProfileCount) { 446e8d8bef9SDimitry Andric auto Count = MBFI->getBlockProfileCount(BB); 447e8d8bef9SDimitry Andric if (Count) 448e8d8bef9SDimitry Andric return *Count; 449e8d8bef9SDimitry Andric else 450e8d8bef9SDimitry Andric return 0; 451e8d8bef9SDimitry Andric } else 452e8d8bef9SDimitry Andric return MBFI->getBlockFreq(BB); 453e8d8bef9SDimitry Andric } 454e8d8bef9SDimitry Andric 4555ffd83dbSDimitry Andric /// Scale the DupThreshold according to basic block size. 4565ffd83dbSDimitry Andric BlockFrequency scaleThreshold(MachineBasicBlock *BB); 4575ffd83dbSDimitry Andric void initDupThreshold(); 4585ffd83dbSDimitry Andric 4590b57cec5SDimitry Andric /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 4600b57cec5SDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 4610b57cec5SDimitry Andric void markChainSuccessors( 4620b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 4630b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 4640b57cec5SDimitry Andric 4650b57cec5SDimitry Andric /// Decrease the UnscheduledPredecessors count for a single block, and 4660b57cec5SDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 4670b57cec5SDimitry Andric void markBlockSuccessors( 4680b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *BB, 4690b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 4700b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 4710b57cec5SDimitry Andric 4720b57cec5SDimitry Andric BranchProbability 4730b57cec5SDimitry Andric collectViableSuccessors( 4740b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 4750b57cec5SDimitry Andric const BlockFilterSet *BlockFilter, 4760b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors); 4775ffd83dbSDimitry Andric bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred, 4785ffd83dbSDimitry Andric BlockFilterSet *BlockFilter); 4795ffd83dbSDimitry Andric void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates, 4805ffd83dbSDimitry Andric MachineBasicBlock *BB, 4815ffd83dbSDimitry Andric BlockFilterSet *BlockFilter); 4820b57cec5SDimitry Andric bool repeatedlyTailDuplicateBlock( 4830b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 4840b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 4850b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 4860b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt); 4870b57cec5SDimitry Andric bool maybeTailDuplicateBlock( 4880b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, 4890b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 4900b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 4910b57cec5SDimitry Andric bool &DuplicatedToLPred); 4920b57cec5SDimitry Andric bool hasBetterLayoutPredecessor( 4930b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 4940b57cec5SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 4950b57cec5SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 4960b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 4970b57cec5SDimitry Andric BlockAndTailDupResult selectBestSuccessor( 4980b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 4990b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5000b57cec5SDimitry Andric MachineBasicBlock *selectBestCandidateBlock( 5010b57cec5SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList); 5020b57cec5SDimitry Andric MachineBasicBlock *getFirstUnplacedBlock( 5030b57cec5SDimitry Andric const BlockChain &PlacedChain, 5040b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 5050b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5060b57cec5SDimitry Andric 5070b57cec5SDimitry Andric /// Add a basic block to the work list if it is appropriate. 5080b57cec5SDimitry Andric /// 5090b57cec5SDimitry Andric /// If the optional parameter BlockFilter is provided, only MBB 5100b57cec5SDimitry Andric /// present in the set will be added to the worklist. If nullptr 5110b57cec5SDimitry Andric /// is provided, no filtering occurs. 5120b57cec5SDimitry Andric void fillWorkLists(const MachineBasicBlock *MBB, 5130b57cec5SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 5140b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5150b57cec5SDimitry Andric 5160b57cec5SDimitry Andric void buildChain(const MachineBasicBlock *BB, BlockChain &Chain, 5170b57cec5SDimitry Andric BlockFilterSet *BlockFilter = nullptr); 5180b57cec5SDimitry Andric bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock, 5190b57cec5SDimitry Andric const MachineBasicBlock *OldTop); 5200b57cec5SDimitry Andric bool hasViableTopFallthrough(const MachineBasicBlock *Top, 5210b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5220b57cec5SDimitry Andric BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top, 5230b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5240b57cec5SDimitry Andric BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop, 5250b57cec5SDimitry Andric const MachineBasicBlock *OldTop, 5260b57cec5SDimitry Andric const MachineBasicBlock *ExitBB, 5270b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5280b57cec5SDimitry Andric MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop, 5290b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 5300b57cec5SDimitry Andric MachineBasicBlock *findBestLoopTop( 5310b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 5320b57cec5SDimitry Andric MachineBasicBlock *findBestLoopExit( 5330b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet, 5340b57cec5SDimitry Andric BlockFrequency &ExitFreq); 5350b57cec5SDimitry Andric BlockFilterSet collectLoopBlockSet(const MachineLoop &L); 5360b57cec5SDimitry Andric void buildLoopChains(const MachineLoop &L); 5370b57cec5SDimitry Andric void rotateLoop( 5380b57cec5SDimitry Andric BlockChain &LoopChain, const MachineBasicBlock *ExitingBB, 5390b57cec5SDimitry Andric BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet); 5400b57cec5SDimitry Andric void rotateLoopWithProfile( 5410b57cec5SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 5420b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5430b57cec5SDimitry Andric void buildCFGChains(); 5440b57cec5SDimitry Andric void optimizeBranches(); 5450b57cec5SDimitry Andric void alignBlocks(); 5460b57cec5SDimitry Andric /// Returns true if a block should be tail-duplicated to increase fallthrough 5470b57cec5SDimitry Andric /// opportunities. 5480b57cec5SDimitry Andric bool shouldTailDuplicate(MachineBasicBlock *BB); 5490b57cec5SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 5500b57cec5SDimitry Andric /// fallthroughs. 5510b57cec5SDimitry Andric bool isProfitableToTailDup( 5520b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 5530b57cec5SDimitry Andric BranchProbability QProb, 5540b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5550b57cec5SDimitry Andric 5560b57cec5SDimitry Andric /// Check for a trellis layout. 5570b57cec5SDimitry Andric bool isTrellis(const MachineBasicBlock *BB, 5580b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 5590b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5600b57cec5SDimitry Andric 5610b57cec5SDimitry Andric /// Get the best successor given a trellis layout. 5620b57cec5SDimitry Andric BlockAndTailDupResult getBestTrellisSuccessor( 5630b57cec5SDimitry Andric const MachineBasicBlock *BB, 5640b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 5650b57cec5SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 5660b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5670b57cec5SDimitry Andric 5680b57cec5SDimitry Andric /// Get the best pair of non-conflicting edges. 5690b57cec5SDimitry Andric static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges( 5700b57cec5SDimitry Andric const MachineBasicBlock *BB, 5710b57cec5SDimitry Andric MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges); 5720b57cec5SDimitry Andric 5730b57cec5SDimitry Andric /// Returns true if a block can tail duplicate into all unplaced 5740b57cec5SDimitry Andric /// predecessors. Filters based on loop. 5750b57cec5SDimitry Andric bool canTailDuplicateUnplacedPreds( 5760b57cec5SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 5770b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5780b57cec5SDimitry Andric 5790b57cec5SDimitry Andric /// Find chains of triangles to tail-duplicate where a global analysis works, 5800b57cec5SDimitry Andric /// but a local analysis would not find them. 5810b57cec5SDimitry Andric void precomputeTriangleChains(); 5820b57cec5SDimitry Andric 5830eae32dcSDimitry Andric /// Apply a post-processing step optimizing block placement. 5840eae32dcSDimitry Andric void applyExtTsp(); 5850eae32dcSDimitry Andric 5860eae32dcSDimitry Andric /// Modify the existing block placement in the function and adjust all jumps. 5870eae32dcSDimitry Andric void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder); 5880eae32dcSDimitry Andric 5890eae32dcSDimitry Andric /// Create a single CFG chain from the current block order. 5900eae32dcSDimitry Andric void createCFGChainExtTsp(); 5910eae32dcSDimitry Andric 5920b57cec5SDimitry Andric public: 5930b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 5940b57cec5SDimitry Andric 5950b57cec5SDimitry Andric MachineBlockPlacement() : MachineFunctionPass(ID) { 5960b57cec5SDimitry Andric initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 5970b57cec5SDimitry Andric } 5980b57cec5SDimitry Andric 5990b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 6000b57cec5SDimitry Andric 6010b57cec5SDimitry Andric bool allowTailDupPlacement() const { 6020b57cec5SDimitry Andric assert(F); 6030b57cec5SDimitry Andric return TailDupPlacement && !F->getTarget().requiresStructuredCFG(); 6040b57cec5SDimitry Andric } 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 6070b57cec5SDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>(); 6080b57cec5SDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>(); 6090b57cec5SDimitry Andric if (TailDupPlacement) 6100b57cec5SDimitry Andric AU.addRequired<MachinePostDominatorTree>(); 6110b57cec5SDimitry Andric AU.addRequired<MachineLoopInfo>(); 612480093f4SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>(); 6130b57cec5SDimitry Andric AU.addRequired<TargetPassConfig>(); 6140b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 6150b57cec5SDimitry Andric } 6160b57cec5SDimitry Andric }; 6170b57cec5SDimitry Andric 6180b57cec5SDimitry Andric } // end anonymous namespace 6190b57cec5SDimitry Andric 6200b57cec5SDimitry Andric char MachineBlockPlacement::ID = 0; 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 6230b57cec5SDimitry Andric 6240b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE, 6250b57cec5SDimitry Andric "Branch Probability Basic Block Placement", false, false) 6260b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 6270b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 6280b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 6290b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 630480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 6310b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE, 6320b57cec5SDimitry Andric "Branch Probability Basic Block Placement", false, false) 6330b57cec5SDimitry Andric 6340b57cec5SDimitry Andric #ifndef NDEBUG 6350b57cec5SDimitry Andric /// Helper to print the name of a MBB. 6360b57cec5SDimitry Andric /// 6370b57cec5SDimitry Andric /// Only used by debug logging. 6380b57cec5SDimitry Andric static std::string getBlockName(const MachineBasicBlock *BB) { 6390b57cec5SDimitry Andric std::string Result; 6400b57cec5SDimitry Andric raw_string_ostream OS(Result); 6410b57cec5SDimitry Andric OS << printMBBReference(*BB); 6420b57cec5SDimitry Andric OS << " ('" << BB->getName() << "')"; 6430b57cec5SDimitry Andric OS.flush(); 6440b57cec5SDimitry Andric return Result; 6450b57cec5SDimitry Andric } 6460b57cec5SDimitry Andric #endif 6470b57cec5SDimitry Andric 6480b57cec5SDimitry Andric /// Mark a chain's successors as having one fewer preds. 6490b57cec5SDimitry Andric /// 6500b57cec5SDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will 6510b57cec5SDimitry Andric /// quickly walk the successors of each block in the chain and mark them as 6520b57cec5SDimitry Andric /// having one fewer active predecessor. It also adds any successors of this 6530b57cec5SDimitry Andric /// chain which reach the zero-predecessor state to the appropriate worklist. 6540b57cec5SDimitry Andric void MachineBlockPlacement::markChainSuccessors( 6550b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 6560b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 6570b57cec5SDimitry Andric // Walk all the blocks in this chain, marking their successors as having 6580b57cec5SDimitry Andric // a predecessor placed. 6590b57cec5SDimitry Andric for (MachineBasicBlock *MBB : Chain) { 6600b57cec5SDimitry Andric markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 6610b57cec5SDimitry Andric } 6620b57cec5SDimitry Andric } 6630b57cec5SDimitry Andric 6640b57cec5SDimitry Andric /// Mark a single block's successors as having one fewer preds. 6650b57cec5SDimitry Andric /// 6660b57cec5SDimitry Andric /// Under normal circumstances, this is only called by markChainSuccessors, 6670b57cec5SDimitry Andric /// but if a block that was to be placed is completely tail-duplicated away, 6680b57cec5SDimitry Andric /// and was duplicated into the chain end, we need to redo markBlockSuccessors 6690b57cec5SDimitry Andric /// for just that block. 6700b57cec5SDimitry Andric void MachineBlockPlacement::markBlockSuccessors( 6710b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *MBB, 6720b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) { 6730b57cec5SDimitry Andric // Add any successors for which this is the only un-placed in-loop 6740b57cec5SDimitry Andric // predecessor to the worklist as a viable candidate for CFG-neutral 6750b57cec5SDimitry Andric // placement. No subsequent placement of this block will violate the CFG 6760b57cec5SDimitry Andric // shape, so we get to use heuristics to choose a favorable placement. 6770b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 6780b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(Succ)) 6790b57cec5SDimitry Andric continue; 6800b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 6810b57cec5SDimitry Andric // Disregard edges within a fixed chain, or edges to the loop header. 6820b57cec5SDimitry Andric if (&Chain == &SuccChain || Succ == LoopHeaderBB) 6830b57cec5SDimitry Andric continue; 6840b57cec5SDimitry Andric 6850b57cec5SDimitry Andric // This is a cross-chain edge that is within the loop, so decrement the 6860b57cec5SDimitry Andric // loop predecessor count of the destination chain. 6870b57cec5SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0 || 6880b57cec5SDimitry Andric --SuccChain.UnscheduledPredecessors > 0) 6890b57cec5SDimitry Andric continue; 6900b57cec5SDimitry Andric 6910b57cec5SDimitry Andric auto *NewBB = *SuccChain.begin(); 6920b57cec5SDimitry Andric if (NewBB->isEHPad()) 6930b57cec5SDimitry Andric EHPadWorkList.push_back(NewBB); 6940b57cec5SDimitry Andric else 6950b57cec5SDimitry Andric BlockWorkList.push_back(NewBB); 6960b57cec5SDimitry Andric } 6970b57cec5SDimitry Andric } 6980b57cec5SDimitry Andric 6990b57cec5SDimitry Andric /// This helper function collects the set of successors of block 7000b57cec5SDimitry Andric /// \p BB that are allowed to be its layout successors, and return 7010b57cec5SDimitry Andric /// the total branch probability of edges from \p BB to those 7020b57cec5SDimitry Andric /// blocks. 7030b57cec5SDimitry Andric BranchProbability MachineBlockPlacement::collectViableSuccessors( 7040b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 7050b57cec5SDimitry Andric const BlockFilterSet *BlockFilter, 7060b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors) { 7070b57cec5SDimitry Andric // Adjust edge probabilities by excluding edges pointing to blocks that is 7080b57cec5SDimitry Andric // either not in BlockFilter or is already in the current chain. Consider the 7090b57cec5SDimitry Andric // following CFG: 7100b57cec5SDimitry Andric // 7110b57cec5SDimitry Andric // --->A 7120b57cec5SDimitry Andric // | / \ 7130b57cec5SDimitry Andric // | B C 7140b57cec5SDimitry Andric // | \ / \ 7150b57cec5SDimitry Andric // ----D E 7160b57cec5SDimitry Andric // 7170b57cec5SDimitry Andric // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 7180b57cec5SDimitry Andric // A->C is chosen as a fall-through, D won't be selected as a successor of C 7190b57cec5SDimitry Andric // due to CFG constraint (the probability of C->D is not greater than 7200b57cec5SDimitry Andric // HotProb to break topo-order). If we exclude E that is not in BlockFilter 7210b57cec5SDimitry Andric // when calculating the probability of C->D, D will be selected and we 7220b57cec5SDimitry Andric // will get A C D B as the layout of this loop. 7230b57cec5SDimitry Andric auto AdjustedSumProb = BranchProbability::getOne(); 7240b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB->successors()) { 7250b57cec5SDimitry Andric bool SkipSucc = false; 7260b57cec5SDimitry Andric if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 7270b57cec5SDimitry Andric SkipSucc = true; 7280b57cec5SDimitry Andric } else { 7290b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 7300b57cec5SDimitry Andric if (SuccChain == &Chain) { 7310b57cec5SDimitry Andric SkipSucc = true; 7320b57cec5SDimitry Andric } else if (Succ != *SuccChain->begin()) { 7330b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(Succ) 7340b57cec5SDimitry Andric << " -> Mid chain!\n"); 7350b57cec5SDimitry Andric continue; 7360b57cec5SDimitry Andric } 7370b57cec5SDimitry Andric } 7380b57cec5SDimitry Andric if (SkipSucc) 7390b57cec5SDimitry Andric AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 7400b57cec5SDimitry Andric else 7410b57cec5SDimitry Andric Successors.push_back(Succ); 7420b57cec5SDimitry Andric } 7430b57cec5SDimitry Andric 7440b57cec5SDimitry Andric return AdjustedSumProb; 7450b57cec5SDimitry Andric } 7460b57cec5SDimitry Andric 7470b57cec5SDimitry Andric /// The helper function returns the branch probability that is adjusted 7480b57cec5SDimitry Andric /// or normalized over the new total \p AdjustedSumProb. 7490b57cec5SDimitry Andric static BranchProbability 7500b57cec5SDimitry Andric getAdjustedProbability(BranchProbability OrigProb, 7510b57cec5SDimitry Andric BranchProbability AdjustedSumProb) { 7520b57cec5SDimitry Andric BranchProbability SuccProb; 7530b57cec5SDimitry Andric uint32_t SuccProbN = OrigProb.getNumerator(); 7540b57cec5SDimitry Andric uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 7550b57cec5SDimitry Andric if (SuccProbN >= SuccProbD) 7560b57cec5SDimitry Andric SuccProb = BranchProbability::getOne(); 7570b57cec5SDimitry Andric else 7580b57cec5SDimitry Andric SuccProb = BranchProbability(SuccProbN, SuccProbD); 7590b57cec5SDimitry Andric 7600b57cec5SDimitry Andric return SuccProb; 7610b57cec5SDimitry Andric } 7620b57cec5SDimitry Andric 7630b57cec5SDimitry Andric /// Check if \p BB has exactly the successors in \p Successors. 7640b57cec5SDimitry Andric static bool 7650b57cec5SDimitry Andric hasSameSuccessors(MachineBasicBlock &BB, 7660b57cec5SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &Successors) { 7670b57cec5SDimitry Andric if (BB.succ_size() != Successors.size()) 7680b57cec5SDimitry Andric return false; 7690b57cec5SDimitry Andric // We don't want to count self-loops 7700b57cec5SDimitry Andric if (Successors.count(&BB)) 7710b57cec5SDimitry Andric return false; 7720b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) 7730b57cec5SDimitry Andric if (!Successors.count(Succ)) 7740b57cec5SDimitry Andric return false; 7750b57cec5SDimitry Andric return true; 7760b57cec5SDimitry Andric } 7770b57cec5SDimitry Andric 7780b57cec5SDimitry Andric /// Check if a block should be tail duplicated to increase fallthrough 7790b57cec5SDimitry Andric /// opportunities. 7800b57cec5SDimitry Andric /// \p BB Block to check. 7810b57cec5SDimitry Andric bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) { 7820b57cec5SDimitry Andric // Blocks with single successors don't create additional fallthrough 7830b57cec5SDimitry Andric // opportunities. Don't duplicate them. TODO: When conditional exits are 7840b57cec5SDimitry Andric // analyzable, allow them to be duplicated. 7850b57cec5SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 7860b57cec5SDimitry Andric 7870b57cec5SDimitry Andric if (BB->succ_size() == 1) 7880b57cec5SDimitry Andric return false; 7890b57cec5SDimitry Andric return TailDup.shouldTailDuplicate(IsSimple, *BB); 7900b57cec5SDimitry Andric } 7910b57cec5SDimitry Andric 7920b57cec5SDimitry Andric /// Compare 2 BlockFrequency's with a small penalty for \p A. 7930b57cec5SDimitry Andric /// In order to be conservative, we apply a X% penalty to account for 7940b57cec5SDimitry Andric /// increased icache pressure and static heuristics. For small frequencies 7950b57cec5SDimitry Andric /// we use only the numerators to improve accuracy. For simplicity, we assume the 7960b57cec5SDimitry Andric /// penalty is less than 100% 7970b57cec5SDimitry Andric /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere. 7980b57cec5SDimitry Andric static bool greaterWithBias(BlockFrequency A, BlockFrequency B, 7990b57cec5SDimitry Andric uint64_t EntryFreq) { 8000b57cec5SDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 8010b57cec5SDimitry Andric BlockFrequency Gain = A - B; 8020b57cec5SDimitry Andric return (Gain / ThresholdProb).getFrequency() >= EntryFreq; 8030b57cec5SDimitry Andric } 8040b57cec5SDimitry Andric 8050b57cec5SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 8060b57cec5SDimitry Andric /// fallthroughs. It only makes sense to call this function when 8070b57cec5SDimitry Andric /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is 8080b57cec5SDimitry Andric /// always locally profitable if we would have picked \p Succ without 8090b57cec5SDimitry Andric /// considering duplication. 8100b57cec5SDimitry Andric bool MachineBlockPlacement::isProfitableToTailDup( 8110b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 8120b57cec5SDimitry Andric BranchProbability QProb, 8130b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 8140b57cec5SDimitry Andric // We need to do a probability calculation to make sure this is profitable. 8150b57cec5SDimitry Andric // First: does succ have a successor that post-dominates? This affects the 8160b57cec5SDimitry Andric // calculation. The 2 relevant cases are: 8170b57cec5SDimitry Andric // BB BB 8180b57cec5SDimitry Andric // | \Qout | \Qout 8190b57cec5SDimitry Andric // P| C |P C 8200b57cec5SDimitry Andric // = C' = C' 8210b57cec5SDimitry Andric // | /Qin | /Qin 8220b57cec5SDimitry Andric // | / | / 8230b57cec5SDimitry Andric // Succ Succ 8240b57cec5SDimitry Andric // / \ | \ V 8250b57cec5SDimitry Andric // U/ =V |U \ 8260b57cec5SDimitry Andric // / \ = D 8270b57cec5SDimitry Andric // D E | / 8280b57cec5SDimitry Andric // | / 8290b57cec5SDimitry Andric // |/ 8300b57cec5SDimitry Andric // PDom 8310b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 8320b57cec5SDimitry Andric // In the second case, Placing Succ while duplicating it into C prevents the 8330b57cec5SDimitry Andric // fallthrough of Succ into either D or PDom, because they now have C as an 8340b57cec5SDimitry Andric // unplaced predecessor 8350b57cec5SDimitry Andric 8360b57cec5SDimitry Andric // Start by figuring out which case we fall into 8370b57cec5SDimitry Andric MachineBasicBlock *PDom = nullptr; 8380b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> SuccSuccs; 8390b57cec5SDimitry Andric // Only scan the relevant successors 8400b57cec5SDimitry Andric auto AdjustedSuccSumProb = 8410b57cec5SDimitry Andric collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs); 8420b57cec5SDimitry Andric BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ); 8430b57cec5SDimitry Andric auto BBFreq = MBFI->getBlockFreq(BB); 8440b57cec5SDimitry Andric auto SuccFreq = MBFI->getBlockFreq(Succ); 8450b57cec5SDimitry Andric BlockFrequency P = BBFreq * PProb; 8460b57cec5SDimitry Andric BlockFrequency Qout = BBFreq * QProb; 8470b57cec5SDimitry Andric uint64_t EntryFreq = MBFI->getEntryFreq(); 8480b57cec5SDimitry Andric // If there are no more successors, it is profitable to copy, as it strictly 8490b57cec5SDimitry Andric // increases fallthrough. 8500b57cec5SDimitry Andric if (SuccSuccs.size() == 0) 8510b57cec5SDimitry Andric return greaterWithBias(P, Qout, EntryFreq); 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric auto BestSuccSucc = BranchProbability::getZero(); 8540b57cec5SDimitry Andric // Find the PDom or the best Succ if no PDom exists. 8550b57cec5SDimitry Andric for (MachineBasicBlock *SuccSucc : SuccSuccs) { 8560b57cec5SDimitry Andric auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc); 8570b57cec5SDimitry Andric if (Prob > BestSuccSucc) 8580b57cec5SDimitry Andric BestSuccSucc = Prob; 8590b57cec5SDimitry Andric if (PDom == nullptr) 8600b57cec5SDimitry Andric if (MPDT->dominates(SuccSucc, Succ)) { 8610b57cec5SDimitry Andric PDom = SuccSucc; 8620b57cec5SDimitry Andric break; 8630b57cec5SDimitry Andric } 8640b57cec5SDimitry Andric } 8650b57cec5SDimitry Andric // For the comparisons, we need to know Succ's best incoming edge that isn't 8660b57cec5SDimitry Andric // from BB. 8670b57cec5SDimitry Andric auto SuccBestPred = BlockFrequency(0); 8680b57cec5SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 8690b57cec5SDimitry Andric if (SuccPred == Succ || SuccPred == BB 8700b57cec5SDimitry Andric || BlockToChain[SuccPred] == &Chain 8710b57cec5SDimitry Andric || (BlockFilter && !BlockFilter->count(SuccPred))) 8720b57cec5SDimitry Andric continue; 8730b57cec5SDimitry Andric auto Freq = MBFI->getBlockFreq(SuccPred) 8740b57cec5SDimitry Andric * MBPI->getEdgeProbability(SuccPred, Succ); 8750b57cec5SDimitry Andric if (Freq > SuccBestPred) 8760b57cec5SDimitry Andric SuccBestPred = Freq; 8770b57cec5SDimitry Andric } 8780b57cec5SDimitry Andric // Qin is Succ's best unplaced incoming edge that isn't BB 8790b57cec5SDimitry Andric BlockFrequency Qin = SuccBestPred; 8800b57cec5SDimitry Andric // If it doesn't have a post-dominating successor, here is the calculation: 8810b57cec5SDimitry Andric // BB BB 8820b57cec5SDimitry Andric // | \Qout | \ 8830b57cec5SDimitry Andric // P| C | = 8840b57cec5SDimitry Andric // = C' | C 8850b57cec5SDimitry Andric // | /Qin | | 8860b57cec5SDimitry Andric // | / | C' (+Succ) 8870b57cec5SDimitry Andric // Succ Succ /| 8880b57cec5SDimitry Andric // / \ | \/ | 8890b57cec5SDimitry Andric // U/ =V | == | 8900b57cec5SDimitry Andric // / \ | / \| 8910b57cec5SDimitry Andric // D E D E 8920b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 8930b57cec5SDimitry Andric // Cost in the first case is: P + V 8940b57cec5SDimitry Andric // For this calculation, we always assume P > Qout. If Qout > P 8950b57cec5SDimitry Andric // The result of this function will be ignored at the caller. 8960b57cec5SDimitry Andric // Let F = SuccFreq - Qin 8970b57cec5SDimitry Andric // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V 8980b57cec5SDimitry Andric 8990b57cec5SDimitry Andric if (PDom == nullptr || !Succ->isSuccessor(PDom)) { 9000b57cec5SDimitry Andric BranchProbability UProb = BestSuccSucc; 9010b57cec5SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 9020b57cec5SDimitry Andric BlockFrequency F = SuccFreq - Qin; 9030b57cec5SDimitry Andric BlockFrequency V = SuccFreq * VProb; 9040b57cec5SDimitry Andric BlockFrequency QinU = std::min(Qin, F) * UProb; 9050b57cec5SDimitry Andric BlockFrequency BaseCost = P + V; 9060b57cec5SDimitry Andric BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb; 9070b57cec5SDimitry Andric return greaterWithBias(BaseCost, DupCost, EntryFreq); 9080b57cec5SDimitry Andric } 9090b57cec5SDimitry Andric BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom); 9100b57cec5SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 9110b57cec5SDimitry Andric BlockFrequency U = SuccFreq * UProb; 9120b57cec5SDimitry Andric BlockFrequency V = SuccFreq * VProb; 9130b57cec5SDimitry Andric BlockFrequency F = SuccFreq - Qin; 9140b57cec5SDimitry Andric // If there is a post-dominating successor, here is the calculation: 9150b57cec5SDimitry Andric // BB BB BB BB 9160b57cec5SDimitry Andric // | \Qout | \ | \Qout | \ 9170b57cec5SDimitry Andric // |P C | = |P C | = 9180b57cec5SDimitry Andric // = C' |P C = C' |P C 9190b57cec5SDimitry Andric // | /Qin | | | /Qin | | 9200b57cec5SDimitry Andric // | / | C' (+Succ) | / | C' (+Succ) 9210b57cec5SDimitry Andric // Succ Succ /| Succ Succ /| 9220b57cec5SDimitry Andric // | \ V | \/ | | \ V | \/ | 9230b57cec5SDimitry Andric // |U \ |U /\ =? |U = |U /\ | 9240b57cec5SDimitry Andric // = D = = =?| | D | = =| 9250b57cec5SDimitry Andric // | / |/ D | / |/ D 9260b57cec5SDimitry Andric // | / | / | = | / 9270b57cec5SDimitry Andric // |/ | / |/ | = 9280b57cec5SDimitry Andric // Dom Dom Dom Dom 9290b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 9300b57cec5SDimitry Andric // The cost for taken branches in the first case is P + U 9310b57cec5SDimitry Andric // Let F = SuccFreq - Qin 9320b57cec5SDimitry Andric // The cost in the second case (assuming independence), given the layout: 9330b57cec5SDimitry Andric // BB, Succ, (C+Succ), D, Dom or the layout: 9340b57cec5SDimitry Andric // BB, Succ, D, Dom, (C+Succ) 9350b57cec5SDimitry Andric // is Qout + max(F, Qin) * U + min(F, Qin) 9360b57cec5SDimitry Andric // compare P + U vs Qout + P * U + Qin. 9370b57cec5SDimitry Andric // 9380b57cec5SDimitry Andric // The 3rd and 4th cases cover when Dom would be chosen to follow Succ. 9390b57cec5SDimitry Andric // 9400b57cec5SDimitry Andric // For the 3rd case, the cost is P + 2 * V 9410b57cec5SDimitry Andric // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V 9420b57cec5SDimitry Andric // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V 9430b57cec5SDimitry Andric if (UProb > AdjustedSuccSumProb / 2 && 9440b57cec5SDimitry Andric !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb, 9450b57cec5SDimitry Andric Chain, BlockFilter)) 9460b57cec5SDimitry Andric // Cases 3 & 4 9470b57cec5SDimitry Andric return greaterWithBias( 9480b57cec5SDimitry Andric (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb), 9490b57cec5SDimitry Andric EntryFreq); 9500b57cec5SDimitry Andric // Cases 1 & 2 9510b57cec5SDimitry Andric return greaterWithBias((P + U), 9520b57cec5SDimitry Andric (Qout + std::min(Qin, F) * AdjustedSuccSumProb + 9530b57cec5SDimitry Andric std::max(Qin, F) * UProb), 9540b57cec5SDimitry Andric EntryFreq); 9550b57cec5SDimitry Andric } 9560b57cec5SDimitry Andric 9570b57cec5SDimitry Andric /// Check for a trellis layout. \p BB is the upper part of a trellis if its 9580b57cec5SDimitry Andric /// successors form the lower part of a trellis. A successor set S forms the 9590b57cec5SDimitry Andric /// lower part of a trellis if all of the predecessors of S are either in S or 9600b57cec5SDimitry Andric /// have all of S as successors. We ignore trellises where BB doesn't have 2 9610b57cec5SDimitry Andric /// successors because for fewer than 2, it's trivial, and for 3 or greater they 9620b57cec5SDimitry Andric /// are very uncommon and complex to compute optimally. Allowing edges within S 9630b57cec5SDimitry Andric /// is not strictly a trellis, but the same algorithm works, so we allow it. 9640b57cec5SDimitry Andric bool MachineBlockPlacement::isTrellis( 9650b57cec5SDimitry Andric const MachineBasicBlock *BB, 9660b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 9670b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 9680b57cec5SDimitry Andric // Technically BB could form a trellis with branching factor higher than 2. 9690b57cec5SDimitry Andric // But that's extremely uncommon. 9700b57cec5SDimitry Andric if (BB->succ_size() != 2 || ViableSuccs.size() != 2) 9710b57cec5SDimitry Andric return false; 9720b57cec5SDimitry Andric 9730b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(), 9740b57cec5SDimitry Andric BB->succ_end()); 9750b57cec5SDimitry Andric // To avoid reviewing the same predecessors twice. 9760b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds; 9770b57cec5SDimitry Andric 9780b57cec5SDimitry Andric for (MachineBasicBlock *Succ : ViableSuccs) { 9790b57cec5SDimitry Andric int PredCount = 0; 980fcaf7f86SDimitry Andric for (auto *SuccPred : Succ->predecessors()) { 9810b57cec5SDimitry Andric // Allow triangle successors, but don't count them. 9820b57cec5SDimitry Andric if (Successors.count(SuccPred)) { 9830b57cec5SDimitry Andric // Make sure that it is actually a triangle. 9840b57cec5SDimitry Andric for (MachineBasicBlock *CheckSucc : SuccPred->successors()) 9850b57cec5SDimitry Andric if (!Successors.count(CheckSucc)) 9860b57cec5SDimitry Andric return false; 9870b57cec5SDimitry Andric continue; 9880b57cec5SDimitry Andric } 9890b57cec5SDimitry Andric const BlockChain *PredChain = BlockToChain[SuccPred]; 9900b57cec5SDimitry Andric if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) || 9910b57cec5SDimitry Andric PredChain == &Chain || PredChain == BlockToChain[Succ]) 9920b57cec5SDimitry Andric continue; 9930b57cec5SDimitry Andric ++PredCount; 9940b57cec5SDimitry Andric // Perform the successor check only once. 9950b57cec5SDimitry Andric if (!SeenPreds.insert(SuccPred).second) 9960b57cec5SDimitry Andric continue; 9970b57cec5SDimitry Andric if (!hasSameSuccessors(*SuccPred, Successors)) 9980b57cec5SDimitry Andric return false; 9990b57cec5SDimitry Andric } 10000b57cec5SDimitry Andric // If one of the successors has only BB as a predecessor, it is not a 10010b57cec5SDimitry Andric // trellis. 10020b57cec5SDimitry Andric if (PredCount < 1) 10030b57cec5SDimitry Andric return false; 10040b57cec5SDimitry Andric } 10050b57cec5SDimitry Andric return true; 10060b57cec5SDimitry Andric } 10070b57cec5SDimitry Andric 10080b57cec5SDimitry Andric /// Pick the highest total weight pair of edges that can both be laid out. 10090b57cec5SDimitry Andric /// The edges in \p Edges[0] are assumed to have a different destination than 10100b57cec5SDimitry Andric /// the edges in \p Edges[1]. Simple counting shows that the best pair is either 10110b57cec5SDimitry Andric /// the individual highest weight edges to the 2 different destinations, or in 10120b57cec5SDimitry Andric /// case of a conflict, one of them should be replaced with a 2nd best edge. 10130b57cec5SDimitry Andric std::pair<MachineBlockPlacement::WeightedEdge, 10140b57cec5SDimitry Andric MachineBlockPlacement::WeightedEdge> 10150b57cec5SDimitry Andric MachineBlockPlacement::getBestNonConflictingEdges( 10160b57cec5SDimitry Andric const MachineBasicBlock *BB, 10170b57cec5SDimitry Andric MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>> 10180b57cec5SDimitry Andric Edges) { 10190b57cec5SDimitry Andric // Sort the edges, and then for each successor, find the best incoming 10200b57cec5SDimitry Andric // predecessor. If the best incoming predecessors aren't the same, 10210b57cec5SDimitry Andric // then that is clearly the best layout. If there is a conflict, one of the 10220b57cec5SDimitry Andric // successors will have to fallthrough from the second best predecessor. We 10230b57cec5SDimitry Andric // compare which combination is better overall. 10240b57cec5SDimitry Andric 10250b57cec5SDimitry Andric // Sort for highest frequency. 10260b57cec5SDimitry Andric auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; }; 10270b57cec5SDimitry Andric 10280b57cec5SDimitry Andric llvm::stable_sort(Edges[0], Cmp); 10290b57cec5SDimitry Andric llvm::stable_sort(Edges[1], Cmp); 10300b57cec5SDimitry Andric auto BestA = Edges[0].begin(); 10310b57cec5SDimitry Andric auto BestB = Edges[1].begin(); 10320b57cec5SDimitry Andric // Arrange for the correct answer to be in BestA and BestB 10330b57cec5SDimitry Andric // If the 2 best edges don't conflict, the answer is already there. 10340b57cec5SDimitry Andric if (BestA->Src == BestB->Src) { 10350b57cec5SDimitry Andric // Compare the total fallthrough of (Best + Second Best) for both pairs 10360b57cec5SDimitry Andric auto SecondBestA = std::next(BestA); 10370b57cec5SDimitry Andric auto SecondBestB = std::next(BestB); 10380b57cec5SDimitry Andric BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight; 10390b57cec5SDimitry Andric BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight; 10400b57cec5SDimitry Andric if (BestAScore < BestBScore) 10410b57cec5SDimitry Andric BestA = SecondBestA; 10420b57cec5SDimitry Andric else 10430b57cec5SDimitry Andric BestB = SecondBestB; 10440b57cec5SDimitry Andric } 10450b57cec5SDimitry Andric // Arrange for the BB edge to be in BestA if it exists. 10460b57cec5SDimitry Andric if (BestB->Src == BB) 10470b57cec5SDimitry Andric std::swap(BestA, BestB); 10480b57cec5SDimitry Andric return std::make_pair(*BestA, *BestB); 10490b57cec5SDimitry Andric } 10500b57cec5SDimitry Andric 10510b57cec5SDimitry Andric /// Get the best successor from \p BB based on \p BB being part of a trellis. 10520b57cec5SDimitry Andric /// We only handle trellises with 2 successors, so the algorithm is 10530b57cec5SDimitry Andric /// straightforward: Find the best pair of edges that don't conflict. We find 10540b57cec5SDimitry Andric /// the best incoming edge for each successor in the trellis. If those conflict, 10550b57cec5SDimitry Andric /// we consider which of them should be replaced with the second best. 10560b57cec5SDimitry Andric /// Upon return the two best edges will be in \p BestEdges. If one of the edges 10570b57cec5SDimitry Andric /// comes from \p BB, it will be in \p BestEdges[0] 10580b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 10590b57cec5SDimitry Andric MachineBlockPlacement::getBestTrellisSuccessor( 10600b57cec5SDimitry Andric const MachineBasicBlock *BB, 10610b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 10620b57cec5SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 10630b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 10640b57cec5SDimitry Andric 10650b57cec5SDimitry Andric BlockAndTailDupResult Result = {nullptr, false}; 10660b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 10670b57cec5SDimitry Andric BB->succ_end()); 10680b57cec5SDimitry Andric 10690b57cec5SDimitry Andric // We assume size 2 because it's common. For general n, we would have to do 10700b57cec5SDimitry Andric // the Hungarian algorithm, but it's not worth the complexity because more 10710b57cec5SDimitry Andric // than 2 successors is fairly uncommon, and a trellis even more so. 10720b57cec5SDimitry Andric if (Successors.size() != 2 || ViableSuccs.size() != 2) 10730b57cec5SDimitry Andric return Result; 10740b57cec5SDimitry Andric 10750b57cec5SDimitry Andric // Collect the edge frequencies of all edges that form the trellis. 10760b57cec5SDimitry Andric SmallVector<WeightedEdge, 8> Edges[2]; 10770b57cec5SDimitry Andric int SuccIndex = 0; 1078fcaf7f86SDimitry Andric for (auto *Succ : ViableSuccs) { 10790b57cec5SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 10800b57cec5SDimitry Andric // Skip any placed predecessors that are not BB 10810b57cec5SDimitry Andric if (SuccPred != BB) 10820b57cec5SDimitry Andric if ((BlockFilter && !BlockFilter->count(SuccPred)) || 10830b57cec5SDimitry Andric BlockToChain[SuccPred] == &Chain || 10840b57cec5SDimitry Andric BlockToChain[SuccPred] == BlockToChain[Succ]) 10850b57cec5SDimitry Andric continue; 10860b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) * 10870b57cec5SDimitry Andric MBPI->getEdgeProbability(SuccPred, Succ); 10880b57cec5SDimitry Andric Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ}); 10890b57cec5SDimitry Andric } 10900b57cec5SDimitry Andric ++SuccIndex; 10910b57cec5SDimitry Andric } 10920b57cec5SDimitry Andric 10930b57cec5SDimitry Andric // Pick the best combination of 2 edges from all the edges in the trellis. 10940b57cec5SDimitry Andric WeightedEdge BestA, BestB; 10950b57cec5SDimitry Andric std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges); 10960b57cec5SDimitry Andric 10970b57cec5SDimitry Andric if (BestA.Src != BB) { 10980b57cec5SDimitry Andric // If we have a trellis, and BB doesn't have the best fallthrough edges, 10990b57cec5SDimitry Andric // we shouldn't choose any successor. We've already looked and there's a 11000b57cec5SDimitry Andric // better fallthrough edge for all the successors. 11010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n"); 11020b57cec5SDimitry Andric return Result; 11030b57cec5SDimitry Andric } 11040b57cec5SDimitry Andric 11050b57cec5SDimitry Andric // Did we pick the triangle edge? If tail-duplication is profitable, do 11060b57cec5SDimitry Andric // that instead. Otherwise merge the triangle edge now while we know it is 11070b57cec5SDimitry Andric // optimal. 11080b57cec5SDimitry Andric if (BestA.Dest == BestB.Src) { 11090b57cec5SDimitry Andric // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2 11100b57cec5SDimitry Andric // would be better. 11110b57cec5SDimitry Andric MachineBasicBlock *Succ1 = BestA.Dest; 11120b57cec5SDimitry Andric MachineBasicBlock *Succ2 = BestB.Dest; 11130b57cec5SDimitry Andric // Check to see if tail-duplication would be profitable. 11140b57cec5SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) && 11150b57cec5SDimitry Andric canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) && 11160b57cec5SDimitry Andric isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1), 11170b57cec5SDimitry Andric Chain, BlockFilter)) { 11180b57cec5SDimitry Andric LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability( 11190b57cec5SDimitry Andric MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb); 11200b57cec5SDimitry Andric dbgs() << " Selected: " << getBlockName(Succ2) 11210b57cec5SDimitry Andric << ", probability: " << Succ2Prob 11220b57cec5SDimitry Andric << " (Tail Duplicate)\n"); 11230b57cec5SDimitry Andric Result.BB = Succ2; 11240b57cec5SDimitry Andric Result.ShouldTailDup = true; 11250b57cec5SDimitry Andric return Result; 11260b57cec5SDimitry Andric } 11270b57cec5SDimitry Andric } 11280b57cec5SDimitry Andric // We have already computed the optimal edge for the other side of the 11290b57cec5SDimitry Andric // trellis. 11300b57cec5SDimitry Andric ComputedEdges[BestB.Src] = { BestB.Dest, false }; 11310b57cec5SDimitry Andric 11320b57cec5SDimitry Andric auto TrellisSucc = BestA.Dest; 11330b57cec5SDimitry Andric LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability( 11340b57cec5SDimitry Andric MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb); 11350b57cec5SDimitry Andric dbgs() << " Selected: " << getBlockName(TrellisSucc) 11360b57cec5SDimitry Andric << ", probability: " << SuccProb << " (Trellis)\n"); 11370b57cec5SDimitry Andric Result.BB = TrellisSucc; 11380b57cec5SDimitry Andric return Result; 11390b57cec5SDimitry Andric } 11400b57cec5SDimitry Andric 11410b57cec5SDimitry Andric /// When the option allowTailDupPlacement() is on, this method checks if the 11420b57cec5SDimitry Andric /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated 11430b57cec5SDimitry Andric /// into all of its unplaced, unfiltered predecessors, that are not BB. 11440b57cec5SDimitry Andric bool MachineBlockPlacement::canTailDuplicateUnplacedPreds( 11450b57cec5SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 11460b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 11470b57cec5SDimitry Andric if (!shouldTailDuplicate(Succ)) 11480b57cec5SDimitry Andric return false; 11490b57cec5SDimitry Andric 1150480093f4SDimitry Andric // The result of canTailDuplicate. 1151480093f4SDimitry Andric bool Duplicate = true; 1152480093f4SDimitry Andric // Number of possible duplication. 1153480093f4SDimitry Andric unsigned int NumDup = 0; 1154480093f4SDimitry Andric 11550b57cec5SDimitry Andric // For CFG checking. 11560b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 11570b57cec5SDimitry Andric BB->succ_end()); 11580b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 11590b57cec5SDimitry Andric // Make sure all unplaced and unfiltered predecessors can be 11600b57cec5SDimitry Andric // tail-duplicated into. 11610b57cec5SDimitry Andric // Skip any blocks that are already placed or not in this loop. 11620b57cec5SDimitry Andric if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) 11630b57cec5SDimitry Andric || BlockToChain[Pred] == &Chain) 11640b57cec5SDimitry Andric continue; 11650b57cec5SDimitry Andric if (!TailDup.canTailDuplicate(Succ, Pred)) { 11660b57cec5SDimitry Andric if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors)) 11670b57cec5SDimitry Andric // This will result in a trellis after tail duplication, so we don't 11680b57cec5SDimitry Andric // need to copy Succ into this predecessor. In the presence 11690b57cec5SDimitry Andric // of a trellis tail duplication can continue to be profitable. 11700b57cec5SDimitry Andric // For example: 11710b57cec5SDimitry Andric // A A 11720b57cec5SDimitry Andric // |\ |\ 11730b57cec5SDimitry Andric // | \ | \ 11740b57cec5SDimitry Andric // | C | C+BB 11750b57cec5SDimitry Andric // | / | | 11760b57cec5SDimitry Andric // |/ | | 11770b57cec5SDimitry Andric // BB => BB | 11780b57cec5SDimitry Andric // |\ |\/| 11790b57cec5SDimitry Andric // | \ |/\| 11800b57cec5SDimitry Andric // | D | D 11810b57cec5SDimitry Andric // | / | / 11820b57cec5SDimitry Andric // |/ |/ 11830b57cec5SDimitry Andric // Succ Succ 11840b57cec5SDimitry Andric // 11850b57cec5SDimitry Andric // After BB was duplicated into C, the layout looks like the one on the 11860b57cec5SDimitry Andric // right. BB and C now have the same successors. When considering 11870b57cec5SDimitry Andric // whether Succ can be duplicated into all its unplaced predecessors, we 11880b57cec5SDimitry Andric // ignore C. 11890b57cec5SDimitry Andric // We can do this because C already has a profitable fallthrough, namely 11900b57cec5SDimitry Andric // D. TODO(iteratee): ignore sufficiently cold predecessors for 11910b57cec5SDimitry Andric // duplication and for this test. 11920b57cec5SDimitry Andric // 11930b57cec5SDimitry Andric // This allows trellises to be laid out in 2 separate chains 11940b57cec5SDimitry Andric // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic 11950b57cec5SDimitry Andric // because it allows the creation of 2 fallthrough paths with links 11960b57cec5SDimitry Andric // between them, and we correctly identify the best layout for these 11970b57cec5SDimitry Andric // CFGs. We want to extend trellises that the user created in addition 11980b57cec5SDimitry Andric // to trellises created by tail-duplication, so we just look for the 11990b57cec5SDimitry Andric // CFG. 12000b57cec5SDimitry Andric continue; 1201480093f4SDimitry Andric Duplicate = false; 1202480093f4SDimitry Andric continue; 1203480093f4SDimitry Andric } 1204480093f4SDimitry Andric NumDup++; 1205480093f4SDimitry Andric } 1206480093f4SDimitry Andric 1207480093f4SDimitry Andric // No possible duplication in current filter set. 1208480093f4SDimitry Andric if (NumDup == 0) 12090b57cec5SDimitry Andric return false; 1210480093f4SDimitry Andric 12115ffd83dbSDimitry Andric // If profile information is available, findDuplicateCandidates can do more 12125ffd83dbSDimitry Andric // precise benefit analysis. 12135ffd83dbSDimitry Andric if (F->getFunction().hasProfileData()) 12145ffd83dbSDimitry Andric return true; 12155ffd83dbSDimitry Andric 1216480093f4SDimitry Andric // This is mainly for function exit BB. 1217480093f4SDimitry Andric // The integrated tail duplication is really designed for increasing 1218480093f4SDimitry Andric // fallthrough from predecessors from Succ to its successors. We may need 1219480093f4SDimitry Andric // other machanism to handle different cases. 1220349cc55cSDimitry Andric if (Succ->succ_empty()) 1221480093f4SDimitry Andric return true; 1222480093f4SDimitry Andric 1223480093f4SDimitry Andric // Plus the already placed predecessor. 1224480093f4SDimitry Andric NumDup++; 1225480093f4SDimitry Andric 1226480093f4SDimitry Andric // If the duplication candidate has more unplaced predecessors than 1227480093f4SDimitry Andric // successors, the extra duplication can't bring more fallthrough. 1228480093f4SDimitry Andric // 1229480093f4SDimitry Andric // Pred1 Pred2 Pred3 1230480093f4SDimitry Andric // \ | / 1231480093f4SDimitry Andric // \ | / 1232480093f4SDimitry Andric // \ | / 1233480093f4SDimitry Andric // Dup 1234480093f4SDimitry Andric // / \ 1235480093f4SDimitry Andric // / \ 1236480093f4SDimitry Andric // Succ1 Succ2 1237480093f4SDimitry Andric // 1238480093f4SDimitry Andric // In this example Dup has 2 successors and 3 predecessors, duplication of Dup 1239480093f4SDimitry Andric // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2, 1240480093f4SDimitry Andric // but the duplication into Pred3 can't increase fallthrough. 1241480093f4SDimitry Andric // 1242480093f4SDimitry Andric // A small number of extra duplication may not hurt too much. We need a better 1243480093f4SDimitry Andric // heuristic to handle it. 1244480093f4SDimitry Andric if ((NumDup > Succ->succ_size()) || !Duplicate) 1245480093f4SDimitry Andric return false; 1246480093f4SDimitry Andric 12470b57cec5SDimitry Andric return true; 12480b57cec5SDimitry Andric } 12490b57cec5SDimitry Andric 12500b57cec5SDimitry Andric /// Find chains of triangles where we believe it would be profitable to 12510b57cec5SDimitry Andric /// tail-duplicate them all, but a local analysis would not find them. 12520b57cec5SDimitry Andric /// There are 3 ways this can be profitable: 12530b57cec5SDimitry Andric /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with 12540b57cec5SDimitry Andric /// longer chains) 12550b57cec5SDimitry Andric /// 2) The chains are statically correlated. Branch probabilities have a very 12560b57cec5SDimitry Andric /// U-shaped distribution. 12570b57cec5SDimitry Andric /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805] 12580b57cec5SDimitry Andric /// If the branches in a chain are likely to be from the same side of the 12590b57cec5SDimitry Andric /// distribution as their predecessor, but are independent at runtime, this 12600b57cec5SDimitry Andric /// transformation is profitable. (Because the cost of being wrong is a small 12610b57cec5SDimitry Andric /// fixed cost, unlike the standard triangle layout where the cost of being 12620b57cec5SDimitry Andric /// wrong scales with the # of triangles.) 12630b57cec5SDimitry Andric /// 3) The chains are dynamically correlated. If the probability that a previous 12640b57cec5SDimitry Andric /// branch was taken positively influences whether the next branch will be 12650b57cec5SDimitry Andric /// taken 12660b57cec5SDimitry Andric /// We believe that 2 and 3 are common enough to justify the small margin in 1. 12670b57cec5SDimitry Andric void MachineBlockPlacement::precomputeTriangleChains() { 12680b57cec5SDimitry Andric struct TriangleChain { 12690b57cec5SDimitry Andric std::vector<MachineBasicBlock *> Edges; 12700b57cec5SDimitry Andric 12710b57cec5SDimitry Andric TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst) 12720b57cec5SDimitry Andric : Edges({src, dst}) {} 12730b57cec5SDimitry Andric 12740b57cec5SDimitry Andric void append(MachineBasicBlock *dst) { 12750b57cec5SDimitry Andric assert(getKey()->isSuccessor(dst) && 12760b57cec5SDimitry Andric "Attempting to append a block that is not a successor."); 12770b57cec5SDimitry Andric Edges.push_back(dst); 12780b57cec5SDimitry Andric } 12790b57cec5SDimitry Andric 12800b57cec5SDimitry Andric unsigned count() const { return Edges.size() - 1; } 12810b57cec5SDimitry Andric 12820b57cec5SDimitry Andric MachineBasicBlock *getKey() const { 12830b57cec5SDimitry Andric return Edges.back(); 12840b57cec5SDimitry Andric } 12850b57cec5SDimitry Andric }; 12860b57cec5SDimitry Andric 12870b57cec5SDimitry Andric if (TriangleChainCount == 0) 12880b57cec5SDimitry Andric return; 12890b57cec5SDimitry Andric 12900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n"); 12910b57cec5SDimitry Andric // Map from last block to the chain that contains it. This allows us to extend 12920b57cec5SDimitry Andric // chains as we find new triangles. 12930b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap; 12940b57cec5SDimitry Andric for (MachineBasicBlock &BB : *F) { 12950b57cec5SDimitry Andric // If BB doesn't have 2 successors, it doesn't start a triangle. 12960b57cec5SDimitry Andric if (BB.succ_size() != 2) 12970b57cec5SDimitry Andric continue; 12980b57cec5SDimitry Andric MachineBasicBlock *PDom = nullptr; 12990b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) { 13000b57cec5SDimitry Andric if (!MPDT->dominates(Succ, &BB)) 13010b57cec5SDimitry Andric continue; 13020b57cec5SDimitry Andric PDom = Succ; 13030b57cec5SDimitry Andric break; 13040b57cec5SDimitry Andric } 13050b57cec5SDimitry Andric // If BB doesn't have a post-dominating successor, it doesn't form a 13060b57cec5SDimitry Andric // triangle. 13070b57cec5SDimitry Andric if (PDom == nullptr) 13080b57cec5SDimitry Andric continue; 13090b57cec5SDimitry Andric // If PDom has a hint that it is low probability, skip this triangle. 13100b57cec5SDimitry Andric if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100)) 13110b57cec5SDimitry Andric continue; 13120b57cec5SDimitry Andric // If PDom isn't eligible for duplication, this isn't the kind of triangle 13130b57cec5SDimitry Andric // we're looking for. 13140b57cec5SDimitry Andric if (!shouldTailDuplicate(PDom)) 13150b57cec5SDimitry Andric continue; 13160b57cec5SDimitry Andric bool CanTailDuplicate = true; 13170b57cec5SDimitry Andric // If PDom can't tail-duplicate into it's non-BB predecessors, then this 13180b57cec5SDimitry Andric // isn't the kind of triangle we're looking for. 13190b57cec5SDimitry Andric for (MachineBasicBlock* Pred : PDom->predecessors()) { 13200b57cec5SDimitry Andric if (Pred == &BB) 13210b57cec5SDimitry Andric continue; 13220b57cec5SDimitry Andric if (!TailDup.canTailDuplicate(PDom, Pred)) { 13230b57cec5SDimitry Andric CanTailDuplicate = false; 13240b57cec5SDimitry Andric break; 13250b57cec5SDimitry Andric } 13260b57cec5SDimitry Andric } 13270b57cec5SDimitry Andric // If we can't tail-duplicate PDom to its predecessors, then skip this 13280b57cec5SDimitry Andric // triangle. 13290b57cec5SDimitry Andric if (!CanTailDuplicate) 13300b57cec5SDimitry Andric continue; 13310b57cec5SDimitry Andric 13320b57cec5SDimitry Andric // Now we have an interesting triangle. Insert it if it's not part of an 13330b57cec5SDimitry Andric // existing chain. 13340b57cec5SDimitry Andric // Note: This cannot be replaced with a call insert() or emplace() because 13350b57cec5SDimitry Andric // the find key is BB, but the insert/emplace key is PDom. 13360b57cec5SDimitry Andric auto Found = TriangleChainMap.find(&BB); 13370b57cec5SDimitry Andric // If it is, remove the chain from the map, grow it, and put it back in the 13380b57cec5SDimitry Andric // map with the end as the new key. 13390b57cec5SDimitry Andric if (Found != TriangleChainMap.end()) { 13400b57cec5SDimitry Andric TriangleChain Chain = std::move(Found->second); 13410b57cec5SDimitry Andric TriangleChainMap.erase(Found); 13420b57cec5SDimitry Andric Chain.append(PDom); 13430b57cec5SDimitry Andric TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain))); 13440b57cec5SDimitry Andric } else { 13450b57cec5SDimitry Andric auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom); 13460b57cec5SDimitry Andric assert(InsertResult.second && "Block seen twice."); 13470b57cec5SDimitry Andric (void)InsertResult; 13480b57cec5SDimitry Andric } 13490b57cec5SDimitry Andric } 13500b57cec5SDimitry Andric 13510b57cec5SDimitry Andric // Iterating over a DenseMap is safe here, because the only thing in the body 13520b57cec5SDimitry Andric // of the loop is inserting into another DenseMap (ComputedEdges). 13530b57cec5SDimitry Andric // ComputedEdges is never iterated, so this doesn't lead to non-determinism. 13540b57cec5SDimitry Andric for (auto &ChainPair : TriangleChainMap) { 13550b57cec5SDimitry Andric TriangleChain &Chain = ChainPair.second; 13560b57cec5SDimitry Andric // Benchmarking has shown that due to branch correlation duplicating 2 or 13570b57cec5SDimitry Andric // more triangles is profitable, despite the calculations assuming 13580b57cec5SDimitry Andric // independence. 13590b57cec5SDimitry Andric if (Chain.count() < TriangleChainCount) 13600b57cec5SDimitry Andric continue; 13610b57cec5SDimitry Andric MachineBasicBlock *dst = Chain.Edges.back(); 13620b57cec5SDimitry Andric Chain.Edges.pop_back(); 13630b57cec5SDimitry Andric for (MachineBasicBlock *src : reverse(Chain.Edges)) { 13640b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" 13650b57cec5SDimitry Andric << getBlockName(dst) 13660b57cec5SDimitry Andric << " as pre-computed based on triangles.\n"); 13670b57cec5SDimitry Andric 13680b57cec5SDimitry Andric auto InsertResult = ComputedEdges.insert({src, {dst, true}}); 13690b57cec5SDimitry Andric assert(InsertResult.second && "Block seen twice."); 13700b57cec5SDimitry Andric (void)InsertResult; 13710b57cec5SDimitry Andric 13720b57cec5SDimitry Andric dst = src; 13730b57cec5SDimitry Andric } 13740b57cec5SDimitry Andric } 13750b57cec5SDimitry Andric } 13760b57cec5SDimitry Andric 13770b57cec5SDimitry Andric // When profile is not present, return the StaticLikelyProb. 13780b57cec5SDimitry Andric // When profile is available, we need to handle the triangle-shape CFG. 13790b57cec5SDimitry Andric static BranchProbability getLayoutSuccessorProbThreshold( 13800b57cec5SDimitry Andric const MachineBasicBlock *BB) { 13810b57cec5SDimitry Andric if (!BB->getParent()->getFunction().hasProfileData()) 13820b57cec5SDimitry Andric return BranchProbability(StaticLikelyProb, 100); 13830b57cec5SDimitry Andric if (BB->succ_size() == 2) { 13840b57cec5SDimitry Andric const MachineBasicBlock *Succ1 = *BB->succ_begin(); 13850b57cec5SDimitry Andric const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 13860b57cec5SDimitry Andric if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 13870b57cec5SDimitry Andric /* See case 1 below for the cost analysis. For BB->Succ to 13880b57cec5SDimitry Andric * be taken with smaller cost, the following needs to hold: 13890b57cec5SDimitry Andric * Prob(BB->Succ) > 2 * Prob(BB->Pred) 13900b57cec5SDimitry Andric * So the threshold T in the calculation below 13910b57cec5SDimitry Andric * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred) 13920b57cec5SDimitry Andric * So T / (1 - T) = 2, Yielding T = 2/3 13930b57cec5SDimitry Andric * Also adding user specified branch bias, we have 13940b57cec5SDimitry Andric * T = (2/3)*(ProfileLikelyProb/50) 13950b57cec5SDimitry Andric * = (2*ProfileLikelyProb)/150) 13960b57cec5SDimitry Andric */ 13970b57cec5SDimitry Andric return BranchProbability(2 * ProfileLikelyProb, 150); 13980b57cec5SDimitry Andric } 13990b57cec5SDimitry Andric } 14000b57cec5SDimitry Andric return BranchProbability(ProfileLikelyProb, 100); 14010b57cec5SDimitry Andric } 14020b57cec5SDimitry Andric 14030b57cec5SDimitry Andric /// Checks to see if the layout candidate block \p Succ has a better layout 14040b57cec5SDimitry Andric /// predecessor than \c BB. If yes, returns true. 14050b57cec5SDimitry Andric /// \p SuccProb: The probability adjusted for only remaining blocks. 14060b57cec5SDimitry Andric /// Only used for logging 14070b57cec5SDimitry Andric /// \p RealSuccProb: The un-adjusted probability. 14080b57cec5SDimitry Andric /// \p Chain: The chain that BB belongs to and Succ is being considered for. 14090b57cec5SDimitry Andric /// \p BlockFilter: if non-null, the set of blocks that make up the loop being 14100b57cec5SDimitry Andric /// considered 14110b57cec5SDimitry Andric bool MachineBlockPlacement::hasBetterLayoutPredecessor( 14120b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 14130b57cec5SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 14140b57cec5SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 14150b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 14160b57cec5SDimitry Andric 14170b57cec5SDimitry Andric // There isn't a better layout when there are no unscheduled predecessors. 14180b57cec5SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0) 14190b57cec5SDimitry Andric return false; 14200b57cec5SDimitry Andric 14210b57cec5SDimitry Andric // There are two basic scenarios here: 14220b57cec5SDimitry Andric // ------------------------------------- 14230b57cec5SDimitry Andric // Case 1: triangular shape CFG (if-then): 14240b57cec5SDimitry Andric // BB 14250b57cec5SDimitry Andric // | \ 14260b57cec5SDimitry Andric // | \ 14270b57cec5SDimitry Andric // | Pred 14280b57cec5SDimitry Andric // | / 14290b57cec5SDimitry Andric // Succ 14300b57cec5SDimitry Andric // In this case, we are evaluating whether to select edge -> Succ, e.g. 14310b57cec5SDimitry Andric // set Succ as the layout successor of BB. Picking Succ as BB's 14320b57cec5SDimitry Andric // successor breaks the CFG constraints (FIXME: define these constraints). 14330b57cec5SDimitry Andric // With this layout, Pred BB 14340b57cec5SDimitry Andric // is forced to be outlined, so the overall cost will be cost of the 14350b57cec5SDimitry Andric // branch taken from BB to Pred, plus the cost of back taken branch 14360b57cec5SDimitry Andric // from Pred to Succ, as well as the additional cost associated 14370b57cec5SDimitry Andric // with the needed unconditional jump instruction from Pred To Succ. 14380b57cec5SDimitry Andric 14390b57cec5SDimitry Andric // The cost of the topological order layout is the taken branch cost 14400b57cec5SDimitry Andric // from BB to Succ, so to make BB->Succ a viable candidate, the following 14410b57cec5SDimitry Andric // must hold: 14420b57cec5SDimitry Andric // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 14430b57cec5SDimitry Andric // < freq(BB->Succ) * taken_branch_cost. 14440b57cec5SDimitry Andric // Ignoring unconditional jump cost, we get 14450b57cec5SDimitry Andric // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 14460b57cec5SDimitry Andric // prob(BB->Succ) > 2 * prob(BB->Pred) 14470b57cec5SDimitry Andric // 14480b57cec5SDimitry Andric // When real profile data is available, we can precisely compute the 14490b57cec5SDimitry Andric // probability threshold that is needed for edge BB->Succ to be considered. 14500b57cec5SDimitry Andric // Without profile data, the heuristic requires the branch bias to be 14510b57cec5SDimitry Andric // a lot larger to make sure the signal is very strong (e.g. 80% default). 14520b57cec5SDimitry Andric // ----------------------------------------------------------------- 14530b57cec5SDimitry Andric // Case 2: diamond like CFG (if-then-else): 14540b57cec5SDimitry Andric // S 14550b57cec5SDimitry Andric // / \ 14560b57cec5SDimitry Andric // | \ 14570b57cec5SDimitry Andric // BB Pred 14580b57cec5SDimitry Andric // \ / 14590b57cec5SDimitry Andric // Succ 14600b57cec5SDimitry Andric // .. 14610b57cec5SDimitry Andric // 14620b57cec5SDimitry Andric // The current block is BB and edge BB->Succ is now being evaluated. 14630b57cec5SDimitry Andric // Note that edge S->BB was previously already selected because 14640b57cec5SDimitry Andric // prob(S->BB) > prob(S->Pred). 14650b57cec5SDimitry Andric // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 14660b57cec5SDimitry Andric // choose Pred, we will have a topological ordering as shown on the left 14670b57cec5SDimitry Andric // in the picture below. If we choose Succ, we have the solution as shown 14680b57cec5SDimitry Andric // on the right: 14690b57cec5SDimitry Andric // 14700b57cec5SDimitry Andric // topo-order: 14710b57cec5SDimitry Andric // 14720b57cec5SDimitry Andric // S----- ---S 14730b57cec5SDimitry Andric // | | | | 14740b57cec5SDimitry Andric // ---BB | | BB 14750b57cec5SDimitry Andric // | | | | 14760b57cec5SDimitry Andric // | Pred-- | Succ-- 14770b57cec5SDimitry Andric // | | | | 14780b57cec5SDimitry Andric // ---Succ ---Pred-- 14790b57cec5SDimitry Andric // 14800b57cec5SDimitry Andric // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 14810b57cec5SDimitry Andric // = freq(S->Pred) + freq(S->BB) 14820b57cec5SDimitry Andric // 14830b57cec5SDimitry Andric // If we have profile data (i.e, branch probabilities can be trusted), the 14840b57cec5SDimitry Andric // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 14850b57cec5SDimitry Andric // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 14860b57cec5SDimitry Andric // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 14870b57cec5SDimitry Andric // means the cost of topological order is greater. 14880b57cec5SDimitry Andric // When profile data is not available, however, we need to be more 14890b57cec5SDimitry Andric // conservative. If the branch prediction is wrong, breaking the topo-order 14900b57cec5SDimitry Andric // will actually yield a layout with large cost. For this reason, we need 14910b57cec5SDimitry Andric // strong biased branch at block S with Prob(S->BB) in order to select 14920b57cec5SDimitry Andric // BB->Succ. This is equivalent to looking the CFG backward with backward 14930b57cec5SDimitry Andric // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 14940b57cec5SDimitry Andric // profile data). 14950b57cec5SDimitry Andric // -------------------------------------------------------------------------- 14960b57cec5SDimitry Andric // Case 3: forked diamond 14970b57cec5SDimitry Andric // S 14980b57cec5SDimitry Andric // / \ 14990b57cec5SDimitry Andric // / \ 15000b57cec5SDimitry Andric // BB Pred 15010b57cec5SDimitry Andric // | \ / | 15020b57cec5SDimitry Andric // | \ / | 15030b57cec5SDimitry Andric // | X | 15040b57cec5SDimitry Andric // | / \ | 15050b57cec5SDimitry Andric // | / \ | 15060b57cec5SDimitry Andric // S1 S2 15070b57cec5SDimitry Andric // 15080b57cec5SDimitry Andric // The current block is BB and edge BB->S1 is now being evaluated. 15090b57cec5SDimitry Andric // As above S->BB was already selected because 15100b57cec5SDimitry Andric // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 15110b57cec5SDimitry Andric // 15120b57cec5SDimitry Andric // topo-order: 15130b57cec5SDimitry Andric // 15140b57cec5SDimitry Andric // S-------| ---S 15150b57cec5SDimitry Andric // | | | | 15160b57cec5SDimitry Andric // ---BB | | BB 15170b57cec5SDimitry Andric // | | | | 15180b57cec5SDimitry Andric // | Pred----| | S1---- 15190b57cec5SDimitry Andric // | | | | 15200b57cec5SDimitry Andric // --(S1 or S2) ---Pred-- 15210b57cec5SDimitry Andric // | 15220b57cec5SDimitry Andric // S2 15230b57cec5SDimitry Andric // 15240b57cec5SDimitry Andric // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 15250b57cec5SDimitry Andric // + min(freq(Pred->S1), freq(Pred->S2)) 15260b57cec5SDimitry Andric // Non-topo-order cost: 15270b57cec5SDimitry Andric // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 15280b57cec5SDimitry Andric // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 15290b57cec5SDimitry Andric // is 0. Then the non topo layout is better when 15300b57cec5SDimitry Andric // freq(S->Pred) < freq(BB->S1). 15310b57cec5SDimitry Andric // This is exactly what is checked below. 15320b57cec5SDimitry Andric // Note there are other shapes that apply (Pred may not be a single block, 15330b57cec5SDimitry Andric // but they all fit this general pattern.) 15340b57cec5SDimitry Andric BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 15350b57cec5SDimitry Andric 15360b57cec5SDimitry Andric // Make sure that a hot successor doesn't have a globally more 15370b57cec5SDimitry Andric // important predecessor. 15380b57cec5SDimitry Andric BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 15390b57cec5SDimitry Andric bool BadCFGConflict = false; 15400b57cec5SDimitry Andric 15410b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 1542480093f4SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 1543480093f4SDimitry Andric if (Pred == Succ || PredChain == &SuccChain || 15440b57cec5SDimitry Andric (BlockFilter && !BlockFilter->count(Pred)) || 1545480093f4SDimitry Andric PredChain == &Chain || Pred != *std::prev(PredChain->end()) || 15460b57cec5SDimitry Andric // This check is redundant except for look ahead. This function is 15470b57cec5SDimitry Andric // called for lookahead by isProfitableToTailDup when BB hasn't been 15480b57cec5SDimitry Andric // placed yet. 15490b57cec5SDimitry Andric (Pred == BB)) 15500b57cec5SDimitry Andric continue; 15510b57cec5SDimitry Andric // Do backward checking. 15520b57cec5SDimitry Andric // For all cases above, we need a backward checking to filter out edges that 15530b57cec5SDimitry Andric // are not 'strongly' biased. 15540b57cec5SDimitry Andric // BB Pred 15550b57cec5SDimitry Andric // \ / 15560b57cec5SDimitry Andric // Succ 15570b57cec5SDimitry Andric // We select edge BB->Succ if 15580b57cec5SDimitry Andric // freq(BB->Succ) > freq(Succ) * HotProb 15590b57cec5SDimitry Andric // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 15600b57cec5SDimitry Andric // HotProb 15610b57cec5SDimitry Andric // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 15620b57cec5SDimitry Andric // Case 1 is covered too, because the first equation reduces to: 15630b57cec5SDimitry Andric // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 15640b57cec5SDimitry Andric BlockFrequency PredEdgeFreq = 15650b57cec5SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 15660b57cec5SDimitry Andric if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 15670b57cec5SDimitry Andric BadCFGConflict = true; 15680b57cec5SDimitry Andric break; 15690b57cec5SDimitry Andric } 15700b57cec5SDimitry Andric } 15710b57cec5SDimitry Andric 15720b57cec5SDimitry Andric if (BadCFGConflict) { 15730b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " 15740b57cec5SDimitry Andric << SuccProb << " (prob) (non-cold CFG conflict)\n"); 15750b57cec5SDimitry Andric return true; 15760b57cec5SDimitry Andric } 15770b57cec5SDimitry Andric 15780b57cec5SDimitry Andric return false; 15790b57cec5SDimitry Andric } 15800b57cec5SDimitry Andric 15810b57cec5SDimitry Andric /// Select the best successor for a block. 15820b57cec5SDimitry Andric /// 15830b57cec5SDimitry Andric /// This looks across all successors of a particular block and attempts to 15840b57cec5SDimitry Andric /// select the "best" one to be the layout successor. It only considers direct 15850b57cec5SDimitry Andric /// successors which also pass the block filter. It will attempt to avoid 15860b57cec5SDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of 15870b57cec5SDimitry Andric /// very hot successor edges. 15880b57cec5SDimitry Andric /// 15890b57cec5SDimitry Andric /// \returns The best successor block found, or null if none are viable, along 15900b57cec5SDimitry Andric /// with a boolean indicating if tail duplication is necessary. 15910b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 15920b57cec5SDimitry Andric MachineBlockPlacement::selectBestSuccessor( 15930b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 15940b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 15950b57cec5SDimitry Andric const BranchProbability HotProb(StaticLikelyProb, 100); 15960b57cec5SDimitry Andric 15970b57cec5SDimitry Andric BlockAndTailDupResult BestSucc = { nullptr, false }; 15980b57cec5SDimitry Andric auto BestProb = BranchProbability::getZero(); 15990b57cec5SDimitry Andric 16000b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> Successors; 16010b57cec5SDimitry Andric auto AdjustedSumProb = 16020b57cec5SDimitry Andric collectViableSuccessors(BB, Chain, BlockFilter, Successors); 16030b57cec5SDimitry Andric 16040b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) 16050b57cec5SDimitry Andric << "\n"); 16060b57cec5SDimitry Andric 16070b57cec5SDimitry Andric // if we already precomputed the best successor for BB, return that if still 16080b57cec5SDimitry Andric // applicable. 16090b57cec5SDimitry Andric auto FoundEdge = ComputedEdges.find(BB); 16100b57cec5SDimitry Andric if (FoundEdge != ComputedEdges.end()) { 16110b57cec5SDimitry Andric MachineBasicBlock *Succ = FoundEdge->second.BB; 16120b57cec5SDimitry Andric ComputedEdges.erase(FoundEdge); 16130b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 16140b57cec5SDimitry Andric if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) && 16150b57cec5SDimitry Andric SuccChain != &Chain && Succ == *SuccChain->begin()) 16160b57cec5SDimitry Andric return FoundEdge->second; 16170b57cec5SDimitry Andric } 16180b57cec5SDimitry Andric 16190b57cec5SDimitry Andric // if BB is part of a trellis, Use the trellis to determine the optimal 16200b57cec5SDimitry Andric // fallthrough edges 16210b57cec5SDimitry Andric if (isTrellis(BB, Successors, Chain, BlockFilter)) 16220b57cec5SDimitry Andric return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain, 16230b57cec5SDimitry Andric BlockFilter); 16240b57cec5SDimitry Andric 16250b57cec5SDimitry Andric // For blocks with CFG violations, we may be able to lay them out anyway with 16260b57cec5SDimitry Andric // tail-duplication. We keep this vector so we can perform the probability 16270b57cec5SDimitry Andric // calculations the minimum number of times. 16285ffd83dbSDimitry Andric SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4> 16290b57cec5SDimitry Andric DupCandidates; 16300b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Successors) { 16310b57cec5SDimitry Andric auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 16320b57cec5SDimitry Andric BranchProbability SuccProb = 16330b57cec5SDimitry Andric getAdjustedProbability(RealSuccProb, AdjustedSumProb); 16340b57cec5SDimitry Andric 16350b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 16360b57cec5SDimitry Andric // Skip the edge \c BB->Succ if block \c Succ has a better layout 16370b57cec5SDimitry Andric // predecessor that yields lower global cost. 16380b57cec5SDimitry Andric if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 16390b57cec5SDimitry Andric Chain, BlockFilter)) { 16400b57cec5SDimitry Andric // If tail duplication would make Succ profitable, place it. 16410b57cec5SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ)) 16425ffd83dbSDimitry Andric DupCandidates.emplace_back(SuccProb, Succ); 16430b57cec5SDimitry Andric continue; 16440b57cec5SDimitry Andric } 16450b57cec5SDimitry Andric 16460b57cec5SDimitry Andric LLVM_DEBUG( 16470b57cec5SDimitry Andric dbgs() << " Candidate: " << getBlockName(Succ) 16480b57cec5SDimitry Andric << ", probability: " << SuccProb 16490b57cec5SDimitry Andric << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 16500b57cec5SDimitry Andric << "\n"); 16510b57cec5SDimitry Andric 16520b57cec5SDimitry Andric if (BestSucc.BB && BestProb >= SuccProb) { 16530b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n"); 16540b57cec5SDimitry Andric continue; 16550b57cec5SDimitry Andric } 16560b57cec5SDimitry Andric 16570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Setting it as best candidate\n"); 16580b57cec5SDimitry Andric BestSucc.BB = Succ; 16590b57cec5SDimitry Andric BestProb = SuccProb; 16600b57cec5SDimitry Andric } 16610b57cec5SDimitry Andric // Handle the tail duplication candidates in order of decreasing probability. 16620b57cec5SDimitry Andric // Stop at the first one that is profitable. Also stop if they are less 16630b57cec5SDimitry Andric // profitable than BestSucc. Position is important because we preserve it and 16640b57cec5SDimitry Andric // prefer first best match. Here we aren't comparing in order, so we capture 16650b57cec5SDimitry Andric // the position instead. 16660b57cec5SDimitry Andric llvm::stable_sort(DupCandidates, 16670b57cec5SDimitry Andric [](std::tuple<BranchProbability, MachineBasicBlock *> L, 16680b57cec5SDimitry Andric std::tuple<BranchProbability, MachineBasicBlock *> R) { 16690b57cec5SDimitry Andric return std::get<0>(L) > std::get<0>(R); 16700b57cec5SDimitry Andric }); 16710b57cec5SDimitry Andric for (auto &Tup : DupCandidates) { 16720b57cec5SDimitry Andric BranchProbability DupProb; 16730b57cec5SDimitry Andric MachineBasicBlock *Succ; 16740b57cec5SDimitry Andric std::tie(DupProb, Succ) = Tup; 16750b57cec5SDimitry Andric if (DupProb < BestProb) 16760b57cec5SDimitry Andric break; 16770b57cec5SDimitry Andric if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) 16780b57cec5SDimitry Andric && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) { 16790b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ) 16800b57cec5SDimitry Andric << ", probability: " << DupProb 16810b57cec5SDimitry Andric << " (Tail Duplicate)\n"); 16820b57cec5SDimitry Andric BestSucc.BB = Succ; 16830b57cec5SDimitry Andric BestSucc.ShouldTailDup = true; 16840b57cec5SDimitry Andric break; 16850b57cec5SDimitry Andric } 16860b57cec5SDimitry Andric } 16870b57cec5SDimitry Andric 16880b57cec5SDimitry Andric if (BestSucc.BB) 16890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n"); 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric return BestSucc; 16920b57cec5SDimitry Andric } 16930b57cec5SDimitry Andric 16940b57cec5SDimitry Andric /// Select the best block from a worklist. 16950b57cec5SDimitry Andric /// 16960b57cec5SDimitry Andric /// This looks through the provided worklist as a list of candidate basic 16970b57cec5SDimitry Andric /// blocks and select the most profitable one to place. The definition of 16980b57cec5SDimitry Andric /// profitable only really makes sense in the context of a loop. This returns 16990b57cec5SDimitry Andric /// the most frequently visited block in the worklist, which in the case of 17000b57cec5SDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the 17010b57cec5SDimitry Andric /// loop body in order to improve i-cache behavior. 17020b57cec5SDimitry Andric /// 17030b57cec5SDimitry Andric /// \returns The best block found, or null if none are viable. 17040b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 17050b57cec5SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 17060b57cec5SDimitry Andric // Once we need to walk the worklist looking for a candidate, cleanup the 17070b57cec5SDimitry Andric // worklist of already placed entries. 17080b57cec5SDimitry Andric // FIXME: If this shows up on profiles, it could be folded (at the cost of 17090b57cec5SDimitry Andric // some code complexity) into the loop below. 1710e8d8bef9SDimitry Andric llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) { 17110b57cec5SDimitry Andric return BlockToChain.lookup(BB) == &Chain; 1712e8d8bef9SDimitry Andric }); 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric if (WorkList.empty()) 17150b57cec5SDimitry Andric return nullptr; 17160b57cec5SDimitry Andric 17170b57cec5SDimitry Andric bool IsEHPad = WorkList[0]->isEHPad(); 17180b57cec5SDimitry Andric 17190b57cec5SDimitry Andric MachineBasicBlock *BestBlock = nullptr; 17200b57cec5SDimitry Andric BlockFrequency BestFreq; 17210b57cec5SDimitry Andric for (MachineBasicBlock *MBB : WorkList) { 17220b57cec5SDimitry Andric assert(MBB->isEHPad() == IsEHPad && 17230b57cec5SDimitry Andric "EHPad mismatch between block and work list."); 17240b57cec5SDimitry Andric 17250b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[MBB]; 17260b57cec5SDimitry Andric if (&SuccChain == &Chain) 17270b57cec5SDimitry Andric continue; 17280b57cec5SDimitry Andric 17290b57cec5SDimitry Andric assert(SuccChain.UnscheduledPredecessors == 0 && 17300b57cec5SDimitry Andric "Found CFG-violating block"); 17310b57cec5SDimitry Andric 17320b57cec5SDimitry Andric BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 17330b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; 17340b57cec5SDimitry Andric MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 17350b57cec5SDimitry Andric 17360b57cec5SDimitry Andric // For ehpad, we layout the least probable first as to avoid jumping back 17370b57cec5SDimitry Andric // from least probable landingpads to more probable ones. 17380b57cec5SDimitry Andric // 17390b57cec5SDimitry Andric // FIXME: Using probability is probably (!) not the best way to achieve 17400b57cec5SDimitry Andric // this. We should probably have a more principled approach to layout 17410b57cec5SDimitry Andric // cleanup code. 17420b57cec5SDimitry Andric // 17430b57cec5SDimitry Andric // The goal is to get: 17440b57cec5SDimitry Andric // 17450b57cec5SDimitry Andric // +--------------------------+ 17460b57cec5SDimitry Andric // | V 17470b57cec5SDimitry Andric // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 17480b57cec5SDimitry Andric // 17490b57cec5SDimitry Andric // Rather than: 17500b57cec5SDimitry Andric // 17510b57cec5SDimitry Andric // +-------------------------------------+ 17520b57cec5SDimitry Andric // V | 17530b57cec5SDimitry Andric // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 17540b57cec5SDimitry Andric if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 17550b57cec5SDimitry Andric continue; 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric BestBlock = MBB; 17580b57cec5SDimitry Andric BestFreq = CandidateFreq; 17590b57cec5SDimitry Andric } 17600b57cec5SDimitry Andric 17610b57cec5SDimitry Andric return BestBlock; 17620b57cec5SDimitry Andric } 17630b57cec5SDimitry Andric 17640b57cec5SDimitry Andric /// Retrieve the first unplaced basic block. 17650b57cec5SDimitry Andric /// 17660b57cec5SDimitry Andric /// This routine is called when we are unable to use the CFG to walk through 17670b57cec5SDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 17680b57cec5SDimitry Andric /// We walk through the function's blocks in order, starting from the 17690b57cec5SDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid 17700b57cec5SDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine. 17710b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 17720b57cec5SDimitry Andric const BlockChain &PlacedChain, 17730b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 17740b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 17750b57cec5SDimitry Andric for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 17760b57cec5SDimitry Andric ++I) { 17770b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(&*I)) 17780b57cec5SDimitry Andric continue; 17790b57cec5SDimitry Andric if (BlockToChain[&*I] != &PlacedChain) { 17800b57cec5SDimitry Andric PrevUnplacedBlockIt = I; 17810b57cec5SDimitry Andric // Now select the head of the chain to which the unplaced block belongs 17820b57cec5SDimitry Andric // as the block to place. This will force the entire chain to be placed, 17830b57cec5SDimitry Andric // and satisfies the requirements of merging chains. 17840b57cec5SDimitry Andric return *BlockToChain[&*I]->begin(); 17850b57cec5SDimitry Andric } 17860b57cec5SDimitry Andric } 17870b57cec5SDimitry Andric return nullptr; 17880b57cec5SDimitry Andric } 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric void MachineBlockPlacement::fillWorkLists( 17910b57cec5SDimitry Andric const MachineBasicBlock *MBB, 17920b57cec5SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 17930b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr) { 17940b57cec5SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 17950b57cec5SDimitry Andric if (!UpdatedPreds.insert(&Chain).second) 17960b57cec5SDimitry Andric return; 17970b57cec5SDimitry Andric 17980b57cec5SDimitry Andric assert( 17990b57cec5SDimitry Andric Chain.UnscheduledPredecessors == 0 && 18000b57cec5SDimitry Andric "Attempting to place block with unscheduled predecessors in worklist."); 18010b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : Chain) { 18020b57cec5SDimitry Andric assert(BlockToChain[ChainBB] == &Chain && 18030b57cec5SDimitry Andric "Block in chain doesn't match BlockToChain map."); 18040b57cec5SDimitry Andric for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 18050b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(Pred)) 18060b57cec5SDimitry Andric continue; 18070b57cec5SDimitry Andric if (BlockToChain[Pred] == &Chain) 18080b57cec5SDimitry Andric continue; 18090b57cec5SDimitry Andric ++Chain.UnscheduledPredecessors; 18100b57cec5SDimitry Andric } 18110b57cec5SDimitry Andric } 18120b57cec5SDimitry Andric 18130b57cec5SDimitry Andric if (Chain.UnscheduledPredecessors != 0) 18140b57cec5SDimitry Andric return; 18150b57cec5SDimitry Andric 18160b57cec5SDimitry Andric MachineBasicBlock *BB = *Chain.begin(); 18170b57cec5SDimitry Andric if (BB->isEHPad()) 18180b57cec5SDimitry Andric EHPadWorkList.push_back(BB); 18190b57cec5SDimitry Andric else 18200b57cec5SDimitry Andric BlockWorkList.push_back(BB); 18210b57cec5SDimitry Andric } 18220b57cec5SDimitry Andric 18230b57cec5SDimitry Andric void MachineBlockPlacement::buildChain( 18240b57cec5SDimitry Andric const MachineBasicBlock *HeadBB, BlockChain &Chain, 18250b57cec5SDimitry Andric BlockFilterSet *BlockFilter) { 18260b57cec5SDimitry Andric assert(HeadBB && "BB must not be null.\n"); 18270b57cec5SDimitry Andric assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n"); 18280b57cec5SDimitry Andric MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 18290b57cec5SDimitry Andric 18300b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB = HeadBB; 18310b57cec5SDimitry Andric markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 18320b57cec5SDimitry Andric MachineBasicBlock *BB = *std::prev(Chain.end()); 18330b57cec5SDimitry Andric while (true) { 18340b57cec5SDimitry Andric assert(BB && "null block found at end of chain in loop."); 18350b57cec5SDimitry Andric assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 18360b57cec5SDimitry Andric assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 18370b57cec5SDimitry Andric 18380b57cec5SDimitry Andric 18390b57cec5SDimitry Andric // Look for the best viable successor if there is one to place immediately 18400b57cec5SDimitry Andric // after this block. 18410b57cec5SDimitry Andric auto Result = selectBestSuccessor(BB, Chain, BlockFilter); 18420b57cec5SDimitry Andric MachineBasicBlock* BestSucc = Result.BB; 18430b57cec5SDimitry Andric bool ShouldTailDup = Result.ShouldTailDup; 18440b57cec5SDimitry Andric if (allowTailDupPlacement()) 1845480093f4SDimitry Andric ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc, 1846480093f4SDimitry Andric Chain, 1847480093f4SDimitry Andric BlockFilter)); 18480b57cec5SDimitry Andric 18490b57cec5SDimitry Andric // If an immediate successor isn't available, look for the best viable 18500b57cec5SDimitry Andric // block among those we've identified as not violating the loop's CFG at 18510b57cec5SDimitry Andric // this point. This won't be a fallthrough, but it will increase locality. 18520b57cec5SDimitry Andric if (!BestSucc) 18530b57cec5SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 18540b57cec5SDimitry Andric if (!BestSucc) 18550b57cec5SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 18560b57cec5SDimitry Andric 18570b57cec5SDimitry Andric if (!BestSucc) { 18580b57cec5SDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); 18590b57cec5SDimitry Andric if (!BestSucc) 18600b57cec5SDimitry Andric break; 18610b57cec5SDimitry Andric 18620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 18630b57cec5SDimitry Andric "layout successor until the CFG reduces\n"); 18640b57cec5SDimitry Andric } 18650b57cec5SDimitry Andric 18660b57cec5SDimitry Andric // Placement may have changed tail duplication opportunities. 18670b57cec5SDimitry Andric // Check for that now. 18680b57cec5SDimitry Andric if (allowTailDupPlacement() && BestSucc && ShouldTailDup) { 18695ffd83dbSDimitry Andric repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 18705ffd83dbSDimitry Andric BlockFilter, PrevUnplacedBlockIt); 18715ffd83dbSDimitry Andric // If the chosen successor was duplicated into BB, don't bother laying 18725ffd83dbSDimitry Andric // it out, just go round the loop again with BB as the chain end. 18735ffd83dbSDimitry Andric if (!BB->isSuccessor(BestSucc)) 18740b57cec5SDimitry Andric continue; 18750b57cec5SDimitry Andric } 18760b57cec5SDimitry Andric 18770b57cec5SDimitry Andric // Place this block, updating the datastructures to reflect its placement. 18780b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[BestSucc]; 18790b57cec5SDimitry Andric // Zero out UnscheduledPredecessors for the successor we're about to merge in case 18800b57cec5SDimitry Andric // we selected a successor that didn't fit naturally into the CFG. 18810b57cec5SDimitry Andric SuccChain.UnscheduledPredecessors = 0; 18820b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 18830b57cec5SDimitry Andric << getBlockName(BestSucc) << "\n"); 18840b57cec5SDimitry Andric markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 18850b57cec5SDimitry Andric Chain.merge(BestSucc, &SuccChain); 18860b57cec5SDimitry Andric BB = *std::prev(Chain.end()); 18870b57cec5SDimitry Andric } 18880b57cec5SDimitry Andric 18890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finished forming chain for header block " 18900b57cec5SDimitry Andric << getBlockName(*Chain.begin()) << "\n"); 18910b57cec5SDimitry Andric } 18920b57cec5SDimitry Andric 18930b57cec5SDimitry Andric // If bottom of block BB has only one successor OldTop, in most cases it is 18940b57cec5SDimitry Andric // profitable to move it before OldTop, except the following case: 18950b57cec5SDimitry Andric // 18960b57cec5SDimitry Andric // -->OldTop<- 18970b57cec5SDimitry Andric // | . | 18980b57cec5SDimitry Andric // | . | 18990b57cec5SDimitry Andric // | . | 19000b57cec5SDimitry Andric // ---Pred | 19010b57cec5SDimitry Andric // | | 19020b57cec5SDimitry Andric // BB----- 19030b57cec5SDimitry Andric // 19040b57cec5SDimitry Andric // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't 19050b57cec5SDimitry Andric // layout the other successor below it, so it can't reduce taken branch. 19060b57cec5SDimitry Andric // In this case we keep its original layout. 19070b57cec5SDimitry Andric bool 19080b57cec5SDimitry Andric MachineBlockPlacement::canMoveBottomBlockToTop( 19090b57cec5SDimitry Andric const MachineBasicBlock *BottomBlock, 19100b57cec5SDimitry Andric const MachineBasicBlock *OldTop) { 19110b57cec5SDimitry Andric if (BottomBlock->pred_size() != 1) 19120b57cec5SDimitry Andric return true; 19130b57cec5SDimitry Andric MachineBasicBlock *Pred = *BottomBlock->pred_begin(); 19140b57cec5SDimitry Andric if (Pred->succ_size() != 2) 19150b57cec5SDimitry Andric return true; 19160b57cec5SDimitry Andric 19170b57cec5SDimitry Andric MachineBasicBlock *OtherBB = *Pred->succ_begin(); 19180b57cec5SDimitry Andric if (OtherBB == BottomBlock) 19190b57cec5SDimitry Andric OtherBB = *Pred->succ_rbegin(); 19200b57cec5SDimitry Andric if (OtherBB == OldTop) 19210b57cec5SDimitry Andric return false; 19220b57cec5SDimitry Andric 19230b57cec5SDimitry Andric return true; 19240b57cec5SDimitry Andric } 19250b57cec5SDimitry Andric 19260b57cec5SDimitry Andric // Find out the possible fall through frequence to the top of a loop. 19270b57cec5SDimitry Andric BlockFrequency 19280b57cec5SDimitry Andric MachineBlockPlacement::TopFallThroughFreq( 19290b57cec5SDimitry Andric const MachineBasicBlock *Top, 19300b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 19310b57cec5SDimitry Andric BlockFrequency MaxFreq = 0; 19320b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) { 19330b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 19340b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 19350b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 19360b57cec5SDimitry Andric // Found a Pred block can be placed before Top. 19370b57cec5SDimitry Andric // Check if Top is the best successor of Pred. 19380b57cec5SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top); 19390b57cec5SDimitry Andric bool TopOK = true; 19400b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) { 19410b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 19420b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 19430b57cec5SDimitry Andric // Check if Succ can be placed after Pred. 19440b57cec5SDimitry Andric // Succ should not be in any chain, or it is the head of some chain. 19450b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) && 19460b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) { 19470b57cec5SDimitry Andric TopOK = false; 19480b57cec5SDimitry Andric break; 19490b57cec5SDimitry Andric } 19500b57cec5SDimitry Andric } 19510b57cec5SDimitry Andric if (TopOK) { 19520b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 19530b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, Top); 19540b57cec5SDimitry Andric if (EdgeFreq > MaxFreq) 19550b57cec5SDimitry Andric MaxFreq = EdgeFreq; 19560b57cec5SDimitry Andric } 19570b57cec5SDimitry Andric } 19580b57cec5SDimitry Andric } 19590b57cec5SDimitry Andric return MaxFreq; 19600b57cec5SDimitry Andric } 19610b57cec5SDimitry Andric 19620b57cec5SDimitry Andric // Compute the fall through gains when move NewTop before OldTop. 19630b57cec5SDimitry Andric // 19640b57cec5SDimitry Andric // In following diagram, edges marked as "-" are reduced fallthrough, edges 19650b57cec5SDimitry Andric // marked as "+" are increased fallthrough, this function computes 19660b57cec5SDimitry Andric // 19670b57cec5SDimitry Andric // SUM(increased fallthrough) - SUM(decreased fallthrough) 19680b57cec5SDimitry Andric // 19690b57cec5SDimitry Andric // | 19700b57cec5SDimitry Andric // | - 19710b57cec5SDimitry Andric // V 19720b57cec5SDimitry Andric // --->OldTop 19730b57cec5SDimitry Andric // | . 19740b57cec5SDimitry Andric // | . 19750b57cec5SDimitry Andric // +| . + 19760b57cec5SDimitry Andric // | Pred ---> 19770b57cec5SDimitry Andric // | |- 19780b57cec5SDimitry Andric // | V 19790b57cec5SDimitry Andric // --- NewTop <--- 19800b57cec5SDimitry Andric // |- 19810b57cec5SDimitry Andric // V 19820b57cec5SDimitry Andric // 19830b57cec5SDimitry Andric BlockFrequency 19840b57cec5SDimitry Andric MachineBlockPlacement::FallThroughGains( 19850b57cec5SDimitry Andric const MachineBasicBlock *NewTop, 19860b57cec5SDimitry Andric const MachineBasicBlock *OldTop, 19870b57cec5SDimitry Andric const MachineBasicBlock *ExitBB, 19880b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 19890b57cec5SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet); 19900b57cec5SDimitry Andric BlockFrequency FallThrough2Exit = 0; 19910b57cec5SDimitry Andric if (ExitBB) 19920b57cec5SDimitry Andric FallThrough2Exit = MBFI->getBlockFreq(NewTop) * 19930b57cec5SDimitry Andric MBPI->getEdgeProbability(NewTop, ExitBB); 19940b57cec5SDimitry Andric BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) * 19950b57cec5SDimitry Andric MBPI->getEdgeProbability(NewTop, OldTop); 19960b57cec5SDimitry Andric 19970b57cec5SDimitry Andric // Find the best Pred of NewTop. 19980b57cec5SDimitry Andric MachineBasicBlock *BestPred = nullptr; 19990b57cec5SDimitry Andric BlockFrequency FallThroughFromPred = 0; 20000b57cec5SDimitry Andric for (MachineBasicBlock *Pred : NewTop->predecessors()) { 20010b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred)) 20020b57cec5SDimitry Andric continue; 20030b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 20040b57cec5SDimitry Andric if (!PredChain || Pred == *std::prev(PredChain->end())) { 20050b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 20060b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, NewTop); 20070b57cec5SDimitry Andric if (EdgeFreq > FallThroughFromPred) { 20080b57cec5SDimitry Andric FallThroughFromPred = EdgeFreq; 20090b57cec5SDimitry Andric BestPred = Pred; 20100b57cec5SDimitry Andric } 20110b57cec5SDimitry Andric } 20120b57cec5SDimitry Andric } 20130b57cec5SDimitry Andric 20140b57cec5SDimitry Andric // If NewTop is not placed after Pred, another successor can be placed 20150b57cec5SDimitry Andric // after Pred. 20160b57cec5SDimitry Andric BlockFrequency NewFreq = 0; 20170b57cec5SDimitry Andric if (BestPred) { 20180b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BestPred->successors()) { 20190b57cec5SDimitry Andric if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ)) 20200b57cec5SDimitry Andric continue; 20210b57cec5SDimitry Andric if (ComputedEdges.find(Succ) != ComputedEdges.end()) 20220b57cec5SDimitry Andric continue; 20230b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 20240b57cec5SDimitry Andric if ((SuccChain && (Succ != *SuccChain->begin())) || 20250b57cec5SDimitry Andric (SuccChain == BlockToChain[BestPred])) 20260b57cec5SDimitry Andric continue; 20270b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) * 20280b57cec5SDimitry Andric MBPI->getEdgeProbability(BestPred, Succ); 20290b57cec5SDimitry Andric if (EdgeFreq > NewFreq) 20300b57cec5SDimitry Andric NewFreq = EdgeFreq; 20310b57cec5SDimitry Andric } 20320b57cec5SDimitry Andric BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) * 20330b57cec5SDimitry Andric MBPI->getEdgeProbability(BestPred, NewTop); 20340b57cec5SDimitry Andric if (NewFreq > OrigEdgeFreq) { 20350b57cec5SDimitry Andric // If NewTop is not the best successor of Pred, then Pred doesn't 20360b57cec5SDimitry Andric // fallthrough to NewTop. So there is no FallThroughFromPred and 20370b57cec5SDimitry Andric // NewFreq. 20380b57cec5SDimitry Andric NewFreq = 0; 20390b57cec5SDimitry Andric FallThroughFromPred = 0; 20400b57cec5SDimitry Andric } 20410b57cec5SDimitry Andric } 20420b57cec5SDimitry Andric 20430b57cec5SDimitry Andric BlockFrequency Result = 0; 20440b57cec5SDimitry Andric BlockFrequency Gains = BackEdgeFreq + NewFreq; 20450b57cec5SDimitry Andric BlockFrequency Lost = FallThrough2Top + FallThrough2Exit + 20460b57cec5SDimitry Andric FallThroughFromPred; 20470b57cec5SDimitry Andric if (Gains > Lost) 20480b57cec5SDimitry Andric Result = Gains - Lost; 20490b57cec5SDimitry Andric return Result; 20500b57cec5SDimitry Andric } 20510b57cec5SDimitry Andric 20520b57cec5SDimitry Andric /// Helper function of findBestLoopTop. Find the best loop top block 20530b57cec5SDimitry Andric /// from predecessors of old top. 20540b57cec5SDimitry Andric /// 20550b57cec5SDimitry Andric /// Look for a block which is strictly better than the old top for laying 20560b57cec5SDimitry Andric /// out before the old top of the loop. This looks for only two patterns: 20570b57cec5SDimitry Andric /// 20580b57cec5SDimitry Andric /// 1. a block has only one successor, the old loop top 20590b57cec5SDimitry Andric /// 20600b57cec5SDimitry Andric /// Because such a block will always result in an unconditional jump, 20610b57cec5SDimitry Andric /// rotating it in front of the old top is always profitable. 20620b57cec5SDimitry Andric /// 20630b57cec5SDimitry Andric /// 2. a block has two successors, one is old top, another is exit 20640b57cec5SDimitry Andric /// and it has more than one predecessors 20650b57cec5SDimitry Andric /// 20660b57cec5SDimitry Andric /// If it is below one of its predecessors P, only P can fall through to 20670b57cec5SDimitry Andric /// it, all other predecessors need a jump to it, and another conditional 20680b57cec5SDimitry Andric /// jump to loop header. If it is moved before loop header, all its 20690b57cec5SDimitry Andric /// predecessors jump to it, then fall through to loop header. So all its 20700b57cec5SDimitry Andric /// predecessors except P can reduce one taken branch. 20710b57cec5SDimitry Andric /// At the same time, move it before old top increases the taken branch 20720b57cec5SDimitry Andric /// to loop exit block, so the reduced taken branch will be compared with 20730b57cec5SDimitry Andric /// the increased taken branch to the loop exit block. 20740b57cec5SDimitry Andric MachineBasicBlock * 20750b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTopHelper( 20760b57cec5SDimitry Andric MachineBasicBlock *OldTop, 20770b57cec5SDimitry Andric const MachineLoop &L, 20780b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 20790b57cec5SDimitry Andric // Check that the header hasn't been fused with a preheader block due to 20800b57cec5SDimitry Andric // crazy branches. If it has, we need to start with the header at the top to 20810b57cec5SDimitry Andric // prevent pulling the preheader into the loop body. 20820b57cec5SDimitry Andric BlockChain &HeaderChain = *BlockToChain[OldTop]; 20830b57cec5SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 20840b57cec5SDimitry Andric return OldTop; 2085349cc55cSDimitry Andric if (OldTop != *HeaderChain.begin()) 2086349cc55cSDimitry Andric return OldTop; 20870b57cec5SDimitry Andric 20880b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop) 20890b57cec5SDimitry Andric << "\n"); 20900b57cec5SDimitry Andric 20910b57cec5SDimitry Andric BlockFrequency BestGains = 0; 20920b57cec5SDimitry Andric MachineBasicBlock *BestPred = nullptr; 20930b57cec5SDimitry Andric for (MachineBasicBlock *Pred : OldTop->predecessors()) { 20940b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred)) 20950b57cec5SDimitry Andric continue; 20960b57cec5SDimitry Andric if (Pred == L.getHeader()) 20970b57cec5SDimitry Andric continue; 20980b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has " 20990b57cec5SDimitry Andric << Pred->succ_size() << " successors, "; 21000b57cec5SDimitry Andric MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 21010b57cec5SDimitry Andric if (Pred->succ_size() > 2) 21020b57cec5SDimitry Andric continue; 21030b57cec5SDimitry Andric 21040b57cec5SDimitry Andric MachineBasicBlock *OtherBB = nullptr; 21050b57cec5SDimitry Andric if (Pred->succ_size() == 2) { 21060b57cec5SDimitry Andric OtherBB = *Pred->succ_begin(); 21070b57cec5SDimitry Andric if (OtherBB == OldTop) 21080b57cec5SDimitry Andric OtherBB = *Pred->succ_rbegin(); 21090b57cec5SDimitry Andric } 21100b57cec5SDimitry Andric 21110b57cec5SDimitry Andric if (!canMoveBottomBlockToTop(Pred, OldTop)) 21120b57cec5SDimitry Andric continue; 21130b57cec5SDimitry Andric 21140b57cec5SDimitry Andric BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB, 21150b57cec5SDimitry Andric LoopBlockSet); 21160b57cec5SDimitry Andric if ((Gains > 0) && (Gains > BestGains || 21170b57cec5SDimitry Andric ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) { 21180b57cec5SDimitry Andric BestPred = Pred; 21190b57cec5SDimitry Andric BestGains = Gains; 21200b57cec5SDimitry Andric } 21210b57cec5SDimitry Andric } 21220b57cec5SDimitry Andric 21230b57cec5SDimitry Andric // If no direct predecessor is fine, just use the loop header. 21240b57cec5SDimitry Andric if (!BestPred) { 21250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " final top unchanged\n"); 21260b57cec5SDimitry Andric return OldTop; 21270b57cec5SDimitry Andric } 21280b57cec5SDimitry Andric 21290b57cec5SDimitry Andric // Walk backwards through any straight line of predecessors. 21300b57cec5SDimitry Andric while (BestPred->pred_size() == 1 && 21310b57cec5SDimitry Andric (*BestPred->pred_begin())->succ_size() == 1 && 21320b57cec5SDimitry Andric *BestPred->pred_begin() != L.getHeader()) 21330b57cec5SDimitry Andric BestPred = *BestPred->pred_begin(); 21340b57cec5SDimitry Andric 21350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 21360b57cec5SDimitry Andric return BestPred; 21370b57cec5SDimitry Andric } 21380b57cec5SDimitry Andric 21390b57cec5SDimitry Andric /// Find the best loop top block for layout. 21400b57cec5SDimitry Andric /// 21410b57cec5SDimitry Andric /// This function iteratively calls findBestLoopTopHelper, until no new better 21420b57cec5SDimitry Andric /// BB can be found. 21430b57cec5SDimitry Andric MachineBasicBlock * 21440b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTop(const MachineLoop &L, 21450b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 21460b57cec5SDimitry Andric // Placing the latch block before the header may introduce an extra branch 21470b57cec5SDimitry Andric // that skips this block the first time the loop is executed, which we want 21480b57cec5SDimitry Andric // to avoid when optimising for size. 21490b57cec5SDimitry Andric // FIXME: in theory there is a case that does not introduce a new branch, 21500b57cec5SDimitry Andric // i.e. when the layout predecessor does not fallthrough to the loop header. 21510b57cec5SDimitry Andric // In practice this never happens though: there always seems to be a preheader 21520b57cec5SDimitry Andric // that can fallthrough and that is also placed before the header. 2153480093f4SDimitry Andric bool OptForSize = F->getFunction().hasOptSize() || 21545ffd83dbSDimitry Andric llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get()); 2155480093f4SDimitry Andric if (OptForSize) 21560b57cec5SDimitry Andric return L.getHeader(); 21570b57cec5SDimitry Andric 21580b57cec5SDimitry Andric MachineBasicBlock *OldTop = nullptr; 21590b57cec5SDimitry Andric MachineBasicBlock *NewTop = L.getHeader(); 21600b57cec5SDimitry Andric while (NewTop != OldTop) { 21610b57cec5SDimitry Andric OldTop = NewTop; 21620b57cec5SDimitry Andric NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet); 21630b57cec5SDimitry Andric if (NewTop != OldTop) 21640b57cec5SDimitry Andric ComputedEdges[NewTop] = { OldTop, false }; 21650b57cec5SDimitry Andric } 21660b57cec5SDimitry Andric return NewTop; 21670b57cec5SDimitry Andric } 21680b57cec5SDimitry Andric 21690b57cec5SDimitry Andric /// Find the best loop exiting block for layout. 21700b57cec5SDimitry Andric /// 21710b57cec5SDimitry Andric /// This routine implements the logic to analyze the loop looking for the best 21720b57cec5SDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize 21730b57cec5SDimitry Andric /// fallthrough opportunities. 21740b57cec5SDimitry Andric MachineBasicBlock * 21750b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopExit(const MachineLoop &L, 21760b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet, 21770b57cec5SDimitry Andric BlockFrequency &ExitFreq) { 21780b57cec5SDimitry Andric // We don't want to layout the loop linearly in all cases. If the loop header 21790b57cec5SDimitry Andric // is just a normal basic block in the loop, we want to look for what block 21800b57cec5SDimitry Andric // within the loop is the best one to layout at the top. However, if the loop 21810b57cec5SDimitry Andric // header has be pre-merged into a chain due to predecessors not having 21820b57cec5SDimitry Andric // analyzable branches, *and* the predecessor it is merged with is *not* part 21830b57cec5SDimitry Andric // of the loop, rotating the header into the middle of the loop will create 21840b57cec5SDimitry Andric // a non-contiguous range of blocks which is Very Bad. So start with the 21850b57cec5SDimitry Andric // header and only rotate if safe. 21860b57cec5SDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 21870b57cec5SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 21880b57cec5SDimitry Andric return nullptr; 21890b57cec5SDimitry Andric 21900b57cec5SDimitry Andric BlockFrequency BestExitEdgeFreq; 21910b57cec5SDimitry Andric unsigned BestExitLoopDepth = 0; 21920b57cec5SDimitry Andric MachineBasicBlock *ExitingBB = nullptr; 21930b57cec5SDimitry Andric // If there are exits to outer loops, loop rotation can severely limit 21940b57cec5SDimitry Andric // fallthrough opportunities unless it selects such an exit. Keep a set of 21950b57cec5SDimitry Andric // blocks where rotating to exit with that block will reach an outer loop. 21960b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 21970b57cec5SDimitry Andric 21980b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop exit for: " 21990b57cec5SDimitry Andric << getBlockName(L.getHeader()) << "\n"); 22000b57cec5SDimitry Andric for (MachineBasicBlock *MBB : L.getBlocks()) { 22010b57cec5SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 22020b57cec5SDimitry Andric // Ensure that this block is at the end of a chain; otherwise it could be 22030b57cec5SDimitry Andric // mid-way through an inner loop or a successor of an unanalyzable branch. 22040b57cec5SDimitry Andric if (MBB != *std::prev(Chain.end())) 22050b57cec5SDimitry Andric continue; 22060b57cec5SDimitry Andric 22070b57cec5SDimitry Andric // Now walk the successors. We need to establish whether this has a viable 22080b57cec5SDimitry Andric // exiting successor and whether it has a viable non-exiting successor. 22090b57cec5SDimitry Andric // We store the old exiting state and restore it if a viable looping 22100b57cec5SDimitry Andric // successor isn't found. 22110b57cec5SDimitry Andric MachineBasicBlock *OldExitingBB = ExitingBB; 22120b57cec5SDimitry Andric BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 22130b57cec5SDimitry Andric bool HasLoopingSucc = false; 22140b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 22150b57cec5SDimitry Andric if (Succ->isEHPad()) 22160b57cec5SDimitry Andric continue; 22170b57cec5SDimitry Andric if (Succ == MBB) 22180b57cec5SDimitry Andric continue; 22190b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 22200b57cec5SDimitry Andric // Don't split chains, either this chain or the successor's chain. 22210b57cec5SDimitry Andric if (&Chain == &SuccChain) { 22220b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 22230b57cec5SDimitry Andric << getBlockName(Succ) << " (chain conflict)\n"); 22240b57cec5SDimitry Andric continue; 22250b57cec5SDimitry Andric } 22260b57cec5SDimitry Andric 22270b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 22280b57cec5SDimitry Andric if (LoopBlockSet.count(Succ)) { 22290b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 22300b57cec5SDimitry Andric << getBlockName(Succ) << " (" << SuccProb << ")\n"); 22310b57cec5SDimitry Andric HasLoopingSucc = true; 22320b57cec5SDimitry Andric continue; 22330b57cec5SDimitry Andric } 22340b57cec5SDimitry Andric 22350b57cec5SDimitry Andric unsigned SuccLoopDepth = 0; 22360b57cec5SDimitry Andric if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 22370b57cec5SDimitry Andric SuccLoopDepth = ExitLoop->getLoopDepth(); 22380b57cec5SDimitry Andric if (ExitLoop->contains(&L)) 22390b57cec5SDimitry Andric BlocksExitingToOuterLoop.insert(MBB); 22400b57cec5SDimitry Andric } 22410b57cec5SDimitry Andric 22420b57cec5SDimitry Andric BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 22430b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 22440b57cec5SDimitry Andric << getBlockName(Succ) << " [L:" << SuccLoopDepth 22450b57cec5SDimitry Andric << "] ("; 22460b57cec5SDimitry Andric MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 22470b57cec5SDimitry Andric // Note that we bias this toward an existing layout successor to retain 22480b57cec5SDimitry Andric // incoming order in the absence of better information. The exit must have 22490b57cec5SDimitry Andric // a frequency higher than the current exit before we consider breaking 22500b57cec5SDimitry Andric // the layout. 22510b57cec5SDimitry Andric BranchProbability Bias(100 - ExitBlockBias, 100); 22520b57cec5SDimitry Andric if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 22530b57cec5SDimitry Andric ExitEdgeFreq > BestExitEdgeFreq || 22540b57cec5SDimitry Andric (MBB->isLayoutSuccessor(Succ) && 22550b57cec5SDimitry Andric !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 22560b57cec5SDimitry Andric BestExitEdgeFreq = ExitEdgeFreq; 22570b57cec5SDimitry Andric ExitingBB = MBB; 22580b57cec5SDimitry Andric } 22590b57cec5SDimitry Andric } 22600b57cec5SDimitry Andric 22610b57cec5SDimitry Andric if (!HasLoopingSucc) { 22620b57cec5SDimitry Andric // Restore the old exiting state, no viable looping successor was found. 22630b57cec5SDimitry Andric ExitingBB = OldExitingBB; 22640b57cec5SDimitry Andric BestExitEdgeFreq = OldBestExitEdgeFreq; 22650b57cec5SDimitry Andric } 22660b57cec5SDimitry Andric } 22670b57cec5SDimitry Andric // Without a candidate exiting block or with only a single block in the 22680b57cec5SDimitry Andric // loop, just use the loop header to layout the loop. 22690b57cec5SDimitry Andric if (!ExitingBB) { 22700b57cec5SDimitry Andric LLVM_DEBUG( 22710b57cec5SDimitry Andric dbgs() << " No other candidate exit blocks, using loop header\n"); 22720b57cec5SDimitry Andric return nullptr; 22730b57cec5SDimitry Andric } 22740b57cec5SDimitry Andric if (L.getNumBlocks() == 1) { 22750b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 22760b57cec5SDimitry Andric return nullptr; 22770b57cec5SDimitry Andric } 22780b57cec5SDimitry Andric 22790b57cec5SDimitry Andric // Also, if we have exit blocks which lead to outer loops but didn't select 22800b57cec5SDimitry Andric // one of them as the exiting block we are rotating toward, disable loop 22810b57cec5SDimitry Andric // rotation altogether. 22820b57cec5SDimitry Andric if (!BlocksExitingToOuterLoop.empty() && 22830b57cec5SDimitry Andric !BlocksExitingToOuterLoop.count(ExitingBB)) 22840b57cec5SDimitry Andric return nullptr; 22850b57cec5SDimitry Andric 22860b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) 22870b57cec5SDimitry Andric << "\n"); 22880b57cec5SDimitry Andric ExitFreq = BestExitEdgeFreq; 22890b57cec5SDimitry Andric return ExitingBB; 22900b57cec5SDimitry Andric } 22910b57cec5SDimitry Andric 22920b57cec5SDimitry Andric /// Check if there is a fallthrough to loop header Top. 22930b57cec5SDimitry Andric /// 22940b57cec5SDimitry Andric /// 1. Look for a Pred that can be layout before Top. 22950b57cec5SDimitry Andric /// 2. Check if Top is the most possible successor of Pred. 22960b57cec5SDimitry Andric bool 22970b57cec5SDimitry Andric MachineBlockPlacement::hasViableTopFallthrough( 22980b57cec5SDimitry Andric const MachineBasicBlock *Top, 22990b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 23000b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) { 23010b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 23020b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 23030b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 23040b57cec5SDimitry Andric // Found a Pred block can be placed before Top. 23050b57cec5SDimitry Andric // Check if Top is the best successor of Pred. 23060b57cec5SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top); 23070b57cec5SDimitry Andric bool TopOK = true; 23080b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) { 23090b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 23100b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 23110b57cec5SDimitry Andric // Check if Succ can be placed after Pred. 23120b57cec5SDimitry Andric // Succ should not be in any chain, or it is the head of some chain. 23130b57cec5SDimitry Andric if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) { 23140b57cec5SDimitry Andric TopOK = false; 23150b57cec5SDimitry Andric break; 23160b57cec5SDimitry Andric } 23170b57cec5SDimitry Andric } 23180b57cec5SDimitry Andric if (TopOK) 23190b57cec5SDimitry Andric return true; 23200b57cec5SDimitry Andric } 23210b57cec5SDimitry Andric } 23220b57cec5SDimitry Andric return false; 23230b57cec5SDimitry Andric } 23240b57cec5SDimitry Andric 23250b57cec5SDimitry Andric /// Attempt to rotate an exiting block to the bottom of the loop. 23260b57cec5SDimitry Andric /// 23270b57cec5SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block 23280b57cec5SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 23290b57cec5SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out 23300b57cec5SDimitry Andric /// of its bottom already, don't rotate it. 23310b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 23320b57cec5SDimitry Andric const MachineBasicBlock *ExitingBB, 23330b57cec5SDimitry Andric BlockFrequency ExitFreq, 23340b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 23350b57cec5SDimitry Andric if (!ExitingBB) 23360b57cec5SDimitry Andric return; 23370b57cec5SDimitry Andric 23380b57cec5SDimitry Andric MachineBasicBlock *Top = *LoopChain.begin(); 23390b57cec5SDimitry Andric MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 23400b57cec5SDimitry Andric 23410b57cec5SDimitry Andric // If ExitingBB is already the last one in a chain then nothing to do. 23420b57cec5SDimitry Andric if (Bottom == ExitingBB) 23430b57cec5SDimitry Andric return; 23440b57cec5SDimitry Andric 2345e8d8bef9SDimitry Andric // The entry block should always be the first BB in a function. 2346e8d8bef9SDimitry Andric if (Top->isEntryBlock()) 2347e8d8bef9SDimitry Andric return; 2348e8d8bef9SDimitry Andric 23490b57cec5SDimitry Andric bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet); 23500b57cec5SDimitry Andric 23510b57cec5SDimitry Andric // If the header has viable fallthrough, check whether the current loop 23520b57cec5SDimitry Andric // bottom is a viable exiting block. If so, bail out as rotating will 23530b57cec5SDimitry Andric // introduce an unnecessary branch. 23540b57cec5SDimitry Andric if (ViableTopFallthrough) { 23550b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Bottom->successors()) { 23560b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 23570b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && 23580b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) 23590b57cec5SDimitry Andric return; 23600b57cec5SDimitry Andric } 23610b57cec5SDimitry Andric 23620b57cec5SDimitry Andric // Rotate will destroy the top fallthrough, we need to ensure the new exit 23630b57cec5SDimitry Andric // frequency is larger than top fallthrough. 23640b57cec5SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet); 23650b57cec5SDimitry Andric if (FallThrough2Top >= ExitFreq) 23660b57cec5SDimitry Andric return; 23670b57cec5SDimitry Andric } 23680b57cec5SDimitry Andric 23690b57cec5SDimitry Andric BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB); 23700b57cec5SDimitry Andric if (ExitIt == LoopChain.end()) 23710b57cec5SDimitry Andric return; 23720b57cec5SDimitry Andric 23730b57cec5SDimitry Andric // Rotating a loop exit to the bottom when there is a fallthrough to top 23740b57cec5SDimitry Andric // trades the entry fallthrough for an exit fallthrough. 23750b57cec5SDimitry Andric // If there is no bottom->top edge, but the chosen exit block does have 23760b57cec5SDimitry Andric // a fallthrough, we break that fallthrough for nothing in return. 23770b57cec5SDimitry Andric 23780b57cec5SDimitry Andric // Let's consider an example. We have a built chain of basic blocks 23790b57cec5SDimitry Andric // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block. 23800b57cec5SDimitry Andric // By doing a rotation we get 23810b57cec5SDimitry Andric // Bk+1, ..., Bn, B1, ..., Bk 23820b57cec5SDimitry Andric // Break of fallthrough to B1 is compensated by a fallthrough from Bk. 23830b57cec5SDimitry Andric // If we had a fallthrough Bk -> Bk+1 it is broken now. 23840b57cec5SDimitry Andric // It might be compensated by fallthrough Bn -> B1. 23850b57cec5SDimitry Andric // So we have a condition to avoid creation of extra branch by loop rotation. 23860b57cec5SDimitry Andric // All below must be true to avoid loop rotation: 23870b57cec5SDimitry Andric // If there is a fallthrough to top (B1) 23880b57cec5SDimitry Andric // There was fallthrough from chosen exit block (Bk) to next one (Bk+1) 23890b57cec5SDimitry Andric // There is no fallthrough from bottom (Bn) to top (B1). 23900b57cec5SDimitry Andric // Please note that there is no exit fallthrough from Bn because we checked it 23910b57cec5SDimitry Andric // above. 23920b57cec5SDimitry Andric if (ViableTopFallthrough) { 23930b57cec5SDimitry Andric assert(std::next(ExitIt) != LoopChain.end() && 23940b57cec5SDimitry Andric "Exit should not be last BB"); 23950b57cec5SDimitry Andric MachineBasicBlock *NextBlockInChain = *std::next(ExitIt); 23960b57cec5SDimitry Andric if (ExitingBB->isSuccessor(NextBlockInChain)) 23970b57cec5SDimitry Andric if (!Bottom->isSuccessor(Top)) 23980b57cec5SDimitry Andric return; 23990b57cec5SDimitry Andric } 24000b57cec5SDimitry Andric 24010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB) 24020b57cec5SDimitry Andric << " at bottom\n"); 24030b57cec5SDimitry Andric std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 24040b57cec5SDimitry Andric } 24050b57cec5SDimitry Andric 24060b57cec5SDimitry Andric /// Attempt to rotate a loop based on profile data to reduce branch cost. 24070b57cec5SDimitry Andric /// 24080b57cec5SDimitry Andric /// With profile data, we can determine the cost in terms of missed fall through 24090b57cec5SDimitry Andric /// opportunities when rotating a loop chain and select the best rotation. 24100b57cec5SDimitry Andric /// Basically, there are three kinds of cost to consider for each rotation: 24110b57cec5SDimitry Andric /// 1. The possibly missed fall through edge (if it exists) from BB out of 24120b57cec5SDimitry Andric /// the loop to the loop header. 24130b57cec5SDimitry Andric /// 2. The possibly missed fall through edges (if they exist) from the loop 24140b57cec5SDimitry Andric /// exits to BB out of the loop. 24150b57cec5SDimitry Andric /// 3. The missed fall through edge (if it exists) from the last BB to the 24160b57cec5SDimitry Andric /// first BB in the loop chain. 24170b57cec5SDimitry Andric /// Therefore, the cost for a given rotation is the sum of costs listed above. 24180b57cec5SDimitry Andric /// We select the best rotation with the smallest cost. 24190b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoopWithProfile( 24200b57cec5SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 24210b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 24220b57cec5SDimitry Andric auto RotationPos = LoopChain.end(); 2423e8d8bef9SDimitry Andric MachineBasicBlock *ChainHeaderBB = *LoopChain.begin(); 2424e8d8bef9SDimitry Andric 2425e8d8bef9SDimitry Andric // The entry block should always be the first BB in a function. 2426e8d8bef9SDimitry Andric if (ChainHeaderBB->isEntryBlock()) 2427e8d8bef9SDimitry Andric return; 24280b57cec5SDimitry Andric 24290b57cec5SDimitry Andric BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); 24300b57cec5SDimitry Andric 24310b57cec5SDimitry Andric // A utility lambda that scales up a block frequency by dividing it by a 24320b57cec5SDimitry Andric // branch probability which is the reciprocal of the scale. 24330b57cec5SDimitry Andric auto ScaleBlockFrequency = [](BlockFrequency Freq, 24340b57cec5SDimitry Andric unsigned Scale) -> BlockFrequency { 24350b57cec5SDimitry Andric if (Scale == 0) 24360b57cec5SDimitry Andric return 0; 24370b57cec5SDimitry Andric // Use operator / between BlockFrequency and BranchProbability to implement 24380b57cec5SDimitry Andric // saturating multiplication. 24390b57cec5SDimitry Andric return Freq / BranchProbability(1, Scale); 24400b57cec5SDimitry Andric }; 24410b57cec5SDimitry Andric 24420b57cec5SDimitry Andric // Compute the cost of the missed fall-through edge to the loop header if the 24430b57cec5SDimitry Andric // chain head is not the loop header. As we only consider natural loops with 24440b57cec5SDimitry Andric // single header, this computation can be done only once. 24450b57cec5SDimitry Andric BlockFrequency HeaderFallThroughCost(0); 24460b57cec5SDimitry Andric for (auto *Pred : ChainHeaderBB->predecessors()) { 24470b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 24480b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 24490b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 24500b57cec5SDimitry Andric auto EdgeFreq = MBFI->getBlockFreq(Pred) * 24510b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, ChainHeaderBB); 24520b57cec5SDimitry Andric auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 24530b57cec5SDimitry Andric // If the predecessor has only an unconditional jump to the header, we 24540b57cec5SDimitry Andric // need to consider the cost of this jump. 24550b57cec5SDimitry Andric if (Pred->succ_size() == 1) 24560b57cec5SDimitry Andric FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 24570b57cec5SDimitry Andric HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 24580b57cec5SDimitry Andric } 24590b57cec5SDimitry Andric } 24600b57cec5SDimitry Andric 24610b57cec5SDimitry Andric // Here we collect all exit blocks in the loop, and for each exit we find out 24620b57cec5SDimitry Andric // its hottest exit edge. For each loop rotation, we define the loop exit cost 24630b57cec5SDimitry Andric // as the sum of frequencies of exit edges we collect here, excluding the exit 24640b57cec5SDimitry Andric // edge from the tail of the loop chain. 24650b57cec5SDimitry Andric SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 2466fcaf7f86SDimitry Andric for (auto *BB : LoopChain) { 24670b57cec5SDimitry Andric auto LargestExitEdgeProb = BranchProbability::getZero(); 24680b57cec5SDimitry Andric for (auto *Succ : BB->successors()) { 24690b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 24700b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && 24710b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) { 24720b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 24730b57cec5SDimitry Andric LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 24740b57cec5SDimitry Andric } 24750b57cec5SDimitry Andric } 24760b57cec5SDimitry Andric if (LargestExitEdgeProb > BranchProbability::getZero()) { 24770b57cec5SDimitry Andric auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 24780b57cec5SDimitry Andric ExitsWithFreq.emplace_back(BB, ExitFreq); 24790b57cec5SDimitry Andric } 24800b57cec5SDimitry Andric } 24810b57cec5SDimitry Andric 24820b57cec5SDimitry Andric // In this loop we iterate every block in the loop chain and calculate the 24830b57cec5SDimitry Andric // cost assuming the block is the head of the loop chain. When the loop ends, 24840b57cec5SDimitry Andric // we should have found the best candidate as the loop chain's head. 24850b57cec5SDimitry Andric for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 24860b57cec5SDimitry Andric EndIter = LoopChain.end(); 24870b57cec5SDimitry Andric Iter != EndIter; Iter++, TailIter++) { 24880b57cec5SDimitry Andric // TailIter is used to track the tail of the loop chain if the block we are 24890b57cec5SDimitry Andric // checking (pointed by Iter) is the head of the chain. 24900b57cec5SDimitry Andric if (TailIter == LoopChain.end()) 24910b57cec5SDimitry Andric TailIter = LoopChain.begin(); 24920b57cec5SDimitry Andric 24930b57cec5SDimitry Andric auto TailBB = *TailIter; 24940b57cec5SDimitry Andric 24950b57cec5SDimitry Andric // Calculate the cost by putting this BB to the top. 24960b57cec5SDimitry Andric BlockFrequency Cost = 0; 24970b57cec5SDimitry Andric 24980b57cec5SDimitry Andric // If the current BB is the loop header, we need to take into account the 24990b57cec5SDimitry Andric // cost of the missed fall through edge from outside of the loop to the 25000b57cec5SDimitry Andric // header. 25010b57cec5SDimitry Andric if (Iter != LoopChain.begin()) 25020b57cec5SDimitry Andric Cost += HeaderFallThroughCost; 25030b57cec5SDimitry Andric 25040b57cec5SDimitry Andric // Collect the loop exit cost by summing up frequencies of all exit edges 25050b57cec5SDimitry Andric // except the one from the chain tail. 25060b57cec5SDimitry Andric for (auto &ExitWithFreq : ExitsWithFreq) 25070b57cec5SDimitry Andric if (TailBB != ExitWithFreq.first) 25080b57cec5SDimitry Andric Cost += ExitWithFreq.second; 25090b57cec5SDimitry Andric 25100b57cec5SDimitry Andric // The cost of breaking the once fall-through edge from the tail to the top 25110b57cec5SDimitry Andric // of the loop chain. Here we need to consider three cases: 25120b57cec5SDimitry Andric // 1. If the tail node has only one successor, then we will get an 25130b57cec5SDimitry Andric // additional jmp instruction. So the cost here is (MisfetchCost + 25140b57cec5SDimitry Andric // JumpInstCost) * tail node frequency. 25150b57cec5SDimitry Andric // 2. If the tail node has two successors, then we may still get an 25160b57cec5SDimitry Andric // additional jmp instruction if the layout successor after the loop 25170b57cec5SDimitry Andric // chain is not its CFG successor. Note that the more frequently executed 25180b57cec5SDimitry Andric // jmp instruction will be put ahead of the other one. Assume the 25190b57cec5SDimitry Andric // frequency of those two branches are x and y, where x is the frequency 25200b57cec5SDimitry Andric // of the edge to the chain head, then the cost will be 25210b57cec5SDimitry Andric // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 25220b57cec5SDimitry Andric // 3. If the tail node has more than two successors (this rarely happens), 25230b57cec5SDimitry Andric // we won't consider any additional cost. 25240b57cec5SDimitry Andric if (TailBB->isSuccessor(*Iter)) { 25250b57cec5SDimitry Andric auto TailBBFreq = MBFI->getBlockFreq(TailBB); 25260b57cec5SDimitry Andric if (TailBB->succ_size() == 1) 25270b57cec5SDimitry Andric Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), 25280b57cec5SDimitry Andric MisfetchCost + JumpInstCost); 25290b57cec5SDimitry Andric else if (TailBB->succ_size() == 2) { 25300b57cec5SDimitry Andric auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 25310b57cec5SDimitry Andric auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 25320b57cec5SDimitry Andric auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 25330b57cec5SDimitry Andric ? TailBBFreq * TailToHeadProb.getCompl() 25340b57cec5SDimitry Andric : TailToHeadFreq; 25350b57cec5SDimitry Andric Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 25360b57cec5SDimitry Andric ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 25370b57cec5SDimitry Andric } 25380b57cec5SDimitry Andric } 25390b57cec5SDimitry Andric 25400b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "The cost of loop rotation by making " 25410b57cec5SDimitry Andric << getBlockName(*Iter) 25420b57cec5SDimitry Andric << " to the top: " << Cost.getFrequency() << "\n"); 25430b57cec5SDimitry Andric 25440b57cec5SDimitry Andric if (Cost < SmallestRotationCost) { 25450b57cec5SDimitry Andric SmallestRotationCost = Cost; 25460b57cec5SDimitry Andric RotationPos = Iter; 25470b57cec5SDimitry Andric } 25480b57cec5SDimitry Andric } 25490b57cec5SDimitry Andric 25500b57cec5SDimitry Andric if (RotationPos != LoopChain.end()) { 25510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 25520b57cec5SDimitry Andric << " to the top\n"); 25530b57cec5SDimitry Andric std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 25540b57cec5SDimitry Andric } 25550b57cec5SDimitry Andric } 25560b57cec5SDimitry Andric 25570b57cec5SDimitry Andric /// Collect blocks in the given loop that are to be placed. 25580b57cec5SDimitry Andric /// 25590b57cec5SDimitry Andric /// When profile data is available, exclude cold blocks from the returned set; 25600b57cec5SDimitry Andric /// otherwise, collect all blocks in the loop. 25610b57cec5SDimitry Andric MachineBlockPlacement::BlockFilterSet 25620b57cec5SDimitry Andric MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) { 25630b57cec5SDimitry Andric BlockFilterSet LoopBlockSet; 25640b57cec5SDimitry Andric 25650b57cec5SDimitry Andric // Filter cold blocks off from LoopBlockSet when profile data is available. 25660b57cec5SDimitry Andric // Collect the sum of frequencies of incoming edges to the loop header from 25670b57cec5SDimitry Andric // outside. If we treat the loop as a super block, this is the frequency of 25680b57cec5SDimitry Andric // the loop. Then for each block in the loop, we calculate the ratio between 25690b57cec5SDimitry Andric // its frequency and the frequency of the loop block. When it is too small, 25700b57cec5SDimitry Andric // don't add it to the loop chain. If there are outer loops, then this block 25710b57cec5SDimitry Andric // will be merged into the first outer loop chain for which this block is not 25720b57cec5SDimitry Andric // cold anymore. This needs precise profile data and we only do this when 25730b57cec5SDimitry Andric // profile data is available. 25740b57cec5SDimitry Andric if (F->getFunction().hasProfileData() || ForceLoopColdBlock) { 25750b57cec5SDimitry Andric BlockFrequency LoopFreq(0); 2576fcaf7f86SDimitry Andric for (auto *LoopPred : L.getHeader()->predecessors()) 25770b57cec5SDimitry Andric if (!L.contains(LoopPred)) 25780b57cec5SDimitry Andric LoopFreq += MBFI->getBlockFreq(LoopPred) * 25790b57cec5SDimitry Andric MBPI->getEdgeProbability(LoopPred, L.getHeader()); 25800b57cec5SDimitry Andric 25810b57cec5SDimitry Andric for (MachineBasicBlock *LoopBB : L.getBlocks()) { 2582e8d8bef9SDimitry Andric if (LoopBlockSet.count(LoopBB)) 2583e8d8bef9SDimitry Andric continue; 25840b57cec5SDimitry Andric auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 25850b57cec5SDimitry Andric if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 25860b57cec5SDimitry Andric continue; 2587e8d8bef9SDimitry Andric BlockChain *Chain = BlockToChain[LoopBB]; 2588e8d8bef9SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) 2589e8d8bef9SDimitry Andric LoopBlockSet.insert(ChainBB); 25900b57cec5SDimitry Andric } 25910b57cec5SDimitry Andric } else 25920b57cec5SDimitry Andric LoopBlockSet.insert(L.block_begin(), L.block_end()); 25930b57cec5SDimitry Andric 25940b57cec5SDimitry Andric return LoopBlockSet; 25950b57cec5SDimitry Andric } 25960b57cec5SDimitry Andric 25970b57cec5SDimitry Andric /// Forms basic block chains from the natural loop structures. 25980b57cec5SDimitry Andric /// 25990b57cec5SDimitry Andric /// These chains are designed to preserve the existing *structure* of the code 26000b57cec5SDimitry Andric /// as much as possible. We can then stitch the chains together in a way which 26010b57cec5SDimitry Andric /// both preserves the topological structure and minimizes taken conditional 26020b57cec5SDimitry Andric /// branches. 26030b57cec5SDimitry Andric void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) { 26040b57cec5SDimitry Andric // First recurse through any nested loops, building chains for those inner 26050b57cec5SDimitry Andric // loops. 26060b57cec5SDimitry Andric for (const MachineLoop *InnerLoop : L) 26070b57cec5SDimitry Andric buildLoopChains(*InnerLoop); 26080b57cec5SDimitry Andric 26090b57cec5SDimitry Andric assert(BlockWorkList.empty() && 26100b57cec5SDimitry Andric "BlockWorkList not empty when starting to build loop chains."); 26110b57cec5SDimitry Andric assert(EHPadWorkList.empty() && 26120b57cec5SDimitry Andric "EHPadWorkList not empty when starting to build loop chains."); 26130b57cec5SDimitry Andric BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 26140b57cec5SDimitry Andric 26150b57cec5SDimitry Andric // Check if we have profile data for this function. If yes, we will rotate 26160b57cec5SDimitry Andric // this loop by modeling costs more precisely which requires the profile data 26170b57cec5SDimitry Andric // for better layout. 26180b57cec5SDimitry Andric bool RotateLoopWithProfile = 26190b57cec5SDimitry Andric ForcePreciseRotationCost || 26200b57cec5SDimitry Andric (PreciseRotationCost && F->getFunction().hasProfileData()); 26210b57cec5SDimitry Andric 26220b57cec5SDimitry Andric // First check to see if there is an obviously preferable top block for the 26230b57cec5SDimitry Andric // loop. This will default to the header, but may end up as one of the 26240b57cec5SDimitry Andric // predecessors to the header if there is one which will result in strictly 26250b57cec5SDimitry Andric // fewer branches in the loop body. 26260b57cec5SDimitry Andric MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet); 26270b57cec5SDimitry Andric 26280b57cec5SDimitry Andric // If we selected just the header for the loop top, look for a potentially 26290b57cec5SDimitry Andric // profitable exit block in the event that rotating the loop can eliminate 26300b57cec5SDimitry Andric // branches by placing an exit edge at the bottom. 26310b57cec5SDimitry Andric // 26320b57cec5SDimitry Andric // Loops are processed innermost to uttermost, make sure we clear 26330b57cec5SDimitry Andric // PreferredLoopExit before processing a new loop. 26340b57cec5SDimitry Andric PreferredLoopExit = nullptr; 26350b57cec5SDimitry Andric BlockFrequency ExitFreq; 26360b57cec5SDimitry Andric if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 26370b57cec5SDimitry Andric PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq); 26380b57cec5SDimitry Andric 26390b57cec5SDimitry Andric BlockChain &LoopChain = *BlockToChain[LoopTop]; 26400b57cec5SDimitry Andric 26410b57cec5SDimitry Andric // FIXME: This is a really lame way of walking the chains in the loop: we 26420b57cec5SDimitry Andric // walk the blocks, and use a set to prevent visiting a particular chain 26430b57cec5SDimitry Andric // twice. 26440b57cec5SDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 26450b57cec5SDimitry Andric assert(LoopChain.UnscheduledPredecessors == 0 && 26460b57cec5SDimitry Andric "LoopChain should not have unscheduled predecessors."); 26470b57cec5SDimitry Andric UpdatedPreds.insert(&LoopChain); 26480b57cec5SDimitry Andric 26490b57cec5SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 26500b57cec5SDimitry Andric fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 26510b57cec5SDimitry Andric 26520b57cec5SDimitry Andric buildChain(LoopTop, LoopChain, &LoopBlockSet); 26530b57cec5SDimitry Andric 26540b57cec5SDimitry Andric if (RotateLoopWithProfile) 26550b57cec5SDimitry Andric rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 26560b57cec5SDimitry Andric else 26570b57cec5SDimitry Andric rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet); 26580b57cec5SDimitry Andric 26590b57cec5SDimitry Andric LLVM_DEBUG({ 26600b57cec5SDimitry Andric // Crash at the end so we get all of the debugging output first. 26610b57cec5SDimitry Andric bool BadLoop = false; 26620b57cec5SDimitry Andric if (LoopChain.UnscheduledPredecessors) { 26630b57cec5SDimitry Andric BadLoop = true; 26640b57cec5SDimitry Andric dbgs() << "Loop chain contains a block without its preds placed!\n" 26650b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 26660b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 26670b57cec5SDimitry Andric } 26680b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : LoopChain) { 26690b57cec5SDimitry Andric dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 26700b57cec5SDimitry Andric if (!LoopBlockSet.remove(ChainBB)) { 26710b57cec5SDimitry Andric // We don't mark the loop as bad here because there are real situations 26720b57cec5SDimitry Andric // where this can occur. For example, with an unanalyzable fallthrough 26730b57cec5SDimitry Andric // from a loop block to a non-loop block or vice versa. 26740b57cec5SDimitry Andric dbgs() << "Loop chain contains a block not contained by the loop!\n" 26750b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 26760b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 26770b57cec5SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 26780b57cec5SDimitry Andric } 26790b57cec5SDimitry Andric } 26800b57cec5SDimitry Andric 26810b57cec5SDimitry Andric if (!LoopBlockSet.empty()) { 26820b57cec5SDimitry Andric BadLoop = true; 26830b57cec5SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 26840b57cec5SDimitry Andric dbgs() << "Loop contains blocks never placed into a chain!\n" 26850b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 26860b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 26870b57cec5SDimitry Andric << " Bad block: " << getBlockName(LoopBB) << "\n"; 26880b57cec5SDimitry Andric } 26890b57cec5SDimitry Andric assert(!BadLoop && "Detected problems with the placement of this loop."); 26900b57cec5SDimitry Andric }); 26910b57cec5SDimitry Andric 26920b57cec5SDimitry Andric BlockWorkList.clear(); 26930b57cec5SDimitry Andric EHPadWorkList.clear(); 26940b57cec5SDimitry Andric } 26950b57cec5SDimitry Andric 26960b57cec5SDimitry Andric void MachineBlockPlacement::buildCFGChains() { 26970b57cec5SDimitry Andric // Ensure that every BB in the function has an associated chain to simplify 26980b57cec5SDimitry Andric // the assumptions of the remaining algorithm. 26995ffd83dbSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 27000b57cec5SDimitry Andric for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 27010b57cec5SDimitry Andric ++FI) { 27020b57cec5SDimitry Andric MachineBasicBlock *BB = &*FI; 27030b57cec5SDimitry Andric BlockChain *Chain = 27040b57cec5SDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 27050b57cec5SDimitry Andric // Also, merge any blocks which we cannot reason about and must preserve 27060b57cec5SDimitry Andric // the exact fallthrough behavior for. 27070b57cec5SDimitry Andric while (true) { 27080b57cec5SDimitry Andric Cond.clear(); 27095ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 27100b57cec5SDimitry Andric if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 27110b57cec5SDimitry Andric break; 27120b57cec5SDimitry Andric 27130b57cec5SDimitry Andric MachineFunction::iterator NextFI = std::next(FI); 27140b57cec5SDimitry Andric MachineBasicBlock *NextBB = &*NextFI; 27150b57cec5SDimitry Andric // Ensure that the layout successor is a viable block, as we know that 27160b57cec5SDimitry Andric // fallthrough is a possibility. 27170b57cec5SDimitry Andric assert(NextFI != FE && "Can't fallthrough past the last block."); 27180b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 27190b57cec5SDimitry Andric << getBlockName(BB) << " -> " << getBlockName(NextBB) 27200b57cec5SDimitry Andric << "\n"); 27210b57cec5SDimitry Andric Chain->merge(NextBB, nullptr); 27220b57cec5SDimitry Andric #ifndef NDEBUG 27230b57cec5SDimitry Andric BlocksWithUnanalyzableExits.insert(&*BB); 27240b57cec5SDimitry Andric #endif 27250b57cec5SDimitry Andric FI = NextFI; 27260b57cec5SDimitry Andric BB = NextBB; 27270b57cec5SDimitry Andric } 27280b57cec5SDimitry Andric } 27290b57cec5SDimitry Andric 27300b57cec5SDimitry Andric // Build any loop-based chains. 27310b57cec5SDimitry Andric PreferredLoopExit = nullptr; 27320b57cec5SDimitry Andric for (MachineLoop *L : *MLI) 27330b57cec5SDimitry Andric buildLoopChains(*L); 27340b57cec5SDimitry Andric 27350b57cec5SDimitry Andric assert(BlockWorkList.empty() && 27360b57cec5SDimitry Andric "BlockWorkList should be empty before building final chain."); 27370b57cec5SDimitry Andric assert(EHPadWorkList.empty() && 27380b57cec5SDimitry Andric "EHPadWorkList should be empty before building final chain."); 27390b57cec5SDimitry Andric 27400b57cec5SDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 27410b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *F) 27420b57cec5SDimitry Andric fillWorkLists(&MBB, UpdatedPreds); 27430b57cec5SDimitry Andric 27440b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 27450b57cec5SDimitry Andric buildChain(&F->front(), FunctionChain); 27460b57cec5SDimitry Andric 27470b57cec5SDimitry Andric #ifndef NDEBUG 27480b57cec5SDimitry Andric using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>; 27490b57cec5SDimitry Andric #endif 27500b57cec5SDimitry Andric LLVM_DEBUG({ 27510b57cec5SDimitry Andric // Crash at the end so we get all of the debugging output first. 27520b57cec5SDimitry Andric bool BadFunc = false; 27530b57cec5SDimitry Andric FunctionBlockSetType FunctionBlockSet; 27540b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *F) 27550b57cec5SDimitry Andric FunctionBlockSet.insert(&MBB); 27560b57cec5SDimitry Andric 27570b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) 27580b57cec5SDimitry Andric if (!FunctionBlockSet.erase(ChainBB)) { 27590b57cec5SDimitry Andric BadFunc = true; 27600b57cec5SDimitry Andric dbgs() << "Function chain contains a block not in the function!\n" 27610b57cec5SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 27620b57cec5SDimitry Andric } 27630b57cec5SDimitry Andric 27640b57cec5SDimitry Andric if (!FunctionBlockSet.empty()) { 27650b57cec5SDimitry Andric BadFunc = true; 27660b57cec5SDimitry Andric for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 27670b57cec5SDimitry Andric dbgs() << "Function contains blocks never placed into a chain!\n" 27680b57cec5SDimitry Andric << " Bad block: " << getBlockName(RemainingBB) << "\n"; 27690b57cec5SDimitry Andric } 27700b57cec5SDimitry Andric assert(!BadFunc && "Detected problems with the block placement."); 27710b57cec5SDimitry Andric }); 27720b57cec5SDimitry Andric 27735ffd83dbSDimitry Andric // Remember original layout ordering, so we can update terminators after 27745ffd83dbSDimitry Andric // reordering to point to the original layout successor. 27755ffd83dbSDimitry Andric SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors( 27765ffd83dbSDimitry Andric F->getNumBlockIDs()); 27775ffd83dbSDimitry Andric { 27785ffd83dbSDimitry Andric MachineBasicBlock *LastMBB = nullptr; 27795ffd83dbSDimitry Andric for (auto &MBB : *F) { 27805ffd83dbSDimitry Andric if (LastMBB != nullptr) 27815ffd83dbSDimitry Andric OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB; 27825ffd83dbSDimitry Andric LastMBB = &MBB; 27835ffd83dbSDimitry Andric } 27845ffd83dbSDimitry Andric OriginalLayoutSuccessors[F->back().getNumber()] = nullptr; 27855ffd83dbSDimitry Andric } 27865ffd83dbSDimitry Andric 27870b57cec5SDimitry Andric // Splice the blocks into place. 27880b57cec5SDimitry Andric MachineFunction::iterator InsertPos = F->begin(); 27890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n"); 27900b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 27910b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 27920b57cec5SDimitry Andric : " ... ") 27930b57cec5SDimitry Andric << getBlockName(ChainBB) << "\n"); 27940b57cec5SDimitry Andric if (InsertPos != MachineFunction::iterator(ChainBB)) 27950b57cec5SDimitry Andric F->splice(InsertPos, ChainBB); 27960b57cec5SDimitry Andric else 27970b57cec5SDimitry Andric ++InsertPos; 27980b57cec5SDimitry Andric 27990b57cec5SDimitry Andric // Update the terminator of the previous block. 28000b57cec5SDimitry Andric if (ChainBB == *FunctionChain.begin()) 28010b57cec5SDimitry Andric continue; 28020b57cec5SDimitry Andric MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 28030b57cec5SDimitry Andric 28040b57cec5SDimitry Andric // FIXME: It would be awesome of updateTerminator would just return rather 28050b57cec5SDimitry Andric // than assert when the branch cannot be analyzed in order to remove this 28060b57cec5SDimitry Andric // boiler plate. 28070b57cec5SDimitry Andric Cond.clear(); 28085ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 28090b57cec5SDimitry Andric 28100b57cec5SDimitry Andric #ifndef NDEBUG 28110b57cec5SDimitry Andric if (!BlocksWithUnanalyzableExits.count(PrevBB)) { 28120b57cec5SDimitry Andric // Given the exact block placement we chose, we may actually not _need_ to 28130b57cec5SDimitry Andric // be able to edit PrevBB's terminator sequence, but not being _able_ to 28140b57cec5SDimitry Andric // do that at this point is a bug. 28150b57cec5SDimitry Andric assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) || 28160b57cec5SDimitry Andric !PrevBB->canFallThrough()) && 28170b57cec5SDimitry Andric "Unexpected block with un-analyzable fallthrough!"); 28180b57cec5SDimitry Andric Cond.clear(); 28190b57cec5SDimitry Andric TBB = FBB = nullptr; 28200b57cec5SDimitry Andric } 28210b57cec5SDimitry Andric #endif 28220b57cec5SDimitry Andric 28230b57cec5SDimitry Andric // The "PrevBB" is not yet updated to reflect current code layout, so, 28240b57cec5SDimitry Andric // o. it may fall-through to a block without explicit "goto" instruction 28250b57cec5SDimitry Andric // before layout, and no longer fall-through it after layout; or 28260b57cec5SDimitry Andric // o. just opposite. 28270b57cec5SDimitry Andric // 28280b57cec5SDimitry Andric // analyzeBranch() may return erroneous value for FBB when these two 28290b57cec5SDimitry Andric // situations take place. For the first scenario FBB is mistakenly set NULL; 28300b57cec5SDimitry Andric // for the 2nd scenario, the FBB, which is expected to be NULL, is 28310b57cec5SDimitry Andric // mistakenly pointing to "*BI". 28320b57cec5SDimitry Andric // Thus, if the future change needs to use FBB before the layout is set, it 28330b57cec5SDimitry Andric // has to correct FBB first by using the code similar to the following: 28340b57cec5SDimitry Andric // 28350b57cec5SDimitry Andric // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 28360b57cec5SDimitry Andric // PrevBB->updateTerminator(); 28370b57cec5SDimitry Andric // Cond.clear(); 28380b57cec5SDimitry Andric // TBB = FBB = nullptr; 28390b57cec5SDimitry Andric // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 28400b57cec5SDimitry Andric // // FIXME: This should never take place. 28410b57cec5SDimitry Andric // TBB = FBB = nullptr; 28420b57cec5SDimitry Andric // } 28430b57cec5SDimitry Andric // } 28445ffd83dbSDimitry Andric if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 28455ffd83dbSDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 28465ffd83dbSDimitry Andric } 28470b57cec5SDimitry Andric } 28480b57cec5SDimitry Andric 28490b57cec5SDimitry Andric // Fixup the last block. 28500b57cec5SDimitry Andric Cond.clear(); 28515ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 28525ffd83dbSDimitry Andric if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) { 28535ffd83dbSDimitry Andric MachineBasicBlock *PrevBB = &F->back(); 28545ffd83dbSDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 28555ffd83dbSDimitry Andric } 28560b57cec5SDimitry Andric 28570b57cec5SDimitry Andric BlockWorkList.clear(); 28580b57cec5SDimitry Andric EHPadWorkList.clear(); 28590b57cec5SDimitry Andric } 28600b57cec5SDimitry Andric 28610b57cec5SDimitry Andric void MachineBlockPlacement::optimizeBranches() { 28620b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 28635ffd83dbSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 28640b57cec5SDimitry Andric 28650b57cec5SDimitry Andric // Now that all the basic blocks in the chain have the proper layout, 28665ffd83dbSDimitry Andric // make a final call to analyzeBranch with AllowModify set. 28670b57cec5SDimitry Andric // Indeed, the target may be able to optimize the branches in a way we 28680b57cec5SDimitry Andric // cannot because all branches may not be analyzable. 28690b57cec5SDimitry Andric // E.g., the target may be able to remove an unconditional branch to 28700b57cec5SDimitry Andric // a fallthrough when it occurs after predicated terminators. 28710b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 28720b57cec5SDimitry Andric Cond.clear(); 28735ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 28740b57cec5SDimitry Andric if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 28750b57cec5SDimitry Andric // If PrevBB has a two-way branch, try to re-order the branches 28760b57cec5SDimitry Andric // such that we branch to the successor with higher probability first. 28770b57cec5SDimitry Andric if (TBB && !Cond.empty() && FBB && 28780b57cec5SDimitry Andric MBPI->getEdgeProbability(ChainBB, FBB) > 28790b57cec5SDimitry Andric MBPI->getEdgeProbability(ChainBB, TBB) && 28800b57cec5SDimitry Andric !TII->reverseBranchCondition(Cond)) { 28810b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Reverse order of the two branches: " 28820b57cec5SDimitry Andric << getBlockName(ChainBB) << "\n"); 28830b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Edge probability: " 28840b57cec5SDimitry Andric << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 28850b57cec5SDimitry Andric << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 28860b57cec5SDimitry Andric DebugLoc dl; // FIXME: this is nowhere 28870b57cec5SDimitry Andric TII->removeBranch(*ChainBB); 28880b57cec5SDimitry Andric TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 28890b57cec5SDimitry Andric } 28900b57cec5SDimitry Andric } 28910b57cec5SDimitry Andric } 28920b57cec5SDimitry Andric } 28930b57cec5SDimitry Andric 28940b57cec5SDimitry Andric void MachineBlockPlacement::alignBlocks() { 28950b57cec5SDimitry Andric // Walk through the backedges of the function now that we have fully laid out 28960b57cec5SDimitry Andric // the basic blocks and align the destination of each backedge. We don't rely 28970b57cec5SDimitry Andric // exclusively on the loop info here so that we can align backedges in 28980b57cec5SDimitry Andric // unnatural CFGs and backedges that were introduced purely because of the 28990b57cec5SDimitry Andric // loop rotations done during this layout pass. 29000b57cec5SDimitry Andric if (F->getFunction().hasMinSize() || 29010b57cec5SDimitry Andric (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize())) 29020b57cec5SDimitry Andric return; 29030b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 29040b57cec5SDimitry Andric if (FunctionChain.begin() == FunctionChain.end()) 29050b57cec5SDimitry Andric return; // Empty chain. 29060b57cec5SDimitry Andric 29070b57cec5SDimitry Andric const BranchProbability ColdProb(1, 5); // 20% 29080b57cec5SDimitry Andric BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 29090b57cec5SDimitry Andric BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 29100b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 29110b57cec5SDimitry Andric if (ChainBB == *FunctionChain.begin()) 29120b57cec5SDimitry Andric continue; 29130b57cec5SDimitry Andric 29140b57cec5SDimitry Andric // Don't align non-looping basic blocks. These are unlikely to execute 29150b57cec5SDimitry Andric // enough times to matter in practice. Note that we'll still handle 29160b57cec5SDimitry Andric // unnatural CFGs inside of a natural outer loop (the common case) and 29170b57cec5SDimitry Andric // rotated loops. 29180b57cec5SDimitry Andric MachineLoop *L = MLI->getLoopFor(ChainBB); 29190b57cec5SDimitry Andric if (!L) 29200b57cec5SDimitry Andric continue; 29210b57cec5SDimitry Andric 29228bcb0991SDimitry Andric const Align Align = TLI->getPrefLoopAlignment(L); 29238bcb0991SDimitry Andric if (Align == 1) 29240b57cec5SDimitry Andric continue; // Don't care about loop alignment. 29250b57cec5SDimitry Andric 29260b57cec5SDimitry Andric // If the block is cold relative to the function entry don't waste space 29270b57cec5SDimitry Andric // aligning it. 29280b57cec5SDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 29290b57cec5SDimitry Andric if (Freq < WeightedEntryFreq) 29300b57cec5SDimitry Andric continue; 29310b57cec5SDimitry Andric 29320b57cec5SDimitry Andric // If the block is cold relative to its loop header, don't align it 29330b57cec5SDimitry Andric // regardless of what edges into the block exist. 29340b57cec5SDimitry Andric MachineBasicBlock *LoopHeader = L->getHeader(); 29350b57cec5SDimitry Andric BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 29360b57cec5SDimitry Andric if (Freq < (LoopHeaderFreq * ColdProb)) 29370b57cec5SDimitry Andric continue; 29380b57cec5SDimitry Andric 2939480093f4SDimitry Andric // If the global profiles indicates so, don't align it. 29405ffd83dbSDimitry Andric if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) && 2941480093f4SDimitry Andric !TLI->alignLoopsWithOptSize()) 2942480093f4SDimitry Andric continue; 2943480093f4SDimitry Andric 29440b57cec5SDimitry Andric // Check for the existence of a non-layout predecessor which would benefit 29450b57cec5SDimitry Andric // from aligning this block. 29460b57cec5SDimitry Andric MachineBasicBlock *LayoutPred = 29470b57cec5SDimitry Andric &*std::prev(MachineFunction::iterator(ChainBB)); 29480b57cec5SDimitry Andric 294904eeddc0SDimitry Andric auto DetermineMaxAlignmentPadding = [&]() { 295004eeddc0SDimitry Andric // Set the maximum bytes allowed to be emitted for alignment. 295104eeddc0SDimitry Andric unsigned MaxBytes; 295204eeddc0SDimitry Andric if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0) 295304eeddc0SDimitry Andric MaxBytes = MaxBytesForAlignmentOverride; 295404eeddc0SDimitry Andric else 295504eeddc0SDimitry Andric MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB); 295604eeddc0SDimitry Andric ChainBB->setMaxBytesForAlignment(MaxBytes); 295704eeddc0SDimitry Andric }; 295804eeddc0SDimitry Andric 29590b57cec5SDimitry Andric // Force alignment if all the predecessors are jumps. We already checked 29600b57cec5SDimitry Andric // that the block isn't cold above. 29610b57cec5SDimitry Andric if (!LayoutPred->isSuccessor(ChainBB)) { 29620b57cec5SDimitry Andric ChainBB->setAlignment(Align); 296304eeddc0SDimitry Andric DetermineMaxAlignmentPadding(); 29640b57cec5SDimitry Andric continue; 29650b57cec5SDimitry Andric } 29660b57cec5SDimitry Andric 29670b57cec5SDimitry Andric // Align this block if the layout predecessor's edge into this block is 29680b57cec5SDimitry Andric // cold relative to the block. When this is true, other predecessors make up 29690b57cec5SDimitry Andric // all of the hot entries into the block and thus alignment is likely to be 29700b57cec5SDimitry Andric // important. 29710b57cec5SDimitry Andric BranchProbability LayoutProb = 29720b57cec5SDimitry Andric MBPI->getEdgeProbability(LayoutPred, ChainBB); 29730b57cec5SDimitry Andric BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 297404eeddc0SDimitry Andric if (LayoutEdgeFreq <= (Freq * ColdProb)) { 29750b57cec5SDimitry Andric ChainBB->setAlignment(Align); 297604eeddc0SDimitry Andric DetermineMaxAlignmentPadding(); 297704eeddc0SDimitry Andric } 29780b57cec5SDimitry Andric } 29790b57cec5SDimitry Andric } 29800b57cec5SDimitry Andric 29810b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 29820b57cec5SDimitry Andric /// it was duplicated into its chain predecessor and removed. 29830b57cec5SDimitry Andric /// \p BB - Basic block that may be duplicated. 29840b57cec5SDimitry Andric /// 29850b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB. 29860b57cec5SDimitry Andric /// Updated to be the chain end if LPred is removed. 29870b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 29880b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 29890b57cec5SDimitry Andric /// Used to identify which blocks to update predecessor 29900b57cec5SDimitry Andric /// counts. 29910b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 29920b57cec5SDimitry Andric /// chosen in the given order due to unnatural CFG 29930b57cec5SDimitry Andric /// only needed if \p BB is removed and 29940b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 29950b57cec5SDimitry Andric /// @return true if \p BB was removed. 29960b57cec5SDimitry Andric bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 29970b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 29980b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 29990b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 30000b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt) { 30010b57cec5SDimitry Andric bool Removed, DuplicatedToLPred; 30020b57cec5SDimitry Andric bool DuplicatedToOriginalLPred; 30030b57cec5SDimitry Andric Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, 30040b57cec5SDimitry Andric PrevUnplacedBlockIt, 30050b57cec5SDimitry Andric DuplicatedToLPred); 30060b57cec5SDimitry Andric if (!Removed) 30070b57cec5SDimitry Andric return false; 30080b57cec5SDimitry Andric DuplicatedToOriginalLPred = DuplicatedToLPred; 30090b57cec5SDimitry Andric // Iteratively try to duplicate again. It can happen that a block that is 30100b57cec5SDimitry Andric // duplicated into is still small enough to be duplicated again. 30110b57cec5SDimitry Andric // No need to call markBlockSuccessors in this case, as the blocks being 30120b57cec5SDimitry Andric // duplicated from here on are already scheduled. 30135ffd83dbSDimitry Andric while (DuplicatedToLPred && Removed) { 30140b57cec5SDimitry Andric MachineBasicBlock *DupBB, *DupPred; 30150b57cec5SDimitry Andric // The removal callback causes Chain.end() to be updated when a block is 30160b57cec5SDimitry Andric // removed. On the first pass through the loop, the chain end should be the 30170b57cec5SDimitry Andric // same as it was on function entry. On subsequent passes, because we are 30180b57cec5SDimitry Andric // duplicating the block at the end of the chain, if it is removed the 30190b57cec5SDimitry Andric // chain will have shrunk by one block. 30200b57cec5SDimitry Andric BlockChain::iterator ChainEnd = Chain.end(); 30210b57cec5SDimitry Andric DupBB = *(--ChainEnd); 30220b57cec5SDimitry Andric // Now try to duplicate again. 30230b57cec5SDimitry Andric if (ChainEnd == Chain.begin()) 30240b57cec5SDimitry Andric break; 30250b57cec5SDimitry Andric DupPred = *std::prev(ChainEnd); 30260b57cec5SDimitry Andric Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, 30270b57cec5SDimitry Andric PrevUnplacedBlockIt, 30280b57cec5SDimitry Andric DuplicatedToLPred); 30290b57cec5SDimitry Andric } 30300b57cec5SDimitry Andric // If BB was duplicated into LPred, it is now scheduled. But because it was 30310b57cec5SDimitry Andric // removed, markChainSuccessors won't be called for its chain. Instead we 30320b57cec5SDimitry Andric // call markBlockSuccessors for LPred to achieve the same effect. This must go 30330b57cec5SDimitry Andric // at the end because repeating the tail duplication can increase the number 30340b57cec5SDimitry Andric // of unscheduled predecessors. 30350b57cec5SDimitry Andric LPred = *std::prev(Chain.end()); 30360b57cec5SDimitry Andric if (DuplicatedToOriginalLPred) 30370b57cec5SDimitry Andric markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 30380b57cec5SDimitry Andric return true; 30390b57cec5SDimitry Andric } 30400b57cec5SDimitry Andric 30410b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable. 30420b57cec5SDimitry Andric /// \p BB - Basic block that may be duplicated 30430b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB 30440b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 30450b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 30460b57cec5SDimitry Andric /// Used to identify which blocks to update predecessor 30470b57cec5SDimitry Andric /// counts. 30480b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 30490b57cec5SDimitry Andric /// chosen in the given order due to unnatural CFG 30500b57cec5SDimitry Andric /// only needed if \p BB is removed and 30510b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 30525ffd83dbSDimitry Andric /// \p DuplicatedToLPred - True if the block was duplicated into LPred. 30530b57cec5SDimitry Andric /// \return - True if the block was duplicated into all preds and removed. 30540b57cec5SDimitry Andric bool MachineBlockPlacement::maybeTailDuplicateBlock( 30550b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, 30560b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 30570b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 30580b57cec5SDimitry Andric bool &DuplicatedToLPred) { 30590b57cec5SDimitry Andric DuplicatedToLPred = false; 30600b57cec5SDimitry Andric if (!shouldTailDuplicate(BB)) 30610b57cec5SDimitry Andric return false; 30620b57cec5SDimitry Andric 30630b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber() 30640b57cec5SDimitry Andric << "\n"); 30650b57cec5SDimitry Andric 30660b57cec5SDimitry Andric // This has to be a callback because none of it can be done after 30670b57cec5SDimitry Andric // BB is deleted. 30680b57cec5SDimitry Andric bool Removed = false; 30690b57cec5SDimitry Andric auto RemovalCallback = 30700b57cec5SDimitry Andric [&](MachineBasicBlock *RemBB) { 30710b57cec5SDimitry Andric // Signal to outer function 30720b57cec5SDimitry Andric Removed = true; 30730b57cec5SDimitry Andric 30740b57cec5SDimitry Andric // Conservative default. 30750b57cec5SDimitry Andric bool InWorkList = true; 30760b57cec5SDimitry Andric // Remove from the Chain and Chain Map 30770b57cec5SDimitry Andric if (BlockToChain.count(RemBB)) { 30780b57cec5SDimitry Andric BlockChain *Chain = BlockToChain[RemBB]; 30790b57cec5SDimitry Andric InWorkList = Chain->UnscheduledPredecessors == 0; 30800b57cec5SDimitry Andric Chain->remove(RemBB); 30810b57cec5SDimitry Andric BlockToChain.erase(RemBB); 30820b57cec5SDimitry Andric } 30830b57cec5SDimitry Andric 30840b57cec5SDimitry Andric // Handle the unplaced block iterator 30850b57cec5SDimitry Andric if (&(*PrevUnplacedBlockIt) == RemBB) { 30860b57cec5SDimitry Andric PrevUnplacedBlockIt++; 30870b57cec5SDimitry Andric } 30880b57cec5SDimitry Andric 30890b57cec5SDimitry Andric // Handle the Work Lists 30900b57cec5SDimitry Andric if (InWorkList) { 30910b57cec5SDimitry Andric SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 30920b57cec5SDimitry Andric if (RemBB->isEHPad()) 30930b57cec5SDimitry Andric RemoveList = EHPadWorkList; 3094e8d8bef9SDimitry Andric llvm::erase_value(RemoveList, RemBB); 30950b57cec5SDimitry Andric } 30960b57cec5SDimitry Andric 30970b57cec5SDimitry Andric // Handle the filter set 30980b57cec5SDimitry Andric if (BlockFilter) { 30990b57cec5SDimitry Andric BlockFilter->remove(RemBB); 31000b57cec5SDimitry Andric } 31010b57cec5SDimitry Andric 31020b57cec5SDimitry Andric // Remove the block from loop info. 31030b57cec5SDimitry Andric MLI->removeBlock(RemBB); 31040b57cec5SDimitry Andric if (RemBB == PreferredLoopExit) 31050b57cec5SDimitry Andric PreferredLoopExit = nullptr; 31060b57cec5SDimitry Andric 31070b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: " 31080b57cec5SDimitry Andric << getBlockName(RemBB) << "\n"); 31090b57cec5SDimitry Andric }; 31100b57cec5SDimitry Andric auto RemovalCallbackRef = 31110b57cec5SDimitry Andric function_ref<void(MachineBasicBlock*)>(RemovalCallback); 31120b57cec5SDimitry Andric 31130b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 31140b57cec5SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 31155ffd83dbSDimitry Andric SmallVector<MachineBasicBlock *, 8> CandidatePreds; 31165ffd83dbSDimitry Andric SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr; 31175ffd83dbSDimitry Andric if (F->getFunction().hasProfileData()) { 31185ffd83dbSDimitry Andric // We can do partial duplication with precise profile information. 31195ffd83dbSDimitry Andric findDuplicateCandidates(CandidatePreds, BB, BlockFilter); 31205ffd83dbSDimitry Andric if (CandidatePreds.size() == 0) 31215ffd83dbSDimitry Andric return false; 31225ffd83dbSDimitry Andric if (CandidatePreds.size() < BB->pred_size()) 31235ffd83dbSDimitry Andric CandidatePtr = &CandidatePreds; 31245ffd83dbSDimitry Andric } 31255ffd83dbSDimitry Andric TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds, 31265ffd83dbSDimitry Andric &RemovalCallbackRef, CandidatePtr); 31270b57cec5SDimitry Andric 31280b57cec5SDimitry Andric // Update UnscheduledPredecessors to reflect tail-duplication. 31290b57cec5SDimitry Andric DuplicatedToLPred = false; 31300b57cec5SDimitry Andric for (MachineBasicBlock *Pred : DuplicatedPreds) { 31310b57cec5SDimitry Andric // We're only looking for unscheduled predecessors that match the filter. 31320b57cec5SDimitry Andric BlockChain* PredChain = BlockToChain[Pred]; 31330b57cec5SDimitry Andric if (Pred == LPred) 31340b57cec5SDimitry Andric DuplicatedToLPred = true; 31350b57cec5SDimitry Andric if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 31360b57cec5SDimitry Andric || PredChain == &Chain) 31370b57cec5SDimitry Andric continue; 31380b57cec5SDimitry Andric for (MachineBasicBlock *NewSucc : Pred->successors()) { 31390b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(NewSucc)) 31400b57cec5SDimitry Andric continue; 31410b57cec5SDimitry Andric BlockChain *NewChain = BlockToChain[NewSucc]; 31420b57cec5SDimitry Andric if (NewChain != &Chain && NewChain != PredChain) 31430b57cec5SDimitry Andric NewChain->UnscheduledPredecessors++; 31440b57cec5SDimitry Andric } 31450b57cec5SDimitry Andric } 31460b57cec5SDimitry Andric return Removed; 31470b57cec5SDimitry Andric } 31480b57cec5SDimitry Andric 31495ffd83dbSDimitry Andric // Count the number of actual machine instructions. 31505ffd83dbSDimitry Andric static uint64_t countMBBInstruction(MachineBasicBlock *MBB) { 31515ffd83dbSDimitry Andric uint64_t InstrCount = 0; 31525ffd83dbSDimitry Andric for (MachineInstr &MI : *MBB) { 31535ffd83dbSDimitry Andric if (!MI.isPHI() && !MI.isMetaInstruction()) 31545ffd83dbSDimitry Andric InstrCount += 1; 31555ffd83dbSDimitry Andric } 31565ffd83dbSDimitry Andric return InstrCount; 31575ffd83dbSDimitry Andric } 31585ffd83dbSDimitry Andric 31595ffd83dbSDimitry Andric // The size cost of duplication is the instruction size of the duplicated block. 31605ffd83dbSDimitry Andric // So we should scale the threshold accordingly. But the instruction size is not 31615ffd83dbSDimitry Andric // available on all targets, so we use the number of instructions instead. 31625ffd83dbSDimitry Andric BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) { 31635ffd83dbSDimitry Andric return DupThreshold.getFrequency() * countMBBInstruction(BB); 31645ffd83dbSDimitry Andric } 31655ffd83dbSDimitry Andric 31665ffd83dbSDimitry Andric // Returns true if BB is Pred's best successor. 31675ffd83dbSDimitry Andric bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB, 31685ffd83dbSDimitry Andric MachineBasicBlock *Pred, 31695ffd83dbSDimitry Andric BlockFilterSet *BlockFilter) { 31705ffd83dbSDimitry Andric if (BB == Pred) 31715ffd83dbSDimitry Andric return false; 31725ffd83dbSDimitry Andric if (BlockFilter && !BlockFilter->count(Pred)) 31735ffd83dbSDimitry Andric return false; 31745ffd83dbSDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 31755ffd83dbSDimitry Andric if (PredChain && (Pred != *std::prev(PredChain->end()))) 31765ffd83dbSDimitry Andric return false; 31775ffd83dbSDimitry Andric 31785ffd83dbSDimitry Andric // Find the successor with largest probability excluding BB. 31795ffd83dbSDimitry Andric BranchProbability BestProb = BranchProbability::getZero(); 31805ffd83dbSDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) 31815ffd83dbSDimitry Andric if (Succ != BB) { 31825ffd83dbSDimitry Andric if (BlockFilter && !BlockFilter->count(Succ)) 31835ffd83dbSDimitry Andric continue; 31845ffd83dbSDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 31855ffd83dbSDimitry Andric if (SuccChain && (Succ != *SuccChain->begin())) 31865ffd83dbSDimitry Andric continue; 31875ffd83dbSDimitry Andric BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ); 31885ffd83dbSDimitry Andric if (SuccProb > BestProb) 31895ffd83dbSDimitry Andric BestProb = SuccProb; 31905ffd83dbSDimitry Andric } 31915ffd83dbSDimitry Andric 31925ffd83dbSDimitry Andric BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB); 31935ffd83dbSDimitry Andric if (BBProb <= BestProb) 31945ffd83dbSDimitry Andric return false; 31955ffd83dbSDimitry Andric 31965ffd83dbSDimitry Andric // Compute the number of reduced taken branches if Pred falls through to BB 31975ffd83dbSDimitry Andric // instead of another successor. Then compare it with threshold. 3198e8d8bef9SDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 31995ffd83dbSDimitry Andric BlockFrequency Gain = PredFreq * (BBProb - BestProb); 32005ffd83dbSDimitry Andric return Gain > scaleThreshold(BB); 32015ffd83dbSDimitry Andric } 32025ffd83dbSDimitry Andric 32035ffd83dbSDimitry Andric // Find out the predecessors of BB and BB can be beneficially duplicated into 32045ffd83dbSDimitry Andric // them. 32055ffd83dbSDimitry Andric void MachineBlockPlacement::findDuplicateCandidates( 32065ffd83dbSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &Candidates, 32075ffd83dbSDimitry Andric MachineBasicBlock *BB, 32085ffd83dbSDimitry Andric BlockFilterSet *BlockFilter) { 32095ffd83dbSDimitry Andric MachineBasicBlock *Fallthrough = nullptr; 32105ffd83dbSDimitry Andric BranchProbability DefaultBranchProb = BranchProbability::getZero(); 32115ffd83dbSDimitry Andric BlockFrequency BBDupThreshold(scaleThreshold(BB)); 3212e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors()); 3213e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> Succs(BB->successors()); 32145ffd83dbSDimitry Andric 32155ffd83dbSDimitry Andric // Sort for highest frequency. 32165ffd83dbSDimitry Andric auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 32175ffd83dbSDimitry Andric return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B); 32185ffd83dbSDimitry Andric }; 32195ffd83dbSDimitry Andric auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 32205ffd83dbSDimitry Andric return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B); 32215ffd83dbSDimitry Andric }; 32225ffd83dbSDimitry Andric llvm::stable_sort(Succs, CmpSucc); 32235ffd83dbSDimitry Andric llvm::stable_sort(Preds, CmpPred); 32245ffd83dbSDimitry Andric 32255ffd83dbSDimitry Andric auto SuccIt = Succs.begin(); 32265ffd83dbSDimitry Andric if (SuccIt != Succs.end()) { 32275ffd83dbSDimitry Andric DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl(); 32285ffd83dbSDimitry Andric } 32295ffd83dbSDimitry Andric 32305ffd83dbSDimitry Andric // For each predecessors of BB, compute the benefit of duplicating BB, 32315ffd83dbSDimitry Andric // if it is larger than the threshold, add it into Candidates. 32325ffd83dbSDimitry Andric // 32335ffd83dbSDimitry Andric // If we have following control flow. 32345ffd83dbSDimitry Andric // 32355ffd83dbSDimitry Andric // PB1 PB2 PB3 PB4 32365ffd83dbSDimitry Andric // \ | / /\ 32375ffd83dbSDimitry Andric // \ | / / \ 32385ffd83dbSDimitry Andric // \ |/ / \ 32395ffd83dbSDimitry Andric // BB----/ OB 32405ffd83dbSDimitry Andric // /\ 32415ffd83dbSDimitry Andric // / \ 32425ffd83dbSDimitry Andric // SB1 SB2 32435ffd83dbSDimitry Andric // 32445ffd83dbSDimitry Andric // And it can be partially duplicated as 32455ffd83dbSDimitry Andric // 32465ffd83dbSDimitry Andric // PB2+BB 32475ffd83dbSDimitry Andric // | PB1 PB3 PB4 32485ffd83dbSDimitry Andric // | | / /\ 32495ffd83dbSDimitry Andric // | | / / \ 32505ffd83dbSDimitry Andric // | |/ / \ 32515ffd83dbSDimitry Andric // | BB----/ OB 32525ffd83dbSDimitry Andric // |\ /| 32535ffd83dbSDimitry Andric // | X | 32545ffd83dbSDimitry Andric // |/ \| 32555ffd83dbSDimitry Andric // SB2 SB1 32565ffd83dbSDimitry Andric // 32575ffd83dbSDimitry Andric // The benefit of duplicating into a predecessor is defined as 32585ffd83dbSDimitry Andric // Orig_taken_branch - Duplicated_taken_branch 32595ffd83dbSDimitry Andric // 32605ffd83dbSDimitry Andric // The Orig_taken_branch is computed with the assumption that predecessor 32615ffd83dbSDimitry Andric // jumps to BB and the most possible successor is laid out after BB. 32625ffd83dbSDimitry Andric // 32635ffd83dbSDimitry Andric // The Duplicated_taken_branch is computed with the assumption that BB is 32645ffd83dbSDimitry Andric // duplicated into PB, and one successor is layout after it (SB1 for PB1 and 32655ffd83dbSDimitry Andric // SB2 for PB2 in our case). If there is no available successor, the combined 32665ffd83dbSDimitry Andric // block jumps to all BB's successor, like PB3 in this example. 32675ffd83dbSDimitry Andric // 32685ffd83dbSDimitry Andric // If a predecessor has multiple successors, so BB can't be duplicated into 32695ffd83dbSDimitry Andric // it. But it can beneficially fall through to BB, and duplicate BB into other 32705ffd83dbSDimitry Andric // predecessors. 32715ffd83dbSDimitry Andric for (MachineBasicBlock *Pred : Preds) { 3272e8d8bef9SDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 32735ffd83dbSDimitry Andric 32745ffd83dbSDimitry Andric if (!TailDup.canTailDuplicate(BB, Pred)) { 32755ffd83dbSDimitry Andric // BB can't be duplicated into Pred, but it is possible to be layout 32765ffd83dbSDimitry Andric // below Pred. 32775ffd83dbSDimitry Andric if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) { 32785ffd83dbSDimitry Andric Fallthrough = Pred; 32795ffd83dbSDimitry Andric if (SuccIt != Succs.end()) 32805ffd83dbSDimitry Andric SuccIt++; 32815ffd83dbSDimitry Andric } 32825ffd83dbSDimitry Andric continue; 32835ffd83dbSDimitry Andric } 32845ffd83dbSDimitry Andric 32855ffd83dbSDimitry Andric BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb; 32865ffd83dbSDimitry Andric BlockFrequency DupCost; 32875ffd83dbSDimitry Andric if (SuccIt == Succs.end()) { 32885ffd83dbSDimitry Andric // Jump to all successors; 32895ffd83dbSDimitry Andric if (Succs.size() > 0) 32905ffd83dbSDimitry Andric DupCost += PredFreq; 32915ffd83dbSDimitry Andric } else { 32925ffd83dbSDimitry Andric // Fallthrough to *SuccIt, jump to all other successors; 32935ffd83dbSDimitry Andric DupCost += PredFreq; 32945ffd83dbSDimitry Andric DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt); 32955ffd83dbSDimitry Andric } 32965ffd83dbSDimitry Andric 32975ffd83dbSDimitry Andric assert(OrigCost >= DupCost); 32985ffd83dbSDimitry Andric OrigCost -= DupCost; 32995ffd83dbSDimitry Andric if (OrigCost > BBDupThreshold) { 33005ffd83dbSDimitry Andric Candidates.push_back(Pred); 33015ffd83dbSDimitry Andric if (SuccIt != Succs.end()) 33025ffd83dbSDimitry Andric SuccIt++; 33035ffd83dbSDimitry Andric } 33045ffd83dbSDimitry Andric } 33055ffd83dbSDimitry Andric 33065ffd83dbSDimitry Andric // No predecessors can optimally fallthrough to BB. 33075ffd83dbSDimitry Andric // So we can change one duplication into fallthrough. 33085ffd83dbSDimitry Andric if (!Fallthrough) { 33095ffd83dbSDimitry Andric if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) { 33105ffd83dbSDimitry Andric Candidates[0] = Candidates.back(); 33115ffd83dbSDimitry Andric Candidates.pop_back(); 33125ffd83dbSDimitry Andric } 33135ffd83dbSDimitry Andric } 33145ffd83dbSDimitry Andric } 33155ffd83dbSDimitry Andric 33165ffd83dbSDimitry Andric void MachineBlockPlacement::initDupThreshold() { 33175ffd83dbSDimitry Andric DupThreshold = 0; 33185ffd83dbSDimitry Andric if (!F->getFunction().hasProfileData()) 33195ffd83dbSDimitry Andric return; 33205ffd83dbSDimitry Andric 3321e8d8bef9SDimitry Andric // We prefer to use prifile count. 3322e8d8bef9SDimitry Andric uint64_t HotThreshold = PSI->getOrCompHotCountThreshold(); 3323e8d8bef9SDimitry Andric if (HotThreshold != UINT64_MAX) { 3324e8d8bef9SDimitry Andric UseProfileCount = true; 3325e8d8bef9SDimitry Andric DupThreshold = HotThreshold * TailDupProfilePercentThreshold / 100; 3326e8d8bef9SDimitry Andric return; 3327e8d8bef9SDimitry Andric } 3328e8d8bef9SDimitry Andric 3329e8d8bef9SDimitry Andric // Profile count is not available, we can use block frequency instead. 33305ffd83dbSDimitry Andric BlockFrequency MaxFreq = 0; 33315ffd83dbSDimitry Andric for (MachineBasicBlock &MBB : *F) { 33325ffd83dbSDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(&MBB); 33335ffd83dbSDimitry Andric if (Freq > MaxFreq) 33345ffd83dbSDimitry Andric MaxFreq = Freq; 33355ffd83dbSDimitry Andric } 33365ffd83dbSDimitry Andric 33375ffd83dbSDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 33385ffd83dbSDimitry Andric DupThreshold = MaxFreq * ThresholdProb; 3339e8d8bef9SDimitry Andric UseProfileCount = false; 33405ffd83dbSDimitry Andric } 33415ffd83dbSDimitry Andric 33420b57cec5SDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 33430b57cec5SDimitry Andric if (skipFunction(MF.getFunction())) 33440b57cec5SDimitry Andric return false; 33450b57cec5SDimitry Andric 33460b57cec5SDimitry Andric // Check for single-block functions and skip them. 33470b57cec5SDimitry Andric if (std::next(MF.begin()) == MF.end()) 33480b57cec5SDimitry Andric return false; 33490b57cec5SDimitry Andric 33500b57cec5SDimitry Andric F = &MF; 33510b57cec5SDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 33525ffd83dbSDimitry Andric MBFI = std::make_unique<MBFIWrapper>( 33530b57cec5SDimitry Andric getAnalysis<MachineBlockFrequencyInfo>()); 33540b57cec5SDimitry Andric MLI = &getAnalysis<MachineLoopInfo>(); 33550b57cec5SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 33560b57cec5SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 33570b57cec5SDimitry Andric MPDT = nullptr; 3358480093f4SDimitry Andric PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 33590b57cec5SDimitry Andric 33605ffd83dbSDimitry Andric initDupThreshold(); 33615ffd83dbSDimitry Andric 33620b57cec5SDimitry Andric // Initialize PreferredLoopExit to nullptr here since it may never be set if 33630b57cec5SDimitry Andric // there are no MachineLoops. 33640b57cec5SDimitry Andric PreferredLoopExit = nullptr; 33650b57cec5SDimitry Andric 33660b57cec5SDimitry Andric assert(BlockToChain.empty() && 33670b57cec5SDimitry Andric "BlockToChain map should be empty before starting placement."); 33680b57cec5SDimitry Andric assert(ComputedEdges.empty() && 33690b57cec5SDimitry Andric "Computed Edge map should be empty before starting placement."); 33700b57cec5SDimitry Andric 33710b57cec5SDimitry Andric unsigned TailDupSize = TailDupPlacementThreshold; 33720b57cec5SDimitry Andric // If only the aggressive threshold is explicitly set, use it. 33730b57cec5SDimitry Andric if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 && 33740b57cec5SDimitry Andric TailDupPlacementThreshold.getNumOccurrences() == 0) 33750b57cec5SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 33760b57cec5SDimitry Andric 33770b57cec5SDimitry Andric TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 33780b57cec5SDimitry Andric // For aggressive optimization, we can adjust some thresholds to be less 33790b57cec5SDimitry Andric // conservative. 33800b57cec5SDimitry Andric if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) { 33810b57cec5SDimitry Andric // At O3 we should be more willing to copy blocks for tail duplication. This 33820b57cec5SDimitry Andric // increases size pressure, so we only do it at O3 33830b57cec5SDimitry Andric // Do this unless only the regular threshold is explicitly set. 33840b57cec5SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 || 33850b57cec5SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0) 33860b57cec5SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 33870b57cec5SDimitry Andric } 33880b57cec5SDimitry Andric 3389fe6060f1SDimitry Andric // If there's no threshold provided through options, query the target 3390fe6060f1SDimitry Andric // information for a threshold instead. 3391fe6060f1SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 && 3392fe6060f1SDimitry Andric (PassConfig->getOptLevel() < CodeGenOpt::Aggressive || 3393fe6060f1SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0)) 3394fe6060f1SDimitry Andric TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel()); 3395fe6060f1SDimitry Andric 33960b57cec5SDimitry Andric if (allowTailDupPlacement()) { 33970b57cec5SDimitry Andric MPDT = &getAnalysis<MachinePostDominatorTree>(); 3398480093f4SDimitry Andric bool OptForSize = MF.getFunction().hasOptSize() || 3399480093f4SDimitry Andric llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI()); 3400480093f4SDimitry Andric if (OptForSize) 34010b57cec5SDimitry Andric TailDupSize = 1; 34020b57cec5SDimitry Andric bool PreRegAlloc = false; 34035ffd83dbSDimitry Andric TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI, 3404480093f4SDimitry Andric /* LayoutMode */ true, TailDupSize); 34050b57cec5SDimitry Andric precomputeTriangleChains(); 34060b57cec5SDimitry Andric } 34070b57cec5SDimitry Andric 34080b57cec5SDimitry Andric buildCFGChains(); 34090b57cec5SDimitry Andric 34100b57cec5SDimitry Andric // Changing the layout can create new tail merging opportunities. 34110b57cec5SDimitry Andric // TailMerge can create jump into if branches that make CFG irreducible for 34120b57cec5SDimitry Andric // HW that requires structured CFG. 34130b57cec5SDimitry Andric bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 34140b57cec5SDimitry Andric PassConfig->getEnableTailMerge() && 34150b57cec5SDimitry Andric BranchFoldPlacement; 34160b57cec5SDimitry Andric // No tail merging opportunities if the block number is less than four. 34170b57cec5SDimitry Andric if (MF.size() > 3 && EnableTailMerge) { 34180b57cec5SDimitry Andric unsigned TailMergeSize = TailDupSize + 1; 3419e8d8bef9SDimitry Andric BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false, 3420e8d8bef9SDimitry Andric *MBFI, *MBPI, PSI, TailMergeSize); 34210b57cec5SDimitry Andric 34225ffd83dbSDimitry Andric if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI, 34230b57cec5SDimitry Andric /*AfterPlacement=*/true)) { 34240b57cec5SDimitry Andric // Redo the layout if tail merging creates/removes/moves blocks. 34250b57cec5SDimitry Andric BlockToChain.clear(); 34260b57cec5SDimitry Andric ComputedEdges.clear(); 34270b57cec5SDimitry Andric // Must redo the post-dominator tree if blocks were changed. 34280b57cec5SDimitry Andric if (MPDT) 34290b57cec5SDimitry Andric MPDT->runOnMachineFunction(MF); 34300b57cec5SDimitry Andric ChainAllocator.DestroyAll(); 34310b57cec5SDimitry Andric buildCFGChains(); 34320b57cec5SDimitry Andric } 34330b57cec5SDimitry Andric } 34340b57cec5SDimitry Andric 34350eae32dcSDimitry Andric // Apply a post-processing optimizing block placement. 343681ad6265SDimitry Andric if (MF.size() >= 3 && EnableExtTspBlockPlacement && 343781ad6265SDimitry Andric (ApplyExtTspWithoutProfile || MF.getFunction().hasProfileData())) { 34380eae32dcSDimitry Andric // Find a new placement and modify the layout of the blocks in the function. 34390eae32dcSDimitry Andric applyExtTsp(); 34400eae32dcSDimitry Andric 34410eae32dcSDimitry Andric // Re-create CFG chain so that we can optimizeBranches and alignBlocks. 34420eae32dcSDimitry Andric createCFGChainExtTsp(); 34430eae32dcSDimitry Andric } 34440eae32dcSDimitry Andric 34450b57cec5SDimitry Andric optimizeBranches(); 34460b57cec5SDimitry Andric alignBlocks(); 34470b57cec5SDimitry Andric 34480b57cec5SDimitry Andric BlockToChain.clear(); 34490b57cec5SDimitry Andric ComputedEdges.clear(); 34500b57cec5SDimitry Andric ChainAllocator.DestroyAll(); 34510b57cec5SDimitry Andric 345204eeddc0SDimitry Andric bool HasMaxBytesOverride = 345304eeddc0SDimitry Andric MaxBytesForAlignmentOverride.getNumOccurrences() > 0; 345404eeddc0SDimitry Andric 34550b57cec5SDimitry Andric if (AlignAllBlock) 34560b57cec5SDimitry Andric // Align all of the blocks in the function to a specific alignment. 345704eeddc0SDimitry Andric for (MachineBasicBlock &MBB : MF) { 345804eeddc0SDimitry Andric if (HasMaxBytesOverride) 345904eeddc0SDimitry Andric MBB.setAlignment(Align(1ULL << AlignAllBlock), 346004eeddc0SDimitry Andric MaxBytesForAlignmentOverride); 346104eeddc0SDimitry Andric else 34628bcb0991SDimitry Andric MBB.setAlignment(Align(1ULL << AlignAllBlock)); 346304eeddc0SDimitry Andric } 34640b57cec5SDimitry Andric else if (AlignAllNonFallThruBlocks) { 34650b57cec5SDimitry Andric // Align all of the blocks that have no fall-through predecessors to a 34660b57cec5SDimitry Andric // specific alignment. 34670b57cec5SDimitry Andric for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 34680b57cec5SDimitry Andric auto LayoutPred = std::prev(MBI); 346904eeddc0SDimitry Andric if (!LayoutPred->isSuccessor(&*MBI)) { 347004eeddc0SDimitry Andric if (HasMaxBytesOverride) 347104eeddc0SDimitry Andric MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks), 347204eeddc0SDimitry Andric MaxBytesForAlignmentOverride); 347304eeddc0SDimitry Andric else 34748bcb0991SDimitry Andric MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks)); 34750b57cec5SDimitry Andric } 34760b57cec5SDimitry Andric } 347704eeddc0SDimitry Andric } 34780b57cec5SDimitry Andric if (ViewBlockLayoutWithBFI != GVDT_None && 34790b57cec5SDimitry Andric (ViewBlockFreqFuncName.empty() || 34800b57cec5SDimitry Andric F->getFunction().getName().equals(ViewBlockFreqFuncName))) { 3481*bdd1243dSDimitry Andric if (RenumberBlocksBeforeView) 3482*bdd1243dSDimitry Andric MF.RenumberBlocks(); 34830b57cec5SDimitry Andric MBFI->view("MBP." + MF.getName(), false); 34840b57cec5SDimitry Andric } 34850b57cec5SDimitry Andric 34860b57cec5SDimitry Andric // We always return true as we have no way to track whether the final order 34870b57cec5SDimitry Andric // differs from the original order. 34880b57cec5SDimitry Andric return true; 34890b57cec5SDimitry Andric } 34900b57cec5SDimitry Andric 34910eae32dcSDimitry Andric void MachineBlockPlacement::applyExtTsp() { 34920eae32dcSDimitry Andric // Prepare data; blocks are indexed by their index in the current ordering. 34930eae32dcSDimitry Andric DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex; 34940eae32dcSDimitry Andric BlockIndex.reserve(F->size()); 34950eae32dcSDimitry Andric std::vector<const MachineBasicBlock *> CurrentBlockOrder; 34960eae32dcSDimitry Andric CurrentBlockOrder.reserve(F->size()); 34970eae32dcSDimitry Andric size_t NumBlocks = 0; 34980eae32dcSDimitry Andric for (const MachineBasicBlock &MBB : *F) { 34990eae32dcSDimitry Andric BlockIndex[&MBB] = NumBlocks++; 35000eae32dcSDimitry Andric CurrentBlockOrder.push_back(&MBB); 35010eae32dcSDimitry Andric } 35020eae32dcSDimitry Andric 35030eae32dcSDimitry Andric auto BlockSizes = std::vector<uint64_t>(F->size()); 35040eae32dcSDimitry Andric auto BlockCounts = std::vector<uint64_t>(F->size()); 3505*bdd1243dSDimitry Andric std::vector<EdgeCountT> JumpCounts; 35060eae32dcSDimitry Andric for (MachineBasicBlock &MBB : *F) { 35070eae32dcSDimitry Andric // Getting the block frequency. 35080eae32dcSDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 35090eae32dcSDimitry Andric BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency(); 35100eae32dcSDimitry Andric // Getting the block size: 35110eae32dcSDimitry Andric // - approximate the size of an instruction by 4 bytes, and 35120eae32dcSDimitry Andric // - ignore debug instructions. 35130eae32dcSDimitry Andric // Note: getting the exact size of each block is target-dependent and can be 35140eae32dcSDimitry Andric // done by extending the interface of MCCodeEmitter. Experimentally we do 35150eae32dcSDimitry Andric // not see a perf improvement with the exact block sizes. 35160eae32dcSDimitry Andric auto NonDbgInsts = 35170eae32dcSDimitry Andric instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end()); 35180eae32dcSDimitry Andric int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end()); 35190eae32dcSDimitry Andric BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts; 35200eae32dcSDimitry Andric // Getting jump frequencies. 35210eae32dcSDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) { 35220eae32dcSDimitry Andric auto EP = MBPI->getEdgeProbability(&MBB, Succ); 3523*bdd1243dSDimitry Andric BlockFrequency JumpFreq = BlockFreq * EP; 3524*bdd1243dSDimitry Andric auto Jump = std::make_pair(BlockIndex[&MBB], BlockIndex[Succ]); 3525*bdd1243dSDimitry Andric JumpCounts.push_back(std::make_pair(Jump, JumpFreq.getFrequency())); 35260eae32dcSDimitry Andric } 35270eae32dcSDimitry Andric } 35280eae32dcSDimitry Andric 35290eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size() 35300eae32dcSDimitry Andric << " with profile = " << F->getFunction().hasProfileData() 35310eae32dcSDimitry Andric << " (" << F->getName().str() << ")" 35320eae32dcSDimitry Andric << "\n"); 35330eae32dcSDimitry Andric LLVM_DEBUG( 35340eae32dcSDimitry Andric dbgs() << format(" original layout score: %0.2f\n", 35350eae32dcSDimitry Andric calcExtTspScore(BlockSizes, BlockCounts, JumpCounts))); 35360eae32dcSDimitry Andric 35370eae32dcSDimitry Andric // Run the layout algorithm. 35380eae32dcSDimitry Andric auto NewOrder = applyExtTspLayout(BlockSizes, BlockCounts, JumpCounts); 35390eae32dcSDimitry Andric std::vector<const MachineBasicBlock *> NewBlockOrder; 35400eae32dcSDimitry Andric NewBlockOrder.reserve(F->size()); 35410eae32dcSDimitry Andric for (uint64_t Node : NewOrder) { 35420eae32dcSDimitry Andric NewBlockOrder.push_back(CurrentBlockOrder[Node]); 35430eae32dcSDimitry Andric } 35440eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n", 35450eae32dcSDimitry Andric calcExtTspScore(NewOrder, BlockSizes, BlockCounts, 35460eae32dcSDimitry Andric JumpCounts))); 35470eae32dcSDimitry Andric 35480eae32dcSDimitry Andric // Assign new block order. 35490eae32dcSDimitry Andric assignBlockOrder(NewBlockOrder); 35500eae32dcSDimitry Andric } 35510eae32dcSDimitry Andric 35520eae32dcSDimitry Andric void MachineBlockPlacement::assignBlockOrder( 35530eae32dcSDimitry Andric const std::vector<const MachineBasicBlock *> &NewBlockOrder) { 35540eae32dcSDimitry Andric assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order"); 35550eae32dcSDimitry Andric F->RenumberBlocks(); 35560eae32dcSDimitry Andric 35570eae32dcSDimitry Andric bool HasChanges = false; 35580eae32dcSDimitry Andric for (size_t I = 0; I < NewBlockOrder.size(); I++) { 35590eae32dcSDimitry Andric if (NewBlockOrder[I] != F->getBlockNumbered(I)) { 35600eae32dcSDimitry Andric HasChanges = true; 35610eae32dcSDimitry Andric break; 35620eae32dcSDimitry Andric } 35630eae32dcSDimitry Andric } 35640eae32dcSDimitry Andric // Stop early if the new block order is identical to the existing one. 35650eae32dcSDimitry Andric if (!HasChanges) 35660eae32dcSDimitry Andric return; 35670eae32dcSDimitry Andric 35680eae32dcSDimitry Andric SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs()); 35690eae32dcSDimitry Andric for (auto &MBB : *F) { 35700eae32dcSDimitry Andric PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 35710eae32dcSDimitry Andric } 35720eae32dcSDimitry Andric 35730eae32dcSDimitry Andric // Sort basic blocks in the function according to the computed order. 35740eae32dcSDimitry Andric DenseMap<const MachineBasicBlock *, size_t> NewIndex; 35750eae32dcSDimitry Andric for (const MachineBasicBlock *MBB : NewBlockOrder) { 35760eae32dcSDimitry Andric NewIndex[MBB] = NewIndex.size(); 35770eae32dcSDimitry Andric } 35780eae32dcSDimitry Andric F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) { 35790eae32dcSDimitry Andric return NewIndex[&L] < NewIndex[&R]; 35800eae32dcSDimitry Andric }); 35810eae32dcSDimitry Andric 35820eae32dcSDimitry Andric // Update basic block branches by inserting explicit fallthrough branches 35830eae32dcSDimitry Andric // when required and re-optimize branches when possible. 35840eae32dcSDimitry Andric const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo(); 35850eae32dcSDimitry Andric SmallVector<MachineOperand, 4> Cond; 35860eae32dcSDimitry Andric for (auto &MBB : *F) { 35870eae32dcSDimitry Andric MachineFunction::iterator NextMBB = std::next(MBB.getIterator()); 35880eae32dcSDimitry Andric MachineFunction::iterator EndIt = MBB.getParent()->end(); 35890eae32dcSDimitry Andric auto *FTMBB = PrevFallThroughs[MBB.getNumber()]; 35900eae32dcSDimitry Andric // If this block had a fallthrough before we need an explicit unconditional 35910eae32dcSDimitry Andric // branch to that block if the fallthrough block is not adjacent to the 35920eae32dcSDimitry Andric // block in the new order. 35930eae32dcSDimitry Andric if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) { 35940eae32dcSDimitry Andric TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 35950eae32dcSDimitry Andric } 35960eae32dcSDimitry Andric 35970eae32dcSDimitry Andric // It might be possible to optimize branches by flipping the condition. 35980eae32dcSDimitry Andric Cond.clear(); 35990eae32dcSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 36000eae32dcSDimitry Andric if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 36010eae32dcSDimitry Andric continue; 36020eae32dcSDimitry Andric MBB.updateTerminator(FTMBB); 36030eae32dcSDimitry Andric } 36040eae32dcSDimitry Andric 36050eae32dcSDimitry Andric #ifndef NDEBUG 36060eae32dcSDimitry Andric // Make sure we correctly constructed all branches. 36070eae32dcSDimitry Andric F->verify(this, "After optimized block reordering"); 36080eae32dcSDimitry Andric #endif 36090eae32dcSDimitry Andric } 36100eae32dcSDimitry Andric 36110eae32dcSDimitry Andric void MachineBlockPlacement::createCFGChainExtTsp() { 36120eae32dcSDimitry Andric BlockToChain.clear(); 36130eae32dcSDimitry Andric ComputedEdges.clear(); 36140eae32dcSDimitry Andric ChainAllocator.DestroyAll(); 36150eae32dcSDimitry Andric 36160eae32dcSDimitry Andric MachineBasicBlock *HeadBB = &F->front(); 36170eae32dcSDimitry Andric BlockChain *FunctionChain = 36180eae32dcSDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB); 36190eae32dcSDimitry Andric 36200eae32dcSDimitry Andric for (MachineBasicBlock &MBB : *F) { 36210eae32dcSDimitry Andric if (HeadBB == &MBB) 36220eae32dcSDimitry Andric continue; // Ignore head of the chain 36230eae32dcSDimitry Andric FunctionChain->merge(&MBB, nullptr); 36240eae32dcSDimitry Andric } 36250eae32dcSDimitry Andric } 36260eae32dcSDimitry Andric 36270b57cec5SDimitry Andric namespace { 36280b57cec5SDimitry Andric 36290b57cec5SDimitry Andric /// A pass to compute block placement statistics. 36300b57cec5SDimitry Andric /// 36310b57cec5SDimitry Andric /// A separate pass to compute interesting statistics for evaluating block 36320b57cec5SDimitry Andric /// placement. This is separate from the actual placement pass so that they can 36330b57cec5SDimitry Andric /// be computed in the absence of any placement transformations or when using 36340b57cec5SDimitry Andric /// alternative placement strategies. 36350b57cec5SDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass { 36360b57cec5SDimitry Andric /// A handle to the branch probability pass. 36370b57cec5SDimitry Andric const MachineBranchProbabilityInfo *MBPI; 36380b57cec5SDimitry Andric 36390b57cec5SDimitry Andric /// A handle to the function-wide block frequency pass. 36400b57cec5SDimitry Andric const MachineBlockFrequencyInfo *MBFI; 36410b57cec5SDimitry Andric 36420b57cec5SDimitry Andric public: 36430b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 36440b57cec5SDimitry Andric 36450b57cec5SDimitry Andric MachineBlockPlacementStats() : MachineFunctionPass(ID) { 36460b57cec5SDimitry Andric initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 36470b57cec5SDimitry Andric } 36480b57cec5SDimitry Andric 36490b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 36500b57cec5SDimitry Andric 36510b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 36520b57cec5SDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>(); 36530b57cec5SDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>(); 36540b57cec5SDimitry Andric AU.setPreservesAll(); 36550b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 36560b57cec5SDimitry Andric } 36570b57cec5SDimitry Andric }; 36580b57cec5SDimitry Andric 36590b57cec5SDimitry Andric } // end anonymous namespace 36600b57cec5SDimitry Andric 36610b57cec5SDimitry Andric char MachineBlockPlacementStats::ID = 0; 36620b57cec5SDimitry Andric 36630b57cec5SDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 36640b57cec5SDimitry Andric 36650b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 36660b57cec5SDimitry Andric "Basic Block Placement Stats", false, false) 36670b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 36680b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 36690b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 36700b57cec5SDimitry Andric "Basic Block Placement Stats", false, false) 36710b57cec5SDimitry Andric 36720b57cec5SDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 36730b57cec5SDimitry Andric // Check for single-block functions and skip them. 36740b57cec5SDimitry Andric if (std::next(F.begin()) == F.end()) 36750b57cec5SDimitry Andric return false; 36760b57cec5SDimitry Andric 367781ad6265SDimitry Andric if (!isFunctionInPrintList(F.getName())) 367881ad6265SDimitry Andric return false; 367981ad6265SDimitry Andric 36800b57cec5SDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 36810b57cec5SDimitry Andric MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 36820b57cec5SDimitry Andric 36830b57cec5SDimitry Andric for (MachineBasicBlock &MBB : F) { 36840b57cec5SDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 36850b57cec5SDimitry Andric Statistic &NumBranches = 36860b57cec5SDimitry Andric (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 36870b57cec5SDimitry Andric Statistic &BranchTakenFreq = 36880b57cec5SDimitry Andric (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 36890b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) { 36900b57cec5SDimitry Andric // Skip if this successor is a fallthrough. 36910b57cec5SDimitry Andric if (MBB.isLayoutSuccessor(Succ)) 36920b57cec5SDimitry Andric continue; 36930b57cec5SDimitry Andric 36940b57cec5SDimitry Andric BlockFrequency EdgeFreq = 36950b57cec5SDimitry Andric BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 36960b57cec5SDimitry Andric ++NumBranches; 36970b57cec5SDimitry Andric BranchTakenFreq += EdgeFreq.getFrequency(); 36980b57cec5SDimitry Andric } 36990b57cec5SDimitry Andric } 37000b57cec5SDimitry Andric 37010b57cec5SDimitry Andric return false; 37020b57cec5SDimitry Andric } 3703