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