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" 370b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h" 380b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 390b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h" 410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineLoopInfo.h" 430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.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" 53480093f4SDimitry Andric #include "llvm/InitializePasses.h" 540b57cec5SDimitry Andric #include "llvm/Pass.h" 550b57cec5SDimitry Andric #include "llvm/Support/Allocator.h" 560b57cec5SDimitry Andric #include "llvm/Support/BlockFrequency.h" 570b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h" 580b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 590b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 600b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 610b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 620b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 630b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h" 64*0eae32dcSDimitry Andric #include "llvm/Transforms/Utils/CodeLayout.h" 650b57cec5SDimitry Andric #include <algorithm> 660b57cec5SDimitry Andric #include <cassert> 670b57cec5SDimitry Andric #include <cstdint> 680b57cec5SDimitry Andric #include <iterator> 690b57cec5SDimitry Andric #include <memory> 700b57cec5SDimitry Andric #include <string> 710b57cec5SDimitry Andric #include <tuple> 720b57cec5SDimitry Andric #include <utility> 730b57cec5SDimitry Andric #include <vector> 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric using namespace llvm; 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric #define DEBUG_TYPE "block-placement" 780b57cec5SDimitry Andric 790b57cec5SDimitry Andric STATISTIC(NumCondBranches, "Number of conditional branches"); 800b57cec5SDimitry Andric STATISTIC(NumUncondBranches, "Number of unconditional branches"); 810b57cec5SDimitry Andric STATISTIC(CondBranchTakenFreq, 820b57cec5SDimitry Andric "Potential frequency of taking conditional branches"); 830b57cec5SDimitry Andric STATISTIC(UncondBranchTakenFreq, 840b57cec5SDimitry Andric "Potential frequency of taking unconditional branches"); 850b57cec5SDimitry Andric 868bcb0991SDimitry Andric static cl::opt<unsigned> AlignAllBlock( 878bcb0991SDimitry Andric "align-all-blocks", 888bcb0991SDimitry Andric cl::desc("Force the alignment of all blocks in the function in log2 format " 898bcb0991SDimitry Andric "(e.g 4 means align on 16B boundaries)."), 900b57cec5SDimitry Andric cl::init(0), cl::Hidden); 910b57cec5SDimitry Andric 920b57cec5SDimitry Andric static cl::opt<unsigned> AlignAllNonFallThruBlocks( 930b57cec5SDimitry Andric "align-all-nofallthru-blocks", 948bcb0991SDimitry Andric cl::desc("Force the alignment of all blocks that have no fall-through " 958bcb0991SDimitry Andric "predecessors (i.e. don't add nops that are executed). In log2 " 968bcb0991SDimitry Andric "format (e.g 4 means align on 16B boundaries)."), 970b57cec5SDimitry Andric cl::init(0), cl::Hidden); 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric // FIXME: Find a good default for this flag and remove the flag. 1000b57cec5SDimitry Andric static cl::opt<unsigned> ExitBlockBias( 1010b57cec5SDimitry Andric "block-placement-exit-block-bias", 1020b57cec5SDimitry Andric cl::desc("Block frequency percentage a loop exit block needs " 1030b57cec5SDimitry Andric "over the original exit to be considered the new exit."), 1040b57cec5SDimitry Andric cl::init(0), cl::Hidden); 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric // Definition: 1070b57cec5SDimitry Andric // - Outlining: placement of a basic block outside the chain or hot path. 1080b57cec5SDimitry Andric 1090b57cec5SDimitry Andric static cl::opt<unsigned> LoopToColdBlockRatio( 1100b57cec5SDimitry Andric "loop-to-cold-block-ratio", 1110b57cec5SDimitry Andric cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " 1120b57cec5SDimitry Andric "(frequency of block) is greater than this ratio"), 1130b57cec5SDimitry Andric cl::init(5), cl::Hidden); 1140b57cec5SDimitry Andric 1150b57cec5SDimitry Andric static cl::opt<bool> ForceLoopColdBlock( 1160b57cec5SDimitry Andric "force-loop-cold-block", 1170b57cec5SDimitry Andric cl::desc("Force outlining cold blocks from loops."), 1180b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1190b57cec5SDimitry Andric 1200b57cec5SDimitry Andric static cl::opt<bool> 1210b57cec5SDimitry Andric PreciseRotationCost("precise-rotation-cost", 1220b57cec5SDimitry Andric cl::desc("Model the cost of loop rotation more " 1230b57cec5SDimitry Andric "precisely by using profile data."), 1240b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1250b57cec5SDimitry Andric 1260b57cec5SDimitry Andric static cl::opt<bool> 1270b57cec5SDimitry Andric ForcePreciseRotationCost("force-precise-rotation-cost", 1280b57cec5SDimitry Andric cl::desc("Force the use of precise cost " 1290b57cec5SDimitry Andric "loop rotation strategy."), 1300b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1310b57cec5SDimitry Andric 1320b57cec5SDimitry Andric static cl::opt<unsigned> MisfetchCost( 1330b57cec5SDimitry Andric "misfetch-cost", 1340b57cec5SDimitry Andric cl::desc("Cost that models the probabilistic risk of an instruction " 1350b57cec5SDimitry Andric "misfetch due to a jump comparing to falling through, whose cost " 1360b57cec5SDimitry Andric "is zero."), 1370b57cec5SDimitry Andric cl::init(1), cl::Hidden); 1380b57cec5SDimitry Andric 1390b57cec5SDimitry Andric static cl::opt<unsigned> JumpInstCost("jump-inst-cost", 1400b57cec5SDimitry Andric cl::desc("Cost of jump instructions."), 1410b57cec5SDimitry Andric cl::init(1), cl::Hidden); 1420b57cec5SDimitry Andric static cl::opt<bool> 1430b57cec5SDimitry Andric TailDupPlacement("tail-dup-placement", 1440b57cec5SDimitry Andric cl::desc("Perform tail duplication during placement. " 1450b57cec5SDimitry Andric "Creates more fallthrough opportunites in " 1460b57cec5SDimitry Andric "outline branches."), 1470b57cec5SDimitry Andric cl::init(true), cl::Hidden); 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric static cl::opt<bool> 1500b57cec5SDimitry Andric BranchFoldPlacement("branch-fold-placement", 1510b57cec5SDimitry Andric cl::desc("Perform branch folding during placement. " 1520b57cec5SDimitry Andric "Reduces code size."), 1530b57cec5SDimitry Andric cl::init(true), cl::Hidden); 1540b57cec5SDimitry Andric 1550b57cec5SDimitry Andric // Heuristic for tail duplication. 1560b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementThreshold( 1570b57cec5SDimitry Andric "tail-dup-placement-threshold", 1580b57cec5SDimitry Andric cl::desc("Instruction cutoff for tail duplication during layout. " 1590b57cec5SDimitry Andric "Tail merging during layout is forced to have a threshold " 1600b57cec5SDimitry Andric "that won't conflict."), cl::init(2), 1610b57cec5SDimitry Andric cl::Hidden); 1620b57cec5SDimitry Andric 1630b57cec5SDimitry Andric // Heuristic for aggressive tail duplication. 1640b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementAggressiveThreshold( 1650b57cec5SDimitry Andric "tail-dup-placement-aggressive-threshold", 1660b57cec5SDimitry Andric cl::desc("Instruction cutoff for aggressive tail duplication during " 1670b57cec5SDimitry Andric "layout. Used at -O3. Tail merging during layout is forced to " 1680b57cec5SDimitry Andric "have a threshold that won't conflict."), cl::init(4), 1690b57cec5SDimitry Andric cl::Hidden); 1700b57cec5SDimitry Andric 1710b57cec5SDimitry Andric // Heuristic for tail duplication. 1720b57cec5SDimitry Andric static cl::opt<unsigned> TailDupPlacementPenalty( 1730b57cec5SDimitry Andric "tail-dup-placement-penalty", 1740b57cec5SDimitry Andric cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. " 1750b57cec5SDimitry Andric "Copying can increase fallthrough, but it also increases icache " 1760b57cec5SDimitry Andric "pressure. This parameter controls the penalty to account for that. " 1770b57cec5SDimitry Andric "Percent as integer."), 1780b57cec5SDimitry Andric cl::init(2), 1790b57cec5SDimitry Andric cl::Hidden); 1800b57cec5SDimitry Andric 181e8d8bef9SDimitry Andric // Heuristic for tail duplication if profile count is used in cost model. 182e8d8bef9SDimitry Andric static cl::opt<unsigned> TailDupProfilePercentThreshold( 183e8d8bef9SDimitry Andric "tail-dup-profile-percent-threshold", 184e8d8bef9SDimitry Andric cl::desc("If profile count information is used in tail duplication cost " 185e8d8bef9SDimitry Andric "model, the gained fall through number from tail duplication " 186e8d8bef9SDimitry Andric "should be at least this percent of hot count."), 187e8d8bef9SDimitry Andric cl::init(50), cl::Hidden); 188e8d8bef9SDimitry Andric 1890b57cec5SDimitry Andric // Heuristic for triangle chains. 1900b57cec5SDimitry Andric static cl::opt<unsigned> TriangleChainCount( 1910b57cec5SDimitry Andric "triangle-chain-count", 1920b57cec5SDimitry Andric cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the " 1930b57cec5SDimitry Andric "triangle tail duplication heuristic to kick in. 0 to disable."), 1940b57cec5SDimitry Andric cl::init(2), 1950b57cec5SDimitry Andric cl::Hidden); 1960b57cec5SDimitry Andric 197*0eae32dcSDimitry Andric static cl::opt<bool> EnableExtTspBlockPlacement( 198*0eae32dcSDimitry Andric "enable-ext-tsp-block-placement", cl::Hidden, cl::init(false), 199*0eae32dcSDimitry Andric cl::desc("Enable machine block placement based on the ext-tsp model, " 200*0eae32dcSDimitry Andric "optimizing I-cache utilization.")); 201*0eae32dcSDimitry Andric 202fe6060f1SDimitry Andric namespace llvm { 2030b57cec5SDimitry Andric extern cl::opt<unsigned> StaticLikelyProb; 2040b57cec5SDimitry Andric extern cl::opt<unsigned> ProfileLikelyProb; 2050b57cec5SDimitry Andric 2060b57cec5SDimitry Andric // Internal option used to control BFI display only after MBP pass. 2070b57cec5SDimitry Andric // Defined in CodeGen/MachineBlockFrequencyInfo.cpp: 2080b57cec5SDimitry Andric // -view-block-layout-with-bfi= 2090b57cec5SDimitry Andric extern cl::opt<GVDAGType> ViewBlockLayoutWithBFI; 2100b57cec5SDimitry Andric 2110b57cec5SDimitry Andric // Command line option to specify the name of the function for CFG dump 2120b57cec5SDimitry Andric // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= 2130b57cec5SDimitry Andric extern cl::opt<std::string> ViewBlockFreqFuncName; 214fe6060f1SDimitry Andric } // namespace llvm 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric namespace { 2170b57cec5SDimitry Andric 2180b57cec5SDimitry Andric class BlockChain; 2190b57cec5SDimitry Andric 2200b57cec5SDimitry Andric /// Type for our function-wide basic block -> block chain mapping. 2210b57cec5SDimitry Andric using BlockToChainMapType = DenseMap<const MachineBasicBlock *, BlockChain *>; 2220b57cec5SDimitry Andric 2230b57cec5SDimitry Andric /// A chain of blocks which will be laid out contiguously. 2240b57cec5SDimitry Andric /// 2250b57cec5SDimitry Andric /// This is the datastructure representing a chain of consecutive blocks that 2260b57cec5SDimitry Andric /// are profitable to layout together in order to maximize fallthrough 2270b57cec5SDimitry Andric /// probabilities and code locality. We also can use a block chain to represent 2280b57cec5SDimitry Andric /// a sequence of basic blocks which have some external (correctness) 2290b57cec5SDimitry Andric /// requirement for sequential layout. 2300b57cec5SDimitry Andric /// 2310b57cec5SDimitry Andric /// Chains can be built around a single basic block and can be merged to grow 2320b57cec5SDimitry Andric /// them. They participate in a block-to-chain mapping, which is updated 2330b57cec5SDimitry Andric /// automatically as chains are merged together. 2340b57cec5SDimitry Andric class BlockChain { 2350b57cec5SDimitry Andric /// The sequence of blocks belonging to this chain. 2360b57cec5SDimitry Andric /// 2370b57cec5SDimitry Andric /// This is the sequence of blocks for a particular chain. These will be laid 2380b57cec5SDimitry Andric /// out in-order within the function. 2390b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> Blocks; 2400b57cec5SDimitry Andric 2410b57cec5SDimitry Andric /// A handle to the function-wide basic block to block chain mapping. 2420b57cec5SDimitry Andric /// 2430b57cec5SDimitry Andric /// This is retained in each block chain to simplify the computation of child 2440b57cec5SDimitry Andric /// block chains for SCC-formation and iteration. We store the edges to child 2450b57cec5SDimitry Andric /// basic blocks, and map them back to their associated chains using this 2460b57cec5SDimitry Andric /// structure. 2470b57cec5SDimitry Andric BlockToChainMapType &BlockToChain; 2480b57cec5SDimitry Andric 2490b57cec5SDimitry Andric public: 2500b57cec5SDimitry Andric /// Construct a new BlockChain. 2510b57cec5SDimitry Andric /// 2520b57cec5SDimitry Andric /// This builds a new block chain representing a single basic block in the 2530b57cec5SDimitry Andric /// function. It also registers itself as the chain that block participates 2540b57cec5SDimitry Andric /// in with the BlockToChain mapping. 2550b57cec5SDimitry Andric BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) 2560b57cec5SDimitry Andric : Blocks(1, BB), BlockToChain(BlockToChain) { 2570b57cec5SDimitry Andric assert(BB && "Cannot create a chain with a null basic block"); 2580b57cec5SDimitry Andric BlockToChain[BB] = this; 2590b57cec5SDimitry Andric } 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric /// Iterator over blocks within the chain. 2620b57cec5SDimitry Andric using iterator = SmallVectorImpl<MachineBasicBlock *>::iterator; 2630b57cec5SDimitry Andric using const_iterator = SmallVectorImpl<MachineBasicBlock *>::const_iterator; 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric /// Beginning of blocks within the chain. 2660b57cec5SDimitry Andric iterator begin() { return Blocks.begin(); } 2670b57cec5SDimitry Andric const_iterator begin() const { return Blocks.begin(); } 2680b57cec5SDimitry Andric 2690b57cec5SDimitry Andric /// End of blocks within the chain. 2700b57cec5SDimitry Andric iterator end() { return Blocks.end(); } 2710b57cec5SDimitry Andric const_iterator end() const { return Blocks.end(); } 2720b57cec5SDimitry Andric 2730b57cec5SDimitry Andric bool remove(MachineBasicBlock* BB) { 2740b57cec5SDimitry Andric for(iterator i = begin(); i != end(); ++i) { 2750b57cec5SDimitry Andric if (*i == BB) { 2760b57cec5SDimitry Andric Blocks.erase(i); 2770b57cec5SDimitry Andric return true; 2780b57cec5SDimitry Andric } 2790b57cec5SDimitry Andric } 2800b57cec5SDimitry Andric return false; 2810b57cec5SDimitry Andric } 2820b57cec5SDimitry Andric 2830b57cec5SDimitry Andric /// Merge a block chain into this one. 2840b57cec5SDimitry Andric /// 2850b57cec5SDimitry Andric /// This routine merges a block chain into this one. It takes care of forming 2860b57cec5SDimitry Andric /// a contiguous sequence of basic blocks, updating the edge list, and 2870b57cec5SDimitry Andric /// updating the block -> chain mapping. It does not free or tear down the 2880b57cec5SDimitry Andric /// old chain, but the old chain's block list is no longer valid. 2890b57cec5SDimitry Andric void merge(MachineBasicBlock *BB, BlockChain *Chain) { 2900b57cec5SDimitry Andric assert(BB && "Can't merge a null block."); 2910b57cec5SDimitry Andric assert(!Blocks.empty() && "Can't merge into an empty chain."); 2920b57cec5SDimitry Andric 2930b57cec5SDimitry Andric // Fast path in case we don't have a chain already. 2940b57cec5SDimitry Andric if (!Chain) { 2950b57cec5SDimitry Andric assert(!BlockToChain[BB] && 2960b57cec5SDimitry Andric "Passed chain is null, but BB has entry in BlockToChain."); 2970b57cec5SDimitry Andric Blocks.push_back(BB); 2980b57cec5SDimitry Andric BlockToChain[BB] = this; 2990b57cec5SDimitry Andric return; 3000b57cec5SDimitry Andric } 3010b57cec5SDimitry Andric 3020b57cec5SDimitry Andric assert(BB == *Chain->begin() && "Passed BB is not head of Chain."); 3030b57cec5SDimitry Andric assert(Chain->begin() != Chain->end()); 3040b57cec5SDimitry Andric 3050b57cec5SDimitry Andric // Update the incoming blocks to point to this chain, and add them to the 3060b57cec5SDimitry Andric // chain structure. 3070b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) { 3080b57cec5SDimitry Andric Blocks.push_back(ChainBB); 3090b57cec5SDimitry Andric assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain."); 3100b57cec5SDimitry Andric BlockToChain[ChainBB] = this; 3110b57cec5SDimitry Andric } 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 3140b57cec5SDimitry Andric #ifndef NDEBUG 3150b57cec5SDimitry Andric /// Dump the blocks in this chain. 3160b57cec5SDimitry Andric LLVM_DUMP_METHOD void dump() { 3170b57cec5SDimitry Andric for (MachineBasicBlock *MBB : *this) 3180b57cec5SDimitry Andric MBB->dump(); 3190b57cec5SDimitry Andric } 3200b57cec5SDimitry Andric #endif // NDEBUG 3210b57cec5SDimitry Andric 3220b57cec5SDimitry Andric /// Count of predecessors of any block within the chain which have not 3230b57cec5SDimitry Andric /// yet been scheduled. In general, we will delay scheduling this chain 3240b57cec5SDimitry Andric /// until those predecessors are scheduled (or we find a sufficiently good 3250b57cec5SDimitry Andric /// reason to override this heuristic.) Note that when forming loop chains, 3260b57cec5SDimitry Andric /// blocks outside the loop are ignored and treated as if they were already 3270b57cec5SDimitry Andric /// scheduled. 3280b57cec5SDimitry Andric /// 3290b57cec5SDimitry Andric /// Note: This field is reinitialized multiple times - once for each loop, 3300b57cec5SDimitry Andric /// and then once for the function as a whole. 3310b57cec5SDimitry Andric unsigned UnscheduledPredecessors = 0; 3320b57cec5SDimitry Andric }; 3330b57cec5SDimitry Andric 3340b57cec5SDimitry Andric class MachineBlockPlacement : public MachineFunctionPass { 3350b57cec5SDimitry Andric /// A type for a block filter set. 3360b57cec5SDimitry Andric using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>; 3370b57cec5SDimitry Andric 3380b57cec5SDimitry Andric /// Pair struct containing basic block and taildup profitability 3390b57cec5SDimitry Andric struct BlockAndTailDupResult { 3400b57cec5SDimitry Andric MachineBasicBlock *BB; 3410b57cec5SDimitry Andric bool ShouldTailDup; 3420b57cec5SDimitry Andric }; 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric /// Triple struct containing edge weight and the edge. 3450b57cec5SDimitry Andric struct WeightedEdge { 3460b57cec5SDimitry Andric BlockFrequency Weight; 3470b57cec5SDimitry Andric MachineBasicBlock *Src; 3480b57cec5SDimitry Andric MachineBasicBlock *Dest; 3490b57cec5SDimitry Andric }; 3500b57cec5SDimitry Andric 3510b57cec5SDimitry Andric /// work lists of blocks that are ready to be laid out 3520b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 16> BlockWorkList; 3530b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 16> EHPadWorkList; 3540b57cec5SDimitry Andric 3550b57cec5SDimitry Andric /// Edges that have already been computed as optimal. 3560b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges; 3570b57cec5SDimitry Andric 3580b57cec5SDimitry Andric /// Machine Function 3590b57cec5SDimitry Andric MachineFunction *F; 3600b57cec5SDimitry Andric 3610b57cec5SDimitry Andric /// A handle to the branch probability pass. 3620b57cec5SDimitry Andric const MachineBranchProbabilityInfo *MBPI; 3630b57cec5SDimitry Andric 3640b57cec5SDimitry Andric /// A handle to the function-wide block frequency pass. 3655ffd83dbSDimitry Andric std::unique_ptr<MBFIWrapper> MBFI; 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric /// A handle to the loop info. 3680b57cec5SDimitry Andric MachineLoopInfo *MLI; 3690b57cec5SDimitry Andric 3700b57cec5SDimitry Andric /// Preferred loop exit. 3710b57cec5SDimitry Andric /// Member variable for convenience. It may be removed by duplication deep 3720b57cec5SDimitry Andric /// in the call stack. 3730b57cec5SDimitry Andric MachineBasicBlock *PreferredLoopExit; 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric /// A handle to the target's instruction info. 3760b57cec5SDimitry Andric const TargetInstrInfo *TII; 3770b57cec5SDimitry Andric 3780b57cec5SDimitry Andric /// A handle to the target's lowering info. 3790b57cec5SDimitry Andric const TargetLoweringBase *TLI; 3800b57cec5SDimitry Andric 3810b57cec5SDimitry Andric /// A handle to the post dominator tree. 3820b57cec5SDimitry Andric MachinePostDominatorTree *MPDT; 3830b57cec5SDimitry Andric 384480093f4SDimitry Andric ProfileSummaryInfo *PSI; 385480093f4SDimitry Andric 3860b57cec5SDimitry Andric /// Duplicator used to duplicate tails during placement. 3870b57cec5SDimitry Andric /// 3880b57cec5SDimitry Andric /// Placement decisions can open up new tail duplication opportunities, but 3890b57cec5SDimitry Andric /// since tail duplication affects placement decisions of later blocks, it 3900b57cec5SDimitry Andric /// must be done inline. 3910b57cec5SDimitry Andric TailDuplicator TailDup; 3920b57cec5SDimitry Andric 3935ffd83dbSDimitry Andric /// Partial tail duplication threshold. 3945ffd83dbSDimitry Andric BlockFrequency DupThreshold; 3955ffd83dbSDimitry Andric 396e8d8bef9SDimitry Andric /// True: use block profile count to compute tail duplication cost. 397e8d8bef9SDimitry Andric /// False: use block frequency to compute tail duplication cost. 398e8d8bef9SDimitry Andric bool UseProfileCount; 399e8d8bef9SDimitry Andric 4000b57cec5SDimitry Andric /// Allocator and owner of BlockChain structures. 4010b57cec5SDimitry Andric /// 4020b57cec5SDimitry Andric /// We build BlockChains lazily while processing the loop structure of 4030b57cec5SDimitry Andric /// a function. To reduce malloc traffic, we allocate them using this 4040b57cec5SDimitry Andric /// slab-like allocator, and destroy them after the pass completes. An 4050b57cec5SDimitry Andric /// important guarantee is that this allocator produces stable pointers to 4060b57cec5SDimitry Andric /// the chains. 4070b57cec5SDimitry Andric SpecificBumpPtrAllocator<BlockChain> ChainAllocator; 4080b57cec5SDimitry Andric 4090b57cec5SDimitry Andric /// Function wide BasicBlock to BlockChain mapping. 4100b57cec5SDimitry Andric /// 4110b57cec5SDimitry Andric /// This mapping allows efficiently moving from any given basic block to the 4120b57cec5SDimitry Andric /// BlockChain it participates in, if any. We use it to, among other things, 4130b57cec5SDimitry Andric /// allow implicitly defining edges between chains as the existing edges 4140b57cec5SDimitry Andric /// between basic blocks. 4150b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain; 4160b57cec5SDimitry Andric 4170b57cec5SDimitry Andric #ifndef NDEBUG 4180b57cec5SDimitry Andric /// The set of basic blocks that have terminators that cannot be fully 4190b57cec5SDimitry Andric /// analyzed. These basic blocks cannot be re-ordered safely by 4200b57cec5SDimitry Andric /// MachineBlockPlacement, and we must preserve physical layout of these 4210b57cec5SDimitry Andric /// blocks and their successors through the pass. 4220b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits; 4230b57cec5SDimitry Andric #endif 4240b57cec5SDimitry Andric 425e8d8bef9SDimitry Andric /// Get block profile count or frequency according to UseProfileCount. 426e8d8bef9SDimitry Andric /// The return value is used to model tail duplication cost. 427e8d8bef9SDimitry Andric BlockFrequency getBlockCountOrFrequency(const MachineBasicBlock *BB) { 428e8d8bef9SDimitry Andric if (UseProfileCount) { 429e8d8bef9SDimitry Andric auto Count = MBFI->getBlockProfileCount(BB); 430e8d8bef9SDimitry Andric if (Count) 431e8d8bef9SDimitry Andric return *Count; 432e8d8bef9SDimitry Andric else 433e8d8bef9SDimitry Andric return 0; 434e8d8bef9SDimitry Andric } else 435e8d8bef9SDimitry Andric return MBFI->getBlockFreq(BB); 436e8d8bef9SDimitry Andric } 437e8d8bef9SDimitry Andric 4385ffd83dbSDimitry Andric /// Scale the DupThreshold according to basic block size. 4395ffd83dbSDimitry Andric BlockFrequency scaleThreshold(MachineBasicBlock *BB); 4405ffd83dbSDimitry Andric void initDupThreshold(); 4415ffd83dbSDimitry Andric 4420b57cec5SDimitry Andric /// Decrease the UnscheduledPredecessors count for all blocks in chain, and 4430b57cec5SDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 4440b57cec5SDimitry Andric void markChainSuccessors( 4450b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 4460b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 4470b57cec5SDimitry Andric 4480b57cec5SDimitry Andric /// Decrease the UnscheduledPredecessors count for a single block, and 4490b57cec5SDimitry Andric /// if the count goes to 0, add them to the appropriate work list. 4500b57cec5SDimitry Andric void markBlockSuccessors( 4510b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *BB, 4520b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 4530b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr); 4540b57cec5SDimitry Andric 4550b57cec5SDimitry Andric BranchProbability 4560b57cec5SDimitry Andric collectViableSuccessors( 4570b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 4580b57cec5SDimitry Andric const BlockFilterSet *BlockFilter, 4590b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors); 4605ffd83dbSDimitry Andric bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred, 4615ffd83dbSDimitry Andric BlockFilterSet *BlockFilter); 4625ffd83dbSDimitry Andric void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates, 4635ffd83dbSDimitry Andric MachineBasicBlock *BB, 4645ffd83dbSDimitry Andric BlockFilterSet *BlockFilter); 4650b57cec5SDimitry Andric bool repeatedlyTailDuplicateBlock( 4660b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 4670b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 4680b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 4690b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt); 4700b57cec5SDimitry Andric bool maybeTailDuplicateBlock( 4710b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, 4720b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 4730b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 4740b57cec5SDimitry Andric bool &DuplicatedToLPred); 4750b57cec5SDimitry Andric bool hasBetterLayoutPredecessor( 4760b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 4770b57cec5SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 4780b57cec5SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 4790b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 4800b57cec5SDimitry Andric BlockAndTailDupResult selectBestSuccessor( 4810b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 4820b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 4830b57cec5SDimitry Andric MachineBasicBlock *selectBestCandidateBlock( 4840b57cec5SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList); 4850b57cec5SDimitry Andric MachineBasicBlock *getFirstUnplacedBlock( 4860b57cec5SDimitry Andric const BlockChain &PlacedChain, 4870b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 4880b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 4890b57cec5SDimitry Andric 4900b57cec5SDimitry Andric /// Add a basic block to the work list if it is appropriate. 4910b57cec5SDimitry Andric /// 4920b57cec5SDimitry Andric /// If the optional parameter BlockFilter is provided, only MBB 4930b57cec5SDimitry Andric /// present in the set will be added to the worklist. If nullptr 4940b57cec5SDimitry Andric /// is provided, no filtering occurs. 4950b57cec5SDimitry Andric void fillWorkLists(const MachineBasicBlock *MBB, 4960b57cec5SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 4970b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 4980b57cec5SDimitry Andric 4990b57cec5SDimitry Andric void buildChain(const MachineBasicBlock *BB, BlockChain &Chain, 5000b57cec5SDimitry Andric BlockFilterSet *BlockFilter = nullptr); 5010b57cec5SDimitry Andric bool canMoveBottomBlockToTop(const MachineBasicBlock *BottomBlock, 5020b57cec5SDimitry Andric const MachineBasicBlock *OldTop); 5030b57cec5SDimitry Andric bool hasViableTopFallthrough(const MachineBasicBlock *Top, 5040b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5050b57cec5SDimitry Andric BlockFrequency TopFallThroughFreq(const MachineBasicBlock *Top, 5060b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5070b57cec5SDimitry Andric BlockFrequency FallThroughGains(const MachineBasicBlock *NewTop, 5080b57cec5SDimitry Andric const MachineBasicBlock *OldTop, 5090b57cec5SDimitry Andric const MachineBasicBlock *ExitBB, 5100b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5110b57cec5SDimitry Andric MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop, 5120b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 5130b57cec5SDimitry Andric MachineBasicBlock *findBestLoopTop( 5140b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet); 5150b57cec5SDimitry Andric MachineBasicBlock *findBestLoopExit( 5160b57cec5SDimitry Andric const MachineLoop &L, const BlockFilterSet &LoopBlockSet, 5170b57cec5SDimitry Andric BlockFrequency &ExitFreq); 5180b57cec5SDimitry Andric BlockFilterSet collectLoopBlockSet(const MachineLoop &L); 5190b57cec5SDimitry Andric void buildLoopChains(const MachineLoop &L); 5200b57cec5SDimitry Andric void rotateLoop( 5210b57cec5SDimitry Andric BlockChain &LoopChain, const MachineBasicBlock *ExitingBB, 5220b57cec5SDimitry Andric BlockFrequency ExitFreq, const BlockFilterSet &LoopBlockSet); 5230b57cec5SDimitry Andric void rotateLoopWithProfile( 5240b57cec5SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 5250b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet); 5260b57cec5SDimitry Andric void buildCFGChains(); 5270b57cec5SDimitry Andric void optimizeBranches(); 5280b57cec5SDimitry Andric void alignBlocks(); 5290b57cec5SDimitry Andric /// Returns true if a block should be tail-duplicated to increase fallthrough 5300b57cec5SDimitry Andric /// opportunities. 5310b57cec5SDimitry Andric bool shouldTailDuplicate(MachineBasicBlock *BB); 5320b57cec5SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 5330b57cec5SDimitry Andric /// fallthroughs. 5340b57cec5SDimitry Andric bool isProfitableToTailDup( 5350b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 5360b57cec5SDimitry Andric BranchProbability QProb, 5370b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5380b57cec5SDimitry Andric 5390b57cec5SDimitry Andric /// Check for a trellis layout. 5400b57cec5SDimitry Andric bool isTrellis(const MachineBasicBlock *BB, 5410b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 5420b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5430b57cec5SDimitry Andric 5440b57cec5SDimitry Andric /// Get the best successor given a trellis layout. 5450b57cec5SDimitry Andric BlockAndTailDupResult getBestTrellisSuccessor( 5460b57cec5SDimitry Andric const MachineBasicBlock *BB, 5470b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 5480b57cec5SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 5490b57cec5SDimitry Andric const BlockFilterSet *BlockFilter); 5500b57cec5SDimitry Andric 5510b57cec5SDimitry Andric /// Get the best pair of non-conflicting edges. 5520b57cec5SDimitry Andric static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges( 5530b57cec5SDimitry Andric const MachineBasicBlock *BB, 5540b57cec5SDimitry Andric MutableArrayRef<SmallVector<WeightedEdge, 8>> Edges); 5550b57cec5SDimitry Andric 5560b57cec5SDimitry Andric /// Returns true if a block can tail duplicate into all unplaced 5570b57cec5SDimitry Andric /// predecessors. Filters based on loop. 5580b57cec5SDimitry Andric bool canTailDuplicateUnplacedPreds( 5590b57cec5SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 5600b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter); 5610b57cec5SDimitry Andric 5620b57cec5SDimitry Andric /// Find chains of triangles to tail-duplicate where a global analysis works, 5630b57cec5SDimitry Andric /// but a local analysis would not find them. 5640b57cec5SDimitry Andric void precomputeTriangleChains(); 5650b57cec5SDimitry Andric 566*0eae32dcSDimitry Andric /// Apply a post-processing step optimizing block placement. 567*0eae32dcSDimitry Andric void applyExtTsp(); 568*0eae32dcSDimitry Andric 569*0eae32dcSDimitry Andric /// Modify the existing block placement in the function and adjust all jumps. 570*0eae32dcSDimitry Andric void assignBlockOrder(const std::vector<const MachineBasicBlock *> &NewOrder); 571*0eae32dcSDimitry Andric 572*0eae32dcSDimitry Andric /// Create a single CFG chain from the current block order. 573*0eae32dcSDimitry Andric void createCFGChainExtTsp(); 574*0eae32dcSDimitry Andric 5750b57cec5SDimitry Andric public: 5760b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 5770b57cec5SDimitry Andric 5780b57cec5SDimitry Andric MachineBlockPlacement() : MachineFunctionPass(ID) { 5790b57cec5SDimitry Andric initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); 5800b57cec5SDimitry Andric } 5810b57cec5SDimitry Andric 5820b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 5830b57cec5SDimitry Andric 5840b57cec5SDimitry Andric bool allowTailDupPlacement() const { 5850b57cec5SDimitry Andric assert(F); 5860b57cec5SDimitry Andric return TailDupPlacement && !F->getTarget().requiresStructuredCFG(); 5870b57cec5SDimitry Andric } 5880b57cec5SDimitry Andric 5890b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 5900b57cec5SDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>(); 5910b57cec5SDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>(); 5920b57cec5SDimitry Andric if (TailDupPlacement) 5930b57cec5SDimitry Andric AU.addRequired<MachinePostDominatorTree>(); 5940b57cec5SDimitry Andric AU.addRequired<MachineLoopInfo>(); 595480093f4SDimitry Andric AU.addRequired<ProfileSummaryInfoWrapperPass>(); 5960b57cec5SDimitry Andric AU.addRequired<TargetPassConfig>(); 5970b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 5980b57cec5SDimitry Andric } 5990b57cec5SDimitry Andric }; 6000b57cec5SDimitry Andric 6010b57cec5SDimitry Andric } // end anonymous namespace 6020b57cec5SDimitry Andric 6030b57cec5SDimitry Andric char MachineBlockPlacement::ID = 0; 6040b57cec5SDimitry Andric 6050b57cec5SDimitry Andric char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; 6060b57cec5SDimitry Andric 6070b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE, 6080b57cec5SDimitry Andric "Branch Probability Basic Block Placement", false, false) 6090b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 6100b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 6110b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 6120b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 613480093f4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 6140b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacement, DEBUG_TYPE, 6150b57cec5SDimitry Andric "Branch Probability Basic Block Placement", false, false) 6160b57cec5SDimitry Andric 6170b57cec5SDimitry Andric #ifndef NDEBUG 6180b57cec5SDimitry Andric /// Helper to print the name of a MBB. 6190b57cec5SDimitry Andric /// 6200b57cec5SDimitry Andric /// Only used by debug logging. 6210b57cec5SDimitry Andric static std::string getBlockName(const MachineBasicBlock *BB) { 6220b57cec5SDimitry Andric std::string Result; 6230b57cec5SDimitry Andric raw_string_ostream OS(Result); 6240b57cec5SDimitry Andric OS << printMBBReference(*BB); 6250b57cec5SDimitry Andric OS << " ('" << BB->getName() << "')"; 6260b57cec5SDimitry Andric OS.flush(); 6270b57cec5SDimitry Andric return Result; 6280b57cec5SDimitry Andric } 6290b57cec5SDimitry Andric #endif 6300b57cec5SDimitry Andric 6310b57cec5SDimitry Andric /// Mark a chain's successors as having one fewer preds. 6320b57cec5SDimitry Andric /// 6330b57cec5SDimitry Andric /// When a chain is being merged into the "placed" chain, this routine will 6340b57cec5SDimitry Andric /// quickly walk the successors of each block in the chain and mark them as 6350b57cec5SDimitry Andric /// having one fewer active predecessor. It also adds any successors of this 6360b57cec5SDimitry Andric /// chain which reach the zero-predecessor state to the appropriate worklist. 6370b57cec5SDimitry Andric void MachineBlockPlacement::markChainSuccessors( 6380b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *LoopHeaderBB, 6390b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 6400b57cec5SDimitry Andric // Walk all the blocks in this chain, marking their successors as having 6410b57cec5SDimitry Andric // a predecessor placed. 6420b57cec5SDimitry Andric for (MachineBasicBlock *MBB : Chain) { 6430b57cec5SDimitry Andric markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); 6440b57cec5SDimitry Andric } 6450b57cec5SDimitry Andric } 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric /// Mark a single block's successors as having one fewer preds. 6480b57cec5SDimitry Andric /// 6490b57cec5SDimitry Andric /// Under normal circumstances, this is only called by markChainSuccessors, 6500b57cec5SDimitry Andric /// but if a block that was to be placed is completely tail-duplicated away, 6510b57cec5SDimitry Andric /// and was duplicated into the chain end, we need to redo markBlockSuccessors 6520b57cec5SDimitry Andric /// for just that block. 6530b57cec5SDimitry Andric void MachineBlockPlacement::markBlockSuccessors( 6540b57cec5SDimitry Andric const BlockChain &Chain, const MachineBasicBlock *MBB, 6550b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, const BlockFilterSet *BlockFilter) { 6560b57cec5SDimitry Andric // Add any successors for which this is the only un-placed in-loop 6570b57cec5SDimitry Andric // predecessor to the worklist as a viable candidate for CFG-neutral 6580b57cec5SDimitry Andric // placement. No subsequent placement of this block will violate the CFG 6590b57cec5SDimitry Andric // shape, so we get to use heuristics to choose a favorable placement. 6600b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 6610b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(Succ)) 6620b57cec5SDimitry Andric continue; 6630b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 6640b57cec5SDimitry Andric // Disregard edges within a fixed chain, or edges to the loop header. 6650b57cec5SDimitry Andric if (&Chain == &SuccChain || Succ == LoopHeaderBB) 6660b57cec5SDimitry Andric continue; 6670b57cec5SDimitry Andric 6680b57cec5SDimitry Andric // This is a cross-chain edge that is within the loop, so decrement the 6690b57cec5SDimitry Andric // loop predecessor count of the destination chain. 6700b57cec5SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0 || 6710b57cec5SDimitry Andric --SuccChain.UnscheduledPredecessors > 0) 6720b57cec5SDimitry Andric continue; 6730b57cec5SDimitry Andric 6740b57cec5SDimitry Andric auto *NewBB = *SuccChain.begin(); 6750b57cec5SDimitry Andric if (NewBB->isEHPad()) 6760b57cec5SDimitry Andric EHPadWorkList.push_back(NewBB); 6770b57cec5SDimitry Andric else 6780b57cec5SDimitry Andric BlockWorkList.push_back(NewBB); 6790b57cec5SDimitry Andric } 6800b57cec5SDimitry Andric } 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric /// This helper function collects the set of successors of block 6830b57cec5SDimitry Andric /// \p BB that are allowed to be its layout successors, and return 6840b57cec5SDimitry Andric /// the total branch probability of edges from \p BB to those 6850b57cec5SDimitry Andric /// blocks. 6860b57cec5SDimitry Andric BranchProbability MachineBlockPlacement::collectViableSuccessors( 6870b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 6880b57cec5SDimitry Andric const BlockFilterSet *BlockFilter, 6890b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> &Successors) { 6900b57cec5SDimitry Andric // Adjust edge probabilities by excluding edges pointing to blocks that is 6910b57cec5SDimitry Andric // either not in BlockFilter or is already in the current chain. Consider the 6920b57cec5SDimitry Andric // following CFG: 6930b57cec5SDimitry Andric // 6940b57cec5SDimitry Andric // --->A 6950b57cec5SDimitry Andric // | / \ 6960b57cec5SDimitry Andric // | B C 6970b57cec5SDimitry Andric // | \ / \ 6980b57cec5SDimitry Andric // ----D E 6990b57cec5SDimitry Andric // 7000b57cec5SDimitry Andric // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after 7010b57cec5SDimitry Andric // A->C is chosen as a fall-through, D won't be selected as a successor of C 7020b57cec5SDimitry Andric // due to CFG constraint (the probability of C->D is not greater than 7030b57cec5SDimitry Andric // HotProb to break topo-order). If we exclude E that is not in BlockFilter 7040b57cec5SDimitry Andric // when calculating the probability of C->D, D will be selected and we 7050b57cec5SDimitry Andric // will get A C D B as the layout of this loop. 7060b57cec5SDimitry Andric auto AdjustedSumProb = BranchProbability::getOne(); 7070b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB->successors()) { 7080b57cec5SDimitry Andric bool SkipSucc = false; 7090b57cec5SDimitry Andric if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { 7100b57cec5SDimitry Andric SkipSucc = true; 7110b57cec5SDimitry Andric } else { 7120b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 7130b57cec5SDimitry Andric if (SuccChain == &Chain) { 7140b57cec5SDimitry Andric SkipSucc = true; 7150b57cec5SDimitry Andric } else if (Succ != *SuccChain->begin()) { 7160b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(Succ) 7170b57cec5SDimitry Andric << " -> Mid chain!\n"); 7180b57cec5SDimitry Andric continue; 7190b57cec5SDimitry Andric } 7200b57cec5SDimitry Andric } 7210b57cec5SDimitry Andric if (SkipSucc) 7220b57cec5SDimitry Andric AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); 7230b57cec5SDimitry Andric else 7240b57cec5SDimitry Andric Successors.push_back(Succ); 7250b57cec5SDimitry Andric } 7260b57cec5SDimitry Andric 7270b57cec5SDimitry Andric return AdjustedSumProb; 7280b57cec5SDimitry Andric } 7290b57cec5SDimitry Andric 7300b57cec5SDimitry Andric /// The helper function returns the branch probability that is adjusted 7310b57cec5SDimitry Andric /// or normalized over the new total \p AdjustedSumProb. 7320b57cec5SDimitry Andric static BranchProbability 7330b57cec5SDimitry Andric getAdjustedProbability(BranchProbability OrigProb, 7340b57cec5SDimitry Andric BranchProbability AdjustedSumProb) { 7350b57cec5SDimitry Andric BranchProbability SuccProb; 7360b57cec5SDimitry Andric uint32_t SuccProbN = OrigProb.getNumerator(); 7370b57cec5SDimitry Andric uint32_t SuccProbD = AdjustedSumProb.getNumerator(); 7380b57cec5SDimitry Andric if (SuccProbN >= SuccProbD) 7390b57cec5SDimitry Andric SuccProb = BranchProbability::getOne(); 7400b57cec5SDimitry Andric else 7410b57cec5SDimitry Andric SuccProb = BranchProbability(SuccProbN, SuccProbD); 7420b57cec5SDimitry Andric 7430b57cec5SDimitry Andric return SuccProb; 7440b57cec5SDimitry Andric } 7450b57cec5SDimitry Andric 7460b57cec5SDimitry Andric /// Check if \p BB has exactly the successors in \p Successors. 7470b57cec5SDimitry Andric static bool 7480b57cec5SDimitry Andric hasSameSuccessors(MachineBasicBlock &BB, 7490b57cec5SDimitry Andric SmallPtrSetImpl<const MachineBasicBlock *> &Successors) { 7500b57cec5SDimitry Andric if (BB.succ_size() != Successors.size()) 7510b57cec5SDimitry Andric return false; 7520b57cec5SDimitry Andric // We don't want to count self-loops 7530b57cec5SDimitry Andric if (Successors.count(&BB)) 7540b57cec5SDimitry Andric return false; 7550b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) 7560b57cec5SDimitry Andric if (!Successors.count(Succ)) 7570b57cec5SDimitry Andric return false; 7580b57cec5SDimitry Andric return true; 7590b57cec5SDimitry Andric } 7600b57cec5SDimitry Andric 7610b57cec5SDimitry Andric /// Check if a block should be tail duplicated to increase fallthrough 7620b57cec5SDimitry Andric /// opportunities. 7630b57cec5SDimitry Andric /// \p BB Block to check. 7640b57cec5SDimitry Andric bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) { 7650b57cec5SDimitry Andric // Blocks with single successors don't create additional fallthrough 7660b57cec5SDimitry Andric // opportunities. Don't duplicate them. TODO: When conditional exits are 7670b57cec5SDimitry Andric // analyzable, allow them to be duplicated. 7680b57cec5SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 7690b57cec5SDimitry Andric 7700b57cec5SDimitry Andric if (BB->succ_size() == 1) 7710b57cec5SDimitry Andric return false; 7720b57cec5SDimitry Andric return TailDup.shouldTailDuplicate(IsSimple, *BB); 7730b57cec5SDimitry Andric } 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric /// Compare 2 BlockFrequency's with a small penalty for \p A. 7760b57cec5SDimitry Andric /// In order to be conservative, we apply a X% penalty to account for 7770b57cec5SDimitry Andric /// increased icache pressure and static heuristics. For small frequencies 7780b57cec5SDimitry Andric /// we use only the numerators to improve accuracy. For simplicity, we assume the 7790b57cec5SDimitry Andric /// penalty is less than 100% 7800b57cec5SDimitry Andric /// TODO(iteratee): Use 64-bit fixed point edge frequencies everywhere. 7810b57cec5SDimitry Andric static bool greaterWithBias(BlockFrequency A, BlockFrequency B, 7820b57cec5SDimitry Andric uint64_t EntryFreq) { 7830b57cec5SDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 7840b57cec5SDimitry Andric BlockFrequency Gain = A - B; 7850b57cec5SDimitry Andric return (Gain / ThresholdProb).getFrequency() >= EntryFreq; 7860b57cec5SDimitry Andric } 7870b57cec5SDimitry Andric 7880b57cec5SDimitry Andric /// Check the edge frequencies to see if tail duplication will increase 7890b57cec5SDimitry Andric /// fallthroughs. It only makes sense to call this function when 7900b57cec5SDimitry Andric /// \p Succ would not be chosen otherwise. Tail duplication of \p Succ is 7910b57cec5SDimitry Andric /// always locally profitable if we would have picked \p Succ without 7920b57cec5SDimitry Andric /// considering duplication. 7930b57cec5SDimitry Andric bool MachineBlockPlacement::isProfitableToTailDup( 7940b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 7950b57cec5SDimitry Andric BranchProbability QProb, 7960b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 7970b57cec5SDimitry Andric // We need to do a probability calculation to make sure this is profitable. 7980b57cec5SDimitry Andric // First: does succ have a successor that post-dominates? This affects the 7990b57cec5SDimitry Andric // calculation. The 2 relevant cases are: 8000b57cec5SDimitry Andric // BB BB 8010b57cec5SDimitry Andric // | \Qout | \Qout 8020b57cec5SDimitry Andric // P| C |P C 8030b57cec5SDimitry Andric // = C' = C' 8040b57cec5SDimitry Andric // | /Qin | /Qin 8050b57cec5SDimitry Andric // | / | / 8060b57cec5SDimitry Andric // Succ Succ 8070b57cec5SDimitry Andric // / \ | \ V 8080b57cec5SDimitry Andric // U/ =V |U \ 8090b57cec5SDimitry Andric // / \ = D 8100b57cec5SDimitry Andric // D E | / 8110b57cec5SDimitry Andric // | / 8120b57cec5SDimitry Andric // |/ 8130b57cec5SDimitry Andric // PDom 8140b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 8150b57cec5SDimitry Andric // In the second case, Placing Succ while duplicating it into C prevents the 8160b57cec5SDimitry Andric // fallthrough of Succ into either D or PDom, because they now have C as an 8170b57cec5SDimitry Andric // unplaced predecessor 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric // Start by figuring out which case we fall into 8200b57cec5SDimitry Andric MachineBasicBlock *PDom = nullptr; 8210b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> SuccSuccs; 8220b57cec5SDimitry Andric // Only scan the relevant successors 8230b57cec5SDimitry Andric auto AdjustedSuccSumProb = 8240b57cec5SDimitry Andric collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs); 8250b57cec5SDimitry Andric BranchProbability PProb = MBPI->getEdgeProbability(BB, Succ); 8260b57cec5SDimitry Andric auto BBFreq = MBFI->getBlockFreq(BB); 8270b57cec5SDimitry Andric auto SuccFreq = MBFI->getBlockFreq(Succ); 8280b57cec5SDimitry Andric BlockFrequency P = BBFreq * PProb; 8290b57cec5SDimitry Andric BlockFrequency Qout = BBFreq * QProb; 8300b57cec5SDimitry Andric uint64_t EntryFreq = MBFI->getEntryFreq(); 8310b57cec5SDimitry Andric // If there are no more successors, it is profitable to copy, as it strictly 8320b57cec5SDimitry Andric // increases fallthrough. 8330b57cec5SDimitry Andric if (SuccSuccs.size() == 0) 8340b57cec5SDimitry Andric return greaterWithBias(P, Qout, EntryFreq); 8350b57cec5SDimitry Andric 8360b57cec5SDimitry Andric auto BestSuccSucc = BranchProbability::getZero(); 8370b57cec5SDimitry Andric // Find the PDom or the best Succ if no PDom exists. 8380b57cec5SDimitry Andric for (MachineBasicBlock *SuccSucc : SuccSuccs) { 8390b57cec5SDimitry Andric auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc); 8400b57cec5SDimitry Andric if (Prob > BestSuccSucc) 8410b57cec5SDimitry Andric BestSuccSucc = Prob; 8420b57cec5SDimitry Andric if (PDom == nullptr) 8430b57cec5SDimitry Andric if (MPDT->dominates(SuccSucc, Succ)) { 8440b57cec5SDimitry Andric PDom = SuccSucc; 8450b57cec5SDimitry Andric break; 8460b57cec5SDimitry Andric } 8470b57cec5SDimitry Andric } 8480b57cec5SDimitry Andric // For the comparisons, we need to know Succ's best incoming edge that isn't 8490b57cec5SDimitry Andric // from BB. 8500b57cec5SDimitry Andric auto SuccBestPred = BlockFrequency(0); 8510b57cec5SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 8520b57cec5SDimitry Andric if (SuccPred == Succ || SuccPred == BB 8530b57cec5SDimitry Andric || BlockToChain[SuccPred] == &Chain 8540b57cec5SDimitry Andric || (BlockFilter && !BlockFilter->count(SuccPred))) 8550b57cec5SDimitry Andric continue; 8560b57cec5SDimitry Andric auto Freq = MBFI->getBlockFreq(SuccPred) 8570b57cec5SDimitry Andric * MBPI->getEdgeProbability(SuccPred, Succ); 8580b57cec5SDimitry Andric if (Freq > SuccBestPred) 8590b57cec5SDimitry Andric SuccBestPred = Freq; 8600b57cec5SDimitry Andric } 8610b57cec5SDimitry Andric // Qin is Succ's best unplaced incoming edge that isn't BB 8620b57cec5SDimitry Andric BlockFrequency Qin = SuccBestPred; 8630b57cec5SDimitry Andric // If it doesn't have a post-dominating successor, here is the calculation: 8640b57cec5SDimitry Andric // BB BB 8650b57cec5SDimitry Andric // | \Qout | \ 8660b57cec5SDimitry Andric // P| C | = 8670b57cec5SDimitry Andric // = C' | C 8680b57cec5SDimitry Andric // | /Qin | | 8690b57cec5SDimitry Andric // | / | C' (+Succ) 8700b57cec5SDimitry Andric // Succ Succ /| 8710b57cec5SDimitry Andric // / \ | \/ | 8720b57cec5SDimitry Andric // U/ =V | == | 8730b57cec5SDimitry Andric // / \ | / \| 8740b57cec5SDimitry Andric // D E D E 8750b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 8760b57cec5SDimitry Andric // Cost in the first case is: P + V 8770b57cec5SDimitry Andric // For this calculation, we always assume P > Qout. If Qout > P 8780b57cec5SDimitry Andric // The result of this function will be ignored at the caller. 8790b57cec5SDimitry Andric // Let F = SuccFreq - Qin 8800b57cec5SDimitry Andric // Cost in the second case is: Qout + min(Qin, F) * U + max(Qin, F) * V 8810b57cec5SDimitry Andric 8820b57cec5SDimitry Andric if (PDom == nullptr || !Succ->isSuccessor(PDom)) { 8830b57cec5SDimitry Andric BranchProbability UProb = BestSuccSucc; 8840b57cec5SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 8850b57cec5SDimitry Andric BlockFrequency F = SuccFreq - Qin; 8860b57cec5SDimitry Andric BlockFrequency V = SuccFreq * VProb; 8870b57cec5SDimitry Andric BlockFrequency QinU = std::min(Qin, F) * UProb; 8880b57cec5SDimitry Andric BlockFrequency BaseCost = P + V; 8890b57cec5SDimitry Andric BlockFrequency DupCost = Qout + QinU + std::max(Qin, F) * VProb; 8900b57cec5SDimitry Andric return greaterWithBias(BaseCost, DupCost, EntryFreq); 8910b57cec5SDimitry Andric } 8920b57cec5SDimitry Andric BranchProbability UProb = MBPI->getEdgeProbability(Succ, PDom); 8930b57cec5SDimitry Andric BranchProbability VProb = AdjustedSuccSumProb - UProb; 8940b57cec5SDimitry Andric BlockFrequency U = SuccFreq * UProb; 8950b57cec5SDimitry Andric BlockFrequency V = SuccFreq * VProb; 8960b57cec5SDimitry Andric BlockFrequency F = SuccFreq - Qin; 8970b57cec5SDimitry Andric // If there is a post-dominating successor, here is the calculation: 8980b57cec5SDimitry Andric // BB BB BB BB 8990b57cec5SDimitry Andric // | \Qout | \ | \Qout | \ 9000b57cec5SDimitry Andric // |P C | = |P C | = 9010b57cec5SDimitry Andric // = C' |P C = C' |P C 9020b57cec5SDimitry Andric // | /Qin | | | /Qin | | 9030b57cec5SDimitry Andric // | / | C' (+Succ) | / | C' (+Succ) 9040b57cec5SDimitry Andric // Succ Succ /| Succ Succ /| 9050b57cec5SDimitry Andric // | \ V | \/ | | \ V | \/ | 9060b57cec5SDimitry Andric // |U \ |U /\ =? |U = |U /\ | 9070b57cec5SDimitry Andric // = D = = =?| | D | = =| 9080b57cec5SDimitry Andric // | / |/ D | / |/ D 9090b57cec5SDimitry Andric // | / | / | = | / 9100b57cec5SDimitry Andric // |/ | / |/ | = 9110b57cec5SDimitry Andric // Dom Dom Dom Dom 9120b57cec5SDimitry Andric // '=' : Branch taken for that CFG edge 9130b57cec5SDimitry Andric // The cost for taken branches in the first case is P + U 9140b57cec5SDimitry Andric // Let F = SuccFreq - Qin 9150b57cec5SDimitry Andric // The cost in the second case (assuming independence), given the layout: 9160b57cec5SDimitry Andric // BB, Succ, (C+Succ), D, Dom or the layout: 9170b57cec5SDimitry Andric // BB, Succ, D, Dom, (C+Succ) 9180b57cec5SDimitry Andric // is Qout + max(F, Qin) * U + min(F, Qin) 9190b57cec5SDimitry Andric // compare P + U vs Qout + P * U + Qin. 9200b57cec5SDimitry Andric // 9210b57cec5SDimitry Andric // The 3rd and 4th cases cover when Dom would be chosen to follow Succ. 9220b57cec5SDimitry Andric // 9230b57cec5SDimitry Andric // For the 3rd case, the cost is P + 2 * V 9240b57cec5SDimitry Andric // For the 4th case, the cost is Qout + min(Qin, F) * U + max(Qin, F) * V + V 9250b57cec5SDimitry Andric // We choose 4 over 3 when (P + V) > Qout + min(Qin, F) * U + max(Qin, F) * V 9260b57cec5SDimitry Andric if (UProb > AdjustedSuccSumProb / 2 && 9270b57cec5SDimitry Andric !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb, 9280b57cec5SDimitry Andric Chain, BlockFilter)) 9290b57cec5SDimitry Andric // Cases 3 & 4 9300b57cec5SDimitry Andric return greaterWithBias( 9310b57cec5SDimitry Andric (P + V), (Qout + std::max(Qin, F) * VProb + std::min(Qin, F) * UProb), 9320b57cec5SDimitry Andric EntryFreq); 9330b57cec5SDimitry Andric // Cases 1 & 2 9340b57cec5SDimitry Andric return greaterWithBias((P + U), 9350b57cec5SDimitry Andric (Qout + std::min(Qin, F) * AdjustedSuccSumProb + 9360b57cec5SDimitry Andric std::max(Qin, F) * UProb), 9370b57cec5SDimitry Andric EntryFreq); 9380b57cec5SDimitry Andric } 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric /// Check for a trellis layout. \p BB is the upper part of a trellis if its 9410b57cec5SDimitry Andric /// successors form the lower part of a trellis. A successor set S forms the 9420b57cec5SDimitry Andric /// lower part of a trellis if all of the predecessors of S are either in S or 9430b57cec5SDimitry Andric /// have all of S as successors. We ignore trellises where BB doesn't have 2 9440b57cec5SDimitry Andric /// successors because for fewer than 2, it's trivial, and for 3 or greater they 9450b57cec5SDimitry Andric /// are very uncommon and complex to compute optimally. Allowing edges within S 9460b57cec5SDimitry Andric /// is not strictly a trellis, but the same algorithm works, so we allow it. 9470b57cec5SDimitry Andric bool MachineBlockPlacement::isTrellis( 9480b57cec5SDimitry Andric const MachineBasicBlock *BB, 9490b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 9500b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 9510b57cec5SDimitry Andric // Technically BB could form a trellis with branching factor higher than 2. 9520b57cec5SDimitry Andric // But that's extremely uncommon. 9530b57cec5SDimitry Andric if (BB->succ_size() != 2 || ViableSuccs.size() != 2) 9540b57cec5SDimitry Andric return false; 9550b57cec5SDimitry Andric 9560b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 2> Successors(BB->succ_begin(), 9570b57cec5SDimitry Andric BB->succ_end()); 9580b57cec5SDimitry Andric // To avoid reviewing the same predecessors twice. 9590b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds; 9600b57cec5SDimitry Andric 9610b57cec5SDimitry Andric for (MachineBasicBlock *Succ : ViableSuccs) { 9620b57cec5SDimitry Andric int PredCount = 0; 9630b57cec5SDimitry Andric for (auto SuccPred : Succ->predecessors()) { 9640b57cec5SDimitry Andric // Allow triangle successors, but don't count them. 9650b57cec5SDimitry Andric if (Successors.count(SuccPred)) { 9660b57cec5SDimitry Andric // Make sure that it is actually a triangle. 9670b57cec5SDimitry Andric for (MachineBasicBlock *CheckSucc : SuccPred->successors()) 9680b57cec5SDimitry Andric if (!Successors.count(CheckSucc)) 9690b57cec5SDimitry Andric return false; 9700b57cec5SDimitry Andric continue; 9710b57cec5SDimitry Andric } 9720b57cec5SDimitry Andric const BlockChain *PredChain = BlockToChain[SuccPred]; 9730b57cec5SDimitry Andric if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) || 9740b57cec5SDimitry Andric PredChain == &Chain || PredChain == BlockToChain[Succ]) 9750b57cec5SDimitry Andric continue; 9760b57cec5SDimitry Andric ++PredCount; 9770b57cec5SDimitry Andric // Perform the successor check only once. 9780b57cec5SDimitry Andric if (!SeenPreds.insert(SuccPred).second) 9790b57cec5SDimitry Andric continue; 9800b57cec5SDimitry Andric if (!hasSameSuccessors(*SuccPred, Successors)) 9810b57cec5SDimitry Andric return false; 9820b57cec5SDimitry Andric } 9830b57cec5SDimitry Andric // If one of the successors has only BB as a predecessor, it is not a 9840b57cec5SDimitry Andric // trellis. 9850b57cec5SDimitry Andric if (PredCount < 1) 9860b57cec5SDimitry Andric return false; 9870b57cec5SDimitry Andric } 9880b57cec5SDimitry Andric return true; 9890b57cec5SDimitry Andric } 9900b57cec5SDimitry Andric 9910b57cec5SDimitry Andric /// Pick the highest total weight pair of edges that can both be laid out. 9920b57cec5SDimitry Andric /// The edges in \p Edges[0] are assumed to have a different destination than 9930b57cec5SDimitry Andric /// the edges in \p Edges[1]. Simple counting shows that the best pair is either 9940b57cec5SDimitry Andric /// the individual highest weight edges to the 2 different destinations, or in 9950b57cec5SDimitry Andric /// case of a conflict, one of them should be replaced with a 2nd best edge. 9960b57cec5SDimitry Andric std::pair<MachineBlockPlacement::WeightedEdge, 9970b57cec5SDimitry Andric MachineBlockPlacement::WeightedEdge> 9980b57cec5SDimitry Andric MachineBlockPlacement::getBestNonConflictingEdges( 9990b57cec5SDimitry Andric const MachineBasicBlock *BB, 10000b57cec5SDimitry Andric MutableArrayRef<SmallVector<MachineBlockPlacement::WeightedEdge, 8>> 10010b57cec5SDimitry Andric Edges) { 10020b57cec5SDimitry Andric // Sort the edges, and then for each successor, find the best incoming 10030b57cec5SDimitry Andric // predecessor. If the best incoming predecessors aren't the same, 10040b57cec5SDimitry Andric // then that is clearly the best layout. If there is a conflict, one of the 10050b57cec5SDimitry Andric // successors will have to fallthrough from the second best predecessor. We 10060b57cec5SDimitry Andric // compare which combination is better overall. 10070b57cec5SDimitry Andric 10080b57cec5SDimitry Andric // Sort for highest frequency. 10090b57cec5SDimitry Andric auto Cmp = [](WeightedEdge A, WeightedEdge B) { return A.Weight > B.Weight; }; 10100b57cec5SDimitry Andric 10110b57cec5SDimitry Andric llvm::stable_sort(Edges[0], Cmp); 10120b57cec5SDimitry Andric llvm::stable_sort(Edges[1], Cmp); 10130b57cec5SDimitry Andric auto BestA = Edges[0].begin(); 10140b57cec5SDimitry Andric auto BestB = Edges[1].begin(); 10150b57cec5SDimitry Andric // Arrange for the correct answer to be in BestA and BestB 10160b57cec5SDimitry Andric // If the 2 best edges don't conflict, the answer is already there. 10170b57cec5SDimitry Andric if (BestA->Src == BestB->Src) { 10180b57cec5SDimitry Andric // Compare the total fallthrough of (Best + Second Best) for both pairs 10190b57cec5SDimitry Andric auto SecondBestA = std::next(BestA); 10200b57cec5SDimitry Andric auto SecondBestB = std::next(BestB); 10210b57cec5SDimitry Andric BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight; 10220b57cec5SDimitry Andric BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight; 10230b57cec5SDimitry Andric if (BestAScore < BestBScore) 10240b57cec5SDimitry Andric BestA = SecondBestA; 10250b57cec5SDimitry Andric else 10260b57cec5SDimitry Andric BestB = SecondBestB; 10270b57cec5SDimitry Andric } 10280b57cec5SDimitry Andric // Arrange for the BB edge to be in BestA if it exists. 10290b57cec5SDimitry Andric if (BestB->Src == BB) 10300b57cec5SDimitry Andric std::swap(BestA, BestB); 10310b57cec5SDimitry Andric return std::make_pair(*BestA, *BestB); 10320b57cec5SDimitry Andric } 10330b57cec5SDimitry Andric 10340b57cec5SDimitry Andric /// Get the best successor from \p BB based on \p BB being part of a trellis. 10350b57cec5SDimitry Andric /// We only handle trellises with 2 successors, so the algorithm is 10360b57cec5SDimitry Andric /// straightforward: Find the best pair of edges that don't conflict. We find 10370b57cec5SDimitry Andric /// the best incoming edge for each successor in the trellis. If those conflict, 10380b57cec5SDimitry Andric /// we consider which of them should be replaced with the second best. 10390b57cec5SDimitry Andric /// Upon return the two best edges will be in \p BestEdges. If one of the edges 10400b57cec5SDimitry Andric /// comes from \p BB, it will be in \p BestEdges[0] 10410b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 10420b57cec5SDimitry Andric MachineBlockPlacement::getBestTrellisSuccessor( 10430b57cec5SDimitry Andric const MachineBasicBlock *BB, 10440b57cec5SDimitry Andric const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs, 10450b57cec5SDimitry Andric BranchProbability AdjustedSumProb, const BlockChain &Chain, 10460b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 10470b57cec5SDimitry Andric 10480b57cec5SDimitry Andric BlockAndTailDupResult Result = {nullptr, false}; 10490b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 10500b57cec5SDimitry Andric BB->succ_end()); 10510b57cec5SDimitry Andric 10520b57cec5SDimitry Andric // We assume size 2 because it's common. For general n, we would have to do 10530b57cec5SDimitry Andric // the Hungarian algorithm, but it's not worth the complexity because more 10540b57cec5SDimitry Andric // than 2 successors is fairly uncommon, and a trellis even more so. 10550b57cec5SDimitry Andric if (Successors.size() != 2 || ViableSuccs.size() != 2) 10560b57cec5SDimitry Andric return Result; 10570b57cec5SDimitry Andric 10580b57cec5SDimitry Andric // Collect the edge frequencies of all edges that form the trellis. 10590b57cec5SDimitry Andric SmallVector<WeightedEdge, 8> Edges[2]; 10600b57cec5SDimitry Andric int SuccIndex = 0; 10610b57cec5SDimitry Andric for (auto Succ : ViableSuccs) { 10620b57cec5SDimitry Andric for (MachineBasicBlock *SuccPred : Succ->predecessors()) { 10630b57cec5SDimitry Andric // Skip any placed predecessors that are not BB 10640b57cec5SDimitry Andric if (SuccPred != BB) 10650b57cec5SDimitry Andric if ((BlockFilter && !BlockFilter->count(SuccPred)) || 10660b57cec5SDimitry Andric BlockToChain[SuccPred] == &Chain || 10670b57cec5SDimitry Andric BlockToChain[SuccPred] == BlockToChain[Succ]) 10680b57cec5SDimitry Andric continue; 10690b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) * 10700b57cec5SDimitry Andric MBPI->getEdgeProbability(SuccPred, Succ); 10710b57cec5SDimitry Andric Edges[SuccIndex].push_back({EdgeFreq, SuccPred, Succ}); 10720b57cec5SDimitry Andric } 10730b57cec5SDimitry Andric ++SuccIndex; 10740b57cec5SDimitry Andric } 10750b57cec5SDimitry Andric 10760b57cec5SDimitry Andric // Pick the best combination of 2 edges from all the edges in the trellis. 10770b57cec5SDimitry Andric WeightedEdge BestA, BestB; 10780b57cec5SDimitry Andric std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges); 10790b57cec5SDimitry Andric 10800b57cec5SDimitry Andric if (BestA.Src != BB) { 10810b57cec5SDimitry Andric // If we have a trellis, and BB doesn't have the best fallthrough edges, 10820b57cec5SDimitry Andric // we shouldn't choose any successor. We've already looked and there's a 10830b57cec5SDimitry Andric // better fallthrough edge for all the successors. 10840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Trellis, but not one of the chosen edges.\n"); 10850b57cec5SDimitry Andric return Result; 10860b57cec5SDimitry Andric } 10870b57cec5SDimitry Andric 10880b57cec5SDimitry Andric // Did we pick the triangle edge? If tail-duplication is profitable, do 10890b57cec5SDimitry Andric // that instead. Otherwise merge the triangle edge now while we know it is 10900b57cec5SDimitry Andric // optimal. 10910b57cec5SDimitry Andric if (BestA.Dest == BestB.Src) { 10920b57cec5SDimitry Andric // The edges are BB->Succ1->Succ2, and we're looking to see if BB->Succ2 10930b57cec5SDimitry Andric // would be better. 10940b57cec5SDimitry Andric MachineBasicBlock *Succ1 = BestA.Dest; 10950b57cec5SDimitry Andric MachineBasicBlock *Succ2 = BestB.Dest; 10960b57cec5SDimitry Andric // Check to see if tail-duplication would be profitable. 10970b57cec5SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) && 10980b57cec5SDimitry Andric canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) && 10990b57cec5SDimitry Andric isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1), 11000b57cec5SDimitry Andric Chain, BlockFilter)) { 11010b57cec5SDimitry Andric LLVM_DEBUG(BranchProbability Succ2Prob = getAdjustedProbability( 11020b57cec5SDimitry Andric MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb); 11030b57cec5SDimitry Andric dbgs() << " Selected: " << getBlockName(Succ2) 11040b57cec5SDimitry Andric << ", probability: " << Succ2Prob 11050b57cec5SDimitry Andric << " (Tail Duplicate)\n"); 11060b57cec5SDimitry Andric Result.BB = Succ2; 11070b57cec5SDimitry Andric Result.ShouldTailDup = true; 11080b57cec5SDimitry Andric return Result; 11090b57cec5SDimitry Andric } 11100b57cec5SDimitry Andric } 11110b57cec5SDimitry Andric // We have already computed the optimal edge for the other side of the 11120b57cec5SDimitry Andric // trellis. 11130b57cec5SDimitry Andric ComputedEdges[BestB.Src] = { BestB.Dest, false }; 11140b57cec5SDimitry Andric 11150b57cec5SDimitry Andric auto TrellisSucc = BestA.Dest; 11160b57cec5SDimitry Andric LLVM_DEBUG(BranchProbability SuccProb = getAdjustedProbability( 11170b57cec5SDimitry Andric MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb); 11180b57cec5SDimitry Andric dbgs() << " Selected: " << getBlockName(TrellisSucc) 11190b57cec5SDimitry Andric << ", probability: " << SuccProb << " (Trellis)\n"); 11200b57cec5SDimitry Andric Result.BB = TrellisSucc; 11210b57cec5SDimitry Andric return Result; 11220b57cec5SDimitry Andric } 11230b57cec5SDimitry Andric 11240b57cec5SDimitry Andric /// When the option allowTailDupPlacement() is on, this method checks if the 11250b57cec5SDimitry Andric /// fallthrough candidate block \p Succ (of block \p BB) can be tail-duplicated 11260b57cec5SDimitry Andric /// into all of its unplaced, unfiltered predecessors, that are not BB. 11270b57cec5SDimitry Andric bool MachineBlockPlacement::canTailDuplicateUnplacedPreds( 11280b57cec5SDimitry Andric const MachineBasicBlock *BB, MachineBasicBlock *Succ, 11290b57cec5SDimitry Andric const BlockChain &Chain, const BlockFilterSet *BlockFilter) { 11300b57cec5SDimitry Andric if (!shouldTailDuplicate(Succ)) 11310b57cec5SDimitry Andric return false; 11320b57cec5SDimitry Andric 1133480093f4SDimitry Andric // The result of canTailDuplicate. 1134480093f4SDimitry Andric bool Duplicate = true; 1135480093f4SDimitry Andric // Number of possible duplication. 1136480093f4SDimitry Andric unsigned int NumDup = 0; 1137480093f4SDimitry Andric 11380b57cec5SDimitry Andric // For CFG checking. 11390b57cec5SDimitry Andric SmallPtrSet<const MachineBasicBlock *, 4> Successors(BB->succ_begin(), 11400b57cec5SDimitry Andric BB->succ_end()); 11410b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 11420b57cec5SDimitry Andric // Make sure all unplaced and unfiltered predecessors can be 11430b57cec5SDimitry Andric // tail-duplicated into. 11440b57cec5SDimitry Andric // Skip any blocks that are already placed or not in this loop. 11450b57cec5SDimitry Andric if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) 11460b57cec5SDimitry Andric || BlockToChain[Pred] == &Chain) 11470b57cec5SDimitry Andric continue; 11480b57cec5SDimitry Andric if (!TailDup.canTailDuplicate(Succ, Pred)) { 11490b57cec5SDimitry Andric if (Successors.size() > 1 && hasSameSuccessors(*Pred, Successors)) 11500b57cec5SDimitry Andric // This will result in a trellis after tail duplication, so we don't 11510b57cec5SDimitry Andric // need to copy Succ into this predecessor. In the presence 11520b57cec5SDimitry Andric // of a trellis tail duplication can continue to be profitable. 11530b57cec5SDimitry Andric // For example: 11540b57cec5SDimitry Andric // A A 11550b57cec5SDimitry Andric // |\ |\ 11560b57cec5SDimitry Andric // | \ | \ 11570b57cec5SDimitry Andric // | C | C+BB 11580b57cec5SDimitry Andric // | / | | 11590b57cec5SDimitry Andric // |/ | | 11600b57cec5SDimitry Andric // BB => BB | 11610b57cec5SDimitry Andric // |\ |\/| 11620b57cec5SDimitry Andric // | \ |/\| 11630b57cec5SDimitry Andric // | D | D 11640b57cec5SDimitry Andric // | / | / 11650b57cec5SDimitry Andric // |/ |/ 11660b57cec5SDimitry Andric // Succ Succ 11670b57cec5SDimitry Andric // 11680b57cec5SDimitry Andric // After BB was duplicated into C, the layout looks like the one on the 11690b57cec5SDimitry Andric // right. BB and C now have the same successors. When considering 11700b57cec5SDimitry Andric // whether Succ can be duplicated into all its unplaced predecessors, we 11710b57cec5SDimitry Andric // ignore C. 11720b57cec5SDimitry Andric // We can do this because C already has a profitable fallthrough, namely 11730b57cec5SDimitry Andric // D. TODO(iteratee): ignore sufficiently cold predecessors for 11740b57cec5SDimitry Andric // duplication and for this test. 11750b57cec5SDimitry Andric // 11760b57cec5SDimitry Andric // This allows trellises to be laid out in 2 separate chains 11770b57cec5SDimitry Andric // (A,B,Succ,...) and later (C,D,...) This is a reasonable heuristic 11780b57cec5SDimitry Andric // because it allows the creation of 2 fallthrough paths with links 11790b57cec5SDimitry Andric // between them, and we correctly identify the best layout for these 11800b57cec5SDimitry Andric // CFGs. We want to extend trellises that the user created in addition 11810b57cec5SDimitry Andric // to trellises created by tail-duplication, so we just look for the 11820b57cec5SDimitry Andric // CFG. 11830b57cec5SDimitry Andric continue; 1184480093f4SDimitry Andric Duplicate = false; 1185480093f4SDimitry Andric continue; 1186480093f4SDimitry Andric } 1187480093f4SDimitry Andric NumDup++; 1188480093f4SDimitry Andric } 1189480093f4SDimitry Andric 1190480093f4SDimitry Andric // No possible duplication in current filter set. 1191480093f4SDimitry Andric if (NumDup == 0) 11920b57cec5SDimitry Andric return false; 1193480093f4SDimitry Andric 11945ffd83dbSDimitry Andric // If profile information is available, findDuplicateCandidates can do more 11955ffd83dbSDimitry Andric // precise benefit analysis. 11965ffd83dbSDimitry Andric if (F->getFunction().hasProfileData()) 11975ffd83dbSDimitry Andric return true; 11985ffd83dbSDimitry Andric 1199480093f4SDimitry Andric // This is mainly for function exit BB. 1200480093f4SDimitry Andric // The integrated tail duplication is really designed for increasing 1201480093f4SDimitry Andric // fallthrough from predecessors from Succ to its successors. We may need 1202480093f4SDimitry Andric // other machanism to handle different cases. 1203349cc55cSDimitry Andric if (Succ->succ_empty()) 1204480093f4SDimitry Andric return true; 1205480093f4SDimitry Andric 1206480093f4SDimitry Andric // Plus the already placed predecessor. 1207480093f4SDimitry Andric NumDup++; 1208480093f4SDimitry Andric 1209480093f4SDimitry Andric // If the duplication candidate has more unplaced predecessors than 1210480093f4SDimitry Andric // successors, the extra duplication can't bring more fallthrough. 1211480093f4SDimitry Andric // 1212480093f4SDimitry Andric // Pred1 Pred2 Pred3 1213480093f4SDimitry Andric // \ | / 1214480093f4SDimitry Andric // \ | / 1215480093f4SDimitry Andric // \ | / 1216480093f4SDimitry Andric // Dup 1217480093f4SDimitry Andric // / \ 1218480093f4SDimitry Andric // / \ 1219480093f4SDimitry Andric // Succ1 Succ2 1220480093f4SDimitry Andric // 1221480093f4SDimitry Andric // In this example Dup has 2 successors and 3 predecessors, duplication of Dup 1222480093f4SDimitry Andric // can increase the fallthrough from Pred1 to Succ1 and from Pred2 to Succ2, 1223480093f4SDimitry Andric // but the duplication into Pred3 can't increase fallthrough. 1224480093f4SDimitry Andric // 1225480093f4SDimitry Andric // A small number of extra duplication may not hurt too much. We need a better 1226480093f4SDimitry Andric // heuristic to handle it. 1227480093f4SDimitry Andric if ((NumDup > Succ->succ_size()) || !Duplicate) 1228480093f4SDimitry Andric return false; 1229480093f4SDimitry Andric 12300b57cec5SDimitry Andric return true; 12310b57cec5SDimitry Andric } 12320b57cec5SDimitry Andric 12330b57cec5SDimitry Andric /// Find chains of triangles where we believe it would be profitable to 12340b57cec5SDimitry Andric /// tail-duplicate them all, but a local analysis would not find them. 12350b57cec5SDimitry Andric /// There are 3 ways this can be profitable: 12360b57cec5SDimitry Andric /// 1) The post-dominators marked 50% are actually taken 55% (This shrinks with 12370b57cec5SDimitry Andric /// longer chains) 12380b57cec5SDimitry Andric /// 2) The chains are statically correlated. Branch probabilities have a very 12390b57cec5SDimitry Andric /// U-shaped distribution. 12400b57cec5SDimitry Andric /// [http://nrs.harvard.edu/urn-3:HUL.InstRepos:24015805] 12410b57cec5SDimitry Andric /// If the branches in a chain are likely to be from the same side of the 12420b57cec5SDimitry Andric /// distribution as their predecessor, but are independent at runtime, this 12430b57cec5SDimitry Andric /// transformation is profitable. (Because the cost of being wrong is a small 12440b57cec5SDimitry Andric /// fixed cost, unlike the standard triangle layout where the cost of being 12450b57cec5SDimitry Andric /// wrong scales with the # of triangles.) 12460b57cec5SDimitry Andric /// 3) The chains are dynamically correlated. If the probability that a previous 12470b57cec5SDimitry Andric /// branch was taken positively influences whether the next branch will be 12480b57cec5SDimitry Andric /// taken 12490b57cec5SDimitry Andric /// We believe that 2 and 3 are common enough to justify the small margin in 1. 12500b57cec5SDimitry Andric void MachineBlockPlacement::precomputeTriangleChains() { 12510b57cec5SDimitry Andric struct TriangleChain { 12520b57cec5SDimitry Andric std::vector<MachineBasicBlock *> Edges; 12530b57cec5SDimitry Andric 12540b57cec5SDimitry Andric TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst) 12550b57cec5SDimitry Andric : Edges({src, dst}) {} 12560b57cec5SDimitry Andric 12570b57cec5SDimitry Andric void append(MachineBasicBlock *dst) { 12580b57cec5SDimitry Andric assert(getKey()->isSuccessor(dst) && 12590b57cec5SDimitry Andric "Attempting to append a block that is not a successor."); 12600b57cec5SDimitry Andric Edges.push_back(dst); 12610b57cec5SDimitry Andric } 12620b57cec5SDimitry Andric 12630b57cec5SDimitry Andric unsigned count() const { return Edges.size() - 1; } 12640b57cec5SDimitry Andric 12650b57cec5SDimitry Andric MachineBasicBlock *getKey() const { 12660b57cec5SDimitry Andric return Edges.back(); 12670b57cec5SDimitry Andric } 12680b57cec5SDimitry Andric }; 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric if (TriangleChainCount == 0) 12710b57cec5SDimitry Andric return; 12720b57cec5SDimitry Andric 12730b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-computing triangle chains.\n"); 12740b57cec5SDimitry Andric // Map from last block to the chain that contains it. This allows us to extend 12750b57cec5SDimitry Andric // chains as we find new triangles. 12760b57cec5SDimitry Andric DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap; 12770b57cec5SDimitry Andric for (MachineBasicBlock &BB : *F) { 12780b57cec5SDimitry Andric // If BB doesn't have 2 successors, it doesn't start a triangle. 12790b57cec5SDimitry Andric if (BB.succ_size() != 2) 12800b57cec5SDimitry Andric continue; 12810b57cec5SDimitry Andric MachineBasicBlock *PDom = nullptr; 12820b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BB.successors()) { 12830b57cec5SDimitry Andric if (!MPDT->dominates(Succ, &BB)) 12840b57cec5SDimitry Andric continue; 12850b57cec5SDimitry Andric PDom = Succ; 12860b57cec5SDimitry Andric break; 12870b57cec5SDimitry Andric } 12880b57cec5SDimitry Andric // If BB doesn't have a post-dominating successor, it doesn't form a 12890b57cec5SDimitry Andric // triangle. 12900b57cec5SDimitry Andric if (PDom == nullptr) 12910b57cec5SDimitry Andric continue; 12920b57cec5SDimitry Andric // If PDom has a hint that it is low probability, skip this triangle. 12930b57cec5SDimitry Andric if (MBPI->getEdgeProbability(&BB, PDom) < BranchProbability(50, 100)) 12940b57cec5SDimitry Andric continue; 12950b57cec5SDimitry Andric // If PDom isn't eligible for duplication, this isn't the kind of triangle 12960b57cec5SDimitry Andric // we're looking for. 12970b57cec5SDimitry Andric if (!shouldTailDuplicate(PDom)) 12980b57cec5SDimitry Andric continue; 12990b57cec5SDimitry Andric bool CanTailDuplicate = true; 13000b57cec5SDimitry Andric // If PDom can't tail-duplicate into it's non-BB predecessors, then this 13010b57cec5SDimitry Andric // isn't the kind of triangle we're looking for. 13020b57cec5SDimitry Andric for (MachineBasicBlock* Pred : PDom->predecessors()) { 13030b57cec5SDimitry Andric if (Pred == &BB) 13040b57cec5SDimitry Andric continue; 13050b57cec5SDimitry Andric if (!TailDup.canTailDuplicate(PDom, Pred)) { 13060b57cec5SDimitry Andric CanTailDuplicate = false; 13070b57cec5SDimitry Andric break; 13080b57cec5SDimitry Andric } 13090b57cec5SDimitry Andric } 13100b57cec5SDimitry Andric // If we can't tail-duplicate PDom to its predecessors, then skip this 13110b57cec5SDimitry Andric // triangle. 13120b57cec5SDimitry Andric if (!CanTailDuplicate) 13130b57cec5SDimitry Andric continue; 13140b57cec5SDimitry Andric 13150b57cec5SDimitry Andric // Now we have an interesting triangle. Insert it if it's not part of an 13160b57cec5SDimitry Andric // existing chain. 13170b57cec5SDimitry Andric // Note: This cannot be replaced with a call insert() or emplace() because 13180b57cec5SDimitry Andric // the find key is BB, but the insert/emplace key is PDom. 13190b57cec5SDimitry Andric auto Found = TriangleChainMap.find(&BB); 13200b57cec5SDimitry Andric // If it is, remove the chain from the map, grow it, and put it back in the 13210b57cec5SDimitry Andric // map with the end as the new key. 13220b57cec5SDimitry Andric if (Found != TriangleChainMap.end()) { 13230b57cec5SDimitry Andric TriangleChain Chain = std::move(Found->second); 13240b57cec5SDimitry Andric TriangleChainMap.erase(Found); 13250b57cec5SDimitry Andric Chain.append(PDom); 13260b57cec5SDimitry Andric TriangleChainMap.insert(std::make_pair(Chain.getKey(), std::move(Chain))); 13270b57cec5SDimitry Andric } else { 13280b57cec5SDimitry Andric auto InsertResult = TriangleChainMap.try_emplace(PDom, &BB, PDom); 13290b57cec5SDimitry Andric assert(InsertResult.second && "Block seen twice."); 13300b57cec5SDimitry Andric (void)InsertResult; 13310b57cec5SDimitry Andric } 13320b57cec5SDimitry Andric } 13330b57cec5SDimitry Andric 13340b57cec5SDimitry Andric // Iterating over a DenseMap is safe here, because the only thing in the body 13350b57cec5SDimitry Andric // of the loop is inserting into another DenseMap (ComputedEdges). 13360b57cec5SDimitry Andric // ComputedEdges is never iterated, so this doesn't lead to non-determinism. 13370b57cec5SDimitry Andric for (auto &ChainPair : TriangleChainMap) { 13380b57cec5SDimitry Andric TriangleChain &Chain = ChainPair.second; 13390b57cec5SDimitry Andric // Benchmarking has shown that due to branch correlation duplicating 2 or 13400b57cec5SDimitry Andric // more triangles is profitable, despite the calculations assuming 13410b57cec5SDimitry Andric // independence. 13420b57cec5SDimitry Andric if (Chain.count() < TriangleChainCount) 13430b57cec5SDimitry Andric continue; 13440b57cec5SDimitry Andric MachineBasicBlock *dst = Chain.Edges.back(); 13450b57cec5SDimitry Andric Chain.Edges.pop_back(); 13460b57cec5SDimitry Andric for (MachineBasicBlock *src : reverse(Chain.Edges)) { 13470b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Marking edge: " << getBlockName(src) << "->" 13480b57cec5SDimitry Andric << getBlockName(dst) 13490b57cec5SDimitry Andric << " as pre-computed based on triangles.\n"); 13500b57cec5SDimitry Andric 13510b57cec5SDimitry Andric auto InsertResult = ComputedEdges.insert({src, {dst, true}}); 13520b57cec5SDimitry Andric assert(InsertResult.second && "Block seen twice."); 13530b57cec5SDimitry Andric (void)InsertResult; 13540b57cec5SDimitry Andric 13550b57cec5SDimitry Andric dst = src; 13560b57cec5SDimitry Andric } 13570b57cec5SDimitry Andric } 13580b57cec5SDimitry Andric } 13590b57cec5SDimitry Andric 13600b57cec5SDimitry Andric // When profile is not present, return the StaticLikelyProb. 13610b57cec5SDimitry Andric // When profile is available, we need to handle the triangle-shape CFG. 13620b57cec5SDimitry Andric static BranchProbability getLayoutSuccessorProbThreshold( 13630b57cec5SDimitry Andric const MachineBasicBlock *BB) { 13640b57cec5SDimitry Andric if (!BB->getParent()->getFunction().hasProfileData()) 13650b57cec5SDimitry Andric return BranchProbability(StaticLikelyProb, 100); 13660b57cec5SDimitry Andric if (BB->succ_size() == 2) { 13670b57cec5SDimitry Andric const MachineBasicBlock *Succ1 = *BB->succ_begin(); 13680b57cec5SDimitry Andric const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); 13690b57cec5SDimitry Andric if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { 13700b57cec5SDimitry Andric /* See case 1 below for the cost analysis. For BB->Succ to 13710b57cec5SDimitry Andric * be taken with smaller cost, the following needs to hold: 13720b57cec5SDimitry Andric * Prob(BB->Succ) > 2 * Prob(BB->Pred) 13730b57cec5SDimitry Andric * So the threshold T in the calculation below 13740b57cec5SDimitry Andric * (1-T) * Prob(BB->Succ) > T * Prob(BB->Pred) 13750b57cec5SDimitry Andric * So T / (1 - T) = 2, Yielding T = 2/3 13760b57cec5SDimitry Andric * Also adding user specified branch bias, we have 13770b57cec5SDimitry Andric * T = (2/3)*(ProfileLikelyProb/50) 13780b57cec5SDimitry Andric * = (2*ProfileLikelyProb)/150) 13790b57cec5SDimitry Andric */ 13800b57cec5SDimitry Andric return BranchProbability(2 * ProfileLikelyProb, 150); 13810b57cec5SDimitry Andric } 13820b57cec5SDimitry Andric } 13830b57cec5SDimitry Andric return BranchProbability(ProfileLikelyProb, 100); 13840b57cec5SDimitry Andric } 13850b57cec5SDimitry Andric 13860b57cec5SDimitry Andric /// Checks to see if the layout candidate block \p Succ has a better layout 13870b57cec5SDimitry Andric /// predecessor than \c BB. If yes, returns true. 13880b57cec5SDimitry Andric /// \p SuccProb: The probability adjusted for only remaining blocks. 13890b57cec5SDimitry Andric /// Only used for logging 13900b57cec5SDimitry Andric /// \p RealSuccProb: The un-adjusted probability. 13910b57cec5SDimitry Andric /// \p Chain: The chain that BB belongs to and Succ is being considered for. 13920b57cec5SDimitry Andric /// \p BlockFilter: if non-null, the set of blocks that make up the loop being 13930b57cec5SDimitry Andric /// considered 13940b57cec5SDimitry Andric bool MachineBlockPlacement::hasBetterLayoutPredecessor( 13950b57cec5SDimitry Andric const MachineBasicBlock *BB, const MachineBasicBlock *Succ, 13960b57cec5SDimitry Andric const BlockChain &SuccChain, BranchProbability SuccProb, 13970b57cec5SDimitry Andric BranchProbability RealSuccProb, const BlockChain &Chain, 13980b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 13990b57cec5SDimitry Andric 14000b57cec5SDimitry Andric // There isn't a better layout when there are no unscheduled predecessors. 14010b57cec5SDimitry Andric if (SuccChain.UnscheduledPredecessors == 0) 14020b57cec5SDimitry Andric return false; 14030b57cec5SDimitry Andric 14040b57cec5SDimitry Andric // There are two basic scenarios here: 14050b57cec5SDimitry Andric // ------------------------------------- 14060b57cec5SDimitry Andric // Case 1: triangular shape CFG (if-then): 14070b57cec5SDimitry Andric // BB 14080b57cec5SDimitry Andric // | \ 14090b57cec5SDimitry Andric // | \ 14100b57cec5SDimitry Andric // | Pred 14110b57cec5SDimitry Andric // | / 14120b57cec5SDimitry Andric // Succ 14130b57cec5SDimitry Andric // In this case, we are evaluating whether to select edge -> Succ, e.g. 14140b57cec5SDimitry Andric // set Succ as the layout successor of BB. Picking Succ as BB's 14150b57cec5SDimitry Andric // successor breaks the CFG constraints (FIXME: define these constraints). 14160b57cec5SDimitry Andric // With this layout, Pred BB 14170b57cec5SDimitry Andric // is forced to be outlined, so the overall cost will be cost of the 14180b57cec5SDimitry Andric // branch taken from BB to Pred, plus the cost of back taken branch 14190b57cec5SDimitry Andric // from Pred to Succ, as well as the additional cost associated 14200b57cec5SDimitry Andric // with the needed unconditional jump instruction from Pred To Succ. 14210b57cec5SDimitry Andric 14220b57cec5SDimitry Andric // The cost of the topological order layout is the taken branch cost 14230b57cec5SDimitry Andric // from BB to Succ, so to make BB->Succ a viable candidate, the following 14240b57cec5SDimitry Andric // must hold: 14250b57cec5SDimitry Andric // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost 14260b57cec5SDimitry Andric // < freq(BB->Succ) * taken_branch_cost. 14270b57cec5SDimitry Andric // Ignoring unconditional jump cost, we get 14280b57cec5SDimitry Andric // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., 14290b57cec5SDimitry Andric // prob(BB->Succ) > 2 * prob(BB->Pred) 14300b57cec5SDimitry Andric // 14310b57cec5SDimitry Andric // When real profile data is available, we can precisely compute the 14320b57cec5SDimitry Andric // probability threshold that is needed for edge BB->Succ to be considered. 14330b57cec5SDimitry Andric // Without profile data, the heuristic requires the branch bias to be 14340b57cec5SDimitry Andric // a lot larger to make sure the signal is very strong (e.g. 80% default). 14350b57cec5SDimitry Andric // ----------------------------------------------------------------- 14360b57cec5SDimitry Andric // Case 2: diamond like CFG (if-then-else): 14370b57cec5SDimitry Andric // S 14380b57cec5SDimitry Andric // / \ 14390b57cec5SDimitry Andric // | \ 14400b57cec5SDimitry Andric // BB Pred 14410b57cec5SDimitry Andric // \ / 14420b57cec5SDimitry Andric // Succ 14430b57cec5SDimitry Andric // .. 14440b57cec5SDimitry Andric // 14450b57cec5SDimitry Andric // The current block is BB and edge BB->Succ is now being evaluated. 14460b57cec5SDimitry Andric // Note that edge S->BB was previously already selected because 14470b57cec5SDimitry Andric // prob(S->BB) > prob(S->Pred). 14480b57cec5SDimitry Andric // At this point, 2 blocks can be placed after BB: Pred or Succ. If we 14490b57cec5SDimitry Andric // choose Pred, we will have a topological ordering as shown on the left 14500b57cec5SDimitry Andric // in the picture below. If we choose Succ, we have the solution as shown 14510b57cec5SDimitry Andric // on the right: 14520b57cec5SDimitry Andric // 14530b57cec5SDimitry Andric // topo-order: 14540b57cec5SDimitry Andric // 14550b57cec5SDimitry Andric // S----- ---S 14560b57cec5SDimitry Andric // | | | | 14570b57cec5SDimitry Andric // ---BB | | BB 14580b57cec5SDimitry Andric // | | | | 14590b57cec5SDimitry Andric // | Pred-- | Succ-- 14600b57cec5SDimitry Andric // | | | | 14610b57cec5SDimitry Andric // ---Succ ---Pred-- 14620b57cec5SDimitry Andric // 14630b57cec5SDimitry Andric // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) 14640b57cec5SDimitry Andric // = freq(S->Pred) + freq(S->BB) 14650b57cec5SDimitry Andric // 14660b57cec5SDimitry Andric // If we have profile data (i.e, branch probabilities can be trusted), the 14670b57cec5SDimitry Andric // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * 14680b57cec5SDimitry Andric // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). 14690b57cec5SDimitry Andric // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which 14700b57cec5SDimitry Andric // means the cost of topological order is greater. 14710b57cec5SDimitry Andric // When profile data is not available, however, we need to be more 14720b57cec5SDimitry Andric // conservative. If the branch prediction is wrong, breaking the topo-order 14730b57cec5SDimitry Andric // will actually yield a layout with large cost. For this reason, we need 14740b57cec5SDimitry Andric // strong biased branch at block S with Prob(S->BB) in order to select 14750b57cec5SDimitry Andric // BB->Succ. This is equivalent to looking the CFG backward with backward 14760b57cec5SDimitry Andric // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without 14770b57cec5SDimitry Andric // profile data). 14780b57cec5SDimitry Andric // -------------------------------------------------------------------------- 14790b57cec5SDimitry Andric // Case 3: forked diamond 14800b57cec5SDimitry Andric // S 14810b57cec5SDimitry Andric // / \ 14820b57cec5SDimitry Andric // / \ 14830b57cec5SDimitry Andric // BB Pred 14840b57cec5SDimitry Andric // | \ / | 14850b57cec5SDimitry Andric // | \ / | 14860b57cec5SDimitry Andric // | X | 14870b57cec5SDimitry Andric // | / \ | 14880b57cec5SDimitry Andric // | / \ | 14890b57cec5SDimitry Andric // S1 S2 14900b57cec5SDimitry Andric // 14910b57cec5SDimitry Andric // The current block is BB and edge BB->S1 is now being evaluated. 14920b57cec5SDimitry Andric // As above S->BB was already selected because 14930b57cec5SDimitry Andric // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). 14940b57cec5SDimitry Andric // 14950b57cec5SDimitry Andric // topo-order: 14960b57cec5SDimitry Andric // 14970b57cec5SDimitry Andric // S-------| ---S 14980b57cec5SDimitry Andric // | | | | 14990b57cec5SDimitry Andric // ---BB | | BB 15000b57cec5SDimitry Andric // | | | | 15010b57cec5SDimitry Andric // | Pred----| | S1---- 15020b57cec5SDimitry Andric // | | | | 15030b57cec5SDimitry Andric // --(S1 or S2) ---Pred-- 15040b57cec5SDimitry Andric // | 15050b57cec5SDimitry Andric // S2 15060b57cec5SDimitry Andric // 15070b57cec5SDimitry Andric // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) 15080b57cec5SDimitry Andric // + min(freq(Pred->S1), freq(Pred->S2)) 15090b57cec5SDimitry Andric // Non-topo-order cost: 15100b57cec5SDimitry Andric // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). 15110b57cec5SDimitry Andric // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) 15120b57cec5SDimitry Andric // is 0. Then the non topo layout is better when 15130b57cec5SDimitry Andric // freq(S->Pred) < freq(BB->S1). 15140b57cec5SDimitry Andric // This is exactly what is checked below. 15150b57cec5SDimitry Andric // Note there are other shapes that apply (Pred may not be a single block, 15160b57cec5SDimitry Andric // but they all fit this general pattern.) 15170b57cec5SDimitry Andric BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); 15180b57cec5SDimitry Andric 15190b57cec5SDimitry Andric // Make sure that a hot successor doesn't have a globally more 15200b57cec5SDimitry Andric // important predecessor. 15210b57cec5SDimitry Andric BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; 15220b57cec5SDimitry Andric bool BadCFGConflict = false; 15230b57cec5SDimitry Andric 15240b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Succ->predecessors()) { 1525480093f4SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 1526480093f4SDimitry Andric if (Pred == Succ || PredChain == &SuccChain || 15270b57cec5SDimitry Andric (BlockFilter && !BlockFilter->count(Pred)) || 1528480093f4SDimitry Andric PredChain == &Chain || Pred != *std::prev(PredChain->end()) || 15290b57cec5SDimitry Andric // This check is redundant except for look ahead. This function is 15300b57cec5SDimitry Andric // called for lookahead by isProfitableToTailDup when BB hasn't been 15310b57cec5SDimitry Andric // placed yet. 15320b57cec5SDimitry Andric (Pred == BB)) 15330b57cec5SDimitry Andric continue; 15340b57cec5SDimitry Andric // Do backward checking. 15350b57cec5SDimitry Andric // For all cases above, we need a backward checking to filter out edges that 15360b57cec5SDimitry Andric // are not 'strongly' biased. 15370b57cec5SDimitry Andric // BB Pred 15380b57cec5SDimitry Andric // \ / 15390b57cec5SDimitry Andric // Succ 15400b57cec5SDimitry Andric // We select edge BB->Succ if 15410b57cec5SDimitry Andric // freq(BB->Succ) > freq(Succ) * HotProb 15420b57cec5SDimitry Andric // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * 15430b57cec5SDimitry Andric // HotProb 15440b57cec5SDimitry Andric // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb 15450b57cec5SDimitry Andric // Case 1 is covered too, because the first equation reduces to: 15460b57cec5SDimitry Andric // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) 15470b57cec5SDimitry Andric BlockFrequency PredEdgeFreq = 15480b57cec5SDimitry Andric MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); 15490b57cec5SDimitry Andric if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { 15500b57cec5SDimitry Andric BadCFGConflict = true; 15510b57cec5SDimitry Andric break; 15520b57cec5SDimitry Andric } 15530b57cec5SDimitry Andric } 15540b57cec5SDimitry Andric 15550b57cec5SDimitry Andric if (BadCFGConflict) { 15560b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " 15570b57cec5SDimitry Andric << SuccProb << " (prob) (non-cold CFG conflict)\n"); 15580b57cec5SDimitry Andric return true; 15590b57cec5SDimitry Andric } 15600b57cec5SDimitry Andric 15610b57cec5SDimitry Andric return false; 15620b57cec5SDimitry Andric } 15630b57cec5SDimitry Andric 15640b57cec5SDimitry Andric /// Select the best successor for a block. 15650b57cec5SDimitry Andric /// 15660b57cec5SDimitry Andric /// This looks across all successors of a particular block and attempts to 15670b57cec5SDimitry Andric /// select the "best" one to be the layout successor. It only considers direct 15680b57cec5SDimitry Andric /// successors which also pass the block filter. It will attempt to avoid 15690b57cec5SDimitry Andric /// breaking CFG structure, but cave and break such structures in the case of 15700b57cec5SDimitry Andric /// very hot successor edges. 15710b57cec5SDimitry Andric /// 15720b57cec5SDimitry Andric /// \returns The best successor block found, or null if none are viable, along 15730b57cec5SDimitry Andric /// with a boolean indicating if tail duplication is necessary. 15740b57cec5SDimitry Andric MachineBlockPlacement::BlockAndTailDupResult 15750b57cec5SDimitry Andric MachineBlockPlacement::selectBestSuccessor( 15760b57cec5SDimitry Andric const MachineBasicBlock *BB, const BlockChain &Chain, 15770b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 15780b57cec5SDimitry Andric const BranchProbability HotProb(StaticLikelyProb, 100); 15790b57cec5SDimitry Andric 15800b57cec5SDimitry Andric BlockAndTailDupResult BestSucc = { nullptr, false }; 15810b57cec5SDimitry Andric auto BestProb = BranchProbability::getZero(); 15820b57cec5SDimitry Andric 15830b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 4> Successors; 15840b57cec5SDimitry Andric auto AdjustedSumProb = 15850b57cec5SDimitry Andric collectViableSuccessors(BB, Chain, BlockFilter, Successors); 15860b57cec5SDimitry Andric 15870b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) 15880b57cec5SDimitry Andric << "\n"); 15890b57cec5SDimitry Andric 15900b57cec5SDimitry Andric // if we already precomputed the best successor for BB, return that if still 15910b57cec5SDimitry Andric // applicable. 15920b57cec5SDimitry Andric auto FoundEdge = ComputedEdges.find(BB); 15930b57cec5SDimitry Andric if (FoundEdge != ComputedEdges.end()) { 15940b57cec5SDimitry Andric MachineBasicBlock *Succ = FoundEdge->second.BB; 15950b57cec5SDimitry Andric ComputedEdges.erase(FoundEdge); 15960b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 15970b57cec5SDimitry Andric if (BB->isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) && 15980b57cec5SDimitry Andric SuccChain != &Chain && Succ == *SuccChain->begin()) 15990b57cec5SDimitry Andric return FoundEdge->second; 16000b57cec5SDimitry Andric } 16010b57cec5SDimitry Andric 16020b57cec5SDimitry Andric // if BB is part of a trellis, Use the trellis to determine the optimal 16030b57cec5SDimitry Andric // fallthrough edges 16040b57cec5SDimitry Andric if (isTrellis(BB, Successors, Chain, BlockFilter)) 16050b57cec5SDimitry Andric return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain, 16060b57cec5SDimitry Andric BlockFilter); 16070b57cec5SDimitry Andric 16080b57cec5SDimitry Andric // For blocks with CFG violations, we may be able to lay them out anyway with 16090b57cec5SDimitry Andric // tail-duplication. We keep this vector so we can perform the probability 16100b57cec5SDimitry Andric // calculations the minimum number of times. 16115ffd83dbSDimitry Andric SmallVector<std::pair<BranchProbability, MachineBasicBlock *>, 4> 16120b57cec5SDimitry Andric DupCandidates; 16130b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Successors) { 16140b57cec5SDimitry Andric auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); 16150b57cec5SDimitry Andric BranchProbability SuccProb = 16160b57cec5SDimitry Andric getAdjustedProbability(RealSuccProb, AdjustedSumProb); 16170b57cec5SDimitry Andric 16180b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 16190b57cec5SDimitry Andric // Skip the edge \c BB->Succ if block \c Succ has a better layout 16200b57cec5SDimitry Andric // predecessor that yields lower global cost. 16210b57cec5SDimitry Andric if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, 16220b57cec5SDimitry Andric Chain, BlockFilter)) { 16230b57cec5SDimitry Andric // If tail duplication would make Succ profitable, place it. 16240b57cec5SDimitry Andric if (allowTailDupPlacement() && shouldTailDuplicate(Succ)) 16255ffd83dbSDimitry Andric DupCandidates.emplace_back(SuccProb, Succ); 16260b57cec5SDimitry Andric continue; 16270b57cec5SDimitry Andric } 16280b57cec5SDimitry Andric 16290b57cec5SDimitry Andric LLVM_DEBUG( 16300b57cec5SDimitry Andric dbgs() << " Candidate: " << getBlockName(Succ) 16310b57cec5SDimitry Andric << ", probability: " << SuccProb 16320b57cec5SDimitry Andric << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") 16330b57cec5SDimitry Andric << "\n"); 16340b57cec5SDimitry Andric 16350b57cec5SDimitry Andric if (BestSucc.BB && BestProb >= SuccProb) { 16360b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Not the best candidate, continuing\n"); 16370b57cec5SDimitry Andric continue; 16380b57cec5SDimitry Andric } 16390b57cec5SDimitry Andric 16400b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Setting it as best candidate\n"); 16410b57cec5SDimitry Andric BestSucc.BB = Succ; 16420b57cec5SDimitry Andric BestProb = SuccProb; 16430b57cec5SDimitry Andric } 16440b57cec5SDimitry Andric // Handle the tail duplication candidates in order of decreasing probability. 16450b57cec5SDimitry Andric // Stop at the first one that is profitable. Also stop if they are less 16460b57cec5SDimitry Andric // profitable than BestSucc. Position is important because we preserve it and 16470b57cec5SDimitry Andric // prefer first best match. Here we aren't comparing in order, so we capture 16480b57cec5SDimitry Andric // the position instead. 16490b57cec5SDimitry Andric llvm::stable_sort(DupCandidates, 16500b57cec5SDimitry Andric [](std::tuple<BranchProbability, MachineBasicBlock *> L, 16510b57cec5SDimitry Andric std::tuple<BranchProbability, MachineBasicBlock *> R) { 16520b57cec5SDimitry Andric return std::get<0>(L) > std::get<0>(R); 16530b57cec5SDimitry Andric }); 16540b57cec5SDimitry Andric for (auto &Tup : DupCandidates) { 16550b57cec5SDimitry Andric BranchProbability DupProb; 16560b57cec5SDimitry Andric MachineBasicBlock *Succ; 16570b57cec5SDimitry Andric std::tie(DupProb, Succ) = Tup; 16580b57cec5SDimitry Andric if (DupProb < BestProb) 16590b57cec5SDimitry Andric break; 16600b57cec5SDimitry Andric if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) 16610b57cec5SDimitry Andric && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) { 16620b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Candidate: " << getBlockName(Succ) 16630b57cec5SDimitry Andric << ", probability: " << DupProb 16640b57cec5SDimitry Andric << " (Tail Duplicate)\n"); 16650b57cec5SDimitry Andric BestSucc.BB = Succ; 16660b57cec5SDimitry Andric BestSucc.ShouldTailDup = true; 16670b57cec5SDimitry Andric break; 16680b57cec5SDimitry Andric } 16690b57cec5SDimitry Andric } 16700b57cec5SDimitry Andric 16710b57cec5SDimitry Andric if (BestSucc.BB) 16720b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc.BB) << "\n"); 16730b57cec5SDimitry Andric 16740b57cec5SDimitry Andric return BestSucc; 16750b57cec5SDimitry Andric } 16760b57cec5SDimitry Andric 16770b57cec5SDimitry Andric /// Select the best block from a worklist. 16780b57cec5SDimitry Andric /// 16790b57cec5SDimitry Andric /// This looks through the provided worklist as a list of candidate basic 16800b57cec5SDimitry Andric /// blocks and select the most profitable one to place. The definition of 16810b57cec5SDimitry Andric /// profitable only really makes sense in the context of a loop. This returns 16820b57cec5SDimitry Andric /// the most frequently visited block in the worklist, which in the case of 16830b57cec5SDimitry Andric /// a loop, is the one most desirable to be physically close to the rest of the 16840b57cec5SDimitry Andric /// loop body in order to improve i-cache behavior. 16850b57cec5SDimitry Andric /// 16860b57cec5SDimitry Andric /// \returns The best block found, or null if none are viable. 16870b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( 16880b57cec5SDimitry Andric const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { 16890b57cec5SDimitry Andric // Once we need to walk the worklist looking for a candidate, cleanup the 16900b57cec5SDimitry Andric // worklist of already placed entries. 16910b57cec5SDimitry Andric // FIXME: If this shows up on profiles, it could be folded (at the cost of 16920b57cec5SDimitry Andric // some code complexity) into the loop below. 1693e8d8bef9SDimitry Andric llvm::erase_if(WorkList, [&](MachineBasicBlock *BB) { 16940b57cec5SDimitry Andric return BlockToChain.lookup(BB) == &Chain; 1695e8d8bef9SDimitry Andric }); 16960b57cec5SDimitry Andric 16970b57cec5SDimitry Andric if (WorkList.empty()) 16980b57cec5SDimitry Andric return nullptr; 16990b57cec5SDimitry Andric 17000b57cec5SDimitry Andric bool IsEHPad = WorkList[0]->isEHPad(); 17010b57cec5SDimitry Andric 17020b57cec5SDimitry Andric MachineBasicBlock *BestBlock = nullptr; 17030b57cec5SDimitry Andric BlockFrequency BestFreq; 17040b57cec5SDimitry Andric for (MachineBasicBlock *MBB : WorkList) { 17050b57cec5SDimitry Andric assert(MBB->isEHPad() == IsEHPad && 17060b57cec5SDimitry Andric "EHPad mismatch between block and work list."); 17070b57cec5SDimitry Andric 17080b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[MBB]; 17090b57cec5SDimitry Andric if (&SuccChain == &Chain) 17100b57cec5SDimitry Andric continue; 17110b57cec5SDimitry Andric 17120b57cec5SDimitry Andric assert(SuccChain.UnscheduledPredecessors == 0 && 17130b57cec5SDimitry Andric "Found CFG-violating block"); 17140b57cec5SDimitry Andric 17150b57cec5SDimitry Andric BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); 17160b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; 17170b57cec5SDimitry Andric MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); 17180b57cec5SDimitry Andric 17190b57cec5SDimitry Andric // For ehpad, we layout the least probable first as to avoid jumping back 17200b57cec5SDimitry Andric // from least probable landingpads to more probable ones. 17210b57cec5SDimitry Andric // 17220b57cec5SDimitry Andric // FIXME: Using probability is probably (!) not the best way to achieve 17230b57cec5SDimitry Andric // this. We should probably have a more principled approach to layout 17240b57cec5SDimitry Andric // cleanup code. 17250b57cec5SDimitry Andric // 17260b57cec5SDimitry Andric // The goal is to get: 17270b57cec5SDimitry Andric // 17280b57cec5SDimitry Andric // +--------------------------+ 17290b57cec5SDimitry Andric // | V 17300b57cec5SDimitry Andric // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume 17310b57cec5SDimitry Andric // 17320b57cec5SDimitry Andric // Rather than: 17330b57cec5SDimitry Andric // 17340b57cec5SDimitry Andric // +-------------------------------------+ 17350b57cec5SDimitry Andric // V | 17360b57cec5SDimitry Andric // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup 17370b57cec5SDimitry Andric if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) 17380b57cec5SDimitry Andric continue; 17390b57cec5SDimitry Andric 17400b57cec5SDimitry Andric BestBlock = MBB; 17410b57cec5SDimitry Andric BestFreq = CandidateFreq; 17420b57cec5SDimitry Andric } 17430b57cec5SDimitry Andric 17440b57cec5SDimitry Andric return BestBlock; 17450b57cec5SDimitry Andric } 17460b57cec5SDimitry Andric 17470b57cec5SDimitry Andric /// Retrieve the first unplaced basic block. 17480b57cec5SDimitry Andric /// 17490b57cec5SDimitry Andric /// This routine is called when we are unable to use the CFG to walk through 17500b57cec5SDimitry Andric /// all of the basic blocks and form a chain due to unnatural loops in the CFG. 17510b57cec5SDimitry Andric /// We walk through the function's blocks in order, starting from the 17520b57cec5SDimitry Andric /// LastUnplacedBlockIt. We update this iterator on each call to avoid 17530b57cec5SDimitry Andric /// re-scanning the entire sequence on repeated calls to this routine. 17540b57cec5SDimitry Andric MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( 17550b57cec5SDimitry Andric const BlockChain &PlacedChain, 17560b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 17570b57cec5SDimitry Andric const BlockFilterSet *BlockFilter) { 17580b57cec5SDimitry Andric for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; 17590b57cec5SDimitry Andric ++I) { 17600b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(&*I)) 17610b57cec5SDimitry Andric continue; 17620b57cec5SDimitry Andric if (BlockToChain[&*I] != &PlacedChain) { 17630b57cec5SDimitry Andric PrevUnplacedBlockIt = I; 17640b57cec5SDimitry Andric // Now select the head of the chain to which the unplaced block belongs 17650b57cec5SDimitry Andric // as the block to place. This will force the entire chain to be placed, 17660b57cec5SDimitry Andric // and satisfies the requirements of merging chains. 17670b57cec5SDimitry Andric return *BlockToChain[&*I]->begin(); 17680b57cec5SDimitry Andric } 17690b57cec5SDimitry Andric } 17700b57cec5SDimitry Andric return nullptr; 17710b57cec5SDimitry Andric } 17720b57cec5SDimitry Andric 17730b57cec5SDimitry Andric void MachineBlockPlacement::fillWorkLists( 17740b57cec5SDimitry Andric const MachineBasicBlock *MBB, 17750b57cec5SDimitry Andric SmallPtrSetImpl<BlockChain *> &UpdatedPreds, 17760b57cec5SDimitry Andric const BlockFilterSet *BlockFilter = nullptr) { 17770b57cec5SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 17780b57cec5SDimitry Andric if (!UpdatedPreds.insert(&Chain).second) 17790b57cec5SDimitry Andric return; 17800b57cec5SDimitry Andric 17810b57cec5SDimitry Andric assert( 17820b57cec5SDimitry Andric Chain.UnscheduledPredecessors == 0 && 17830b57cec5SDimitry Andric "Attempting to place block with unscheduled predecessors in worklist."); 17840b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : Chain) { 17850b57cec5SDimitry Andric assert(BlockToChain[ChainBB] == &Chain && 17860b57cec5SDimitry Andric "Block in chain doesn't match BlockToChain map."); 17870b57cec5SDimitry Andric for (MachineBasicBlock *Pred : ChainBB->predecessors()) { 17880b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(Pred)) 17890b57cec5SDimitry Andric continue; 17900b57cec5SDimitry Andric if (BlockToChain[Pred] == &Chain) 17910b57cec5SDimitry Andric continue; 17920b57cec5SDimitry Andric ++Chain.UnscheduledPredecessors; 17930b57cec5SDimitry Andric } 17940b57cec5SDimitry Andric } 17950b57cec5SDimitry Andric 17960b57cec5SDimitry Andric if (Chain.UnscheduledPredecessors != 0) 17970b57cec5SDimitry Andric return; 17980b57cec5SDimitry Andric 17990b57cec5SDimitry Andric MachineBasicBlock *BB = *Chain.begin(); 18000b57cec5SDimitry Andric if (BB->isEHPad()) 18010b57cec5SDimitry Andric EHPadWorkList.push_back(BB); 18020b57cec5SDimitry Andric else 18030b57cec5SDimitry Andric BlockWorkList.push_back(BB); 18040b57cec5SDimitry Andric } 18050b57cec5SDimitry Andric 18060b57cec5SDimitry Andric void MachineBlockPlacement::buildChain( 18070b57cec5SDimitry Andric const MachineBasicBlock *HeadBB, BlockChain &Chain, 18080b57cec5SDimitry Andric BlockFilterSet *BlockFilter) { 18090b57cec5SDimitry Andric assert(HeadBB && "BB must not be null.\n"); 18100b57cec5SDimitry Andric assert(BlockToChain[HeadBB] == &Chain && "BlockToChainMap mis-match.\n"); 18110b57cec5SDimitry Andric MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); 18120b57cec5SDimitry Andric 18130b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB = HeadBB; 18140b57cec5SDimitry Andric markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); 18150b57cec5SDimitry Andric MachineBasicBlock *BB = *std::prev(Chain.end()); 18160b57cec5SDimitry Andric while (true) { 18170b57cec5SDimitry Andric assert(BB && "null block found at end of chain in loop."); 18180b57cec5SDimitry Andric assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); 18190b57cec5SDimitry Andric assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); 18200b57cec5SDimitry Andric 18210b57cec5SDimitry Andric 18220b57cec5SDimitry Andric // Look for the best viable successor if there is one to place immediately 18230b57cec5SDimitry Andric // after this block. 18240b57cec5SDimitry Andric auto Result = selectBestSuccessor(BB, Chain, BlockFilter); 18250b57cec5SDimitry Andric MachineBasicBlock* BestSucc = Result.BB; 18260b57cec5SDimitry Andric bool ShouldTailDup = Result.ShouldTailDup; 18270b57cec5SDimitry Andric if (allowTailDupPlacement()) 1828480093f4SDimitry Andric ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc, 1829480093f4SDimitry Andric Chain, 1830480093f4SDimitry Andric BlockFilter)); 18310b57cec5SDimitry Andric 18320b57cec5SDimitry Andric // If an immediate successor isn't available, look for the best viable 18330b57cec5SDimitry Andric // block among those we've identified as not violating the loop's CFG at 18340b57cec5SDimitry Andric // this point. This won't be a fallthrough, but it will increase locality. 18350b57cec5SDimitry Andric if (!BestSucc) 18360b57cec5SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); 18370b57cec5SDimitry Andric if (!BestSucc) 18380b57cec5SDimitry Andric BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); 18390b57cec5SDimitry Andric 18400b57cec5SDimitry Andric if (!BestSucc) { 18410b57cec5SDimitry Andric BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); 18420b57cec5SDimitry Andric if (!BestSucc) 18430b57cec5SDimitry Andric break; 18440b57cec5SDimitry Andric 18450b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " 18460b57cec5SDimitry Andric "layout successor until the CFG reduces\n"); 18470b57cec5SDimitry Andric } 18480b57cec5SDimitry Andric 18490b57cec5SDimitry Andric // Placement may have changed tail duplication opportunities. 18500b57cec5SDimitry Andric // Check for that now. 18510b57cec5SDimitry Andric if (allowTailDupPlacement() && BestSucc && ShouldTailDup) { 18525ffd83dbSDimitry Andric repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, 18535ffd83dbSDimitry Andric BlockFilter, PrevUnplacedBlockIt); 18545ffd83dbSDimitry Andric // If the chosen successor was duplicated into BB, don't bother laying 18555ffd83dbSDimitry Andric // it out, just go round the loop again with BB as the chain end. 18565ffd83dbSDimitry Andric if (!BB->isSuccessor(BestSucc)) 18570b57cec5SDimitry Andric continue; 18580b57cec5SDimitry Andric } 18590b57cec5SDimitry Andric 18600b57cec5SDimitry Andric // Place this block, updating the datastructures to reflect its placement. 18610b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[BestSucc]; 18620b57cec5SDimitry Andric // Zero out UnscheduledPredecessors for the successor we're about to merge in case 18630b57cec5SDimitry Andric // we selected a successor that didn't fit naturally into the CFG. 18640b57cec5SDimitry Andric SuccChain.UnscheduledPredecessors = 0; 18650b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " 18660b57cec5SDimitry Andric << getBlockName(BestSucc) << "\n"); 18670b57cec5SDimitry Andric markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); 18680b57cec5SDimitry Andric Chain.merge(BestSucc, &SuccChain); 18690b57cec5SDimitry Andric BB = *std::prev(Chain.end()); 18700b57cec5SDimitry Andric } 18710b57cec5SDimitry Andric 18720b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finished forming chain for header block " 18730b57cec5SDimitry Andric << getBlockName(*Chain.begin()) << "\n"); 18740b57cec5SDimitry Andric } 18750b57cec5SDimitry Andric 18760b57cec5SDimitry Andric // If bottom of block BB has only one successor OldTop, in most cases it is 18770b57cec5SDimitry Andric // profitable to move it before OldTop, except the following case: 18780b57cec5SDimitry Andric // 18790b57cec5SDimitry Andric // -->OldTop<- 18800b57cec5SDimitry Andric // | . | 18810b57cec5SDimitry Andric // | . | 18820b57cec5SDimitry Andric // | . | 18830b57cec5SDimitry Andric // ---Pred | 18840b57cec5SDimitry Andric // | | 18850b57cec5SDimitry Andric // BB----- 18860b57cec5SDimitry Andric // 18870b57cec5SDimitry Andric // If BB is moved before OldTop, Pred needs a taken branch to BB, and it can't 18880b57cec5SDimitry Andric // layout the other successor below it, so it can't reduce taken branch. 18890b57cec5SDimitry Andric // In this case we keep its original layout. 18900b57cec5SDimitry Andric bool 18910b57cec5SDimitry Andric MachineBlockPlacement::canMoveBottomBlockToTop( 18920b57cec5SDimitry Andric const MachineBasicBlock *BottomBlock, 18930b57cec5SDimitry Andric const MachineBasicBlock *OldTop) { 18940b57cec5SDimitry Andric if (BottomBlock->pred_size() != 1) 18950b57cec5SDimitry Andric return true; 18960b57cec5SDimitry Andric MachineBasicBlock *Pred = *BottomBlock->pred_begin(); 18970b57cec5SDimitry Andric if (Pred->succ_size() != 2) 18980b57cec5SDimitry Andric return true; 18990b57cec5SDimitry Andric 19000b57cec5SDimitry Andric MachineBasicBlock *OtherBB = *Pred->succ_begin(); 19010b57cec5SDimitry Andric if (OtherBB == BottomBlock) 19020b57cec5SDimitry Andric OtherBB = *Pred->succ_rbegin(); 19030b57cec5SDimitry Andric if (OtherBB == OldTop) 19040b57cec5SDimitry Andric return false; 19050b57cec5SDimitry Andric 19060b57cec5SDimitry Andric return true; 19070b57cec5SDimitry Andric } 19080b57cec5SDimitry Andric 19090b57cec5SDimitry Andric // Find out the possible fall through frequence to the top of a loop. 19100b57cec5SDimitry Andric BlockFrequency 19110b57cec5SDimitry Andric MachineBlockPlacement::TopFallThroughFreq( 19120b57cec5SDimitry Andric const MachineBasicBlock *Top, 19130b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 19140b57cec5SDimitry Andric BlockFrequency MaxFreq = 0; 19150b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) { 19160b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 19170b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 19180b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 19190b57cec5SDimitry Andric // Found a Pred block can be placed before Top. 19200b57cec5SDimitry Andric // Check if Top is the best successor of Pred. 19210b57cec5SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top); 19220b57cec5SDimitry Andric bool TopOK = true; 19230b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) { 19240b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 19250b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 19260b57cec5SDimitry Andric // Check if Succ can be placed after Pred. 19270b57cec5SDimitry Andric // Succ should not be in any chain, or it is the head of some chain. 19280b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) && 19290b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) { 19300b57cec5SDimitry Andric TopOK = false; 19310b57cec5SDimitry Andric break; 19320b57cec5SDimitry Andric } 19330b57cec5SDimitry Andric } 19340b57cec5SDimitry Andric if (TopOK) { 19350b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 19360b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, Top); 19370b57cec5SDimitry Andric if (EdgeFreq > MaxFreq) 19380b57cec5SDimitry Andric MaxFreq = EdgeFreq; 19390b57cec5SDimitry Andric } 19400b57cec5SDimitry Andric } 19410b57cec5SDimitry Andric } 19420b57cec5SDimitry Andric return MaxFreq; 19430b57cec5SDimitry Andric } 19440b57cec5SDimitry Andric 19450b57cec5SDimitry Andric // Compute the fall through gains when move NewTop before OldTop. 19460b57cec5SDimitry Andric // 19470b57cec5SDimitry Andric // In following diagram, edges marked as "-" are reduced fallthrough, edges 19480b57cec5SDimitry Andric // marked as "+" are increased fallthrough, this function computes 19490b57cec5SDimitry Andric // 19500b57cec5SDimitry Andric // SUM(increased fallthrough) - SUM(decreased fallthrough) 19510b57cec5SDimitry Andric // 19520b57cec5SDimitry Andric // | 19530b57cec5SDimitry Andric // | - 19540b57cec5SDimitry Andric // V 19550b57cec5SDimitry Andric // --->OldTop 19560b57cec5SDimitry Andric // | . 19570b57cec5SDimitry Andric // | . 19580b57cec5SDimitry Andric // +| . + 19590b57cec5SDimitry Andric // | Pred ---> 19600b57cec5SDimitry Andric // | |- 19610b57cec5SDimitry Andric // | V 19620b57cec5SDimitry Andric // --- NewTop <--- 19630b57cec5SDimitry Andric // |- 19640b57cec5SDimitry Andric // V 19650b57cec5SDimitry Andric // 19660b57cec5SDimitry Andric BlockFrequency 19670b57cec5SDimitry Andric MachineBlockPlacement::FallThroughGains( 19680b57cec5SDimitry Andric const MachineBasicBlock *NewTop, 19690b57cec5SDimitry Andric const MachineBasicBlock *OldTop, 19700b57cec5SDimitry Andric const MachineBasicBlock *ExitBB, 19710b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 19720b57cec5SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet); 19730b57cec5SDimitry Andric BlockFrequency FallThrough2Exit = 0; 19740b57cec5SDimitry Andric if (ExitBB) 19750b57cec5SDimitry Andric FallThrough2Exit = MBFI->getBlockFreq(NewTop) * 19760b57cec5SDimitry Andric MBPI->getEdgeProbability(NewTop, ExitBB); 19770b57cec5SDimitry Andric BlockFrequency BackEdgeFreq = MBFI->getBlockFreq(NewTop) * 19780b57cec5SDimitry Andric MBPI->getEdgeProbability(NewTop, OldTop); 19790b57cec5SDimitry Andric 19800b57cec5SDimitry Andric // Find the best Pred of NewTop. 19810b57cec5SDimitry Andric MachineBasicBlock *BestPred = nullptr; 19820b57cec5SDimitry Andric BlockFrequency FallThroughFromPred = 0; 19830b57cec5SDimitry Andric for (MachineBasicBlock *Pred : NewTop->predecessors()) { 19840b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred)) 19850b57cec5SDimitry Andric continue; 19860b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 19870b57cec5SDimitry Andric if (!PredChain || Pred == *std::prev(PredChain->end())) { 19880b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(Pred) * 19890b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, NewTop); 19900b57cec5SDimitry Andric if (EdgeFreq > FallThroughFromPred) { 19910b57cec5SDimitry Andric FallThroughFromPred = EdgeFreq; 19920b57cec5SDimitry Andric BestPred = Pred; 19930b57cec5SDimitry Andric } 19940b57cec5SDimitry Andric } 19950b57cec5SDimitry Andric } 19960b57cec5SDimitry Andric 19970b57cec5SDimitry Andric // If NewTop is not placed after Pred, another successor can be placed 19980b57cec5SDimitry Andric // after Pred. 19990b57cec5SDimitry Andric BlockFrequency NewFreq = 0; 20000b57cec5SDimitry Andric if (BestPred) { 20010b57cec5SDimitry Andric for (MachineBasicBlock *Succ : BestPred->successors()) { 20020b57cec5SDimitry Andric if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ)) 20030b57cec5SDimitry Andric continue; 20040b57cec5SDimitry Andric if (ComputedEdges.find(Succ) != ComputedEdges.end()) 20050b57cec5SDimitry Andric continue; 20060b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 20070b57cec5SDimitry Andric if ((SuccChain && (Succ != *SuccChain->begin())) || 20080b57cec5SDimitry Andric (SuccChain == BlockToChain[BestPred])) 20090b57cec5SDimitry Andric continue; 20100b57cec5SDimitry Andric BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) * 20110b57cec5SDimitry Andric MBPI->getEdgeProbability(BestPred, Succ); 20120b57cec5SDimitry Andric if (EdgeFreq > NewFreq) 20130b57cec5SDimitry Andric NewFreq = EdgeFreq; 20140b57cec5SDimitry Andric } 20150b57cec5SDimitry Andric BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) * 20160b57cec5SDimitry Andric MBPI->getEdgeProbability(BestPred, NewTop); 20170b57cec5SDimitry Andric if (NewFreq > OrigEdgeFreq) { 20180b57cec5SDimitry Andric // If NewTop is not the best successor of Pred, then Pred doesn't 20190b57cec5SDimitry Andric // fallthrough to NewTop. So there is no FallThroughFromPred and 20200b57cec5SDimitry Andric // NewFreq. 20210b57cec5SDimitry Andric NewFreq = 0; 20220b57cec5SDimitry Andric FallThroughFromPred = 0; 20230b57cec5SDimitry Andric } 20240b57cec5SDimitry Andric } 20250b57cec5SDimitry Andric 20260b57cec5SDimitry Andric BlockFrequency Result = 0; 20270b57cec5SDimitry Andric BlockFrequency Gains = BackEdgeFreq + NewFreq; 20280b57cec5SDimitry Andric BlockFrequency Lost = FallThrough2Top + FallThrough2Exit + 20290b57cec5SDimitry Andric FallThroughFromPred; 20300b57cec5SDimitry Andric if (Gains > Lost) 20310b57cec5SDimitry Andric Result = Gains - Lost; 20320b57cec5SDimitry Andric return Result; 20330b57cec5SDimitry Andric } 20340b57cec5SDimitry Andric 20350b57cec5SDimitry Andric /// Helper function of findBestLoopTop. Find the best loop top block 20360b57cec5SDimitry Andric /// from predecessors of old top. 20370b57cec5SDimitry Andric /// 20380b57cec5SDimitry Andric /// Look for a block which is strictly better than the old top for laying 20390b57cec5SDimitry Andric /// out before the old top of the loop. This looks for only two patterns: 20400b57cec5SDimitry Andric /// 20410b57cec5SDimitry Andric /// 1. a block has only one successor, the old loop top 20420b57cec5SDimitry Andric /// 20430b57cec5SDimitry Andric /// Because such a block will always result in an unconditional jump, 20440b57cec5SDimitry Andric /// rotating it in front of the old top is always profitable. 20450b57cec5SDimitry Andric /// 20460b57cec5SDimitry Andric /// 2. a block has two successors, one is old top, another is exit 20470b57cec5SDimitry Andric /// and it has more than one predecessors 20480b57cec5SDimitry Andric /// 20490b57cec5SDimitry Andric /// If it is below one of its predecessors P, only P can fall through to 20500b57cec5SDimitry Andric /// it, all other predecessors need a jump to it, and another conditional 20510b57cec5SDimitry Andric /// jump to loop header. If it is moved before loop header, all its 20520b57cec5SDimitry Andric /// predecessors jump to it, then fall through to loop header. So all its 20530b57cec5SDimitry Andric /// predecessors except P can reduce one taken branch. 20540b57cec5SDimitry Andric /// At the same time, move it before old top increases the taken branch 20550b57cec5SDimitry Andric /// to loop exit block, so the reduced taken branch will be compared with 20560b57cec5SDimitry Andric /// the increased taken branch to the loop exit block. 20570b57cec5SDimitry Andric MachineBasicBlock * 20580b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTopHelper( 20590b57cec5SDimitry Andric MachineBasicBlock *OldTop, 20600b57cec5SDimitry Andric const MachineLoop &L, 20610b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 20620b57cec5SDimitry Andric // Check that the header hasn't been fused with a preheader block due to 20630b57cec5SDimitry Andric // crazy branches. If it has, we need to start with the header at the top to 20640b57cec5SDimitry Andric // prevent pulling the preheader into the loop body. 20650b57cec5SDimitry Andric BlockChain &HeaderChain = *BlockToChain[OldTop]; 20660b57cec5SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 20670b57cec5SDimitry Andric return OldTop; 2068349cc55cSDimitry Andric if (OldTop != *HeaderChain.begin()) 2069349cc55cSDimitry Andric return OldTop; 20700b57cec5SDimitry Andric 20710b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(OldTop) 20720b57cec5SDimitry Andric << "\n"); 20730b57cec5SDimitry Andric 20740b57cec5SDimitry Andric BlockFrequency BestGains = 0; 20750b57cec5SDimitry Andric MachineBasicBlock *BestPred = nullptr; 20760b57cec5SDimitry Andric for (MachineBasicBlock *Pred : OldTop->predecessors()) { 20770b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred)) 20780b57cec5SDimitry Andric continue; 20790b57cec5SDimitry Andric if (Pred == L.getHeader()) 20800b57cec5SDimitry Andric continue; 20810b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " old top pred: " << getBlockName(Pred) << ", has " 20820b57cec5SDimitry Andric << Pred->succ_size() << " successors, "; 20830b57cec5SDimitry Andric MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); 20840b57cec5SDimitry Andric if (Pred->succ_size() > 2) 20850b57cec5SDimitry Andric continue; 20860b57cec5SDimitry Andric 20870b57cec5SDimitry Andric MachineBasicBlock *OtherBB = nullptr; 20880b57cec5SDimitry Andric if (Pred->succ_size() == 2) { 20890b57cec5SDimitry Andric OtherBB = *Pred->succ_begin(); 20900b57cec5SDimitry Andric if (OtherBB == OldTop) 20910b57cec5SDimitry Andric OtherBB = *Pred->succ_rbegin(); 20920b57cec5SDimitry Andric } 20930b57cec5SDimitry Andric 20940b57cec5SDimitry Andric if (!canMoveBottomBlockToTop(Pred, OldTop)) 20950b57cec5SDimitry Andric continue; 20960b57cec5SDimitry Andric 20970b57cec5SDimitry Andric BlockFrequency Gains = FallThroughGains(Pred, OldTop, OtherBB, 20980b57cec5SDimitry Andric LoopBlockSet); 20990b57cec5SDimitry Andric if ((Gains > 0) && (Gains > BestGains || 21000b57cec5SDimitry Andric ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) { 21010b57cec5SDimitry Andric BestPred = Pred; 21020b57cec5SDimitry Andric BestGains = Gains; 21030b57cec5SDimitry Andric } 21040b57cec5SDimitry Andric } 21050b57cec5SDimitry Andric 21060b57cec5SDimitry Andric // If no direct predecessor is fine, just use the loop header. 21070b57cec5SDimitry Andric if (!BestPred) { 21080b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " final top unchanged\n"); 21090b57cec5SDimitry Andric return OldTop; 21100b57cec5SDimitry Andric } 21110b57cec5SDimitry Andric 21120b57cec5SDimitry Andric // Walk backwards through any straight line of predecessors. 21130b57cec5SDimitry Andric while (BestPred->pred_size() == 1 && 21140b57cec5SDimitry Andric (*BestPred->pred_begin())->succ_size() == 1 && 21150b57cec5SDimitry Andric *BestPred->pred_begin() != L.getHeader()) 21160b57cec5SDimitry Andric BestPred = *BestPred->pred_begin(); 21170b57cec5SDimitry Andric 21180b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); 21190b57cec5SDimitry Andric return BestPred; 21200b57cec5SDimitry Andric } 21210b57cec5SDimitry Andric 21220b57cec5SDimitry Andric /// Find the best loop top block for layout. 21230b57cec5SDimitry Andric /// 21240b57cec5SDimitry Andric /// This function iteratively calls findBestLoopTopHelper, until no new better 21250b57cec5SDimitry Andric /// BB can be found. 21260b57cec5SDimitry Andric MachineBasicBlock * 21270b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopTop(const MachineLoop &L, 21280b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 21290b57cec5SDimitry Andric // Placing the latch block before the header may introduce an extra branch 21300b57cec5SDimitry Andric // that skips this block the first time the loop is executed, which we want 21310b57cec5SDimitry Andric // to avoid when optimising for size. 21320b57cec5SDimitry Andric // FIXME: in theory there is a case that does not introduce a new branch, 21330b57cec5SDimitry Andric // i.e. when the layout predecessor does not fallthrough to the loop header. 21340b57cec5SDimitry Andric // In practice this never happens though: there always seems to be a preheader 21350b57cec5SDimitry Andric // that can fallthrough and that is also placed before the header. 2136480093f4SDimitry Andric bool OptForSize = F->getFunction().hasOptSize() || 21375ffd83dbSDimitry Andric llvm::shouldOptimizeForSize(L.getHeader(), PSI, MBFI.get()); 2138480093f4SDimitry Andric if (OptForSize) 21390b57cec5SDimitry Andric return L.getHeader(); 21400b57cec5SDimitry Andric 21410b57cec5SDimitry Andric MachineBasicBlock *OldTop = nullptr; 21420b57cec5SDimitry Andric MachineBasicBlock *NewTop = L.getHeader(); 21430b57cec5SDimitry Andric while (NewTop != OldTop) { 21440b57cec5SDimitry Andric OldTop = NewTop; 21450b57cec5SDimitry Andric NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet); 21460b57cec5SDimitry Andric if (NewTop != OldTop) 21470b57cec5SDimitry Andric ComputedEdges[NewTop] = { OldTop, false }; 21480b57cec5SDimitry Andric } 21490b57cec5SDimitry Andric return NewTop; 21500b57cec5SDimitry Andric } 21510b57cec5SDimitry Andric 21520b57cec5SDimitry Andric /// Find the best loop exiting block for layout. 21530b57cec5SDimitry Andric /// 21540b57cec5SDimitry Andric /// This routine implements the logic to analyze the loop looking for the best 21550b57cec5SDimitry Andric /// block to layout at the top of the loop. Typically this is done to maximize 21560b57cec5SDimitry Andric /// fallthrough opportunities. 21570b57cec5SDimitry Andric MachineBasicBlock * 21580b57cec5SDimitry Andric MachineBlockPlacement::findBestLoopExit(const MachineLoop &L, 21590b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet, 21600b57cec5SDimitry Andric BlockFrequency &ExitFreq) { 21610b57cec5SDimitry Andric // We don't want to layout the loop linearly in all cases. If the loop header 21620b57cec5SDimitry Andric // is just a normal basic block in the loop, we want to look for what block 21630b57cec5SDimitry Andric // within the loop is the best one to layout at the top. However, if the loop 21640b57cec5SDimitry Andric // header has be pre-merged into a chain due to predecessors not having 21650b57cec5SDimitry Andric // analyzable branches, *and* the predecessor it is merged with is *not* part 21660b57cec5SDimitry Andric // of the loop, rotating the header into the middle of the loop will create 21670b57cec5SDimitry Andric // a non-contiguous range of blocks which is Very Bad. So start with the 21680b57cec5SDimitry Andric // header and only rotate if safe. 21690b57cec5SDimitry Andric BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; 21700b57cec5SDimitry Andric if (!LoopBlockSet.count(*HeaderChain.begin())) 21710b57cec5SDimitry Andric return nullptr; 21720b57cec5SDimitry Andric 21730b57cec5SDimitry Andric BlockFrequency BestExitEdgeFreq; 21740b57cec5SDimitry Andric unsigned BestExitLoopDepth = 0; 21750b57cec5SDimitry Andric MachineBasicBlock *ExitingBB = nullptr; 21760b57cec5SDimitry Andric // If there are exits to outer loops, loop rotation can severely limit 21770b57cec5SDimitry Andric // fallthrough opportunities unless it selects such an exit. Keep a set of 21780b57cec5SDimitry Andric // blocks where rotating to exit with that block will reach an outer loop. 21790b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; 21800b57cec5SDimitry Andric 21810b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Finding best loop exit for: " 21820b57cec5SDimitry Andric << getBlockName(L.getHeader()) << "\n"); 21830b57cec5SDimitry Andric for (MachineBasicBlock *MBB : L.getBlocks()) { 21840b57cec5SDimitry Andric BlockChain &Chain = *BlockToChain[MBB]; 21850b57cec5SDimitry Andric // Ensure that this block is at the end of a chain; otherwise it could be 21860b57cec5SDimitry Andric // mid-way through an inner loop or a successor of an unanalyzable branch. 21870b57cec5SDimitry Andric if (MBB != *std::prev(Chain.end())) 21880b57cec5SDimitry Andric continue; 21890b57cec5SDimitry Andric 21900b57cec5SDimitry Andric // Now walk the successors. We need to establish whether this has a viable 21910b57cec5SDimitry Andric // exiting successor and whether it has a viable non-exiting successor. 21920b57cec5SDimitry Andric // We store the old exiting state and restore it if a viable looping 21930b57cec5SDimitry Andric // successor isn't found. 21940b57cec5SDimitry Andric MachineBasicBlock *OldExitingBB = ExitingBB; 21950b57cec5SDimitry Andric BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; 21960b57cec5SDimitry Andric bool HasLoopingSucc = false; 21970b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB->successors()) { 21980b57cec5SDimitry Andric if (Succ->isEHPad()) 21990b57cec5SDimitry Andric continue; 22000b57cec5SDimitry Andric if (Succ == MBB) 22010b57cec5SDimitry Andric continue; 22020b57cec5SDimitry Andric BlockChain &SuccChain = *BlockToChain[Succ]; 22030b57cec5SDimitry Andric // Don't split chains, either this chain or the successor's chain. 22040b57cec5SDimitry Andric if (&Chain == &SuccChain) { 22050b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 22060b57cec5SDimitry Andric << getBlockName(Succ) << " (chain conflict)\n"); 22070b57cec5SDimitry Andric continue; 22080b57cec5SDimitry Andric } 22090b57cec5SDimitry Andric 22100b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); 22110b57cec5SDimitry Andric if (LoopBlockSet.count(Succ)) { 22120b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " 22130b57cec5SDimitry Andric << getBlockName(Succ) << " (" << SuccProb << ")\n"); 22140b57cec5SDimitry Andric HasLoopingSucc = true; 22150b57cec5SDimitry Andric continue; 22160b57cec5SDimitry Andric } 22170b57cec5SDimitry Andric 22180b57cec5SDimitry Andric unsigned SuccLoopDepth = 0; 22190b57cec5SDimitry Andric if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { 22200b57cec5SDimitry Andric SuccLoopDepth = ExitLoop->getLoopDepth(); 22210b57cec5SDimitry Andric if (ExitLoop->contains(&L)) 22220b57cec5SDimitry Andric BlocksExitingToOuterLoop.insert(MBB); 22230b57cec5SDimitry Andric } 22240b57cec5SDimitry Andric 22250b57cec5SDimitry Andric BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; 22260b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " 22270b57cec5SDimitry Andric << getBlockName(Succ) << " [L:" << SuccLoopDepth 22280b57cec5SDimitry Andric << "] ("; 22290b57cec5SDimitry Andric MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); 22300b57cec5SDimitry Andric // Note that we bias this toward an existing layout successor to retain 22310b57cec5SDimitry Andric // incoming order in the absence of better information. The exit must have 22320b57cec5SDimitry Andric // a frequency higher than the current exit before we consider breaking 22330b57cec5SDimitry Andric // the layout. 22340b57cec5SDimitry Andric BranchProbability Bias(100 - ExitBlockBias, 100); 22350b57cec5SDimitry Andric if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || 22360b57cec5SDimitry Andric ExitEdgeFreq > BestExitEdgeFreq || 22370b57cec5SDimitry Andric (MBB->isLayoutSuccessor(Succ) && 22380b57cec5SDimitry Andric !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { 22390b57cec5SDimitry Andric BestExitEdgeFreq = ExitEdgeFreq; 22400b57cec5SDimitry Andric ExitingBB = MBB; 22410b57cec5SDimitry Andric } 22420b57cec5SDimitry Andric } 22430b57cec5SDimitry Andric 22440b57cec5SDimitry Andric if (!HasLoopingSucc) { 22450b57cec5SDimitry Andric // Restore the old exiting state, no viable looping successor was found. 22460b57cec5SDimitry Andric ExitingBB = OldExitingBB; 22470b57cec5SDimitry Andric BestExitEdgeFreq = OldBestExitEdgeFreq; 22480b57cec5SDimitry Andric } 22490b57cec5SDimitry Andric } 22500b57cec5SDimitry Andric // Without a candidate exiting block or with only a single block in the 22510b57cec5SDimitry Andric // loop, just use the loop header to layout the loop. 22520b57cec5SDimitry Andric if (!ExitingBB) { 22530b57cec5SDimitry Andric LLVM_DEBUG( 22540b57cec5SDimitry Andric dbgs() << " No other candidate exit blocks, using loop header\n"); 22550b57cec5SDimitry Andric return nullptr; 22560b57cec5SDimitry Andric } 22570b57cec5SDimitry Andric if (L.getNumBlocks() == 1) { 22580b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); 22590b57cec5SDimitry Andric return nullptr; 22600b57cec5SDimitry Andric } 22610b57cec5SDimitry Andric 22620b57cec5SDimitry Andric // Also, if we have exit blocks which lead to outer loops but didn't select 22630b57cec5SDimitry Andric // one of them as the exiting block we are rotating toward, disable loop 22640b57cec5SDimitry Andric // rotation altogether. 22650b57cec5SDimitry Andric if (!BlocksExitingToOuterLoop.empty() && 22660b57cec5SDimitry Andric !BlocksExitingToOuterLoop.count(ExitingBB)) 22670b57cec5SDimitry Andric return nullptr; 22680b57cec5SDimitry Andric 22690b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) 22700b57cec5SDimitry Andric << "\n"); 22710b57cec5SDimitry Andric ExitFreq = BestExitEdgeFreq; 22720b57cec5SDimitry Andric return ExitingBB; 22730b57cec5SDimitry Andric } 22740b57cec5SDimitry Andric 22750b57cec5SDimitry Andric /// Check if there is a fallthrough to loop header Top. 22760b57cec5SDimitry Andric /// 22770b57cec5SDimitry Andric /// 1. Look for a Pred that can be layout before Top. 22780b57cec5SDimitry Andric /// 2. Check if Top is the most possible successor of Pred. 22790b57cec5SDimitry Andric bool 22800b57cec5SDimitry Andric MachineBlockPlacement::hasViableTopFallthrough( 22810b57cec5SDimitry Andric const MachineBasicBlock *Top, 22820b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 22830b57cec5SDimitry Andric for (MachineBasicBlock *Pred : Top->predecessors()) { 22840b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 22850b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 22860b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 22870b57cec5SDimitry Andric // Found a Pred block can be placed before Top. 22880b57cec5SDimitry Andric // Check if Top is the best successor of Pred. 22890b57cec5SDimitry Andric auto TopProb = MBPI->getEdgeProbability(Pred, Top); 22900b57cec5SDimitry Andric bool TopOK = true; 22910b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) { 22920b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(Pred, Succ); 22930b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 22940b57cec5SDimitry Andric // Check if Succ can be placed after Pred. 22950b57cec5SDimitry Andric // Succ should not be in any chain, or it is the head of some chain. 22960b57cec5SDimitry Andric if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) { 22970b57cec5SDimitry Andric TopOK = false; 22980b57cec5SDimitry Andric break; 22990b57cec5SDimitry Andric } 23000b57cec5SDimitry Andric } 23010b57cec5SDimitry Andric if (TopOK) 23020b57cec5SDimitry Andric return true; 23030b57cec5SDimitry Andric } 23040b57cec5SDimitry Andric } 23050b57cec5SDimitry Andric return false; 23060b57cec5SDimitry Andric } 23070b57cec5SDimitry Andric 23080b57cec5SDimitry Andric /// Attempt to rotate an exiting block to the bottom of the loop. 23090b57cec5SDimitry Andric /// 23100b57cec5SDimitry Andric /// Once we have built a chain, try to rotate it to line up the hot exit block 23110b57cec5SDimitry Andric /// with fallthrough out of the loop if doing so doesn't introduce unnecessary 23120b57cec5SDimitry Andric /// branches. For example, if the loop has fallthrough into its header and out 23130b57cec5SDimitry Andric /// of its bottom already, don't rotate it. 23140b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, 23150b57cec5SDimitry Andric const MachineBasicBlock *ExitingBB, 23160b57cec5SDimitry Andric BlockFrequency ExitFreq, 23170b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 23180b57cec5SDimitry Andric if (!ExitingBB) 23190b57cec5SDimitry Andric return; 23200b57cec5SDimitry Andric 23210b57cec5SDimitry Andric MachineBasicBlock *Top = *LoopChain.begin(); 23220b57cec5SDimitry Andric MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); 23230b57cec5SDimitry Andric 23240b57cec5SDimitry Andric // If ExitingBB is already the last one in a chain then nothing to do. 23250b57cec5SDimitry Andric if (Bottom == ExitingBB) 23260b57cec5SDimitry Andric return; 23270b57cec5SDimitry Andric 2328e8d8bef9SDimitry Andric // The entry block should always be the first BB in a function. 2329e8d8bef9SDimitry Andric if (Top->isEntryBlock()) 2330e8d8bef9SDimitry Andric return; 2331e8d8bef9SDimitry Andric 23320b57cec5SDimitry Andric bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet); 23330b57cec5SDimitry Andric 23340b57cec5SDimitry Andric // If the header has viable fallthrough, check whether the current loop 23350b57cec5SDimitry Andric // bottom is a viable exiting block. If so, bail out as rotating will 23360b57cec5SDimitry Andric // introduce an unnecessary branch. 23370b57cec5SDimitry Andric if (ViableTopFallthrough) { 23380b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Bottom->successors()) { 23390b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 23400b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && 23410b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) 23420b57cec5SDimitry Andric return; 23430b57cec5SDimitry Andric } 23440b57cec5SDimitry Andric 23450b57cec5SDimitry Andric // Rotate will destroy the top fallthrough, we need to ensure the new exit 23460b57cec5SDimitry Andric // frequency is larger than top fallthrough. 23470b57cec5SDimitry Andric BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet); 23480b57cec5SDimitry Andric if (FallThrough2Top >= ExitFreq) 23490b57cec5SDimitry Andric return; 23500b57cec5SDimitry Andric } 23510b57cec5SDimitry Andric 23520b57cec5SDimitry Andric BlockChain::iterator ExitIt = llvm::find(LoopChain, ExitingBB); 23530b57cec5SDimitry Andric if (ExitIt == LoopChain.end()) 23540b57cec5SDimitry Andric return; 23550b57cec5SDimitry Andric 23560b57cec5SDimitry Andric // Rotating a loop exit to the bottom when there is a fallthrough to top 23570b57cec5SDimitry Andric // trades the entry fallthrough for an exit fallthrough. 23580b57cec5SDimitry Andric // If there is no bottom->top edge, but the chosen exit block does have 23590b57cec5SDimitry Andric // a fallthrough, we break that fallthrough for nothing in return. 23600b57cec5SDimitry Andric 23610b57cec5SDimitry Andric // Let's consider an example. We have a built chain of basic blocks 23620b57cec5SDimitry Andric // B1, B2, ..., Bn, where Bk is a ExitingBB - chosen exit block. 23630b57cec5SDimitry Andric // By doing a rotation we get 23640b57cec5SDimitry Andric // Bk+1, ..., Bn, B1, ..., Bk 23650b57cec5SDimitry Andric // Break of fallthrough to B1 is compensated by a fallthrough from Bk. 23660b57cec5SDimitry Andric // If we had a fallthrough Bk -> Bk+1 it is broken now. 23670b57cec5SDimitry Andric // It might be compensated by fallthrough Bn -> B1. 23680b57cec5SDimitry Andric // So we have a condition to avoid creation of extra branch by loop rotation. 23690b57cec5SDimitry Andric // All below must be true to avoid loop rotation: 23700b57cec5SDimitry Andric // If there is a fallthrough to top (B1) 23710b57cec5SDimitry Andric // There was fallthrough from chosen exit block (Bk) to next one (Bk+1) 23720b57cec5SDimitry Andric // There is no fallthrough from bottom (Bn) to top (B1). 23730b57cec5SDimitry Andric // Please note that there is no exit fallthrough from Bn because we checked it 23740b57cec5SDimitry Andric // above. 23750b57cec5SDimitry Andric if (ViableTopFallthrough) { 23760b57cec5SDimitry Andric assert(std::next(ExitIt) != LoopChain.end() && 23770b57cec5SDimitry Andric "Exit should not be last BB"); 23780b57cec5SDimitry Andric MachineBasicBlock *NextBlockInChain = *std::next(ExitIt); 23790b57cec5SDimitry Andric if (ExitingBB->isSuccessor(NextBlockInChain)) 23800b57cec5SDimitry Andric if (!Bottom->isSuccessor(Top)) 23810b57cec5SDimitry Andric return; 23820b57cec5SDimitry Andric } 23830b57cec5SDimitry Andric 23840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotating loop to put exit " << getBlockName(ExitingBB) 23850b57cec5SDimitry Andric << " at bottom\n"); 23860b57cec5SDimitry Andric std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); 23870b57cec5SDimitry Andric } 23880b57cec5SDimitry Andric 23890b57cec5SDimitry Andric /// Attempt to rotate a loop based on profile data to reduce branch cost. 23900b57cec5SDimitry Andric /// 23910b57cec5SDimitry Andric /// With profile data, we can determine the cost in terms of missed fall through 23920b57cec5SDimitry Andric /// opportunities when rotating a loop chain and select the best rotation. 23930b57cec5SDimitry Andric /// Basically, there are three kinds of cost to consider for each rotation: 23940b57cec5SDimitry Andric /// 1. The possibly missed fall through edge (if it exists) from BB out of 23950b57cec5SDimitry Andric /// the loop to the loop header. 23960b57cec5SDimitry Andric /// 2. The possibly missed fall through edges (if they exist) from the loop 23970b57cec5SDimitry Andric /// exits to BB out of the loop. 23980b57cec5SDimitry Andric /// 3. The missed fall through edge (if it exists) from the last BB to the 23990b57cec5SDimitry Andric /// first BB in the loop chain. 24000b57cec5SDimitry Andric /// Therefore, the cost for a given rotation is the sum of costs listed above. 24010b57cec5SDimitry Andric /// We select the best rotation with the smallest cost. 24020b57cec5SDimitry Andric void MachineBlockPlacement::rotateLoopWithProfile( 24030b57cec5SDimitry Andric BlockChain &LoopChain, const MachineLoop &L, 24040b57cec5SDimitry Andric const BlockFilterSet &LoopBlockSet) { 24050b57cec5SDimitry Andric auto RotationPos = LoopChain.end(); 2406e8d8bef9SDimitry Andric MachineBasicBlock *ChainHeaderBB = *LoopChain.begin(); 2407e8d8bef9SDimitry Andric 2408e8d8bef9SDimitry Andric // The entry block should always be the first BB in a function. 2409e8d8bef9SDimitry Andric if (ChainHeaderBB->isEntryBlock()) 2410e8d8bef9SDimitry Andric return; 24110b57cec5SDimitry Andric 24120b57cec5SDimitry Andric BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); 24130b57cec5SDimitry Andric 24140b57cec5SDimitry Andric // A utility lambda that scales up a block frequency by dividing it by a 24150b57cec5SDimitry Andric // branch probability which is the reciprocal of the scale. 24160b57cec5SDimitry Andric auto ScaleBlockFrequency = [](BlockFrequency Freq, 24170b57cec5SDimitry Andric unsigned Scale) -> BlockFrequency { 24180b57cec5SDimitry Andric if (Scale == 0) 24190b57cec5SDimitry Andric return 0; 24200b57cec5SDimitry Andric // Use operator / between BlockFrequency and BranchProbability to implement 24210b57cec5SDimitry Andric // saturating multiplication. 24220b57cec5SDimitry Andric return Freq / BranchProbability(1, Scale); 24230b57cec5SDimitry Andric }; 24240b57cec5SDimitry Andric 24250b57cec5SDimitry Andric // Compute the cost of the missed fall-through edge to the loop header if the 24260b57cec5SDimitry Andric // chain head is not the loop header. As we only consider natural loops with 24270b57cec5SDimitry Andric // single header, this computation can be done only once. 24280b57cec5SDimitry Andric BlockFrequency HeaderFallThroughCost(0); 24290b57cec5SDimitry Andric for (auto *Pred : ChainHeaderBB->predecessors()) { 24300b57cec5SDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 24310b57cec5SDimitry Andric if (!LoopBlockSet.count(Pred) && 24320b57cec5SDimitry Andric (!PredChain || Pred == *std::prev(PredChain->end()))) { 24330b57cec5SDimitry Andric auto EdgeFreq = MBFI->getBlockFreq(Pred) * 24340b57cec5SDimitry Andric MBPI->getEdgeProbability(Pred, ChainHeaderBB); 24350b57cec5SDimitry Andric auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); 24360b57cec5SDimitry Andric // If the predecessor has only an unconditional jump to the header, we 24370b57cec5SDimitry Andric // need to consider the cost of this jump. 24380b57cec5SDimitry Andric if (Pred->succ_size() == 1) 24390b57cec5SDimitry Andric FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); 24400b57cec5SDimitry Andric HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); 24410b57cec5SDimitry Andric } 24420b57cec5SDimitry Andric } 24430b57cec5SDimitry Andric 24440b57cec5SDimitry Andric // Here we collect all exit blocks in the loop, and for each exit we find out 24450b57cec5SDimitry Andric // its hottest exit edge. For each loop rotation, we define the loop exit cost 24460b57cec5SDimitry Andric // as the sum of frequencies of exit edges we collect here, excluding the exit 24470b57cec5SDimitry Andric // edge from the tail of the loop chain. 24480b57cec5SDimitry Andric SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; 24490b57cec5SDimitry Andric for (auto BB : LoopChain) { 24500b57cec5SDimitry Andric auto LargestExitEdgeProb = BranchProbability::getZero(); 24510b57cec5SDimitry Andric for (auto *Succ : BB->successors()) { 24520b57cec5SDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 24530b57cec5SDimitry Andric if (!LoopBlockSet.count(Succ) && 24540b57cec5SDimitry Andric (!SuccChain || Succ == *SuccChain->begin())) { 24550b57cec5SDimitry Andric auto SuccProb = MBPI->getEdgeProbability(BB, Succ); 24560b57cec5SDimitry Andric LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); 24570b57cec5SDimitry Andric } 24580b57cec5SDimitry Andric } 24590b57cec5SDimitry Andric if (LargestExitEdgeProb > BranchProbability::getZero()) { 24600b57cec5SDimitry Andric auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; 24610b57cec5SDimitry Andric ExitsWithFreq.emplace_back(BB, ExitFreq); 24620b57cec5SDimitry Andric } 24630b57cec5SDimitry Andric } 24640b57cec5SDimitry Andric 24650b57cec5SDimitry Andric // In this loop we iterate every block in the loop chain and calculate the 24660b57cec5SDimitry Andric // cost assuming the block is the head of the loop chain. When the loop ends, 24670b57cec5SDimitry Andric // we should have found the best candidate as the loop chain's head. 24680b57cec5SDimitry Andric for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), 24690b57cec5SDimitry Andric EndIter = LoopChain.end(); 24700b57cec5SDimitry Andric Iter != EndIter; Iter++, TailIter++) { 24710b57cec5SDimitry Andric // TailIter is used to track the tail of the loop chain if the block we are 24720b57cec5SDimitry Andric // checking (pointed by Iter) is the head of the chain. 24730b57cec5SDimitry Andric if (TailIter == LoopChain.end()) 24740b57cec5SDimitry Andric TailIter = LoopChain.begin(); 24750b57cec5SDimitry Andric 24760b57cec5SDimitry Andric auto TailBB = *TailIter; 24770b57cec5SDimitry Andric 24780b57cec5SDimitry Andric // Calculate the cost by putting this BB to the top. 24790b57cec5SDimitry Andric BlockFrequency Cost = 0; 24800b57cec5SDimitry Andric 24810b57cec5SDimitry Andric // If the current BB is the loop header, we need to take into account the 24820b57cec5SDimitry Andric // cost of the missed fall through edge from outside of the loop to the 24830b57cec5SDimitry Andric // header. 24840b57cec5SDimitry Andric if (Iter != LoopChain.begin()) 24850b57cec5SDimitry Andric Cost += HeaderFallThroughCost; 24860b57cec5SDimitry Andric 24870b57cec5SDimitry Andric // Collect the loop exit cost by summing up frequencies of all exit edges 24880b57cec5SDimitry Andric // except the one from the chain tail. 24890b57cec5SDimitry Andric for (auto &ExitWithFreq : ExitsWithFreq) 24900b57cec5SDimitry Andric if (TailBB != ExitWithFreq.first) 24910b57cec5SDimitry Andric Cost += ExitWithFreq.second; 24920b57cec5SDimitry Andric 24930b57cec5SDimitry Andric // The cost of breaking the once fall-through edge from the tail to the top 24940b57cec5SDimitry Andric // of the loop chain. Here we need to consider three cases: 24950b57cec5SDimitry Andric // 1. If the tail node has only one successor, then we will get an 24960b57cec5SDimitry Andric // additional jmp instruction. So the cost here is (MisfetchCost + 24970b57cec5SDimitry Andric // JumpInstCost) * tail node frequency. 24980b57cec5SDimitry Andric // 2. If the tail node has two successors, then we may still get an 24990b57cec5SDimitry Andric // additional jmp instruction if the layout successor after the loop 25000b57cec5SDimitry Andric // chain is not its CFG successor. Note that the more frequently executed 25010b57cec5SDimitry Andric // jmp instruction will be put ahead of the other one. Assume the 25020b57cec5SDimitry Andric // frequency of those two branches are x and y, where x is the frequency 25030b57cec5SDimitry Andric // of the edge to the chain head, then the cost will be 25040b57cec5SDimitry Andric // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. 25050b57cec5SDimitry Andric // 3. If the tail node has more than two successors (this rarely happens), 25060b57cec5SDimitry Andric // we won't consider any additional cost. 25070b57cec5SDimitry Andric if (TailBB->isSuccessor(*Iter)) { 25080b57cec5SDimitry Andric auto TailBBFreq = MBFI->getBlockFreq(TailBB); 25090b57cec5SDimitry Andric if (TailBB->succ_size() == 1) 25100b57cec5SDimitry Andric Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), 25110b57cec5SDimitry Andric MisfetchCost + JumpInstCost); 25120b57cec5SDimitry Andric else if (TailBB->succ_size() == 2) { 25130b57cec5SDimitry Andric auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); 25140b57cec5SDimitry Andric auto TailToHeadFreq = TailBBFreq * TailToHeadProb; 25150b57cec5SDimitry Andric auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) 25160b57cec5SDimitry Andric ? TailBBFreq * TailToHeadProb.getCompl() 25170b57cec5SDimitry Andric : TailToHeadFreq; 25180b57cec5SDimitry Andric Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + 25190b57cec5SDimitry Andric ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); 25200b57cec5SDimitry Andric } 25210b57cec5SDimitry Andric } 25220b57cec5SDimitry Andric 25230b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "The cost of loop rotation by making " 25240b57cec5SDimitry Andric << getBlockName(*Iter) 25250b57cec5SDimitry Andric << " to the top: " << Cost.getFrequency() << "\n"); 25260b57cec5SDimitry Andric 25270b57cec5SDimitry Andric if (Cost < SmallestRotationCost) { 25280b57cec5SDimitry Andric SmallestRotationCost = Cost; 25290b57cec5SDimitry Andric RotationPos = Iter; 25300b57cec5SDimitry Andric } 25310b57cec5SDimitry Andric } 25320b57cec5SDimitry Andric 25330b57cec5SDimitry Andric if (RotationPos != LoopChain.end()) { 25340b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) 25350b57cec5SDimitry Andric << " to the top\n"); 25360b57cec5SDimitry Andric std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); 25370b57cec5SDimitry Andric } 25380b57cec5SDimitry Andric } 25390b57cec5SDimitry Andric 25400b57cec5SDimitry Andric /// Collect blocks in the given loop that are to be placed. 25410b57cec5SDimitry Andric /// 25420b57cec5SDimitry Andric /// When profile data is available, exclude cold blocks from the returned set; 25430b57cec5SDimitry Andric /// otherwise, collect all blocks in the loop. 25440b57cec5SDimitry Andric MachineBlockPlacement::BlockFilterSet 25450b57cec5SDimitry Andric MachineBlockPlacement::collectLoopBlockSet(const MachineLoop &L) { 25460b57cec5SDimitry Andric BlockFilterSet LoopBlockSet; 25470b57cec5SDimitry Andric 25480b57cec5SDimitry Andric // Filter cold blocks off from LoopBlockSet when profile data is available. 25490b57cec5SDimitry Andric // Collect the sum of frequencies of incoming edges to the loop header from 25500b57cec5SDimitry Andric // outside. If we treat the loop as a super block, this is the frequency of 25510b57cec5SDimitry Andric // the loop. Then for each block in the loop, we calculate the ratio between 25520b57cec5SDimitry Andric // its frequency and the frequency of the loop block. When it is too small, 25530b57cec5SDimitry Andric // don't add it to the loop chain. If there are outer loops, then this block 25540b57cec5SDimitry Andric // will be merged into the first outer loop chain for which this block is not 25550b57cec5SDimitry Andric // cold anymore. This needs precise profile data and we only do this when 25560b57cec5SDimitry Andric // profile data is available. 25570b57cec5SDimitry Andric if (F->getFunction().hasProfileData() || ForceLoopColdBlock) { 25580b57cec5SDimitry Andric BlockFrequency LoopFreq(0); 25590b57cec5SDimitry Andric for (auto LoopPred : L.getHeader()->predecessors()) 25600b57cec5SDimitry Andric if (!L.contains(LoopPred)) 25610b57cec5SDimitry Andric LoopFreq += MBFI->getBlockFreq(LoopPred) * 25620b57cec5SDimitry Andric MBPI->getEdgeProbability(LoopPred, L.getHeader()); 25630b57cec5SDimitry Andric 25640b57cec5SDimitry Andric for (MachineBasicBlock *LoopBB : L.getBlocks()) { 2565e8d8bef9SDimitry Andric if (LoopBlockSet.count(LoopBB)) 2566e8d8bef9SDimitry Andric continue; 25670b57cec5SDimitry Andric auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); 25680b57cec5SDimitry Andric if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) 25690b57cec5SDimitry Andric continue; 2570e8d8bef9SDimitry Andric BlockChain *Chain = BlockToChain[LoopBB]; 2571e8d8bef9SDimitry Andric for (MachineBasicBlock *ChainBB : *Chain) 2572e8d8bef9SDimitry Andric LoopBlockSet.insert(ChainBB); 25730b57cec5SDimitry Andric } 25740b57cec5SDimitry Andric } else 25750b57cec5SDimitry Andric LoopBlockSet.insert(L.block_begin(), L.block_end()); 25760b57cec5SDimitry Andric 25770b57cec5SDimitry Andric return LoopBlockSet; 25780b57cec5SDimitry Andric } 25790b57cec5SDimitry Andric 25800b57cec5SDimitry Andric /// Forms basic block chains from the natural loop structures. 25810b57cec5SDimitry Andric /// 25820b57cec5SDimitry Andric /// These chains are designed to preserve the existing *structure* of the code 25830b57cec5SDimitry Andric /// as much as possible. We can then stitch the chains together in a way which 25840b57cec5SDimitry Andric /// both preserves the topological structure and minimizes taken conditional 25850b57cec5SDimitry Andric /// branches. 25860b57cec5SDimitry Andric void MachineBlockPlacement::buildLoopChains(const MachineLoop &L) { 25870b57cec5SDimitry Andric // First recurse through any nested loops, building chains for those inner 25880b57cec5SDimitry Andric // loops. 25890b57cec5SDimitry Andric for (const MachineLoop *InnerLoop : L) 25900b57cec5SDimitry Andric buildLoopChains(*InnerLoop); 25910b57cec5SDimitry Andric 25920b57cec5SDimitry Andric assert(BlockWorkList.empty() && 25930b57cec5SDimitry Andric "BlockWorkList not empty when starting to build loop chains."); 25940b57cec5SDimitry Andric assert(EHPadWorkList.empty() && 25950b57cec5SDimitry Andric "EHPadWorkList not empty when starting to build loop chains."); 25960b57cec5SDimitry Andric BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); 25970b57cec5SDimitry Andric 25980b57cec5SDimitry Andric // Check if we have profile data for this function. If yes, we will rotate 25990b57cec5SDimitry Andric // this loop by modeling costs more precisely which requires the profile data 26000b57cec5SDimitry Andric // for better layout. 26010b57cec5SDimitry Andric bool RotateLoopWithProfile = 26020b57cec5SDimitry Andric ForcePreciseRotationCost || 26030b57cec5SDimitry Andric (PreciseRotationCost && F->getFunction().hasProfileData()); 26040b57cec5SDimitry Andric 26050b57cec5SDimitry Andric // First check to see if there is an obviously preferable top block for the 26060b57cec5SDimitry Andric // loop. This will default to the header, but may end up as one of the 26070b57cec5SDimitry Andric // predecessors to the header if there is one which will result in strictly 26080b57cec5SDimitry Andric // fewer branches in the loop body. 26090b57cec5SDimitry Andric MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet); 26100b57cec5SDimitry Andric 26110b57cec5SDimitry Andric // If we selected just the header for the loop top, look for a potentially 26120b57cec5SDimitry Andric // profitable exit block in the event that rotating the loop can eliminate 26130b57cec5SDimitry Andric // branches by placing an exit edge at the bottom. 26140b57cec5SDimitry Andric // 26150b57cec5SDimitry Andric // Loops are processed innermost to uttermost, make sure we clear 26160b57cec5SDimitry Andric // PreferredLoopExit before processing a new loop. 26170b57cec5SDimitry Andric PreferredLoopExit = nullptr; 26180b57cec5SDimitry Andric BlockFrequency ExitFreq; 26190b57cec5SDimitry Andric if (!RotateLoopWithProfile && LoopTop == L.getHeader()) 26200b57cec5SDimitry Andric PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq); 26210b57cec5SDimitry Andric 26220b57cec5SDimitry Andric BlockChain &LoopChain = *BlockToChain[LoopTop]; 26230b57cec5SDimitry Andric 26240b57cec5SDimitry Andric // FIXME: This is a really lame way of walking the chains in the loop: we 26250b57cec5SDimitry Andric // walk the blocks, and use a set to prevent visiting a particular chain 26260b57cec5SDimitry Andric // twice. 26270b57cec5SDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 26280b57cec5SDimitry Andric assert(LoopChain.UnscheduledPredecessors == 0 && 26290b57cec5SDimitry Andric "LoopChain should not have unscheduled predecessors."); 26300b57cec5SDimitry Andric UpdatedPreds.insert(&LoopChain); 26310b57cec5SDimitry Andric 26320b57cec5SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 26330b57cec5SDimitry Andric fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); 26340b57cec5SDimitry Andric 26350b57cec5SDimitry Andric buildChain(LoopTop, LoopChain, &LoopBlockSet); 26360b57cec5SDimitry Andric 26370b57cec5SDimitry Andric if (RotateLoopWithProfile) 26380b57cec5SDimitry Andric rotateLoopWithProfile(LoopChain, L, LoopBlockSet); 26390b57cec5SDimitry Andric else 26400b57cec5SDimitry Andric rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet); 26410b57cec5SDimitry Andric 26420b57cec5SDimitry Andric LLVM_DEBUG({ 26430b57cec5SDimitry Andric // Crash at the end so we get all of the debugging output first. 26440b57cec5SDimitry Andric bool BadLoop = false; 26450b57cec5SDimitry Andric if (LoopChain.UnscheduledPredecessors) { 26460b57cec5SDimitry Andric BadLoop = true; 26470b57cec5SDimitry Andric dbgs() << "Loop chain contains a block without its preds placed!\n" 26480b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 26490b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; 26500b57cec5SDimitry Andric } 26510b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : LoopChain) { 26520b57cec5SDimitry Andric dbgs() << " ... " << getBlockName(ChainBB) << "\n"; 26530b57cec5SDimitry Andric if (!LoopBlockSet.remove(ChainBB)) { 26540b57cec5SDimitry Andric // We don't mark the loop as bad here because there are real situations 26550b57cec5SDimitry Andric // where this can occur. For example, with an unanalyzable fallthrough 26560b57cec5SDimitry Andric // from a loop block to a non-loop block or vice versa. 26570b57cec5SDimitry Andric dbgs() << "Loop chain contains a block not contained by the loop!\n" 26580b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 26590b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 26600b57cec5SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 26610b57cec5SDimitry Andric } 26620b57cec5SDimitry Andric } 26630b57cec5SDimitry Andric 26640b57cec5SDimitry Andric if (!LoopBlockSet.empty()) { 26650b57cec5SDimitry Andric BadLoop = true; 26660b57cec5SDimitry Andric for (const MachineBasicBlock *LoopBB : LoopBlockSet) 26670b57cec5SDimitry Andric dbgs() << "Loop contains blocks never placed into a chain!\n" 26680b57cec5SDimitry Andric << " Loop header: " << getBlockName(*L.block_begin()) << "\n" 26690b57cec5SDimitry Andric << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" 26700b57cec5SDimitry Andric << " Bad block: " << getBlockName(LoopBB) << "\n"; 26710b57cec5SDimitry Andric } 26720b57cec5SDimitry Andric assert(!BadLoop && "Detected problems with the placement of this loop."); 26730b57cec5SDimitry Andric }); 26740b57cec5SDimitry Andric 26750b57cec5SDimitry Andric BlockWorkList.clear(); 26760b57cec5SDimitry Andric EHPadWorkList.clear(); 26770b57cec5SDimitry Andric } 26780b57cec5SDimitry Andric 26790b57cec5SDimitry Andric void MachineBlockPlacement::buildCFGChains() { 26800b57cec5SDimitry Andric // Ensure that every BB in the function has an associated chain to simplify 26810b57cec5SDimitry Andric // the assumptions of the remaining algorithm. 26825ffd83dbSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 26830b57cec5SDimitry Andric for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; 26840b57cec5SDimitry Andric ++FI) { 26850b57cec5SDimitry Andric MachineBasicBlock *BB = &*FI; 26860b57cec5SDimitry Andric BlockChain *Chain = 26870b57cec5SDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); 26880b57cec5SDimitry Andric // Also, merge any blocks which we cannot reason about and must preserve 26890b57cec5SDimitry Andric // the exact fallthrough behavior for. 26900b57cec5SDimitry Andric while (true) { 26910b57cec5SDimitry Andric Cond.clear(); 26925ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 26930b57cec5SDimitry Andric if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) 26940b57cec5SDimitry Andric break; 26950b57cec5SDimitry Andric 26960b57cec5SDimitry Andric MachineFunction::iterator NextFI = std::next(FI); 26970b57cec5SDimitry Andric MachineBasicBlock *NextBB = &*NextFI; 26980b57cec5SDimitry Andric // Ensure that the layout successor is a viable block, as we know that 26990b57cec5SDimitry Andric // fallthrough is a possibility. 27000b57cec5SDimitry Andric assert(NextFI != FE && "Can't fallthrough past the last block."); 27010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " 27020b57cec5SDimitry Andric << getBlockName(BB) << " -> " << getBlockName(NextBB) 27030b57cec5SDimitry Andric << "\n"); 27040b57cec5SDimitry Andric Chain->merge(NextBB, nullptr); 27050b57cec5SDimitry Andric #ifndef NDEBUG 27060b57cec5SDimitry Andric BlocksWithUnanalyzableExits.insert(&*BB); 27070b57cec5SDimitry Andric #endif 27080b57cec5SDimitry Andric FI = NextFI; 27090b57cec5SDimitry Andric BB = NextBB; 27100b57cec5SDimitry Andric } 27110b57cec5SDimitry Andric } 27120b57cec5SDimitry Andric 27130b57cec5SDimitry Andric // Build any loop-based chains. 27140b57cec5SDimitry Andric PreferredLoopExit = nullptr; 27150b57cec5SDimitry Andric for (MachineLoop *L : *MLI) 27160b57cec5SDimitry Andric buildLoopChains(*L); 27170b57cec5SDimitry Andric 27180b57cec5SDimitry Andric assert(BlockWorkList.empty() && 27190b57cec5SDimitry Andric "BlockWorkList should be empty before building final chain."); 27200b57cec5SDimitry Andric assert(EHPadWorkList.empty() && 27210b57cec5SDimitry Andric "EHPadWorkList should be empty before building final chain."); 27220b57cec5SDimitry Andric 27230b57cec5SDimitry Andric SmallPtrSet<BlockChain *, 4> UpdatedPreds; 27240b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *F) 27250b57cec5SDimitry Andric fillWorkLists(&MBB, UpdatedPreds); 27260b57cec5SDimitry Andric 27270b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 27280b57cec5SDimitry Andric buildChain(&F->front(), FunctionChain); 27290b57cec5SDimitry Andric 27300b57cec5SDimitry Andric #ifndef NDEBUG 27310b57cec5SDimitry Andric using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>; 27320b57cec5SDimitry Andric #endif 27330b57cec5SDimitry Andric LLVM_DEBUG({ 27340b57cec5SDimitry Andric // Crash at the end so we get all of the debugging output first. 27350b57cec5SDimitry Andric bool BadFunc = false; 27360b57cec5SDimitry Andric FunctionBlockSetType FunctionBlockSet; 27370b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *F) 27380b57cec5SDimitry Andric FunctionBlockSet.insert(&MBB); 27390b57cec5SDimitry Andric 27400b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) 27410b57cec5SDimitry Andric if (!FunctionBlockSet.erase(ChainBB)) { 27420b57cec5SDimitry Andric BadFunc = true; 27430b57cec5SDimitry Andric dbgs() << "Function chain contains a block not in the function!\n" 27440b57cec5SDimitry Andric << " Bad block: " << getBlockName(ChainBB) << "\n"; 27450b57cec5SDimitry Andric } 27460b57cec5SDimitry Andric 27470b57cec5SDimitry Andric if (!FunctionBlockSet.empty()) { 27480b57cec5SDimitry Andric BadFunc = true; 27490b57cec5SDimitry Andric for (MachineBasicBlock *RemainingBB : FunctionBlockSet) 27500b57cec5SDimitry Andric dbgs() << "Function contains blocks never placed into a chain!\n" 27510b57cec5SDimitry Andric << " Bad block: " << getBlockName(RemainingBB) << "\n"; 27520b57cec5SDimitry Andric } 27530b57cec5SDimitry Andric assert(!BadFunc && "Detected problems with the block placement."); 27540b57cec5SDimitry Andric }); 27550b57cec5SDimitry Andric 27565ffd83dbSDimitry Andric // Remember original layout ordering, so we can update terminators after 27575ffd83dbSDimitry Andric // reordering to point to the original layout successor. 27585ffd83dbSDimitry Andric SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors( 27595ffd83dbSDimitry Andric F->getNumBlockIDs()); 27605ffd83dbSDimitry Andric { 27615ffd83dbSDimitry Andric MachineBasicBlock *LastMBB = nullptr; 27625ffd83dbSDimitry Andric for (auto &MBB : *F) { 27635ffd83dbSDimitry Andric if (LastMBB != nullptr) 27645ffd83dbSDimitry Andric OriginalLayoutSuccessors[LastMBB->getNumber()] = &MBB; 27655ffd83dbSDimitry Andric LastMBB = &MBB; 27665ffd83dbSDimitry Andric } 27675ffd83dbSDimitry Andric OriginalLayoutSuccessors[F->back().getNumber()] = nullptr; 27685ffd83dbSDimitry Andric } 27695ffd83dbSDimitry Andric 27700b57cec5SDimitry Andric // Splice the blocks into place. 27710b57cec5SDimitry Andric MachineFunction::iterator InsertPos = F->begin(); 27720b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "[MBP] Function: " << F->getName() << "\n"); 27730b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 27740b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " 27750b57cec5SDimitry Andric : " ... ") 27760b57cec5SDimitry Andric << getBlockName(ChainBB) << "\n"); 27770b57cec5SDimitry Andric if (InsertPos != MachineFunction::iterator(ChainBB)) 27780b57cec5SDimitry Andric F->splice(InsertPos, ChainBB); 27790b57cec5SDimitry Andric else 27800b57cec5SDimitry Andric ++InsertPos; 27810b57cec5SDimitry Andric 27820b57cec5SDimitry Andric // Update the terminator of the previous block. 27830b57cec5SDimitry Andric if (ChainBB == *FunctionChain.begin()) 27840b57cec5SDimitry Andric continue; 27850b57cec5SDimitry Andric MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); 27860b57cec5SDimitry Andric 27870b57cec5SDimitry Andric // FIXME: It would be awesome of updateTerminator would just return rather 27880b57cec5SDimitry Andric // than assert when the branch cannot be analyzed in order to remove this 27890b57cec5SDimitry Andric // boiler plate. 27900b57cec5SDimitry Andric Cond.clear(); 27915ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 27920b57cec5SDimitry Andric 27930b57cec5SDimitry Andric #ifndef NDEBUG 27940b57cec5SDimitry Andric if (!BlocksWithUnanalyzableExits.count(PrevBB)) { 27950b57cec5SDimitry Andric // Given the exact block placement we chose, we may actually not _need_ to 27960b57cec5SDimitry Andric // be able to edit PrevBB's terminator sequence, but not being _able_ to 27970b57cec5SDimitry Andric // do that at this point is a bug. 27980b57cec5SDimitry Andric assert((!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond) || 27990b57cec5SDimitry Andric !PrevBB->canFallThrough()) && 28000b57cec5SDimitry Andric "Unexpected block with un-analyzable fallthrough!"); 28010b57cec5SDimitry Andric Cond.clear(); 28020b57cec5SDimitry Andric TBB = FBB = nullptr; 28030b57cec5SDimitry Andric } 28040b57cec5SDimitry Andric #endif 28050b57cec5SDimitry Andric 28060b57cec5SDimitry Andric // The "PrevBB" is not yet updated to reflect current code layout, so, 28070b57cec5SDimitry Andric // o. it may fall-through to a block without explicit "goto" instruction 28080b57cec5SDimitry Andric // before layout, and no longer fall-through it after layout; or 28090b57cec5SDimitry Andric // o. just opposite. 28100b57cec5SDimitry Andric // 28110b57cec5SDimitry Andric // analyzeBranch() may return erroneous value for FBB when these two 28120b57cec5SDimitry Andric // situations take place. For the first scenario FBB is mistakenly set NULL; 28130b57cec5SDimitry Andric // for the 2nd scenario, the FBB, which is expected to be NULL, is 28140b57cec5SDimitry Andric // mistakenly pointing to "*BI". 28150b57cec5SDimitry Andric // Thus, if the future change needs to use FBB before the layout is set, it 28160b57cec5SDimitry Andric // has to correct FBB first by using the code similar to the following: 28170b57cec5SDimitry Andric // 28180b57cec5SDimitry Andric // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { 28190b57cec5SDimitry Andric // PrevBB->updateTerminator(); 28200b57cec5SDimitry Andric // Cond.clear(); 28210b57cec5SDimitry Andric // TBB = FBB = nullptr; 28220b57cec5SDimitry Andric // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 28230b57cec5SDimitry Andric // // FIXME: This should never take place. 28240b57cec5SDimitry Andric // TBB = FBB = nullptr; 28250b57cec5SDimitry Andric // } 28260b57cec5SDimitry Andric // } 28275ffd83dbSDimitry Andric if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { 28285ffd83dbSDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 28295ffd83dbSDimitry Andric } 28300b57cec5SDimitry Andric } 28310b57cec5SDimitry Andric 28320b57cec5SDimitry Andric // Fixup the last block. 28330b57cec5SDimitry Andric Cond.clear(); 28345ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 28355ffd83dbSDimitry Andric if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) { 28365ffd83dbSDimitry Andric MachineBasicBlock *PrevBB = &F->back(); 28375ffd83dbSDimitry Andric PrevBB->updateTerminator(OriginalLayoutSuccessors[PrevBB->getNumber()]); 28385ffd83dbSDimitry Andric } 28390b57cec5SDimitry Andric 28400b57cec5SDimitry Andric BlockWorkList.clear(); 28410b57cec5SDimitry Andric EHPadWorkList.clear(); 28420b57cec5SDimitry Andric } 28430b57cec5SDimitry Andric 28440b57cec5SDimitry Andric void MachineBlockPlacement::optimizeBranches() { 28450b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 28465ffd83dbSDimitry Andric SmallVector<MachineOperand, 4> Cond; // For analyzeBranch. 28470b57cec5SDimitry Andric 28480b57cec5SDimitry Andric // Now that all the basic blocks in the chain have the proper layout, 28495ffd83dbSDimitry Andric // make a final call to analyzeBranch with AllowModify set. 28500b57cec5SDimitry Andric // Indeed, the target may be able to optimize the branches in a way we 28510b57cec5SDimitry Andric // cannot because all branches may not be analyzable. 28520b57cec5SDimitry Andric // E.g., the target may be able to remove an unconditional branch to 28530b57cec5SDimitry Andric // a fallthrough when it occurs after predicated terminators. 28540b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 28550b57cec5SDimitry Andric Cond.clear(); 28565ffd83dbSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 28570b57cec5SDimitry Andric if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { 28580b57cec5SDimitry Andric // If PrevBB has a two-way branch, try to re-order the branches 28590b57cec5SDimitry Andric // such that we branch to the successor with higher probability first. 28600b57cec5SDimitry Andric if (TBB && !Cond.empty() && FBB && 28610b57cec5SDimitry Andric MBPI->getEdgeProbability(ChainBB, FBB) > 28620b57cec5SDimitry Andric MBPI->getEdgeProbability(ChainBB, TBB) && 28630b57cec5SDimitry Andric !TII->reverseBranchCondition(Cond)) { 28640b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Reverse order of the two branches: " 28650b57cec5SDimitry Andric << getBlockName(ChainBB) << "\n"); 28660b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << " Edge probability: " 28670b57cec5SDimitry Andric << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " 28680b57cec5SDimitry Andric << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); 28690b57cec5SDimitry Andric DebugLoc dl; // FIXME: this is nowhere 28700b57cec5SDimitry Andric TII->removeBranch(*ChainBB); 28710b57cec5SDimitry Andric TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); 28720b57cec5SDimitry Andric } 28730b57cec5SDimitry Andric } 28740b57cec5SDimitry Andric } 28750b57cec5SDimitry Andric } 28760b57cec5SDimitry Andric 28770b57cec5SDimitry Andric void MachineBlockPlacement::alignBlocks() { 28780b57cec5SDimitry Andric // Walk through the backedges of the function now that we have fully laid out 28790b57cec5SDimitry Andric // the basic blocks and align the destination of each backedge. We don't rely 28800b57cec5SDimitry Andric // exclusively on the loop info here so that we can align backedges in 28810b57cec5SDimitry Andric // unnatural CFGs and backedges that were introduced purely because of the 28820b57cec5SDimitry Andric // loop rotations done during this layout pass. 28830b57cec5SDimitry Andric if (F->getFunction().hasMinSize() || 28840b57cec5SDimitry Andric (F->getFunction().hasOptSize() && !TLI->alignLoopsWithOptSize())) 28850b57cec5SDimitry Andric return; 28860b57cec5SDimitry Andric BlockChain &FunctionChain = *BlockToChain[&F->front()]; 28870b57cec5SDimitry Andric if (FunctionChain.begin() == FunctionChain.end()) 28880b57cec5SDimitry Andric return; // Empty chain. 28890b57cec5SDimitry Andric 28900b57cec5SDimitry Andric const BranchProbability ColdProb(1, 5); // 20% 28910b57cec5SDimitry Andric BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); 28920b57cec5SDimitry Andric BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; 28930b57cec5SDimitry Andric for (MachineBasicBlock *ChainBB : FunctionChain) { 28940b57cec5SDimitry Andric if (ChainBB == *FunctionChain.begin()) 28950b57cec5SDimitry Andric continue; 28960b57cec5SDimitry Andric 28970b57cec5SDimitry Andric // Don't align non-looping basic blocks. These are unlikely to execute 28980b57cec5SDimitry Andric // enough times to matter in practice. Note that we'll still handle 28990b57cec5SDimitry Andric // unnatural CFGs inside of a natural outer loop (the common case) and 29000b57cec5SDimitry Andric // rotated loops. 29010b57cec5SDimitry Andric MachineLoop *L = MLI->getLoopFor(ChainBB); 29020b57cec5SDimitry Andric if (!L) 29030b57cec5SDimitry Andric continue; 29040b57cec5SDimitry Andric 29058bcb0991SDimitry Andric const Align Align = TLI->getPrefLoopAlignment(L); 29068bcb0991SDimitry Andric if (Align == 1) 29070b57cec5SDimitry Andric continue; // Don't care about loop alignment. 29080b57cec5SDimitry Andric 29090b57cec5SDimitry Andric // If the block is cold relative to the function entry don't waste space 29100b57cec5SDimitry Andric // aligning it. 29110b57cec5SDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); 29120b57cec5SDimitry Andric if (Freq < WeightedEntryFreq) 29130b57cec5SDimitry Andric continue; 29140b57cec5SDimitry Andric 29150b57cec5SDimitry Andric // If the block is cold relative to its loop header, don't align it 29160b57cec5SDimitry Andric // regardless of what edges into the block exist. 29170b57cec5SDimitry Andric MachineBasicBlock *LoopHeader = L->getHeader(); 29180b57cec5SDimitry Andric BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); 29190b57cec5SDimitry Andric if (Freq < (LoopHeaderFreq * ColdProb)) 29200b57cec5SDimitry Andric continue; 29210b57cec5SDimitry Andric 2922480093f4SDimitry Andric // If the global profiles indicates so, don't align it. 29235ffd83dbSDimitry Andric if (llvm::shouldOptimizeForSize(ChainBB, PSI, MBFI.get()) && 2924480093f4SDimitry Andric !TLI->alignLoopsWithOptSize()) 2925480093f4SDimitry Andric continue; 2926480093f4SDimitry Andric 29270b57cec5SDimitry Andric // Check for the existence of a non-layout predecessor which would benefit 29280b57cec5SDimitry Andric // from aligning this block. 29290b57cec5SDimitry Andric MachineBasicBlock *LayoutPred = 29300b57cec5SDimitry Andric &*std::prev(MachineFunction::iterator(ChainBB)); 29310b57cec5SDimitry Andric 29320b57cec5SDimitry Andric // Force alignment if all the predecessors are jumps. We already checked 29330b57cec5SDimitry Andric // that the block isn't cold above. 29340b57cec5SDimitry Andric if (!LayoutPred->isSuccessor(ChainBB)) { 29350b57cec5SDimitry Andric ChainBB->setAlignment(Align); 29360b57cec5SDimitry Andric continue; 29370b57cec5SDimitry Andric } 29380b57cec5SDimitry Andric 29390b57cec5SDimitry Andric // Align this block if the layout predecessor's edge into this block is 29400b57cec5SDimitry Andric // cold relative to the block. When this is true, other predecessors make up 29410b57cec5SDimitry Andric // all of the hot entries into the block and thus alignment is likely to be 29420b57cec5SDimitry Andric // important. 29430b57cec5SDimitry Andric BranchProbability LayoutProb = 29440b57cec5SDimitry Andric MBPI->getEdgeProbability(LayoutPred, ChainBB); 29450b57cec5SDimitry Andric BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; 29460b57cec5SDimitry Andric if (LayoutEdgeFreq <= (Freq * ColdProb)) 29470b57cec5SDimitry Andric ChainBB->setAlignment(Align); 29480b57cec5SDimitry Andric } 29490b57cec5SDimitry Andric } 29500b57cec5SDimitry Andric 29510b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if 29520b57cec5SDimitry Andric /// it was duplicated into its chain predecessor and removed. 29530b57cec5SDimitry Andric /// \p BB - Basic block that may be duplicated. 29540b57cec5SDimitry Andric /// 29550b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB. 29560b57cec5SDimitry Andric /// Updated to be the chain end if LPred is removed. 29570b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 29580b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 29590b57cec5SDimitry Andric /// Used to identify which blocks to update predecessor 29600b57cec5SDimitry Andric /// counts. 29610b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 29620b57cec5SDimitry Andric /// chosen in the given order due to unnatural CFG 29630b57cec5SDimitry Andric /// only needed if \p BB is removed and 29640b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 29650b57cec5SDimitry Andric /// @return true if \p BB was removed. 29660b57cec5SDimitry Andric bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( 29670b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *&LPred, 29680b57cec5SDimitry Andric const MachineBasicBlock *LoopHeaderBB, 29690b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 29700b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt) { 29710b57cec5SDimitry Andric bool Removed, DuplicatedToLPred; 29720b57cec5SDimitry Andric bool DuplicatedToOriginalLPred; 29730b57cec5SDimitry Andric Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, 29740b57cec5SDimitry Andric PrevUnplacedBlockIt, 29750b57cec5SDimitry Andric DuplicatedToLPred); 29760b57cec5SDimitry Andric if (!Removed) 29770b57cec5SDimitry Andric return false; 29780b57cec5SDimitry Andric DuplicatedToOriginalLPred = DuplicatedToLPred; 29790b57cec5SDimitry Andric // Iteratively try to duplicate again. It can happen that a block that is 29800b57cec5SDimitry Andric // duplicated into is still small enough to be duplicated again. 29810b57cec5SDimitry Andric // No need to call markBlockSuccessors in this case, as the blocks being 29820b57cec5SDimitry Andric // duplicated from here on are already scheduled. 29835ffd83dbSDimitry Andric while (DuplicatedToLPred && Removed) { 29840b57cec5SDimitry Andric MachineBasicBlock *DupBB, *DupPred; 29850b57cec5SDimitry Andric // The removal callback causes Chain.end() to be updated when a block is 29860b57cec5SDimitry Andric // removed. On the first pass through the loop, the chain end should be the 29870b57cec5SDimitry Andric // same as it was on function entry. On subsequent passes, because we are 29880b57cec5SDimitry Andric // duplicating the block at the end of the chain, if it is removed the 29890b57cec5SDimitry Andric // chain will have shrunk by one block. 29900b57cec5SDimitry Andric BlockChain::iterator ChainEnd = Chain.end(); 29910b57cec5SDimitry Andric DupBB = *(--ChainEnd); 29920b57cec5SDimitry Andric // Now try to duplicate again. 29930b57cec5SDimitry Andric if (ChainEnd == Chain.begin()) 29940b57cec5SDimitry Andric break; 29950b57cec5SDimitry Andric DupPred = *std::prev(ChainEnd); 29960b57cec5SDimitry Andric Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, 29970b57cec5SDimitry Andric PrevUnplacedBlockIt, 29980b57cec5SDimitry Andric DuplicatedToLPred); 29990b57cec5SDimitry Andric } 30000b57cec5SDimitry Andric // If BB was duplicated into LPred, it is now scheduled. But because it was 30010b57cec5SDimitry Andric // removed, markChainSuccessors won't be called for its chain. Instead we 30020b57cec5SDimitry Andric // call markBlockSuccessors for LPred to achieve the same effect. This must go 30030b57cec5SDimitry Andric // at the end because repeating the tail duplication can increase the number 30040b57cec5SDimitry Andric // of unscheduled predecessors. 30050b57cec5SDimitry Andric LPred = *std::prev(Chain.end()); 30060b57cec5SDimitry Andric if (DuplicatedToOriginalLPred) 30070b57cec5SDimitry Andric markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); 30080b57cec5SDimitry Andric return true; 30090b57cec5SDimitry Andric } 30100b57cec5SDimitry Andric 30110b57cec5SDimitry Andric /// Tail duplicate \p BB into (some) predecessors if profitable. 30120b57cec5SDimitry Andric /// \p BB - Basic block that may be duplicated 30130b57cec5SDimitry Andric /// \p LPred - Chosen layout predecessor of \p BB 30140b57cec5SDimitry Andric /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. 30150b57cec5SDimitry Andric /// \p BlockFilter - Set of blocks that belong to the loop being laid out. 30160b57cec5SDimitry Andric /// Used to identify which blocks to update predecessor 30170b57cec5SDimitry Andric /// counts. 30180b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was 30190b57cec5SDimitry Andric /// chosen in the given order due to unnatural CFG 30200b57cec5SDimitry Andric /// only needed if \p BB is removed and 30210b57cec5SDimitry Andric /// \p PrevUnplacedBlockIt pointed to \p BB. 30225ffd83dbSDimitry Andric /// \p DuplicatedToLPred - True if the block was duplicated into LPred. 30230b57cec5SDimitry Andric /// \return - True if the block was duplicated into all preds and removed. 30240b57cec5SDimitry Andric bool MachineBlockPlacement::maybeTailDuplicateBlock( 30250b57cec5SDimitry Andric MachineBasicBlock *BB, MachineBasicBlock *LPred, 30260b57cec5SDimitry Andric BlockChain &Chain, BlockFilterSet *BlockFilter, 30270b57cec5SDimitry Andric MachineFunction::iterator &PrevUnplacedBlockIt, 30280b57cec5SDimitry Andric bool &DuplicatedToLPred) { 30290b57cec5SDimitry Andric DuplicatedToLPred = false; 30300b57cec5SDimitry Andric if (!shouldTailDuplicate(BB)) 30310b57cec5SDimitry Andric return false; 30320b57cec5SDimitry Andric 30330b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Redoing tail duplication for Succ#" << BB->getNumber() 30340b57cec5SDimitry Andric << "\n"); 30350b57cec5SDimitry Andric 30360b57cec5SDimitry Andric // This has to be a callback because none of it can be done after 30370b57cec5SDimitry Andric // BB is deleted. 30380b57cec5SDimitry Andric bool Removed = false; 30390b57cec5SDimitry Andric auto RemovalCallback = 30400b57cec5SDimitry Andric [&](MachineBasicBlock *RemBB) { 30410b57cec5SDimitry Andric // Signal to outer function 30420b57cec5SDimitry Andric Removed = true; 30430b57cec5SDimitry Andric 30440b57cec5SDimitry Andric // Conservative default. 30450b57cec5SDimitry Andric bool InWorkList = true; 30460b57cec5SDimitry Andric // Remove from the Chain and Chain Map 30470b57cec5SDimitry Andric if (BlockToChain.count(RemBB)) { 30480b57cec5SDimitry Andric BlockChain *Chain = BlockToChain[RemBB]; 30490b57cec5SDimitry Andric InWorkList = Chain->UnscheduledPredecessors == 0; 30500b57cec5SDimitry Andric Chain->remove(RemBB); 30510b57cec5SDimitry Andric BlockToChain.erase(RemBB); 30520b57cec5SDimitry Andric } 30530b57cec5SDimitry Andric 30540b57cec5SDimitry Andric // Handle the unplaced block iterator 30550b57cec5SDimitry Andric if (&(*PrevUnplacedBlockIt) == RemBB) { 30560b57cec5SDimitry Andric PrevUnplacedBlockIt++; 30570b57cec5SDimitry Andric } 30580b57cec5SDimitry Andric 30590b57cec5SDimitry Andric // Handle the Work Lists 30600b57cec5SDimitry Andric if (InWorkList) { 30610b57cec5SDimitry Andric SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; 30620b57cec5SDimitry Andric if (RemBB->isEHPad()) 30630b57cec5SDimitry Andric RemoveList = EHPadWorkList; 3064e8d8bef9SDimitry Andric llvm::erase_value(RemoveList, RemBB); 30650b57cec5SDimitry Andric } 30660b57cec5SDimitry Andric 30670b57cec5SDimitry Andric // Handle the filter set 30680b57cec5SDimitry Andric if (BlockFilter) { 30690b57cec5SDimitry Andric BlockFilter->remove(RemBB); 30700b57cec5SDimitry Andric } 30710b57cec5SDimitry Andric 30720b57cec5SDimitry Andric // Remove the block from loop info. 30730b57cec5SDimitry Andric MLI->removeBlock(RemBB); 30740b57cec5SDimitry Andric if (RemBB == PreferredLoopExit) 30750b57cec5SDimitry Andric PreferredLoopExit = nullptr; 30760b57cec5SDimitry Andric 30770b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "TailDuplicator deleted block: " 30780b57cec5SDimitry Andric << getBlockName(RemBB) << "\n"); 30790b57cec5SDimitry Andric }; 30800b57cec5SDimitry Andric auto RemovalCallbackRef = 30810b57cec5SDimitry Andric function_ref<void(MachineBasicBlock*)>(RemovalCallback); 30820b57cec5SDimitry Andric 30830b57cec5SDimitry Andric SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; 30840b57cec5SDimitry Andric bool IsSimple = TailDup.isSimpleBB(BB); 30855ffd83dbSDimitry Andric SmallVector<MachineBasicBlock *, 8> CandidatePreds; 30865ffd83dbSDimitry Andric SmallVectorImpl<MachineBasicBlock *> *CandidatePtr = nullptr; 30875ffd83dbSDimitry Andric if (F->getFunction().hasProfileData()) { 30885ffd83dbSDimitry Andric // We can do partial duplication with precise profile information. 30895ffd83dbSDimitry Andric findDuplicateCandidates(CandidatePreds, BB, BlockFilter); 30905ffd83dbSDimitry Andric if (CandidatePreds.size() == 0) 30915ffd83dbSDimitry Andric return false; 30925ffd83dbSDimitry Andric if (CandidatePreds.size() < BB->pred_size()) 30935ffd83dbSDimitry Andric CandidatePtr = &CandidatePreds; 30945ffd83dbSDimitry Andric } 30955ffd83dbSDimitry Andric TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, &DuplicatedPreds, 30965ffd83dbSDimitry Andric &RemovalCallbackRef, CandidatePtr); 30970b57cec5SDimitry Andric 30980b57cec5SDimitry Andric // Update UnscheduledPredecessors to reflect tail-duplication. 30990b57cec5SDimitry Andric DuplicatedToLPred = false; 31000b57cec5SDimitry Andric for (MachineBasicBlock *Pred : DuplicatedPreds) { 31010b57cec5SDimitry Andric // We're only looking for unscheduled predecessors that match the filter. 31020b57cec5SDimitry Andric BlockChain* PredChain = BlockToChain[Pred]; 31030b57cec5SDimitry Andric if (Pred == LPred) 31040b57cec5SDimitry Andric DuplicatedToLPred = true; 31050b57cec5SDimitry Andric if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) 31060b57cec5SDimitry Andric || PredChain == &Chain) 31070b57cec5SDimitry Andric continue; 31080b57cec5SDimitry Andric for (MachineBasicBlock *NewSucc : Pred->successors()) { 31090b57cec5SDimitry Andric if (BlockFilter && !BlockFilter->count(NewSucc)) 31100b57cec5SDimitry Andric continue; 31110b57cec5SDimitry Andric BlockChain *NewChain = BlockToChain[NewSucc]; 31120b57cec5SDimitry Andric if (NewChain != &Chain && NewChain != PredChain) 31130b57cec5SDimitry Andric NewChain->UnscheduledPredecessors++; 31140b57cec5SDimitry Andric } 31150b57cec5SDimitry Andric } 31160b57cec5SDimitry Andric return Removed; 31170b57cec5SDimitry Andric } 31180b57cec5SDimitry Andric 31195ffd83dbSDimitry Andric // Count the number of actual machine instructions. 31205ffd83dbSDimitry Andric static uint64_t countMBBInstruction(MachineBasicBlock *MBB) { 31215ffd83dbSDimitry Andric uint64_t InstrCount = 0; 31225ffd83dbSDimitry Andric for (MachineInstr &MI : *MBB) { 31235ffd83dbSDimitry Andric if (!MI.isPHI() && !MI.isMetaInstruction()) 31245ffd83dbSDimitry Andric InstrCount += 1; 31255ffd83dbSDimitry Andric } 31265ffd83dbSDimitry Andric return InstrCount; 31275ffd83dbSDimitry Andric } 31285ffd83dbSDimitry Andric 31295ffd83dbSDimitry Andric // The size cost of duplication is the instruction size of the duplicated block. 31305ffd83dbSDimitry Andric // So we should scale the threshold accordingly. But the instruction size is not 31315ffd83dbSDimitry Andric // available on all targets, so we use the number of instructions instead. 31325ffd83dbSDimitry Andric BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) { 31335ffd83dbSDimitry Andric return DupThreshold.getFrequency() * countMBBInstruction(BB); 31345ffd83dbSDimitry Andric } 31355ffd83dbSDimitry Andric 31365ffd83dbSDimitry Andric // Returns true if BB is Pred's best successor. 31375ffd83dbSDimitry Andric bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB, 31385ffd83dbSDimitry Andric MachineBasicBlock *Pred, 31395ffd83dbSDimitry Andric BlockFilterSet *BlockFilter) { 31405ffd83dbSDimitry Andric if (BB == Pred) 31415ffd83dbSDimitry Andric return false; 31425ffd83dbSDimitry Andric if (BlockFilter && !BlockFilter->count(Pred)) 31435ffd83dbSDimitry Andric return false; 31445ffd83dbSDimitry Andric BlockChain *PredChain = BlockToChain[Pred]; 31455ffd83dbSDimitry Andric if (PredChain && (Pred != *std::prev(PredChain->end()))) 31465ffd83dbSDimitry Andric return false; 31475ffd83dbSDimitry Andric 31485ffd83dbSDimitry Andric // Find the successor with largest probability excluding BB. 31495ffd83dbSDimitry Andric BranchProbability BestProb = BranchProbability::getZero(); 31505ffd83dbSDimitry Andric for (MachineBasicBlock *Succ : Pred->successors()) 31515ffd83dbSDimitry Andric if (Succ != BB) { 31525ffd83dbSDimitry Andric if (BlockFilter && !BlockFilter->count(Succ)) 31535ffd83dbSDimitry Andric continue; 31545ffd83dbSDimitry Andric BlockChain *SuccChain = BlockToChain[Succ]; 31555ffd83dbSDimitry Andric if (SuccChain && (Succ != *SuccChain->begin())) 31565ffd83dbSDimitry Andric continue; 31575ffd83dbSDimitry Andric BranchProbability SuccProb = MBPI->getEdgeProbability(Pred, Succ); 31585ffd83dbSDimitry Andric if (SuccProb > BestProb) 31595ffd83dbSDimitry Andric BestProb = SuccProb; 31605ffd83dbSDimitry Andric } 31615ffd83dbSDimitry Andric 31625ffd83dbSDimitry Andric BranchProbability BBProb = MBPI->getEdgeProbability(Pred, BB); 31635ffd83dbSDimitry Andric if (BBProb <= BestProb) 31645ffd83dbSDimitry Andric return false; 31655ffd83dbSDimitry Andric 31665ffd83dbSDimitry Andric // Compute the number of reduced taken branches if Pred falls through to BB 31675ffd83dbSDimitry Andric // instead of another successor. Then compare it with threshold. 3168e8d8bef9SDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 31695ffd83dbSDimitry Andric BlockFrequency Gain = PredFreq * (BBProb - BestProb); 31705ffd83dbSDimitry Andric return Gain > scaleThreshold(BB); 31715ffd83dbSDimitry Andric } 31725ffd83dbSDimitry Andric 31735ffd83dbSDimitry Andric // Find out the predecessors of BB and BB can be beneficially duplicated into 31745ffd83dbSDimitry Andric // them. 31755ffd83dbSDimitry Andric void MachineBlockPlacement::findDuplicateCandidates( 31765ffd83dbSDimitry Andric SmallVectorImpl<MachineBasicBlock *> &Candidates, 31775ffd83dbSDimitry Andric MachineBasicBlock *BB, 31785ffd83dbSDimitry Andric BlockFilterSet *BlockFilter) { 31795ffd83dbSDimitry Andric MachineBasicBlock *Fallthrough = nullptr; 31805ffd83dbSDimitry Andric BranchProbability DefaultBranchProb = BranchProbability::getZero(); 31815ffd83dbSDimitry Andric BlockFrequency BBDupThreshold(scaleThreshold(BB)); 3182e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> Preds(BB->predecessors()); 3183e8d8bef9SDimitry Andric SmallVector<MachineBasicBlock *, 8> Succs(BB->successors()); 31845ffd83dbSDimitry Andric 31855ffd83dbSDimitry Andric // Sort for highest frequency. 31865ffd83dbSDimitry Andric auto CmpSucc = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 31875ffd83dbSDimitry Andric return MBPI->getEdgeProbability(BB, A) > MBPI->getEdgeProbability(BB, B); 31885ffd83dbSDimitry Andric }; 31895ffd83dbSDimitry Andric auto CmpPred = [&](MachineBasicBlock *A, MachineBasicBlock *B) { 31905ffd83dbSDimitry Andric return MBFI->getBlockFreq(A) > MBFI->getBlockFreq(B); 31915ffd83dbSDimitry Andric }; 31925ffd83dbSDimitry Andric llvm::stable_sort(Succs, CmpSucc); 31935ffd83dbSDimitry Andric llvm::stable_sort(Preds, CmpPred); 31945ffd83dbSDimitry Andric 31955ffd83dbSDimitry Andric auto SuccIt = Succs.begin(); 31965ffd83dbSDimitry Andric if (SuccIt != Succs.end()) { 31975ffd83dbSDimitry Andric DefaultBranchProb = MBPI->getEdgeProbability(BB, *SuccIt).getCompl(); 31985ffd83dbSDimitry Andric } 31995ffd83dbSDimitry Andric 32005ffd83dbSDimitry Andric // For each predecessors of BB, compute the benefit of duplicating BB, 32015ffd83dbSDimitry Andric // if it is larger than the threshold, add it into Candidates. 32025ffd83dbSDimitry Andric // 32035ffd83dbSDimitry Andric // If we have following control flow. 32045ffd83dbSDimitry Andric // 32055ffd83dbSDimitry Andric // PB1 PB2 PB3 PB4 32065ffd83dbSDimitry Andric // \ | / /\ 32075ffd83dbSDimitry Andric // \ | / / \ 32085ffd83dbSDimitry Andric // \ |/ / \ 32095ffd83dbSDimitry Andric // BB----/ OB 32105ffd83dbSDimitry Andric // /\ 32115ffd83dbSDimitry Andric // / \ 32125ffd83dbSDimitry Andric // SB1 SB2 32135ffd83dbSDimitry Andric // 32145ffd83dbSDimitry Andric // And it can be partially duplicated as 32155ffd83dbSDimitry Andric // 32165ffd83dbSDimitry Andric // PB2+BB 32175ffd83dbSDimitry Andric // | PB1 PB3 PB4 32185ffd83dbSDimitry Andric // | | / /\ 32195ffd83dbSDimitry Andric // | | / / \ 32205ffd83dbSDimitry Andric // | |/ / \ 32215ffd83dbSDimitry Andric // | BB----/ OB 32225ffd83dbSDimitry Andric // |\ /| 32235ffd83dbSDimitry Andric // | X | 32245ffd83dbSDimitry Andric // |/ \| 32255ffd83dbSDimitry Andric // SB2 SB1 32265ffd83dbSDimitry Andric // 32275ffd83dbSDimitry Andric // The benefit of duplicating into a predecessor is defined as 32285ffd83dbSDimitry Andric // Orig_taken_branch - Duplicated_taken_branch 32295ffd83dbSDimitry Andric // 32305ffd83dbSDimitry Andric // The Orig_taken_branch is computed with the assumption that predecessor 32315ffd83dbSDimitry Andric // jumps to BB and the most possible successor is laid out after BB. 32325ffd83dbSDimitry Andric // 32335ffd83dbSDimitry Andric // The Duplicated_taken_branch is computed with the assumption that BB is 32345ffd83dbSDimitry Andric // duplicated into PB, and one successor is layout after it (SB1 for PB1 and 32355ffd83dbSDimitry Andric // SB2 for PB2 in our case). If there is no available successor, the combined 32365ffd83dbSDimitry Andric // block jumps to all BB's successor, like PB3 in this example. 32375ffd83dbSDimitry Andric // 32385ffd83dbSDimitry Andric // If a predecessor has multiple successors, so BB can't be duplicated into 32395ffd83dbSDimitry Andric // it. But it can beneficially fall through to BB, and duplicate BB into other 32405ffd83dbSDimitry Andric // predecessors. 32415ffd83dbSDimitry Andric for (MachineBasicBlock *Pred : Preds) { 3242e8d8bef9SDimitry Andric BlockFrequency PredFreq = getBlockCountOrFrequency(Pred); 32435ffd83dbSDimitry Andric 32445ffd83dbSDimitry Andric if (!TailDup.canTailDuplicate(BB, Pred)) { 32455ffd83dbSDimitry Andric // BB can't be duplicated into Pred, but it is possible to be layout 32465ffd83dbSDimitry Andric // below Pred. 32475ffd83dbSDimitry Andric if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) { 32485ffd83dbSDimitry Andric Fallthrough = Pred; 32495ffd83dbSDimitry Andric if (SuccIt != Succs.end()) 32505ffd83dbSDimitry Andric SuccIt++; 32515ffd83dbSDimitry Andric } 32525ffd83dbSDimitry Andric continue; 32535ffd83dbSDimitry Andric } 32545ffd83dbSDimitry Andric 32555ffd83dbSDimitry Andric BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb; 32565ffd83dbSDimitry Andric BlockFrequency DupCost; 32575ffd83dbSDimitry Andric if (SuccIt == Succs.end()) { 32585ffd83dbSDimitry Andric // Jump to all successors; 32595ffd83dbSDimitry Andric if (Succs.size() > 0) 32605ffd83dbSDimitry Andric DupCost += PredFreq; 32615ffd83dbSDimitry Andric } else { 32625ffd83dbSDimitry Andric // Fallthrough to *SuccIt, jump to all other successors; 32635ffd83dbSDimitry Andric DupCost += PredFreq; 32645ffd83dbSDimitry Andric DupCost -= PredFreq * MBPI->getEdgeProbability(BB, *SuccIt); 32655ffd83dbSDimitry Andric } 32665ffd83dbSDimitry Andric 32675ffd83dbSDimitry Andric assert(OrigCost >= DupCost); 32685ffd83dbSDimitry Andric OrigCost -= DupCost; 32695ffd83dbSDimitry Andric if (OrigCost > BBDupThreshold) { 32705ffd83dbSDimitry Andric Candidates.push_back(Pred); 32715ffd83dbSDimitry Andric if (SuccIt != Succs.end()) 32725ffd83dbSDimitry Andric SuccIt++; 32735ffd83dbSDimitry Andric } 32745ffd83dbSDimitry Andric } 32755ffd83dbSDimitry Andric 32765ffd83dbSDimitry Andric // No predecessors can optimally fallthrough to BB. 32775ffd83dbSDimitry Andric // So we can change one duplication into fallthrough. 32785ffd83dbSDimitry Andric if (!Fallthrough) { 32795ffd83dbSDimitry Andric if ((Candidates.size() < Preds.size()) && (Candidates.size() > 0)) { 32805ffd83dbSDimitry Andric Candidates[0] = Candidates.back(); 32815ffd83dbSDimitry Andric Candidates.pop_back(); 32825ffd83dbSDimitry Andric } 32835ffd83dbSDimitry Andric } 32845ffd83dbSDimitry Andric } 32855ffd83dbSDimitry Andric 32865ffd83dbSDimitry Andric void MachineBlockPlacement::initDupThreshold() { 32875ffd83dbSDimitry Andric DupThreshold = 0; 32885ffd83dbSDimitry Andric if (!F->getFunction().hasProfileData()) 32895ffd83dbSDimitry Andric return; 32905ffd83dbSDimitry Andric 3291e8d8bef9SDimitry Andric // We prefer to use prifile count. 3292e8d8bef9SDimitry Andric uint64_t HotThreshold = PSI->getOrCompHotCountThreshold(); 3293e8d8bef9SDimitry Andric if (HotThreshold != UINT64_MAX) { 3294e8d8bef9SDimitry Andric UseProfileCount = true; 3295e8d8bef9SDimitry Andric DupThreshold = HotThreshold * TailDupProfilePercentThreshold / 100; 3296e8d8bef9SDimitry Andric return; 3297e8d8bef9SDimitry Andric } 3298e8d8bef9SDimitry Andric 3299e8d8bef9SDimitry Andric // Profile count is not available, we can use block frequency instead. 33005ffd83dbSDimitry Andric BlockFrequency MaxFreq = 0; 33015ffd83dbSDimitry Andric for (MachineBasicBlock &MBB : *F) { 33025ffd83dbSDimitry Andric BlockFrequency Freq = MBFI->getBlockFreq(&MBB); 33035ffd83dbSDimitry Andric if (Freq > MaxFreq) 33045ffd83dbSDimitry Andric MaxFreq = Freq; 33055ffd83dbSDimitry Andric } 33065ffd83dbSDimitry Andric 33075ffd83dbSDimitry Andric BranchProbability ThresholdProb(TailDupPlacementPenalty, 100); 33085ffd83dbSDimitry Andric DupThreshold = MaxFreq * ThresholdProb; 3309e8d8bef9SDimitry Andric UseProfileCount = false; 33105ffd83dbSDimitry Andric } 33115ffd83dbSDimitry Andric 33120b57cec5SDimitry Andric bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { 33130b57cec5SDimitry Andric if (skipFunction(MF.getFunction())) 33140b57cec5SDimitry Andric return false; 33150b57cec5SDimitry Andric 33160b57cec5SDimitry Andric // Check for single-block functions and skip them. 33170b57cec5SDimitry Andric if (std::next(MF.begin()) == MF.end()) 33180b57cec5SDimitry Andric return false; 33190b57cec5SDimitry Andric 33200b57cec5SDimitry Andric F = &MF; 33210b57cec5SDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 33225ffd83dbSDimitry Andric MBFI = std::make_unique<MBFIWrapper>( 33230b57cec5SDimitry Andric getAnalysis<MachineBlockFrequencyInfo>()); 33240b57cec5SDimitry Andric MLI = &getAnalysis<MachineLoopInfo>(); 33250b57cec5SDimitry Andric TII = MF.getSubtarget().getInstrInfo(); 33260b57cec5SDimitry Andric TLI = MF.getSubtarget().getTargetLowering(); 33270b57cec5SDimitry Andric MPDT = nullptr; 3328480093f4SDimitry Andric PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 33290b57cec5SDimitry Andric 33305ffd83dbSDimitry Andric initDupThreshold(); 33315ffd83dbSDimitry Andric 33320b57cec5SDimitry Andric // Initialize PreferredLoopExit to nullptr here since it may never be set if 33330b57cec5SDimitry Andric // there are no MachineLoops. 33340b57cec5SDimitry Andric PreferredLoopExit = nullptr; 33350b57cec5SDimitry Andric 33360b57cec5SDimitry Andric assert(BlockToChain.empty() && 33370b57cec5SDimitry Andric "BlockToChain map should be empty before starting placement."); 33380b57cec5SDimitry Andric assert(ComputedEdges.empty() && 33390b57cec5SDimitry Andric "Computed Edge map should be empty before starting placement."); 33400b57cec5SDimitry Andric 33410b57cec5SDimitry Andric unsigned TailDupSize = TailDupPlacementThreshold; 33420b57cec5SDimitry Andric // If only the aggressive threshold is explicitly set, use it. 33430b57cec5SDimitry Andric if (TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0 && 33440b57cec5SDimitry Andric TailDupPlacementThreshold.getNumOccurrences() == 0) 33450b57cec5SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 33460b57cec5SDimitry Andric 33470b57cec5SDimitry Andric TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); 33480b57cec5SDimitry Andric // For aggressive optimization, we can adjust some thresholds to be less 33490b57cec5SDimitry Andric // conservative. 33500b57cec5SDimitry Andric if (PassConfig->getOptLevel() >= CodeGenOpt::Aggressive) { 33510b57cec5SDimitry Andric // At O3 we should be more willing to copy blocks for tail duplication. This 33520b57cec5SDimitry Andric // increases size pressure, so we only do it at O3 33530b57cec5SDimitry Andric // Do this unless only the regular threshold is explicitly set. 33540b57cec5SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 || 33550b57cec5SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() != 0) 33560b57cec5SDimitry Andric TailDupSize = TailDupPlacementAggressiveThreshold; 33570b57cec5SDimitry Andric } 33580b57cec5SDimitry Andric 3359fe6060f1SDimitry Andric // If there's no threshold provided through options, query the target 3360fe6060f1SDimitry Andric // information for a threshold instead. 3361fe6060f1SDimitry Andric if (TailDupPlacementThreshold.getNumOccurrences() == 0 && 3362fe6060f1SDimitry Andric (PassConfig->getOptLevel() < CodeGenOpt::Aggressive || 3363fe6060f1SDimitry Andric TailDupPlacementAggressiveThreshold.getNumOccurrences() == 0)) 3364fe6060f1SDimitry Andric TailDupSize = TII->getTailDuplicateSize(PassConfig->getOptLevel()); 3365fe6060f1SDimitry Andric 33660b57cec5SDimitry Andric if (allowTailDupPlacement()) { 33670b57cec5SDimitry Andric MPDT = &getAnalysis<MachinePostDominatorTree>(); 3368480093f4SDimitry Andric bool OptForSize = MF.getFunction().hasOptSize() || 3369480093f4SDimitry Andric llvm::shouldOptimizeForSize(&MF, PSI, &MBFI->getMBFI()); 3370480093f4SDimitry Andric if (OptForSize) 33710b57cec5SDimitry Andric TailDupSize = 1; 33720b57cec5SDimitry Andric bool PreRegAlloc = false; 33735ffd83dbSDimitry Andric TailDup.initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI, 3374480093f4SDimitry Andric /* LayoutMode */ true, TailDupSize); 33750b57cec5SDimitry Andric precomputeTriangleChains(); 33760b57cec5SDimitry Andric } 33770b57cec5SDimitry Andric 33780b57cec5SDimitry Andric buildCFGChains(); 33790b57cec5SDimitry Andric 33800b57cec5SDimitry Andric // Changing the layout can create new tail merging opportunities. 33810b57cec5SDimitry Andric // TailMerge can create jump into if branches that make CFG irreducible for 33820b57cec5SDimitry Andric // HW that requires structured CFG. 33830b57cec5SDimitry Andric bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && 33840b57cec5SDimitry Andric PassConfig->getEnableTailMerge() && 33850b57cec5SDimitry Andric BranchFoldPlacement; 33860b57cec5SDimitry Andric // No tail merging opportunities if the block number is less than four. 33870b57cec5SDimitry Andric if (MF.size() > 3 && EnableTailMerge) { 33880b57cec5SDimitry Andric unsigned TailMergeSize = TailDupSize + 1; 3389e8d8bef9SDimitry Andric BranchFolder BF(/*DefaultEnableTailMerge=*/true, /*CommonHoist=*/false, 3390e8d8bef9SDimitry Andric *MBFI, *MBPI, PSI, TailMergeSize); 33910b57cec5SDimitry Andric 33925ffd83dbSDimitry Andric if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), MLI, 33930b57cec5SDimitry Andric /*AfterPlacement=*/true)) { 33940b57cec5SDimitry Andric // Redo the layout if tail merging creates/removes/moves blocks. 33950b57cec5SDimitry Andric BlockToChain.clear(); 33960b57cec5SDimitry Andric ComputedEdges.clear(); 33970b57cec5SDimitry Andric // Must redo the post-dominator tree if blocks were changed. 33980b57cec5SDimitry Andric if (MPDT) 33990b57cec5SDimitry Andric MPDT->runOnMachineFunction(MF); 34000b57cec5SDimitry Andric ChainAllocator.DestroyAll(); 34010b57cec5SDimitry Andric buildCFGChains(); 34020b57cec5SDimitry Andric } 34030b57cec5SDimitry Andric } 34040b57cec5SDimitry Andric 3405*0eae32dcSDimitry Andric // Apply a post-processing optimizing block placement. 3406*0eae32dcSDimitry Andric if (MF.size() >= 3 && EnableExtTspBlockPlacement) { 3407*0eae32dcSDimitry Andric // Find a new placement and modify the layout of the blocks in the function. 3408*0eae32dcSDimitry Andric applyExtTsp(); 3409*0eae32dcSDimitry Andric 3410*0eae32dcSDimitry Andric // Re-create CFG chain so that we can optimizeBranches and alignBlocks. 3411*0eae32dcSDimitry Andric createCFGChainExtTsp(); 3412*0eae32dcSDimitry Andric } 3413*0eae32dcSDimitry Andric 34140b57cec5SDimitry Andric optimizeBranches(); 34150b57cec5SDimitry Andric alignBlocks(); 34160b57cec5SDimitry Andric 34170b57cec5SDimitry Andric BlockToChain.clear(); 34180b57cec5SDimitry Andric ComputedEdges.clear(); 34190b57cec5SDimitry Andric ChainAllocator.DestroyAll(); 34200b57cec5SDimitry Andric 34210b57cec5SDimitry Andric if (AlignAllBlock) 34220b57cec5SDimitry Andric // Align all of the blocks in the function to a specific alignment. 34230b57cec5SDimitry Andric for (MachineBasicBlock &MBB : MF) 34248bcb0991SDimitry Andric MBB.setAlignment(Align(1ULL << AlignAllBlock)); 34250b57cec5SDimitry Andric else if (AlignAllNonFallThruBlocks) { 34260b57cec5SDimitry Andric // Align all of the blocks that have no fall-through predecessors to a 34270b57cec5SDimitry Andric // specific alignment. 34280b57cec5SDimitry Andric for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { 34290b57cec5SDimitry Andric auto LayoutPred = std::prev(MBI); 34300b57cec5SDimitry Andric if (!LayoutPred->isSuccessor(&*MBI)) 34318bcb0991SDimitry Andric MBI->setAlignment(Align(1ULL << AlignAllNonFallThruBlocks)); 34320b57cec5SDimitry Andric } 34330b57cec5SDimitry Andric } 34340b57cec5SDimitry Andric if (ViewBlockLayoutWithBFI != GVDT_None && 34350b57cec5SDimitry Andric (ViewBlockFreqFuncName.empty() || 34360b57cec5SDimitry Andric F->getFunction().getName().equals(ViewBlockFreqFuncName))) { 34370b57cec5SDimitry Andric MBFI->view("MBP." + MF.getName(), false); 34380b57cec5SDimitry Andric } 34390b57cec5SDimitry Andric 34400b57cec5SDimitry Andric // We always return true as we have no way to track whether the final order 34410b57cec5SDimitry Andric // differs from the original order. 34420b57cec5SDimitry Andric return true; 34430b57cec5SDimitry Andric } 34440b57cec5SDimitry Andric 3445*0eae32dcSDimitry Andric void MachineBlockPlacement::applyExtTsp() { 3446*0eae32dcSDimitry Andric // Prepare data; blocks are indexed by their index in the current ordering. 3447*0eae32dcSDimitry Andric DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex; 3448*0eae32dcSDimitry Andric BlockIndex.reserve(F->size()); 3449*0eae32dcSDimitry Andric std::vector<const MachineBasicBlock *> CurrentBlockOrder; 3450*0eae32dcSDimitry Andric CurrentBlockOrder.reserve(F->size()); 3451*0eae32dcSDimitry Andric size_t NumBlocks = 0; 3452*0eae32dcSDimitry Andric for (const MachineBasicBlock &MBB : *F) { 3453*0eae32dcSDimitry Andric BlockIndex[&MBB] = NumBlocks++; 3454*0eae32dcSDimitry Andric CurrentBlockOrder.push_back(&MBB); 3455*0eae32dcSDimitry Andric } 3456*0eae32dcSDimitry Andric 3457*0eae32dcSDimitry Andric auto BlockSizes = std::vector<uint64_t>(F->size()); 3458*0eae32dcSDimitry Andric auto BlockCounts = std::vector<uint64_t>(F->size()); 3459*0eae32dcSDimitry Andric DenseMap<std::pair<uint64_t, uint64_t>, uint64_t> JumpCounts; 3460*0eae32dcSDimitry Andric for (MachineBasicBlock &MBB : *F) { 3461*0eae32dcSDimitry Andric // Getting the block frequency. 3462*0eae32dcSDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 3463*0eae32dcSDimitry Andric BlockCounts[BlockIndex[&MBB]] = BlockFreq.getFrequency(); 3464*0eae32dcSDimitry Andric // Getting the block size: 3465*0eae32dcSDimitry Andric // - approximate the size of an instruction by 4 bytes, and 3466*0eae32dcSDimitry Andric // - ignore debug instructions. 3467*0eae32dcSDimitry Andric // Note: getting the exact size of each block is target-dependent and can be 3468*0eae32dcSDimitry Andric // done by extending the interface of MCCodeEmitter. Experimentally we do 3469*0eae32dcSDimitry Andric // not see a perf improvement with the exact block sizes. 3470*0eae32dcSDimitry Andric auto NonDbgInsts = 3471*0eae32dcSDimitry Andric instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end()); 3472*0eae32dcSDimitry Andric int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end()); 3473*0eae32dcSDimitry Andric BlockSizes[BlockIndex[&MBB]] = 4 * NumInsts; 3474*0eae32dcSDimitry Andric // Getting jump frequencies. 3475*0eae32dcSDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) { 3476*0eae32dcSDimitry Andric auto EP = MBPI->getEdgeProbability(&MBB, Succ); 3477*0eae32dcSDimitry Andric BlockFrequency EdgeFreq = BlockFreq * EP; 3478*0eae32dcSDimitry Andric auto Edge = std::make_pair(BlockIndex[&MBB], BlockIndex[Succ]); 3479*0eae32dcSDimitry Andric JumpCounts[Edge] = EdgeFreq.getFrequency(); 3480*0eae32dcSDimitry Andric } 3481*0eae32dcSDimitry Andric } 3482*0eae32dcSDimitry Andric 3483*0eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << "Applying ext-tsp layout for |V| = " << F->size() 3484*0eae32dcSDimitry Andric << " with profile = " << F->getFunction().hasProfileData() 3485*0eae32dcSDimitry Andric << " (" << F->getName().str() << ")" 3486*0eae32dcSDimitry Andric << "\n"); 3487*0eae32dcSDimitry Andric LLVM_DEBUG( 3488*0eae32dcSDimitry Andric dbgs() << format(" original layout score: %0.2f\n", 3489*0eae32dcSDimitry Andric calcExtTspScore(BlockSizes, BlockCounts, JumpCounts))); 3490*0eae32dcSDimitry Andric 3491*0eae32dcSDimitry Andric // Run the layout algorithm. 3492*0eae32dcSDimitry Andric auto NewOrder = applyExtTspLayout(BlockSizes, BlockCounts, JumpCounts); 3493*0eae32dcSDimitry Andric std::vector<const MachineBasicBlock *> NewBlockOrder; 3494*0eae32dcSDimitry Andric NewBlockOrder.reserve(F->size()); 3495*0eae32dcSDimitry Andric for (uint64_t Node : NewOrder) { 3496*0eae32dcSDimitry Andric NewBlockOrder.push_back(CurrentBlockOrder[Node]); 3497*0eae32dcSDimitry Andric } 3498*0eae32dcSDimitry Andric LLVM_DEBUG(dbgs() << format(" optimized layout score: %0.2f\n", 3499*0eae32dcSDimitry Andric calcExtTspScore(NewOrder, BlockSizes, BlockCounts, 3500*0eae32dcSDimitry Andric JumpCounts))); 3501*0eae32dcSDimitry Andric 3502*0eae32dcSDimitry Andric // Assign new block order. 3503*0eae32dcSDimitry Andric assignBlockOrder(NewBlockOrder); 3504*0eae32dcSDimitry Andric } 3505*0eae32dcSDimitry Andric 3506*0eae32dcSDimitry Andric void MachineBlockPlacement::assignBlockOrder( 3507*0eae32dcSDimitry Andric const std::vector<const MachineBasicBlock *> &NewBlockOrder) { 3508*0eae32dcSDimitry Andric assert(F->size() == NewBlockOrder.size() && "Incorrect size of block order"); 3509*0eae32dcSDimitry Andric F->RenumberBlocks(); 3510*0eae32dcSDimitry Andric 3511*0eae32dcSDimitry Andric bool HasChanges = false; 3512*0eae32dcSDimitry Andric for (size_t I = 0; I < NewBlockOrder.size(); I++) { 3513*0eae32dcSDimitry Andric if (NewBlockOrder[I] != F->getBlockNumbered(I)) { 3514*0eae32dcSDimitry Andric HasChanges = true; 3515*0eae32dcSDimitry Andric break; 3516*0eae32dcSDimitry Andric } 3517*0eae32dcSDimitry Andric } 3518*0eae32dcSDimitry Andric // Stop early if the new block order is identical to the existing one. 3519*0eae32dcSDimitry Andric if (!HasChanges) 3520*0eae32dcSDimitry Andric return; 3521*0eae32dcSDimitry Andric 3522*0eae32dcSDimitry Andric SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(F->getNumBlockIDs()); 3523*0eae32dcSDimitry Andric for (auto &MBB : *F) { 3524*0eae32dcSDimitry Andric PrevFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 3525*0eae32dcSDimitry Andric } 3526*0eae32dcSDimitry Andric 3527*0eae32dcSDimitry Andric // Sort basic blocks in the function according to the computed order. 3528*0eae32dcSDimitry Andric DenseMap<const MachineBasicBlock *, size_t> NewIndex; 3529*0eae32dcSDimitry Andric for (const MachineBasicBlock *MBB : NewBlockOrder) { 3530*0eae32dcSDimitry Andric NewIndex[MBB] = NewIndex.size(); 3531*0eae32dcSDimitry Andric } 3532*0eae32dcSDimitry Andric F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) { 3533*0eae32dcSDimitry Andric return NewIndex[&L] < NewIndex[&R]; 3534*0eae32dcSDimitry Andric }); 3535*0eae32dcSDimitry Andric 3536*0eae32dcSDimitry Andric // Update basic block branches by inserting explicit fallthrough branches 3537*0eae32dcSDimitry Andric // when required and re-optimize branches when possible. 3538*0eae32dcSDimitry Andric const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo(); 3539*0eae32dcSDimitry Andric SmallVector<MachineOperand, 4> Cond; 3540*0eae32dcSDimitry Andric for (auto &MBB : *F) { 3541*0eae32dcSDimitry Andric MachineFunction::iterator NextMBB = std::next(MBB.getIterator()); 3542*0eae32dcSDimitry Andric MachineFunction::iterator EndIt = MBB.getParent()->end(); 3543*0eae32dcSDimitry Andric auto *FTMBB = PrevFallThroughs[MBB.getNumber()]; 3544*0eae32dcSDimitry Andric // If this block had a fallthrough before we need an explicit unconditional 3545*0eae32dcSDimitry Andric // branch to that block if the fallthrough block is not adjacent to the 3546*0eae32dcSDimitry Andric // block in the new order. 3547*0eae32dcSDimitry Andric if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) { 3548*0eae32dcSDimitry Andric TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 3549*0eae32dcSDimitry Andric } 3550*0eae32dcSDimitry Andric 3551*0eae32dcSDimitry Andric // It might be possible to optimize branches by flipping the condition. 3552*0eae32dcSDimitry Andric Cond.clear(); 3553*0eae32dcSDimitry Andric MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 3554*0eae32dcSDimitry Andric if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 3555*0eae32dcSDimitry Andric continue; 3556*0eae32dcSDimitry Andric MBB.updateTerminator(FTMBB); 3557*0eae32dcSDimitry Andric } 3558*0eae32dcSDimitry Andric 3559*0eae32dcSDimitry Andric #ifndef NDEBUG 3560*0eae32dcSDimitry Andric // Make sure we correctly constructed all branches. 3561*0eae32dcSDimitry Andric F->verify(this, "After optimized block reordering"); 3562*0eae32dcSDimitry Andric #endif 3563*0eae32dcSDimitry Andric } 3564*0eae32dcSDimitry Andric 3565*0eae32dcSDimitry Andric void MachineBlockPlacement::createCFGChainExtTsp() { 3566*0eae32dcSDimitry Andric BlockToChain.clear(); 3567*0eae32dcSDimitry Andric ComputedEdges.clear(); 3568*0eae32dcSDimitry Andric ChainAllocator.DestroyAll(); 3569*0eae32dcSDimitry Andric 3570*0eae32dcSDimitry Andric MachineBasicBlock *HeadBB = &F->front(); 3571*0eae32dcSDimitry Andric BlockChain *FunctionChain = 3572*0eae32dcSDimitry Andric new (ChainAllocator.Allocate()) BlockChain(BlockToChain, HeadBB); 3573*0eae32dcSDimitry Andric 3574*0eae32dcSDimitry Andric for (MachineBasicBlock &MBB : *F) { 3575*0eae32dcSDimitry Andric if (HeadBB == &MBB) 3576*0eae32dcSDimitry Andric continue; // Ignore head of the chain 3577*0eae32dcSDimitry Andric FunctionChain->merge(&MBB, nullptr); 3578*0eae32dcSDimitry Andric } 3579*0eae32dcSDimitry Andric } 3580*0eae32dcSDimitry Andric 35810b57cec5SDimitry Andric namespace { 35820b57cec5SDimitry Andric 35830b57cec5SDimitry Andric /// A pass to compute block placement statistics. 35840b57cec5SDimitry Andric /// 35850b57cec5SDimitry Andric /// A separate pass to compute interesting statistics for evaluating block 35860b57cec5SDimitry Andric /// placement. This is separate from the actual placement pass so that they can 35870b57cec5SDimitry Andric /// be computed in the absence of any placement transformations or when using 35880b57cec5SDimitry Andric /// alternative placement strategies. 35890b57cec5SDimitry Andric class MachineBlockPlacementStats : public MachineFunctionPass { 35900b57cec5SDimitry Andric /// A handle to the branch probability pass. 35910b57cec5SDimitry Andric const MachineBranchProbabilityInfo *MBPI; 35920b57cec5SDimitry Andric 35930b57cec5SDimitry Andric /// A handle to the function-wide block frequency pass. 35940b57cec5SDimitry Andric const MachineBlockFrequencyInfo *MBFI; 35950b57cec5SDimitry Andric 35960b57cec5SDimitry Andric public: 35970b57cec5SDimitry Andric static char ID; // Pass identification, replacement for typeid 35980b57cec5SDimitry Andric 35990b57cec5SDimitry Andric MachineBlockPlacementStats() : MachineFunctionPass(ID) { 36000b57cec5SDimitry Andric initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); 36010b57cec5SDimitry Andric } 36020b57cec5SDimitry Andric 36030b57cec5SDimitry Andric bool runOnMachineFunction(MachineFunction &F) override; 36040b57cec5SDimitry Andric 36050b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 36060b57cec5SDimitry Andric AU.addRequired<MachineBranchProbabilityInfo>(); 36070b57cec5SDimitry Andric AU.addRequired<MachineBlockFrequencyInfo>(); 36080b57cec5SDimitry Andric AU.setPreservesAll(); 36090b57cec5SDimitry Andric MachineFunctionPass::getAnalysisUsage(AU); 36100b57cec5SDimitry Andric } 36110b57cec5SDimitry Andric }; 36120b57cec5SDimitry Andric 36130b57cec5SDimitry Andric } // end anonymous namespace 36140b57cec5SDimitry Andric 36150b57cec5SDimitry Andric char MachineBlockPlacementStats::ID = 0; 36160b57cec5SDimitry Andric 36170b57cec5SDimitry Andric char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; 36180b57cec5SDimitry Andric 36190b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", 36200b57cec5SDimitry Andric "Basic Block Placement Stats", false, false) 36210b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 36220b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 36230b57cec5SDimitry Andric INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", 36240b57cec5SDimitry Andric "Basic Block Placement Stats", false, false) 36250b57cec5SDimitry Andric 36260b57cec5SDimitry Andric bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { 36270b57cec5SDimitry Andric // Check for single-block functions and skip them. 36280b57cec5SDimitry Andric if (std::next(F.begin()) == F.end()) 36290b57cec5SDimitry Andric return false; 36300b57cec5SDimitry Andric 36310b57cec5SDimitry Andric MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 36320b57cec5SDimitry Andric MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 36330b57cec5SDimitry Andric 36340b57cec5SDimitry Andric for (MachineBasicBlock &MBB : F) { 36350b57cec5SDimitry Andric BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); 36360b57cec5SDimitry Andric Statistic &NumBranches = 36370b57cec5SDimitry Andric (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; 36380b57cec5SDimitry Andric Statistic &BranchTakenFreq = 36390b57cec5SDimitry Andric (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; 36400b57cec5SDimitry Andric for (MachineBasicBlock *Succ : MBB.successors()) { 36410b57cec5SDimitry Andric // Skip if this successor is a fallthrough. 36420b57cec5SDimitry Andric if (MBB.isLayoutSuccessor(Succ)) 36430b57cec5SDimitry Andric continue; 36440b57cec5SDimitry Andric 36450b57cec5SDimitry Andric BlockFrequency EdgeFreq = 36460b57cec5SDimitry Andric BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); 36470b57cec5SDimitry Andric ++NumBranches; 36480b57cec5SDimitry Andric BranchTakenFreq += EdgeFreq.getFrequency(); 36490b57cec5SDimitry Andric } 36500b57cec5SDimitry Andric } 36510b57cec5SDimitry Andric 36520b57cec5SDimitry Andric return false; 36530b57cec5SDimitry Andric } 3654