MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1 | //===- LoopFusion.cpp - Code to perform loop fusion -----------------------===// |
| 2 | // |
| 3 | // Copyright 2019 The MLIR Authors. |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | // ============================================================================= |
| 17 | // |
| 18 | // This file implements loop fusion. |
| 19 | // |
| 20 | //===----------------------------------------------------------------------===// |
| 21 | |
River Riddle | 7555383 | 2019-01-29 05:23:53 | [diff] [blame] | 22 | #include "mlir/AffineOps/AffineOps.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 23 | #include "mlir/Analysis/AffineAnalysis.h" |
Uday Bondhugula | dfe07b7 | 2019-02-23 00:51:08 | [diff] [blame] | 24 | #include "mlir/Analysis/AffineStructures.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 25 | #include "mlir/Analysis/LoopAnalysis.h" |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 26 | #include "mlir/Analysis/Utils.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 27 | #include "mlir/IR/AffineExpr.h" |
| 28 | #include "mlir/IR/AffineMap.h" |
| 29 | #include "mlir/IR/Builders.h" |
River Riddle | 48ccae2 | 2019-02-20 01:17:46 | [diff] [blame] | 30 | #include "mlir/Pass/Pass.h" |
Lei Zhang | 85d9b6c | 2019-03-01 21:48:24 | [diff] [blame] | 31 | #include "mlir/StandardOps/Ops.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 32 | #include "mlir/Transforms/LoopUtils.h" |
| 33 | #include "mlir/Transforms/Passes.h" |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 34 | #include "mlir/Transforms/Utils.h" |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 35 | #include "llvm/ADT/DenseMap.h" |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 36 | #include "llvm/ADT/DenseSet.h" |
| 37 | #include "llvm/ADT/SetVector.h" |
MLIR Team | 4eef795 | 2018-12-21 19:06:23 | [diff] [blame] | 38 | #include "llvm/Support/CommandLine.h" |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 40 | #include "llvm/Support/raw_ostream.h" |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 41 | #include <iomanip> |
Nicolas Vasilache | 258e8d9 | 2019-05-03 18:07:37 | [diff] [blame] | 42 | #define DEBUG_TYPE "affine-loop-fusion" |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 43 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 44 | using llvm::SetVector; |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 45 | |
| 46 | using namespace mlir; |
| 47 | |
River Riddle | 75c21e1 | 2019-01-26 06:14:04 | [diff] [blame] | 48 | static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options"); |
| 49 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 50 | /// Disables fusion profitability check and fuses if valid. Ignore any |
| 51 | /// additional (redundant) computation tolerance threshold |
| 52 | /// that would have prevented fusion. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 53 | static llvm::cl::opt<bool> |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 54 | clMaximalLoopFusion("fusion-maximal", |
River Riddle | 75c21e1 | 2019-01-26 06:14:04 | [diff] [blame] | 55 | llvm::cl::desc("Enables maximal loop fusion"), |
| 56 | llvm::cl::cat(clOptionsCategory)); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 57 | |
| 58 | /// A threshold in percent of additional computation allowed when fusing. |
| 59 | static llvm::cl::opt<double> clFusionAddlComputeTolerance( |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 60 | "fusion-compute-tolerance", |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 61 | llvm::cl::desc("Fractional increase in additional " |
| 62 | "computation tolerated while fusing"), |
River Riddle | 75c21e1 | 2019-01-26 06:14:04 | [diff] [blame] | 63 | llvm::cl::cat(clOptionsCategory)); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 64 | |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 65 | static llvm::cl::opt<unsigned> clFusionFastMemorySpace( |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 66 | "fusion-fast-mem-space", |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 67 | llvm::cl::desc("Faster memory space number to promote fusion buffers to"), |
| 68 | llvm::cl::cat(clOptionsCategory)); |
| 69 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 70 | // A local buffer of size less than or equal to this size is automatically |
| 71 | // promoted to fast memory after producer-consumer fusion. |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 72 | static llvm::cl::opt<unsigned long long> clFusionLocalBufThreshold( |
Uday Bondhugula | eee8536 | 2019-03-02 01:42:13 | [diff] [blame] | 73 | "fusion-local-buf-threshold", |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 74 | llvm::cl::desc("Threshold size (KiB) for promoting local buffers to fast " |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 75 | "memory space"), |
| 76 | llvm::cl::cat(clOptionsCategory)); |
| 77 | |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 78 | namespace { |
| 79 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 80 | /// Loop fusion pass. This pass currently supports a greedy fusion policy, |
| 81 | /// which fuses loop nests with single-writer/single-reader memref dependences |
| 82 | /// with the goal of improving locality. |
| 83 | |
| 84 | // TODO(andydavis) Support fusion of source loop nests which write to multiple |
| 85 | // memrefs, where each memref can have multiple users (if profitable). |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 86 | // TODO(andydavis) Extend this pass to check for fusion preventing dependences, |
| 87 | // and add support for more general loop fusion algorithms. |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 88 | |
River Riddle | c6c5344 | 2019-02-27 18:59:29 | [diff] [blame] | 89 | struct LoopFusion : public FunctionPass<LoopFusion> { |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 90 | LoopFusion(unsigned fastMemorySpace = 0, uint64_t localBufSizeThreshold = 0, |
| 91 | bool maximalFusion = false) |
River Riddle | c6c5344 | 2019-02-27 18:59:29 | [diff] [blame] | 92 | : localBufSizeThreshold(localBufSizeThreshold), |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 93 | fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {} |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 94 | |
River Riddle | ed5fe20 | 2019-02-28 22:50:42 | [diff] [blame] | 95 | void runOnFunction() override; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 96 | |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 97 | // Any local buffers smaller than this size (in bytes) will be created in |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 98 | // `fastMemorySpace` if provided. |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 99 | uint64_t localBufSizeThreshold; |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 100 | Optional<unsigned> fastMemorySpace = None; |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 101 | // If true, ignore any additional (redundant) computation tolerance threshold |
| 102 | // that would have prevented fusion. |
| 103 | bool maximalFusion; |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 104 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 105 | // The amount of additional computation that is tolerated while fusing |
| 106 | // pair-wise as a fraction of the total computation. |
| 107 | constexpr static double kComputeToleranceThreshold = 0.30f; |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 108 | }; |
| 109 | |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 110 | } // end anonymous namespace |
| 111 | |
River Riddle | c6c5344 | 2019-02-27 18:59:29 | [diff] [blame] | 112 | FunctionPassBase *mlir::createLoopFusionPass(unsigned fastMemorySpace, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 113 | uint64_t localBufSizeThreshold, |
| 114 | bool maximalFusion) { |
| 115 | return new LoopFusion(fastMemorySpace, localBufSizeThreshold, maximalFusion); |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 116 | } |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 117 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 118 | namespace { |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 119 | |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 120 | // LoopNestStateCollector walks loop nests and collects load and store |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 121 | // operations, and whether or not an IfInst was encountered in the loop nest. |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 122 | struct LoopNestStateCollector { |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 123 | SmallVector<AffineForOp, 4> forOps; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 124 | SmallVector<Operation *, 4> loadOpInsts; |
| 125 | SmallVector<Operation *, 4> storeOpInsts; |
River Riddle | 7555383 | 2019-01-29 05:23:53 | [diff] [blame] | 126 | bool hasNonForRegion = false; |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 127 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 128 | void collect(Operation *opToWalk) { |
| 129 | opToWalk->walk([&](Operation *op) { |
| 130 | if (op->isa<AffineForOp>()) |
| 131 | forOps.push_back(op->cast<AffineForOp>()); |
| 132 | else if (op->getNumRegions() != 0) |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 133 | hasNonForRegion = true; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 134 | else if (op->isa<LoadOp>()) |
| 135 | loadOpInsts.push_back(op); |
| 136 | else if (op->isa<StoreOp>()) |
| 137 | storeOpInsts.push_back(op); |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 138 | }); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 139 | } |
| 140 | }; |
| 141 | |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 142 | // TODO(b/117228571) Replace when this is modeled through side-effects/op traits |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 143 | static bool isMemRefDereferencingOp(Operation &op) { |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 144 | if (op.isa<LoadOp>() || op.isa<StoreOp>() || op.isa<DmaStartOp>() || |
| 145 | op.isa<DmaWaitOp>()) |
| 146 | return true; |
| 147 | return false; |
| 148 | } |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 149 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 150 | // MemRefDependenceGraph is a graph data structure where graph nodes are |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 151 | // top-level operations in a Function which contain load/store ops, and edges |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 152 | // are memref dependences between the nodes. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 153 | // TODO(andydavis) Add a more flexible dependece graph representation. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 154 | // TODO(andydavis) Add a depth parameter to dependence graph construction. |
| 155 | struct MemRefDependenceGraph { |
| 156 | public: |
| 157 | // Node represents a node in the graph. A Node is either an entire loop nest |
| 158 | // rooted at the top level which contains loads/stores, or a top level |
| 159 | // load/store. |
| 160 | struct Node { |
| 161 | // The unique identifier of this node in the graph. |
| 162 | unsigned id; |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 163 | // The top-level statement which is (or contains) a load/store. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 164 | Operation *op; |
Chris Lattner | 5187cfc | 2018-12-28 05:21:41 | [diff] [blame] | 165 | // List of load operations. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 166 | SmallVector<Operation *, 4> loads; |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 167 | // List of store op insts. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 168 | SmallVector<Operation *, 4> stores; |
| 169 | Node(unsigned id, Operation *op) : id(id), op(op) {} |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 170 | |
| 171 | // Returns the load op count for 'memref'. |
Chris Lattner | 3f19031 | 2018-12-27 22:35:10 | [diff] [blame] | 172 | unsigned getLoadOpCount(Value *memref) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 173 | unsigned loadOpCount = 0; |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 174 | for (auto *loadOpInst : loads) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 175 | if (memref == loadOpInst->cast<LoadOp>().getMemRef()) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 176 | ++loadOpCount; |
| 177 | } |
| 178 | return loadOpCount; |
| 179 | } |
| 180 | |
| 181 | // Returns the store op count for 'memref'. |
Chris Lattner | 3f19031 | 2018-12-27 22:35:10 | [diff] [blame] | 182 | unsigned getStoreOpCount(Value *memref) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 183 | unsigned storeOpCount = 0; |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 184 | for (auto *storeOpInst : stores) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 185 | if (memref == storeOpInst->cast<StoreOp>().getMemRef()) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 186 | ++storeOpCount; |
| 187 | } |
| 188 | return storeOpCount; |
| 189 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 190 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 191 | // Returns all store ops in 'storeOps' which access 'memref'. |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 192 | void getStoreOpsForMemref(Value *memref, |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 193 | SmallVectorImpl<Operation *> *storeOps) { |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 194 | for (auto *storeOpInst : stores) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 195 | if (memref == storeOpInst->cast<StoreOp>().getMemRef()) |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 196 | storeOps->push_back(storeOpInst); |
| 197 | } |
| 198 | } |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 199 | |
| 200 | // Returns all load ops in 'loadOps' which access 'memref'. |
| 201 | void getLoadOpsForMemref(Value *memref, |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 202 | SmallVectorImpl<Operation *> *loadOps) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 203 | for (auto *loadOpInst : loads) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 204 | if (memref == loadOpInst->cast<LoadOp>().getMemRef()) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 205 | loadOps->push_back(loadOpInst); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // Returns all memrefs in 'loadAndStoreMemrefSet' for which this node |
| 210 | // has at least one load and store operation. |
| 211 | void getLoadAndStoreMemrefSet(DenseSet<Value *> *loadAndStoreMemrefSet) { |
| 212 | llvm::SmallDenseSet<Value *, 2> loadMemrefs; |
| 213 | for (auto *loadOpInst : loads) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 214 | loadMemrefs.insert(loadOpInst->cast<LoadOp>().getMemRef()); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 215 | } |
| 216 | for (auto *storeOpInst : stores) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 217 | auto *memref = storeOpInst->cast<StoreOp>().getMemRef(); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 218 | if (loadMemrefs.count(memref) > 0) |
| 219 | loadAndStoreMemrefSet->insert(memref); |
| 220 | } |
| 221 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 222 | }; |
| 223 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 224 | // Edge represents a data dependece between nodes in the graph. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 225 | struct Edge { |
| 226 | // The id of the node at the other end of the edge. |
MLIR Team | 1e85191 | 2019-01-31 00:01:46 | [diff] [blame] | 227 | // If this edge is stored in Edge = Node.inEdges[i], then |
| 228 | // 'Node.inEdges[i].id' is the identifier of the source node of the edge. |
| 229 | // If this edge is stored in Edge = Node.outEdges[i], then |
| 230 | // 'Node.outEdges[i].id' is the identifier of the dest node of the edge. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 231 | unsigned id; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 232 | // The SSA value on which this edge represents a dependence. |
| 233 | // If the value is a memref, then the dependence is between graph nodes |
| 234 | // which contain accesses to the same memref 'value'. If the value is a |
| 235 | // non-memref value, then the dependence is between a graph node which |
| 236 | // defines an SSA value and another graph node which uses the SSA value |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 237 | // (e.g. a constant operation defining a value which is used inside a loop |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 238 | // nest). |
| 239 | Value *value; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 240 | }; |
| 241 | |
| 242 | // Map from node id to Node. |
| 243 | DenseMap<unsigned, Node> nodes; |
| 244 | // Map from node id to list of input edges. |
| 245 | DenseMap<unsigned, SmallVector<Edge, 2>> inEdges; |
| 246 | // Map from node id to list of output edges. |
| 247 | DenseMap<unsigned, SmallVector<Edge, 2>> outEdges; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 248 | // Map from memref to a count on the dependence edges associated with that |
| 249 | // memref. |
| 250 | DenseMap<Value *, unsigned> memrefEdgeCount; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 251 | // The next unique identifier to use for newly created graph nodes. |
| 252 | unsigned nextNodeId = 0; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 253 | |
| 254 | MemRefDependenceGraph() {} |
| 255 | |
| 256 | // Initializes the dependence graph based on operations in 'f'. |
| 257 | // Returns true on success, false otherwise. |
Chris Lattner | 46ade28 | 2019-03-26 01:02:49 | [diff] [blame] | 258 | bool init(Function &f); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 259 | |
| 260 | // Returns the graph node for 'id'. |
| 261 | Node *getNode(unsigned id) { |
| 262 | auto it = nodes.find(id); |
| 263 | assert(it != nodes.end()); |
| 264 | return &it->second; |
| 265 | } |
| 266 | |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 267 | // Returns the graph node for 'forOp'. |
| 268 | Node *getForOpNode(AffineForOp forOp) { |
| 269 | for (auto &idAndNode : nodes) |
| 270 | if (idAndNode.second.op == forOp.getOperation()) |
| 271 | return &idAndNode.second; |
| 272 | return nullptr; |
| 273 | } |
| 274 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 275 | // Adds a node with 'op' to the graph and returns its unique identifier. |
| 276 | unsigned addNode(Operation *op) { |
| 277 | Node node(nextNodeId++, op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 278 | nodes.insert({node.id, node}); |
| 279 | return node.id; |
| 280 | } |
| 281 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 282 | // Remove node 'id' (and its associated edges) from graph. |
| 283 | void removeNode(unsigned id) { |
| 284 | // Remove each edge in 'inEdges[id]'. |
| 285 | if (inEdges.count(id) > 0) { |
| 286 | SmallVector<Edge, 2> oldInEdges = inEdges[id]; |
| 287 | for (auto &inEdge : oldInEdges) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 288 | removeEdge(inEdge.id, id, inEdge.value); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 289 | } |
| 290 | } |
| 291 | // Remove each edge in 'outEdges[id]'. |
| 292 | if (outEdges.count(id) > 0) { |
| 293 | SmallVector<Edge, 2> oldOutEdges = outEdges[id]; |
| 294 | for (auto &outEdge : oldOutEdges) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 295 | removeEdge(id, outEdge.id, outEdge.value); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 296 | } |
| 297 | } |
| 298 | // Erase remaining node state. |
| 299 | inEdges.erase(id); |
| 300 | outEdges.erase(id); |
| 301 | nodes.erase(id); |
| 302 | } |
| 303 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 304 | // Returns true if node 'id' writes to any memref which escapes (or is an |
| 305 | // argument to) the function/block. Returns false otherwise. |
| 306 | bool writesToLiveInOrEscapingMemrefs(unsigned id) { |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 307 | Node *node = getNode(id); |
| 308 | for (auto *storeOpInst : node->stores) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 309 | auto *memref = storeOpInst->cast<StoreOp>().getMemRef(); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 310 | auto *op = memref->getDefiningOp(); |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 311 | // Return true if 'memref' is a block argument. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 312 | if (!op) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 313 | return true; |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 314 | // Return true if any use of 'memref' escapes the function. |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 315 | for (auto &use : memref->getUses()) |
| 316 | if (!isMemRefDereferencingOp(*use.getOwner())) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 317 | return true; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 318 | } |
| 319 | return false; |
| 320 | } |
| 321 | |
| 322 | // Returns true if node 'id' can be removed from the graph. Returns false |
| 323 | // otherwise. A node can be removed from the graph iff the following |
| 324 | // conditions are met: |
| 325 | // *) The node does not write to any memref which escapes (or is a |
| 326 | // function/block argument). |
| 327 | // *) The node has no successors in the dependence graph. |
| 328 | bool canRemoveNode(unsigned id) { |
| 329 | if (writesToLiveInOrEscapingMemrefs(id)) |
| 330 | return false; |
| 331 | Node *node = getNode(id); |
| 332 | for (auto *storeOpInst : node->stores) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 333 | // Return false if there exist out edges from 'id' on 'memref'. |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 334 | if (getOutEdgeCount(id, storeOpInst->cast<StoreOp>().getMemRef()) > 0) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 335 | return false; |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 336 | } |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 337 | return true; |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 338 | } |
| 339 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 340 | // Returns true iff there is an edge from node 'srcId' to node 'dstId' which |
| 341 | // is for 'value' if non-null, or for any value otherwise. Returns false |
| 342 | // otherwise. |
| 343 | bool hasEdge(unsigned srcId, unsigned dstId, Value *value = nullptr) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 344 | if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) { |
| 345 | return false; |
| 346 | } |
| 347 | bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 348 | return edge.id == dstId && (!value || edge.value == value); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 349 | }); |
| 350 | bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 351 | return edge.id == srcId && (!value || edge.value == value); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 352 | }); |
| 353 | return hasOutEdge && hasInEdge; |
| 354 | } |
| 355 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 356 | // Adds an edge from node 'srcId' to node 'dstId' for 'value'. |
| 357 | void addEdge(unsigned srcId, unsigned dstId, Value *value) { |
| 358 | if (!hasEdge(srcId, dstId, value)) { |
| 359 | outEdges[srcId].push_back({dstId, value}); |
| 360 | inEdges[dstId].push_back({srcId, value}); |
| 361 | if (value->getType().isa<MemRefType>()) |
| 362 | memrefEdgeCount[value]++; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 363 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 364 | } |
| 365 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 366 | // Removes an edge from node 'srcId' to node 'dstId' for 'value'. |
| 367 | void removeEdge(unsigned srcId, unsigned dstId, Value *value) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 368 | assert(inEdges.count(dstId) > 0); |
| 369 | assert(outEdges.count(srcId) > 0); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 370 | if (value->getType().isa<MemRefType>()) { |
| 371 | assert(memrefEdgeCount.count(value) > 0); |
| 372 | memrefEdgeCount[value]--; |
| 373 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 374 | // Remove 'srcId' from 'inEdges[dstId]'. |
| 375 | for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 376 | if ((*it).id == srcId && (*it).value == value) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 377 | inEdges[dstId].erase(it); |
| 378 | break; |
| 379 | } |
| 380 | } |
| 381 | // Remove 'dstId' from 'outEdges[srcId]'. |
| 382 | for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 383 | if ((*it).id == dstId && (*it).value == value) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 384 | outEdges[srcId].erase(it); |
| 385 | break; |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 390 | // Returns true if there is a path in the dependence graph from node 'srcId' |
| 391 | // to node 'dstId'. Returns false otherwise. |
| 392 | bool hasDependencePath(unsigned srcId, unsigned dstId) { |
| 393 | // Worklist state is: <node-id, next-output-edge-index-to-visit> |
| 394 | SmallVector<std::pair<unsigned, unsigned>, 4> worklist; |
| 395 | worklist.push_back({srcId, 0}); |
| 396 | // Run DFS traversal to see if 'dstId' is reachable from 'srcId'. |
| 397 | while (!worklist.empty()) { |
| 398 | auto &idAndIndex = worklist.back(); |
| 399 | // Return true if we have reached 'dstId'. |
| 400 | if (idAndIndex.first == dstId) |
| 401 | return true; |
| 402 | // Pop and continue if node has no out edges, or if all out edges have |
| 403 | // already been visited. |
| 404 | if (outEdges.count(idAndIndex.first) == 0 || |
| 405 | idAndIndex.second == outEdges[idAndIndex.first].size()) { |
| 406 | worklist.pop_back(); |
| 407 | continue; |
| 408 | } |
| 409 | // Get graph edge to traverse. |
| 410 | Edge edge = outEdges[idAndIndex.first][idAndIndex.second]; |
| 411 | // Increment next output edge index for 'idAndIndex'. |
| 412 | ++idAndIndex.second; |
| 413 | // Add node at 'edge.id' to worklist. |
| 414 | worklist.push_back({edge.id, 0}); |
| 415 | } |
| 416 | return false; |
| 417 | } |
| 418 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 419 | // Returns the input edge count for node 'id' and 'memref' from src nodes |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 420 | // which access 'memref' with a store operation. |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 421 | unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 422 | unsigned inEdgeCount = 0; |
| 423 | if (inEdges.count(id) > 0) |
| 424 | for (auto &inEdge : inEdges[id]) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 425 | if (inEdge.value == memref) { |
| 426 | Node *srcNode = getNode(inEdge.id); |
| 427 | // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref' |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 428 | if (srcNode->getStoreOpCount(memref) > 0) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 429 | ++inEdgeCount; |
| 430 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 431 | return inEdgeCount; |
| 432 | } |
| 433 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 434 | // Returns the output edge count for node 'id' and 'memref' (if non-null), |
| 435 | // otherwise returns the total output edge count from node 'id'. |
| 436 | unsigned getOutEdgeCount(unsigned id, Value *memref = nullptr) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 437 | unsigned outEdgeCount = 0; |
| 438 | if (outEdges.count(id) > 0) |
| 439 | for (auto &outEdge : outEdges[id]) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 440 | if (!memref || outEdge.value == memref) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 441 | ++outEdgeCount; |
| 442 | return outEdgeCount; |
| 443 | } |
| 444 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 445 | // Computes and returns an insertion point operation, before which the |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 446 | // the fused <srcId, dstId> loop nest can be inserted while preserving |
| 447 | // dependences. Returns nullptr if no such insertion point is found. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 448 | Operation *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) { |
MLIR Team | 5c5739d | 2019-01-25 06:27:40 | [diff] [blame] | 449 | if (outEdges.count(srcId) == 0) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 450 | return getNode(dstId)->op; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 451 | |
| 452 | // Build set of insts in range (srcId, dstId) which depend on 'srcId'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 453 | SmallPtrSet<Operation *, 2> srcDepInsts; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 454 | for (auto &outEdge : outEdges[srcId]) |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 455 | if (outEdge.id != dstId) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 456 | srcDepInsts.insert(getNode(outEdge.id)->op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 457 | |
| 458 | // Build set of insts in range (srcId, dstId) on which 'dstId' depends. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 459 | SmallPtrSet<Operation *, 2> dstDepInsts; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 460 | for (auto &inEdge : inEdges[dstId]) |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 461 | if (inEdge.id != srcId) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 462 | dstDepInsts.insert(getNode(inEdge.id)->op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 463 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 464 | Operation *srcNodeInst = getNode(srcId)->op; |
| 465 | Operation *dstNodeInst = getNode(dstId)->op; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 466 | |
| 467 | // Computing insertion point: |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 468 | // *) Walk all operation positions in Block operation list in the |
| 469 | // range (src, dst). For each operation 'op' visited in this search: |
| 470 | // *) Store in 'firstSrcDepPos' the first position where 'op' has a |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 471 | // dependence edge from 'srcNode'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 472 | // *) Store in 'lastDstDepPost' the last position where 'op' has a |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 473 | // dependence edge to 'dstNode'. |
| 474 | // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 475 | // operation insertion point (or return null pointer if no such |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 476 | // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos'). |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 477 | SmallVector<Operation *, 2> depInsts; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 478 | Optional<unsigned> firstSrcDepPos; |
| 479 | Optional<unsigned> lastDstDepPos; |
| 480 | unsigned pos = 0; |
| 481 | for (Block::iterator it = std::next(Block::iterator(srcNodeInst)); |
| 482 | it != Block::iterator(dstNodeInst); ++it) { |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 483 | Operation *op = &(*it); |
| 484 | if (srcDepInsts.count(op) > 0 && firstSrcDepPos == None) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 485 | firstSrcDepPos = pos; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 486 | if (dstDepInsts.count(op) > 0) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 487 | lastDstDepPos = pos; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 488 | depInsts.push_back(op); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 489 | ++pos; |
MLIR Team | 5c5739d | 2019-01-25 06:27:40 | [diff] [blame] | 490 | } |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 491 | |
| 492 | if (firstSrcDepPos.hasValue()) { |
| 493 | if (lastDstDepPos.hasValue()) { |
| 494 | if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) { |
| 495 | // No valid insertion point exists which preserves dependences. |
| 496 | return nullptr; |
| 497 | } |
| 498 | } |
| 499 | // Return the insertion point at 'firstSrcDepPos'. |
| 500 | return depInsts[firstSrcDepPos.getValue()]; |
| 501 | } |
| 502 | // No dependence targets in range (or only dst deps in range), return |
| 503 | // 'dstNodInst' insertion point. |
| 504 | return dstNodeInst; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 505 | } |
| 506 | |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 507 | // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef' |
| 508 | // has been replaced in node at 'dstId' by a private memref. |
| 509 | void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 510 | // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'. |
| 511 | if (inEdges.count(srcId) > 0) { |
| 512 | SmallVector<Edge, 2> oldInEdges = inEdges[srcId]; |
| 513 | for (auto &inEdge : oldInEdges) { |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 514 | // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'. |
| 515 | if (inEdge.value != oldMemRef) |
| 516 | addEdge(inEdge.id, dstId, inEdge.value); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 517 | } |
| 518 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 519 | // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 520 | if (outEdges.count(srcId) > 0) { |
| 521 | SmallVector<Edge, 2> oldOutEdges = outEdges[srcId]; |
| 522 | for (auto &outEdge : oldOutEdges) { |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 523 | // Remove any out edges from 'srcId' to 'dstId' across memrefs. |
| 524 | if (outEdge.id == dstId) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 525 | removeEdge(srcId, outEdge.id, outEdge.value); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 526 | } |
| 527 | } |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 528 | // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being |
| 529 | // replaced by a private memref). These edges could come from nodes |
| 530 | // other than 'srcId' which were removed in the previous step. |
| 531 | if (inEdges.count(dstId) > 0) { |
| 532 | SmallVector<Edge, 2> oldInEdges = inEdges[dstId]; |
| 533 | for (auto &inEdge : oldInEdges) |
| 534 | if (inEdge.value == oldMemRef) |
| 535 | removeEdge(inEdge.id, dstId, inEdge.value); |
| 536 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 537 | } |
| 538 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 539 | // Update edge mappings for nodes 'sibId' and 'dstId' to reflect fusion |
| 540 | // of sibling node 'sidId' into node 'dstId'. |
| 541 | void updateEdges(unsigned sibId, unsigned dstId) { |
| 542 | // For each edge in 'inEdges[sibId]': |
| 543 | // *) Add new edge from source node 'inEdge.id' to 'dstNode'. |
| 544 | // *) Remove edge from source node 'inEdge.id' to 'sibNode'. |
| 545 | if (inEdges.count(sibId) > 0) { |
| 546 | SmallVector<Edge, 2> oldInEdges = inEdges[sibId]; |
| 547 | for (auto &inEdge : oldInEdges) { |
| 548 | addEdge(inEdge.id, dstId, inEdge.value); |
| 549 | removeEdge(inEdge.id, sibId, inEdge.value); |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | // For each edge in 'outEdges[sibId]' to node 'id' |
| 554 | // *) Add new edge from 'dstId' to 'outEdge.id'. |
| 555 | // *) Remove edge from 'sibId' to 'outEdge.id'. |
| 556 | if (outEdges.count(sibId) > 0) { |
| 557 | SmallVector<Edge, 2> oldOutEdges = outEdges[sibId]; |
| 558 | for (auto &outEdge : oldOutEdges) { |
| 559 | addEdge(dstId, outEdge.id, outEdge.value); |
| 560 | removeEdge(sibId, outEdge.id, outEdge.value); |
| 561 | } |
| 562 | } |
| 563 | } |
| 564 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 565 | // Adds ops in 'loads' and 'stores' to node at 'id'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 566 | void addToNode(unsigned id, const SmallVectorImpl<Operation *> &loads, |
| 567 | const SmallVectorImpl<Operation *> &stores) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 568 | Node *node = getNode(id); |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 569 | for (auto *loadOpInst : loads) |
| 570 | node->loads.push_back(loadOpInst); |
| 571 | for (auto *storeOpInst : stores) |
| 572 | node->stores.push_back(storeOpInst); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 573 | } |
| 574 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 575 | void clearNodeLoadAndStores(unsigned id) { |
| 576 | Node *node = getNode(id); |
| 577 | node->loads.clear(); |
| 578 | node->stores.clear(); |
| 579 | } |
| 580 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 581 | // Calls 'callback' for each input edge incident to node 'id' which carries a |
| 582 | // memref dependence. |
| 583 | void forEachMemRefInputEdge(unsigned id, |
| 584 | const std::function<void(Edge)> &callback) { |
| 585 | if (inEdges.count(id) > 0) |
| 586 | forEachMemRefEdge(inEdges[id], callback); |
| 587 | } |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 588 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 589 | // Calls 'callback' for each output edge from node 'id' which carries a |
| 590 | // memref dependence. |
| 591 | void forEachMemRefOutputEdge(unsigned id, |
| 592 | const std::function<void(Edge)> &callback) { |
| 593 | if (outEdges.count(id) > 0) |
| 594 | forEachMemRefEdge(outEdges[id], callback); |
| 595 | } |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 596 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 597 | // Calls 'callback' for each edge in 'edges' which carries a memref |
| 598 | // dependence. |
| 599 | void forEachMemRefEdge(ArrayRef<Edge> edges, |
| 600 | const std::function<void(Edge)> &callback) { |
| 601 | for (auto &edge : edges) { |
| 602 | // Skip if 'edge' is not a memref dependence edge. |
| 603 | if (!edge.value->getType().isa<MemRefType>()) |
| 604 | continue; |
| 605 | assert(nodes.count(edge.id) > 0); |
| 606 | // Skip if 'edge.id' is not a loop nest. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 607 | if (!getNode(edge.id)->op->isa<AffineForOp>()) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 608 | continue; |
| 609 | // Visit current input edge 'edge'. |
| 610 | callback(edge); |
| 611 | } |
| 612 | } |
| 613 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 614 | void print(raw_ostream &os) const { |
| 615 | os << "\nMemRefDependenceGraph\n"; |
| 616 | os << "\nNodes:\n"; |
| 617 | for (auto &idAndNode : nodes) { |
| 618 | os << "Node: " << idAndNode.first << "\n"; |
| 619 | auto it = inEdges.find(idAndNode.first); |
| 620 | if (it != inEdges.end()) { |
| 621 | for (const auto &e : it->second) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 622 | os << " InEdge: " << e.id << " " << e.value << "\n"; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 623 | } |
| 624 | it = outEdges.find(idAndNode.first); |
| 625 | if (it != outEdges.end()) { |
| 626 | for (const auto &e : it->second) |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 627 | os << " OutEdge: " << e.id << " " << e.value << "\n"; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 628 | } |
| 629 | } |
| 630 | } |
| 631 | void dump() const { print(llvm::errs()); } |
| 632 | }; |
| 633 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 634 | // Intializes the data dependence graph by walking operations in 'f'. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 635 | // Assigns each node in the graph a node id based on program order in 'f'. |
Chris Lattner | 315a466 | 2018-12-28 21:07:39 | [diff] [blame] | 636 | // TODO(andydavis) Add support for taking a Block arg to construct the |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 637 | // dependence graph at a different depth. |
Chris Lattner | 46ade28 | 2019-03-26 01:02:49 | [diff] [blame] | 638 | bool MemRefDependenceGraph::init(Function &f) { |
Chris Lattner | 3f19031 | 2018-12-27 22:35:10 | [diff] [blame] | 639 | DenseMap<Value *, SetVector<unsigned>> memrefAccesses; |
Chris Lattner | dffc589 | 2018-12-29 23:33:43 | [diff] [blame] | 640 | |
| 641 | // TODO: support multi-block functions. |
Chris Lattner | 46ade28 | 2019-03-26 01:02:49 | [diff] [blame] | 642 | if (f.getBlocks().size() != 1) |
Chris Lattner | dffc589 | 2018-12-29 23:33:43 | [diff] [blame] | 643 | return false; |
| 644 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 645 | DenseMap<Operation *, unsigned> forToNodeMap; |
| 646 | for (auto &op : f.front()) { |
River Riddle | c5ecf99 | 2019-05-11 22:56:50 | [diff] [blame^] | 647 | if (auto forOp = dyn_cast<AffineForOp>(op)) { |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 648 | // Create graph node 'id' to represent top-level 'forOp' and record |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 649 | // all loads and store accesses it contains. |
| 650 | LoopNestStateCollector collector; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 651 | collector.collect(&op); |
River Riddle | 832567b | 2019-03-25 17:14:34 | [diff] [blame] | 652 | // Return false if a non 'affine.for' region was found (not currently |
| 653 | // supported). |
River Riddle | 7555383 | 2019-01-29 05:23:53 | [diff] [blame] | 654 | if (collector.hasNonForRegion) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 655 | return false; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 656 | Node node(nextNodeId++, &op); |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 657 | for (auto *opInst : collector.loadOpInsts) { |
| 658 | node.loads.push_back(opInst); |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 659 | auto *memref = opInst->cast<LoadOp>().getMemRef(); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 660 | memrefAccesses[memref].insert(node.id); |
| 661 | } |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 662 | for (auto *opInst : collector.storeOpInsts) { |
| 663 | node.stores.push_back(opInst); |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 664 | auto *memref = opInst->cast<StoreOp>().getMemRef(); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 665 | memrefAccesses[memref].insert(node.id); |
| 666 | } |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 667 | forToNodeMap[&op] = node.id; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 668 | nodes.insert({node.id, node}); |
River Riddle | c5ecf99 | 2019-05-11 22:56:50 | [diff] [blame^] | 669 | } else if (auto loadOp = dyn_cast<LoadOp>(op)) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 670 | // Create graph node for top-level load op. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 671 | Node node(nextNodeId++, &op); |
| 672 | node.loads.push_back(&op); |
| 673 | auto *memref = op.cast<LoadOp>().getMemRef(); |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 674 | memrefAccesses[memref].insert(node.id); |
| 675 | nodes.insert({node.id, node}); |
River Riddle | c5ecf99 | 2019-05-11 22:56:50 | [diff] [blame^] | 676 | } else if (auto storeOp = dyn_cast<StoreOp>(op)) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 677 | // Create graph node for top-level store op. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 678 | Node node(nextNodeId++, &op); |
| 679 | node.stores.push_back(&op); |
| 680 | auto *memref = op.cast<StoreOp>().getMemRef(); |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 681 | memrefAccesses[memref].insert(node.id); |
| 682 | nodes.insert({node.id, node}); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 683 | } else if (op.getNumRegions() != 0) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 684 | // Return false if another region is found (not currently supported). |
| 685 | return false; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 686 | } else if (op.getNumResults() > 0 && !op.use_empty()) { |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 687 | // Create graph node for top-level producer of SSA values, which |
| 688 | // could be used by loop nest nodes. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 689 | Node node(nextNodeId++, &op); |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 690 | nodes.insert({node.id, node}); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 691 | } |
| 692 | } |
| 693 | |
| 694 | // Add dependence edges between nodes which produce SSA values and their |
| 695 | // users. |
| 696 | for (auto &idAndNode : nodes) { |
| 697 | const Node &node = idAndNode.second; |
| 698 | if (!node.loads.empty() || !node.stores.empty()) |
| 699 | continue; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 700 | auto *opInst = node.op; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 701 | for (auto *value : opInst->getResults()) { |
| 702 | for (auto &use : value->getUses()) { |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 703 | SmallVector<AffineForOp, 4> loops; |
River Riddle | b499277 | 2019-02-04 18:38:47 | [diff] [blame] | 704 | getLoopIVs(*use.getOwner(), &loops); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 705 | if (loops.empty()) |
| 706 | continue; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 707 | assert(forToNodeMap.count(loops[0].getOperation()) > 0); |
| 708 | unsigned userLoopNestId = forToNodeMap[loops[0].getOperation()]; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 709 | addEdge(node.id, userLoopNestId, value); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 710 | } |
| 711 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 712 | } |
| 713 | |
| 714 | // Walk memref access lists and add graph edges between dependent nodes. |
| 715 | for (auto &memrefAndList : memrefAccesses) { |
| 716 | unsigned n = memrefAndList.second.size(); |
| 717 | for (unsigned i = 0; i < n; ++i) { |
| 718 | unsigned srcId = memrefAndList.second[i]; |
| 719 | bool srcHasStore = |
| 720 | getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0; |
| 721 | for (unsigned j = i + 1; j < n; ++j) { |
| 722 | unsigned dstId = memrefAndList.second[j]; |
| 723 | bool dstHasStore = |
| 724 | getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0; |
| 725 | if (srcHasStore || dstHasStore) |
| 726 | addEdge(srcId, dstId, memrefAndList.first); |
| 727 | } |
| 728 | } |
| 729 | } |
| 730 | return true; |
| 731 | } |
| 732 | |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 733 | namespace { |
| 734 | |
| 735 | // LoopNestStats aggregates various per-loop statistics (eg. loop trip count |
| 736 | // and operation count) for a loop nest up until the innermost loop body. |
| 737 | struct LoopNestStats { |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 738 | // Map from AffineForOp to immediate child AffineForOps in its loop body. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 739 | DenseMap<Operation *, SmallVector<AffineForOp, 2>> loopMap; |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 740 | // Map from AffineForOp to count of operations in its loop body. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 741 | DenseMap<Operation *, uint64_t> opCountMap; |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 742 | // Map from AffineForOp to its constant trip count. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 743 | DenseMap<Operation *, uint64_t> tripCountMap; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 744 | }; |
| 745 | |
| 746 | // LoopNestStatsCollector walks a single loop nest and gathers per-loop |
| 747 | // trip count and operation count statistics and records them in 'stats'. |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 748 | struct LoopNestStatsCollector { |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 749 | LoopNestStats *stats; |
| 750 | bool hasLoopWithNonConstTripCount = false; |
| 751 | |
| 752 | LoopNestStatsCollector(LoopNestStats *stats) : stats(stats) {} |
| 753 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 754 | void collect(Operation *op) { |
| 755 | op->walk<AffineForOp>([&](AffineForOp forOp) { |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 756 | auto *forInst = forOp.getOperation(); |
River Riddle | 9c08540 | 2019-03-27 15:55:17 | [diff] [blame] | 757 | auto *parentInst = forOp.getOperation()->getParentOp(); |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 758 | if (parentInst != nullptr) { |
| 759 | assert(parentInst->isa<AffineForOp>() && "Expected parent AffineForOp"); |
| 760 | // Add mapping to 'forOp' from its parent AffineForOp. |
| 761 | stats->loopMap[parentInst].push_back(forOp); |
| 762 | } |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 763 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 764 | // Record the number of op operations in the body of 'forOp'. |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 765 | unsigned count = 0; |
| 766 | stats->opCountMap[forInst] = 0; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 767 | for (auto &op : *forOp.getBody()) { |
| 768 | if (!op.isa<AffineForOp>() && !op.isa<AffineIfOp>()) |
River Riddle | bf9c381 | 2019-02-05 00:24:44 | [diff] [blame] | 769 | ++count; |
| 770 | } |
| 771 | stats->opCountMap[forInst] = count; |
| 772 | // Record trip count for 'forOp'. Set flag if trip count is not |
| 773 | // constant. |
| 774 | Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp); |
| 775 | if (!maybeConstTripCount.hasValue()) { |
| 776 | hasLoopWithNonConstTripCount = true; |
| 777 | return; |
| 778 | } |
| 779 | stats->tripCountMap[forInst] = maybeConstTripCount.getValue(); |
| 780 | }); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 781 | } |
| 782 | }; |
| 783 | |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 784 | // Computes the total cost of the loop nest rooted at 'forOp'. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 785 | // Currently, the total cost is computed by counting the total operation |
| 786 | // instance count (i.e. total number of operations in the loop bodyloop |
| 787 | // operation count * loop trip count) for the entire loop nest. |
| 788 | // If 'tripCountOverrideMap' is non-null, overrides the trip count for loops |
| 789 | // specified in the map when computing the total op instance count. |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 790 | // NOTEs: 1) This is used to compute the cost of computation slices, which are |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 791 | // sliced along the iteration dimension, and thus reduce the trip count. |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 792 | // If 'computeCostMap' is non-null, the total op count for forOps specified |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 793 | // in the map is increased (not overridden) by adding the op count from the |
| 794 | // map to the existing op count for the for loop. This is done before |
| 795 | // multiplying by the loop's trip count, and is used to model the cost of |
| 796 | // inserting a sliced loop nest of known cost into the loop's body. |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 797 | // 2) This is also used to compute the cost of fusing a slice of some loop nest |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 798 | // within another loop. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 799 | static int64_t getComputeCost( |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 800 | Operation *forInst, LoopNestStats *stats, |
| 801 | llvm::SmallDenseMap<Operation *, uint64_t, 8> *tripCountOverrideMap, |
| 802 | DenseMap<Operation *, int64_t> *computeCostMap) { |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 803 | // 'opCount' is the total number operations in one iteration of 'forOp' body |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 804 | int64_t opCount = stats->opCountMap[forInst]; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 805 | if (stats->loopMap.count(forInst) > 0) { |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 806 | for (auto childForOp : stats->loopMap[forInst]) { |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 807 | opCount += getComputeCost(childForOp.getOperation(), stats, |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 808 | tripCountOverrideMap, computeCostMap); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 809 | } |
| 810 | } |
| 811 | // Add in additional op instances from slice (if specified in map). |
| 812 | if (computeCostMap != nullptr) { |
| 813 | auto it = computeCostMap->find(forInst); |
| 814 | if (it != computeCostMap->end()) { |
| 815 | opCount += it->second; |
| 816 | } |
| 817 | } |
| 818 | // Override trip count (if specified in map). |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 819 | int64_t tripCount = stats->tripCountMap[forInst]; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 820 | if (tripCountOverrideMap != nullptr) { |
| 821 | auto it = tripCountOverrideMap->find(forInst); |
| 822 | if (it != tripCountOverrideMap->end()) { |
| 823 | tripCount = it->second; |
| 824 | } |
| 825 | } |
| 826 | // Returns the total number of dynamic instances of operations in loop body. |
| 827 | return tripCount * opCount; |
| 828 | } |
| 829 | |
| 830 | } // end anonymous namespace |
| 831 | |
Uday Bondhugula | 7aa60a3 | 2019-02-27 01:32:47 | [diff] [blame] | 832 | // TODO(andydavis,b/126426796): extend this to handle multiple result maps. |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 833 | static Optional<uint64_t> getConstDifference(AffineMap lbMap, AffineMap ubMap) { |
Uday Bondhugula | c1ca23e | 2019-01-16 21:13:00 | [diff] [blame] | 834 | assert(lbMap.getNumResults() == 1 && "expected single result bound map"); |
| 835 | assert(ubMap.getNumResults() == 1 && "expected single result bound map"); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 836 | assert(lbMap.getNumDims() == ubMap.getNumDims()); |
| 837 | assert(lbMap.getNumSymbols() == ubMap.getNumSymbols()); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 838 | AffineExpr lbExpr(lbMap.getResult(0)); |
| 839 | AffineExpr ubExpr(ubMap.getResult(0)); |
| 840 | auto loopSpanExpr = simplifyAffineExpr(ubExpr - lbExpr, lbMap.getNumDims(), |
| 841 | lbMap.getNumSymbols()); |
| 842 | auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>(); |
| 843 | if (!cExpr) |
| 844 | return None; |
| 845 | return cExpr.getValue(); |
| 846 | } |
| 847 | |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 848 | // Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 849 | // nest surrounding 'srcAccess' utilizing slice loop bounds in 'sliceState'. |
| 850 | // Returns true on success, false otherwise (if a non-constant trip count |
| 851 | // was encountered). |
| 852 | // TODO(andydavis) Make this work with non-unit step loops. |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 853 | static bool buildSliceTripCountMap( |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 854 | Operation *srcOpInst, ComputationSliceState *sliceState, |
| 855 | llvm::SmallDenseMap<Operation *, uint64_t, 8> *tripCountMap) { |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 856 | SmallVector<AffineForOp, 4> srcLoopIVs; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 857 | getLoopIVs(*srcOpInst, &srcLoopIVs); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 858 | unsigned numSrcLoopIVs = srcLoopIVs.size(); |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 859 | // Populate map from AffineForOp -> trip count |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 860 | for (unsigned i = 0; i < numSrcLoopIVs; ++i) { |
| 861 | AffineMap lbMap = sliceState->lbs[i]; |
| 862 | AffineMap ubMap = sliceState->ubs[i]; |
Nicolas Vasilache | 0e7a8a9 | 2019-01-26 18:41:17 | [diff] [blame] | 863 | if (lbMap == AffineMap() || ubMap == AffineMap()) { |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 864 | // The iteration of src loop IV 'i' was not sliced. Use full loop bounds. |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 865 | if (srcLoopIVs[i].hasConstantLowerBound() && |
| 866 | srcLoopIVs[i].hasConstantUpperBound()) { |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 867 | (*tripCountMap)[srcLoopIVs[i].getOperation()] = |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 868 | srcLoopIVs[i].getConstantUpperBound() - |
| 869 | srcLoopIVs[i].getConstantLowerBound(); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 870 | continue; |
| 871 | } |
| 872 | return false; |
| 873 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 874 | Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap); |
| 875 | if (!tripCount.hasValue()) |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 876 | return false; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 877 | (*tripCountMap)[srcLoopIVs[i].getOperation()] = tripCount.getValue(); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 878 | } |
| 879 | return true; |
| 880 | } |
| 881 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 882 | // Removes load operations from 'srcLoads' which operate on 'memref', and |
| 883 | // adds them to 'dstLoads'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 884 | static void moveLoadsAccessingMemrefTo(Value *memref, |
| 885 | SmallVectorImpl<Operation *> *srcLoads, |
| 886 | SmallVectorImpl<Operation *> *dstLoads) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 887 | dstLoads->clear(); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 888 | SmallVector<Operation *, 4> srcLoadsToKeep; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 889 | for (auto *load : *srcLoads) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 890 | if (load->cast<LoadOp>().getMemRef() == memref) |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 891 | dstLoads->push_back(load); |
| 892 | else |
| 893 | srcLoadsToKeep.push_back(load); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 894 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 895 | srcLoads->swap(srcLoadsToKeep); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 896 | } |
| 897 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 898 | // Returns the innermost common loop depth for the set of operations in 'ops'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 899 | static unsigned getInnermostCommonLoopDepth(ArrayRef<Operation *> ops) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 900 | unsigned numOps = ops.size(); |
| 901 | assert(numOps > 0); |
| 902 | |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 903 | std::vector<SmallVector<AffineForOp, 4>> loops(numOps); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 904 | unsigned loopDepthLimit = std::numeric_limits<unsigned>::max(); |
| 905 | for (unsigned i = 0; i < numOps; ++i) { |
| 906 | getLoopIVs(*ops[i], &loops[i]); |
| 907 | loopDepthLimit = |
| 908 | std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size())); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 909 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 910 | |
| 911 | unsigned loopDepth = 0; |
| 912 | for (unsigned d = 0; d < loopDepthLimit; ++d) { |
| 913 | unsigned i; |
| 914 | for (i = 1; i < numOps; ++i) { |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 915 | if (loops[i - 1][d] != loops[i][d]) |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 916 | break; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 917 | } |
| 918 | if (i != numOps) |
| 919 | break; |
| 920 | ++loopDepth; |
| 921 | } |
| 922 | return loopDepth; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 923 | } |
| 924 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 925 | // Returns the maximum loop depth at which no dependences between 'loadOpInsts' |
| 926 | // and 'storeOpInsts' are satisfied. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 927 | static unsigned getMaxLoopDepth(ArrayRef<Operation *> loadOpInsts, |
| 928 | ArrayRef<Operation *> storeOpInsts) { |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 929 | // Merge loads and stores into the same array. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 930 | SmallVector<Operation *, 2> ops(loadOpInsts.begin(), loadOpInsts.end()); |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 931 | ops.append(storeOpInsts.begin(), storeOpInsts.end()); |
| 932 | |
| 933 | // Compute the innermost common loop depth for loads and stores. |
| 934 | unsigned loopDepth = getInnermostCommonLoopDepth(ops); |
| 935 | |
| 936 | // Return common loop depth for loads if there are no store ops. |
| 937 | if (storeOpInsts.empty()) |
| 938 | return loopDepth; |
| 939 | |
| 940 | // Check dependences on all pairs of ops in 'ops' and store the minimum |
| 941 | // loop depth at which a dependence is satisfied. |
| 942 | for (unsigned i = 0, e = ops.size(); i < e; ++i) { |
| 943 | auto *srcOpInst = ops[i]; |
| 944 | MemRefAccess srcAccess(srcOpInst); |
| 945 | for (unsigned j = 0; j < e; ++j) { |
| 946 | auto *dstOpInst = ops[j]; |
| 947 | MemRefAccess dstAccess(dstOpInst); |
| 948 | |
| 949 | unsigned numCommonLoops = |
| 950 | getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst); |
| 951 | for (unsigned d = 1; d <= numCommonLoops + 1; ++d) { |
| 952 | FlatAffineConstraints dependenceConstraints; |
| 953 | // TODO(andydavis) Cache dependence analysis results, check cache here. |
| 954 | if (checkMemrefAccessDependence(srcAccess, dstAccess, d, |
| 955 | &dependenceConstraints, |
| 956 | /*dependenceComponents=*/nullptr)) { |
| 957 | // Store minimum loop depth and break because we want the min 'd' at |
| 958 | // which there is a dependence. |
| 959 | loopDepth = std::min(loopDepth, d - 1); |
| 960 | break; |
| 961 | } |
| 962 | } |
| 963 | } |
| 964 | } |
| 965 | return loopDepth; |
| 966 | } |
| 967 | |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 968 | // Compute loop interchange permutation: |
Andy Davis | 44f6dff | 2019-04-09 19:21:28 | [diff] [blame] | 969 | // *) Computes dependence components between all op pairs of ops in loop nest |
| 970 | // rooted at 'loops[0]', for loop depths in range [1, 'maxLoopDepth']. |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 971 | // *) Classifies the outermost 'maxLoopDepth' loops surrounding 'ops' as either |
| 972 | // parallel or sequential. |
| 973 | // *) Computes the loop permutation which sinks sequential loops deeper into |
| 974 | // the loop nest, while preserving the relative order between other loops. |
| 975 | // *) Checks each dependence component against the permutation to see if the |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 976 | // desired loop interchange would violate dependences by making the |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 977 | // dependence componenent lexicographically negative. |
| 978 | // TODO(andydavis) Move this function to LoopUtils. |
| 979 | static bool |
Andy Davis | 44f6dff | 2019-04-09 19:21:28 | [diff] [blame] | 980 | computeLoopInterchangePermutation(ArrayRef<AffineForOp> loops, |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 981 | SmallVectorImpl<unsigned> *loopPermMap) { |
Andy Davis | 44f6dff | 2019-04-09 19:21:28 | [diff] [blame] | 982 | assert(loops.size() > 1); |
| 983 | // Gather dependence components for dependences between all ops in loop nest |
| 984 | // rooted at 'loops[0]', at loop depths in range [1, maxLoopDepth]. |
| 985 | unsigned maxLoopDepth = loops.size(); |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 986 | std::vector<llvm::SmallVector<DependenceComponent, 2>> depCompsVec; |
Andy Davis | 44f6dff | 2019-04-09 19:21:28 | [diff] [blame] | 987 | getDependenceComponents(loops[0], maxLoopDepth, &depCompsVec); |
| 988 | // Mark loops as either parallel or sequential. |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 989 | llvm::SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true); |
Andy Davis | 44f6dff | 2019-04-09 19:21:28 | [diff] [blame] | 990 | for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) { |
| 991 | llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i]; |
| 992 | assert(depComps.size() >= maxLoopDepth); |
| 993 | for (unsigned j = 0; j < maxLoopDepth; ++j) { |
| 994 | DependenceComponent &depComp = depComps[j]; |
| 995 | assert(depComp.lb.hasValue() && depComp.ub.hasValue()); |
| 996 | if (depComp.lb.getValue() != 0 || depComp.ub.getValue() != 0) |
| 997 | isParallelLoop[j] = false; |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 998 | } |
| 999 | } |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1000 | |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 1001 | // Count the number of parallel loops. |
| 1002 | unsigned numParallelLoops = 0; |
| 1003 | for (unsigned i = 0, e = isParallelLoop.size(); i < e; ++i) |
| 1004 | if (isParallelLoop[i]) |
| 1005 | ++numParallelLoops; |
| 1006 | |
| 1007 | // Compute permutation of loops that sinks sequential loops (and thus raises |
| 1008 | // parallel loops) while preserving relative order. |
| 1009 | llvm::SmallVector<unsigned, 4> loopPermMapInv; |
| 1010 | loopPermMapInv.resize(maxLoopDepth); |
| 1011 | loopPermMap->resize(maxLoopDepth); |
| 1012 | unsigned nextSequentialLoop = numParallelLoops; |
| 1013 | unsigned nextParallelLoop = 0; |
| 1014 | for (unsigned i = 0; i < maxLoopDepth; ++i) { |
| 1015 | if (isParallelLoop[i]) { |
| 1016 | (*loopPermMap)[i] = nextParallelLoop; |
| 1017 | loopPermMapInv[nextParallelLoop++] = i; |
| 1018 | } else { |
| 1019 | (*loopPermMap)[i] = nextSequentialLoop; |
| 1020 | loopPermMapInv[nextSequentialLoop++] = i; |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | // Check each dependence component against the permutation to see if the |
| 1025 | // desired loop interchange permutation would make the dependence vectors |
| 1026 | // lexicographically negative. |
| 1027 | // Example 1: [-1, 1][0, 0] |
| 1028 | // Example 2: [0, 0][-1, 1] |
| 1029 | for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) { |
| 1030 | llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i]; |
| 1031 | assert(depComps.size() >= maxLoopDepth); |
| 1032 | // Check if the first non-zero dependence component is positive. |
| 1033 | for (unsigned j = 0; j < maxLoopDepth; ++j) { |
| 1034 | unsigned permIndex = loopPermMapInv[j]; |
| 1035 | assert(depComps[permIndex].lb.hasValue()); |
| 1036 | int64_t depCompLb = depComps[permIndex].lb.getValue(); |
| 1037 | if (depCompLb > 0) |
| 1038 | break; |
| 1039 | if (depCompLb < 0) |
| 1040 | return false; |
| 1041 | } |
| 1042 | } |
| 1043 | return true; |
| 1044 | } |
| 1045 | |
| 1046 | // Sinks all sequential loops to the innermost levels (while preserving |
| 1047 | // relative order among them) and moves all parallel loops to the |
| 1048 | // outermost (while again preserving relative order among them). |
| 1049 | // This can increase the loop depth at which we can fuse a slice, since we are |
| 1050 | // pushing loop carried dependence to a greater depth in the loop nest. |
| 1051 | static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) { |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1052 | assert(node->op->isa<AffineForOp>()); |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1053 | SmallVector<AffineForOp, 4> loops; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1054 | AffineForOp curr = node->op->cast<AffineForOp>(); |
MLIR Team | 0cd589c | 2019-04-04 22:19:17 | [diff] [blame] | 1055 | getPerfectlyNestedLoops(loops, curr); |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 1056 | if (loops.size() < 2) |
| 1057 | return; |
| 1058 | |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 1059 | // Compute loop permutation in 'loopPermMap'. |
| 1060 | llvm::SmallVector<unsigned, 4> loopPermMap; |
Andy Davis | 44f6dff | 2019-04-09 19:21:28 | [diff] [blame] | 1061 | if (!computeLoopInterchangePermutation(loops, &loopPermMap)) |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 1062 | return; |
| 1063 | |
| 1064 | int loopNestRootIndex = -1; |
| 1065 | for (int i = loops.size() - 1; i >= 0; --i) { |
| 1066 | int permIndex = static_cast<int>(loopPermMap[i]); |
| 1067 | // Store the index of the for loop which will be the new loop nest root. |
| 1068 | if (permIndex == 0) |
| 1069 | loopNestRootIndex = i; |
| 1070 | if (permIndex > i) { |
| 1071 | // Sink loop 'i' by 'permIndex - i' levels deeper into the loop nest. |
| 1072 | sinkLoop(loops[i], permIndex - i); |
| 1073 | } |
| 1074 | } |
| 1075 | assert(loopNestRootIndex != -1 && "invalid root index"); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1076 | node->op = loops[loopNestRootIndex].getOperation(); |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 1077 | } |
| 1078 | |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 1079 | // TODO(mlir-team): improve/complete this when we have target data. |
| 1080 | unsigned getMemRefEltSizeInBytes(MemRefType memRefType) { |
| 1081 | auto elementType = memRefType.getElementType(); |
| 1082 | |
| 1083 | unsigned sizeInBits; |
| 1084 | if (elementType.isIntOrFloat()) { |
| 1085 | sizeInBits = elementType.getIntOrFloatBitWidth(); |
| 1086 | } else { |
| 1087 | auto vectorType = elementType.cast<VectorType>(); |
| 1088 | sizeInBits = |
| 1089 | vectorType.getElementTypeBitWidth() * vectorType.getNumElements(); |
| 1090 | } |
| 1091 | return llvm::divideCeil(sizeInBits, 8); |
| 1092 | } |
| 1093 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1094 | // Creates and returns a private (single-user) memref for fused loop rooted |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1095 | // at 'forOp', with (potentially reduced) memref size based on the |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1096 | // MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'. |
| 1097 | // TODO(bondhugula): consider refactoring the common code from generateDma and |
| 1098 | // this one. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1099 | static Value *createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst, |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 1100 | unsigned dstLoopDepth, |
| 1101 | Optional<unsigned> fastMemorySpace, |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 1102 | uint64_t localBufSizeThreshold) { |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1103 | auto *forInst = forOp.getOperation(); |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1104 | |
| 1105 | // Create builder to insert alloc op just before 'forOp'. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1106 | FuncBuilder b(forInst); |
| 1107 | // Builder to create constants at the top level. |
| 1108 | FuncBuilder top(forInst->getFunction()); |
| 1109 | // Create new memref type based on slice bounds. |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 1110 | auto *oldMemRef = srcStoreOpInst->cast<StoreOp>().getMemRef(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1111 | auto oldMemRefType = oldMemRef->getType().cast<MemRefType>(); |
| 1112 | unsigned rank = oldMemRefType.getRank(); |
| 1113 | |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1114 | // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'. |
Uday Bondhugula | 0f50414 | 2019-02-04 21:48:44 | [diff] [blame] | 1115 | MemRefRegion region(srcStoreOpInst->getLoc()); |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1116 | bool validRegion = succeeded(region.compute(srcStoreOpInst, dstLoopDepth)); |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1117 | (void)validRegion; |
| 1118 | assert(validRegion && "unexpected memref region failure"); |
River Riddle | 6859f33 | 2019-01-23 22:39:45 | [diff] [blame] | 1119 | SmallVector<int64_t, 4> newShape; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1120 | std::vector<SmallVector<int64_t, 4>> lbs; |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1121 | SmallVector<int64_t, 8> lbDivisors; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1122 | lbs.reserve(rank); |
| 1123 | // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1124 | // by 'srcStoreOpInst' at depth 'dstLoopDepth'. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1125 | Optional<int64_t> numElements = |
Uday Bondhugula | 0f50414 | 2019-02-04 21:48:44 | [diff] [blame] | 1126 | region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors); |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 1127 | assert(numElements.hasValue() && |
| 1128 | "non-constant number of elts in local buffer"); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1129 | |
Uday Bondhugula | 0f50414 | 2019-02-04 21:48:44 | [diff] [blame] | 1130 | const FlatAffineConstraints *cst = region.getConstraints(); |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1131 | // 'outerIVs' holds the values that this memory region is symbolic/paramteric |
| 1132 | // on; this would correspond to loop IVs surrounding the level at which the |
| 1133 | // slice is being materialized. |
| 1134 | SmallVector<Value *, 8> outerIVs; |
| 1135 | cst->getIdValues(rank, cst->getNumIds(), &outerIVs); |
| 1136 | |
| 1137 | // Build 'rank' AffineExprs from MemRefRegion 'lbs' |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1138 | SmallVector<AffineExpr, 4> offsets; |
| 1139 | offsets.reserve(rank); |
| 1140 | for (unsigned d = 0; d < rank; ++d) { |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1141 | assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size"); |
| 1142 | |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1143 | AffineExpr offset = top.getAffineConstantExpr(0); |
| 1144 | for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) { |
| 1145 | offset = offset + lbs[d][j] * top.getAffineDimExpr(j); |
| 1146 | } |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1147 | assert(lbDivisors[d] > 0); |
| 1148 | offset = |
| 1149 | (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1150 | offsets.push_back(offset); |
| 1151 | } |
| 1152 | |
| 1153 | // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed |
| 1154 | // by 'srcStoreOpInst'. |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 1155 | uint64_t bufSize = |
| 1156 | getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue(); |
| 1157 | unsigned newMemSpace; |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 1158 | if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) { |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 1159 | newMemSpace = fastMemorySpace.getValue(); |
| 1160 | } else { |
| 1161 | newMemSpace = oldMemRefType.getMemorySpace(); |
| 1162 | } |
| 1163 | auto newMemRefType = top.getMemRefType( |
| 1164 | newShape, oldMemRefType.getElementType(), {}, newMemSpace); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1165 | // Gather alloc operands for the dynamic dimensions of the memref. |
| 1166 | SmallVector<Value *, 4> allocOperands; |
| 1167 | unsigned dynamicDimCount = 0; |
| 1168 | for (auto dimSize : oldMemRefType.getShape()) { |
| 1169 | if (dimSize == -1) |
| 1170 | allocOperands.push_back( |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 1171 | top.create<DimOp>(forOp.getLoc(), oldMemRef, dynamicDimCount++)); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1172 | } |
| 1173 | |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1174 | // Create new private memref for fused loop 'forOp'. |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1175 | // TODO(andydavis) Create/move alloc ops for private memrefs closer to their |
| 1176 | // consumer loop nests to reduce their live range. Currently they are added |
| 1177 | // at the beginning of the function, because loop nests can be reordered |
| 1178 | // during the fusion pass. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1179 | Value *newMemRef = |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 1180 | top.create<AllocOp>(forOp.getLoc(), newMemRefType, allocOperands); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1181 | |
| 1182 | // Build an AffineMap to remap access functions based on lower bound offsets. |
| 1183 | SmallVector<AffineExpr, 4> remapExprs; |
| 1184 | remapExprs.reserve(rank); |
| 1185 | unsigned zeroOffsetCount = 0; |
| 1186 | for (unsigned i = 0; i < rank; i++) { |
| 1187 | if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>()) |
| 1188 | if (constExpr.getValue() == 0) |
| 1189 | ++zeroOffsetCount; |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1190 | auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i); |
| 1191 | |
| 1192 | auto remapExpr = |
| 1193 | simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0); |
| 1194 | remapExprs.push_back(remapExpr); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1195 | } |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1196 | auto indexRemap = |
| 1197 | zeroOffsetCount == rank |
Nicolas Vasilache | 0e7a8a9 | 2019-01-26 18:41:17 | [diff] [blame] | 1198 | ? AffineMap() |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1199 | : b.getAffineMap(outerIVs.size() + rank, 0, remapExprs, {}); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1200 | // Replace all users of 'oldMemRef' with 'newMemRef'. |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1201 | bool ret = |
| 1202 | replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap, |
| 1203 | /*extraOperands=*/outerIVs, |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 1204 | /*domInstFilter=*/&*forOp.getBody()->begin()); |
Uday Bondhugula | 94a03f8 | 2019-01-22 21:58:52 | [diff] [blame] | 1205 | assert(ret && "replaceAllMemrefUsesWith should always succeed here"); |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 1206 | (void)ret; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1207 | return newMemRef; |
| 1208 | } |
| 1209 | |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1210 | // Return the number of iterations in the given slice. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1211 | static uint64_t getSliceIterationCount( |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1212 | const llvm::SmallDenseMap<Operation *, uint64_t, 8> &sliceTripCountMap) { |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1213 | uint64_t iterCount = 1; |
| 1214 | for (const auto &count : sliceTripCountMap) { |
| 1215 | iterCount *= count.second; |
| 1216 | } |
| 1217 | return iterCount; |
| 1218 | } |
| 1219 | |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1220 | // Checks if node 'srcId' (which writes to a live out memref), can be safely |
| 1221 | // fused into node 'dstId'. Returns true if the following conditions are met: |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1222 | // *) 'srcNode' only writes to live out 'memref'. |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1223 | // *) 'srcNode' has exactly one output edge on 'memref' (which is to 'dstId'). |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1224 | // *) 'dstNode's read/write region to 'memref' is a super set of 'srcNode's |
| 1225 | // write region to 'memref'. |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1226 | // TODO(andydavis) Generalize this to handle more live in/out cases. |
| 1227 | static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId, |
| 1228 | Value *memref, |
| 1229 | MemRefDependenceGraph *mdg) { |
| 1230 | auto *srcNode = mdg->getNode(srcId); |
| 1231 | auto *dstNode = mdg->getNode(dstId); |
| 1232 | |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1233 | // Gather all memrefs from 'srcNode' store ops. |
| 1234 | DenseSet<Value *> storeMemrefs; |
| 1235 | for (auto *storeOpInst : srcNode->stores) { |
| 1236 | storeMemrefs.insert(storeOpInst->cast<StoreOp>().getMemRef()); |
| 1237 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1238 | // Return false if any of the following are true: |
| 1239 | // *) 'srcNode' writes to a live in/out memref other than 'memref'. |
| 1240 | // *) 'srcNode' has more than one output edge on 'memref'. |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1241 | // Check that all stores are to the same memref. |
| 1242 | if (storeMemrefs.size() != 1 || |
| 1243 | mdg->getOutEdgeCount(srcNode->id, memref) != 1) |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1244 | return false; |
| 1245 | // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOpInst' on 'memref'. |
| 1246 | auto *srcStoreOpInst = srcNode->stores.front(); |
| 1247 | MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc()); |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1248 | if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) { |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1249 | LLVM_DEBUG(llvm::dbgs() |
| 1250 | << "Unable to compute MemRefRegion for source operation\n."); |
| 1251 | return false; |
| 1252 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1253 | SmallVector<int64_t, 4> srcShape; |
| 1254 | // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'. |
| 1255 | // by 'srcStoreOpInst' at depth 'dstLoopDepth'. |
| 1256 | Optional<int64_t> srcNumElements = |
| 1257 | srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape); |
| 1258 | if (!srcNumElements.hasValue()) |
| 1259 | return false; |
| 1260 | |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1261 | // Compute MemRefRegion 'dstRegion' for 'dstStore/LoadOpInst' on 'memref'. |
MLIR Team | 9d9675f | 2019-03-28 21:54:49 | [diff] [blame] | 1262 | // TODO(andydavis) Compute 'unionboundingbox' of all write regions (one for |
| 1263 | // each store op in 'dstStoreOps'). |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1264 | SmallVector<Operation *, 2> dstStoreOps; |
| 1265 | dstNode->getStoreOpsForMemref(memref, &dstStoreOps); |
| 1266 | SmallVector<Operation *, 2> dstLoadOps; |
| 1267 | dstNode->getLoadOpsForMemref(memref, &dstLoadOps); |
| 1268 | |
| 1269 | auto *dstOpInst = dstStoreOps.empty() ? dstLoadOps[0] : dstStoreOps[0]; |
| 1270 | MemRefRegion dstRegion(dstOpInst->getLoc()); |
| 1271 | if (failed(dstRegion.compute(dstOpInst, /*loopDepth=*/0))) { |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1272 | LLVM_DEBUG(llvm::dbgs() |
| 1273 | << "Unable to compute MemRefRegion for dest operation\n."); |
| 1274 | return false; |
| 1275 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1276 | SmallVector<int64_t, 4> dstShape; |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1277 | // Query 'dstRegion' for 'dstShape' and 'dstNumElements'. |
| 1278 | // by 'dstOpInst' at depth 'dstLoopDepth'. |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1279 | Optional<int64_t> dstNumElements = |
Andy Davis | 7c1fc9e | 2019-04-02 13:37:40 | [diff] [blame] | 1280 | dstRegion.getConstantBoundingSizeAndShape(&dstShape); |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1281 | if (!dstNumElements.hasValue()) |
| 1282 | return false; |
| 1283 | |
| 1284 | // Return false if write region is not a superset of 'srcNodes' write |
| 1285 | // region to 'memref'. |
| 1286 | // TODO(andydavis) Check the shape and lower bounds here too. |
| 1287 | if (srcNumElements != dstNumElements) |
| 1288 | return false; |
| 1289 | return true; |
| 1290 | } |
| 1291 | |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1292 | // Computes the union of all slice bounds computed between 'srcOpInst' |
| 1293 | // and each load op in 'dstLoadOpInsts' at 'dstLoopDepth', and returns |
| 1294 | // the union in 'sliceState'. Returns true on success, false otherwise. |
| 1295 | // TODO(andydavis) Move this to a loop fusion utility function. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1296 | static bool getSliceUnion(Operation *srcOpInst, |
| 1297 | ArrayRef<Operation *> dstLoadOpInsts, |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1298 | unsigned numSrcLoopIVs, unsigned dstLoopDepth, |
| 1299 | ComputationSliceState *sliceState) { |
| 1300 | MemRefAccess srcAccess(srcOpInst); |
| 1301 | unsigned numDstLoadOpInsts = dstLoadOpInsts.size(); |
| 1302 | assert(numDstLoadOpInsts > 0); |
| 1303 | // Compute the slice bounds between 'srcOpInst' and 'dstLoadOpInsts[0]'. |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1304 | if (failed(mlir::getBackwardComputationSliceState( |
| 1305 | srcAccess, MemRefAccess(dstLoadOpInsts[0]), dstLoopDepth, |
| 1306 | sliceState))) |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1307 | return false; |
| 1308 | // Handle the common case of one dst load without a copy. |
| 1309 | if (numDstLoadOpInsts == 1) |
| 1310 | return true; |
| 1311 | |
| 1312 | // Initialize 'sliceUnionCst' with the bounds computed in previous step. |
| 1313 | FlatAffineConstraints sliceUnionCst; |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1314 | if (failed(sliceState->getAsConstraints(&sliceUnionCst))) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1315 | LLVM_DEBUG(llvm::dbgs() << "Unable to compute slice bound constraints\n."); |
| 1316 | return false; |
| 1317 | } |
| 1318 | |
| 1319 | // Compute the union of slice bounds between 'srcOpInst' and each load |
| 1320 | // in 'dstLoadOpInsts' in range [1, numDstLoadOpInsts), in 'sliceUnionCst'. |
| 1321 | for (unsigned i = 1; i < numDstLoadOpInsts; ++i) { |
| 1322 | MemRefAccess dstAccess(dstLoadOpInsts[i]); |
| 1323 | // Compute slice bounds for 'srcOpInst' and 'dstLoadOpInsts[i]'. |
| 1324 | ComputationSliceState tmpSliceState; |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1325 | if (failed(mlir::getBackwardComputationSliceState( |
| 1326 | srcAccess, dstAccess, dstLoopDepth, &tmpSliceState))) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1327 | LLVM_DEBUG(llvm::dbgs() << "Unable to compute slice bounds\n."); |
| 1328 | return false; |
| 1329 | } |
| 1330 | |
| 1331 | // Compute constraints for 'tmpSliceState' in 'tmpSliceCst'. |
| 1332 | FlatAffineConstraints tmpSliceCst; |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1333 | if (failed(tmpSliceState.getAsConstraints(&tmpSliceCst))) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1334 | LLVM_DEBUG(llvm::dbgs() |
| 1335 | << "Unable to compute slice bound constraints\n."); |
| 1336 | return false; |
| 1337 | } |
| 1338 | // Compute union bounding box of 'sliceUnionCst' and 'tmpSliceCst'. |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1339 | if (failed(sliceUnionCst.unionBoundingBox(tmpSliceCst))) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1340 | LLVM_DEBUG(llvm::dbgs() |
| 1341 | << "Unable to compute union bounding box of slice bounds.\n."); |
| 1342 | return false; |
| 1343 | } |
| 1344 | } |
| 1345 | |
| 1346 | // Convert any dst loop IVs which are symbol identifiers to dim identifiers. |
| 1347 | sliceUnionCst.convertLoopIVSymbolsToDims(); |
| 1348 | |
| 1349 | sliceState->clearBounds(); |
| 1350 | sliceState->lbs.resize(numSrcLoopIVs, AffineMap()); |
| 1351 | sliceState->ubs.resize(numSrcLoopIVs, AffineMap()); |
| 1352 | |
| 1353 | // Get slice bounds from slice union constraints 'sliceUnionCst'. |
| 1354 | sliceUnionCst.getSliceBounds(numSrcLoopIVs, srcOpInst->getContext(), |
| 1355 | &sliceState->lbs, &sliceState->ubs); |
| 1356 | // Add slice bound operands of union. |
| 1357 | SmallVector<Value *, 4> sliceBoundOperands; |
| 1358 | sliceUnionCst.getIdValues(numSrcLoopIVs, |
| 1359 | sliceUnionCst.getNumDimAndSymbolIds(), |
| 1360 | &sliceBoundOperands); |
| 1361 | // Give each bound its own copy of 'sliceBoundOperands' for subsequent |
| 1362 | // canonicalization. |
| 1363 | sliceState->lbOperands.resize(numSrcLoopIVs, sliceBoundOperands); |
| 1364 | sliceState->ubOperands.resize(numSrcLoopIVs, sliceBoundOperands); |
| 1365 | return true; |
| 1366 | } |
| 1367 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1368 | // Checks the profitability of fusing a backwards slice of the loop nest |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1369 | // surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1370 | // The argument 'srcStoreOpInst' is used to calculate the storage reduction on |
| 1371 | // the memref being produced and consumed, which is an input to the cost model. |
| 1372 | // For producer-constumer fusion, 'srcStoreOpInst' will be the same as |
| 1373 | // 'srcOpInst', as we are slicing w.r.t to that producer. |
| 1374 | // For input-reuse fusion, 'srcOpInst' will be the src loop nest LoadOp which |
| 1375 | // reads from the same memref as dst loop nest load ops, and 'srcStoreOpInst' |
| 1376 | // will be the unique store op in the src node, which will be used to check |
| 1377 | // that the write region is the same after input-reuse fusion. |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1378 | // Returns true if it is profitable to fuse the candidate loop nests. Returns |
| 1379 | // false otherwise. `dstLoopDepth` is set to the most profitable depth at which |
| 1380 | // to materialize the source loop nest slice. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1381 | // The profitability model executes the following steps: |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1382 | // *) Computes the backward computation slice at 'srcOpInst'. This |
| 1383 | // computation slice of the loop nest surrounding 'srcOpInst' is |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1384 | // represented by modified src loop bounds in 'sliceState', which are |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1385 | // functions of loop IVs in the loop nest surrounding 'srcOpInst'. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1386 | // *) Computes the cost of unfused src/dst loop nests (currently the cost of a |
| 1387 | // loop nest is the total number of dynamic operation instances in the loop |
| 1388 | // nest). |
| 1389 | // *) Computes the cost of fusing a slice of the src loop nest into the dst |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1390 | // loop nest at various values of dst loop depth, attempting to fuse |
| 1391 | // the largest compution slice at the maximal dst loop depth (closest to the |
| 1392 | // load) to minimize reuse distance and potentially enable subsequent |
| 1393 | // load/store forwarding. |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1394 | // NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1395 | // the same memref as is written by 'srcOpInst', then the union of slice |
| 1396 | // loop bounds is used to compute the slice and associated slice cost. |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1397 | // NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1398 | // nest, at which the src computation slice is inserted/fused. |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1399 | // NOTE: We attempt to maximize the dst loop depth, but there are cases |
| 1400 | // where a particular setting for 'dstLoopNest' might fuse an unsliced |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1401 | // loop (within the src computation slice) at a depth which results in |
| 1402 | // execessive recomputation (see unit tests for examples). |
| 1403 | // *) Compares the total cost of the unfused loop nests to the min cost fused |
| 1404 | // loop nest computed in the previous step, and returns true if the latter |
| 1405 | // is lower. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1406 | static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst, |
| 1407 | ArrayRef<Operation *> dstLoadOpInsts, |
| 1408 | ArrayRef<Operation *> dstStoreOpInsts, |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1409 | ComputationSliceState *sliceState, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1410 | unsigned *dstLoopDepth, bool maximalFusion) { |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1411 | LLVM_DEBUG({ |
| 1412 | llvm::dbgs() << "Checking whether fusion is profitable between:\n"; |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1413 | llvm::dbgs() << " " << *srcOpInst << " and \n"; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1414 | for (auto dstOpInst : dstLoadOpInsts) { |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1415 | llvm::dbgs() << " " << *dstOpInst << "\n"; |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1416 | }; |
| 1417 | }); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1418 | |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1419 | // Compute cost of sliced and unsliced src loop nest. |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1420 | SmallVector<AffineForOp, 4> srcLoopIVs; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1421 | getLoopIVs(*srcOpInst, &srcLoopIVs); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1422 | unsigned numSrcLoopIVs = srcLoopIVs.size(); |
| 1423 | |
| 1424 | // Walk src loop nest and collect stats. |
| 1425 | LoopNestStats srcLoopNestStats; |
| 1426 | LoopNestStatsCollector srcStatsCollector(&srcLoopNestStats); |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1427 | srcStatsCollector.collect(srcLoopIVs[0].getOperation()); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1428 | // Currently only constant trip count loop nests are supported. |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1429 | if (srcStatsCollector.hasLoopWithNonConstTripCount) { |
| 1430 | LLVM_DEBUG(llvm::dbgs() << "Non-constant trip count loops unsupported.\n"); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1431 | return false; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1432 | } |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1433 | // Compute cost of dst loop nest. |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1434 | SmallVector<AffineForOp, 4> dstLoopIVs; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1435 | getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1436 | |
| 1437 | LoopNestStats dstLoopNestStats; |
| 1438 | LoopNestStatsCollector dstStatsCollector(&dstLoopNestStats); |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1439 | dstStatsCollector.collect(dstLoopIVs[0].getOperation()); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1440 | // Currently only constant trip count loop nests are supported. |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1441 | if (dstStatsCollector.hasLoopWithNonConstTripCount) { |
| 1442 | LLVM_DEBUG(llvm::dbgs() << "Non-constant trip count loops unsupported.\n"); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1443 | return false; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1444 | } |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1445 | |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1446 | // Compute the maximum loop depth at which we can can insert the src slice |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1447 | // and still satisfy dest loop nest dependences, for producer-consumer fusion. |
| 1448 | unsigned maxDstLoopDepth = |
| 1449 | (srcOpInst == srcStoreOpInst) |
| 1450 | ? getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts) |
| 1451 | : dstLoopIVs.size(); |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1452 | if (maxDstLoopDepth == 0) { |
| 1453 | LLVM_DEBUG(llvm::dbgs() << "Can't fuse: maxDstLoopDepth == 0 .\n"); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1454 | return false; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1455 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1456 | |
| 1457 | // Search for min cost value for 'dstLoopDepth'. At each value of |
| 1458 | // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice |
| 1459 | // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union |
| 1460 | // of these bounds). Next the union slice bounds are used to calculate |
| 1461 | // the cost of the slice and the cost of the slice inserted into the dst |
| 1462 | // loop nest at 'dstLoopDepth'. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1463 | uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max(); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1464 | double maxStorageReduction = 0.0; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1465 | Optional<uint64_t> sliceMemEstimate = None; |
| 1466 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1467 | SmallVector<ComputationSliceState, 4> sliceStates; |
| 1468 | sliceStates.resize(maxDstLoopDepth); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1469 | // The best loop depth at which to materialize the slice. |
| 1470 | Optional<unsigned> bestDstLoopDepth = None; |
| 1471 | |
| 1472 | // Compute op instance count for the src loop nest without iteration slicing. |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1473 | uint64_t srcLoopNestCost = |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1474 | getComputeCost(srcLoopIVs[0].getOperation(), &srcLoopNestStats, |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1475 | /*tripCountOverrideMap=*/nullptr, |
| 1476 | /*computeCostMap=*/nullptr); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1477 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1478 | // Compute src loop nest write region size. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1479 | MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc()); |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1480 | if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) { |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1481 | LLVM_DEBUG(llvm::dbgs() |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1482 | << "Unable to compute MemRefRegion for source operation\n."); |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1483 | return false; |
| 1484 | } |
| 1485 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1486 | Optional<int64_t> maybeSrcWriteRegionSizeBytes = |
| 1487 | srcWriteRegion.getRegionSize(); |
| 1488 | if (!maybeSrcWriteRegionSizeBytes.hasValue()) |
| 1489 | return false; |
| 1490 | int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue(); |
| 1491 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1492 | // Compute op instance count for the src loop nest. |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1493 | uint64_t dstLoopNestCost = |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1494 | getComputeCost(dstLoopIVs[0].getOperation(), &dstLoopNestStats, |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1495 | /*tripCountOverrideMap=*/nullptr, |
| 1496 | /*computeCostMap=*/nullptr); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1497 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1498 | // Evaluate all depth choices for materializing the slice in the destination |
| 1499 | // loop nest. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1500 | llvm::SmallDenseMap<Operation *, uint64_t, 8> sliceTripCountMap; |
| 1501 | DenseMap<Operation *, int64_t> computeCostMap; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1502 | for (unsigned i = maxDstLoopDepth; i >= 1; --i) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1503 | // Compute the union of slice bounds of all ops in 'dstLoadOpInsts'. |
| 1504 | if (!getSliceUnion(srcOpInst, dstLoadOpInsts, numSrcLoopIVs, i, |
| 1505 | &sliceStates[i - 1])) { |
| 1506 | LLVM_DEBUG(llvm::dbgs() |
| 1507 | << "getSliceUnion failed for loopDepth: " << i << "\n"); |
| 1508 | continue; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1509 | } |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1510 | |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1511 | // Build trip count map for computation slice. We'll skip cases where the |
| 1512 | // trip count was non-constant. |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1513 | sliceTripCountMap.clear(); |
| 1514 | if (!buildSliceTripCountMap(srcOpInst, &sliceStates[i - 1], |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1515 | &sliceTripCountMap)) { |
| 1516 | LLVM_DEBUG(llvm::dbgs() << "Unable to build slice trip count map.\n."); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1517 | continue; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1518 | } |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1519 | |
| 1520 | // Checks whether a store to load forwarding will happen. |
| 1521 | int64_t sliceIterationCount = getSliceIterationCount(sliceTripCountMap); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1522 | assert(sliceIterationCount > 0); |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1523 | bool storeLoadFwdGuaranteed = (sliceIterationCount == 1); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1524 | |
| 1525 | // Compute cost of fusion for this dest loop depth. |
| 1526 | |
| 1527 | computeCostMap.clear(); |
| 1528 | |
| 1529 | // The store and loads to this memref will disappear. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1530 | // TODO(andydavis) Add load coalescing to memref data flow opt pass. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1531 | if (storeLoadFwdGuaranteed) { |
| 1532 | // A single store disappears: -1 for that. |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1533 | computeCostMap[srcLoopIVs[numSrcLoopIVs - 1].getOperation()] = -1; |
River Riddle | e4628b7 | 2019-04-05 19:24:03 | [diff] [blame] | 1534 | for (auto *loadOp : dstLoadOpInsts) |
| 1535 | if (auto forOp = dyn_cast_or_null<AffineForOp>(loadOp->getParentOp())) |
| 1536 | computeCostMap[forOp] = -1; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1537 | } |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1538 | |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1539 | // Compute op instance count for the src loop nest with iteration slicing. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1540 | int64_t sliceComputeCost = |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1541 | getComputeCost(srcLoopIVs[0].getOperation(), &srcLoopNestStats, |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1542 | /*tripCountOverrideMap=*/&sliceTripCountMap, |
| 1543 | /*computeCostMap=*/&computeCostMap); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1544 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1545 | // Compute cost of fusion for this depth. |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1546 | computeCostMap[dstLoopIVs[i - 1].getOperation()] = sliceComputeCost; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1547 | |
| 1548 | int64_t fusedLoopNestComputeCost = |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1549 | getComputeCost(dstLoopIVs[0].getOperation(), &dstLoopNestStats, |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1550 | /*tripCountOverrideMap=*/nullptr, &computeCostMap); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1551 | |
| 1552 | double additionalComputeFraction = |
| 1553 | fusedLoopNestComputeCost / |
| 1554 | (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) - |
| 1555 | 1; |
| 1556 | |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1557 | // Determine what the slice write MemRefRegion would be, if the src loop |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1558 | // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop |
| 1559 | // nest at loop depth 'i' |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1560 | MemRefRegion sliceWriteRegion(srcStoreOpInst->getLoc()); |
River Riddle | 1e55ae1 | 2019-03-08 06:14:47 | [diff] [blame] | 1561 | if (failed(sliceWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0, |
| 1562 | &sliceStates[i - 1]))) { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1563 | LLVM_DEBUG(llvm::dbgs() |
| 1564 | << "Failed to compute slice write region at loopDepth: " << i |
| 1565 | << "\n"); |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1566 | continue; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1567 | } |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1568 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1569 | Optional<int64_t> maybeSliceWriteRegionSizeBytes = |
| 1570 | sliceWriteRegion.getRegionSize(); |
| 1571 | if (!maybeSliceWriteRegionSizeBytes.hasValue() || |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1572 | maybeSliceWriteRegionSizeBytes.getValue() == 0) { |
| 1573 | LLVM_DEBUG(llvm::dbgs() |
| 1574 | << "Failed to get slice write region size at loopDepth: " << i |
| 1575 | << "\n"); |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1576 | continue; |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1577 | } |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1578 | int64_t sliceWriteRegionSizeBytes = |
| 1579 | maybeSliceWriteRegionSizeBytes.getValue(); |
| 1580 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1581 | // If we are fusing for reuse, check that write regions remain the same. |
| 1582 | // TODO(andydavis) Write region check should check sizes and offsets in |
| 1583 | // each dimension, so that we are sure they are covering the same memref |
| 1584 | // region. Also, move this out to a isMemRefRegionSuperSet helper function. |
| 1585 | if (srcOpInst != srcStoreOpInst && |
| 1586 | sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes) |
| 1587 | continue; |
| 1588 | |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1589 | double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) / |
| 1590 | static_cast<double>(sliceWriteRegionSizeBytes); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1591 | |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1592 | LLVM_DEBUG({ |
| 1593 | std::stringstream msg; |
| 1594 | msg << " evaluating fusion profitability at depth : " << i << "\n" |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 1595 | << std::fixed << std::setprecision(2) |
| 1596 | << " additional compute fraction: " |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1597 | << 100.0 * additionalComputeFraction << "%\n" |
| 1598 | << " storage reduction factor: " << storageReduction << "x\n" |
| 1599 | << " fused nest cost: " << fusedLoopNestComputeCost << "\n" |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1600 | << " slice iteration count: " << sliceIterationCount << "\n" |
| 1601 | << " src write region size: " << srcWriteRegionSizeBytes << "\n" |
| 1602 | << " slice write region size: " << sliceWriteRegionSizeBytes |
| 1603 | << "\n"; |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1604 | llvm::dbgs() << msg.str(); |
| 1605 | }); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1606 | |
| 1607 | double computeToleranceThreshold = |
| 1608 | clFusionAddlComputeTolerance.getNumOccurrences() > 0 |
| 1609 | ? clFusionAddlComputeTolerance |
| 1610 | : LoopFusion::kComputeToleranceThreshold; |
| 1611 | |
| 1612 | // TODO(b/123247369): This is a placeholder cost model. |
| 1613 | // Among all choices that add an acceptable amount of redundant computation |
| 1614 | // (as per computeToleranceThreshold), we will simply pick the one that |
| 1615 | // reduces the intermediary size the most. |
| 1616 | if ((storageReduction > maxStorageReduction) && |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1617 | (maximalFusion || |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1618 | (additionalComputeFraction < computeToleranceThreshold))) { |
| 1619 | maxStorageReduction = storageReduction; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1620 | bestDstLoopDepth = i; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1621 | minFusedLoopNestComputeCost = fusedLoopNestComputeCost; |
MLIR Team | b9dde91 | 2019-02-06 19:01:10 | [diff] [blame] | 1622 | sliceMemEstimate = sliceWriteRegionSizeBytes; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1623 | } |
| 1624 | } |
| 1625 | |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1626 | // A simple cost model: fuse if it reduces the memory footprint. If |
| 1627 | // -maximal-fusion is set, fuse nevertheless. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1628 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1629 | if (!maximalFusion && !bestDstLoopDepth.hasValue()) { |
Uday Bondhugula | a1dad3a | 2019-02-20 02:17:19 | [diff] [blame] | 1630 | LLVM_DEBUG( |
| 1631 | llvm::dbgs() |
| 1632 | << "All fusion choices involve more than the threshold amount of " |
| 1633 | "redundant computation; NOT fusing.\n"); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1634 | return false; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1635 | } |
| 1636 | |
MLIR Team | d42ef78 | 2019-03-04 19:01:25 | [diff] [blame] | 1637 | if (!bestDstLoopDepth.hasValue()) { |
| 1638 | LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n"); |
| 1639 | return false; |
| 1640 | } |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1641 | |
| 1642 | // Set dstLoopDepth based on best values from search. |
| 1643 | *dstLoopDepth = bestDstLoopDepth.getValue(); |
| 1644 | |
| 1645 | LLVM_DEBUG( |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1646 | llvm::dbgs() << " LoopFusion fusion stats:" |
| 1647 | << "\n best loop depth: " << bestDstLoopDepth |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1648 | << "\n src loop nest compute cost: " << srcLoopNestCost |
| 1649 | << "\n dst loop nest compute cost: " << dstLoopNestCost |
| 1650 | << "\n fused loop nest compute cost: " |
| 1651 | << minFusedLoopNestComputeCost << "\n"); |
| 1652 | |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1653 | auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]); |
| 1654 | auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1655 | |
| 1656 | Optional<double> storageReduction = None; |
| 1657 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1658 | if (!maximalFusion) { |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1659 | if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) { |
| 1660 | LLVM_DEBUG( |
| 1661 | llvm::dbgs() |
| 1662 | << " fusion memory benefit cannot be evaluated; NOT fusing.\n"); |
| 1663 | return false; |
| 1664 | } |
| 1665 | |
| 1666 | auto srcMemSizeVal = srcMemSize.getValue(); |
| 1667 | auto dstMemSizeVal = dstMemSize.getValue(); |
| 1668 | |
| 1669 | assert(sliceMemEstimate.hasValue() && "expected value"); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1670 | auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue(); |
| 1671 | |
| 1672 | LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n" |
| 1673 | << " dst mem: " << dstMemSizeVal << "\n" |
| 1674 | << " fused mem: " << fusedMem << "\n" |
| 1675 | << " slice mem: " << sliceMemEstimate << "\n"); |
| 1676 | |
Jacques Pienaar | 2fe8ae4 | 2019-05-04 02:48:57 | [diff] [blame] | 1677 | if (static_cast<long>(fusedMem) > srcMemSizeVal + dstMemSizeVal) { |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1678 | LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n"); |
| 1679 | return false; |
| 1680 | } |
| 1681 | storageReduction = |
| 1682 | 100.0 * |
| 1683 | (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal)); |
| 1684 | } |
| 1685 | |
| 1686 | double additionalComputeFraction = |
| 1687 | 100.0 * (minFusedLoopNestComputeCost / |
| 1688 | (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) - |
| 1689 | 1); |
MLIR Team | 5c5739d | 2019-01-25 06:27:40 | [diff] [blame] | 1690 | (void)additionalComputeFraction; |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1691 | LLVM_DEBUG({ |
| 1692 | std::stringstream msg; |
| 1693 | msg << " fusion is most profitable at depth " << *dstLoopDepth << " with " |
MLIR Team | 8564b27 | 2019-02-22 15:48:59 | [diff] [blame] | 1694 | << std::setprecision(2) << additionalComputeFraction |
Uday Bondhugula | 06d21d9 | 2019-01-25 01:01:49 | [diff] [blame] | 1695 | << "% redundant computation and a "; |
| 1696 | msg << (storageReduction.hasValue() |
| 1697 | ? std::to_string(storageReduction.getValue()) |
| 1698 | : "<unknown>"); |
| 1699 | msg << "% storage reduction.\n"; |
| 1700 | llvm::dbgs() << msg.str(); |
| 1701 | }); |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1702 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1703 | // Update return parameter 'sliceState' with 'bestSliceState'. |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1704 | ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1]; |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1705 | sliceState->lbs = bestSliceState->lbs; |
| 1706 | sliceState->ubs = bestSliceState->ubs; |
| 1707 | sliceState->lbOperands = bestSliceState->lbOperands; |
| 1708 | sliceState->ubOperands = bestSliceState->ubOperands; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1709 | |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1710 | // Canonicalize slice bound affine maps. |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1711 | for (unsigned i = 0; i < numSrcLoopIVs; ++i) { |
Nicolas Vasilache | 0e7a8a9 | 2019-01-26 18:41:17 | [diff] [blame] | 1712 | if (sliceState->lbs[i] != AffineMap()) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1713 | canonicalizeMapAndOperands(&sliceState->lbs[i], |
| 1714 | &sliceState->lbOperands[i]); |
| 1715 | } |
Nicolas Vasilache | 0e7a8a9 | 2019-01-26 18:41:17 | [diff] [blame] | 1716 | if (sliceState->ubs[i] != AffineMap()) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1717 | canonicalizeMapAndOperands(&sliceState->ubs[i], |
| 1718 | &sliceState->ubOperands[i]); |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1719 | } |
| 1720 | } |
| 1721 | return true; |
| 1722 | } |
| 1723 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1724 | // GreedyFusion greedily fuses loop nests which have a producer/consumer or |
| 1725 | // input-reuse relationship on a memref, with the goal of improving locality. |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1726 | // |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1727 | // The steps of the producer-consumer fusion algorithm are as follows: |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1728 | // |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1729 | // *) A worklist is initialized with node ids from the dependence graph. |
| 1730 | // *) For each node id in the worklist: |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1731 | // *) Pop an AffineForOp of the worklist. This 'dstAffineForOp' will be a |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1732 | // candidate destination AffineForOp into which fusion will be attempted. |
| 1733 | // *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'. |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1734 | // *) For each LoadOp in 'dstLoadOps' do: |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1735 | // *) Look up dependent loop nests which have a single store op to the same |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1736 | // memref. |
| 1737 | // *) Check if dependences would be violated by the fusion. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1738 | // *) Get a computation slice of 'srcLoopNest', which adjusts its loop |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1739 | // bounds to be functions of 'dstLoopNest' IVs and symbols. |
| 1740 | // *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest', |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1741 | // at a loop depth determined by the cost model in 'isFusionProfitable'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1742 | // *) Add the newly fused load/store operations to the state, |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1743 | // and also add newly fused load ops to 'dstLoopOps' to be considered |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1744 | // as fusion dst load ops in another iteration. |
| 1745 | // *) Remove old src loop nest and its associated state. |
| 1746 | // |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1747 | // The steps of the input-reuse fusion algorithm are as follows: |
| 1748 | // |
| 1749 | // *) Initialize 'worklist' with node ids from the dependence graph. |
| 1750 | // *) For each 'dstNode' in the worklist: |
| 1751 | // *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which |
| 1752 | // loads from the same memref, but which has no dependence paths to/from. |
| 1753 | // *) Get a computation slice of 'sibLoopNest', which adjusts its loop |
| 1754 | // bounds to be functions of 'dstLoopNest' IVs and symbols. |
| 1755 | // *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest', |
| 1756 | // at a loop depth determined by the cost model in 'isFusionProfitable'. |
| 1757 | // This function also checks that the memref write region of 'sibLoopNest', |
| 1758 | // is preserved in the fused loop nest. |
| 1759 | // *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'. |
| 1760 | // |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1761 | // Given a graph where top-level operations are vertices in the set 'V' and |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1762 | // edges in the set 'E' are dependences between vertices, this algorithm |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1763 | // takes O(V) time for initialization, and has runtime O(V + E). |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1764 | // |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1765 | // This greedy algorithm is not 'maximal' due to the current restriction of |
| 1766 | // fusing along single producer consumer edges, but there is a TODO to fix this. |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1767 | // |
| 1768 | // TODO(andydavis) Experiment with other fusion policies. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1769 | struct GreedyFusion { |
| 1770 | public: |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1771 | // The data dependence graph to traverse during fusion. |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1772 | MemRefDependenceGraph *mdg; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1773 | // Worklist of graph nodes visited during the fusion pass. |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1774 | SmallVector<unsigned, 8> worklist; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1775 | // Set of graph nodes which are present on the worklist. |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1776 | llvm::SmallDenseSet<unsigned, 16> worklistSet; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1777 | // Parameter for local buffer size threshold. |
| 1778 | unsigned localBufSizeThreshold; |
| 1779 | // Parameter for fast memory space. |
| 1780 | Optional<unsigned> fastMemorySpace; |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1781 | // If true, ignore any additional (redundant) computation tolerance threshold |
| 1782 | // that would have prevented fusion. |
| 1783 | bool maximalFusion; |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 1784 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1785 | using Node = MemRefDependenceGraph::Node; |
| 1786 | |
| 1787 | GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1788 | Optional<unsigned> fastMemorySpace, bool maximalFusion) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1789 | : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold), |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1790 | fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {} |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1791 | |
| 1792 | // Initializes 'worklist' with nodes from 'mdg' |
| 1793 | void init() { |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1794 | // TODO(andydavis) Add a priority queue for prioritizing nodes by different |
| 1795 | // metrics (e.g. arithmetic intensity/flops-to-bytes ratio). |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1796 | worklist.clear(); |
| 1797 | worklistSet.clear(); |
| 1798 | for (auto &idAndNode : mdg->nodes) { |
| 1799 | const Node &node = idAndNode.second; |
| 1800 | worklist.push_back(node.id); |
| 1801 | worklistSet.insert(node.id); |
| 1802 | } |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1803 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1804 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1805 | // Run the GreedyFusion pass. |
| 1806 | // *) First pass through the nodes fuses single-use producer nodes into their |
| 1807 | // unique consumer. |
| 1808 | // *) Second pass fuses sibling nodes which share no dependence edges. |
| 1809 | // *) Third pass fuses any remaining producer nodes into their users. |
| 1810 | void run() { |
MLIR Team | c1ff9e8 | 2019-03-06 04:33:30 | [diff] [blame] | 1811 | // TODO(andydavis) Run this repeatedly until a fixed-point is reached. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1812 | fuseProducerConsumerNodes(/*maxSrcUserCount=*/1); |
| 1813 | fuseSiblingNodes(); |
| 1814 | fuseProducerConsumerNodes( |
| 1815 | /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max()); |
| 1816 | eraseUnusedMemRefAllocations(); |
| 1817 | } |
| 1818 | |
| 1819 | void fuseProducerConsumerNodes(unsigned maxSrcUserCount) { |
| 1820 | init(); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1821 | while (!worklist.empty()) { |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1822 | unsigned dstId = worklist.back(); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1823 | worklist.pop_back(); |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1824 | worklistSet.erase(dstId); |
| 1825 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1826 | // Skip if this node was removed (fused into another node). |
| 1827 | if (mdg->nodes.count(dstId) == 0) |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1828 | continue; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1829 | // Get 'dstNode' into which to attempt fusion. |
| 1830 | auto *dstNode = mdg->getNode(dstId); |
| 1831 | // Skip if 'dstNode' is not a loop nest. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1832 | if (!dstNode->op->isa<AffineForOp>()) |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1833 | continue; |
MLIR Team | 8f5f2c7 | 2019-02-15 17:32:18 | [diff] [blame] | 1834 | // Sink sequential loops in 'dstNode' (and thus raise parallel loops) |
| 1835 | // while preserving relative order. This can increase the maximum loop |
| 1836 | // depth at which we can fuse a slice of a producer loop nest into a |
| 1837 | // consumer loop nest. |
| 1838 | sinkSequentialLoops(dstNode); |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1839 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1840 | SmallVector<Operation *, 4> loads = dstNode->loads; |
| 1841 | SmallVector<Operation *, 4> dstLoadOpInsts; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1842 | DenseSet<Value *> visitedMemrefs; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1843 | while (!loads.empty()) { |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1844 | // Get memref of load on top of the stack. |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 1845 | auto *memref = loads.back()->cast<LoadOp>().getMemRef(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1846 | if (visitedMemrefs.count(memref) > 0) |
| 1847 | continue; |
| 1848 | visitedMemrefs.insert(memref); |
MLIR Team | 27d067e | 2019-01-16 17:55:02 | [diff] [blame] | 1849 | // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'. |
| 1850 | moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1851 | // Skip if no input edges along which to fuse. |
| 1852 | if (mdg->inEdges.count(dstId) == 0) |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1853 | continue; |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1854 | // Iterate through in-edges for 'dstId' and src node id for any |
MLIR Team | 1e85191 | 2019-01-31 00:01:46 | [diff] [blame] | 1855 | // edges on 'memref'. |
| 1856 | SmallVector<unsigned, 2> srcNodeIds; |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1857 | for (auto &srcEdge : mdg->inEdges[dstId]) { |
| 1858 | // Skip 'srcEdge' if not for 'memref'. |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1859 | if (srcEdge.value != memref) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1860 | continue; |
MLIR Team | 1e85191 | 2019-01-31 00:01:46 | [diff] [blame] | 1861 | srcNodeIds.push_back(srcEdge.id); |
| 1862 | } |
| 1863 | for (unsigned srcId : srcNodeIds) { |
| 1864 | // Skip if this node was removed (fused into another node). |
| 1865 | if (mdg->nodes.count(srcId) == 0) |
| 1866 | continue; |
| 1867 | // Get 'srcNode' from which to attempt fusion into 'dstNode'. |
| 1868 | auto *srcNode = mdg->getNode(srcId); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1869 | // Skip if 'srcNode' is not a loop nest. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1870 | if (!srcNode->op->isa<AffineForOp>()) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1871 | continue; |
MLIR Team | b28009b | 2019-01-23 19:11:43 | [diff] [blame] | 1872 | // Skip if 'srcNode' has more than one store to any memref. |
| 1873 | // TODO(andydavis) Support fusing multi-output src loop nests. |
| 1874 | if (srcNode->stores.size() != 1) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1875 | continue; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1876 | |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1877 | // Skip if 'srcNode' writes to any live in or escaping memrefs, |
| 1878 | // and cannot be fused. |
| 1879 | bool writesToLiveInOrOut = |
| 1880 | mdg->writesToLiveInOrEscapingMemrefs(srcNode->id); |
| 1881 | if (writesToLiveInOrOut && |
| 1882 | !canFuseSrcWhichWritesToLiveOut(srcId, dstId, memref, mdg)) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1883 | continue; |
| 1884 | |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1885 | // Skip if 'srcNode' out edge count on 'memref' > 'maxSrcUserCount'. |
| 1886 | if (mdg->getOutEdgeCount(srcNode->id, memref) > maxSrcUserCount) |
| 1887 | continue; |
| 1888 | |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1889 | // Compute an operation list insertion point for the fused loop |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1890 | // nest which preserves dependences. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1891 | Operation *insertPointInst = |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1892 | mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1893 | if (insertPointInst == nullptr) |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1894 | continue; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1895 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1896 | // Get unique 'srcNode' store op. |
Chris Lattner | 456ad6a | 2018-12-29 00:05:35 | [diff] [blame] | 1897 | auto *srcStoreOpInst = srcNode->stores.front(); |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1898 | // Gather 'dstNode' store ops to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1899 | SmallVector<Operation *, 2> dstStoreOpInsts; |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1900 | for (auto *storeOpInst : dstNode->stores) |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 1901 | if (storeOpInst->cast<StoreOp>().getMemRef() == memref) |
MLIR Team | d7c8244 | 2019-01-30 23:53:41 | [diff] [blame] | 1902 | dstStoreOpInsts.push_back(storeOpInst); |
| 1903 | |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1904 | unsigned bestDstLoopDepth; |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1905 | mlir::ComputationSliceState sliceState; |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1906 | // Check if fusion would be profitable. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1907 | if (!isFusionProfitable(srcStoreOpInst, srcStoreOpInst, |
| 1908 | dstLoadOpInsts, dstStoreOpInsts, &sliceState, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 1909 | &bestDstLoopDepth, maximalFusion)) |
MLIR Team | 38c2fe3 | 2019-01-14 19:26:25 | [diff] [blame] | 1910 | continue; |
Uday Bondhugula | 864d9e0 | 2019-01-23 17:16:24 | [diff] [blame] | 1911 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1912 | // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'. |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1913 | auto sliceLoopNest = mlir::insertBackwardComputationSlice( |
Uday Bondhugula | b4a1443 | 2019-01-26 00:00:50 | [diff] [blame] | 1914 | srcStoreOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState); |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 1915 | if (sliceLoopNest) { |
River Riddle | af1abcc | 2019-03-25 18:13:31 | [diff] [blame] | 1916 | LLVM_DEBUG(llvm::dbgs() << "\tslice loop nest:\n" |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1917 | << *sliceLoopNest.getOperation() << "\n"); |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1918 | // Move 'dstAffineForOp' before 'insertPointInst' if needed. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1919 | auto dstAffineForOp = dstNode->op->cast<AffineForOp>(); |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1920 | if (insertPointInst != dstAffineForOp.getOperation()) { |
| 1921 | dstAffineForOp.getOperation()->moveBefore(insertPointInst); |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1922 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1923 | // Update edges between 'srcNode' and 'dstNode'. |
MLIR Team | a0f3db40 | 2019-01-29 17:36:41 | [diff] [blame] | 1924 | mdg->updateEdges(srcNode->id, dstNode->id, memref); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1925 | |
| 1926 | // Collect slice loop stats. |
| 1927 | LoopNestStateCollector sliceCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1928 | sliceCollector.collect(sliceLoopNest.getOperation()); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1929 | // Promote single iteration slice loops to single IV value. |
River Riddle | 5052bd8 | 2019-02-02 00:42:18 | [diff] [blame] | 1930 | for (auto forOp : sliceCollector.forOps) { |
| 1931 | promoteIfSingleIteration(forOp); |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 1932 | } |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1933 | if (!writesToLiveInOrOut) { |
| 1934 | // Create private memref for 'memref' in 'dstAffineForOp'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1935 | SmallVector<Operation *, 4> storesForMemref; |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1936 | for (auto *storeOpInst : sliceCollector.storeOpInsts) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 1937 | if (storeOpInst->cast<StoreOp>().getMemRef() == memref) |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1938 | storesForMemref.push_back(storeOpInst); |
| 1939 | } |
| 1940 | assert(storesForMemref.size() == 1); |
| 1941 | auto *newMemRef = createPrivateMemRef( |
| 1942 | dstAffineForOp, storesForMemref[0], bestDstLoopDepth, |
| 1943 | fastMemorySpace, localBufSizeThreshold); |
| 1944 | visitedMemrefs.insert(newMemRef); |
| 1945 | // Create new node in dependence graph for 'newMemRef' alloc op. |
| 1946 | unsigned newMemRefNodeId = |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1947 | mdg->addNode(newMemRef->getDefiningOp()); |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1948 | // Add edge from 'newMemRef' node to dstNode. |
| 1949 | mdg->addEdge(newMemRefNodeId, dstId, newMemRef); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1950 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1951 | |
| 1952 | // Collect dst loop stats after memref privatizaton transformation. |
| 1953 | LoopNestStateCollector dstLoopCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 1954 | dstLoopCollector.collect(dstAffineForOp.getOperation()); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1955 | |
| 1956 | // Add new load ops to current Node load op list 'loads' to |
| 1957 | // continue fusing based on new operands. |
| 1958 | for (auto *loadOpInst : dstLoopCollector.loadOpInsts) { |
River Riddle | 96ebde9 | 2019-03-25 20:02:06 | [diff] [blame] | 1959 | auto *loadMemRef = loadOpInst->cast<LoadOp>().getMemRef(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1960 | if (visitedMemrefs.count(loadMemRef) == 0) |
| 1961 | loads.push_back(loadOpInst); |
| 1962 | } |
| 1963 | |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1964 | // Clear and add back loads and stores. |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1965 | mdg->clearNodeLoadAndStores(dstNode->id); |
| 1966 | mdg->addToNode(dstId, dstLoopCollector.loadOpInsts, |
| 1967 | dstLoopCollector.storeOpInsts); |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 1968 | // Remove old src loop nest if it no longer has outgoing dependence |
Amit Sabne | 70a416d | 2019-04-09 16:17:40 | [diff] [blame] | 1969 | // edges, and if it does not write to a memref which escapes the |
MLIR Team | 58aa383 | 2019-02-16 01:12:19 | [diff] [blame] | 1970 | // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has |
| 1971 | // been fused into 'dstNode' and write region of 'dstNode' covers |
| 1972 | // the write region of 'srcNode', and 'srcNode' has no other users |
| 1973 | // so it is safe to remove. |
| 1974 | if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) { |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1975 | mdg->removeNode(srcNode->id); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 1976 | srcNode->op->erase(); |
MLIR Team | a78edcd | 2019-02-05 14:57:08 | [diff] [blame] | 1977 | } else { |
| 1978 | // Add remaining users of 'oldMemRef' back on the worklist (if not |
| 1979 | // already there), as its replacement with a local/private memref |
| 1980 | // has reduced dependences on 'oldMemRef' which may have created |
| 1981 | // new fusion opportunities. |
| 1982 | if (mdg->outEdges.count(srcNode->id) > 0) { |
| 1983 | SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges = |
| 1984 | mdg->outEdges[srcNode->id]; |
| 1985 | for (auto &outEdge : oldOutEdges) { |
| 1986 | if (outEdge.value == memref && |
| 1987 | worklistSet.count(outEdge.id) == 0) { |
| 1988 | worklist.push_back(outEdge.id); |
| 1989 | worklistSet.insert(outEdge.id); |
| 1990 | } |
| 1991 | } |
| 1992 | } |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 1993 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1994 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 1995 | } |
| 1996 | } |
| 1997 | } |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 1998 | } |
| 1999 | |
| 2000 | // Visits each node in the graph, and for each node, attempts to fuse it with |
| 2001 | // its sibling nodes (nodes which share a parent, but no dependence edges). |
| 2002 | void fuseSiblingNodes() { |
| 2003 | init(); |
| 2004 | while (!worklist.empty()) { |
| 2005 | unsigned dstId = worklist.back(); |
| 2006 | worklist.pop_back(); |
| 2007 | worklistSet.erase(dstId); |
| 2008 | |
| 2009 | // Skip if this node was removed (fused into another node). |
| 2010 | if (mdg->nodes.count(dstId) == 0) |
| 2011 | continue; |
| 2012 | // Get 'dstNode' into which to attempt fusion. |
| 2013 | auto *dstNode = mdg->getNode(dstId); |
| 2014 | // Skip if 'dstNode' is not a loop nest. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2015 | if (!dstNode->op->isa<AffineForOp>()) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2016 | continue; |
| 2017 | // Attempt to fuse 'dstNode' with its sibling nodes in the graph. |
| 2018 | fuseWithSiblingNodes(dstNode); |
| 2019 | } |
| 2020 | } |
| 2021 | |
| 2022 | // Attempt to fuse 'dstNode' with sibling nodes in the graph. |
| 2023 | void fuseWithSiblingNodes(Node *dstNode) { |
| 2024 | DenseSet<unsigned> visitedSibNodeIds; |
| 2025 | std::pair<unsigned, Value *> idAndMemref; |
| 2026 | while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) { |
| 2027 | unsigned sibId = idAndMemref.first; |
| 2028 | Value *memref = idAndMemref.second; |
| 2029 | // TODO(andydavis) Check that 'sibStoreOpInst' post-dominates all other |
| 2030 | // stores to the same memref in 'sibNode' loop nest. |
| 2031 | auto *sibNode = mdg->getNode(sibId); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2032 | // Compute an operation list insertion point for the fused loop |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2033 | // nest which preserves dependences. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2034 | assert(sibNode->op->getBlock() == dstNode->op->getBlock()); |
| 2035 | Operation *insertPointInst = |
| 2036 | sibNode->op->isBeforeInBlock(dstNode->op) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2037 | ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id) |
| 2038 | : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id); |
| 2039 | if (insertPointInst == nullptr) |
| 2040 | continue; |
| 2041 | |
| 2042 | // Check if fusion would be profitable and at what depth. |
| 2043 | |
| 2044 | // Get unique 'sibNode' load op to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2045 | SmallVector<Operation *, 2> sibLoadOpInsts; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2046 | sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts); |
| 2047 | // Currently findSiblingNodeToFuse searches for siblings with one load. |
| 2048 | assert(sibLoadOpInsts.size() == 1); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2049 | Operation *sibLoadOpInst = sibLoadOpInsts[0]; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2050 | assert(!sibNode->stores.empty()); |
| 2051 | // TODO(andydavis) Choose the store which postdominates all other stores. |
| 2052 | auto *sibStoreOpInst = sibNode->stores.back(); |
| 2053 | |
| 2054 | // Gather 'dstNode' load ops to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2055 | SmallVector<Operation *, 2> dstLoadOpInsts; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2056 | dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts); |
| 2057 | |
| 2058 | // Gather 'dstNode' store ops to 'memref'. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2059 | SmallVector<Operation *, 2> dstStoreOpInsts; |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2060 | dstNode->getStoreOpsForMemref(memref, &dstStoreOpInsts); |
| 2061 | |
| 2062 | unsigned bestDstLoopDepth; |
| 2063 | mlir::ComputationSliceState sliceState; |
| 2064 | |
| 2065 | // Check if fusion would be profitable. |
| 2066 | if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstLoadOpInsts, |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 2067 | dstStoreOpInsts, &sliceState, &bestDstLoopDepth, |
| 2068 | maximalFusion)) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2069 | continue; |
| 2070 | |
| 2071 | // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'. |
| 2072 | auto sliceLoopNest = mlir::insertBackwardComputationSlice( |
| 2073 | sibLoadOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState); |
| 2074 | if (sliceLoopNest != nullptr) { |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2075 | auto dstForInst = dstNode->op->cast<AffineForOp>(); |
| 2076 | // Update operation position of fused loop nest (if needed). |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 2077 | if (insertPointInst != dstForInst.getOperation()) { |
| 2078 | dstForInst.getOperation()->moveBefore(insertPointInst); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2079 | } |
| 2080 | // Update data dependence graph state post fusion. |
| 2081 | updateStateAfterSiblingFusion(sliceLoopNest, sibNode, dstNode); |
| 2082 | } |
| 2083 | } |
| 2084 | } |
| 2085 | |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 2086 | // Searches function argument uses and the graph from 'dstNode' looking for a |
| 2087 | // fusion candidate sibling node which shares no dependences with 'dstNode' |
| 2088 | // but which loads from the same memref. Returns true and sets |
| 2089 | // 'idAndMemrefToFuse' on success. Returns false otherwise. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2090 | bool findSiblingNodeToFuse(Node *dstNode, |
| 2091 | DenseSet<unsigned> *visitedSibNodeIds, |
| 2092 | std::pair<unsigned, Value *> *idAndMemrefToFuse) { |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 2093 | // Returns true if 'sibNode' can be fused with 'dstNode' for input reuse |
| 2094 | // on 'memref'. |
| 2095 | auto canFuseWithSibNode = [&](Node *sibNode, Value *memref) { |
| 2096 | // Skip if 'outEdge' is not a read-after-write dependence. |
| 2097 | // TODO(andydavis) Remove restrict to single load op restriction. |
| 2098 | if (sibNode->getLoadOpCount(memref) != 1) |
| 2099 | return false; |
| 2100 | // Skip if there exists a path of dependent edges between |
| 2101 | // 'sibNode' and 'dstNode'. |
| 2102 | if (mdg->hasDependencePath(sibNode->id, dstNode->id) || |
| 2103 | mdg->hasDependencePath(dstNode->id, sibNode->id)) |
| 2104 | return false; |
| 2105 | // Skip sib node if it loads to (and stores from) the same memref on |
| 2106 | // which it also has an input dependence edge. |
| 2107 | DenseSet<Value *> loadAndStoreMemrefSet; |
| 2108 | sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet); |
| 2109 | if (llvm::any_of(loadAndStoreMemrefSet, [=](Value *memref) { |
| 2110 | return mdg->getIncomingMemRefAccesses(sibNode->id, memref) > 0; |
| 2111 | })) |
| 2112 | return false; |
| 2113 | |
| 2114 | // Check that all stores are to the same memref. |
| 2115 | DenseSet<Value *> storeMemrefs; |
| 2116 | for (auto *storeOpInst : sibNode->stores) { |
| 2117 | storeMemrefs.insert(storeOpInst->cast<StoreOp>().getMemRef()); |
| 2118 | } |
| 2119 | if (storeMemrefs.size() != 1) |
| 2120 | return false; |
| 2121 | return true; |
| 2122 | }; |
| 2123 | |
| 2124 | // Search for siblings which load the same memref function argument. |
| 2125 | auto *fn = dstNode->op->getFunction(); |
| 2126 | for (unsigned i = 0, e = fn->getNumArguments(); i != e; ++i) { |
| 2127 | for (auto &use : fn->getArgument(i)->getUses()) { |
River Riddle | c5ecf99 | 2019-05-11 22:56:50 | [diff] [blame^] | 2128 | if (auto loadOp = dyn_cast<LoadOp>(use.getOwner())) { |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 2129 | // Gather loops surrounding 'use'. |
| 2130 | SmallVector<AffineForOp, 4> loops; |
| 2131 | getLoopIVs(*use.getOwner(), &loops); |
| 2132 | // Skip 'use' if it is not within a loop nest. |
| 2133 | if (loops.empty()) |
| 2134 | continue; |
| 2135 | Node *sibNode = mdg->getForOpNode(loops[0]); |
| 2136 | assert(sibNode != nullptr); |
| 2137 | // Skip 'use' if it not a sibling to 'dstNode'. |
| 2138 | if (sibNode->id == dstNode->id) |
| 2139 | continue; |
| 2140 | // Skip 'use' if it has been visited. |
| 2141 | if (visitedSibNodeIds->count(sibNode->id) > 0) |
| 2142 | continue; |
| 2143 | // Skip 'use' if it does not load from the same memref as 'dstNode'. |
| 2144 | auto *memref = loadOp.getMemRef(); |
| 2145 | if (dstNode->getLoadOpCount(memref) == 0) |
| 2146 | continue; |
| 2147 | // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'. |
| 2148 | if (canFuseWithSibNode(sibNode, memref)) { |
| 2149 | visitedSibNodeIds->insert(sibNode->id); |
| 2150 | idAndMemrefToFuse->first = sibNode->id; |
| 2151 | idAndMemrefToFuse->second = memref; |
| 2152 | return true; |
| 2153 | } |
| 2154 | } |
| 2155 | } |
| 2156 | } |
| 2157 | |
| 2158 | // Search for siblings by following edges through an intermediate src node. |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2159 | // Collect candidate 'dstNode' input edges in 'inEdges'. |
| 2160 | SmallVector<MemRefDependenceGraph::Edge, 2> inEdges; |
| 2161 | mdg->forEachMemRefInputEdge( |
| 2162 | dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) { |
| 2163 | // Add 'inEdge' if it is a read-after-write dependence. |
| 2164 | if (dstNode->getLoadOpCount(inEdge.value) > 0 && |
| 2165 | mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0) |
| 2166 | inEdges.push_back(inEdge); |
| 2167 | }); |
| 2168 | |
| 2169 | // Search for sibling nodes to fuse by visiting output edges from each input |
| 2170 | // edge in 'inEdges'. |
| 2171 | for (auto &inEdge : inEdges) { |
| 2172 | // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'. |
| 2173 | SmallVector<MemRefDependenceGraph::Edge, 2> outEdges; |
| 2174 | mdg->forEachMemRefOutputEdge( |
| 2175 | inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) { |
| 2176 | unsigned sibNodeId = outEdge.id; |
| 2177 | if (visitedSibNodeIds->count(sibNodeId) > 0) |
| 2178 | return; |
| 2179 | // Skip output edge if not a sibling using the same memref. |
| 2180 | if (outEdge.id == dstNode->id || outEdge.value != inEdge.value) |
| 2181 | return; |
| 2182 | auto *sibNode = mdg->getNode(sibNodeId); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2183 | if (!sibNode->op->isa<AffineForOp>()) |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2184 | return; |
MLIR Team | 9d30b36 | 2019-03-29 15:06:25 | [diff] [blame] | 2185 | // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'. |
| 2186 | if (canFuseWithSibNode(sibNode, outEdge.value)) { |
| 2187 | // Add candidate 'outEdge' to sibling node. |
| 2188 | outEdges.push_back(outEdge); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2189 | } |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2190 | }); |
| 2191 | |
| 2192 | // Add first candidate if any were returned. |
| 2193 | if (!outEdges.empty()) { |
| 2194 | visitedSibNodeIds->insert(outEdges[0].id); |
| 2195 | idAndMemrefToFuse->first = outEdges[0].id; |
| 2196 | idAndMemrefToFuse->second = outEdges[0].value; |
| 2197 | return true; |
| 2198 | } |
| 2199 | } |
| 2200 | return false; |
| 2201 | } |
| 2202 | |
Chris Lattner | d9b5bc8 | 2019-03-25 02:53:05 | [diff] [blame] | 2203 | void updateStateAfterSiblingFusion(AffineForOp sliceLoopNest, Node *sibNode, |
| 2204 | Node *dstNode) { |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2205 | // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion. |
| 2206 | mdg->updateEdges(sibNode->id, dstNode->id); |
| 2207 | |
| 2208 | // Collect slice loop stats. |
| 2209 | LoopNestStateCollector sliceCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 2210 | sliceCollector.collect(sliceLoopNest.getOperation()); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2211 | // Promote single iteration slice loops to single IV value. |
| 2212 | for (auto forOp : sliceCollector.forOps) { |
| 2213 | promoteIfSingleIteration(forOp); |
| 2214 | } |
| 2215 | |
| 2216 | // Collect dst loop stats after memref privatizaton transformation. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2217 | auto dstForInst = dstNode->op->cast<AffineForOp>(); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2218 | LoopNestStateCollector dstLoopCollector; |
River Riddle | f9d9153 | 2019-03-27 00:05:09 | [diff] [blame] | 2219 | dstLoopCollector.collect(dstForInst.getOperation()); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2220 | // Clear and add back loads and stores |
| 2221 | mdg->clearNodeLoadAndStores(dstNode->id); |
| 2222 | mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts, |
| 2223 | dstLoopCollector.storeOpInsts); |
| 2224 | // Remove old sibling loop nest if it no longer has outgoing dependence |
| 2225 | // edges, and it does not write to a memref which escapes the |
| 2226 | // function. |
| 2227 | if (mdg->getOutEdgeCount(sibNode->id) == 0) { |
| 2228 | mdg->removeNode(sibNode->id); |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2229 | sibNode->op->cast<AffineForOp>().erase(); |
MLIR Team | d038e34 | 2019-03-01 19:50:25 | [diff] [blame] | 2230 | } |
| 2231 | } |
| 2232 | |
| 2233 | // Clean up any allocs with no users. |
| 2234 | void eraseUnusedMemRefAllocations() { |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 2235 | for (auto &pair : mdg->memrefEdgeCount) { |
| 2236 | if (pair.second > 0) |
| 2237 | continue; |
| 2238 | auto *memref = pair.first; |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2239 | // Skip if there exist other uses (return operation or function calls). |
MLIR Team | 71495d5 | 2019-01-22 21:23:37 | [diff] [blame] | 2240 | if (!memref->use_empty()) |
| 2241 | continue; |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 2242 | // Use list expected to match the dep graph info. |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2243 | auto *op = memref->getDefiningOp(); |
River Riddle | 1423acc | 2019-04-23 21:38:26 | [diff] [blame] | 2244 | if (isa_and_nonnull<AllocOp>(op)) |
River Riddle | 99b87c9 | 2019-03-27 21:02:02 | [diff] [blame] | 2245 | op->erase(); |
MLIR Team | c4237ae | 2019-01-18 16:56:27 | [diff] [blame] | 2246 | } |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 2247 | } |
MLIR Team | 3b69230 | 2018-12-17 17:57:14 | [diff] [blame] | 2248 | }; |
| 2249 | |
| 2250 | } // end anonymous namespace |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 2251 | |
River Riddle | ed5fe20 | 2019-02-28 22:50:42 | [diff] [blame] | 2252 | void LoopFusion::runOnFunction() { |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 2253 | // Override if a command line argument was provided. |
Uday Bondhugula | 8be2627 | 2019-02-02 01:06:22 | [diff] [blame] | 2254 | if (clFusionFastMemorySpace.getNumOccurrences() > 0) { |
| 2255 | fastMemorySpace = clFusionFastMemorySpace.getValue(); |
| 2256 | } |
| 2257 | |
Uday Bondhugula | d4b3ff1 | 2019-02-27 00:10:19 | [diff] [blame] | 2258 | // Override if a command line argument was provided. |
| 2259 | if (clFusionLocalBufThreshold.getNumOccurrences() > 0) { |
| 2260 | localBufSizeThreshold = clFusionLocalBufThreshold * 1024; |
| 2261 | } |
| 2262 | |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 2263 | if (clMaximalLoopFusion.getNumOccurrences() > 0) |
| 2264 | maximalFusion = clMaximalLoopFusion; |
| 2265 | |
MLIR Team | 6892ffb | 2018-12-20 04:42:55 | [diff] [blame] | 2266 | MemRefDependenceGraph g; |
Uday Bondhugula | 02af8c2 | 2019-03-05 23:05:34 | [diff] [blame] | 2267 | if (g.init(getFunction())) |
Uday Bondhugula | ce7e5953 | 2019-03-08 17:21:52 | [diff] [blame] | 2268 | GreedyFusion(&g, localBufSizeThreshold, fastMemorySpace, maximalFusion) |
| 2269 | .run(); |
MLIR Team | f28e4df | 2018-11-01 14:26:00 | [diff] [blame] | 2270 | } |
Jacques Pienaar | 6f0fb22 | 2018-11-07 02:34:18 | [diff] [blame] | 2271 | |
Nicolas Vasilache | 258e8d9 | 2019-05-03 18:07:37 | [diff] [blame] | 2272 | static PassRegistration<LoopFusion> pass("affine-loop-fusion", |
| 2273 | "Fuse loop nests"); |