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 204bdd1243dSDimitry Andric // Use case: When block layout is visualized after MBP pass, the basic blocks 205bdd1243dSDimitry Andric // are labeled in layout order; meanwhile blocks could be numbered in a 206bdd1243dSDimitry Andric // different order. It's hard to map between the graph and pass output. 207bdd1243dSDimitry Andric // With this option on, the basic blocks are renumbered in function layout 208bdd1243dSDimitry Andric // order. For debugging only. 209bdd1243dSDimitry Andric static cl::opt<bool> RenumberBlocksBeforeView( 210bdd1243dSDimitry Andric "renumber-blocks-before-view", 211bdd1243dSDimitry Andric cl::desc( 212bdd1243dSDimitry Andric "If true, basic blocks are re-numbered before MBP layout is printed " 213bdd1243dSDimitry Andric "into a dot graph. Only used when a function is being printed."), 214bdd1243dSDimitry Andric cl::init(false), cl::Hidden); 215bdd1243dSDimitry Andric 21606c3fb27SDimitry Andric namespace llvm { 21781ad6265SDimitry Andric extern cl::opt<bool> EnableExtTspBlockPlacement; 21881ad6265SDimitry Andric extern cl::opt<bool> ApplyExtTspWithoutProfile; 2190b57cec5SDimitry Andric extern cl::opt<unsigned> StaticLikelyProb; 2200b57cec5SDimitry Andric extern cl::opt<unsigned> ProfileLikelyProb; 2210b57cec5SDimitry Andric 2220b57cec5SDimitry Andric // Internal option used to control BFI display only after MBP pass. 2230b57cec5SDimitry Andric // Defined in CodeGen/MachineBlockFrequencyInfo.cpp: 2240b57cec5SDimitry Andric // -view-block-layout-with-bfi= 2250b57cec5SDimitry Andric extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI; 2260b57cec5SDimitry Andric 2270b57cec5SDimitry Andric // Command line option to specify the name of the function for CFG dump 2280b57cec5SDimitry Andric // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 2290b57cec5SDimitry Andric extern cl::opt<std::string> ViewBlockFreqFuncName; 230fe6060f1SDimitry Andric } // namespace llvm 2310b57cec5SDimitry Andric 2320b57cec5SDimitry Andric namespace { 2330b57cec5SDimitry Andric 2340b57cec5SDimitry Andric class BlockChain; 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric /// Type for our function-wide basic block -> block chain mapping. 2370b57cec5SDimitry Andric using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>; 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric /// A chain of blocks which will be laid out contiguously. 2400b57cec5SDimitry Andric /// 2410b57cec5SDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that 2420b57cec5SDimitry Andric /// are profitable to layout together in order to maximize fallthrough 2430b57cec5SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent 2440b57cec5SDimitry Andric /// a sequence of basic blocks which have some external (correctness) 2450b57cec5SDimitry Andric /// requirement for sequential layout. 2460b57cec5SDimitry Andric /// 2470b57cec5SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow 2480b57cec5SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated 2490b57cec5SDimitry Andric /// automatically as chains are merged together. 2500b57cec5SDimitry Andric class BlockChain { 2510b57cec5SDimitry Andric /// The sequence of blocks belonging to this chain. 2520b57cec5SDimitry Andric /// 2530b57cec5SDimitry Andric /// This is the sequence of blocks for a particular chain. These will be laid 2540b57cec5SDimitry Andric /// out in-order within the function. 2550b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> Blocks; 2560b57cec5SDimitry Andric 2570b57cec5SDimitry Andric /// A handle to the function-wide basic block to block chain mapping. 2580b57cec5SDimitry Andric /// 2590b57cec5SDimitry Andric /// This is retained in each block chain to simplify the computation of child 2600b57cec5SDimitry Andric /// block chains for SCC-formation and iteration. We store the edges to child 2610b57cec5SDimitry Andric /// basic blocks, and map them back to their associated chains using this 2620b57cec5SDimitry Andric /// structure. 2630b57cec5SDimitry Andric BlockToChainMapType &BlockToChain; 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric public: 2660b57cec5SDimitry Andric /// Construct a new BlockChain. 2670b57cec5SDimitry Andric /// 2680b57cec5SDimitry Andric /// This builds a new block chain representing a single basic block in the 2690b57cec5SDimitry Andric /// function. It also registers itself as the chain that block participates 2700b57cec5SDimitry Andric /// in with the BlockToChain mapping. 2710b57cec5SDimitry Andric BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 2720b57cec5SDimitry Andric : Blocks(1, BB), BlockToChain(BlockToChain) { 2730b57cec5SDimitry Andric assert(BB && "Cannot create a chain with a null basic block"); 2740b57cec5SDimitry Andric BlockToChain[BB] = this; 2750b57cec5SDimitry Andric } 2760b57cec5SDimitry Andric 2770b57cec5SDimitry Andric /// Iterator over blocks within the chain. 2780b57cec5SDimitry Andric using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator; 2790b57cec5SDimitry Andric using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator; 2800b57cec5SDimitry Andric 2810b57cec5SDimitry Andric /// Beginning of blocks within the chain. 2820b57cec5SDimitry Andric iterator begin() { return Blocks.begin(); } 2830b57cec5SDimitry Andric const_iterator begin() const { return Blocks.begin(); } 2840b57cec5SDimitry Andric 2850b57cec5SDimitry Andric /// End of blocks within the chain. 2860b57cec5SDimitry Andric iterator end() { return Blocks.end(); } 2870b57cec5SDimitry Andric const_iterator end() const { return Blocks.end(); } 2880b57cec5SDimitry Andric 2890b57cec5SDimitry Andric bool remove(MachineBasicBlock* BB) { 2900b57cec5SDimitry Andric for(iterator i = begin(); i != end(); ++i) { 2910b57cec5SDimitry Andric if (*i == BB) { 2920b57cec5SDimitry Andric Blocks.erase(i); 2930b57cec5SDimitry Andric return true; 2940b57cec5SDimitry Andric } 2950b57cec5SDimitry Andric } 2960b57cec5SDimitry Andric return false; 2970b57cec5SDimitry Andric } 2980b57cec5SDimitry Andric 2990b57cec5SDimitry Andric /// Merge a block chain into this one. 3000b57cec5SDimitry Andric /// 3010b57cec5SDimitry Andric /// This routine merges a block chain into this one. It takes care of forming 3020b57cec5SDimitry Andric /// a contiguous sequence of basic blocks, updating the edge list, and 3030b57cec5SDimitry Andric /// updating the block -> chain mapping. It does not free or tear down the 3040b57cec5SDimitry Andric /// old chain, but the old chain's block list is no longer valid. 3050b57cec5SDimitry Andric void merge(MachineBasicBlock *BB, BlockChain *Chain) { 3060b57cec5SDimitry Andric assert(BB && "Can't merge a null block."); 3070b57cec5SDimitry Andric assert(!Blocks.empty() && "Can't merge into an empty chain."); 3080b57cec5SDimitry Andric 3090b57cec5SDimitry Andric // Fast path in case we don't have a chain already. 3100b57cec5SDimitry Andric if (!Chain) { 3110b57cec5SDimitry Andric assert(!BlockToChain[BB] && 3120b57cec5SDimitry Andric "Passed chain is null, but BB has entry in BlockToChain."); 3130b57cec5SDimitry Andric Blocks.push_back(BB); 3140b57cec5SDimitry Andric BlockToChain[BB] = this; 3150b57cec5SDimitry Andric return; 3160b57cec5SDimitry Andric } 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric assert(BB == *Chain->begin() && "Passed BB is not head of Chain."); 3190b57cec5SDimitry Andric assert(Chain->begin() != Chain->end()); 3200b57cec5SDimitry Andric 3210b57cec5SDimitry Andric // Update the incoming blocks to point to this chain, and add them to the 3220b57cec5SDimitry Andric // chain structure. 3230b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) { 3240b57cec5SDimitry Andric Blocks.push_back(ChainBB); 3250b57cec5SDimitry Andric assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain."); 3260b57cec5SDimitry Andric BlockToChain[ChainBB] = this; 3270b57cec5SDimitry Andric } 3280b57cec5SDimitry Andric } 3290b57cec5SDimitry Andric 3300b57cec5SDimitry Andric #ifndef NDEBUG 3310b57cec5SDimitry Andric /// Dump the blocks in this chain. 3320b57cec5SDimitry Andric LLVM_DUMP_METHOD void dump() { 3330b57cec5SDimitry Andric for (MachineBasicBlock *MBB : *this) 3340b57cec5SDimitry Andric MBB->dump(); 3350b57cec5SDimitry Andric } 3360b57cec5SDimitry Andric #endif // NDEBUG 3370b57cec5SDimitry Andric 3380b57cec5SDimitry Andric /// Count of predecessors of any block within the chain which have not 3390b57cec5SDimitry Andric /// yet been scheduled. In general, we will delay scheduling this chain 3400b57cec5SDimitry Andric /// until those predecessors are scheduled (or we find a sufficiently good 3410b57cec5SDimitry Andric /// reason to override this heuristic.) Note that when forming loop chains, 3420b57cec5SDimitry Andric /// blocks outside the loop are ignored and treated as if they were already 3430b57cec5SDimitry Andric /// scheduled. 3440b57cec5SDimitry Andric /// 3450b57cec5SDimitry Andric /// Note: This field is reinitialized multiple times - once for each loop, 3460b57cec5SDimitry Andric /// and then once for the function as a whole. 3470b57cec5SDimitry Andric unsigned UnscheduledPredecessors = 0; 3480b57cec5SDimitry Andric }; 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric class MachineBlockPlacement : public MachineFunctionPass { 3510b57cec5SDimitry Andric /// A type for a block filter set. 3520b57cec5SDimitry Andric using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>; 3530b57cec5SDimitry Andric 3540b57cec5SDimitry Andric /// Pair struct containing basic block and taildup profitability 3550b57cec5SDimitry Andric struct BlockAndTailDupResult { 35606c3fb27SDimitry Andric MachineBasicBlock *BB = nullptr; 3570b57cec5SDimitry Andric bool ShouldTailDup; 3580b57cec5SDimitry Andric }; 3590b57cec5SDimitry Andric 3600b57cec5SDimitry Andric /// Triple struct containing edge weight and the edge. 3610b57cec5SDimitry Andric struct WeightedEdge { 3620b57cec5SDimitry Andric BlockFrequency Weight; 36306c3fb27SDimitry Andric MachineBasicBlock *Src = nullptr; 36406c3fb27SDimitry Andric MachineBasicBlock *Dest = nullptr; 3650b57cec5SDimitry Andric }; 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric /// work lists of blocks that are ready to be laid out 3680b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 16> BlockWorkList; 3690b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 3700b57cec5SDimitry Andric 3710b57cec5SDimitry Andric /// Edges that have already been computed as optimal. 3720b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges; 3730b57cec5SDimitry Andric 3740b57cec5SDimitry Andric /// Machine Function 37506c3fb27SDimitry Andric MachineFunction *F = nullptr; 3760b57cec5SDimitry Andric 3770b57cec5SDimitry Andric /// A handle to the branch probability pass. 37806c3fb27SDimitry Andric const MachineBranchProbabilityInfo *MBPI = nullptr; 3790b57cec5SDimitry Andric 3800b57cec5SDimitry Andric /// A handle to the function-wide block frequency pass. 3815ffd83dbSDimitry Andric std::unique_ptr<MBFIWrapper> MBFI; 3820b57cec5SDimitry Andric 3830b57cec5SDimitry Andric /// A handle to the loop info. 38406c3fb27SDimitry Andric MachineLoopInfo *MLI = nullptr; 3850b57cec5SDimitry Andric 3860b57cec5SDimitry Andric /// Preferred loop exit. 3870b57cec5SDimitry Andric /// Member variable for convenience. It may be removed by duplication deep 3880b57cec5SDimitry Andric /// in the call stack. 38906c3fb27SDimitry Andric MachineBasicBlock *PreferredLoopExit = nullptr; 3900b57cec5SDimitry Andric 3910b57cec5SDimitry Andric /// A handle to the target's instruction info. 39206c3fb27SDimitry Andric const TargetInstrInfo *TII = nullptr; 3930b57cec5SDimitry Andric 3940b57cec5SDimitry Andric /// A handle to the target's lowering info. 39506c3fb27SDimitry Andric const TargetLoweringBase *TLI = nullptr; 3960b57cec5SDimitry Andric 3970b57cec5SDimitry Andric /// A handle to the post dominator tree. 39806c3fb27SDimitry Andric MachinePostDominatorTree *MPDT = nullptr; 3990b57cec5SDimitry Andric 40006c3fb27SDimitry Andric ProfileSummaryInfo *PSI = nullptr; 401480093f4SDimitry Andric 4020b57cec5SDimitry Andric /// Duplicator used to duplicate tails during placement. 4030b57cec5SDimitry Andric /// 4040b57cec5SDimitry Andric /// Placement decisions can open up new tail duplication opportunities, but 4050b57cec5SDimitry Andric /// since tail duplication affects placement decisions of later blocks, it 4060b57cec5SDimitry Andric /// must be done inline. 4070b57cec5SDimitry Andric TailDuplicator TailDup; 4080b57cec5SDimitry Andric 4095ffd83dbSDimitry Andric /// Partial tail duplication threshold. 4105ffd83dbSDimitry Andric BlockFrequency DupThreshold; 4115ffd83dbSDimitry Andric 412e8d8bef9SDimitry Andric /// True: use block profile count to compute tail duplication cost. 413e8d8bef9SDimitry Andric /// False: use block frequency to compute tail duplication cost. 41406c3fb27SDimitry Andric bool UseProfileCount = false; 415e8d8bef9SDimitry Andric 4160b57cec5SDimitry Andric /// Allocator and owner of BlockChain structures. 4170b57cec5SDimitry Andric /// 4180b57cec5SDimitry Andric /// We build BlockChains lazily while processing the loop structure of 4190b57cec5SDimitry Andric /// a function. To reduce malloc traffic, we allocate them using this 4200b57cec5SDimitry Andric /// slab-like allocator, and destroy them after the pass completes. An 4210b57cec5SDimitry Andric /// important guarantee is that this allocator produces stable pointers to 4220b57cec5SDimitry Andric /// the chains. 4230b57cec5SDimitry Andric SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 4240b57cec5SDimitry Andric 4250b57cec5SDimitry Andric /// Function wide BasicBlock to BlockChain mapping. 4260b57cec5SDimitry Andric /// 4270b57cec5SDimitry Andric /// This mapping allows efficiently moving from any given basic block to the 4280b57cec5SDimitry Andric /// BlockChain it participates in, if any. We use it to, among other things, 4290b57cec5SDimitry Andric /// allow implicitly defining edges between chains as the existing edges 4300b57cec5SDimitry Andric /// between basic blocks. 4310b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain; 4320b57cec5SDimitry Andric 4330b57cec5SDimitry Andric #ifndef NDEBUG 4340b57cec5SDimitry Andric /// The set of basic blocks that have terminators that cannot be fully 4350b57cec5SDimitry Andric /// analyzed. These basic blocks cannot be re-ordered safely by 4360b57cec5SDimitry Andric /// MachineBlockPlacement, and we must preserve physical layout of these 4370b57cec5SDimitry Andric /// blocks and their successors through the pass. 4380b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits; 4390b57cec5SDimitry Andric #endif 4400b57cec5SDimitry Andric 441e8d8bef9SDimitry Andric /// Get block profile count or frequency according to UseProfileCount. 442e8d8bef9SDimitry Andric /// The return value is used to model tail duplication cost. 443e8d8bef9SDimitry Andric BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) { 444e8d8bef9SDimitry Andric if (UseProfileCount) { 445e8d8bef9SDimitry Andric auto Count = MBFI->getBlockProfileCount(BB); 446e8d8bef9SDimitry Andric if (Count) 4475f757f3fSDimitry Andric return BlockFrequency(*Count); 448e8d8bef9SDimitry Andric else 4495f757f3fSDimitry Andric return BlockFrequency(0); 450e8d8bef9SDimitry Andric } else 451e8d8bef9SDimitry Andric return MBFI->getBlockFreq(BB); 452e8d8bef9SDimitry Andric } 453e8d8bef9SDimitry Andric 4545ffd83dbSDimitry Andric /// Scale the DupThreshold according to basic block size. 4555ffd83dbSDimitry Andric BlockFrequency scaleThreshold(MachineBasicBlock *BB); 4565ffd83dbSDimitry Andric void initDupThreshold(); 4575ffd83dbSDimitry Andric 4580b57cec5SDimitry Andric /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 4590b57cec5SDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 4600b57cec5SDimitry Andric void markChainSuccessors( 4610b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 4620b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric /// Decrease the UnscheduledPredecessors count for a single block, and 4650b57cec5SDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 4660b57cec5SDimitry Andric void markBlockSuccessors( 4670b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *BB, 4680b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 4690b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 4700b57cec5SDimitry Andric 4710b57cec5SDimitry Andric BranchProbability 4720b57cec5SDimitry Andric collectViableSuccessors( 4730b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 4740b57cec5SDimitry Andric const BlockFilterSet *BlockFilter, 4750b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors); 4765ffd83dbSDimitry Andric bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred, 4775ffd83dbSDimitry Andric BlockFilterSet *BlockFilter); 4785ffd83dbSDimitry Andric void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates, 4795ffd83dbSDimitry Andric MachineBasicBlock *BB, 4805ffd83dbSDimitry Andric BlockFilterSet *BlockFilter); 4810b57cec5SDimitry Andric bool repeatedlyTailDuplicateBlock( 4820b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 483*0fca6ea1SDimitry Andric const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain, 484*0fca6ea1SDimitry Andric BlockFilterSet *BlockFilter, 485*0fca6ea1SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 486*0fca6ea1SDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt); 487*0fca6ea1SDimitry Andric bool 488*0fca6ea1SDimitry Andric maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred, 4890b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 4900b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 491*0fca6ea1SDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt, 4920b57cec5SDimitry Andric bool &DuplicatedToLPred); 4930b57cec5SDimitry Andric bool hasBetterLayoutPredecessor( 4940b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 4950b57cec5SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 4960b57cec5SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 4970b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 4980b57cec5SDimitry Andric BlockAndTailDupResult selectBestSuccessor( 4990b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 5000b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5010b57cec5SDimitry Andric MachineBasicBlock *selectBestCandidateBlock( 5020b57cec5SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList); 503*0fca6ea1SDimitry Andric MachineBasicBlock * 504*0fca6ea1SDimitry Andric getFirstUnplacedBlock(const BlockChain &PlacedChain, 505*0fca6ea1SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt); 506*0fca6ea1SDimitry Andric MachineBasicBlock * 507*0fca6ea1SDimitry Andric getFirstUnplacedBlock(const BlockChain &PlacedChain, 508*0fca6ea1SDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt, 5090b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5100b57cec5SDimitry Andric 5110b57cec5SDimitry Andric /// Add a basic block to the work list if it is appropriate. 5120b57cec5SDimitry Andric /// 5130b57cec5SDimitry Andric /// If the optional parameter BlockFilter is provided, only MBB 5140b57cec5SDimitry Andric /// present in the set will be added to the worklist. If nullptr 5150b57cec5SDimitry Andric /// is provided, no filtering occurs. 5160b57cec5SDimitry Andric void fillWorkLists(const MachineBasicBlock *MBB, 5170b57cec5SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 5180b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5190b57cec5SDimitry Andric 5200b57cec5SDimitry Andric void buildChain(const MachineBasicBlock *BB, BlockChain &Chain, 5210b57cec5SDimitry Andric BlockFilterSet *BlockFilter = nullptr); 5220b57cec5SDimitry Andric bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock, 5230b57cec5SDimitry Andric const MachineBasicBlock *OldTop); 5240b57cec5SDimitry Andric bool hasViableTopFallthrough(const MachineBasicBlock *Top, 5250b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5260b57cec5SDimitry Andric BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top, 5270b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5280b57cec5SDimitry Andric BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop, 5290b57cec5SDimitry Andric const MachineBasicBlock *OldTop, 5300b57cec5SDimitry Andric const MachineBasicBlock *ExitBB, 5310b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5320b57cec5SDimitry Andric MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop, 5330b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 5340b57cec5SDimitry Andric MachineBasicBlock *findBestLoopTop( 5350b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 5360b57cec5SDimitry Andric MachineBasicBlock *findBestLoopExit( 5370b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet, 5380b57cec5SDimitry Andric BlockFrequency &ExitFreq); 5390b57cec5SDimitry Andric BlockFilterSet collectLoopBlockSet(const MachineLoop &L); 5400b57cec5SDimitry Andric void buildLoopChains(const MachineLoop &L); 5410b57cec5SDimitry Andric void rotateLoop( 5420b57cec5SDimitry Andric BlockChain &LoopChain, const MachineBasicBlock *ExitingBB, 5430b57cec5SDimitry Andric BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet); 5440b57cec5SDimitry Andric void rotateLoopWithProfile( 5450b57cec5SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 5460b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5470b57cec5SDimitry Andric void buildCFGChains(); 5480b57cec5SDimitry Andric void optimizeBranches(); 5490b57cec5SDimitry Andric void alignBlocks(); 5500b57cec5SDimitry Andric /// Returns true if a block should be tail-duplicated to increase fallthrough 5510b57cec5SDimitry Andric /// opportunities. 5520b57cec5SDimitry Andric bool shouldTailDuplicate(MachineBasicBlock *BB); 5530b57cec5SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 5540b57cec5SDimitry Andric /// fallthroughs. 5550b57cec5SDimitry Andric bool isProfitableToTailDup( 5560b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 5570b57cec5SDimitry Andric BranchProbability QProb, 5580b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5590b57cec5SDimitry Andric 5600b57cec5SDimitry Andric /// Check for a trellis layout. 5610b57cec5SDimitry Andric bool isTrellis(const MachineBasicBlock *BB, 5620b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 5630b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5640b57cec5SDimitry Andric 5650b57cec5SDimitry Andric /// Get the best successor given a trellis layout. 5660b57cec5SDimitry Andric BlockAndTailDupResult getBestTrellisSuccessor( 5670b57cec5SDimitry Andric const MachineBasicBlock *BB, 5680b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 5690b57cec5SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 5700b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5710b57cec5SDimitry Andric 5720b57cec5SDimitry Andric /// Get the best pair of non-conflicting edges. 5730b57cec5SDimitry Andric static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges( 5740b57cec5SDimitry Andric const MachineBasicBlock *BB, 5750b57cec5SDimitry Andric MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges); 5760b57cec5SDimitry Andric 5770b57cec5SDimitry Andric /// Returns true if a block can tail duplicate into all unplaced 5780b57cec5SDimitry Andric /// predecessors. Filters based on loop. 5790b57cec5SDimitry Andric bool canTailDuplicateUnplacedPreds( 5800b57cec5SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 5810b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5820b57cec5SDimitry Andric 5830b57cec5SDimitry Andric /// Find chains of triangles to tail-duplicate where a global analysis works, 5840b57cec5SDimitry Andric /// but a local analysis would not find them. 5850b57cec5SDimitry Andric void precomputeTriangleChains(); 5860b57cec5SDimitry Andric 5870eae32dcSDimitry Andric /// Apply a post-processing step optimizing block placement. 5880eae32dcSDimitry Andric void applyExtTsp(); 5890eae32dcSDimitry Andric 5900eae32dcSDimitry Andric /// Modify the existing block placement in the function and adjust all jumps. 5910eae32dcSDimitry Andric void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder); 5920eae32dcSDimitry Andric 5930eae32dcSDimitry Andric /// Create a single CFG chain from the current block order. 5940eae32dcSDimitry Andric void createCFGChainExtTsp(); 5950eae32dcSDimitry Andric 5960b57cec5SDimitry Andric public: 5970b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 5980b57cec5SDimitry Andric 5990b57cec5SDimitry Andric MachineBlockPlacement() : MachineFunctionPass(ID) { 6000b57cec5SDimitry Andric initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 6010b57cec5SDimitry Andric } 6020b57cec5SDimitry Andric 6030b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 6040b57cec5SDimitry Andric 6050b57cec5SDimitry Andric bool allowTailDupPlacement() const { 6060b57cec5SDimitry Andric assert(F); 6070b57cec5SDimitry Andric return TailDupPlacement && !F->getTarget().requiresStructuredCFG(); 6080b57cec5SDimitry Andric } 6090b57cec5SDimitry Andric 6100b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 611*0fca6ea1SDimitry Andric AU.addRequired<MachineBranchProbabilityInfoWrapperPass>(); 612*0fca6ea1SDimitry Andric AU.addRequired<MachineBlockFrequencyInfoWrapperPass>(); 6130b57cec5SDimitry Andric if (TailDupPlacement) 614*0fca6ea1SDimitry Andric AU.addRequired<MachinePostDominatorTreeWrapperPass>(); 615*0fca6ea1SDimitry Andric AU.addRequired<MachineLoopInfoWrapperPass>(); 616480093f4SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>(); 6170b57cec5SDimitry Andric AU.addRequired<TargetPassConfig>(); 6180b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 6190b57cec5SDimitry Andric } 6200b57cec5SDimitry Andric }; 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric } // end anonymous namespace 6230b57cec5SDimitry Andric 6240b57cec5SDimitry Andric char MachineBlockPlacement::ID = 0; 6250b57cec5SDimitry Andric 6260b57cec5SDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 6270b57cec5SDimitry Andric 6280b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE, 6290b57cec5SDimitry Andric "Branch Probability Basic Block Placement", false, false) 630*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass) 631*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass) 632*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTreeWrapperPass) 633*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfoWrapperPass) 634480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 6350b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE, 6360b57cec5SDimitry Andric "Branch Probability Basic Block Placement", false, false) 6370b57cec5SDimitry Andric 6380b57cec5SDimitry Andric #ifndef NDEBUG 6390b57cec5SDimitry Andric /// Helper to print the name of a MBB. 6400b57cec5SDimitry Andric /// 6410b57cec5SDimitry Andric /// Only used by debug logging. 6420b57cec5SDimitry Andric static std::string getBlockName(const MachineBasicBlock *BB) { 6430b57cec5SDimitry Andric std::string Result; 6440b57cec5SDimitry Andric raw_string_ostream OS(Result); 6450b57cec5SDimitry Andric OS << printMBBReference(*BB); 6460b57cec5SDimitry Andric OS << " ('" << BB->getName() << "')"; 6470b57cec5SDimitry Andric OS.flush(); 6480b57cec5SDimitry Andric return Result; 6490b57cec5SDimitry Andric } 6500b57cec5SDimitry Andric #endif 6510b57cec5SDimitry Andric 6520b57cec5SDimitry Andric /// Mark a chain's successors as having one fewer preds. 6530b57cec5SDimitry Andric /// 6540b57cec5SDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will 6550b57cec5SDimitry Andric /// quickly walk the successors of each block in the chain and mark them as 6560b57cec5SDimitry Andric /// having one fewer active predecessor. It also adds any successors of this 6570b57cec5SDimitry Andric /// chain which reach the zero-predecessor state to the appropriate worklist. 6580b57cec5SDimitry Andric void MachineBlockPlacement::markChainSuccessors( 6590b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 6600b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 6610b57cec5SDimitry Andric // Walk all the blocks in this chain, marking their successors as having 6620b57cec5SDimitry Andric // a predecessor placed. 6630b57cec5SDimitry Andric for (MachineBasicBlock *MBB : Chain) { 6640b57cec5SDimitry Andric markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 6650b57cec5SDimitry Andric } 6660b57cec5SDimitry Andric } 6670b57cec5SDimitry Andric 6680b57cec5SDimitry Andric /// Mark a single block's successors as having one fewer preds. 6690b57cec5SDimitry Andric /// 6700b57cec5SDimitry Andric /// Under normal circumstances, this is only called by markChainSuccessors, 6710b57cec5SDimitry Andric /// but if a block that was to be placed is completely tail-duplicated away, 6720b57cec5SDimitry Andric /// and was duplicated into the chain end, we need to redo markBlockSuccessors 6730b57cec5SDimitry Andric /// for just that block. 6740b57cec5SDimitry Andric void MachineBlockPlacement::markBlockSuccessors( 6750b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *MBB, 6760b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) { 6770b57cec5SDimitry Andric // Add any successors for which this is the only un-placed in-loop 6780b57cec5SDimitry Andric // predecessor to the worklist as a viable candidate for CFG-neutral 6790b57cec5SDimitry Andric // placement. No subsequent placement of this block will violate the CFG 6800b57cec5SDimitry Andric // shape, so we get to use heuristics to choose a favorable placement. 6810b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 6820b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(Succ)) 6830b57cec5SDimitry Andric continue; 6840b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 6850b57cec5SDimitry Andric // Disregard edges within a fixed chain, or edges to the loop header. 6860b57cec5SDimitry Andric if (&Chain == &SuccChain || Succ == LoopHeaderBB) 6870b57cec5SDimitry Andric continue; 6880b57cec5SDimitry Andric 6890b57cec5SDimitry Andric // This is a cross-chain edge that is within the loop, so decrement the 6900b57cec5SDimitry Andric // loop predecessor count of the destination chain. 6910b57cec5SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0 || 6920b57cec5SDimitry Andric --SuccChain.UnscheduledPredecessors > 0) 6930b57cec5SDimitry Andric continue; 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric auto *NewBB = *SuccChain.begin(); 6960b57cec5SDimitry Andric if (NewBB->isEHPad()) 6970b57cec5SDimitry Andric EHPadWorkList.push_back(NewBB); 6980b57cec5SDimitry Andric else 6990b57cec5SDimitry Andric BlockWorkList.push_back(NewBB); 7000b57cec5SDimitry Andric } 7010b57cec5SDimitry Andric } 7020b57cec5SDimitry Andric 7030b57cec5SDimitry Andric /// This helper function collects the set of successors of block 7040b57cec5SDimitry Andric /// \p BB that are allowed to be its layout successors, and return 7050b57cec5SDimitry Andric /// the total branch probability of edges from \p BB to those 7060b57cec5SDimitry Andric /// blocks. 7070b57cec5SDimitry Andric BranchProbability MachineBlockPlacement::collectViableSuccessors( 7080b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 7090b57cec5SDimitry Andric const BlockFilterSet *BlockFilter, 7100b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors) { 7110b57cec5SDimitry Andric // Adjust edge probabilities by excluding edges pointing to blocks that is 7120b57cec5SDimitry Andric // either not in BlockFilter or is already in the current chain. Consider the 7130b57cec5SDimitry Andric // following CFG: 7140b57cec5SDimitry Andric // 7150b57cec5SDimitry Andric // --->A 7160b57cec5SDimitry Andric // | / \ 7170b57cec5SDimitry Andric // | B C 7180b57cec5SDimitry Andric // | \ / \ 7190b57cec5SDimitry Andric // ----D E 7200b57cec5SDimitry Andric // 7210b57cec5SDimitry Andric // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 7220b57cec5SDimitry Andric // A->C is chosen as a fall-through, D won't be selected as a successor of C 7230b57cec5SDimitry Andric // due to CFG constraint (the probability of C->D is not greater than 7240b57cec5SDimitry Andric // HotProb to break topo-order). If we exclude E that is not in BlockFilter 7250b57cec5SDimitry Andric // when calculating the probability of C->D, D will be selected and we 7260b57cec5SDimitry Andric // will get A C D B as the layout of this loop. 7270b57cec5SDimitry Andric auto AdjustedSumProb = BranchProbability::getOne(); 7280b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB->successors()) { 7290b57cec5SDimitry Andric bool SkipSucc = false; 7300b57cec5SDimitry Andric if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 7310b57cec5SDimitry Andric SkipSucc = true; 7320b57cec5SDimitry Andric } else { 7330b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 7340b57cec5SDimitry Andric if (SuccChain == &Chain) { 7350b57cec5SDimitry Andric SkipSucc = true; 7360b57cec5SDimitry Andric } else if (Succ != *SuccChain->begin()) { 7370b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(Succ) 7380b57cec5SDimitry Andric << " -> Mid chain!\n"); 7390b57cec5SDimitry Andric continue; 7400b57cec5SDimitry Andric } 7410b57cec5SDimitry Andric } 7420b57cec5SDimitry Andric if (SkipSucc) 7430b57cec5SDimitry Andric AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 7440b57cec5SDimitry Andric else 7450b57cec5SDimitry Andric Successors.push_back(Succ); 7460b57cec5SDimitry Andric } 7470b57cec5SDimitry Andric 7480b57cec5SDimitry Andric return AdjustedSumProb; 7490b57cec5SDimitry Andric } 7500b57cec5SDimitry Andric 7510b57cec5SDimitry Andric /// The helper function returns the branch probability that is adjusted 7520b57cec5SDimitry Andric /// or normalized over the new total \p AdjustedSumProb. 7530b57cec5SDimitry Andric static BranchProbability 7540b57cec5SDimitry Andric getAdjustedProbability(BranchProbability OrigProb, 7550b57cec5SDimitry Andric BranchProbability AdjustedSumProb) { 7560b57cec5SDimitry Andric BranchProbability SuccProb; 7570b57cec5SDimitry Andric uint32_t SuccProbN = OrigProb.getNumerator(); 7580b57cec5SDimitry Andric uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 7590b57cec5SDimitry Andric if (SuccProbN >= SuccProbD) 7600b57cec5SDimitry Andric SuccProb = BranchProbability::getOne(); 7610b57cec5SDimitry Andric else 7620b57cec5SDimitry Andric SuccProb = BranchProbability(SuccProbN, SuccProbD); 7630b57cec5SDimitry Andric 7640b57cec5SDimitry Andric return SuccProb; 7650b57cec5SDimitry Andric } 7660b57cec5SDimitry Andric 7670b57cec5SDimitry Andric /// Check if \p BB has exactly the successors in \p Successors. 7680b57cec5SDimitry Andric static bool 7690b57cec5SDimitry Andric hasSameSuccessors(MachineBasicBlock &BB, 7700b57cec5SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &Successors) { 7710b57cec5SDimitry Andric if (BB.succ_size() != Successors.size()) 7720b57cec5SDimitry Andric return false; 7730b57cec5SDimitry Andric // We don't want to count self-loops 7740b57cec5SDimitry Andric if (Successors.count(&BB)) 7750b57cec5SDimitry Andric return false; 7760b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) 7770b57cec5SDimitry Andric if (!Successors.count(Succ)) 7780b57cec5SDimitry Andric return false; 7790b57cec5SDimitry Andric return true; 7800b57cec5SDimitry Andric } 7810b57cec5SDimitry Andric 7820b57cec5SDimitry Andric /// Check if a block should be tail duplicated to increase fallthrough 7830b57cec5SDimitry Andric /// opportunities. 7840b57cec5SDimitry Andric /// \p BB Block to check. 7850b57cec5SDimitry Andric bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) { 7860b57cec5SDimitry Andric // Blocks with single successors don't create additional fallthrough 7870b57cec5SDimitry Andric // opportunities. Don't duplicate them. TODO: When conditional exits are 7880b57cec5SDimitry Andric // analyzable, allow them to be duplicated. 7890b57cec5SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric if (BB->succ_size() == 1) 7920b57cec5SDimitry Andric return false; 7930b57cec5SDimitry Andric return TailDup.shouldTailDuplicate(IsSimple, *BB); 7940b57cec5SDimitry Andric } 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric /// Compare 2 BlockFrequency's with a small penalty for \p A. 7970b57cec5SDimitry Andric /// In order to be conservative, we apply a X% penalty to account for 7980b57cec5SDimitry Andric /// increased icache pressure and static heuristics. For small frequencies 7990b57cec5SDimitry Andric /// we use only the numerators to improve accuracy. For simplicity, we assume the 8000b57cec5SDimitry Andric /// penalty is less than 100% 8010b57cec5SDimitry Andric /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere. 8020b57cec5SDimitry Andric static bool greaterWithBias(BlockFrequency A, BlockFrequency B, 8035f757f3fSDimitry Andric BlockFrequency EntryFreq) { 8040b57cec5SDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 8050b57cec5SDimitry Andric BlockFrequency Gain = A - B; 8065f757f3fSDimitry Andric return (Gain / ThresholdProb) >= EntryFreq; 8070b57cec5SDimitry Andric } 8080b57cec5SDimitry Andric 8090b57cec5SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 8100b57cec5SDimitry Andric /// fallthroughs. It only makes sense to call this function when 8110b57cec5SDimitry Andric /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is 8120b57cec5SDimitry Andric /// always locally profitable if we would have picked \p Succ without 8130b57cec5SDimitry Andric /// considering duplication. 8140b57cec5SDimitry Andric bool MachineBlockPlacement::isProfitableToTailDup( 8150b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 8160b57cec5SDimitry Andric BranchProbability QProb, 8170b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 8180b57cec5SDimitry Andric // We need to do a probability calculation to make sure this is profitable. 8190b57cec5SDimitry Andric // First: does succ have a successor that post-dominates? This affects the 8200b57cec5SDimitry Andric // calculation. The 2 relevant cases are: 8210b57cec5SDimitry Andric // BB BB 8220b57cec5SDimitry Andric // | \Qout | \Qout 8230b57cec5SDimitry Andric // P| C |P C 8240b57cec5SDimitry Andric // = C' = C' 8250b57cec5SDimitry Andric // | /Qin | /Qin 8260b57cec5SDimitry Andric // | / | / 8270b57cec5SDimitry Andric // Succ Succ 8280b57cec5SDimitry Andric // / \ | \ V 8290b57cec5SDimitry Andric // U/ =V |U \ 8300b57cec5SDimitry Andric // / \ = D 8310b57cec5SDimitry Andric // D E | / 8320b57cec5SDimitry Andric // | / 8330b57cec5SDimitry Andric // |/ 8340b57cec5SDimitry Andric // PDom 8350b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 8360b57cec5SDimitry Andric // In the second case, Placing Succ while duplicating it into C prevents the 8370b57cec5SDimitry Andric // fallthrough of Succ into either D or PDom, because they now have C as an 8380b57cec5SDimitry Andric // unplaced predecessor 8390b57cec5SDimitry Andric 8400b57cec5SDimitry Andric // Start by figuring out which case we fall into 8410b57cec5SDimitry Andric MachineBasicBlock *PDom = nullptr; 8420b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> SuccSuccs; 8430b57cec5SDimitry Andric // Only scan the relevant successors 8440b57cec5SDimitry Andric auto AdjustedSuccSumProb = 8450b57cec5SDimitry Andric collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs); 8460b57cec5SDimitry Andric BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ); 8470b57cec5SDimitry Andric auto BBFreq = MBFI->getBlockFreq(BB); 8480b57cec5SDimitry Andric auto SuccFreq = MBFI->getBlockFreq(Succ); 8490b57cec5SDimitry Andric BlockFrequency P = BBFreq * PProb; 8500b57cec5SDimitry Andric BlockFrequency Qout = BBFreq * QProb; 8515f757f3fSDimitry Andric BlockFrequency EntryFreq = MBFI->getEntryFreq(); 8520b57cec5SDimitry Andric // If there are no more successors, it is profitable to copy, as it strictly 8530b57cec5SDimitry Andric // increases fallthrough. 8540b57cec5SDimitry Andric if (SuccSuccs.size() == 0) 8550b57cec5SDimitry Andric return greaterWithBias(P, Qout, EntryFreq); 8560b57cec5SDimitry Andric 8570b57cec5SDimitry Andric auto BestSuccSucc = BranchProbability::getZero(); 8580b57cec5SDimitry Andric // Find the PDom or the best Succ if no PDom exists. 8590b57cec5SDimitry Andric for (MachineBasicBlock *SuccSucc : SuccSuccs) { 8600b57cec5SDimitry Andric auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc); 8610b57cec5SDimitry Andric if (Prob > BestSuccSucc) 8620b57cec5SDimitry Andric BestSuccSucc = Prob; 8630b57cec5SDimitry Andric if (PDom == nullptr) 8640b57cec5SDimitry Andric if (MPDT->dominates(SuccSucc, Succ)) { 8650b57cec5SDimitry Andric PDom = SuccSucc; 8660b57cec5SDimitry Andric break; 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric } 8690b57cec5SDimitry Andric // For the comparisons, we need to know Succ's best incoming edge that isn't 8700b57cec5SDimitry Andric // from BB. 8710b57cec5SDimitry Andric auto SuccBestPred = BlockFrequency(0); 8720b57cec5SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 8730b57cec5SDimitry Andric if (SuccPred == Succ || SuccPred == BB 8740b57cec5SDimitry Andric || BlockToChain[SuccPred] == &Chain 8750b57cec5SDimitry Andric || (BlockFilter && !BlockFilter->count(SuccPred))) 8760b57cec5SDimitry Andric continue; 8770b57cec5SDimitry Andric auto Freq = MBFI->getBlockFreq(SuccPred) 8780b57cec5SDimitry Andric * MBPI->getEdgeProbability(SuccPred, Succ); 8790b57cec5SDimitry Andric if (Freq > SuccBestPred) 8800b57cec5SDimitry Andric SuccBestPred = Freq; 8810b57cec5SDimitry Andric } 8820b57cec5SDimitry Andric // Qin is Succ's best unplaced incoming edge that isn't BB 8830b57cec5SDimitry Andric BlockFrequency Qin = SuccBestPred; 8840b57cec5SDimitry Andric // If it doesn't have a post-dominating successor, here is the calculation: 8850b57cec5SDimitry Andric // BB BB 8860b57cec5SDimitry Andric // | \Qout | \ 8870b57cec5SDimitry Andric // P| C | = 8880b57cec5SDimitry Andric // = C' | C 8890b57cec5SDimitry Andric // | /Qin | | 8900b57cec5SDimitry Andric // | / | C' (+Succ) 8910b57cec5SDimitry Andric // Succ Succ /| 8920b57cec5SDimitry Andric // / \ | \/ | 8930b57cec5SDimitry Andric // U/ =V | == | 8940b57cec5SDimitry Andric // / \ | / \| 8950b57cec5SDimitry Andric // D E D E 8960b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 8970b57cec5SDimitry Andric // Cost in the first case is: P + V 8980b57cec5SDimitry Andric // For this calculation, we always assume P > Qout. If Qout > P 8990b57cec5SDimitry Andric // The result of this function will be ignored at the caller. 9000b57cec5SDimitry Andric // Let F = SuccFreq - Qin 9010b57cec5SDimitry Andric // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V 9020b57cec5SDimitry Andric 9030b57cec5SDimitry Andric if (PDom == nullptr || !Succ->isSuccessor(PDom)) { 9040b57cec5SDimitry Andric BranchProbability UProb = BestSuccSucc; 9050b57cec5SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 9060b57cec5SDimitry Andric BlockFrequency F = SuccFreq - Qin; 9070b57cec5SDimitry Andric BlockFrequency V = SuccFreq * VProb; 9080b57cec5SDimitry Andric BlockFrequency QinU = std::min(Qin, F) * UProb; 9090b57cec5SDimitry Andric BlockFrequency BaseCost = P + V; 9100b57cec5SDimitry Andric BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb; 9110b57cec5SDimitry Andric return greaterWithBias(BaseCost, DupCost, EntryFreq); 9120b57cec5SDimitry Andric } 9130b57cec5SDimitry Andric BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom); 9140b57cec5SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 9150b57cec5SDimitry Andric BlockFrequency U = SuccFreq * UProb; 9160b57cec5SDimitry Andric BlockFrequency V = SuccFreq * VProb; 9170b57cec5SDimitry Andric BlockFrequency F = SuccFreq - Qin; 9180b57cec5SDimitry Andric // If there is a post-dominating successor, here is the calculation: 9190b57cec5SDimitry Andric // BB BB BB BB 9200b57cec5SDimitry Andric // | \Qout | \ | \Qout | \ 9210b57cec5SDimitry Andric // |P C | = |P C | = 9220b57cec5SDimitry Andric // = C' |P C = C' |P C 9230b57cec5SDimitry Andric // | /Qin | | | /Qin | | 9240b57cec5SDimitry Andric // | / | C' (+Succ) | / | C' (+Succ) 9250b57cec5SDimitry Andric // Succ Succ /| Succ Succ /| 9260b57cec5SDimitry Andric // | \ V | \/ | | \ V | \/ | 9270b57cec5SDimitry Andric // |U \ |U /\ =? |U = |U /\ | 9280b57cec5SDimitry Andric // = D = = =?| | D | = =| 9290b57cec5SDimitry Andric // | / |/ D | / |/ D 9300b57cec5SDimitry Andric // | / | / | = | / 9310b57cec5SDimitry Andric // |/ | / |/ | = 9320b57cec5SDimitry Andric // Dom Dom Dom Dom 9330b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 9340b57cec5SDimitry Andric // The cost for taken branches in the first case is P + U 9350b57cec5SDimitry Andric // Let F = SuccFreq - Qin 9360b57cec5SDimitry Andric // The cost in the second case (assuming independence), given the layout: 9370b57cec5SDimitry Andric // BB, Succ, (C+Succ), D, Dom or the layout: 9380b57cec5SDimitry Andric // BB, Succ, D, Dom, (C+Succ) 9390b57cec5SDimitry Andric // is Qout + max(F, Qin) * U + min(F, Qin) 9400b57cec5SDimitry Andric // compare P + U vs Qout + P * U + Qin. 9410b57cec5SDimitry Andric // 9420b57cec5SDimitry Andric // The 3rd and 4th cases cover when Dom would be chosen to follow Succ. 9430b57cec5SDimitry Andric // 9440b57cec5SDimitry Andric // For the 3rd case, the cost is P + 2 * V 9450b57cec5SDimitry Andric // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V 9460b57cec5SDimitry Andric // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V 9470b57cec5SDimitry Andric if (UProb > AdjustedSuccSumProb / 2 && 9480b57cec5SDimitry Andric !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb, 9490b57cec5SDimitry Andric Chain, BlockFilter)) 9500b57cec5SDimitry Andric // Cases 3 & 4 9510b57cec5SDimitry Andric return greaterWithBias( 9520b57cec5SDimitry Andric (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb), 9530b57cec5SDimitry Andric EntryFreq); 9540b57cec5SDimitry Andric // Cases 1 & 2 9550b57cec5SDimitry Andric return greaterWithBias((P + U), 9560b57cec5SDimitry Andric (Qout + std::min(Qin, F) * AdjustedSuccSumProb + 9570b57cec5SDimitry Andric std::max(Qin, F) * UProb), 9580b57cec5SDimitry Andric EntryFreq); 9590b57cec5SDimitry Andric } 9600b57cec5SDimitry Andric 9610b57cec5SDimitry Andric /// Check for a trellis layout. \p BB is the upper part of a trellis if its 9620b57cec5SDimitry Andric /// successors form the lower part of a trellis. A successor set S forms the 9630b57cec5SDimitry Andric /// lower part of a trellis if all of the predecessors of S are either in S or 9640b57cec5SDimitry Andric /// have all of S as successors. We ignore trellises where BB doesn't have 2 9650b57cec5SDimitry Andric /// successors because for fewer than 2, it's trivial, and for 3 or greater they 9660b57cec5SDimitry Andric /// are very uncommon and complex to compute optimally. Allowing edges within S 9670b57cec5SDimitry Andric /// is not strictly a trellis, but the same algorithm works, so we allow it. 9680b57cec5SDimitry Andric bool MachineBlockPlacement::isTrellis( 9690b57cec5SDimitry Andric const MachineBasicBlock *BB, 9700b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 9710b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 9720b57cec5SDimitry Andric // Technically BB could form a trellis with branching factor higher than 2. 9730b57cec5SDimitry Andric // But that's extremely uncommon. 9740b57cec5SDimitry Andric if (BB->succ_size() != 2 || ViableSuccs.size() != 2) 9750b57cec5SDimitry Andric return false; 9760b57cec5SDimitry Andric 9770b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(), 9780b57cec5SDimitry Andric BB->succ_end()); 9790b57cec5SDimitry Andric // To avoid reviewing the same predecessors twice. 9800b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds; 9810b57cec5SDimitry Andric 9820b57cec5SDimitry Andric for (MachineBasicBlock *Succ : ViableSuccs) { 9830b57cec5SDimitry Andric int PredCount = 0; 984fcaf7f86SDimitry Andric for (auto *SuccPred : Succ->predecessors()) { 9850b57cec5SDimitry Andric // Allow triangle successors, but don't count them. 9860b57cec5SDimitry Andric if (Successors.count(SuccPred)) { 9870b57cec5SDimitry Andric // Make sure that it is actually a triangle. 9880b57cec5SDimitry Andric for (MachineBasicBlock *CheckSucc : SuccPred->successors()) 9890b57cec5SDimitry Andric if (!Successors.count(CheckSucc)) 9900b57cec5SDimitry Andric return false; 9910b57cec5SDimitry Andric continue; 9920b57cec5SDimitry Andric } 9930b57cec5SDimitry Andric const BlockChain *PredChain = BlockToChain[SuccPred]; 9940b57cec5SDimitry Andric if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) || 9950b57cec5SDimitry Andric PredChain == &Chain || PredChain == BlockToChain[Succ]) 9960b57cec5SDimitry Andric continue; 9970b57cec5SDimitry Andric ++PredCount; 9980b57cec5SDimitry Andric // Perform the successor check only once. 9990b57cec5SDimitry Andric if (!SeenPreds.insert(SuccPred).second) 10000b57cec5SDimitry Andric continue; 10010b57cec5SDimitry Andric if (!hasSameSuccessors(*SuccPred, Successors)) 10020b57cec5SDimitry Andric return false; 10030b57cec5SDimitry Andric } 10040b57cec5SDimitry Andric // If one of the successors has only BB as a predecessor, it is not a 10050b57cec5SDimitry Andric // trellis. 10060b57cec5SDimitry Andric if (PredCount < 1) 10070b57cec5SDimitry Andric return false; 10080b57cec5SDimitry Andric } 10090b57cec5SDimitry Andric return true; 10100b57cec5SDimitry Andric } 10110b57cec5SDimitry Andric 10120b57cec5SDimitry Andric /// Pick the highest total weight pair of edges that can both be laid out. 10130b57cec5SDimitry Andric /// The edges in \p Edges[0] are assumed to have a different destination than 10140b57cec5SDimitry Andric /// the edges in \p Edges[1]. Simple counting shows that the best pair is either 10150b57cec5SDimitry Andric /// the individual highest weight edges to the 2 different destinations, or in 10160b57cec5SDimitry Andric /// case of a conflict, one of them should be replaced with a 2nd best edge. 10170b57cec5SDimitry Andric std::pair<MachineBlockPlacement::WeightedEdge, 10180b57cec5SDimitry Andric MachineBlockPlacement::WeightedEdge> 10190b57cec5SDimitry Andric MachineBlockPlacement::getBestNonConflictingEdges( 10200b57cec5SDimitry Andric const MachineBasicBlock *BB, 10210b57cec5SDimitry Andric MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>> 10220b57cec5SDimitry Andric Edges) { 10230b57cec5SDimitry Andric // Sort the edges, and then for each successor, find the best incoming 10240b57cec5SDimitry Andric // predecessor. If the best incoming predecessors aren't the same, 10250b57cec5SDimitry Andric // then that is clearly the best layout. If there is a conflict, one of the 10260b57cec5SDimitry Andric // successors will have to fallthrough from the second best predecessor. We 10270b57cec5SDimitry Andric // compare which combination is better overall. 10280b57cec5SDimitry Andric 10290b57cec5SDimitry Andric // Sort for highest frequency. 10300b57cec5SDimitry Andric auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; }; 10310b57cec5SDimitry Andric 10320b57cec5SDimitry Andric llvm::stable_sort(Edges[0], Cmp); 10330b57cec5SDimitry Andric llvm::stable_sort(Edges[1], Cmp); 10340b57cec5SDimitry Andric auto BestA = Edges[0].begin(); 10350b57cec5SDimitry Andric auto BestB = Edges[1].begin(); 10360b57cec5SDimitry Andric // Arrange for the correct answer to be in BestA and BestB 10370b57cec5SDimitry Andric // If the 2 best edges don't conflict, the answer is already there. 10380b57cec5SDimitry Andric if (BestA->Src == BestB->Src) { 10390b57cec5SDimitry Andric // Compare the total fallthrough of (Best + Second Best) for both pairs 10400b57cec5SDimitry Andric auto SecondBestA = std::next(BestA); 10410b57cec5SDimitry Andric auto SecondBestB = std::next(BestB); 10420b57cec5SDimitry Andric BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight; 10430b57cec5SDimitry Andric BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight; 10440b57cec5SDimitry Andric if (BestAScore < BestBScore) 10450b57cec5SDimitry Andric BestA = SecondBestA; 10460b57cec5SDimitry Andric else 10470b57cec5SDimitry Andric BestB = SecondBestB; 10480b57cec5SDimitry Andric } 10490b57cec5SDimitry Andric // Arrange for the BB edge to be in BestA if it exists. 10500b57cec5SDimitry Andric if (BestB->Src == BB) 10510b57cec5SDimitry Andric std::swap(BestA, BestB); 10520b57cec5SDimitry Andric return std::make_pair(*BestA, *BestB); 10530b57cec5SDimitry Andric } 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric /// Get the best successor from \p BB based on \p BB being part of a trellis. 10560b57cec5SDimitry Andric /// We only handle trellises with 2 successors, so the algorithm is 10570b57cec5SDimitry Andric /// straightforward: Find the best pair of edges that don't conflict. We find 10580b57cec5SDimitry Andric /// the best incoming edge for each successor in the trellis. If those conflict, 10590b57cec5SDimitry Andric /// we consider which of them should be replaced with the second best. 10600b57cec5SDimitry Andric /// Upon return the two best edges will be in \p BestEdges. If one of the edges 10610b57cec5SDimitry Andric /// comes from \p BB, it will be in \p BestEdges[0] 10620b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 10630b57cec5SDimitry Andric MachineBlockPlacement::getBestTrellisSuccessor( 10640b57cec5SDimitry Andric const MachineBasicBlock *BB, 10650b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 10660b57cec5SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 10670b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 10680b57cec5SDimitry Andric 10690b57cec5SDimitry Andric BlockAndTailDupResult Result = {nullptr, false}; 10700b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 10710b57cec5SDimitry Andric BB->succ_end()); 10720b57cec5SDimitry Andric 10730b57cec5SDimitry Andric // We assume size 2 because it's common. For general n, we would have to do 10740b57cec5SDimitry Andric // the Hungarian algorithm, but it's not worth the complexity because more 10750b57cec5SDimitry Andric // than 2 successors is fairly uncommon, and a trellis even more so. 10760b57cec5SDimitry Andric if (Successors.size() != 2 || ViableSuccs.size() != 2) 10770b57cec5SDimitry Andric return Result; 10780b57cec5SDimitry Andric 10790b57cec5SDimitry Andric // Collect the edge frequencies of all edges that form the trellis. 10800b57cec5SDimitry Andric SmallVector<WeightedEdge, 8> Edges[2]; 10810b57cec5SDimitry Andric int SuccIndex = 0; 1082fcaf7f86SDimitry Andric for (auto *Succ : ViableSuccs) { 10830b57cec5SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 10840b57cec5SDimitry Andric // Skip any placed predecessors that are not BB 10850b57cec5SDimitry Andric if (SuccPred != BB) 10860b57cec5SDimitry Andric if ((BlockFilter && !BlockFilter->count(SuccPred)) || 10870b57cec5SDimitry Andric BlockToChain[SuccPred] == &Chain || 10880b57cec5SDimitry Andric BlockToChain[SuccPred] == BlockToChain[Succ]) 10890b57cec5SDimitry Andric continue; 10900b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) * 10910b57cec5SDimitry Andric MBPI->getEdgeProbability(SuccPred, Succ); 10920b57cec5SDimitry Andric Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ}); 10930b57cec5SDimitry Andric } 10940b57cec5SDimitry Andric ++SuccIndex; 10950b57cec5SDimitry Andric } 10960b57cec5SDimitry Andric 10970b57cec5SDimitry Andric // Pick the best combination of 2 edges from all the edges in the trellis. 10980b57cec5SDimitry Andric WeightedEdge BestA, BestB; 10990b57cec5SDimitry Andric std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges); 11000b57cec5SDimitry Andric 11010b57cec5SDimitry Andric if (BestA.Src != BB) { 11020b57cec5SDimitry Andric // If we have a trellis, and BB doesn't have the best fallthrough edges, 11030b57cec5SDimitry Andric // we shouldn't choose any successor. We've already looked and there's a 11040b57cec5SDimitry Andric // better fallthrough edge for all the successors. 11050b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n"); 11060b57cec5SDimitry Andric return Result; 11070b57cec5SDimitry Andric } 11080b57cec5SDimitry Andric 11090b57cec5SDimitry Andric // Did we pick the triangle edge? If tail-duplication is profitable, do 11100b57cec5SDimitry Andric // that instead. Otherwise merge the triangle edge now while we know it is 11110b57cec5SDimitry Andric // optimal. 11120b57cec5SDimitry Andric if (BestA.Dest == BestB.Src) { 11130b57cec5SDimitry Andric // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2 11140b57cec5SDimitry Andric // would be better. 11150b57cec5SDimitry Andric MachineBasicBlock *Succ1 = BestA.Dest; 11160b57cec5SDimitry Andric MachineBasicBlock *Succ2 = BestB.Dest; 11170b57cec5SDimitry Andric // Check to see if tail-duplication would be profitable. 11180b57cec5SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) && 11190b57cec5SDimitry Andric canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) && 11200b57cec5SDimitry Andric isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1), 11210b57cec5SDimitry Andric Chain, BlockFilter)) { 11220b57cec5SDimitry Andric LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability( 11230b57cec5SDimitry Andric MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb); 11240b57cec5SDimitry Andric dbgs() << " Selected: " << getBlockName(Succ2) 11250b57cec5SDimitry Andric << ", probability: " << Succ2Prob 11260b57cec5SDimitry Andric << " (Tail Duplicate)\n"); 11270b57cec5SDimitry Andric Result.BB = Succ2; 11280b57cec5SDimitry Andric Result.ShouldTailDup = true; 11290b57cec5SDimitry Andric return Result; 11300b57cec5SDimitry Andric } 11310b57cec5SDimitry Andric } 11320b57cec5SDimitry Andric // We have already computed the optimal edge for the other side of the 11330b57cec5SDimitry Andric // trellis. 11340b57cec5SDimitry Andric ComputedEdges[BestB.Src] = { BestB.Dest, false }; 11350b57cec5SDimitry Andric 11360b57cec5SDimitry Andric auto TrellisSucc = BestA.Dest; 11370b57cec5SDimitry Andric LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability( 11380b57cec5SDimitry Andric MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb); 11390b57cec5SDimitry Andric dbgs() << " Selected: " << getBlockName(TrellisSucc) 11400b57cec5SDimitry Andric << ", probability: " << SuccProb << " (Trellis)\n"); 11410b57cec5SDimitry Andric Result.BB = TrellisSucc; 11420b57cec5SDimitry Andric return Result; 11430b57cec5SDimitry Andric } 11440b57cec5SDimitry Andric 11450b57cec5SDimitry Andric /// When the option allowTailDupPlacement() is on, this method checks if the 11460b57cec5SDimitry Andric /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated 11470b57cec5SDimitry Andric /// into all of its unplaced, unfiltered predecessors, that are not BB. 11480b57cec5SDimitry Andric bool MachineBlockPlacement::canTailDuplicateUnplacedPreds( 11490b57cec5SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 11500b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 11510b57cec5SDimitry Andric if (!shouldTailDuplicate(Succ)) 11520b57cec5SDimitry Andric return false; 11530b57cec5SDimitry Andric 1154480093f4SDimitry Andric // The result of canTailDuplicate. 1155480093f4SDimitry Andric bool Duplicate = true; 1156480093f4SDimitry Andric // Number of possible duplication. 1157480093f4SDimitry Andric unsigned int NumDup = 0; 1158480093f4SDimitry Andric 11590b57cec5SDimitry Andric // For CFG checking. 11600b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 11610b57cec5SDimitry Andric BB->succ_end()); 11620b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 11630b57cec5SDimitry Andric // Make sure all unplaced and unfiltered predecessors can be 11640b57cec5SDimitry Andric // tail-duplicated into. 11650b57cec5SDimitry Andric // Skip any blocks that are already placed or not in this loop. 11660b57cec5SDimitry Andric if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) 116706c3fb27SDimitry Andric || (BlockToChain[Pred] == &Chain && !Succ->succ_empty())) 11680b57cec5SDimitry Andric continue; 11690b57cec5SDimitry Andric if (!TailDup.canTailDuplicate(Succ, Pred)) { 11700b57cec5SDimitry Andric if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors)) 11710b57cec5SDimitry Andric // This will result in a trellis after tail duplication, so we don't 11720b57cec5SDimitry Andric // need to copy Succ into this predecessor. In the presence 11730b57cec5SDimitry Andric // of a trellis tail duplication can continue to be profitable. 11740b57cec5SDimitry Andric // For example: 11750b57cec5SDimitry Andric // A A 11760b57cec5SDimitry Andric // |\ |\ 11770b57cec5SDimitry Andric // | \ | \ 11780b57cec5SDimitry Andric // | C | C+BB 11790b57cec5SDimitry Andric // | / | | 11800b57cec5SDimitry Andric // |/ | | 11810b57cec5SDimitry Andric // BB => BB | 11820b57cec5SDimitry Andric // |\ |\/| 11830b57cec5SDimitry Andric // | \ |/\| 11840b57cec5SDimitry Andric // | D | D 11850b57cec5SDimitry Andric // | / | / 11860b57cec5SDimitry Andric // |/ |/ 11870b57cec5SDimitry Andric // Succ Succ 11880b57cec5SDimitry Andric // 11890b57cec5SDimitry Andric // After BB was duplicated into C, the layout looks like the one on the 11900b57cec5SDimitry Andric // right. BB and C now have the same successors. When considering 11910b57cec5SDimitry Andric // whether Succ can be duplicated into all its unplaced predecessors, we 11920b57cec5SDimitry Andric // ignore C. 11930b57cec5SDimitry Andric // We can do this because C already has a profitable fallthrough, namely 11940b57cec5SDimitry Andric // D. TODO(iteratee): ignore sufficiently cold predecessors for 11950b57cec5SDimitry Andric // duplication and for this test. 11960b57cec5SDimitry Andric // 11970b57cec5SDimitry Andric // This allows trellises to be laid out in 2 separate chains 11980b57cec5SDimitry Andric // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic 11990b57cec5SDimitry Andric // because it allows the creation of 2 fallthrough paths with links 12000b57cec5SDimitry Andric // between them, and we correctly identify the best layout for these 12010b57cec5SDimitry Andric // CFGs. We want to extend trellises that the user created in addition 12020b57cec5SDimitry Andric // to trellises created by tail-duplication, so we just look for the 12030b57cec5SDimitry Andric // CFG. 12040b57cec5SDimitry Andric continue; 1205480093f4SDimitry Andric Duplicate = false; 1206480093f4SDimitry Andric continue; 1207480093f4SDimitry Andric } 1208480093f4SDimitry Andric NumDup++; 1209480093f4SDimitry Andric } 1210480093f4SDimitry Andric 1211480093f4SDimitry Andric // No possible duplication in current filter set. 1212480093f4SDimitry Andric if (NumDup == 0) 12130b57cec5SDimitry Andric return false; 1214480093f4SDimitry Andric 12155ffd83dbSDimitry Andric // If profile information is available, findDuplicateCandidates can do more 12165ffd83dbSDimitry Andric // precise benefit analysis. 12175ffd83dbSDimitry Andric if (F->getFunction().hasProfileData()) 12185ffd83dbSDimitry Andric return true; 12195ffd83dbSDimitry Andric 1220480093f4SDimitry Andric // This is mainly for function exit BB. 1221480093f4SDimitry Andric // The integrated tail duplication is really designed for increasing 1222480093f4SDimitry Andric // fallthrough from predecessors from Succ to its successors. We may need 1223480093f4SDimitry Andric // other machanism to handle different cases. 1224349cc55cSDimitry Andric if (Succ->succ_empty()) 1225480093f4SDimitry Andric return true; 1226480093f4SDimitry Andric 1227480093f4SDimitry Andric // Plus the already placed predecessor. 1228480093f4SDimitry Andric NumDup++; 1229480093f4SDimitry Andric 1230480093f4SDimitry Andric // If the duplication candidate has more unplaced predecessors than 1231480093f4SDimitry Andric // successors, the extra duplication can't bring more fallthrough. 1232480093f4SDimitry Andric // 1233480093f4SDimitry Andric // Pred1 Pred2 Pred3 1234480093f4SDimitry Andric // \ | / 1235480093f4SDimitry Andric // \ | / 1236480093f4SDimitry Andric // \ | / 1237480093f4SDimitry Andric // Dup 1238480093f4SDimitry Andric // / \ 1239480093f4SDimitry Andric // / \ 1240480093f4SDimitry Andric // Succ1 Succ2 1241480093f4SDimitry Andric // 1242480093f4SDimitry Andric // In this example Dup has 2 successors and 3 predecessors, duplication of Dup 1243480093f4SDimitry Andric // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2, 1244480093f4SDimitry Andric // but the duplication into Pred3 can't increase fallthrough. 1245480093f4SDimitry Andric // 1246480093f4SDimitry Andric // A small number of extra duplication may not hurt too much. We need a better 1247480093f4SDimitry Andric // heuristic to handle it. 1248480093f4SDimitry Andric if ((NumDup > Succ->succ_size()) || !Duplicate) 1249480093f4SDimitry Andric return false; 1250480093f4SDimitry Andric 12510b57cec5SDimitry Andric return true; 12520b57cec5SDimitry Andric } 12530b57cec5SDimitry Andric 12540b57cec5SDimitry Andric /// Find chains of triangles where we believe it would be profitable to 12550b57cec5SDimitry Andric /// tail-duplicate them all, but a local analysis would not find them. 12560b57cec5SDimitry Andric /// There are 3 ways this can be profitable: 12570b57cec5SDimitry Andric /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with 12580b57cec5SDimitry Andric /// longer chains) 12590b57cec5SDimitry Andric /// 2) The chains are statically correlated. Branch probabilities have a very 12600b57cec5SDimitry Andric /// U-shaped distribution. 12610b57cec5SDimitry Andric /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805] 12620b57cec5SDimitry Andric /// If the branches in a chain are likely to be from the same side of the 12630b57cec5SDimitry Andric /// distribution as their predecessor, but are independent at runtime, this 12640b57cec5SDimitry Andric /// transformation is profitable. (Because the cost of being wrong is a small 12650b57cec5SDimitry Andric /// fixed cost, unlike the standard triangle layout where the cost of being 12660b57cec5SDimitry Andric /// wrong scales with the # of triangles.) 12670b57cec5SDimitry Andric /// 3) The chains are dynamically correlated. If the probability that a previous 12680b57cec5SDimitry Andric /// branch was taken positively influences whether the next branch will be 12690b57cec5SDimitry Andric /// taken 12700b57cec5SDimitry Andric /// We believe that 2 and 3 are common enough to justify the small margin in 1. 12710b57cec5SDimitry Andric void MachineBlockPlacement::precomputeTriangleChains() { 12720b57cec5SDimitry Andric struct TriangleChain { 12730b57cec5SDimitry Andric std::vector<MachineBasicBlock *> Edges; 12740b57cec5SDimitry Andric 12750b57cec5SDimitry Andric TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst) 12760b57cec5SDimitry Andric : Edges({src, dst}) {} 12770b57cec5SDimitry Andric 12780b57cec5SDimitry Andric void append(MachineBasicBlock *dst) { 12790b57cec5SDimitry Andric assert(getKey()->isSuccessor(dst) && 12800b57cec5SDimitry Andric "Attempting to append a block that is not a successor."); 12810b57cec5SDimitry Andric Edges.push_back(dst); 12820b57cec5SDimitry Andric } 12830b57cec5SDimitry Andric 12840b57cec5SDimitry Andric unsigned count() const { return Edges.size() - 1; } 12850b57cec5SDimitry Andric 12860b57cec5SDimitry Andric MachineBasicBlock *getKey() const { 12870b57cec5SDimitry Andric return Edges.back(); 12880b57cec5SDimitry Andric } 12890b57cec5SDimitry Andric }; 12900b57cec5SDimitry Andric 12910b57cec5SDimitry Andric if (TriangleChainCount == 0) 12920b57cec5SDimitry Andric return; 12930b57cec5SDimitry Andric 12940b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n"); 12950b57cec5SDimitry Andric // Map from last block to the chain that contains it. This allows us to extend 12960b57cec5SDimitry Andric // chains as we find new triangles. 12970b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap; 12980b57cec5SDimitry Andric for (MachineBasicBlock &BB : *F) { 12990b57cec5SDimitry Andric // If BB doesn't have 2 successors, it doesn't start a triangle. 13000b57cec5SDimitry Andric if (BB.succ_size() != 2) 13010b57cec5SDimitry Andric continue; 13020b57cec5SDimitry Andric MachineBasicBlock *PDom = nullptr; 13030b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) { 13040b57cec5SDimitry Andric if (!MPDT->dominates(Succ, &BB)) 13050b57cec5SDimitry Andric continue; 13060b57cec5SDimitry Andric PDom = Succ; 13070b57cec5SDimitry Andric break; 13080b57cec5SDimitry Andric } 13090b57cec5SDimitry Andric // If BB doesn't have a post-dominating successor, it doesn't form a 13100b57cec5SDimitry Andric // triangle. 13110b57cec5SDimitry Andric if (PDom == nullptr) 13120b57cec5SDimitry Andric continue; 13130b57cec5SDimitry Andric // If PDom has a hint that it is low probability, skip this triangle. 13140b57cec5SDimitry Andric if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100)) 13150b57cec5SDimitry Andric continue; 13160b57cec5SDimitry Andric // If PDom isn't eligible for duplication, this isn't the kind of triangle 13170b57cec5SDimitry Andric // we're looking for. 13180b57cec5SDimitry Andric if (!shouldTailDuplicate(PDom)) 13190b57cec5SDimitry Andric continue; 13200b57cec5SDimitry Andric bool CanTailDuplicate = true; 13210b57cec5SDimitry Andric // If PDom can't tail-duplicate into it's non-BB predecessors, then this 13220b57cec5SDimitry Andric // isn't the kind of triangle we're looking for. 13230b57cec5SDimitry Andric for (MachineBasicBlock* Pred : PDom->predecessors()) { 13240b57cec5SDimitry Andric if (Pred == &BB) 13250b57cec5SDimitry Andric continue; 13260b57cec5SDimitry Andric if (!TailDup.canTailDuplicate(PDom, Pred)) { 13270b57cec5SDimitry Andric CanTailDuplicate = false; 13280b57cec5SDimitry Andric break; 13290b57cec5SDimitry Andric } 13300b57cec5SDimitry Andric } 13310b57cec5SDimitry Andric // If we can't tail-duplicate PDom to its predecessors, then skip this 13320b57cec5SDimitry Andric // triangle. 13330b57cec5SDimitry Andric if (!CanTailDuplicate) 13340b57cec5SDimitry Andric continue; 13350b57cec5SDimitry Andric 13360b57cec5SDimitry Andric // Now we have an interesting triangle. Insert it if it's not part of an 13370b57cec5SDimitry Andric // existing chain. 13380b57cec5SDimitry Andric // Note: This cannot be replaced with a call insert() or emplace() because 13390b57cec5SDimitry Andric // the find key is BB, but the insert/emplace key is PDom. 13400b57cec5SDimitry Andric auto Found = TriangleChainMap.find(&BB); 13410b57cec5SDimitry Andric // If it is, remove the chain from the map, grow it, and put it back in the 13420b57cec5SDimitry Andric // map with the end as the new key. 13430b57cec5SDimitry Andric if (Found != TriangleChainMap.end()) { 13440b57cec5SDimitry Andric TriangleChain Chain = std::move(Found->second); 13450b57cec5SDimitry Andric TriangleChainMap.erase(Found); 13460b57cec5SDimitry Andric Chain.append(PDom); 13470b57cec5SDimitry Andric TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain))); 13480b57cec5SDimitry Andric } else { 13490b57cec5SDimitry Andric auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom); 13500b57cec5SDimitry Andric assert(InsertResult.second && "Block seen twice."); 13510b57cec5SDimitry Andric (void)InsertResult; 13520b57cec5SDimitry Andric } 13530b57cec5SDimitry Andric } 13540b57cec5SDimitry Andric 13550b57cec5SDimitry Andric // Iterating over a DenseMap is safe here, because the only thing in the body 13560b57cec5SDimitry Andric // of the loop is inserting into another DenseMap (ComputedEdges). 13570b57cec5SDimitry Andric // ComputedEdges is never iterated, so this doesn't lead to non-determinism. 13580b57cec5SDimitry Andric for (auto &ChainPair : TriangleChainMap) { 13590b57cec5SDimitry Andric TriangleChain &Chain = ChainPair.second; 13600b57cec5SDimitry Andric // Benchmarking has shown that due to branch correlation duplicating 2 or 13610b57cec5SDimitry Andric // more triangles is profitable, despite the calculations assuming 13620b57cec5SDimitry Andric // independence. 13630b57cec5SDimitry Andric if (Chain.count() < TriangleChainCount) 13640b57cec5SDimitry Andric continue; 13650b57cec5SDimitry Andric MachineBasicBlock *dst = Chain.Edges.back(); 13660b57cec5SDimitry Andric Chain.Edges.pop_back(); 13670b57cec5SDimitry Andric for (MachineBasicBlock *src : reverse(Chain.Edges)) { 13680b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" 13690b57cec5SDimitry Andric << getBlockName(dst) 13700b57cec5SDimitry Andric << " as pre-computed based on triangles.\n"); 13710b57cec5SDimitry Andric 13720b57cec5SDimitry Andric auto InsertResult = ComputedEdges.insert({src, {dst, true}}); 13730b57cec5SDimitry Andric assert(InsertResult.second && "Block seen twice."); 13740b57cec5SDimitry Andric (void)InsertResult; 13750b57cec5SDimitry Andric 13760b57cec5SDimitry Andric dst = src; 13770b57cec5SDimitry Andric } 13780b57cec5SDimitry Andric } 13790b57cec5SDimitry Andric } 13800b57cec5SDimitry Andric 13810b57cec5SDimitry Andric // When profile is not present, return the StaticLikelyProb. 13820b57cec5SDimitry Andric // When profile is available, we need to handle the triangle-shape CFG. 13830b57cec5SDimitry Andric static BranchProbability getLayoutSuccessorProbThreshold( 13840b57cec5SDimitry Andric const MachineBasicBlock *BB) { 13850b57cec5SDimitry Andric if (!BB->getParent()->getFunction().hasProfileData()) 13860b57cec5SDimitry Andric return BranchProbability(StaticLikelyProb, 100); 13870b57cec5SDimitry Andric if (BB->succ_size() == 2) { 13880b57cec5SDimitry Andric const MachineBasicBlock *Succ1 = *BB->succ_begin(); 13890b57cec5SDimitry Andric const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 13900b57cec5SDimitry Andric if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 13910b57cec5SDimitry Andric /* See case 1 below for the cost analysis. For BB->Succ to 13920b57cec5SDimitry Andric * be taken with smaller cost, the following needs to hold: 13930b57cec5SDimitry Andric * Prob(BB->Succ) > 2 * Prob(BB->Pred) 13940b57cec5SDimitry Andric * So the threshold T in the calculation below 13950b57cec5SDimitry Andric * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred) 13960b57cec5SDimitry Andric * So T / (1 - T) = 2, Yielding T = 2/3 13970b57cec5SDimitry Andric * Also adding user specified branch bias, we have 13980b57cec5SDimitry Andric * T = (2/3)*(ProfileLikelyProb/50) 13990b57cec5SDimitry Andric * = (2*ProfileLikelyProb)/150) 14000b57cec5SDimitry Andric */ 14010b57cec5SDimitry Andric return BranchProbability(2 * ProfileLikelyProb, 150); 14020b57cec5SDimitry Andric } 14030b57cec5SDimitry Andric } 14040b57cec5SDimitry Andric return BranchProbability(ProfileLikelyProb, 100); 14050b57cec5SDimitry Andric } 14060b57cec5SDimitry Andric 14070b57cec5SDimitry Andric /// Checks to see if the layout candidate block \p Succ has a better layout 14080b57cec5SDimitry Andric /// predecessor than \c BB. If yes, returns true. 14090b57cec5SDimitry Andric /// \p SuccProb: The probability adjusted for only remaining blocks. 14100b57cec5SDimitry Andric /// Only used for logging 14110b57cec5SDimitry Andric /// \p RealSuccProb: The un-adjusted probability. 14120b57cec5SDimitry Andric /// \p Chain: The chain that BB belongs to and Succ is being considered for. 14130b57cec5SDimitry Andric /// \p BlockFilter: if non-null, the set of blocks that make up the loop being 14140b57cec5SDimitry Andric /// considered 14150b57cec5SDimitry Andric bool MachineBlockPlacement::hasBetterLayoutPredecessor( 14160b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 14170b57cec5SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 14180b57cec5SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 14190b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 14200b57cec5SDimitry Andric 14210b57cec5SDimitry Andric // There isn't a better layout when there are no unscheduled predecessors. 14220b57cec5SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0) 14230b57cec5SDimitry Andric return false; 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric // There are two basic scenarios here: 14260b57cec5SDimitry Andric // ------------------------------------- 14270b57cec5SDimitry Andric // Case 1: triangular shape CFG (if-then): 14280b57cec5SDimitry Andric // BB 14290b57cec5SDimitry Andric // | \ 14300b57cec5SDimitry Andric // | \ 14310b57cec5SDimitry Andric // | Pred 14320b57cec5SDimitry Andric // | / 14330b57cec5SDimitry Andric // Succ 14340b57cec5SDimitry Andric // In this case, we are evaluating whether to select edge -> Succ, e.g. 14350b57cec5SDimitry Andric // set Succ as the layout successor of BB. Picking Succ as BB's 14360b57cec5SDimitry Andric // successor breaks the CFG constraints (FIXME: define these constraints). 14370b57cec5SDimitry Andric // With this layout, Pred BB 14380b57cec5SDimitry Andric // is forced to be outlined, so the overall cost will be cost of the 14390b57cec5SDimitry Andric // branch taken from BB to Pred, plus the cost of back taken branch 14400b57cec5SDimitry Andric // from Pred to Succ, as well as the additional cost associated 14410b57cec5SDimitry Andric // with the needed unconditional jump instruction from Pred To Succ. 14420b57cec5SDimitry Andric 14430b57cec5SDimitry Andric // The cost of the topological order layout is the taken branch cost 14440b57cec5SDimitry Andric // from BB to Succ, so to make BB->Succ a viable candidate, the following 14450b57cec5SDimitry Andric // must hold: 14460b57cec5SDimitry Andric // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 14470b57cec5SDimitry Andric // < freq(BB->Succ) * taken_branch_cost. 14480b57cec5SDimitry Andric // Ignoring unconditional jump cost, we get 14490b57cec5SDimitry Andric // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 14500b57cec5SDimitry Andric // prob(BB->Succ) > 2 * prob(BB->Pred) 14510b57cec5SDimitry Andric // 14520b57cec5SDimitry Andric // When real profile data is available, we can precisely compute the 14530b57cec5SDimitry Andric // probability threshold that is needed for edge BB->Succ to be considered. 14540b57cec5SDimitry Andric // Without profile data, the heuristic requires the branch bias to be 14550b57cec5SDimitry Andric // a lot larger to make sure the signal is very strong (e.g. 80% default). 14560b57cec5SDimitry Andric // ----------------------------------------------------------------- 14570b57cec5SDimitry Andric // Case 2: diamond like CFG (if-then-else): 14580b57cec5SDimitry Andric // S 14590b57cec5SDimitry Andric // / \ 14600b57cec5SDimitry Andric // | \ 14610b57cec5SDimitry Andric // BB Pred 14620b57cec5SDimitry Andric // \ / 14630b57cec5SDimitry Andric // Succ 14640b57cec5SDimitry Andric // .. 14650b57cec5SDimitry Andric // 14660b57cec5SDimitry Andric // The current block is BB and edge BB->Succ is now being evaluated. 14670b57cec5SDimitry Andric // Note that edge S->BB was previously already selected because 14680b57cec5SDimitry Andric // prob(S->BB) > prob(S->Pred). 14690b57cec5SDimitry Andric // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 14700b57cec5SDimitry Andric // choose Pred, we will have a topological ordering as shown on the left 14710b57cec5SDimitry Andric // in the picture below. If we choose Succ, we have the solution as shown 14720b57cec5SDimitry Andric // on the right: 14730b57cec5SDimitry Andric // 14740b57cec5SDimitry Andric // topo-order: 14750b57cec5SDimitry Andric // 14760b57cec5SDimitry Andric // S----- ---S 14770b57cec5SDimitry Andric // | | | | 14780b57cec5SDimitry Andric // ---BB | | BB 14790b57cec5SDimitry Andric // | | | | 14800b57cec5SDimitry Andric // | Pred-- | Succ-- 14810b57cec5SDimitry Andric // | | | | 14820b57cec5SDimitry Andric // ---Succ ---Pred-- 14830b57cec5SDimitry Andric // 14840b57cec5SDimitry Andric // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 14850b57cec5SDimitry Andric // = freq(S->Pred) + freq(S->BB) 14860b57cec5SDimitry Andric // 14870b57cec5SDimitry Andric // If we have profile data (i.e, branch probabilities can be trusted), the 14880b57cec5SDimitry Andric // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 14890b57cec5SDimitry Andric // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 14900b57cec5SDimitry Andric // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 14910b57cec5SDimitry Andric // means the cost of topological order is greater. 14920b57cec5SDimitry Andric // When profile data is not available, however, we need to be more 14930b57cec5SDimitry Andric // conservative. If the branch prediction is wrong, breaking the topo-order 14940b57cec5SDimitry Andric // will actually yield a layout with large cost. For this reason, we need 14950b57cec5SDimitry Andric // strong biased branch at block S with Prob(S->BB) in order to select 14960b57cec5SDimitry Andric // BB->Succ. This is equivalent to looking the CFG backward with backward 14970b57cec5SDimitry Andric // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 14980b57cec5SDimitry Andric // profile data). 14990b57cec5SDimitry Andric // -------------------------------------------------------------------------- 15000b57cec5SDimitry Andric // Case 3: forked diamond 15010b57cec5SDimitry Andric // S 15020b57cec5SDimitry Andric // / \ 15030b57cec5SDimitry Andric // / \ 15040b57cec5SDimitry Andric // BB Pred 15050b57cec5SDimitry Andric // | \ / | 15060b57cec5SDimitry Andric // | \ / | 15070b57cec5SDimitry Andric // | X | 15080b57cec5SDimitry Andric // | / \ | 15090b57cec5SDimitry Andric // | / \ | 15100b57cec5SDimitry Andric // S1 S2 15110b57cec5SDimitry Andric // 15120b57cec5SDimitry Andric // The current block is BB and edge BB->S1 is now being evaluated. 15130b57cec5SDimitry Andric // As above S->BB was already selected because 15140b57cec5SDimitry Andric // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 15150b57cec5SDimitry Andric // 15160b57cec5SDimitry Andric // topo-order: 15170b57cec5SDimitry Andric // 15180b57cec5SDimitry Andric // S-------| ---S 15190b57cec5SDimitry Andric // | | | | 15200b57cec5SDimitry Andric // ---BB | | BB 15210b57cec5SDimitry Andric // | | | | 15220b57cec5SDimitry Andric // | Pred----| | S1---- 15230b57cec5SDimitry Andric // | | | | 15240b57cec5SDimitry Andric // --(S1 or S2) ---Pred-- 15250b57cec5SDimitry Andric // | 15260b57cec5SDimitry Andric // S2 15270b57cec5SDimitry Andric // 15280b57cec5SDimitry Andric // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 15290b57cec5SDimitry Andric // + min(freq(Pred->S1), freq(Pred->S2)) 15300b57cec5SDimitry Andric // Non-topo-order cost: 15310b57cec5SDimitry Andric // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 15320b57cec5SDimitry Andric // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 15330b57cec5SDimitry Andric // is 0. Then the non topo layout is better when 15340b57cec5SDimitry Andric // freq(S->Pred) < freq(BB->S1). 15350b57cec5SDimitry Andric // This is exactly what is checked below. 15360b57cec5SDimitry Andric // Note there are other shapes that apply (Pred may not be a single block, 15370b57cec5SDimitry Andric // but they all fit this general pattern.) 15380b57cec5SDimitry Andric BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 15390b57cec5SDimitry Andric 15400b57cec5SDimitry Andric // Make sure that a hot successor doesn't have a globally more 15410b57cec5SDimitry Andric // important predecessor. 15420b57cec5SDimitry Andric BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 15430b57cec5SDimitry Andric bool BadCFGConflict = false; 15440b57cec5SDimitry Andric 15450b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 1546480093f4SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 1547480093f4SDimitry Andric if (Pred == Succ || PredChain == &SuccChain || 15480b57cec5SDimitry Andric (BlockFilter && !BlockFilter->count(Pred)) || 1549480093f4SDimitry Andric PredChain == &Chain || Pred != *std::prev(PredChain->end()) || 15500b57cec5SDimitry Andric // This check is redundant except for look ahead. This function is 15510b57cec5SDimitry Andric // called for lookahead by isProfitableToTailDup when BB hasn't been 15520b57cec5SDimitry Andric // placed yet. 15530b57cec5SDimitry Andric (Pred == BB)) 15540b57cec5SDimitry Andric continue; 15550b57cec5SDimitry Andric // Do backward checking. 15560b57cec5SDimitry Andric // For all cases above, we need a backward checking to filter out edges that 15570b57cec5SDimitry Andric // are not 'strongly' biased. 15580b57cec5SDimitry Andric // BB Pred 15590b57cec5SDimitry Andric // \ / 15600b57cec5SDimitry Andric // Succ 15610b57cec5SDimitry Andric // We select edge BB->Succ if 15620b57cec5SDimitry Andric // freq(BB->Succ) > freq(Succ) * HotProb 15630b57cec5SDimitry Andric // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 15640b57cec5SDimitry Andric // HotProb 15650b57cec5SDimitry Andric // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 15660b57cec5SDimitry Andric // Case 1 is covered too, because the first equation reduces to: 15670b57cec5SDimitry Andric // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 15680b57cec5SDimitry Andric BlockFrequency PredEdgeFreq = 15690b57cec5SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 15700b57cec5SDimitry Andric if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 15710b57cec5SDimitry Andric BadCFGConflict = true; 15720b57cec5SDimitry Andric break; 15730b57cec5SDimitry Andric } 15740b57cec5SDimitry Andric } 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric if (BadCFGConflict) { 15770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " 15780b57cec5SDimitry Andric << SuccProb << " (prob) (non-cold CFG conflict)\n"); 15790b57cec5SDimitry Andric return true; 15800b57cec5SDimitry Andric } 15810b57cec5SDimitry Andric 15820b57cec5SDimitry Andric return false; 15830b57cec5SDimitry Andric } 15840b57cec5SDimitry Andric 15850b57cec5SDimitry Andric /// Select the best successor for a block. 15860b57cec5SDimitry Andric /// 15870b57cec5SDimitry Andric /// This looks across all successors of a particular block and attempts to 15880b57cec5SDimitry Andric /// select the "best" one to be the layout successor. It only considers direct 15890b57cec5SDimitry Andric /// successors which also pass the block filter. It will attempt to avoid 15900b57cec5SDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of 15910b57cec5SDimitry Andric /// very hot successor edges. 15920b57cec5SDimitry Andric /// 15930b57cec5SDimitry Andric /// \returns The best successor block found, or null if none are viable, along 15940b57cec5SDimitry Andric /// with a boolean indicating if tail duplication is necessary. 15950b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 15960b57cec5SDimitry Andric MachineBlockPlacement::selectBestSuccessor( 15970b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 15980b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 15990b57cec5SDimitry Andric const BranchProbability HotProb(StaticLikelyProb, 100); 16000b57cec5SDimitry Andric 16010b57cec5SDimitry Andric BlockAndTailDupResult BestSucc = { nullptr, false }; 16020b57cec5SDimitry Andric auto BestProb = BranchProbability::getZero(); 16030b57cec5SDimitry Andric 16040b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> Successors; 16050b57cec5SDimitry Andric auto AdjustedSumProb = 16060b57cec5SDimitry Andric collectViableSuccessors(BB, Chain, BlockFilter, Successors); 16070b57cec5SDimitry Andric 16080b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) 16090b57cec5SDimitry Andric << "\n"); 16100b57cec5SDimitry Andric 16110b57cec5SDimitry Andric // if we already precomputed the best successor for BB, return that if still 16120b57cec5SDimitry Andric // applicable. 16130b57cec5SDimitry Andric auto FoundEdge = ComputedEdges.find(BB); 16140b57cec5SDimitry Andric if (FoundEdge != ComputedEdges.end()) { 16150b57cec5SDimitry Andric MachineBasicBlock *Succ = FoundEdge->second.BB; 16160b57cec5SDimitry Andric ComputedEdges.erase(FoundEdge); 16170b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 16180b57cec5SDimitry Andric if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) && 16190b57cec5SDimitry Andric SuccChain != &Chain && Succ == *SuccChain->begin()) 16200b57cec5SDimitry Andric return FoundEdge->second; 16210b57cec5SDimitry Andric } 16220b57cec5SDimitry Andric 16230b57cec5SDimitry Andric // if BB is part of a trellis, Use the trellis to determine the optimal 16240b57cec5SDimitry Andric // fallthrough edges 16250b57cec5SDimitry Andric if (isTrellis(BB, Successors, Chain, BlockFilter)) 16260b57cec5SDimitry Andric return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain, 16270b57cec5SDimitry Andric BlockFilter); 16280b57cec5SDimitry Andric 16290b57cec5SDimitry Andric // For blocks with CFG violations, we may be able to lay them out anyway with 16300b57cec5SDimitry Andric // tail-duplication. We keep this vector so we can perform the probability 16310b57cec5SDimitry Andric // calculations the minimum number of times. 16325ffd83dbSDimitry Andric SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4> 16330b57cec5SDimitry Andric DupCandidates; 16340b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Successors) { 16350b57cec5SDimitry Andric auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 16360b57cec5SDimitry Andric BranchProbability SuccProb = 16370b57cec5SDimitry Andric getAdjustedProbability(RealSuccProb, AdjustedSumProb); 16380b57cec5SDimitry Andric 16390b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 16400b57cec5SDimitry Andric // Skip the edge \c BB->Succ if block \c Succ has a better layout 16410b57cec5SDimitry Andric // predecessor that yields lower global cost. 16420b57cec5SDimitry Andric if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 16430b57cec5SDimitry Andric Chain, BlockFilter)) { 16440b57cec5SDimitry Andric // If tail duplication would make Succ profitable, place it. 16450b57cec5SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ)) 16465ffd83dbSDimitry Andric DupCandidates.emplace_back(SuccProb, Succ); 16470b57cec5SDimitry Andric continue; 16480b57cec5SDimitry Andric } 16490b57cec5SDimitry Andric 16500b57cec5SDimitry Andric LLVM_DEBUG( 16510b57cec5SDimitry Andric dbgs() << " Candidate: " << getBlockName(Succ) 16520b57cec5SDimitry Andric << ", probability: " << SuccProb 16530b57cec5SDimitry Andric << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 16540b57cec5SDimitry Andric << "\n"); 16550b57cec5SDimitry Andric 16560b57cec5SDimitry Andric if (BestSucc.BB && BestProb >= SuccProb) { 16570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n"); 16580b57cec5SDimitry Andric continue; 16590b57cec5SDimitry Andric } 16600b57cec5SDimitry Andric 16610b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Setting it as best candidate\n"); 16620b57cec5SDimitry Andric BestSucc.BB = Succ; 16630b57cec5SDimitry Andric BestProb = SuccProb; 16640b57cec5SDimitry Andric } 16650b57cec5SDimitry Andric // Handle the tail duplication candidates in order of decreasing probability. 16660b57cec5SDimitry Andric // Stop at the first one that is profitable. Also stop if they are less 16670b57cec5SDimitry Andric // profitable than BestSucc. Position is important because we preserve it and 16680b57cec5SDimitry Andric // prefer first best match. Here we aren't comparing in order, so we capture 16690b57cec5SDimitry Andric // the position instead. 16700b57cec5SDimitry Andric llvm::stable_sort(DupCandidates, 16710b57cec5SDimitry Andric [](std::tuple<BranchProbability, MachineBasicBlock *> L, 16720b57cec5SDimitry Andric std::tuple<BranchProbability, MachineBasicBlock *> R) { 16730b57cec5SDimitry Andric return std::get<0>(L) > std::get<0>(R); 16740b57cec5SDimitry Andric }); 16750b57cec5SDimitry Andric for (auto &Tup : DupCandidates) { 16760b57cec5SDimitry Andric BranchProbability DupProb; 16770b57cec5SDimitry Andric MachineBasicBlock *Succ; 16780b57cec5SDimitry Andric std::tie(DupProb, Succ) = Tup; 16790b57cec5SDimitry Andric if (DupProb < BestProb) 16800b57cec5SDimitry Andric break; 16810b57cec5SDimitry Andric if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) 16820b57cec5SDimitry Andric && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) { 16830b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ) 16840b57cec5SDimitry Andric << ", probability: " << DupProb 16850b57cec5SDimitry Andric << " (Tail Duplicate)\n"); 16860b57cec5SDimitry Andric BestSucc.BB = Succ; 16870b57cec5SDimitry Andric BestSucc.ShouldTailDup = true; 16880b57cec5SDimitry Andric break; 16890b57cec5SDimitry Andric } 16900b57cec5SDimitry Andric } 16910b57cec5SDimitry Andric 16920b57cec5SDimitry Andric if (BestSucc.BB) 16930b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n"); 16940b57cec5SDimitry Andric 16950b57cec5SDimitry Andric return BestSucc; 16960b57cec5SDimitry Andric } 16970b57cec5SDimitry Andric 16980b57cec5SDimitry Andric /// Select the best block from a worklist. 16990b57cec5SDimitry Andric /// 17000b57cec5SDimitry Andric /// This looks through the provided worklist as a list of candidate basic 17010b57cec5SDimitry Andric /// blocks and select the most profitable one to place. The definition of 17020b57cec5SDimitry Andric /// profitable only really makes sense in the context of a loop. This returns 17030b57cec5SDimitry Andric /// the most frequently visited block in the worklist, which in the case of 17040b57cec5SDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the 17050b57cec5SDimitry Andric /// loop body in order to improve i-cache behavior. 17060b57cec5SDimitry Andric /// 17070b57cec5SDimitry Andric /// \returns The best block found, or null if none are viable. 17080b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 17090b57cec5SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 17100b57cec5SDimitry Andric // Once we need to walk the worklist looking for a candidate, cleanup the 17110b57cec5SDimitry Andric // worklist of already placed entries. 17120b57cec5SDimitry Andric // FIXME: If this shows up on profiles, it could be folded (at the cost of 17130b57cec5SDimitry Andric // some code complexity) into the loop below. 1714e8d8bef9SDimitry Andric llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) { 17150b57cec5SDimitry Andric return BlockToChain.lookup(BB) == &Chain; 1716e8d8bef9SDimitry Andric }); 17170b57cec5SDimitry Andric 17180b57cec5SDimitry Andric if (WorkList.empty()) 17190b57cec5SDimitry Andric return nullptr; 17200b57cec5SDimitry Andric 17210b57cec5SDimitry Andric bool IsEHPad = WorkList[0]->isEHPad(); 17220b57cec5SDimitry Andric 17230b57cec5SDimitry Andric MachineBasicBlock *BestBlock = nullptr; 17240b57cec5SDimitry Andric BlockFrequency BestFreq; 17250b57cec5SDimitry Andric for (MachineBasicBlock *MBB : WorkList) { 17260b57cec5SDimitry Andric assert(MBB->isEHPad() == IsEHPad && 17270b57cec5SDimitry Andric "EHPad mismatch between block and work list."); 17280b57cec5SDimitry Andric 17290b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[MBB]; 17300b57cec5SDimitry Andric if (&SuccChain == &Chain) 17310b57cec5SDimitry Andric continue; 17320b57cec5SDimitry Andric 17330b57cec5SDimitry Andric assert(SuccChain.UnscheduledPredecessors == 0 && 17340b57cec5SDimitry Andric "Found CFG-violating block"); 17350b57cec5SDimitry Andric 17360b57cec5SDimitry Andric BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 17375f757f3fSDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> " 17385f757f3fSDimitry Andric << printBlockFreq(MBFI->getMBFI(), CandidateFreq) 17395f757f3fSDimitry Andric << " (freq)\n"); 17400b57cec5SDimitry Andric 17410b57cec5SDimitry Andric // For ehpad, we layout the least probable first as to avoid jumping back 17420b57cec5SDimitry Andric // from least probable landingpads to more probable ones. 17430b57cec5SDimitry Andric // 17440b57cec5SDimitry Andric // FIXME: Using probability is probably (!) not the best way to achieve 17450b57cec5SDimitry Andric // this. We should probably have a more principled approach to layout 17460b57cec5SDimitry Andric // cleanup code. 17470b57cec5SDimitry Andric // 17480b57cec5SDimitry Andric // The goal is to get: 17490b57cec5SDimitry Andric // 17500b57cec5SDimitry Andric // +--------------------------+ 17510b57cec5SDimitry Andric // | V 17520b57cec5SDimitry Andric // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 17530b57cec5SDimitry Andric // 17540b57cec5SDimitry Andric // Rather than: 17550b57cec5SDimitry Andric // 17560b57cec5SDimitry Andric // +-------------------------------------+ 17570b57cec5SDimitry Andric // V | 17580b57cec5SDimitry Andric // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 17590b57cec5SDimitry Andric if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 17600b57cec5SDimitry Andric continue; 17610b57cec5SDimitry Andric 17620b57cec5SDimitry Andric BestBlock = MBB; 17630b57cec5SDimitry Andric BestFreq = CandidateFreq; 17640b57cec5SDimitry Andric } 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric return BestBlock; 17670b57cec5SDimitry Andric } 17680b57cec5SDimitry Andric 1769*0fca6ea1SDimitry Andric /// Retrieve the first unplaced basic block in the entire function. 17700b57cec5SDimitry Andric /// 17710b57cec5SDimitry Andric /// This routine is called when we are unable to use the CFG to walk through 17720b57cec5SDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 17730b57cec5SDimitry Andric /// We walk through the function's blocks in order, starting from the 17740b57cec5SDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid 17750b57cec5SDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine. 17760b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 17770b57cec5SDimitry Andric const BlockChain &PlacedChain, 1778*0fca6ea1SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt) { 1779*0fca6ea1SDimitry Andric 17800b57cec5SDimitry Andric for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 17810b57cec5SDimitry Andric ++I) { 17820b57cec5SDimitry Andric if (BlockToChain[&*I] != &PlacedChain) { 17830b57cec5SDimitry Andric PrevUnplacedBlockIt = I; 17840b57cec5SDimitry Andric // Now select the head of the chain to which the unplaced block belongs 17850b57cec5SDimitry Andric // as the block to place. This will force the entire chain to be placed, 17860b57cec5SDimitry Andric // and satisfies the requirements of merging chains. 17870b57cec5SDimitry Andric return *BlockToChain[&*I]->begin(); 17880b57cec5SDimitry Andric } 17890b57cec5SDimitry Andric } 17900b57cec5SDimitry Andric return nullptr; 17910b57cec5SDimitry Andric } 17920b57cec5SDimitry Andric 1793*0fca6ea1SDimitry Andric /// Retrieve the first unplaced basic block among the blocks in BlockFilter. 1794*0fca6ea1SDimitry Andric /// 1795*0fca6ea1SDimitry Andric /// This is similar to getFirstUnplacedBlock for the entire function, but since 1796*0fca6ea1SDimitry Andric /// the size of BlockFilter is typically far less than the number of blocks in 1797*0fca6ea1SDimitry Andric /// the entire function, iterating through the BlockFilter is more efficient. 1798*0fca6ea1SDimitry Andric /// When processing the entire funciton, using the version without BlockFilter 1799*0fca6ea1SDimitry Andric /// has a complexity of #(loops in function) * #(blocks in function), while this 1800*0fca6ea1SDimitry Andric /// version has a complexity of sum(#(loops in block) foreach block in function) 1801*0fca6ea1SDimitry Andric /// which is always smaller. For long function mostly sequential in structure, 1802*0fca6ea1SDimitry Andric /// the complexity is amortized to 1 * #(blocks in function). 1803*0fca6ea1SDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 1804*0fca6ea1SDimitry Andric const BlockChain &PlacedChain, 1805*0fca6ea1SDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt, 1806*0fca6ea1SDimitry Andric const BlockFilterSet *BlockFilter) { 1807*0fca6ea1SDimitry Andric assert(BlockFilter); 1808*0fca6ea1SDimitry Andric for (; PrevUnplacedBlockInFilterIt != BlockFilter->end(); 1809*0fca6ea1SDimitry Andric ++PrevUnplacedBlockInFilterIt) { 1810*0fca6ea1SDimitry Andric BlockChain *C = BlockToChain[*PrevUnplacedBlockInFilterIt]; 1811*0fca6ea1SDimitry Andric if (C != &PlacedChain) { 1812*0fca6ea1SDimitry Andric return *C->begin(); 1813*0fca6ea1SDimitry Andric } 1814*0fca6ea1SDimitry Andric } 1815*0fca6ea1SDimitry Andric return nullptr; 1816*0fca6ea1SDimitry Andric } 1817*0fca6ea1SDimitry Andric 18180b57cec5SDimitry Andric void MachineBlockPlacement::fillWorkLists( 18190b57cec5SDimitry Andric const MachineBasicBlock *MBB, 18200b57cec5SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 18210b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr) { 18220b57cec5SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 18230b57cec5SDimitry Andric if (!UpdatedPreds.insert(&Chain).second) 18240b57cec5SDimitry Andric return; 18250b57cec5SDimitry Andric 18260b57cec5SDimitry Andric assert( 18270b57cec5SDimitry Andric Chain.UnscheduledPredecessors == 0 && 18280b57cec5SDimitry Andric "Attempting to place block with unscheduled predecessors in worklist."); 18290b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : Chain) { 18300b57cec5SDimitry Andric assert(BlockToChain[ChainBB] == &Chain && 18310b57cec5SDimitry Andric "Block in chain doesn't match BlockToChain map."); 18320b57cec5SDimitry Andric for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 18330b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(Pred)) 18340b57cec5SDimitry Andric continue; 18350b57cec5SDimitry Andric if (BlockToChain[Pred] == &Chain) 18360b57cec5SDimitry Andric continue; 18370b57cec5SDimitry Andric ++Chain.UnscheduledPredecessors; 18380b57cec5SDimitry Andric } 18390b57cec5SDimitry Andric } 18400b57cec5SDimitry Andric 18410b57cec5SDimitry Andric if (Chain.UnscheduledPredecessors != 0) 18420b57cec5SDimitry Andric return; 18430b57cec5SDimitry Andric 18440b57cec5SDimitry Andric MachineBasicBlock *BB = *Chain.begin(); 18450b57cec5SDimitry Andric if (BB->isEHPad()) 18460b57cec5SDimitry Andric EHPadWorkList.push_back(BB); 18470b57cec5SDimitry Andric else 18480b57cec5SDimitry Andric BlockWorkList.push_back(BB); 18490b57cec5SDimitry Andric } 18500b57cec5SDimitry Andric 18510b57cec5SDimitry Andric void MachineBlockPlacement::buildChain( 18520b57cec5SDimitry Andric const MachineBasicBlock *HeadBB, BlockChain &Chain, 18530b57cec5SDimitry Andric BlockFilterSet *BlockFilter) { 18540b57cec5SDimitry Andric assert(HeadBB && "BB must not be null.\n"); 18550b57cec5SDimitry Andric assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n"); 18560b57cec5SDimitry Andric MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 1857*0fca6ea1SDimitry Andric BlockFilterSet::iterator PrevUnplacedBlockInFilterIt; 1858*0fca6ea1SDimitry Andric if (BlockFilter) 1859*0fca6ea1SDimitry Andric PrevUnplacedBlockInFilterIt = BlockFilter->begin(); 18600b57cec5SDimitry Andric 18610b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB = HeadBB; 18620b57cec5SDimitry Andric markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 18630b57cec5SDimitry Andric MachineBasicBlock *BB = *std::prev(Chain.end()); 18640b57cec5SDimitry Andric while (true) { 18650b57cec5SDimitry Andric assert(BB && "null block found at end of chain in loop."); 18660b57cec5SDimitry Andric assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 18670b57cec5SDimitry Andric assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 18680b57cec5SDimitry Andric 18690b57cec5SDimitry Andric 18700b57cec5SDimitry Andric // Look for the best viable successor if there is one to place immediately 18710b57cec5SDimitry Andric // after this block. 18720b57cec5SDimitry Andric auto Result = selectBestSuccessor(BB, Chain, BlockFilter); 18730b57cec5SDimitry Andric MachineBasicBlock* BestSucc = Result.BB; 18740b57cec5SDimitry Andric bool ShouldTailDup = Result.ShouldTailDup; 18750b57cec5SDimitry Andric if (allowTailDupPlacement()) 1876480093f4SDimitry Andric ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc, 1877480093f4SDimitry Andric Chain, 1878480093f4SDimitry Andric BlockFilter)); 18790b57cec5SDimitry Andric 18800b57cec5SDimitry Andric // If an immediate successor isn't available, look for the best viable 18810b57cec5SDimitry Andric // block among those we've identified as not violating the loop's CFG at 18820b57cec5SDimitry Andric // this point. This won't be a fallthrough, but it will increase locality. 18830b57cec5SDimitry Andric if (!BestSucc) 18840b57cec5SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 18850b57cec5SDimitry Andric if (!BestSucc) 18860b57cec5SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 18870b57cec5SDimitry Andric 18880b57cec5SDimitry Andric if (!BestSucc) { 1889*0fca6ea1SDimitry Andric if (BlockFilter) 1890*0fca6ea1SDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockInFilterIt, 1891*0fca6ea1SDimitry Andric BlockFilter); 1892*0fca6ea1SDimitry Andric else 1893*0fca6ea1SDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt); 18940b57cec5SDimitry Andric if (!BestSucc) 18950b57cec5SDimitry Andric break; 18960b57cec5SDimitry Andric 18970b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 18980b57cec5SDimitry Andric "layout successor until the CFG reduces\n"); 18990b57cec5SDimitry Andric } 19000b57cec5SDimitry Andric 19010b57cec5SDimitry Andric // Placement may have changed tail duplication opportunities. 19020b57cec5SDimitry Andric // Check for that now. 19030b57cec5SDimitry Andric if (allowTailDupPlacement() && BestSucc && ShouldTailDup) { 19045ffd83dbSDimitry Andric repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 1905*0fca6ea1SDimitry Andric BlockFilter, PrevUnplacedBlockIt, 1906*0fca6ea1SDimitry Andric PrevUnplacedBlockInFilterIt); 19075ffd83dbSDimitry Andric // If the chosen successor was duplicated into BB, don't bother laying 19085ffd83dbSDimitry Andric // it out, just go round the loop again with BB as the chain end. 19095ffd83dbSDimitry Andric if (!BB->isSuccessor(BestSucc)) 19100b57cec5SDimitry Andric continue; 19110b57cec5SDimitry Andric } 19120b57cec5SDimitry Andric 19130b57cec5SDimitry Andric // Place this block, updating the datastructures to reflect its placement. 19140b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[BestSucc]; 19150b57cec5SDimitry Andric // Zero out UnscheduledPredecessors for the successor we're about to merge in case 19160b57cec5SDimitry Andric // we selected a successor that didn't fit naturally into the CFG. 19170b57cec5SDimitry Andric SuccChain.UnscheduledPredecessors = 0; 19180b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 19190b57cec5SDimitry Andric << getBlockName(BestSucc) << "\n"); 19200b57cec5SDimitry Andric markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 19210b57cec5SDimitry Andric Chain.merge(BestSucc, &SuccChain); 19220b57cec5SDimitry Andric BB = *std::prev(Chain.end()); 19230b57cec5SDimitry Andric } 19240b57cec5SDimitry Andric 19250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finished forming chain for header block " 19260b57cec5SDimitry Andric << getBlockName(*Chain.begin()) << "\n"); 19270b57cec5SDimitry Andric } 19280b57cec5SDimitry Andric 19290b57cec5SDimitry Andric // If bottom of block BB has only one successor OldTop, in most cases it is 19300b57cec5SDimitry Andric // profitable to move it before OldTop, except the following case: 19310b57cec5SDimitry Andric // 19320b57cec5SDimitry Andric // -->OldTop<- 19330b57cec5SDimitry Andric // | . | 19340b57cec5SDimitry Andric // | . | 19350b57cec5SDimitry Andric // | . | 19360b57cec5SDimitry Andric // ---Pred | 19370b57cec5SDimitry Andric // | | 19380b57cec5SDimitry Andric // BB----- 19390b57cec5SDimitry Andric // 19400b57cec5SDimitry Andric // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't 19410b57cec5SDimitry Andric // layout the other successor below it, so it can't reduce taken branch. 19420b57cec5SDimitry Andric // In this case we keep its original layout. 19430b57cec5SDimitry Andric bool 19440b57cec5SDimitry Andric MachineBlockPlacement::canMoveBottomBlockToTop( 19450b57cec5SDimitry Andric const MachineBasicBlock *BottomBlock, 19460b57cec5SDimitry Andric const MachineBasicBlock *OldTop) { 19470b57cec5SDimitry Andric if (BottomBlock->pred_size() != 1) 19480b57cec5SDimitry Andric return true; 19490b57cec5SDimitry Andric MachineBasicBlock *Pred = *BottomBlock->pred_begin(); 19500b57cec5SDimitry Andric if (Pred->succ_size() != 2) 19510b57cec5SDimitry Andric return true; 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric MachineBasicBlock *OtherBB = *Pred->succ_begin(); 19540b57cec5SDimitry Andric if (OtherBB == BottomBlock) 19550b57cec5SDimitry Andric OtherBB = *Pred->succ_rbegin(); 19560b57cec5SDimitry Andric if (OtherBB == OldTop) 19570b57cec5SDimitry Andric return false; 19580b57cec5SDimitry Andric 19590b57cec5SDimitry Andric return true; 19600b57cec5SDimitry Andric } 19610b57cec5SDimitry Andric 19620b57cec5SDimitry Andric // Find out the possible fall through frequence to the top of a loop. 19630b57cec5SDimitry Andric BlockFrequency 19640b57cec5SDimitry Andric MachineBlockPlacement::TopFallThroughFreq( 19650b57cec5SDimitry Andric const MachineBasicBlock *Top, 19660b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 19675f757f3fSDimitry Andric BlockFrequency MaxFreq = BlockFrequency(0); 19680b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) { 19690b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 19700b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 19710b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 19720b57cec5SDimitry Andric // Found a Pred block can be placed before Top. 19730b57cec5SDimitry Andric // Check if Top is the best successor of Pred. 19740b57cec5SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top); 19750b57cec5SDimitry Andric bool TopOK = true; 19760b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) { 19770b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 19780b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 19790b57cec5SDimitry Andric // Check if Succ can be placed after Pred. 19800b57cec5SDimitry Andric // Succ should not be in any chain, or it is the head of some chain. 19810b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) && 19820b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) { 19830b57cec5SDimitry Andric TopOK = false; 19840b57cec5SDimitry Andric break; 19850b57cec5SDimitry Andric } 19860b57cec5SDimitry Andric } 19870b57cec5SDimitry Andric if (TopOK) { 19880b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 19890b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, Top); 19900b57cec5SDimitry Andric if (EdgeFreq > MaxFreq) 19910b57cec5SDimitry Andric MaxFreq = EdgeFreq; 19920b57cec5SDimitry Andric } 19930b57cec5SDimitry Andric } 19940b57cec5SDimitry Andric } 19950b57cec5SDimitry Andric return MaxFreq; 19960b57cec5SDimitry Andric } 19970b57cec5SDimitry Andric 19980b57cec5SDimitry Andric // Compute the fall through gains when move NewTop before OldTop. 19990b57cec5SDimitry Andric // 20000b57cec5SDimitry Andric // In following diagram, edges marked as "-" are reduced fallthrough, edges 20010b57cec5SDimitry Andric // marked as "+" are increased fallthrough, this function computes 20020b57cec5SDimitry Andric // 20030b57cec5SDimitry Andric // SUM(increased fallthrough) - SUM(decreased fallthrough) 20040b57cec5SDimitry Andric // 20050b57cec5SDimitry Andric // | 20060b57cec5SDimitry Andric // | - 20070b57cec5SDimitry Andric // V 20080b57cec5SDimitry Andric // --->OldTop 20090b57cec5SDimitry Andric // | . 20100b57cec5SDimitry Andric // | . 20110b57cec5SDimitry Andric // +| . + 20120b57cec5SDimitry Andric // | Pred ---> 20130b57cec5SDimitry Andric // | |- 20140b57cec5SDimitry Andric // | V 20150b57cec5SDimitry Andric // --- NewTop <--- 20160b57cec5SDimitry Andric // |- 20170b57cec5SDimitry Andric // V 20180b57cec5SDimitry Andric // 20190b57cec5SDimitry Andric BlockFrequency 20200b57cec5SDimitry Andric MachineBlockPlacement::FallThroughGains( 20210b57cec5SDimitry Andric const MachineBasicBlock *NewTop, 20220b57cec5SDimitry Andric const MachineBasicBlock *OldTop, 20230b57cec5SDimitry Andric const MachineBasicBlock *ExitBB, 20240b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 20250b57cec5SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet); 20265f757f3fSDimitry Andric BlockFrequency FallThrough2Exit = BlockFrequency(0); 20270b57cec5SDimitry Andric if (ExitBB) 20280b57cec5SDimitry Andric FallThrough2Exit = MBFI->getBlockFreq(NewTop) * 20290b57cec5SDimitry Andric MBPI->getEdgeProbability(NewTop, ExitBB); 20300b57cec5SDimitry Andric BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) * 20310b57cec5SDimitry Andric MBPI->getEdgeProbability(NewTop, OldTop); 20320b57cec5SDimitry Andric 20330b57cec5SDimitry Andric // Find the best Pred of NewTop. 20340b57cec5SDimitry Andric MachineBasicBlock *BestPred = nullptr; 20355f757f3fSDimitry Andric BlockFrequency FallThroughFromPred = BlockFrequency(0); 20360b57cec5SDimitry Andric for (MachineBasicBlock *Pred : NewTop->predecessors()) { 20370b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred)) 20380b57cec5SDimitry Andric continue; 20390b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 20400b57cec5SDimitry Andric if (!PredChain || Pred == *std::prev(PredChain->end())) { 20415f757f3fSDimitry Andric BlockFrequency EdgeFreq = 20425f757f3fSDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, NewTop); 20430b57cec5SDimitry Andric if (EdgeFreq > FallThroughFromPred) { 20440b57cec5SDimitry Andric FallThroughFromPred = EdgeFreq; 20450b57cec5SDimitry Andric BestPred = Pred; 20460b57cec5SDimitry Andric } 20470b57cec5SDimitry Andric } 20480b57cec5SDimitry Andric } 20490b57cec5SDimitry Andric 20500b57cec5SDimitry Andric // If NewTop is not placed after Pred, another successor can be placed 20510b57cec5SDimitry Andric // after Pred. 20525f757f3fSDimitry Andric BlockFrequency NewFreq = BlockFrequency(0); 20530b57cec5SDimitry Andric if (BestPred) { 20540b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BestPred->successors()) { 20550b57cec5SDimitry Andric if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ)) 20560b57cec5SDimitry Andric continue; 205706c3fb27SDimitry Andric if (ComputedEdges.contains(Succ)) 20580b57cec5SDimitry Andric continue; 20590b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 20600b57cec5SDimitry Andric if ((SuccChain && (Succ != *SuccChain->begin())) || 20610b57cec5SDimitry Andric (SuccChain == BlockToChain[BestPred])) 20620b57cec5SDimitry Andric continue; 20630b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) * 20640b57cec5SDimitry Andric MBPI->getEdgeProbability(BestPred, Succ); 20650b57cec5SDimitry Andric if (EdgeFreq > NewFreq) 20660b57cec5SDimitry Andric NewFreq = EdgeFreq; 20670b57cec5SDimitry Andric } 20680b57cec5SDimitry Andric BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) * 20690b57cec5SDimitry Andric MBPI->getEdgeProbability(BestPred, NewTop); 20700b57cec5SDimitry Andric if (NewFreq > OrigEdgeFreq) { 20710b57cec5SDimitry Andric // If NewTop is not the best successor of Pred, then Pred doesn't 20720b57cec5SDimitry Andric // fallthrough to NewTop. So there is no FallThroughFromPred and 20730b57cec5SDimitry Andric // NewFreq. 20745f757f3fSDimitry Andric NewFreq = BlockFrequency(0); 20755f757f3fSDimitry Andric FallThroughFromPred = BlockFrequency(0); 20760b57cec5SDimitry Andric } 20770b57cec5SDimitry Andric } 20780b57cec5SDimitry Andric 20795f757f3fSDimitry Andric BlockFrequency Result = BlockFrequency(0); 20800b57cec5SDimitry Andric BlockFrequency Gains = BackEdgeFreq + NewFreq; 20815f757f3fSDimitry Andric BlockFrequency Lost = 20825f757f3fSDimitry Andric FallThrough2Top + FallThrough2Exit + FallThroughFromPred; 20830b57cec5SDimitry Andric if (Gains > Lost) 20840b57cec5SDimitry Andric Result = Gains - Lost; 20850b57cec5SDimitry Andric return Result; 20860b57cec5SDimitry Andric } 20870b57cec5SDimitry Andric 20880b57cec5SDimitry Andric /// Helper function of findBestLoopTop. Find the best loop top block 20890b57cec5SDimitry Andric /// from predecessors of old top. 20900b57cec5SDimitry Andric /// 20910b57cec5SDimitry Andric /// Look for a block which is strictly better than the old top for laying 20920b57cec5SDimitry Andric /// out before the old top of the loop. This looks for only two patterns: 20930b57cec5SDimitry Andric /// 20940b57cec5SDimitry Andric /// 1. a block has only one successor, the old loop top 20950b57cec5SDimitry Andric /// 20960b57cec5SDimitry Andric /// Because such a block will always result in an unconditional jump, 20970b57cec5SDimitry Andric /// rotating it in front of the old top is always profitable. 20980b57cec5SDimitry Andric /// 20990b57cec5SDimitry Andric /// 2. a block has two successors, one is old top, another is exit 21000b57cec5SDimitry Andric /// and it has more than one predecessors 21010b57cec5SDimitry Andric /// 21020b57cec5SDimitry Andric /// If it is below one of its predecessors P, only P can fall through to 21030b57cec5SDimitry Andric /// it, all other predecessors need a jump to it, and another conditional 21040b57cec5SDimitry Andric /// jump to loop header. If it is moved before loop header, all its 21050b57cec5SDimitry Andric /// predecessors jump to it, then fall through to loop header. So all its 21060b57cec5SDimitry Andric /// predecessors except P can reduce one taken branch. 21070b57cec5SDimitry Andric /// At the same time, move it before old top increases the taken branch 21080b57cec5SDimitry Andric /// to loop exit block, so the reduced taken branch will be compared with 21090b57cec5SDimitry Andric /// the increased taken branch to the loop exit block. 21100b57cec5SDimitry Andric MachineBasicBlock * 21110b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTopHelper( 21120b57cec5SDimitry Andric MachineBasicBlock *OldTop, 21130b57cec5SDimitry Andric const MachineLoop &L, 21140b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 21150b57cec5SDimitry Andric // Check that the header hasn't been fused with a preheader block due to 21160b57cec5SDimitry Andric // crazy branches. If it has, we need to start with the header at the top to 21170b57cec5SDimitry Andric // prevent pulling the preheader into the loop body. 21180b57cec5SDimitry Andric BlockChain &HeaderChain = *BlockToChain[OldTop]; 21190b57cec5SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 21200b57cec5SDimitry Andric return OldTop; 2121349cc55cSDimitry Andric if (OldTop != *HeaderChain.begin()) 2122349cc55cSDimitry Andric return OldTop; 21230b57cec5SDimitry Andric 21240b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop) 21250b57cec5SDimitry Andric << "\n"); 21260b57cec5SDimitry Andric 21275f757f3fSDimitry Andric BlockFrequency BestGains = BlockFrequency(0); 21280b57cec5SDimitry Andric MachineBasicBlock *BestPred = nullptr; 21290b57cec5SDimitry Andric for (MachineBasicBlock *Pred : OldTop->predecessors()) { 21300b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred)) 21310b57cec5SDimitry Andric continue; 21320b57cec5SDimitry Andric if (Pred == L.getHeader()) 21330b57cec5SDimitry Andric continue; 21340b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has " 21355f757f3fSDimitry Andric << Pred->succ_size() << " successors, " 21365f757f3fSDimitry Andric << printBlockFreq(MBFI->getMBFI(), *Pred) << " freq\n"); 21370b57cec5SDimitry Andric if (Pred->succ_size() > 2) 21380b57cec5SDimitry Andric continue; 21390b57cec5SDimitry Andric 21400b57cec5SDimitry Andric MachineBasicBlock *OtherBB = nullptr; 21410b57cec5SDimitry Andric if (Pred->succ_size() == 2) { 21420b57cec5SDimitry Andric OtherBB = *Pred->succ_begin(); 21430b57cec5SDimitry Andric if (OtherBB == OldTop) 21440b57cec5SDimitry Andric OtherBB = *Pred->succ_rbegin(); 21450b57cec5SDimitry Andric } 21460b57cec5SDimitry Andric 21470b57cec5SDimitry Andric if (!canMoveBottomBlockToTop(Pred, OldTop)) 21480b57cec5SDimitry Andric continue; 21490b57cec5SDimitry Andric 21500b57cec5SDimitry Andric BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB, 21510b57cec5SDimitry Andric LoopBlockSet); 21525f757f3fSDimitry Andric if ((Gains > BlockFrequency(0)) && 21535f757f3fSDimitry Andric (Gains > BestGains || 21540b57cec5SDimitry Andric ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) { 21550b57cec5SDimitry Andric BestPred = Pred; 21560b57cec5SDimitry Andric BestGains = Gains; 21570b57cec5SDimitry Andric } 21580b57cec5SDimitry Andric } 21590b57cec5SDimitry Andric 21600b57cec5SDimitry Andric // If no direct predecessor is fine, just use the loop header. 21610b57cec5SDimitry Andric if (!BestPred) { 21620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " final top unchanged\n"); 21630b57cec5SDimitry Andric return OldTop; 21640b57cec5SDimitry Andric } 21650b57cec5SDimitry Andric 21660b57cec5SDimitry Andric // Walk backwards through any straight line of predecessors. 21670b57cec5SDimitry Andric while (BestPred->pred_size() == 1 && 21680b57cec5SDimitry Andric (*BestPred->pred_begin())->succ_size() == 1 && 21690b57cec5SDimitry Andric *BestPred->pred_begin() != L.getHeader()) 21700b57cec5SDimitry Andric BestPred = *BestPred->pred_begin(); 21710b57cec5SDimitry Andric 21720b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 21730b57cec5SDimitry Andric return BestPred; 21740b57cec5SDimitry Andric } 21750b57cec5SDimitry Andric 21760b57cec5SDimitry Andric /// Find the best loop top block for layout. 21770b57cec5SDimitry Andric /// 21780b57cec5SDimitry Andric /// This function iteratively calls findBestLoopTopHelper, until no new better 21790b57cec5SDimitry Andric /// BB can be found. 21800b57cec5SDimitry Andric MachineBasicBlock * 21810b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTop(const MachineLoop &L, 21820b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 21830b57cec5SDimitry Andric // Placing the latch block before the header may introduce an extra branch 21840b57cec5SDimitry Andric // that skips this block the first time the loop is executed, which we want 21850b57cec5SDimitry Andric // to avoid when optimising for size. 21860b57cec5SDimitry Andric // FIXME: in theory there is a case that does not introduce a new branch, 21870b57cec5SDimitry Andric // i.e. when the layout predecessor does not fallthrough to the loop header. 21880b57cec5SDimitry Andric // In practice this never happens though: there always seems to be a preheader 21890b57cec5SDimitry Andric // that can fallthrough and that is also placed before the header. 2190480093f4SDimitry Andric bool OptForSize = F->getFunction().hasOptSize() || 21915ffd83dbSDimitry Andric llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get()); 2192480093f4SDimitry Andric if (OptForSize) 21930b57cec5SDimitry Andric return L.getHeader(); 21940b57cec5SDimitry Andric 21950b57cec5SDimitry Andric MachineBasicBlock *OldTop = nullptr; 21960b57cec5SDimitry Andric MachineBasicBlock *NewTop = L.getHeader(); 21970b57cec5SDimitry Andric while (NewTop != OldTop) { 21980b57cec5SDimitry Andric OldTop = NewTop; 21990b57cec5SDimitry Andric NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet); 22000b57cec5SDimitry Andric if (NewTop != OldTop) 22010b57cec5SDimitry Andric ComputedEdges[NewTop] = { OldTop, false }; 22020b57cec5SDimitry Andric } 22030b57cec5SDimitry Andric return NewTop; 22040b57cec5SDimitry Andric } 22050b57cec5SDimitry Andric 22060b57cec5SDimitry Andric /// Find the best loop exiting block for layout. 22070b57cec5SDimitry Andric /// 22080b57cec5SDimitry Andric /// This routine implements the logic to analyze the loop looking for the best 22090b57cec5SDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize 22100b57cec5SDimitry Andric /// fallthrough opportunities. 22110b57cec5SDimitry Andric MachineBasicBlock * 22120b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopExit(const MachineLoop &L, 22130b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet, 22140b57cec5SDimitry Andric BlockFrequency &ExitFreq) { 22150b57cec5SDimitry Andric // We don't want to layout the loop linearly in all cases. If the loop header 22160b57cec5SDimitry Andric // is just a normal basic block in the loop, we want to look for what block 22170b57cec5SDimitry Andric // within the loop is the best one to layout at the top. However, if the loop 22180b57cec5SDimitry Andric // header has be pre-merged into a chain due to predecessors not having 22190b57cec5SDimitry Andric // analyzable branches, *and* the predecessor it is merged with is *not* part 22200b57cec5SDimitry Andric // of the loop, rotating the header into the middle of the loop will create 22210b57cec5SDimitry Andric // a non-contiguous range of blocks which is Very Bad. So start with the 22220b57cec5SDimitry Andric // header and only rotate if safe. 22230b57cec5SDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 22240b57cec5SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 22250b57cec5SDimitry Andric return nullptr; 22260b57cec5SDimitry Andric 22270b57cec5SDimitry Andric BlockFrequency BestExitEdgeFreq; 22280b57cec5SDimitry Andric unsigned BestExitLoopDepth = 0; 22290b57cec5SDimitry Andric MachineBasicBlock *ExitingBB = nullptr; 22300b57cec5SDimitry Andric // If there are exits to outer loops, loop rotation can severely limit 22310b57cec5SDimitry Andric // fallthrough opportunities unless it selects such an exit. Keep a set of 22320b57cec5SDimitry Andric // blocks where rotating to exit with that block will reach an outer loop. 22330b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 22340b57cec5SDimitry Andric 22350b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop exit for: " 22360b57cec5SDimitry Andric << getBlockName(L.getHeader()) << "\n"); 22370b57cec5SDimitry Andric for (MachineBasicBlock *MBB : L.getBlocks()) { 22380b57cec5SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 22390b57cec5SDimitry Andric // Ensure that this block is at the end of a chain; otherwise it could be 22400b57cec5SDimitry Andric // mid-way through an inner loop or a successor of an unanalyzable branch. 22410b57cec5SDimitry Andric if (MBB != *std::prev(Chain.end())) 22420b57cec5SDimitry Andric continue; 22430b57cec5SDimitry Andric 22440b57cec5SDimitry Andric // Now walk the successors. We need to establish whether this has a viable 22450b57cec5SDimitry Andric // exiting successor and whether it has a viable non-exiting successor. 22460b57cec5SDimitry Andric // We store the old exiting state and restore it if a viable looping 22470b57cec5SDimitry Andric // successor isn't found. 22480b57cec5SDimitry Andric MachineBasicBlock *OldExitingBB = ExitingBB; 22490b57cec5SDimitry Andric BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 22500b57cec5SDimitry Andric bool HasLoopingSucc = false; 22510b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 22520b57cec5SDimitry Andric if (Succ->isEHPad()) 22530b57cec5SDimitry Andric continue; 22540b57cec5SDimitry Andric if (Succ == MBB) 22550b57cec5SDimitry Andric continue; 22560b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 22570b57cec5SDimitry Andric // Don't split chains, either this chain or the successor's chain. 22580b57cec5SDimitry Andric if (&Chain == &SuccChain) { 22590b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 22600b57cec5SDimitry Andric << getBlockName(Succ) << " (chain conflict)\n"); 22610b57cec5SDimitry Andric continue; 22620b57cec5SDimitry Andric } 22630b57cec5SDimitry Andric 22640b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 22650b57cec5SDimitry Andric if (LoopBlockSet.count(Succ)) { 22660b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 22670b57cec5SDimitry Andric << getBlockName(Succ) << " (" << SuccProb << ")\n"); 22680b57cec5SDimitry Andric HasLoopingSucc = true; 22690b57cec5SDimitry Andric continue; 22700b57cec5SDimitry Andric } 22710b57cec5SDimitry Andric 22720b57cec5SDimitry Andric unsigned SuccLoopDepth = 0; 22730b57cec5SDimitry Andric if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 22740b57cec5SDimitry Andric SuccLoopDepth = ExitLoop->getLoopDepth(); 22750b57cec5SDimitry Andric if (ExitLoop->contains(&L)) 22760b57cec5SDimitry Andric BlocksExitingToOuterLoop.insert(MBB); 22770b57cec5SDimitry Andric } 22780b57cec5SDimitry Andric 22790b57cec5SDimitry Andric BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 22805f757f3fSDimitry Andric LLVM_DEBUG( 22815f757f3fSDimitry Andric dbgs() << " exiting: " << getBlockName(MBB) << " -> " 22825f757f3fSDimitry Andric << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] (" 22835f757f3fSDimitry Andric << printBlockFreq(MBFI->getMBFI(), ExitEdgeFreq) << ")\n"); 22840b57cec5SDimitry Andric // Note that we bias this toward an existing layout successor to retain 22850b57cec5SDimitry Andric // incoming order in the absence of better information. The exit must have 22860b57cec5SDimitry Andric // a frequency higher than the current exit before we consider breaking 22870b57cec5SDimitry Andric // the layout. 22880b57cec5SDimitry Andric BranchProbability Bias(100 - ExitBlockBias, 100); 22890b57cec5SDimitry Andric if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 22900b57cec5SDimitry Andric ExitEdgeFreq > BestExitEdgeFreq || 22910b57cec5SDimitry Andric (MBB->isLayoutSuccessor(Succ) && 22920b57cec5SDimitry Andric !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 22930b57cec5SDimitry Andric BestExitEdgeFreq = ExitEdgeFreq; 22940b57cec5SDimitry Andric ExitingBB = MBB; 22950b57cec5SDimitry Andric } 22960b57cec5SDimitry Andric } 22970b57cec5SDimitry Andric 22980b57cec5SDimitry Andric if (!HasLoopingSucc) { 22990b57cec5SDimitry Andric // Restore the old exiting state, no viable looping successor was found. 23000b57cec5SDimitry Andric ExitingBB = OldExitingBB; 23010b57cec5SDimitry Andric BestExitEdgeFreq = OldBestExitEdgeFreq; 23020b57cec5SDimitry Andric } 23030b57cec5SDimitry Andric } 23040b57cec5SDimitry Andric // Without a candidate exiting block or with only a single block in the 23050b57cec5SDimitry Andric // loop, just use the loop header to layout the loop. 23060b57cec5SDimitry Andric if (!ExitingBB) { 23070b57cec5SDimitry Andric LLVM_DEBUG( 23080b57cec5SDimitry Andric dbgs() << " No other candidate exit blocks, using loop header\n"); 23090b57cec5SDimitry Andric return nullptr; 23100b57cec5SDimitry Andric } 23110b57cec5SDimitry Andric if (L.getNumBlocks() == 1) { 23120b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 23130b57cec5SDimitry Andric return nullptr; 23140b57cec5SDimitry Andric } 23150b57cec5SDimitry Andric 23160b57cec5SDimitry Andric // Also, if we have exit blocks which lead to outer loops but didn't select 23170b57cec5SDimitry Andric // one of them as the exiting block we are rotating toward, disable loop 23180b57cec5SDimitry Andric // rotation altogether. 23190b57cec5SDimitry Andric if (!BlocksExitingToOuterLoop.empty() && 23200b57cec5SDimitry Andric !BlocksExitingToOuterLoop.count(ExitingBB)) 23210b57cec5SDimitry Andric return nullptr; 23220b57cec5SDimitry Andric 23230b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) 23240b57cec5SDimitry Andric << "\n"); 23250b57cec5SDimitry Andric ExitFreq = BestExitEdgeFreq; 23260b57cec5SDimitry Andric return ExitingBB; 23270b57cec5SDimitry Andric } 23280b57cec5SDimitry Andric 23290b57cec5SDimitry Andric /// Check if there is a fallthrough to loop header Top. 23300b57cec5SDimitry Andric /// 23310b57cec5SDimitry Andric /// 1. Look for a Pred that can be layout before Top. 23320b57cec5SDimitry Andric /// 2. Check if Top is the most possible successor of Pred. 23330b57cec5SDimitry Andric bool 23340b57cec5SDimitry Andric MachineBlockPlacement::hasViableTopFallthrough( 23350b57cec5SDimitry Andric const MachineBasicBlock *Top, 23360b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 23370b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) { 23380b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 23390b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 23400b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 23410b57cec5SDimitry Andric // Found a Pred block can be placed before Top. 23420b57cec5SDimitry Andric // Check if Top is the best successor of Pred. 23430b57cec5SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top); 23440b57cec5SDimitry Andric bool TopOK = true; 23450b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) { 23460b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 23470b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 23480b57cec5SDimitry Andric // Check if Succ can be placed after Pred. 23490b57cec5SDimitry Andric // Succ should not be in any chain, or it is the head of some chain. 23500b57cec5SDimitry Andric if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) { 23510b57cec5SDimitry Andric TopOK = false; 23520b57cec5SDimitry Andric break; 23530b57cec5SDimitry Andric } 23540b57cec5SDimitry Andric } 23550b57cec5SDimitry Andric if (TopOK) 23560b57cec5SDimitry Andric return true; 23570b57cec5SDimitry Andric } 23580b57cec5SDimitry Andric } 23590b57cec5SDimitry Andric return false; 23600b57cec5SDimitry Andric } 23610b57cec5SDimitry Andric 23620b57cec5SDimitry Andric /// Attempt to rotate an exiting block to the bottom of the loop. 23630b57cec5SDimitry Andric /// 23640b57cec5SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block 23650b57cec5SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 23660b57cec5SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out 23670b57cec5SDimitry Andric /// of its bottom already, don't rotate it. 23680b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 23690b57cec5SDimitry Andric const MachineBasicBlock *ExitingBB, 23700b57cec5SDimitry Andric BlockFrequency ExitFreq, 23710b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 23720b57cec5SDimitry Andric if (!ExitingBB) 23730b57cec5SDimitry Andric return; 23740b57cec5SDimitry Andric 23750b57cec5SDimitry Andric MachineBasicBlock *Top = *LoopChain.begin(); 23760b57cec5SDimitry Andric MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 23770b57cec5SDimitry Andric 23780b57cec5SDimitry Andric // If ExitingBB is already the last one in a chain then nothing to do. 23790b57cec5SDimitry Andric if (Bottom == ExitingBB) 23800b57cec5SDimitry Andric return; 23810b57cec5SDimitry Andric 2382e8d8bef9SDimitry Andric // The entry block should always be the first BB in a function. 2383e8d8bef9SDimitry Andric if (Top->isEntryBlock()) 2384e8d8bef9SDimitry Andric return; 2385e8d8bef9SDimitry Andric 23860b57cec5SDimitry Andric bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet); 23870b57cec5SDimitry Andric 23880b57cec5SDimitry Andric // If the header has viable fallthrough, check whether the current loop 23890b57cec5SDimitry Andric // bottom is a viable exiting block. If so, bail out as rotating will 23900b57cec5SDimitry Andric // introduce an unnecessary branch. 23910b57cec5SDimitry Andric if (ViableTopFallthrough) { 23920b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Bottom->successors()) { 23930b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 23940b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && 23950b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) 23960b57cec5SDimitry Andric return; 23970b57cec5SDimitry Andric } 23980b57cec5SDimitry Andric 23990b57cec5SDimitry Andric // Rotate will destroy the top fallthrough, we need to ensure the new exit 24000b57cec5SDimitry Andric // frequency is larger than top fallthrough. 24010b57cec5SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet); 24020b57cec5SDimitry Andric if (FallThrough2Top >= ExitFreq) 24030b57cec5SDimitry Andric return; 24040b57cec5SDimitry Andric } 24050b57cec5SDimitry Andric 24060b57cec5SDimitry Andric BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB); 24070b57cec5SDimitry Andric if (ExitIt == LoopChain.end()) 24080b57cec5SDimitry Andric return; 24090b57cec5SDimitry Andric 24100b57cec5SDimitry Andric // Rotating a loop exit to the bottom when there is a fallthrough to top 24110b57cec5SDimitry Andric // trades the entry fallthrough for an exit fallthrough. 24120b57cec5SDimitry Andric // If there is no bottom->top edge, but the chosen exit block does have 24130b57cec5SDimitry Andric // a fallthrough, we break that fallthrough for nothing in return. 24140b57cec5SDimitry Andric 24150b57cec5SDimitry Andric // Let's consider an example. We have a built chain of basic blocks 24160b57cec5SDimitry Andric // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block. 24170b57cec5SDimitry Andric // By doing a rotation we get 24180b57cec5SDimitry Andric // Bk+1, ..., Bn, B1, ..., Bk 24190b57cec5SDimitry Andric // Break of fallthrough to B1 is compensated by a fallthrough from Bk. 24200b57cec5SDimitry Andric // If we had a fallthrough Bk -> Bk+1 it is broken now. 24210b57cec5SDimitry Andric // It might be compensated by fallthrough Bn -> B1. 24220b57cec5SDimitry Andric // So we have a condition to avoid creation of extra branch by loop rotation. 24230b57cec5SDimitry Andric // All below must be true to avoid loop rotation: 24240b57cec5SDimitry Andric // If there is a fallthrough to top (B1) 24250b57cec5SDimitry Andric // There was fallthrough from chosen exit block (Bk) to next one (Bk+1) 24260b57cec5SDimitry Andric // There is no fallthrough from bottom (Bn) to top (B1). 24270b57cec5SDimitry Andric // Please note that there is no exit fallthrough from Bn because we checked it 24280b57cec5SDimitry Andric // above. 24290b57cec5SDimitry Andric if (ViableTopFallthrough) { 24300b57cec5SDimitry Andric assert(std::next(ExitIt) != LoopChain.end() && 24310b57cec5SDimitry Andric "Exit should not be last BB"); 24320b57cec5SDimitry Andric MachineBasicBlock *NextBlockInChain = *std::next(ExitIt); 24330b57cec5SDimitry Andric if (ExitingBB->isSuccessor(NextBlockInChain)) 24340b57cec5SDimitry Andric if (!Bottom->isSuccessor(Top)) 24350b57cec5SDimitry Andric return; 24360b57cec5SDimitry Andric } 24370b57cec5SDimitry Andric 24380b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB) 24390b57cec5SDimitry Andric << " at bottom\n"); 24400b57cec5SDimitry Andric std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 24410b57cec5SDimitry Andric } 24420b57cec5SDimitry Andric 24430b57cec5SDimitry Andric /// Attempt to rotate a loop based on profile data to reduce branch cost. 24440b57cec5SDimitry Andric /// 24450b57cec5SDimitry Andric /// With profile data, we can determine the cost in terms of missed fall through 24460b57cec5SDimitry Andric /// opportunities when rotating a loop chain and select the best rotation. 24470b57cec5SDimitry Andric /// Basically, there are three kinds of cost to consider for each rotation: 24480b57cec5SDimitry Andric /// 1. The possibly missed fall through edge (if it exists) from BB out of 24490b57cec5SDimitry Andric /// the loop to the loop header. 24500b57cec5SDimitry Andric /// 2. The possibly missed fall through edges (if they exist) from the loop 24510b57cec5SDimitry Andric /// exits to BB out of the loop. 24520b57cec5SDimitry Andric /// 3. The missed fall through edge (if it exists) from the last BB to the 24530b57cec5SDimitry Andric /// first BB in the loop chain. 24540b57cec5SDimitry Andric /// Therefore, the cost for a given rotation is the sum of costs listed above. 24550b57cec5SDimitry Andric /// We select the best rotation with the smallest cost. 24560b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoopWithProfile( 24570b57cec5SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 24580b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 24590b57cec5SDimitry Andric auto RotationPos = LoopChain.end(); 2460e8d8bef9SDimitry Andric MachineBasicBlock *ChainHeaderBB = *LoopChain.begin(); 2461e8d8bef9SDimitry Andric 2462e8d8bef9SDimitry Andric // The entry block should always be the first BB in a function. 2463e8d8bef9SDimitry Andric if (ChainHeaderBB->isEntryBlock()) 2464e8d8bef9SDimitry Andric return; 24650b57cec5SDimitry Andric 24665f757f3fSDimitry Andric BlockFrequency SmallestRotationCost = BlockFrequency::max(); 24670b57cec5SDimitry Andric 24680b57cec5SDimitry Andric // A utility lambda that scales up a block frequency by dividing it by a 24690b57cec5SDimitry Andric // branch probability which is the reciprocal of the scale. 24700b57cec5SDimitry Andric auto ScaleBlockFrequency = [](BlockFrequency Freq, 24710b57cec5SDimitry Andric unsigned Scale) -> BlockFrequency { 24720b57cec5SDimitry Andric if (Scale == 0) 24735f757f3fSDimitry Andric return BlockFrequency(0); 24740b57cec5SDimitry Andric // Use operator / between BlockFrequency and BranchProbability to implement 24750b57cec5SDimitry Andric // saturating multiplication. 24760b57cec5SDimitry Andric return Freq / BranchProbability(1, Scale); 24770b57cec5SDimitry Andric }; 24780b57cec5SDimitry Andric 24790b57cec5SDimitry Andric // Compute the cost of the missed fall-through edge to the loop header if the 24800b57cec5SDimitry Andric // chain head is not the loop header. As we only consider natural loops with 24810b57cec5SDimitry Andric // single header, this computation can be done only once. 24820b57cec5SDimitry Andric BlockFrequency HeaderFallThroughCost(0); 24830b57cec5SDimitry Andric for (auto *Pred : ChainHeaderBB->predecessors()) { 24840b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 24850b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 24860b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 24870b57cec5SDimitry Andric auto EdgeFreq = MBFI->getBlockFreq(Pred) * 24880b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, ChainHeaderBB); 24890b57cec5SDimitry Andric auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 24900b57cec5SDimitry Andric // If the predecessor has only an unconditional jump to the header, we 24910b57cec5SDimitry Andric // need to consider the cost of this jump. 24920b57cec5SDimitry Andric if (Pred->succ_size() == 1) 24930b57cec5SDimitry Andric FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 24940b57cec5SDimitry Andric HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 24950b57cec5SDimitry Andric } 24960b57cec5SDimitry Andric } 24970b57cec5SDimitry Andric 24980b57cec5SDimitry Andric // Here we collect all exit blocks in the loop, and for each exit we find out 24990b57cec5SDimitry Andric // its hottest exit edge. For each loop rotation, we define the loop exit cost 25000b57cec5SDimitry Andric // as the sum of frequencies of exit edges we collect here, excluding the exit 25010b57cec5SDimitry Andric // edge from the tail of the loop chain. 25020b57cec5SDimitry Andric SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 2503fcaf7f86SDimitry Andric for (auto *BB : LoopChain) { 25040b57cec5SDimitry Andric auto LargestExitEdgeProb = BranchProbability::getZero(); 25050b57cec5SDimitry Andric for (auto *Succ : BB->successors()) { 25060b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 25070b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && 25080b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) { 25090b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 25100b57cec5SDimitry Andric LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 25110b57cec5SDimitry Andric } 25120b57cec5SDimitry Andric } 25130b57cec5SDimitry Andric if (LargestExitEdgeProb > BranchProbability::getZero()) { 25140b57cec5SDimitry Andric auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 25150b57cec5SDimitry Andric ExitsWithFreq.emplace_back(BB, ExitFreq); 25160b57cec5SDimitry Andric } 25170b57cec5SDimitry Andric } 25180b57cec5SDimitry Andric 25190b57cec5SDimitry Andric // In this loop we iterate every block in the loop chain and calculate the 25200b57cec5SDimitry Andric // cost assuming the block is the head of the loop chain. When the loop ends, 25210b57cec5SDimitry Andric // we should have found the best candidate as the loop chain's head. 25220b57cec5SDimitry Andric for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 25230b57cec5SDimitry Andric EndIter = LoopChain.end(); 25240b57cec5SDimitry Andric Iter != EndIter; Iter++, TailIter++) { 25250b57cec5SDimitry Andric // TailIter is used to track the tail of the loop chain if the block we are 25260b57cec5SDimitry Andric // checking (pointed by Iter) is the head of the chain. 25270b57cec5SDimitry Andric if (TailIter == LoopChain.end()) 25280b57cec5SDimitry Andric TailIter = LoopChain.begin(); 25290b57cec5SDimitry Andric 25300b57cec5SDimitry Andric auto TailBB = *TailIter; 25310b57cec5SDimitry Andric 25320b57cec5SDimitry Andric // Calculate the cost by putting this BB to the top. 25335f757f3fSDimitry Andric BlockFrequency Cost = BlockFrequency(0); 25340b57cec5SDimitry Andric 25350b57cec5SDimitry Andric // If the current BB is the loop header, we need to take into account the 25360b57cec5SDimitry Andric // cost of the missed fall through edge from outside of the loop to the 25370b57cec5SDimitry Andric // header. 25380b57cec5SDimitry Andric if (Iter != LoopChain.begin()) 25390b57cec5SDimitry Andric Cost += HeaderFallThroughCost; 25400b57cec5SDimitry Andric 25410b57cec5SDimitry Andric // Collect the loop exit cost by summing up frequencies of all exit edges 25420b57cec5SDimitry Andric // except the one from the chain tail. 25430b57cec5SDimitry Andric for (auto &ExitWithFreq : ExitsWithFreq) 25440b57cec5SDimitry Andric if (TailBB != ExitWithFreq.first) 25450b57cec5SDimitry Andric Cost += ExitWithFreq.second; 25460b57cec5SDimitry Andric 25470b57cec5SDimitry Andric // The cost of breaking the once fall-through edge from the tail to the top 25480b57cec5SDimitry Andric // of the loop chain. Here we need to consider three cases: 25490b57cec5SDimitry Andric // 1. If the tail node has only one successor, then we will get an 25500b57cec5SDimitry Andric // additional jmp instruction. So the cost here is (MisfetchCost + 25510b57cec5SDimitry Andric // JumpInstCost) * tail node frequency. 25520b57cec5SDimitry Andric // 2. If the tail node has two successors, then we may still get an 25530b57cec5SDimitry Andric // additional jmp instruction if the layout successor after the loop 25540b57cec5SDimitry Andric // chain is not its CFG successor. Note that the more frequently executed 25550b57cec5SDimitry Andric // jmp instruction will be put ahead of the other one. Assume the 25560b57cec5SDimitry Andric // frequency of those two branches are x and y, where x is the frequency 25570b57cec5SDimitry Andric // of the edge to the chain head, then the cost will be 25580b57cec5SDimitry Andric // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 25590b57cec5SDimitry Andric // 3. If the tail node has more than two successors (this rarely happens), 25600b57cec5SDimitry Andric // we won't consider any additional cost. 25610b57cec5SDimitry Andric if (TailBB->isSuccessor(*Iter)) { 25620b57cec5SDimitry Andric auto TailBBFreq = MBFI->getBlockFreq(TailBB); 25630b57cec5SDimitry Andric if (TailBB->succ_size() == 1) 25645f757f3fSDimitry Andric Cost += ScaleBlockFrequency(TailBBFreq, MisfetchCost + JumpInstCost); 25650b57cec5SDimitry Andric else if (TailBB->succ_size() == 2) { 25660b57cec5SDimitry Andric auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 25670b57cec5SDimitry Andric auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 25680b57cec5SDimitry Andric auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 25690b57cec5SDimitry Andric ? TailBBFreq * TailToHeadProb.getCompl() 25700b57cec5SDimitry Andric : TailToHeadFreq; 25710b57cec5SDimitry Andric Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 25720b57cec5SDimitry Andric ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 25730b57cec5SDimitry Andric } 25740b57cec5SDimitry Andric } 25750b57cec5SDimitry Andric 25760b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "The cost of loop rotation by making " 25775f757f3fSDimitry Andric << getBlockName(*Iter) << " to the top: " 25785f757f3fSDimitry Andric << printBlockFreq(MBFI->getMBFI(), Cost) << "\n"); 25790b57cec5SDimitry Andric 25800b57cec5SDimitry Andric if (Cost < SmallestRotationCost) { 25810b57cec5SDimitry Andric SmallestRotationCost = Cost; 25820b57cec5SDimitry Andric RotationPos = Iter; 25830b57cec5SDimitry Andric } 25840b57cec5SDimitry Andric } 25850b57cec5SDimitry Andric 25860b57cec5SDimitry Andric if (RotationPos != LoopChain.end()) { 25870b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 25880b57cec5SDimitry Andric << " to the top\n"); 25890b57cec5SDimitry Andric std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 25900b57cec5SDimitry Andric } 25910b57cec5SDimitry Andric } 25920b57cec5SDimitry Andric 25930b57cec5SDimitry Andric /// Collect blocks in the given loop that are to be placed. 25940b57cec5SDimitry Andric /// 25950b57cec5SDimitry Andric /// When profile data is available, exclude cold blocks from the returned set; 25960b57cec5SDimitry Andric /// otherwise, collect all blocks in the loop. 25970b57cec5SDimitry Andric MachineBlockPlacement::BlockFilterSet 25980b57cec5SDimitry Andric MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) { 25990b57cec5SDimitry Andric BlockFilterSet LoopBlockSet; 26000b57cec5SDimitry Andric 26010b57cec5SDimitry Andric // Filter cold blocks off from LoopBlockSet when profile data is available. 26020b57cec5SDimitry Andric // Collect the sum of frequencies of incoming edges to the loop header from 26030b57cec5SDimitry Andric // outside. If we treat the loop as a super block, this is the frequency of 26040b57cec5SDimitry Andric // the loop. Then for each block in the loop, we calculate the ratio between 26050b57cec5SDimitry Andric // its frequency and the frequency of the loop block. When it is too small, 26060b57cec5SDimitry Andric // don't add it to the loop chain. If there are outer loops, then this block 26070b57cec5SDimitry Andric // will be merged into the first outer loop chain for which this block is not 26080b57cec5SDimitry Andric // cold anymore. This needs precise profile data and we only do this when 26090b57cec5SDimitry Andric // profile data is available. 26100b57cec5SDimitry Andric if (F->getFunction().hasProfileData() || ForceLoopColdBlock) { 26110b57cec5SDimitry Andric BlockFrequency LoopFreq(0); 2612fcaf7f86SDimitry Andric for (auto *LoopPred : L.getHeader()->predecessors()) 26130b57cec5SDimitry Andric if (!L.contains(LoopPred)) 26140b57cec5SDimitry Andric LoopFreq += MBFI->getBlockFreq(LoopPred) * 26150b57cec5SDimitry Andric MBPI->getEdgeProbability(LoopPred, L.getHeader()); 26160b57cec5SDimitry Andric 26170b57cec5SDimitry Andric for (MachineBasicBlock *LoopBB : L.getBlocks()) { 2618e8d8bef9SDimitry Andric if (LoopBlockSet.count(LoopBB)) 2619e8d8bef9SDimitry Andric continue; 26200b57cec5SDimitry Andric auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 26210b57cec5SDimitry Andric if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 26220b57cec5SDimitry Andric continue; 2623e8d8bef9SDimitry Andric BlockChain *Chain = BlockToChain[LoopBB]; 2624e8d8bef9SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) 2625e8d8bef9SDimitry Andric LoopBlockSet.insert(ChainBB); 26260b57cec5SDimitry Andric } 26270b57cec5SDimitry Andric } else 26280b57cec5SDimitry Andric LoopBlockSet.insert(L.block_begin(), L.block_end()); 26290b57cec5SDimitry Andric 26300b57cec5SDimitry Andric return LoopBlockSet; 26310b57cec5SDimitry Andric } 26320b57cec5SDimitry Andric 26330b57cec5SDimitry Andric /// Forms basic block chains from the natural loop structures. 26340b57cec5SDimitry Andric /// 26350b57cec5SDimitry Andric /// These chains are designed to preserve the existing *structure* of the code 26360b57cec5SDimitry Andric /// as much as possible. We can then stitch the chains together in a way which 26370b57cec5SDimitry Andric /// both preserves the topological structure and minimizes taken conditional 26380b57cec5SDimitry Andric /// branches. 26390b57cec5SDimitry Andric void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) { 26400b57cec5SDimitry Andric // First recurse through any nested loops, building chains for those inner 26410b57cec5SDimitry Andric // loops. 26420b57cec5SDimitry Andric for (const MachineLoop *InnerLoop : L) 26430b57cec5SDimitry Andric buildLoopChains(*InnerLoop); 26440b57cec5SDimitry Andric 26450b57cec5SDimitry Andric assert(BlockWorkList.empty() && 26460b57cec5SDimitry Andric "BlockWorkList not empty when starting to build loop chains."); 26470b57cec5SDimitry Andric assert(EHPadWorkList.empty() && 26480b57cec5SDimitry Andric "EHPadWorkList not empty when starting to build loop chains."); 26490b57cec5SDimitry Andric BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 26500b57cec5SDimitry Andric 26510b57cec5SDimitry Andric // Check if we have profile data for this function. If yes, we will rotate 26520b57cec5SDimitry Andric // this loop by modeling costs more precisely which requires the profile data 26530b57cec5SDimitry Andric // for better layout. 26540b57cec5SDimitry Andric bool RotateLoopWithProfile = 26550b57cec5SDimitry Andric ForcePreciseRotationCost || 26560b57cec5SDimitry Andric (PreciseRotationCost && F->getFunction().hasProfileData()); 26570b57cec5SDimitry Andric 26580b57cec5SDimitry Andric // First check to see if there is an obviously preferable top block for the 26590b57cec5SDimitry Andric // loop. This will default to the header, but may end up as one of the 26600b57cec5SDimitry Andric // predecessors to the header if there is one which will result in strictly 26610b57cec5SDimitry Andric // fewer branches in the loop body. 26620b57cec5SDimitry Andric MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet); 26630b57cec5SDimitry Andric 26640b57cec5SDimitry Andric // If we selected just the header for the loop top, look for a potentially 26650b57cec5SDimitry Andric // profitable exit block in the event that rotating the loop can eliminate 26660b57cec5SDimitry Andric // branches by placing an exit edge at the bottom. 26670b57cec5SDimitry Andric // 26680b57cec5SDimitry Andric // Loops are processed innermost to uttermost, make sure we clear 26690b57cec5SDimitry Andric // PreferredLoopExit before processing a new loop. 26700b57cec5SDimitry Andric PreferredLoopExit = nullptr; 26710b57cec5SDimitry Andric BlockFrequency ExitFreq; 26720b57cec5SDimitry Andric if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 26730b57cec5SDimitry Andric PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq); 26740b57cec5SDimitry Andric 26750b57cec5SDimitry Andric BlockChain &LoopChain = *BlockToChain[LoopTop]; 26760b57cec5SDimitry Andric 26770b57cec5SDimitry Andric // FIXME: This is a really lame way of walking the chains in the loop: we 26780b57cec5SDimitry Andric // walk the blocks, and use a set to prevent visiting a particular chain 26790b57cec5SDimitry Andric // twice. 26800b57cec5SDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 26810b57cec5SDimitry Andric assert(LoopChain.UnscheduledPredecessors == 0 && 26820b57cec5SDimitry Andric "LoopChain should not have unscheduled predecessors."); 26830b57cec5SDimitry Andric UpdatedPreds.insert(&LoopChain); 26840b57cec5SDimitry Andric 26850b57cec5SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 26860b57cec5SDimitry Andric fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 26870b57cec5SDimitry Andric 26880b57cec5SDimitry Andric buildChain(LoopTop, LoopChain, &LoopBlockSet); 26890b57cec5SDimitry Andric 26900b57cec5SDimitry Andric if (RotateLoopWithProfile) 26910b57cec5SDimitry Andric rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 26920b57cec5SDimitry Andric else 26930b57cec5SDimitry Andric rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet); 26940b57cec5SDimitry Andric 26950b57cec5SDimitry Andric LLVM_DEBUG({ 26960b57cec5SDimitry Andric // Crash at the end so we get all of the debugging output first. 26970b57cec5SDimitry Andric bool BadLoop = false; 26980b57cec5SDimitry Andric if (LoopChain.UnscheduledPredecessors) { 26990b57cec5SDimitry Andric BadLoop = true; 27000b57cec5SDimitry Andric dbgs() << "Loop chain contains a block without its preds placed!\n" 27010b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 27020b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 27030b57cec5SDimitry Andric } 27040b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : LoopChain) { 27050b57cec5SDimitry Andric dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 27060b57cec5SDimitry Andric if (!LoopBlockSet.remove(ChainBB)) { 27070b57cec5SDimitry Andric // We don't mark the loop as bad here because there are real situations 27080b57cec5SDimitry Andric // where this can occur. For example, with an unanalyzable fallthrough 27090b57cec5SDimitry Andric // from a loop block to a non-loop block or vice versa. 27100b57cec5SDimitry Andric dbgs() << "Loop chain contains a block not contained by the loop!\n" 27110b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 27120b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 27130b57cec5SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 27140b57cec5SDimitry Andric } 27150b57cec5SDimitry Andric } 27160b57cec5SDimitry Andric 27170b57cec5SDimitry Andric if (!LoopBlockSet.empty()) { 27180b57cec5SDimitry Andric BadLoop = true; 27190b57cec5SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 27200b57cec5SDimitry Andric dbgs() << "Loop contains blocks never placed into a chain!\n" 27210b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 27220b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 27230b57cec5SDimitry Andric << " Bad block: " << getBlockName(LoopBB) << "\n"; 27240b57cec5SDimitry Andric } 27250b57cec5SDimitry Andric assert(!BadLoop && "Detected problems with the placement of this loop."); 27260b57cec5SDimitry Andric }); 27270b57cec5SDimitry Andric 27280b57cec5SDimitry Andric BlockWorkList.clear(); 27290b57cec5SDimitry Andric EHPadWorkList.clear(); 27300b57cec5SDimitry Andric } 27310b57cec5SDimitry Andric 27320b57cec5SDimitry Andric void MachineBlockPlacement::buildCFGChains() { 27330b57cec5SDimitry Andric // Ensure that every BB in the function has an associated chain to simplify 27340b57cec5SDimitry Andric // the assumptions of the remaining algorithm. 27355ffd83dbSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 27360b57cec5SDimitry Andric for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 27370b57cec5SDimitry Andric ++FI) { 27380b57cec5SDimitry Andric MachineBasicBlock *BB = &*FI; 27390b57cec5SDimitry Andric BlockChain *Chain = 27400b57cec5SDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 27410b57cec5SDimitry Andric // Also, merge any blocks which we cannot reason about and must preserve 27420b57cec5SDimitry Andric // the exact fallthrough behavior for. 27430b57cec5SDimitry Andric while (true) { 27440b57cec5SDimitry Andric Cond.clear(); 27455ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 27460b57cec5SDimitry Andric if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 27470b57cec5SDimitry Andric break; 27480b57cec5SDimitry Andric 27490b57cec5SDimitry Andric MachineFunction::iterator NextFI = std::next(FI); 27500b57cec5SDimitry Andric MachineBasicBlock *NextBB = &*NextFI; 27510b57cec5SDimitry Andric // Ensure that the layout successor is a viable block, as we know that 27520b57cec5SDimitry Andric // fallthrough is a possibility. 27530b57cec5SDimitry Andric assert(NextFI != FE && "Can't fallthrough past the last block."); 27540b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 27550b57cec5SDimitry Andric << getBlockName(BB) << " -> " << getBlockName(NextBB) 27560b57cec5SDimitry Andric << "\n"); 27570b57cec5SDimitry Andric Chain->merge(NextBB, nullptr); 27580b57cec5SDimitry Andric #ifndef NDEBUG 27590b57cec5SDimitry Andric BlocksWithUnanalyzableExits.insert(&*BB); 27600b57cec5SDimitry Andric #endif 27610b57cec5SDimitry Andric FI = NextFI; 27620b57cec5SDimitry Andric BB = NextBB; 27630b57cec5SDimitry Andric } 27640b57cec5SDimitry Andric } 27650b57cec5SDimitry Andric 27660b57cec5SDimitry Andric // Build any loop-based chains. 27670b57cec5SDimitry Andric PreferredLoopExit = nullptr; 27680b57cec5SDimitry Andric for (MachineLoop *L : *MLI) 27690b57cec5SDimitry Andric buildLoopChains(*L); 27700b57cec5SDimitry Andric 27710b57cec5SDimitry Andric assert(BlockWorkList.empty() && 27720b57cec5SDimitry Andric "BlockWorkList should be empty before building final chain."); 27730b57cec5SDimitry Andric assert(EHPadWorkList.empty() && 27740b57cec5SDimitry Andric "EHPadWorkList should be empty before building final chain."); 27750b57cec5SDimitry Andric 27760b57cec5SDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 27770b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *F) 27780b57cec5SDimitry Andric fillWorkLists(&MBB, UpdatedPreds); 27790b57cec5SDimitry Andric 27800b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 27810b57cec5SDimitry Andric buildChain(&F->front(), FunctionChain); 27820b57cec5SDimitry Andric 27830b57cec5SDimitry Andric #ifndef NDEBUG 27840b57cec5SDimitry Andric using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>; 27850b57cec5SDimitry Andric #endif 27860b57cec5SDimitry Andric LLVM_DEBUG({ 27870b57cec5SDimitry Andric // Crash at the end so we get all of the debugging output first. 27880b57cec5SDimitry Andric bool BadFunc = false; 27890b57cec5SDimitry Andric FunctionBlockSetType FunctionBlockSet; 27900b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *F) 27910b57cec5SDimitry Andric FunctionBlockSet.insert(&MBB); 27920b57cec5SDimitry Andric 27930b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) 27940b57cec5SDimitry Andric if (!FunctionBlockSet.erase(ChainBB)) { 27950b57cec5SDimitry Andric BadFunc = true; 27960b57cec5SDimitry Andric dbgs() << "Function chain contains a block not in the function!\n" 27970b57cec5SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 27980b57cec5SDimitry Andric } 27990b57cec5SDimitry Andric 28000b57cec5SDimitry Andric if (!FunctionBlockSet.empty()) { 28010b57cec5SDimitry Andric BadFunc = true; 28020b57cec5SDimitry Andric for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 28030b57cec5SDimitry Andric dbgs() << "Function contains blocks never placed into a chain!\n" 28040b57cec5SDimitry Andric << " Bad block: " << getBlockName(RemainingBB) << "\n"; 28050b57cec5SDimitry Andric } 28060b57cec5SDimitry Andric assert(!BadFunc && "Detected problems with the block placement."); 28070b57cec5SDimitry Andric }); 28080b57cec5SDimitry Andric 28095ffd83dbSDimitry Andric // Remember original layout ordering, so we can update terminators after 28105ffd83dbSDimitry Andric // reordering to point to the original layout successor. 28115ffd83dbSDimitry Andric SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors( 28125ffd83dbSDimitry Andric F->getNumBlockIDs()); 28135ffd83dbSDimitry Andric { 28145ffd83dbSDimitry Andric MachineBasicBlock *LastMBB = nullptr; 28155ffd83dbSDimitry Andric for (auto &MBB : *F) { 28165ffd83dbSDimitry Andric if (LastMBB != nullptr) 28175ffd83dbSDimitry Andric OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB; 28185ffd83dbSDimitry Andric LastMBB = &MBB; 28195ffd83dbSDimitry Andric } 28205ffd83dbSDimitry Andric OriginalLayoutSuccessors[F->back().getNumber()] = nullptr; 28215ffd83dbSDimitry Andric } 28225ffd83dbSDimitry Andric 28230b57cec5SDimitry Andric // Splice the blocks into place. 28240b57cec5SDimitry Andric MachineFunction::iterator InsertPos = F->begin(); 28250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n"); 28260b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 28270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 28280b57cec5SDimitry Andric : " ... ") 28290b57cec5SDimitry Andric << getBlockName(ChainBB) << "\n"); 28300b57cec5SDimitry Andric if (InsertPos != MachineFunction::iterator(ChainBB)) 28310b57cec5SDimitry Andric F->splice(InsertPos, ChainBB); 28320b57cec5SDimitry Andric else 28330b57cec5SDimitry Andric ++InsertPos; 28340b57cec5SDimitry Andric 28350b57cec5SDimitry Andric // Update the terminator of the previous block. 28360b57cec5SDimitry Andric if (ChainBB == *FunctionChain.begin()) 28370b57cec5SDimitry Andric continue; 28380b57cec5SDimitry Andric MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 28390b57cec5SDimitry Andric 28400b57cec5SDimitry Andric // FIXME: It would be awesome of updateTerminator would just return rather 28410b57cec5SDimitry Andric // than assert when the branch cannot be analyzed in order to remove this 28420b57cec5SDimitry Andric // boiler plate. 28430b57cec5SDimitry Andric Cond.clear(); 28445ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 28450b57cec5SDimitry Andric 28460b57cec5SDimitry Andric #ifndef NDEBUG 28470b57cec5SDimitry Andric if (!BlocksWithUnanalyzableExits.count(PrevBB)) { 28480b57cec5SDimitry Andric // Given the exact block placement we chose, we may actually not _need_ to 28490b57cec5SDimitry Andric // be able to edit PrevBB's terminator sequence, but not being _able_ to 28500b57cec5SDimitry Andric // do that at this point is a bug. 28510b57cec5SDimitry Andric assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) || 28520b57cec5SDimitry Andric !PrevBB->canFallThrough()) && 28530b57cec5SDimitry Andric "Unexpected block with un-analyzable fallthrough!"); 28540b57cec5SDimitry Andric Cond.clear(); 28550b57cec5SDimitry Andric TBB = FBB = nullptr; 28560b57cec5SDimitry Andric } 28570b57cec5SDimitry Andric #endif 28580b57cec5SDimitry Andric 28590b57cec5SDimitry Andric // The "PrevBB" is not yet updated to reflect current code layout, so, 28600b57cec5SDimitry Andric // o. it may fall-through to a block without explicit "goto" instruction 28610b57cec5SDimitry Andric // before layout, and no longer fall-through it after layout; or 28620b57cec5SDimitry Andric // o. just opposite. 28630b57cec5SDimitry Andric // 28640b57cec5SDimitry Andric // analyzeBranch() may return erroneous value for FBB when these two 28650b57cec5SDimitry Andric // situations take place. For the first scenario FBB is mistakenly set NULL; 28660b57cec5SDimitry Andric // for the 2nd scenario, the FBB, which is expected to be NULL, is 28670b57cec5SDimitry Andric // mistakenly pointing to "*BI". 28680b57cec5SDimitry Andric // Thus, if the future change needs to use FBB before the layout is set, it 28690b57cec5SDimitry Andric // has to correct FBB first by using the code similar to the following: 28700b57cec5SDimitry Andric // 28710b57cec5SDimitry Andric // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 28720b57cec5SDimitry Andric // PrevBB->updateTerminator(); 28730b57cec5SDimitry Andric // Cond.clear(); 28740b57cec5SDimitry Andric // TBB = FBB = nullptr; 28750b57cec5SDimitry Andric // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 28760b57cec5SDimitry Andric // // FIXME: This should never take place. 28770b57cec5SDimitry Andric // TBB = FBB = nullptr; 28780b57cec5SDimitry Andric // } 28790b57cec5SDimitry Andric // } 28805ffd83dbSDimitry Andric if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 28815ffd83dbSDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 28825ffd83dbSDimitry Andric } 28830b57cec5SDimitry Andric } 28840b57cec5SDimitry Andric 28850b57cec5SDimitry Andric // Fixup the last block. 28860b57cec5SDimitry Andric Cond.clear(); 28875ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 28885ffd83dbSDimitry Andric if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) { 28895ffd83dbSDimitry Andric MachineBasicBlock *PrevBB = &F->back(); 28905ffd83dbSDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 28915ffd83dbSDimitry Andric } 28920b57cec5SDimitry Andric 28930b57cec5SDimitry Andric BlockWorkList.clear(); 28940b57cec5SDimitry Andric EHPadWorkList.clear(); 28950b57cec5SDimitry Andric } 28960b57cec5SDimitry Andric 28970b57cec5SDimitry Andric void MachineBlockPlacement::optimizeBranches() { 28980b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 28995ffd83dbSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 29000b57cec5SDimitry Andric 29010b57cec5SDimitry Andric // Now that all the basic blocks in the chain have the proper layout, 29025ffd83dbSDimitry Andric // make a final call to analyzeBranch with AllowModify set. 29030b57cec5SDimitry Andric // Indeed, the target may be able to optimize the branches in a way we 29040b57cec5SDimitry Andric // cannot because all branches may not be analyzable. 29050b57cec5SDimitry Andric // E.g., the target may be able to remove an unconditional branch to 29060b57cec5SDimitry Andric // a fallthrough when it occurs after predicated terminators. 29070b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 29080b57cec5SDimitry Andric Cond.clear(); 29095ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 29100b57cec5SDimitry Andric if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 29110b57cec5SDimitry Andric // If PrevBB has a two-way branch, try to re-order the branches 29120b57cec5SDimitry Andric // such that we branch to the successor with higher probability first. 29130b57cec5SDimitry Andric if (TBB && !Cond.empty() && FBB && 29140b57cec5SDimitry Andric MBPI->getEdgeProbability(ChainBB, FBB) > 29150b57cec5SDimitry Andric MBPI->getEdgeProbability(ChainBB, TBB) && 29160b57cec5SDimitry Andric !TII->reverseBranchCondition(Cond)) { 29170b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Reverse order of the two branches: " 29180b57cec5SDimitry Andric << getBlockName(ChainBB) << "\n"); 29190b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Edge probability: " 29200b57cec5SDimitry Andric << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 29210b57cec5SDimitry Andric << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 29220b57cec5SDimitry Andric DebugLoc dl; // FIXME: this is nowhere 29230b57cec5SDimitry Andric TII->removeBranch(*ChainBB); 29240b57cec5SDimitry Andric TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 29250b57cec5SDimitry Andric } 29260b57cec5SDimitry Andric } 29270b57cec5SDimitry Andric } 29280b57cec5SDimitry Andric } 29290b57cec5SDimitry Andric 29300b57cec5SDimitry Andric void MachineBlockPlacement::alignBlocks() { 29310b57cec5SDimitry Andric // Walk through the backedges of the function now that we have fully laid out 29320b57cec5SDimitry Andric // the basic blocks and align the destination of each backedge. We don't rely 29330b57cec5SDimitry Andric // exclusively on the loop info here so that we can align backedges in 29340b57cec5SDimitry Andric // unnatural CFGs and backedges that were introduced purely because of the 29350b57cec5SDimitry Andric // loop rotations done during this layout pass. 29360b57cec5SDimitry Andric if (F->getFunction().hasMinSize() || 29370b57cec5SDimitry Andric (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize())) 29380b57cec5SDimitry Andric return; 29390b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 29400b57cec5SDimitry Andric if (FunctionChain.begin() == FunctionChain.end()) 29410b57cec5SDimitry Andric return; // Empty chain. 29420b57cec5SDimitry Andric 29430b57cec5SDimitry Andric const BranchProbability ColdProb(1, 5); // 20% 29440b57cec5SDimitry Andric BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 29450b57cec5SDimitry Andric BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 29460b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 29470b57cec5SDimitry Andric if (ChainBB == *FunctionChain.begin()) 29480b57cec5SDimitry Andric continue; 29490b57cec5SDimitry Andric 29500b57cec5SDimitry Andric // Don't align non-looping basic blocks. These are unlikely to execute 29510b57cec5SDimitry Andric // enough times to matter in practice. Note that we'll still handle 29520b57cec5SDimitry Andric // unnatural CFGs inside of a natural outer loop (the common case) and 29530b57cec5SDimitry Andric // rotated loops. 29540b57cec5SDimitry Andric MachineLoop *L = MLI->getLoopFor(ChainBB); 29550b57cec5SDimitry Andric if (!L) 29560b57cec5SDimitry Andric continue; 29570b57cec5SDimitry Andric 29585f757f3fSDimitry Andric const Align TLIAlign = TLI->getPrefLoopAlignment(L); 29595f757f3fSDimitry Andric unsigned MDAlign = 1; 29605f757f3fSDimitry Andric MDNode *LoopID = L->getLoopID(); 29615f757f3fSDimitry Andric if (LoopID) { 2962*0fca6ea1SDimitry Andric for (const MDOperand &MDO : llvm::drop_begin(LoopID->operands())) { 2963*0fca6ea1SDimitry Andric MDNode *MD = dyn_cast<MDNode>(MDO); 29645f757f3fSDimitry Andric if (MD == nullptr) 29655f757f3fSDimitry Andric continue; 29665f757f3fSDimitry Andric MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 29675f757f3fSDimitry Andric if (S == nullptr) 29685f757f3fSDimitry Andric continue; 29695f757f3fSDimitry Andric if (S->getString() == "llvm.loop.align") { 29705f757f3fSDimitry Andric assert(MD->getNumOperands() == 2 && 29715f757f3fSDimitry Andric "per-loop align metadata should have two operands."); 29725f757f3fSDimitry Andric MDAlign = 29735f757f3fSDimitry Andric mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 29745f757f3fSDimitry Andric assert(MDAlign >= 1 && "per-loop align value must be positive."); 29755f757f3fSDimitry Andric } 29765f757f3fSDimitry Andric } 29775f757f3fSDimitry Andric } 29785f757f3fSDimitry Andric 29795f757f3fSDimitry Andric // Use max of the TLIAlign and MDAlign 29805f757f3fSDimitry Andric const Align LoopAlign = std::max(TLIAlign, Align(MDAlign)); 29815f757f3fSDimitry Andric if (LoopAlign == 1) 29820b57cec5SDimitry Andric continue; // Don't care about loop alignment. 29830b57cec5SDimitry Andric 29840b57cec5SDimitry Andric // If the block is cold relative to the function entry don't waste space 29850b57cec5SDimitry Andric // aligning it. 29860b57cec5SDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 29870b57cec5SDimitry Andric if (Freq < WeightedEntryFreq) 29880b57cec5SDimitry Andric continue; 29890b57cec5SDimitry Andric 29900b57cec5SDimitry Andric // If the block is cold relative to its loop header, don't align it 29910b57cec5SDimitry Andric // regardless of what edges into the block exist. 29920b57cec5SDimitry Andric MachineBasicBlock *LoopHeader = L->getHeader(); 29930b57cec5SDimitry Andric BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 29940b57cec5SDimitry Andric if (Freq < (LoopHeaderFreq * ColdProb)) 29950b57cec5SDimitry Andric continue; 29960b57cec5SDimitry Andric 2997480093f4SDimitry Andric // If the global profiles indicates so, don't align it. 29985ffd83dbSDimitry Andric if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) && 2999480093f4SDimitry Andric !TLI->alignLoopsWithOptSize()) 3000480093f4SDimitry Andric continue; 3001480093f4SDimitry Andric 30020b57cec5SDimitry Andric // Check for the existence of a non-layout predecessor which would benefit 30030b57cec5SDimitry Andric // from aligning this block. 30040b57cec5SDimitry Andric MachineBasicBlock *LayoutPred = 30050b57cec5SDimitry Andric &*std::prev(MachineFunction::iterator(ChainBB)); 30060b57cec5SDimitry Andric 300704eeddc0SDimitry Andric auto DetermineMaxAlignmentPadding = [&]() { 300804eeddc0SDimitry Andric // Set the maximum bytes allowed to be emitted for alignment. 300904eeddc0SDimitry Andric unsigned MaxBytes; 301004eeddc0SDimitry Andric if (MaxBytesForAlignmentOverride.getNumOccurrences() > 0) 301104eeddc0SDimitry Andric MaxBytes = MaxBytesForAlignmentOverride; 301204eeddc0SDimitry Andric else 301304eeddc0SDimitry Andric MaxBytes = TLI->getMaxPermittedBytesForAlignment(ChainBB); 301404eeddc0SDimitry Andric ChainBB->setMaxBytesForAlignment(MaxBytes); 301504eeddc0SDimitry Andric }; 301604eeddc0SDimitry Andric 30170b57cec5SDimitry Andric // Force alignment if all the predecessors are jumps. We already checked 30180b57cec5SDimitry Andric // that the block isn't cold above. 30190b57cec5SDimitry Andric if (!LayoutPred->isSuccessor(ChainBB)) { 30205f757f3fSDimitry Andric ChainBB->setAlignment(LoopAlign); 302104eeddc0SDimitry Andric DetermineMaxAlignmentPadding(); 30220b57cec5SDimitry Andric continue; 30230b57cec5SDimitry Andric } 30240b57cec5SDimitry Andric 30250b57cec5SDimitry Andric // Align this block if the layout predecessor's edge into this block is 30260b57cec5SDimitry Andric // cold relative to the block. When this is true, other predecessors make up 30270b57cec5SDimitry Andric // all of the hot entries into the block and thus alignment is likely to be 30280b57cec5SDimitry Andric // important. 30290b57cec5SDimitry Andric BranchProbability LayoutProb = 30300b57cec5SDimitry Andric MBPI->getEdgeProbability(LayoutPred, ChainBB); 30310b57cec5SDimitry Andric BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 303204eeddc0SDimitry Andric if (LayoutEdgeFreq <= (Freq * ColdProb)) { 30335f757f3fSDimitry Andric ChainBB->setAlignment(LoopAlign); 303404eeddc0SDimitry Andric DetermineMaxAlignmentPadding(); 303504eeddc0SDimitry Andric } 30360b57cec5SDimitry Andric } 30370b57cec5SDimitry Andric } 30380b57cec5SDimitry Andric 30390b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 30400b57cec5SDimitry Andric /// it was duplicated into its chain predecessor and removed. 30410b57cec5SDimitry Andric /// \p BB - Basic block that may be duplicated. 30420b57cec5SDimitry Andric /// 30430b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB. 30440b57cec5SDimitry Andric /// Updated to be the chain end if LPred is removed. 30450b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 30460b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 30470b57cec5SDimitry Andric /// Used to identify which blocks to update predecessor 30480b57cec5SDimitry Andric /// counts. 30490b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 30500b57cec5SDimitry Andric /// chosen in the given order due to unnatural CFG 30510b57cec5SDimitry Andric /// only needed if \p BB is removed and 30520b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 30530b57cec5SDimitry Andric /// @return true if \p BB was removed. 30540b57cec5SDimitry Andric bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 30550b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 3056*0fca6ea1SDimitry Andric const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain, 3057*0fca6ea1SDimitry Andric BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt, 3058*0fca6ea1SDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt) { 30590b57cec5SDimitry Andric bool Removed, DuplicatedToLPred; 30600b57cec5SDimitry Andric bool DuplicatedToOriginalLPred; 3061*0fca6ea1SDimitry Andric Removed = maybeTailDuplicateBlock( 3062*0fca6ea1SDimitry Andric BB, LPred, Chain, BlockFilter, PrevUnplacedBlockIt, 3063*0fca6ea1SDimitry Andric PrevUnplacedBlockInFilterIt, DuplicatedToLPred); 30640b57cec5SDimitry Andric if (!Removed) 30650b57cec5SDimitry Andric return false; 30660b57cec5SDimitry Andric DuplicatedToOriginalLPred = DuplicatedToLPred; 30670b57cec5SDimitry Andric // Iteratively try to duplicate again. It can happen that a block that is 30680b57cec5SDimitry Andric // duplicated into is still small enough to be duplicated again. 30690b57cec5SDimitry Andric // No need to call markBlockSuccessors in this case, as the blocks being 30700b57cec5SDimitry Andric // duplicated from here on are already scheduled. 30715ffd83dbSDimitry Andric while (DuplicatedToLPred && Removed) { 30720b57cec5SDimitry Andric MachineBasicBlock *DupBB, *DupPred; 30730b57cec5SDimitry Andric // The removal callback causes Chain.end() to be updated when a block is 30740b57cec5SDimitry Andric // removed. On the first pass through the loop, the chain end should be the 30750b57cec5SDimitry Andric // same as it was on function entry. On subsequent passes, because we are 30760b57cec5SDimitry Andric // duplicating the block at the end of the chain, if it is removed the 30770b57cec5SDimitry Andric // chain will have shrunk by one block. 30780b57cec5SDimitry Andric BlockChain::iterator ChainEnd = Chain.end(); 30790b57cec5SDimitry Andric DupBB = *(--ChainEnd); 30800b57cec5SDimitry Andric // Now try to duplicate again. 30810b57cec5SDimitry Andric if (ChainEnd == Chain.begin()) 30820b57cec5SDimitry Andric break; 30830b57cec5SDimitry Andric DupPred = *std::prev(ChainEnd); 3084*0fca6ea1SDimitry Andric Removed = maybeTailDuplicateBlock( 3085*0fca6ea1SDimitry Andric DupBB, DupPred, Chain, BlockFilter, PrevUnplacedBlockIt, 3086*0fca6ea1SDimitry Andric PrevUnplacedBlockInFilterIt, DuplicatedToLPred); 30870b57cec5SDimitry Andric } 30880b57cec5SDimitry Andric // If BB was duplicated into LPred, it is now scheduled. But because it was 30890b57cec5SDimitry Andric // removed, markChainSuccessors won't be called for its chain. Instead we 30900b57cec5SDimitry Andric // call markBlockSuccessors for LPred to achieve the same effect. This must go 30910b57cec5SDimitry Andric // at the end because repeating the tail duplication can increase the number 30920b57cec5SDimitry Andric // of unscheduled predecessors. 30930b57cec5SDimitry Andric LPred = *std::prev(Chain.end()); 30940b57cec5SDimitry Andric if (DuplicatedToOriginalLPred) 30950b57cec5SDimitry Andric markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 30960b57cec5SDimitry Andric return true; 30970b57cec5SDimitry Andric } 30980b57cec5SDimitry Andric 30990b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable. 31000b57cec5SDimitry Andric /// \p BB - Basic block that may be duplicated 31010b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB 31020b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 31030b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 31040b57cec5SDimitry Andric /// Used to identify which blocks to update predecessor 31050b57cec5SDimitry Andric /// counts. 31060b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 31070b57cec5SDimitry Andric /// chosen in the given order due to unnatural CFG 31080b57cec5SDimitry Andric /// only needed if \p BB is removed and 31090b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 31105ffd83dbSDimitry Andric /// \p DuplicatedToLPred - True if the block was duplicated into LPred. 31110b57cec5SDimitry Andric /// \return - True if the block was duplicated into all preds and removed. 31120b57cec5SDimitry Andric bool MachineBlockPlacement::maybeTailDuplicateBlock( 3113*0fca6ea1SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, BlockChain &Chain, 3114*0fca6ea1SDimitry Andric BlockFilterSet *BlockFilter, MachineFunction::iterator &PrevUnplacedBlockIt, 3115*0fca6ea1SDimitry Andric BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt, 31160b57cec5SDimitry Andric bool &DuplicatedToLPred) { 31170b57cec5SDimitry Andric DuplicatedToLPred = false; 31180b57cec5SDimitry Andric if (!shouldTailDuplicate(BB)) 31190b57cec5SDimitry Andric return false; 31200b57cec5SDimitry Andric 31210b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber() 31220b57cec5SDimitry Andric << "\n"); 31230b57cec5SDimitry Andric 31240b57cec5SDimitry Andric // This has to be a callback because none of it can be done after 31250b57cec5SDimitry Andric // BB is deleted. 31260b57cec5SDimitry Andric bool Removed = false; 31270b57cec5SDimitry Andric auto RemovalCallback = 31280b57cec5SDimitry Andric [&](MachineBasicBlock *RemBB) { 31290b57cec5SDimitry Andric // Signal to outer function 31300b57cec5SDimitry Andric Removed = true; 31310b57cec5SDimitry Andric 31320b57cec5SDimitry Andric // Conservative default. 31330b57cec5SDimitry Andric bool InWorkList = true; 31340b57cec5SDimitry Andric // Remove from the Chain and Chain Map 31350b57cec5SDimitry Andric if (BlockToChain.count(RemBB)) { 31360b57cec5SDimitry Andric BlockChain *Chain = BlockToChain[RemBB]; 31370b57cec5SDimitry Andric InWorkList = Chain->UnscheduledPredecessors == 0; 31380b57cec5SDimitry Andric Chain->remove(RemBB); 31390b57cec5SDimitry Andric BlockToChain.erase(RemBB); 31400b57cec5SDimitry Andric } 31410b57cec5SDimitry Andric 31420b57cec5SDimitry Andric // Handle the unplaced block iterator 31430b57cec5SDimitry Andric if (&(*PrevUnplacedBlockIt) == RemBB) { 31440b57cec5SDimitry Andric PrevUnplacedBlockIt++; 31450b57cec5SDimitry Andric } 31460b57cec5SDimitry Andric 31470b57cec5SDimitry Andric // Handle the Work Lists 31480b57cec5SDimitry Andric if (InWorkList) { 31490b57cec5SDimitry Andric SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 31500b57cec5SDimitry Andric if (RemBB->isEHPad()) 31510b57cec5SDimitry Andric RemoveList = EHPadWorkList; 31525f757f3fSDimitry Andric llvm::erase(RemoveList, RemBB); 31530b57cec5SDimitry Andric } 31540b57cec5SDimitry Andric 31550b57cec5SDimitry Andric // Handle the filter set 31560b57cec5SDimitry Andric if (BlockFilter) { 3157*0fca6ea1SDimitry Andric auto It = llvm::find(*BlockFilter, RemBB); 3158*0fca6ea1SDimitry Andric // Erase RemBB from BlockFilter, and keep PrevUnplacedBlockInFilterIt 3159*0fca6ea1SDimitry Andric // pointing to the same element as before. 3160*0fca6ea1SDimitry Andric if (It != BlockFilter->end()) { 3161*0fca6ea1SDimitry Andric if (It < PrevUnplacedBlockInFilterIt) { 3162*0fca6ea1SDimitry Andric const MachineBasicBlock *PrevBB = *PrevUnplacedBlockInFilterIt; 3163*0fca6ea1SDimitry Andric // BlockFilter is a SmallVector so all elements after RemBB are 3164*0fca6ea1SDimitry Andric // shifted to the front by 1 after its deletion. 3165*0fca6ea1SDimitry Andric auto Distance = PrevUnplacedBlockInFilterIt - It - 1; 3166*0fca6ea1SDimitry Andric PrevUnplacedBlockInFilterIt = BlockFilter->erase(It) + Distance; 3167*0fca6ea1SDimitry Andric assert(*PrevUnplacedBlockInFilterIt == PrevBB); 3168*0fca6ea1SDimitry Andric (void)PrevBB; 3169*0fca6ea1SDimitry Andric } else if (It == PrevUnplacedBlockInFilterIt) 3170*0fca6ea1SDimitry Andric // The block pointed by PrevUnplacedBlockInFilterIt is erased, we 3171*0fca6ea1SDimitry Andric // have to set it to the next element. 3172*0fca6ea1SDimitry Andric PrevUnplacedBlockInFilterIt = BlockFilter->erase(It); 3173*0fca6ea1SDimitry Andric else 3174*0fca6ea1SDimitry Andric BlockFilter->erase(It); 3175*0fca6ea1SDimitry Andric } 31760b57cec5SDimitry Andric } 31770b57cec5SDimitry Andric 31780b57cec5SDimitry Andric // Remove the block from loop info. 31790b57cec5SDimitry Andric MLI->removeBlock(RemBB); 31800b57cec5SDimitry Andric if (RemBB == PreferredLoopExit) 31810b57cec5SDimitry Andric PreferredLoopExit = nullptr; 31820b57cec5SDimitry Andric 31830b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: " 31840b57cec5SDimitry Andric << getBlockName(RemBB) << "\n"); 31850b57cec5SDimitry Andric }; 31860b57cec5SDimitry Andric auto RemovalCallbackRef = 31870b57cec5SDimitry Andric function_ref<void(MachineBasicBlock*)>(RemovalCallback); 31880b57cec5SDimitry Andric 31890b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 31900b57cec5SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 31915ffd83dbSDimitry Andric SmallVector<MachineBasicBlock *, 8> CandidatePreds; 31925ffd83dbSDimitry Andric SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr; 31935ffd83dbSDimitry Andric if (F->getFunction().hasProfileData()) { 31945ffd83dbSDimitry Andric // We can do partial duplication with precise profile information. 31955ffd83dbSDimitry Andric findDuplicateCandidates(CandidatePreds, BB, BlockFilter); 31965ffd83dbSDimitry Andric if (CandidatePreds.size() == 0) 31975ffd83dbSDimitry Andric return false; 31985ffd83dbSDimitry Andric if (CandidatePreds.size() < BB->pred_size()) 31995ffd83dbSDimitry Andric CandidatePtr = &CandidatePreds; 32005ffd83dbSDimitry Andric } 32015ffd83dbSDimitry Andric TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds, 32025ffd83dbSDimitry Andric &RemovalCallbackRef, CandidatePtr); 32030b57cec5SDimitry Andric 32040b57cec5SDimitry Andric // Update UnscheduledPredecessors to reflect tail-duplication. 32050b57cec5SDimitry Andric DuplicatedToLPred = false; 32060b57cec5SDimitry Andric for (MachineBasicBlock *Pred : DuplicatedPreds) { 32070b57cec5SDimitry Andric // We're only looking for unscheduled predecessors that match the filter. 32080b57cec5SDimitry Andric BlockChain* PredChain = BlockToChain[Pred]; 32090b57cec5SDimitry Andric if (Pred == LPred) 32100b57cec5SDimitry Andric DuplicatedToLPred = true; 32110b57cec5SDimitry Andric if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 32120b57cec5SDimitry Andric || PredChain == &Chain) 32130b57cec5SDimitry Andric continue; 32140b57cec5SDimitry Andric for (MachineBasicBlock *NewSucc : Pred->successors()) { 32150b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(NewSucc)) 32160b57cec5SDimitry Andric continue; 32170b57cec5SDimitry Andric BlockChain *NewChain = BlockToChain[NewSucc]; 32180b57cec5SDimitry Andric if (NewChain != &Chain && NewChain != PredChain) 32190b57cec5SDimitry Andric NewChain->UnscheduledPredecessors++; 32200b57cec5SDimitry Andric } 32210b57cec5SDimitry Andric } 32220b57cec5SDimitry Andric return Removed; 32230b57cec5SDimitry Andric } 32240b57cec5SDimitry Andric 32255ffd83dbSDimitry Andric // Count the number of actual machine instructions. 32265ffd83dbSDimitry Andric static uint64_t countMBBInstruction(MachineBasicBlock *MBB) { 32275ffd83dbSDimitry Andric uint64_t InstrCount = 0; 32285ffd83dbSDimitry Andric for (MachineInstr &MI : *MBB) { 32295ffd83dbSDimitry Andric if (!MI.isPHI() && !MI.isMetaInstruction()) 32305ffd83dbSDimitry Andric InstrCount += 1; 32315ffd83dbSDimitry Andric } 32325ffd83dbSDimitry Andric return InstrCount; 32335ffd83dbSDimitry Andric } 32345ffd83dbSDimitry Andric 32355ffd83dbSDimitry Andric // The size cost of duplication is the instruction size of the duplicated block. 32365ffd83dbSDimitry Andric // So we should scale the threshold accordingly. But the instruction size is not 32375ffd83dbSDimitry Andric // available on all targets, so we use the number of instructions instead. 32385ffd83dbSDimitry Andric BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) { 32395f757f3fSDimitry Andric return BlockFrequency(DupThreshold.getFrequency() * countMBBInstruction(BB)); 32405ffd83dbSDimitry Andric } 32415ffd83dbSDimitry Andric 32425ffd83dbSDimitry Andric // Returns true if BB is Pred's best successor. 32435ffd83dbSDimitry Andric bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB, 32445ffd83dbSDimitry Andric MachineBasicBlock *Pred, 32455ffd83dbSDimitry Andric BlockFilterSet *BlockFilter) { 32465ffd83dbSDimitry Andric if (BB == Pred) 32475ffd83dbSDimitry Andric return false; 32485ffd83dbSDimitry Andric if (BlockFilter && !BlockFilter->count(Pred)) 32495ffd83dbSDimitry Andric return false; 32505ffd83dbSDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 32515ffd83dbSDimitry Andric if (PredChain && (Pred != *std::prev(PredChain->end()))) 32525ffd83dbSDimitry Andric return false; 32535ffd83dbSDimitry Andric 32545ffd83dbSDimitry Andric // Find the successor with largest probability excluding BB. 32555ffd83dbSDimitry Andric BranchProbability BestProb = BranchProbability::getZero(); 32565ffd83dbSDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) 32575ffd83dbSDimitry Andric if (Succ != BB) { 32585ffd83dbSDimitry Andric if (BlockFilter && !BlockFilter->count(Succ)) 32595ffd83dbSDimitry Andric continue; 32605ffd83dbSDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 32615ffd83dbSDimitry Andric if (SuccChain && (Succ != *SuccChain->begin())) 32625ffd83dbSDimitry Andric continue; 32635ffd83dbSDimitry Andric BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ); 32645ffd83dbSDimitry Andric if (SuccProb > BestProb) 32655ffd83dbSDimitry Andric BestProb = SuccProb; 32665ffd83dbSDimitry Andric } 32675ffd83dbSDimitry Andric 32685ffd83dbSDimitry Andric BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB); 32695ffd83dbSDimitry Andric if (BBProb <= BestProb) 32705ffd83dbSDimitry Andric return false; 32715ffd83dbSDimitry Andric 32725ffd83dbSDimitry Andric // Compute the number of reduced taken branches if Pred falls through to BB 32735ffd83dbSDimitry Andric // instead of another successor. Then compare it with threshold. 3274e8d8bef9SDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 32755ffd83dbSDimitry Andric BlockFrequency Gain = PredFreq * (BBProb - BestProb); 32765ffd83dbSDimitry Andric return Gain > scaleThreshold(BB); 32775ffd83dbSDimitry Andric } 32785ffd83dbSDimitry Andric 32795ffd83dbSDimitry Andric // Find out the predecessors of BB and BB can be beneficially duplicated into 32805ffd83dbSDimitry Andric // them. 32815ffd83dbSDimitry Andric void MachineBlockPlacement::findDuplicateCandidates( 32825ffd83dbSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &Candidates, 32835ffd83dbSDimitry Andric MachineBasicBlock *BB, 32845ffd83dbSDimitry Andric BlockFilterSet *BlockFilter) { 32855ffd83dbSDimitry Andric MachineBasicBlock *Fallthrough = nullptr; 32865ffd83dbSDimitry Andric BranchProbability DefaultBranchProb = BranchProbability::getZero(); 32875ffd83dbSDimitry Andric BlockFrequency BBDupThreshold(scaleThreshold(BB)); 3288e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors()); 3289e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> Succs(BB->successors()); 32905ffd83dbSDimitry Andric 32915ffd83dbSDimitry Andric // Sort for highest frequency. 32925ffd83dbSDimitry Andric auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 32935ffd83dbSDimitry Andric return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B); 32945ffd83dbSDimitry Andric }; 32955ffd83dbSDimitry Andric auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 32965ffd83dbSDimitry Andric return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B); 32975ffd83dbSDimitry Andric }; 32985ffd83dbSDimitry Andric llvm::stable_sort(Succs, CmpSucc); 32995ffd83dbSDimitry Andric llvm::stable_sort(Preds, CmpPred); 33005ffd83dbSDimitry Andric 33015ffd83dbSDimitry Andric auto SuccIt = Succs.begin(); 33025ffd83dbSDimitry Andric if (SuccIt != Succs.end()) { 33035ffd83dbSDimitry Andric DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl(); 33045ffd83dbSDimitry Andric } 33055ffd83dbSDimitry Andric 33065ffd83dbSDimitry Andric // For each predecessors of BB, compute the benefit of duplicating BB, 33075ffd83dbSDimitry Andric // if it is larger than the threshold, add it into Candidates. 33085ffd83dbSDimitry Andric // 33095ffd83dbSDimitry Andric // If we have following control flow. 33105ffd83dbSDimitry Andric // 33115ffd83dbSDimitry Andric // PB1 PB2 PB3 PB4 33125ffd83dbSDimitry Andric // \ | / /\ 33135ffd83dbSDimitry Andric // \ | / / \ 33145ffd83dbSDimitry Andric // \ |/ / \ 33155ffd83dbSDimitry Andric // BB----/ OB 33165ffd83dbSDimitry Andric // /\ 33175ffd83dbSDimitry Andric // / \ 33185ffd83dbSDimitry Andric // SB1 SB2 33195ffd83dbSDimitry Andric // 33205ffd83dbSDimitry Andric // And it can be partially duplicated as 33215ffd83dbSDimitry Andric // 33225ffd83dbSDimitry Andric // PB2+BB 33235ffd83dbSDimitry Andric // | PB1 PB3 PB4 33245ffd83dbSDimitry Andric // | | / /\ 33255ffd83dbSDimitry Andric // | | / / \ 33265ffd83dbSDimitry Andric // | |/ / \ 33275ffd83dbSDimitry Andric // | BB----/ OB 33285ffd83dbSDimitry Andric // |\ /| 33295ffd83dbSDimitry Andric // | X | 33305ffd83dbSDimitry Andric // |/ \| 33315ffd83dbSDimitry Andric // SB2 SB1 33325ffd83dbSDimitry Andric // 33335ffd83dbSDimitry Andric // The benefit of duplicating into a predecessor is defined as 33345ffd83dbSDimitry Andric // Orig_taken_branch - Duplicated_taken_branch 33355ffd83dbSDimitry Andric // 33365ffd83dbSDimitry Andric // The Orig_taken_branch is computed with the assumption that predecessor 33375ffd83dbSDimitry Andric // jumps to BB and the most possible successor is laid out after BB. 33385ffd83dbSDimitry Andric // 33395ffd83dbSDimitry Andric // The Duplicated_taken_branch is computed with the assumption that BB is 33405ffd83dbSDimitry Andric // duplicated into PB, and one successor is layout after it (SB1 for PB1 and 33415ffd83dbSDimitry Andric // SB2 for PB2 in our case). If there is no available successor, the combined 33425ffd83dbSDimitry Andric // block jumps to all BB's successor, like PB3 in this example. 33435ffd83dbSDimitry Andric // 33445ffd83dbSDimitry Andric // If a predecessor has multiple successors, so BB can't be duplicated into 33455ffd83dbSDimitry Andric // it. But it can beneficially fall through to BB, and duplicate BB into other 33465ffd83dbSDimitry Andric // predecessors. 33475ffd83dbSDimitry Andric for (MachineBasicBlock *Pred : Preds) { 3348e8d8bef9SDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 33495ffd83dbSDimitry Andric 33505ffd83dbSDimitry Andric if (!TailDup.canTailDuplicate(BB, Pred)) { 33515ffd83dbSDimitry Andric // BB can't be duplicated into Pred, but it is possible to be layout 33525ffd83dbSDimitry Andric // below Pred. 33535ffd83dbSDimitry Andric if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) { 33545ffd83dbSDimitry Andric Fallthrough = Pred; 33555ffd83dbSDimitry Andric if (SuccIt != Succs.end()) 33565ffd83dbSDimitry Andric SuccIt++; 33575ffd83dbSDimitry Andric } 33585ffd83dbSDimitry Andric continue; 33595ffd83dbSDimitry Andric } 33605ffd83dbSDimitry Andric 33615ffd83dbSDimitry Andric BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb; 33625ffd83dbSDimitry Andric BlockFrequency DupCost; 33635ffd83dbSDimitry Andric if (SuccIt == Succs.end()) { 33645ffd83dbSDimitry Andric // Jump to all successors; 33655ffd83dbSDimitry Andric if (Succs.size() > 0) 33665ffd83dbSDimitry Andric DupCost += PredFreq; 33675ffd83dbSDimitry Andric } else { 33685ffd83dbSDimitry Andric // Fallthrough to *SuccIt, jump to all other successors; 33695ffd83dbSDimitry Andric DupCost += PredFreq; 33705ffd83dbSDimitry Andric DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt); 33715ffd83dbSDimitry Andric } 33725ffd83dbSDimitry Andric 33735ffd83dbSDimitry Andric assert(OrigCost >= DupCost); 33745ffd83dbSDimitry Andric OrigCost -= DupCost; 33755ffd83dbSDimitry Andric if (OrigCost > BBDupThreshold) { 33765ffd83dbSDimitry Andric Candidates.push_back(Pred); 33775ffd83dbSDimitry Andric if (SuccIt != Succs.end()) 33785ffd83dbSDimitry Andric SuccIt++; 33795ffd83dbSDimitry Andric } 33805ffd83dbSDimitry Andric } 33815ffd83dbSDimitry Andric 33825ffd83dbSDimitry Andric // No predecessors can optimally fallthrough to BB. 33835ffd83dbSDimitry Andric // So we can change one duplication into fallthrough. 33845ffd83dbSDimitry Andric if (!Fallthrough) { 33855ffd83dbSDimitry Andric if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) { 33865ffd83dbSDimitry Andric Candidates[0] = Candidates.back(); 33875ffd83dbSDimitry Andric Candidates.pop_back(); 33885ffd83dbSDimitry Andric } 33895ffd83dbSDimitry Andric } 33905ffd83dbSDimitry Andric } 33915ffd83dbSDimitry Andric 33925ffd83dbSDimitry Andric void MachineBlockPlacement::initDupThreshold() { 33935f757f3fSDimitry Andric DupThreshold = BlockFrequency(0); 33945ffd83dbSDimitry Andric if (!F->getFunction().hasProfileData()) 33955ffd83dbSDimitry Andric return; 33965ffd83dbSDimitry Andric 3397e8d8bef9SDimitry Andric // We prefer to use prifile count. 3398e8d8bef9SDimitry Andric uint64_t HotThreshold = PSI->getOrCompHotCountThreshold(); 3399e8d8bef9SDimitry Andric if (HotThreshold != UINT64_MAX) { 3400e8d8bef9SDimitry Andric UseProfileCount = true; 34015f757f3fSDimitry Andric DupThreshold = 34025f757f3fSDimitry Andric BlockFrequency(HotThreshold * TailDupProfilePercentThreshold / 100); 3403e8d8bef9SDimitry Andric return; 3404e8d8bef9SDimitry Andric } 3405e8d8bef9SDimitry Andric 3406e8d8bef9SDimitry Andric // Profile count is not available, we can use block frequency instead. 34075f757f3fSDimitry Andric BlockFrequency MaxFreq = BlockFrequency(0); 34085ffd83dbSDimitry Andric for (MachineBasicBlock &MBB : *F) { 34095ffd83dbSDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(&MBB); 34105ffd83dbSDimitry Andric if (Freq > MaxFreq) 34115ffd83dbSDimitry Andric MaxFreq = Freq; 34125ffd83dbSDimitry Andric } 34135ffd83dbSDimitry Andric 34145ffd83dbSDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 34155f757f3fSDimitry Andric DupThreshold = BlockFrequency(MaxFreq * ThresholdProb); 3416e8d8bef9SDimitry Andric UseProfileCount = false; 34175ffd83dbSDimitry Andric } 34185ffd83dbSDimitry Andric 34190b57cec5SDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 34200b57cec5SDimitry Andric if (skipFunction(MF.getFunction())) 34210b57cec5SDimitry Andric return false; 34220b57cec5SDimitry Andric 34230b57cec5SDimitry Andric // Check for single-block functions and skip them. 34240b57cec5SDimitry Andric if (std::next(MF.begin()) == MF.end()) 34250b57cec5SDimitry Andric return false; 34260b57cec5SDimitry Andric 34270b57cec5SDimitry Andric F = &MF; 3428*0fca6ea1SDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI(); 34295ffd83dbSDimitry Andric MBFI = std::make_unique<MBFIWrapper>( 3430*0fca6ea1SDimitry Andric getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI()); 3431*0fca6ea1SDimitry Andric MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI(); 34320b57cec5SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 34330b57cec5SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 34340b57cec5SDimitry Andric MPDT = nullptr; 3435480093f4SDimitry Andric PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 34360b57cec5SDimitry Andric 34375ffd83dbSDimitry Andric initDupThreshold(); 34385ffd83dbSDimitry Andric 34390b57cec5SDimitry Andric // Initialize PreferredLoopExit to nullptr here since it may never be set if 34400b57cec5SDimitry Andric // there are no MachineLoops. 34410b57cec5SDimitry Andric PreferredLoopExit = nullptr; 34420b57cec5SDimitry Andric 34430b57cec5SDimitry Andric assert(BlockToChain.empty() && 34440b57cec5SDimitry Andric "BlockToChain map should be empty before starting placement."); 34450b57cec5SDimitry Andric assert(ComputedEdges.empty() && 34460b57cec5SDimitry Andric "Computed Edge map should be empty before starting placement."); 34470b57cec5SDimitry Andric 34480b57cec5SDimitry Andric unsigned TailDupSize = TailDupPlacementThreshold; 34490b57cec5SDimitry Andric // If only the aggressive threshold is explicitly set, use it. 34500b57cec5SDimitry Andric if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 && 34510b57cec5SDimitry Andric TailDupPlacementThreshold.getNumOccurrences() == 0) 34520b57cec5SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 34530b57cec5SDimitry Andric 34540b57cec5SDimitry Andric TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 34550b57cec5SDimitry Andric // For aggressive optimization, we can adjust some thresholds to be less 34560b57cec5SDimitry Andric // conservative. 34575f757f3fSDimitry Andric if (PassConfig->getOptLevel() >= CodeGenOptLevel::Aggressive) { 34580b57cec5SDimitry Andric // At O3 we should be more willing to copy blocks for tail duplication. This 34590b57cec5SDimitry Andric // increases size pressure, so we only do it at O3 34600b57cec5SDimitry Andric // Do this unless only the regular threshold is explicitly set. 34610b57cec5SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 || 34620b57cec5SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0) 34630b57cec5SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 34640b57cec5SDimitry Andric } 34650b57cec5SDimitry Andric 3466fe6060f1SDimitry Andric // If there's no threshold provided through options, query the target 3467fe6060f1SDimitry Andric // information for a threshold instead. 3468fe6060f1SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 && 34695f757f3fSDimitry Andric (PassConfig->getOptLevel() < CodeGenOptLevel::Aggressive || 3470fe6060f1SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0)) 3471fe6060f1SDimitry Andric TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel()); 3472fe6060f1SDimitry Andric 34730b57cec5SDimitry Andric if (allowTailDupPlacement()) { 3474*0fca6ea1SDimitry Andric MPDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree(); 3475480093f4SDimitry Andric bool OptForSize = MF.getFunction().hasOptSize() || 3476480093f4SDimitry Andric llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI()); 3477480093f4SDimitry Andric if (OptForSize) 34780b57cec5SDimitry Andric TailDupSize = 1; 34790b57cec5SDimitry Andric bool PreRegAlloc = false; 34805ffd83dbSDimitry Andric TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI, 3481480093f4SDimitry Andric /* LayoutMode */ true, TailDupSize); 34820b57cec5SDimitry Andric precomputeTriangleChains(); 34830b57cec5SDimitry Andric } 34840b57cec5SDimitry Andric 34850b57cec5SDimitry Andric buildCFGChains(); 34860b57cec5SDimitry Andric 34870b57cec5SDimitry Andric // Changing the layout can create new tail merging opportunities. 34880b57cec5SDimitry Andric // TailMerge can create jump into if branches that make CFG irreducible for 34890b57cec5SDimitry Andric // HW that requires structured CFG. 34900b57cec5SDimitry Andric bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 34910b57cec5SDimitry Andric PassConfig->getEnableTailMerge() && 34920b57cec5SDimitry Andric BranchFoldPlacement; 34930b57cec5SDimitry Andric // No tail merging opportunities if the block number is less than four. 34940b57cec5SDimitry Andric if (MF.size() > 3 && EnableTailMerge) { 34950b57cec5SDimitry Andric unsigned TailMergeSize = TailDupSize + 1; 3496e8d8bef9SDimitry Andric BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false, 3497e8d8bef9SDimitry Andric *MBFI, *MBPI, PSI, TailMergeSize); 34980b57cec5SDimitry Andric 34995ffd83dbSDimitry Andric if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI, 35000b57cec5SDimitry Andric /*AfterPlacement=*/true)) { 35010b57cec5SDimitry Andric // Redo the layout if tail merging creates/removes/moves blocks. 35020b57cec5SDimitry Andric BlockToChain.clear(); 35030b57cec5SDimitry Andric ComputedEdges.clear(); 35040b57cec5SDimitry Andric // Must redo the post-dominator tree if blocks were changed. 35050b57cec5SDimitry Andric if (MPDT) 3506*0fca6ea1SDimitry Andric MPDT->recalculate(MF); 35070b57cec5SDimitry Andric ChainAllocator.DestroyAll(); 35080b57cec5SDimitry Andric buildCFGChains(); 35090b57cec5SDimitry Andric } 35100b57cec5SDimitry Andric } 35110b57cec5SDimitry Andric 35120eae32dcSDimitry Andric // Apply a post-processing optimizing block placement. 351381ad6265SDimitry Andric if (MF.size() >= 3 && EnableExtTspBlockPlacement && 351481ad6265SDimitry Andric (ApplyExtTspWithoutProfile || MF.getFunction().hasProfileData())) { 35150eae32dcSDimitry Andric // Find a new placement and modify the layout of the blocks in the function. 35160eae32dcSDimitry Andric applyExtTsp(); 35170eae32dcSDimitry Andric 35180eae32dcSDimitry Andric // Re-create CFG chain so that we can optimizeBranches and alignBlocks. 35190eae32dcSDimitry Andric createCFGChainExtTsp(); 35200eae32dcSDimitry Andric } 35210eae32dcSDimitry Andric 35220b57cec5SDimitry Andric optimizeBranches(); 35230b57cec5SDimitry Andric alignBlocks(); 35240b57cec5SDimitry Andric 35250b57cec5SDimitry Andric BlockToChain.clear(); 35260b57cec5SDimitry Andric ComputedEdges.clear(); 35270b57cec5SDimitry Andric ChainAllocator.DestroyAll(); 35280b57cec5SDimitry Andric 352904eeddc0SDimitry Andric bool HasMaxBytesOverride = 353004eeddc0SDimitry Andric MaxBytesForAlignmentOverride.getNumOccurrences() > 0; 353104eeddc0SDimitry Andric 35320b57cec5SDimitry Andric if (AlignAllBlock) 35330b57cec5SDimitry Andric // Align all of the blocks in the function to a specific alignment. 353404eeddc0SDimitry Andric for (MachineBasicBlock &MBB : MF) { 353504eeddc0SDimitry Andric if (HasMaxBytesOverride) 353604eeddc0SDimitry Andric MBB.setAlignment(Align(1ULL << AlignAllBlock), 353704eeddc0SDimitry Andric MaxBytesForAlignmentOverride); 353804eeddc0SDimitry Andric else 35398bcb0991SDimitry Andric MBB.setAlignment(Align(1ULL << AlignAllBlock)); 354004eeddc0SDimitry Andric } 35410b57cec5SDimitry Andric else if (AlignAllNonFallThruBlocks) { 35420b57cec5SDimitry Andric // Align all of the blocks that have no fall-through predecessors to a 35430b57cec5SDimitry Andric // specific alignment. 35440b57cec5SDimitry Andric for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 35450b57cec5SDimitry Andric auto LayoutPred = std::prev(MBI); 354604eeddc0SDimitry Andric if (!LayoutPred->isSuccessor(&*MBI)) { 354704eeddc0SDimitry Andric if (HasMaxBytesOverride) 354804eeddc0SDimitry Andric MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks), 354904eeddc0SDimitry Andric MaxBytesForAlignmentOverride); 355004eeddc0SDimitry Andric else 35518bcb0991SDimitry Andric MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks)); 35520b57cec5SDimitry Andric } 35530b57cec5SDimitry Andric } 355404eeddc0SDimitry Andric } 35550b57cec5SDimitry Andric if (ViewBlockLayoutWithBFI != GVDT_None && 35560b57cec5SDimitry Andric (ViewBlockFreqFuncName.empty() || 3557*0fca6ea1SDimitry Andric F->getFunction().getName() == ViewBlockFreqFuncName)) { 3558bdd1243dSDimitry Andric if (RenumberBlocksBeforeView) 3559bdd1243dSDimitry Andric MF.RenumberBlocks(); 35600b57cec5SDimitry Andric MBFI->view("MBP." + MF.getName(), false); 35610b57cec5SDimitry Andric } 35620b57cec5SDimitry Andric 35630b57cec5SDimitry Andric // We always return true as we have no way to track whether the final order 35640b57cec5SDimitry Andric // differs from the original order. 35650b57cec5SDimitry Andric return true; 35660b57cec5SDimitry Andric } 35670b57cec5SDimitry Andric 35680eae32dcSDimitry Andric void MachineBlockPlacement::applyExtTsp() { 35690eae32dcSDimitry Andric // Prepare data; blocks are indexed by their index in the current ordering. 35700eae32dcSDimitry Andric DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex; 35710eae32dcSDimitry Andric BlockIndex.reserve(F->size()); 35720eae32dcSDimitry Andric std::vector<const MachineBasicBlock *> CurrentBlockOrder; 35730eae32dcSDimitry Andric CurrentBlockOrder.reserve(F->size()); 35740eae32dcSDimitry Andric size_t NumBlocks = 0; 35750eae32dcSDimitry Andric for (const MachineBasicBlock &MBB : *F) { 35760eae32dcSDimitry Andric BlockIndex[&MBB] = NumBlocks++; 35770eae32dcSDimitry Andric CurrentBlockOrder.push_back(&MBB); 35780eae32dcSDimitry Andric } 35790eae32dcSDimitry Andric 35800eae32dcSDimitry Andric auto BlockSizes = std::vector<uint64_t>(F->size()); 35810eae32dcSDimitry Andric auto BlockCounts = std::vector<uint64_t>(F->size()); 35825f757f3fSDimitry Andric std::vector<codelayout::EdgeCount> JumpCounts; 35830eae32dcSDimitry Andric for (MachineBasicBlock &MBB : *F) { 35840eae32dcSDimitry Andric // Getting the block frequency. 35850eae32dcSDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 35860eae32dcSDimitry Andric BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency(); 35870eae32dcSDimitry Andric // Getting the block size: 35880eae32dcSDimitry Andric // - approximate the size of an instruction by 4 bytes, and 35890eae32dcSDimitry Andric // - ignore debug instructions. 35900eae32dcSDimitry Andric // Note: getting the exact size of each block is target-dependent and can be 35910eae32dcSDimitry Andric // done by extending the interface of MCCodeEmitter. Experimentally we do 35920eae32dcSDimitry Andric // not see a perf improvement with the exact block sizes. 35930eae32dcSDimitry Andric auto NonDbgInsts = 35940eae32dcSDimitry Andric instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end()); 35950eae32dcSDimitry Andric int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end()); 35960eae32dcSDimitry Andric BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts; 35970eae32dcSDimitry Andric // Getting jump frequencies. 35980eae32dcSDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) { 35990eae32dcSDimitry Andric auto EP = MBPI->getEdgeProbability(&MBB, Succ); 3600bdd1243dSDimitry Andric BlockFrequency JumpFreq = BlockFreq * EP; 36015f757f3fSDimitry Andric JumpCounts.push_back( 36025f757f3fSDimitry Andric {BlockIndex[&MBB], BlockIndex[Succ], JumpFreq.getFrequency()}); 36030eae32dcSDimitry Andric } 36040eae32dcSDimitry Andric } 36050eae32dcSDimitry Andric 36060eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size() 36070eae32dcSDimitry Andric << " with profile = " << F->getFunction().hasProfileData() 36080eae32dcSDimitry Andric << " (" << F->getName().str() << ")" 36090eae32dcSDimitry Andric << "\n"); 36100eae32dcSDimitry Andric LLVM_DEBUG( 36110eae32dcSDimitry Andric dbgs() << format(" original layout score: %0.2f\n", 36120eae32dcSDimitry Andric calcExtTspScore(BlockSizes, BlockCounts, JumpCounts))); 36130eae32dcSDimitry Andric 36140eae32dcSDimitry Andric // Run the layout algorithm. 36155f757f3fSDimitry Andric auto NewOrder = computeExtTspLayout(BlockSizes, BlockCounts, JumpCounts); 36160eae32dcSDimitry Andric std::vector<const MachineBasicBlock *> NewBlockOrder; 36170eae32dcSDimitry Andric NewBlockOrder.reserve(F->size()); 36180eae32dcSDimitry Andric for (uint64_t Node : NewOrder) { 36190eae32dcSDimitry Andric NewBlockOrder.push_back(CurrentBlockOrder[Node]); 36200eae32dcSDimitry Andric } 36210eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n", 36220eae32dcSDimitry Andric calcExtTspScore(NewOrder, BlockSizes, BlockCounts, 36230eae32dcSDimitry Andric JumpCounts))); 36240eae32dcSDimitry Andric 36250eae32dcSDimitry Andric // Assign new block order. 36260eae32dcSDimitry Andric assignBlockOrder(NewBlockOrder); 36270eae32dcSDimitry Andric } 36280eae32dcSDimitry Andric 36290eae32dcSDimitry Andric void MachineBlockPlacement::assignBlockOrder( 36300eae32dcSDimitry Andric const std::vector<const MachineBasicBlock *> &NewBlockOrder) { 36310eae32dcSDimitry Andric assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order"); 36320eae32dcSDimitry Andric F->RenumberBlocks(); 36330eae32dcSDimitry Andric 36340eae32dcSDimitry Andric bool HasChanges = false; 36350eae32dcSDimitry Andric for (size_t I = 0; I < NewBlockOrder.size(); I++) { 36360eae32dcSDimitry Andric if (NewBlockOrder[I] != F->getBlockNumbered(I)) { 36370eae32dcSDimitry Andric HasChanges = true; 36380eae32dcSDimitry Andric break; 36390eae32dcSDimitry Andric } 36400eae32dcSDimitry Andric } 36410eae32dcSDimitry Andric // Stop early if the new block order is identical to the existing one. 36420eae32dcSDimitry Andric if (!HasChanges) 36430eae32dcSDimitry Andric return; 36440eae32dcSDimitry Andric 36450eae32dcSDimitry Andric SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs()); 36460eae32dcSDimitry Andric for (auto &MBB : *F) { 36470eae32dcSDimitry Andric PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 36480eae32dcSDimitry Andric } 36490eae32dcSDimitry Andric 36500eae32dcSDimitry Andric // Sort basic blocks in the function according to the computed order. 36510eae32dcSDimitry Andric DenseMap<const MachineBasicBlock *, size_t> NewIndex; 36520eae32dcSDimitry Andric for (const MachineBasicBlock *MBB : NewBlockOrder) { 36530eae32dcSDimitry Andric NewIndex[MBB] = NewIndex.size(); 36540eae32dcSDimitry Andric } 36550eae32dcSDimitry Andric F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) { 36560eae32dcSDimitry Andric return NewIndex[&L] < NewIndex[&R]; 36570eae32dcSDimitry Andric }); 36580eae32dcSDimitry Andric 36590eae32dcSDimitry Andric // Update basic block branches by inserting explicit fallthrough branches 36600eae32dcSDimitry Andric // when required and re-optimize branches when possible. 36610eae32dcSDimitry Andric const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo(); 36620eae32dcSDimitry Andric SmallVector<MachineOperand, 4> Cond; 36630eae32dcSDimitry Andric for (auto &MBB : *F) { 36640eae32dcSDimitry Andric MachineFunction::iterator NextMBB = std::next(MBB.getIterator()); 36650eae32dcSDimitry Andric MachineFunction::iterator EndIt = MBB.getParent()->end(); 36660eae32dcSDimitry Andric auto *FTMBB = PrevFallThroughs[MBB.getNumber()]; 36670eae32dcSDimitry Andric // If this block had a fallthrough before we need an explicit unconditional 36680eae32dcSDimitry Andric // branch to that block if the fallthrough block is not adjacent to the 36690eae32dcSDimitry Andric // block in the new order. 36700eae32dcSDimitry Andric if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) { 36710eae32dcSDimitry Andric TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 36720eae32dcSDimitry Andric } 36730eae32dcSDimitry Andric 36740eae32dcSDimitry Andric // It might be possible to optimize branches by flipping the condition. 36750eae32dcSDimitry Andric Cond.clear(); 36760eae32dcSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 36770eae32dcSDimitry Andric if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 36780eae32dcSDimitry Andric continue; 36790eae32dcSDimitry Andric MBB.updateTerminator(FTMBB); 36800eae32dcSDimitry Andric } 36810eae32dcSDimitry Andric 36820eae32dcSDimitry Andric #ifndef NDEBUG 36830eae32dcSDimitry Andric // Make sure we correctly constructed all branches. 36840eae32dcSDimitry Andric F->verify(this, "After optimized block reordering"); 36850eae32dcSDimitry Andric #endif 36860eae32dcSDimitry Andric } 36870eae32dcSDimitry Andric 36880eae32dcSDimitry Andric void MachineBlockPlacement::createCFGChainExtTsp() { 36890eae32dcSDimitry Andric BlockToChain.clear(); 36900eae32dcSDimitry Andric ComputedEdges.clear(); 36910eae32dcSDimitry Andric ChainAllocator.DestroyAll(); 36920eae32dcSDimitry Andric 36930eae32dcSDimitry Andric MachineBasicBlock *HeadBB = &F->front(); 36940eae32dcSDimitry Andric BlockChain *FunctionChain = 36950eae32dcSDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB); 36960eae32dcSDimitry Andric 36970eae32dcSDimitry Andric for (MachineBasicBlock &MBB : *F) { 36980eae32dcSDimitry Andric if (HeadBB == &MBB) 36990eae32dcSDimitry Andric continue; // Ignore head of the chain 37000eae32dcSDimitry Andric FunctionChain->merge(&MBB, nullptr); 37010eae32dcSDimitry Andric } 37020eae32dcSDimitry Andric } 37030eae32dcSDimitry Andric 37040b57cec5SDimitry Andric namespace { 37050b57cec5SDimitry Andric 37060b57cec5SDimitry Andric /// A pass to compute block placement statistics. 37070b57cec5SDimitry Andric /// 37080b57cec5SDimitry Andric /// A separate pass to compute interesting statistics for evaluating block 37090b57cec5SDimitry Andric /// placement. This is separate from the actual placement pass so that they can 37100b57cec5SDimitry Andric /// be computed in the absence of any placement transformations or when using 37110b57cec5SDimitry Andric /// alternative placement strategies. 37120b57cec5SDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass { 37130b57cec5SDimitry Andric /// A handle to the branch probability pass. 37140b57cec5SDimitry Andric const MachineBranchProbabilityInfo *MBPI; 37150b57cec5SDimitry Andric 37160b57cec5SDimitry Andric /// A handle to the function-wide block frequency pass. 37170b57cec5SDimitry Andric const MachineBlockFrequencyInfo *MBFI; 37180b57cec5SDimitry Andric 37190b57cec5SDimitry Andric public: 37200b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 37210b57cec5SDimitry Andric 37220b57cec5SDimitry Andric MachineBlockPlacementStats() : MachineFunctionPass(ID) { 37230b57cec5SDimitry Andric initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 37240b57cec5SDimitry Andric } 37250b57cec5SDimitry Andric 37260b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 37270b57cec5SDimitry Andric 37280b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 3729*0fca6ea1SDimitry Andric AU.addRequired<MachineBranchProbabilityInfoWrapperPass>(); 3730*0fca6ea1SDimitry Andric AU.addRequired<MachineBlockFrequencyInfoWrapperPass>(); 37310b57cec5SDimitry Andric AU.setPreservesAll(); 37320b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 37330b57cec5SDimitry Andric } 37340b57cec5SDimitry Andric }; 37350b57cec5SDimitry Andric 37360b57cec5SDimitry Andric } // end anonymous namespace 37370b57cec5SDimitry Andric 37380b57cec5SDimitry Andric char MachineBlockPlacementStats::ID = 0; 37390b57cec5SDimitry Andric 37400b57cec5SDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 37410b57cec5SDimitry Andric 37420b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 37430b57cec5SDimitry Andric "Basic Block Placement Stats", false, false) 3744*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfoWrapperPass) 3745*0fca6ea1SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass) 37460b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 37470b57cec5SDimitry Andric "Basic Block Placement Stats", false, false) 37480b57cec5SDimitry Andric 37490b57cec5SDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 37500b57cec5SDimitry Andric // Check for single-block functions and skip them. 37510b57cec5SDimitry Andric if (std::next(F.begin()) == F.end()) 37520b57cec5SDimitry Andric return false; 37530b57cec5SDimitry Andric 375481ad6265SDimitry Andric if (!isFunctionInPrintList(F.getName())) 375581ad6265SDimitry Andric return false; 375681ad6265SDimitry Andric 3757*0fca6ea1SDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI(); 3758*0fca6ea1SDimitry Andric MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI(); 37590b57cec5SDimitry Andric 37600b57cec5SDimitry Andric for (MachineBasicBlock &MBB : F) { 37610b57cec5SDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 37620b57cec5SDimitry Andric Statistic &NumBranches = 37630b57cec5SDimitry Andric (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 37640b57cec5SDimitry Andric Statistic &BranchTakenFreq = 37650b57cec5SDimitry Andric (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 37660b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) { 37670b57cec5SDimitry Andric // Skip if this successor is a fallthrough. 37680b57cec5SDimitry Andric if (MBB.isLayoutSuccessor(Succ)) 37690b57cec5SDimitry Andric continue; 37700b57cec5SDimitry Andric 37710b57cec5SDimitry Andric BlockFrequency EdgeFreq = 37720b57cec5SDimitry Andric BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 37730b57cec5SDimitry Andric ++NumBranches; 37740b57cec5SDimitry Andric BranchTakenFreq += EdgeFreq.getFrequency(); 37750b57cec5SDimitry Andric } 37760b57cec5SDimitry Andric } 37770b57cec5SDimitry Andric 37780b57cec5SDimitry Andric return false; 37790b57cec5SDimitry Andric } 3780