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