blob: 4ca27b479494c79b6c7326d14bb32706fd6c5db3 [file] [log] [blame]
MLIR Teamf28e4df2018-11-01 14:26:001//===- LoopFusion.cpp - Code to perform loop fusion -----------------------===//
2//
Mehdi Amini30857102020-01-26 03:58:303// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
Mehdi Amini56222a02019-12-23 17:35:364// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
MLIR Teamf28e4df2018-11-01 14:26:006//
Mehdi Amini56222a02019-12-23 17:35:367//===----------------------------------------------------------------------===//
MLIR Teamf28e4df2018-11-01 14:26:008//
9// This file implements loop fusion.
10//
11//===----------------------------------------------------------------------===//
12
River Riddle1834ad4a2020-04-07 20:58:1213#include "PassDetail.h"
MLIR Teamf28e4df2018-11-01 14:26:0014#include "mlir/Analysis/AffineAnalysis.h"
Uday Bondhuguladfe07b72019-02-23 00:51:0815#include "mlir/Analysis/AffineStructures.h"
MLIR Teamf28e4df2018-11-01 14:26:0016#include "mlir/Analysis/LoopAnalysis.h"
MLIR Team3b692302018-12-17 17:57:1417#include "mlir/Analysis/Utils.h"
Rob Sudermane7084712020-03-20 21:18:4718#include "mlir/Dialect/Affine/IR/AffineOps.h"
MLIR Teamf28e4df2018-11-01 14:26:0019#include "mlir/IR/AffineExpr.h"
20#include "mlir/IR/AffineMap.h"
21#include "mlir/IR/Builders.h"
Andy Davisa560f2c2019-05-24 17:54:2222#include "mlir/Transforms/LoopFusionUtils.h"
MLIR Teamf28e4df2018-11-01 14:26:0023#include "mlir/Transforms/LoopUtils.h"
24#include "mlir/Transforms/Passes.h"
MLIR Teamc4237ae2019-01-18 16:56:2725#include "mlir/Transforms/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0026#include "llvm/ADT/DenseMap.h"
MLIR Team3b692302018-12-17 17:57:1427#include "llvm/ADT/DenseSet.h"
28#include "llvm/ADT/SetVector.h"
MLIR Team4eef7952018-12-21 19:06:2329#include "llvm/Support/CommandLine.h"
MLIR Team38c2fe32019-01-14 19:26:2530#include "llvm/Support/Debug.h"
MLIR Team3b692302018-12-17 17:57:1431#include "llvm/Support/raw_ostream.h"
Uday Bondhugula864d9e02019-01-23 17:16:2432#include <iomanip>
Stella Laurenzo1a2ad062019-05-14 01:10:4833#include <sstream>
Nicolas Vasilache258e8d92019-05-03 18:07:3734#define DEBUG_TYPE "affine-loop-fusion"
MLIR Team38c2fe32019-01-14 19:26:2535
MLIR Team3b692302018-12-17 17:57:1436using llvm::SetVector;
MLIR Teamf28e4df2018-11-01 14:26:0037
38using namespace mlir;
39
MLIR Teamf28e4df2018-11-01 14:26:0040namespace {
MLIR Team3b692302018-12-17 17:57:1441/// Loop fusion pass. This pass currently supports a greedy fusion policy,
42/// which fuses loop nests with single-writer/single-reader memref dependences
43/// with the goal of improving locality.
44
45// TODO(andydavis) Support fusion of source loop nests which write to multiple
46// memrefs, where each memref can have multiple users (if profitable).
MLIR Teamf28e4df2018-11-01 14:26:0047// TODO(andydavis) Extend this pass to check for fusion preventing dependences,
48// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1449
River Riddle1834ad4a2020-04-07 20:58:1250struct LoopFusion : public AffineLoopFusionBase<LoopFusion> {
River Riddle400ad6f2020-04-08 19:57:0251 LoopFusion() = default;
52 LoopFusion(unsigned fastMemorySpace, uint64_t localBufSizeThresholdBytes,
53 bool maximalFusion) {
54 this->fastMemorySpace = fastMemorySpace;
55 this->localBufSizeThreshold = localBufSizeThresholdBytes / 1024;
56 this->maximalFusion = maximalFusion;
57 }
MLIR Teamf28e4df2018-11-01 14:26:0058
River Riddleed5fe202019-02-28 22:50:4259 void runOnFunction() override;
MLIR Teamf28e4df2018-11-01 14:26:0060};
61
MLIR Teamf28e4df2018-11-01 14:26:0062} // end anonymous namespace
63
River Riddle80aca1e2020-04-07 20:56:1664std::unique_ptr<OperationPass<FuncOp>>
Mehdi Amini926fb682019-08-13 02:12:4265mlir::createLoopFusionPass(unsigned fastMemorySpace,
66 uint64_t localBufSizeThreshold, bool maximalFusion) {
Jacques Pienaar79f53b02019-08-17 18:05:3567 return std::make_unique<LoopFusion>(fastMemorySpace, localBufSizeThreshold,
68 maximalFusion);
Uday Bondhugulad4b3ff12019-02-27 00:10:1969}
MLIR Teamf28e4df2018-11-01 14:26:0070
River Riddle2666b972019-12-18 18:46:1671// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
72static bool isMemRefDereferencingOp(Operation &op) {
Diego Caballeroa45fb192020-05-20 00:16:0473 if (isa<AffineReadOpInterface>(op) || isa<AffineWriteOpInterface>(op) ||
River Riddle2666b972019-12-18 18:46:1674 isa<AffineDmaStartOp>(op) || isa<AffineDmaWaitOp>(op))
75 return true;
76 return false;
77}
78
MLIR Team3b692302018-12-17 17:57:1479namespace {
MLIR Teamf28e4df2018-11-01 14:26:0080
MLIR Team3b692302018-12-17 17:57:1481// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:3582// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:4483struct LoopNestStateCollector {
Chris Lattnerd9b5bc82019-03-25 02:53:0584 SmallVector<AffineForOp, 4> forOps;
River Riddle99b87c92019-03-27 21:02:0285 SmallVector<Operation *, 4> loadOpInsts;
86 SmallVector<Operation *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:5387 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:1488
River Riddle99b87c92019-03-27 21:02:0289 void collect(Operation *opToWalk) {
90 opToWalk->walk([&](Operation *op) {
River Riddled5b60ee82019-05-12 01:59:5491 if (isa<AffineForOp>(op))
River Riddleadca3c22019-05-12 00:57:3292 forOps.push_back(cast<AffineForOp>(op));
River Riddle99b87c92019-03-27 21:02:0293 else if (op->getNumRegions() != 0)
River Riddlebf9c3812019-02-05 00:24:4494 hasNonForRegion = true;
Diego Caballeroa45fb192020-05-20 00:16:0495 else if (isa<AffineReadOpInterface>(op))
River Riddle99b87c92019-03-27 21:02:0296 loadOpInsts.push_back(op);
Diego Caballeroa45fb192020-05-20 00:16:0497 else if (isa<AffineWriteOpInterface>(op))
River Riddle99b87c92019-03-27 21:02:0298 storeOpInsts.push_back(op);
River Riddlebf9c3812019-02-05 00:24:4499 });
MLIR Team3b692302018-12-17 17:57:14100 }
101};
102
MLIR Team6892ffb2018-12-20 04:42:55103// MemRefDependenceGraph is a graph data structure where graph nodes are
River Riddle8c443672019-07-09 23:17:55104// top-level operations in a FuncOp which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55105// are memref dependences between the nodes.
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03106// TODO(andydavis) Add a more flexible dependence graph representation.
MLIR Team6892ffb2018-12-20 04:42:55107// TODO(andydavis) Add a depth parameter to dependence graph construction.
108struct MemRefDependenceGraph {
109public:
110 // Node represents a node in the graph. A Node is either an entire loop nest
111 // rooted at the top level which contains loads/stores, or a top level
112 // load/store.
113 struct Node {
114 // The unique identifier of this node in the graph.
115 unsigned id;
Amit Sabne70a416d2019-04-09 16:17:40116 // The top-level statement which is (or contains) a load/store.
River Riddle99b87c92019-03-27 21:02:02117 Operation *op;
Chris Lattner5187cfc2018-12-28 05:21:41118 // List of load operations.
River Riddle99b87c92019-03-27 21:02:02119 SmallVector<Operation *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35120 // List of store op insts.
River Riddle99b87c92019-03-27 21:02:02121 SmallVector<Operation *, 4> stores;
122 Node(unsigned id, Operation *op) : id(id), op(op) {}
MLIR Team6892ffb2018-12-20 04:42:55123
124 // Returns the load op count for 'memref'.
River Riddlee62a6952019-12-23 22:45:01125 unsigned getLoadOpCount(Value memref) {
MLIR Team6892ffb2018-12-20 04:42:55126 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35127 for (auto *loadOpInst : loads) {
Diego Caballeroa45fb192020-05-20 00:16:04128 if (memref == cast<AffineReadOpInterface>(loadOpInst).getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55129 ++loadOpCount;
130 }
131 return loadOpCount;
132 }
133
134 // Returns the store op count for 'memref'.
River Riddlee62a6952019-12-23 22:45:01135 unsigned getStoreOpCount(Value memref) {
MLIR Team6892ffb2018-12-20 04:42:55136 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35137 for (auto *storeOpInst : stores) {
Diego Caballeroa45fb192020-05-20 00:16:04138 if (memref == cast<AffineWriteOpInterface>(storeOpInst).getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55139 ++storeOpCount;
140 }
141 return storeOpCount;
142 }
MLIR Team58aa3832019-02-16 01:12:19143
MLIR Teamd038e342019-03-01 19:50:25144 // Returns all store ops in 'storeOps' which access 'memref'.
River Riddlee62a6952019-12-23 22:45:01145 void getStoreOpsForMemref(Value memref,
River Riddle99b87c92019-03-27 21:02:02146 SmallVectorImpl<Operation *> *storeOps) {
MLIR Team58aa3832019-02-16 01:12:19147 for (auto *storeOpInst : stores) {
Diego Caballeroa45fb192020-05-20 00:16:04148 if (memref == cast<AffineWriteOpInterface>(storeOpInst).getMemRef())
MLIR Team58aa3832019-02-16 01:12:19149 storeOps->push_back(storeOpInst);
150 }
151 }
MLIR Teamd038e342019-03-01 19:50:25152
153 // Returns all load ops in 'loadOps' which access 'memref'.
River Riddlee62a6952019-12-23 22:45:01154 void getLoadOpsForMemref(Value memref,
River Riddle99b87c92019-03-27 21:02:02155 SmallVectorImpl<Operation *> *loadOps) {
MLIR Teamd038e342019-03-01 19:50:25156 for (auto *loadOpInst : loads) {
Diego Caballeroa45fb192020-05-20 00:16:04157 if (memref == cast<AffineReadOpInterface>(loadOpInst).getMemRef())
MLIR Teamd038e342019-03-01 19:50:25158 loadOps->push_back(loadOpInst);
159 }
160 }
161
162 // Returns all memrefs in 'loadAndStoreMemrefSet' for which this node
163 // has at least one load and store operation.
River Riddlee62a6952019-12-23 22:45:01164 void getLoadAndStoreMemrefSet(DenseSet<Value> *loadAndStoreMemrefSet) {
165 llvm::SmallDenseSet<Value, 2> loadMemrefs;
MLIR Teamd038e342019-03-01 19:50:25166 for (auto *loadOpInst : loads) {
Diego Caballeroa45fb192020-05-20 00:16:04167 loadMemrefs.insert(cast<AffineReadOpInterface>(loadOpInst).getMemRef());
MLIR Teamd038e342019-03-01 19:50:25168 }
169 for (auto *storeOpInst : stores) {
Diego Caballeroa45fb192020-05-20 00:16:04170 auto memref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
MLIR Teamd038e342019-03-01 19:50:25171 if (loadMemrefs.count(memref) > 0)
172 loadAndStoreMemrefSet->insert(memref);
173 }
174 }
MLIR Team6892ffb2018-12-20 04:42:55175 };
176
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03177 // Edge represents a data dependence between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55178 struct Edge {
179 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46180 // If this edge is stored in Edge = Node.inEdges[i], then
181 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
182 // If this edge is stored in Edge = Node.outEdges[i], then
183 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55184 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41185 // The SSA value on which this edge represents a dependence.
186 // If the value is a memref, then the dependence is between graph nodes
187 // which contain accesses to the same memref 'value'. If the value is a
188 // non-memref value, then the dependence is between a graph node which
189 // defines an SSA value and another graph node which uses the SSA value
River Riddle99b87c92019-03-27 21:02:02190 // (e.g. a constant operation defining a value which is used inside a loop
MLIR Teama0f3db402019-01-29 17:36:41191 // nest).
River Riddlee62a6952019-12-23 22:45:01192 Value value;
MLIR Team6892ffb2018-12-20 04:42:55193 };
194
195 // Map from node id to Node.
196 DenseMap<unsigned, Node> nodes;
197 // Map from node id to list of input edges.
198 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
199 // Map from node id to list of output edges.
200 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27201 // Map from memref to a count on the dependence edges associated with that
202 // memref.
River Riddlee62a6952019-12-23 22:45:01203 DenseMap<Value, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41204 // The next unique identifier to use for newly created graph nodes.
205 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55206
207 MemRefDependenceGraph() {}
208
209 // Initializes the dependence graph based on operations in 'f'.
210 // Returns true on success, false otherwise.
River Riddle8c443672019-07-09 23:17:55211 bool init(FuncOp f);
MLIR Team6892ffb2018-12-20 04:42:55212
213 // Returns the graph node for 'id'.
214 Node *getNode(unsigned id) {
215 auto it = nodes.find(id);
216 assert(it != nodes.end());
217 return &it->second;
218 }
219
MLIR Team9d30b362019-03-29 15:06:25220 // Returns the graph node for 'forOp'.
221 Node *getForOpNode(AffineForOp forOp) {
222 for (auto &idAndNode : nodes)
223 if (idAndNode.second.op == forOp.getOperation())
224 return &idAndNode.second;
225 return nullptr;
226 }
227
River Riddle99b87c92019-03-27 21:02:02228 // Adds a node with 'op' to the graph and returns its unique identifier.
229 unsigned addNode(Operation *op) {
230 Node node(nextNodeId++, op);
MLIR Teama0f3db402019-01-29 17:36:41231 nodes.insert({node.id, node});
232 return node.id;
233 }
234
MLIR Teamc4237ae2019-01-18 16:56:27235 // Remove node 'id' (and its associated edges) from graph.
236 void removeNode(unsigned id) {
237 // Remove each edge in 'inEdges[id]'.
238 if (inEdges.count(id) > 0) {
239 SmallVector<Edge, 2> oldInEdges = inEdges[id];
240 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41241 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27242 }
243 }
244 // Remove each edge in 'outEdges[id]'.
245 if (outEdges.count(id) > 0) {
246 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
247 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41248 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27249 }
250 }
251 // Erase remaining node state.
252 inEdges.erase(id);
253 outEdges.erase(id);
254 nodes.erase(id);
255 }
256
MLIR Teamd7c82442019-01-30 23:53:41257 // Returns true if node 'id' writes to any memref which escapes (or is an
258 // argument to) the function/block. Returns false otherwise.
259 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37260 Node *node = getNode(id);
261 for (auto *storeOpInst : node->stores) {
Diego Caballeroa45fb192020-05-20 00:16:04262 auto memref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
River Riddle2bdf33c2020-01-11 16:54:04263 auto *op = memref.getDefiningOp();
MLIR Team58aa3832019-02-16 01:12:19264 // Return true if 'memref' is a block argument.
River Riddle99b87c92019-03-27 21:02:02265 if (!op)
MLIR Teamd7c82442019-01-30 23:53:41266 return true;
MLIR Team58aa3832019-02-16 01:12:19267 // Return true if any use of 'memref' escapes the function.
River Riddle2bdf33c2020-01-11 16:54:04268 for (auto *user : memref.getUsers())
River Riddle8780d8d2019-05-18 18:09:07269 if (!isMemRefDereferencingOp(*user))
MLIR Teamd7c82442019-01-30 23:53:41270 return true;
MLIR Teamd7c82442019-01-30 23:53:41271 }
272 return false;
273 }
274
Diego Caballeroa45fb192020-05-20 00:16:04275 // Returns the unique AffineWriteOpInterface in `node` that meets all the
276 // following:
Diego Caballero34510552019-10-09 17:36:54277 // *) store is the only one that writes to a function-local memref live out
278 // of `node`,
279 // *) store is not the source of a self-dependence on `node`.
Diego Caballeroa45fb192020-05-20 00:16:04280 // Otherwise, returns a null AffineWriteOpInterface.
281 AffineWriteOpInterface getUniqueOutgoingStore(Node *node) {
282 AffineWriteOpInterface uniqueStore;
Diego Caballero34510552019-10-09 17:36:54283
284 // Return null if `node` doesn't have any outgoing edges.
285 auto outEdgeIt = outEdges.find(node->id);
286 if (outEdgeIt == outEdges.end())
287 return nullptr;
288
289 const auto &nodeOutEdges = outEdgeIt->second;
290 for (auto *op : node->stores) {
Diego Caballeroa45fb192020-05-20 00:16:04291 auto storeOp = cast<AffineWriteOpInterface>(op);
River Riddle35807bc2019-12-23 05:59:55292 auto memref = storeOp.getMemRef();
Diego Caballero34510552019-10-09 17:36:54293 // Skip this store if there are no dependences on its memref. This means
294 // that store either:
295 // *) writes to a memref that is only read within the same loop nest
296 // (self-dependence edges are not represented in graph at the moment),
297 // *) writes to a function live out memref (function parameter), or
298 // *) is dead.
299 if (llvm::all_of(nodeOutEdges, [=](const Edge &edge) {
300 return (edge.value != memref);
301 }))
302 continue;
303
304 if (uniqueStore)
305 // Found multiple stores to function-local live-out memrefs.
306 return nullptr;
307 // Found first store to function-local live-out memref.
308 uniqueStore = storeOp;
309 }
310
311 return uniqueStore;
312 }
313
MLIR Teamd7c82442019-01-30 23:53:41314 // Returns true if node 'id' can be removed from the graph. Returns false
315 // otherwise. A node can be removed from the graph iff the following
316 // conditions are met:
317 // *) The node does not write to any memref which escapes (or is a
318 // function/block argument).
319 // *) The node has no successors in the dependence graph.
320 bool canRemoveNode(unsigned id) {
321 if (writesToLiveInOrEscapingMemrefs(id))
322 return false;
323 Node *node = getNode(id);
324 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41325 // Return false if there exist out edges from 'id' on 'memref'.
Diego Caballeroa45fb192020-05-20 00:16:04326 auto storeMemref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
327 if (getOutEdgeCount(id, storeMemref) > 0)
MLIR Teama0f3db402019-01-29 17:36:41328 return false;
MLIR Team71495d52019-01-22 21:23:37329 }
MLIR Teama0f3db402019-01-29 17:36:41330 return true;
MLIR Team71495d52019-01-22 21:23:37331 }
332
MLIR Teamd038e342019-03-01 19:50:25333 // Returns true iff there is an edge from node 'srcId' to node 'dstId' which
334 // is for 'value' if non-null, or for any value otherwise. Returns false
335 // otherwise.
River Riddlee62a6952019-12-23 22:45:01336 bool hasEdge(unsigned srcId, unsigned dstId, Value value = nullptr) {
MLIR Team27d067e2019-01-16 17:55:02337 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
338 return false;
339 }
340 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25341 return edge.id == dstId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02342 });
343 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teamd038e342019-03-01 19:50:25344 return edge.id == srcId && (!value || edge.value == value);
MLIR Team27d067e2019-01-16 17:55:02345 });
346 return hasOutEdge && hasInEdge;
347 }
348
MLIR Teama0f3db402019-01-29 17:36:41349 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
River Riddlee62a6952019-12-23 22:45:01350 void addEdge(unsigned srcId, unsigned dstId, Value value) {
MLIR Teama0f3db402019-01-29 17:36:41351 if (!hasEdge(srcId, dstId, value)) {
352 outEdges[srcId].push_back({dstId, value});
353 inEdges[dstId].push_back({srcId, value});
River Riddle2bdf33c2020-01-11 16:54:04354 if (value.getType().isa<MemRefType>())
MLIR Teama0f3db402019-01-29 17:36:41355 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02356 }
MLIR Team6892ffb2018-12-20 04:42:55357 }
358
MLIR Teama0f3db402019-01-29 17:36:41359 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
River Riddlee62a6952019-12-23 22:45:01360 void removeEdge(unsigned srcId, unsigned dstId, Value value) {
MLIR Team6892ffb2018-12-20 04:42:55361 assert(inEdges.count(dstId) > 0);
362 assert(outEdges.count(srcId) > 0);
River Riddle2bdf33c2020-01-11 16:54:04363 if (value.getType().isa<MemRefType>()) {
MLIR Teama0f3db402019-01-29 17:36:41364 assert(memrefEdgeCount.count(value) > 0);
365 memrefEdgeCount[value]--;
366 }
MLIR Team6892ffb2018-12-20 04:42:55367 // Remove 'srcId' from 'inEdges[dstId]'.
368 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41369 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55370 inEdges[dstId].erase(it);
371 break;
372 }
373 }
374 // Remove 'dstId' from 'outEdges[srcId]'.
375 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41376 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55377 outEdges[srcId].erase(it);
378 break;
379 }
380 }
381 }
382
MLIR Teamd038e342019-03-01 19:50:25383 // Returns true if there is a path in the dependence graph from node 'srcId'
384 // to node 'dstId'. Returns false otherwise.
385 bool hasDependencePath(unsigned srcId, unsigned dstId) {
386 // Worklist state is: <node-id, next-output-edge-index-to-visit>
387 SmallVector<std::pair<unsigned, unsigned>, 4> worklist;
388 worklist.push_back({srcId, 0});
389 // Run DFS traversal to see if 'dstId' is reachable from 'srcId'.
390 while (!worklist.empty()) {
391 auto &idAndIndex = worklist.back();
392 // Return true if we have reached 'dstId'.
393 if (idAndIndex.first == dstId)
394 return true;
395 // Pop and continue if node has no out edges, or if all out edges have
396 // already been visited.
397 if (outEdges.count(idAndIndex.first) == 0 ||
398 idAndIndex.second == outEdges[idAndIndex.first].size()) {
399 worklist.pop_back();
400 continue;
401 }
402 // Get graph edge to traverse.
403 Edge edge = outEdges[idAndIndex.first][idAndIndex.second];
404 // Increment next output edge index for 'idAndIndex'.
405 ++idAndIndex.second;
406 // Add node at 'edge.id' to worklist.
407 worklist.push_back({edge.id, 0});
408 }
409 return false;
410 }
411
MLIR Teama0f3db402019-01-29 17:36:41412 // Returns the input edge count for node 'id' and 'memref' from src nodes
MLIR Teamd038e342019-03-01 19:50:25413 // which access 'memref' with a store operation.
River Riddlee62a6952019-12-23 22:45:01414 unsigned getIncomingMemRefAccesses(unsigned id, Value memref) {
MLIR Team6892ffb2018-12-20 04:42:55415 unsigned inEdgeCount = 0;
416 if (inEdges.count(id) > 0)
417 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41418 if (inEdge.value == memref) {
419 Node *srcNode = getNode(inEdge.id);
420 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
MLIR Teamd038e342019-03-01 19:50:25421 if (srcNode->getStoreOpCount(memref) > 0)
MLIR Teama0f3db402019-01-29 17:36:41422 ++inEdgeCount;
423 }
MLIR Team6892ffb2018-12-20 04:42:55424 return inEdgeCount;
425 }
426
MLIR Teamd038e342019-03-01 19:50:25427 // Returns the output edge count for node 'id' and 'memref' (if non-null),
428 // otherwise returns the total output edge count from node 'id'.
River Riddlee62a6952019-12-23 22:45:01429 unsigned getOutEdgeCount(unsigned id, Value memref = nullptr) {
MLIR Team6892ffb2018-12-20 04:42:55430 unsigned outEdgeCount = 0;
431 if (outEdges.count(id) > 0)
432 for (auto &outEdge : outEdges[id])
MLIR Teamd038e342019-03-01 19:50:25433 if (!memref || outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55434 ++outEdgeCount;
435 return outEdgeCount;
436 }
437
River Riddle99b87c92019-03-27 21:02:02438 // Computes and returns an insertion point operation, before which the
MLIR Teama0f3db402019-01-29 17:36:41439 // the fused <srcId, dstId> loop nest can be inserted while preserving
440 // dependences. Returns nullptr if no such insertion point is found.
River Riddle99b87c92019-03-27 21:02:02441 Operation *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40442 if (outEdges.count(srcId) == 0)
River Riddle99b87c92019-03-27 21:02:02443 return getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41444
445 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
River Riddle99b87c92019-03-27 21:02:02446 SmallPtrSet<Operation *, 2> srcDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41447 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08448 if (outEdge.id != dstId)
River Riddle99b87c92019-03-27 21:02:02449 srcDepInsts.insert(getNode(outEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41450
451 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
River Riddle99b87c92019-03-27 21:02:02452 SmallPtrSet<Operation *, 2> dstDepInsts;
MLIR Teama0f3db402019-01-29 17:36:41453 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08454 if (inEdge.id != srcId)
River Riddle99b87c92019-03-27 21:02:02455 dstDepInsts.insert(getNode(inEdge.id)->op);
MLIR Teama0f3db402019-01-29 17:36:41456
River Riddle99b87c92019-03-27 21:02:02457 Operation *srcNodeInst = getNode(srcId)->op;
458 Operation *dstNodeInst = getNode(dstId)->op;
MLIR Teama0f3db402019-01-29 17:36:41459
460 // Computing insertion point:
River Riddle99b87c92019-03-27 21:02:02461 // *) Walk all operation positions in Block operation list in the
462 // range (src, dst). For each operation 'op' visited in this search:
463 // *) Store in 'firstSrcDepPos' the first position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41464 // dependence edge from 'srcNode'.
River Riddle99b87c92019-03-27 21:02:02465 // *) Store in 'lastDstDepPost' the last position where 'op' has a
MLIR Teama0f3db402019-01-29 17:36:41466 // dependence edge to 'dstNode'.
467 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
River Riddle99b87c92019-03-27 21:02:02468 // operation insertion point (or return null pointer if no such
MLIR Teama0f3db402019-01-29 17:36:41469 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
River Riddle99b87c92019-03-27 21:02:02470 SmallVector<Operation *, 2> depInsts;
MLIR Teama0f3db402019-01-29 17:36:41471 Optional<unsigned> firstSrcDepPos;
472 Optional<unsigned> lastDstDepPos;
473 unsigned pos = 0;
474 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
475 it != Block::iterator(dstNodeInst); ++it) {
River Riddle99b87c92019-03-27 21:02:02476 Operation *op = &(*it);
477 if (srcDepInsts.count(op) > 0 && firstSrcDepPos == None)
MLIR Teama0f3db402019-01-29 17:36:41478 firstSrcDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02479 if (dstDepInsts.count(op) > 0)
MLIR Teama0f3db402019-01-29 17:36:41480 lastDstDepPos = pos;
River Riddle99b87c92019-03-27 21:02:02481 depInsts.push_back(op);
MLIR Teama0f3db402019-01-29 17:36:41482 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40483 }
MLIR Teama0f3db402019-01-29 17:36:41484
485 if (firstSrcDepPos.hasValue()) {
486 if (lastDstDepPos.hasValue()) {
487 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
488 // No valid insertion point exists which preserves dependences.
489 return nullptr;
490 }
491 }
492 // Return the insertion point at 'firstSrcDepPos'.
493 return depInsts[firstSrcDepPos.getValue()];
494 }
495 // No dependence targets in range (or only dst deps in range), return
496 // 'dstNodInst' insertion point.
497 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55498 }
499
MLIR Teama0f3db402019-01-29 17:36:41500 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
Andy Davis68a8da42019-11-18 19:20:03501 // has been replaced in node at 'dstId' by a private memref depending
502 // on the value of 'createPrivateMemRef'.
River Riddlee62a6952019-12-23 22:45:01503 void updateEdges(unsigned srcId, unsigned dstId, Value oldMemRef,
Andy Davis68a8da42019-11-18 19:20:03504 bool createPrivateMemRef) {
Kazuaki Ishizakifc817b02020-01-20 03:14:37505 // For each edge in 'inEdges[srcId]': add new edge remapping to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55506 if (inEdges.count(srcId) > 0) {
507 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
508 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41509 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
510 if (inEdge.value != oldMemRef)
511 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55512 }
513 }
MLIR Teamc4237ae2019-01-18 16:56:27514 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55515 if (outEdges.count(srcId) > 0) {
516 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
517 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27518 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
519 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41520 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55521 }
522 }
MLIR Teama0f3db402019-01-29 17:36:41523 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
524 // replaced by a private memref). These edges could come from nodes
525 // other than 'srcId' which were removed in the previous step.
Andy Davis68a8da42019-11-18 19:20:03526 if (inEdges.count(dstId) > 0 && createPrivateMemRef) {
MLIR Teama0f3db402019-01-29 17:36:41527 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
528 for (auto &inEdge : oldInEdges)
529 if (inEdge.value == oldMemRef)
530 removeEdge(inEdge.id, dstId, inEdge.value);
531 }
MLIR Team6892ffb2018-12-20 04:42:55532 }
533
MLIR Teamd038e342019-03-01 19:50:25534 // Update edge mappings for nodes 'sibId' and 'dstId' to reflect fusion
535 // of sibling node 'sidId' into node 'dstId'.
536 void updateEdges(unsigned sibId, unsigned dstId) {
537 // For each edge in 'inEdges[sibId]':
538 // *) Add new edge from source node 'inEdge.id' to 'dstNode'.
539 // *) Remove edge from source node 'inEdge.id' to 'sibNode'.
540 if (inEdges.count(sibId) > 0) {
541 SmallVector<Edge, 2> oldInEdges = inEdges[sibId];
542 for (auto &inEdge : oldInEdges) {
543 addEdge(inEdge.id, dstId, inEdge.value);
544 removeEdge(inEdge.id, sibId, inEdge.value);
545 }
546 }
547
548 // For each edge in 'outEdges[sibId]' to node 'id'
549 // *) Add new edge from 'dstId' to 'outEdge.id'.
550 // *) Remove edge from 'sibId' to 'outEdge.id'.
551 if (outEdges.count(sibId) > 0) {
552 SmallVector<Edge, 2> oldOutEdges = outEdges[sibId];
553 for (auto &outEdge : oldOutEdges) {
554 addEdge(dstId, outEdge.id, outEdge.value);
555 removeEdge(sibId, outEdge.id, outEdge.value);
556 }
557 }
558 }
559
MLIR Team6892ffb2018-12-20 04:42:55560 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddle99b87c92019-03-27 21:02:02561 void addToNode(unsigned id, const SmallVectorImpl<Operation *> &loads,
562 const SmallVectorImpl<Operation *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55563 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35564 for (auto *loadOpInst : loads)
565 node->loads.push_back(loadOpInst);
566 for (auto *storeOpInst : stores)
567 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55568 }
569
MLIR Teamc4237ae2019-01-18 16:56:27570 void clearNodeLoadAndStores(unsigned id) {
571 Node *node = getNode(id);
572 node->loads.clear();
573 node->stores.clear();
574 }
575
MLIR Teamd038e342019-03-01 19:50:25576 // Calls 'callback' for each input edge incident to node 'id' which carries a
577 // memref dependence.
578 void forEachMemRefInputEdge(unsigned id,
579 const std::function<void(Edge)> &callback) {
580 if (inEdges.count(id) > 0)
581 forEachMemRefEdge(inEdges[id], callback);
582 }
Amit Sabne70a416d2019-04-09 16:17:40583
MLIR Teamd038e342019-03-01 19:50:25584 // Calls 'callback' for each output edge from node 'id' which carries a
585 // memref dependence.
586 void forEachMemRefOutputEdge(unsigned id,
587 const std::function<void(Edge)> &callback) {
588 if (outEdges.count(id) > 0)
589 forEachMemRefEdge(outEdges[id], callback);
590 }
Amit Sabne70a416d2019-04-09 16:17:40591
MLIR Teamd038e342019-03-01 19:50:25592 // Calls 'callback' for each edge in 'edges' which carries a memref
593 // dependence.
594 void forEachMemRefEdge(ArrayRef<Edge> edges,
595 const std::function<void(Edge)> &callback) {
596 for (auto &edge : edges) {
597 // Skip if 'edge' is not a memref dependence edge.
River Riddle2bdf33c2020-01-11 16:54:04598 if (!edge.value.getType().isa<MemRefType>())
MLIR Teamd038e342019-03-01 19:50:25599 continue;
600 assert(nodes.count(edge.id) > 0);
601 // Skip if 'edge.id' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:54602 if (!isa<AffineForOp>(getNode(edge.id)->op))
MLIR Teamd038e342019-03-01 19:50:25603 continue;
604 // Visit current input edge 'edge'.
605 callback(edge);
606 }
607 }
608
MLIR Team6892ffb2018-12-20 04:42:55609 void print(raw_ostream &os) const {
610 os << "\nMemRefDependenceGraph\n";
611 os << "\nNodes:\n";
612 for (auto &idAndNode : nodes) {
613 os << "Node: " << idAndNode.first << "\n";
614 auto it = inEdges.find(idAndNode.first);
615 if (it != inEdges.end()) {
616 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41617 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55618 }
619 it = outEdges.find(idAndNode.first);
620 if (it != outEdges.end()) {
621 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41622 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55623 }
624 }
625 }
626 void dump() const { print(llvm::errs()); }
627};
628
River Riddle2666b972019-12-18 18:46:16629} // end anonymous namespace
630
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03631// Initializes the data dependence graph by walking operations in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55632// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39633// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55634// dependence graph at a different depth.
River Riddle8c443672019-07-09 23:17:55635bool MemRefDependenceGraph::init(FuncOp f) {
River Riddlee62a6952019-12-23 22:45:01636 DenseMap<Value, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43637
638 // TODO: support multi-block functions.
Rahul Joshi2eaadfc2020-06-17 20:20:36639 if (!llvm::hasSingleElement(f))
Chris Lattnerdffc5892018-12-29 23:33:43640 return false;
641
River Riddle99b87c92019-03-27 21:02:02642 DenseMap<Operation *, unsigned> forToNodeMap;
643 for (auto &op : f.front()) {
River Riddlec5ecf992019-05-11 22:56:50644 if (auto forOp = dyn_cast<AffineForOp>(op)) {
River Riddle5052bd82019-02-02 00:42:18645 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55646 // all loads and store accesses it contains.
647 LoopNestStateCollector collector;
River Riddle99b87c92019-03-27 21:02:02648 collector.collect(&op);
River Riddle832567b2019-03-25 17:14:34649 // Return false if a non 'affine.for' region was found (not currently
650 // supported).
River Riddle75553832019-01-29 05:23:53651 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55652 return false;
River Riddle99b87c92019-03-27 21:02:02653 Node node(nextNodeId++, &op);
Chris Lattner456ad6a2018-12-29 00:05:35654 for (auto *opInst : collector.loadOpInsts) {
655 node.loads.push_back(opInst);
Diego Caballeroa45fb192020-05-20 00:16:04656 auto memref = cast<AffineReadOpInterface>(opInst).getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55657 memrefAccesses[memref].insert(node.id);
658 }
Chris Lattner456ad6a2018-12-29 00:05:35659 for (auto *opInst : collector.storeOpInsts) {
660 node.stores.push_back(opInst);
Diego Caballeroa45fb192020-05-20 00:16:04661 auto memref = cast<AffineWriteOpInterface>(opInst).getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55662 memrefAccesses[memref].insert(node.id);
663 }
River Riddle99b87c92019-03-27 21:02:02664 forToNodeMap[&op] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55665 nodes.insert({node.id, node});
Diego Caballeroa45fb192020-05-20 00:16:04666 } else if (auto loadOp = dyn_cast<AffineReadOpInterface>(op)) {
River Riddleb4992772019-02-04 18:38:47667 // Create graph node for top-level load op.
River Riddle99b87c92019-03-27 21:02:02668 Node node(nextNodeId++, &op);
669 node.loads.push_back(&op);
Diego Caballeroa45fb192020-05-20 00:16:04670 auto memref = cast<AffineReadOpInterface>(op).getMemRef();
River Riddleb4992772019-02-04 18:38:47671 memrefAccesses[memref].insert(node.id);
672 nodes.insert({node.id, node});
Diego Caballeroa45fb192020-05-20 00:16:04673 } else if (auto storeOp = dyn_cast<AffineWriteOpInterface>(op)) {
River Riddleb4992772019-02-04 18:38:47674 // Create graph node for top-level store op.
River Riddle99b87c92019-03-27 21:02:02675 Node node(nextNodeId++, &op);
676 node.stores.push_back(&op);
Diego Caballeroa45fb192020-05-20 00:16:04677 auto memref = cast<AffineWriteOpInterface>(op).getMemRef();
River Riddleb4992772019-02-04 18:38:47678 memrefAccesses[memref].insert(node.id);
679 nodes.insert({node.id, node});
River Riddle99b87c92019-03-27 21:02:02680 } else if (op.getNumRegions() != 0) {
River Riddleb4992772019-02-04 18:38:47681 // Return false if another region is found (not currently supported).
682 return false;
River Riddle99b87c92019-03-27 21:02:02683 } else if (op.getNumResults() > 0 && !op.use_empty()) {
River Riddleb4992772019-02-04 18:38:47684 // Create graph node for top-level producer of SSA values, which
685 // could be used by loop nest nodes.
River Riddle99b87c92019-03-27 21:02:02686 Node node(nextNodeId++, &op);
River Riddleb4992772019-02-04 18:38:47687 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41688 }
689 }
690
691 // Add dependence edges between nodes which produce SSA values and their
692 // users.
693 for (auto &idAndNode : nodes) {
694 const Node &node = idAndNode.second;
695 if (!node.loads.empty() || !node.stores.empty())
696 continue;
River Riddle99b87c92019-03-27 21:02:02697 auto *opInst = node.op;
River Riddle35807bc2019-12-23 05:59:55698 for (auto value : opInst->getResults()) {
River Riddle2bdf33c2020-01-11 16:54:04699 for (auto *user : value.getUsers()) {
Chris Lattnerd9b5bc82019-03-25 02:53:05700 SmallVector<AffineForOp, 4> loops;
River Riddle8780d8d2019-05-18 18:09:07701 getLoopIVs(*user, &loops);
MLIR Teama0f3db402019-01-29 17:36:41702 if (loops.empty())
703 continue;
River Riddlef9d91532019-03-27 00:05:09704 assert(forToNodeMap.count(loops[0].getOperation()) > 0);
705 unsigned userLoopNestId = forToNodeMap[loops[0].getOperation()];
MLIR Teama0f3db402019-01-29 17:36:41706 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55707 }
708 }
MLIR Team6892ffb2018-12-20 04:42:55709 }
710
711 // Walk memref access lists and add graph edges between dependent nodes.
712 for (auto &memrefAndList : memrefAccesses) {
713 unsigned n = memrefAndList.second.size();
714 for (unsigned i = 0; i < n; ++i) {
715 unsigned srcId = memrefAndList.second[i];
716 bool srcHasStore =
717 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
718 for (unsigned j = i + 1; j < n; ++j) {
719 unsigned dstId = memrefAndList.second[j];
720 bool dstHasStore =
721 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
722 if (srcHasStore || dstHasStore)
723 addEdge(srcId, dstId, memrefAndList.first);
724 }
725 }
726 }
727 return true;
728}
729
MLIR Team27d067e2019-01-16 17:55:02730// Removes load operations from 'srcLoads' which operate on 'memref', and
731// adds them to 'dstLoads'.
River Riddlee62a6952019-12-23 22:45:01732static void moveLoadsAccessingMemrefTo(Value memref,
River Riddle99b87c92019-03-27 21:02:02733 SmallVectorImpl<Operation *> *srcLoads,
734 SmallVectorImpl<Operation *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02735 dstLoads->clear();
River Riddle99b87c92019-03-27 21:02:02736 SmallVector<Operation *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02737 for (auto *load : *srcLoads) {
Diego Caballeroa45fb192020-05-20 00:16:04738 if (cast<AffineReadOpInterface>(load).getMemRef() == memref)
MLIR Team27d067e2019-01-16 17:55:02739 dstLoads->push_back(load);
740 else
741 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25742 }
MLIR Team27d067e2019-01-16 17:55:02743 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25744}
745
MLIR Team27d067e2019-01-16 17:55:02746// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddle99b87c92019-03-27 21:02:02747static unsigned getInnermostCommonLoopDepth(ArrayRef<Operation *> ops) {
MLIR Team27d067e2019-01-16 17:55:02748 unsigned numOps = ops.size();
749 assert(numOps > 0);
750
Chris Lattnerd9b5bc82019-03-25 02:53:05751 std::vector<SmallVector<AffineForOp, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02752 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
753 for (unsigned i = 0; i < numOps; ++i) {
754 getLoopIVs(*ops[i], &loops[i]);
755 loopDepthLimit =
756 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25757 }
MLIR Team27d067e2019-01-16 17:55:02758
759 unsigned loopDepth = 0;
760 for (unsigned d = 0; d < loopDepthLimit; ++d) {
761 unsigned i;
762 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18763 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02764 break;
MLIR Team27d067e2019-01-16 17:55:02765 }
766 if (i != numOps)
767 break;
768 ++loopDepth;
769 }
770 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25771}
772
MLIR Teamd7c82442019-01-30 23:53:41773// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
774// and 'storeOpInsts' are satisfied.
River Riddle99b87c92019-03-27 21:02:02775static unsigned getMaxLoopDepth(ArrayRef<Operation *> loadOpInsts,
776 ArrayRef<Operation *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41777 // Merge loads and stores into the same array.
River Riddle99b87c92019-03-27 21:02:02778 SmallVector<Operation *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41779 ops.append(storeOpInsts.begin(), storeOpInsts.end());
780
781 // Compute the innermost common loop depth for loads and stores.
782 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
783
784 // Return common loop depth for loads if there are no store ops.
785 if (storeOpInsts.empty())
786 return loopDepth;
787
788 // Check dependences on all pairs of ops in 'ops' and store the minimum
789 // loop depth at which a dependence is satisfied.
790 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
791 auto *srcOpInst = ops[i];
792 MemRefAccess srcAccess(srcOpInst);
793 for (unsigned j = 0; j < e; ++j) {
794 auto *dstOpInst = ops[j];
795 MemRefAccess dstAccess(dstOpInst);
796
797 unsigned numCommonLoops =
798 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
799 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
800 FlatAffineConstraints dependenceConstraints;
801 // TODO(andydavis) Cache dependence analysis results, check cache here.
Andy Davise33e36f2019-06-10 17:50:08802 DependenceResult result = checkMemrefAccessDependence(
803 srcAccess, dstAccess, d, &dependenceConstraints,
804 /*dependenceComponents=*/nullptr);
805 if (hasDependence(result)) {
MLIR Teamd7c82442019-01-30 23:53:41806 // Store minimum loop depth and break because we want the min 'd' at
807 // which there is a dependence.
808 loopDepth = std::min(loopDepth, d - 1);
809 break;
810 }
811 }
812 }
813 }
814 return loopDepth;
815}
816
MLIR Team8f5f2c72019-02-15 17:32:18817// Sinks all sequential loops to the innermost levels (while preserving
818// relative order among them) and moves all parallel loops to the
819// outermost (while again preserving relative order among them).
820// This can increase the loop depth at which we can fuse a slice, since we are
821// pushing loop carried dependence to a greater depth in the loop nest.
822static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
River Riddled5b60ee82019-05-12 01:59:54823 assert(isa<AffineForOp>(node->op));
Andy Davis90d40232019-05-13 13:57:56824 AffineForOp newRootForOp = sinkSequentialLoops(cast<AffineForOp>(node->op));
825 node->op = newRootForOp.getOperation();
MLIR Team8f5f2c72019-02-15 17:32:18826}
827
Uday Bondhugula8be26272019-02-02 01:06:22828// TODO(mlir-team): improve/complete this when we have target data.
River Riddle2666b972019-12-18 18:46:16829static unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
Uday Bondhugula8be26272019-02-02 01:06:22830 auto elementType = memRefType.getElementType();
831
832 unsigned sizeInBits;
River Riddlede5a81b2020-03-02 17:18:45833 if (elementType.isIntOrFloat()) {
Uday Bondhugula8be26272019-02-02 01:06:22834 sizeInBits = elementType.getIntOrFloatBitWidth();
835 } else {
836 auto vectorType = elementType.cast<VectorType>();
837 sizeInBits =
838 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
839 }
840 return llvm::divideCeil(sizeInBits, 8);
841}
842
MLIR Teamc4237ae2019-01-18 16:56:27843// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:18844// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:52845// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
846// TODO(bondhugula): consider refactoring the common code from generateDma and
847// this one.
River Riddlee62a6952019-12-23 22:45:01848static Value createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst,
849 unsigned dstLoopDepth,
850 Optional<unsigned> fastMemorySpace,
851 uint64_t localBufSizeThreshold) {
River Riddlef9d91532019-03-27 00:05:09852 auto *forInst = forOp.getOperation();
River Riddle5052bd82019-02-02 00:42:18853
854 // Create builder to insert alloc op just before 'forOp'.
River Riddlef1b848e2019-06-05 02:18:23855 OpBuilder b(forInst);
MLIR Teamc4237ae2019-01-18 16:56:27856 // Builder to create constants at the top level.
River Riddlece502af2019-07-08 18:20:26857 OpBuilder top(forInst->getParentOfType<FuncOp>().getBody());
MLIR Teamc4237ae2019-01-18 16:56:27858 // Create new memref type based on slice bounds.
Diego Caballeroa45fb192020-05-20 00:16:04859 auto oldMemRef = cast<AffineWriteOpInterface>(srcStoreOpInst).getMemRef();
River Riddle2bdf33c2020-01-11 16:54:04860 auto oldMemRefType = oldMemRef.getType().cast<MemRefType>();
MLIR Teamc4237ae2019-01-18 16:56:27861 unsigned rank = oldMemRefType.getRank();
862
Uday Bondhugula94a03f82019-01-22 21:58:52863 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:44864 MemRefRegion region(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:47865 bool validRegion = succeeded(region.compute(srcStoreOpInst, dstLoopDepth));
MLIR Teamd42ef782019-03-04 19:01:25866 (void)validRegion;
867 assert(validRegion && "unexpected memref region failure");
River Riddle6859f332019-01-23 22:39:45868 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:27869 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:52870 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:27871 lbs.reserve(rank);
872 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:52873 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:27874 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:44875 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:22876 assert(numElements.hasValue() &&
877 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:27878
Uday Bondhugula0f504142019-02-04 21:48:44879 const FlatAffineConstraints *cst = region.getConstraints();
Kazuaki Ishizaki8bfedb32019-10-20 07:11:03880 // 'outerIVs' holds the values that this memory region is symbolic/parametric
Uday Bondhugula94a03f82019-01-22 21:58:52881 // on; this would correspond to loop IVs surrounding the level at which the
882 // slice is being materialized.
River Riddlee62a6952019-12-23 22:45:01883 SmallVector<Value, 8> outerIVs;
Uday Bondhugula94a03f82019-01-22 21:58:52884 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
885
886 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:27887 SmallVector<AffineExpr, 4> offsets;
888 offsets.reserve(rank);
889 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:52890 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
891
MLIR Teamc4237ae2019-01-18 16:56:27892 AffineExpr offset = top.getAffineConstantExpr(0);
893 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
894 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
895 }
Uday Bondhugula94a03f82019-01-22 21:58:52896 assert(lbDivisors[d] > 0);
897 offset =
898 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:27899 offsets.push_back(offset);
900 }
901
902 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
903 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:22904 uint64_t bufSize =
905 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
906 unsigned newMemSpace;
Uday Bondhugulad4b3ff12019-02-27 00:10:19907 if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
Uday Bondhugula8be26272019-02-02 01:06:22908 newMemSpace = fastMemorySpace.getValue();
909 } else {
910 newMemSpace = oldMemRefType.getMemorySpace();
911 }
River Riddle2acc2202019-10-18 03:08:01912 auto newMemRefType = MemRefType::get(newShape, oldMemRefType.getElementType(),
913 {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:27914
Uday Bondhugulaaec53442020-06-23 20:52:03915 // Create new private memref for fused loop 'forOp'. 'newShape' is always
916 // a constant shape.
MLIR Teama0f3db402019-01-29 17:36:41917 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
918 // consumer loop nests to reduce their live range. Currently they are added
919 // at the beginning of the function, because loop nests can be reordered
920 // during the fusion pass.
Uday Bondhugulaaec53442020-06-23 20:52:03921 Value newMemRef = top.create<AllocOp>(forOp.getLoc(), newMemRefType);
MLIR Teamc4237ae2019-01-18 16:56:27922
923 // Build an AffineMap to remap access functions based on lower bound offsets.
924 SmallVector<AffineExpr, 4> remapExprs;
925 remapExprs.reserve(rank);
926 unsigned zeroOffsetCount = 0;
927 for (unsigned i = 0; i < rank; i++) {
928 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
929 if (constExpr.getValue() == 0)
930 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:52931 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
932
933 auto remapExpr =
934 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
935 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:27936 }
MLIR Team5a91b982019-05-29 21:56:41937 auto indexRemap = zeroOffsetCount == rank
938 ? AffineMap()
Jeremy Bruestle9f3ab922020-04-15 18:12:47939 : AffineMap::get(outerIVs.size() + rank, 0, remapExprs,
940 forOp.getContext());
MLIR Teamc4237ae2019-01-18 16:56:27941 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugulaaa2cee92019-08-28 00:56:25942 LogicalResult res =
Uday Bondhugula94a03f82019-01-22 21:58:52943 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
944 /*extraOperands=*/outerIVs,
Uday Bondhugula727a50a2019-09-18 18:25:33945 /*symbolOperands=*/{},
River Riddleaf1abcc2019-03-25 18:13:31946 /*domInstFilter=*/&*forOp.getBody()->begin());
Uday Bondhugulaaa2cee92019-08-28 00:56:25947 assert(succeeded(res) &&
948 "replaceAllMemrefUsesWith should always succeed here");
949 (void)res;
MLIR Teamc4237ae2019-01-18 16:56:27950 return newMemRef;
951}
952
Diego Caballero34510552019-10-09 17:36:54953// Checks if node 'srcId' can be safely fused into node 'dstId'. Node 'srcId'
954// may write to multiple memrefs but it is required that only one of them,
Diego Caballero330d1ff2019-12-03 14:09:21955// 'srcLiveOutStoreOp', has output edges.
Diego Caballero34510552019-10-09 17:36:54956// Returns true if 'dstNode's read/write region to 'memref' is a super set of
Diego Caballero330d1ff2019-12-03 14:09:21957// 'srcNode's write region to 'memref' and 'srcId' has only one output edge.
MLIR Team58aa3832019-02-16 01:12:19958// TODO(andydavis) Generalize this to handle more live in/out cases.
Diego Caballeroa45fb192020-05-20 00:16:04959static bool
960canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
961 AffineWriteOpInterface srcLiveOutStoreOp,
962 MemRefDependenceGraph *mdg) {
Diego Caballero34510552019-10-09 17:36:54963 assert(srcLiveOutStoreOp && "Expected a valid store op");
MLIR Team58aa3832019-02-16 01:12:19964 auto *dstNode = mdg->getNode(dstId);
River Riddlee62a6952019-12-23 22:45:01965 Value memref = srcLiveOutStoreOp.getMemRef();
Diego Caballero330d1ff2019-12-03 14:09:21966 // Return false if 'srcNode' has more than one output edge on 'memref'.
967 if (mdg->getOutEdgeCount(srcId, memref) > 1)
968 return false;
MLIR Team58aa3832019-02-16 01:12:19969
Diego Caballero34510552019-10-09 17:36:54970 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOp' on 'memref'.
971 MemRefRegion srcWriteRegion(srcLiveOutStoreOp.getLoc());
972 if (failed(srcWriteRegion.compute(srcLiveOutStoreOp, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:25973 LLVM_DEBUG(llvm::dbgs()
974 << "Unable to compute MemRefRegion for source operation\n.");
975 return false;
976 }
MLIR Team58aa3832019-02-16 01:12:19977 SmallVector<int64_t, 4> srcShape;
978 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
Diego Caballero34510552019-10-09 17:36:54979 // by 'srcStoreOp' at depth 'dstLoopDepth'.
MLIR Team58aa3832019-02-16 01:12:19980 Optional<int64_t> srcNumElements =
981 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
982 if (!srcNumElements.hasValue())
983 return false;
984
Andy Davis7c1fc9e2019-04-02 13:37:40985 // Compute MemRefRegion 'dstRegion' for 'dstStore/LoadOpInst' on 'memref'.
MLIR Team9d9675f2019-03-28 21:54:49986 // TODO(andydavis) Compute 'unionboundingbox' of all write regions (one for
987 // each store op in 'dstStoreOps').
Andy Davis7c1fc9e2019-04-02 13:37:40988 SmallVector<Operation *, 2> dstStoreOps;
989 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
990 SmallVector<Operation *, 2> dstLoadOps;
991 dstNode->getLoadOpsForMemref(memref, &dstLoadOps);
992
993 auto *dstOpInst = dstStoreOps.empty() ? dstLoadOps[0] : dstStoreOps[0];
994 MemRefRegion dstRegion(dstOpInst->getLoc());
995 if (failed(dstRegion.compute(dstOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:25996 LLVM_DEBUG(llvm::dbgs()
997 << "Unable to compute MemRefRegion for dest operation\n.");
998 return false;
999 }
MLIR Team58aa3832019-02-16 01:12:191000 SmallVector<int64_t, 4> dstShape;
Andy Davis7c1fc9e2019-04-02 13:37:401001 // Query 'dstRegion' for 'dstShape' and 'dstNumElements'.
1002 // by 'dstOpInst' at depth 'dstLoopDepth'.
MLIR Team58aa3832019-02-16 01:12:191003 Optional<int64_t> dstNumElements =
Andy Davis7c1fc9e2019-04-02 13:37:401004 dstRegion.getConstantBoundingSizeAndShape(&dstShape);
MLIR Team58aa3832019-02-16 01:12:191005 if (!dstNumElements.hasValue())
1006 return false;
1007
1008 // Return false if write region is not a superset of 'srcNodes' write
1009 // region to 'memref'.
1010 // TODO(andydavis) Check the shape and lower bounds here too.
1011 if (srcNumElements != dstNumElements)
1012 return false;
1013 return true;
1014}
1015
MLIR Team27d067e2019-01-16 17:55:021016// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411017// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
MLIR Teamd038e342019-03-01 19:50:251018// The argument 'srcStoreOpInst' is used to calculate the storage reduction on
1019// the memref being produced and consumed, which is an input to the cost model.
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031020// For producer-consumer fusion, 'srcStoreOpInst' will be the same as
MLIR Teamd038e342019-03-01 19:50:251021// 'srcOpInst', as we are slicing w.r.t to that producer.
1022// For input-reuse fusion, 'srcOpInst' will be the src loop nest LoadOp which
1023// reads from the same memref as dst loop nest load ops, and 'srcStoreOpInst'
1024// will be the unique store op in the src node, which will be used to check
1025// that the write region is the same after input-reuse fusion.
Uday Bondhugulab4a14432019-01-26 00:00:501026// Returns true if it is profitable to fuse the candidate loop nests. Returns
1027// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1028// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251029// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021030// *) Computes the backward computation slice at 'srcOpInst'. This
1031// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251032// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021033// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251034// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1035// loop nest is the total number of dynamic operation instances in the loop
1036// nest).
1037// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021038// loop nest at various values of dst loop depth, attempting to fuse
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031039// the largest computation slice at the maximal dst loop depth (closest to
1040// the load) to minimize reuse distance and potentially enable subsequent
MLIR Team27d067e2019-01-16 17:55:021041// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411042// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021043// the same memref as is written by 'srcOpInst', then the union of slice
1044// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501045// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251046// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021047// NOTE: We attempt to maximize the dst loop depth, but there are cases
1048// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251049// loop (within the src computation slice) at a depth which results in
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031050// excessive recomputation (see unit tests for examples).
MLIR Team38c2fe32019-01-14 19:26:251051// *) Compares the total cost of the unfused loop nests to the min cost fused
1052// loop nest computed in the previous step, and returns true if the latter
1053// is lower.
River Riddle99b87c92019-03-27 21:02:021054static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
1055 ArrayRef<Operation *> dstLoadOpInsts,
1056 ArrayRef<Operation *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251057 ComputationSliceState *sliceState,
River Riddle400ad6f2020-04-08 19:57:021058 unsigned *dstLoopDepth, bool maximalFusion,
1059 double computeToleranceThreshold) {
Uday Bondhugula06d21d92019-01-25 01:01:491060 LLVM_DEBUG({
Uday Bondhugulaca09dab2020-05-06 06:17:161061 llvm::dbgs() << "Checking whether fusion is profitable between src op:\n";
1062 llvm::dbgs() << ' ' << *srcOpInst << " and destination op(s)\n";
MLIR Teamd7c82442019-01-30 23:53:411063 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191064 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491065 };
1066 });
Uday Bondhugula864d9e02019-01-23 17:16:241067
MLIR Team38c2fe32019-01-14 19:26:251068 // Compute cost of sliced and unsliced src loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051069 SmallVector<AffineForOp, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021070 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251071 unsigned numSrcLoopIVs = srcLoopIVs.size();
1072
1073 // Walk src loop nest and collect stats.
1074 LoopNestStats srcLoopNestStats;
Andy Davis59b68142019-06-18 15:52:091075 if (!getLoopNestStats(srcLoopIVs[0], &srcLoopNestStats))
MLIR Team38c2fe32019-01-14 19:26:251076 return false;
Andy Davis59b68142019-06-18 15:52:091077
MLIR Team38c2fe32019-01-14 19:26:251078 // Compute cost of dst loop nest.
Chris Lattnerd9b5bc82019-03-25 02:53:051079 SmallVector<AffineForOp, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411080 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251081
1082 LoopNestStats dstLoopNestStats;
Andy Davis59b68142019-06-18 15:52:091083 if (!getLoopNestStats(dstLoopIVs[0], &dstLoopNestStats))
MLIR Team38c2fe32019-01-14 19:26:251084 return false;
1085
MLIR Teamd7c82442019-01-30 23:53:411086 // Compute the maximum loop depth at which we can can insert the src slice
MLIR Teamd038e342019-03-01 19:50:251087 // and still satisfy dest loop nest dependences, for producer-consumer fusion.
1088 unsigned maxDstLoopDepth =
1089 (srcOpInst == srcStoreOpInst)
1090 ? getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts)
1091 : dstLoopIVs.size();
MLIR Teamc1ff9e82019-03-06 04:33:301092 if (maxDstLoopDepth == 0) {
1093 LLVM_DEBUG(llvm::dbgs() << "Can't fuse: maxDstLoopDepth == 0 .\n");
MLIR Team27d067e2019-01-16 17:55:021094 return false;
MLIR Teamc1ff9e82019-03-06 04:33:301095 }
MLIR Team27d067e2019-01-16 17:55:021096
1097 // Search for min cost value for 'dstLoopDepth'. At each value of
1098 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1099 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1100 // of these bounds). Next the union slice bounds are used to calculate
1101 // the cost of the slice and the cost of the slice inserted into the dst
1102 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241103 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
MLIR Teamd038e342019-03-01 19:50:251104 double maxStorageReduction = 0.0;
Uday Bondhugula864d9e02019-01-23 17:16:241105 Optional<uint64_t> sliceMemEstimate = None;
1106
MLIR Team27d067e2019-01-16 17:55:021107 SmallVector<ComputationSliceState, 4> sliceStates;
1108 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241109 // The best loop depth at which to materialize the slice.
1110 Optional<unsigned> bestDstLoopDepth = None;
1111
1112 // Compute op instance count for the src loop nest without iteration slicing.
Andy Davis59b68142019-06-18 15:52:091113 uint64_t srcLoopNestCost = getComputeCost(srcLoopIVs[0], srcLoopNestStats);
Uday Bondhugula864d9e02019-01-23 17:16:241114
MLIR Teamb9dde912019-02-06 19:01:101115 // Compute src loop nest write region size.
MLIR Teamd038e342019-03-01 19:50:251116 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471117 if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) {
MLIR Teamd42ef782019-03-04 19:01:251118 LLVM_DEBUG(llvm::dbgs()
River Riddle99b87c92019-03-27 21:02:021119 << "Unable to compute MemRefRegion for source operation\n.");
MLIR Teamd42ef782019-03-04 19:01:251120 return false;
1121 }
1122
MLIR Teamb9dde912019-02-06 19:01:101123 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1124 srcWriteRegion.getRegionSize();
1125 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1126 return false;
1127 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1128
Uday Bondhugula864d9e02019-01-23 17:16:241129 // Compute op instance count for the src loop nest.
Andy Davis59b68142019-06-18 15:52:091130 uint64_t dstLoopNestCost = getComputeCost(dstLoopIVs[0], dstLoopNestStats);
MLIR Team27d067e2019-01-16 17:55:021131
MLIR Teamb9dde912019-02-06 19:01:101132 // Evaluate all depth choices for materializing the slice in the destination
1133 // loop nest.
MLIR Team27d067e2019-01-16 17:55:021134 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
MLIR Teamc1ff9e82019-03-06 04:33:301135 // Compute the union of slice bounds of all ops in 'dstLoadOpInsts'.
Andy Davis1de0f972019-05-29 21:02:141136 if (failed(mlir::computeSliceUnion({srcOpInst}, dstLoadOpInsts,
Andy Davis898cf0e2019-06-17 16:59:351137 /*loopDepth=*/i,
1138 /*numCommonLoops=*/0,
1139 /*isBackwardSlice=*/true,
Andy Davis1de0f972019-05-29 21:02:141140 &sliceStates[i - 1]))) {
MLIR Teamc1ff9e82019-03-06 04:33:301141 LLVM_DEBUG(llvm::dbgs()
Andy Davis1de0f972019-05-29 21:02:141142 << "computeSliceUnion failed for loopDepth: " << i << "\n");
MLIR Teamc1ff9e82019-03-06 04:33:301143 continue;
MLIR Team38c2fe32019-01-14 19:26:251144 }
MLIR Teamc1ff9e82019-03-06 04:33:301145
Andy Davis59b68142019-06-18 15:52:091146 int64_t fusedLoopNestComputeCost;
1147 if (!getFusionComputeCost(srcLoopIVs[0], srcLoopNestStats, dstLoopIVs[0],
1148 dstLoopNestStats, &sliceStates[i - 1],
1149 &fusedLoopNestComputeCost)) {
1150 LLVM_DEBUG(llvm::dbgs() << "Unable to compute fusion compute cost.\n.");
Uday Bondhugula864d9e02019-01-23 17:16:241151 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301152 }
Uday Bondhugula864d9e02019-01-23 17:16:241153
Uday Bondhugula864d9e02019-01-23 17:16:241154 double additionalComputeFraction =
1155 fusedLoopNestComputeCost /
1156 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1157 1;
1158
Amit Sabne70a416d2019-04-09 16:17:401159 // Determine what the slice write MemRefRegion would be, if the src loop
MLIR Teamb9dde912019-02-06 19:01:101160 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1161 // nest at loop depth 'i'
MLIR Teamd038e342019-03-01 19:50:251162 MemRefRegion sliceWriteRegion(srcStoreOpInst->getLoc());
River Riddle1e55ae12019-03-08 06:14:471163 if (failed(sliceWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0,
1164 &sliceStates[i - 1]))) {
MLIR Teamc1ff9e82019-03-06 04:33:301165 LLVM_DEBUG(llvm::dbgs()
1166 << "Failed to compute slice write region at loopDepth: " << i
1167 << "\n");
MLIR Teamd42ef782019-03-04 19:01:251168 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301169 }
MLIR Teamd42ef782019-03-04 19:01:251170
MLIR Teamb9dde912019-02-06 19:01:101171 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1172 sliceWriteRegion.getRegionSize();
1173 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
MLIR Teamc1ff9e82019-03-06 04:33:301174 maybeSliceWriteRegionSizeBytes.getValue() == 0) {
1175 LLVM_DEBUG(llvm::dbgs()
1176 << "Failed to get slice write region size at loopDepth: " << i
1177 << "\n");
MLIR Teamb9dde912019-02-06 19:01:101178 continue;
MLIR Teamc1ff9e82019-03-06 04:33:301179 }
MLIR Teamb9dde912019-02-06 19:01:101180 int64_t sliceWriteRegionSizeBytes =
1181 maybeSliceWriteRegionSizeBytes.getValue();
1182
MLIR Teamd038e342019-03-01 19:50:251183 // If we are fusing for reuse, check that write regions remain the same.
1184 // TODO(andydavis) Write region check should check sizes and offsets in
1185 // each dimension, so that we are sure they are covering the same memref
1186 // region. Also, move this out to a isMemRefRegionSuperSet helper function.
1187 if (srcOpInst != srcStoreOpInst &&
1188 sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes)
1189 continue;
1190
MLIR Teamb9dde912019-02-06 19:01:101191 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1192 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241193
Uday Bondhugula06d21d92019-01-25 01:01:491194 LLVM_DEBUG({
1195 std::stringstream msg;
1196 msg << " evaluating fusion profitability at depth : " << i << "\n"
Uday Bondhugulad4b3ff12019-02-27 00:10:191197 << std::fixed << std::setprecision(2)
1198 << " additional compute fraction: "
Uday Bondhugula06d21d92019-01-25 01:01:491199 << 100.0 * additionalComputeFraction << "%\n"
1200 << " storage reduction factor: " << storageReduction << "x\n"
1201 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191202 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1203 << " slice write region size: " << sliceWriteRegionSizeBytes
1204 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491205 llvm::dbgs() << msg.str();
1206 });
Uday Bondhugula864d9e02019-01-23 17:16:241207
Uday Bondhugula864d9e02019-01-23 17:16:241208 // TODO(b/123247369): This is a placeholder cost model.
1209 // Among all choices that add an acceptable amount of redundant computation
1210 // (as per computeToleranceThreshold), we will simply pick the one that
1211 // reduces the intermediary size the most.
1212 if ((storageReduction > maxStorageReduction) &&
Uday Bondhugulace7e59532019-03-08 17:21:521213 (maximalFusion ||
Uday Bondhugula864d9e02019-01-23 17:16:241214 (additionalComputeFraction < computeToleranceThreshold))) {
1215 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021216 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241217 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101218 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251219 }
1220 }
1221
Uday Bondhugula864d9e02019-01-23 17:16:241222 // A simple cost model: fuse if it reduces the memory footprint. If
1223 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251224
Uday Bondhugulace7e59532019-03-08 17:21:521225 if (!maximalFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191226 LLVM_DEBUG(
1227 llvm::dbgs()
1228 << "All fusion choices involve more than the threshold amount of "
1229 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251230 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241231 }
1232
MLIR Teamd42ef782019-03-04 19:01:251233 if (!bestDstLoopDepth.hasValue()) {
1234 LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n");
1235 return false;
1236 }
Uday Bondhugula864d9e02019-01-23 17:16:241237
1238 // Set dstLoopDepth based on best values from search.
1239 *dstLoopDepth = bestDstLoopDepth.getValue();
1240
1241 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491242 llvm::dbgs() << " LoopFusion fusion stats:"
1243 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241244 << "\n src loop nest compute cost: " << srcLoopNestCost
1245 << "\n dst loop nest compute cost: " << dstLoopNestCost
1246 << "\n fused loop nest compute cost: "
1247 << minFusedLoopNestComputeCost << "\n");
1248
River Riddle5052bd82019-02-02 00:42:181249 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1250 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241251
1252 Optional<double> storageReduction = None;
1253
Uday Bondhugulace7e59532019-03-08 17:21:521254 if (!maximalFusion) {
Uday Bondhugula864d9e02019-01-23 17:16:241255 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1256 LLVM_DEBUG(
1257 llvm::dbgs()
1258 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1259 return false;
1260 }
1261
1262 auto srcMemSizeVal = srcMemSize.getValue();
1263 auto dstMemSizeVal = dstMemSize.getValue();
1264
1265 assert(sliceMemEstimate.hasValue() && "expected value");
Uday Bondhugula864d9e02019-01-23 17:16:241266 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1267
1268 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1269 << " dst mem: " << dstMemSizeVal << "\n"
1270 << " fused mem: " << fusedMem << "\n"
1271 << " slice mem: " << sliceMemEstimate << "\n");
1272
Jacques Pienaar2fe8ae42019-05-04 02:48:571273 if (static_cast<long>(fusedMem) > srcMemSizeVal + dstMemSizeVal) {
Uday Bondhugula864d9e02019-01-23 17:16:241274 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1275 return false;
1276 }
1277 storageReduction =
1278 100.0 *
1279 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1280 }
1281
1282 double additionalComputeFraction =
1283 100.0 * (minFusedLoopNestComputeCost /
1284 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1285 1);
MLIR Team5c5739d2019-01-25 06:27:401286 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491287 LLVM_DEBUG({
1288 std::stringstream msg;
1289 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591290 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491291 << "% redundant computation and a ";
1292 msg << (storageReduction.hasValue()
1293 ? std::to_string(storageReduction.getValue())
1294 : "<unknown>");
1295 msg << "% storage reduction.\n";
1296 llvm::dbgs() << msg.str();
1297 });
Uday Bondhugula864d9e02019-01-23 17:16:241298
MLIR Team27d067e2019-01-16 17:55:021299 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241300 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021301 sliceState->lbs = bestSliceState->lbs;
1302 sliceState->ubs = bestSliceState->ubs;
1303 sliceState->lbOperands = bestSliceState->lbOperands;
1304 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241305
MLIR Team27d067e2019-01-16 17:55:021306 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251307 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171308 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021309 canonicalizeMapAndOperands(&sliceState->lbs[i],
1310 &sliceState->lbOperands[i]);
1311 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171312 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021313 canonicalizeMapAndOperands(&sliceState->ubs[i],
1314 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251315 }
1316 }
1317 return true;
1318}
1319
River Riddle2666b972019-12-18 18:46:161320namespace {
1321
MLIR Teamd038e342019-03-01 19:50:251322// GreedyFusion greedily fuses loop nests which have a producer/consumer or
1323// input-reuse relationship on a memref, with the goal of improving locality.
MLIR Teamf28e4df2018-11-01 14:26:001324//
MLIR Teamd038e342019-03-01 19:50:251325// The steps of the producer-consumer fusion algorithm are as follows:
MLIR Team3b692302018-12-17 17:57:141326//
MLIR Team6892ffb2018-12-20 04:42:551327// *) A worklist is initialized with node ids from the dependence graph.
1328// *) For each node id in the worklist:
Amit Sabne70a416d2019-04-09 16:17:401329// *) Pop an AffineForOp of the worklist. This 'dstAffineForOp' will be a
River Riddle5052bd82019-02-02 00:42:181330// candidate destination AffineForOp into which fusion will be attempted.
1331// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141332// *) For each LoadOp in 'dstLoadOps' do:
Amit Sabne70a416d2019-04-09 16:17:401333// *) Look up dependent loop nests which have a single store op to the same
MLIR Teamd038e342019-03-01 19:50:251334// memref.
1335// *) Check if dependences would be violated by the fusion.
MLIR Team6892ffb2018-12-20 04:42:551336// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141337// bounds to be functions of 'dstLoopNest' IVs and symbols.
1338// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
MLIR Teamd038e342019-03-01 19:50:251339// at a loop depth determined by the cost model in 'isFusionProfitable'.
River Riddle99b87c92019-03-27 21:02:021340// *) Add the newly fused load/store operations to the state,
Amit Sabne70a416d2019-04-09 16:17:401341// and also add newly fused load ops to 'dstLoopOps' to be considered
MLIR Team3b692302018-12-17 17:57:141342// as fusion dst load ops in another iteration.
1343// *) Remove old src loop nest and its associated state.
1344//
MLIR Teamd038e342019-03-01 19:50:251345// The steps of the input-reuse fusion algorithm are as follows:
1346//
1347// *) Initialize 'worklist' with node ids from the dependence graph.
1348// *) For each 'dstNode' in the worklist:
1349// *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which
1350// loads from the same memref, but which has no dependence paths to/from.
1351// *) Get a computation slice of 'sibLoopNest', which adjusts its loop
1352// bounds to be functions of 'dstLoopNest' IVs and symbols.
1353// *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest',
1354// at a loop depth determined by the cost model in 'isFusionProfitable'.
1355// This function also checks that the memref write region of 'sibLoopNest',
1356// is preserved in the fused loop nest.
1357// *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'.
1358//
River Riddle99b87c92019-03-27 21:02:021359// Given a graph where top-level operations are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141360// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551361// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141362//
MLIR Team6892ffb2018-12-20 04:42:551363// This greedy algorithm is not 'maximal' due to the current restriction of
1364// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141365//
1366// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551367struct GreedyFusion {
1368public:
MLIR Teamd038e342019-03-01 19:50:251369 // The data dependence graph to traverse during fusion.
MLIR Team6892ffb2018-12-20 04:42:551370 MemRefDependenceGraph *mdg;
MLIR Teamd038e342019-03-01 19:50:251371 // Worklist of graph nodes visited during the fusion pass.
MLIR Teama78edcd2019-02-05 14:57:081372 SmallVector<unsigned, 8> worklist;
MLIR Teamd038e342019-03-01 19:50:251373 // Set of graph nodes which are present on the worklist.
MLIR Teama78edcd2019-02-05 14:57:081374 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamd038e342019-03-01 19:50:251375 // Parameter for local buffer size threshold.
1376 unsigned localBufSizeThreshold;
1377 // Parameter for fast memory space.
1378 Optional<unsigned> fastMemorySpace;
Uday Bondhugulace7e59532019-03-08 17:21:521379 // If true, ignore any additional (redundant) computation tolerance threshold
1380 // that would have prevented fusion.
1381 bool maximalFusion;
River Riddle400ad6f2020-04-08 19:57:021382 // The amount of additional computation that is tolerated while fusing
1383 // pair-wise as a fraction of the total computation.
1384 double computeToleranceThreshold;
MLIR Teamf28e4df2018-11-01 14:26:001385
MLIR Teamd038e342019-03-01 19:50:251386 using Node = MemRefDependenceGraph::Node;
1387
1388 GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold,
River Riddle400ad6f2020-04-08 19:57:021389 Optional<unsigned> fastMemorySpace, bool maximalFusion,
1390 double computeToleranceThreshold)
MLIR Teamd038e342019-03-01 19:50:251391 : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold),
River Riddle400ad6f2020-04-08 19:57:021392 fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion),
1393 computeToleranceThreshold(computeToleranceThreshold) {}
MLIR Teamd038e342019-03-01 19:50:251394
1395 // Initializes 'worklist' with nodes from 'mdg'
1396 void init() {
MLIR Teama78edcd2019-02-05 14:57:081397 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1398 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Teamd038e342019-03-01 19:50:251399 worklist.clear();
1400 worklistSet.clear();
1401 for (auto &idAndNode : mdg->nodes) {
1402 const Node &node = idAndNode.second;
1403 worklist.push_back(node.id);
1404 worklistSet.insert(node.id);
1405 }
MLIR Team6892ffb2018-12-20 04:42:551406 }
MLIR Team3b692302018-12-17 17:57:141407
MLIR Teamd038e342019-03-01 19:50:251408 // Run the GreedyFusion pass.
1409 // *) First pass through the nodes fuses single-use producer nodes into their
1410 // unique consumer.
1411 // *) Second pass fuses sibling nodes which share no dependence edges.
1412 // *) Third pass fuses any remaining producer nodes into their users.
1413 void run() {
MLIR Teamc1ff9e82019-03-06 04:33:301414 // TODO(andydavis) Run this repeatedly until a fixed-point is reached.
MLIR Teamd038e342019-03-01 19:50:251415 fuseProducerConsumerNodes(/*maxSrcUserCount=*/1);
1416 fuseSiblingNodes();
1417 fuseProducerConsumerNodes(
1418 /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max());
1419 eraseUnusedMemRefAllocations();
1420 }
1421
1422 void fuseProducerConsumerNodes(unsigned maxSrcUserCount) {
1423 init();
MLIR Team3b692302018-12-17 17:57:141424 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551425 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141426 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081427 worklistSet.erase(dstId);
1428
MLIR Team6892ffb2018-12-20 04:42:551429 // Skip if this node was removed (fused into another node).
1430 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141431 continue;
MLIR Team6892ffb2018-12-20 04:42:551432 // Get 'dstNode' into which to attempt fusion.
1433 auto *dstNode = mdg->getNode(dstId);
1434 // Skip if 'dstNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541435 if (!isa<AffineForOp>(dstNode->op))
MLIR Team3b692302018-12-17 17:57:141436 continue;
MLIR Team8f5f2c72019-02-15 17:32:181437 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1438 // while preserving relative order. This can increase the maximum loop
1439 // depth at which we can fuse a slice of a producer loop nest into a
1440 // consumer loop nest.
1441 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141442
River Riddle99b87c92019-03-27 21:02:021443 SmallVector<Operation *, 4> loads = dstNode->loads;
1444 SmallVector<Operation *, 4> dstLoadOpInsts;
River Riddlee62a6952019-12-23 22:45:011445 DenseSet<Value> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551446 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021447 // Get memref of load on top of the stack.
Diego Caballeroa45fb192020-05-20 00:16:041448 auto memref = cast<AffineReadOpInterface>(loads.back()).getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271449 if (visitedMemrefs.count(memref) > 0)
1450 continue;
1451 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021452 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1453 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551454 // Skip if no input edges along which to fuse.
1455 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141456 continue;
Amit Sabne70a416d2019-04-09 16:17:401457 // Iterate through in-edges for 'dstId' and src node id for any
MLIR Team1e851912019-01-31 00:01:461458 // edges on 'memref'.
1459 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551460 for (auto &srcEdge : mdg->inEdges[dstId]) {
1461 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411462 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551463 continue;
MLIR Team1e851912019-01-31 00:01:461464 srcNodeIds.push_back(srcEdge.id);
1465 }
1466 for (unsigned srcId : srcNodeIds) {
1467 // Skip if this node was removed (fused into another node).
1468 if (mdg->nodes.count(srcId) == 0)
1469 continue;
1470 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1471 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551472 // Skip if 'srcNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541473 if (!isa<AffineForOp>(srcNode->op))
MLIR Team6892ffb2018-12-20 04:42:551474 continue;
Diego Caballero34510552019-10-09 17:36:541475 // Skip if 'srcNode' has more than one live-out store to a
1476 // function-local memref.
1477 // TODO(andydavis) Support more generic multi-output src loop nests
1478 // fusion.
1479 auto srcStoreOp = mdg->getUniqueOutgoingStore(srcNode);
Andy Davis68a8da42019-11-18 19:20:031480 if (!srcStoreOp) {
1481 // Get the src store op at the deepest loop depth.
1482 // We will use 'LoopFusionUtils::canFuseLoops' to check fusion
1483 // feasibility for loops with multiple stores.
1484 unsigned maxLoopDepth = 0;
1485 for (auto *op : srcNode->stores) {
Diego Caballeroa45fb192020-05-20 00:16:041486 auto storeOp = cast<AffineWriteOpInterface>(op);
Andy Davis68a8da42019-11-18 19:20:031487 if (storeOp.getMemRef() != memref) {
1488 srcStoreOp = nullptr;
1489 break;
1490 }
Uday Bondhugula42ada5f2020-04-13 04:48:101491 unsigned loopDepth = getNestingDepth(storeOp);
Andy Davis68a8da42019-11-18 19:20:031492 if (loopDepth > maxLoopDepth) {
1493 maxLoopDepth = loopDepth;
1494 srcStoreOp = storeOp;
1495 }
1496 }
1497 if (!srcStoreOp)
1498 continue;
1499 }
1500
Diego Caballero34510552019-10-09 17:36:541501 // Unique outgoing store found must write to 'memref' since 'memref'
1502 // is the one that established the producer-consumer relationship
1503 // between 'srcNode' and 'dstNode'.
1504 assert(srcStoreOp.getMemRef() == memref &&
1505 "Found store to unexpected memref");
Uday Bondhugula864d9e02019-01-23 17:16:241506
MLIR Team58aa3832019-02-16 01:12:191507 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1508 // and cannot be fused.
1509 bool writesToLiveInOrOut =
1510 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1511 if (writesToLiveInOrOut &&
Diego Caballero34510552019-10-09 17:36:541512 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, srcStoreOp, mdg))
MLIR Teamd7c82442019-01-30 23:53:411513 continue;
1514
Kazuaki Ishizaki84a61822019-12-06 13:58:591515 // Don't create a private memref if 'writesToLiveInOrOut'.
Andy Davis68a8da42019-11-18 19:20:031516 bool createPrivateMemref = !writesToLiveInOrOut;
Kazuaki Ishizaki84a61822019-12-06 13:58:591517 // Don't create a private memref if 'srcNode' has in edges on
1518 // 'memref', or if 'dstNode' has out edges on 'memref'.
Andy Davis68a8da42019-11-18 19:20:031519 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) > 0 ||
1520 mdg->getOutEdgeCount(dstNode->id, memref) > 0) {
1521 createPrivateMemref = false;
1522 }
1523
MLIR Teamd038e342019-03-01 19:50:251524 // Skip if 'srcNode' out edge count on 'memref' > 'maxSrcUserCount'.
1525 if (mdg->getOutEdgeCount(srcNode->id, memref) > maxSrcUserCount)
1526 continue;
1527
River Riddle99b87c92019-03-27 21:02:021528 // Compute an operation list insertion point for the fused loop
MLIR Teama0f3db402019-01-29 17:36:411529 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:021530 Operation *insertPointInst =
MLIR Teama78edcd2019-02-05 14:57:081531 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411532 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551533 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241534
Andy Davis68a8da42019-11-18 19:20:031535 // Compute the innermost common loop depth for dstNode loads/stores.
1536 SmallVector<Operation *, 2> dstOps(dstNode->loads.begin(),
1537 dstNode->loads.end());
1538 dstOps.append(dstNode->stores.begin(), dstNode->stores.end());
1539 unsigned dstLoopDepthTest = getInnermostCommonLoopDepth(dstOps);
1540 // Check the feasibility of fusing src loop nest into dst loop nest
1541 // at loop depths in range [1, dstLoopDepthTest].
1542 // TODO(andydavis) Use slice union computation and union of memref
1543 // read/write regions to cost model and fusion.
1544 bool canFuse = false;
1545 for (unsigned i = 1; i <= dstLoopDepthTest; ++i) {
1546 ComputationSliceState sliceUnion;
1547 FusionResult result = mlir::canFuseLoops(
1548 cast<AffineForOp>(srcNode->op), cast<AffineForOp>(dstNode->op),
1549 /*dstLoopDepth=*/i, &sliceUnion);
1550 if (result.value == FusionResult::Success)
1551 canFuse = true;
1552 }
1553
1554 // Skip if fusion is not feasible at all loop depths.
1555 if (!canFuse)
1556 continue;
1557
MLIR Teamd7c82442019-01-30 23:53:411558 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021559 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411560 for (auto *storeOpInst : dstNode->stores)
Diego Caballeroa45fb192020-05-20 00:16:041561 if (cast<AffineWriteOpInterface>(storeOpInst).getMemRef() == memref)
MLIR Teamd7c82442019-01-30 23:53:411562 dstStoreOpInsts.push_back(storeOpInst);
1563
Uday Bondhugulab4a14432019-01-26 00:00:501564 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251565 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411566 // Check if fusion would be profitable.
Diego Caballero34510552019-10-09 17:36:541567 if (!isFusionProfitable(srcStoreOp, srcStoreOp, dstLoadOpInsts,
1568 dstStoreOpInsts, &sliceState,
River Riddle400ad6f2020-04-08 19:57:021569 &bestDstLoopDepth, maximalFusion,
1570 computeToleranceThreshold))
MLIR Team38c2fe32019-01-14 19:26:251571 continue;
Andy Davis68a8da42019-11-18 19:20:031572
MLIR Team6892ffb2018-12-20 04:42:551573 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181574 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Diego Caballero34510552019-10-09 17:36:541575 srcStoreOp, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
Chris Lattnerd9b5bc82019-03-25 02:53:051576 if (sliceLoopNest) {
River Riddleaf1abcc2019-03-25 18:13:311577 LLVM_DEBUG(llvm::dbgs() << "\tslice loop nest:\n"
River Riddlef9d91532019-03-27 00:05:091578 << *sliceLoopNest.getOperation() << "\n");
River Riddle5052bd82019-02-02 00:42:181579 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleadca3c22019-05-12 00:57:321580 auto dstAffineForOp = cast<AffineForOp>(dstNode->op);
River Riddlef9d91532019-03-27 00:05:091581 if (insertPointInst != dstAffineForOp.getOperation()) {
1582 dstAffineForOp.getOperation()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411583 }
MLIR Teamc4237ae2019-01-18 16:56:271584 // Update edges between 'srcNode' and 'dstNode'.
Andy Davis68a8da42019-11-18 19:20:031585 mdg->updateEdges(srcNode->id, dstNode->id, memref,
1586 createPrivateMemref);
MLIR Teamc4237ae2019-01-18 16:56:271587
1588 // Collect slice loop stats.
1589 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:091590 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271591 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181592 for (auto forOp : sliceCollector.forOps) {
1593 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551594 }
Andy Davis68a8da42019-11-18 19:20:031595 if (createPrivateMemref) {
MLIR Team58aa3832019-02-16 01:12:191596 // Create private memref for 'memref' in 'dstAffineForOp'.
River Riddle99b87c92019-03-27 21:02:021597 SmallVector<Operation *, 4> storesForMemref;
MLIR Team58aa3832019-02-16 01:12:191598 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
Diego Caballeroa45fb192020-05-20 00:16:041599 if (cast<AffineWriteOpInterface>(storeOpInst).getMemRef() ==
1600 memref)
MLIR Team58aa3832019-02-16 01:12:191601 storesForMemref.push_back(storeOpInst);
1602 }
Andy Davis68a8da42019-11-18 19:20:031603 // TODO(andydavis) Use union of memref write regions to compute
1604 // private memref footprint.
River Riddle35807bc2019-12-23 05:59:551605 auto newMemRef = createPrivateMemRef(
MLIR Team58aa3832019-02-16 01:12:191606 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1607 fastMemorySpace, localBufSizeThreshold);
1608 visitedMemrefs.insert(newMemRef);
1609 // Create new node in dependence graph for 'newMemRef' alloc op.
1610 unsigned newMemRefNodeId =
River Riddle2bdf33c2020-01-11 16:54:041611 mdg->addNode(newMemRef.getDefiningOp());
MLIR Team58aa3832019-02-16 01:12:191612 // Add edge from 'newMemRef' node to dstNode.
1613 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271614 }
MLIR Teamc4237ae2019-01-18 16:56:271615
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031616 // Collect dst loop stats after memref privatization transformation.
MLIR Teamc4237ae2019-01-18 16:56:271617 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:091618 dstLoopCollector.collect(dstAffineForOp.getOperation());
MLIR Teamc4237ae2019-01-18 16:56:271619
1620 // Add new load ops to current Node load op list 'loads' to
1621 // continue fusing based on new operands.
1622 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
Uday Bondhugula2affcd62020-05-07 03:51:111623 // NOTE: Change 'loads' to a hash set in case efficiency is an
1624 // issue. We still use a vector since it's expected to be small.
Diego Caballero2e7a0842020-06-11 21:39:441625 if (!llvm::is_contained(loads, loadOpInst))
MLIR Teamc4237ae2019-01-18 16:56:271626 loads.push_back(loadOpInst);
1627 }
Diego Caballero2e7a0842020-06-11 21:39:441628 // Clear visited memrefs after fusion so that previously visited src
1629 // nodes are considered for fusion again in the context of the new
1630 // fused node.
1631 // TODO: This shouldn't be necessary if we visited candidates in the
1632 // dependence graph in post-order or once we fully support
1633 // multi-store producers. Currently, in a multi-store producer
1634 // scenario such as A->B, A->C, B->C, we fail to fuse A+B due to the
1635 // multiple outgoing edges. However, after fusing B+C, A has a
1636 // single outgoing edge and can be fused if we revisit it in the
1637 // context of the new fused B+C node.
1638 visitedMemrefs.clear();
MLIR Teamc4237ae2019-01-18 16:56:271639
Amit Sabne70a416d2019-04-09 16:17:401640 // Clear and add back loads and stores.
MLIR Teamc4237ae2019-01-18 16:56:271641 mdg->clearNodeLoadAndStores(dstNode->id);
1642 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1643 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371644 // Remove old src loop nest if it no longer has outgoing dependence
Amit Sabne70a416d2019-04-09 16:17:401645 // edges, and if it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191646 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1647 // been fused into 'dstNode' and write region of 'dstNode' covers
1648 // the write region of 'srcNode', and 'srcNode' has no other users
1649 // so it is safe to remove.
1650 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271651 mdg->removeNode(srcNode->id);
River Riddle99b87c92019-03-27 21:02:021652 srcNode->op->erase();
MLIR Teama78edcd2019-02-05 14:57:081653 } else {
1654 // Add remaining users of 'oldMemRef' back on the worklist (if not
1655 // already there), as its replacement with a local/private memref
1656 // has reduced dependences on 'oldMemRef' which may have created
1657 // new fusion opportunities.
1658 if (mdg->outEdges.count(srcNode->id) > 0) {
1659 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1660 mdg->outEdges[srcNode->id];
1661 for (auto &outEdge : oldOutEdges) {
1662 if (outEdge.value == memref &&
1663 worklistSet.count(outEdge.id) == 0) {
1664 worklist.push_back(outEdge.id);
1665 worklistSet.insert(outEdge.id);
1666 }
1667 }
1668 }
MLIR Teamc4237ae2019-01-18 16:56:271669 }
MLIR Team3b692302018-12-17 17:57:141670 }
MLIR Team3b692302018-12-17 17:57:141671 }
1672 }
1673 }
MLIR Teamd038e342019-03-01 19:50:251674 }
1675
1676 // Visits each node in the graph, and for each node, attempts to fuse it with
1677 // its sibling nodes (nodes which share a parent, but no dependence edges).
1678 void fuseSiblingNodes() {
1679 init();
1680 while (!worklist.empty()) {
1681 unsigned dstId = worklist.back();
1682 worklist.pop_back();
1683 worklistSet.erase(dstId);
1684
1685 // Skip if this node was removed (fused into another node).
1686 if (mdg->nodes.count(dstId) == 0)
1687 continue;
1688 // Get 'dstNode' into which to attempt fusion.
1689 auto *dstNode = mdg->getNode(dstId);
1690 // Skip if 'dstNode' is not a loop nest.
River Riddled5b60ee82019-05-12 01:59:541691 if (!isa<AffineForOp>(dstNode->op))
MLIR Teamd038e342019-03-01 19:50:251692 continue;
1693 // Attempt to fuse 'dstNode' with its sibling nodes in the graph.
1694 fuseWithSiblingNodes(dstNode);
1695 }
1696 }
1697
1698 // Attempt to fuse 'dstNode' with sibling nodes in the graph.
1699 void fuseWithSiblingNodes(Node *dstNode) {
1700 DenseSet<unsigned> visitedSibNodeIds;
River Riddlee62a6952019-12-23 22:45:011701 std::pair<unsigned, Value> idAndMemref;
MLIR Teamd038e342019-03-01 19:50:251702 while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) {
1703 unsigned sibId = idAndMemref.first;
River Riddlee62a6952019-12-23 22:45:011704 Value memref = idAndMemref.second;
MLIR Teamd038e342019-03-01 19:50:251705 // TODO(andydavis) Check that 'sibStoreOpInst' post-dominates all other
1706 // stores to the same memref in 'sibNode' loop nest.
1707 auto *sibNode = mdg->getNode(sibId);
River Riddle99b87c92019-03-27 21:02:021708 // Compute an operation list insertion point for the fused loop
MLIR Teamd038e342019-03-01 19:50:251709 // nest which preserves dependences.
River Riddle99b87c92019-03-27 21:02:021710 assert(sibNode->op->getBlock() == dstNode->op->getBlock());
1711 Operation *insertPointInst =
1712 sibNode->op->isBeforeInBlock(dstNode->op)
MLIR Teamd038e342019-03-01 19:50:251713 ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id)
1714 : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id);
1715 if (insertPointInst == nullptr)
1716 continue;
1717
1718 // Check if fusion would be profitable and at what depth.
1719
1720 // Get unique 'sibNode' load op to 'memref'.
River Riddle99b87c92019-03-27 21:02:021721 SmallVector<Operation *, 2> sibLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:251722 sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts);
1723 // Currently findSiblingNodeToFuse searches for siblings with one load.
1724 assert(sibLoadOpInsts.size() == 1);
River Riddle99b87c92019-03-27 21:02:021725 Operation *sibLoadOpInst = sibLoadOpInsts[0];
MLIR Teamd038e342019-03-01 19:50:251726 assert(!sibNode->stores.empty());
1727 // TODO(andydavis) Choose the store which postdominates all other stores.
1728 auto *sibStoreOpInst = sibNode->stores.back();
1729
1730 // Gather 'dstNode' load ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021731 SmallVector<Operation *, 2> dstLoadOpInsts;
MLIR Teamd038e342019-03-01 19:50:251732 dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts);
1733
1734 // Gather 'dstNode' store ops to 'memref'.
River Riddle99b87c92019-03-27 21:02:021735 SmallVector<Operation *, 2> dstStoreOpInsts;
MLIR Teamd038e342019-03-01 19:50:251736 dstNode->getStoreOpsForMemref(memref, &dstStoreOpInsts);
1737
1738 unsigned bestDstLoopDepth;
1739 mlir::ComputationSliceState sliceState;
1740
1741 // Check if fusion would be profitable.
1742 if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstLoadOpInsts,
Uday Bondhugulace7e59532019-03-08 17:21:521743 dstStoreOpInsts, &sliceState, &bestDstLoopDepth,
River Riddle400ad6f2020-04-08 19:57:021744 maximalFusion, computeToleranceThreshold))
MLIR Teamd038e342019-03-01 19:50:251745 continue;
1746
1747 // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'.
1748 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
1749 sibLoadOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
1750 if (sliceLoopNest != nullptr) {
River Riddleadca3c22019-05-12 00:57:321751 auto dstForInst = cast<AffineForOp>(dstNode->op);
River Riddle99b87c92019-03-27 21:02:021752 // Update operation position of fused loop nest (if needed).
River Riddlef9d91532019-03-27 00:05:091753 if (insertPointInst != dstForInst.getOperation()) {
1754 dstForInst.getOperation()->moveBefore(insertPointInst);
MLIR Teamd038e342019-03-01 19:50:251755 }
1756 // Update data dependence graph state post fusion.
1757 updateStateAfterSiblingFusion(sliceLoopNest, sibNode, dstNode);
1758 }
1759 }
1760 }
1761
MLIR Team9d30b362019-03-29 15:06:251762 // Searches function argument uses and the graph from 'dstNode' looking for a
1763 // fusion candidate sibling node which shares no dependences with 'dstNode'
1764 // but which loads from the same memref. Returns true and sets
1765 // 'idAndMemrefToFuse' on success. Returns false otherwise.
MLIR Teamd038e342019-03-01 19:50:251766 bool findSiblingNodeToFuse(Node *dstNode,
1767 DenseSet<unsigned> *visitedSibNodeIds,
River Riddlee62a6952019-12-23 22:45:011768 std::pair<unsigned, Value> *idAndMemrefToFuse) {
MLIR Team9d30b362019-03-29 15:06:251769 // Returns true if 'sibNode' can be fused with 'dstNode' for input reuse
1770 // on 'memref'.
River Riddlee62a6952019-12-23 22:45:011771 auto canFuseWithSibNode = [&](Node *sibNode, Value memref) {
MLIR Team9d30b362019-03-29 15:06:251772 // Skip if 'outEdge' is not a read-after-write dependence.
1773 // TODO(andydavis) Remove restrict to single load op restriction.
1774 if (sibNode->getLoadOpCount(memref) != 1)
1775 return false;
1776 // Skip if there exists a path of dependent edges between
1777 // 'sibNode' and 'dstNode'.
1778 if (mdg->hasDependencePath(sibNode->id, dstNode->id) ||
1779 mdg->hasDependencePath(dstNode->id, sibNode->id))
1780 return false;
1781 // Skip sib node if it loads to (and stores from) the same memref on
1782 // which it also has an input dependence edge.
River Riddlee62a6952019-12-23 22:45:011783 DenseSet<Value> loadAndStoreMemrefSet;
MLIR Team9d30b362019-03-29 15:06:251784 sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet);
River Riddlee62a6952019-12-23 22:45:011785 if (llvm::any_of(loadAndStoreMemrefSet, [=](Value memref) {
MLIR Team9d30b362019-03-29 15:06:251786 return mdg->getIncomingMemRefAccesses(sibNode->id, memref) > 0;
1787 }))
1788 return false;
1789
1790 // Check that all stores are to the same memref.
River Riddlee62a6952019-12-23 22:45:011791 DenseSet<Value> storeMemrefs;
MLIR Team9d30b362019-03-29 15:06:251792 for (auto *storeOpInst : sibNode->stores) {
Diego Caballeroa45fb192020-05-20 00:16:041793 storeMemrefs.insert(
1794 cast<AffineWriteOpInterface>(storeOpInst).getMemRef());
MLIR Team9d30b362019-03-29 15:06:251795 }
1796 if (storeMemrefs.size() != 1)
1797 return false;
1798 return true;
1799 };
1800
1801 // Search for siblings which load the same memref function argument.
River Riddlece502af2019-07-08 18:20:261802 auto fn = dstNode->op->getParentOfType<FuncOp>();
River Riddle54cd6a72019-07-01 17:29:091803 for (unsigned i = 0, e = fn.getNumArguments(); i != e; ++i) {
River Riddle2bdf33c2020-01-11 16:54:041804 for (auto *user : fn.getArgument(i).getUsers()) {
Diego Caballeroa45fb192020-05-20 00:16:041805 if (auto loadOp = dyn_cast<AffineReadOpInterface>(user)) {
MLIR Team9d30b362019-03-29 15:06:251806 // Gather loops surrounding 'use'.
1807 SmallVector<AffineForOp, 4> loops;
River Riddle8780d8d2019-05-18 18:09:071808 getLoopIVs(*user, &loops);
MLIR Team9d30b362019-03-29 15:06:251809 // Skip 'use' if it is not within a loop nest.
1810 if (loops.empty())
1811 continue;
1812 Node *sibNode = mdg->getForOpNode(loops[0]);
1813 assert(sibNode != nullptr);
1814 // Skip 'use' if it not a sibling to 'dstNode'.
1815 if (sibNode->id == dstNode->id)
1816 continue;
1817 // Skip 'use' if it has been visited.
1818 if (visitedSibNodeIds->count(sibNode->id) > 0)
1819 continue;
1820 // Skip 'use' if it does not load from the same memref as 'dstNode'.
River Riddle35807bc2019-12-23 05:59:551821 auto memref = loadOp.getMemRef();
MLIR Team9d30b362019-03-29 15:06:251822 if (dstNode->getLoadOpCount(memref) == 0)
1823 continue;
1824 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1825 if (canFuseWithSibNode(sibNode, memref)) {
1826 visitedSibNodeIds->insert(sibNode->id);
1827 idAndMemrefToFuse->first = sibNode->id;
1828 idAndMemrefToFuse->second = memref;
1829 return true;
1830 }
1831 }
1832 }
1833 }
1834
1835 // Search for siblings by following edges through an intermediate src node.
MLIR Teamd038e342019-03-01 19:50:251836 // Collect candidate 'dstNode' input edges in 'inEdges'.
1837 SmallVector<MemRefDependenceGraph::Edge, 2> inEdges;
1838 mdg->forEachMemRefInputEdge(
1839 dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) {
1840 // Add 'inEdge' if it is a read-after-write dependence.
1841 if (dstNode->getLoadOpCount(inEdge.value) > 0 &&
1842 mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0)
1843 inEdges.push_back(inEdge);
1844 });
1845
1846 // Search for sibling nodes to fuse by visiting output edges from each input
1847 // edge in 'inEdges'.
1848 for (auto &inEdge : inEdges) {
1849 // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'.
1850 SmallVector<MemRefDependenceGraph::Edge, 2> outEdges;
1851 mdg->forEachMemRefOutputEdge(
1852 inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) {
1853 unsigned sibNodeId = outEdge.id;
1854 if (visitedSibNodeIds->count(sibNodeId) > 0)
1855 return;
1856 // Skip output edge if not a sibling using the same memref.
1857 if (outEdge.id == dstNode->id || outEdge.value != inEdge.value)
1858 return;
1859 auto *sibNode = mdg->getNode(sibNodeId);
River Riddled5b60ee82019-05-12 01:59:541860 if (!isa<AffineForOp>(sibNode->op))
MLIR Teamd038e342019-03-01 19:50:251861 return;
MLIR Team9d30b362019-03-29 15:06:251862 // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1863 if (canFuseWithSibNode(sibNode, outEdge.value)) {
1864 // Add candidate 'outEdge' to sibling node.
1865 outEdges.push_back(outEdge);
MLIR Teamd038e342019-03-01 19:50:251866 }
MLIR Teamd038e342019-03-01 19:50:251867 });
1868
1869 // Add first candidate if any were returned.
1870 if (!outEdges.empty()) {
1871 visitedSibNodeIds->insert(outEdges[0].id);
1872 idAndMemrefToFuse->first = outEdges[0].id;
1873 idAndMemrefToFuse->second = outEdges[0].value;
1874 return true;
1875 }
1876 }
1877 return false;
1878 }
1879
Chris Lattnerd9b5bc82019-03-25 02:53:051880 void updateStateAfterSiblingFusion(AffineForOp sliceLoopNest, Node *sibNode,
1881 Node *dstNode) {
MLIR Teamd038e342019-03-01 19:50:251882 // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion.
1883 mdg->updateEdges(sibNode->id, dstNode->id);
1884
1885 // Collect slice loop stats.
1886 LoopNestStateCollector sliceCollector;
River Riddlef9d91532019-03-27 00:05:091887 sliceCollector.collect(sliceLoopNest.getOperation());
MLIR Teamd038e342019-03-01 19:50:251888 // Promote single iteration slice loops to single IV value.
1889 for (auto forOp : sliceCollector.forOps) {
1890 promoteIfSingleIteration(forOp);
1891 }
1892
Kazuaki Ishizaki8bfedb32019-10-20 07:11:031893 // Collect dst loop stats after memref privatization transformation.
River Riddleadca3c22019-05-12 00:57:321894 auto dstForInst = cast<AffineForOp>(dstNode->op);
MLIR Teamd038e342019-03-01 19:50:251895 LoopNestStateCollector dstLoopCollector;
River Riddlef9d91532019-03-27 00:05:091896 dstLoopCollector.collect(dstForInst.getOperation());
MLIR Teamd038e342019-03-01 19:50:251897 // Clear and add back loads and stores
1898 mdg->clearNodeLoadAndStores(dstNode->id);
1899 mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts,
1900 dstLoopCollector.storeOpInsts);
1901 // Remove old sibling loop nest if it no longer has outgoing dependence
1902 // edges, and it does not write to a memref which escapes the
1903 // function.
1904 if (mdg->getOutEdgeCount(sibNode->id) == 0) {
1905 mdg->removeNode(sibNode->id);
River Riddleadca3c22019-05-12 00:57:321906 sibNode->op->erase();
MLIR Teamd038e342019-03-01 19:50:251907 }
1908 }
1909
1910 // Clean up any allocs with no users.
1911 void eraseUnusedMemRefAllocations() {
MLIR Teamc4237ae2019-01-18 16:56:271912 for (auto &pair : mdg->memrefEdgeCount) {
1913 if (pair.second > 0)
1914 continue;
River Riddle35807bc2019-12-23 05:59:551915 auto memref = pair.first;
River Riddle99b87c92019-03-27 21:02:021916 // Skip if there exist other uses (return operation or function calls).
River Riddle2bdf33c2020-01-11 16:54:041917 if (!memref.use_empty())
MLIR Team71495d52019-01-22 21:23:371918 continue;
MLIR Teamc4237ae2019-01-18 16:56:271919 // Use list expected to match the dep graph info.
River Riddle2bdf33c2020-01-11 16:54:041920 auto *op = memref.getDefiningOp();
River Riddle1423acc2019-04-23 21:38:261921 if (isa_and_nonnull<AllocOp>(op))
River Riddle99b87c92019-03-27 21:02:021922 op->erase();
MLIR Teamc4237ae2019-01-18 16:56:271923 }
MLIR Teamf28e4df2018-11-01 14:26:001924 }
MLIR Team3b692302018-12-17 17:57:141925};
1926
1927} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001928
River Riddleed5fe202019-02-28 22:50:421929void LoopFusion::runOnFunction() {
MLIR Team6892ffb2018-12-20 04:42:551930 MemRefDependenceGraph g;
River Riddle400ad6f2020-04-08 19:57:021931 if (!g.init(getFunction()))
1932 return;
1933
1934 Optional<unsigned> fastMemorySpaceOpt;
1935 if (fastMemorySpace.hasValue())
1936 fastMemorySpaceOpt = fastMemorySpace;
1937 unsigned localBufSizeThresholdBytes = localBufSizeThreshold * 1024;
1938 GreedyFusion fusion(&g, localBufSizeThresholdBytes, fastMemorySpaceOpt,
1939 maximalFusion, computeToleranceThreshold);
1940 fusion.run();
MLIR Teamf28e4df2018-11-01 14:26:001941}