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