blob: aebf2716c4e79ab7b0613094cbe8b4db7f00e8d9 [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"
MLIR Teamf28e4df2018-11-01 14:26:0024#include "mlir/Analysis/LoopAnalysis.h"
MLIR Team3b692302018-12-17 17:57:1425#include "mlir/Analysis/Utils.h"
MLIR Teamf28e4df2018-11-01 14:26:0026#include "mlir/IR/AffineExpr.h"
27#include "mlir/IR/AffineMap.h"
River Riddle10237de2019-02-06 01:00:1328#include "mlir/IR/AffineStructures.h"
MLIR Teamf28e4df2018-11-01 14:26:0029#include "mlir/IR/Builders.h"
30#include "mlir/IR/BuiltinOps.h"
MLIR Teamf28e4df2018-11-01 14:26:0031#include "mlir/Pass.h"
32#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,
61 llvm::cl::desc("Fractional increase in additional"
River Riddle75c21e12019-01-26 06:14:0462 " computation tolerated while fusing"),
63 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
70static llvm::cl::opt<unsigned> clFusionLocalBufThreshold(
71 "fusion-local-buf-threshold", llvm::cl::Hidden,
72 llvm::cl::desc("Threshold size (bytes) for promoting local buffers to fast "
73 "memory space"),
74 llvm::cl::cat(clOptionsCategory));
75
MLIR Teamf28e4df2018-11-01 14:26:0076namespace {
77
MLIR Team3b692302018-12-17 17:57:1478/// Loop fusion pass. This pass currently supports a greedy fusion policy,
79/// which fuses loop nests with single-writer/single-reader memref dependences
80/// with the goal of improving locality.
81
82// TODO(andydavis) Support fusion of source loop nests which write to multiple
83// memrefs, where each memref can have multiple users (if profitable).
MLIR Teamf28e4df2018-11-01 14:26:0084// TODO(andydavis) Extend this pass to check for fusion preventing dependences,
85// and add support for more general loop fusion algorithms.
MLIR Team3b692302018-12-17 17:57:1486
MLIR Teamf28e4df2018-11-01 14:26:0087struct LoopFusion : public FunctionPass {
Jacques Pienaarcc9a6ed2018-11-07 18:24:0388 LoopFusion() : FunctionPass(&LoopFusion::passID) {}
MLIR Teamf28e4df2018-11-01 14:26:0089
Chris Lattner79748892018-12-31 07:10:3590 PassResult runOnFunction(Function *f) override;
Jacques Pienaar6f0fb222018-11-07 02:34:1891 static char passID;
Uday Bondhugula864d9e02019-01-23 17:16:2492
Uday Bondhugula8be26272019-02-02 01:06:2293 // Any local buffers smaller than this size will be created in
94 // `fastMemorySpace` if provided.
95 unsigned localBufSizeThreshold = 1024;
96 Optional<unsigned> fastMemorySpace = None;
97
Uday Bondhugula864d9e02019-01-23 17:16:2498 // The amount of additional computation that is tolerated while fusing
99 // pair-wise as a fraction of the total computation.
100 constexpr static double kComputeToleranceThreshold = 0.30f;
MLIR Teamf28e4df2018-11-01 14:26:00101};
102
MLIR Teamf28e4df2018-11-01 14:26:00103} // end anonymous namespace
104
Jacques Pienaar6f0fb222018-11-07 02:34:18105char LoopFusion::passID = 0;
106
MLIR Teamf28e4df2018-11-01 14:26:00107FunctionPass *mlir::createLoopFusionPass() { return new LoopFusion; }
108
MLIR Team3b692302018-12-17 17:57:14109namespace {
MLIR Teamf28e4df2018-11-01 14:26:00110
MLIR Team3b692302018-12-17 17:57:14111// LoopNestStateCollector walks loop nests and collects load and store
Chris Lattner456ad6a2018-12-29 00:05:35112// operations, and whether or not an IfInst was encountered in the loop nest.
River Riddlebf9c3812019-02-05 00:24:44113struct LoopNestStateCollector {
River Riddle5052bd82019-02-02 00:42:18114 SmallVector<OpPointer<AffineForOp>, 4> forOps;
River Riddleb4992772019-02-04 18:38:47115 SmallVector<Instruction *, 4> loadOpInsts;
116 SmallVector<Instruction *, 4> storeOpInsts;
River Riddle75553832019-01-29 05:23:53117 bool hasNonForRegion = false;
MLIR Team3b692302018-12-17 17:57:14118
River Riddlebf9c3812019-02-05 00:24:44119 void collect(Instruction *instToWalk) {
120 instToWalk->walk([&](Instruction *opInst) {
121 if (opInst->isa<AffineForOp>())
122 forOps.push_back(opInst->cast<AffineForOp>());
123 else if (opInst->getNumBlockLists() != 0)
124 hasNonForRegion = true;
125 else if (opInst->isa<LoadOp>())
126 loadOpInsts.push_back(opInst);
127 else if (opInst->isa<StoreOp>())
128 storeOpInsts.push_back(opInst);
129 });
MLIR Team3b692302018-12-17 17:57:14130 }
131};
132
MLIR Team71495d52019-01-22 21:23:37133// TODO(b/117228571) Replace when this is modeled through side-effects/op traits
River Riddleb4992772019-02-04 18:38:47134static bool isMemRefDereferencingOp(const Instruction &op) {
MLIR Team71495d52019-01-22 21:23:37135 if (op.isa<LoadOp>() || op.isa<StoreOp>() || op.isa<DmaStartOp>() ||
136 op.isa<DmaWaitOp>())
137 return true;
138 return false;
139}
MLIR Team6892ffb2018-12-20 04:42:55140// MemRefDependenceGraph is a graph data structure where graph nodes are
Chris Lattner456ad6a2018-12-29 00:05:35141// top-level instructions in a Function which contain load/store ops, and edges
MLIR Team6892ffb2018-12-20 04:42:55142// are memref dependences between the nodes.
MLIR Teamc4237ae2019-01-18 16:56:27143// TODO(andydavis) Add a more flexible dependece graph representation.
MLIR Team6892ffb2018-12-20 04:42:55144// TODO(andydavis) Add a depth parameter to dependence graph construction.
145struct MemRefDependenceGraph {
146public:
147 // Node represents a node in the graph. A Node is either an entire loop nest
148 // rooted at the top level which contains loads/stores, or a top level
149 // load/store.
150 struct Node {
151 // The unique identifier of this node in the graph.
152 unsigned id;
153 // The top-level statment which is (or contains) loads/stores.
Chris Lattner456ad6a2018-12-29 00:05:35154 Instruction *inst;
Chris Lattner5187cfc2018-12-28 05:21:41155 // List of load operations.
River Riddleb4992772019-02-04 18:38:47156 SmallVector<Instruction *, 4> loads;
Chris Lattner456ad6a2018-12-29 00:05:35157 // List of store op insts.
River Riddleb4992772019-02-04 18:38:47158 SmallVector<Instruction *, 4> stores;
Chris Lattner456ad6a2018-12-29 00:05:35159 Node(unsigned id, Instruction *inst) : id(id), inst(inst) {}
MLIR Team6892ffb2018-12-20 04:42:55160
161 // Returns the load op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10162 unsigned getLoadOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55163 unsigned loadOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35164 for (auto *loadOpInst : loads) {
165 if (memref == loadOpInst->cast<LoadOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55166 ++loadOpCount;
167 }
168 return loadOpCount;
169 }
170
171 // Returns the store op count for 'memref'.
Chris Lattner3f190312018-12-27 22:35:10172 unsigned getStoreOpCount(Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55173 unsigned storeOpCount = 0;
Chris Lattner456ad6a2018-12-29 00:05:35174 for (auto *storeOpInst : stores) {
175 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
MLIR Team6892ffb2018-12-20 04:42:55176 ++storeOpCount;
177 }
178 return storeOpCount;
179 }
MLIR Team58aa3832019-02-16 01:12:19180
181 // Returns all store ups in 'storeOps' which access 'memref'.
182 void getStoreOpsForMemref(Value *memref,
183 SmallVectorImpl<Instruction *> *storeOps) {
184 for (auto *storeOpInst : stores) {
185 if (memref == storeOpInst->cast<StoreOp>()->getMemRef())
186 storeOps->push_back(storeOpInst);
187 }
188 }
MLIR Team6892ffb2018-12-20 04:42:55189 };
190
MLIR Teama0f3db402019-01-29 17:36:41191 // Edge represents a data dependece between nodes in the graph.
MLIR Team6892ffb2018-12-20 04:42:55192 struct Edge {
193 // The id of the node at the other end of the edge.
MLIR Team1e851912019-01-31 00:01:46194 // If this edge is stored in Edge = Node.inEdges[i], then
195 // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
196 // If this edge is stored in Edge = Node.outEdges[i], then
197 // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
MLIR Team6892ffb2018-12-20 04:42:55198 unsigned id;
MLIR Teama0f3db402019-01-29 17:36:41199 // The SSA value on which this edge represents a dependence.
200 // If the value is a memref, then the dependence is between graph nodes
201 // which contain accesses to the same memref 'value'. If the value is a
202 // non-memref value, then the dependence is between a graph node which
203 // defines an SSA value and another graph node which uses the SSA value
204 // (e.g. a constant instruction defining a value which is used inside a loop
205 // nest).
206 Value *value;
MLIR Team6892ffb2018-12-20 04:42:55207 };
208
209 // Map from node id to Node.
210 DenseMap<unsigned, Node> nodes;
211 // Map from node id to list of input edges.
212 DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
213 // Map from node id to list of output edges.
214 DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
MLIR Teamc4237ae2019-01-18 16:56:27215 // Map from memref to a count on the dependence edges associated with that
216 // memref.
217 DenseMap<Value *, unsigned> memrefEdgeCount;
MLIR Teama0f3db402019-01-29 17:36:41218 // The next unique identifier to use for newly created graph nodes.
219 unsigned nextNodeId = 0;
MLIR Team6892ffb2018-12-20 04:42:55220
221 MemRefDependenceGraph() {}
222
223 // Initializes the dependence graph based on operations in 'f'.
224 // Returns true on success, false otherwise.
Chris Lattner69d9e992018-12-28 16:48:09225 bool init(Function *f);
MLIR Team6892ffb2018-12-20 04:42:55226
227 // Returns the graph node for 'id'.
228 Node *getNode(unsigned id) {
229 auto it = nodes.find(id);
230 assert(it != nodes.end());
231 return &it->second;
232 }
233
MLIR Teama0f3db402019-01-29 17:36:41234 // Adds a node with 'inst' to the graph and returns its unique identifier.
235 unsigned addNode(Instruction *inst) {
236 Node node(nextNodeId++, inst);
237 nodes.insert({node.id, node});
238 return node.id;
239 }
240
MLIR Teamc4237ae2019-01-18 16:56:27241 // Remove node 'id' (and its associated edges) from graph.
242 void removeNode(unsigned id) {
243 // Remove each edge in 'inEdges[id]'.
244 if (inEdges.count(id) > 0) {
245 SmallVector<Edge, 2> oldInEdges = inEdges[id];
246 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41247 removeEdge(inEdge.id, id, inEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27248 }
249 }
250 // Remove each edge in 'outEdges[id]'.
251 if (outEdges.count(id) > 0) {
252 SmallVector<Edge, 2> oldOutEdges = outEdges[id];
253 for (auto &outEdge : oldOutEdges) {
MLIR Teama0f3db402019-01-29 17:36:41254 removeEdge(id, outEdge.id, outEdge.value);
MLIR Teamc4237ae2019-01-18 16:56:27255 }
256 }
257 // Erase remaining node state.
258 inEdges.erase(id);
259 outEdges.erase(id);
260 nodes.erase(id);
261 }
262
MLIR Teamd7c82442019-01-30 23:53:41263 // Returns true if node 'id' writes to any memref which escapes (or is an
264 // argument to) the function/block. Returns false otherwise.
265 bool writesToLiveInOrEscapingMemrefs(unsigned id) {
MLIR Team71495d52019-01-22 21:23:37266 Node *node = getNode(id);
267 for (auto *storeOpInst : node->stores) {
268 auto *memref = storeOpInst->cast<StoreOp>()->getMemRef();
269 auto *inst = memref->getDefiningInst();
MLIR Team58aa3832019-02-16 01:12:19270 // Return true if 'memref' is a block argument.
River Riddleb4992772019-02-04 18:38:47271 if (!inst)
MLIR Teamd7c82442019-01-30 23:53:41272 return true;
MLIR Team58aa3832019-02-16 01:12:19273 // Return true if any use of 'memref' escapes the function.
River Riddleb4992772019-02-04 18:38:47274 for (auto &use : memref->getUses())
275 if (!isMemRefDereferencingOp(*use.getOwner()))
MLIR Teamd7c82442019-01-30 23:53:41276 return true;
MLIR Teamd7c82442019-01-30 23:53:41277 }
278 return false;
279 }
280
281 // Returns true if node 'id' can be removed from the graph. Returns false
282 // otherwise. A node can be removed from the graph iff the following
283 // conditions are met:
284 // *) The node does not write to any memref which escapes (or is a
285 // function/block argument).
286 // *) The node has no successors in the dependence graph.
287 bool canRemoveNode(unsigned id) {
288 if (writesToLiveInOrEscapingMemrefs(id))
289 return false;
290 Node *node = getNode(id);
291 for (auto *storeOpInst : node->stores) {
MLIR Teama0f3db402019-01-29 17:36:41292 // Return false if there exist out edges from 'id' on 'memref'.
MLIR Teamd7c82442019-01-30 23:53:41293 if (getOutEdgeCount(id, storeOpInst->cast<StoreOp>()->getMemRef()) > 0)
MLIR Teama0f3db402019-01-29 17:36:41294 return false;
MLIR Team71495d52019-01-22 21:23:37295 }
MLIR Teama0f3db402019-01-29 17:36:41296 return true;
MLIR Team71495d52019-01-22 21:23:37297 }
298
MLIR Team27d067e2019-01-16 17:55:02299 // Returns true iff there is an edge from node 'srcId' to node 'dstId' for
MLIR Teama0f3db402019-01-29 17:36:41300 // 'value'. Returns false otherwise.
301 bool hasEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team27d067e2019-01-16 17:55:02302 if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
303 return false;
304 }
305 bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41306 return edge.id == dstId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02307 });
308 bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
MLIR Teama0f3db402019-01-29 17:36:41309 return edge.id == srcId && edge.value == value;
MLIR Team27d067e2019-01-16 17:55:02310 });
311 return hasOutEdge && hasInEdge;
312 }
313
MLIR Teama0f3db402019-01-29 17:36:41314 // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
315 void addEdge(unsigned srcId, unsigned dstId, Value *value) {
316 if (!hasEdge(srcId, dstId, value)) {
317 outEdges[srcId].push_back({dstId, value});
318 inEdges[dstId].push_back({srcId, value});
319 if (value->getType().isa<MemRefType>())
320 memrefEdgeCount[value]++;
MLIR Team27d067e2019-01-16 17:55:02321 }
MLIR Team6892ffb2018-12-20 04:42:55322 }
323
MLIR Teama0f3db402019-01-29 17:36:41324 // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
325 void removeEdge(unsigned srcId, unsigned dstId, Value *value) {
MLIR Team6892ffb2018-12-20 04:42:55326 assert(inEdges.count(dstId) > 0);
327 assert(outEdges.count(srcId) > 0);
MLIR Teama0f3db402019-01-29 17:36:41328 if (value->getType().isa<MemRefType>()) {
329 assert(memrefEdgeCount.count(value) > 0);
330 memrefEdgeCount[value]--;
331 }
MLIR Team6892ffb2018-12-20 04:42:55332 // Remove 'srcId' from 'inEdges[dstId]'.
333 for (auto it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41334 if ((*it).id == srcId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55335 inEdges[dstId].erase(it);
336 break;
337 }
338 }
339 // Remove 'dstId' from 'outEdges[srcId]'.
340 for (auto it = outEdges[srcId].begin(); it != outEdges[srcId].end(); ++it) {
MLIR Teama0f3db402019-01-29 17:36:41341 if ((*it).id == dstId && (*it).value == value) {
MLIR Team6892ffb2018-12-20 04:42:55342 outEdges[srcId].erase(it);
343 break;
344 }
345 }
346 }
347
MLIR Teama0f3db402019-01-29 17:36:41348 // Returns the input edge count for node 'id' and 'memref' from src nodes
349 // which access 'memref'.
350 unsigned getIncomingMemRefAccesses(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55351 unsigned inEdgeCount = 0;
352 if (inEdges.count(id) > 0)
353 for (auto &inEdge : inEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41354 if (inEdge.value == memref) {
355 Node *srcNode = getNode(inEdge.id);
356 // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
357 if (srcNode->getLoadOpCount(memref) > 0 ||
358 srcNode->getStoreOpCount(memref) > 0)
359 ++inEdgeCount;
360 }
MLIR Team6892ffb2018-12-20 04:42:55361 return inEdgeCount;
362 }
363
364 // Returns the output edge count for node 'id' and 'memref'.
Chris Lattner3f190312018-12-27 22:35:10365 unsigned getOutEdgeCount(unsigned id, Value *memref) {
MLIR Team6892ffb2018-12-20 04:42:55366 unsigned outEdgeCount = 0;
367 if (outEdges.count(id) > 0)
368 for (auto &outEdge : outEdges[id])
MLIR Teama0f3db402019-01-29 17:36:41369 if (outEdge.value == memref)
MLIR Team6892ffb2018-12-20 04:42:55370 ++outEdgeCount;
371 return outEdgeCount;
372 }
373
MLIR Teama0f3db402019-01-29 17:36:41374 // Computes and returns an insertion point instruction, before which the
375 // the fused <srcId, dstId> loop nest can be inserted while preserving
376 // dependences. Returns nullptr if no such insertion point is found.
MLIR Teama78edcd2019-02-05 14:57:08377 Instruction *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
MLIR Team5c5739d2019-01-25 06:27:40378 if (outEdges.count(srcId) == 0)
MLIR Teama0f3db402019-01-29 17:36:41379 return getNode(dstId)->inst;
380
381 // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
382 SmallPtrSet<Instruction *, 2> srcDepInsts;
383 for (auto &outEdge : outEdges[srcId])
MLIR Teama78edcd2019-02-05 14:57:08384 if (outEdge.id != dstId)
MLIR Teama0f3db402019-01-29 17:36:41385 srcDepInsts.insert(getNode(outEdge.id)->inst);
386
387 // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
388 SmallPtrSet<Instruction *, 2> dstDepInsts;
389 for (auto &inEdge : inEdges[dstId])
MLIR Teama78edcd2019-02-05 14:57:08390 if (inEdge.id != srcId)
MLIR Teama0f3db402019-01-29 17:36:41391 dstDepInsts.insert(getNode(inEdge.id)->inst);
392
393 Instruction *srcNodeInst = getNode(srcId)->inst;
394 Instruction *dstNodeInst = getNode(dstId)->inst;
395
396 // Computing insertion point:
397 // *) Walk all instruction positions in Block instruction list in the
398 // range (src, dst). For each instruction 'inst' visited in this search:
399 // *) Store in 'firstSrcDepPos' the first position where 'inst' has a
400 // dependence edge from 'srcNode'.
401 // *) Store in 'lastDstDepPost' the last position where 'inst' has a
402 // dependence edge to 'dstNode'.
403 // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
404 // instruction insertion point (or return null pointer if no such
405 // insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
406 SmallVector<Instruction *, 2> depInsts;
407 Optional<unsigned> firstSrcDepPos;
408 Optional<unsigned> lastDstDepPos;
409 unsigned pos = 0;
410 for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
411 it != Block::iterator(dstNodeInst); ++it) {
412 Instruction *inst = &(*it);
413 if (srcDepInsts.count(inst) > 0 && firstSrcDepPos == None)
414 firstSrcDepPos = pos;
415 if (dstDepInsts.count(inst) > 0)
416 lastDstDepPos = pos;
417 depInsts.push_back(inst);
418 ++pos;
MLIR Team5c5739d2019-01-25 06:27:40419 }
MLIR Teama0f3db402019-01-29 17:36:41420
421 if (firstSrcDepPos.hasValue()) {
422 if (lastDstDepPos.hasValue()) {
423 if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
424 // No valid insertion point exists which preserves dependences.
425 return nullptr;
426 }
427 }
428 // Return the insertion point at 'firstSrcDepPos'.
429 return depInsts[firstSrcDepPos.getValue()];
430 }
431 // No dependence targets in range (or only dst deps in range), return
432 // 'dstNodInst' insertion point.
433 return dstNodeInst;
MLIR Team6892ffb2018-12-20 04:42:55434 }
435
MLIR Teama0f3db402019-01-29 17:36:41436 // Updates edge mappings from node 'srcId' to node 'dstId' after 'oldMemRef'
437 // has been replaced in node at 'dstId' by a private memref.
438 void updateEdges(unsigned srcId, unsigned dstId, Value *oldMemRef) {
MLIR Team6892ffb2018-12-20 04:42:55439 // For each edge in 'inEdges[srcId]': add new edge remaping to 'dstId'.
440 if (inEdges.count(srcId) > 0) {
441 SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
442 for (auto &inEdge : oldInEdges) {
MLIR Teama0f3db402019-01-29 17:36:41443 // Add edge from 'inEdge.id' to 'dstId' if not for 'oldMemRef'.
444 if (inEdge.value != oldMemRef)
445 addEdge(inEdge.id, dstId, inEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55446 }
447 }
MLIR Teamc4237ae2019-01-18 16:56:27448 // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
MLIR Team6892ffb2018-12-20 04:42:55449 if (outEdges.count(srcId) > 0) {
450 SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
451 for (auto &outEdge : oldOutEdges) {
MLIR Teamc4237ae2019-01-18 16:56:27452 // Remove any out edges from 'srcId' to 'dstId' across memrefs.
453 if (outEdge.id == dstId)
MLIR Teama0f3db402019-01-29 17:36:41454 removeEdge(srcId, outEdge.id, outEdge.value);
MLIR Team6892ffb2018-12-20 04:42:55455 }
456 }
MLIR Teama0f3db402019-01-29 17:36:41457 // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
458 // replaced by a private memref). These edges could come from nodes
459 // other than 'srcId' which were removed in the previous step.
460 if (inEdges.count(dstId) > 0) {
461 SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
462 for (auto &inEdge : oldInEdges)
463 if (inEdge.value == oldMemRef)
464 removeEdge(inEdge.id, dstId, inEdge.value);
465 }
MLIR Team6892ffb2018-12-20 04:42:55466 }
467
468 // Adds ops in 'loads' and 'stores' to node at 'id'.
River Riddleb4992772019-02-04 18:38:47469 void addToNode(unsigned id, const SmallVectorImpl<Instruction *> &loads,
470 const SmallVectorImpl<Instruction *> &stores) {
MLIR Team6892ffb2018-12-20 04:42:55471 Node *node = getNode(id);
Chris Lattner456ad6a2018-12-29 00:05:35472 for (auto *loadOpInst : loads)
473 node->loads.push_back(loadOpInst);
474 for (auto *storeOpInst : stores)
475 node->stores.push_back(storeOpInst);
MLIR Team6892ffb2018-12-20 04:42:55476 }
477
MLIR Teamc4237ae2019-01-18 16:56:27478 void clearNodeLoadAndStores(unsigned id) {
479 Node *node = getNode(id);
480 node->loads.clear();
481 node->stores.clear();
482 }
483
MLIR Team6892ffb2018-12-20 04:42:55484 void print(raw_ostream &os) const {
485 os << "\nMemRefDependenceGraph\n";
486 os << "\nNodes:\n";
487 for (auto &idAndNode : nodes) {
488 os << "Node: " << idAndNode.first << "\n";
489 auto it = inEdges.find(idAndNode.first);
490 if (it != inEdges.end()) {
491 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41492 os << " InEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55493 }
494 it = outEdges.find(idAndNode.first);
495 if (it != outEdges.end()) {
496 for (const auto &e : it->second)
MLIR Teama0f3db402019-01-29 17:36:41497 os << " OutEdge: " << e.id << " " << e.value << "\n";
MLIR Team6892ffb2018-12-20 04:42:55498 }
499 }
500 }
501 void dump() const { print(llvm::errs()); }
502};
503
Chris Lattner456ad6a2018-12-29 00:05:35504// Intializes the data dependence graph by walking instructions in 'f'.
MLIR Team6892ffb2018-12-20 04:42:55505// Assigns each node in the graph a node id based on program order in 'f'.
Chris Lattner315a4662018-12-28 21:07:39506// TODO(andydavis) Add support for taking a Block arg to construct the
MLIR Team6892ffb2018-12-20 04:42:55507// dependence graph at a different depth.
Chris Lattner69d9e992018-12-28 16:48:09508bool MemRefDependenceGraph::init(Function *f) {
Chris Lattner3f190312018-12-27 22:35:10509 DenseMap<Value *, SetVector<unsigned>> memrefAccesses;
Chris Lattnerdffc5892018-12-29 23:33:43510
511 // TODO: support multi-block functions.
512 if (f->getBlocks().size() != 1)
513 return false;
514
River Riddle5052bd82019-02-02 00:42:18515 DenseMap<Instruction *, unsigned> forToNodeMap;
Chris Lattnerdffc5892018-12-29 23:33:43516 for (auto &inst : f->front()) {
River Riddleb4992772019-02-04 18:38:47517 if (auto forOp = inst.dyn_cast<AffineForOp>()) {
River Riddle5052bd82019-02-02 00:42:18518 // Create graph node 'id' to represent top-level 'forOp' and record
MLIR Team6892ffb2018-12-20 04:42:55519 // all loads and store accesses it contains.
520 LoopNestStateCollector collector;
River Riddlebf9c3812019-02-05 00:24:44521 collector.collect(&inst);
Uday Bondhugula4ba8c912019-02-07 05:54:18522 // Return false if a non 'for' region was found (not currently supported).
River Riddle75553832019-01-29 05:23:53523 if (collector.hasNonForRegion)
MLIR Team6892ffb2018-12-20 04:42:55524 return false;
MLIR Teama0f3db402019-01-29 17:36:41525 Node node(nextNodeId++, &inst);
Chris Lattner456ad6a2018-12-29 00:05:35526 for (auto *opInst : collector.loadOpInsts) {
527 node.loads.push_back(opInst);
528 auto *memref = opInst->cast<LoadOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55529 memrefAccesses[memref].insert(node.id);
530 }
Chris Lattner456ad6a2018-12-29 00:05:35531 for (auto *opInst : collector.storeOpInsts) {
532 node.stores.push_back(opInst);
533 auto *memref = opInst->cast<StoreOp>()->getMemRef();
MLIR Team6892ffb2018-12-20 04:42:55534 memrefAccesses[memref].insert(node.id);
535 }
River Riddle5052bd82019-02-02 00:42:18536 forToNodeMap[&inst] = node.id;
MLIR Team6892ffb2018-12-20 04:42:55537 nodes.insert({node.id, node});
River Riddleb4992772019-02-04 18:38:47538 } else if (auto loadOp = inst.dyn_cast<LoadOp>()) {
539 // Create graph node for top-level load op.
540 Node node(nextNodeId++, &inst);
541 node.loads.push_back(&inst);
542 auto *memref = inst.cast<LoadOp>()->getMemRef();
543 memrefAccesses[memref].insert(node.id);
544 nodes.insert({node.id, node});
545 } else if (auto storeOp = inst.dyn_cast<StoreOp>()) {
546 // Create graph node for top-level store op.
547 Node node(nextNodeId++, &inst);
548 node.stores.push_back(&inst);
549 auto *memref = inst.cast<StoreOp>()->getMemRef();
550 memrefAccesses[memref].insert(node.id);
551 nodes.insert({node.id, node});
552 } else if (inst.getNumBlockLists() != 0) {
553 // Return false if another region is found (not currently supported).
554 return false;
555 } else if (inst.getNumResults() > 0 && !inst.use_empty()) {
556 // Create graph node for top-level producer of SSA values, which
557 // could be used by loop nest nodes.
558 Node node(nextNodeId++, &inst);
559 nodes.insert({node.id, node});
MLIR Teama0f3db402019-01-29 17:36:41560 }
561 }
562
563 // Add dependence edges between nodes which produce SSA values and their
564 // users.
565 for (auto &idAndNode : nodes) {
566 const Node &node = idAndNode.second;
567 if (!node.loads.empty() || !node.stores.empty())
568 continue;
River Riddleb4992772019-02-04 18:38:47569 auto *opInst = node.inst;
MLIR Teama0f3db402019-01-29 17:36:41570 for (auto *value : opInst->getResults()) {
571 for (auto &use : value->getUses()) {
River Riddle5052bd82019-02-02 00:42:18572 SmallVector<OpPointer<AffineForOp>, 4> loops;
River Riddleb4992772019-02-04 18:38:47573 getLoopIVs(*use.getOwner(), &loops);
MLIR Teama0f3db402019-01-29 17:36:41574 if (loops.empty())
575 continue;
River Riddle5052bd82019-02-02 00:42:18576 assert(forToNodeMap.count(loops[0]->getInstruction()) > 0);
577 unsigned userLoopNestId = forToNodeMap[loops[0]->getInstruction()];
MLIR Teama0f3db402019-01-29 17:36:41578 addEdge(node.id, userLoopNestId, value);
MLIR Team6892ffb2018-12-20 04:42:55579 }
580 }
MLIR Team6892ffb2018-12-20 04:42:55581 }
582
583 // Walk memref access lists and add graph edges between dependent nodes.
584 for (auto &memrefAndList : memrefAccesses) {
585 unsigned n = memrefAndList.second.size();
586 for (unsigned i = 0; i < n; ++i) {
587 unsigned srcId = memrefAndList.second[i];
588 bool srcHasStore =
589 getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
590 for (unsigned j = i + 1; j < n; ++j) {
591 unsigned dstId = memrefAndList.second[j];
592 bool dstHasStore =
593 getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
594 if (srcHasStore || dstHasStore)
595 addEdge(srcId, dstId, memrefAndList.first);
596 }
597 }
598 }
599 return true;
600}
601
MLIR Team38c2fe32019-01-14 19:26:25602namespace {
603
604// LoopNestStats aggregates various per-loop statistics (eg. loop trip count
605// and operation count) for a loop nest up until the innermost loop body.
606struct LoopNestStats {
River Riddle5052bd82019-02-02 00:42:18607 // Map from AffineForOp to immediate child AffineForOps in its loop body.
608 DenseMap<Instruction *, SmallVector<OpPointer<AffineForOp>, 2>> loopMap;
609 // Map from AffineForOp to count of operations in its loop body.
610 DenseMap<Instruction *, uint64_t> opCountMap;
611 // Map from AffineForOp to its constant trip count.
612 DenseMap<Instruction *, uint64_t> tripCountMap;
MLIR Team38c2fe32019-01-14 19:26:25613};
614
615// LoopNestStatsCollector walks a single loop nest and gathers per-loop
616// trip count and operation count statistics and records them in 'stats'.
River Riddlebf9c3812019-02-05 00:24:44617struct LoopNestStatsCollector {
MLIR Team38c2fe32019-01-14 19:26:25618 LoopNestStats *stats;
619 bool hasLoopWithNonConstTripCount = false;
620
621 LoopNestStatsCollector(LoopNestStats *stats) : stats(stats) {}
622
River Riddlebf9c3812019-02-05 00:24:44623 void collect(Instruction *inst) {
624 inst->walk<AffineForOp>([&](OpPointer<AffineForOp> forOp) {
625 auto *forInst = forOp->getInstruction();
626 auto *parentInst = forOp->getInstruction()->getParentInst();
627 if (parentInst != nullptr) {
628 assert(parentInst->isa<AffineForOp>() && "Expected parent AffineForOp");
629 // Add mapping to 'forOp' from its parent AffineForOp.
630 stats->loopMap[parentInst].push_back(forOp);
631 }
River Riddle5052bd82019-02-02 00:42:18632
River Riddlebf9c3812019-02-05 00:24:44633 // Record the number of op instructions in the body of 'forOp'.
634 unsigned count = 0;
635 stats->opCountMap[forInst] = 0;
636 for (auto &inst : *forOp->getBody()) {
637 if (!(inst.isa<AffineForOp>() || inst.isa<AffineIfOp>()))
638 ++count;
639 }
640 stats->opCountMap[forInst] = count;
641 // Record trip count for 'forOp'. Set flag if trip count is not
642 // constant.
643 Optional<uint64_t> maybeConstTripCount = getConstantTripCount(forOp);
644 if (!maybeConstTripCount.hasValue()) {
645 hasLoopWithNonConstTripCount = true;
646 return;
647 }
648 stats->tripCountMap[forInst] = maybeConstTripCount.getValue();
649 });
MLIR Team38c2fe32019-01-14 19:26:25650 }
651};
652
River Riddle5052bd82019-02-02 00:42:18653// Computes the total cost of the loop nest rooted at 'forOp'.
MLIR Team38c2fe32019-01-14 19:26:25654// Currently, the total cost is computed by counting the total operation
655// instance count (i.e. total number of operations in the loop bodyloop
656// operation count * loop trip count) for the entire loop nest.
657// If 'tripCountOverrideMap' is non-null, overrides the trip count for loops
658// specified in the map when computing the total op instance count.
659// NOTE: this is used to compute the cost of computation slices, which are
660// sliced along the iteration dimension, and thus reduce the trip count.
River Riddle5052bd82019-02-02 00:42:18661// If 'computeCostMap' is non-null, the total op count for forOps specified
MLIR Team38c2fe32019-01-14 19:26:25662// in the map is increased (not overridden) by adding the op count from the
663// map to the existing op count for the for loop. This is done before
664// multiplying by the loop's trip count, and is used to model the cost of
665// inserting a sliced loop nest of known cost into the loop's body.
666// NOTE: this is used to compute the cost of fusing a slice of some loop nest
667// within another loop.
Uday Bondhugula864d9e02019-01-23 17:16:24668static int64_t getComputeCost(
River Riddle5052bd82019-02-02 00:42:18669 Instruction *forInst, LoopNestStats *stats,
670 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountOverrideMap,
671 DenseMap<Instruction *, int64_t> *computeCostMap) {
672 // 'opCount' is the total number operations in one iteration of 'forOp' body
Uday Bondhugula864d9e02019-01-23 17:16:24673 int64_t opCount = stats->opCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25674 if (stats->loopMap.count(forInst) > 0) {
River Riddle5052bd82019-02-02 00:42:18675 for (auto childForOp : stats->loopMap[forInst]) {
676 opCount += getComputeCost(childForOp->getInstruction(), stats,
677 tripCountOverrideMap, computeCostMap);
MLIR Team38c2fe32019-01-14 19:26:25678 }
679 }
680 // Add in additional op instances from slice (if specified in map).
681 if (computeCostMap != nullptr) {
682 auto it = computeCostMap->find(forInst);
683 if (it != computeCostMap->end()) {
684 opCount += it->second;
685 }
686 }
687 // Override trip count (if specified in map).
Uday Bondhugula864d9e02019-01-23 17:16:24688 int64_t tripCount = stats->tripCountMap[forInst];
MLIR Team38c2fe32019-01-14 19:26:25689 if (tripCountOverrideMap != nullptr) {
690 auto it = tripCountOverrideMap->find(forInst);
691 if (it != tripCountOverrideMap->end()) {
692 tripCount = it->second;
693 }
694 }
695 // Returns the total number of dynamic instances of operations in loop body.
696 return tripCount * opCount;
697}
698
699} // end anonymous namespace
700
MLIR Team27d067e2019-01-16 17:55:02701static Optional<uint64_t> getConstDifference(AffineMap lbMap, AffineMap ubMap) {
Uday Bondhugulac1ca23e2019-01-16 21:13:00702 assert(lbMap.getNumResults() == 1 && "expected single result bound map");
703 assert(ubMap.getNumResults() == 1 && "expected single result bound map");
MLIR Team27d067e2019-01-16 17:55:02704 assert(lbMap.getNumDims() == ubMap.getNumDims());
705 assert(lbMap.getNumSymbols() == ubMap.getNumSymbols());
706 // TODO(andydavis) Merge this code with 'mlir::getTripCountExpr'.
707 // ub_expr - lb_expr
708 AffineExpr lbExpr(lbMap.getResult(0));
709 AffineExpr ubExpr(ubMap.getResult(0));
710 auto loopSpanExpr = simplifyAffineExpr(ubExpr - lbExpr, lbMap.getNumDims(),
711 lbMap.getNumSymbols());
712 auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();
713 if (!cExpr)
714 return None;
715 return cExpr.getValue();
716}
717
River Riddle5052bd82019-02-02 00:42:18718// Builds a map 'tripCountMap' from AffineForOp to constant trip count for loop
MLIR Team38c2fe32019-01-14 19:26:25719// nest surrounding 'srcAccess' utilizing slice loop bounds in 'sliceState'.
720// Returns true on success, false otherwise (if a non-constant trip count
721// was encountered).
722// TODO(andydavis) Make this work with non-unit step loops.
MLIR Team27d067e2019-01-16 17:55:02723static bool buildSliceTripCountMap(
River Riddleb4992772019-02-04 18:38:47724 Instruction *srcOpInst, ComputationSliceState *sliceState,
River Riddle5052bd82019-02-02 00:42:18725 llvm::SmallDenseMap<Instruction *, uint64_t, 8> *tripCountMap) {
726 SmallVector<OpPointer<AffineForOp>, 4> srcLoopIVs;
MLIR Team27d067e2019-01-16 17:55:02727 getLoopIVs(*srcOpInst, &srcLoopIVs);
MLIR Team38c2fe32019-01-14 19:26:25728 unsigned numSrcLoopIVs = srcLoopIVs.size();
River Riddle5052bd82019-02-02 00:42:18729 // Populate map from AffineForOp -> trip count
MLIR Team38c2fe32019-01-14 19:26:25730 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
731 AffineMap lbMap = sliceState->lbs[i];
732 AffineMap ubMap = sliceState->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17733 if (lbMap == AffineMap() || ubMap == AffineMap()) {
MLIR Team38c2fe32019-01-14 19:26:25734 // The iteration of src loop IV 'i' was not sliced. Use full loop bounds.
735 if (srcLoopIVs[i]->hasConstantLowerBound() &&
736 srcLoopIVs[i]->hasConstantUpperBound()) {
River Riddle5052bd82019-02-02 00:42:18737 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] =
MLIR Team38c2fe32019-01-14 19:26:25738 srcLoopIVs[i]->getConstantUpperBound() -
739 srcLoopIVs[i]->getConstantLowerBound();
740 continue;
741 }
742 return false;
743 }
MLIR Team27d067e2019-01-16 17:55:02744 Optional<uint64_t> tripCount = getConstDifference(lbMap, ubMap);
745 if (!tripCount.hasValue())
MLIR Team38c2fe32019-01-14 19:26:25746 return false;
River Riddle5052bd82019-02-02 00:42:18747 (*tripCountMap)[srcLoopIVs[i]->getInstruction()] = tripCount.getValue();
MLIR Team38c2fe32019-01-14 19:26:25748 }
749 return true;
750}
751
MLIR Team27d067e2019-01-16 17:55:02752// Removes load operations from 'srcLoads' which operate on 'memref', and
753// adds them to 'dstLoads'.
754static void
755moveLoadsAccessingMemrefTo(Value *memref,
River Riddleb4992772019-02-04 18:38:47756 SmallVectorImpl<Instruction *> *srcLoads,
757 SmallVectorImpl<Instruction *> *dstLoads) {
MLIR Team27d067e2019-01-16 17:55:02758 dstLoads->clear();
River Riddleb4992772019-02-04 18:38:47759 SmallVector<Instruction *, 4> srcLoadsToKeep;
MLIR Team27d067e2019-01-16 17:55:02760 for (auto *load : *srcLoads) {
761 if (load->cast<LoadOp>()->getMemRef() == memref)
762 dstLoads->push_back(load);
763 else
764 srcLoadsToKeep.push_back(load);
MLIR Team38c2fe32019-01-14 19:26:25765 }
MLIR Team27d067e2019-01-16 17:55:02766 srcLoads->swap(srcLoadsToKeep);
MLIR Team38c2fe32019-01-14 19:26:25767}
768
MLIR Team27d067e2019-01-16 17:55:02769// Returns the innermost common loop depth for the set of operations in 'ops'.
River Riddleb4992772019-02-04 18:38:47770static unsigned getInnermostCommonLoopDepth(ArrayRef<Instruction *> ops) {
MLIR Team27d067e2019-01-16 17:55:02771 unsigned numOps = ops.size();
772 assert(numOps > 0);
773
River Riddle5052bd82019-02-02 00:42:18774 std::vector<SmallVector<OpPointer<AffineForOp>, 4>> loops(numOps);
MLIR Team27d067e2019-01-16 17:55:02775 unsigned loopDepthLimit = std::numeric_limits<unsigned>::max();
776 for (unsigned i = 0; i < numOps; ++i) {
777 getLoopIVs(*ops[i], &loops[i]);
778 loopDepthLimit =
779 std::min(loopDepthLimit, static_cast<unsigned>(loops[i].size()));
MLIR Team38c2fe32019-01-14 19:26:25780 }
MLIR Team27d067e2019-01-16 17:55:02781
782 unsigned loopDepth = 0;
783 for (unsigned d = 0; d < loopDepthLimit; ++d) {
784 unsigned i;
785 for (i = 1; i < numOps; ++i) {
River Riddle5052bd82019-02-02 00:42:18786 if (loops[i - 1][d] != loops[i][d])
MLIR Team27d067e2019-01-16 17:55:02787 break;
MLIR Team27d067e2019-01-16 17:55:02788 }
789 if (i != numOps)
790 break;
791 ++loopDepth;
792 }
793 return loopDepth;
MLIR Team38c2fe32019-01-14 19:26:25794}
795
MLIR Teamd7c82442019-01-30 23:53:41796// Returns the maximum loop depth at which no dependences between 'loadOpInsts'
797// and 'storeOpInsts' are satisfied.
River Riddleb4992772019-02-04 18:38:47798static unsigned getMaxLoopDepth(ArrayRef<Instruction *> loadOpInsts,
799 ArrayRef<Instruction *> storeOpInsts) {
MLIR Teamd7c82442019-01-30 23:53:41800 // Merge loads and stores into the same array.
River Riddleb4992772019-02-04 18:38:47801 SmallVector<Instruction *, 2> ops(loadOpInsts.begin(), loadOpInsts.end());
MLIR Teamd7c82442019-01-30 23:53:41802 ops.append(storeOpInsts.begin(), storeOpInsts.end());
803
804 // Compute the innermost common loop depth for loads and stores.
805 unsigned loopDepth = getInnermostCommonLoopDepth(ops);
806
807 // Return common loop depth for loads if there are no store ops.
808 if (storeOpInsts.empty())
809 return loopDepth;
810
811 // Check dependences on all pairs of ops in 'ops' and store the minimum
812 // loop depth at which a dependence is satisfied.
813 for (unsigned i = 0, e = ops.size(); i < e; ++i) {
814 auto *srcOpInst = ops[i];
815 MemRefAccess srcAccess(srcOpInst);
816 for (unsigned j = 0; j < e; ++j) {
817 auto *dstOpInst = ops[j];
818 MemRefAccess dstAccess(dstOpInst);
819
820 unsigned numCommonLoops =
821 getNumCommonSurroundingLoops(*srcOpInst, *dstOpInst);
822 for (unsigned d = 1; d <= numCommonLoops + 1; ++d) {
823 FlatAffineConstraints dependenceConstraints;
824 // TODO(andydavis) Cache dependence analysis results, check cache here.
825 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
826 &dependenceConstraints,
827 /*dependenceComponents=*/nullptr)) {
828 // Store minimum loop depth and break because we want the min 'd' at
829 // which there is a dependence.
830 loopDepth = std::min(loopDepth, d - 1);
831 break;
832 }
833 }
834 }
835 }
836 return loopDepth;
837}
838
MLIR Team8f5f2c72019-02-15 17:32:18839// Compute loop interchange permutation:
840// *) Computes dependence components between all op pairs in 'ops' for loop
841// depths in range [1, 'maxLoopDepth'].
842// *) Classifies the outermost 'maxLoopDepth' loops surrounding 'ops' as either
843// parallel or sequential.
844// *) Computes the loop permutation which sinks sequential loops deeper into
845// the loop nest, while preserving the relative order between other loops.
846// *) Checks each dependence component against the permutation to see if the
847// desired loop interchange would violated dependences by making the a
848// dependence componenent lexicographically negative.
849// TODO(andydavis) Move this function to LoopUtils.
850static bool
851computeLoopInterchangePermutation(ArrayRef<Instruction *> ops,
852 unsigned maxLoopDepth,
853 SmallVectorImpl<unsigned> *loopPermMap) {
854 // Gather dependence components for dependences between all ops in 'ops'
855 // at loop depths in range [1, maxLoopDepth].
856 // TODO(andydavis) Refactor this loop into a LoopUtil utility function:
857 // mlir::getDependenceComponents().
858 // TODO(andydavis) Split this loop into two: first check all dependences,
859 // and construct dep vectors. Then, scan through them to detect the parallel
860 // ones.
861 std::vector<llvm::SmallVector<DependenceComponent, 2>> depCompsVec;
862 llvm::SmallVector<bool, 8> isParallelLoop(maxLoopDepth, true);
863 unsigned numOps = ops.size();
864 for (unsigned d = 1; d <= maxLoopDepth; ++d) {
865 for (unsigned i = 0; i < numOps; ++i) {
866 auto *srcOpInst = ops[i];
867 MemRefAccess srcAccess(srcOpInst);
868 for (unsigned j = 0; j < numOps; ++j) {
869 auto *dstOpInst = ops[j];
870 MemRefAccess dstAccess(dstOpInst);
871
872 FlatAffineConstraints dependenceConstraints;
873 llvm::SmallVector<DependenceComponent, 2> depComps;
874 // TODO(andydavis,bondhugula) Explore whether it would be profitable
875 // to pre-compute and store deps instead of repeatidly checking.
876 if (checkMemrefAccessDependence(srcAccess, dstAccess, d,
877 &dependenceConstraints, &depComps)) {
878 isParallelLoop[d - 1] = false;
879 depCompsVec.push_back(depComps);
880 }
881 }
882 }
883 }
884 // Count the number of parallel loops.
885 unsigned numParallelLoops = 0;
886 for (unsigned i = 0, e = isParallelLoop.size(); i < e; ++i)
887 if (isParallelLoop[i])
888 ++numParallelLoops;
889
890 // Compute permutation of loops that sinks sequential loops (and thus raises
891 // parallel loops) while preserving relative order.
892 llvm::SmallVector<unsigned, 4> loopPermMapInv;
893 loopPermMapInv.resize(maxLoopDepth);
894 loopPermMap->resize(maxLoopDepth);
895 unsigned nextSequentialLoop = numParallelLoops;
896 unsigned nextParallelLoop = 0;
897 for (unsigned i = 0; i < maxLoopDepth; ++i) {
898 if (isParallelLoop[i]) {
899 (*loopPermMap)[i] = nextParallelLoop;
900 loopPermMapInv[nextParallelLoop++] = i;
901 } else {
902 (*loopPermMap)[i] = nextSequentialLoop;
903 loopPermMapInv[nextSequentialLoop++] = i;
904 }
905 }
906
907 // Check each dependence component against the permutation to see if the
908 // desired loop interchange permutation would make the dependence vectors
909 // lexicographically negative.
910 // Example 1: [-1, 1][0, 0]
911 // Example 2: [0, 0][-1, 1]
912 for (unsigned i = 0, e = depCompsVec.size(); i < e; ++i) {
913 llvm::SmallVector<DependenceComponent, 2> &depComps = depCompsVec[i];
914 assert(depComps.size() >= maxLoopDepth);
915 // Check if the first non-zero dependence component is positive.
916 for (unsigned j = 0; j < maxLoopDepth; ++j) {
917 unsigned permIndex = loopPermMapInv[j];
918 assert(depComps[permIndex].lb.hasValue());
919 int64_t depCompLb = depComps[permIndex].lb.getValue();
920 if (depCompLb > 0)
921 break;
922 if (depCompLb < 0)
923 return false;
924 }
925 }
926 return true;
927}
928
929// Sinks all sequential loops to the innermost levels (while preserving
930// relative order among them) and moves all parallel loops to the
931// outermost (while again preserving relative order among them).
932// This can increase the loop depth at which we can fuse a slice, since we are
933// pushing loop carried dependence to a greater depth in the loop nest.
934static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
935 assert(node->inst->isa<AffineForOp>());
936 // Get perfectly nested sequence of loops starting at root of loop nest.
937 // TODO(andydavis,bondhugula) Share this with similar code in loop tiling.
938 SmallVector<OpPointer<AffineForOp>, 4> loops;
939 OpPointer<AffineForOp> curr = node->inst->cast<AffineForOp>();
940 loops.push_back(curr);
941 auto *currBody = curr->getBody();
942 while (!currBody->empty() &&
943 std::next(currBody->begin()) == currBody->end() &&
944 (curr = curr->getBody()->front().dyn_cast<AffineForOp>())) {
945 loops.push_back(curr);
946 currBody = curr->getBody();
947 }
948 if (loops.size() < 2)
949 return;
950
951 // Merge loads and stores into the same array.
952 SmallVector<Instruction *, 2> memOps(node->loads.begin(), node->loads.end());
953 memOps.append(node->stores.begin(), node->stores.end());
954
955 // Compute loop permutation in 'loopPermMap'.
956 llvm::SmallVector<unsigned, 4> loopPermMap;
957 if (!computeLoopInterchangePermutation(memOps, loops.size(), &loopPermMap))
958 return;
959
960 int loopNestRootIndex = -1;
961 for (int i = loops.size() - 1; i >= 0; --i) {
962 int permIndex = static_cast<int>(loopPermMap[i]);
963 // Store the index of the for loop which will be the new loop nest root.
964 if (permIndex == 0)
965 loopNestRootIndex = i;
966 if (permIndex > i) {
967 // Sink loop 'i' by 'permIndex - i' levels deeper into the loop nest.
968 sinkLoop(loops[i], permIndex - i);
969 }
970 }
971 assert(loopNestRootIndex != -1 && "invalid root index");
972 node->inst = loops[loopNestRootIndex]->getInstruction();
973}
974
Uday Bondhugulac1ca23e2019-01-16 21:13:00975// Returns the slice union of 'sliceStateA' and 'sliceStateB' in 'sliceStateB'
976// using a rectangular bounding box.
MLIR Team27d067e2019-01-16 17:55:02977// TODO(andydavis) This function assumes that lower bounds for 'sliceStateA'
978// and 'sliceStateB' are aligned.
979// Specifically, when taking the union of overlapping intervals, it assumes
980// that both intervals start at zero. Support needs to be added to take into
981// account interval start offset when computing the union.
982// TODO(andydavis) Move this function to an analysis library.
Uday Bondhugulac1ca23e2019-01-16 21:13:00983static bool getSliceUnion(const ComputationSliceState &sliceStateA,
984 ComputationSliceState *sliceStateB) {
MLIR Team27d067e2019-01-16 17:55:02985 assert(sliceStateA.lbs.size() == sliceStateB->lbs.size());
986 assert(sliceStateA.ubs.size() == sliceStateB->ubs.size());
987
988 for (unsigned i = 0, e = sliceStateA.lbs.size(); i < e; ++i) {
989 AffineMap lbMapA = sliceStateA.lbs[i];
990 AffineMap ubMapA = sliceStateA.ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17991 if (lbMapA == AffineMap()) {
992 assert(ubMapA == AffineMap());
MLIR Team27d067e2019-01-16 17:55:02993 continue;
994 }
Uday Bondhugulac1ca23e2019-01-16 21:13:00995 assert(ubMapA && "expected non-null ub map");
MLIR Team27d067e2019-01-16 17:55:02996
997 AffineMap lbMapB = sliceStateB->lbs[i];
998 AffineMap ubMapB = sliceStateB->ubs[i];
Nicolas Vasilache0e7a8a92019-01-26 18:41:17999 if (lbMapB == AffineMap()) {
1000 assert(ubMapB == AffineMap());
MLIR Team27d067e2019-01-16 17:55:021001 // Union 'sliceStateB' does not have a bound for 'i' so copy from A.
1002 sliceStateB->lbs[i] = lbMapA;
1003 sliceStateB->ubs[i] = ubMapA;
1004 continue;
1005 }
Uday Bondhugulac1ca23e2019-01-16 21:13:001006
1007 // TODO(andydavis) Change this code to take the min across all lower bounds
1008 // and max across all upper bounds for each dimension. This code can for
1009 // cases where a unique min or max could not be statically determined.
1010
1011 // Assumption: both lower bounds are the same.
1012 if (lbMapA != lbMapB)
MLIR Team27d067e2019-01-16 17:55:021013 return false;
1014
1015 // Add bound with the largest trip count to union.
1016 Optional<uint64_t> tripCountA = getConstDifference(lbMapA, ubMapA);
1017 Optional<uint64_t> tripCountB = getConstDifference(lbMapB, ubMapB);
1018 if (!tripCountA.hasValue() || !tripCountB.hasValue())
1019 return false;
Uday Bondhugulac1ca23e2019-01-16 21:13:001020
MLIR Team27d067e2019-01-16 17:55:021021 if (tripCountA.getValue() > tripCountB.getValue()) {
1022 sliceStateB->lbs[i] = lbMapA;
1023 sliceStateB->ubs[i] = ubMapA;
1024 }
1025 }
1026 return true;
1027}
1028
Uday Bondhugula8be26272019-02-02 01:06:221029// TODO(mlir-team): improve/complete this when we have target data.
1030unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
1031 auto elementType = memRefType.getElementType();
1032
1033 unsigned sizeInBits;
1034 if (elementType.isIntOrFloat()) {
1035 sizeInBits = elementType.getIntOrFloatBitWidth();
1036 } else {
1037 auto vectorType = elementType.cast<VectorType>();
1038 sizeInBits =
1039 vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
1040 }
1041 return llvm::divideCeil(sizeInBits, 8);
1042}
1043
MLIR Teamc4237ae2019-01-18 16:56:271044// Creates and returns a private (single-user) memref for fused loop rooted
River Riddle5052bd82019-02-02 00:42:181045// at 'forOp', with (potentially reduced) memref size based on the
Uday Bondhugula94a03f82019-01-22 21:58:521046// MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1047// TODO(bondhugula): consider refactoring the common code from generateDma and
1048// this one.
River Riddle5052bd82019-02-02 00:42:181049static Value *createPrivateMemRef(OpPointer<AffineForOp> forOp,
River Riddleb4992772019-02-04 18:38:471050 Instruction *srcStoreOpInst,
Uday Bondhugula8be26272019-02-02 01:06:221051 unsigned dstLoopDepth,
1052 Optional<unsigned> fastMemorySpace,
1053 unsigned localBufSizeThreshold) {
River Riddle5052bd82019-02-02 00:42:181054 auto *forInst = forOp->getInstruction();
1055
1056 // Create builder to insert alloc op just before 'forOp'.
MLIR Teamc4237ae2019-01-18 16:56:271057 FuncBuilder b(forInst);
1058 // Builder to create constants at the top level.
1059 FuncBuilder top(forInst->getFunction());
1060 // Create new memref type based on slice bounds.
1061 auto *oldMemRef = srcStoreOpInst->cast<StoreOp>()->getMemRef();
1062 auto oldMemRefType = oldMemRef->getType().cast<MemRefType>();
1063 unsigned rank = oldMemRefType.getRank();
1064
Uday Bondhugula94a03f82019-01-22 21:58:521065 // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
Uday Bondhugula0f504142019-02-04 21:48:441066 MemRefRegion region(srcStoreOpInst->getLoc());
1067 region.compute(srcStoreOpInst, dstLoopDepth);
River Riddle6859f332019-01-23 22:39:451068 SmallVector<int64_t, 4> newShape;
MLIR Teamc4237ae2019-01-18 16:56:271069 std::vector<SmallVector<int64_t, 4>> lbs;
Uday Bondhugula94a03f82019-01-22 21:58:521070 SmallVector<int64_t, 8> lbDivisors;
MLIR Teamc4237ae2019-01-18 16:56:271071 lbs.reserve(rank);
1072 // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
Uday Bondhugula94a03f82019-01-22 21:58:521073 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
MLIR Teamc4237ae2019-01-18 16:56:271074 Optional<int64_t> numElements =
Uday Bondhugula0f504142019-02-04 21:48:441075 region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
Uday Bondhugula8be26272019-02-02 01:06:221076 assert(numElements.hasValue() &&
1077 "non-constant number of elts in local buffer");
MLIR Teamc4237ae2019-01-18 16:56:271078
Uday Bondhugula0f504142019-02-04 21:48:441079 const FlatAffineConstraints *cst = region.getConstraints();
Uday Bondhugula94a03f82019-01-22 21:58:521080 // 'outerIVs' holds the values that this memory region is symbolic/paramteric
1081 // on; this would correspond to loop IVs surrounding the level at which the
1082 // slice is being materialized.
1083 SmallVector<Value *, 8> outerIVs;
1084 cst->getIdValues(rank, cst->getNumIds(), &outerIVs);
1085
1086 // Build 'rank' AffineExprs from MemRefRegion 'lbs'
MLIR Teamc4237ae2019-01-18 16:56:271087 SmallVector<AffineExpr, 4> offsets;
1088 offsets.reserve(rank);
1089 for (unsigned d = 0; d < rank; ++d) {
Uday Bondhugula94a03f82019-01-22 21:58:521090 assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
1091
MLIR Teamc4237ae2019-01-18 16:56:271092 AffineExpr offset = top.getAffineConstantExpr(0);
1093 for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
1094 offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
1095 }
Uday Bondhugula94a03f82019-01-22 21:58:521096 assert(lbDivisors[d] > 0);
1097 offset =
1098 (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
MLIR Teamc4237ae2019-01-18 16:56:271099 offsets.push_back(offset);
1100 }
1101
1102 // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
1103 // by 'srcStoreOpInst'.
Uday Bondhugula8be26272019-02-02 01:06:221104 uint64_t bufSize =
1105 getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
1106 unsigned newMemSpace;
1107 if (bufSize < localBufSizeThreshold && fastMemorySpace.hasValue()) {
1108 newMemSpace = fastMemorySpace.getValue();
1109 } else {
1110 newMemSpace = oldMemRefType.getMemorySpace();
1111 }
1112 auto newMemRefType = top.getMemRefType(
1113 newShape, oldMemRefType.getElementType(), {}, newMemSpace);
MLIR Teamc4237ae2019-01-18 16:56:271114 // Gather alloc operands for the dynamic dimensions of the memref.
1115 SmallVector<Value *, 4> allocOperands;
1116 unsigned dynamicDimCount = 0;
1117 for (auto dimSize : oldMemRefType.getShape()) {
1118 if (dimSize == -1)
1119 allocOperands.push_back(
River Riddle5052bd82019-02-02 00:42:181120 top.create<DimOp>(forOp->getLoc(), oldMemRef, dynamicDimCount++));
MLIR Teamc4237ae2019-01-18 16:56:271121 }
1122
River Riddle5052bd82019-02-02 00:42:181123 // Create new private memref for fused loop 'forOp'.
MLIR Teama0f3db402019-01-29 17:36:411124 // TODO(andydavis) Create/move alloc ops for private memrefs closer to their
1125 // consumer loop nests to reduce their live range. Currently they are added
1126 // at the beginning of the function, because loop nests can be reordered
1127 // during the fusion pass.
MLIR Teamc4237ae2019-01-18 16:56:271128 Value *newMemRef =
River Riddle5052bd82019-02-02 00:42:181129 top.create<AllocOp>(forOp->getLoc(), newMemRefType, allocOperands);
MLIR Teamc4237ae2019-01-18 16:56:271130
1131 // Build an AffineMap to remap access functions based on lower bound offsets.
1132 SmallVector<AffineExpr, 4> remapExprs;
1133 remapExprs.reserve(rank);
1134 unsigned zeroOffsetCount = 0;
1135 for (unsigned i = 0; i < rank; i++) {
1136 if (auto constExpr = offsets[i].dyn_cast<AffineConstantExpr>())
1137 if (constExpr.getValue() == 0)
1138 ++zeroOffsetCount;
Uday Bondhugula94a03f82019-01-22 21:58:521139 auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
1140
1141 auto remapExpr =
1142 simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
1143 remapExprs.push_back(remapExpr);
MLIR Teamc4237ae2019-01-18 16:56:271144 }
Uday Bondhugula94a03f82019-01-22 21:58:521145 auto indexRemap =
1146 zeroOffsetCount == rank
Nicolas Vasilache0e7a8a92019-01-26 18:41:171147 ? AffineMap()
Uday Bondhugula94a03f82019-01-22 21:58:521148 : b.getAffineMap(outerIVs.size() + rank, 0, remapExprs, {});
MLIR Teamc4237ae2019-01-18 16:56:271149 // Replace all users of 'oldMemRef' with 'newMemRef'.
Uday Bondhugula94a03f82019-01-22 21:58:521150 bool ret =
1151 replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
1152 /*extraOperands=*/outerIVs,
River Riddle5052bd82019-02-02 00:42:181153 /*domInstFilter=*/&*forOp->getBody()->begin());
Uday Bondhugula94a03f82019-01-22 21:58:521154 assert(ret && "replaceAllMemrefUsesWith should always succeed here");
MLIR Team71495d52019-01-22 21:23:371155 (void)ret;
MLIR Teamc4237ae2019-01-18 16:56:271156 return newMemRef;
1157}
1158
Uday Bondhugula864d9e02019-01-23 17:16:241159// Does the slice have a single iteration?
1160static uint64_t getSliceIterationCount(
River Riddle5052bd82019-02-02 00:42:181161 const llvm::SmallDenseMap<Instruction *, uint64_t, 8> &sliceTripCountMap) {
Uday Bondhugula864d9e02019-01-23 17:16:241162 uint64_t iterCount = 1;
1163 for (const auto &count : sliceTripCountMap) {
1164 iterCount *= count.second;
1165 }
1166 return iterCount;
1167}
1168
MLIR Team58aa3832019-02-16 01:12:191169// Checks if node 'srcId' (which writes to a live out memref), can be safely
1170// fused into node 'dstId'. Returns true if the following conditions are met:
1171// *) 'srcNode' writes only writes to live out 'memref'.
1172// *) 'srcNode' has exaclty one output edge on 'memref' (which is to 'dstId').
1173// *) 'dstNode' does write to 'memref'.
1174// *) 'dstNode's write region to 'memref' is a super set of 'srcNode's write
1175// region to 'memref'.
1176// TODO(andydavis) Generalize this to handle more live in/out cases.
1177static bool canFuseSrcWhichWritesToLiveOut(unsigned srcId, unsigned dstId,
1178 Value *memref,
1179 MemRefDependenceGraph *mdg) {
1180 auto *srcNode = mdg->getNode(srcId);
1181 auto *dstNode = mdg->getNode(dstId);
1182
1183 // Return false if any of the following are true:
1184 // *) 'srcNode' writes to a live in/out memref other than 'memref'.
1185 // *) 'srcNode' has more than one output edge on 'memref'.
1186 // *) 'dstNode' does not write to 'memref'.
1187 if (srcNode->getStoreOpCount(memref) != 1 ||
1188 mdg->getOutEdgeCount(srcNode->id, memref) != 1 ||
1189 dstNode->getStoreOpCount(memref) == 0)
1190 return false;
1191 // Compute MemRefRegion 'srcWriteRegion' for 'srcStoreOpInst' on 'memref'.
1192 auto *srcStoreOpInst = srcNode->stores.front();
1193 MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
1194 srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0);
1195 SmallVector<int64_t, 4> srcShape;
1196 // Query 'srcWriteRegion' for 'srcShape' and 'srcNumElements'.
1197 // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
1198 Optional<int64_t> srcNumElements =
1199 srcWriteRegion.getConstantBoundingSizeAndShape(&srcShape);
1200 if (!srcNumElements.hasValue())
1201 return false;
1202
1203 // Compute MemRefRegion 'dstWriteRegion' for 'dstStoreOpInst' on 'memref'.
1204 SmallVector<Instruction *, 2> dstStoreOps;
1205 dstNode->getStoreOpsForMemref(memref, &dstStoreOps);
1206 assert(dstStoreOps.size() == 1);
1207 auto *dstStoreOpInst = dstStoreOps[0];
1208 MemRefRegion dstWriteRegion(dstStoreOpInst->getLoc());
1209 dstWriteRegion.compute(dstStoreOpInst, /*loopDepth=*/0);
1210 SmallVector<int64_t, 4> dstShape;
1211 // Query 'dstWriteRegion' for 'dstShape' and 'dstNumElements'.
1212 // by 'dstStoreOpInst' at depth 'dstLoopDepth'.
1213 Optional<int64_t> dstNumElements =
1214 dstWriteRegion.getConstantBoundingSizeAndShape(&dstShape);
1215 if (!dstNumElements.hasValue())
1216 return false;
1217
1218 // Return false if write region is not a superset of 'srcNodes' write
1219 // region to 'memref'.
1220 // TODO(andydavis) Check the shape and lower bounds here too.
1221 if (srcNumElements != dstNumElements)
1222 return false;
1223 return true;
1224}
1225
MLIR Team27d067e2019-01-16 17:55:021226// Checks the profitability of fusing a backwards slice of the loop nest
MLIR Teamd7c82442019-01-30 23:53:411227// surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
Uday Bondhugulab4a14432019-01-26 00:00:501228// Returns true if it is profitable to fuse the candidate loop nests. Returns
1229// false otherwise. `dstLoopDepth` is set to the most profitable depth at which
1230// to materialize the source loop nest slice.
MLIR Team38c2fe32019-01-14 19:26:251231// The profitability model executes the following steps:
MLIR Team27d067e2019-01-16 17:55:021232// *) Computes the backward computation slice at 'srcOpInst'. This
1233// computation slice of the loop nest surrounding 'srcOpInst' is
MLIR Team38c2fe32019-01-14 19:26:251234// represented by modified src loop bounds in 'sliceState', which are
MLIR Team27d067e2019-01-16 17:55:021235// functions of loop IVs in the loop nest surrounding 'srcOpInst'.
MLIR Team38c2fe32019-01-14 19:26:251236// *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1237// loop nest is the total number of dynamic operation instances in the loop
1238// nest).
1239// *) Computes the cost of fusing a slice of the src loop nest into the dst
MLIR Team27d067e2019-01-16 17:55:021240// loop nest at various values of dst loop depth, attempting to fuse
1241// the largest compution slice at the maximal dst loop depth (closest to the
1242// load) to minimize reuse distance and potentially enable subsequent
1243// load/store forwarding.
MLIR Teamd7c82442019-01-30 23:53:411244// NOTE: If the dst loop nest includes multiple loads in 'dstLoadOpInsts' for
MLIR Team27d067e2019-01-16 17:55:021245// the same memref as is written by 'srcOpInst', then the union of slice
1246// loop bounds is used to compute the slice and associated slice cost.
Uday Bondhugulab4a14432019-01-26 00:00:501247// NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
MLIR Team38c2fe32019-01-14 19:26:251248// nest, at which the src computation slice is inserted/fused.
MLIR Team27d067e2019-01-16 17:55:021249// NOTE: We attempt to maximize the dst loop depth, but there are cases
1250// where a particular setting for 'dstLoopNest' might fuse an unsliced
MLIR Team38c2fe32019-01-14 19:26:251251// loop (within the src computation slice) at a depth which results in
1252// execessive recomputation (see unit tests for examples).
1253// *) Compares the total cost of the unfused loop nests to the min cost fused
1254// loop nest computed in the previous step, and returns true if the latter
1255// is lower.
River Riddleb4992772019-02-04 18:38:471256static bool isFusionProfitable(Instruction *srcOpInst,
1257 ArrayRef<Instruction *> dstLoadOpInsts,
1258 ArrayRef<Instruction *> dstStoreOpInsts,
MLIR Team38c2fe32019-01-14 19:26:251259 ComputationSliceState *sliceState,
MLIR Team27d067e2019-01-16 17:55:021260 unsigned *dstLoopDepth) {
Uday Bondhugula06d21d92019-01-25 01:01:491261 LLVM_DEBUG({
1262 llvm::dbgs() << "Checking whether fusion is profitable between:\n";
1263 llvm::dbgs() << " ";
1264 srcOpInst->dump();
1265 llvm::dbgs() << " and \n";
MLIR Teamd7c82442019-01-30 23:53:411266 for (auto dstOpInst : dstLoadOpInsts) {
Uday Bondhugula06d21d92019-01-25 01:01:491267 llvm::dbgs() << " ";
1268 dstOpInst->dump();
1269 };
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"
1422 << std::setprecision(2) << " additional compute fraction: "
1423 << 100.0 * additionalComputeFraction << "%\n"
1424 << " storage reduction factor: " << storageReduction << "x\n"
1425 << " fused nest cost: " << fusedLoopNestComputeCost << "\n"
1426 << " slice iteration count: " << sliceIterationCount << "\n";
1427 llvm::dbgs() << msg.str();
1428 });
Uday Bondhugula864d9e02019-01-23 17:16:241429
1430 double computeToleranceThreshold =
1431 clFusionAddlComputeTolerance.getNumOccurrences() > 0
1432 ? clFusionAddlComputeTolerance
1433 : LoopFusion::kComputeToleranceThreshold;
1434
1435 // TODO(b/123247369): This is a placeholder cost model.
1436 // Among all choices that add an acceptable amount of redundant computation
1437 // (as per computeToleranceThreshold), we will simply pick the one that
1438 // reduces the intermediary size the most.
1439 if ((storageReduction > maxStorageReduction) &&
1440 (clMaximalLoopFusion ||
1441 (additionalComputeFraction < computeToleranceThreshold))) {
1442 maxStorageReduction = storageReduction;
MLIR Team27d067e2019-01-16 17:55:021443 bestDstLoopDepth = i;
Uday Bondhugula864d9e02019-01-23 17:16:241444 minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
MLIR Teamb9dde912019-02-06 19:01:101445 sliceMemEstimate = sliceWriteRegionSizeBytes;
MLIR Team38c2fe32019-01-14 19:26:251446 }
1447 }
1448
Uday Bondhugula864d9e02019-01-23 17:16:241449 // A simple cost model: fuse if it reduces the memory footprint. If
1450 // -maximal-fusion is set, fuse nevertheless.
MLIR Team38c2fe32019-01-14 19:26:251451
Uday Bondhugula864d9e02019-01-23 17:16:241452 if (!clMaximalLoopFusion && !bestDstLoopDepth.hasValue()) {
1453 LLVM_DEBUG(llvm::dbgs()
1454 << "All fusion choices involve more than the threshold amount of"
1455 "redundant computation; NOT fusing.\n");
MLIR Team38c2fe32019-01-14 19:26:251456 return false;
Uday Bondhugula864d9e02019-01-23 17:16:241457 }
1458
1459 assert(bestDstLoopDepth.hasValue() &&
1460 "expected to have a value per logic above");
1461
1462 // Set dstLoopDepth based on best values from search.
1463 *dstLoopDepth = bestDstLoopDepth.getValue();
1464
1465 LLVM_DEBUG(
Uday Bondhugula06d21d92019-01-25 01:01:491466 llvm::dbgs() << " LoopFusion fusion stats:"
1467 << "\n best loop depth: " << bestDstLoopDepth
Uday Bondhugula864d9e02019-01-23 17:16:241468 << "\n src loop nest compute cost: " << srcLoopNestCost
1469 << "\n dst loop nest compute cost: " << dstLoopNestCost
1470 << "\n fused loop nest compute cost: "
1471 << minFusedLoopNestComputeCost << "\n");
1472
River Riddle5052bd82019-02-02 00:42:181473 auto dstMemSize = getMemoryFootprintBytes(dstLoopIVs[0]);
1474 auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
Uday Bondhugula864d9e02019-01-23 17:16:241475
1476 Optional<double> storageReduction = None;
1477
1478 if (!clMaximalLoopFusion) {
1479 if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1480 LLVM_DEBUG(
1481 llvm::dbgs()
1482 << " fusion memory benefit cannot be evaluated; NOT fusing.\n");
1483 return false;
1484 }
1485
1486 auto srcMemSizeVal = srcMemSize.getValue();
1487 auto dstMemSizeVal = dstMemSize.getValue();
1488
1489 assert(sliceMemEstimate.hasValue() && "expected value");
1490 // This is an inaccurate estimate since sliceMemEstimate is isaccurate.
1491 auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1492
1493 LLVM_DEBUG(llvm::dbgs() << " src mem: " << srcMemSizeVal << "\n"
1494 << " dst mem: " << dstMemSizeVal << "\n"
1495 << " fused mem: " << fusedMem << "\n"
1496 << " slice mem: " << sliceMemEstimate << "\n");
1497
1498 if (fusedMem > srcMemSizeVal + dstMemSizeVal) {
1499 LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1500 return false;
1501 }
1502 storageReduction =
1503 100.0 *
1504 (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1505 }
1506
1507 double additionalComputeFraction =
1508 100.0 * (minFusedLoopNestComputeCost /
1509 (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1510 1);
MLIR Team5c5739d2019-01-25 06:27:401511 (void)additionalComputeFraction;
Uday Bondhugula06d21d92019-01-25 01:01:491512 LLVM_DEBUG({
1513 std::stringstream msg;
1514 msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
1515 << setprecision(2) << additionalComputeFraction
1516 << "% redundant computation and a ";
1517 msg << (storageReduction.hasValue()
1518 ? std::to_string(storageReduction.getValue())
1519 : "<unknown>");
1520 msg << "% storage reduction.\n";
1521 llvm::dbgs() << msg.str();
1522 });
Uday Bondhugula864d9e02019-01-23 17:16:241523
MLIR Team27d067e2019-01-16 17:55:021524 // Update return parameter 'sliceState' with 'bestSliceState'.
Uday Bondhugula864d9e02019-01-23 17:16:241525 ComputationSliceState *bestSliceState = &sliceStates[*dstLoopDepth - 1];
MLIR Team27d067e2019-01-16 17:55:021526 sliceState->lbs = bestSliceState->lbs;
1527 sliceState->ubs = bestSliceState->ubs;
1528 sliceState->lbOperands = bestSliceState->lbOperands;
1529 sliceState->ubOperands = bestSliceState->ubOperands;
Uday Bondhugula864d9e02019-01-23 17:16:241530
MLIR Team27d067e2019-01-16 17:55:021531 // Canonicalize slice bound affine maps.
MLIR Team38c2fe32019-01-14 19:26:251532 for (unsigned i = 0; i < numSrcLoopIVs; ++i) {
Nicolas Vasilache0e7a8a92019-01-26 18:41:171533 if (sliceState->lbs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021534 canonicalizeMapAndOperands(&sliceState->lbs[i],
1535 &sliceState->lbOperands[i]);
1536 }
Nicolas Vasilache0e7a8a92019-01-26 18:41:171537 if (sliceState->ubs[i] != AffineMap()) {
MLIR Team27d067e2019-01-16 17:55:021538 canonicalizeMapAndOperands(&sliceState->ubs[i],
1539 &sliceState->ubOperands[i]);
MLIR Team38c2fe32019-01-14 19:26:251540 }
1541 }
1542 return true;
1543}
1544
MLIR Team6892ffb2018-12-20 04:42:551545// GreedyFusion greedily fuses loop nests which have a producer/consumer
MLIR Team3b692302018-12-17 17:57:141546// relationship on a memref, with the goal of improving locality. Currently,
1547// this the producer/consumer relationship is required to be unique in the
Chris Lattner69d9e992018-12-28 16:48:091548// Function (there are TODOs to relax this constraint in the future).
MLIR Teamf28e4df2018-11-01 14:26:001549//
MLIR Team3b692302018-12-17 17:57:141550// The steps of the algorithm are as follows:
1551//
MLIR Team6892ffb2018-12-20 04:42:551552// *) A worklist is initialized with node ids from the dependence graph.
1553// *) For each node id in the worklist:
River Riddle5052bd82019-02-02 00:42:181554// *) Pop a AffineForOp of the worklist. This 'dstAffineForOp' will be a
1555// candidate destination AffineForOp into which fusion will be attempted.
1556// *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
MLIR Team3b692302018-12-17 17:57:141557// *) For each LoadOp in 'dstLoadOps' do:
Chris Lattner69d9e992018-12-28 16:48:091558// *) Lookup dependent loop nests at earlier positions in the Function
MLIR Team3b692302018-12-17 17:57:141559// which have a single store op to the same memref.
1560// *) Check if dependences would be violated by the fusion. For example,
1561// the src loop nest may load from memrefs which are different than
1562// the producer-consumer memref between src and dest loop nests.
MLIR Team6892ffb2018-12-20 04:42:551563// *) Get a computation slice of 'srcLoopNest', which adjusts its loop
MLIR Team3b692302018-12-17 17:57:141564// bounds to be functions of 'dstLoopNest' IVs and symbols.
1565// *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
1566// just before the dst load op user.
Chris Lattner456ad6a2018-12-29 00:05:351567// *) Add the newly fused load/store operation instructions to the state,
MLIR Team3b692302018-12-17 17:57:141568// and also add newly fuse load ops to 'dstLoopOps' to be considered
1569// as fusion dst load ops in another iteration.
1570// *) Remove old src loop nest and its associated state.
1571//
Chris Lattner456ad6a2018-12-29 00:05:351572// Given a graph where top-level instructions are vertices in the set 'V' and
MLIR Team3b692302018-12-17 17:57:141573// edges in the set 'E' are dependences between vertices, this algorithm
MLIR Team6892ffb2018-12-20 04:42:551574// takes O(V) time for initialization, and has runtime O(V + E).
MLIR Team3b692302018-12-17 17:57:141575//
MLIR Team6892ffb2018-12-20 04:42:551576// This greedy algorithm is not 'maximal' due to the current restriction of
1577// fusing along single producer consumer edges, but there is a TODO to fix this.
MLIR Team3b692302018-12-17 17:57:141578//
1579// TODO(andydavis) Experiment with other fusion policies.
MLIR Team6892ffb2018-12-20 04:42:551580// TODO(andydavis) Add support for fusing for input reuse (perhaps by
1581// constructing a graph with edges which represent loads from the same memref
MLIR Team5c5739d2019-01-25 06:27:401582// in two different loop nests.
MLIR Team6892ffb2018-12-20 04:42:551583struct GreedyFusion {
1584public:
1585 MemRefDependenceGraph *mdg;
MLIR Teama78edcd2019-02-05 14:57:081586 SmallVector<unsigned, 8> worklist;
1587 llvm::SmallDenseSet<unsigned, 16> worklistSet;
MLIR Teamf28e4df2018-11-01 14:26:001588
MLIR Team6892ffb2018-12-20 04:42:551589 GreedyFusion(MemRefDependenceGraph *mdg) : mdg(mdg) {
1590 // Initialize worklist with nodes from 'mdg'.
MLIR Teama78edcd2019-02-05 14:57:081591 // TODO(andydavis) Add a priority queue for prioritizing nodes by different
1592 // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
MLIR Team6892ffb2018-12-20 04:42:551593 worklist.resize(mdg->nodes.size());
1594 std::iota(worklist.begin(), worklist.end(), 0);
MLIR Teama78edcd2019-02-05 14:57:081595 worklistSet.insert(worklist.begin(), worklist.end());
MLIR Team6892ffb2018-12-20 04:42:551596 }
MLIR Team3b692302018-12-17 17:57:141597
Uday Bondhugula8be26272019-02-02 01:06:221598 void run(unsigned localBufSizeThreshold, Optional<unsigned> fastMemorySpace) {
MLIR Team3b692302018-12-17 17:57:141599 while (!worklist.empty()) {
MLIR Team6892ffb2018-12-20 04:42:551600 unsigned dstId = worklist.back();
MLIR Team3b692302018-12-17 17:57:141601 worklist.pop_back();
MLIR Teama78edcd2019-02-05 14:57:081602 worklistSet.erase(dstId);
1603
MLIR Team6892ffb2018-12-20 04:42:551604 // Skip if this node was removed (fused into another node).
1605 if (mdg->nodes.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141606 continue;
MLIR Team6892ffb2018-12-20 04:42:551607 // Get 'dstNode' into which to attempt fusion.
1608 auto *dstNode = mdg->getNode(dstId);
1609 // Skip if 'dstNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471610 if (!dstNode->inst->isa<AffineForOp>())
MLIR Team3b692302018-12-17 17:57:141611 continue;
MLIR Team8f5f2c72019-02-15 17:32:181612 // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1613 // while preserving relative order. This can increase the maximum loop
1614 // depth at which we can fuse a slice of a producer loop nest into a
1615 // consumer loop nest.
1616 sinkSequentialLoops(dstNode);
MLIR Team3b692302018-12-17 17:57:141617
River Riddleb4992772019-02-04 18:38:471618 SmallVector<Instruction *, 4> loads = dstNode->loads;
1619 SmallVector<Instruction *, 4> dstLoadOpInsts;
MLIR Teamc4237ae2019-01-18 16:56:271620 DenseSet<Value *> visitedMemrefs;
MLIR Team6892ffb2018-12-20 04:42:551621 while (!loads.empty()) {
MLIR Team27d067e2019-01-16 17:55:021622 // Get memref of load on top of the stack.
1623 auto *memref = loads.back()->cast<LoadOp>()->getMemRef();
MLIR Teamc4237ae2019-01-18 16:56:271624 if (visitedMemrefs.count(memref) > 0)
1625 continue;
1626 visitedMemrefs.insert(memref);
MLIR Team27d067e2019-01-16 17:55:021627 // Move all loads in 'loads' accessing 'memref' to 'dstLoadOpInsts'.
1628 moveLoadsAccessingMemrefTo(memref, &loads, &dstLoadOpInsts);
MLIR Team6892ffb2018-12-20 04:42:551629 // Skip if no input edges along which to fuse.
1630 if (mdg->inEdges.count(dstId) == 0)
MLIR Team3b692302018-12-17 17:57:141631 continue;
MLIR Team1e851912019-01-31 00:01:461632 // Iterate through in edges for 'dstId' and src node id for any
1633 // edges on 'memref'.
1634 SmallVector<unsigned, 2> srcNodeIds;
MLIR Team6892ffb2018-12-20 04:42:551635 for (auto &srcEdge : mdg->inEdges[dstId]) {
1636 // Skip 'srcEdge' if not for 'memref'.
MLIR Teama0f3db402019-01-29 17:36:411637 if (srcEdge.value != memref)
MLIR Team6892ffb2018-12-20 04:42:551638 continue;
MLIR Team1e851912019-01-31 00:01:461639 srcNodeIds.push_back(srcEdge.id);
1640 }
1641 for (unsigned srcId : srcNodeIds) {
1642 // Skip if this node was removed (fused into another node).
1643 if (mdg->nodes.count(srcId) == 0)
1644 continue;
1645 // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1646 auto *srcNode = mdg->getNode(srcId);
MLIR Team6892ffb2018-12-20 04:42:551647 // Skip if 'srcNode' is not a loop nest.
River Riddleb4992772019-02-04 18:38:471648 if (!srcNode->inst->isa<AffineForOp>())
MLIR Team6892ffb2018-12-20 04:42:551649 continue;
MLIR Teamb28009b2019-01-23 19:11:431650 // Skip if 'srcNode' has more than one store to any memref.
1651 // TODO(andydavis) Support fusing multi-output src loop nests.
1652 if (srcNode->stores.size() != 1)
MLIR Team6892ffb2018-12-20 04:42:551653 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241654
MLIR Teama0f3db402019-01-29 17:36:411655 // Skip 'srcNode' if it has in edges on 'memref'.
MLIR Team6892ffb2018-12-20 04:42:551656 // TODO(andydavis) Track dependence type with edges, and just check
MLIR Teama0f3db402019-01-29 17:36:411657 // for WAW dependence edge here. Note that this check is overly
1658 // conservative and will be removed in the future.
1659 if (mdg->getIncomingMemRefAccesses(srcNode->id, memref) != 0)
MLIR Team6892ffb2018-12-20 04:42:551660 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241661
MLIR Team58aa3832019-02-16 01:12:191662 // Skip if 'srcNode' writes to any live in or escaping memrefs,
1663 // and cannot be fused.
1664 bool writesToLiveInOrOut =
1665 mdg->writesToLiveInOrEscapingMemrefs(srcNode->id);
1666 if (writesToLiveInOrOut &&
1667 !canFuseSrcWhichWritesToLiveOut(srcId, dstId, memref, mdg))
MLIR Teamd7c82442019-01-30 23:53:411668 continue;
1669
MLIR Teama0f3db402019-01-29 17:36:411670 // Compute an instruction list insertion point for the fused loop
1671 // nest which preserves dependences.
MLIR Teama78edcd2019-02-05 14:57:081672 Instruction *insertPointInst =
1673 mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
MLIR Teama0f3db402019-01-29 17:36:411674 if (insertPointInst == nullptr)
MLIR Team6892ffb2018-12-20 04:42:551675 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241676
MLIR Team6892ffb2018-12-20 04:42:551677 // Get unique 'srcNode' store op.
Chris Lattner456ad6a2018-12-29 00:05:351678 auto *srcStoreOpInst = srcNode->stores.front();
MLIR Teamd7c82442019-01-30 23:53:411679 // Gather 'dstNode' store ops to 'memref'.
River Riddleb4992772019-02-04 18:38:471680 SmallVector<Instruction *, 2> dstStoreOpInsts;
MLIR Teamd7c82442019-01-30 23:53:411681 for (auto *storeOpInst : dstNode->stores)
1682 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1683 dstStoreOpInsts.push_back(storeOpInst);
1684
Uday Bondhugulab4a14432019-01-26 00:00:501685 unsigned bestDstLoopDepth;
MLIR Team38c2fe32019-01-14 19:26:251686 mlir::ComputationSliceState sliceState;
MLIR Teama0f3db402019-01-29 17:36:411687 // Check if fusion would be profitable.
MLIR Teamd7c82442019-01-30 23:53:411688 if (!isFusionProfitable(srcStoreOpInst, dstLoadOpInsts,
1689 dstStoreOpInsts, &sliceState,
Uday Bondhugulab4a14432019-01-26 00:00:501690 &bestDstLoopDepth))
MLIR Team38c2fe32019-01-14 19:26:251691 continue;
Uday Bondhugula864d9e02019-01-23 17:16:241692
MLIR Team6892ffb2018-12-20 04:42:551693 // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
River Riddle5052bd82019-02-02 00:42:181694 auto sliceLoopNest = mlir::insertBackwardComputationSlice(
Uday Bondhugulab4a14432019-01-26 00:00:501695 srcStoreOpInst, dstLoadOpInsts[0], bestDstLoopDepth, &sliceState);
MLIR Team6892ffb2018-12-20 04:42:551696 if (sliceLoopNest != nullptr) {
River Riddle5052bd82019-02-02 00:42:181697 // Move 'dstAffineForOp' before 'insertPointInst' if needed.
River Riddleb4992772019-02-04 18:38:471698 auto dstAffineForOp = dstNode->inst->cast<AffineForOp>();
River Riddle5052bd82019-02-02 00:42:181699 if (insertPointInst != dstAffineForOp->getInstruction()) {
1700 dstAffineForOp->getInstruction()->moveBefore(insertPointInst);
MLIR Teama0f3db402019-01-29 17:36:411701 }
MLIR Teamc4237ae2019-01-18 16:56:271702 // Update edges between 'srcNode' and 'dstNode'.
MLIR Teama0f3db402019-01-29 17:36:411703 mdg->updateEdges(srcNode->id, dstNode->id, memref);
MLIR Teamc4237ae2019-01-18 16:56:271704
1705 // Collect slice loop stats.
1706 LoopNestStateCollector sliceCollector;
River Riddlebf9c3812019-02-05 00:24:441707 sliceCollector.collect(sliceLoopNest->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271708 // Promote single iteration slice loops to single IV value.
River Riddle5052bd82019-02-02 00:42:181709 for (auto forOp : sliceCollector.forOps) {
1710 promoteIfSingleIteration(forOp);
MLIR Team6892ffb2018-12-20 04:42:551711 }
MLIR Team58aa3832019-02-16 01:12:191712 if (!writesToLiveInOrOut) {
1713 // Create private memref for 'memref' in 'dstAffineForOp'.
1714 SmallVector<Instruction *, 4> storesForMemref;
1715 for (auto *storeOpInst : sliceCollector.storeOpInsts) {
1716 if (storeOpInst->cast<StoreOp>()->getMemRef() == memref)
1717 storesForMemref.push_back(storeOpInst);
1718 }
1719 assert(storesForMemref.size() == 1);
1720 auto *newMemRef = createPrivateMemRef(
1721 dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1722 fastMemorySpace, localBufSizeThreshold);
1723 visitedMemrefs.insert(newMemRef);
1724 // Create new node in dependence graph for 'newMemRef' alloc op.
1725 unsigned newMemRefNodeId =
1726 mdg->addNode(newMemRef->getDefiningInst());
1727 // Add edge from 'newMemRef' node to dstNode.
1728 mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
MLIR Teamc4237ae2019-01-18 16:56:271729 }
MLIR Teamc4237ae2019-01-18 16:56:271730
1731 // Collect dst loop stats after memref privatizaton transformation.
1732 LoopNestStateCollector dstLoopCollector;
River Riddlebf9c3812019-02-05 00:24:441733 dstLoopCollector.collect(dstAffineForOp->getInstruction());
MLIR Teamc4237ae2019-01-18 16:56:271734
1735 // Add new load ops to current Node load op list 'loads' to
1736 // continue fusing based on new operands.
1737 for (auto *loadOpInst : dstLoopCollector.loadOpInsts) {
1738 auto *loadMemRef = loadOpInst->cast<LoadOp>()->getMemRef();
1739 if (visitedMemrefs.count(loadMemRef) == 0)
1740 loads.push_back(loadOpInst);
1741 }
1742
1743 // Clear and add back loads and stores
1744 mdg->clearNodeLoadAndStores(dstNode->id);
1745 mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1746 dstLoopCollector.storeOpInsts);
MLIR Team71495d52019-01-22 21:23:371747 // Remove old src loop nest if it no longer has outgoing dependence
1748 // edges, and it does not write to a memref which escapes the
MLIR Team58aa3832019-02-16 01:12:191749 // function. If 'writesToLiveInOrOut' is true, then 'srcNode' has
1750 // been fused into 'dstNode' and write region of 'dstNode' covers
1751 // the write region of 'srcNode', and 'srcNode' has no other users
1752 // so it is safe to remove.
1753 if (writesToLiveInOrOut || mdg->canRemoveNode(srcNode->id)) {
MLIR Teamc4237ae2019-01-18 16:56:271754 mdg->removeNode(srcNode->id);
River Riddle5052bd82019-02-02 00:42:181755 srcNode->inst->erase();
MLIR Teama78edcd2019-02-05 14:57:081756 } else {
1757 // Add remaining users of 'oldMemRef' back on the worklist (if not
1758 // already there), as its replacement with a local/private memref
1759 // has reduced dependences on 'oldMemRef' which may have created
1760 // new fusion opportunities.
1761 if (mdg->outEdges.count(srcNode->id) > 0) {
1762 SmallVector<MemRefDependenceGraph::Edge, 2> oldOutEdges =
1763 mdg->outEdges[srcNode->id];
1764 for (auto &outEdge : oldOutEdges) {
1765 if (outEdge.value == memref &&
1766 worklistSet.count(outEdge.id) == 0) {
1767 worklist.push_back(outEdge.id);
1768 worklistSet.insert(outEdge.id);
1769 }
1770 }
1771 }
MLIR Teamc4237ae2019-01-18 16:56:271772 }
MLIR Team3b692302018-12-17 17:57:141773 }
MLIR Team3b692302018-12-17 17:57:141774 }
1775 }
1776 }
MLIR Teamc4237ae2019-01-18 16:56:271777 // Clean up any allocs with no users.
1778 for (auto &pair : mdg->memrefEdgeCount) {
1779 if (pair.second > 0)
1780 continue;
1781 auto *memref = pair.first;
MLIR Team71495d52019-01-22 21:23:371782 // Skip if there exist other uses (return instruction or function calls).
1783 if (!memref->use_empty())
1784 continue;
MLIR Teamc4237ae2019-01-18 16:56:271785 // Use list expected to match the dep graph info.
MLIR Teamc4237ae2019-01-18 16:56:271786 auto *inst = memref->getDefiningInst();
River Riddleb4992772019-02-04 18:38:471787 if (inst && inst->isa<AllocOp>())
1788 inst->erase();
MLIR Teamc4237ae2019-01-18 16:56:271789 }
MLIR Teamf28e4df2018-11-01 14:26:001790 }
MLIR Team3b692302018-12-17 17:57:141791};
1792
1793} // end anonymous namespace
MLIR Teamf28e4df2018-11-01 14:26:001794
Chris Lattner79748892018-12-31 07:10:351795PassResult LoopFusion::runOnFunction(Function *f) {
Uday Bondhugula8be26272019-02-02 01:06:221796 if (clFusionFastMemorySpace.getNumOccurrences() > 0) {
1797 fastMemorySpace = clFusionFastMemorySpace.getValue();
1798 }
1799
MLIR Team6892ffb2018-12-20 04:42:551800 MemRefDependenceGraph g;
1801 if (g.init(f))
Uday Bondhugula8be26272019-02-02 01:06:221802 GreedyFusion(&g).run(localBufSizeThreshold, fastMemorySpace);
MLIR Teamf28e4df2018-11-01 14:26:001803 return success();
1804}
Jacques Pienaar6f0fb222018-11-07 02:34:181805
1806static PassRegistration<LoopFusion> pass("loop-fusion", "Fuse loop nests");