blob: 6627e73056af3aceef79f31560000280077cadf1 [file] [log] [blame]
MLIR Teamf28e4df2018-11-01 14:26:001//===- 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
22#include "mlir/Analysis/AffineAnalysis.h"
Uday Bondhuguladfe07b72019-02-23 00:51:0823#include "mlir/Analysis/AffineStructures.h"
MLIR Teamf28e4df2018-11-01 14:26:0024#include "mlir/Analysis/LoopAnalysis.h"
MLIR Team3b692302018-12-17 17:57:1425#include "mlir/Analysis/Utils.h"
River Riddleffde9752019-08-20 22:36:0826#include "mlir/Dialect/AffineOps/AffineOps.h"
River Riddleba0fa922019-08-19 18:00:4727#include "mlir/Dialect/StandardOps/Ops.h"
MLIR Teamf28e4df2018-11-01 14:26:0028#include "mlir/IR/AffineExpr.h"
29#include "mlir/IR/AffineMap.h"
30#include "mlir/IR/Builders.h"
River Riddle48ccae22019-02-20 01:17:4631#include "mlir/Pass/Pass.h"
Andy Davisa560f2c2019-05-24 17:54:2232#include "mlir/Transforms/LoopFusionUtils.h"
MLIR Teamf28e4df2018-11-01 14:26:0033#include "mlir/Transforms/LoopUtils.h"
34#include "mlir/Transforms/Passes.h"
MLIR Teamc4237ae2019-01-18 16:56:2735#include "mlir/Transforms/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0036#include "llvm/ADT/DenseMap.h"
MLIR Team3b692302018-12-17 17:57:1437#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/SetVector.h"
MLIR Team4eef7952018-12-21 19:06:2339#include "llvm/Support/CommandLine.h"
MLIR Team38c2fe32019-01-14 19:26:2540#include "llvm/Support/Debug.h"
MLIR Team3b692302018-12-17 17:57:1441#include "llvm/Support/raw_ostream.h"
Uday Bondhugula864d9e02019-01-23 17:16:2442#include <iomanip>
Stella Laurenzo1a2ad062019-05-14 01:10:4843#include <sstream>
Nicolas Vasilache258e8d92019-05-03 18:07:3744#define DEBUG_TYPE "affine-loop-fusion"
MLIR Team38c2fe32019-01-14 19:26:2545
MLIR Team3b692302018-12-17 17:57:1446using llvm::SetVector;
MLIR Teamf28e4df2018-11-01 14:26:0047
48using namespace mlir;
49
River Riddle75c21e12019-01-26 06:14:0450static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options");
51
Uday Bondhugulace7e59532019-03-08 17:21:5252/// Disables fusion profitability check and fuses if valid. Ignore any
53/// additional (redundant) computation tolerance threshold
54/// that would have prevented fusion.
MLIR Teamc4237ae2019-01-18 16:56:2755static llvm::cl::opt<bool>
Uday Bondhugulaeee85362019-03-02 01:42:1356 clMaximalLoopFusion("fusion-maximal",
River Riddle75c21e12019-01-26 06:14:0457 llvm::cl::desc("Enables maximal loop fusion"),
58 llvm::cl::cat(clOptionsCategory));
Uday Bondhugula864d9e02019-01-23 17:16:2459
60/// A threshold in percent of additional computation allowed when fusing.
61static llvm::cl::opt<double> clFusionAddlComputeTolerance(
Uday Bondhugulaeee85362019-03-02 01:42:1362 "fusion-compute-tolerance",
Uday Bondhugulaa1dad3a2019-02-20 02:17:1963 llvm::cl::desc("Fractional increase in additional "
64 "computation tolerated while fusing"),
River Riddle75c21e12019-01-26 06:14:0465 llvm::cl::cat(clOptionsCategory));
MLIR Teamc4237ae2019-01-18 16:56:2766
Uday Bondhugula8be26272019-02-02 01:06:2267static llvm::cl::opt<unsigned> clFusionFastMemorySpace(
Uday Bondhugulaeee85362019-03-02 01:42:1368 "fusion-fast-mem-space",
Uday Bondhugula8be26272019-02-02 01:06:2269 llvm::cl::desc("Faster memory space number to promote fusion buffers to"),
70 llvm::cl::cat(clOptionsCategory));
71
Uday Bondhugulace7e59532019-03-08 17:21:5272// A local buffer of size less than or equal to this size is automatically
73// promoted to fast memory after producer-consumer fusion.
Uday Bondhugulad4b3ff12019-02-27 00:10:1974static llvm::cl::opt<unsigned long long> clFusionLocalBufThreshold(
Uday Bondhugulaeee85362019-03-02 01:42:1375 "fusion-local-buf-threshold",
Uday Bondhugulad4b3ff12019-02-27 00:10:1976 llvm::cl::desc("Threshold size (KiB) for promoting local buffers to fast "
Uday Bondhugula8be26272019-02-02 01:06:2277 "memory space"),
78 llvm::cl::cat(clOptionsCategory));
79
MLIR Teamf28e4df2018-11-01 14:26:0080namespace {
81
MLIR Team3b692302018-12-17 17:57:1482/// Loop fusion pass. This pass currently supports a greedy fusion policy,
83/// which fuses loop nests with single-writer/single-reader memref dependences
84/// with the goal of improving locality.
85
86// TODO(andydavis) Support fusion of source loop nests which write to multiple
87// memrefs, where each memref can have multiple users (if profitable).
MLIR Teamf28e4df2018-11-01 14:26:0088// TODO(andydavis) Extend this pass to check for fusion preventing dependences,
89// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1490
River Riddlec6c53442019-02-27 18:59:2991struct LoopFusion : public FunctionPass<LoopFusion> {
Uday Bondhugulace7e59532019-03-08 17:21:5292 LoopFusion(unsigned fastMemorySpace = 0, uint64_t localBufSizeThreshold = 0,
93 bool maximalFusion = false)
River Riddlec6c53442019-02-27 18:59:2994 : localBufSizeThreshold(localBufSizeThreshold),
Uday Bondhugulace7e59532019-03-08 17:21:5295 fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {}
MLIR Teamf28e4df2018-11-01 14:26:0096
River Riddleed5fe202019-02-28 22:50:4297 void runOnFunction() override;
Uday Bondhugula864d9e02019-01-23 17:16:2498
Uday Bondhugulad4b3ff12019-02-27 00:10:1999 // Any local buffers smaller than this size (in bytes) will be created in
Uday Bondhugula8be26272019-02-02 01:06:22100 // `fastMemorySpace` if provided.
Uday Bondhugulad4b3ff12019-02-27 00:10:19101 uint64_t localBufSizeThreshold;
Uday Bondhugula8be26272019-02-02 01:06:22102 Optional<unsigned> fastMemorySpace = None;
Uday Bondhugulace7e59532019-03-08 17:21:52103 // If true, ignore any additional (redundant) computation tolerance threshold
104 // that would have prevented fusion.
105 bool maximalFusion;
Uday Bondhugula8be26272019-02-02 01:06:22106
Uday Bondhugula864d9e02019-01-23 17:16:24107 // The amount of additional computation that is tolerated while fusing
108 // pair-wise as a fraction of the total computation.
109 constexpr static double kComputeToleranceThreshold = 0.30f;
MLIR Teamf28e4df2018-11-01 14:26:00110};
111
MLIR Teamf28e4df2018-11-01 14:26:00112} // end anonymous namespace
113
River Riddlef1b100c2019-09-13 20:33:46114std::unique_ptr<OpPassBase<FuncOp>>
Mehdi Amini926fb682019-08-13 02:12:42115mlir::createLoopFusionPass(unsigned fastMemorySpace,
116 uint64_t localBufSizeThreshold, bool maximalFusion) {
Jacques Pienaar79f53b02019-08-17 18:05:35117 return std::make_unique<LoopFusion>(fastMemorySpace, localBufSizeThreshold,
118 maximalFusion);
Uday Bondhugulad4b3ff12019-02-27 00:10:19119}
MLIR Teamf28e4df2018-11-01 14:26:00120
MLIR Team3b692302018-12-17 17:57:14121namespace {
MLIR Teamf28e4df2018-11-01 14:26:00122
MLIR Team3b692302018-12-17 17:57:14123// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:35124// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:44125struct LoopNestStateCollector {
Chris Lattnerd9b5bc82019-03-25 02:53:05126 SmallVector<AffineForOp, 4> forOps;
River Riddle99b87c92019-03-27 21:02:02127 SmallVector<Operation *, 4> loadOpInsts;
128 SmallVector<Operation *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:53129 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:14130
River Riddle99b87c92019-03-27 21:02:02131 void collect(Operation *opToWalk) {
132 opToWalk->walk([&](Operation *op) {
River Riddled5b60ee82019-05-12 01:59:54133 if (isa<AffineForOp>(op))
River Riddleadca3c22019-05-12 00:57:32134 forOps.push_back(cast<AffineForOp>(op));
River Riddle99b87c92019-03-27 21:02:02135 else if (op->getNumRegions() != 0)
River Riddlebf9c3812019-02-05 00:24:44136 hasNonForRegion = true;
Andy Davis2e1187d2019-07-03 17:35:03137 else if (isa<AffineLoadOp>(op))
River Riddle99b87c92019-03-27 21:02:02138 loadOpInsts.push_back(op);
Andy Davis2e1187d2019-07-03 17:35:03139 else if (isa<AffineStoreOp>(op))
River Riddle99b87c92019-03-27 21:02:02140 storeOpInsts.push_back(op);
River Riddlebf9c3812019-02-05 00:24:44141 });
MLIR Team3b692302018-12-17 17:57:14142 }
143};
144
MLIR Team71495d52019-01-22 21:23:37145// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
River Riddle99b87c92019-03-27 21:02:02146static bool isMemRefDereferencingOp(Operation &op) {
Andy Davis2e1187d2019-07-03 17:35:03147 if (isa<AffineLoadOp>(op) || isa<AffineStoreOp>(op) ||
148 isa<AffineDmaStartOp>(op) || isa<AffineDmaWaitOp>(op))
MLIR Team71495d52019-01-22 21:23:37149 return true;
150 return false;
151}
MLIR Teamd038e342019-03-01 19:50:25152
MLIR Team6892ffb2018-12-20 04:42:55153// MemRefDependenceGraph is a graph data structure where graph nodes are
River Riddle8c443672019-07-09 23:17:55154// top-level operations in a FuncOp which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55155// are memref dependences between the nodes.
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03156// TODO(andydavis) Add a more flexible dependence graph representation.
MLIR Team6892ffb2018-12-20 04:42:55157// TODO(andydavis) Add a depth parameter to dependence graph construction.
158struct MemRefDependenceGraph {
159public:
160 // Node represents a node in the graph. A Node is either an entire loop nest
161 // rooted at the top level which contains loads/stores, or a top level
162 // load/store.
163 struct Node {
164 // The unique identifier of this node in the graph.
165 unsigned id;
Amit Sabne70a416d2019-04-09 16:17:40166 // The top-level statement which is (or contains) a load/store.
River Riddle99b87c92019-03-27 21:02:02167 Operation *op;
Chris Lattner5187cfc2018-12-28 05:21:41168 // List of load operations.
River Riddle99b87c92019-03-27 21:02:02169 SmallVector<Operation *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35170 // List of store op insts.
River Riddle99b87c92019-03-27 21:02:02171 SmallVector<Operation *, 4> stores;
172 Node(unsigned id, Operation *op) : id(id), op(op) {}
MLIR Team6892ffb2018-12-20 04:42:55173
174 // Returns the load op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10175 unsigned getLoadOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55176 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35177 for (auto *loadOpInst : loads) {
Andy Davis2e1187d2019-07-03 17:35:03178 if (memref == cast<AffineLoadOp>(loadOpInst).getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55179 ++loadOpCount;
180 }
181 return loadOpCount;
182 }
183
184 // Returns the store op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10185 unsigned getStoreOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55186 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35187 for (auto *storeOpInst : stores) {
Andy Davis2e1187d2019-07-03 17:35:03188 if (memref == cast<AffineStoreOp>(storeOpInst).getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55189 ++storeOpCount;
190 }
191 return storeOpCount;
192 }
MLIR Team58aa3832019-02-16 01:12:19193
MLIR Teamd038e342019-03-01 19:50:25194 // Returns all store ops in 'storeOps' which access 'memref'.
MLIR Team58aa3832019-02-16 01:12:19195 void getStoreOpsForMemref(Value *memref,
River Riddle99b87c92019-03-27 21:02:02196 SmallVectorImpl<Operation *> *storeOps) {
MLIR Team58aa3832019-02-16 01:12:19197 for (auto *storeOpInst : stores) {
Andy Davis2e1187d2019-07-03 17:35:03198 if (memref == cast<AffineStoreOp>(storeOpInst).getMemRef())
MLIR Team58aa3832019-02-16 01:12:19199 storeOps->push_back(storeOpInst);
200 }
201 }
MLIR Teamd038e342019-03-01 19:50:25202
203 // Returns all load ops in 'loadOps' which access 'memref'.
204 void getLoadOpsForMemref(Value *memref,
River Riddle99b87c92019-03-27 21:02:02205 SmallVectorImpl<Operation *> *loadOps) {
MLIR Teamd038e342019-03-01 19:50:25206 for (auto *loadOpInst : loads) {
Andy Davis2e1187d2019-07-03 17:35:03207 if (memref == cast<AffineLoadOp>(loadOpInst).getMemRef())
MLIR Teamd038e342019-03-01 19:50:25208 loadOps->push_back(loadOpInst);
209 }
210 }
211
212 // Returns all memrefs in 'loadAndStoreMemrefSet' for which this node
213 // has at least one load and store operation.
214 void getLoadAndStoreMemrefSet(DenseSet<Value *> *loadAndStoreMemrefSet) {
215 llvm::SmallDenseSet<Value *, 2> loadMemrefs;
216 for (auto *loadOpInst : loads) {
Andy Davis2e1187d2019-07-03 17:35:03217 loadMemrefs.insert(cast<AffineLoadOp>(loadOpInst).getMemRef());
MLIR Teamd038e342019-03-01 19:50:25218 }
219 for (auto *storeOpInst : stores) {
Andy Davis2e1187d2019-07-03 17:35:03220 auto *memref = cast<AffineStoreOp>(storeOpInst).getMemRef();
MLIR Teamd038e342019-03-01 19:50:25221 if (loadMemrefs.count(memref) > 0)
222 loadAndStoreMemrefSet->insert(memref);
223 }
224 }
MLIR Team6892ffb2018-12-20 04:42:55225 };
226
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03227 // Edge represents a data dependence between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55228 struct Edge {
229 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46230 // If this edge is stored in Edge = Node.inEdges[i], then
231 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
232 // If this edge is stored in Edge = Node.outEdges[i], then
233 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55234 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41235 // The SSA value on which this edge represents a dependence.
236 // If the value is a memref, then the dependence is between graph nodes
237 // which contain accesses to the same memref 'value'. If the value is a
238 // non-memref value, then the dependence is between a graph node which
239 // defines an SSA value and another graph node which uses the SSA value
River Riddle99b87c92019-03-27 21:02:02240 // (e.g. a constant operation defining a value which is used inside a loop
MLIR Teama0f3db402019-01-29 17:36:41241 // nest).
242 Value *value;
MLIR Team6892ffb2018-12-20 04:42:55243 };
244
245 // Map from node id to Node.
246 DenseMap<unsigned, Node> nodes;
247 // Map from node id to list of input edges.
248 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
249 // Map from node id to list of output edges.
250 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27251 // Map from memref to a count on the dependence edges associated with that
252 // memref.
253 DenseMap<Value *, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41254 // The next unique identifier to use for newly created graph nodes.
255 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55256
257 MemRefDependenceGraph() {}
258
259 // Initializes the dependence graph based on operations in 'f'.
260 // Returns true on success, false otherwise.
River Riddle8c443672019-07-09 23:17:55261 bool init(FuncOp f);
MLIR Team6892ffb2018-12-20 04:42:55262
263 // Returns the graph node for 'id'.
264 Node *getNode(unsigned id) {
265 auto it = nodes.find(id);
266 assert(it != nodes.end());
267 return &it->second;
268 }
269
MLIR Team9d30b362019-03-29 15:06:25270 // Returns the graph node for 'forOp'.
271 Node *getForOpNode(AffineForOp forOp) {
272 for (auto &idAndNode : nodes)
273 if (idAndNode.second.op == forOp.getOperation())
274 return &idAndNode.second;
275 return nullptr;
276 }
277
River Riddle99b87c92019-03-27 21:02:02278 // Adds a node with 'op' to the graph and returns its unique identifier.
279 unsigned addNode(Operation *op) {
280 Node node(nextNodeId++, op);
MLIR Teama0f3db402019-01-29 17:36:41281 nodes.insert({node.id, node});
282 return node.id;
283 }
284
MLIR Teamc4237ae2019-01-18 16:56:27285 // Remove node 'id' (and its associated edges) from graph.
286 void removeNode(unsigned id) {
287 // Remove each edge in 'inEdges[id]'.
288 if (inEdges.count(id) > 0) {
289 SmallVector<Edge, 2> oldInEdges = inEdges[id];
290 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41291 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27292 }
293 }
294 // Remove each edge in 'outEdges[id]'.
295 if (outEdges.count(id) > 0) {
296 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
297 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41298 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27299 }
300 }
301 // Erase remaining node state.
302 inEdges.erase(id);
303 outEdges.erase(id);
304 nodes.erase(id);
305 }
306
MLIR Teamd7c82442019-01-30 23:53:41307 // Returns true if node 'id' writes to any memref which escapes (or is an
308 // argument to) the function/block. Returns false otherwise.
309 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37310 Node *node = getNode(id);
311 for (auto *storeOpInst : node->stores) {
Andy Davis2e1187d2019-07-03 17:35:03312 auto *memref = cast<AffineStoreOp>(storeOpInst).getMemRef();
River Riddle99b87c92019-03-27 21:02:02313 auto *op = memref->getDefiningOp();
MLIR Team58aa3832019-02-16 01:12:19314 // Return true if 'memref' is a block argument.
River Riddle99b87c92019-03-27 21:02:02315 if (!op)
MLIR Teamd7c82442019-01-30 23:53:41316 return true;
MLIR Team58aa3832019-02-16 01:12:19317 // Return true if any use of 'memref' escapes the function.
River Riddle8780d8d2019-05-18 18:09:07318 for (auto *user : memref->getUsers())
319 if (!isMemRefDereferencingOp(*user))
MLIR Teamd7c82442019-01-30 23:53:41320 return true;
MLIR Teamd7c82442019-01-30 23:53:41321 }
322 return false;
323 }
324
Diego Caballero34510552019-10-09 17:36:54325 // Returns the unique AffineStoreOp in `node` that meets all the following:
326 // *) store is the only one that writes to a function-local memref live out
327 // of `node`,
328 // *) store is not the source of a self-dependence on `node`.
329 // Otherwise, returns a null AffineStoreOp.
330 AffineStoreOp getUniqueOutgoingStore(Node *node) {
331 AffineStoreOp uniqueStore;
332
333 // Return null if `node` doesn't have any outgoing edges.
334 auto outEdgeIt = outEdges.find(node->id);
335 if (outEdgeIt == outEdges.end())
336 return nullptr;
337
338 const auto &nodeOutEdges = outEdgeIt->second;
339 for (auto *op : node->stores) {
340 auto storeOp = cast<AffineStoreOp>(op);
341 auto *memref = storeOp.getMemRef();
342 // Skip this store if there are no dependences on its memref. This means
343 // that store either:
344 // *) writes to a memref that is only read within the same loop nest
345 // (self-dependence edges are not represented in graph at the moment),
346 // *) writes to a function live out memref (function parameter), or
347 // *) is dead.
348 if (llvm::all_of(nodeOutEdges, [=](const Edge &edge) {
349 return (edge.value != memref);
350 }))
351 continue;
352
353 if (uniqueStore)
354 // Found multiple stores to function-local live-out memrefs.
355 return nullptr;
356 // Found first store to function-local live-out memref.
357 uniqueStore = storeOp;
358 }
359
360 return uniqueStore;
361 }
362
MLIR Teamd7c82442019-01-30 23:53:41363 // Returns true if node 'id' can be removed from the graph. Returns false
364 // otherwise. A node can be removed from the graph iff the following
365 // conditions are met:
366 // *) The node does not write to any memref which escapes (or is a
367 // function/block argument).
368 // *) The node has no successors in the dependence graph.
369 bool canRemoveNode(unsigned id) {
370 if (writesToLiveInOrEscapingMemrefs(id))
371 return false;
372 Node *node = getNode(id);
373 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41374 // Return false if there exist out edges from 'id' on 'memref'.
Andy Davis2e1187d2019-07-03 17:35:03375 if (getOutEdgeCount(id, cast<AffineStoreOp>(storeOpInst).getMemRef()) > 0)
MLIR Teama0f3db402019-01-29 17:36:41376 return false;
MLIR Team71495d52019-01-22 21:23:37377 }
MLIR Teama0f3db402019-01-29 17:36:41378 return true;
MLIR Team71495d52019-01-22 21:23:37379 }
380
MLIR Teamd038e342019-03-01 19:50:25381 // Returns true iff there is an edge from node 'srcId' to node 'dstId' which
382 // is for 'value' if non-null, or for any value otherwise. Returns false
383 // otherwise.
384 bool hasEdge(unsigned srcId, unsigned dstId, Value *value = nullptr) {
MLIR Team27d067e2019-01-16 17:55:02385 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
386 return false;
387 }
388 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25389 return edge.id == dstId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02390 });
391 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25392 return edge.id == srcId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02393 });
394 return hasOutEdge && hasInEdge;
395 }
396
MLIR Teama0f3db402019-01-29 17:36:41397 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
398 void addEdge(unsigned srcId, unsigned dstId, Value *value) {
399 if (!hasEdge(srcId, dstId, value)) {
400 outEdges[srcId].push_back({dstId, value});
401 inEdges[dstId].push_back({srcId, value});
402 if (value->getType().isa<MemRefType>())
403 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02404 }
MLIR Team6892ffb2018-12-20 04:42:55405 }
406
MLIR Teama0f3db402019-01-29 17:36:41407 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
408 void removeEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team6892ffb2018-12-20 04:42:55409 assert(inEdges.count(dstId) > 0);
410 assert(outEdges.count(srcId) > 0);
MLIR Teama0f3db402019-01-29 17:36:41411 if (value->getType().isa<MemRefType>()) {
412 assert(memrefEdgeCount.count(value) > 0);
413 memrefEdgeCount[value]--;
414 }
MLIR Team6892ffb2018-12-20 04:42:55415 // Remove 'srcId' from 'inEdges[dstId]'.
416 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41417 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55418 inEdges[dstId].erase(it);
419 break;
420 }
421 }
422 // Remove 'dstId' from 'outEdges[srcId]'.
423 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41424 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55425 outEdges[srcId].erase(it);
426 break;
427 }
428 }
429 }
430
MLIR Teamd038e342019-03-01 19:50:25431 // Returns true if there is a path in the dependence graph from node 'srcId'
432 // to node 'dstId'. Returns false otherwise.
433 bool hasDependencePath(unsigned srcId, unsigned dstId) {
434 // Worklist state is: <node-id, next-output-edge-index-to-visit>
435 SmallVector<std::pair<unsigned, unsigned>, 4> worklist;
436 worklist.push_back({srcId, 0});
437 // Run DFS traversal to see if 'dstId' is reachable from 'srcId'.
438 while (!worklist.empty()) {
439 auto &idAndIndex = worklist.back();
440 // Return true if we have reached 'dstId'.
441 if (idAndIndex.first == dstId)
442 return true;
443 // Pop and continue if node has no out edges, or if all out edges have
444 // already been visited.
445 if (outEdges.count(idAndIndex.first) == 0 ||
446 idAndIndex.second == outEdges[idAndIndex.first].size()) {
447 worklist.pop_back();
448 continue;
449 }
450 // Get graph edge to traverse.
451 Edge edge = outEdges[idAndIndex.first][idAndIndex.second];
452 // Increment next output edge index for 'idAndIndex'.
453 ++idAndIndex.second;
454 // Add node at 'edge.id' to worklist.
455 worklist.push_back({edge.id, 0});
456 }
457 return false;
458 }
459
MLIR Teama0f3db402019-01-29 17:36:41460 // Returns the input edge count for node 'id' and 'memref' from src nodes
MLIR Teamd038e342019-03-01 19:50:25461 // which access 'memref' with a store operation.
MLIR Teama0f3db402019-01-29 17:36:41462 unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55463 unsigned inEdgeCount = 0;
464 if (inEdges.count(id) > 0)
465 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41466 if (inEdge.value == memref) {
467 Node *srcNode = getNode(inEdge.id);
468 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
MLIR Teamd038e342019-03-01 19:50:25469 if (srcNode->getStoreOpCount(memref) > 0)
MLIR Teama0f3db402019-01-29 17:36:41470 ++inEdgeCount;
471 }
MLIR Team6892ffb2018-12-20 04:42:55472 return inEdgeCount;
473 }
474
MLIR Teamd038e342019-03-01 19:50:25475 // Returns the output edge count for node 'id' and 'memref' (if non-null),
476 // otherwise returns the total output edge count from node 'id'.
477 unsigned getOutEdgeCount(unsigned id, Value *memref = nullptr) {
MLIR Team6892ffb2018-12-20 04:42:55478 unsigned outEdgeCount = 0;
479 if (outEdges.count(id) > 0)
480 for (auto &outEdge : outEdges[id])
MLIR Teamd038e342019-03-01 19:50:25481 if (!memref || outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55482 ++outEdgeCount;
483 return outEdgeCount;
484 }
485
River Riddle99b87c92019-03-27 21:02:02486 // Computes and returns an insertion point operation, before which the
MLIR Teama0f3db402019-01-29 17:36:41487 // the fused <srcId, dstId> loop nest can be inserted while preserving
488 // dependences. Returns nullptr if no such insertion point is found.
River Riddle99b87c92019-03-27 21:02:02489 Operation *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40490 if (outEdges.count(srcId) == 0)
River Riddle99b87c92019-03-27 21:02:02491 return getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41492
493 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
River Riddle99b87c92019-03-27 21:02:02494 SmallPtrSet<Operation *, 2> srcDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41495 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08496 if (outEdge.id != dstId)
River Riddle99b87c92019-03-27 21:02:02497 srcDepInsts.insert(getNode(outEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41498
499 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
River Riddle99b87c92019-03-27 21:02:02500 SmallPtrSet<Operation *, 2> dstDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41501 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08502 if (inEdge.id != srcId)
River Riddle99b87c92019-03-27 21:02:02503 dstDepInsts.insert(getNode(inEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41504
River Riddle99b87c92019-03-27 21:02:02505 Operation *srcNodeInst = getNode(srcId)->op;
506 Operation *dstNodeInst = getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41507
508 // Computing insertion point:
River Riddle99b87c92019-03-27 21:02:02509 // *) Walk all operation positions in Block operation list in the
510 // range (src, dst). For each operation 'op' visited in this search:
511 // *) Store in 'firstSrcDepPos' the first position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41512 // dependence edge from 'srcNode'.
River Riddle99b87c92019-03-27 21:02:02513 // *) Store in 'lastDstDepPost' the last position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41514 // dependence edge to 'dstNode'.
515 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
River Riddle99b87c92019-03-27 21:02:02516 // operation insertion point (or return null pointer if no such
MLIR Teama0f3db402019-01-29 17:36:41517 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
River Riddle99b87c92019-03-27 21:02:02518 SmallVector<Operation *, 2> depInsts;
MLIR Teama0f3db402019-01-29 17:36:41519 Optional<unsigned> firstSrcDepPos;
520 Optional<unsigned> lastDstDepPos;
521 unsigned pos = 0;
522 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
523 it != Block::iterator(dstNodeInst); ++it) {
River Riddle99b87c92019-03-27 21:02:02524 Operation *op = &(*it);
525 if (srcDepInsts.count(op) > 0 && firstSrcDepPos == None)
MLIR Teama0f3db402019-01-29 17:36:41526 firstSrcDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02527 if (dstDepInsts.count(op) > 0)
MLIR Teama0f3db402019-01-29 17:36:41528 lastDstDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02529 depInsts.push_back(op);
MLIR Teama0f3db402019-01-29 17:36:41530 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40531 }
MLIR Teama0f3db402019-01-29 17:36:41532
533 if (firstSrcDepPos.hasValue()) {
534 if (lastDstDepPos.hasValue()) {
535 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
536 // No valid insertion point exists which preserves dependences.
537 return nullptr;
538 }
539 }
540 // Return the insertion point at 'firstSrcDepPos'.
541 return depInsts[firstSrcDepPos.getValue()];
542 }
543 // No dependence targets in range (or only dst deps in range), return
544 // 'dstNodInst' insertion point.
545 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55546 }
547
MLIR Teama0f3db402019-01-29 17:36:41548 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
Andy Davis68a8da42019-11-18 19:20:03549 // has been replaced in node at 'dstId' by a private memref depending
550 // on the value of 'createPrivateMemRef'.
551 void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef,
552 bool createPrivateMemRef) {
MLIR Team6892ffb2018-12-20 04:42:55553 // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'.
554 if (inEdges.count(srcId) > 0) {
555 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
556 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41557 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
558 if (inEdge.value != oldMemRef)
559 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55560 }
561 }
MLIR Teamc4237ae2019-01-18 16:56:27562 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55563 if (outEdges.count(srcId) > 0) {
564 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
565 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27566 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
567 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41568 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55569 }
570 }
MLIR Teama0f3db402019-01-29 17:36:41571 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
572 // replaced by a private memref). These edges could come from nodes
573 // other than 'srcId' which were removed in the previous step.
Andy Davis68a8da42019-11-18 19:20:03574 if (inEdges.count(dstId) > 0 && createPrivateMemRef) {
MLIR Teama0f3db402019-01-29 17:36:41575 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
576 for (auto &inEdge : oldInEdges)
577 if (inEdge.value == oldMemRef)
578 removeEdge(inEdge.id, dstId, inEdge.value);
579 }
MLIR Team6892ffb2018-12-20 04:42:55580 }
581
MLIR Teamd038e342019-03-01 19:50:25582 // Update edge mappings for nodes 'sibId' and 'dstId' to reflect fusion
583 // of sibling node 'sidId' into node 'dstId'.
584 void updateEdges(unsigned sibId, unsigned dstId) {
585 // For each edge in 'inEdges[sibId]':
586 // *) Add new edge from source node 'inEdge.id' to 'dstNode'.
587 // *) Remove edge from source node 'inEdge.id' to 'sibNode'.
588 if (inEdges.count(sibId) > 0) {
589 SmallVector<Edge, 2> oldInEdges = inEdges[sibId];
590 for (auto &inEdge : oldInEdges) {
591 addEdge(inEdge.id, dstId, inEdge.value);
592 removeEdge(inEdge.id, sibId, inEdge.value);
593 }
594 }
595
596 // For each edge in 'outEdges[sibId]' to node 'id'
597 // *) Add new edge from 'dstId' to 'outEdge.id'.
598 // *) Remove edge from 'sibId' to 'outEdge.id'.
599 if (outEdges.count(sibId) > 0) {
600 SmallVector<Edge, 2> oldOutEdges = outEdges[sibId];
601 for (auto &outEdge : oldOutEdges) {
602 addEdge(dstId, outEdge.id, outEdge.value);
603 removeEdge(sibId, outEdge.id, outEdge.value);
604 }
605 }
606 }
607
MLIR Team6892ffb2018-12-20 04:42:55608 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddle99b87c92019-03-27 21:02:02609 void addToNode(unsigned id, const SmallVectorImpl<Operation *> &loads,
610 const SmallVectorImpl<Operation *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55611 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35612 for (auto *loadOpInst : loads)
613 node->loads.push_back(loadOpInst);
614 for (auto *storeOpInst : stores)
615 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55616 }
617
MLIR Teamc4237ae2019-01-18 16:56:27618 void clearNodeLoadAndStores(unsigned id) {
619 Node *node = getNode(id);
620 node->loads.clear();
621 node->stores.clear();
622 }
623
MLIR Teamd038e342019-03-01 19:50:25624 // Calls 'callback' for each input edge incident to node 'id' which carries a
625 // memref dependence.
626 void forEachMemRefInputEdge(unsigned id,
627 const std::function<void(Edge)> &callback) {
628 if (inEdges.count(id) > 0)
629 forEachMemRefEdge(inEdges[id], callback);
630 }
Amit Sabne70a416d2019-04-09 16:17:40631
MLIR Teamd038e342019-03-01 19:50:25632 // Calls 'callback' for each output edge from node 'id' which carries a
633 // memref dependence.
634 void forEachMemRefOutputEdge(unsigned id,
635 const std::function<void(Edge)> &callback) {
636 if (outEdges.count(id) > 0)
637 forEachMemRefEdge(outEdges[id], callback);
638 }
Amit Sabne70a416d2019-04-09 16:17:40639
MLIR Teamd038e342019-03-01 19:50:25640 // Calls 'callback' for each edge in 'edges' which carries a memref
641 // dependence.
642 void forEachMemRefEdge(ArrayRef<Edge> edges,
643 const std::function<void(Edge)> &callback) {
644 for (auto &edge : edges) {
645 // Skip if 'edge' is not a memref dependence edge.
646 if (!edge.value->getType().isa<MemRefType>())
647 continue;
648 assert(nodes.count(edge.id) > 0);
649 // Skip if 'edge.id' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:54650 if (!isa<AffineForOp>(getNode(edge.id)->op))
MLIR Teamd038e342019-03-01 19:50:25651 continue;
652 // Visit current input edge 'edge'.
653 callback(edge);
654 }
655 }
656
MLIR Team6892ffb2018-12-20 04:42:55657 void print(raw_ostream &os) const {
658 os << "\nMemRefDependenceGraph\n";
659 os << "\nNodes:\n";
660 for (auto &idAndNode : nodes) {
661 os << "Node: " << idAndNode.first << "\n";
662 auto it = inEdges.find(idAndNode.first);
663 if (it != inEdges.end()) {
664 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41665 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55666 }
667 it = outEdges.find(idAndNode.first);
668 if (it != outEdges.end()) {
669 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41670 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55671 }
672 }
673 }
674 void dump() const { print(llvm::errs()); }
675};
676
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03677// Initializes the data dependence graph by walking operations in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55678// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39679// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55680// dependence graph at a different depth.
River Riddle8c443672019-07-09 23:17:55681bool MemRefDependenceGraph::init(FuncOp f) {
Chris Lattner3f190312018-12-27 22:35:10682 DenseMap<Value *, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43683
684 // TODO: support multi-block functions.
Chris Lattner46ade282019-03-26 01:02:49685 if (f.getBlocks().size() != 1)
Chris Lattnerdffc5892018-12-29 23:33:43686 return false;
687
River Riddle99b87c92019-03-27 21:02:02688 DenseMap<Operation *, unsigned> forToNodeMap;
689 for (auto &op : f.front()) {
River Riddlec5ecf992019-05-11 22:56:50690 if (auto forOp = dyn_cast<AffineForOp>(op)) {
River Riddle5052bd82019-02-02 00:42:18691 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55692 // all loads and store accesses it contains.
693 LoopNestStateCollector collector;
River Riddle99b87c92019-03-27 21:02:02694 collector.collect(&op);
River Riddle832567b2019-03-25 17:14:34695 // Return false if a non 'affine.for' region was found (not currently
696 // supported).
River Riddle75553832019-01-29 05:23:53697 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55698 return false;
River Riddle99b87c92019-03-27 21:02:02699 Node node(nextNodeId++, &op);
Chris Lattner456ad6a2018-12-29 00:05:35700 for (auto *opInst : collector.loadOpInsts) {
701 node.loads.push_back(opInst);
Andy Davis2e1187d2019-07-03 17:35:03702 auto *memref = cast<AffineLoadOp>(opInst).getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55703 memrefAccesses[memref].insert(node.id);
704 }
Chris Lattner456ad6a2018-12-29 00:05:35705 for (auto *opInst : collector.storeOpInsts) {
706 node.stores.push_back(opInst);
Andy Davis2e1187d2019-07-03 17:35:03707 auto *memref = cast<AffineStoreOp>(opInst).getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55708 memrefAccesses[memref].insert(node.id);
709 }
River Riddle99b87c92019-03-27 21:02:02710 forToNodeMap[&op] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55711 nodes.insert({node.id, node});
Andy Davis2e1187d2019-07-03 17:35:03712 } else if (auto loadOp = dyn_cast<AffineLoadOp>(op)) {
River Riddleb4992772019-02-04 18:38:47713 // Create graph node for top-level load op.
River Riddle99b87c92019-03-27 21:02:02714 Node node(nextNodeId++, &op);
715 node.loads.push_back(&op);
Andy Davis2e1187d2019-07-03 17:35:03716 auto *memref = cast<AffineLoadOp>(op).getMemRef();
River Riddleb4992772019-02-04 18:38:47717 memrefAccesses[memref].insert(node.id);
718 nodes.insert({node.id, node});
Andy Davis2e1187d2019-07-03 17:35:03719 } else if (auto storeOp = dyn_cast<AffineStoreOp>(op)) {
River Riddleb4992772019-02-04 18:38:47720 // Create graph node for top-level store op.
River Riddle99b87c92019-03-27 21:02:02721 Node node(nextNodeId++, &op);
722 node.stores.push_back(&op);
Andy Davis2e1187d2019-07-03 17:35:03723 auto *memref = cast<AffineStoreOp>(op).getMemRef();
River Riddleb4992772019-02-04 18:38:47724 memrefAccesses[memref].insert(node.id);
725 nodes.insert({node.id, node});
River Riddle99b87c92019-03-27 21:02:02726 } else if (op.getNumRegions() != 0) {
River Riddleb4992772019-02-04 18:38:47727 // Return false if another region is found (not currently supported).
728 return false;
River Riddle99b87c92019-03-27 21:02:02729 } else if (op.getNumResults() > 0 && !op.use_empty()) {
River Riddleb4992772019-02-04 18:38:47730 // Create graph node for top-level producer of SSA values, which
731 // could be used by loop nest nodes.
River Riddle99b87c92019-03-27 21:02:02732 Node node(nextNodeId++, &op);
River Riddleb4992772019-02-04 18:38:47733 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41734 }
735 }
736
737 // Add dependence edges between nodes which produce SSA values and their
738 // users.
739 for (auto &idAndNode : nodes) {
740 const Node &node = idAndNode.second;
741 if (!node.loads.empty() || !node.stores.empty())
742 continue;
River Riddle99b87c92019-03-27 21:02:02743 auto *opInst = node.op;
MLIR Teama0f3db402019-01-29 17:36:41744 for (auto *value : opInst->getResults()) {
River Riddle8780d8d2019-05-18 18:09:07745 for (auto *user : value->getUsers()) {
Chris Lattnerd9b5bc82019-03-25 02:53:05746 SmallVector<AffineForOp, 4> loops;
River Riddle8780d8d2019-05-18 18:09:07747 getLoopIVs(*user, &loops);
MLIR Teama0f3db402019-01-29 17:36:41748 if (loops.empty())
749 continue;
River Riddlef9d91532019-03-27 00:05:09750 assert(forToNodeMap.count(loops[0].getOperation()) > 0);
751 unsigned userLoopNestId = forToNodeMap[loops[0].getOperation()];
MLIR Teama0f3db402019-01-29 17:36:41752 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55753 }
754 }
MLIR Team6892ffb2018-12-20 04:42:55755 }
756
757 // Walk memref access lists and add graph edges between dependent nodes.
758 for (auto &memrefAndList : memrefAccesses) {
759 unsigned n = memrefAndList.second.size();
760 for (unsigned i = 0; i < n; ++i) {
761 unsigned srcId = memrefAndList.second[i];
762 bool srcHasStore =
763 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
764 for (unsigned j = i + 1; j < n; ++j) {
765 unsigned dstId = memrefAndList.second[j];
766 bool dstHasStore =
767 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
768 if (srcHasStore || dstHasStore)
769 addEdge(srcId, dstId, memrefAndList.first);
770 }
771 }
772 }
773 return true;
774}
775
MLIR Team27d067e2019-01-16 17:55:02776// Removes load operations from 'srcLoads' which operate on 'memref', and
777// adds them to 'dstLoads'.
River Riddle99b87c92019-03-27 21:02:02778static void moveLoadsAccessingMemrefTo(Value *memref,
779 SmallVectorImpl<Operation *> *srcLoads,
780 SmallVectorImpl<Operation *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02781 dstLoads->clear();
River Riddle99b87c92019-03-27 21:02:02782 SmallVector<Operation *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02783 for (auto *load : *srcLoads) {
Andy Davis2e1187d2019-07-03 17:35:03784 if (cast<AffineLoadOp>(load).getMemRef() == memref)
MLIR Team27d067e2019-01-16 17:55:02785 dstLoads->push_back(load);
786 else
787 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25788 }
MLIR Team27d067e2019-01-16 17:55:02789 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25790}
791
MLIR Team27d067e2019-01-16 17:55:02792// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddle99b87c92019-03-27 21:02:02793static unsigned getInnermostCommonLoopDepth(ArrayRef<Operation *> ops) {
MLIR Team27d067e2019-01-16 17:55:02794 unsigned numOps = ops.size();
795 assert(numOps > 0);
796
Chris Lattnerd9b5bc82019-03-25 02:53:05797 std::vector<SmallVector<AffineForOp, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02798 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
799 for (unsigned i = 0; i < numOps; ++i) {
800 getLoopIVs(*ops[i], &loops[i]);
801 loopDepthLimit =
802 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25803 }
MLIR Team27d067e2019-01-16 17:55:02804
805 unsigned loopDepth = 0;
806 for (unsigned d = 0; d < loopDepthLimit; ++d) {
807 unsigned i;
808 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18809 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02810 break;
MLIR Team27d067e2019-01-16 17:55:02811 }
812 if (i != numOps)
813 break;
814 ++loopDepth;
815 }
816 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25817}
818
MLIR Teamd7c82442019-01-30 23:53:41819// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
820// and 'storeOpInsts' are satisfied.
River Riddle99b87c92019-03-27 21:02:02821static unsigned getMaxLoopDepth(ArrayRef<Operation *> loadOpInsts,
822 ArrayRef<Operation *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41823 // Merge loads and stores into the same array.
River Riddle99b87c92019-03-27 21:02:02824 SmallVector<Operation *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41825 ops.append(storeOpInsts.begin(), storeOpInsts.end());
826
827 // Compute the innermost common loop depth for loads and stores.
828 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
829
830 // Return common loop depth for loads if there are no store ops.
831 if (storeOpInsts.empty())
832 return loopDepth;
833
834 // Check dependences on all pairs of ops in 'ops' and store the minimum
835 // loop depth at which a dependence is satisfied.
836 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
837 auto *srcOpInst = ops[i];
838 MemRefAccess srcAccess(srcOpInst);
839 for (unsigned j = 0; j < e; ++j) {
840 auto *dstOpInst = ops[j];
841 MemRefAccess dstAccess(dstOpInst);
842
843 unsigned numCommonLoops =
844 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
845 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
846 FlatAffineConstraints dependenceConstraints;
847 // TODO(andydavis) Cache dependence analysis results, check cache here.
Andy Davise33e36f2019-06-10 17:50:08848 DependenceResult result = checkMemrefAccessDependence(
849 srcAccess, dstAccess, d, &dependenceConstraints,
850 /*dependenceComponents=*/nullptr);
851 if (hasDependence(result)) {
MLIR Teamd7c82442019-01-30 23:53:41852 // Store minimum loop depth and break because we want the min 'd' at
853 // which there is a dependence.
854 loopDepth = std::min(loopDepth, d - 1);
855 break;
856 }
857 }
858 }
859 }
860 return loopDepth;
861}
862
MLIR Team8f5f2c72019-02-15 17:32:18863// Sinks all sequential loops to the innermost levels (while preserving
864// relative order among them) and moves all parallel loops to the
865// outermost (while again preserving relative order among them).
866// This can increase the loop depth at which we can fuse a slice, since we are
867// pushing loop carried dependence to a greater depth in the loop nest.
868static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
River Riddled5b60ee82019-05-12 01:59:54869 assert(isa<AffineForOp>(node->op));
Andy Davis90d40232019-05-13 13:57:56870 AffineForOp newRootForOp = sinkSequentialLoops(cast<AffineForOp>(node->op));
871 node->op = newRootForOp.getOperation();
MLIR Team8f5f2c72019-02-15 17:32:18872}
873
Uday Bondhugula8be26272019-02-02 01:06:22874// TODO(mlir-team): improve/complete this when we have target data.
875unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
876 auto elementType = memRefType.getElementType();
877
878 unsigned sizeInBits;
879 if (elementType.isIntOrFloat()) {
880 sizeInBits = elementType.getIntOrFloatBitWidth();
881 } else {
882 auto vectorType = elementType.cast<VectorType>();
883 sizeInBits =
884 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
885 }
886 return llvm::divideCeil(sizeInBits, 8);
887}
888
MLIR Teamc4237ae2019-01-18 16:56:27889// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:18890// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:52891// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
892// TODO(bondhugula): consider refactoring the common code from generateDma and
893// this one.
River Riddle99b87c92019-03-27 21:02:02894static Value *createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst,
Uday Bondhugula8be26272019-02-02 01:06:22895 unsigned dstLoopDepth,
896 Optional<unsigned> fastMemorySpace,
Uday Bondhugulad4b3ff12019-02-27 00:10:19897 uint64_t localBufSizeThreshold) {
River Riddlef9d91532019-03-27 00:05:09898 auto *forInst = forOp.getOperation();
River Riddle5052bd82019-02-02 00:42:18899
900 // Create builder to insert alloc op just before 'forOp'.
River Riddlef1b848e2019-06-05 02:18:23901 OpBuilder b(forInst);
MLIR Teamc4237ae2019-01-18 16:56:27902 // Builder to create constants at the top level.
River Riddlece502af2019-07-08 18:20:26903 OpBuilder top(forInst->getParentOfType<FuncOp>().getBody());
MLIR Teamc4237ae2019-01-18 16:56:27904 // Create new memref type based on slice bounds.
Andy Davis2e1187d2019-07-03 17:35:03905 auto *oldMemRef = cast<AffineStoreOp>(srcStoreOpInst).getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:27906 auto oldMemRefType = oldMemRef->getType().cast<MemRefType>();
907 unsigned rank = oldMemRefType.getRank();
908
Uday Bondhugula94a03f82019-01-22 21:58:52909 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:44910 MemRefRegion region(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:47911 bool validRegion = succeeded(region.compute(srcStoreOpInst, dstLoopDepth));
MLIR Teamd42ef782019-03-04 19:01:25912 (void)validRegion;
913 assert(validRegion && "unexpected memref region failure");
River Riddle6859f332019-01-23 22:39:45914 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:27915 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:52916 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:27917 lbs.reserve(rank);
918 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:52919 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:27920 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:44921 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:22922 assert(numElements.hasValue() &&
923 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:27924
Uday Bondhugula0f504142019-02-04 21:48:44925 const FlatAffineConstraints *cst = region.getConstraints();
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03926 // 'outerIVs' holds the values that this memory region is symbolic/parametric
Uday Bondhugula94a03f82019-01-22 21:58:52927 // on; this would correspond to loop IVs surrounding the level at which the
928 // slice is being materialized.
929 SmallVector<Value *, 8> outerIVs;
930 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
931
932 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:27933 SmallVector<AffineExpr, 4> offsets;
934 offsets.reserve(rank);
935 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:52936 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
937
MLIR Teamc4237ae2019-01-18 16:56:27938 AffineExpr offset = top.getAffineConstantExpr(0);
939 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
940 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
941 }
Uday Bondhugula94a03f82019-01-22 21:58:52942 assert(lbDivisors[d] > 0);
943 offset =
944 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:27945 offsets.push_back(offset);
946 }
947
948 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
949 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:22950 uint64_t bufSize =
951 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
952 unsigned newMemSpace;
Uday Bondhugulad4b3ff12019-02-27 00:10:19953 if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
Uday Bondhugula8be26272019-02-02 01:06:22954 newMemSpace = fastMemorySpace.getValue();
955 } else {
956 newMemSpace = oldMemRefType.getMemorySpace();
957 }
River Riddle2acc2202019-10-18 03:08:01958 auto newMemRefType = MemRefType::get(newShape, oldMemRefType.getElementType(),
959 {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:27960 // Gather alloc operands for the dynamic dimensions of the memref.
961 SmallVector<Value *, 4> allocOperands;
962 unsigned dynamicDimCount = 0;
963 for (auto dimSize : oldMemRefType.getShape()) {
964 if (dimSize == -1)
965 allocOperands.push_back(
River Riddleaf1abcc2019-03-25 18:13:31966 top.create<DimOp>(forOp.getLoc(), oldMemRef, dynamicDimCount++));
MLIR Teamc4237ae2019-01-18 16:56:27967 }
968
River Riddle5052bd82019-02-02 00:42:18969 // Create new private memref for fused loop 'forOp'.
MLIR Teama0f3db402019-01-29 17:36:41970 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
971 // consumer loop nests to reduce their live range. Currently they are added
972 // at the beginning of the function, because loop nests can be reordered
973 // during the fusion pass.
MLIR Teamc4237ae2019-01-18 16:56:27974 Value *newMemRef =
River Riddleaf1abcc2019-03-25 18:13:31975 top.create<AllocOp>(forOp.getLoc(), newMemRefType, allocOperands);
MLIR Teamc4237ae2019-01-18 16:56:27976
977 // Build an AffineMap to remap access functions based on lower bound offsets.
978 SmallVector<AffineExpr, 4> remapExprs;
979 remapExprs.reserve(rank);
980 unsigned zeroOffsetCount = 0;
981 for (unsigned i = 0; i < rank; i++) {
982 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
983 if (constExpr.getValue() == 0)
984 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:52985 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
986
987 auto remapExpr =
988 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
989 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:27990 }
MLIR Team5a91b982019-05-29 21:56:41991 auto indexRemap = zeroOffsetCount == rank
992 ? AffineMap()
River Riddle2acc2202019-10-18 03:08:01993 : AffineMap::get(outerIVs.size() + rank, 0, remapExprs);
MLIR Teamc4237ae2019-01-18 16:56:27994 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugulaaa2cee92019-08-28 00:56:25995 LogicalResult res =
Uday Bondhugula94a03f82019-01-22 21:58:52996 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
997 /*extraOperands=*/outerIVs,
Uday Bondhugula727a50a2019-09-18 18:25:33998 /*symbolOperands=*/{},
River Riddleaf1abcc2019-03-25 18:13:31999 /*domInstFilter=*/&*forOp.getBody()->begin());
Uday Bondhugulaaa2cee92019-08-28 00:56:251000 assert(succeeded(res) &&
1001 "replaceAllMemrefUsesWith should always succeed here");
1002 (void)res;
MLIR Teamc4237ae2019-01-18 16:56:271003 return newMemRef;
1004}
1005
Diego Caballero34510552019-10-09 17:36:541006// Checks if node 'srcId' can be safely fused into node 'dstId'. Node 'srcId'
1007// may write to multiple memrefs but it is required that only one of them,
Diego Caballero330d1ff2019-12-03 14:09:211008// 'srcLiveOutStoreOp', has output edges.
Diego Caballero34510552019-10-09 17:36:541009// Returns true if 'dstNode's read/write region to 'memref' is a super set of
Diego Caballero330d1ff2019-12-03 14:09:211010// 'srcNode's write region to 'memref' and 'srcId' has only one output edge.
MLIR Team58aa3832019-02-16 01:12:191011// TODO(andydavis) Generalize this to handle more live in/out cases.
1012static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
Diego Caballero34510552019-10-09 17:36:541013 AffineStoreOp srcLiveOutStoreOp,
MLIR Team58aa3832019-02-16 01:12:191014 MemRefDependenceGraph *mdg) {
Diego Caballero34510552019-10-09 17:36:541015 assert(srcLiveOutStoreOp && "Expected a valid store op");
MLIR Team58aa3832019-02-16 01:12:191016 auto *dstNode = mdg->getNode(dstId);
Diego Caballero34510552019-10-09 17:36:541017 Value *memref = srcLiveOutStoreOp.getMemRef();
Diego Caballero330d1ff2019-12-03 14:09:211018 // Return false if 'srcNode' has more than one output edge on 'memref'.
1019 if (mdg->getOutEdgeCount(srcId, memref) > 1)
1020 return false;
MLIR Team58aa3832019-02-16 01:12:191021
Diego Caballero34510552019-10-09 17:36:541022 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOp' on 'memref'.
1023 MemRefRegion srcWriteRegion(srcLiveOutStoreOp.getLoc());
1024 if (failed(srcWriteRegion.compute(srcLiveOutStoreOp, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251025 LLVM_DEBUG(llvm::dbgs()
1026 << "Unable to compute MemRefRegion for source operation\n.");
1027 return false;
1028 }
MLIR Team58aa3832019-02-16 01:12:191029 SmallVector<int64_t, 4> srcShape;
1030 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
Diego Caballero34510552019-10-09 17:36:541031 // by 'srcStoreOp' at depth 'dstLoopDepth'.
MLIR Team58aa3832019-02-16 01:12:191032 Optional<int64_t> srcNumElements =
1033 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1034 if (!srcNumElements.hasValue())
1035 return false;
1036
Andy Davis7c1fc9e2019-04-02 13:37:401037 // Compute MemRefRegion 'dstRegion' for 'dstStore/LoadOpInst' on 'memref'.
MLIR Team9d9675f2019-03-28 21:54:491038 // TODO(andydavis) Compute 'unionboundingbox' of all write regions (one for
1039 // each store op in 'dstStoreOps').
Andy Davis7c1fc9e2019-04-02 13:37:401040 SmallVector<Operation *, 2> dstStoreOps;
1041 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1042 SmallVector<Operation *, 2> dstLoadOps;
1043 dstNode->getLoadOpsForMemref(memref, &dstLoadOps);
1044
1045 auto *dstOpInst = dstStoreOps.empty() ? dstLoadOps[0] : dstStoreOps[0];
1046 MemRefRegion dstRegion(dstOpInst->getLoc());
1047 if (failed(dstRegion.compute(dstOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251048 LLVM_DEBUG(llvm::dbgs()
1049 << "Unable to compute MemRefRegion for dest operation\n.");
1050 return false;
1051 }
MLIR Team58aa3832019-02-16 01:12:191052 SmallVector<int64_t, 4> dstShape;
Andy Davis7c1fc9e2019-04-02 13:37:401053 // Query 'dstRegion' for 'dstShape' and 'dstNumElements'.
1054 // by 'dstOpInst' at depth 'dstLoopDepth'.
MLIR Team58aa3832019-02-16 01:12:191055 Optional<int64_t> dstNumElements =
Andy Davis7c1fc9e2019-04-02 13:37:401056 dstRegion.getConstantBoundingSizeAndShape(&dstShape);
MLIR Team58aa3832019-02-16 01:12:191057 if (!dstNumElements.hasValue())
1058 return false;
1059
1060 // Return false if write region is not a superset of 'srcNodes' write
1061 // region to 'memref'.
1062 // TODO(andydavis) Check the shape and lower bounds here too.
1063 if (srcNumElements != dstNumElements)
1064 return false;
1065 return true;
1066}
1067
MLIR Team27d067e2019-01-16 17:55:021068// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411069// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
MLIR Teamd038e342019-03-01 19:50:251070// The argument 'srcStoreOpInst' is used to calculate the storage reduction on
1071// the memref being produced and consumed, which is an input to the cost model.
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031072// For producer-consumer fusion, 'srcStoreOpInst' will be the same as
MLIR Teamd038e342019-03-01 19:50:251073// 'srcOpInst', as we are slicing w.r.t to that producer.
1074// For input-reuse fusion, 'srcOpInst' will be the src loop nest LoadOp which
1075// reads from the same memref as dst loop nest load ops, and 'srcStoreOpInst'
1076// will be the unique store op in the src node, which will be used to check
1077// that the write region is the same after input-reuse fusion.
Uday Bondhugulab4a14432019-01-26 00:00:501078// Returns true if it is profitable to fuse the candidate loop nests. Returns
1079// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1080// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251081// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021082// *) Computes the backward computation slice at 'srcOpInst'. This
1083// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251084// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021085// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251086// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1087// loop nest is the total number of dynamic operation instances in the loop
1088// nest).
1089// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021090// loop nest at various values of dst loop depth, attempting to fuse
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031091// the largest computation slice at the maximal dst loop depth (closest to
1092// the load) to minimize reuse distance and potentially enable subsequent
MLIR Team27d067e2019-01-16 17:55:021093// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411094// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021095// the same memref as is written by 'srcOpInst', then the union of slice
1096// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501097// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251098// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021099// NOTE: We attempt to maximize the dst loop depth, but there are cases
1100// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251101// loop (within the src computation slice) at a depth which results in
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031102// excessive recomputation (see unit tests for examples).
MLIR Team38c2fe32019-01-14 19:26:251103// *) Compares the total cost of the unfused loop nests to the min cost fused
1104// loop nest computed in the previous step, and returns true if the latter
1105// is lower.
River Riddle99b87c92019-03-27 21:02:021106static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
1107 ArrayRef<Operation *> dstLoadOpInsts,
1108 ArrayRef<Operation *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251109 ComputationSliceState *sliceState,
Uday Bondhugulace7e59532019-03-08 17:21:521110 unsigned *dstLoopDepth, bool maximalFusion) {
Uday Bondhugula06d21d92019-01-25 01:01:491111 LLVM_DEBUG({
1112 llvm::dbgs() << "Checking whether fusion is profitable between:\n";
Uday Bondhugulaa1dad3a2019-02-20 02:17:191113 llvm::dbgs() << " " << *srcOpInst << " and \n";
MLIR Teamd7c82442019-01-30 23:53:411114 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191115 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491116 };
1117 });
Uday Bondhugula864d9e02019-01-23 17:16:241118
MLIR Team38c2fe32019-01-14 19:26:251119 // Compute cost of sliced and unsliced src loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051120 SmallVector<AffineForOp, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021121 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251122 unsigned numSrcLoopIVs = srcLoopIVs.size();
1123
1124 // Walk src loop nest and collect stats.
1125 LoopNestStats srcLoopNestStats;
Andy Davis59b68142019-06-18 15:52:091126 if (!getLoopNestStats(srcLoopIVs[0], &srcLoopNestStats))
MLIR Team38c2fe32019-01-14 19:26:251127 return false;
Andy Davis59b68142019-06-18 15:52:091128
MLIR Team38c2fe32019-01-14 19:26:251129 // Compute cost of dst loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051130 SmallVector<AffineForOp, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411131 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251132
1133 LoopNestStats dstLoopNestStats;
Andy Davis59b68142019-06-18 15:52:091134 if (!getLoopNestStats(dstLoopIVs[0], &dstLoopNestStats))
MLIR Team38c2fe32019-01-14 19:26:251135 return false;
1136
MLIR Teamd7c82442019-01-30 23:53:411137 // Compute the maximum loop depth at which we can can insert the src slice
MLIR Teamd038e342019-03-01 19:50:251138 // and still satisfy dest loop nest dependences, for producer-consumer fusion.
1139 unsigned maxDstLoopDepth =
1140 (srcOpInst == srcStoreOpInst)
1141 ? getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts)
1142 : dstLoopIVs.size();
MLIR Teamc1ff9e82019-03-06 04:33:301143 if (maxDstLoopDepth == 0) {
1144 LLVM_DEBUG(llvm::dbgs() << "Can't fuse: maxDstLoopDepth == 0 .\n");
MLIR Team27d067e2019-01-16 17:55:021145 return false;
MLIR Teamc1ff9e82019-03-06 04:33:301146 }
MLIR Team27d067e2019-01-16 17:55:021147
1148 // Search for min cost value for 'dstLoopDepth'. At each value of
1149 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1150 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1151 // of these bounds). Next the union slice bounds are used to calculate
1152 // the cost of the slice and the cost of the slice inserted into the dst
1153 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241154 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
MLIR Teamd038e342019-03-01 19:50:251155 double maxStorageReduction = 0.0;
Uday Bondhugula864d9e02019-01-23 17:16:241156 Optional<uint64_t> sliceMemEstimate = None;
1157
MLIR Team27d067e2019-01-16 17:55:021158 SmallVector<ComputationSliceState, 4> sliceStates;
1159 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241160 // The best loop depth at which to materialize the slice.
1161 Optional<unsigned> bestDstLoopDepth = None;
1162
1163 // Compute op instance count for the src loop nest without iteration slicing.
Andy Davis59b68142019-06-18 15:52:091164 uint64_t srcLoopNestCost = getComputeCost(srcLoopIVs[0], srcLoopNestStats);
Uday Bondhugula864d9e02019-01-23 17:16:241165
MLIR Teamb9dde912019-02-06 19:01:101166 // Compute src loop nest write region size.
MLIR Teamd038e342019-03-01 19:50:251167 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471168 if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251169 LLVM_DEBUG(llvm::dbgs()
River Riddle99b87c92019-03-27 21:02:021170 << "Unable to compute MemRefRegion for source operation\n.");
MLIR Teamd42ef782019-03-04 19:01:251171 return false;
1172 }
1173
MLIR Teamb9dde912019-02-06 19:01:101174 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1175 srcWriteRegion.getRegionSize();
1176 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1177 return false;
1178 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1179
Uday Bondhugula864d9e02019-01-23 17:16:241180 // Compute op instance count for the src loop nest.
Andy Davis59b68142019-06-18 15:52:091181 uint64_t dstLoopNestCost = getComputeCost(dstLoopIVs[0], dstLoopNestStats);
MLIR Team27d067e2019-01-16 17:55:021182
MLIR Teamb9dde912019-02-06 19:01:101183 // Evaluate all depth choices for materializing the slice in the destination
1184 // loop nest.
MLIR Team27d067e2019-01-16 17:55:021185 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
MLIR Teamc1ff9e82019-03-06 04:33:301186 // Compute the union of slice bounds of all ops in 'dstLoadOpInsts'.
Andy Davis1de0f972019-05-29 21:02:141187 if (failed(mlir::computeSliceUnion({srcOpInst}, dstLoadOpInsts,
Andy Davis898cf0e2019-06-17 16:59:351188 /*loopDepth=*/i,
1189 /*numCommonLoops=*/0,
1190 /*isBackwardSlice=*/true,
Andy Davis1de0f972019-05-29 21:02:141191 &sliceStates[i - 1]))) {
MLIR Teamc1ff9e82019-03-06 04:33:301192 LLVM_DEBUG(llvm::dbgs()
Andy Davis1de0f972019-05-29 21:02:141193 << "computeSliceUnion failed for loopDepth: " << i << "\n");
MLIR Teamc1ff9e82019-03-06 04:33:301194 continue;
MLIR Team38c2fe32019-01-14 19:26:251195 }
MLIR Teamc1ff9e82019-03-06 04:33:301196
Andy Davis59b68142019-06-18 15:52:091197 int64_t fusedLoopNestComputeCost;
1198 if (!getFusionComputeCost(srcLoopIVs[0], srcLoopNestStats, dstLoopIVs[0],
1199 dstLoopNestStats, &sliceStates[i - 1],
1200 &fusedLoopNestComputeCost)) {
1201 LLVM_DEBUG(llvm::dbgs() << "Unable to compute fusion compute cost.\n.");
Uday Bondhugula864d9e02019-01-23 17:16:241202 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301203 }
Uday Bondhugula864d9e02019-01-23 17:16:241204
Uday Bondhugula864d9e02019-01-23 17:16:241205 double additionalComputeFraction =
1206 fusedLoopNestComputeCost /
1207 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1208 1;
1209
Amit Sabne70a416d2019-04-09 16:17:401210 // Determine what the slice write MemRefRegion would be, if the src loop
MLIR Teamb9dde912019-02-06 19:01:101211 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1212 // nest at loop depth 'i'
MLIR Teamd038e342019-03-01 19:50:251213 MemRefRegion sliceWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471214 if (failed(sliceWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0,
1215 &sliceStates[i - 1]))) {
MLIR Teamc1ff9e82019-03-06 04:33:301216 LLVM_DEBUG(llvm::dbgs()
1217 << "Failed to compute slice write region at loopDepth: " << i
1218 << "\n");
MLIR Teamd42ef782019-03-04 19:01:251219 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301220 }
MLIR Teamd42ef782019-03-04 19:01:251221
MLIR Teamb9dde912019-02-06 19:01:101222 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1223 sliceWriteRegion.getRegionSize();
1224 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
MLIR Teamc1ff9e82019-03-06 04:33:301225 maybeSliceWriteRegionSizeBytes.getValue() == 0) {
1226 LLVM_DEBUG(llvm::dbgs()
1227 << "Failed to get slice write region size at loopDepth: " << i
1228 << "\n");
MLIR Teamb9dde912019-02-06 19:01:101229 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301230 }
MLIR Teamb9dde912019-02-06 19:01:101231 int64_t sliceWriteRegionSizeBytes =
1232 maybeSliceWriteRegionSizeBytes.getValue();
1233
MLIR Teamd038e342019-03-01 19:50:251234 // If we are fusing for reuse, check that write regions remain the same.
1235 // TODO(andydavis) Write region check should check sizes and offsets in
1236 // each dimension, so that we are sure they are covering the same memref
1237 // region. Also, move this out to a isMemRefRegionSuperSet helper function.
1238 if (srcOpInst != srcStoreOpInst &&
1239 sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes)
1240 continue;
1241
MLIR Teamb9dde912019-02-06 19:01:101242 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1243 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241244
Uday Bondhugula06d21d92019-01-25 01:01:491245 LLVM_DEBUG({
1246 std::stringstream msg;
1247 msg << " evaluating fusion profitability at depth : " << i << "\n"
Uday Bondhugulad4b3ff12019-02-27 00:10:191248 << std::fixed << std::setprecision(2)
1249 << " additional compute fraction: "
Uday Bondhugula06d21d92019-01-25 01:01:491250 << 100.0 * additionalComputeFraction << "%\n"
1251 << " storage reduction factor: " << storageReduction << "x\n"
1252 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191253 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1254 << " slice write region size: " << sliceWriteRegionSizeBytes
1255 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491256 llvm::dbgs() << msg.str();
1257 });
Uday Bondhugula864d9e02019-01-23 17:16:241258
1259 double computeToleranceThreshold =
1260 clFusionAddlComputeTolerance.getNumOccurrences() > 0
1261 ? clFusionAddlComputeTolerance
1262 : LoopFusion::kComputeToleranceThreshold;
1263
1264 // TODO(b/123247369): This is a placeholder cost model.
1265 // Among all choices that add an acceptable amount of redundant computation
1266 // (as per computeToleranceThreshold), we will simply pick the one that
1267 // reduces the intermediary size the most.
1268 if ((storageReduction > maxStorageReduction) &&
Uday Bondhugulace7e59532019-03-08 17:21:521269 (maximalFusion ||
Uday Bondhugula864d9e02019-01-23 17:16:241270 (additionalComputeFraction < computeToleranceThreshold))) {
1271 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021272 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241273 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101274 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251275 }
1276 }
1277
Uday Bondhugula864d9e02019-01-23 17:16:241278 // A simple cost model: fuse if it reduces the memory footprint. If
1279 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251280
Uday Bondhugulace7e59532019-03-08 17:21:521281 if (!maximalFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191282 LLVM_DEBUG(
1283 llvm::dbgs()
1284 << "All fusion choices involve more than the threshold amount of "
1285 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251286 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241287 }
1288
MLIR Teamd42ef782019-03-04 19:01:251289 if (!bestDstLoopDepth.hasValue()) {
1290 LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n");
1291 return false;
1292 }
Uday Bondhugula864d9e02019-01-23 17:16:241293
1294 // Set dstLoopDepth based on best values from search.
1295 *dstLoopDepth = bestDstLoopDepth.getValue();
1296
1297 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491298 llvm::dbgs() << " LoopFusion fusion stats:"
1299 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241300 << "\n src loop nest compute cost: " << srcLoopNestCost
1301 << "\n dst loop nest compute cost: " << dstLoopNestCost
1302 << "\n fused loop nest compute cost: "
1303 << minFusedLoopNestComputeCost << "\n");
1304
River Riddle5052bd82019-02-02 00:42:181305 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1306 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241307
1308 Optional<double> storageReduction = None;
1309
Uday Bondhugulace7e59532019-03-08 17:21:521310 if (!maximalFusion) {
Uday Bondhugula864d9e02019-01-23 17:16:241311 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1312 LLVM_DEBUG(
1313 llvm::dbgs()
1314 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1315 return false;
1316 }
1317
1318 auto srcMemSizeVal = srcMemSize.getValue();
1319 auto dstMemSizeVal = dstMemSize.getValue();
1320
1321 assert(sliceMemEstimate.hasValue() && "expected value");
Uday Bondhugula864d9e02019-01-23 17:16:241322 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1323
1324 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1325 << " dst mem: " << dstMemSizeVal << "\n"
1326 << " fused mem: " << fusedMem << "\n"
1327 << " slice mem: " << sliceMemEstimate << "\n");
1328
Jacques Pienaar2fe8ae42019-05-04 02:48:571329 if (static_cast<long>(fusedMem) > srcMemSizeVal + dstMemSizeVal) {
Uday Bondhugula864d9e02019-01-23 17:16:241330 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1331 return false;
1332 }
1333 storageReduction =
1334 100.0 *
1335 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1336 }
1337
1338 double additionalComputeFraction =
1339 100.0 * (minFusedLoopNestComputeCost /
1340 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1341 1);
MLIR Team5c5739d2019-01-25 06:27:401342 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491343 LLVM_DEBUG({
1344 std::stringstream msg;
1345 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591346 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491347 << "% redundant computation and a ";
1348 msg << (storageReduction.hasValue()
1349 ? std::to_string(storageReduction.getValue())
1350 : "<unknown>");
1351 msg << "% storage reduction.\n";
1352 llvm::dbgs() << msg.str();
1353 });
Uday Bondhugula864d9e02019-01-23 17:16:241354
MLIR Team27d067e2019-01-16 17:55:021355 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241356 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021357 sliceState->lbs = bestSliceState->lbs;
1358 sliceState->ubs = bestSliceState->ubs;
1359 sliceState->lbOperands = bestSliceState->lbOperands;
1360 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241361
MLIR Team27d067e2019-01-16 17:55:021362 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251363 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171364 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021365 canonicalizeMapAndOperands(&sliceState->lbs[i],
1366 &sliceState->lbOperands[i]);
1367 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171368 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021369 canonicalizeMapAndOperands(&sliceState->ubs[i],
1370 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251371 }
1372 }
1373 return true;
1374}
1375
MLIR Teamd038e342019-03-01 19:50:251376// GreedyFusion greedily fuses loop nests which have a producer/consumer or
1377// input-reuse relationship on a memref, with the goal of improving locality.
MLIR Teamf28e4df2018-11-01 14:26:001378//
MLIR Teamd038e342019-03-01 19:50:251379// The steps of the producer-consumer fusion algorithm are as follows:
MLIR Team3b692302018-12-17 17:57:141380//
MLIR Team6892ffb2018-12-20 04:42:551381// *) A worklist is initialized with node ids from the dependence graph.
1382// *) For each node id in the worklist:
Amit Sabne70a416d2019-04-09 16:17:401383// *) Pop an AffineForOp of the worklist. This 'dstAffineForOp' will be a
River Riddle5052bd82019-02-02 00:42:181384// candidate destination AffineForOp into which fusion will be attempted.
1385// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141386// *) For each LoadOp in 'dstLoadOps' do:
Amit Sabne70a416d2019-04-09 16:17:401387// *) Look up dependent loop nests which have a single store op to the same
MLIR Teamd038e342019-03-01 19:50:251388// memref.
1389// *) Check if dependences would be violated by the fusion.
MLIR Team6892ffb2018-12-20 04:42:551390// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141391// bounds to be functions of 'dstLoopNest' IVs and symbols.
1392// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
MLIR Teamd038e342019-03-01 19:50:251393// at a loop depth determined by the cost model in 'isFusionProfitable'.
River Riddle99b87c92019-03-27 21:02:021394// *) Add the newly fused load/store operations to the state,
Amit Sabne70a416d2019-04-09 16:17:401395// and also add newly fused load ops to 'dstLoopOps' to be considered
MLIR Team3b692302018-12-17 17:57:141396// as fusion dst load ops in another iteration.
1397// *) Remove old src loop nest and its associated state.
1398//
MLIR Teamd038e342019-03-01 19:50:251399// The steps of the input-reuse fusion algorithm are as follows:
1400//
1401// *) Initialize 'worklist' with node ids from the dependence graph.
1402// *) For each 'dstNode' in the worklist:
1403// *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which
1404// loads from the same memref, but which has no dependence paths to/from.
1405// *) Get a computation slice of 'sibLoopNest', which adjusts its loop
1406// bounds to be functions of 'dstLoopNest' IVs and symbols.
1407// *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest',
1408// at a loop depth determined by the cost model in 'isFusionProfitable'.
1409// This function also checks that the memref write region of 'sibLoopNest',
1410// is preserved in the fused loop nest.
1411// *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'.
1412//
River Riddle99b87c92019-03-27 21:02:021413// Given a graph where top-level operations are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141414// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551415// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141416//
MLIR Team6892ffb2018-12-20 04:42:551417// This greedy algorithm is not 'maximal' due to the current restriction of
1418// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141419//
1420// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551421struct GreedyFusion {
1422public:
MLIR Teamd038e342019-03-01 19:50:251423 // The data dependence graph to traverse during fusion.
MLIR Team6892ffb2018-12-20 04:42:551424 MemRefDependenceGraph *mdg;
MLIR Teamd038e342019-03-01 19:50:251425 // Worklist of graph nodes visited during the fusion pass.
MLIR Teama78edcd2019-02-05 14:57:081426 SmallVector<unsigned, 8> worklist;
MLIR Teamd038e342019-03-01 19:50:251427 // Set of graph nodes which are present on the worklist.
MLIR Teama78edcd2019-02-05 14:57:081428 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamd038e342019-03-01 19:50:251429 // Parameter for local buffer size threshold.
1430 unsigned localBufSizeThreshold;
1431 // Parameter for fast memory space.
1432 Optional<unsigned> fastMemorySpace;
Uday Bondhugulace7e59532019-03-08 17:21:521433 // If true, ignore any additional (redundant) computation tolerance threshold
1434 // that would have prevented fusion.
1435 bool maximalFusion;
MLIR Teamf28e4df2018-11-01 14:26:001436
MLIR Teamd038e342019-03-01 19:50:251437 using Node = MemRefDependenceGraph::Node;
1438
1439 GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold,
Uday Bondhugulace7e59532019-03-08 17:21:521440 Optional<unsigned> fastMemorySpace, bool maximalFusion)
MLIR Teamd038e342019-03-01 19:50:251441 : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold),
Uday Bondhugulace7e59532019-03-08 17:21:521442 fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion) {}
MLIR Teamd038e342019-03-01 19:50:251443
1444 // Initializes 'worklist' with nodes from 'mdg'
1445 void init() {
MLIR Teama78edcd2019-02-05 14:57:081446 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1447 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Teamd038e342019-03-01 19:50:251448 worklist.clear();
1449 worklistSet.clear();
1450 for (auto &idAndNode : mdg->nodes) {
1451 const Node &node = idAndNode.second;
1452 worklist.push_back(node.id);
1453 worklistSet.insert(node.id);
1454 }
MLIR Team6892ffb2018-12-20 04:42:551455 }
MLIR Team3b692302018-12-17 17:57:141456
MLIR Teamd038e342019-03-01 19:50:251457 // Run the GreedyFusion pass.
1458 // *) First pass through the nodes fuses single-use producer nodes into their
1459 // unique consumer.
1460 // *) Second pass fuses sibling nodes which share no dependence edges.
1461 // *) Third pass fuses any remaining producer nodes into their users.
1462 void run() {
MLIR Teamc1ff9e82019-03-06 04:33:301463 // TODO(andydavis) Run this repeatedly until a fixed-point is reached.
MLIR Teamd038e342019-03-01 19:50:251464 fuseProducerConsumerNodes(/*maxSrcUserCount=*/1);
1465 fuseSiblingNodes();
1466 fuseProducerConsumerNodes(
1467 /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max());
1468 eraseUnusedMemRefAllocations();
1469 }
1470
1471 void fuseProducerConsumerNodes(unsigned maxSrcUserCount) {
1472 init();
MLIR Team3b692302018-12-17 17:57:141473 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551474 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141475 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081476 worklistSet.erase(dstId);
1477
MLIR Team6892ffb2018-12-20 04:42:551478 // Skip if this node was removed (fused into another node).
1479 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141480 continue;
MLIR Team6892ffb2018-12-20 04:42:551481 // Get 'dstNode' into which to attempt fusion.
1482 auto *dstNode = mdg->getNode(dstId);
1483 // Skip if 'dstNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541484 if (!isa<AffineForOp>(dstNode->op))
MLIR Team3b692302018-12-17 17:57:141485 continue;
MLIR Team8f5f2c72019-02-15 17:32:181486 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1487 // while preserving relative order. This can increase the maximum loop
1488 // depth at which we can fuse a slice of a producer loop nest into a
1489 // consumer loop nest.
1490 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141491
River Riddle99b87c92019-03-27 21:02:021492 SmallVector<Operation *, 4> loads = dstNode->loads;
1493 SmallVector<Operation *, 4> dstLoadOpInsts;
MLIR Teamc4237ae2019-01-18 16:56:271494 DenseSet<Value *> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551495 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021496 // Get memref of load on top of the stack.
Andy Davis2e1187d2019-07-03 17:35:031497 auto *memref = cast<AffineLoadOp>(loads.back()).getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271498 if (visitedMemrefs.count(memref) > 0)
1499 continue;
1500 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021501 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1502 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551503 // Skip if no input edges along which to fuse.
1504 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141505 continue;
Amit Sabne70a416d2019-04-09 16:17:401506 // Iterate through in-edges for 'dstId' and src node id for any
MLIR Team1e851912019-01-31 00:01:461507 // edges on 'memref'.
1508 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551509 for (auto &srcEdge : mdg->inEdges[dstId]) {
1510 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411511 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551512 continue;
MLIR Team1e851912019-01-31 00:01:461513 srcNodeIds.push_back(srcEdge.id);
1514 }
1515 for (unsigned srcId : srcNodeIds) {
1516 // Skip if this node was removed (fused into another node).
1517 if (mdg->nodes.count(srcId) == 0)
1518 continue;
1519 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1520 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551521 // Skip if 'srcNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541522 if (!isa<AffineForOp>(srcNode->op))
MLIR Team6892ffb2018-12-20 04:42:551523 continue;
Diego Caballero34510552019-10-09 17:36:541524 // Skip if 'srcNode' has more than one live-out store to a
1525 // function-local memref.
1526 // TODO(andydavis) Support more generic multi-output src loop nests
1527 // fusion.
1528 auto srcStoreOp = mdg->getUniqueOutgoingStore(srcNode);
Andy Davis68a8da42019-11-18 19:20:031529 if (!srcStoreOp) {
1530 // Get the src store op at the deepest loop depth.
1531 // We will use 'LoopFusionUtils::canFuseLoops' to check fusion
1532 // feasibility for loops with multiple stores.
1533 unsigned maxLoopDepth = 0;
1534 for (auto *op : srcNode->stores) {
1535 auto storeOp = cast<AffineStoreOp>(op);
1536 if (storeOp.getMemRef() != memref) {
1537 srcStoreOp = nullptr;
1538 break;
1539 }
1540 unsigned loopDepth = getNestingDepth(*storeOp);
1541 if (loopDepth > maxLoopDepth) {
1542 maxLoopDepth = loopDepth;
1543 srcStoreOp = storeOp;
1544 }
1545 }
1546 if (!srcStoreOp)
1547 continue;
1548 }
1549
Diego Caballero34510552019-10-09 17:36:541550 // Unique outgoing store found must write to 'memref' since 'memref'
1551 // is the one that established the producer-consumer relationship
1552 // between 'srcNode' and 'dstNode'.
1553 assert(srcStoreOp.getMemRef() == memref &&
1554 "Found store to unexpected memref");
Uday Bondhugula864d9e02019-01-23 17:16:241555
MLIR Team58aa3832019-02-16 01:12:191556 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1557 // and cannot be fused.
1558 bool writesToLiveInOrOut =
1559 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1560 if (writesToLiveInOrOut &&
Diego Caballero34510552019-10-09 17:36:541561 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, srcStoreOp, mdg))
MLIR Teamd7c82442019-01-30 23:53:411562 continue;
1563
Kazuaki Ishizaki84a61822019-12-06 13:58:591564 // Don't create a private memref if 'writesToLiveInOrOut'.
Andy Davis68a8da42019-11-18 19:20:031565 bool createPrivateMemref = !writesToLiveInOrOut;
Kazuaki Ishizaki84a61822019-12-06 13:58:591566 // Don't create a private memref if 'srcNode' has in edges on
1567 // 'memref', or if 'dstNode' has out edges on 'memref'.
Andy Davis68a8da42019-11-18 19:20:031568 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) > 0 ||
1569 mdg->getOutEdgeCount(dstNode->id, memref) > 0) {
1570 createPrivateMemref = false;
1571 }
1572
MLIR Teamd038e342019-03-01 19:50:251573 // Skip if 'srcNode' out edge count on 'memref' > 'maxSrcUserCount'.
1574 if (mdg->getOutEdgeCount(srcNode->id, memref) > maxSrcUserCount)
1575 continue;
1576
River Riddle99b87c92019-03-27 21:02:021577 // Compute an operation list insertion point for the fused loop
MLIR Teama0f3db402019-01-29 17:36:411578 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:021579 Operation *insertPointInst =
MLIR Teama78edcd2019-02-05 14:57:081580 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411581 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551582 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241583
Andy Davis68a8da42019-11-18 19:20:031584 // Compute the innermost common loop depth for dstNode loads/stores.
1585 SmallVector<Operation *, 2> dstOps(dstNode->loads.begin(),
1586 dstNode->loads.end());
1587 dstOps.append(dstNode->stores.begin(), dstNode->stores.end());
1588 unsigned dstLoopDepthTest = getInnermostCommonLoopDepth(dstOps);
1589 // Check the feasibility of fusing src loop nest into dst loop nest
1590 // at loop depths in range [1, dstLoopDepthTest].
1591 // TODO(andydavis) Use slice union computation and union of memref
1592 // read/write regions to cost model and fusion.
1593 bool canFuse = false;
1594 for (unsigned i = 1; i <= dstLoopDepthTest; ++i) {
1595 ComputationSliceState sliceUnion;
1596 FusionResult result = mlir::canFuseLoops(
1597 cast<AffineForOp>(srcNode->op), cast<AffineForOp>(dstNode->op),
1598 /*dstLoopDepth=*/i, &sliceUnion);
1599 if (result.value == FusionResult::Success)
1600 canFuse = true;
1601 }
1602
1603 // Skip if fusion is not feasible at all loop depths.
1604 if (!canFuse)
1605 continue;
1606
MLIR Teamd7c82442019-01-30 23:53:411607 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021608 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411609 for (auto *storeOpInst : dstNode->stores)
Andy Davis2e1187d2019-07-03 17:35:031610 if (cast<AffineStoreOp>(storeOpInst).getMemRef() == memref)
MLIR Teamd7c82442019-01-30 23:53:411611 dstStoreOpInsts.push_back(storeOpInst);
1612
Uday Bondhugulab4a14432019-01-26 00:00:501613 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251614 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411615 // Check if fusion would be profitable.
Diego Caballero34510552019-10-09 17:36:541616 if (!isFusionProfitable(srcStoreOp, srcStoreOp, dstLoadOpInsts,
1617 dstStoreOpInsts, &sliceState,
Uday Bondhugulace7e59532019-03-08 17:21:521618 &bestDstLoopDepth, maximalFusion))
MLIR Team38c2fe32019-01-14 19:26:251619 continue;
Andy Davis68a8da42019-11-18 19:20:031620
MLIR Team6892ffb2018-12-20 04:42:551621 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181622 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Diego Caballero34510552019-10-09 17:36:541623 srcStoreOp, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
Chris Lattnerd9b5bc82019-03-25 02:53:051624 if (sliceLoopNest) {
River Riddleaf1abcc2019-03-25 18:13:311625 LLVM_DEBUG(llvm::dbgs() << "\tslice loop nest:\n"
River Riddlef9d91532019-03-27 00:05:091626 << *sliceLoopNest.getOperation() << "\n");
River Riddle5052bd82019-02-02 00:42:181627 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleadca3c22019-05-12 00:57:321628 auto dstAffineForOp = cast<AffineForOp>(dstNode->op);
River Riddlef9d91532019-03-27 00:05:091629 if (insertPointInst != dstAffineForOp.getOperation()) {
1630 dstAffineForOp.getOperation()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411631 }
MLIR Teamc4237ae2019-01-18 16:56:271632 // Update edges between 'srcNode' and 'dstNode'.
Andy Davis68a8da42019-11-18 19:20:031633 mdg->updateEdges(srcNode->id, dstNode->id, memref,
1634 createPrivateMemref);
MLIR Teamc4237ae2019-01-18 16:56:271635
1636 // Collect slice loop stats.
1637 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:091638 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271639 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181640 for (auto forOp : sliceCollector.forOps) {
1641 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551642 }
Andy Davis68a8da42019-11-18 19:20:031643 if (createPrivateMemref) {
MLIR Team58aa3832019-02-16 01:12:191644 // Create private memref for 'memref' in 'dstAffineForOp'.
River Riddle99b87c92019-03-27 21:02:021645 SmallVector<Operation *, 4> storesForMemref;
MLIR Team58aa3832019-02-16 01:12:191646 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
Andy Davis2e1187d2019-07-03 17:35:031647 if (cast<AffineStoreOp>(storeOpInst).getMemRef() == memref)
MLIR Team58aa3832019-02-16 01:12:191648 storesForMemref.push_back(storeOpInst);
1649 }
Andy Davis68a8da42019-11-18 19:20:031650 // TODO(andydavis) Use union of memref write regions to compute
1651 // private memref footprint.
MLIR Team58aa3832019-02-16 01:12:191652 auto *newMemRef = createPrivateMemRef(
1653 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1654 fastMemorySpace, localBufSizeThreshold);
1655 visitedMemrefs.insert(newMemRef);
1656 // Create new node in dependence graph for 'newMemRef' alloc op.
1657 unsigned newMemRefNodeId =
River Riddlef9d91532019-03-27 00:05:091658 mdg->addNode(newMemRef->getDefiningOp());
MLIR Team58aa3832019-02-16 01:12:191659 // Add edge from 'newMemRef' node to dstNode.
1660 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271661 }
MLIR Teamc4237ae2019-01-18 16:56:271662
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031663 // Collect dst loop stats after memref privatization transformation.
MLIR Teamc4237ae2019-01-18 16:56:271664 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:091665 dstLoopCollector.collect(dstAffineForOp.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271666
1667 // Add new load ops to current Node load op list 'loads' to
1668 // continue fusing based on new operands.
1669 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
Andy Davis2e1187d2019-07-03 17:35:031670 auto *loadMemRef = cast<AffineLoadOp>(loadOpInst).getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271671 if (visitedMemrefs.count(loadMemRef) == 0)
1672 loads.push_back(loadOpInst);
1673 }
1674
Amit Sabne70a416d2019-04-09 16:17:401675 // Clear and add back loads and stores.
MLIR Teamc4237ae2019-01-18 16:56:271676 mdg->clearNodeLoadAndStores(dstNode->id);
1677 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1678 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371679 // Remove old src loop nest if it no longer has outgoing dependence
Amit Sabne70a416d2019-04-09 16:17:401680 // edges, and if it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191681 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1682 // been fused into 'dstNode' and write region of 'dstNode' covers
1683 // the write region of 'srcNode', and 'srcNode' has no other users
1684 // so it is safe to remove.
1685 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271686 mdg->removeNode(srcNode->id);
River Riddle99b87c92019-03-27 21:02:021687 srcNode->op->erase();
MLIR Teama78edcd2019-02-05 14:57:081688 } else {
1689 // Add remaining users of 'oldMemRef' back on the worklist (if not
1690 // already there), as its replacement with a local/private memref
1691 // has reduced dependences on 'oldMemRef' which may have created
1692 // new fusion opportunities.
1693 if (mdg->outEdges.count(srcNode->id) > 0) {
1694 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1695 mdg->outEdges[srcNode->id];
1696 for (auto &outEdge : oldOutEdges) {
1697 if (outEdge.value == memref &&
1698 worklistSet.count(outEdge.id) == 0) {
1699 worklist.push_back(outEdge.id);
1700 worklistSet.insert(outEdge.id);
1701 }
1702 }
1703 }
MLIR Teamc4237ae2019-01-18 16:56:271704 }
MLIR Team3b692302018-12-17 17:57:141705 }
MLIR Team3b692302018-12-17 17:57:141706 }
1707 }
1708 }
MLIR Teamd038e342019-03-01 19:50:251709 }
1710
1711 // Visits each node in the graph, and for each node, attempts to fuse it with
1712 // its sibling nodes (nodes which share a parent, but no dependence edges).
1713 void fuseSiblingNodes() {
1714 init();
1715 while (!worklist.empty()) {
1716 unsigned dstId = worklist.back();
1717 worklist.pop_back();
1718 worklistSet.erase(dstId);
1719
1720 // Skip if this node was removed (fused into another node).
1721 if (mdg->nodes.count(dstId) == 0)
1722 continue;
1723 // Get 'dstNode' into which to attempt fusion.
1724 auto *dstNode = mdg->getNode(dstId);
1725 // Skip if 'dstNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541726 if (!isa<AffineForOp>(dstNode->op))
MLIR Teamd038e342019-03-01 19:50:251727 continue;
1728 // Attempt to fuse 'dstNode' with its sibling nodes in the graph.
1729 fuseWithSiblingNodes(dstNode);
1730 }
1731 }
1732
1733 // Attempt to fuse 'dstNode' with sibling nodes in the graph.
1734 void fuseWithSiblingNodes(Node *dstNode) {
1735 DenseSet<unsigned> visitedSibNodeIds;
1736 std::pair<unsigned, Value *> idAndMemref;
1737 while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) {
1738 unsigned sibId = idAndMemref.first;
1739 Value *memref = idAndMemref.second;
1740 // TODO(andydavis) Check that 'sibStoreOpInst' post-dominates all other
1741 // stores to the same memref in 'sibNode' loop nest.
1742 auto *sibNode = mdg->getNode(sibId);
River Riddle99b87c92019-03-27 21:02:021743 // Compute an operation list insertion point for the fused loop
MLIR Teamd038e342019-03-01 19:50:251744 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:021745 assert(sibNode->op->getBlock() == dstNode->op->getBlock());
1746 Operation *insertPointInst =
1747 sibNode->op->isBeforeInBlock(dstNode->op)
MLIR Teamd038e342019-03-01 19:50:251748 ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id)
1749 : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id);
1750 if (insertPointInst == nullptr)
1751 continue;
1752
1753 // Check if fusion would be profitable and at what depth.
1754
1755 // Get unique 'sibNode' load op to 'memref'.
River Riddle99b87c92019-03-27 21:02:021756 SmallVector<Operation *, 2> sibLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:251757 sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts);
1758 // Currently findSiblingNodeToFuse searches for siblings with one load.
1759 assert(sibLoadOpInsts.size() == 1);
River Riddle99b87c92019-03-27 21:02:021760 Operation *sibLoadOpInst = sibLoadOpInsts[0];
MLIR Teamd038e342019-03-01 19:50:251761 assert(!sibNode->stores.empty());
1762 // TODO(andydavis) Choose the store which postdominates all other stores.
1763 auto *sibStoreOpInst = sibNode->stores.back();
1764
1765 // Gather 'dstNode' load ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021766 SmallVector<Operation *, 2> dstLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:251767 dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts);
1768
1769 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021770 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd038e342019-03-01 19:50:251771 dstNode->getStoreOpsForMemref(memref, &dstStoreOpInsts);
1772
1773 unsigned bestDstLoopDepth;
1774 mlir::ComputationSliceState sliceState;
1775
1776 // Check if fusion would be profitable.
1777 if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstLoadOpInsts,
Uday Bondhugulace7e59532019-03-08 17:21:521778 dstStoreOpInsts, &sliceState, &bestDstLoopDepth,
1779 maximalFusion))
MLIR Teamd038e342019-03-01 19:50:251780 continue;
1781
1782 // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'.
1783 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
1784 sibLoadOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
1785 if (sliceLoopNest != nullptr) {
River Riddleadca3c22019-05-12 00:57:321786 auto dstForInst = cast<AffineForOp>(dstNode->op);
River Riddle99b87c92019-03-27 21:02:021787 // Update operation position of fused loop nest (if needed).
River Riddlef9d91532019-03-27 00:05:091788 if (insertPointInst != dstForInst.getOperation()) {
1789 dstForInst.getOperation()->moveBefore(insertPointInst);
MLIR Teamd038e342019-03-01 19:50:251790 }
1791 // Update data dependence graph state post fusion.
1792 updateStateAfterSiblingFusion(sliceLoopNest, sibNode, dstNode);
1793 }
1794 }
1795 }
1796
MLIR Team9d30b362019-03-29 15:06:251797 // Searches function argument uses and the graph from 'dstNode' looking for a
1798 // fusion candidate sibling node which shares no dependences with 'dstNode'
1799 // but which loads from the same memref. Returns true and sets
1800 // 'idAndMemrefToFuse' on success. Returns false otherwise.
MLIR Teamd038e342019-03-01 19:50:251801 bool findSiblingNodeToFuse(Node *dstNode,
1802 DenseSet<unsigned> *visitedSibNodeIds,
1803 std::pair<unsigned, Value *> *idAndMemrefToFuse) {
MLIR Team9d30b362019-03-29 15:06:251804 // Returns true if 'sibNode' can be fused with 'dstNode' for input reuse
1805 // on 'memref'.
1806 auto canFuseWithSibNode = [&](Node *sibNode, Value *memref) {
1807 // Skip if 'outEdge' is not a read-after-write dependence.
1808 // TODO(andydavis) Remove restrict to single load op restriction.
1809 if (sibNode->getLoadOpCount(memref) != 1)
1810 return false;
1811 // Skip if there exists a path of dependent edges between
1812 // 'sibNode' and 'dstNode'.
1813 if (mdg->hasDependencePath(sibNode->id, dstNode->id) ||
1814 mdg->hasDependencePath(dstNode->id, sibNode->id))
1815 return false;
1816 // Skip sib node if it loads to (and stores from) the same memref on
1817 // which it also has an input dependence edge.
1818 DenseSet<Value *> loadAndStoreMemrefSet;
1819 sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet);
1820 if (llvm::any_of(loadAndStoreMemrefSet, [=](Value *memref) {
1821 return mdg->getIncomingMemRefAccesses(sibNode->id, memref) > 0;
1822 }))
1823 return false;
1824
1825 // Check that all stores are to the same memref.
1826 DenseSet<Value *> storeMemrefs;
1827 for (auto *storeOpInst : sibNode->stores) {
Andy Davis2e1187d2019-07-03 17:35:031828 storeMemrefs.insert(cast<AffineStoreOp>(storeOpInst).getMemRef());
MLIR Team9d30b362019-03-29 15:06:251829 }
1830 if (storeMemrefs.size() != 1)
1831 return false;
1832 return true;
1833 };
1834
1835 // Search for siblings which load the same memref function argument.
River Riddlece502af2019-07-08 18:20:261836 auto fn = dstNode->op->getParentOfType<FuncOp>();
River Riddle54cd6a72019-07-01 17:29:091837 for (unsigned i = 0, e = fn.getNumArguments(); i != e; ++i) {
1838 for (auto *user : fn.getArgument(i)->getUsers()) {
Andy Davis2e1187d2019-07-03 17:35:031839 if (auto loadOp = dyn_cast<AffineLoadOp>(user)) {
MLIR Team9d30b362019-03-29 15:06:251840 // Gather loops surrounding 'use'.
1841 SmallVector<AffineForOp, 4> loops;
River Riddle8780d8d2019-05-18 18:09:071842 getLoopIVs(*user, &loops);
MLIR Team9d30b362019-03-29 15:06:251843 // Skip 'use' if it is not within a loop nest.
1844 if (loops.empty())
1845 continue;
1846 Node *sibNode = mdg->getForOpNode(loops[0]);
1847 assert(sibNode != nullptr);
1848 // Skip 'use' if it not a sibling to 'dstNode'.
1849 if (sibNode->id == dstNode->id)
1850 continue;
1851 // Skip 'use' if it has been visited.
1852 if (visitedSibNodeIds->count(sibNode->id) > 0)
1853 continue;
1854 // Skip 'use' if it does not load from the same memref as 'dstNode'.
1855 auto *memref = loadOp.getMemRef();
1856 if (dstNode->getLoadOpCount(memref) == 0)
1857 continue;
1858 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1859 if (canFuseWithSibNode(sibNode, memref)) {
1860 visitedSibNodeIds->insert(sibNode->id);
1861 idAndMemrefToFuse->first = sibNode->id;
1862 idAndMemrefToFuse->second = memref;
1863 return true;
1864 }
1865 }
1866 }
1867 }
1868
1869 // Search for siblings by following edges through an intermediate src node.
MLIR Teamd038e342019-03-01 19:50:251870 // Collect candidate 'dstNode' input edges in 'inEdges'.
1871 SmallVector<MemRefDependenceGraph::Edge, 2> inEdges;
1872 mdg->forEachMemRefInputEdge(
1873 dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) {
1874 // Add 'inEdge' if it is a read-after-write dependence.
1875 if (dstNode->getLoadOpCount(inEdge.value) > 0 &&
1876 mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0)
1877 inEdges.push_back(inEdge);
1878 });
1879
1880 // Search for sibling nodes to fuse by visiting output edges from each input
1881 // edge in 'inEdges'.
1882 for (auto &inEdge : inEdges) {
1883 // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'.
1884 SmallVector<MemRefDependenceGraph::Edge, 2> outEdges;
1885 mdg->forEachMemRefOutputEdge(
1886 inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) {
1887 unsigned sibNodeId = outEdge.id;
1888 if (visitedSibNodeIds->count(sibNodeId) > 0)
1889 return;
1890 // Skip output edge if not a sibling using the same memref.
1891 if (outEdge.id == dstNode->id || outEdge.value != inEdge.value)
1892 return;
1893 auto *sibNode = mdg->getNode(sibNodeId);
River Riddled5b60ee82019-05-12 01:59:541894 if (!isa<AffineForOp>(sibNode->op))
MLIR Teamd038e342019-03-01 19:50:251895 return;
MLIR Team9d30b362019-03-29 15:06:251896 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1897 if (canFuseWithSibNode(sibNode, outEdge.value)) {
1898 // Add candidate 'outEdge' to sibling node.
1899 outEdges.push_back(outEdge);
MLIR Teamd038e342019-03-01 19:50:251900 }
MLIR Teamd038e342019-03-01 19:50:251901 });
1902
1903 // Add first candidate if any were returned.
1904 if (!outEdges.empty()) {
1905 visitedSibNodeIds->insert(outEdges[0].id);
1906 idAndMemrefToFuse->first = outEdges[0].id;
1907 idAndMemrefToFuse->second = outEdges[0].value;
1908 return true;
1909 }
1910 }
1911 return false;
1912 }
1913
Chris Lattnerd9b5bc82019-03-25 02:53:051914 void updateStateAfterSiblingFusion(AffineForOp sliceLoopNest, Node *sibNode,
1915 Node *dstNode) {
MLIR Teamd038e342019-03-01 19:50:251916 // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion.
1917 mdg->updateEdges(sibNode->id, dstNode->id);
1918
1919 // Collect slice loop stats.
1920 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:091921 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamd038e342019-03-01 19:50:251922 // Promote single iteration slice loops to single IV value.
1923 for (auto forOp : sliceCollector.forOps) {
1924 promoteIfSingleIteration(forOp);
1925 }
1926
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031927 // Collect dst loop stats after memref privatization transformation.
River Riddleadca3c22019-05-12 00:57:321928 auto dstForInst = cast<AffineForOp>(dstNode->op);
MLIR Teamd038e342019-03-01 19:50:251929 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:091930 dstLoopCollector.collect(dstForInst.getOperation());
MLIR Teamd038e342019-03-01 19:50:251931 // Clear and add back loads and stores
1932 mdg->clearNodeLoadAndStores(dstNode->id);
1933 mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts,
1934 dstLoopCollector.storeOpInsts);
1935 // Remove old sibling loop nest if it no longer has outgoing dependence
1936 // edges, and it does not write to a memref which escapes the
1937 // function.
1938 if (mdg->getOutEdgeCount(sibNode->id) == 0) {
1939 mdg->removeNode(sibNode->id);
River Riddleadca3c22019-05-12 00:57:321940 sibNode->op->erase();
MLIR Teamd038e342019-03-01 19:50:251941 }
1942 }
1943
1944 // Clean up any allocs with no users.
1945 void eraseUnusedMemRefAllocations() {
MLIR Teamc4237ae2019-01-18 16:56:271946 for (auto &pair : mdg->memrefEdgeCount) {
1947 if (pair.second > 0)
1948 continue;
1949 auto *memref = pair.first;
River Riddle99b87c92019-03-27 21:02:021950 // Skip if there exist other uses (return operation or function calls).
MLIR Team71495d52019-01-22 21:23:371951 if (!memref->use_empty())
1952 continue;
MLIR Teamc4237ae2019-01-18 16:56:271953 // Use list expected to match the dep graph info.
River Riddle99b87c92019-03-27 21:02:021954 auto *op = memref->getDefiningOp();
River Riddle1423acc2019-04-23 21:38:261955 if (isa_and_nonnull<AllocOp>(op))
River Riddle99b87c92019-03-27 21:02:021956 op->erase();
MLIR Teamc4237ae2019-01-18 16:56:271957 }
MLIR Teamf28e4df2018-11-01 14:26:001958 }
MLIR Team3b692302018-12-17 17:57:141959};
1960
1961} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001962
River Riddleed5fe202019-02-28 22:50:421963void LoopFusion::runOnFunction() {
Uday Bondhugulad4b3ff12019-02-27 00:10:191964 // Override if a command line argument was provided.
Uday Bondhugula8be26272019-02-02 01:06:221965 if (clFusionFastMemorySpace.getNumOccurrences() > 0) {
1966 fastMemorySpace = clFusionFastMemorySpace.getValue();
1967 }
1968
Uday Bondhugulad4b3ff12019-02-27 00:10:191969 // Override if a command line argument was provided.
1970 if (clFusionLocalBufThreshold.getNumOccurrences() > 0) {
1971 localBufSizeThreshold = clFusionLocalBufThreshold * 1024;
1972 }
1973
Uday Bondhugulace7e59532019-03-08 17:21:521974 if (clMaximalLoopFusion.getNumOccurrences() > 0)
1975 maximalFusion = clMaximalLoopFusion;
1976
MLIR Team6892ffb2018-12-20 04:42:551977 MemRefDependenceGraph g;
Uday Bondhugula02af8c22019-03-05 23:05:341978 if (g.init(getFunction()))
Uday Bondhugulace7e59532019-03-08 17:21:521979 GreedyFusion(&g, localBufSizeThreshold, fastMemorySpace, maximalFusion)
1980 .run();
MLIR Teamf28e4df2018-11-01 14:26:001981}
Jacques Pienaar6f0fb222018-11-07 02:34:181982
Nicolas Vasilache258e8d92019-05-03 18:07:371983static PassRegistration<LoopFusion> pass("affine-loop-fusion",
1984 "Fuse loop nests");