blob: 1528e394506e60060f088908f1e0b53685eaf7b7 [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"
29#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
River Riddlec6c53442019-02-27 18:59:2989struct LoopFusion : public FunctionPass<LoopFusion> {
Uday Bondhugulad4b3ff12019-02-27 00:10:1990 LoopFusion(unsigned fastMemorySpace = 0, uint64_t localBufSizeThreshold = 0)
River Riddlec6c53442019-02-27 18:59:2991 : localBufSizeThreshold(localBufSizeThreshold),
Uday Bondhugulad4b3ff12019-02-27 00:10:1992 fastMemorySpace(fastMemorySpace) {}
MLIR Teamf28e4df2018-11-01 14:26:0093
River Riddlec6c53442019-02-27 18:59:2994 PassResult runOnFunction() override;
Uday Bondhugula864d9e02019-01-23 17:16:2495
Uday Bondhugulad4b3ff12019-02-27 00:10:1996 // Any local buffers smaller than this size (in bytes) will be created in
Uday Bondhugula8be26272019-02-02 01:06:2297 // `fastMemorySpace` if provided.
Uday Bondhugulad4b3ff12019-02-27 00:10:1998 uint64_t localBufSizeThreshold;
Uday Bondhugula8be26272019-02-02 01:06:2299 Optional<unsigned> fastMemorySpace = None;
100
Uday Bondhugula864d9e02019-01-23 17:16:24101 // The amount of additional computation that is tolerated while fusing
102 // pair-wise as a fraction of the total computation.
103 constexpr static double kComputeToleranceThreshold = 0.30f;
MLIR Teamf28e4df2018-11-01 14:26:00104};
105
MLIR Teamf28e4df2018-11-01 14:26:00106} // end anonymous namespace
107
River Riddlec6c53442019-02-27 18:59:29108FunctionPassBase *mlir::createLoopFusionPass(unsigned fastMemorySpace,
109 uint64_t localBufSizeThreshold) {
Uday Bondhugulad4b3ff12019-02-27 00:10:19110 return new LoopFusion(fastMemorySpace, localBufSizeThreshold);
111}
MLIR Teamf28e4df2018-11-01 14:26:00112
MLIR Team3b692302018-12-17 17:57:14113namespace {
MLIR Teamf28e4df2018-11-01 14:26:00114
MLIR Team3b692302018-12-17 17:57:14115// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:35116// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:44117struct LoopNestStateCollector {
River Riddle5052bd82019-02-02 00:42:18118 SmallVector<OpPointer<AffineForOp>, 4> forOps;
River Riddleb4992772019-02-04 18:38:47119 SmallVector<Instruction *, 4> loadOpInsts;
120 SmallVector<Instruction *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:53121 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:14122
River Riddlebf9c3812019-02-05 00:24:44123 void collect(Instruction *instToWalk) {
124 instToWalk->walk([&](Instruction *opInst) {
125 if (opInst->isa<AffineForOp>())
126 forOps.push_back(opInst->cast<AffineForOp>());
127 else if (opInst->getNumBlockLists() != 0)
128 hasNonForRegion = true;
129 else if (opInst->isa<LoadOp>())
130 loadOpInsts.push_back(opInst);
131 else if (opInst->isa<StoreOp>())
132 storeOpInsts.push_back(opInst);
133 });
MLIR Team3b692302018-12-17 17:57:14134 }
135};
136
MLIR Team71495d52019-01-22 21:23:37137// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
River Riddleb4992772019-02-04 18:38:47138static bool isMemRefDereferencingOp(const Instruction &op) {
MLIR Team71495d52019-01-22 21:23:37139 if (op.isa<LoadOp>() || op.isa<StoreOp>() || op.isa<DmaStartOp>() ||
140 op.isa<DmaWaitOp>())
141 return true;
142 return false;
143}
MLIR Team6892ffb2018-12-20 04:42:55144// MemRefDependenceGraph is a graph data structure where graph nodes are
Chris Lattner456ad6a2018-12-29 00:05:35145// top-level instructions in a Function which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55146// are memref dependences between the nodes.
MLIR Teamc4237ae2019-01-18 16:56:27147// TODO(andydavis) Add a more flexible dependece graph representation.
MLIR Team6892ffb2018-12-20 04:42:55148// TODO(andydavis) Add a depth parameter to dependence graph construction.
149struct MemRefDependenceGraph {
150public:
151 // Node represents a node in the graph. A Node is either an entire loop nest
152 // rooted at the top level which contains loads/stores, or a top level
153 // load/store.
154 struct Node {
155 // The unique identifier of this node in the graph.
156 unsigned id;
157 // The top-level statment which is (or contains) loads/stores.
Chris Lattner456ad6a2018-12-29 00:05:35158 Instruction *inst;
Chris Lattner5187cfc2018-12-28 05:21:41159 // List of load operations.
River Riddleb4992772019-02-04 18:38:47160 SmallVector<Instruction *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35161 // List of store op insts.
River Riddleb4992772019-02-04 18:38:47162 SmallVector<Instruction *, 4> stores;
Chris Lattner456ad6a2018-12-29 00:05:35163 Node(unsigned id, Instruction *inst) : id(id), inst(inst) {}
MLIR Team6892ffb2018-12-20 04:42:55164
165 // Returns the load op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10166 unsigned getLoadOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55167 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35168 for (auto *loadOpInst : loads) {
169 if (memref == loadOpInst->cast<LoadOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55170 ++loadOpCount;
171 }
172 return loadOpCount;
173 }
174
175 // Returns the store op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10176 unsigned getStoreOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55177 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35178 for (auto *storeOpInst : stores) {
179 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55180 ++storeOpCount;
181 }
182 return storeOpCount;
183 }
MLIR Team58aa3832019-02-16 01:12:19184
185 // Returns all store ups in 'storeOps' which access 'memref'.
186 void getStoreOpsForMemref(Value *memref,
187 SmallVectorImpl<Instruction *> *storeOps) {
188 for (auto *storeOpInst : stores) {
189 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
190 storeOps->push_back(storeOpInst);
191 }
192 }
MLIR Team6892ffb2018-12-20 04:42:55193 };
194
MLIR Teama0f3db402019-01-29 17:36:41195 // Edge represents a data dependece between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55196 struct Edge {
197 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46198 // If this edge is stored in Edge = Node.inEdges[i], then
199 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
200 // If this edge is stored in Edge = Node.outEdges[i], then
201 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55202 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41203 // The SSA value on which this edge represents a dependence.
204 // If the value is a memref, then the dependence is between graph nodes
205 // which contain accesses to the same memref 'value'. If the value is a
206 // non-memref value, then the dependence is between a graph node which
207 // defines an SSA value and another graph node which uses the SSA value
208 // (e.g. a constant instruction defining a value which is used inside a loop
209 // nest).
210 Value *value;
MLIR Team6892ffb2018-12-20 04:42:55211 };
212
213 // Map from node id to Node.
214 DenseMap<unsigned, Node> nodes;
215 // Map from node id to list of input edges.
216 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
217 // Map from node id to list of output edges.
218 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27219 // Map from memref to a count on the dependence edges associated with that
220 // memref.
221 DenseMap<Value *, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41222 // The next unique identifier to use for newly created graph nodes.
223 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55224
225 MemRefDependenceGraph() {}
226
227 // Initializes the dependence graph based on operations in 'f'.
228 // Returns true on success, false otherwise.
Chris Lattner69d9e992018-12-28 16:48:09229 bool init(Function *f);
MLIR Team6892ffb2018-12-20 04:42:55230
231 // Returns the graph node for 'id'.
232 Node *getNode(unsigned id) {
233 auto it = nodes.find(id);
234 assert(it != nodes.end());
235 return &it->second;
236 }
237
MLIR Teama0f3db402019-01-29 17:36:41238 // Adds a node with 'inst' to the graph and returns its unique identifier.
239 unsigned addNode(Instruction *inst) {
240 Node node(nextNodeId++, inst);
241 nodes.insert({node.id, node});
242 return node.id;
243 }
244
MLIR Teamc4237ae2019-01-18 16:56:27245 // Remove node 'id' (and its associated edges) from graph.
246 void removeNode(unsigned id) {
247 // Remove each edge in 'inEdges[id]'.
248 if (inEdges.count(id) > 0) {
249 SmallVector<Edge, 2> oldInEdges = inEdges[id];
250 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41251 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27252 }
253 }
254 // Remove each edge in 'outEdges[id]'.
255 if (outEdges.count(id) > 0) {
256 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
257 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41258 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27259 }
260 }
261 // Erase remaining node state.
262 inEdges.erase(id);
263 outEdges.erase(id);
264 nodes.erase(id);
265 }
266
MLIR Teamd7c82442019-01-30 23:53:41267 // Returns true if node 'id' writes to any memref which escapes (or is an
268 // argument to) the function/block. Returns false otherwise.
269 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37270 Node *node = getNode(id);
271 for (auto *storeOpInst : node->stores) {
272 auto *memref = storeOpInst->cast<StoreOp>()->getMemRef();
273 auto *inst = memref->getDefiningInst();
MLIR Team58aa3832019-02-16 01:12:19274 // Return true if 'memref' is a block argument.
River Riddleb4992772019-02-04 18:38:47275 if (!inst)
MLIR Teamd7c82442019-01-30 23:53:41276 return true;
MLIR Team58aa3832019-02-16 01:12:19277 // Return true if any use of 'memref' escapes the function.
River Riddleb4992772019-02-04 18:38:47278 for (auto &use : memref->getUses())
279 if (!isMemRefDereferencingOp(*use.getOwner()))
MLIR Teamd7c82442019-01-30 23:53:41280 return true;
MLIR Teamd7c82442019-01-30 23:53:41281 }
282 return false;
283 }
284
285 // Returns true if node 'id' can be removed from the graph. Returns false
286 // otherwise. A node can be removed from the graph iff the following
287 // conditions are met:
288 // *) The node does not write to any memref which escapes (or is a
289 // function/block argument).
290 // *) The node has no successors in the dependence graph.
291 bool canRemoveNode(unsigned id) {
292 if (writesToLiveInOrEscapingMemrefs(id))
293 return false;
294 Node *node = getNode(id);
295 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41296 // Return false if there exist out edges from 'id' on 'memref'.
MLIR Teamd7c82442019-01-30 23:53:41297 if (getOutEdgeCount(id, storeOpInst->cast<StoreOp>()->getMemRef()) > 0)
MLIR Teama0f3db402019-01-29 17:36:41298 return false;
MLIR Team71495d52019-01-22 21:23:37299 }
MLIR Teama0f3db402019-01-29 17:36:41300 return true;
MLIR Team71495d52019-01-22 21:23:37301 }
302
MLIR Team27d067e2019-01-16 17:55:02303 // Returns true iff there is an edge from node 'srcId' to node 'dstId' for
MLIR Teama0f3db402019-01-29 17:36:41304 // 'value'. Returns false otherwise.
305 bool hasEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team27d067e2019-01-16 17:55:02306 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
307 return false;
308 }
309 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41310 return edge.id == dstId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02311 });
312 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41313 return edge.id == srcId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02314 });
315 return hasOutEdge && hasInEdge;
316 }
317
MLIR Teama0f3db402019-01-29 17:36:41318 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
319 void addEdge(unsigned srcId, unsigned dstId, Value *value) {
320 if (!hasEdge(srcId, dstId, value)) {
321 outEdges[srcId].push_back({dstId, value});
322 inEdges[dstId].push_back({srcId, value});
323 if (value->getType().isa<MemRefType>())
324 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02325 }
MLIR Team6892ffb2018-12-20 04:42:55326 }
327
MLIR Teama0f3db402019-01-29 17:36:41328 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
329 void removeEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team6892ffb2018-12-20 04:42:55330 assert(inEdges.count(dstId) > 0);
331 assert(outEdges.count(srcId) > 0);
MLIR Teama0f3db402019-01-29 17:36:41332 if (value->getType().isa<MemRefType>()) {
333 assert(memrefEdgeCount.count(value) > 0);
334 memrefEdgeCount[value]--;
335 }
MLIR Team6892ffb2018-12-20 04:42:55336 // Remove 'srcId' from 'inEdges[dstId]'.
337 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41338 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55339 inEdges[dstId].erase(it);
340 break;
341 }
342 }
343 // Remove 'dstId' from 'outEdges[srcId]'.
344 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41345 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55346 outEdges[srcId].erase(it);
347 break;
348 }
349 }
350 }
351
MLIR Teama0f3db402019-01-29 17:36:41352 // Returns the input edge count for node 'id' and 'memref' from src nodes
353 // which access 'memref'.
354 unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55355 unsigned inEdgeCount = 0;
356 if (inEdges.count(id) > 0)
357 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41358 if (inEdge.value == memref) {
359 Node *srcNode = getNode(inEdge.id);
360 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
361 if (srcNode->getLoadOpCount(memref) > 0 ||
362 srcNode->getStoreOpCount(memref) > 0)
363 ++inEdgeCount;
364 }
MLIR Team6892ffb2018-12-20 04:42:55365 return inEdgeCount;
366 }
367
368 // Returns the output edge count for node 'id' and 'memref'.
Chris Lattner3f190312018-12-27 22:35:10369 unsigned getOutEdgeCount(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55370 unsigned outEdgeCount = 0;
371 if (outEdges.count(id) > 0)
372 for (auto &outEdge : outEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41373 if (outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55374 ++outEdgeCount;
375 return outEdgeCount;
376 }
377
MLIR Teama0f3db402019-01-29 17:36:41378 // Computes and returns an insertion point instruction, before which the
379 // the fused <srcId, dstId> loop nest can be inserted while preserving
380 // dependences. Returns nullptr if no such insertion point is found.
MLIR Teama78edcd2019-02-05 14:57:08381 Instruction *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40382 if (outEdges.count(srcId) == 0)
MLIR Teama0f3db402019-01-29 17:36:41383 return getNode(dstId)->inst;
384
385 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
386 SmallPtrSet<Instruction *, 2> srcDepInsts;
387 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08388 if (outEdge.id != dstId)
MLIR Teama0f3db402019-01-29 17:36:41389 srcDepInsts.insert(getNode(outEdge.id)->inst);
390
391 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
392 SmallPtrSet<Instruction *, 2> dstDepInsts;
393 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08394 if (inEdge.id != srcId)
MLIR Teama0f3db402019-01-29 17:36:41395 dstDepInsts.insert(getNode(inEdge.id)->inst);
396
397 Instruction *srcNodeInst = getNode(srcId)->inst;
398 Instruction *dstNodeInst = getNode(dstId)->inst;
399
400 // Computing insertion point:
401 // *) Walk all instruction positions in Block instruction list in the
402 // range (src, dst). For each instruction 'inst' visited in this search:
403 // *) Store in 'firstSrcDepPos' the first position where 'inst' has a
404 // dependence edge from 'srcNode'.
405 // *) Store in 'lastDstDepPost' the last position where 'inst' has a
406 // dependence edge to 'dstNode'.
407 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
408 // instruction insertion point (or return null pointer if no such
409 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
410 SmallVector<Instruction *, 2> depInsts;
411 Optional<unsigned> firstSrcDepPos;
412 Optional<unsigned> lastDstDepPos;
413 unsigned pos = 0;
414 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
415 it != Block::iterator(dstNodeInst); ++it) {
416 Instruction *inst = &(*it);
417 if (srcDepInsts.count(inst) > 0 && firstSrcDepPos == None)
418 firstSrcDepPos = pos;
419 if (dstDepInsts.count(inst) > 0)
420 lastDstDepPos = pos;
421 depInsts.push_back(inst);
422 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40423 }
MLIR Teama0f3db402019-01-29 17:36:41424
425 if (firstSrcDepPos.hasValue()) {
426 if (lastDstDepPos.hasValue()) {
427 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
428 // No valid insertion point exists which preserves dependences.
429 return nullptr;
430 }
431 }
432 // Return the insertion point at 'firstSrcDepPos'.
433 return depInsts[firstSrcDepPos.getValue()];
434 }
435 // No dependence targets in range (or only dst deps in range), return
436 // 'dstNodInst' insertion point.
437 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55438 }
439
MLIR Teama0f3db402019-01-29 17:36:41440 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
441 // has been replaced in node at 'dstId' by a private memref.
442 void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef) {
MLIR Team6892ffb2018-12-20 04:42:55443 // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'.
444 if (inEdges.count(srcId) > 0) {
445 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
446 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41447 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
448 if (inEdge.value != oldMemRef)
449 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55450 }
451 }
MLIR Teamc4237ae2019-01-18 16:56:27452 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55453 if (outEdges.count(srcId) > 0) {
454 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
455 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27456 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
457 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41458 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55459 }
460 }
MLIR Teama0f3db402019-01-29 17:36:41461 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
462 // replaced by a private memref). These edges could come from nodes
463 // other than 'srcId' which were removed in the previous step.
464 if (inEdges.count(dstId) > 0) {
465 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
466 for (auto &inEdge : oldInEdges)
467 if (inEdge.value == oldMemRef)
468 removeEdge(inEdge.id, dstId, inEdge.value);
469 }
MLIR Team6892ffb2018-12-20 04:42:55470 }
471
472 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddleb4992772019-02-04 18:38:47473 void addToNode(unsigned id, const SmallVectorImpl<Instruction *> &loads,
474 const SmallVectorImpl<Instruction *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55475 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35476 for (auto *loadOpInst : loads)
477 node->loads.push_back(loadOpInst);
478 for (auto *storeOpInst : stores)
479 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55480 }
481
MLIR Teamc4237ae2019-01-18 16:56:27482 void clearNodeLoadAndStores(unsigned id) {
483 Node *node = getNode(id);
484 node->loads.clear();
485 node->stores.clear();
486 }
487
MLIR Team6892ffb2018-12-20 04:42:55488 void print(raw_ostream &os) const {
489 os << "\nMemRefDependenceGraph\n";
490 os << "\nNodes:\n";
491 for (auto &idAndNode : nodes) {
492 os << "Node: " << idAndNode.first << "\n";
493 auto it = inEdges.find(idAndNode.first);
494 if (it != inEdges.end()) {
495 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41496 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55497 }
498 it = outEdges.find(idAndNode.first);
499 if (it != outEdges.end()) {
500 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41501 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55502 }
503 }
504 }
505 void dump() const { print(llvm::errs()); }
506};
507
Chris Lattner456ad6a2018-12-29 00:05:35508// Intializes the data dependence graph by walking instructions in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55509// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39510// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55511// dependence graph at a different depth.
Chris Lattner69d9e992018-12-28 16:48:09512bool MemRefDependenceGraph::init(Function *f) {
Chris Lattner3f190312018-12-27 22:35:10513 DenseMap<Value *, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43514
515 // TODO: support multi-block functions.
516 if (f->getBlocks().size() != 1)
517 return false;
518
River Riddle5052bd82019-02-02 00:42:18519 DenseMap<Instruction *, unsigned> forToNodeMap;
Chris Lattnerdffc5892018-12-29 23:33:43520 for (auto &inst : f->front()) {
River Riddleb4992772019-02-04 18:38:47521 if (auto forOp = inst.dyn_cast<AffineForOp>()) {
River Riddle5052bd82019-02-02 00:42:18522 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55523 // all loads and store accesses it contains.
524 LoopNestStateCollector collector;
River Riddlebf9c3812019-02-05 00:24:44525 collector.collect(&inst);
Uday Bondhugula4ba8c912019-02-07 05:54:18526 // Return false if a non 'for' region was found (not currently supported).
River Riddle75553832019-01-29 05:23:53527 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55528 return false;
MLIR Teama0f3db402019-01-29 17:36:41529 Node node(nextNodeId++, &inst);
Chris Lattner456ad6a2018-12-29 00:05:35530 for (auto *opInst : collector.loadOpInsts) {
531 node.loads.push_back(opInst);
532 auto *memref = opInst->cast<LoadOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55533 memrefAccesses[memref].insert(node.id);
534 }
Chris Lattner456ad6a2018-12-29 00:05:35535 for (auto *opInst : collector.storeOpInsts) {
536 node.stores.push_back(opInst);
537 auto *memref = opInst->cast<StoreOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55538 memrefAccesses[memref].insert(node.id);
539 }
River Riddle5052bd82019-02-02 00:42:18540 forToNodeMap[&inst] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55541 nodes.insert({node.id, node});
River Riddleb4992772019-02-04 18:38:47542 } else if (auto loadOp = inst.dyn_cast<LoadOp>()) {
543 // Create graph node for top-level load op.
544 Node node(nextNodeId++, &inst);
545 node.loads.push_back(&inst);
546 auto *memref = inst.cast<LoadOp>()->getMemRef();
547 memrefAccesses[memref].insert(node.id);
548 nodes.insert({node.id, node});
549 } else if (auto storeOp = inst.dyn_cast<StoreOp>()) {
550 // Create graph node for top-level store op.
551 Node node(nextNodeId++, &inst);
552 node.stores.push_back(&inst);
553 auto *memref = inst.cast<StoreOp>()->getMemRef();
554 memrefAccesses[memref].insert(node.id);
555 nodes.insert({node.id, node});
556 } else if (inst.getNumBlockLists() != 0) {
557 // Return false if another region is found (not currently supported).
558 return false;
559 } else if (inst.getNumResults() > 0 && !inst.use_empty()) {
560 // Create graph node for top-level producer of SSA values, which
561 // could be used by loop nest nodes.
562 Node node(nextNodeId++, &inst);
563 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41564 }
565 }
566
567 // Add dependence edges between nodes which produce SSA values and their
568 // users.
569 for (auto &idAndNode : nodes) {
570 const Node &node = idAndNode.second;
571 if (!node.loads.empty() || !node.stores.empty())
572 continue;
River Riddleb4992772019-02-04 18:38:47573 auto *opInst = node.inst;
MLIR Teama0f3db402019-01-29 17:36:41574 for (auto *value : opInst->getResults()) {
575 for (auto &use : value->getUses()) {
River Riddle5052bd82019-02-02 00:42:18576 SmallVector<OpPointer<AffineForOp>, 4> loops;
River Riddleb4992772019-02-04 18:38:47577 getLoopIVs(*use.getOwner(), &loops);
MLIR Teama0f3db402019-01-29 17:36:41578 if (loops.empty())
579 continue;
River Riddle5052bd82019-02-02 00:42:18580 assert(forToNodeMap.count(loops[0]->getInstruction()) > 0);
581 unsigned userLoopNestId = forToNodeMap[loops[0]->getInstruction()];
MLIR Teama0f3db402019-01-29 17:36:41582 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55583 }
584 }
MLIR Team6892ffb2018-12-20 04:42:55585 }
586
587 // Walk memref access lists and add graph edges between dependent nodes.
588 for (auto &memrefAndList : memrefAccesses) {
589 unsigned n = memrefAndList.second.size();
590 for (unsigned i = 0; i < n; ++i) {
591 unsigned srcId = memrefAndList.second[i];
592 bool srcHasStore =
593 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
594 for (unsigned j = i + 1; j < n; ++j) {
595 unsigned dstId = memrefAndList.second[j];
596 bool dstHasStore =
597 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
598 if (srcHasStore || dstHasStore)
599 addEdge(srcId, dstId, memrefAndList.first);
600 }
601 }
602 }
603 return true;
604}
605
MLIR Team38c2fe32019-01-14 19:26:25606namespace {
607
608// LoopNestStats aggregates various per-loop statistics (eg. loop trip count
609// and operation count) for a loop nest up until the innermost loop body.
610struct LoopNestStats {
River Riddle5052bd82019-02-02 00:42:18611 // Map from AffineForOp to immediate child AffineForOps in its loop body.
612 DenseMap<Instruction *, SmallVector<OpPointer<AffineForOp>, 2>> loopMap;
613 // Map from AffineForOp to count of operations in its loop body.
614 DenseMap<Instruction *, uint64_t> opCountMap;
615 // Map from AffineForOp to its constant trip count.
616 DenseMap<Instruction *, uint64_t> tripCountMap;
MLIR Team38c2fe32019-01-14 19:26:25617};
618
619// LoopNestStatsCollector walks a single loop nest and gathers per-loop
620// trip count and operation count statistics and records them in 'stats'.
River Riddlebf9c3812019-02-05 00:24:44621struct LoopNestStatsCollector {
MLIR Team38c2fe32019-01-14 19:26:25622 LoopNestStats *stats;
623 bool hasLoopWithNonConstTripCount = false;
624
625 LoopNestStatsCollector(LoopNestStats *stats) : stats(stats) {}
626
River Riddlebf9c3812019-02-05 00:24:44627 void collect(Instruction *inst) {
628 inst->walk<AffineForOp>([&](OpPointer<AffineForOp> forOp) {
629 auto *forInst = forOp->getInstruction();
630 auto *parentInst = forOp->getInstruction()->getParentInst();
631 if (parentInst != nullptr) {
632 assert(parentInst->isa<AffineForOp>() && "Expected parent AffineForOp");
633 // Add mapping to 'forOp' from its parent AffineForOp.
634 stats->loopMap[parentInst].push_back(forOp);
635 }
River Riddle5052bd82019-02-02 00:42:18636
River Riddlebf9c3812019-02-05 00:24:44637 // Record the number of op instructions in the body of 'forOp'.
638 unsigned count = 0;
639 stats->opCountMap[forInst] = 0;
640 for (auto &inst : *forOp->getBody()) {
Uday Bondhugulad4b3ff12019-02-27 00:10:19641 if (!inst.isa<AffineForOp>() && !inst.isa<AffineIfOp>())
River Riddlebf9c3812019-02-05 00:24:44642 ++count;
643 }
644 stats->opCountMap[forInst] = count;
645 // Record trip count for 'forOp'. Set flag if trip count is not
646 // constant.
647 Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp);
648 if (!maybeConstTripCount.hasValue()) {
649 hasLoopWithNonConstTripCount = true;
650 return;
651 }
652 stats->tripCountMap[forInst] = maybeConstTripCount.getValue();
653 });
MLIR Team38c2fe32019-01-14 19:26:25654 }
655};
656
River Riddle5052bd82019-02-02 00:42:18657// Computes the total cost of the loop nest rooted at 'forOp'.
MLIR Team38c2fe32019-01-14 19:26:25658// Currently, the total cost is computed by counting the total operation
659// instance count (i.e. total number of operations in the loop bodyloop
660// operation count * loop trip count) for the entire loop nest.
661// If 'tripCountOverrideMap' is non-null, overrides the trip count for loops
662// specified in the map when computing the total op instance count.
663// NOTE: this is used to compute the cost of computation slices, which are
664// sliced along the iteration dimension, and thus reduce the trip count.
River Riddle5052bd82019-02-02 00:42:18665// If 'computeCostMap' is non-null, the total op count for forOps specified
MLIR Team38c2fe32019-01-14 19:26:25666// in the map is increased (not overridden) by adding the op count from the
667// map to the existing op count for the for loop. This is done before
668// multiplying by the loop's trip count, and is used to model the cost of
669// inserting a sliced loop nest of known cost into the loop's body.
670// NOTE: this is used to compute the cost of fusing a slice of some loop nest
671// within another loop.
Uday Bondhugula864d9e02019-01-23 17:16:24672static int64_t getComputeCost(
River Riddle5052bd82019-02-02 00:42:18673 Instruction *forInst, LoopNestStats *stats,
674 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountOverrideMap,
675 DenseMap<Instruction *, int64_t> *computeCostMap) {
676 // 'opCount' is the total number operations in one iteration of 'forOp' body
Uday Bondhugula864d9e02019-01-23 17:16:24677 int64_t opCount = stats->opCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25678 if (stats->loopMap.count(forInst) > 0) {
River Riddle5052bd82019-02-02 00:42:18679 for (auto childForOp : stats->loopMap[forInst]) {
680 opCount += getComputeCost(childForOp->getInstruction(), stats,
681 tripCountOverrideMap, computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:25682 }
683 }
684 // Add in additional op instances from slice (if specified in map).
685 if (computeCostMap != nullptr) {
686 auto it = computeCostMap->find(forInst);
687 if (it != computeCostMap->end()) {
688 opCount += it->second;
689 }
690 }
691 // Override trip count (if specified in map).
Uday Bondhugula864d9e02019-01-23 17:16:24692 int64_t tripCount = stats->tripCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25693 if (tripCountOverrideMap != nullptr) {
694 auto it = tripCountOverrideMap->find(forInst);
695 if (it != tripCountOverrideMap->end()) {
696 tripCount = it->second;
697 }
698 }
699 // Returns the total number of dynamic instances of operations in loop body.
700 return tripCount * opCount;
701}
702
703} // end anonymous namespace
704
Uday Bondhugula7aa60a32019-02-27 01:32:47705// TODO(andydavis,b/126426796): extend this to handle multiple result maps.
MLIR Team27d067e2019-01-16 17:55:02706static Optional<uint64_t> getConstDifference(AffineMap lbMap, AffineMap ubMap) {
Uday Bondhugulac1ca23e2019-01-16 21:13:00707 assert(lbMap.getNumResults() == 1 && "expected single result bound map");
708 assert(ubMap.getNumResults() == 1 && "expected single result bound map");
MLIR Team27d067e2019-01-16 17:55:02709 assert(lbMap.getNumDims() == ubMap.getNumDims());
710 assert(lbMap.getNumSymbols() == ubMap.getNumSymbols());
MLIR Team27d067e2019-01-16 17:55:02711 AffineExpr lbExpr(lbMap.getResult(0));
712 AffineExpr ubExpr(ubMap.getResult(0));
713 auto loopSpanExpr = simplifyAffineExpr(ubExpr - lbExpr, lbMap.getNumDims(),
714 lbMap.getNumSymbols());
715 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
716 if (!cExpr)
717 return None;
718 return cExpr.getValue();
719}
720
River Riddle5052bd82019-02-02 00:42:18721// Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop
MLIR Team38c2fe32019-01-14 19:26:25722// nest surrounding 'srcAccess' utilizing slice loop bounds in 'sliceState'.
723// Returns true on success, false otherwise (if a non-constant trip count
724// was encountered).
725// TODO(andydavis) Make this work with non-unit step loops.
MLIR Team27d067e2019-01-16 17:55:02726static bool buildSliceTripCountMap(
River Riddleb4992772019-02-04 18:38:47727 Instruction *srcOpInst, ComputationSliceState *sliceState,
River Riddle5052bd82019-02-02 00:42:18728 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountMap) {
729 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:02730 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:25731 unsigned numSrcLoopIVs = srcLoopIVs.size();
River Riddle5052bd82019-02-02 00:42:18732 // Populate map from AffineForOp -> trip count
MLIR Team38c2fe32019-01-14 19:26:25733 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
734 AffineMap lbMap = sliceState->lbs[i];
735 AffineMap ubMap = sliceState->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17736 if (lbMap == AffineMap() || ubMap == AffineMap()) {
MLIR Team38c2fe32019-01-14 19:26:25737 // The iteration of src loop IV 'i' was not sliced. Use full loop bounds.
738 if (srcLoopIVs[i]->hasConstantLowerBound() &&
739 srcLoopIVs[i]->hasConstantUpperBound()) {
River Riddle5052bd82019-02-02 00:42:18740 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] =
MLIR Team38c2fe32019-01-14 19:26:25741 srcLoopIVs[i]->getConstantUpperBound() -
742 srcLoopIVs[i]->getConstantLowerBound();
743 continue;
744 }
745 return false;
746 }
MLIR Team27d067e2019-01-16 17:55:02747 Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap);
748 if (!tripCount.hasValue())
MLIR Team38c2fe32019-01-14 19:26:25749 return false;
River Riddle5052bd82019-02-02 00:42:18750 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] = tripCount.getValue();
MLIR Team38c2fe32019-01-14 19:26:25751 }
752 return true;
753}
754
MLIR Team27d067e2019-01-16 17:55:02755// Removes load operations from 'srcLoads' which operate on 'memref', and
756// adds them to 'dstLoads'.
757static void
758moveLoadsAccessingMemrefTo(Value *memref,
River Riddleb4992772019-02-04 18:38:47759 SmallVectorImpl<Instruction *> *srcLoads,
760 SmallVectorImpl<Instruction *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02761 dstLoads->clear();
River Riddleb4992772019-02-04 18:38:47762 SmallVector<Instruction *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02763 for (auto *load : *srcLoads) {
764 if (load->cast<LoadOp>()->getMemRef() == memref)
765 dstLoads->push_back(load);
766 else
767 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25768 }
MLIR Team27d067e2019-01-16 17:55:02769 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25770}
771
MLIR Team27d067e2019-01-16 17:55:02772// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddleb4992772019-02-04 18:38:47773static unsigned getInnermostCommonLoopDepth(ArrayRef<Instruction *> ops) {
MLIR Team27d067e2019-01-16 17:55:02774 unsigned numOps = ops.size();
775 assert(numOps > 0);
776
River Riddle5052bd82019-02-02 00:42:18777 std::vector<SmallVector<OpPointer<AffineForOp>, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02778 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
779 for (unsigned i = 0; i < numOps; ++i) {
780 getLoopIVs(*ops[i], &loops[i]);
781 loopDepthLimit =
782 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25783 }
MLIR Team27d067e2019-01-16 17:55:02784
785 unsigned loopDepth = 0;
786 for (unsigned d = 0; d < loopDepthLimit; ++d) {
787 unsigned i;
788 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18789 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02790 break;
MLIR Team27d067e2019-01-16 17:55:02791 }
792 if (i != numOps)
793 break;
794 ++loopDepth;
795 }
796 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25797}
798
MLIR Teamd7c82442019-01-30 23:53:41799// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
800// and 'storeOpInsts' are satisfied.
River Riddleb4992772019-02-04 18:38:47801static unsigned getMaxLoopDepth(ArrayRef<Instruction *> loadOpInsts,
802 ArrayRef<Instruction *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41803 // Merge loads and stores into the same array.
River Riddleb4992772019-02-04 18:38:47804 SmallVector<Instruction *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41805 ops.append(storeOpInsts.begin(), storeOpInsts.end());
806
807 // Compute the innermost common loop depth for loads and stores.
808 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
809
810 // Return common loop depth for loads if there are no store ops.
811 if (storeOpInsts.empty())
812 return loopDepth;
813
814 // Check dependences on all pairs of ops in 'ops' and store the minimum
815 // loop depth at which a dependence is satisfied.
816 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
817 auto *srcOpInst = ops[i];
818 MemRefAccess srcAccess(srcOpInst);
819 for (unsigned j = 0; j < e; ++j) {
820 auto *dstOpInst = ops[j];
821 MemRefAccess dstAccess(dstOpInst);
822
823 unsigned numCommonLoops =
824 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
825 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
826 FlatAffineConstraints dependenceConstraints;
827 // TODO(andydavis) Cache dependence analysis results, check cache here.
828 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
829 &dependenceConstraints,
830 /*dependenceComponents=*/nullptr)) {
831 // Store minimum loop depth and break because we want the min 'd' at
832 // which there is a dependence.
833 loopDepth = std::min(loopDepth, d - 1);
834 break;
835 }
836 }
837 }
838 }
839 return loopDepth;
840}
841
MLIR Team8f5f2c72019-02-15 17:32:18842// Compute loop interchange permutation:
843// *) Computes dependence components between all op pairs in 'ops' for loop
844// depths in range [1, 'maxLoopDepth'].
845// *) Classifies the outermost 'maxLoopDepth' loops surrounding 'ops' as either
846// parallel or sequential.
847// *) Computes the loop permutation which sinks sequential loops deeper into
848// the loop nest, while preserving the relative order between other loops.
849// *) Checks each dependence component against the permutation to see if the
850// desired loop interchange would violated dependences by making the a
851// dependence componenent lexicographically negative.
852// TODO(andydavis) Move this function to LoopUtils.
853static bool
854computeLoopInterchangePermutation(ArrayRef<Instruction *> ops,
855 unsigned maxLoopDepth,
856 SmallVectorImpl<unsigned> *loopPermMap) {
857 // Gather dependence components for dependences between all ops in 'ops'
858 // at loop depths in range [1, maxLoopDepth].
859 // TODO(andydavis) Refactor this loop into a LoopUtil utility function:
860 // mlir::getDependenceComponents().
861 // TODO(andydavis) Split this loop into two: first check all dependences,
862 // and construct dep vectors. Then, scan through them to detect the parallel
863 // ones.
864 std::vector<llvm::SmallVector<DependenceComponent, 2>> depCompsVec;
865 llvm::SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true);
866 unsigned numOps = ops.size();
867 for (unsigned d = 1; d <= maxLoopDepth; ++d) {
868 for (unsigned i = 0; i < numOps; ++i) {
869 auto *srcOpInst = ops[i];
870 MemRefAccess srcAccess(srcOpInst);
871 for (unsigned j = 0; j < numOps; ++j) {
872 auto *dstOpInst = ops[j];
873 MemRefAccess dstAccess(dstOpInst);
874
875 FlatAffineConstraints dependenceConstraints;
876 llvm::SmallVector<DependenceComponent, 2> depComps;
877 // TODO(andydavis,bondhugula) Explore whether it would be profitable
878 // to pre-compute and store deps instead of repeatidly checking.
879 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
880 &dependenceConstraints, &depComps)) {
881 isParallelLoop[d - 1] = false;
882 depCompsVec.push_back(depComps);
883 }
884 }
885 }
886 }
887 // Count the number of parallel loops.
888 unsigned numParallelLoops = 0;
889 for (unsigned i = 0, e = isParallelLoop.size(); i < e; ++i)
890 if (isParallelLoop[i])
891 ++numParallelLoops;
892
893 // Compute permutation of loops that sinks sequential loops (and thus raises
894 // parallel loops) while preserving relative order.
895 llvm::SmallVector<unsigned, 4> loopPermMapInv;
896 loopPermMapInv.resize(maxLoopDepth);
897 loopPermMap->resize(maxLoopDepth);
898 unsigned nextSequentialLoop = numParallelLoops;
899 unsigned nextParallelLoop = 0;
900 for (unsigned i = 0; i < maxLoopDepth; ++i) {
901 if (isParallelLoop[i]) {
902 (*loopPermMap)[i] = nextParallelLoop;
903 loopPermMapInv[nextParallelLoop++] = i;
904 } else {
905 (*loopPermMap)[i] = nextSequentialLoop;
906 loopPermMapInv[nextSequentialLoop++] = i;
907 }
908 }
909
910 // Check each dependence component against the permutation to see if the
911 // desired loop interchange permutation would make the dependence vectors
912 // lexicographically negative.
913 // Example 1: [-1, 1][0, 0]
914 // Example 2: [0, 0][-1, 1]
915 for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) {
916 llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i];
917 assert(depComps.size() >= maxLoopDepth);
918 // Check if the first non-zero dependence component is positive.
919 for (unsigned j = 0; j < maxLoopDepth; ++j) {
920 unsigned permIndex = loopPermMapInv[j];
921 assert(depComps[permIndex].lb.hasValue());
922 int64_t depCompLb = depComps[permIndex].lb.getValue();
923 if (depCompLb > 0)
924 break;
925 if (depCompLb < 0)
926 return false;
927 }
928 }
929 return true;
930}
931
932// Sinks all sequential loops to the innermost levels (while preserving
933// relative order among them) and moves all parallel loops to the
934// outermost (while again preserving relative order among them).
935// This can increase the loop depth at which we can fuse a slice, since we are
936// pushing loop carried dependence to a greater depth in the loop nest.
937static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
938 assert(node->inst->isa<AffineForOp>());
939 // Get perfectly nested sequence of loops starting at root of loop nest.
940 // TODO(andydavis,bondhugula) Share this with similar code in loop tiling.
941 SmallVector<OpPointer<AffineForOp>, 4> loops;
942 OpPointer<AffineForOp> curr = node->inst->cast<AffineForOp>();
943 loops.push_back(curr);
944 auto *currBody = curr->getBody();
945 while (!currBody->empty() &&
946 std::next(currBody->begin()) == currBody->end() &&
947 (curr = curr->getBody()->front().dyn_cast<AffineForOp>())) {
948 loops.push_back(curr);
949 currBody = curr->getBody();
950 }
951 if (loops.size() < 2)
952 return;
953
954 // Merge loads and stores into the same array.
955 SmallVector<Instruction *, 2> memOps(node->loads.begin(), node->loads.end());
956 memOps.append(node->stores.begin(), node->stores.end());
957
958 // Compute loop permutation in 'loopPermMap'.
959 llvm::SmallVector<unsigned, 4> loopPermMap;
960 if (!computeLoopInterchangePermutation(memOps, loops.size(), &loopPermMap))
961 return;
962
963 int loopNestRootIndex = -1;
964 for (int i = loops.size() - 1; i >= 0; --i) {
965 int permIndex = static_cast<int>(loopPermMap[i]);
966 // Store the index of the for loop which will be the new loop nest root.
967 if (permIndex == 0)
968 loopNestRootIndex = i;
969 if (permIndex > i) {
970 // Sink loop 'i' by 'permIndex - i' levels deeper into the loop nest.
971 sinkLoop(loops[i], permIndex - i);
972 }
973 }
974 assert(loopNestRootIndex != -1 && "invalid root index");
975 node->inst = loops[loopNestRootIndex]->getInstruction();
976}
977
Uday Bondhugulac1ca23e2019-01-16 21:13:00978// Returns the slice union of 'sliceStateA' and 'sliceStateB' in 'sliceStateB'
979// using a rectangular bounding box.
MLIR Team27d067e2019-01-16 17:55:02980// TODO(andydavis) This function assumes that lower bounds for 'sliceStateA'
981// and 'sliceStateB' are aligned.
982// Specifically, when taking the union of overlapping intervals, it assumes
983// that both intervals start at zero. Support needs to be added to take into
984// account interval start offset when computing the union.
985// TODO(andydavis) Move this function to an analysis library.
Uday Bondhugulac1ca23e2019-01-16 21:13:00986static bool getSliceUnion(const ComputationSliceState &sliceStateA,
987 ComputationSliceState *sliceStateB) {
MLIR Team27d067e2019-01-16 17:55:02988 assert(sliceStateA.lbs.size() == sliceStateB->lbs.size());
989 assert(sliceStateA.ubs.size() == sliceStateB->ubs.size());
990
991 for (unsigned i = 0, e = sliceStateA.lbs.size(); i < e; ++i) {
992 AffineMap lbMapA = sliceStateA.lbs[i];
993 AffineMap ubMapA = sliceStateA.ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17994 if (lbMapA == AffineMap()) {
995 assert(ubMapA == AffineMap());
MLIR Team27d067e2019-01-16 17:55:02996 continue;
997 }
Uday Bondhugulac1ca23e2019-01-16 21:13:00998 assert(ubMapA && "expected non-null ub map");
MLIR Team27d067e2019-01-16 17:55:02999
1000 AffineMap lbMapB = sliceStateB->lbs[i];
1001 AffineMap ubMapB = sliceStateB->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:171002 if (lbMapB == AffineMap()) {
1003 assert(ubMapB == AffineMap());
MLIR Team27d067e2019-01-16 17:55:021004 // Union 'sliceStateB' does not have a bound for 'i' so copy from A.
1005 sliceStateB->lbs[i] = lbMapA;
1006 sliceStateB->ubs[i] = ubMapA;
1007 continue;
1008 }
Uday Bondhugulac1ca23e2019-01-16 21:13:001009
1010 // TODO(andydavis) Change this code to take the min across all lower bounds
1011 // and max across all upper bounds for each dimension. This code can for
1012 // cases where a unique min or max could not be statically determined.
1013
1014 // Assumption: both lower bounds are the same.
1015 if (lbMapA != lbMapB)
MLIR Team27d067e2019-01-16 17:55:021016 return false;
1017
1018 // Add bound with the largest trip count to union.
1019 Optional<uint64_t> tripCountA = getConstDifference(lbMapA, ubMapA);
1020 Optional<uint64_t> tripCountB = getConstDifference(lbMapB, ubMapB);
1021 if (!tripCountA.hasValue() || !tripCountB.hasValue())
1022 return false;
Uday Bondhugulac1ca23e2019-01-16 21:13:001023
MLIR Team27d067e2019-01-16 17:55:021024 if (tripCountA.getValue() > tripCountB.getValue()) {
1025 sliceStateB->lbs[i] = lbMapA;
1026 sliceStateB->ubs[i] = ubMapA;
1027 }
1028 }
1029 return true;
1030}
1031
Uday Bondhugula8be26272019-02-02 01:06:221032// TODO(mlir-team): improve/complete this when we have target data.
1033unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
1034 auto elementType = memRefType.getElementType();
1035
1036 unsigned sizeInBits;
1037 if (elementType.isIntOrFloat()) {
1038 sizeInBits = elementType.getIntOrFloatBitWidth();
1039 } else {
1040 auto vectorType = elementType.cast<VectorType>();
1041 sizeInBits =
1042 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
1043 }
1044 return llvm::divideCeil(sizeInBits, 8);
1045}
1046
MLIR Teamc4237ae2019-01-18 16:56:271047// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:181048// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:521049// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1050// TODO(bondhugula): consider refactoring the common code from generateDma and
1051// this one.
River Riddle5052bd82019-02-02 00:42:181052static Value *createPrivateMemRef(OpPointer<AffineForOp> forOp,
River Riddleb4992772019-02-04 18:38:471053 Instruction *srcStoreOpInst,
Uday Bondhugula8be26272019-02-02 01:06:221054 unsigned dstLoopDepth,
1055 Optional<unsigned> fastMemorySpace,
Uday Bondhugulad4b3ff12019-02-27 00:10:191056 uint64_t localBufSizeThreshold) {
River Riddle5052bd82019-02-02 00:42:181057 auto *forInst = forOp->getInstruction();
1058
1059 // Create builder to insert alloc op just before 'forOp'.
MLIR Teamc4237ae2019-01-18 16:56:271060 FuncBuilder b(forInst);
1061 // Builder to create constants at the top level.
1062 FuncBuilder top(forInst->getFunction());
1063 // Create new memref type based on slice bounds.
1064 auto *oldMemRef = srcStoreOpInst->cast<StoreOp>()->getMemRef();
1065 auto oldMemRefType = oldMemRef->getType().cast<MemRefType>();
1066 unsigned rank = oldMemRefType.getRank();
1067
Uday Bondhugula94a03f82019-01-22 21:58:521068 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:441069 MemRefRegion region(srcStoreOpInst->getLoc());
1070 region.compute(srcStoreOpInst, dstLoopDepth);
River Riddle6859f332019-01-23 22:39:451071 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:271072 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:521073 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:271074 lbs.reserve(rank);
1075 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:521076 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:271077 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:441078 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:221079 assert(numElements.hasValue() &&
1080 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:271081
Uday Bondhugula0f504142019-02-04 21:48:441082 const FlatAffineConstraints *cst = region.getConstraints();
Uday Bondhugula94a03f82019-01-22 21:58:521083 // 'outerIVs' holds the values that this memory region is symbolic/paramteric
1084 // on; this would correspond to loop IVs surrounding the level at which the
1085 // slice is being materialized.
1086 SmallVector<Value *, 8> outerIVs;
1087 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
1088
1089 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:271090 SmallVector<AffineExpr, 4> offsets;
1091 offsets.reserve(rank);
1092 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:521093 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
1094
MLIR Teamc4237ae2019-01-18 16:56:271095 AffineExpr offset = top.getAffineConstantExpr(0);
1096 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
1097 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
1098 }
Uday Bondhugula94a03f82019-01-22 21:58:521099 assert(lbDivisors[d] > 0);
1100 offset =
1101 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:271102 offsets.push_back(offset);
1103 }
1104
1105 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
1106 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:221107 uint64_t bufSize =
1108 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
1109 unsigned newMemSpace;
Uday Bondhugulad4b3ff12019-02-27 00:10:191110 if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
Uday Bondhugula8be26272019-02-02 01:06:221111 newMemSpace = fastMemorySpace.getValue();
1112 } else {
1113 newMemSpace = oldMemRefType.getMemorySpace();
1114 }
1115 auto newMemRefType = top.getMemRefType(
1116 newShape, oldMemRefType.getElementType(), {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:271117 // Gather alloc operands for the dynamic dimensions of the memref.
1118 SmallVector<Value *, 4> allocOperands;
1119 unsigned dynamicDimCount = 0;
1120 for (auto dimSize : oldMemRefType.getShape()) {
1121 if (dimSize == -1)
1122 allocOperands.push_back(
River Riddle5052bd82019-02-02 00:42:181123 top.create<DimOp>(forOp->getLoc(), oldMemRef, dynamicDimCount++));
MLIR Teamc4237ae2019-01-18 16:56:271124 }
1125
River Riddle5052bd82019-02-02 00:42:181126 // Create new private memref for fused loop 'forOp'.
MLIR Teama0f3db402019-01-29 17:36:411127 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
1128 // consumer loop nests to reduce their live range. Currently they are added
1129 // at the beginning of the function, because loop nests can be reordered
1130 // during the fusion pass.
MLIR Teamc4237ae2019-01-18 16:56:271131 Value *newMemRef =
River Riddle5052bd82019-02-02 00:42:181132 top.create<AllocOp>(forOp->getLoc(), newMemRefType, allocOperands);
MLIR Teamc4237ae2019-01-18 16:56:271133
1134 // Build an AffineMap to remap access functions based on lower bound offsets.
1135 SmallVector<AffineExpr, 4> remapExprs;
1136 remapExprs.reserve(rank);
1137 unsigned zeroOffsetCount = 0;
1138 for (unsigned i = 0; i < rank; i++) {
1139 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
1140 if (constExpr.getValue() == 0)
1141 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:521142 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
1143
1144 auto remapExpr =
1145 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
1146 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:271147 }
Uday Bondhugula94a03f82019-01-22 21:58:521148 auto indexRemap =
1149 zeroOffsetCount == rank
Nicolas Vasilache0e7a8a92019-01-26 18:41:171150 ? AffineMap()
Uday Bondhugula94a03f82019-01-22 21:58:521151 : b.getAffineMap(outerIVs.size() + rank, 0, remapExprs, {});
MLIR Teamc4237ae2019-01-18 16:56:271152 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugula94a03f82019-01-22 21:58:521153 bool ret =
1154 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
1155 /*extraOperands=*/outerIVs,
River Riddle5052bd82019-02-02 00:42:181156 /*domInstFilter=*/&*forOp->getBody()->begin());
Uday Bondhugula94a03f82019-01-22 21:58:521157 assert(ret && "replaceAllMemrefUsesWith should always succeed here");
MLIR Team71495d52019-01-22 21:23:371158 (void)ret;
MLIR Teamc4237ae2019-01-18 16:56:271159 return newMemRef;
1160}
1161
Uday Bondhugula864d9e02019-01-23 17:16:241162// Does the slice have a single iteration?
1163static uint64_t getSliceIterationCount(
River Riddle5052bd82019-02-02 00:42:181164 const llvm::SmallDenseMap<Instruction *, uint64_t, 8> &sliceTripCountMap) {
Uday Bondhugula864d9e02019-01-23 17:16:241165 uint64_t iterCount = 1;
1166 for (const auto &count : sliceTripCountMap) {
1167 iterCount *= count.second;
1168 }
1169 return iterCount;
1170}
1171
MLIR Team58aa3832019-02-16 01:12:191172// Checks if node 'srcId' (which writes to a live out memref), can be safely
1173// fused into node 'dstId'. Returns true if the following conditions are met:
1174// *) 'srcNode' writes only writes to live out 'memref'.
1175// *) 'srcNode' has exaclty one output edge on 'memref' (which is to 'dstId').
1176// *) 'dstNode' does write to 'memref'.
1177// *) 'dstNode's write region to 'memref' is a super set of 'srcNode's write
1178// region to 'memref'.
1179// TODO(andydavis) Generalize this to handle more live in/out cases.
1180static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
1181 Value *memref,
1182 MemRefDependenceGraph *mdg) {
1183 auto *srcNode = mdg->getNode(srcId);
1184 auto *dstNode = mdg->getNode(dstId);
1185
1186 // Return false if any of the following are true:
1187 // *) 'srcNode' writes to a live in/out memref other than 'memref'.
1188 // *) 'srcNode' has more than one output edge on 'memref'.
1189 // *) 'dstNode' does not write to 'memref'.
1190 if (srcNode->getStoreOpCount(memref) != 1 ||
1191 mdg->getOutEdgeCount(srcNode->id, memref) != 1 ||
1192 dstNode->getStoreOpCount(memref) == 0)
1193 return false;
1194 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOpInst' on 'memref'.
1195 auto *srcStoreOpInst = srcNode->stores.front();
1196 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
1197 srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0);
1198 SmallVector<int64_t, 4> srcShape;
1199 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
1200 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1201 Optional<int64_t> srcNumElements =
1202 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1203 if (!srcNumElements.hasValue())
1204 return false;
1205
1206 // Compute MemRefRegion 'dstWriteRegion' for 'dstStoreOpInst' on 'memref'.
1207 SmallVector<Instruction *, 2> dstStoreOps;
1208 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1209 assert(dstStoreOps.size() == 1);
1210 auto *dstStoreOpInst = dstStoreOps[0];
1211 MemRefRegion dstWriteRegion(dstStoreOpInst->getLoc());
1212 dstWriteRegion.compute(dstStoreOpInst, /*loopDepth=*/0);
1213 SmallVector<int64_t, 4> dstShape;
1214 // Query 'dstWriteRegion' for 'dstShape' and 'dstNumElements'.
1215 // by 'dstStoreOpInst' at depth 'dstLoopDepth'.
1216 Optional<int64_t> dstNumElements =
1217 dstWriteRegion.getConstantBoundingSizeAndShape(&dstShape);
1218 if (!dstNumElements.hasValue())
1219 return false;
1220
1221 // Return false if write region is not a superset of 'srcNodes' write
1222 // region to 'memref'.
1223 // TODO(andydavis) Check the shape and lower bounds here too.
1224 if (srcNumElements != dstNumElements)
1225 return false;
1226 return true;
1227}
1228
MLIR Team27d067e2019-01-16 17:55:021229// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411230// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
Uday Bondhugulab4a14432019-01-26 00:00:501231// Returns true if it is profitable to fuse the candidate loop nests. Returns
1232// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1233// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251234// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021235// *) Computes the backward computation slice at 'srcOpInst'. This
1236// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251237// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021238// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251239// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1240// loop nest is the total number of dynamic operation instances in the loop
1241// nest).
1242// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021243// loop nest at various values of dst loop depth, attempting to fuse
1244// the largest compution slice at the maximal dst loop depth (closest to the
1245// load) to minimize reuse distance and potentially enable subsequent
1246// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411247// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021248// the same memref as is written by 'srcOpInst', then the union of slice
1249// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501250// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251251// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021252// NOTE: We attempt to maximize the dst loop depth, but there are cases
1253// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251254// loop (within the src computation slice) at a depth which results in
1255// execessive recomputation (see unit tests for examples).
1256// *) Compares the total cost of the unfused loop nests to the min cost fused
1257// loop nest computed in the previous step, and returns true if the latter
1258// is lower.
River Riddleb4992772019-02-04 18:38:471259static bool isFusionProfitable(Instruction *srcOpInst,
1260 ArrayRef<Instruction *> dstLoadOpInsts,
1261 ArrayRef<Instruction *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251262 ComputationSliceState *sliceState,
MLIR Team27d067e2019-01-16 17:55:021263 unsigned *dstLoopDepth) {
Uday Bondhugula06d21d92019-01-25 01:01:491264 LLVM_DEBUG({
1265 llvm::dbgs() << "Checking whether fusion is profitable between:\n";
Uday Bondhugulaa1dad3a2019-02-20 02:17:191266 llvm::dbgs() << " " << *srcOpInst << " and \n";
MLIR Teamd7c82442019-01-30 23:53:411267 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191268 llvm::dbgs() << " " << *dstOpInst << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491269 };
1270 });
Uday Bondhugula864d9e02019-01-23 17:16:241271
MLIR Team38c2fe32019-01-14 19:26:251272 // Compute cost of sliced and unsliced src loop nest.
River Riddle5052bd82019-02-02 00:42:181273 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:021274 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251275 unsigned numSrcLoopIVs = srcLoopIVs.size();
1276
1277 // Walk src loop nest and collect stats.
1278 LoopNestStats srcLoopNestStats;
1279 LoopNestStatsCollector srcStatsCollector(&srcLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441280 srcStatsCollector.collect(srcLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251281 // Currently only constant trip count loop nests are supported.
1282 if (srcStatsCollector.hasLoopWithNonConstTripCount)
1283 return false;
1284
1285 // Compute cost of dst loop nest.
River Riddle5052bd82019-02-02 00:42:181286 SmallVector<OpPointer<AffineForOp>, 4> dstLoopIVs;
MLIR Teamd7c82442019-01-30 23:53:411287 getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:251288
1289 LoopNestStats dstLoopNestStats;
1290 LoopNestStatsCollector dstStatsCollector(&dstLoopNestStats);
River Riddlebf9c3812019-02-05 00:24:441291 dstStatsCollector.collect(dstLoopIVs[0]->getInstruction());
MLIR Team38c2fe32019-01-14 19:26:251292 // Currently only constant trip count loop nests are supported.
1293 if (dstStatsCollector.hasLoopWithNonConstTripCount)
1294 return false;
1295
MLIR Teamd7c82442019-01-30 23:53:411296 // Compute the maximum loop depth at which we can can insert the src slice
1297 // and still satisfy dest loop nest dependences.
1298 unsigned maxDstLoopDepth = getMaxLoopDepth(dstLoadOpInsts, dstStoreOpInsts);
MLIR Team27d067e2019-01-16 17:55:021299 if (maxDstLoopDepth == 0)
1300 return false;
1301
1302 // Search for min cost value for 'dstLoopDepth'. At each value of
1303 // 'dstLoopDepth' from 'maxDstLoopDepth' to '1', compute computation slice
1304 // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1305 // of these bounds). Next the union slice bounds are used to calculate
1306 // the cost of the slice and the cost of the slice inserted into the dst
1307 // loop nest at 'dstLoopDepth'.
Uday Bondhugula864d9e02019-01-23 17:16:241308 uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
1309 uint64_t maxStorageReduction = 0;
1310 Optional<uint64_t> sliceMemEstimate = None;
1311
MLIR Team27d067e2019-01-16 17:55:021312 SmallVector<ComputationSliceState, 4> sliceStates;
1313 sliceStates.resize(maxDstLoopDepth);
Uday Bondhugula864d9e02019-01-23 17:16:241314 // The best loop depth at which to materialize the slice.
1315 Optional<unsigned> bestDstLoopDepth = None;
1316
1317 // Compute op instance count for the src loop nest without iteration slicing.
River Riddle5052bd82019-02-02 00:42:181318 uint64_t srcLoopNestCost =
1319 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
1320 /*tripCountOverrideMap=*/nullptr,
1321 /*computeCostMap=*/nullptr);
Uday Bondhugula864d9e02019-01-23 17:16:241322
MLIR Teamb9dde912019-02-06 19:01:101323 // Compute src loop nest write region size.
1324 MemRefRegion srcWriteRegion(srcOpInst->getLoc());
1325 srcWriteRegion.compute(srcOpInst, /*loopDepth=*/0);
1326 Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1327 srcWriteRegion.getRegionSize();
1328 if (!maybeSrcWriteRegionSizeBytes.hasValue())
1329 return false;
1330 int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1331
Uday Bondhugula864d9e02019-01-23 17:16:241332 // Compute op instance count for the src loop nest.
River Riddle5052bd82019-02-02 00:42:181333 uint64_t dstLoopNestCost =
1334 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
1335 /*tripCountOverrideMap=*/nullptr,
1336 /*computeCostMap=*/nullptr);
MLIR Team27d067e2019-01-16 17:55:021337
MLIR Teamb9dde912019-02-06 19:01:101338 // Evaluate all depth choices for materializing the slice in the destination
1339 // loop nest.
River Riddle5052bd82019-02-02 00:42:181340 llvm::SmallDenseMap<Instruction *, uint64_t, 8> sliceTripCountMap;
1341 DenseMap<Instruction *, int64_t> computeCostMap;
MLIR Team27d067e2019-01-16 17:55:021342 for (unsigned i = maxDstLoopDepth; i >= 1; --i) {
1343 MemRefAccess srcAccess(srcOpInst);
1344 // Handle the common case of one dst load without a copy.
1345 if (!mlir::getBackwardComputationSliceState(
MLIR Teamd7c82442019-01-30 23:53:411346 srcAccess, MemRefAccess(dstLoadOpInsts[0]), i, &sliceStates[i - 1]))
MLIR Team27d067e2019-01-16 17:55:021347 return false;
MLIR Teamd7c82442019-01-30 23:53:411348 // Compute the union of slice bound of all ops in 'dstLoadOpInsts'.
1349 for (int j = 1, e = dstLoadOpInsts.size(); j < e; ++j) {
1350 MemRefAccess dstAccess(dstLoadOpInsts[j]);
MLIR Team27d067e2019-01-16 17:55:021351 ComputationSliceState tmpSliceState;
1352 if (!mlir::getBackwardComputationSliceState(srcAccess, dstAccess, i,
1353 &tmpSliceState))
1354 return false;
1355 // Compute slice boun dunion of 'tmpSliceState' and 'sliceStates[i - 1]'.
Uday Bondhugulac1ca23e2019-01-16 21:13:001356 getSliceUnion(tmpSliceState, &sliceStates[i - 1]);
MLIR Team38c2fe32019-01-14 19:26:251357 }
Uday Bondhugulab4a14432019-01-26 00:00:501358 // Build trip count map for computation slice. We'll skip cases where the
1359 // trip count was non-constant.
MLIR Team27d067e2019-01-16 17:55:021360 sliceTripCountMap.clear();
1361 if (!buildSliceTripCountMap(srcOpInst, &sliceStates[i - 1],
1362 &sliceTripCountMap))
Uday Bondhugula864d9e02019-01-23 17:16:241363 continue;
1364
1365 // Checks whether a store to load forwarding will happen.
1366 int64_t sliceIterationCount = getSliceIterationCount(sliceTripCountMap);
Uday Bondhugula864d9e02019-01-23 17:16:241367 assert(sliceIterationCount > 0);
Uday Bondhugulab4a14432019-01-26 00:00:501368 bool storeLoadFwdGuaranteed = (sliceIterationCount == 1);
Uday Bondhugula864d9e02019-01-23 17:16:241369
1370 // Compute cost of fusion for this dest loop depth.
1371
1372 computeCostMap.clear();
1373
1374 // The store and loads to this memref will disappear.
1375 if (storeLoadFwdGuaranteed) {
1376 // A single store disappears: -1 for that.
River Riddle5052bd82019-02-02 00:42:181377 computeCostMap[srcLoopIVs[numSrcLoopIVs - 1]->getInstruction()] = -1;
MLIR Teamd7c82442019-01-30 23:53:411378 for (auto *loadOp : dstLoadOpInsts) {
River Riddle5052bd82019-02-02 00:42:181379 auto *parentInst = loadOp->getParentInst();
River Riddleb4992772019-02-04 18:38:471380 if (parentInst && parentInst->isa<AffineForOp>())
River Riddle5052bd82019-02-02 00:42:181381 computeCostMap[parentInst] = -1;
Uday Bondhugula864d9e02019-01-23 17:16:241382 }
1383 }
MLIR Team27d067e2019-01-16 17:55:021384
MLIR Team38c2fe32019-01-14 19:26:251385 // Compute op instance count for the src loop nest with iteration slicing.
Uday Bondhugula864d9e02019-01-23 17:16:241386 int64_t sliceComputeCost =
River Riddle5052bd82019-02-02 00:42:181387 getComputeCost(srcLoopIVs[0]->getInstruction(), &srcLoopNestStats,
Uday Bondhugula864d9e02019-01-23 17:16:241388 /*tripCountOverrideMap=*/&sliceTripCountMap,
1389 /*computeCostMap=*/&computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:251390
Uday Bondhugula864d9e02019-01-23 17:16:241391 // Compute cost of fusion for this depth.
River Riddle5052bd82019-02-02 00:42:181392 computeCostMap[dstLoopIVs[i - 1]->getInstruction()] = sliceComputeCost;
Uday Bondhugula864d9e02019-01-23 17:16:241393
1394 int64_t fusedLoopNestComputeCost =
River Riddle5052bd82019-02-02 00:42:181395 getComputeCost(dstLoopIVs[0]->getInstruction(), &dstLoopNestStats,
MLIR Team27d067e2019-01-16 17:55:021396 /*tripCountOverrideMap=*/nullptr, &computeCostMap);
Uday Bondhugula864d9e02019-01-23 17:16:241397
1398 double additionalComputeFraction =
1399 fusedLoopNestComputeCost /
1400 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1401 1;
1402
MLIR Teamb9dde912019-02-06 19:01:101403 // Compute what the slice write MemRefRegion would be, if the src loop
1404 // nest slice 'sliceStates[i - 1]' were to be inserted into the dst loop
1405 // nest at loop depth 'i'
1406 MemRefRegion sliceWriteRegion(srcOpInst->getLoc());
1407 sliceWriteRegion.compute(srcOpInst, /*loopDepth=*/0, &sliceStates[i - 1]);
1408 Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1409 sliceWriteRegion.getRegionSize();
1410 if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
1411 maybeSliceWriteRegionSizeBytes.getValue() == 0)
1412 continue;
1413 int64_t sliceWriteRegionSizeBytes =
1414 maybeSliceWriteRegionSizeBytes.getValue();
1415
1416 double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1417 static_cast<double>(sliceWriteRegionSizeBytes);
Uday Bondhugula864d9e02019-01-23 17:16:241418
Uday Bondhugula06d21d92019-01-25 01:01:491419 LLVM_DEBUG({
1420 std::stringstream msg;
1421 msg << " evaluating fusion profitability at depth : " << i << "\n"
Uday Bondhugulad4b3ff12019-02-27 00:10:191422 << std::fixed << std::setprecision(2)
1423 << " additional compute fraction: "
Uday Bondhugula06d21d92019-01-25 01:01:491424 << 100.0 * additionalComputeFraction << "%\n"
1425 << " storage reduction factor: " << storageReduction << "x\n"
1426 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
Uday Bondhugulaa1dad3a2019-02-20 02:17:191427 << " slice iteration count: " << sliceIterationCount << "\n"
1428 << " src write region size: " << srcWriteRegionSizeBytes << "\n"
1429 << " slice write region size: " << sliceWriteRegionSizeBytes
1430 << "\n";
Uday Bondhugula06d21d92019-01-25 01:01:491431 llvm::dbgs() << msg.str();
1432 });
Uday Bondhugula864d9e02019-01-23 17:16:241433
1434 double computeToleranceThreshold =
1435 clFusionAddlComputeTolerance.getNumOccurrences() > 0
1436 ? clFusionAddlComputeTolerance
1437 : LoopFusion::kComputeToleranceThreshold;
1438
1439 // TODO(b/123247369): This is a placeholder cost model.
1440 // Among all choices that add an acceptable amount of redundant computation
1441 // (as per computeToleranceThreshold), we will simply pick the one that
1442 // reduces the intermediary size the most.
1443 if ((storageReduction > maxStorageReduction) &&
1444 (clMaximalLoopFusion ||
1445 (additionalComputeFraction < computeToleranceThreshold))) {
1446 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021447 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241448 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101449 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251450 }
1451 }
1452
Uday Bondhugula864d9e02019-01-23 17:16:241453 // A simple cost model: fuse if it reduces the memory footprint. If
1454 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251455
Uday Bondhugula864d9e02019-01-23 17:16:241456 if (!clMaximalLoopFusion && !bestDstLoopDepth.hasValue()) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191457 LLVM_DEBUG(
1458 llvm::dbgs()
1459 << "All fusion choices involve more than the threshold amount of "
1460 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251461 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241462 }
1463
1464 assert(bestDstLoopDepth.hasValue() &&
1465 "expected to have a value per logic above");
1466
1467 // Set dstLoopDepth based on best values from search.
1468 *dstLoopDepth = bestDstLoopDepth.getValue();
1469
1470 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491471 llvm::dbgs() << " LoopFusion fusion stats:"
1472 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241473 << "\n src loop nest compute cost: " << srcLoopNestCost
1474 << "\n dst loop nest compute cost: " << dstLoopNestCost
1475 << "\n fused loop nest compute cost: "
1476 << minFusedLoopNestComputeCost << "\n");
1477
River Riddle5052bd82019-02-02 00:42:181478 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1479 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241480
1481 Optional<double> storageReduction = None;
1482
1483 if (!clMaximalLoopFusion) {
1484 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1485 LLVM_DEBUG(
1486 llvm::dbgs()
1487 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1488 return false;
1489 }
1490
1491 auto srcMemSizeVal = srcMemSize.getValue();
1492 auto dstMemSizeVal = dstMemSize.getValue();
1493
1494 assert(sliceMemEstimate.hasValue() && "expected value");
1495 // This is an inaccurate estimate since sliceMemEstimate is isaccurate.
1496 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1497
1498 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1499 << " dst mem: " << dstMemSizeVal << "\n"
1500 << " fused mem: " << fusedMem << "\n"
1501 << " slice mem: " << sliceMemEstimate << "\n");
1502
1503 if (fusedMem > srcMemSizeVal + dstMemSizeVal) {
1504 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1505 return false;
1506 }
1507 storageReduction =
1508 100.0 *
1509 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1510 }
1511
1512 double additionalComputeFraction =
1513 100.0 * (minFusedLoopNestComputeCost /
1514 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1515 1);
MLIR Team5c5739d2019-01-25 06:27:401516 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491517 LLVM_DEBUG({
1518 std::stringstream msg;
1519 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
MLIR Team8564b272019-02-22 15:48:591520 << std::setprecision(2) << additionalComputeFraction
Uday Bondhugula06d21d92019-01-25 01:01:491521 << "% redundant computation and a ";
1522 msg << (storageReduction.hasValue()
1523 ? std::to_string(storageReduction.getValue())
1524 : "<unknown>");
1525 msg << "% storage reduction.\n";
1526 llvm::dbgs() << msg.str();
1527 });
Uday Bondhugula864d9e02019-01-23 17:16:241528
MLIR Team27d067e2019-01-16 17:55:021529 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241530 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021531 sliceState->lbs = bestSliceState->lbs;
1532 sliceState->ubs = bestSliceState->ubs;
1533 sliceState->lbOperands = bestSliceState->lbOperands;
1534 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241535
MLIR Team27d067e2019-01-16 17:55:021536 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251537 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171538 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021539 canonicalizeMapAndOperands(&sliceState->lbs[i],
1540 &sliceState->lbOperands[i]);
1541 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171542 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021543 canonicalizeMapAndOperands(&sliceState->ubs[i],
1544 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251545 }
1546 }
1547 return true;
1548}
1549
MLIR Team6892ffb2018-12-20 04:42:551550// GreedyFusion greedily fuses loop nests which have a producer/consumer
MLIR Team3b692302018-12-17 17:57:141551// relationship on a memref, with the goal of improving locality. Currently,
1552// this the producer/consumer relationship is required to be unique in the
Chris Lattner69d9e992018-12-28 16:48:091553// Function (there are TODOs to relax this constraint in the future).
MLIR Teamf28e4df2018-11-01 14:26:001554//
MLIR Team3b692302018-12-17 17:57:141555// The steps of the algorithm are as follows:
1556//
MLIR Team6892ffb2018-12-20 04:42:551557// *) A worklist is initialized with node ids from the dependence graph.
1558// *) For each node id in the worklist:
River Riddle5052bd82019-02-02 00:42:181559// *) Pop a AffineForOp of the worklist. This 'dstAffineForOp' will be a
1560// candidate destination AffineForOp into which fusion will be attempted.
1561// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141562// *) For each LoadOp in 'dstLoadOps' do:
Chris Lattner69d9e992018-12-28 16:48:091563// *) Lookup dependent loop nests at earlier positions in the Function
MLIR Team3b692302018-12-17 17:57:141564// which have a single store op to the same memref.
1565// *) Check if dependences would be violated by the fusion. For example,
1566// the src loop nest may load from memrefs which are different than
1567// the producer-consumer memref between src and dest loop nests.
MLIR Team6892ffb2018-12-20 04:42:551568// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141569// bounds to be functions of 'dstLoopNest' IVs and symbols.
1570// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
1571// just before the dst load op user.
Chris Lattner456ad6a2018-12-29 00:05:351572// *) Add the newly fused load/store operation instructions to the state,
MLIR Team3b692302018-12-17 17:57:141573// and also add newly fuse load ops to 'dstLoopOps' to be considered
1574// as fusion dst load ops in another iteration.
1575// *) Remove old src loop nest and its associated state.
1576//
Chris Lattner456ad6a2018-12-29 00:05:351577// Given a graph where top-level instructions are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141578// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551579// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141580//
MLIR Team6892ffb2018-12-20 04:42:551581// This greedy algorithm is not 'maximal' due to the current restriction of
1582// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141583//
1584// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551585// TODO(andydavis) Add support for fusing for input reuse (perhaps by
1586// constructing a graph with edges which represent loads from the same memref
MLIR Team5c5739d2019-01-25 06:27:401587// in two different loop nests.
MLIR Team6892ffb2018-12-20 04:42:551588struct GreedyFusion {
1589public:
1590 MemRefDependenceGraph *mdg;
MLIR Teama78edcd2019-02-05 14:57:081591 SmallVector<unsigned, 8> worklist;
1592 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamf28e4df2018-11-01 14:26:001593
MLIR Team6892ffb2018-12-20 04:42:551594 GreedyFusion(MemRefDependenceGraph *mdg) : mdg(mdg) {
1595 // Initialize worklist with nodes from 'mdg'.
MLIR Teama78edcd2019-02-05 14:57:081596 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1597 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Team6892ffb2018-12-20 04:42:551598 worklist.resize(mdg->nodes.size());
1599 std::iota(worklist.begin(), worklist.end(), 0);
MLIR Teama78edcd2019-02-05 14:57:081600 worklistSet.insert(worklist.begin(), worklist.end());
MLIR Team6892ffb2018-12-20 04:42:551601 }
MLIR Team3b692302018-12-17 17:57:141602
Uday Bondhugula8be26272019-02-02 01:06:221603 void run(unsigned localBufSizeThreshold, Optional<unsigned> fastMemorySpace) {
MLIR Team3b692302018-12-17 17:57:141604 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551605 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141606 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081607 worklistSet.erase(dstId);
1608
MLIR Team6892ffb2018-12-20 04:42:551609 // Skip if this node was removed (fused into another node).
1610 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141611 continue;
MLIR Team6892ffb2018-12-20 04:42:551612 // Get 'dstNode' into which to attempt fusion.
1613 auto *dstNode = mdg->getNode(dstId);
1614 // Skip if 'dstNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471615 if (!dstNode->inst->isa<AffineForOp>())
MLIR Team3b692302018-12-17 17:57:141616 continue;
MLIR Team8f5f2c72019-02-15 17:32:181617 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1618 // while preserving relative order. This can increase the maximum loop
1619 // depth at which we can fuse a slice of a producer loop nest into a
1620 // consumer loop nest.
1621 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141622
River Riddleb4992772019-02-04 18:38:471623 SmallVector<Instruction *, 4> loads = dstNode->loads;
1624 SmallVector<Instruction *, 4> dstLoadOpInsts;
MLIR Teamc4237ae2019-01-18 16:56:271625 DenseSet<Value *> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551626 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021627 // Get memref of load on top of the stack.
1628 auto *memref = loads.back()->cast<LoadOp>()->getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271629 if (visitedMemrefs.count(memref) > 0)
1630 continue;
1631 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021632 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1633 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551634 // Skip if no input edges along which to fuse.
1635 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141636 continue;
MLIR Team1e851912019-01-31 00:01:461637 // Iterate through in edges for 'dstId' and src node id for any
1638 // edges on 'memref'.
1639 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551640 for (auto &srcEdge : mdg->inEdges[dstId]) {
1641 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411642 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551643 continue;
MLIR Team1e851912019-01-31 00:01:461644 srcNodeIds.push_back(srcEdge.id);
1645 }
1646 for (unsigned srcId : srcNodeIds) {
1647 // Skip if this node was removed (fused into another node).
1648 if (mdg->nodes.count(srcId) == 0)
1649 continue;
1650 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1651 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551652 // Skip if 'srcNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471653 if (!srcNode->inst->isa<AffineForOp>())
MLIR Team6892ffb2018-12-20 04:42:551654 continue;
MLIR Teamb28009b2019-01-23 19:11:431655 // Skip if 'srcNode' has more than one store to any memref.
1656 // TODO(andydavis) Support fusing multi-output src loop nests.
1657 if (srcNode->stores.size() != 1)
MLIR Team6892ffb2018-12-20 04:42:551658 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241659
MLIR Teama0f3db402019-01-29 17:36:411660 // Skip 'srcNode' if it has in edges on 'memref'.
MLIR Team6892ffb2018-12-20 04:42:551661 // TODO(andydavis) Track dependence type with edges, and just check
MLIR Teama0f3db402019-01-29 17:36:411662 // for WAW dependence edge here. Note that this check is overly
1663 // conservative and will be removed in the future.
1664 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) != 0)
MLIR Team6892ffb2018-12-20 04:42:551665 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241666
MLIR Team58aa3832019-02-16 01:12:191667 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1668 // and cannot be fused.
1669 bool writesToLiveInOrOut =
1670 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1671 if (writesToLiveInOrOut &&
1672 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, memref, mdg))
MLIR Teamd7c82442019-01-30 23:53:411673 continue;
1674
MLIR Teama0f3db402019-01-29 17:36:411675 // Compute an instruction list insertion point for the fused loop
1676 // nest which preserves dependences.
MLIR Teama78edcd2019-02-05 14:57:081677 Instruction *insertPointInst =
1678 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411679 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551680 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241681
MLIR Team6892ffb2018-12-20 04:42:551682 // Get unique 'srcNode' store op.
Chris Lattner456ad6a2018-12-29 00:05:351683 auto *srcStoreOpInst = srcNode->stores.front();
MLIR Teamd7c82442019-01-30 23:53:411684 // Gather 'dstNode' store ops to 'memref'.
River Riddleb4992772019-02-04 18:38:471685 SmallVector<Instruction *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411686 for (auto *storeOpInst : dstNode->stores)
1687 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1688 dstStoreOpInsts.push_back(storeOpInst);
1689
Uday Bondhugulab4a14432019-01-26 00:00:501690 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251691 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411692 // Check if fusion would be profitable.
MLIR Teamd7c82442019-01-30 23:53:411693 if (!isFusionProfitable(srcStoreOpInst, dstLoadOpInsts,
1694 dstStoreOpInsts, &sliceState,
Uday Bondhugulab4a14432019-01-26 00:00:501695 &bestDstLoopDepth))
MLIR Team38c2fe32019-01-14 19:26:251696 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241697
MLIR Team6892ffb2018-12-20 04:42:551698 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181699 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Uday Bondhugulab4a14432019-01-26 00:00:501700 srcStoreOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
MLIR Team6892ffb2018-12-20 04:42:551701 if (sliceLoopNest != nullptr) {
Uday Bondhugulaa1dad3a2019-02-20 02:17:191702 LLVM_DEBUG(llvm::dbgs()
1703 << "\tslice loop nest:\n"
1704 << *sliceLoopNest->getInstruction() << "\n");
River Riddle5052bd82019-02-02 00:42:181705 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleb4992772019-02-04 18:38:471706 auto dstAffineForOp = dstNode->inst->cast<AffineForOp>();
River Riddle5052bd82019-02-02 00:42:181707 if (insertPointInst != dstAffineForOp->getInstruction()) {
1708 dstAffineForOp->getInstruction()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411709 }
MLIR Teamc4237ae2019-01-18 16:56:271710 // Update edges between 'srcNode' and 'dstNode'.
MLIR Teama0f3db402019-01-29 17:36:411711 mdg->updateEdges(srcNode->id, dstNode->id, memref);
MLIR Teamc4237ae2019-01-18 16:56:271712
1713 // Collect slice loop stats.
1714 LoopNestStateCollector sliceCollector;
River Riddlebf9c3812019-02-05 00:24:441715 sliceCollector.collect(sliceLoopNest->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271716 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181717 for (auto forOp : sliceCollector.forOps) {
1718 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551719 }
MLIR Team58aa3832019-02-16 01:12:191720 if (!writesToLiveInOrOut) {
1721 // Create private memref for 'memref' in 'dstAffineForOp'.
1722 SmallVector<Instruction *, 4> storesForMemref;
1723 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
1724 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1725 storesForMemref.push_back(storeOpInst);
1726 }
1727 assert(storesForMemref.size() == 1);
1728 auto *newMemRef = createPrivateMemRef(
1729 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1730 fastMemorySpace, localBufSizeThreshold);
1731 visitedMemrefs.insert(newMemRef);
1732 // Create new node in dependence graph for 'newMemRef' alloc op.
1733 unsigned newMemRefNodeId =
1734 mdg->addNode(newMemRef->getDefiningInst());
1735 // Add edge from 'newMemRef' node to dstNode.
1736 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271737 }
MLIR Teamc4237ae2019-01-18 16:56:271738
1739 // Collect dst loop stats after memref privatizaton transformation.
1740 LoopNestStateCollector dstLoopCollector;
River Riddlebf9c3812019-02-05 00:24:441741 dstLoopCollector.collect(dstAffineForOp->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271742
1743 // Add new load ops to current Node load op list 'loads' to
1744 // continue fusing based on new operands.
1745 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
1746 auto *loadMemRef = loadOpInst->cast<LoadOp>()->getMemRef();
1747 if (visitedMemrefs.count(loadMemRef) == 0)
1748 loads.push_back(loadOpInst);
1749 }
1750
1751 // Clear and add back loads and stores
1752 mdg->clearNodeLoadAndStores(dstNode->id);
1753 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1754 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371755 // Remove old src loop nest if it no longer has outgoing dependence
1756 // edges, and it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191757 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1758 // been fused into 'dstNode' and write region of 'dstNode' covers
1759 // the write region of 'srcNode', and 'srcNode' has no other users
1760 // so it is safe to remove.
1761 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271762 mdg->removeNode(srcNode->id);
River Riddle5052bd82019-02-02 00:42:181763 srcNode->inst->erase();
MLIR Teama78edcd2019-02-05 14:57:081764 } else {
1765 // Add remaining users of 'oldMemRef' back on the worklist (if not
1766 // already there), as its replacement with a local/private memref
1767 // has reduced dependences on 'oldMemRef' which may have created
1768 // new fusion opportunities.
1769 if (mdg->outEdges.count(srcNode->id) > 0) {
1770 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1771 mdg->outEdges[srcNode->id];
1772 for (auto &outEdge : oldOutEdges) {
1773 if (outEdge.value == memref &&
1774 worklistSet.count(outEdge.id) == 0) {
1775 worklist.push_back(outEdge.id);
1776 worklistSet.insert(outEdge.id);
1777 }
1778 }
1779 }
MLIR Teamc4237ae2019-01-18 16:56:271780 }
MLIR Team3b692302018-12-17 17:57:141781 }
MLIR Team3b692302018-12-17 17:57:141782 }
1783 }
1784 }
MLIR Teamc4237ae2019-01-18 16:56:271785 // Clean up any allocs with no users.
1786 for (auto &pair : mdg->memrefEdgeCount) {
1787 if (pair.second > 0)
1788 continue;
1789 auto *memref = pair.first;
MLIR Team71495d52019-01-22 21:23:371790 // Skip if there exist other uses (return instruction or function calls).
1791 if (!memref->use_empty())
1792 continue;
MLIR Teamc4237ae2019-01-18 16:56:271793 // Use list expected to match the dep graph info.
MLIR Teamc4237ae2019-01-18 16:56:271794 auto *inst = memref->getDefiningInst();
River Riddleb4992772019-02-04 18:38:471795 if (inst && inst->isa<AllocOp>())
1796 inst->erase();
MLIR Teamc4237ae2019-01-18 16:56:271797 }
MLIR Teamf28e4df2018-11-01 14:26:001798 }
MLIR Team3b692302018-12-17 17:57:141799};
1800
1801} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001802
River Riddlec6c53442019-02-27 18:59:291803PassResult LoopFusion::runOnFunction() {
Uday Bondhugulad4b3ff12019-02-27 00:10:191804 // Override if a command line argument was provided.
Uday Bondhugula8be26272019-02-02 01:06:221805 if (clFusionFastMemorySpace.getNumOccurrences() > 0) {
1806 fastMemorySpace = clFusionFastMemorySpace.getValue();
1807 }
1808
Uday Bondhugulad4b3ff12019-02-27 00:10:191809 // Override if a command line argument was provided.
1810 if (clFusionLocalBufThreshold.getNumOccurrences() > 0) {
1811 localBufSizeThreshold = clFusionLocalBufThreshold * 1024;
1812 }
1813
MLIR Team6892ffb2018-12-20 04:42:551814 MemRefDependenceGraph g;
River Riddlec6c53442019-02-27 18:59:291815 if (g.init(&getFunction()))
Uday Bondhugula8be26272019-02-02 01:06:221816 GreedyFusion(&g).run(localBufSizeThreshold, fastMemorySpace);
MLIR Teamf28e4df2018-11-01 14:26:001817 return success();
1818}
Jacques Pienaar6f0fb222018-11-07 02:34:181819
1820static PassRegistration<LoopFusion> pass("loop-fusion", "Fuse loop nests");