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