Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1 | //===-- MachineBlockPlacement.cpp - Basic Block Code Layout optimization --===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 10 | // This file implements basic block placement transformations using the CFG |
| 11 | // structure and branch probability estimates. |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 12 | // |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 13 | // The pass strives to preserve the structure of the CFG (that is, retain |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 14 | // a topological ordering of basic blocks) in the absence of a *strong* signal |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 15 | // to the contrary from probabilities. However, within the CFG structure, it |
| 16 | // attempts to choose an ordering which favors placing more likely sequences of |
| 17 | // blocks adjacent to each other. |
| 18 | // |
| 19 | // The algorithm works from the inner-most loop within a function outward, and |
| 20 | // at each stage walks through the basic blocks, trying to coalesce them into |
| 21 | // sequential chains where allowed by the CFG (or demanded by heavy |
| 22 | // probabilities). Finally, it walks the blocks in topological order, and the |
| 23 | // first time it reaches a chain of basic blocks, it schedules them in the |
| 24 | // function in-order. |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 25 | // |
| 26 | //===----------------------------------------------------------------------===// |
| 27 | |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 28 | #include "llvm/CodeGen/Passes.h" |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 29 | #include "llvm/CodeGen/TargetPassConfig.h" |
| 30 | #include "BranchFolding.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 31 | #include "llvm/ADT/DenseMap.h" |
| 32 | #include "llvm/ADT/SmallPtrSet.h" |
| 33 | #include "llvm/ADT/SmallVector.h" |
| 34 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 35 | #include "llvm/CodeGen/MachineBasicBlock.h" |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 36 | #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" |
| 37 | #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 38 | #include "llvm/CodeGen/MachineDominators.h" |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 39 | #include "llvm/CodeGen/MachineFunction.h" |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 40 | #include "llvm/CodeGen/MachineFunctionPass.h" |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 41 | #include "llvm/CodeGen/MachineLoopInfo.h" |
| 42 | #include "llvm/CodeGen/MachineModuleInfo.h" |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 43 | #include "llvm/CodeGen/TailDuplicator.h" |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 44 | #include "llvm/Support/Allocator.h" |
Nadav Rotem | c3b0f50 | 2013-04-12 00:48:32 +0000 | [diff] [blame] | 45 | #include "llvm/Support/CommandLine.h" |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 46 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 47 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 48 | #include "llvm/Target/TargetInstrInfo.h" |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 49 | #include "llvm/Target/TargetLowering.h" |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 50 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 51 | #include <algorithm> |
| 52 | using namespace llvm; |
| 53 | |
Chandler Carruth | d0dced5 | 2015-03-05 02:28:25 +0000 | [diff] [blame] | 54 | #define DEBUG_TYPE "block-placement" |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 55 | |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 56 | STATISTIC(NumCondBranches, "Number of conditional branches"); |
Craig Topper | 77ec077 | 2015-09-16 03:52:32 +0000 | [diff] [blame] | 57 | STATISTIC(NumUncondBranches, "Number of unconditional branches"); |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 58 | STATISTIC(CondBranchTakenFreq, |
| 59 | "Potential frequency of taking conditional branches"); |
| 60 | STATISTIC(UncondBranchTakenFreq, |
| 61 | "Potential frequency of taking unconditional branches"); |
| 62 | |
Nadav Rotem | c3b0f50 | 2013-04-12 00:48:32 +0000 | [diff] [blame] | 63 | static cl::opt<unsigned> AlignAllBlock("align-all-blocks", |
| 64 | cl::desc("Force the alignment of all " |
| 65 | "blocks in the function."), |
| 66 | cl::init(0), cl::Hidden); |
| 67 | |
Geoff Berry | 10494ac | 2016-01-21 17:25:52 +0000 | [diff] [blame] | 68 | static cl::opt<unsigned> AlignAllNonFallThruBlocks( |
| 69 | "align-all-nofallthru-blocks", |
| 70 | cl::desc("Force the alignment of all " |
| 71 | "blocks that have no fall-through predecessors (i.e. don't add " |
| 72 | "nops that are executed)."), |
| 73 | cl::init(0), cl::Hidden); |
| 74 | |
Benjamin Kramer | c8160d6 | 2013-11-20 19:08:44 +0000 | [diff] [blame] | 75 | // FIXME: Find a good default for this flag and remove the flag. |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 76 | static cl::opt<unsigned> ExitBlockBias( |
| 77 | "block-placement-exit-block-bias", |
| 78 | cl::desc("Block frequency percentage a loop exit block needs " |
| 79 | "over the original exit to be considered the new exit."), |
| 80 | cl::init(0), cl::Hidden); |
Benjamin Kramer | c8160d6 | 2013-11-20 19:08:44 +0000 | [diff] [blame] | 81 | |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 82 | // Definition: |
| 83 | // - Outlining: placement of a basic block outside the chain or hot path. |
| 84 | |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 85 | static cl::opt<bool> OutlineOptionalBranches( |
| 86 | "outline-optional-branches", |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 87 | cl::desc("Outlining optional branches will place blocks that are optional " |
| 88 | "branches, i.e. branches with a common post dominator, outside " |
| 89 | "the hot path or chain"), |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 90 | cl::init(false), cl::Hidden); |
| 91 | |
Daniel Jasper | 214997c | 2015-03-20 10:00:37 +0000 | [diff] [blame] | 92 | static cl::opt<unsigned> OutlineOptionalThreshold( |
| 93 | "outline-optional-threshold", |
| 94 | cl::desc("Don't outline optional branches that are a single block with an " |
| 95 | "instruction count below this threshold"), |
| 96 | cl::init(4), cl::Hidden); |
| 97 | |
Cong Hou | b90b9e0 | 2015-11-02 21:24:00 +0000 | [diff] [blame] | 98 | static cl::opt<unsigned> LoopToColdBlockRatio( |
| 99 | "loop-to-cold-block-ratio", |
| 100 | cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " |
| 101 | "(frequency of block) is greater than this ratio"), |
| 102 | cl::init(5), cl::Hidden); |
| 103 | |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 104 | static cl::opt<bool> |
| 105 | PreciseRotationCost("precise-rotation-cost", |
| 106 | cl::desc("Model the cost of loop rotation more " |
| 107 | "precisely by using profile data."), |
| 108 | cl::init(false), cl::Hidden); |
Xinliang David Li | f0ab6df | 2016-05-12 02:04:41 +0000 | [diff] [blame] | 109 | static cl::opt<bool> |
| 110 | ForcePreciseRotationCost("force-precise-rotation-cost", |
Xinliang David Li | b840bb8 | 2016-05-12 16:39:02 +0000 | [diff] [blame] | 111 | cl::desc("Force the use of precise cost " |
| 112 | "loop rotation strategy."), |
Xinliang David Li | f0ab6df | 2016-05-12 02:04:41 +0000 | [diff] [blame] | 113 | cl::init(false), cl::Hidden); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 114 | |
| 115 | static cl::opt<unsigned> MisfetchCost( |
| 116 | "misfetch-cost", |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 117 | cl::desc("Cost that models the probabilistic risk of an instruction " |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 118 | "misfetch due to a jump comparing to falling through, whose cost " |
| 119 | "is zero."), |
| 120 | cl::init(1), cl::Hidden); |
| 121 | |
| 122 | static cl::opt<unsigned> JumpInstCost("jump-inst-cost", |
| 123 | cl::desc("Cost of jump instructions."), |
| 124 | cl::init(1), cl::Hidden); |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 125 | static cl::opt<bool> |
| 126 | TailDupPlacement("tail-dup-placement", |
| 127 | cl::desc("Perform tail duplication during placement. " |
| 128 | "Creates more fallthrough opportunites in " |
| 129 | "outline branches."), |
| 130 | cl::init(true), cl::Hidden); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 131 | |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 132 | static cl::opt<bool> |
| 133 | BranchFoldPlacement("branch-fold-placement", |
| 134 | cl::desc("Perform branch folding during placement. " |
| 135 | "Reduces code size."), |
| 136 | cl::init(true), cl::Hidden); |
| 137 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 138 | // Heuristic for tail duplication. |
| 139 | static cl::opt<unsigned> TailDuplicatePlacementThreshold( |
| 140 | "tail-dup-placement-threshold", |
| 141 | cl::desc("Instruction cutoff for tail duplication during layout. " |
| 142 | "Tail merging during layout is forced to have a threshold " |
| 143 | "that won't conflict."), cl::init(2), |
| 144 | cl::Hidden); |
| 145 | |
Xinliang David Li | ff28737 | 2016-06-03 23:48:36 +0000 | [diff] [blame] | 146 | extern cl::opt<unsigned> StaticLikelyProb; |
Dehao Chen | 9f2bdfb | 2016-06-14 22:27:17 +0000 | [diff] [blame] | 147 | extern cl::opt<unsigned> ProfileLikelyProb; |
Xinliang David Li | ff28737 | 2016-06-03 23:48:36 +0000 | [diff] [blame] | 148 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 149 | namespace { |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 150 | class BlockChain; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 151 | /// \brief Type for our function-wide basic block -> block chain mapping. |
| 152 | typedef DenseMap<MachineBasicBlock *, BlockChain *> BlockToChainMapType; |
| 153 | } |
| 154 | |
| 155 | namespace { |
| 156 | /// \brief A chain of blocks which will be laid out contiguously. |
| 157 | /// |
| 158 | /// This is the datastructure representing a chain of consecutive blocks that |
| 159 | /// are profitable to layout together in order to maximize fallthrough |
Chandler Carruth | 9139f44 | 2012-06-26 05:16:37 +0000 | [diff] [blame] | 160 | /// probabilities and code locality. We also can use a block chain to represent |
| 161 | /// a sequence of basic blocks which have some external (correctness) |
| 162 | /// requirement for sequential layout. |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 163 | /// |
Chandler Carruth | 9139f44 | 2012-06-26 05:16:37 +0000 | [diff] [blame] | 164 | /// Chains can be built around a single basic block and can be merged to grow |
| 165 | /// them. They participate in a block-to-chain mapping, which is updated |
| 166 | /// automatically as chains are merged together. |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 167 | class BlockChain { |
| 168 | /// \brief The sequence of blocks belonging to this chain. |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 169 | /// |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 170 | /// This is the sequence of blocks for a particular chain. These will be laid |
| 171 | /// out in-order within the function. |
| 172 | SmallVector<MachineBasicBlock *, 4> Blocks; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 173 | |
| 174 | /// \brief A handle to the function-wide basic block to block chain mapping. |
| 175 | /// |
| 176 | /// This is retained in each block chain to simplify the computation of child |
| 177 | /// block chains for SCC-formation and iteration. We store the edges to child |
| 178 | /// basic blocks, and map them back to their associated chains using this |
| 179 | /// structure. |
| 180 | BlockToChainMapType &BlockToChain; |
| 181 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 182 | public: |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 183 | /// \brief Construct a new BlockChain. |
| 184 | /// |
| 185 | /// This builds a new block chain representing a single basic block in the |
| 186 | /// function. It also registers itself as the chain that block participates |
| 187 | /// in with the BlockToChain mapping. |
| 188 | BlockChain(BlockToChainMapType &BlockToChain, MachineBasicBlock *BB) |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 189 | : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) { |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 190 | assert(BB && "Cannot create a chain with a null basic block"); |
| 191 | BlockToChain[BB] = this; |
| 192 | } |
| 193 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 194 | /// \brief Iterator over blocks within the chain. |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 195 | typedef SmallVectorImpl<MachineBasicBlock *>::iterator iterator; |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 196 | |
| 197 | /// \brief Beginning of blocks within the chain. |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 198 | iterator begin() { return Blocks.begin(); } |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 199 | |
| 200 | /// \brief End of blocks within the chain. |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 201 | iterator end() { return Blocks.end(); } |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 202 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 203 | bool remove(MachineBasicBlock* BB) { |
| 204 | for(iterator i = begin(); i != end(); ++i) { |
| 205 | if (*i == BB) { |
| 206 | Blocks.erase(i); |
| 207 | return true; |
| 208 | } |
| 209 | } |
| 210 | return false; |
| 211 | } |
| 212 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 213 | /// \brief Merge a block chain into this one. |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 214 | /// |
| 215 | /// This routine merges a block chain into this one. It takes care of forming |
| 216 | /// a contiguous sequence of basic blocks, updating the edge list, and |
| 217 | /// updating the block -> chain mapping. It does not free or tear down the |
| 218 | /// old chain, but the old chain's block list is no longer valid. |
Jakub Staszak | 9061616 | 2011-12-21 23:02:08 +0000 | [diff] [blame] | 219 | void merge(MachineBasicBlock *BB, BlockChain *Chain) { |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 220 | assert(BB); |
| 221 | assert(!Blocks.empty()); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 222 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 223 | // Fast path in case we don't have a chain already. |
| 224 | if (!Chain) { |
| 225 | assert(!BlockToChain[BB]); |
| 226 | Blocks.push_back(BB); |
| 227 | BlockToChain[BB] = this; |
| 228 | return; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 229 | } |
| 230 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 231 | assert(BB == *Chain->begin()); |
| 232 | assert(Chain->begin() != Chain->end()); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 233 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 234 | // Update the incoming blocks to point to this chain, and add them to the |
| 235 | // chain structure. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 236 | for (MachineBasicBlock *ChainBB : *Chain) { |
| 237 | Blocks.push_back(ChainBB); |
| 238 | assert(BlockToChain[ChainBB] == Chain && "Incoming blocks not in chain"); |
| 239 | BlockToChain[ChainBB] = this; |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 240 | } |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 241 | } |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 242 | |
Chandler Carruth | 4915890 | 2012-04-08 14:37:01 +0000 | [diff] [blame] | 243 | #ifndef NDEBUG |
| 244 | /// \brief Dump the blocks in this chain. |
Nico Weber | 7408c70 | 2014-01-03 22:53:37 +0000 | [diff] [blame] | 245 | LLVM_DUMP_METHOD void dump() { |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 246 | for (MachineBasicBlock *MBB : *this) |
| 247 | MBB->dump(); |
Chandler Carruth | 4915890 | 2012-04-08 14:37:01 +0000 | [diff] [blame] | 248 | } |
| 249 | #endif // NDEBUG |
| 250 | |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 251 | /// \brief Count of predecessors of any block within the chain which have not |
| 252 | /// yet been scheduled. In general, we will delay scheduling this chain |
| 253 | /// until those predecessors are scheduled (or we find a sufficiently good |
| 254 | /// reason to override this heuristic.) Note that when forming loop chains, |
| 255 | /// blocks outside the loop are ignored and treated as if they were already |
| 256 | /// scheduled. |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 257 | /// |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 258 | /// Note: This field is reinitialized multiple times - once for each loop, |
| 259 | /// and then once for the function as a whole. |
| 260 | unsigned UnscheduledPredecessors; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 261 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 262 | } |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 263 | |
| 264 | namespace { |
| 265 | class MachineBlockPlacement : public MachineFunctionPass { |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 266 | /// \brief A typedef for a block filter set. |
| 267 | typedef SmallPtrSet<MachineBasicBlock *, 16> BlockFilterSet; |
| 268 | |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 269 | /// \brief work lists of blocks that are ready to be laid out |
| 270 | SmallVector<MachineBasicBlock *, 16> BlockWorkList; |
| 271 | SmallVector<MachineBasicBlock *, 16> EHPadWorkList; |
| 272 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 273 | /// \brief Machine Function |
| 274 | MachineFunction *F; |
| 275 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 276 | /// \brief A handle to the branch probability pass. |
| 277 | const MachineBranchProbabilityInfo *MBPI; |
| 278 | |
| 279 | /// \brief A handle to the function-wide block frequency pass. |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 280 | std::unique_ptr<BranchFolder::MBFIWrapper> MBFI; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 281 | |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 282 | /// \brief A handle to the loop info. |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 283 | MachineLoopInfo *MLI; |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 284 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 285 | /// \brief A handle to the target's instruction info. |
| 286 | const TargetInstrInfo *TII; |
| 287 | |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 288 | /// \brief A handle to the target's lowering info. |
Benjamin Kramer | 56b31bd | 2013-01-11 20:05:37 +0000 | [diff] [blame] | 289 | const TargetLoweringBase *TLI; |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 290 | |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 291 | /// \brief A handle to the post dominator tree. |
| 292 | MachineDominatorTree *MDT; |
| 293 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 294 | /// \brief Duplicator used to duplicate tails during placement. |
| 295 | /// |
| 296 | /// Placement decisions can open up new tail duplication opportunities, but |
| 297 | /// since tail duplication affects placement decisions of later blocks, it |
| 298 | /// must be done inline. |
| 299 | TailDuplicator TailDup; |
| 300 | |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 301 | /// \brief A set of blocks that are unavoidably execute, i.e. they dominate |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 302 | /// all terminators of the MachineFunction. |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 303 | SmallPtrSet<MachineBasicBlock *, 4> UnavoidableBlocks; |
| 304 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 305 | /// \brief Allocator and owner of BlockChain structures. |
| 306 | /// |
Chandler Carruth | 9139f44 | 2012-06-26 05:16:37 +0000 | [diff] [blame] | 307 | /// We build BlockChains lazily while processing the loop structure of |
| 308 | /// a function. To reduce malloc traffic, we allocate them using this |
| 309 | /// slab-like allocator, and destroy them after the pass completes. An |
| 310 | /// important guarantee is that this allocator produces stable pointers to |
| 311 | /// the chains. |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 312 | SpecificBumpPtrAllocator<BlockChain> ChainAllocator; |
| 313 | |
| 314 | /// \brief Function wide BasicBlock to BlockChain mapping. |
| 315 | /// |
| 316 | /// This mapping allows efficiently moving from any given basic block to the |
| 317 | /// BlockChain it participates in, if any. We use it to, among other things, |
| 318 | /// allow implicitly defining edges between chains as the existing edges |
| 319 | /// between basic blocks. |
| 320 | DenseMap<MachineBasicBlock *, BlockChain *> BlockToChain; |
| 321 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 322 | /// Decrease the UnscheduledPredecessors count for all blocks in chain, and |
| 323 | /// if the count goes to 0, add them to the appropriate work list. |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 324 | void markChainSuccessors(BlockChain &Chain, MachineBasicBlock *LoopHeaderBB, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 325 | const BlockFilterSet *BlockFilter = nullptr); |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 326 | |
| 327 | /// Decrease the UnscheduledPredecessors count for a single block, and |
| 328 | /// if the count goes to 0, add them to the appropriate work list. |
| 329 | void markBlockSuccessors( |
| 330 | BlockChain &Chain, MachineBasicBlock *BB, MachineBasicBlock *LoopHeaderBB, |
| 331 | const BlockFilterSet *BlockFilter = nullptr); |
| 332 | |
| 333 | |
Xinliang David Li | 594ffa3 | 2016-06-11 18:35:40 +0000 | [diff] [blame] | 334 | BranchProbability |
| 335 | collectViableSuccessors(MachineBasicBlock *BB, BlockChain &Chain, |
| 336 | const BlockFilterSet *BlockFilter, |
| 337 | SmallVector<MachineBasicBlock *, 4> &Successors); |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 338 | bool shouldPredBlockBeOutlined(MachineBasicBlock *BB, MachineBasicBlock *Succ, |
| 339 | BlockChain &Chain, |
| 340 | const BlockFilterSet *BlockFilter, |
| 341 | BranchProbability SuccProb, |
| 342 | BranchProbability HotProb); |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 343 | bool repeatedlyTailDuplicateBlock( |
| 344 | MachineBasicBlock *BB, MachineBasicBlock *&LPred, |
| 345 | MachineBasicBlock *LoopHeaderBB, |
| 346 | BlockChain &Chain, BlockFilterSet *BlockFilter, |
| 347 | MachineFunction::iterator &PrevUnplacedBlockIt); |
| 348 | bool maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred, |
| 349 | const BlockChain &Chain, |
| 350 | BlockFilterSet *BlockFilter, |
| 351 | MachineFunction::iterator &PrevUnplacedBlockIt, |
| 352 | bool &DuplicatedToPred); |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 353 | bool |
| 354 | hasBetterLayoutPredecessor(MachineBasicBlock *BB, MachineBasicBlock *Succ, |
| 355 | BlockChain &SuccChain, BranchProbability SuccProb, |
| 356 | BranchProbability RealSuccProb, BlockChain &Chain, |
| 357 | const BlockFilterSet *BlockFilter); |
Jakub Staszak | 9061616 | 2011-12-21 23:02:08 +0000 | [diff] [blame] | 358 | MachineBasicBlock *selectBestSuccessor(MachineBasicBlock *BB, |
| 359 | BlockChain &Chain, |
| 360 | const BlockFilterSet *BlockFilter); |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 361 | MachineBasicBlock * |
| 362 | selectBestCandidateBlock(BlockChain &Chain, |
Amaury Sechet | 9ee4ddd | 2016-04-07 06:34:47 +0000 | [diff] [blame] | 363 | SmallVectorImpl<MachineBasicBlock *> &WorkList); |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 364 | MachineBasicBlock * |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 365 | getFirstUnplacedBlock(const BlockChain &PlacedChain, |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 366 | MachineFunction::iterator &PrevUnplacedBlockIt, |
| 367 | const BlockFilterSet *BlockFilter); |
Amaury Sechet | eae09c2 | 2016-03-14 21:24:11 +0000 | [diff] [blame] | 368 | |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 369 | /// \brief Add a basic block to the work list if it is appropriate. |
Amaury Sechet | eae09c2 | 2016-03-14 21:24:11 +0000 | [diff] [blame] | 370 | /// |
| 371 | /// If the optional parameter BlockFilter is provided, only MBB |
| 372 | /// present in the set will be added to the worklist. If nullptr |
| 373 | /// is provided, no filtering occurs. |
| 374 | void fillWorkLists(MachineBasicBlock *MBB, |
| 375 | SmallPtrSetImpl<BlockChain *> &UpdatedPreds, |
Amaury Sechet | eae09c2 | 2016-03-14 21:24:11 +0000 | [diff] [blame] | 376 | const BlockFilterSet *BlockFilter); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 377 | void buildChain(MachineBasicBlock *BB, BlockChain &Chain, |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 378 | BlockFilterSet *BlockFilter = nullptr); |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 379 | MachineBasicBlock *findBestLoopTop(MachineLoop &L, |
| 380 | const BlockFilterSet &LoopBlockSet); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 381 | MachineBasicBlock *findBestLoopExit(MachineLoop &L, |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 382 | const BlockFilterSet &LoopBlockSet); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 383 | BlockFilterSet collectLoopBlockSet(MachineLoop &L); |
| 384 | void buildLoopChains(MachineLoop &L); |
Chandler Carruth | 8c74c7b | 2012-04-16 09:31:23 +0000 | [diff] [blame] | 385 | void rotateLoop(BlockChain &LoopChain, MachineBasicBlock *ExitingBB, |
| 386 | const BlockFilterSet &LoopBlockSet); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 387 | void rotateLoopWithProfile(BlockChain &LoopChain, MachineLoop &L, |
| 388 | const BlockFilterSet &LoopBlockSet); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 389 | void collectMustExecuteBBs(); |
| 390 | void buildCFGChains(); |
| 391 | void optimizeBranches(); |
| 392 | void alignBlocks(); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 393 | |
| 394 | public: |
| 395 | static char ID; // Pass identification, replacement for typeid |
| 396 | MachineBlockPlacement() : MachineFunctionPass(ID) { |
| 397 | initializeMachineBlockPlacementPass(*PassRegistry::getPassRegistry()); |
| 398 | } |
| 399 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 400 | bool runOnMachineFunction(MachineFunction &F) override; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 401 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 402 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 403 | AU.addRequired<MachineBranchProbabilityInfo>(); |
| 404 | AU.addRequired<MachineBlockFrequencyInfo>(); |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 405 | AU.addRequired<MachineDominatorTree>(); |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 406 | AU.addRequired<MachineLoopInfo>(); |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 407 | AU.addRequired<TargetPassConfig>(); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 408 | MachineFunctionPass::getAnalysisUsage(AU); |
| 409 | } |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 410 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 411 | } |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 412 | |
| 413 | char MachineBlockPlacement::ID = 0; |
Andrew Trick | 1fa5bcb | 2012-02-08 21:23:13 +0000 | [diff] [blame] | 414 | char &llvm::MachineBlockPlacementID = MachineBlockPlacement::ID; |
Chandler Carruth | d0dced5 | 2015-03-05 02:28:25 +0000 | [diff] [blame] | 415 | INITIALIZE_PASS_BEGIN(MachineBlockPlacement, "block-placement", |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 416 | "Branch Probability Basic Block Placement", false, false) |
| 417 | INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) |
| 418 | INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 419 | INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 420 | INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) |
Chandler Carruth | d0dced5 | 2015-03-05 02:28:25 +0000 | [diff] [blame] | 421 | INITIALIZE_PASS_END(MachineBlockPlacement, "block-placement", |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 422 | "Branch Probability Basic Block Placement", false, false) |
| 423 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 424 | #ifndef NDEBUG |
| 425 | /// \brief Helper to print the name of a MBB. |
| 426 | /// |
| 427 | /// Only used by debug logging. |
Jakub Staszak | 9061616 | 2011-12-21 23:02:08 +0000 | [diff] [blame] | 428 | static std::string getBlockName(MachineBasicBlock *BB) { |
Alp Toker | e69170a | 2014-06-26 22:52:05 +0000 | [diff] [blame] | 429 | std::string Result; |
| 430 | raw_string_ostream OS(Result); |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 431 | OS << "BB#" << BB->getNumber(); |
Philip Reames | b9688f4 | 2016-03-02 21:45:13 +0000 | [diff] [blame] | 432 | OS << " ('" << BB->getName() << "')"; |
Alp Toker | e69170a | 2014-06-26 22:52:05 +0000 | [diff] [blame] | 433 | OS.flush(); |
| 434 | return Result; |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 435 | } |
| 436 | #endif |
| 437 | |
Chandler Carruth | eb4ec3a | 2011-11-13 11:34:55 +0000 | [diff] [blame] | 438 | /// \brief Mark a chain's successors as having one fewer preds. |
| 439 | /// |
| 440 | /// When a chain is being merged into the "placed" chain, this routine will |
| 441 | /// quickly walk the successors of each block in the chain and mark them as |
| 442 | /// having one fewer active predecessor. It also adds any successors of this |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 443 | /// chain which reach the zero-predecessor state to the appropriate worklist. |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 444 | void MachineBlockPlacement::markChainSuccessors( |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 445 | BlockChain &Chain, MachineBasicBlock *LoopHeaderBB, |
Jakub Staszak | 9061616 | 2011-12-21 23:02:08 +0000 | [diff] [blame] | 446 | const BlockFilterSet *BlockFilter) { |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 447 | // Walk all the blocks in this chain, marking their successors as having |
| 448 | // a predecessor placed. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 449 | for (MachineBasicBlock *MBB : Chain) { |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 450 | markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter); |
| 451 | } |
| 452 | } |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 453 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 454 | /// \brief Mark a single block's successors as having one fewer preds. |
| 455 | /// |
| 456 | /// Under normal circumstances, this is only called by markChainSuccessors, |
| 457 | /// but if a block that was to be placed is completely tail-duplicated away, |
| 458 | /// and was duplicated into the chain end, we need to redo markBlockSuccessors |
| 459 | /// for just that block. |
| 460 | void MachineBlockPlacement::markBlockSuccessors( |
| 461 | BlockChain &Chain, MachineBasicBlock *MBB, MachineBasicBlock *LoopHeaderBB, |
| 462 | const BlockFilterSet *BlockFilter) { |
| 463 | // Add any successors for which this is the only un-placed in-loop |
| 464 | // predecessor to the worklist as a viable candidate for CFG-neutral |
| 465 | // placement. No subsequent placement of this block will violate the CFG |
| 466 | // shape, so we get to use heuristics to choose a favorable placement. |
| 467 | for (MachineBasicBlock *Succ : MBB->successors()) { |
| 468 | if (BlockFilter && !BlockFilter->count(Succ)) |
| 469 | continue; |
| 470 | BlockChain &SuccChain = *BlockToChain[Succ]; |
| 471 | // Disregard edges within a fixed chain, or edges to the loop header. |
| 472 | if (&Chain == &SuccChain || Succ == LoopHeaderBB) |
| 473 | continue; |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 474 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 475 | // This is a cross-chain edge that is within the loop, so decrement the |
| 476 | // loop predecessor count of the destination chain. |
| 477 | if (SuccChain.UnscheduledPredecessors == 0 || |
| 478 | --SuccChain.UnscheduledPredecessors > 0) |
| 479 | continue; |
| 480 | |
| 481 | auto *NewBB = *SuccChain.begin(); |
| 482 | if (NewBB->isEHPad()) |
| 483 | EHPadWorkList.push_back(NewBB); |
| 484 | else |
| 485 | BlockWorkList.push_back(NewBB); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 486 | } |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 487 | } |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 488 | |
Xinliang David Li | 594ffa3 | 2016-06-11 18:35:40 +0000 | [diff] [blame] | 489 | /// This helper function collects the set of successors of block |
| 490 | /// \p BB that are allowed to be its layout successors, and return |
| 491 | /// the total branch probability of edges from \p BB to those |
| 492 | /// blocks. |
| 493 | BranchProbability MachineBlockPlacement::collectViableSuccessors( |
| 494 | MachineBasicBlock *BB, BlockChain &Chain, const BlockFilterSet *BlockFilter, |
| 495 | SmallVector<MachineBasicBlock *, 4> &Successors) { |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 496 | // Adjust edge probabilities by excluding edges pointing to blocks that is |
| 497 | // either not in BlockFilter or is already in the current chain. Consider the |
| 498 | // following CFG: |
Cong Hou | 41cf1a5 | 2015-11-18 00:52:52 +0000 | [diff] [blame] | 499 | // |
| 500 | // --->A |
| 501 | // | / \ |
| 502 | // | B C |
| 503 | // | \ / \ |
| 504 | // ----D E |
| 505 | // |
| 506 | // Assume A->C is very hot (>90%), and C->D has a 50% probability, then after |
| 507 | // A->C is chosen as a fall-through, D won't be selected as a successor of C |
| 508 | // due to CFG constraint (the probability of C->D is not greater than |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 509 | // HotProb to break top-order). If we exclude E that is not in BlockFilter |
Xinliang David Li | 594ffa3 | 2016-06-11 18:35:40 +0000 | [diff] [blame] | 510 | // when calculating the probability of C->D, D will be selected and we |
| 511 | // will get A C D B as the layout of this loop. |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 512 | auto AdjustedSumProb = BranchProbability::getOne(); |
Cong Hou | 41cf1a5 | 2015-11-18 00:52:52 +0000 | [diff] [blame] | 513 | for (MachineBasicBlock *Succ : BB->successors()) { |
| 514 | bool SkipSucc = false; |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 515 | if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) { |
Cong Hou | 41cf1a5 | 2015-11-18 00:52:52 +0000 | [diff] [blame] | 516 | SkipSucc = true; |
| 517 | } else { |
| 518 | BlockChain *SuccChain = BlockToChain[Succ]; |
| 519 | if (SuccChain == &Chain) { |
Cong Hou | 41cf1a5 | 2015-11-18 00:52:52 +0000 | [diff] [blame] | 520 | SkipSucc = true; |
| 521 | } else if (Succ != *SuccChain->begin()) { |
| 522 | DEBUG(dbgs() << " " << getBlockName(Succ) << " -> Mid chain!\n"); |
| 523 | continue; |
| 524 | } |
| 525 | } |
| 526 | if (SkipSucc) |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 527 | AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ); |
Cong Hou | 41cf1a5 | 2015-11-18 00:52:52 +0000 | [diff] [blame] | 528 | else |
| 529 | Successors.push_back(Succ); |
| 530 | } |
| 531 | |
Xinliang David Li | 594ffa3 | 2016-06-11 18:35:40 +0000 | [diff] [blame] | 532 | return AdjustedSumProb; |
| 533 | } |
| 534 | |
| 535 | /// The helper function returns the branch probability that is adjusted |
| 536 | /// or normalized over the new total \p AdjustedSumProb. |
Xinliang David Li | 594ffa3 | 2016-06-11 18:35:40 +0000 | [diff] [blame] | 537 | static BranchProbability |
| 538 | getAdjustedProbability(BranchProbability OrigProb, |
| 539 | BranchProbability AdjustedSumProb) { |
| 540 | BranchProbability SuccProb; |
| 541 | uint32_t SuccProbN = OrigProb.getNumerator(); |
| 542 | uint32_t SuccProbD = AdjustedSumProb.getNumerator(); |
| 543 | if (SuccProbN >= SuccProbD) |
| 544 | SuccProb = BranchProbability::getOne(); |
| 545 | else |
| 546 | SuccProb = BranchProbability(SuccProbN, SuccProbD); |
| 547 | |
| 548 | return SuccProb; |
| 549 | } |
| 550 | |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 551 | /// When the option OutlineOptionalBranches is on, this method |
| 552 | /// checks if the fallthrough candidate block \p Succ (of block |
| 553 | /// \p BB) also has other unscheduled predecessor blocks which |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 554 | /// are also successors of \p BB (forming triangular shape CFG). |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 555 | /// If none of such predecessors are small, it returns true. |
| 556 | /// The caller can choose to select \p Succ as the layout successors |
| 557 | /// so that \p Succ's predecessors (optional branches) can be |
| 558 | /// outlined. |
| 559 | /// FIXME: fold this with more general layout cost analysis. |
| 560 | bool MachineBlockPlacement::shouldPredBlockBeOutlined( |
| 561 | MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &Chain, |
| 562 | const BlockFilterSet *BlockFilter, BranchProbability SuccProb, |
| 563 | BranchProbability HotProb) { |
| 564 | if (!OutlineOptionalBranches) |
| 565 | return false; |
| 566 | // If we outline optional branches, look whether Succ is unavoidable, i.e. |
| 567 | // dominates all terminators of the MachineFunction. If it does, other |
| 568 | // successors must be optional. Don't do this for cold branches. |
| 569 | if (SuccProb > HotProb.getCompl() && UnavoidableBlocks.count(Succ) > 0) { |
| 570 | for (MachineBasicBlock *Pred : Succ->predecessors()) { |
| 571 | // Check whether there is an unplaced optional branch. |
| 572 | if (Pred == Succ || (BlockFilter && !BlockFilter->count(Pred)) || |
| 573 | BlockToChain[Pred] == &Chain) |
| 574 | continue; |
| 575 | // Check whether the optional branch has exactly one BB. |
| 576 | if (Pred->pred_size() > 1 || *Pred->pred_begin() != BB) |
| 577 | continue; |
| 578 | // Check whether the optional branch is small. |
| 579 | if (Pred->size() < OutlineOptionalThreshold) |
| 580 | return false; |
| 581 | } |
| 582 | return true; |
| 583 | } else |
| 584 | return false; |
| 585 | } |
| 586 | |
Dehao Chen | 9f2bdfb | 2016-06-14 22:27:17 +0000 | [diff] [blame] | 587 | // When profile is not present, return the StaticLikelyProb. |
| 588 | // When profile is available, we need to handle the triangle-shape CFG. |
| 589 | static BranchProbability getLayoutSuccessorProbThreshold( |
| 590 | MachineBasicBlock *BB) { |
| 591 | if (!BB->getParent()->getFunction()->getEntryCount()) |
| 592 | return BranchProbability(StaticLikelyProb, 100); |
| 593 | if (BB->succ_size() == 2) { |
| 594 | const MachineBasicBlock *Succ1 = *BB->succ_begin(); |
| 595 | const MachineBasicBlock *Succ2 = *(BB->succ_begin() + 1); |
Xinliang David Li | e34ed83 | 2016-06-15 03:03:30 +0000 | [diff] [blame] | 596 | if (Succ1->isSuccessor(Succ2) || Succ2->isSuccessor(Succ1)) { |
| 597 | /* See case 1 below for the cost analysis. For BB->Succ to |
| 598 | * be taken with smaller cost, the following needs to hold: |
| 599 | * Prob(BB->Succ) > 2* Prob(BB->Pred) |
| 600 | * So the threshold T |
| 601 | * T = 2 * (1-Prob(BB->Pred). Since T + Prob(BB->Pred) == 1, |
| 602 | * We have T + T/2 = 1, i.e. T = 2/3. Also adding user specified |
| 603 | * branch bias, we have |
| 604 | * T = (2/3)*(ProfileLikelyProb/50) |
| 605 | * = (2*ProfileLikelyProb)/150) |
| 606 | */ |
| 607 | return BranchProbability(2 * ProfileLikelyProb, 150); |
| 608 | } |
Dehao Chen | 9f2bdfb | 2016-06-14 22:27:17 +0000 | [diff] [blame] | 609 | } |
| 610 | return BranchProbability(ProfileLikelyProb, 100); |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 611 | } |
| 612 | |
| 613 | /// Checks to see if the layout candidate block \p Succ has a better layout |
| 614 | /// predecessor than \c BB. If yes, returns true. |
| 615 | bool MachineBlockPlacement::hasBetterLayoutPredecessor( |
| 616 | MachineBasicBlock *BB, MachineBasicBlock *Succ, BlockChain &SuccChain, |
| 617 | BranchProbability SuccProb, BranchProbability RealSuccProb, |
| 618 | BlockChain &Chain, const BlockFilterSet *BlockFilter) { |
| 619 | |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 620 | // There isn't a better layout when there are no unscheduled predecessors. |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 621 | if (SuccChain.UnscheduledPredecessors == 0) |
| 622 | return false; |
| 623 | |
| 624 | // There are two basic scenarios here: |
| 625 | // ------------------------------------- |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 626 | // Case 1: triangular shape CFG (if-then): |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 627 | // BB |
| 628 | // | \ |
| 629 | // | \ |
| 630 | // | Pred |
| 631 | // | / |
| 632 | // Succ |
| 633 | // In this case, we are evaluating whether to select edge -> Succ, e.g. |
| 634 | // set Succ as the layout successor of BB. Picking Succ as BB's |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 635 | // successor breaks the CFG constraints (FIXME: define these constraints). |
| 636 | // With this layout, Pred BB |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 637 | // is forced to be outlined, so the overall cost will be cost of the |
| 638 | // branch taken from BB to Pred, plus the cost of back taken branch |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 639 | // from Pred to Succ, as well as the additional cost associated |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 640 | // with the needed unconditional jump instruction from Pred To Succ. |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 641 | |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 642 | // The cost of the topological order layout is the taken branch cost |
| 643 | // from BB to Succ, so to make BB->Succ a viable candidate, the following |
| 644 | // must hold: |
| 645 | // 2 * freq(BB->Pred) * taken_branch_cost + unconditional_jump_cost |
| 646 | // < freq(BB->Succ) * taken_branch_cost. |
| 647 | // Ignoring unconditional jump cost, we get |
| 648 | // freq(BB->Succ) > 2 * freq(BB->Pred), i.e., |
| 649 | // prob(BB->Succ) > 2 * prob(BB->Pred) |
| 650 | // |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 651 | // When real profile data is available, we can precisely compute the |
| 652 | // probability threshold that is needed for edge BB->Succ to be considered. |
| 653 | // Without profile data, the heuristic requires the branch bias to be |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 654 | // a lot larger to make sure the signal is very strong (e.g. 80% default). |
| 655 | // ----------------------------------------------------------------- |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 656 | // Case 2: diamond like CFG (if-then-else): |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 657 | // S |
| 658 | // / \ |
| 659 | // | \ |
| 660 | // BB Pred |
| 661 | // \ / |
| 662 | // Succ |
| 663 | // .. |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 664 | // |
| 665 | // The current block is BB and edge BB->Succ is now being evaluated. |
| 666 | // Note that edge S->BB was previously already selected because |
| 667 | // prob(S->BB) > prob(S->Pred). |
| 668 | // At this point, 2 blocks can be placed after BB: Pred or Succ. If we |
| 669 | // choose Pred, we will have a topological ordering as shown on the left |
| 670 | // in the picture below. If we choose Succ, we have the solution as shown |
| 671 | // on the right: |
| 672 | // |
| 673 | // topo-order: |
| 674 | // |
| 675 | // S----- ---S |
| 676 | // | | | | |
| 677 | // ---BB | | BB |
| 678 | // | | | | |
| 679 | // | pred-- | Succ-- |
| 680 | // | | | | |
| 681 | // ---succ ---pred-- |
| 682 | // |
| 683 | // cost = freq(S->Pred) + freq(BB->Succ) cost = 2 * freq (S->Pred) |
| 684 | // = freq(S->Pred) + freq(S->BB) |
| 685 | // |
| 686 | // If we have profile data (i.e, branch probabilities can be trusted), the |
| 687 | // cost (number of taken branches) with layout S->BB->Succ->Pred is 2 * |
| 688 | // freq(S->Pred) while the cost of topo order is freq(S->Pred) + freq(S->BB). |
| 689 | // We know Prob(S->BB) > Prob(S->Pred), so freq(S->BB) > freq(S->Pred), which |
| 690 | // means the cost of topological order is greater. |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 691 | // When profile data is not available, however, we need to be more |
| 692 | // conservative. If the branch prediction is wrong, breaking the topo-order |
| 693 | // will actually yield a layout with large cost. For this reason, we need |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 694 | // strong biased branch at block S with Prob(S->BB) in order to select |
| 695 | // BB->Succ. This is equivalent to looking the CFG backward with backward |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 696 | // edge: Prob(Succ->BB) needs to >= HotProb in order to be selected (without |
| 697 | // profile data). |
Kyle Butt | 02d8d05 | 2016-07-29 18:09:28 +0000 | [diff] [blame] | 698 | // -------------------------------------------------------------------------- |
| 699 | // Case 3: forked diamond |
| 700 | // S |
| 701 | // / \ |
| 702 | // / \ |
| 703 | // BB Pred |
| 704 | // | \ / | |
| 705 | // | \ / | |
| 706 | // | X | |
| 707 | // | / \ | |
| 708 | // | / \ | |
| 709 | // S1 S2 |
| 710 | // |
| 711 | // The current block is BB and edge BB->S1 is now being evaluated. |
| 712 | // As above S->BB was already selected because |
| 713 | // prob(S->BB) > prob(S->Pred). Assume that prob(BB->S1) >= prob(BB->S2). |
| 714 | // |
| 715 | // topo-order: |
| 716 | // |
| 717 | // S-------| ---S |
| 718 | // | | | | |
| 719 | // ---BB | | BB |
| 720 | // | | | | |
| 721 | // | Pred----| | S1---- |
| 722 | // | | | | |
| 723 | // --(S1 or S2) ---Pred-- |
| 724 | // |
| 725 | // topo-cost = freq(S->Pred) + freq(BB->S1) + freq(BB->S2) |
| 726 | // + min(freq(Pred->S1), freq(Pred->S2)) |
| 727 | // Non-topo-order cost: |
| 728 | // In the worst case, S2 will not get laid out after Pred. |
| 729 | // non-topo-cost = 2 * freq(S->Pred) + freq(BB->S2). |
| 730 | // To be conservative, we can assume that min(freq(Pred->S1), freq(Pred->S2)) |
| 731 | // is 0. Then the non topo layout is better when |
| 732 | // freq(S->Pred) < freq(BB->S1). |
| 733 | // This is exactly what is checked below. |
| 734 | // Note there are other shapes that apply (Pred may not be a single block, |
| 735 | // but they all fit this general pattern.) |
Dehao Chen | 9f2bdfb | 2016-06-14 22:27:17 +0000 | [diff] [blame] | 736 | BranchProbability HotProb = getLayoutSuccessorProbThreshold(BB); |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 737 | |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 738 | // Make sure that a hot successor doesn't have a globally more |
| 739 | // important predecessor. |
| 740 | BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb; |
| 741 | bool BadCFGConflict = false; |
| 742 | |
| 743 | for (MachineBasicBlock *Pred : Succ->predecessors()) { |
| 744 | if (Pred == Succ || BlockToChain[Pred] == &SuccChain || |
| 745 | (BlockFilter && !BlockFilter->count(Pred)) || |
| 746 | BlockToChain[Pred] == &Chain) |
| 747 | continue; |
Kyle Butt | 02d8d05 | 2016-07-29 18:09:28 +0000 | [diff] [blame] | 748 | // Do backward checking. |
| 749 | // For all cases above, we need a backward checking to filter out edges that |
| 750 | // are not 'strongly' biased. With profile data available, the check is |
| 751 | // mostly redundant for case 2 (when threshold prob is set at 50%) unless S |
| 752 | // has more than two successors. |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 753 | // BB Pred |
| 754 | // \ / |
| 755 | // Succ |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 756 | // We select edge BB->Succ if |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 757 | // freq(BB->Succ) > freq(Succ) * HotProb |
| 758 | // i.e. freq(BB->Succ) > freq(BB->Succ) * HotProb + freq(Pred->Succ) * |
| 759 | // HotProb |
| 760 | // i.e. freq((BB->Succ) * (1 - HotProb) > freq(Pred->Succ) * HotProb |
Kyle Butt | 02d8d05 | 2016-07-29 18:09:28 +0000 | [diff] [blame] | 761 | // Case 1 is covered too, because the first equation reduces to: |
| 762 | // prob(BB->Succ) > HotProb. (freq(Succ) = freq(BB) for a triangle) |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 763 | BlockFrequency PredEdgeFreq = |
| 764 | MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ); |
| 765 | if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.getCompl()) { |
| 766 | BadCFGConflict = true; |
| 767 | break; |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | if (BadCFGConflict) { |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 772 | DEBUG(dbgs() << " Not a candidate: " << getBlockName(Succ) << " -> " << SuccProb |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 773 | << " (prob) (non-cold CFG conflict)\n"); |
| 774 | return true; |
| 775 | } |
| 776 | |
| 777 | return false; |
| 778 | } |
| 779 | |
Xinliang David Li | 594ffa3 | 2016-06-11 18:35:40 +0000 | [diff] [blame] | 780 | /// \brief Select the best successor for a block. |
| 781 | /// |
| 782 | /// This looks across all successors of a particular block and attempts to |
| 783 | /// select the "best" one to be the layout successor. It only considers direct |
| 784 | /// successors which also pass the block filter. It will attempt to avoid |
| 785 | /// breaking CFG structure, but cave and break such structures in the case of |
| 786 | /// very hot successor edges. |
| 787 | /// |
| 788 | /// \returns The best successor block found, or null if none are viable. |
| 789 | MachineBasicBlock * |
| 790 | MachineBlockPlacement::selectBestSuccessor(MachineBasicBlock *BB, |
| 791 | BlockChain &Chain, |
| 792 | const BlockFilterSet *BlockFilter) { |
| 793 | const BranchProbability HotProb(StaticLikelyProb, 100); |
| 794 | |
| 795 | MachineBasicBlock *BestSucc = nullptr; |
| 796 | auto BestProb = BranchProbability::getZero(); |
| 797 | |
| 798 | SmallVector<MachineBasicBlock *, 4> Successors; |
| 799 | auto AdjustedSumProb = |
| 800 | collectViableSuccessors(BB, Chain, BlockFilter, Successors); |
| 801 | |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 802 | DEBUG(dbgs() << "Selecting best successor for: " << getBlockName(BB) << "\n"); |
Cong Hou | 41cf1a5 | 2015-11-18 00:52:52 +0000 | [diff] [blame] | 803 | for (MachineBasicBlock *Succ : Successors) { |
Xinliang David Li | 594ffa3 | 2016-06-11 18:35:40 +0000 | [diff] [blame] | 804 | auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ); |
| 805 | BranchProbability SuccProb = |
| 806 | getAdjustedProbability(RealSuccProb, AdjustedSumProb); |
Chandler Carruth | b336172 | 2011-11-13 11:34:53 +0000 | [diff] [blame] | 807 | |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 808 | // This heuristic is off by default. |
| 809 | if (shouldPredBlockBeOutlined(BB, Succ, Chain, BlockFilter, SuccProb, |
| 810 | HotProb)) |
| 811 | return Succ; |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 812 | |
Cong Hou | 41cf1a5 | 2015-11-18 00:52:52 +0000 | [diff] [blame] | 813 | BlockChain &SuccChain = *BlockToChain[Succ]; |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 814 | // Skip the edge \c BB->Succ if block \c Succ has a better layout |
| 815 | // predecessor that yields lower global cost. |
| 816 | if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb, |
| 817 | Chain, BlockFilter)) |
| 818 | continue; |
Chandler Carruth | 18dfac3 | 2011-11-20 11:22:06 +0000 | [diff] [blame] | 819 | |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 820 | DEBUG( |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 821 | dbgs() << " Candidate: " << getBlockName(Succ) << ", probability: " |
| 822 | << SuccProb |
Xinliang David Li | cbf1214 | 2016-06-13 20:24:19 +0000 | [diff] [blame] | 823 | << (SuccChain.UnscheduledPredecessors != 0 ? " (CFG break)" : "") |
| 824 | << "\n"); |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 825 | |
| 826 | if (BestSucc && BestProb >= SuccProb) { |
| 827 | DEBUG(dbgs() << " Not the best candidate, continuing\n"); |
Chandler Carruth | b336172 | 2011-11-13 11:34:53 +0000 | [diff] [blame] | 828 | continue; |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 829 | } |
| 830 | |
| 831 | DEBUG(dbgs() << " Setting it as best candidate\n"); |
Daniel Jasper | ed9eb72 | 2015-02-18 08:19:16 +0000 | [diff] [blame] | 832 | BestSucc = Succ; |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 833 | BestProb = SuccProb; |
Chandler Carruth | b336172 | 2011-11-13 11:34:53 +0000 | [diff] [blame] | 834 | } |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 835 | if (BestSucc) |
| 836 | DEBUG(dbgs() << " Selected: " << getBlockName(BestSucc) << "\n"); |
| 837 | |
Chandler Carruth | b336172 | 2011-11-13 11:34:53 +0000 | [diff] [blame] | 838 | return BestSucc; |
| 839 | } |
| 840 | |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 841 | /// \brief Select the best block from a worklist. |
| 842 | /// |
| 843 | /// This looks through the provided worklist as a list of candidate basic |
| 844 | /// blocks and select the most profitable one to place. The definition of |
| 845 | /// profitable only really makes sense in the context of a loop. This returns |
| 846 | /// the most frequently visited block in the worklist, which in the case of |
| 847 | /// a loop, is the one most desirable to be physically close to the rest of the |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 848 | /// loop body in order to improve i-cache behavior. |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 849 | /// |
| 850 | /// \returns The best block found, or null if none are viable. |
| 851 | MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock( |
Amaury Sechet | 9ee4ddd | 2016-04-07 06:34:47 +0000 | [diff] [blame] | 852 | BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) { |
Chandler Carruth | 0af6a0b | 2011-11-14 09:46:33 +0000 | [diff] [blame] | 853 | // Once we need to walk the worklist looking for a candidate, cleanup the |
| 854 | // worklist of already placed entries. |
| 855 | // FIXME: If this shows up on profiles, it could be folded (at the cost of |
| 856 | // some code complexity) into the loop below. |
David Majnemer | c700490 | 2016-08-12 04:32:37 +0000 | [diff] [blame] | 857 | WorkList.erase(remove_if(WorkList, |
| 858 | [&](MachineBasicBlock *BB) { |
| 859 | return BlockToChain.lookup(BB) == &Chain; |
| 860 | }), |
Chandler Carruth | 0af6a0b | 2011-11-14 09:46:33 +0000 | [diff] [blame] | 861 | WorkList.end()); |
| 862 | |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 863 | if (WorkList.empty()) |
| 864 | return nullptr; |
| 865 | |
| 866 | bool IsEHPad = WorkList[0]->isEHPad(); |
| 867 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 868 | MachineBasicBlock *BestBlock = nullptr; |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 869 | BlockFrequency BestFreq; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 870 | for (MachineBasicBlock *MBB : WorkList) { |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 871 | assert(MBB->isEHPad() == IsEHPad); |
| 872 | |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 873 | BlockChain &SuccChain = *BlockToChain[MBB]; |
Philip Reames | 02e1132 | 2016-03-02 22:40:51 +0000 | [diff] [blame] | 874 | if (&SuccChain == &Chain) |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 875 | continue; |
Junmo Park | 4ba6cf6 | 2016-03-11 05:07:07 +0000 | [diff] [blame] | 876 | |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 877 | assert(SuccChain.UnscheduledPredecessors == 0 && "Found CFG-violating block"); |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 878 | |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 879 | BlockFrequency CandidateFreq = MBFI->getBlockFreq(MBB); |
| 880 | DEBUG(dbgs() << " " << getBlockName(MBB) << " -> "; |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 881 | MBFI->printBlockFreq(dbgs(), CandidateFreq) << " (freq)\n"); |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 882 | |
| 883 | // For ehpad, we layout the least probable first as to avoid jumping back |
| 884 | // from least probable landingpads to more probable ones. |
| 885 | // |
| 886 | // FIXME: Using probability is probably (!) not the best way to achieve |
| 887 | // this. We should probably have a more principled approach to layout |
| 888 | // cleanup code. |
| 889 | // |
| 890 | // The goal is to get: |
| 891 | // |
| 892 | // +--------------------------+ |
| 893 | // | V |
| 894 | // InnerLp -> InnerCleanup OuterLp -> OuterCleanup -> Resume |
| 895 | // |
| 896 | // Rather than: |
| 897 | // |
| 898 | // +-------------------------------------+ |
| 899 | // V | |
| 900 | // OuterLp -> OuterCleanup -> Resume InnerLp -> InnerCleanup |
| 901 | if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq))) |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 902 | continue; |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 903 | |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 904 | BestBlock = MBB; |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 905 | BestFreq = CandidateFreq; |
| 906 | } |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 907 | |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 908 | return BestBlock; |
| 909 | } |
| 910 | |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 911 | /// \brief Retrieve the first unplaced basic block. |
| 912 | /// |
| 913 | /// This routine is called when we are unable to use the CFG to walk through |
| 914 | /// all of the basic blocks and form a chain due to unnatural loops in the CFG. |
Chandler Carruth | 9b548a7f | 2011-11-15 06:26:43 +0000 | [diff] [blame] | 915 | /// We walk through the function's blocks in order, starting from the |
| 916 | /// LastUnplacedBlockIt. We update this iterator on each call to avoid |
| 917 | /// re-scanning the entire sequence on repeated calls to this routine. |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 918 | MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock( |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 919 | const BlockChain &PlacedChain, |
Chandler Carruth | 9b548a7f | 2011-11-15 06:26:43 +0000 | [diff] [blame] | 920 | MachineFunction::iterator &PrevUnplacedBlockIt, |
Jakub Staszak | 9061616 | 2011-12-21 23:02:08 +0000 | [diff] [blame] | 921 | const BlockFilterSet *BlockFilter) { |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 922 | for (MachineFunction::iterator I = PrevUnplacedBlockIt, E = F->end(); I != E; |
Chandler Carruth | 9b548a7f | 2011-11-15 06:26:43 +0000 | [diff] [blame] | 923 | ++I) { |
Duncan P. N. Exon Smith | 6ac07fd | 2015-10-09 19:36:12 +0000 | [diff] [blame] | 924 | if (BlockFilter && !BlockFilter->count(&*I)) |
Chandler Carruth | 9b548a7f | 2011-11-15 06:26:43 +0000 | [diff] [blame] | 925 | continue; |
Duncan P. N. Exon Smith | 6ac07fd | 2015-10-09 19:36:12 +0000 | [diff] [blame] | 926 | if (BlockToChain[&*I] != &PlacedChain) { |
Chandler Carruth | 9b548a7f | 2011-11-15 06:26:43 +0000 | [diff] [blame] | 927 | PrevUnplacedBlockIt = I; |
Chandler Carruth | 4a87aa0 | 2011-11-23 03:03:21 +0000 | [diff] [blame] | 928 | // Now select the head of the chain to which the unplaced block belongs |
| 929 | // as the block to place. This will force the entire chain to be placed, |
| 930 | // and satisfies the requirements of merging chains. |
Duncan P. N. Exon Smith | 6ac07fd | 2015-10-09 19:36:12 +0000 | [diff] [blame] | 931 | return *BlockToChain[&*I]->begin(); |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 932 | } |
| 933 | } |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 934 | return nullptr; |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 935 | } |
| 936 | |
Amaury Sechet | eae09c2 | 2016-03-14 21:24:11 +0000 | [diff] [blame] | 937 | void MachineBlockPlacement::fillWorkLists( |
| 938 | MachineBasicBlock *MBB, |
| 939 | SmallPtrSetImpl<BlockChain *> &UpdatedPreds, |
Amaury Sechet | eae09c2 | 2016-03-14 21:24:11 +0000 | [diff] [blame] | 940 | const BlockFilterSet *BlockFilter = nullptr) { |
| 941 | BlockChain &Chain = *BlockToChain[MBB]; |
| 942 | if (!UpdatedPreds.insert(&Chain).second) |
| 943 | return; |
| 944 | |
| 945 | assert(Chain.UnscheduledPredecessors == 0); |
| 946 | for (MachineBasicBlock *ChainBB : Chain) { |
| 947 | assert(BlockToChain[ChainBB] == &Chain); |
| 948 | for (MachineBasicBlock *Pred : ChainBB->predecessors()) { |
| 949 | if (BlockFilter && !BlockFilter->count(Pred)) |
| 950 | continue; |
| 951 | if (BlockToChain[Pred] == &Chain) |
| 952 | continue; |
| 953 | ++Chain.UnscheduledPredecessors; |
| 954 | } |
| 955 | } |
| 956 | |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 957 | if (Chain.UnscheduledPredecessors != 0) |
| 958 | return; |
| 959 | |
| 960 | MBB = *Chain.begin(); |
| 961 | if (MBB->isEHPad()) |
| 962 | EHPadWorkList.push_back(MBB); |
| 963 | else |
| 964 | BlockWorkList.push_back(MBB); |
Amaury Sechet | eae09c2 | 2016-03-14 21:24:11 +0000 | [diff] [blame] | 965 | } |
| 966 | |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 967 | void MachineBlockPlacement::buildChain( |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 968 | MachineBasicBlock *BB, BlockChain &Chain, |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 969 | BlockFilterSet *BlockFilter) { |
Kyle Butt | b3875ea | 2016-06-17 22:40:19 +0000 | [diff] [blame] | 970 | assert(BB && "BB must not be null.\n"); |
| 971 | assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match.\n"); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 972 | MachineFunction::iterator PrevUnplacedBlockIt = F->begin(); |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 973 | |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 974 | MachineBasicBlock *LoopHeaderBB = BB; |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 975 | markChainSuccessors(Chain, LoopHeaderBB, BlockFilter); |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 976 | BB = *std::prev(Chain.end()); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 977 | for (;;) { |
Kyle Butt | 82c2290 | 2016-06-28 22:50:54 +0000 | [diff] [blame] | 978 | assert(BB && "null block found at end of chain in loop."); |
| 979 | assert(BlockToChain[BB] == &Chain && "BlockToChainMap mis-match in loop."); |
| 980 | assert(*std::prev(Chain.end()) == BB && "BB Not found at end of chain."); |
| 981 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 982 | |
Chandler Carruth | f3dc9ef | 2011-11-19 10:26:02 +0000 | [diff] [blame] | 983 | // Look for the best viable successor if there is one to place immediately |
| 984 | // after this block. |
Duncan Sands | 291d47e | 2012-09-14 09:00:11 +0000 | [diff] [blame] | 985 | MachineBasicBlock *BestSucc = selectBestSuccessor(BB, Chain, BlockFilter); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 986 | |
| 987 | // If an immediate successor isn't available, look for the best viable |
| 988 | // block among those we've identified as not violating the loop's CFG at |
| 989 | // this point. This won't be a fallthrough, but it will increase locality. |
Chandler Carruth | f9213fe | 2011-11-13 11:42:26 +0000 | [diff] [blame] | 990 | if (!BestSucc) |
Amaury Sechet | 9ee4ddd | 2016-04-07 06:34:47 +0000 | [diff] [blame] | 991 | BestSucc = selectBestCandidateBlock(Chain, BlockWorkList); |
Amaury Sechet | c53ad4f | 2016-04-07 21:29:39 +0000 | [diff] [blame] | 992 | if (!BestSucc) |
| 993 | BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 994 | |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 995 | if (!BestSucc) { |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 996 | BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter); |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 997 | if (!BestSucc) |
| 998 | break; |
| 999 | |
| 1000 | DEBUG(dbgs() << "Unnatural loop CFG detected, forcibly merging the " |
| 1001 | "layout successor until the CFG reduces\n"); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1002 | } |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 1003 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 1004 | // Placement may have changed tail duplication opportunities. |
| 1005 | // Check for that now. |
| 1006 | if (TailDupPlacement && BestSucc) { |
| 1007 | // If the chosen successor was duplicated into all its predecessors, |
| 1008 | // don't bother laying it out, just go round the loop again with BB as |
| 1009 | // the chain end. |
| 1010 | if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain, |
| 1011 | BlockFilter, PrevUnplacedBlockIt)) |
| 1012 | continue; |
| 1013 | } |
| 1014 | |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1015 | // Place this block, updating the datastructures to reflect its placement. |
Jakub Staszak | 9061616 | 2011-12-21 23:02:08 +0000 | [diff] [blame] | 1016 | BlockChain &SuccChain = *BlockToChain[BestSucc]; |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 1017 | // Zero out UnscheduledPredecessors for the successor we're about to merge in case |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 1018 | // we selected a successor that didn't fit naturally into the CFG. |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 1019 | SuccChain.UnscheduledPredecessors = 0; |
Philip Reames | b9688f4 | 2016-03-02 21:45:13 +0000 | [diff] [blame] | 1020 | DEBUG(dbgs() << "Merging from " << getBlockName(BB) << " to " |
| 1021 | << getBlockName(BestSucc) << "\n"); |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1022 | markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1023 | Chain.merge(BestSucc, &SuccChain); |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1024 | BB = *std::prev(Chain.end()); |
Jakub Staszak | 190c712 | 2011-12-07 19:46:10 +0000 | [diff] [blame] | 1025 | } |
Chandler Carruth | 1071cfa | 2011-11-14 00:00:35 +0000 | [diff] [blame] | 1026 | |
| 1027 | DEBUG(dbgs() << "Finished forming chain for header block " |
Philip Reames | b9688f4 | 2016-03-02 21:45:13 +0000 | [diff] [blame] | 1028 | << getBlockName(*Chain.begin()) << "\n"); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1029 | } |
| 1030 | |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1031 | /// \brief Find the best loop top block for layout. |
Chandler Carruth | 9ffb97e | 2011-11-27 00:38:03 +0000 | [diff] [blame] | 1032 | /// |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1033 | /// Look for a block which is strictly better than the loop header for laying |
| 1034 | /// out at the top of the loop. This looks for one and only one pattern: |
| 1035 | /// a latch block with no conditional exit. This block will cause a conditional |
| 1036 | /// jump around it or will be the bottom of the loop if we lay it out in place, |
| 1037 | /// but if it it doesn't end up at the bottom of the loop for any reason, |
| 1038 | /// rotation alone won't fix it. Because such a block will always result in an |
| 1039 | /// unconditional jump (for the backedge) rotating it in front of the loop |
| 1040 | /// header is always profitable. |
| 1041 | MachineBasicBlock * |
| 1042 | MachineBlockPlacement::findBestLoopTop(MachineLoop &L, |
| 1043 | const BlockFilterSet &LoopBlockSet) { |
Sjoerd Meijer | 15c81b0 | 2016-08-16 19:50:33 +0000 | [diff] [blame] | 1044 | // Placing the latch block before the header may introduce an extra branch |
| 1045 | // that skips this block the first time the loop is executed, which we want |
| 1046 | // to avoid when optimising for size. |
| 1047 | // FIXME: in theory there is a case that does not introduce a new branch, |
| 1048 | // i.e. when the layout predecessor does not fallthrough to the loop header. |
| 1049 | // In practice this never happens though: there always seems to be a preheader |
| 1050 | // that can fallthrough and that is also placed before the header. |
| 1051 | if (F->getFunction()->optForSize()) |
| 1052 | return L.getHeader(); |
| 1053 | |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1054 | // Check that the header hasn't been fused with a preheader block due to |
| 1055 | // crazy branches. If it has, we need to start with the header at the top to |
| 1056 | // prevent pulling the preheader into the loop body. |
| 1057 | BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; |
| 1058 | if (!LoopBlockSet.count(*HeaderChain.begin())) |
| 1059 | return L.getHeader(); |
| 1060 | |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 1061 | DEBUG(dbgs() << "Finding best loop top for: " << getBlockName(L.getHeader()) |
| 1062 | << "\n"); |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1063 | |
| 1064 | BlockFrequency BestPredFreq; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1065 | MachineBasicBlock *BestPred = nullptr; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1066 | for (MachineBasicBlock *Pred : L.getHeader()->predecessors()) { |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1067 | if (!LoopBlockSet.count(Pred)) |
| 1068 | continue; |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 1069 | DEBUG(dbgs() << " header pred: " << getBlockName(Pred) << ", has " |
Michael Gottesman | b78dec8 | 2013-12-14 00:25:45 +0000 | [diff] [blame] | 1070 | << Pred->succ_size() << " successors, "; |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 1071 | MBFI->printBlockFreq(dbgs(), Pred) << " freq\n"); |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1072 | if (Pred->succ_size() > 1) |
| 1073 | continue; |
| 1074 | |
| 1075 | BlockFrequency PredFreq = MBFI->getBlockFreq(Pred); |
| 1076 | if (!BestPred || PredFreq > BestPredFreq || |
| 1077 | (!(PredFreq < BestPredFreq) && |
| 1078 | Pred->isLayoutSuccessor(L.getHeader()))) { |
| 1079 | BestPred = Pred; |
| 1080 | BestPredFreq = PredFreq; |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | // If no direct predecessor is fine, just use the loop header. |
Philip Reames | b9688f4 | 2016-03-02 21:45:13 +0000 | [diff] [blame] | 1085 | if (!BestPred) { |
| 1086 | DEBUG(dbgs() << " final top unchanged\n"); |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1087 | return L.getHeader(); |
Philip Reames | b9688f4 | 2016-03-02 21:45:13 +0000 | [diff] [blame] | 1088 | } |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1089 | |
| 1090 | // Walk backwards through any straight line of predecessors. |
| 1091 | while (BestPred->pred_size() == 1 && |
| 1092 | (*BestPred->pred_begin())->succ_size() == 1 && |
| 1093 | *BestPred->pred_begin() != L.getHeader()) |
| 1094 | BestPred = *BestPred->pred_begin(); |
| 1095 | |
| 1096 | DEBUG(dbgs() << " final top: " << getBlockName(BestPred) << "\n"); |
| 1097 | return BestPred; |
| 1098 | } |
| 1099 | |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1100 | /// \brief Find the best loop exiting block for layout. |
| 1101 | /// |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1102 | /// This routine implements the logic to analyze the loop looking for the best |
| 1103 | /// block to layout at the top of the loop. Typically this is done to maximize |
| 1104 | /// fallthrough opportunities. |
| 1105 | MachineBasicBlock * |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1106 | MachineBlockPlacement::findBestLoopExit(MachineLoop &L, |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1107 | const BlockFilterSet &LoopBlockSet) { |
Chandler Carruth | 6806261 | 2012-04-10 13:35:57 +0000 | [diff] [blame] | 1108 | // We don't want to layout the loop linearly in all cases. If the loop header |
| 1109 | // is just a normal basic block in the loop, we want to look for what block |
| 1110 | // within the loop is the best one to layout at the top. However, if the loop |
| 1111 | // header has be pre-merged into a chain due to predecessors not having |
| 1112 | // analyzable branches, *and* the predecessor it is merged with is *not* part |
| 1113 | // of the loop, rotating the header into the middle of the loop will create |
| 1114 | // a non-contiguous range of blocks which is Very Bad. So start with the |
| 1115 | // header and only rotate if safe. |
| 1116 | BlockChain &HeaderChain = *BlockToChain[L.getHeader()]; |
| 1117 | if (!LoopBlockSet.count(*HeaderChain.begin())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1118 | return nullptr; |
Chandler Carruth | 6806261 | 2012-04-10 13:35:57 +0000 | [diff] [blame] | 1119 | |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1120 | BlockFrequency BestExitEdgeFreq; |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1121 | unsigned BestExitLoopDepth = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1122 | MachineBasicBlock *ExitingBB = nullptr; |
Chandler Carruth | 4f56720 | 2011-11-27 20:18:00 +0000 | [diff] [blame] | 1123 | // If there are exits to outer loops, loop rotation can severely limit |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 1124 | // fallthrough opportunities unless it selects such an exit. Keep a set of |
Chandler Carruth | 4f56720 | 2011-11-27 20:18:00 +0000 | [diff] [blame] | 1125 | // blocks where rotating to exit with that block will reach an outer loop. |
| 1126 | SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop; |
| 1127 | |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 1128 | DEBUG(dbgs() << "Finding best loop exit for: " << getBlockName(L.getHeader()) |
| 1129 | << "\n"); |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1130 | for (MachineBasicBlock *MBB : L.getBlocks()) { |
| 1131 | BlockChain &Chain = *BlockToChain[MBB]; |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1132 | // Ensure that this block is at the end of a chain; otherwise it could be |
Chandler Carruth | 9a512a4 | 2015-04-15 13:19:54 +0000 | [diff] [blame] | 1133 | // mid-way through an inner loop or a successor of an unanalyzable branch. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1134 | if (MBB != *std::prev(Chain.end())) |
Chandler Carruth | 9ffb97e | 2011-11-27 00:38:03 +0000 | [diff] [blame] | 1135 | continue; |
Chandler Carruth | 9ffb97e | 2011-11-27 00:38:03 +0000 | [diff] [blame] | 1136 | |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1137 | // Now walk the successors. We need to establish whether this has a viable |
| 1138 | // exiting successor and whether it has a viable non-exiting successor. |
| 1139 | // We store the old exiting state and restore it if a viable looping |
| 1140 | // successor isn't found. |
| 1141 | MachineBasicBlock *OldExitingBB = ExitingBB; |
| 1142 | BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq; |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1143 | bool HasLoopingSucc = false; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1144 | for (MachineBasicBlock *Succ : MBB->successors()) { |
Reid Kleckner | 0e28823 | 2015-08-27 23:27:47 +0000 | [diff] [blame] | 1145 | if (Succ->isEHPad()) |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1146 | continue; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1147 | if (Succ == MBB) |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1148 | continue; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1149 | BlockChain &SuccChain = *BlockToChain[Succ]; |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1150 | // Don't split chains, either this chain or the successor's chain. |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1151 | if (&Chain == &SuccChain) { |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1152 | DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " |
| 1153 | << getBlockName(Succ) << " (chain conflict)\n"); |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1154 | continue; |
| 1155 | } |
| 1156 | |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 1157 | auto SuccProb = MBPI->getEdgeProbability(MBB, Succ); |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1158 | if (LoopBlockSet.count(Succ)) { |
| 1159 | DEBUG(dbgs() << " looping: " << getBlockName(MBB) << " -> " |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 1160 | << getBlockName(Succ) << " (" << SuccProb << ")\n"); |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1161 | HasLoopingSucc = true; |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1162 | continue; |
| 1163 | } |
| 1164 | |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1165 | unsigned SuccLoopDepth = 0; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1166 | if (MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) { |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1167 | SuccLoopDepth = ExitLoop->getLoopDepth(); |
| 1168 | if (ExitLoop->contains(&L)) |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1169 | BlocksExitingToOuterLoop.insert(MBB); |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1170 | } |
| 1171 | |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1172 | BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb; |
| 1173 | DEBUG(dbgs() << " exiting: " << getBlockName(MBB) << " -> " |
| 1174 | << getBlockName(Succ) << " [L:" << SuccLoopDepth << "] ("; |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 1175 | MBFI->printBlockFreq(dbgs(), ExitEdgeFreq) << ")\n"); |
Benjamin Kramer | c8160d6 | 2013-11-20 19:08:44 +0000 | [diff] [blame] | 1176 | // Note that we bias this toward an existing layout successor to retain |
| 1177 | // incoming order in the absence of better information. The exit must have |
| 1178 | // a frequency higher than the current exit before we consider breaking |
| 1179 | // the layout. |
| 1180 | BranchProbability Bias(100 - ExitBlockBias, 100); |
Chandler Carruth | 26d3017 | 2015-04-15 13:39:42 +0000 | [diff] [blame] | 1181 | if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth || |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1182 | ExitEdgeFreq > BestExitEdgeFreq || |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1183 | (MBB->isLayoutSuccessor(Succ) && |
Benjamin Kramer | c8160d6 | 2013-11-20 19:08:44 +0000 | [diff] [blame] | 1184 | !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) { |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1185 | BestExitEdgeFreq = ExitEdgeFreq; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1186 | ExitingBB = MBB; |
Chandler Carruth | a054580 | 2011-11-27 09:22:53 +0000 | [diff] [blame] | 1187 | } |
Chandler Carruth | 9ffb97e | 2011-11-27 00:38:03 +0000 | [diff] [blame] | 1188 | } |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1189 | |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1190 | if (!HasLoopingSucc) { |
Chandler Carruth | cfb2b9d | 2015-04-15 13:26:41 +0000 | [diff] [blame] | 1191 | // Restore the old exiting state, no viable looping successor was found. |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1192 | ExitingBB = OldExitingBB; |
| 1193 | BestExitEdgeFreq = OldBestExitEdgeFreq; |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1194 | } |
Chandler Carruth | 9ffb97e | 2011-11-27 00:38:03 +0000 | [diff] [blame] | 1195 | } |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1196 | // Without a candidate exiting block or with only a single block in the |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1197 | // loop, just use the loop header to layout the loop. |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 1198 | if (!ExitingBB) { |
| 1199 | DEBUG(dbgs() << " No other candidate exit blocks, using loop header\n"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1200 | return nullptr; |
Sjoerd Meijer | 5e11a18 | 2016-07-27 08:49:23 +0000 | [diff] [blame] | 1201 | } |
| 1202 | if (L.getNumBlocks() == 1) { |
| 1203 | DEBUG(dbgs() << " Loop has 1 block, using loop header as exit\n"); |
| 1204 | return nullptr; |
| 1205 | } |
Chandler Carruth | 9ffb97e | 2011-11-27 00:38:03 +0000 | [diff] [blame] | 1206 | |
Chandler Carruth | 4f56720 | 2011-11-27 20:18:00 +0000 | [diff] [blame] | 1207 | // Also, if we have exit blocks which lead to outer loops but didn't select |
| 1208 | // one of them as the exiting block we are rotating toward, disable loop |
| 1209 | // rotation altogether. |
| 1210 | if (!BlocksExitingToOuterLoop.empty() && |
| 1211 | !BlocksExitingToOuterLoop.count(ExitingBB)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1212 | return nullptr; |
Chandler Carruth | 4f56720 | 2011-11-27 20:18:00 +0000 | [diff] [blame] | 1213 | |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1214 | DEBUG(dbgs() << " Best exiting block: " << getBlockName(ExitingBB) << "\n"); |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1215 | return ExitingBB; |
Chandler Carruth | 9ffb97e | 2011-11-27 00:38:03 +0000 | [diff] [blame] | 1216 | } |
| 1217 | |
Chandler Carruth | 8c74c7b | 2012-04-16 09:31:23 +0000 | [diff] [blame] | 1218 | /// \brief Attempt to rotate an exiting block to the bottom of the loop. |
| 1219 | /// |
| 1220 | /// Once we have built a chain, try to rotate it to line up the hot exit block |
| 1221 | /// with fallthrough out of the loop if doing so doesn't introduce unnecessary |
| 1222 | /// branches. For example, if the loop has fallthrough into its header and out |
| 1223 | /// of its bottom already, don't rotate it. |
| 1224 | void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain, |
| 1225 | MachineBasicBlock *ExitingBB, |
| 1226 | const BlockFilterSet &LoopBlockSet) { |
| 1227 | if (!ExitingBB) |
| 1228 | return; |
| 1229 | |
| 1230 | MachineBasicBlock *Top = *LoopChain.begin(); |
| 1231 | bool ViableTopFallthrough = false; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1232 | for (MachineBasicBlock *Pred : Top->predecessors()) { |
| 1233 | BlockChain *PredChain = BlockToChain[Pred]; |
| 1234 | if (!LoopBlockSet.count(Pred) && |
| 1235 | (!PredChain || Pred == *std::prev(PredChain->end()))) { |
Chandler Carruth | 8c74c7b | 2012-04-16 09:31:23 +0000 | [diff] [blame] | 1236 | ViableTopFallthrough = true; |
| 1237 | break; |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | // If the header has viable fallthrough, check whether the current loop |
| 1242 | // bottom is a viable exiting block. If so, bail out as rotating will |
| 1243 | // introduce an unnecessary branch. |
| 1244 | if (ViableTopFallthrough) { |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1245 | MachineBasicBlock *Bottom = *std::prev(LoopChain.end()); |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1246 | for (MachineBasicBlock *Succ : Bottom->successors()) { |
| 1247 | BlockChain *SuccChain = BlockToChain[Succ]; |
| 1248 | if (!LoopBlockSet.count(Succ) && |
| 1249 | (!SuccChain || Succ == *SuccChain->begin())) |
Chandler Carruth | 8c74c7b | 2012-04-16 09:31:23 +0000 | [diff] [blame] | 1250 | return; |
| 1251 | } |
| 1252 | } |
| 1253 | |
David Majnemer | 0d955d0 | 2016-08-11 22:21:41 +0000 | [diff] [blame] | 1254 | BlockChain::iterator ExitIt = find(LoopChain, ExitingBB); |
Chandler Carruth | 8c74c7b | 2012-04-16 09:31:23 +0000 | [diff] [blame] | 1255 | if (ExitIt == LoopChain.end()) |
| 1256 | return; |
| 1257 | |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 1258 | std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end()); |
Chandler Carruth | 8c74c7b | 2012-04-16 09:31:23 +0000 | [diff] [blame] | 1259 | } |
| 1260 | |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1261 | /// \brief Attempt to rotate a loop based on profile data to reduce branch cost. |
| 1262 | /// |
| 1263 | /// With profile data, we can determine the cost in terms of missed fall through |
| 1264 | /// opportunities when rotating a loop chain and select the best rotation. |
| 1265 | /// Basically, there are three kinds of cost to consider for each rotation: |
| 1266 | /// 1. The possibly missed fall through edge (if it exists) from BB out of |
| 1267 | /// the loop to the loop header. |
| 1268 | /// 2. The possibly missed fall through edges (if they exist) from the loop |
| 1269 | /// exits to BB out of the loop. |
| 1270 | /// 3. The missed fall through edge (if it exists) from the last BB to the |
| 1271 | /// first BB in the loop chain. |
| 1272 | /// Therefore, the cost for a given rotation is the sum of costs listed above. |
| 1273 | /// We select the best rotation with the smallest cost. |
| 1274 | void MachineBlockPlacement::rotateLoopWithProfile( |
| 1275 | BlockChain &LoopChain, MachineLoop &L, const BlockFilterSet &LoopBlockSet) { |
| 1276 | auto HeaderBB = L.getHeader(); |
David Majnemer | 0d955d0 | 2016-08-11 22:21:41 +0000 | [diff] [blame] | 1277 | auto HeaderIter = find(LoopChain, HeaderBB); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1278 | auto RotationPos = LoopChain.end(); |
| 1279 | |
| 1280 | BlockFrequency SmallestRotationCost = BlockFrequency::getMaxFrequency(); |
| 1281 | |
| 1282 | // A utility lambda that scales up a block frequency by dividing it by a |
| 1283 | // branch probability which is the reciprocal of the scale. |
| 1284 | auto ScaleBlockFrequency = [](BlockFrequency Freq, |
| 1285 | unsigned Scale) -> BlockFrequency { |
| 1286 | if (Scale == 0) |
| 1287 | return 0; |
| 1288 | // Use operator / between BlockFrequency and BranchProbability to implement |
| 1289 | // saturating multiplication. |
| 1290 | return Freq / BranchProbability(1, Scale); |
| 1291 | }; |
| 1292 | |
| 1293 | // Compute the cost of the missed fall-through edge to the loop header if the |
| 1294 | // chain head is not the loop header. As we only consider natural loops with |
| 1295 | // single header, this computation can be done only once. |
| 1296 | BlockFrequency HeaderFallThroughCost(0); |
| 1297 | for (auto *Pred : HeaderBB->predecessors()) { |
| 1298 | BlockChain *PredChain = BlockToChain[Pred]; |
| 1299 | if (!LoopBlockSet.count(Pred) && |
| 1300 | (!PredChain || Pred == *std::prev(PredChain->end()))) { |
| 1301 | auto EdgeFreq = |
| 1302 | MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB); |
| 1303 | auto FallThruCost = ScaleBlockFrequency(EdgeFreq, MisfetchCost); |
| 1304 | // If the predecessor has only an unconditional jump to the header, we |
| 1305 | // need to consider the cost of this jump. |
| 1306 | if (Pred->succ_size() == 1) |
| 1307 | FallThruCost += ScaleBlockFrequency(EdgeFreq, JumpInstCost); |
| 1308 | HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost); |
| 1309 | } |
| 1310 | } |
| 1311 | |
| 1312 | // Here we collect all exit blocks in the loop, and for each exit we find out |
| 1313 | // its hottest exit edge. For each loop rotation, we define the loop exit cost |
| 1314 | // as the sum of frequencies of exit edges we collect here, excluding the exit |
| 1315 | // edge from the tail of the loop chain. |
| 1316 | SmallVector<std::pair<MachineBasicBlock *, BlockFrequency>, 4> ExitsWithFreq; |
| 1317 | for (auto BB : LoopChain) { |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 1318 | auto LargestExitEdgeProb = BranchProbability::getZero(); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1319 | for (auto *Succ : BB->successors()) { |
| 1320 | BlockChain *SuccChain = BlockToChain[Succ]; |
| 1321 | if (!LoopBlockSet.count(Succ) && |
| 1322 | (!SuccChain || Succ == *SuccChain->begin())) { |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 1323 | auto SuccProb = MBPI->getEdgeProbability(BB, Succ); |
| 1324 | LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1325 | } |
| 1326 | } |
Cong Hou | d97c100 | 2015-12-01 05:29:22 +0000 | [diff] [blame] | 1327 | if (LargestExitEdgeProb > BranchProbability::getZero()) { |
| 1328 | auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb; |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1329 | ExitsWithFreq.emplace_back(BB, ExitFreq); |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | // In this loop we iterate every block in the loop chain and calculate the |
| 1334 | // cost assuming the block is the head of the loop chain. When the loop ends, |
| 1335 | // we should have found the best candidate as the loop chain's head. |
| 1336 | for (auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()), |
| 1337 | EndIter = LoopChain.end(); |
| 1338 | Iter != EndIter; Iter++, TailIter++) { |
| 1339 | // TailIter is used to track the tail of the loop chain if the block we are |
| 1340 | // checking (pointed by Iter) is the head of the chain. |
| 1341 | if (TailIter == LoopChain.end()) |
| 1342 | TailIter = LoopChain.begin(); |
| 1343 | |
| 1344 | auto TailBB = *TailIter; |
| 1345 | |
| 1346 | // Calculate the cost by putting this BB to the top. |
| 1347 | BlockFrequency Cost = 0; |
| 1348 | |
| 1349 | // If the current BB is the loop header, we need to take into account the |
| 1350 | // cost of the missed fall through edge from outside of the loop to the |
| 1351 | // header. |
| 1352 | if (Iter != HeaderIter) |
| 1353 | Cost += HeaderFallThroughCost; |
| 1354 | |
| 1355 | // Collect the loop exit cost by summing up frequencies of all exit edges |
| 1356 | // except the one from the chain tail. |
| 1357 | for (auto &ExitWithFreq : ExitsWithFreq) |
| 1358 | if (TailBB != ExitWithFreq.first) |
| 1359 | Cost += ExitWithFreq.second; |
| 1360 | |
| 1361 | // The cost of breaking the once fall-through edge from the tail to the top |
| 1362 | // of the loop chain. Here we need to consider three cases: |
| 1363 | // 1. If the tail node has only one successor, then we will get an |
| 1364 | // additional jmp instruction. So the cost here is (MisfetchCost + |
| 1365 | // JumpInstCost) * tail node frequency. |
| 1366 | // 2. If the tail node has two successors, then we may still get an |
| 1367 | // additional jmp instruction if the layout successor after the loop |
| 1368 | // chain is not its CFG successor. Note that the more frequently executed |
| 1369 | // jmp instruction will be put ahead of the other one. Assume the |
| 1370 | // frequency of those two branches are x and y, where x is the frequency |
| 1371 | // of the edge to the chain head, then the cost will be |
| 1372 | // (x * MisfetechCost + min(x, y) * JumpInstCost) * tail node frequency. |
| 1373 | // 3. If the tail node has more than two successors (this rarely happens), |
| 1374 | // we won't consider any additional cost. |
| 1375 | if (TailBB->isSuccessor(*Iter)) { |
| 1376 | auto TailBBFreq = MBFI->getBlockFreq(TailBB); |
| 1377 | if (TailBB->succ_size() == 1) |
| 1378 | Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(), |
| 1379 | MisfetchCost + JumpInstCost); |
| 1380 | else if (TailBB->succ_size() == 2) { |
| 1381 | auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter); |
| 1382 | auto TailToHeadFreq = TailBBFreq * TailToHeadProb; |
| 1383 | auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2) |
| 1384 | ? TailBBFreq * TailToHeadProb.getCompl() |
| 1385 | : TailToHeadFreq; |
| 1386 | Cost += ScaleBlockFrequency(TailToHeadFreq, MisfetchCost) + |
| 1387 | ScaleBlockFrequency(ColderEdgeFreq, JumpInstCost); |
| 1388 | } |
| 1389 | } |
| 1390 | |
Philip Reames | b9688f4 | 2016-03-02 21:45:13 +0000 | [diff] [blame] | 1391 | DEBUG(dbgs() << "The cost of loop rotation by making " << getBlockName(*Iter) |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1392 | << " to the top: " << Cost.getFrequency() << "\n"); |
| 1393 | |
| 1394 | if (Cost < SmallestRotationCost) { |
| 1395 | SmallestRotationCost = Cost; |
| 1396 | RotationPos = Iter; |
| 1397 | } |
| 1398 | } |
| 1399 | |
| 1400 | if (RotationPos != LoopChain.end()) { |
Philip Reames | b9688f4 | 2016-03-02 21:45:13 +0000 | [diff] [blame] | 1401 | DEBUG(dbgs() << "Rotate loop by making " << getBlockName(*RotationPos) |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1402 | << " to the top\n"); |
| 1403 | std::rotate(LoopChain.begin(), RotationPos, LoopChain.end()); |
| 1404 | } |
| 1405 | } |
| 1406 | |
Cong Hou | b90b9e0 | 2015-11-02 21:24:00 +0000 | [diff] [blame] | 1407 | /// \brief Collect blocks in the given loop that are to be placed. |
| 1408 | /// |
| 1409 | /// When profile data is available, exclude cold blocks from the returned set; |
| 1410 | /// otherwise, collect all blocks in the loop. |
| 1411 | MachineBlockPlacement::BlockFilterSet |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1412 | MachineBlockPlacement::collectLoopBlockSet(MachineLoop &L) { |
Cong Hou | b90b9e0 | 2015-11-02 21:24:00 +0000 | [diff] [blame] | 1413 | BlockFilterSet LoopBlockSet; |
| 1414 | |
| 1415 | // Filter cold blocks off from LoopBlockSet when profile data is available. |
| 1416 | // Collect the sum of frequencies of incoming edges to the loop header from |
| 1417 | // outside. If we treat the loop as a super block, this is the frequency of |
| 1418 | // the loop. Then for each block in the loop, we calculate the ratio between |
| 1419 | // its frequency and the frequency of the loop block. When it is too small, |
| 1420 | // don't add it to the loop chain. If there are outer loops, then this block |
| 1421 | // will be merged into the first outer loop chain for which this block is not |
| 1422 | // cold anymore. This needs precise profile data and we only do this when |
| 1423 | // profile data is available. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1424 | if (F->getFunction()->getEntryCount()) { |
Cong Hou | b90b9e0 | 2015-11-02 21:24:00 +0000 | [diff] [blame] | 1425 | BlockFrequency LoopFreq(0); |
| 1426 | for (auto LoopPred : L.getHeader()->predecessors()) |
| 1427 | if (!L.contains(LoopPred)) |
| 1428 | LoopFreq += MBFI->getBlockFreq(LoopPred) * |
| 1429 | MBPI->getEdgeProbability(LoopPred, L.getHeader()); |
| 1430 | |
| 1431 | for (MachineBasicBlock *LoopBB : L.getBlocks()) { |
| 1432 | auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency(); |
| 1433 | if (Freq == 0 || LoopFreq.getFrequency() / Freq > LoopToColdBlockRatio) |
| 1434 | continue; |
| 1435 | LoopBlockSet.insert(LoopBB); |
| 1436 | } |
| 1437 | } else |
| 1438 | LoopBlockSet.insert(L.block_begin(), L.block_end()); |
| 1439 | |
| 1440 | return LoopBlockSet; |
| 1441 | } |
| 1442 | |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 1443 | /// \brief Forms basic block chains from the natural loop structures. |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1444 | /// |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 1445 | /// These chains are designed to preserve the existing *structure* of the code |
| 1446 | /// as much as possible. We can then stitch the chains together in a way which |
| 1447 | /// both preserves the topological structure and minimizes taken conditional |
| 1448 | /// branches. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1449 | void MachineBlockPlacement::buildLoopChains(MachineLoop &L) { |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 1450 | // First recurse through any nested loops, building chains for those inner |
| 1451 | // loops. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1452 | for (MachineLoop *InnerLoop : L) |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1453 | buildLoopChains(*InnerLoop); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1454 | |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1455 | assert(BlockWorkList.empty()); |
| 1456 | assert(EHPadWorkList.empty()); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1457 | BlockFilterSet LoopBlockSet = collectLoopBlockSet(L); |
Chandler Carruth | 03adbd4 | 2011-11-27 13:34:33 +0000 | [diff] [blame] | 1458 | |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1459 | // Check if we have profile data for this function. If yes, we will rotate |
| 1460 | // this loop by modeling costs more precisely which requires the profile data |
| 1461 | // for better layout. |
| 1462 | bool RotateLoopWithProfile = |
Xinliang David Li | f0ab6df | 2016-05-12 02:04:41 +0000 | [diff] [blame] | 1463 | ForcePreciseRotationCost || |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1464 | (PreciseRotationCost && F->getFunction()->getEntryCount()); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1465 | |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1466 | // First check to see if there is an obviously preferable top block for the |
| 1467 | // loop. This will default to the header, but may end up as one of the |
| 1468 | // predecessors to the header if there is one which will result in strictly |
| 1469 | // fewer branches in the loop body. |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1470 | // When we use profile data to rotate the loop, this is unnecessary. |
| 1471 | MachineBasicBlock *LoopTop = |
| 1472 | RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet); |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1473 | |
| 1474 | // If we selected just the header for the loop top, look for a potentially |
| 1475 | // profitable exit block in the event that rotating the loop can eliminate |
| 1476 | // branches by placing an exit edge at the bottom. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1477 | MachineBasicBlock *ExitingBB = nullptr; |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1478 | if (!RotateLoopWithProfile && LoopTop == L.getHeader()) |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1479 | ExitingBB = findBestLoopExit(L, LoopBlockSet); |
Chandler Carruth | 8c0b41d | 2012-04-16 13:33:36 +0000 | [diff] [blame] | 1480 | |
| 1481 | BlockChain &LoopChain = *BlockToChain[LoopTop]; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1482 | |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1483 | // FIXME: This is a really lame way of walking the chains in the loop: we |
| 1484 | // walk the blocks, and use a set to prevent visiting a particular chain |
| 1485 | // twice. |
Jakub Staszak | 9061616 | 2011-12-21 23:02:08 +0000 | [diff] [blame] | 1486 | SmallPtrSet<BlockChain *, 4> UpdatedPreds; |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 1487 | assert(LoopChain.UnscheduledPredecessors == 0); |
Jakub Staszak | 190c712 | 2011-12-07 19:46:10 +0000 | [diff] [blame] | 1488 | UpdatedPreds.insert(&LoopChain); |
Cong Hou | b90b9e0 | 2015-11-02 21:24:00 +0000 | [diff] [blame] | 1489 | |
Amaury Sechet | eae09c2 | 2016-03-14 21:24:11 +0000 | [diff] [blame] | 1490 | for (MachineBasicBlock *LoopBB : LoopBlockSet) |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1491 | fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1492 | |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1493 | buildChain(LoopTop, LoopChain, &LoopBlockSet); |
Cong Hou | 7745dbc | 2015-10-19 23:16:40 +0000 | [diff] [blame] | 1494 | |
| 1495 | if (RotateLoopWithProfile) |
| 1496 | rotateLoopWithProfile(LoopChain, L, LoopBlockSet); |
| 1497 | else |
| 1498 | rotateLoop(LoopChain, ExitingBB, LoopBlockSet); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1499 | |
| 1500 | DEBUG({ |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1501 | // Crash at the end so we get all of the debugging output first. |
| 1502 | bool BadLoop = false; |
Philip Reames | ae27b23 | 2016-03-03 00:58:43 +0000 | [diff] [blame] | 1503 | if (LoopChain.UnscheduledPredecessors) { |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1504 | BadLoop = true; |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1505 | dbgs() << "Loop chain contains a block without its preds placed!\n" |
| 1506 | << " Loop header: " << getBlockName(*L.block_begin()) << "\n" |
| 1507 | << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n"; |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1508 | } |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1509 | for (MachineBasicBlock *ChainBB : LoopChain) { |
| 1510 | dbgs() << " ... " << getBlockName(ChainBB) << "\n"; |
| 1511 | if (!LoopBlockSet.erase(ChainBB)) { |
Chandler Carruth | 0a31d14 | 2011-11-14 10:55:53 +0000 | [diff] [blame] | 1512 | // We don't mark the loop as bad here because there are real situations |
| 1513 | // where this can occur. For example, with an unanalyzable fallthrough |
Chandler Carruth | 99fe42f | 2011-11-23 10:35:36 +0000 | [diff] [blame] | 1514 | // from a loop block to a non-loop block or vice versa. |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1515 | dbgs() << "Loop chain contains a block not contained by the loop!\n" |
| 1516 | << " Loop header: " << getBlockName(*L.block_begin()) << "\n" |
| 1517 | << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1518 | << " Bad block: " << getBlockName(ChainBB) << "\n"; |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1519 | } |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1520 | } |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1521 | |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1522 | if (!LoopBlockSet.empty()) { |
| 1523 | BadLoop = true; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1524 | for (MachineBasicBlock *LoopBB : LoopBlockSet) |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1525 | dbgs() << "Loop contains blocks never placed into a chain!\n" |
| 1526 | << " Loop header: " << getBlockName(*L.block_begin()) << "\n" |
| 1527 | << " Chain header: " << getBlockName(*LoopChain.begin()) << "\n" |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1528 | << " Bad block: " << getBlockName(LoopBB) << "\n"; |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1529 | } |
| 1530 | assert(!BadLoop && "Detected problems with the placement of this loop."); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1531 | }); |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1532 | |
| 1533 | BlockWorkList.clear(); |
| 1534 | EHPadWorkList.clear(); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1535 | } |
| 1536 | |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 1537 | /// When OutlineOpitonalBranches is on, this method collects BBs that |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 1538 | /// dominates all terminator blocks of the function \p F. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1539 | void MachineBlockPlacement::collectMustExecuteBBs() { |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 1540 | if (OutlineOptionalBranches) { |
| 1541 | // Find the nearest common dominator of all of F's terminators. |
| 1542 | MachineBasicBlock *Terminator = nullptr; |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1543 | for (MachineBasicBlock &MBB : *F) { |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 1544 | if (MBB.succ_size() == 0) { |
| 1545 | if (Terminator == nullptr) |
| 1546 | Terminator = &MBB; |
| 1547 | else |
| 1548 | Terminator = MDT->findNearestCommonDominator(Terminator, &MBB); |
| 1549 | } |
| 1550 | } |
| 1551 | |
| 1552 | // MBBs dominating this common dominator are unavoidable. |
| 1553 | UnavoidableBlocks.clear(); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1554 | for (MachineBasicBlock &MBB : *F) { |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 1555 | if (MDT->dominates(&MBB, Terminator)) { |
| 1556 | UnavoidableBlocks.insert(&MBB); |
| 1557 | } |
| 1558 | } |
| 1559 | } |
| 1560 | } |
| 1561 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1562 | void MachineBlockPlacement::buildCFGChains() { |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1563 | // Ensure that every BB in the function has an associated chain to simplify |
| 1564 | // the assumptions of the remaining algorithm. |
Chandler Carruth | f3dc9ef | 2011-11-19 10:26:02 +0000 | [diff] [blame] | 1565 | SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1566 | for (MachineFunction::iterator FI = F->begin(), FE = F->end(); FI != FE; |
| 1567 | ++FI) { |
Duncan P. N. Exon Smith | 6ac07fd | 2015-10-09 19:36:12 +0000 | [diff] [blame] | 1568 | MachineBasicBlock *BB = &*FI; |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 1569 | BlockChain *Chain = |
| 1570 | new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB); |
Chandler Carruth | f3dc9ef | 2011-11-19 10:26:02 +0000 | [diff] [blame] | 1571 | // Also, merge any blocks which we cannot reason about and must preserve |
| 1572 | // the exact fallthrough behavior for. |
| 1573 | for (;;) { |
| 1574 | Cond.clear(); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1575 | MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 1576 | if (!TII->analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough()) |
Chandler Carruth | f3dc9ef | 2011-11-19 10:26:02 +0000 | [diff] [blame] | 1577 | break; |
| 1578 | |
Duncan P. N. Exon Smith | 6ac07fd | 2015-10-09 19:36:12 +0000 | [diff] [blame] | 1579 | MachineFunction::iterator NextFI = std::next(FI); |
| 1580 | MachineBasicBlock *NextBB = &*NextFI; |
Chandler Carruth | f3dc9ef | 2011-11-19 10:26:02 +0000 | [diff] [blame] | 1581 | // Ensure that the layout successor is a viable block, as we know that |
| 1582 | // fallthrough is a possibility. |
| 1583 | assert(NextFI != FE && "Can't fallthrough past the last block."); |
| 1584 | DEBUG(dbgs() << "Pre-merging due to unanalyzable fallthrough: " |
| 1585 | << getBlockName(BB) << " -> " << getBlockName(NextBB) |
| 1586 | << "\n"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1587 | Chain->merge(NextBB, nullptr); |
Chandler Carruth | f3dc9ef | 2011-11-19 10:26:02 +0000 | [diff] [blame] | 1588 | FI = NextFI; |
| 1589 | BB = NextBB; |
| 1590 | } |
| 1591 | } |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1592 | |
Xinliang David Li | 071d0f1 | 2016-06-12 16:54:03 +0000 | [diff] [blame] | 1593 | // Turned on with OutlineOptionalBranches option |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1594 | collectMustExecuteBBs(); |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 1595 | |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1596 | // Build any loop-based chains. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1597 | for (MachineLoop *L : *MLI) |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1598 | buildLoopChains(*L); |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 1599 | |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1600 | assert(BlockWorkList.empty()); |
| 1601 | assert(EHPadWorkList.empty()); |
Chandler Carruth | bd1be4d | 2011-10-23 09:18:45 +0000 | [diff] [blame] | 1602 | |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1603 | SmallPtrSet<BlockChain *, 4> UpdatedPreds; |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1604 | for (MachineBasicBlock &MBB : *F) |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1605 | fillWorkLists(&MBB, UpdatedPreds); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1606 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1607 | BlockChain &FunctionChain = *BlockToChain[&F->front()]; |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1608 | buildChain(&F->front(), FunctionChain); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1609 | |
Matt Arsenault | 0f5f015 | 2013-12-10 18:55:37 +0000 | [diff] [blame] | 1610 | #ifndef NDEBUG |
Matt Arsenault | 79d55f5 | 2013-12-05 20:02:18 +0000 | [diff] [blame] | 1611 | typedef SmallPtrSet<MachineBasicBlock *, 16> FunctionBlockSetType; |
Matt Arsenault | 0f5f015 | 2013-12-10 18:55:37 +0000 | [diff] [blame] | 1612 | #endif |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1613 | DEBUG({ |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1614 | // Crash at the end so we get all of the debugging output first. |
| 1615 | bool BadFunc = false; |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1616 | FunctionBlockSetType FunctionBlockSet; |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1617 | for (MachineBasicBlock &MBB : *F) |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1618 | FunctionBlockSet.insert(&MBB); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1619 | |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1620 | for (MachineBasicBlock *ChainBB : FunctionChain) |
| 1621 | if (!FunctionBlockSet.erase(ChainBB)) { |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1622 | BadFunc = true; |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1623 | dbgs() << "Function chain contains a block not in the function!\n" |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1624 | << " Bad block: " << getBlockName(ChainBB) << "\n"; |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1625 | } |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1626 | |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1627 | if (!FunctionBlockSet.empty()) { |
| 1628 | BadFunc = true; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1629 | for (MachineBasicBlock *RemainingBB : FunctionBlockSet) |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1630 | dbgs() << "Function contains blocks never placed into a chain!\n" |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1631 | << " Bad block: " << getBlockName(RemainingBB) << "\n"; |
Chandler Carruth | 8e1d906 | 2011-11-13 21:39:51 +0000 | [diff] [blame] | 1632 | } |
| 1633 | assert(!BadFunc && "Detected problems with the block placement."); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1634 | }); |
| 1635 | |
| 1636 | // Splice the blocks into place. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1637 | MachineFunction::iterator InsertPos = F->begin(); |
Xinliang David Li | 449cdfd | 2016-06-24 22:54:21 +0000 | [diff] [blame] | 1638 | DEBUG(dbgs() << "[MBP] Function: "<< F->getName() << "\n"); |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1639 | for (MachineBasicBlock *ChainBB : FunctionChain) { |
| 1640 | DEBUG(dbgs() << (ChainBB == *FunctionChain.begin() ? "Placing chain " |
| 1641 | : " ... ") |
| 1642 | << getBlockName(ChainBB) << "\n"); |
| 1643 | if (InsertPos != MachineFunction::iterator(ChainBB)) |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1644 | F->splice(InsertPos, ChainBB); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1645 | else |
| 1646 | ++InsertPos; |
| 1647 | |
| 1648 | // Update the terminator of the previous block. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1649 | if (ChainBB == *FunctionChain.begin()) |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1650 | continue; |
Duncan P. N. Exon Smith | 6ac07fd | 2015-10-09 19:36:12 +0000 | [diff] [blame] | 1651 | MachineBasicBlock *PrevBB = &*std::prev(MachineFunction::iterator(ChainBB)); |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1652 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1653 | // FIXME: It would be awesome of updateTerminator would just return rather |
| 1654 | // than assert when the branch cannot be analyzed in order to remove this |
| 1655 | // boiler plate. |
| 1656 | Cond.clear(); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1657 | MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. |
Shuxin Yang | 8b8fd21 | 2013-06-04 01:00:57 +0000 | [diff] [blame] | 1658 | |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1659 | // The "PrevBB" is not yet updated to reflect current code layout, so, |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 1660 | // o. it may fall-through to a block without explicit "goto" instruction |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1661 | // before layout, and no longer fall-through it after layout; or |
| 1662 | // o. just opposite. |
| 1663 | // |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 1664 | // analyzeBranch() may return erroneous value for FBB when these two |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1665 | // situations take place. For the first scenario FBB is mistakenly set NULL; |
| 1666 | // for the 2nd scenario, the FBB, which is expected to be NULL, is |
| 1667 | // mistakenly pointing to "*BI". |
| 1668 | // Thus, if the future change needs to use FBB before the layout is set, it |
| 1669 | // has to correct FBB first by using the code similar to the following: |
| 1670 | // |
| 1671 | // if (!Cond.empty() && (!FBB || FBB == ChainBB)) { |
| 1672 | // PrevBB->updateTerminator(); |
| 1673 | // Cond.clear(); |
| 1674 | // TBB = FBB = nullptr; |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 1675 | // if (TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) { |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1676 | // // FIXME: This should never take place. |
| 1677 | // TBB = FBB = nullptr; |
| 1678 | // } |
| 1679 | // } |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 1680 | if (!TII->analyzeBranch(*PrevBB, TBB, FBB, Cond)) |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1681 | PrevBB->updateTerminator(); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1682 | } |
Chandler Carruth | 8d15078 | 2011-11-13 11:20:44 +0000 | [diff] [blame] | 1683 | |
| 1684 | // Fixup the last block. |
| 1685 | Cond.clear(); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1686 | MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 1687 | if (!TII->analyzeBranch(F->back(), TBB, FBB, Cond)) |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1688 | F->back().updateTerminator(); |
Xinliang David Li | 93926ac | 2016-07-01 05:46:48 +0000 | [diff] [blame] | 1689 | |
| 1690 | BlockWorkList.clear(); |
| 1691 | EHPadWorkList.clear(); |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1692 | } |
| 1693 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1694 | void MachineBlockPlacement::optimizeBranches() { |
| 1695 | BlockChain &FunctionChain = *BlockToChain[&F->front()]; |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1696 | SmallVector<MachineOperand, 4> Cond; // For AnalyzeBranch. |
Quentin Colombet | 776e6de | 2016-05-02 22:58:59 +0000 | [diff] [blame] | 1697 | |
| 1698 | // Now that all the basic blocks in the chain have the proper layout, |
| 1699 | // make a final call to AnalyzeBranch with AllowModify set. |
| 1700 | // Indeed, the target may be able to optimize the branches in a way we |
| 1701 | // cannot because all branches may not be analyzable. |
| 1702 | // E.g., the target may be able to remove an unconditional branch to |
| 1703 | // a fallthrough when it occurs after predicated terminators. |
| 1704 | for (MachineBasicBlock *ChainBB : FunctionChain) { |
| 1705 | Cond.clear(); |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1706 | MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For AnalyzeBranch. |
Jacques Pienaar | 71c30a1 | 2016-07-15 14:41:04 +0000 | [diff] [blame] | 1707 | if (!TII->analyzeBranch(*ChainBB, TBB, FBB, Cond, /*AllowModify*/ true)) { |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1708 | // If PrevBB has a two-way branch, try to re-order the branches |
| 1709 | // such that we branch to the successor with higher probability first. |
| 1710 | if (TBB && !Cond.empty() && FBB && |
| 1711 | MBPI->getEdgeProbability(ChainBB, FBB) > |
| 1712 | MBPI->getEdgeProbability(ChainBB, TBB) && |
Matt Arsenault | 1b9fc8e | 2016-09-14 20:43:16 +0000 | [diff] [blame] | 1713 | !TII->reverseBranchCondition(Cond)) { |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1714 | DEBUG(dbgs() << "Reverse order of the two branches: " |
| 1715 | << getBlockName(ChainBB) << "\n"); |
| 1716 | DEBUG(dbgs() << " Edge probability: " |
| 1717 | << MBPI->getEdgeProbability(ChainBB, FBB) << " vs " |
| 1718 | << MBPI->getEdgeProbability(ChainBB, TBB) << "\n"); |
| 1719 | DebugLoc dl; // FIXME: this is nowhere |
Matt Arsenault | 1b9fc8e | 2016-09-14 20:43:16 +0000 | [diff] [blame] | 1720 | TII->removeBranch(*ChainBB); |
Matt Arsenault | e8e0f5c | 2016-09-14 17:24:15 +0000 | [diff] [blame] | 1721 | TII->insertBranch(*ChainBB, FBB, TBB, Cond, dl); |
Haicheng Wu | 90a5565 | 2016-05-24 22:16:14 +0000 | [diff] [blame] | 1722 | ChainBB->updateTerminator(); |
| 1723 | } |
| 1724 | } |
Quentin Colombet | 776e6de | 2016-05-02 22:58:59 +0000 | [diff] [blame] | 1725 | } |
Haicheng Wu | e749ce5 | 2016-04-29 17:06:44 +0000 | [diff] [blame] | 1726 | } |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1727 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1728 | void MachineBlockPlacement::alignBlocks() { |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1729 | // Walk through the backedges of the function now that we have fully laid out |
| 1730 | // the basic blocks and align the destination of each backedge. We don't rely |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1731 | // exclusively on the loop info here so that we can align backedges in |
| 1732 | // unnatural CFGs and backedges that were introduced purely because of the |
| 1733 | // loop rotations done during this layout pass. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1734 | if (F->getFunction()->optForSize()) |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 1735 | return; |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1736 | BlockChain &FunctionChain = *BlockToChain[&F->front()]; |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1737 | if (FunctionChain.begin() == FunctionChain.end()) |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 1738 | return; // Empty chain. |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 1739 | |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1740 | const BranchProbability ColdProb(1, 5); // 20% |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1741 | BlockFrequency EntryFreq = MBFI->getBlockFreq(&F->front()); |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1742 | BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb; |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1743 | for (MachineBasicBlock *ChainBB : FunctionChain) { |
| 1744 | if (ChainBB == *FunctionChain.begin()) |
| 1745 | continue; |
| 1746 | |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1747 | // Don't align non-looping basic blocks. These are unlikely to execute |
| 1748 | // enough times to matter in practice. Note that we'll still handle |
| 1749 | // unnatural CFGs inside of a natural outer loop (the common case) and |
| 1750 | // rotated loops. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1751 | MachineLoop *L = MLI->getLoopFor(ChainBB); |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1752 | if (!L) |
| 1753 | continue; |
| 1754 | |
Hal Finkel | 5772566 | 2015-01-03 17:58:24 +0000 | [diff] [blame] | 1755 | unsigned Align = TLI->getPrefLoopAlignment(L); |
| 1756 | if (!Align) |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 1757 | continue; // Don't care about loop alignment. |
Hal Finkel | 5772566 | 2015-01-03 17:58:24 +0000 | [diff] [blame] | 1758 | |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1759 | // If the block is cold relative to the function entry don't waste space |
| 1760 | // aligning it. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1761 | BlockFrequency Freq = MBFI->getBlockFreq(ChainBB); |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1762 | if (Freq < WeightedEntryFreq) |
| 1763 | continue; |
| 1764 | |
| 1765 | // If the block is cold relative to its loop header, don't align it |
| 1766 | // regardless of what edges into the block exist. |
| 1767 | MachineBasicBlock *LoopHeader = L->getHeader(); |
| 1768 | BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader); |
| 1769 | if (Freq < (LoopHeaderFreq * ColdProb)) |
| 1770 | continue; |
| 1771 | |
| 1772 | // Check for the existence of a non-layout predecessor which would benefit |
| 1773 | // from aligning this block. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1774 | MachineBasicBlock *LayoutPred = |
| 1775 | &*std::prev(MachineFunction::iterator(ChainBB)); |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1776 | |
| 1777 | // Force alignment if all the predecessors are jumps. We already checked |
| 1778 | // that the block isn't cold above. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1779 | if (!LayoutPred->isSuccessor(ChainBB)) { |
| 1780 | ChainBB->setAlignment(Align); |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1781 | continue; |
| 1782 | } |
| 1783 | |
| 1784 | // Align this block if the layout predecessor's edge into this block is |
Nadav Rotem | 6036f58 | 2013-03-29 16:34:23 +0000 | [diff] [blame] | 1785 | // cold relative to the block. When this is true, other predecessors make up |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1786 | // all of the hot entries into the block and thus alignment is likely to be |
| 1787 | // important. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1788 | BranchProbability LayoutProb = |
| 1789 | MBPI->getEdgeProbability(LayoutPred, ChainBB); |
Chandler Carruth | 881d0a7 | 2012-08-07 09:45:24 +0000 | [diff] [blame] | 1790 | BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb; |
| 1791 | if (LayoutEdgeFreq <= (Freq * ColdProb)) |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 1792 | ChainBB->setAlignment(Align); |
Chandler Carruth | ccc7e42 | 2012-04-16 01:12:56 +0000 | [diff] [blame] | 1793 | } |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 1794 | } |
| 1795 | |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 1796 | /// Tail duplicate \p BB into (some) predecessors if profitable, repeating if |
| 1797 | /// it was duplicated into its chain predecessor and removed. |
| 1798 | /// \p BB - Basic block that may be duplicated. |
| 1799 | /// |
| 1800 | /// \p LPred - Chosen layout predecessor of \p BB. |
| 1801 | /// Updated to be the chain end if LPred is removed. |
| 1802 | /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. |
| 1803 | /// \p BlockFilter - Set of blocks that belong to the loop being laid out. |
| 1804 | /// Used to identify which blocks to update predecessor |
| 1805 | /// counts. |
| 1806 | /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was |
| 1807 | /// chosen in the given order due to unnatural CFG |
| 1808 | /// only needed if \p BB is removed and |
| 1809 | /// \p PrevUnplacedBlockIt pointed to \p BB. |
| 1810 | /// @return true if \p BB was removed. |
| 1811 | bool MachineBlockPlacement::repeatedlyTailDuplicateBlock( |
| 1812 | MachineBasicBlock *BB, MachineBasicBlock *&LPred, |
| 1813 | MachineBasicBlock *LoopHeaderBB, |
| 1814 | BlockChain &Chain, BlockFilterSet *BlockFilter, |
| 1815 | MachineFunction::iterator &PrevUnplacedBlockIt) { |
| 1816 | bool Removed, DuplicatedToLPred; |
| 1817 | bool DuplicatedToOriginalLPred; |
| 1818 | Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter, |
| 1819 | PrevUnplacedBlockIt, |
| 1820 | DuplicatedToLPred); |
| 1821 | if (!Removed) |
| 1822 | return false; |
| 1823 | DuplicatedToOriginalLPred = DuplicatedToLPred; |
| 1824 | // Iteratively try to duplicate again. It can happen that a block that is |
| 1825 | // duplicated into is still small enough to be duplicated again. |
| 1826 | // No need to call markBlockSuccessors in this case, as the blocks being |
| 1827 | // duplicated from here on are already scheduled. |
| 1828 | // Note that DuplicatedToLPred always implies Removed. |
| 1829 | while (DuplicatedToLPred) { |
| 1830 | assert (Removed && "Block must have been removed to be duplicated into its " |
| 1831 | "layout predecessor."); |
| 1832 | MachineBasicBlock *DupBB, *DupPred; |
| 1833 | // The removal callback causes Chain.end() to be updated when a block is |
| 1834 | // removed. On the first pass through the loop, the chain end should be the |
| 1835 | // same as it was on function entry. On subsequent passes, because we are |
| 1836 | // duplicating the block at the end of the chain, if it is removed the |
| 1837 | // chain will have shrunk by one block. |
| 1838 | BlockChain::iterator ChainEnd = Chain.end(); |
| 1839 | DupBB = *(--ChainEnd); |
| 1840 | // Now try to duplicate again. |
| 1841 | if (ChainEnd == Chain.begin()) |
| 1842 | break; |
| 1843 | DupPred = *std::prev(ChainEnd); |
| 1844 | Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter, |
| 1845 | PrevUnplacedBlockIt, |
| 1846 | DuplicatedToLPred); |
| 1847 | } |
| 1848 | // If BB was duplicated into LPred, it is now scheduled. But because it was |
| 1849 | // removed, markChainSuccessors won't be called for its chain. Instead we |
| 1850 | // call markBlockSuccessors for LPred to achieve the same effect. This must go |
| 1851 | // at the end because repeating the tail duplication can increase the number |
| 1852 | // of unscheduled predecessors. |
| 1853 | LPred = *std::prev(Chain.end()); |
| 1854 | if (DuplicatedToOriginalLPred) |
| 1855 | markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter); |
| 1856 | return true; |
| 1857 | } |
| 1858 | |
| 1859 | /// Tail duplicate \p BB into (some) predecessors if profitable. |
| 1860 | /// \p BB - Basic block that may be duplicated |
| 1861 | /// \p LPred - Chosen layout predecessor of \p BB |
| 1862 | /// \p Chain - Chain to which \p LPred belongs, and \p BB will belong. |
| 1863 | /// \p BlockFilter - Set of blocks that belong to the loop being laid out. |
| 1864 | /// Used to identify which blocks to update predecessor |
| 1865 | /// counts. |
| 1866 | /// \p PrevUnplacedBlockIt - Iterator pointing to the last block that was |
| 1867 | /// chosen in the given order due to unnatural CFG |
| 1868 | /// only needed if \p BB is removed and |
| 1869 | /// \p PrevUnplacedBlockIt pointed to \p BB. |
| 1870 | /// \p DuplicatedToLPred - True if the block was duplicated into LPred. Will |
| 1871 | /// only be true if the block was removed. |
| 1872 | /// \return - True if the block was duplicated into all preds and removed. |
| 1873 | bool MachineBlockPlacement::maybeTailDuplicateBlock( |
| 1874 | MachineBasicBlock *BB, MachineBasicBlock *LPred, |
| 1875 | const BlockChain &Chain, BlockFilterSet *BlockFilter, |
| 1876 | MachineFunction::iterator &PrevUnplacedBlockIt, |
| 1877 | bool &DuplicatedToLPred) { |
| 1878 | |
| 1879 | DuplicatedToLPred = false; |
| 1880 | DEBUG(dbgs() << "Redoing tail duplication for Succ#" |
| 1881 | << BB->getNumber() << "\n"); |
| 1882 | bool IsSimple = TailDup.isSimpleBB(BB); |
| 1883 | // Blocks with single successors don't create additional fallthrough |
| 1884 | // opportunities. Don't duplicate them. TODO: When conditional exits are |
| 1885 | // analyzable, allow them to be duplicated. |
| 1886 | if (!IsSimple && BB->succ_size() == 1) |
| 1887 | return false; |
| 1888 | if (!TailDup.shouldTailDuplicate(IsSimple, *BB)) |
| 1889 | return false; |
| 1890 | // This has to be a callback because none of it can be done after |
| 1891 | // BB is deleted. |
| 1892 | bool Removed = false; |
| 1893 | auto RemovalCallback = |
| 1894 | [&](MachineBasicBlock *RemBB) { |
| 1895 | // Signal to outer function |
| 1896 | Removed = true; |
| 1897 | |
| 1898 | // Conservative default. |
| 1899 | bool InWorkList = true; |
| 1900 | // Remove from the Chain and Chain Map |
| 1901 | if (BlockToChain.count(RemBB)) { |
| 1902 | BlockChain *Chain = BlockToChain[RemBB]; |
| 1903 | InWorkList = Chain->UnscheduledPredecessors == 0; |
| 1904 | Chain->remove(RemBB); |
| 1905 | BlockToChain.erase(RemBB); |
| 1906 | } |
| 1907 | |
| 1908 | // Handle the unplaced block iterator |
| 1909 | if (&(*PrevUnplacedBlockIt) == RemBB) { |
| 1910 | PrevUnplacedBlockIt++; |
| 1911 | } |
| 1912 | |
| 1913 | // Handle the Work Lists |
| 1914 | if (InWorkList) { |
| 1915 | SmallVectorImpl<MachineBasicBlock *> &RemoveList = BlockWorkList; |
| 1916 | if (RemBB->isEHPad()) |
| 1917 | RemoveList = EHPadWorkList; |
| 1918 | RemoveList.erase( |
| 1919 | remove_if(RemoveList, |
| 1920 | [RemBB](MachineBasicBlock *BB) {return BB == RemBB;}), |
| 1921 | RemoveList.end()); |
| 1922 | } |
| 1923 | |
| 1924 | // Handle the filter set |
| 1925 | if (BlockFilter) { |
| 1926 | BlockFilter->erase(RemBB); |
| 1927 | } |
| 1928 | |
| 1929 | // Remove the block from loop info. |
| 1930 | MLI->removeBlock(RemBB); |
| 1931 | |
| 1932 | // TailDuplicator handles removing it from loops. |
| 1933 | DEBUG(dbgs() << "TailDuplicator deleted block: " |
| 1934 | << getBlockName(RemBB) << "\n"); |
| 1935 | }; |
| 1936 | auto RemovalCallbackRef = |
| 1937 | llvm::function_ref<void(MachineBasicBlock*)>(RemovalCallback); |
| 1938 | |
| 1939 | SmallVector<MachineBasicBlock *, 8> DuplicatedPreds; |
| 1940 | TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred, |
| 1941 | &DuplicatedPreds, &RemovalCallbackRef); |
| 1942 | |
| 1943 | // Update UnscheduledPredecessors to reflect tail-duplication. |
| 1944 | DuplicatedToLPred = false; |
| 1945 | for (MachineBasicBlock *Pred : DuplicatedPreds) { |
| 1946 | // We're only looking for unscheduled predecessors that match the filter. |
| 1947 | BlockChain* PredChain = BlockToChain[Pred]; |
| 1948 | if (Pred == LPred) |
| 1949 | DuplicatedToLPred = true; |
| 1950 | if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) |
| 1951 | || PredChain == &Chain) |
| 1952 | continue; |
| 1953 | for (MachineBasicBlock *NewSucc : Pred->successors()) { |
| 1954 | if (BlockFilter && !BlockFilter->count(NewSucc)) |
| 1955 | continue; |
| 1956 | BlockChain *NewChain = BlockToChain[NewSucc]; |
| 1957 | if (NewChain != &Chain && NewChain != PredChain) |
| 1958 | NewChain->UnscheduledPredecessors++; |
| 1959 | } |
| 1960 | } |
| 1961 | return Removed; |
| 1962 | } |
| 1963 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1964 | bool MachineBlockPlacement::runOnMachineFunction(MachineFunction &MF) { |
| 1965 | if (skipFunction(*MF.getFunction())) |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 1966 | return false; |
| 1967 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1968 | // Check for single-block functions and skip them. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1969 | if (std::next(MF.begin()) == MF.end()) |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1970 | return false; |
| 1971 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1972 | F = &MF; |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1973 | MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 1974 | MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>( |
| 1975 | getAnalysis<MachineBlockFrequencyInfo>()); |
Chandler Carruth | 8b9737c | 2011-10-21 08:57:37 +0000 | [diff] [blame] | 1976 | MLI = &getAnalysis<MachineLoopInfo>(); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1977 | TII = MF.getSubtarget().getInstrInfo(); |
| 1978 | TLI = MF.getSubtarget().getTargetLowering(); |
Daniel Jasper | 471e856 | 2015-03-04 11:05:34 +0000 | [diff] [blame] | 1979 | MDT = &getAnalysis<MachineDominatorTree>(); |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 1980 | if (TailDupPlacement) { |
| 1981 | unsigned TailDupSize = TailDuplicatePlacementThreshold; |
| 1982 | if (MF.getFunction()->optForSize()) |
| 1983 | TailDupSize = 1; |
| 1984 | TailDup.initMF(MF, MBPI, /* LayoutMode */ true, TailDupSize); |
| 1985 | } |
| 1986 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1987 | assert(BlockToChain.empty()); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 1988 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1989 | buildCFGChains(); |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 1990 | |
| 1991 | // Changing the layout can create new tail merging opportunities. |
| 1992 | TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>(); |
| 1993 | // TailMerge can create jump into if branches that make CFG irreducible for |
Sjoerd Meijer | fd0ad4e | 2016-07-15 18:41:56 +0000 | [diff] [blame] | 1994 | // HW that requires structured CFG. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1995 | bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() && |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 1996 | PassConfig->getEnableTailMerge() && |
| 1997 | BranchFoldPlacement; |
| 1998 | // No tail merging opportunities if the block number is less than four. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 1999 | if (MF.size() > 3 && EnableTailMerge) { |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 2000 | unsigned TailMergeSize = TailDuplicatePlacementThreshold + 1; |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 2001 | BranchFolder BF(/*EnableTailMerge=*/true, /*CommonHoist=*/false, *MBFI, |
Kyle Butt | 64e4281 | 2016-08-18 18:57:29 +0000 | [diff] [blame] | 2002 | *MBPI, TailMergeSize); |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 2003 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 2004 | if (BF.OptimizeFunction(MF, TII, MF.getSubtarget().getRegisterInfo(), |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 2005 | getAnalysisIfAvailable<MachineModuleInfo>(), MLI, |
| 2006 | /*AfterBlockPlacement=*/true)) { |
| 2007 | // Redo the layout if tail merging creates/removes/moves blocks. |
| 2008 | BlockToChain.clear(); |
Kyle Butt | 0846e56 | 2016-10-11 20:36:43 +0000 | [diff] [blame^] | 2009 | // Must redo the dominator tree if blocks were changed. |
| 2010 | MDT->runOnMachineFunction(MF); |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 2011 | ChainAllocator.DestroyAll(); |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 2012 | buildCFGChains(); |
Haicheng Wu | 5b458cc | 2016-06-09 15:24:29 +0000 | [diff] [blame] | 2013 | } |
| 2014 | } |
| 2015 | |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 2016 | optimizeBranches(); |
| 2017 | alignBlocks(); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 2018 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 2019 | BlockToChain.clear(); |
Chandler Carruth | fd9b4d9 | 2011-11-14 10:57:23 +0000 | [diff] [blame] | 2020 | ChainAllocator.DestroyAll(); |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 2021 | |
Nadav Rotem | c0adc9f | 2013-04-12 01:24:16 +0000 | [diff] [blame] | 2022 | if (AlignAllBlock) |
| 2023 | // Align all of the blocks in the function to a specific alignment. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 2024 | for (MachineBasicBlock &MBB : MF) |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 2025 | MBB.setAlignment(AlignAllBlock); |
Geoff Berry | 10494ac | 2016-01-21 17:25:52 +0000 | [diff] [blame] | 2026 | else if (AlignAllNonFallThruBlocks) { |
| 2027 | // Align all of the blocks that have no fall-through predecessors to a |
| 2028 | // specific alignment. |
Xinliang David Li | 52530a7 | 2016-06-13 22:23:44 +0000 | [diff] [blame] | 2029 | for (auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) { |
Geoff Berry | 10494ac | 2016-01-21 17:25:52 +0000 | [diff] [blame] | 2030 | auto LayoutPred = std::prev(MBI); |
| 2031 | if (!LayoutPred->isSuccessor(&*MBI)) |
| 2032 | MBI->setAlignment(AlignAllNonFallThruBlocks); |
| 2033 | } |
| 2034 | } |
Nadav Rotem | c0adc9f | 2013-04-12 01:24:16 +0000 | [diff] [blame] | 2035 | |
Chandler Carruth | 1028142 | 2011-10-21 06:46:38 +0000 | [diff] [blame] | 2036 | // We always return true as we have no way to track whether the final order |
| 2037 | // differs from the original order. |
| 2038 | return true; |
| 2039 | } |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2040 | |
| 2041 | namespace { |
| 2042 | /// \brief A pass to compute block placement statistics. |
| 2043 | /// |
| 2044 | /// A separate pass to compute interesting statistics for evaluating block |
| 2045 | /// placement. This is separate from the actual placement pass so that they can |
Benjamin Kramer | bde9176 | 2012-06-02 10:20:22 +0000 | [diff] [blame] | 2046 | /// be computed in the absence of any placement transformations or when using |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2047 | /// alternative placement strategies. |
| 2048 | class MachineBlockPlacementStats : public MachineFunctionPass { |
| 2049 | /// \brief A handle to the branch probability pass. |
| 2050 | const MachineBranchProbabilityInfo *MBPI; |
| 2051 | |
| 2052 | /// \brief A handle to the function-wide block frequency pass. |
| 2053 | const MachineBlockFrequencyInfo *MBFI; |
| 2054 | |
| 2055 | public: |
| 2056 | static char ID; // Pass identification, replacement for typeid |
| 2057 | MachineBlockPlacementStats() : MachineFunctionPass(ID) { |
| 2058 | initializeMachineBlockPlacementStatsPass(*PassRegistry::getPassRegistry()); |
| 2059 | } |
| 2060 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2061 | bool runOnMachineFunction(MachineFunction &F) override; |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2062 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2063 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2064 | AU.addRequired<MachineBranchProbabilityInfo>(); |
| 2065 | AU.addRequired<MachineBlockFrequencyInfo>(); |
| 2066 | AU.setPreservesAll(); |
| 2067 | MachineFunctionPass::getAnalysisUsage(AU); |
| 2068 | } |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2069 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 2070 | } |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2071 | |
| 2072 | char MachineBlockPlacementStats::ID = 0; |
Andrew Trick | 1fa5bcb | 2012-02-08 21:23:13 +0000 | [diff] [blame] | 2073 | char &llvm::MachineBlockPlacementStatsID = MachineBlockPlacementStats::ID; |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2074 | INITIALIZE_PASS_BEGIN(MachineBlockPlacementStats, "block-placement-stats", |
| 2075 | "Basic Block Placement Stats", false, false) |
| 2076 | INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) |
| 2077 | INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) |
| 2078 | INITIALIZE_PASS_END(MachineBlockPlacementStats, "block-placement-stats", |
| 2079 | "Basic Block Placement Stats", false, false) |
| 2080 | |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2081 | bool MachineBlockPlacementStats::runOnMachineFunction(MachineFunction &F) { |
| 2082 | // Check for single-block functions and skip them. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 2083 | if (std::next(F.begin()) == F.end()) |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2084 | return false; |
| 2085 | |
| 2086 | MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); |
| 2087 | MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); |
| 2088 | |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 2089 | for (MachineBasicBlock &MBB : F) { |
| 2090 | BlockFrequency BlockFreq = MBFI->getBlockFreq(&MBB); |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 2091 | Statistic &NumBranches = |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 2092 | (MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches; |
Chandler Carruth | 2fc3fe1 | 2015-03-05 02:35:31 +0000 | [diff] [blame] | 2093 | Statistic &BranchTakenFreq = |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 2094 | (MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq; |
| 2095 | for (MachineBasicBlock *Succ : MBB.successors()) { |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2096 | // Skip if this successor is a fallthrough. |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 2097 | if (MBB.isLayoutSuccessor(Succ)) |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2098 | continue; |
| 2099 | |
Chandler Carruth | 7a715da | 2015-03-05 03:19:05 +0000 | [diff] [blame] | 2100 | BlockFrequency EdgeFreq = |
| 2101 | BlockFreq * MBPI->getEdgeProbability(&MBB, Succ); |
Chandler Carruth | ae4e800 | 2011-11-02 07:17:12 +0000 | [diff] [blame] | 2102 | ++NumBranches; |
| 2103 | BranchTakenFreq += EdgeFreq.getFrequency(); |
| 2104 | } |
| 2105 | } |
| 2106 | |
| 2107 | return false; |
| 2108 | } |