blob: 72176bacf9a1d56c707f42e41756b841e6c8fb29 [file] [log] [blame]
MLIR Teamf28e4df2018-11-01 14:26:001//===- LoopFusion.cpp - Code to perform loop fusion -----------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements loop fusion.
19//
20//===----------------------------------------------------------------------===//
21
River Riddle75553832019-01-29 05:23:5322#include "mlir/AffineOps/AffineOps.h"
MLIR Teamf28e4df2018-11-01 14:26:0023#include "mlir/Analysis/AffineAnalysis.h"
Uday Bondhuguladfe07b72019-02-23 00:51:0824#include "mlir/Analysis/AffineStructures.h"
MLIR Teamf28e4df2018-11-01 14:26:0025#include "mlir/Analysis/LoopAnalysis.h"
MLIR Team3b692302018-12-17 17:57:1426#include "mlir/Analysis/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0027#include "mlir/IR/AffineExpr.h"
28#include "mlir/IR/AffineMap.h"
MLIR Teamf28e4df2018-11-01 14:26:0029#include "mlir/IR/Builders.h"
30#include "mlir/IR/BuiltinOps.h"
River Riddle48ccae22019-02-20 01:17:4631#include "mlir/Pass/Pass.h"
MLIR Teamf28e4df2018-11-01 14:26:0032#include "mlir/StandardOps/StandardOps.h"
33#include "mlir/Transforms/LoopUtils.h"
34#include "mlir/Transforms/Passes.h"
MLIR Teamc4237ae2019-01-18 16:56:2735#include "mlir/Transforms/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0036#include "llvm/ADT/DenseMap.h"
MLIR Team3b692302018-12-17 17:57:1437#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/SetVector.h"
MLIR Team4eef7952018-12-21 19:06:2339#include "llvm/Support/CommandLine.h"
MLIR Team38c2fe32019-01-14 19:26:2540#include "llvm/Support/Debug.h"
MLIR Team3b692302018-12-17 17:57:1441#include "llvm/Support/raw_ostream.h"
Uday Bondhugula864d9e02019-01-23 17:16:2442#include <iomanip>
MLIR Team3b692302018-12-17 17:57:1443
MLIR Team38c2fe32019-01-14 19:26:2544#define DEBUG_TYPE "loop-fusion"
45
MLIR Team3b692302018-12-17 17:57:1446using llvm::SetVector;
MLIR Teamf28e4df2018-11-01 14:26:0047
48using namespace mlir;
49
River Riddle75c21e12019-01-26 06:14:0450static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options");
51
Uday Bondhugula864d9e02019-01-23 17:16:2452/// Disables fusion profitability check and fuses if valid.
MLIR Teamc4237ae2019-01-18 16:56:2753static llvm::cl::opt<bool>
54 clMaximalLoopFusion("fusion-maximal", llvm::cl::Hidden,
River Riddle75c21e12019-01-26 06:14:0455 llvm::cl::desc("Enables maximal loop fusion"),
56 llvm::cl::cat(clOptionsCategory));
Uday Bondhugula864d9e02019-01-23 17:16:2457
58/// A threshold in percent of additional computation allowed when fusing.
59static llvm::cl::opt<double> clFusionAddlComputeTolerance(
60 "fusion-compute-tolerance", llvm::cl::Hidden,
Uday Bondhugulaa1dad3a2019-02-20 02:17:1961 llvm::cl::desc("Fractional increase in additional "
62 "computation tolerated while fusing"),
River Riddle75c21e12019-01-26 06:14:0463 llvm::cl::cat(clOptionsCategory));
MLIR Teamc4237ae2019-01-18 16:56:2764
Uday Bondhugula8be26272019-02-02 01:06:2265static llvm::cl::opt<unsigned> clFusionFastMemorySpace(
66 "fusion-fast-mem-space", llvm::cl::Hidden,
67 llvm::cl::desc("Faster memory space number to promote fusion buffers to"),
68 llvm::cl::cat(clOptionsCategory));
69
Uday Bondhugulad4b3ff12019-02-27 00:10:1970// A local buffer of size less than or equal to this size is promoted to fast
71// memory.
72static llvm::cl::opt<unsigned long long> clFusionLocalBufThreshold(
Uday Bondhugula8be26272019-02-02 01:06:2273 "fusion-local-buf-threshold", llvm::cl::Hidden,
Uday Bondhugulad4b3ff12019-02-27 00:10:1974 llvm::cl::desc("Threshold size (KiB) for promoting local buffers to fast "
Uday Bondhugula8be26272019-02-02 01:06:2275 "memory space"),
76 llvm::cl::cat(clOptionsCategory));
77
MLIR Teamf28e4df2018-11-01 14:26:0078namespace {
79
MLIR Team3b692302018-12-17 17:57:1480/// Loop fusion pass. This pass currently supports a greedy fusion policy,
81/// which fuses loop nests with single-writer/single-reader memref dependences
82/// with the goal of improving locality.
83
84// TODO(andydavis) Support fusion of source loop nests which write to multiple
85// memrefs, where each memref can have multiple users (if profitable).
MLIR Teamf28e4df2018-11-01 14:26:0086// TODO(andydavis) Extend this pass to check for fusion preventing dependences,
87// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1488
MLIR Teamf28e4df2018-11-01 14:26:0089struct LoopFusion : public FunctionPass {
Uday Bondhugulad4b3ff12019-02-27 00:10:1990 LoopFusion(unsigned fastMemorySpace = 0, uint64_t localBufSizeThreshold = 0)
91 : FunctionPass(&LoopFusion::passID),
92 localBufSizeThreshold(localBufSizeThreshold),
93 fastMemorySpace(fastMemorySpace) {}
MLIR Teamf28e4df2018-11-01 14:26:0094
Chris Lattner79748892018-12-31 07:10:3595 PassResult runOnFunction(Function *f) override;
River Riddle3e656592019-02-22 02:01:0996 constexpr static PassID passID = {};
Uday Bondhugula864d9e02019-01-23 17:16:2497
Uday Bondhugulad4b3ff12019-02-27 00:10:1998 // Any local buffers smaller than this size (in bytes) will be created in
Uday Bondhugula8be26272019-02-02 01:06:2299 // `fastMemorySpace` if provided.
Uday Bondhugulad4b3ff12019-02-27 00:10:19100 uint64_t localBufSizeThreshold;
Uday Bondhugula8be26272019-02-02 01:06:22101 Optional<unsigned> fastMemorySpace = None;
102
Uday Bondhugula864d9e02019-01-23 17:16:24103 // The amount of additional computation that is tolerated while fusing
104 // pair-wise as a fraction of the total computation.
105 constexpr static double kComputeToleranceThreshold = 0.30f;
MLIR Teamf28e4df2018-11-01 14:26:00106};
107
MLIR Teamf28e4df2018-11-01 14:26:00108} // end anonymous namespace
109
Uday Bondhugulad4b3ff12019-02-27 00:10:19110FunctionPass *mlir::createLoopFusionPass(unsigned fastMemorySpace,
111 uint64_t localBufSizeThreshold) {
112 return new LoopFusion(fastMemorySpace, localBufSizeThreshold);
113}
MLIR Teamf28e4df2018-11-01 14:26:00114
MLIR Team3b692302018-12-17 17:57:14115namespace {
MLIR Teamf28e4df2018-11-01 14:26:00116
MLIR Team3b692302018-12-17 17:57:14117// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:35118// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:44119struct LoopNestStateCollector {
River Riddle5052bd82019-02-02 00:42:18120 SmallVector<OpPointer<AffineForOp>, 4> forOps;
River Riddleb4992772019-02-04 18:38:47121 SmallVector<Instruction *, 4> loadOpInsts;
122 SmallVector<Instruction *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:53123 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:14124
River Riddlebf9c3812019-02-05 00:24:44125 void collect(Instruction *instToWalk) {
126 instToWalk->walk([&](Instruction *opInst) {
127 if (opInst->isa<AffineForOp>())
128 forOps.push_back(opInst->cast<AffineForOp>());
129 else if (opInst->getNumBlockLists() != 0)
130 hasNonForRegion = true;
131 else if (opInst->isa<LoadOp>())
132 loadOpInsts.push_back(opInst);
133 else if (opInst->isa<StoreOp>())
134 storeOpInsts.push_back(opInst);
135 });
MLIR Team3b692302018-12-17 17:57:14136 }
137};
138
MLIR Team71495d52019-01-22 21:23:37139// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
River Riddleb4992772019-02-04 18:38:47140static bool isMemRefDereferencingOp(const Instruction &op) {
MLIR Team71495d52019-01-22 21:23:37141 if (op.isa<LoadOp>() || op.isa<StoreOp>() || op.isa<DmaStartOp>() ||
142 op.isa<DmaWaitOp>())
143 return true;
144 return false;
145}
MLIR Team6892ffb2018-12-20 04:42:55146// MemRefDependenceGraph is a graph data structure where graph nodes are
Chris Lattner456ad6a2018-12-29 00:05:35147// top-level instructions in a Function which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55148// are memref dependences between the nodes.
MLIR Teamc4237ae2019-01-18 16:56:27149// TODO(andydavis) Add a more flexible dependece graph representation.
MLIR Team6892ffb2018-12-20 04:42:55150// TODO(andydavis) Add a depth parameter to dependence graph construction.
151struct MemRefDependenceGraph {
152public:
153 // Node represents a node in the graph. A Node is either an entire loop nest
154 // rooted at the top level which contains loads/stores, or a top level
155 // load/store.
156 struct Node {
157 // The unique identifier of this node in the graph.
158 unsigned id;
159 // The top-level statment which is (or contains) loads/stores.
Chris Lattner456ad6a2018-12-29 00:05:35160 Instruction *inst;
Chris Lattner5187cfc2018-12-28 05:21:41161 // List of load operations.
River Riddleb4992772019-02-04 18:38:47162 SmallVector<Instruction *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35163 // List of store op insts.
River Riddleb4992772019-02-04 18:38:47164 SmallVector<Instruction *, 4> stores;
Chris Lattner456ad6a2018-12-29 00:05:35165 Node(unsigned id, Instruction *inst) : id(id), inst(inst) {}
MLIR Team6892ffb2018-12-20 04:42:55166
167 // Returns the load op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10168 unsigned getLoadOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55169 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35170 for (auto *loadOpInst : loads) {
171 if (memref == loadOpInst->cast<LoadOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55172 ++loadOpCount;
173 }
174 return loadOpCount;
175 }
176
177 // Returns the store op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10178 unsigned getStoreOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55179 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35180 for (auto *storeOpInst : stores) {
181 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55182 ++storeOpCount;
183 }
184 return storeOpCount;
185 }
MLIR Team58aa3832019-02-16 01:12:19186
187 // Returns all store ups in 'storeOps' which access 'memref'.
188 void getStoreOpsForMemref(Value *memref,
189 SmallVectorImpl<Instruction *> *storeOps) {
190 for (auto *storeOpInst : stores) {
191 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
192 storeOps->push_back(storeOpInst);
193 }
194 }
MLIR Team6892ffb2018-12-20 04:42:55195 };
196
MLIR Teama0f3db402019-01-29 17:36:41197 // Edge represents a data dependece between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55198 struct Edge {
199 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46200 // If this edge is stored in Edge = Node.inEdges[i], then
201 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
202 // If this edge is stored in Edge = Node.outEdges[i], then
203 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55204 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41205 // The SSA value on which this edge represents a dependence.
206 // If the value is a memref, then the dependence is between graph nodes
207 // which contain accesses to the same memref 'value'. If the value is a
208 // non-memref value, then the dependence is between a graph node which
209 // defines an SSA value and another graph node which uses the SSA value
210 // (e.g. a constant instruction defining a value which is used inside a loop
211 // nest).
212 Value *value;
MLIR Team6892ffb2018-12-20 04:42:55213 };
214
215 // Map from node id to Node.
216 DenseMap<unsigned, Node> nodes;
217 // Map from node id to list of input edges.
218 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
219 // Map from node id to list of output edges.
220 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27221 // Map from memref to a count on the dependence edges associated with that
222 // memref.
223 DenseMap<Value *, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41224 // The next unique identifier to use for newly created graph nodes.
225 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55226
227 MemRefDependenceGraph() {}
228
229 // Initializes the dependence graph based on operations in 'f'.
230 // Returns true on success, false otherwise.
Chris Lattner69d9e992018-12-28 16:48:09231 bool init(Function *f);
MLIR Team6892ffb2018-12-20 04:42:55232
233 // Returns the graph node for 'id'.
234 Node *getNode(unsigned id) {
235 auto it = nodes.find(id);
236 assert(it != nodes.end());
237 return &it->second;
238 }
239
MLIR Teama0f3db402019-01-29 17:36:41240 // Adds a node with 'inst' to the graph and returns its unique identifier.
241 unsigned addNode(Instruction *inst) {
242 Node node(nextNodeId++, inst);
243 nodes.insert({node.id, node});
244 return node.id;
245 }
246
MLIR Teamc4237ae2019-01-18 16:56:27247 // Remove node 'id' (and its associated edges) from graph.
248 void removeNode(unsigned id) {
249 // Remove each edge in 'inEdges[id]'.
250 if (inEdges.count(id) > 0) {
251 SmallVector<Edge, 2> oldInEdges = inEdges[id];
252 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41253 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27254 }
255 }
256 // Remove each edge in 'outEdges[id]'.
257 if (outEdges.count(id) > 0) {
258 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
259 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41260 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27261 }
262 }
263 // Erase remaining node state.
264 inEdges.erase(id);
265 outEdges.erase(id);
266 nodes.erase(id);
267 }
268
MLIR Teamd7c82442019-01-30 23:53:41269 // Returns true if node 'id' writes to any memref which escapes (or is an
270 // argument to) the function/block. Returns false otherwise.
271 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37272 Node *node = getNode(id);
273 for (auto *storeOpInst : node->stores) {
274 auto *memref = storeOpInst->cast<StoreOp>()->getMemRef();
275 auto *inst = memref->getDefiningInst();
MLIR Team58aa3832019-02-16 01:12:19276 // Return true if 'memref' is a block argument.
River Riddleb4992772019-02-04 18:38:47277 if (!inst)
MLIR Teamd7c82442019-01-30 23:53:41278 return true;
MLIR Team58aa3832019-02-16 01:12:19279 // Return true if any use of 'memref' escapes the function.
River Riddleb4992772019-02-04 18:38:47280 for (auto &use : memref->getUses())
281 if (!isMemRefDereferencingOp(*use.getOwner()))
MLIR Teamd7c82442019-01-30 23:53:41282 return true;
MLIR Teamd7c82442019-01-30 23:53:41283 }
284 return false;
285 }
286
287 // Returns true if node 'id' can be removed from the graph. Returns false
288 // otherwise. A node can be removed from the graph iff the following
289 // conditions are met:
290 // *) The node does not write to any memref which escapes (or is a
291 // function/block argument).
292 // *) The node has no successors in the dependence graph.
293 bool canRemoveNode(unsigned id) {
294 if (writesToLiveInOrEscapingMemrefs(id))
295 return false;
296 Node *node = getNode(id);
297 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41298 // Return false if there exist out edges from 'id' on 'memref'.
MLIR Teamd7c82442019-01-30 23:53:41299 if (getOutEdgeCount(id, storeOpInst->cast<StoreOp>()->getMemRef()) > 0)
MLIR Teama0f3db402019-01-29 17:36:41300 return false;
MLIR Team71495d52019-01-22 21:23:37301 }
MLIR Teama0f3db402019-01-29 17:36:41302 return true;
MLIR Team71495d52019-01-22 21:23:37303 }
304
MLIR Team27d067e2019-01-16 17:55:02305 // Returns true iff there is an edge from node 'srcId' to node 'dstId' for
MLIR Teama0f3db402019-01-29 17:36:41306 // 'value'. Returns false otherwise.
307 bool hasEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team27d067e2019-01-16 17:55:02308 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
309 return false;
310 }
311 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41312 return edge.id == dstId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02313 });
314 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41315 return edge.id == srcId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02316 });
317 return hasOutEdge && hasInEdge;
318 }
319
MLIR Teama0f3db402019-01-29 17:36:41320 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
321 void addEdge(unsigned srcId, unsigned dstId, Value *value) {
322 if (!hasEdge(srcId, dstId, value)) {
323 outEdges[srcId].push_back({dstId, value});
324 inEdges[dstId].push_back({srcId, value});
325 if (value->getType().isa<MemRefType>())
326 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02327 }
MLIR Team6892ffb2018-12-20 04:42:55328 }
329
MLIR Teama0f3db402019-01-29 17:36:41330 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
331 void removeEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team6892ffb2018-12-20 04:42:55332 assert(inEdges.count(dstId) > 0);
333 assert(outEdges.count(srcId) > 0);
MLIR Teama0f3db402019-01-29 17:36:41334 if (value->getType().isa<MemRefType>()) {
335 assert(memrefEdgeCount.count(value) > 0);
336 memrefEdgeCount[value]--;
337 }
MLIR Team6892ffb2018-12-20 04:42:55338 // Remove 'srcId' from 'inEdges[dstId]'.
339 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41340 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55341 inEdges[dstId].erase(it);
342 break;
343 }
344 }
345 // Remove 'dstId' from 'outEdges[srcId]'.
346 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41347 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55348 outEdges[srcId].erase(it);
349 break;
350 }
351 }
352 }
353
MLIR Teama0f3db402019-01-29 17:36:41354 // Returns the input edge count for node 'id' and 'memref' from src nodes
355 // which access 'memref'.
356 unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55357 unsigned inEdgeCount = 0;
358 if (inEdges.count(id) > 0)
359 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41360 if (inEdge.value == memref) {
361 Node *srcNode = getNode(inEdge.id);
362 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
363 if (srcNode->getLoadOpCount(memref) > 0 ||
364 srcNode->getStoreOpCount(memref) > 0)
365 ++inEdgeCount;
366 }
MLIR Team6892ffb2018-12-20 04:42:55367 return inEdgeCount;
368 }
369
370 // Returns the output edge count for node 'id' and 'memref'.
Chris Lattner3f190312018-12-27 22:35:10371 unsigned getOutEdgeCount(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55372 unsigned outEdgeCount = 0;
373 if (outEdges.count(id) > 0)
374 for (auto &outEdge : outEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41375 if (outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55376 ++outEdgeCount;
377 return outEdgeCount;
378 }
379
MLIR Teama0f3db402019-01-29 17:36:41380 // Computes and returns an insertion point instruction, before which the
381 // the fused <srcId, dstId> loop nest can be inserted while preserving
382 // dependences. Returns nullptr if no such insertion point is found.
MLIR Teama78edcd2019-02-05 14:57:08383 Instruction *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40384 if (outEdges.count(srcId) == 0)
MLIR Teama0f3db402019-01-29 17:36:41385 return getNode(dstId)->inst;
386
387 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
388 SmallPtrSet<Instruction *, 2> srcDepInsts;
389 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08390 if (outEdge.id != dstId)
MLIR Teama0f3db402019-01-29 17:36:41391 srcDepInsts.insert(getNode(outEdge.id)->inst);
392
393 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
394 SmallPtrSet<Instruction *, 2> dstDepInsts;
395 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08396 if (inEdge.id != srcId)
MLIR Teama0f3db402019-01-29 17:36:41397 dstDepInsts.insert(getNode(inEdge.id)->inst);
398
399 Instruction *srcNodeInst = getNode(srcId)->inst;
400 Instruction *dstNodeInst = getNode(dstId)->inst;
401
402 // Computing insertion point:
403 // *) Walk all instruction positions in Block instruction list in the
404 // range (src, dst). For each instruction 'inst' visited in this search:
405 // *) Store in 'firstSrcDepPos' the first position where 'inst' has a
406 // dependence edge from 'srcNode'.
407 // *) Store in 'lastDstDepPost' the last position where 'inst' has a
408 // dependence edge to 'dstNode'.
409 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
410 // instruction insertion point (or return null pointer if no such
411 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
412 SmallVector<Instruction *, 2> depInsts;
413 Optional<unsigned> firstSrcDepPos;
414 Optional<unsigned> lastDstDepPos;
415 unsigned pos = 0;
416 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
417 it != Block::iterator(dstNodeInst); ++it) {
418 Instruction *inst = &(*it);
419 if (srcDepInsts.count(inst) > 0 && firstSrcDepPos == None)
420 firstSrcDepPos = pos;
421 if (dstDepInsts.count(inst) > 0)
422 lastDstDepPos = pos;
423 depInsts.push_back(inst);
424 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40425 }
MLIR Teama0f3db402019-01-29 17:36:41426
427 if (firstSrcDepPos.hasValue()) {
428 if (lastDstDepPos.hasValue()) {
429 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
430 // No valid insertion point exists which preserves dependences.
431 return nullptr;
432 }
433 }
434 // Return the insertion point at 'firstSrcDepPos'.
435 return depInsts[firstSrcDepPos.getValue()];
436 }
437 // No dependence targets in range (or only dst deps in range), return
438 // 'dstNodInst' insertion point.
439 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55440 }
441
MLIR Teama0f3db402019-01-29 17:36:41442 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
443 // has been replaced in node at 'dstId' by a private memref.
444 void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef) {
MLIR Team6892ffb2018-12-20 04:42:55445 // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'.
446 if (inEdges.count(srcId) > 0) {
447 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
448 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41449 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
450 if (inEdge.value != oldMemRef)
451 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55452 }
453 }
MLIR Teamc4237ae2019-01-18 16:56:27454 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55455 if (outEdges.count(srcId) > 0) {
456 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
457 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27458 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
459 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41460 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55461 }
462 }
MLIR Teama0f3db402019-01-29 17:36:41463 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
464 // replaced by a private memref). These edges could come from nodes
465 // other than 'srcId' which were removed in the previous step.
466 if (inEdges.count(dstId) > 0) {
467 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
468 for (auto &inEdge : oldInEdges)
469 if (inEdge.value == oldMemRef)
470 removeEdge(inEdge.id, dstId, inEdge.value);
471 }
MLIR Team6892ffb2018-12-20 04:42:55472 }
473
474 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddleb4992772019-02-04 18:38:47475 void addToNode(unsigned id, const SmallVectorImpl<Instruction *> &loads,
476 const SmallVectorImpl<Instruction *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55477 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35478 for (auto *loadOpInst : loads)
479 node->loads.push_back(loadOpInst);
480 for (auto *storeOpInst : stores)
481 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55482 }
483
MLIR Teamc4237ae2019-01-18 16:56:27484 void clearNodeLoadAndStores(unsigned id) {
485 Node *node = getNode(id);
486 node->loads.clear();
487 node->stores.clear();
488 }
489
MLIR Team6892ffb2018-12-20 04:42:55490 void print(raw_ostream &os) const {
491 os << "\nMemRefDependenceGraph\n";
492 os << "\nNodes:\n";
493 for (auto &idAndNode : nodes) {
494 os << "Node: " << idAndNode.first << "\n";
495 auto it = inEdges.find(idAndNode.first);
496 if (it != inEdges.end()) {
497 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41498 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55499 }
500 it = outEdges.find(idAndNode.first);
501 if (it != outEdges.end()) {
502 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41503 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55504 }
505 }
506 }
507 void dump() const { print(llvm::errs()); }
508};
509
Chris Lattner456ad6a2018-12-29 00:05:35510// Intializes the data dependence graph by walking instructions in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55511// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39512// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55513// dependence graph at a different depth.
Chris Lattner69d9e992018-12-28 16:48:09514bool MemRefDependenceGraph::init(Function *f) {
Chris Lattner3f190312018-12-27 22:35:10515 DenseMap<Value *, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43516
517 // TODO: support multi-block functions.
518 if (f->getBlocks().size() != 1)
519 return false;
520
River Riddle5052bd82019-02-02 00:42:18521 DenseMap<Instruction *, unsigned> forToNodeMap;
Chris Lattnerdffc5892018-12-29 23:33:43522 for (auto &inst : f->front()) {
River Riddleb4992772019-02-04 18:38:47523 if (auto forOp = inst.dyn_cast<AffineForOp>()) {
River Riddle5052bd82019-02-02 00:42:18524 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55525 // all loads and store accesses it contains.
526 LoopNestStateCollector collector;
River Riddlebf9c3812019-02-05 00:24:44527 collector.collect(&inst);
Uday Bondhugula4ba8c912019-02-07 05:54:18528 // Return false if a non 'for' region was found (not currently supported).
River Riddle75553832019-01-29 05:23:53529 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55530 return false;
MLIR Teama0f3db402019-01-29 17:36:41531 Node node(nextNodeId++, &inst);
Chris Lattner456ad6a2018-12-29 00:05:35532 for (auto *opInst : collector.loadOpInsts) {
533 node.loads.push_back(opInst);
534 auto *memref = opInst->cast<LoadOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55535 memrefAccesses[memref].insert(node.id);
536 }
Chris Lattner456ad6a2018-12-29 00:05:35537 for (auto *opInst : collector.storeOpInsts) {
538 node.stores.push_back(opInst);
539 auto *memref = opInst->cast<StoreOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55540 memrefAccesses[memref].insert(node.id);
541 }
River Riddle5052bd82019-02-02 00:42:18542 forToNodeMap[&inst] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55543 nodes.insert({node.id, node});
River Riddleb4992772019-02-04 18:38:47544 } else if (auto loadOp = inst.dyn_cast<LoadOp>()) {
545 // Create graph node for top-level load op.
546 Node node(nextNodeId++, &inst);
547 node.loads.push_back(&inst);
548 auto *memref = inst.cast<LoadOp>()->getMemRef();
549 memrefAccesses[memref].insert(node.id);
550 nodes.insert({node.id, node});
551 } else if (auto storeOp = inst.dyn_cast<StoreOp>()) {
552 // Create graph node for top-level store op.
553 Node node(nextNodeId++, &inst);
554 node.stores.push_back(&inst);
555 auto *memref = inst.cast<StoreOp>()->getMemRef();
556 memrefAccesses[memref].insert(node.id);
557 nodes.insert({node.id, node});
558 } else if (inst.getNumBlockLists() != 0) {
559 // Return false if another region is found (not currently supported).
560 return false;
561 } else if (inst.getNumResults() > 0 && !inst.use_empty()) {
562 // Create graph node for top-level producer of SSA values, which
563 // could be used by loop nest nodes.
564 Node node(nextNodeId++, &inst);
565 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41566 }
567 }
568
569 // Add dependence edges between nodes which produce SSA values and their
570 // users.
571 for (auto &idAndNode : nodes) {
572 const Node &node = idAndNode.second;
573 if (!node.loads.empty() || !node.stores.empty())
574 continue;
River Riddleb4992772019-02-04 18:38:47575 auto *opInst = node.inst;
MLIR Teama0f3db402019-01-29 17:36:41576 for (auto *value : opInst->getResults()) {
577 for (auto &use : value->getUses()) {
River Riddle5052bd82019-02-02 00:42:18578 SmallVector<OpPointer<AffineForOp>, 4> loops;
River Riddleb4992772019-02-04 18:38:47579 getLoopIVs(*use.getOwner(), &loops);
MLIR Teama0f3db402019-01-29 17:36:41580 if (loops.empty())
581 continue;
River Riddle5052bd82019-02-02 00:42:18582 assert(forToNodeMap.count(loops[0]->getInstruction()) > 0);
583 unsigned userLoopNestId = forToNodeMap[loops[0]->getInstruction()];
MLIR Teama0f3db402019-01-29 17:36:41584 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55585 }
586 }
MLIR Team6892ffb2018-12-20 04:42:55587 }
588
589 // Walk memref access lists and add graph edges between dependent nodes.
590 for (auto &memrefAndList : memrefAccesses) {
591 unsigned n = memrefAndList.second.size();
592 for (unsigned i = 0; i < n; ++i) {
593 unsigned srcId = memrefAndList.second[i];
594 bool srcHasStore =
595 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
596 for (unsigned j = i + 1; j < n; ++j) {
597 unsigned dstId = memrefAndList.second[j];
598 bool dstHasStore =
599 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
600 if (srcHasStore || dstHasStore)
601 addEdge(srcId, dstId, memrefAndList.first);
602 }
603 }
604 }
605 return true;
606}
607
MLIR Team38c2fe32019-01-14 19:26:25608namespace {
609
610// LoopNestStats aggregates various per-loop statistics (eg. loop trip count
611// and operation count) for a loop nest up until the innermost loop body.
612struct LoopNestStats {
River Riddle5052bd82019-02-02 00:42:18613 // Map from AffineForOp to immediate child AffineForOps in its loop body.
614 DenseMap<Instruction *, SmallVector<OpPointer<AffineForOp>, 2>> loopMap;
615 // Map from AffineForOp to count of operations in its loop body.
616 DenseMap<Instruction *, uint64_t> opCountMap;
617 // Map from AffineForOp to its constant trip count.
618 DenseMap<Instruction *, uint64_t> tripCountMap;
MLIR Team38c2fe32019-01-14 19:26:25619};
620
621// LoopNestStatsCollector walks a single loop nest and gathers per-loop
622// trip count and operation count statistics and records them in 'stats'.
River Riddlebf9c3812019-02-05 00:24:44623struct LoopNestStatsCollector {
MLIR Team38c2fe32019-01-14 19:26:25624 LoopNestStats *stats;
625 bool hasLoopWithNonConstTripCount = false;
626
627 LoopNestStatsCollector(LoopNestStats *stats) : stats(stats) {}
628
River Riddlebf9c3812019-02-05 00:24:44629 void collect(Instruction *inst) {
630 inst->walk<AffineForOp>([&](OpPointer<AffineForOp> forOp) {
631 auto *forInst = forOp->getInstruction();
632 auto *parentInst = forOp->getInstruction()->getParentInst();
633 if (parentInst != nullptr) {
634 assert(parentInst->isa<AffineForOp>() && "Expected parent AffineForOp");
635 // Add mapping to 'forOp' from its parent AffineForOp.
636 stats->loopMap[parentInst].push_back(forOp);
637 }
River Riddle5052bd82019-02-02 00:42:18638
River Riddlebf9c3812019-02-05 00:24:44639 // Record the number of op instructions in the body of 'forOp'.
640 unsigned count = 0;
641 stats->opCountMap[forInst] = 0;
642 for (auto &inst : *forOp->getBody()) {
Uday Bondhugulad4b3ff12019-02-27 00:10:19643 if (!inst.isa<AffineForOp>() && !inst.isa<AffineIfOp>())
River Riddlebf9c3812019-02-05 00:24:44644 ++count;
645 }
646 stats->opCountMap[forInst] = count;
647 // Record trip count for 'forOp'. Set flag if trip count is not
648 // constant.
649 Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp);
650 if (!maybeConstTripCount.hasValue()) {
651 hasLoopWithNonConstTripCount = true;
652 return;
653 }
654 stats->tripCountMap[forInst] = maybeConstTripCount.getValue();
655 });
MLIR Team38c2fe32019-01-14 19:26:25656 }
657};
658
River Riddle5052bd82019-02-02 00:42:18659// Computes the total cost of the loop nest rooted at 'forOp'.
MLIR Team38c2fe32019-01-14 19:26:25660// Currently, the total cost is computed by counting the total operation
661// instance count (i.e. total number of operations in the loop bodyloop
662// operation count * loop trip count) for the entire loop nest.
663// If 'tripCountOverrideMap' is non-null, overrides the trip count for loops
664// specified in the map when computing the total op instance count.
665// NOTE: this is used to compute the cost of computation slices, which are
666// sliced along the iteration dimension, and thus reduce the trip count.
River Riddle5052bd82019-02-02 00:42:18667// If 'computeCostMap' is non-null, the total op count for forOps specified
MLIR Team38c2fe32019-01-14 19:26:25668// in the map is increased (not overridden) by adding the op count from the
669// map to the existing op count for the for loop. This is done before
670// multiplying by the loop's trip count, and is used to model the cost of
671// inserting a sliced loop nest of known cost into the loop's body.
672// NOTE: this is used to compute the cost of fusing a slice of some loop nest
673// within another loop.
Uday Bondhugula864d9e02019-01-23 17:16:24674static int64_t getComputeCost(
River Riddle5052bd82019-02-02 00:42:18675 Instruction *forInst, LoopNestStats *stats,
676 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountOverrideMap,
677 DenseMap<Instruction *, int64_t> *computeCostMap) {
678 // 'opCount' is the total number operations in one iteration of 'forOp' body
Uday Bondhugula864d9e02019-01-23 17:16:24679 int64_t opCount = stats->opCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25680 if (stats->loopMap.count(forInst) > 0) {
River Riddle5052bd82019-02-02 00:42:18681 for (auto childForOp : stats->loopMap[forInst]) {
682 opCount += getComputeCost(childForOp->getInstruction(), stats,
683 tripCountOverrideMap, computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:25684 }
685 }
686 // Add in additional op instances from slice (if specified in map).
687 if (computeCostMap != nullptr) {
688 auto it = computeCostMap->find(forInst);
689 if (it != computeCostMap->end()) {
690 opCount += it->second;
691 }
692 }
693 // Override trip count (if specified in map).
Uday Bondhugula864d9e02019-01-23 17:16:24694 int64_t tripCount = stats->tripCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25695 if (tripCountOverrideMap != nullptr) {
696 auto it = tripCountOverrideMap->find(forInst);
697 if (it != tripCountOverrideMap->end()) {
698 tripCount = it->second;
699 }
700 }
701 // Returns the total number of dynamic instances of operations in loop body.
702 return tripCount * opCount;
703}
704
705} // end anonymous namespace
706
MLIR Team27d067e2019-01-16 17:55:02707static Optional<uint64_t> getConstDifference(AffineMap lbMap, AffineMap ubMap) {
Uday Bondhugulac1ca23e2019-01-16 21:13:00708 assert(lbMap.getNumResults() == 1 && "expected single result bound map");
709 assert(ubMap.getNumResults() == 1 && "expected single result bound map");
MLIR Team27d067e2019-01-16 17:55:02710 assert(lbMap.getNumDims() == ubMap.getNumDims());
711 assert(lbMap.getNumSymbols() == ubMap.getNumSymbols());
712 // TODO(andydavis) Merge this code with 'mlir::getTripCountExpr'.
713 // ub_expr - lb_expr
714 AffineExpr lbExpr(lbMap.getResult(0));
715 AffineExpr ubExpr(ubMap.getResult(0));
716 auto loopSpanExpr = simplifyAffineExpr(ubExpr - lbExpr, lbMap.getNumDims(),
717 lbMap.getNumSymbols());
718 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
719 if (!cExpr)
720 return None;
721 return cExpr.getValue();
722}
723
River Riddle5052bd82019-02-02 00:42:18724// Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop
MLIR Team38c2fe32019-01-14 19:26:25725// nest surrounding 'srcAccess' utilizing slice loop bounds in 'sliceState'.
726// Returns true on success, false otherwise (if a non-constant trip count
727// was encountered).
728// TODO(andydavis) Make this work with non-unit step loops.
MLIR Team27d067e2019-01-16 17:55:02729static bool buildSliceTripCountMap(
River Riddleb4992772019-02-04 18:38:47730 Instruction *srcOpInst, ComputationSliceState *sliceState,
River Riddle5052bd82019-02-02 00:42:18731 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountMap) {
732 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:02733 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:25734 unsigned numSrcLoopIVs = srcLoopIVs.size();
River Riddle5052bd82019-02-02 00:42:18735 // Populate map from AffineForOp -> trip count
MLIR Team38c2fe32019-01-14 19:26:25736 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
737 AffineMap lbMap = sliceState->lbs[i];
738 AffineMap ubMap = sliceState->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17739 if (lbMap == AffineMap() || ubMap == AffineMap()) {
MLIR Team38c2fe32019-01-14 19:26:25740 // The iteration of src loop IV 'i' was not sliced. Use full loop bounds.
741 if (srcLoopIVs[i]->hasConstantLowerBound() &&
742 srcLoopIVs[i]->hasConstantUpperBound()) {
River Riddle5052bd82019-02-02 00:42:18743 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] =
MLIR Team38c2fe32019-01-14 19:26:25744 srcLoopIVs[i]->getConstantUpperBound() -
745 srcLoopIVs[i]->getConstantLowerBound();
746 continue;
747 }
748 return false;
749 }
MLIR Team27d067e2019-01-16 17:55:02750 Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap);
751 if (!tripCount.hasValue())
MLIR Team38c2fe32019-01-14 19:26:25752 return false;
River Riddle5052bd82019-02-02 00:42:18753 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] = tripCount.getValue();
MLIR Team38c2fe32019-01-14 19:26:25754 }
755 return true;
756}
757
MLIR Team27d067e2019-01-16 17:55:02758// Removes load operations from 'srcLoads' which operate on 'memref', and
759// adds them to 'dstLoads'.
760static void
761moveLoadsAccessingMemrefTo(Value *memref,
River Riddleb4992772019-02-04 18:38:47762 SmallVectorImpl<Instruction *> *srcLoads,
763 SmallVectorImpl<Instruction *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02764 dstLoads->clear();
River Riddleb4992772019-02-04 18:38:47765 SmallVector<Instruction *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02766 for (auto *load : *srcLoads) {
767 if (load->cast<LoadOp>()->getMemRef() == memref)
768 dstLoads->push_back(load);
769 else
770 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25771 }
MLIR Team27d067e2019-01-16 17:55:02772 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25773}
774
MLIR Team27d067e2019-01-16 17:55:02775// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddleb4992772019-02-04 18:38:47776static unsigned getInnermostCommonLoopDepth(ArrayRef<Instruction *> ops) {
MLIR Team27d067e2019-01-16 17:55:02777 unsigned numOps = ops.size();
778 assert(numOps > 0);
779
River Riddle5052bd82019-02-02 00:42:18780 std::vector<SmallVector<OpPointer<AffineForOp>, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02781 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
782 for (unsigned i = 0; i < numOps; ++i) {
783 getLoopIVs(*ops[i], &loops[i]);
784 loopDepthLimit =
785 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25786 }
MLIR Team27d067e2019-01-16 17:55:02787
788 unsigned loopDepth = 0;
789 for (unsigned d = 0; d < loopDepthLimit; ++d) {
790 unsigned i;
791 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18792 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02793 break;
MLIR Team27d067e2019-01-16 17:55:02794 }
795 if (i != numOps)
796 break;
797 ++loopDepth;
798 }
799 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25800}
801
MLIR Teamd7c82442019-01-30 23:53:41802// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
803// and 'storeOpInsts' are satisfied.
River Riddleb4992772019-02-04 18:38:47804static unsigned getMaxLoopDepth(ArrayRef<Instruction *> loadOpInsts,
805 ArrayRef<Instruction *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41806 // Merge loads and stores into the same array.
River Riddleb4992772019-02-04 18:38:47807 SmallVector<Instruction *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41808 ops.append(storeOpInsts.begin(), storeOpInsts.end());
809
810 // Compute the innermost common loop depth for loads and stores.
811 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
812
813 // Return common loop depth for loads if there are no store ops.
814 if (storeOpInsts.empty())
815 return loopDepth;
816
817 // Check dependences on all pairs of ops in 'ops' and store the minimum
818 // loop depth at which a dependence is satisfied.
819 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
820 auto *srcOpInst = ops[i];
821 MemRefAccess srcAccess(srcOpInst);
822 for (unsigned j = 0; j < e; ++j) {
823 auto *dstOpInst = ops[j];
824 MemRefAccess dstAccess(dstOpInst);
825
826 unsigned numCommonLoops =
827 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
828 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
829 FlatAffineConstraints dependenceConstraints;
830 // TODO(andydavis) Cache dependence analysis results, check cache here.
831 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
832 &dependenceConstraints,
833 /*dependenceComponents=*/nullptr)) {
834 // Store minimum loop depth and break because we want the min 'd' at
835 // which there is a dependence.
836 loopDepth = std::min(loopDepth, d - 1);
837 break;
838 }
839 }
840 }
841 }
842 return loopDepth;
843}
844
MLIR Team8f5f2c72019-02-15 17:32:18845// Compute loop interchange permutation:
846// *) Computes dependence components between all op pairs in 'ops' for loop
847// depths in range [1, 'maxLoopDepth'].
848// *) Classifies the outermost 'maxLoopDepth' loops surrounding 'ops' as either
849// parallel or sequential.
850// *) Computes the loop permutation which sinks sequential loops deeper into
851// the loop nest, while preserving the relative order between other loops.
852// *) Checks each dependence component against the permutation to see if the
853// desired loop interchange would violated dependences by making the a
854// dependence componenent lexicographically negative.
855// TODO(andydavis) Move this function to LoopUtils.
856static bool
857computeLoopInterchangePermutation(ArrayRef<Instruction *> ops,
858 unsigned maxLoopDepth,
859 SmallVectorImpl<unsigned> *loopPermMap) {
860 // Gather dependence components for dependences between all ops in 'ops'
861 // at loop depths in range [1, maxLoopDepth].
862 // TODO(andydavis) Refactor this loop into a LoopUtil utility function:
863 // mlir::getDependenceComponents().
864 // TODO(andydavis) Split this loop into two: first check all dependences,
865 // and construct dep vectors. Then, scan through them to detect the parallel
866 // ones.
867 std::vector<llvm::SmallVector<DependenceComponent, 2>> depCompsVec;
868 llvm::SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true);
869 unsigned numOps = ops.size();
870 for (unsigned d = 1; d <= maxLoopDepth; ++d) {
871 for (unsigned i = 0; i < numOps; ++i) {
872 auto *srcOpInst = ops[i];
873 MemRefAccess srcAccess(srcOpInst);
874 for (unsigned j = 0; j < numOps; ++j) {
875 auto *dstOpInst = ops[j];
876 MemRefAccess dstAccess(dstOpInst);
877
878 FlatAffineConstraints dependenceConstraints;
879 llvm::SmallVector<DependenceComponent, 2> depComps;
880 // TODO(andydavis,bondhugula) Explore whether it would be profitable
881 // to pre-compute and store deps instead of repeatidly checking.
882 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
883 &dependenceConstraints, &depComps)) {
884 isParallelLoop[d - 1] = false;
885 depCompsVec.push_back(depComps);
886 }
887 }
888 }
889 }
890 // Count the number of parallel loops.
891 unsigned numParallelLoops = 0;
892 for (unsigned i = 0, e = isParallelLoop.size(); i < e; ++i)
893 if (isParallelLoop[i])
894 ++numParallelLoops;
895
896 // Compute permutation of loops that sinks sequential loops (and thus raises
897 // parallel loops) while preserving relative order.
898 llvm::SmallVector<unsigned, 4> loopPermMapInv;
899 loopPermMapInv.resize(maxLoopDepth);
900 loopPermMap->resize(maxLoopDepth);
901 unsigned nextSequentialLoop = numParallelLoops;
902 unsigned nextParallelLoop = 0;
903 for (unsigned i = 0; i < maxLoopDepth; ++i) {
904 if (isParallelLoop[i]) {
905 (*loopPermMap)[i] = nextParallelLoop;
906 loopPermMapInv[nextParallelLoop++] = i;
907 } else {
908 (*loopPermMap)[i] = nextSequentialLoop;
909 loopPermMapInv[nextSequentialLoop++] = i;
910 }
911 }
912
913 // Check each dependence component against the permutation to see if the
914 // desired loop interchange permutation would make the dependence vectors
915 // lexicographically negative.
916 // Example 1: [-1, 1][0, 0]
917 // Example 2: [0, 0][-1, 1]
918 for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) {
919 llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i];
920 assert(depComps.size() >= maxLoopDepth);
921 // Check if the first non-zero dependence component is positive.
922 for (unsigned j = 0; j < maxLoopDepth; ++j) {
923 unsigned permIndex = loopPermMapInv[j];
924 assert(depComps[permIndex].lb.hasValue());
925 int64_t depCompLb = depComps[permIndex].lb.getValue();
926 if (depCompLb > 0)
927 break;
928 if (depCompLb < 0)
929 return false;
930 }
931 }
932 return true;
933}
934
935// Sinks all sequential loops to the innermost levels (while preserving
936// relative order among them) and moves all parallel loops to the
937// outermost (while again preserving relative order among them).
938// This can increase the loop depth at which we can fuse a slice, since we are
939// pushing loop carried dependence to a greater depth in the loop nest.
940static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
941 assert(node->inst->isa<AffineForOp>());
942 // Get perfectly nested sequence of loops starting at root of loop nest.
943 // TODO(andydavis,bondhugula) Share this with similar code in loop tiling.
944 SmallVector<OpPointer<AffineForOp>, 4> loops;
945 OpPointer<AffineForOp> curr = node->inst->cast<AffineForOp>();
946 loops.push_back(curr);
947 auto *currBody = curr->getBody();
948 while (!currBody->empty() &&
949 std::next(currBody->begin()) == currBody->end() &&
950 (curr = curr->getBody()->front().dyn_cast<AffineForOp>())) {
951 loops.push_back(curr);
952 currBody = curr->getBody();
953 }
954 if (loops.size() < 2)
955 return;
956
957 // Merge loads and stores into the same array.
958 SmallVector<Instruction *, 2> memOps(node->loads.begin(), node->loads.end());
959 memOps.append(node->stores.begin(), node->stores.end());
960
961 // Compute loop permutation in 'loopPermMap'.
962 llvm::SmallVector<unsigned, 4> loopPermMap;
963 if (!computeLoopInterchangePermutation(memOps, loops.size(), &loopPermMap))
964 return;
965
966 int loopNestRootIndex = -1;
967 for (int i = loops.size() - 1; i >= 0; --i) {
968 int permIndex = static_cast<int>(loopPermMap[i]);
969 // Store the index of the for loop which will be the new loop nest root.
970 if (permIndex == 0)
971 loopNestRootIndex = i;
972 if (permIndex > i) {
973 // Sink loop 'i' by 'permIndex - i' levels deeper into the loop nest.
974 sinkLoop(loops[i], permIndex - i);
975 }
976 }
977 assert(loopNestRootIndex != -1 && "invalid root index");
978 node->inst = loops[loopNestRootIndex]->getInstruction();
979}
980
Uday Bondhugulac1ca23e2019-01-16 21:13:00981// Returns the slice union of 'sliceStateA' and 'sliceStateB' in 'sliceStateB'
982// using a rectangular bounding box.
MLIR Team27d067e2019-01-16 17:55:02983// TODO(andydavis) This function assumes that lower bounds for 'sliceStateA'
984// and 'sliceStateB' are aligned.
985// Specifically, when taking the union of overlapping intervals, it assumes
986// that both intervals start at zero. Support needs to be added to take into
987// account interval start offset when computing the union.
988// TODO(andydavis) Move this function to an analysis library.
Uday Bondhugulac1ca23e2019-01-16 21:13:00989static bool getSliceUnion(const ComputationSliceState &sliceStateA,
990 ComputationSliceState *sliceStateB) {
MLIR Team27d067e2019-01-16 17:55:02991 assert(sliceStateA.lbs.size() == sliceStateB->lbs.size());
992 assert(sliceStateA.ubs.size() == sliceStateB->ubs.size());
993
994 for (unsigned i = 0, e = sliceStateA.lbs.size(); i < e; ++i) {
995 AffineMap lbMapA = sliceStateA.lbs[i];
996 AffineMap ubMapA = sliceStateA.ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17997 if (lbMapA == AffineMap()) {
998 assert(ubMapA == AffineMap());
MLIR Team27d067e2019-01-16 17:55:02999 continue;
1000 }
Uday Bondhugulac1ca23e2019-01-16 21:13:001001 assert(ubMapA && "expected non-null ub map");
MLIR Team27d067e2019-01-16 17:55:021002
1003 AffineMap lbMapB = sliceStateB->lbs[i];
1004 AffineMap ubMapB = sliceStateB->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:171005 if (lbMapB == AffineMap()) {
1006 assert(ubMapB == AffineMap());
MLIR Team27d067e2019-01-16 17:55:021007 // Union 'sliceStateB' does not have a bound for 'i' so copy from A.
1008 sliceStateB->lbs[i] = lbMapA;
1009 sliceStateB->ubs[i] = ubMapA;
1010 continue;
1011 }
Uday Bondhugulac1ca23e2019-01-16 21:13:001012
1013 // TODO(andydavis) Change this code to take the min across all lower bounds
1014 // and max across all upper bounds for each dimension. This code can for
1015 // cases where a unique min or max could not be statically determined.
1016
1017 // Assumption: both lower bounds are the same.
1018 if (lbMapA != lbMapB)
MLIR Team27d067e2019-01-16 17:55:021019 return false;
1020
1021 // Add bound with the largest trip count to union.
1022 Optional<uint64_t> tripCountA = getConstDifference(lbMapA, ubMapA);
1023 Optional<uint64_t> tripCountB = getConstDifference(lbMapB, ubMapB);
1024 if (!tripCountA.hasValue() || !tripCountB.hasValue())
1025 return false;
Uday Bondhugulac1ca23e2019-01-16 21:13:001026
MLIR Team27d067e2019-01-16 17:55:021027 if (tripCountA.getValue() > tripCountB.getValue()) {
1028 sliceStateB->lbs[i] = lbMapA;
1029 sliceStateB->ubs[i] = ubMapA;
1030 }
1031 }
1032 return true;
1033}
1034
Uday Bondhugula8be26272019-02-02 01:06:221035// TODO(mlir-team): improve/complete this when we have target data.
1036unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
1037 auto elementType = memRefType.getElementType();
1038
1039 unsigned sizeInBits;
1040 if (elementType.isIntOrFloat()) {
1041 sizeInBits = elementType.getIntOrFloatBitWidth();
1042 } else {
1043 auto vectorType = elementType.cast<VectorType>();
1044 sizeInBits =
1045 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
1046 }
1047 return llvm::divideCeil(sizeInBits, 8);
1048}
1049
MLIR Teamc4237ae2019-01-18 16:56:271050// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:181051// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:521052// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1053// TODO(bondhugula): consider refactoring the common code from generateDma and
1054// this one.
River Riddle5052bd82019-02-02 00:42:181055static Value *createPrivateMemRef(OpPointer<AffineForOp> forOp,
River Riddleb4992772019-02-04 18:38:471056 Instruction *srcStoreOpInst,
Uday Bondhugula8be26272019-02-02 01:06:221057 unsigned dstLoopDepth,
1058 Optional<unsigned> fastMemorySpace,
Uday Bondhugulad4b3ff12019-02-27 00:10:191059 uint64_t localBufSizeThreshold) {
River Riddle5052bd82019-02-02 00:42:181060 auto *forInst = forOp->getInstruction();
1061
1062 // Create builder to insert alloc op just before 'forOp'.
MLIR Teamc4237ae2019-01-18 16:56:271063 FuncBuilder b(forInst);
1064 // Builder to create constants at the top level.
1065 FuncBuilder top(forInst->getFunction());
1066 // Create new memref type based on slice bounds.
1067 auto *oldMemRef = srcStoreOpInst->cast<StoreOp>()->getMemRef();
1068 auto oldMemRefType = oldMemRef->getType().cast<MemRefType>();
1069 unsigned rank = oldMemRefType.getRank();
1070
Uday Bondhugula94a03f82019-01-22 21:58:521071 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:441072 MemRefRegion region(srcStoreOpInst->getLoc());
1073 region.compute(srcStoreOpInst, dstLoopDepth);
River Riddle6859f332019-01-23 22:39:451074 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:271075 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:521076 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:271077 lbs.reserve(rank);
1078 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:521079 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:271080 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:441081 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:221082 assert(numElements.hasValue() &&
1083 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:271084
Uday Bondhugula0f504142019-02-04 21:48:441085 const FlatAffineConstraints *cst = region.getConstraints();
Uday Bondhugula94a03f82019-01-22 21:58:521086 // 'outerIVs' holds the values that this memory region is symbolic/paramteric
1087 // on; this would correspond to loop IVs surrounding the level at which the
1088 // slice is being materialized.
1089 SmallVector<Value *, 8> outerIVs;
1090 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
1091
1092 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:271093 SmallVector<AffineExpr, 4> offsets;
1094 offsets.reserve(rank);
1095 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:521096 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
1097
MLIR Teamc4237ae2019-01-18 16:56:271098 AffineExpr offset = top.getAffineConstantExpr(0);
1099 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
1100 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
1101 }
Uday Bondhugula94a03f82019-01-22 21:58:521102 assert(lbDivisors[d] > 0);
1103 offset =
1104 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:271105 offsets.push_back(offset);
1106 }
1107
1108 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
1109 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:221110 uint64_t bufSize =
1111 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
1112 unsigned newMemSpace;
Uday Bondhugulad4b3ff12019-02-27 00:10:191113 if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
Uday Bondhugula8be26272019-02-02 01:06:221114 newMemSpace = fastMemorySpace.getValue();
1115 } else {
1116 newMemSpace = oldMemRefType.getMemorySpace();
1117 }
1118 auto newMemRefType = top.getMemRefType(
1119 newShape, oldMemRefType.getElementType(), {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:271120 // Gather alloc operands for the dynamic dimensions of the memref.
1121 SmallVector<Value *, 4> allocOperands;
1122 unsigned dynamicDimCount = 0;
1123 for (auto dimSize : oldMemRefType.getShape()) {
1124 if (dimSize == -1)
1125 allocOperands.push_back(
River Riddle5052bd82019-02-02 00:42:181126 top.create<DimOp>(forOp->getLoc(), oldMemRef, dynamicDimCount++));
MLIR Teamc4237ae2019-01-18 16:56:271127 }
1128
River Riddle5052bd82019-02-02 00:42:181129 // Create new private memref for fused loop 'forOp'.
MLIR Teama0f3db402019-01-29 17:36:411130 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
1131 // consumer loop nests to reduce their live range. Currently they are added
1132 // at the beginning of the function, because loop nests can be reordered
1133 // during the fusion pass.
MLIR Teamc4237ae2019-01-18 16:56:271134 Value *newMemRef =
River Riddle5052bd82019-02-02 00:42:181135 top.create<AllocOp>(forOp->getLoc(), newMemRefType, allocOperands);
MLIR Teamc4237ae2019-01-18 16:56:271136
1137 // Build an AffineMap to remap access functions based on lower bound offsets.
1138 SmallVector<AffineExpr, 4> remapExprs;
1139 remapExprs.reserve(rank);
1140 unsigned zeroOffsetCount = 0;
1141 for (unsigned i = 0; i < rank; i++) {
1142 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
1143 if (constExpr.getValue() == 0)
1144 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:521145 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
1146
1147 auto remapExpr =
1148 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
1149 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:271150 }
Uday Bondhugula94a03f82019-01-22 21:58:521151 auto indexRemap =
1152 zeroOffsetCount == rank
Nicolas Vasilache0e7a8a92019-01-26 18:41:171153 ? AffineMap()
Uday Bondhugula94a03f82019-01-22 21:58:521154 : b.getAffineMap(outerIVs.size() + rank, 0, remapExprs, {});
MLIR Teamc4237ae2019-01-18 16:56:271155 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugula94a03f82019-01-22 21:58:521156 bool ret =
1157 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
1158 /*extraOperands=*/outerIVs,
River Riddle5052bd82019-02-02 00:42:181159 /*domInstFilter=*/&*forOp->getBody()->begin());
Uday Bondhugula94a03f82019-01-22 21:58:521160 assert(ret && "replaceAllMemrefUsesWith should always succeed here");
MLIR Team71495d52019-01-22 21:23:371161 (void)ret;
MLIR Teamc4237ae2019-01-18 16:56:271162 return newMemRef;
1163}
1164
Uday Bondhugula864d9e02019-01-23 17:16:241165// Does the slice have a single iteration?
1166static uint64_t getSliceIterationCount(
River Riddle5052bd82019-02-02 00:42:181167 const llvm::SmallDenseMap<Instruction *, uint64_t, 8> &sliceTripCountMap) {
Uday Bondhugula864d9e02019-01-23 17:16:241168 uint64_t iterCount = 1;
1169 for (const auto &count : sliceTripCountMap) {
1170 iterCount *= count.second;
1171 }
1172 return iterCount;
1173}
1174
MLIR Team58aa3832019-02-16 01:12:191175// Checks if node 'srcId' (which writes to a live out memref), can be safely
1176// fused into node 'dstId'. Returns true if the following conditions are met:
1177// *) 'srcNode' writes only writes to live out 'memref'.
1178// *) 'srcNode' has exaclty one output edge on 'memref' (which is to 'dstId').
1179// *) 'dstNode' does write to 'memref'.
1180// *) 'dstNode's write region to 'memref' is a super set of 'srcNode's write
1181// region to 'memref'.
1182// TODO(andydavis) Generalize this to handle more live in/out cases.
1183static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
1184 Value *memref,
1185 MemRefDependenceGraph *mdg) {
1186 auto *srcNode = mdg->getNode(srcId);
1187 auto *dstNode = mdg->getNode(dstId);
1188
1189 // Return false if any of the following are true:
1190 // *) 'srcNode' writes to a live in/out memref other than 'memref'.
1191 // *) 'srcNode' has more than one output edge on 'memref'.
1192 // *) 'dstNode' does not write to 'memref'.
1193 if (srcNode->getStoreOpCount(memref) != 1 ||
1194 mdg->getOutEdgeCount(srcNode->id, memref) != 1 ||
1195 dstNode->getStoreOpCount(memref) == 0)
1196 return false;
1197 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOpInst' on 'memref'.
1198 auto *srcStoreOpInst = srcNode->stores.front();
1199 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
1200 srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0);
1201 SmallVector<int64_t, 4> srcShape;
1202 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
1203 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1204 Optional<int64_t> srcNumElements =
1205 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1206 if (!srcNumElements.hasValue())
1207 return false;
1208
1209 // Compute MemRefRegion 'dstWriteRegion' for 'dstStoreOpInst' on 'memref'.
1210 SmallVector<Instruction *, 2> dstStoreOps;
1211 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1212 assert(dstStoreOps.size() == 1);
1213 auto *dstStoreOpInst = dstStoreOps[0];
1214 MemRefRegion dstWriteRegion(dstStoreOpInst->getLoc());
1215 dstWriteRegion.compute(dstStoreOpInst, /*loopDepth=*/0);
1216 SmallVector<int64_t, 4> dstShape;
1217 // Query 'dstWriteRegion' for 'dstShape' and 'dstNumElements'.
1218 // by 'dstStoreOpInst' at depth 'dstLoopDepth'.
1219 Optional<int64_t> dstNumElements =
1220 dstWriteRegion.getConstantBoundingSizeAndShape(&dstShape);
1221 if (!dstNumElements.hasValue())
1222 return false;
1223
1224 // Return false if write region is not a superset of 'srcNodes' write
1225 // region to 'memref'.
1226 // TODO(andydavis) Check the shape and lower bounds here too.
1227 if (srcNumElements != dstNumElements)
1228 return false;
1229 return true;
1230}
1231
MLIR Team27d067e2019-01-16 17:55:021232// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411233// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
Uday Bondhugulab4a14432019-01-26 00:00:501234// Returns true if it is profitable to fuse the candidate loop nests. Returns
1235// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1236// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251237// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021238// *) Computes the backward computation slice at 'srcOpInst'. This
1239// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251240// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021241// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251242// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1243// loop nest is the total number of dynamic operation instances in the loop
1244// nest).
1245// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021246// loop nest at various values of dst loop depth, attempting to fuse
1247// the largest compution slice at the maximal dst loop depth (closest to the
1248// load) to minimize reuse distance and potentially enable subsequent
1249// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411250// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021251// the same memref as is written by 'srcOpInst', then the union of slice
1252// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501253// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251254// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021255// NOTE: We attempt to maximize the dst loop depth, but there are cases
1256// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251257// loop (within the src computation slice) at a depth which results in
1258// execessive recomputation (see unit tests for examples).
1259// *) Compares the total cost of the unfused loop nests to the min cost fused
1260// loop nest computed in the previous step, and returns true if the latter
1261// is lower.
River Riddleb4992772019-02-04 18:38:471262static bool isFusionProfitable(Instruction *srcOpInst,
1263 ArrayRef<Instruction *> dstLoadOpInsts,
1264 ArrayRef<Instruction *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251265 ComputationSliceState *sliceState,
MLIR Team27d067e2019-01-16 17:55:021266 unsigned *dstLoopDepth) {
Uday Bondhugula06d21d92019-01-25 01:01:491267 LLVM_DEBUG({
1268 llvm::dbgs() << "Checking whether fusion is profitable between:\n";
Uday Bondhugulaa1dad3a2019-02-20 02:17:191269 llvm::dbgs() << " " << *srcOpInst << " and \n";
MLIR Teamd7c82442019-01-30 23:53:411270 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191271 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491272 };
1273 });
Uday Bondhugula864d9e02019-01-23 17:16:241274
MLIR Team38c2fe32019-01-14 19:26:251275 // Compute cost of sliced and unsliced src loop nest.
River Riddle5052bd82019-02-02 00:42:181276 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021277 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251278 unsigned numSrcLoopIVs = srcLoopIVs.size();
1279
1280 // Walk src loop nest and collect stats.
1281 LoopNestStats srcLoopNestStats;
1282 LoopNestStatsCollector srcStatsCollector(&srcLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441283 srcStatsCollector.collect(srcLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251284 // Currently only constant trip count loop nests are supported.
1285 if (srcStatsCollector.hasLoopWithNonConstTripCount)
1286 return false;
1287
1288 // Compute cost of dst loop nest.
River Riddle5052bd82019-02-02 00:42:181289 SmallVector<OpPointer<AffineForOp>, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411290 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251291
1292 LoopNestStats dstLoopNestStats;
1293 LoopNestStatsCollector dstStatsCollector(&dstLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441294 dstStatsCollector.collect(dstLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251295 // Currently only constant trip count loop nests are supported.
1296 if (dstStatsCollector.hasLoopWithNonConstTripCount)
1297 return false;
1298
MLIR Teamd7c82442019-01-30 23:53:411299 // Compute the maximum loop depth at which we can can insert the src slice
1300 // and still satisfy dest loop nest dependences.
1301 unsigned maxDstLoopDepth = getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts);
MLIR Team27d067e2019-01-16 17:55:021302 if (maxDstLoopDepth == 0)
1303 return false;
1304
1305 // Search for min cost value for 'dstLoopDepth'. At each value of
1306 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1307 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1308 // of these bounds). Next the union slice bounds are used to calculate
1309 // the cost of the slice and the cost of the slice inserted into the dst
1310 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241311 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
1312 uint64_t maxStorageReduction = 0;
1313 Optional<uint64_t> sliceMemEstimate = None;
1314
MLIR Team27d067e2019-01-16 17:55:021315 SmallVector<ComputationSliceState, 4> sliceStates;
1316 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241317 // The best loop depth at which to materialize the slice.
1318 Optional<unsigned> bestDstLoopDepth = None;
1319
1320 // Compute op instance count for the src loop nest without iteration slicing.
River Riddle5052bd82019-02-02 00:42:181321 uint64_t srcLoopNestCost =
1322 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
1323 /*tripCountOverrideMap=*/nullptr,
1324 /*computeCostMap=*/nullptr);
Uday Bondhugula864d9e02019-01-23 17:16:241325
MLIR Teamb9dde912019-02-06 19:01:101326 // Compute src loop nest write region size.
1327 MemRefRegion srcWriteRegion(srcOpInst->getLoc());
1328 srcWriteRegion.compute(srcOpInst, /*loopDepth=*/0);
1329 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1330 srcWriteRegion.getRegionSize();
1331 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1332 return false;
1333 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1334
Uday Bondhugula864d9e02019-01-23 17:16:241335 // Compute op instance count for the src loop nest.
River Riddle5052bd82019-02-02 00:42:181336 uint64_t dstLoopNestCost =
1337 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
1338 /*tripCountOverrideMap=*/nullptr,
1339 /*computeCostMap=*/nullptr);
MLIR Team27d067e2019-01-16 17:55:021340
MLIR Teamb9dde912019-02-06 19:01:101341 // Evaluate all depth choices for materializing the slice in the destination
1342 // loop nest.
River Riddle5052bd82019-02-02 00:42:181343 llvm::SmallDenseMap<Instruction *, uint64_t, 8> sliceTripCountMap;
1344 DenseMap<Instruction *, int64_t> computeCostMap;
MLIR Team27d067e2019-01-16 17:55:021345 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
1346 MemRefAccess srcAccess(srcOpInst);
1347 // Handle the common case of one dst load without a copy.
1348 if (!mlir::getBackwardComputationSliceState(
MLIR Teamd7c82442019-01-30 23:53:411349 srcAccess, MemRefAccess(dstLoadOpInsts[0]), i, &sliceStates[i - 1]))
MLIR Team27d067e2019-01-16 17:55:021350 return false;
MLIR Teamd7c82442019-01-30 23:53:411351 // Compute the union of slice bound of all ops in 'dstLoadOpInsts'.
1352 for (int j = 1, e = dstLoadOpInsts.size(); j < e; ++j) {
1353 MemRefAccess dstAccess(dstLoadOpInsts[j]);
MLIR Team27d067e2019-01-16 17:55:021354 ComputationSliceState tmpSliceState;
1355 if (!mlir::getBackwardComputationSliceState(srcAccess, dstAccess, i,
1356 &tmpSliceState))
1357 return false;
1358 // Compute slice boun dunion of 'tmpSliceState' and 'sliceStates[i - 1]'.
Uday Bondhugulac1ca23e2019-01-16 21:13:001359 getSliceUnion(tmpSliceState, &sliceStates[i - 1]);
MLIR Team38c2fe32019-01-14 19:26:251360 }
Uday Bondhugulab4a14432019-01-26 00:00:501361 // Build trip count map for computation slice. We'll skip cases where the
1362 // trip count was non-constant.
MLIR Team27d067e2019-01-16 17:55:021363 sliceTripCountMap.clear();
1364 if (!buildSliceTripCountMap(srcOpInst, &sliceStates[i - 1],
1365 &sliceTripCountMap))
Uday Bondhugula864d9e02019-01-23 17:16:241366 continue;
1367
1368 // Checks whether a store to load forwarding will happen.
1369 int64_t sliceIterationCount = getSliceIterationCount(sliceTripCountMap);
Uday Bondhugula864d9e02019-01-23 17:16:241370 assert(sliceIterationCount > 0);
Uday Bondhugulab4a14432019-01-26 00:00:501371 bool storeLoadFwdGuaranteed = (sliceIterationCount == 1);
Uday Bondhugula864d9e02019-01-23 17:16:241372
1373 // Compute cost of fusion for this dest loop depth.
1374
1375 computeCostMap.clear();
1376
1377 // The store and loads to this memref will disappear.
1378 if (storeLoadFwdGuaranteed) {
1379 // A single store disappears: -1 for that.
River Riddle5052bd82019-02-02 00:42:181380 computeCostMap[srcLoopIVs[numSrcLoopIVs - 1]->getInstruction()] = -1;
MLIR Teamd7c82442019-01-30 23:53:411381 for (auto *loadOp : dstLoadOpInsts) {
River Riddle5052bd82019-02-02 00:42:181382 auto *parentInst = loadOp->getParentInst();
River Riddleb4992772019-02-04 18:38:471383 if (parentInst && parentInst->isa<AffineForOp>())
River Riddle5052bd82019-02-02 00:42:181384 computeCostMap[parentInst] = -1;
Uday Bondhugula864d9e02019-01-23 17:16:241385 }
1386 }
MLIR Team27d067e2019-01-16 17:55:021387
MLIR Team38c2fe32019-01-14 19:26:251388 // Compute op instance count for the src loop nest with iteration slicing.
Uday Bondhugula864d9e02019-01-23 17:16:241389 int64_t sliceComputeCost =
River Riddle5052bd82019-02-02 00:42:181390 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
Uday Bondhugula864d9e02019-01-23 17:16:241391 /*tripCountOverrideMap=*/&sliceTripCountMap,
1392 /*computeCostMap=*/&computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:251393
Uday Bondhugula864d9e02019-01-23 17:16:241394 // Compute cost of fusion for this depth.
River Riddle5052bd82019-02-02 00:42:181395 computeCostMap[dstLoopIVs[i - 1]->getInstruction()] = sliceComputeCost;
Uday Bondhugula864d9e02019-01-23 17:16:241396
1397 int64_t fusedLoopNestComputeCost =
River Riddle5052bd82019-02-02 00:42:181398 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
MLIR Team27d067e2019-01-16 17:55:021399 /*tripCountOverrideMap=*/nullptr, &computeCostMap);
Uday Bondhugula864d9e02019-01-23 17:16:241400
1401 double additionalComputeFraction =
1402 fusedLoopNestComputeCost /
1403 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1404 1;
1405
MLIR Teamb9dde912019-02-06 19:01:101406 // Compute what the slice write MemRefRegion would be, if the src loop
1407 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1408 // nest at loop depth 'i'
1409 MemRefRegion sliceWriteRegion(srcOpInst->getLoc());
1410 sliceWriteRegion.compute(srcOpInst, /*loopDepth=*/0, &sliceStates[i - 1]);
1411 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1412 sliceWriteRegion.getRegionSize();
1413 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
1414 maybeSliceWriteRegionSizeBytes.getValue() == 0)
1415 continue;
1416 int64_t sliceWriteRegionSizeBytes =
1417 maybeSliceWriteRegionSizeBytes.getValue();
1418
1419 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1420 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241421
Uday Bondhugula06d21d92019-01-25 01:01:491422 LLVM_DEBUG({
1423 std::stringstream msg;
1424 msg << " evaluating fusion profitability at depth : " << i << "\n"
Uday Bondhugulad4b3ff12019-02-27 00:10:191425 << std::fixed << std::setprecision(2)
1426 << " additional compute fraction: "
Uday Bondhugula06d21d92019-01-25 01:01:491427 << 100.0 * additionalComputeFraction << "%\n"
1428 << " storage reduction factor: " << storageReduction << "x\n"
1429 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191430 << " slice iteration count: " << sliceIterationCount << "\n"
1431 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1432 << " slice write region size: " << sliceWriteRegionSizeBytes
1433 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491434 llvm::dbgs() << msg.str();
1435 });
Uday Bondhugula864d9e02019-01-23 17:16:241436
1437 double computeToleranceThreshold =
1438 clFusionAddlComputeTolerance.getNumOccurrences() > 0
1439 ? clFusionAddlComputeTolerance
1440 : LoopFusion::kComputeToleranceThreshold;
1441
1442 // TODO(b/123247369): This is a placeholder cost model.
1443 // Among all choices that add an acceptable amount of redundant computation
1444 // (as per computeToleranceThreshold), we will simply pick the one that
1445 // reduces the intermediary size the most.
1446 if ((storageReduction > maxStorageReduction) &&
1447 (clMaximalLoopFusion ||
1448 (additionalComputeFraction < computeToleranceThreshold))) {
1449 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021450 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241451 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101452 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251453 }
1454 }
1455
Uday Bondhugula864d9e02019-01-23 17:16:241456 // A simple cost model: fuse if it reduces the memory footprint. If
1457 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251458
Uday Bondhugula864d9e02019-01-23 17:16:241459 if (!clMaximalLoopFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191460 LLVM_DEBUG(
1461 llvm::dbgs()
1462 << "All fusion choices involve more than the threshold amount of "
1463 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251464 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241465 }
1466
1467 assert(bestDstLoopDepth.hasValue() &&
1468 "expected to have a value per logic above");
1469
1470 // Set dstLoopDepth based on best values from search.
1471 *dstLoopDepth = bestDstLoopDepth.getValue();
1472
1473 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491474 llvm::dbgs() << " LoopFusion fusion stats:"
1475 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241476 << "\n src loop nest compute cost: " << srcLoopNestCost
1477 << "\n dst loop nest compute cost: " << dstLoopNestCost
1478 << "\n fused loop nest compute cost: "
1479 << minFusedLoopNestComputeCost << "\n");
1480
River Riddle5052bd82019-02-02 00:42:181481 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1482 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241483
1484 Optional<double> storageReduction = None;
1485
1486 if (!clMaximalLoopFusion) {
1487 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1488 LLVM_DEBUG(
1489 llvm::dbgs()
1490 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1491 return false;
1492 }
1493
1494 auto srcMemSizeVal = srcMemSize.getValue();
1495 auto dstMemSizeVal = dstMemSize.getValue();
1496
1497 assert(sliceMemEstimate.hasValue() && "expected value");
1498 // This is an inaccurate estimate since sliceMemEstimate is isaccurate.
1499 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1500
1501 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1502 << " dst mem: " << dstMemSizeVal << "\n"
1503 << " fused mem: " << fusedMem << "\n"
1504 << " slice mem: " << sliceMemEstimate << "\n");
1505
1506 if (fusedMem > srcMemSizeVal + dstMemSizeVal) {
1507 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1508 return false;
1509 }
1510 storageReduction =
1511 100.0 *
1512 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1513 }
1514
1515 double additionalComputeFraction =
1516 100.0 * (minFusedLoopNestComputeCost /
1517 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1518 1);
MLIR Team5c5739d2019-01-25 06:27:401519 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491520 LLVM_DEBUG({
1521 std::stringstream msg;
1522 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591523 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491524 << "% redundant computation and a ";
1525 msg << (storageReduction.hasValue()
1526 ? std::to_string(storageReduction.getValue())
1527 : "<unknown>");
1528 msg << "% storage reduction.\n";
1529 llvm::dbgs() << msg.str();
1530 });
Uday Bondhugula864d9e02019-01-23 17:16:241531
MLIR Team27d067e2019-01-16 17:55:021532 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241533 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021534 sliceState->lbs = bestSliceState->lbs;
1535 sliceState->ubs = bestSliceState->ubs;
1536 sliceState->lbOperands = bestSliceState->lbOperands;
1537 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241538
MLIR Team27d067e2019-01-16 17:55:021539 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251540 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171541 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021542 canonicalizeMapAndOperands(&sliceState->lbs[i],
1543 &sliceState->lbOperands[i]);
1544 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171545 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021546 canonicalizeMapAndOperands(&sliceState->ubs[i],
1547 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251548 }
1549 }
1550 return true;
1551}
1552
MLIR Team6892ffb2018-12-20 04:42:551553// GreedyFusion greedily fuses loop nests which have a producer/consumer
MLIR Team3b692302018-12-17 17:57:141554// relationship on a memref, with the goal of improving locality. Currently,
1555// this the producer/consumer relationship is required to be unique in the
Chris Lattner69d9e992018-12-28 16:48:091556// Function (there are TODOs to relax this constraint in the future).
MLIR Teamf28e4df2018-11-01 14:26:001557//
MLIR Team3b692302018-12-17 17:57:141558// The steps of the algorithm are as follows:
1559//
MLIR Team6892ffb2018-12-20 04:42:551560// *) A worklist is initialized with node ids from the dependence graph.
1561// *) For each node id in the worklist:
River Riddle5052bd82019-02-02 00:42:181562// *) Pop a AffineForOp of the worklist. This 'dstAffineForOp' will be a
1563// candidate destination AffineForOp into which fusion will be attempted.
1564// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141565// *) For each LoadOp in 'dstLoadOps' do:
Chris Lattner69d9e992018-12-28 16:48:091566// *) Lookup dependent loop nests at earlier positions in the Function
MLIR Team3b692302018-12-17 17:57:141567// which have a single store op to the same memref.
1568// *) Check if dependences would be violated by the fusion. For example,
1569// the src loop nest may load from memrefs which are different than
1570// the producer-consumer memref between src and dest loop nests.
MLIR Team6892ffb2018-12-20 04:42:551571// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141572// bounds to be functions of 'dstLoopNest' IVs and symbols.
1573// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
1574// just before the dst load op user.
Chris Lattner456ad6a2018-12-29 00:05:351575// *) Add the newly fused load/store operation instructions to the state,
MLIR Team3b692302018-12-17 17:57:141576// and also add newly fuse load ops to 'dstLoopOps' to be considered
1577// as fusion dst load ops in another iteration.
1578// *) Remove old src loop nest and its associated state.
1579//
Chris Lattner456ad6a2018-12-29 00:05:351580// Given a graph where top-level instructions are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141581// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551582// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141583//
MLIR Team6892ffb2018-12-20 04:42:551584// This greedy algorithm is not 'maximal' due to the current restriction of
1585// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141586//
1587// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551588// TODO(andydavis) Add support for fusing for input reuse (perhaps by
1589// constructing a graph with edges which represent loads from the same memref
MLIR Team5c5739d2019-01-25 06:27:401590// in two different loop nests.
MLIR Team6892ffb2018-12-20 04:42:551591struct GreedyFusion {
1592public:
1593 MemRefDependenceGraph *mdg;
MLIR Teama78edcd2019-02-05 14:57:081594 SmallVector<unsigned, 8> worklist;
1595 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamf28e4df2018-11-01 14:26:001596
MLIR Team6892ffb2018-12-20 04:42:551597 GreedyFusion(MemRefDependenceGraph *mdg) : mdg(mdg) {
1598 // Initialize worklist with nodes from 'mdg'.
MLIR Teama78edcd2019-02-05 14:57:081599 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1600 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Team6892ffb2018-12-20 04:42:551601 worklist.resize(mdg->nodes.size());
1602 std::iota(worklist.begin(), worklist.end(), 0);
MLIR Teama78edcd2019-02-05 14:57:081603 worklistSet.insert(worklist.begin(), worklist.end());
MLIR Team6892ffb2018-12-20 04:42:551604 }
MLIR Team3b692302018-12-17 17:57:141605
Uday Bondhugula8be26272019-02-02 01:06:221606 void run(unsigned localBufSizeThreshold, Optional<unsigned> fastMemorySpace) {
MLIR Team3b692302018-12-17 17:57:141607 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551608 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141609 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081610 worklistSet.erase(dstId);
1611
MLIR Team6892ffb2018-12-20 04:42:551612 // Skip if this node was removed (fused into another node).
1613 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141614 continue;
MLIR Team6892ffb2018-12-20 04:42:551615 // Get 'dstNode' into which to attempt fusion.
1616 auto *dstNode = mdg->getNode(dstId);
1617 // Skip if 'dstNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471618 if (!dstNode->inst->isa<AffineForOp>())
MLIR Team3b692302018-12-17 17:57:141619 continue;
MLIR Team8f5f2c72019-02-15 17:32:181620 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1621 // while preserving relative order. This can increase the maximum loop
1622 // depth at which we can fuse a slice of a producer loop nest into a
1623 // consumer loop nest.
1624 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141625
River Riddleb4992772019-02-04 18:38:471626 SmallVector<Instruction *, 4> loads = dstNode->loads;
1627 SmallVector<Instruction *, 4> dstLoadOpInsts;
MLIR Teamc4237ae2019-01-18 16:56:271628 DenseSet<Value *> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551629 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021630 // Get memref of load on top of the stack.
1631 auto *memref = loads.back()->cast<LoadOp>()->getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271632 if (visitedMemrefs.count(memref) > 0)
1633 continue;
1634 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021635 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1636 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551637 // Skip if no input edges along which to fuse.
1638 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141639 continue;
MLIR Team1e851912019-01-31 00:01:461640 // Iterate through in edges for 'dstId' and src node id for any
1641 // edges on 'memref'.
1642 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551643 for (auto &srcEdge : mdg->inEdges[dstId]) {
1644 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411645 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551646 continue;
MLIR Team1e851912019-01-31 00:01:461647 srcNodeIds.push_back(srcEdge.id);
1648 }
1649 for (unsigned srcId : srcNodeIds) {
1650 // Skip if this node was removed (fused into another node).
1651 if (mdg->nodes.count(srcId) == 0)
1652 continue;
1653 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1654 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551655 // Skip if 'srcNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471656 if (!srcNode->inst->isa<AffineForOp>())
MLIR Team6892ffb2018-12-20 04:42:551657 continue;
MLIR Teamb28009b2019-01-23 19:11:431658 // Skip if 'srcNode' has more than one store to any memref.
1659 // TODO(andydavis) Support fusing multi-output src loop nests.
1660 if (srcNode->stores.size() != 1)
MLIR Team6892ffb2018-12-20 04:42:551661 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241662
MLIR Teama0f3db402019-01-29 17:36:411663 // Skip 'srcNode' if it has in edges on 'memref'.
MLIR Team6892ffb2018-12-20 04:42:551664 // TODO(andydavis) Track dependence type with edges, and just check
MLIR Teama0f3db402019-01-29 17:36:411665 // for WAW dependence edge here. Note that this check is overly
1666 // conservative and will be removed in the future.
1667 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) != 0)
MLIR Team6892ffb2018-12-20 04:42:551668 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241669
MLIR Team58aa3832019-02-16 01:12:191670 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1671 // and cannot be fused.
1672 bool writesToLiveInOrOut =
1673 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1674 if (writesToLiveInOrOut &&
1675 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, memref, mdg))
MLIR Teamd7c82442019-01-30 23:53:411676 continue;
1677
MLIR Teama0f3db402019-01-29 17:36:411678 // Compute an instruction list insertion point for the fused loop
1679 // nest which preserves dependences.
MLIR Teama78edcd2019-02-05 14:57:081680 Instruction *insertPointInst =
1681 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411682 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551683 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241684
MLIR Team6892ffb2018-12-20 04:42:551685 // Get unique 'srcNode' store op.
Chris Lattner456ad6a2018-12-29 00:05:351686 auto *srcStoreOpInst = srcNode->stores.front();
MLIR Teamd7c82442019-01-30 23:53:411687 // Gather 'dstNode' store ops to 'memref'.
River Riddleb4992772019-02-04 18:38:471688 SmallVector<Instruction *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411689 for (auto *storeOpInst : dstNode->stores)
1690 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1691 dstStoreOpInsts.push_back(storeOpInst);
1692
Uday Bondhugulab4a14432019-01-26 00:00:501693 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251694 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411695 // Check if fusion would be profitable.
MLIR Teamd7c82442019-01-30 23:53:411696 if (!isFusionProfitable(srcStoreOpInst, dstLoadOpInsts,
1697 dstStoreOpInsts, &sliceState,
Uday Bondhugulab4a14432019-01-26 00:00:501698 &bestDstLoopDepth))
MLIR Team38c2fe32019-01-14 19:26:251699 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241700
MLIR Team6892ffb2018-12-20 04:42:551701 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181702 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Uday Bondhugulab4a14432019-01-26 00:00:501703 srcStoreOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
MLIR Team6892ffb2018-12-20 04:42:551704 if (sliceLoopNest != nullptr) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191705 LLVM_DEBUG(llvm::dbgs()
1706 << "\tslice loop nest:\n"
1707 << *sliceLoopNest->getInstruction() << "\n");
River Riddle5052bd82019-02-02 00:42:181708 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleb4992772019-02-04 18:38:471709 auto dstAffineForOp = dstNode->inst->cast<AffineForOp>();
River Riddle5052bd82019-02-02 00:42:181710 if (insertPointInst != dstAffineForOp->getInstruction()) {
1711 dstAffineForOp->getInstruction()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411712 }
MLIR Teamc4237ae2019-01-18 16:56:271713 // Update edges between 'srcNode' and 'dstNode'.
MLIR Teama0f3db402019-01-29 17:36:411714 mdg->updateEdges(srcNode->id, dstNode->id, memref);
MLIR Teamc4237ae2019-01-18 16:56:271715
1716 // Collect slice loop stats.
1717 LoopNestStateCollector sliceCollector;
River Riddlebf9c3812019-02-05 00:24:441718 sliceCollector.collect(sliceLoopNest->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271719 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181720 for (auto forOp : sliceCollector.forOps) {
1721 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551722 }
MLIR Team58aa3832019-02-16 01:12:191723 if (!writesToLiveInOrOut) {
1724 // Create private memref for 'memref' in 'dstAffineForOp'.
1725 SmallVector<Instruction *, 4> storesForMemref;
1726 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
1727 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1728 storesForMemref.push_back(storeOpInst);
1729 }
1730 assert(storesForMemref.size() == 1);
1731 auto *newMemRef = createPrivateMemRef(
1732 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1733 fastMemorySpace, localBufSizeThreshold);
1734 visitedMemrefs.insert(newMemRef);
1735 // Create new node in dependence graph for 'newMemRef' alloc op.
1736 unsigned newMemRefNodeId =
1737 mdg->addNode(newMemRef->getDefiningInst());
1738 // Add edge from 'newMemRef' node to dstNode.
1739 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271740 }
MLIR Teamc4237ae2019-01-18 16:56:271741
1742 // Collect dst loop stats after memref privatizaton transformation.
1743 LoopNestStateCollector dstLoopCollector;
River Riddlebf9c3812019-02-05 00:24:441744 dstLoopCollector.collect(dstAffineForOp->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271745
1746 // Add new load ops to current Node load op list 'loads' to
1747 // continue fusing based on new operands.
1748 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
1749 auto *loadMemRef = loadOpInst->cast<LoadOp>()->getMemRef();
1750 if (visitedMemrefs.count(loadMemRef) == 0)
1751 loads.push_back(loadOpInst);
1752 }
1753
1754 // Clear and add back loads and stores
1755 mdg->clearNodeLoadAndStores(dstNode->id);
1756 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1757 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371758 // Remove old src loop nest if it no longer has outgoing dependence
1759 // edges, and it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191760 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1761 // been fused into 'dstNode' and write region of 'dstNode' covers
1762 // the write region of 'srcNode', and 'srcNode' has no other users
1763 // so it is safe to remove.
1764 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271765 mdg->removeNode(srcNode->id);
River Riddle5052bd82019-02-02 00:42:181766 srcNode->inst->erase();
MLIR Teama78edcd2019-02-05 14:57:081767 } else {
1768 // Add remaining users of 'oldMemRef' back on the worklist (if not
1769 // already there), as its replacement with a local/private memref
1770 // has reduced dependences on 'oldMemRef' which may have created
1771 // new fusion opportunities.
1772 if (mdg->outEdges.count(srcNode->id) > 0) {
1773 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1774 mdg->outEdges[srcNode->id];
1775 for (auto &outEdge : oldOutEdges) {
1776 if (outEdge.value == memref &&
1777 worklistSet.count(outEdge.id) == 0) {
1778 worklist.push_back(outEdge.id);
1779 worklistSet.insert(outEdge.id);
1780 }
1781 }
1782 }
MLIR Teamc4237ae2019-01-18 16:56:271783 }
MLIR Team3b692302018-12-17 17:57:141784 }
MLIR Team3b692302018-12-17 17:57:141785 }
1786 }
1787 }
MLIR Teamc4237ae2019-01-18 16:56:271788 // Clean up any allocs with no users.
1789 for (auto &pair : mdg->memrefEdgeCount) {
1790 if (pair.second > 0)
1791 continue;
1792 auto *memref = pair.first;
MLIR Team71495d52019-01-22 21:23:371793 // Skip if there exist other uses (return instruction or function calls).
1794 if (!memref->use_empty())
1795 continue;
MLIR Teamc4237ae2019-01-18 16:56:271796 // Use list expected to match the dep graph info.
MLIR Teamc4237ae2019-01-18 16:56:271797 auto *inst = memref->getDefiningInst();
River Riddleb4992772019-02-04 18:38:471798 if (inst && inst->isa<AllocOp>())
1799 inst->erase();
MLIR Teamc4237ae2019-01-18 16:56:271800 }
MLIR Teamf28e4df2018-11-01 14:26:001801 }
MLIR Team3b692302018-12-17 17:57:141802};
1803
1804} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001805
Chris Lattner79748892018-12-31 07:10:351806PassResult LoopFusion::runOnFunction(Function *f) {
Uday Bondhugulad4b3ff12019-02-27 00:10:191807 // Override if a command line argument was provided.
Uday Bondhugula8be26272019-02-02 01:06:221808 if (clFusionFastMemorySpace.getNumOccurrences() > 0) {
1809 fastMemorySpace = clFusionFastMemorySpace.getValue();
1810 }
1811
Uday Bondhugulad4b3ff12019-02-27 00:10:191812 // Override if a command line argument was provided.
1813 if (clFusionLocalBufThreshold.getNumOccurrences() > 0) {
1814 localBufSizeThreshold = clFusionLocalBufThreshold * 1024;
1815 }
1816
MLIR Team6892ffb2018-12-20 04:42:551817 MemRefDependenceGraph g;
1818 if (g.init(f))
Uday Bondhugula8be26272019-02-02 01:06:221819 GreedyFusion(&g).run(localBufSizeThreshold, fastMemorySpace);
MLIR Teamf28e4df2018-11-01 14:26:001820 return success();
1821}
Jacques Pienaar6f0fb222018-11-07 02:34:181822
1823static PassRegistration<LoopFusion> pass("loop-fusion", "Fuse loop nests");