1 //===- LoopFusion.cpp - Code to perform loop fusion -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements loop fusion.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Affine/Analysis/AffineAnalysis.h"
15 #include "mlir/Dialect/Affine/Analysis/AffineStructures.h"
16 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h"
17 #include "mlir/Dialect/Affine/Analysis/Utils.h"
18 #include "mlir/Dialect/Affine/IR/AffineOps.h"
19 #include "mlir/Dialect/Affine/LoopFusionUtils.h"
20 #include "mlir/Dialect/Affine/LoopUtils.h"
21 #include "mlir/Dialect/Affine/Utils.h"
22 #include "mlir/Dialect/MemRef/IR/MemRef.h"
23 #include "mlir/IR/AffineExpr.h"
24 #include "mlir/IR/AffineMap.h"
25 #include "mlir/IR/Builders.h"
26 #include "mlir/Transforms/Passes.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <iomanip>
34 #include <sstream>
35 #define DEBUG_TYPE "affine-loop-fusion"
36 
37 using namespace mlir;
38 
39 namespace {
40 /// Loop fusion pass. This pass currently supports a greedy fusion policy,
41 /// which fuses loop nests with single-writer/single-reader memref dependences
42 /// with the goal of improving locality.
43 
44 // TODO: Support fusion of source loop nests which write to multiple
45 // memrefs, where each memref can have multiple users (if profitable).
46 // TODO: Extend this pass to check for fusion preventing dependences,
47 // and add support for more general loop fusion algorithms.
48 
49 struct LoopFusion : public AffineLoopFusionBase<LoopFusion> {
50   LoopFusion() = default;
51   LoopFusion(unsigned fastMemorySpace, uint64_t localBufSizeThresholdBytes,
52              bool maximalFusion, enum FusionMode affineFusionMode) {
53     this->fastMemorySpace = fastMemorySpace;
54     this->localBufSizeThreshold = localBufSizeThresholdBytes / 1024;
55     this->maximalFusion = maximalFusion;
56     this->affineFusionMode = affineFusionMode;
57   }
58 
59   void runOnOperation() override;
60 };
61 
62 } // namespace
63 
64 std::unique_ptr<OperationPass<func::FuncOp>>
65 mlir::createLoopFusionPass(unsigned fastMemorySpace,
66                            uint64_t localBufSizeThreshold, bool maximalFusion,
67                            enum FusionMode affineFusionMode) {
68   return std::make_unique<LoopFusion>(fastMemorySpace, localBufSizeThreshold,
69                                       maximalFusion, affineFusionMode);
70 }
71 
72 namespace {
73 
74 // LoopNestStateCollector walks loop nests and collects load and store
75 // operations, and whether or not a region holding op other than ForOp and IfOp
76 // was encountered in the loop nest.
77 struct LoopNestStateCollector {
78   SmallVector<AffineForOp, 4> forOps;
79   SmallVector<Operation *, 4> loadOpInsts;
80   SmallVector<Operation *, 4> storeOpInsts;
81   bool hasNonAffineRegionOp = false;
82 
83   void collect(Operation *opToWalk) {
84     opToWalk->walk([&](Operation *op) {
85       if (isa<AffineForOp>(op))
86         forOps.push_back(cast<AffineForOp>(op));
87       else if (op->getNumRegions() != 0 && !isa<AffineIfOp>(op))
88         hasNonAffineRegionOp = true;
89       else if (isa<AffineReadOpInterface>(op))
90         loadOpInsts.push_back(op);
91       else if (isa<AffineWriteOpInterface>(op))
92         storeOpInsts.push_back(op);
93     });
94   }
95 };
96 
97 // MemRefDependenceGraph is a graph data structure where graph nodes are
98 // top-level operations in a FuncOp which contain load/store ops, and edges
99 // are memref dependences between the nodes.
100 // TODO: Add a more flexible dependence graph representation.
101 // TODO: Add a depth parameter to dependence graph construction.
102 struct MemRefDependenceGraph {
103 public:
104   // Node represents a node in the graph. A Node is either an entire loop nest
105   // rooted at the top level which contains loads/stores, or a top level
106   // load/store.
107   struct Node {
108     // The unique identifier of this node in the graph.
109     unsigned id;
110     // The top-level statement which is (or contains) a load/store.
111     Operation *op;
112     // List of load operations.
113     SmallVector<Operation *, 4> loads;
114     // List of store op insts.
115     SmallVector<Operation *, 4> stores;
116     Node(unsigned id, Operation *op) : id(id), op(op) {}
117 
118     // Returns the load op count for 'memref'.
119     unsigned getLoadOpCount(Value memref) {
120       unsigned loadOpCount = 0;
121       for (auto *loadOpInst : loads) {
122         if (memref == cast<AffineReadOpInterface>(loadOpInst).getMemRef())
123           ++loadOpCount;
124       }
125       return loadOpCount;
126     }
127 
128     // Returns the store op count for 'memref'.
129     unsigned getStoreOpCount(Value memref) {
130       unsigned storeOpCount = 0;
131       for (auto *storeOpInst : stores) {
132         if (memref == cast<AffineWriteOpInterface>(storeOpInst).getMemRef())
133           ++storeOpCount;
134       }
135       return storeOpCount;
136     }
137 
138     // Returns all store ops in 'storeOps' which access 'memref'.
139     void getStoreOpsForMemref(Value memref,
140                               SmallVectorImpl<Operation *> *storeOps) {
141       for (auto *storeOpInst : stores) {
142         if (memref == cast<AffineWriteOpInterface>(storeOpInst).getMemRef())
143           storeOps->push_back(storeOpInst);
144       }
145     }
146 
147     // Returns all load ops in 'loadOps' which access 'memref'.
148     void getLoadOpsForMemref(Value memref,
149                              SmallVectorImpl<Operation *> *loadOps) {
150       for (auto *loadOpInst : loads) {
151         if (memref == cast<AffineReadOpInterface>(loadOpInst).getMemRef())
152           loadOps->push_back(loadOpInst);
153       }
154     }
155 
156     // Returns all memrefs in 'loadAndStoreMemrefSet' for which this node
157     // has at least one load and store operation.
158     void getLoadAndStoreMemrefSet(DenseSet<Value> *loadAndStoreMemrefSet) {
159       llvm::SmallDenseSet<Value, 2> loadMemrefs;
160       for (auto *loadOpInst : loads) {
161         loadMemrefs.insert(cast<AffineReadOpInterface>(loadOpInst).getMemRef());
162       }
163       for (auto *storeOpInst : stores) {
164         auto memref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
165         if (loadMemrefs.count(memref) > 0)
166           loadAndStoreMemrefSet->insert(memref);
167       }
168     }
169   };
170 
171   // Edge represents a data dependence between nodes in the graph.
172   struct Edge {
173     // The id of the node at the other end of the edge.
174     // If this edge is stored in Edge = Node.inEdges[i], then
175     // 'Node.inEdges[i].id' is the identifier of the source node of the edge.
176     // If this edge is stored in Edge = Node.outEdges[i], then
177     // 'Node.outEdges[i].id' is the identifier of the dest node of the edge.
178     unsigned id;
179     // The SSA value on which this edge represents a dependence.
180     // If the value is a memref, then the dependence is between graph nodes
181     // which contain accesses to the same memref 'value'. If the value is a
182     // non-memref value, then the dependence is between a graph node which
183     // defines an SSA value and another graph node which uses the SSA value
184     // (e.g. a constant or load operation defining a value which is used inside
185     // a loop nest).
186     Value value;
187   };
188 
189   // Map from node id to Node.
190   DenseMap<unsigned, Node> nodes;
191   // Map from node id to list of input edges.
192   DenseMap<unsigned, SmallVector<Edge, 2>> inEdges;
193   // Map from node id to list of output edges.
194   DenseMap<unsigned, SmallVector<Edge, 2>> outEdges;
195   // Map from memref to a count on the dependence edges associated with that
196   // memref.
197   DenseMap<Value, unsigned> memrefEdgeCount;
198   // The next unique identifier to use for newly created graph nodes.
199   unsigned nextNodeId = 0;
200 
201   MemRefDependenceGraph() = default;
202 
203   // Initializes the dependence graph based on operations in 'f'.
204   // Returns true on success, false otherwise.
205   bool init(func::FuncOp f);
206 
207   // Returns the graph node for 'id'.
208   Node *getNode(unsigned id) {
209     auto it = nodes.find(id);
210     assert(it != nodes.end());
211     return &it->second;
212   }
213 
214   // Returns the graph node for 'forOp'.
215   Node *getForOpNode(AffineForOp forOp) {
216     for (auto &idAndNode : nodes)
217       if (idAndNode.second.op == forOp.getOperation())
218         return &idAndNode.second;
219     return nullptr;
220   }
221 
222   // Adds a node with 'op' to the graph and returns its unique identifier.
223   unsigned addNode(Operation *op) {
224     Node node(nextNodeId++, op);
225     nodes.insert({node.id, node});
226     return node.id;
227   }
228 
229   // Remove node 'id' (and its associated edges) from graph.
230   void removeNode(unsigned id) {
231     // Remove each edge in 'inEdges[id]'.
232     if (inEdges.count(id) > 0) {
233       SmallVector<Edge, 2> oldInEdges = inEdges[id];
234       for (auto &inEdge : oldInEdges) {
235         removeEdge(inEdge.id, id, inEdge.value);
236       }
237     }
238     // Remove each edge in 'outEdges[id]'.
239     if (outEdges.count(id) > 0) {
240       SmallVector<Edge, 2> oldOutEdges = outEdges[id];
241       for (auto &outEdge : oldOutEdges) {
242         removeEdge(id, outEdge.id, outEdge.value);
243       }
244     }
245     // Erase remaining node state.
246     inEdges.erase(id);
247     outEdges.erase(id);
248     nodes.erase(id);
249   }
250 
251   // Returns true if node 'id' writes to any memref which escapes (or is an
252   // argument to) the function/block. Returns false otherwise.
253   bool writesToLiveInOrEscapingMemrefs(unsigned id) {
254     Node *node = getNode(id);
255     for (auto *storeOpInst : node->stores) {
256       auto memref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
257       auto *op = memref.getDefiningOp();
258       // Return true if 'memref' is a block argument.
259       if (!op)
260         return true;
261       // Return true if any use of 'memref' escapes the function.
262       for (auto *user : memref.getUsers())
263         if (!isa<AffineMapAccessInterface>(*user))
264           return true;
265     }
266     return false;
267   }
268 
269   // Returns true iff there is an edge from node 'srcId' to node 'dstId' which
270   // is for 'value' if non-null, or for any value otherwise. Returns false
271   // otherwise.
272   bool hasEdge(unsigned srcId, unsigned dstId, Value value = nullptr) {
273     if (outEdges.count(srcId) == 0 || inEdges.count(dstId) == 0) {
274       return false;
275     }
276     bool hasOutEdge = llvm::any_of(outEdges[srcId], [=](Edge &edge) {
277       return edge.id == dstId && (!value || edge.value == value);
278     });
279     bool hasInEdge = llvm::any_of(inEdges[dstId], [=](Edge &edge) {
280       return edge.id == srcId && (!value || edge.value == value);
281     });
282     return hasOutEdge && hasInEdge;
283   }
284 
285   // Adds an edge from node 'srcId' to node 'dstId' for 'value'.
286   void addEdge(unsigned srcId, unsigned dstId, Value value) {
287     if (!hasEdge(srcId, dstId, value)) {
288       outEdges[srcId].push_back({dstId, value});
289       inEdges[dstId].push_back({srcId, value});
290       if (value.getType().isa<MemRefType>())
291         memrefEdgeCount[value]++;
292     }
293   }
294 
295   // Removes an edge from node 'srcId' to node 'dstId' for 'value'.
296   void removeEdge(unsigned srcId, unsigned dstId, Value value) {
297     assert(inEdges.count(dstId) > 0);
298     assert(outEdges.count(srcId) > 0);
299     if (value.getType().isa<MemRefType>()) {
300       assert(memrefEdgeCount.count(value) > 0);
301       memrefEdgeCount[value]--;
302     }
303     // Remove 'srcId' from 'inEdges[dstId]'.
304     for (auto *it = inEdges[dstId].begin(); it != inEdges[dstId].end(); ++it) {
305       if ((*it).id == srcId && (*it).value == value) {
306         inEdges[dstId].erase(it);
307         break;
308       }
309     }
310     // Remove 'dstId' from 'outEdges[srcId]'.
311     for (auto *it = outEdges[srcId].begin(); it != outEdges[srcId].end();
312          ++it) {
313       if ((*it).id == dstId && (*it).value == value) {
314         outEdges[srcId].erase(it);
315         break;
316       }
317     }
318   }
319 
320   // Returns true if there is a path in the dependence graph from node 'srcId'
321   // to node 'dstId'. Returns false otherwise.
322   bool hasDependencePath(unsigned srcId, unsigned dstId) {
323     // Worklist state is: <node-id, next-output-edge-index-to-visit>
324     SmallVector<std::pair<unsigned, unsigned>, 4> worklist;
325     worklist.push_back({srcId, 0});
326     // Run DFS traversal to see if 'dstId' is reachable from 'srcId'.
327     while (!worklist.empty()) {
328       auto &idAndIndex = worklist.back();
329       // Return true if we have reached 'dstId'.
330       if (idAndIndex.first == dstId)
331         return true;
332       // Pop and continue if node has no out edges, or if all out edges have
333       // already been visited.
334       if (outEdges.count(idAndIndex.first) == 0 ||
335           idAndIndex.second == outEdges[idAndIndex.first].size()) {
336         worklist.pop_back();
337         continue;
338       }
339       // Get graph edge to traverse.
340       Edge edge = outEdges[idAndIndex.first][idAndIndex.second];
341       // Increment next output edge index for 'idAndIndex'.
342       ++idAndIndex.second;
343       // Add node at 'edge.id' to worklist.
344       worklist.push_back({edge.id, 0});
345     }
346     return false;
347   }
348 
349   // Returns the input edge count for node 'id' and 'memref' from src nodes
350   // which access 'memref' with a store operation.
351   unsigned getIncomingMemRefAccesses(unsigned id, Value memref) {
352     unsigned inEdgeCount = 0;
353     if (inEdges.count(id) > 0)
354       for (auto &inEdge : inEdges[id])
355         if (inEdge.value == memref) {
356           Node *srcNode = getNode(inEdge.id);
357           // Only count in edges from 'srcNode' if 'srcNode' accesses 'memref'
358           if (srcNode->getStoreOpCount(memref) > 0)
359             ++inEdgeCount;
360         }
361     return inEdgeCount;
362   }
363 
364   // Returns the output edge count for node 'id' and 'memref' (if non-null),
365   // otherwise returns the total output edge count from node 'id'.
366   unsigned getOutEdgeCount(unsigned id, Value memref = nullptr) {
367     unsigned outEdgeCount = 0;
368     if (outEdges.count(id) > 0)
369       for (auto &outEdge : outEdges[id])
370         if (!memref || outEdge.value == memref)
371           ++outEdgeCount;
372     return outEdgeCount;
373   }
374 
375   /// Return all nodes which define SSA values used in node 'id'.
376   void gatherDefiningNodes(unsigned id, DenseSet<unsigned> &definingNodes) {
377     for (MemRefDependenceGraph::Edge edge : inEdges[id])
378       // By definition of edge, if the edge value is a non-memref value,
379       // then the dependence is between a graph node which defines an SSA value
380       // and another graph node which uses the SSA value.
381       if (!edge.value.getType().isa<MemRefType>())
382         definingNodes.insert(edge.id);
383   }
384 
385   // Computes and returns an insertion point operation, before which the
386   // the fused <srcId, dstId> loop nest can be inserted while preserving
387   // dependences. Returns nullptr if no such insertion point is found.
388   Operation *getFusedLoopNestInsertionPoint(unsigned srcId, unsigned dstId) {
389     if (outEdges.count(srcId) == 0)
390       return getNode(dstId)->op;
391 
392     // Skip if there is any defining node of 'dstId' that depends on 'srcId'.
393     DenseSet<unsigned> definingNodes;
394     gatherDefiningNodes(dstId, definingNodes);
395     if (llvm::any_of(definingNodes, [&](unsigned id) {
396           return hasDependencePath(srcId, id);
397         })) {
398       LLVM_DEBUG(llvm::dbgs()
399                  << "Can't fuse: a defining op with a user in the dst "
400                     "loop has dependence from the src loop\n");
401       return nullptr;
402     }
403 
404     // Build set of insts in range (srcId, dstId) which depend on 'srcId'.
405     SmallPtrSet<Operation *, 2> srcDepInsts;
406     for (auto &outEdge : outEdges[srcId])
407       if (outEdge.id != dstId)
408         srcDepInsts.insert(getNode(outEdge.id)->op);
409 
410     // Build set of insts in range (srcId, dstId) on which 'dstId' depends.
411     SmallPtrSet<Operation *, 2> dstDepInsts;
412     for (auto &inEdge : inEdges[dstId])
413       if (inEdge.id != srcId)
414         dstDepInsts.insert(getNode(inEdge.id)->op);
415 
416     Operation *srcNodeInst = getNode(srcId)->op;
417     Operation *dstNodeInst = getNode(dstId)->op;
418 
419     // Computing insertion point:
420     // *) Walk all operation positions in Block operation list in the
421     //    range (src, dst). For each operation 'op' visited in this search:
422     //   *) Store in 'firstSrcDepPos' the first position where 'op' has a
423     //      dependence edge from 'srcNode'.
424     //   *) Store in 'lastDstDepPost' the last position where 'op' has a
425     //      dependence edge to 'dstNode'.
426     // *) Compare 'firstSrcDepPos' and 'lastDstDepPost' to determine the
427     //    operation insertion point (or return null pointer if no such
428     //    insertion point exists: 'firstSrcDepPos' <= 'lastDstDepPos').
429     SmallVector<Operation *, 2> depInsts;
430     Optional<unsigned> firstSrcDepPos;
431     Optional<unsigned> lastDstDepPos;
432     unsigned pos = 0;
433     for (Block::iterator it = std::next(Block::iterator(srcNodeInst));
434          it != Block::iterator(dstNodeInst); ++it) {
435       Operation *op = &(*it);
436       if (srcDepInsts.count(op) > 0 && firstSrcDepPos == None)
437         firstSrcDepPos = pos;
438       if (dstDepInsts.count(op) > 0)
439         lastDstDepPos = pos;
440       depInsts.push_back(op);
441       ++pos;
442     }
443 
444     if (firstSrcDepPos.hasValue()) {
445       if (lastDstDepPos.hasValue()) {
446         if (firstSrcDepPos.getValue() <= lastDstDepPos.getValue()) {
447           // No valid insertion point exists which preserves dependences.
448           return nullptr;
449         }
450       }
451       // Return the insertion point at 'firstSrcDepPos'.
452       return depInsts[firstSrcDepPos.getValue()];
453     }
454     // No dependence targets in range (or only dst deps in range), return
455     // 'dstNodInst' insertion point.
456     return dstNodeInst;
457   }
458 
459   // Updates edge mappings from node 'srcId' to node 'dstId' after fusing them,
460   // taking into account that:
461   //   *) if 'removeSrcId' is true, 'srcId' will be removed after fusion,
462   //   *) memrefs in 'privateMemRefs' has been replaced in node at 'dstId' by a
463   //      private memref.
464   void updateEdges(unsigned srcId, unsigned dstId,
465                    const DenseSet<Value> &privateMemRefs, bool removeSrcId) {
466     // For each edge in 'inEdges[srcId]': add new edge remapping to 'dstId'.
467     if (inEdges.count(srcId) > 0) {
468       SmallVector<Edge, 2> oldInEdges = inEdges[srcId];
469       for (auto &inEdge : oldInEdges) {
470         // Add edge from 'inEdge.id' to 'dstId' if it's not a private memref.
471         if (privateMemRefs.count(inEdge.value) == 0)
472           addEdge(inEdge.id, dstId, inEdge.value);
473       }
474     }
475     // For each edge in 'outEdges[srcId]': remove edge from 'srcId' to 'dstId'.
476     // If 'srcId' is going to be removed, remap all the out edges to 'dstId'.
477     if (outEdges.count(srcId) > 0) {
478       SmallVector<Edge, 2> oldOutEdges = outEdges[srcId];
479       for (auto &outEdge : oldOutEdges) {
480         // Remove any out edges from 'srcId' to 'dstId' across memrefs.
481         if (outEdge.id == dstId)
482           removeEdge(srcId, outEdge.id, outEdge.value);
483         else if (removeSrcId) {
484           addEdge(dstId, outEdge.id, outEdge.value);
485           removeEdge(srcId, outEdge.id, outEdge.value);
486         }
487       }
488     }
489     // Remove any edges in 'inEdges[dstId]' on 'oldMemRef' (which is being
490     // replaced by a private memref). These edges could come from nodes
491     // other than 'srcId' which were removed in the previous step.
492     if (inEdges.count(dstId) > 0 && !privateMemRefs.empty()) {
493       SmallVector<Edge, 2> oldInEdges = inEdges[dstId];
494       for (auto &inEdge : oldInEdges)
495         if (privateMemRefs.count(inEdge.value) > 0)
496           removeEdge(inEdge.id, dstId, inEdge.value);
497     }
498   }
499 
500   // Update edge mappings for nodes 'sibId' and 'dstId' to reflect fusion
501   // of sibling node 'sibId' into node 'dstId'.
502   void updateEdges(unsigned sibId, unsigned dstId) {
503     // For each edge in 'inEdges[sibId]':
504     // *) Add new edge from source node 'inEdge.id' to 'dstNode'.
505     // *) Remove edge from source node 'inEdge.id' to 'sibNode'.
506     if (inEdges.count(sibId) > 0) {
507       SmallVector<Edge, 2> oldInEdges = inEdges[sibId];
508       for (auto &inEdge : oldInEdges) {
509         addEdge(inEdge.id, dstId, inEdge.value);
510         removeEdge(inEdge.id, sibId, inEdge.value);
511       }
512     }
513 
514     // For each edge in 'outEdges[sibId]' to node 'id'
515     // *) Add new edge from 'dstId' to 'outEdge.id'.
516     // *) Remove edge from 'sibId' to 'outEdge.id'.
517     if (outEdges.count(sibId) > 0) {
518       SmallVector<Edge, 2> oldOutEdges = outEdges[sibId];
519       for (auto &outEdge : oldOutEdges) {
520         addEdge(dstId, outEdge.id, outEdge.value);
521         removeEdge(sibId, outEdge.id, outEdge.value);
522       }
523     }
524   }
525 
526   // Adds ops in 'loads' and 'stores' to node at 'id'.
527   void addToNode(unsigned id, const SmallVectorImpl<Operation *> &loads,
528                  const SmallVectorImpl<Operation *> &stores) {
529     Node *node = getNode(id);
530     llvm::append_range(node->loads, loads);
531     llvm::append_range(node->stores, stores);
532   }
533 
534   void clearNodeLoadAndStores(unsigned id) {
535     Node *node = getNode(id);
536     node->loads.clear();
537     node->stores.clear();
538   }
539 
540   // Calls 'callback' for each input edge incident to node 'id' which carries a
541   // memref dependence.
542   void forEachMemRefInputEdge(unsigned id,
543                               const std::function<void(Edge)> &callback) {
544     if (inEdges.count(id) > 0)
545       forEachMemRefEdge(inEdges[id], callback);
546   }
547 
548   // Calls 'callback' for each output edge from node 'id' which carries a
549   // memref dependence.
550   void forEachMemRefOutputEdge(unsigned id,
551                                const std::function<void(Edge)> &callback) {
552     if (outEdges.count(id) > 0)
553       forEachMemRefEdge(outEdges[id], callback);
554   }
555 
556   // Calls 'callback' for each edge in 'edges' which carries a memref
557   // dependence.
558   void forEachMemRefEdge(ArrayRef<Edge> edges,
559                          const std::function<void(Edge)> &callback) {
560     for (const auto &edge : edges) {
561       // Skip if 'edge' is not a memref dependence edge.
562       if (!edge.value.getType().isa<MemRefType>())
563         continue;
564       assert(nodes.count(edge.id) > 0);
565       // Skip if 'edge.id' is not a loop nest.
566       if (!isa<AffineForOp>(getNode(edge.id)->op))
567         continue;
568       // Visit current input edge 'edge'.
569       callback(edge);
570     }
571   }
572 
573   void print(raw_ostream &os) const {
574     os << "\nMemRefDependenceGraph\n";
575     os << "\nNodes:\n";
576     for (const auto &idAndNode : nodes) {
577       os << "Node: " << idAndNode.first << "\n";
578       auto it = inEdges.find(idAndNode.first);
579       if (it != inEdges.end()) {
580         for (const auto &e : it->second)
581           os << "  InEdge: " << e.id << " " << e.value << "\n";
582       }
583       it = outEdges.find(idAndNode.first);
584       if (it != outEdges.end()) {
585         for (const auto &e : it->second)
586           os << "  OutEdge: " << e.id << " " << e.value << "\n";
587       }
588     }
589   }
590   void dump() const { print(llvm::errs()); }
591 };
592 
593 /// Returns true if node 'srcId' can be removed after fusing it with node
594 /// 'dstId'. The node can be removed if any of the following conditions are met:
595 ///   1. 'srcId' has no output dependences after fusion and no escaping memrefs.
596 ///   2. 'srcId' has no output dependences after fusion, has escaping memrefs
597 ///       and the fusion slice is maximal.
598 ///   3. 'srcId' has output dependences after fusion, the fusion slice is
599 ///      maximal and the fusion insertion point dominates all the dependences.
600 static bool canRemoveSrcNodeAfterFusion(
601     unsigned srcId, unsigned dstId, const ComputationSliceState &fusionSlice,
602     Operation *fusedLoopInsPoint, const DenseSet<Value> &escapingMemRefs,
603     MemRefDependenceGraph *mdg) {
604 
605   Operation *dstNodeOp = mdg->getNode(dstId)->op;
606   bool hasOutDepsAfterFusion = false;
607 
608   for (auto &outEdge : mdg->outEdges[srcId]) {
609     Operation *depNodeOp = mdg->getNode(outEdge.id)->op;
610     // Skip dependence with dstOp since it will be removed after fusion.
611     if (depNodeOp == dstNodeOp)
612       continue;
613 
614     // Only fusion within the same block is supported. Use domination analysis
615     // when needed.
616     if (depNodeOp->getBlock() != dstNodeOp->getBlock())
617       return false;
618 
619     // Check if the insertion point of the fused loop dominates the dependence.
620     // Otherwise, the src loop can't be removed.
621     if (fusedLoopInsPoint != depNodeOp &&
622         !fusedLoopInsPoint->isBeforeInBlock(depNodeOp)) {
623       LLVM_DEBUG(llvm::dbgs() << "Src loop can't be removed: dst loop doesn't "
624                                  "dominate dependence\n");
625       return false;
626     }
627 
628     hasOutDepsAfterFusion = true;
629   }
630 
631   // If src loop has dependences after fusion or it writes to an live-out or
632   // escaping memref, we can only remove it if the fusion slice is maximal so
633   // that all the dependences are preserved.
634   if (hasOutDepsAfterFusion || !escapingMemRefs.empty()) {
635     Optional<bool> isMaximal = fusionSlice.isMaximal();
636     if (!isMaximal.hasValue()) {
637       LLVM_DEBUG(llvm::dbgs() << "Src loop can't be removed: can't determine "
638                                  "if fusion is maximal\n");
639       return false;
640     }
641 
642     if (!isMaximal.getValue()) {
643       LLVM_DEBUG(llvm::dbgs()
644                  << "Src loop can't be removed: fusion is not maximal\n");
645       return false;
646     }
647   }
648 
649   return true;
650 }
651 
652 /// Returns in 'srcIdCandidates' the producer fusion candidates for consumer
653 /// 'dstId'. Candidates are sorted by node id order. This order corresponds to
654 /// the program order when the 'mdg' is created. However, program order is not
655 /// guaranteed and must not be required by the client. Program order won't be
656 /// held if the 'mdg' is reused from a previous fusion step or if the node
657 /// creation order changes in the future to support more advance cases.
658 // TODO: Move this to a loop fusion utility once 'mdg' is also moved.
659 static void getProducerCandidates(unsigned dstId, MemRefDependenceGraph *mdg,
660                                   SmallVectorImpl<unsigned> &srcIdCandidates) {
661   // Skip if no input edges along which to fuse.
662   if (mdg->inEdges.count(dstId) == 0)
663     return;
664 
665   // Gather memrefs from loads in 'dstId'.
666   auto *dstNode = mdg->getNode(dstId);
667   DenseSet<Value> consumedMemrefs;
668   for (Operation *load : dstNode->loads)
669     consumedMemrefs.insert(cast<AffineReadOpInterface>(load).getMemRef());
670 
671   // Traverse 'dstId' incoming edges and gather the nodes that contain a store
672   // to one of the consumed memrefs.
673   for (auto &srcEdge : mdg->inEdges[dstId]) {
674     auto *srcNode = mdg->getNode(srcEdge.id);
675     // Skip if 'srcNode' is not a loop nest.
676     if (!isa<AffineForOp>(srcNode->op))
677       continue;
678 
679     if (any_of(srcNode->stores, [&](Operation *op) {
680           auto storeOp = cast<AffineWriteOpInterface>(op);
681           return consumedMemrefs.count(storeOp.getMemRef()) > 0;
682         }))
683       srcIdCandidates.push_back(srcNode->id);
684   }
685 
686   std::sort(srcIdCandidates.begin(), srcIdCandidates.end());
687   srcIdCandidates.erase(
688       std::unique(srcIdCandidates.begin(), srcIdCandidates.end()),
689       srcIdCandidates.end());
690 }
691 
692 /// Returns in 'producerConsumerMemrefs' the memrefs involved in a
693 /// producer-consumer dependence between 'srcId' and 'dstId'.
694 static void
695 gatherProducerConsumerMemrefs(unsigned srcId, unsigned dstId,
696                               MemRefDependenceGraph *mdg,
697                               DenseSet<Value> &producerConsumerMemrefs) {
698   auto *dstNode = mdg->getNode(dstId);
699   auto *srcNode = mdg->getNode(srcId);
700   gatherProducerConsumerMemrefs(srcNode->stores, dstNode->loads,
701                                 producerConsumerMemrefs);
702 }
703 
704 /// Returns in 'escapingMemRefs' the memrefs from affine store ops in node 'id'
705 /// that escape the function. A memref escapes the function if either:
706 ///   1. It's a function argument, or
707 ///   2. It's used by a non-affine op (e.g., std load/store, std call, etc.)
708 void gatherEscapingMemrefs(unsigned id, MemRefDependenceGraph *mdg,
709                            DenseSet<Value> &escapingMemRefs) {
710   auto *node = mdg->getNode(id);
711   for (auto *storeOpInst : node->stores) {
712     auto memref = cast<AffineWriteOpInterface>(storeOpInst).getMemRef();
713     if (escapingMemRefs.count(memref))
714       continue;
715     // Check if 'memref' escapes because it's a block argument.
716     if (memref.isa<BlockArgument>()) {
717       escapingMemRefs.insert(memref);
718       continue;
719     }
720     // Check if 'memref' escapes through a non-affine op (e.g., std load/store,
721     // call op, etc.).
722     for (Operation *user : memref.getUsers())
723       if (!isa<AffineMapAccessInterface>(*user))
724         escapingMemRefs.insert(memref);
725   }
726 }
727 
728 } // namespace
729 
730 // Initializes the data dependence graph by walking operations in 'f'.
731 // Assigns each node in the graph a node id based on program order in 'f'.
732 // TODO: Add support for taking a Block arg to construct the
733 // dependence graph at a different depth.
734 bool MemRefDependenceGraph::init(func::FuncOp f) {
735   LLVM_DEBUG(llvm::dbgs() << "--- Initializing MDG ---\n");
736   DenseMap<Value, SetVector<unsigned>> memrefAccesses;
737 
738   // TODO: support multi-block functions.
739   if (!llvm::hasSingleElement(f))
740     return false;
741 
742   DenseMap<Operation *, unsigned> forToNodeMap;
743   for (auto &op : f.front()) {
744     if (auto forOp = dyn_cast<AffineForOp>(op)) {
745       // Create graph node 'id' to represent top-level 'forOp' and record
746       // all loads and store accesses it contains.
747       LoopNestStateCollector collector;
748       collector.collect(&op);
749       // Return false if a region holding op other than 'affine.for' and
750       // 'affine.if' was found (not currently supported).
751       if (collector.hasNonAffineRegionOp)
752         return false;
753       Node node(nextNodeId++, &op);
754       for (auto *opInst : collector.loadOpInsts) {
755         node.loads.push_back(opInst);
756         auto memref = cast<AffineReadOpInterface>(opInst).getMemRef();
757         memrefAccesses[memref].insert(node.id);
758       }
759       for (auto *opInst : collector.storeOpInsts) {
760         node.stores.push_back(opInst);
761         auto memref = cast<AffineWriteOpInterface>(opInst).getMemRef();
762         memrefAccesses[memref].insert(node.id);
763       }
764       forToNodeMap[&op] = node.id;
765       nodes.insert({node.id, node});
766     } else if (auto loadOp = dyn_cast<AffineReadOpInterface>(op)) {
767       // Create graph node for top-level load op.
768       Node node(nextNodeId++, &op);
769       node.loads.push_back(&op);
770       auto memref = cast<AffineReadOpInterface>(op).getMemRef();
771       memrefAccesses[memref].insert(node.id);
772       nodes.insert({node.id, node});
773     } else if (auto storeOp = dyn_cast<AffineWriteOpInterface>(op)) {
774       // Create graph node for top-level store op.
775       Node node(nextNodeId++, &op);
776       node.stores.push_back(&op);
777       auto memref = cast<AffineWriteOpInterface>(op).getMemRef();
778       memrefAccesses[memref].insert(node.id);
779       nodes.insert({node.id, node});
780     } else if (op.getNumRegions() != 0) {
781       // Return false if another region is found (not currently supported).
782       return false;
783     } else if (op.getNumResults() > 0 && !op.use_empty()) {
784       // Create graph node for top-level producer of SSA values, which
785       // could be used by loop nest nodes.
786       Node node(nextNodeId++, &op);
787       nodes.insert({node.id, node});
788     } else if (isa<CallOpInterface>(op)) {
789       // Create graph node for top-level Call Op that takes any argument of
790       // memref type. Call Op that returns one or more memref type results
791       // is already taken care of, by the previous conditions.
792       if (llvm::any_of(op.getOperandTypes(),
793                        [&](Type t) { return t.isa<MemRefType>(); })) {
794         Node node(nextNodeId++, &op);
795         nodes.insert({node.id, node});
796       }
797     } else if (auto effectInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
798       // Create graph node for top-level op, which could have a memory write
799       // side effect.
800       SmallVector<MemoryEffects::EffectInstance, 1> effects;
801       effectInterface.getEffects(effects);
802       if (llvm::any_of(effects, [](const MemoryEffects::EffectInstance &it) {
803             return isa<MemoryEffects::Write, MemoryEffects::Free>(
804                 it.getEffect());
805           })) {
806         Node node(nextNodeId++, &op);
807         nodes.insert({node.id, node});
808       }
809     }
810   }
811 
812   for (auto &idAndNode : nodes) {
813     LLVM_DEBUG(llvm::dbgs() << "Create node " << idAndNode.first << " for:\n"
814                             << *(idAndNode.second.op) << "\n");
815     (void)idAndNode;
816   }
817 
818   // Add dependence edges between nodes which produce SSA values and their
819   // users. Load ops can be considered as the ones producing SSA values.
820   for (auto &idAndNode : nodes) {
821     const Node &node = idAndNode.second;
822     // Stores don't define SSA values, skip them.
823     if (!node.stores.empty())
824       continue;
825     auto *opInst = node.op;
826     for (auto value : opInst->getResults()) {
827       for (auto *user : value.getUsers()) {
828         SmallVector<AffineForOp, 4> loops;
829         getLoopIVs(*user, &loops);
830         if (loops.empty())
831           continue;
832         assert(forToNodeMap.count(loops[0].getOperation()) > 0);
833         unsigned userLoopNestId = forToNodeMap[loops[0].getOperation()];
834         addEdge(node.id, userLoopNestId, value);
835       }
836     }
837   }
838 
839   // Walk memref access lists and add graph edges between dependent nodes.
840   for (auto &memrefAndList : memrefAccesses) {
841     unsigned n = memrefAndList.second.size();
842     for (unsigned i = 0; i < n; ++i) {
843       unsigned srcId = memrefAndList.second[i];
844       bool srcHasStore =
845           getNode(srcId)->getStoreOpCount(memrefAndList.first) > 0;
846       for (unsigned j = i + 1; j < n; ++j) {
847         unsigned dstId = memrefAndList.second[j];
848         bool dstHasStore =
849             getNode(dstId)->getStoreOpCount(memrefAndList.first) > 0;
850         if (srcHasStore || dstHasStore)
851           addEdge(srcId, dstId, memrefAndList.first);
852       }
853     }
854   }
855   return true;
856 }
857 
858 // Sinks all sequential loops to the innermost levels (while preserving
859 // relative order among them) and moves all parallel loops to the
860 // outermost (while again preserving relative order among them).
861 // This can increase the loop depth at which we can fuse a slice, since we are
862 // pushing loop carried dependence to a greater depth in the loop nest.
863 static void sinkSequentialLoops(MemRefDependenceGraph::Node *node) {
864   assert(isa<AffineForOp>(node->op));
865   AffineForOp newRootForOp = sinkSequentialLoops(cast<AffineForOp>(node->op));
866   node->op = newRootForOp.getOperation();
867 }
868 
869 //  TODO: improve/complete this when we have target data.
870 static unsigned getMemRefEltSizeInBytes(MemRefType memRefType) {
871   auto elementType = memRefType.getElementType();
872 
873   unsigned sizeInBits;
874   if (elementType.isIntOrFloat()) {
875     sizeInBits = elementType.getIntOrFloatBitWidth();
876   } else {
877     auto vectorType = elementType.cast<VectorType>();
878     sizeInBits =
879         vectorType.getElementTypeBitWidth() * vectorType.getNumElements();
880   }
881   return llvm::divideCeil(sizeInBits, 8);
882 }
883 
884 // Creates and returns a private (single-user) memref for fused loop rooted
885 // at 'forOp', with (potentially reduced) memref size based on the
886 // MemRefRegion written to by 'srcStoreOpInst' at depth 'dstLoopDepth'.
887 // TODO: consider refactoring the common code from generateDma and
888 // this one.
889 static Value createPrivateMemRef(AffineForOp forOp, Operation *srcStoreOpInst,
890                                  unsigned dstLoopDepth,
891                                  Optional<unsigned> fastMemorySpace,
892                                  uint64_t localBufSizeThreshold) {
893   auto *forInst = forOp.getOperation();
894 
895   // Create builder to insert alloc op just before 'forOp'.
896   OpBuilder b(forInst);
897   // Builder to create constants at the top level.
898   OpBuilder top(forInst->getParentOfType<func::FuncOp>().getBody());
899   // Create new memref type based on slice bounds.
900   auto oldMemRef = cast<AffineWriteOpInterface>(srcStoreOpInst).getMemRef();
901   auto oldMemRefType = oldMemRef.getType().cast<MemRefType>();
902   unsigned rank = oldMemRefType.getRank();
903 
904   // Compute MemRefRegion for 'srcStoreOpInst' at depth 'dstLoopDepth'.
905   MemRefRegion region(srcStoreOpInst->getLoc());
906   bool validRegion = succeeded(region.compute(srcStoreOpInst, dstLoopDepth));
907   (void)validRegion;
908   assert(validRegion && "unexpected memref region failure");
909   SmallVector<int64_t, 4> newShape;
910   std::vector<SmallVector<int64_t, 4>> lbs;
911   SmallVector<int64_t, 8> lbDivisors;
912   lbs.reserve(rank);
913   // Query 'region' for 'newShape' and lower bounds of MemRefRegion accessed
914   // by 'srcStoreOpInst' at depth 'dstLoopDepth'.
915   Optional<int64_t> numElements =
916       region.getConstantBoundingSizeAndShape(&newShape, &lbs, &lbDivisors);
917   assert(numElements.hasValue() &&
918          "non-constant number of elts in local buffer");
919 
920   const FlatAffineValueConstraints *cst = region.getConstraints();
921   // 'outerIVs' holds the values that this memory region is symbolic/parametric
922   // on; this would correspond to loop IVs surrounding the level at which the
923   // slice is being materialized.
924   SmallVector<Value, 8> outerIVs;
925   cst->getValues(rank, cst->getNumIds(), &outerIVs);
926 
927   // Build 'rank' AffineExprs from MemRefRegion 'lbs'
928   SmallVector<AffineExpr, 4> offsets;
929   offsets.reserve(rank);
930   for (unsigned d = 0; d < rank; ++d) {
931     assert(lbs[d].size() == cst->getNumCols() - rank && "incorrect bound size");
932 
933     AffineExpr offset = top.getAffineConstantExpr(0);
934     for (unsigned j = 0, e = cst->getNumCols() - rank - 1; j < e; j++) {
935       offset = offset + lbs[d][j] * top.getAffineDimExpr(j);
936     }
937     assert(lbDivisors[d] > 0);
938     offset =
939         (offset + lbs[d][cst->getNumCols() - 1 - rank]).floorDiv(lbDivisors[d]);
940     offsets.push_back(offset);
941   }
942 
943   // Create 'newMemRefType' using 'newShape' from MemRefRegion accessed
944   // by 'srcStoreOpInst'.
945   uint64_t bufSize =
946       getMemRefEltSizeInBytes(oldMemRefType) * numElements.getValue();
947   unsigned newMemSpace;
948   if (bufSize <= localBufSizeThreshold && fastMemorySpace.hasValue()) {
949     newMemSpace = fastMemorySpace.getValue();
950   } else {
951     newMemSpace = oldMemRefType.getMemorySpaceAsInt();
952   }
953   auto newMemRefType = MemRefType::get(newShape, oldMemRefType.getElementType(),
954                                        {}, newMemSpace);
955 
956   // Create new private memref for fused loop 'forOp'. 'newShape' is always
957   // a constant shape.
958   // TODO: Create/move alloc ops for private memrefs closer to their
959   // consumer loop nests to reduce their live range. Currently they are added
960   // at the beginning of the function, because loop nests can be reordered
961   // during the fusion pass.
962   Value newMemRef = top.create<memref::AllocOp>(forOp.getLoc(), newMemRefType);
963 
964   // Build an AffineMap to remap access functions based on lower bound offsets.
965   SmallVector<AffineExpr, 4> remapExprs;
966   remapExprs.reserve(rank);
967   for (unsigned i = 0; i < rank; i++) {
968     auto dimExpr = b.getAffineDimExpr(outerIVs.size() + i);
969 
970     auto remapExpr =
971         simplifyAffineExpr(dimExpr - offsets[i], outerIVs.size() + rank, 0);
972     remapExprs.push_back(remapExpr);
973   }
974 
975   auto indexRemap =
976       AffineMap::get(outerIVs.size() + rank, 0, remapExprs, forOp.getContext());
977 
978   // Replace all users of 'oldMemRef' with 'newMemRef'.
979   LogicalResult res =
980       replaceAllMemRefUsesWith(oldMemRef, newMemRef, {}, indexRemap,
981                                /*extraOperands=*/outerIVs,
982                                /*symbolOperands=*/{},
983                                /*domOpFilter=*/&*forOp.getBody()->begin());
984   assert(succeeded(res) &&
985          "replaceAllMemrefUsesWith should always succeed here");
986   (void)res;
987   return newMemRef;
988 }
989 
990 /// Walking from node 'srcId' to node 'dstId' (exclusive of 'srcId' and
991 /// 'dstId'), if there is any non-affine operation accessing 'memref', return
992 /// true. Otherwise, return false.
993 static bool hasNonAffineUsersOnThePath(unsigned srcId, unsigned dstId,
994                                        Value memref,
995                                        MemRefDependenceGraph *mdg) {
996   auto *srcNode = mdg->getNode(srcId);
997   auto *dstNode = mdg->getNode(dstId);
998   Value::user_range users = memref.getUsers();
999   // For each MemRefDependenceGraph's node that is between 'srcNode' and
1000   // 'dstNode' (exclusive of 'srcNodes' and 'dstNode'), check whether any
1001   // non-affine operation in the node accesses the 'memref'.
1002   for (auto &idAndNode : mdg->nodes) {
1003     Operation *op = idAndNode.second.op;
1004     // Take care of operations between 'srcNode' and 'dstNode'.
1005     if (srcNode->op->isBeforeInBlock(op) && op->isBeforeInBlock(dstNode->op)) {
1006       // Walk inside the operation to find any use of the memref.
1007       // Interrupt the walk if found.
1008       auto walkResult = op->walk([&](Operation *user) {
1009         // Skip affine ops.
1010         if (isa<AffineMapAccessInterface>(*user))
1011           return WalkResult::advance();
1012         // Find a non-affine op that uses the memref.
1013         if (llvm::is_contained(users, user))
1014           return WalkResult::interrupt();
1015         return WalkResult::advance();
1016       });
1017       if (walkResult.wasInterrupted())
1018         return true;
1019     }
1020   }
1021   return false;
1022 }
1023 
1024 /// Check whether a memref value in node 'srcId' has a non-affine that
1025 /// is between node 'srcId' and node 'dstId' (exclusive of 'srcNode' and
1026 /// 'dstNode').
1027 static bool hasNonAffineUsersOnThePath(unsigned srcId, unsigned dstId,
1028                                        MemRefDependenceGraph *mdg) {
1029   // Collect memref values in node 'srcId'.
1030   auto *srcNode = mdg->getNode(srcId);
1031   llvm::SmallDenseSet<Value, 2> memRefValues;
1032   srcNode->op->walk([&](Operation *op) {
1033     // Skip affine ops.
1034     if (isa<AffineForOp>(op))
1035       return WalkResult::advance();
1036     for (Value v : op->getOperands())
1037       // Collect memref values only.
1038       if (v.getType().isa<MemRefType>())
1039         memRefValues.insert(v);
1040     return WalkResult::advance();
1041   });
1042   // Looking for users between node 'srcId' and node 'dstId'.
1043   for (Value memref : memRefValues)
1044     if (hasNonAffineUsersOnThePath(srcId, dstId, memref, mdg))
1045       return true;
1046   return false;
1047 }
1048 
1049 // Checks the profitability of fusing a backwards slice of the loop nest
1050 // surrounding 'srcOpInst' into the loop nest surrounding 'dstLoadOpInsts'.
1051 // The argument 'srcStoreOpInst' is used to calculate the storage reduction on
1052 // the memref being produced and consumed, which is an input to the cost model.
1053 // For producer-consumer fusion, 'srcStoreOpInst' will be the same as
1054 // 'srcOpInst', as we are slicing w.r.t to that producer. For input-reuse
1055 // fusion, 'srcOpInst' will be the src loop nest LoadOp which reads from the
1056 // same memref as dst loop nest load ops, and 'srcStoreOpInst' will be the
1057 // unique store op in the src node, which will be used to check that the write
1058 // region is the same after input-reuse fusion. Computation slices are provided
1059 // in 'depthSliceUnions' for each legal fusion depth. The maximal depth at which
1060 // fusion is legal is provided in 'maxLegalFusionDepth'. Returns true if it is
1061 // profitable to fuse the candidate loop nests. Returns false otherwise.
1062 // `dstLoopDepth` is set to the most profitable depth at which to materialize
1063 // the source loop nest slice.
1064 // The profitability model executes the following steps:
1065 // *) Computes the backward computation slice at 'srcOpInst'. This
1066 //    computation slice of the loop nest surrounding 'srcOpInst' is
1067 //    represented by modified src loop bounds in 'sliceState', which are
1068 //    functions of loop IVs in the loop nest surrounding 'srcOpInst'.
1069 // *) Computes the cost of unfused src/dst loop nests (currently the cost of a
1070 //    loop nest is the total number of dynamic operation instances in the loop
1071 //    nest).
1072 // *) Computes the cost of fusing a slice of the src loop nest into the dst
1073 //    loop nest at various values of dst loop depth, attempting to fuse
1074 //    the largest computation slice at the maximal dst loop depth (closest to
1075 //    the load) to minimize reuse distance and potentially enable subsequent
1076 //    load/store forwarding.
1077 //    NOTE: 'dstLoopDepth' refers to the loop depth within the destination loop
1078 //    nest, at which the src computation slice is inserted/fused.
1079 //    NOTE: We attempt to maximize the dst loop depth, but there are cases
1080 //    where a particular setting for 'dstLoopNest' might fuse an unsliced
1081 //    loop (within the src computation slice) at a depth which results in
1082 //    excessive recomputation (see unit tests for examples).
1083 // *) Compares the total cost of the unfused loop nests to the min cost fused
1084 //    loop nest computed in the previous step, and returns true if the latter
1085 //    is lower.
1086 // TODO: Extend profitability analysis to support scenarios with multiple
1087 // stores.
1088 static bool isFusionProfitable(Operation *srcOpInst, Operation *srcStoreOpInst,
1089                                AffineForOp dstForOp,
1090                                ArrayRef<ComputationSliceState> depthSliceUnions,
1091                                unsigned maxLegalFusionDepth,
1092                                unsigned *dstLoopDepth,
1093                                double computeToleranceThreshold) {
1094   LLVM_DEBUG({
1095     llvm::dbgs() << "Checking whether fusion is profitable between src op:\n";
1096     llvm::dbgs() << ' ' << *srcOpInst << " and destination loop:\n";
1097     llvm::dbgs() << dstForOp << "\n";
1098   });
1099 
1100   if (maxLegalFusionDepth == 0) {
1101     LLVM_DEBUG(llvm::dbgs() << "Can't fuse: maxLegalFusionDepth == 0 .\n");
1102     return false;
1103   }
1104 
1105   // Compute cost of sliced and unsliced src loop nest.
1106   SmallVector<AffineForOp, 4> srcLoopIVs;
1107   getLoopIVs(*srcOpInst, &srcLoopIVs);
1108 
1109   // Walk src loop nest and collect stats.
1110   LoopNestStats srcLoopNestStats;
1111   if (!getLoopNestStats(srcLoopIVs[0], &srcLoopNestStats))
1112     return false;
1113 
1114   // Compute cost of dst loop nest.
1115   LoopNestStats dstLoopNestStats;
1116   if (!getLoopNestStats(dstForOp, &dstLoopNestStats))
1117     return false;
1118 
1119   // Search for min cost value for 'dstLoopDepth'. At each value of
1120   // 'dstLoopDepth' from 'maxLegalLoopDepth' to '1', compute computation slice
1121   // bounds between 'srcOpInst' and each op in 'dstOpinsts' (taking the union
1122   // of these bounds). Next the union slice bounds are used to calculate
1123   // the cost of the slice and the cost of the slice inserted into the dst
1124   // loop nest at 'dstLoopDepth'.
1125   uint64_t minFusedLoopNestComputeCost = std::numeric_limits<uint64_t>::max();
1126   double maxStorageReduction = 0.0;
1127   Optional<uint64_t> sliceMemEstimate = None;
1128 
1129   // The best loop depth at which to materialize the slice.
1130   Optional<unsigned> bestDstLoopDepth = None;
1131 
1132   // Compute op instance count for the src loop nest without iteration slicing.
1133   uint64_t srcLoopNestCost = getComputeCost(srcLoopIVs[0], srcLoopNestStats);
1134 
1135   // Compute src loop nest write region size.
1136   MemRefRegion srcWriteRegion(srcStoreOpInst->getLoc());
1137   if (failed(srcWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0))) {
1138     LLVM_DEBUG(llvm::dbgs()
1139                << "Unable to compute MemRefRegion for source operation\n.");
1140     return false;
1141   }
1142 
1143   Optional<int64_t> maybeSrcWriteRegionSizeBytes =
1144       srcWriteRegion.getRegionSize();
1145   if (!maybeSrcWriteRegionSizeBytes.hasValue())
1146     return false;
1147   int64_t srcWriteRegionSizeBytes = maybeSrcWriteRegionSizeBytes.getValue();
1148 
1149   // Compute op instance count for the src loop nest.
1150   uint64_t dstLoopNestCost = getComputeCost(dstForOp, dstLoopNestStats);
1151 
1152   // Evaluate all depth choices for materializing the slice in the destination
1153   // loop nest.
1154   for (unsigned i = maxLegalFusionDepth; i >= 1; --i) {
1155     const ComputationSliceState &slice = depthSliceUnions[i - 1];
1156     // Skip slice union if it wasn't computed for this depth.
1157     if (slice.isEmpty())
1158       continue;
1159 
1160     int64_t fusedLoopNestComputeCost;
1161     if (!getFusionComputeCost(srcLoopIVs[0], srcLoopNestStats, dstForOp,
1162                               dstLoopNestStats, slice,
1163                               &fusedLoopNestComputeCost)) {
1164       LLVM_DEBUG(llvm::dbgs() << "Unable to compute fusion compute cost.\n.");
1165       continue;
1166     }
1167 
1168     double additionalComputeFraction =
1169         fusedLoopNestComputeCost /
1170             (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1171         1;
1172 
1173     // Determine what the slice write MemRefRegion would be, if the src loop
1174     // nest slice 'slice' were to be inserted into the dst loop nest at loop
1175     // depth 'i'.
1176     MemRefRegion sliceWriteRegion(srcStoreOpInst->getLoc());
1177     if (failed(sliceWriteRegion.compute(srcStoreOpInst, /*loopDepth=*/0,
1178                                         &slice))) {
1179       LLVM_DEBUG(llvm::dbgs()
1180                  << "Failed to compute slice write region at loopDepth: " << i
1181                  << "\n");
1182       continue;
1183     }
1184 
1185     Optional<int64_t> maybeSliceWriteRegionSizeBytes =
1186         sliceWriteRegion.getRegionSize();
1187     if (!maybeSliceWriteRegionSizeBytes.hasValue() ||
1188         maybeSliceWriteRegionSizeBytes.getValue() == 0) {
1189       LLVM_DEBUG(llvm::dbgs()
1190                  << "Failed to get slice write region size at loopDepth: " << i
1191                  << "\n");
1192       continue;
1193     }
1194     int64_t sliceWriteRegionSizeBytes =
1195         maybeSliceWriteRegionSizeBytes.getValue();
1196 
1197     // If we are fusing for reuse, check that write regions remain the same.
1198     // TODO: Write region check should check sizes and offsets in
1199     // each dimension, so that we are sure they are covering the same memref
1200     // region. Also, move this out to a isMemRefRegionSuperSet helper function.
1201     if (srcOpInst != srcStoreOpInst &&
1202         sliceWriteRegionSizeBytes != srcWriteRegionSizeBytes)
1203       continue;
1204 
1205     double storageReduction = static_cast<double>(srcWriteRegionSizeBytes) /
1206                               static_cast<double>(sliceWriteRegionSizeBytes);
1207 
1208     LLVM_DEBUG({
1209       std::stringstream msg;
1210       msg << "  evaluating fusion profitability at depth : " << i << "\n"
1211           << std::fixed << std::setprecision(2)
1212           << "   additional compute fraction: "
1213           << 100.0 * additionalComputeFraction << "%\n"
1214           << "   storage reduction factor: " << storageReduction << "x\n"
1215           << "   fused nest cost: " << fusedLoopNestComputeCost << "\n"
1216           << "   src write region size: " << srcWriteRegionSizeBytes << "\n"
1217           << "   slice write region size: " << sliceWriteRegionSizeBytes
1218           << "\n";
1219       llvm::dbgs() << msg.str();
1220     });
1221 
1222     // TODO: This is a placeholder cost model.
1223     // Among all choices that add an acceptable amount of redundant computation
1224     // (as per computeToleranceThreshold), we will simply pick the one that
1225     // reduces the intermediary size the most.
1226     if ((storageReduction > maxStorageReduction) &&
1227         (additionalComputeFraction < computeToleranceThreshold)) {
1228       maxStorageReduction = storageReduction;
1229       bestDstLoopDepth = i;
1230       minFusedLoopNestComputeCost = fusedLoopNestComputeCost;
1231       sliceMemEstimate = sliceWriteRegionSizeBytes;
1232     }
1233   }
1234 
1235   // A simple cost model: fuse if it reduces the memory footprint.
1236 
1237   if (!bestDstLoopDepth.hasValue()) {
1238     LLVM_DEBUG(
1239         llvm::dbgs()
1240         << "All fusion choices involve more than the threshold amount of "
1241            "redundant computation; NOT fusing.\n");
1242     return false;
1243   }
1244 
1245   if (!bestDstLoopDepth.hasValue()) {
1246     LLVM_DEBUG(llvm::dbgs() << "no fusion depth could be evaluated.\n");
1247     return false;
1248   }
1249 
1250   // Set dstLoopDepth based on best values from search.
1251   *dstLoopDepth = bestDstLoopDepth.getValue();
1252 
1253   LLVM_DEBUG(
1254       llvm::dbgs() << " LoopFusion fusion stats:"
1255                    << "\n  best loop depth: " << bestDstLoopDepth
1256                    << "\n  src loop nest compute cost: " << srcLoopNestCost
1257                    << "\n  dst loop nest compute cost: " << dstLoopNestCost
1258                    << "\n  fused loop nest compute cost: "
1259                    << minFusedLoopNestComputeCost << "\n");
1260 
1261   auto dstMemSize = getMemoryFootprintBytes(dstForOp);
1262   auto srcMemSize = getMemoryFootprintBytes(srcLoopIVs[0]);
1263 
1264   Optional<double> storageReduction = None;
1265 
1266   if (!dstMemSize.hasValue() || !srcMemSize.hasValue()) {
1267     LLVM_DEBUG(llvm::dbgs()
1268                << "  fusion memory benefit cannot be evaluated; NOT fusing.\n");
1269     return false;
1270   }
1271 
1272   auto srcMemSizeVal = srcMemSize.getValue();
1273   auto dstMemSizeVal = dstMemSize.getValue();
1274 
1275   assert(sliceMemEstimate.hasValue() && "expected value");
1276   auto fusedMem = dstMemSizeVal + sliceMemEstimate.getValue();
1277 
1278   LLVM_DEBUG(llvm::dbgs() << "   src mem: " << srcMemSizeVal << "\n"
1279                           << "   dst mem: " << dstMemSizeVal << "\n"
1280                           << "   fused mem: " << fusedMem << "\n"
1281                           << "   slice mem: " << sliceMemEstimate << "\n");
1282 
1283   if (static_cast<long>(fusedMem) > srcMemSizeVal + dstMemSizeVal) {
1284     LLVM_DEBUG(llvm::dbgs() << "Fusion is not profitable; NOT fusing.\n");
1285     return false;
1286   }
1287   storageReduction =
1288       100.0 *
1289       (1.0 - fusedMem / (static_cast<double>(srcMemSizeVal) + dstMemSizeVal));
1290 
1291   double additionalComputeFraction =
1292       100.0 * (minFusedLoopNestComputeCost /
1293                    (static_cast<double>(srcLoopNestCost) + dstLoopNestCost) -
1294                1);
1295   (void)additionalComputeFraction;
1296   LLVM_DEBUG({
1297     std::stringstream msg;
1298     msg << " fusion is most profitable at depth " << *dstLoopDepth << " with "
1299         << std::setprecision(2) << additionalComputeFraction
1300         << "% redundant computation and a ";
1301     msg << (storageReduction.hasValue()
1302                 ? std::to_string(storageReduction.getValue())
1303                 : "<unknown>");
1304     msg << "% storage reduction.\n";
1305     llvm::dbgs() << msg.str();
1306   });
1307 
1308   return true;
1309 }
1310 
1311 namespace {
1312 
1313 // GreedyFusion greedily fuses loop nests which have a producer/consumer or
1314 // input-reuse relationship on a memref, with the goal of improving locality.
1315 //
1316 // The steps of the producer-consumer fusion algorithm are as follows:
1317 //
1318 // *) A worklist is initialized with node ids from the dependence graph.
1319 // *) For each node id in the worklist:
1320 //   *) Pop an AffineForOp of the worklist. This 'dstAffineForOp' will be a
1321 //      candidate destination AffineForOp into which fusion will be attempted.
1322 //   *) Add each LoadOp currently in 'dstAffineForOp' into list 'dstLoadOps'.
1323 //   *) For each LoadOp in 'dstLoadOps' do:
1324 //      *) Look up dependent loop nests which have a single store op to the same
1325 //         memref.
1326 //      *) Check if dependences would be violated by the fusion.
1327 //      *) Get a computation slice of 'srcLoopNest', which adjusts its loop
1328 //         bounds to be functions of 'dstLoopNest' IVs and symbols.
1329 //      *) Fuse the 'srcLoopNest' computation slice into the 'dstLoopNest',
1330 //         at a loop depth determined by the cost model in 'isFusionProfitable'.
1331 //      *) Add the newly fused load/store operations to the state,
1332 //         and also add newly fused load ops to 'dstLoopOps' to be considered
1333 //         as fusion dst load ops in another iteration.
1334 //      *) Remove old src loop nest and its associated state.
1335 //
1336 // The steps of the input-reuse fusion algorithm are as follows:
1337 //
1338 // *) Initialize 'worklist' with node ids from the dependence graph.
1339 // *) For each 'dstNode' in the worklist:
1340 //   *) Find a candidate sibling node 'sibNode' to fuse with 'dstNode' which
1341 //      loads from the same memref, but which has no dependence paths to/from.
1342 //   *) Get a computation slice of 'sibLoopNest', which adjusts its loop
1343 //      bounds to be functions of 'dstLoopNest' IVs and symbols.
1344 //   *) Fuse the 'sibLoopNest' computation slice into the 'dstLoopNest',
1345 //      at a loop depth determined by the cost model in 'isFusionProfitable'.
1346 //      This function also checks that the memref write region of 'sibLoopNest',
1347 //      is preserved in the fused loop nest.
1348 //   *) Update graph state to reflect the fusion of 'sibNode' into 'dstNode'.
1349 //
1350 // Given a graph where top-level operations are vertices in the set 'V' and
1351 // edges in the set 'E' are dependences between vertices, this algorithm
1352 // takes O(V) time for initialization, and has runtime O(V + E).
1353 //
1354 // This greedy algorithm is not 'maximal' due to the current restriction of
1355 // fusing along single producer consumer edges, but there is a TODO: to fix
1356 // this.
1357 //
1358 // TODO: Experiment with other fusion policies.
1359 struct GreedyFusion {
1360 public:
1361   // The data dependence graph to traverse during fusion.
1362   MemRefDependenceGraph *mdg;
1363   // Worklist of graph nodes visited during the fusion pass.
1364   SmallVector<unsigned, 8> worklist;
1365   // Parameter for local buffer size threshold.
1366   unsigned localBufSizeThreshold;
1367   // Parameter for fast memory space.
1368   Optional<unsigned> fastMemorySpace;
1369   // If true, ignore any additional (redundant) computation tolerance threshold
1370   // that would have prevented fusion.
1371   bool maximalFusion;
1372   // The amount of additional computation that is tolerated while fusing
1373   // pair-wise as a fraction of the total computation.
1374   double computeToleranceThreshold;
1375 
1376   using Node = MemRefDependenceGraph::Node;
1377 
1378   GreedyFusion(MemRefDependenceGraph *mdg, unsigned localBufSizeThreshold,
1379                Optional<unsigned> fastMemorySpace, bool maximalFusion,
1380                double computeToleranceThreshold)
1381       : mdg(mdg), localBufSizeThreshold(localBufSizeThreshold),
1382         fastMemorySpace(fastMemorySpace), maximalFusion(maximalFusion),
1383         computeToleranceThreshold(computeToleranceThreshold) {}
1384 
1385   /// Initializes 'worklist' with nodes from 'mdg'.
1386   void init() {
1387     // TODO: Add a priority queue for prioritizing nodes by different
1388     // metrics (e.g. arithmetic intensity/flops-to-bytes ratio).
1389     worklist.clear();
1390     for (auto &idAndNode : mdg->nodes) {
1391       const Node &node = idAndNode.second;
1392       worklist.push_back(node.id);
1393     }
1394   }
1395   /// Run only sibling fusion on the `mdg`.
1396   void runSiblingFusionOnly() {
1397     fuseSiblingNodes();
1398     eraseUnusedMemRefAllocations();
1399   }
1400 
1401   /// Run only producer/consumer fusion on the `mdg`.
1402   void runProducerConsumerFusionOnly() {
1403     fuseProducerConsumerNodes(
1404         /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max());
1405     eraseUnusedMemRefAllocations();
1406   }
1407 
1408   // Run the GreedyFusion pass.
1409   // *) First pass through the nodes fuses single-use producer nodes into their
1410   //    unique consumer.
1411   // *) Second pass fuses sibling nodes which share no dependence edges.
1412   // *) Third pass fuses any remaining producer nodes into their users.
1413   void runGreedyFusion() {
1414     // TODO: Run this repeatedly until a fixed-point is reached.
1415     fuseProducerConsumerNodes(/*maxSrcUserCount=*/1);
1416     fuseSiblingNodes();
1417     fuseProducerConsumerNodes(
1418         /*maxSrcUserCount=*/std::numeric_limits<unsigned>::max());
1419     eraseUnusedMemRefAllocations();
1420   }
1421 
1422   void fuseProducerConsumerNodes(unsigned maxSrcUserCount) {
1423     LLVM_DEBUG(llvm::dbgs() << "--- Producer/Consumer Fusion ---\n");
1424     init();
1425     while (!worklist.empty()) {
1426       unsigned dstId = worklist.back();
1427       worklist.pop_back();
1428 
1429       // Skip if this node was removed (fused into another node).
1430       if (mdg->nodes.count(dstId) == 0)
1431         continue;
1432       // Get 'dstNode' into which to attempt fusion.
1433       auto *dstNode = mdg->getNode(dstId);
1434       // Skip if 'dstNode' is not a loop nest.
1435       if (!isa<AffineForOp>(dstNode->op))
1436         continue;
1437       // Skip if 'dstNode' is a loop nest returning values.
1438       // TODO: support loop nests that return values.
1439       if (dstNode->op->getNumResults() > 0)
1440         continue;
1441 
1442       LLVM_DEBUG(llvm::dbgs() << "Evaluating dst loop " << dstId << "\n");
1443 
1444       // Sink sequential loops in 'dstNode' (and thus raise parallel loops)
1445       // while preserving relative order. This can increase the maximum loop
1446       // depth at which we can fuse a slice of a producer loop nest into a
1447       // consumer loop nest.
1448       sinkSequentialLoops(dstNode);
1449       auto dstAffineForOp = cast<AffineForOp>(dstNode->op);
1450 
1451       // Try to fuse 'dstNode' with candidate producer loops until a fixed point
1452       // is reached. Fusing two loops may expose new fusion opportunities.
1453       bool dstNodeChanged;
1454       do {
1455         // Gather src loop candidates for 'dstNode' and visit them in "quasi"
1456         // reverse program order to minimize the number of iterations needed to
1457         // reach the fixed point. Note that this is a best effort approach since
1458         // 'getProducerCandidates' does not always guarantee that program order
1459         // in 'srcIdCandidates'.
1460         dstNodeChanged = false;
1461         SmallVector<unsigned, 16> srcIdCandidates;
1462         getProducerCandidates(dstId, mdg, srcIdCandidates);
1463 
1464         for (unsigned srcId : llvm::reverse(srcIdCandidates)) {
1465           // Get 'srcNode' from which to attempt fusion into 'dstNode'.
1466           auto *srcNode = mdg->getNode(srcId);
1467           auto srcAffineForOp = cast<AffineForOp>(srcNode->op);
1468           LLVM_DEBUG(llvm::dbgs() << "Evaluating src loop " << srcId
1469                                   << " for dst loop " << dstId << "\n");
1470 
1471           // Skip if 'srcNode' is a loop nest returning values.
1472           // TODO: support loop nests that return values.
1473           if (isa<AffineForOp>(srcNode->op) && srcNode->op->getNumResults() > 0)
1474             continue;
1475 
1476           DenseSet<Value> producerConsumerMemrefs;
1477           gatherProducerConsumerMemrefs(srcId, dstId, mdg,
1478                                         producerConsumerMemrefs);
1479 
1480           // Skip if 'srcNode' out edge count on any memref is greater than
1481           // 'maxSrcUserCount'.
1482           if (any_of(producerConsumerMemrefs, [&](Value memref) {
1483                 return mdg->getOutEdgeCount(srcNode->id, memref) >
1484                        maxSrcUserCount;
1485               }))
1486             continue;
1487 
1488           // Gather memrefs in 'srcNode' that are written and escape to the
1489           // function (e.g., memref function arguments, returned memrefs,
1490           // memrefs passed to function calls, etc.).
1491           DenseSet<Value> srcEscapingMemRefs;
1492           gatherEscapingMemrefs(srcNode->id, mdg, srcEscapingMemRefs);
1493 
1494           // Skip if there are non-affine operations in between the 'srcNode'
1495           // and 'dstNode' using their memrefs. If so, we wouldn't be able to
1496           // compute a legal insertion point for now. 'srcNode' and 'dstNode'
1497           // memrefs with non-affine operation users would be considered
1498           // escaping memrefs so we can limit this check to only scenarios with
1499           // escaping memrefs.
1500           if (!srcEscapingMemRefs.empty() &&
1501               hasNonAffineUsersOnThePath(srcId, dstId, mdg)) {
1502             LLVM_DEBUG(
1503                 llvm::dbgs()
1504                 << "Can't fuse: non-affine users in between the loops\n.");
1505             continue;
1506           }
1507 
1508           // Compute an operation list insertion point for the fused loop
1509           // nest which preserves dependences.
1510           Operation *fusedLoopInsPoint =
1511               mdg->getFusedLoopNestInsertionPoint(srcNode->id, dstNode->id);
1512           if (fusedLoopInsPoint == nullptr)
1513             continue;
1514 
1515           // Compute the innermost common loop depth for dstNode
1516           // producer-consumer loads/stores.
1517           SmallVector<Operation *, 2> dstMemrefOps;
1518           for (Operation *op : dstNode->loads)
1519             if (producerConsumerMemrefs.count(
1520                     cast<AffineReadOpInterface>(op).getMemRef()) > 0)
1521               dstMemrefOps.push_back(op);
1522           for (Operation *op : dstNode->stores)
1523             if (producerConsumerMemrefs.count(
1524                     cast<AffineWriteOpInterface>(op).getMemRef()))
1525               dstMemrefOps.push_back(op);
1526           unsigned dstLoopDepthTest = getInnermostCommonLoopDepth(dstMemrefOps);
1527 
1528           // Check the feasibility of fusing src loop nest into dst loop nest
1529           // at loop depths in range [1, dstLoopDepthTest].
1530           unsigned maxLegalFusionDepth = 0;
1531           SmallVector<ComputationSliceState, 8> depthSliceUnions;
1532           depthSliceUnions.resize(dstLoopDepthTest);
1533           FusionStrategy strategy(FusionStrategy::ProducerConsumer);
1534           for (unsigned i = 1; i <= dstLoopDepthTest; ++i) {
1535             FusionResult result = mlir::canFuseLoops(
1536                 srcAffineForOp, dstAffineForOp,
1537                 /*dstLoopDepth=*/i, &depthSliceUnions[i - 1], strategy);
1538 
1539             if (result.value == FusionResult::Success)
1540               maxLegalFusionDepth = i;
1541           }
1542 
1543           if (maxLegalFusionDepth == 0) {
1544             LLVM_DEBUG(llvm::dbgs()
1545                        << "Can't fuse: fusion is not legal at any depth\n");
1546             continue;
1547           }
1548 
1549           // Check if fusion would be profitable. We skip profitability analysis
1550           // for maximal fusion since we already know the maximal legal depth to
1551           // fuse.
1552           unsigned bestDstLoopDepth = maxLegalFusionDepth;
1553           if (!maximalFusion) {
1554             // Retrieve producer stores from the src loop.
1555             SmallVector<Operation *, 2> producerStores;
1556             for (Operation *op : srcNode->stores)
1557               if (producerConsumerMemrefs.count(
1558                       cast<AffineWriteOpInterface>(op).getMemRef()))
1559                 producerStores.push_back(op);
1560 
1561             // TODO: Suppport multiple producer stores in profitability
1562             // analysis. We limit profitability analysis to only scenarios with
1563             // a single producer store for now. Note that some multi-store
1564             // producer scenarios will still go through profitability analysis
1565             // if only one of the stores is involved the producer-consumer
1566             // relationship of the candidate loops.
1567             assert(!producerStores.empty() && "Expected producer store");
1568             if (producerStores.size() > 1)
1569               LLVM_DEBUG(llvm::dbgs() << "Skipping profitability analysis. Not "
1570                                          "supported for this case\n");
1571             else if (!isFusionProfitable(producerStores[0], producerStores[0],
1572                                          dstAffineForOp, depthSliceUnions,
1573                                          maxLegalFusionDepth, &bestDstLoopDepth,
1574                                          computeToleranceThreshold))
1575               continue;
1576           }
1577 
1578           assert(bestDstLoopDepth > 0 && "Unexpected loop fusion depth");
1579           ComputationSliceState &bestSlice =
1580               depthSliceUnions[bestDstLoopDepth - 1];
1581           assert(!bestSlice.isEmpty() && "Missing slice union for depth");
1582 
1583           // Determine if 'srcId' can be removed after fusion, taking into
1584           // account remaining dependences, escaping memrefs and the fusion
1585           // insertion point.
1586           bool removeSrcNode = canRemoveSrcNodeAfterFusion(
1587               srcId, dstId, bestSlice, fusedLoopInsPoint, srcEscapingMemRefs,
1588               mdg);
1589 
1590           DenseSet<Value> privateMemrefs;
1591           for (Value memref : producerConsumerMemrefs) {
1592             // If `memref` is an escaping one, do not create a private memref
1593             // for the below scenarios, since doing so will leave the escaping
1594             // memref unmodified as all the writes originally meant for the
1595             // escaping memref would be performed on the private memref:
1596             // 1. The source is to be removed after fusion,
1597             // OR
1598             // 2. The destination writes to `memref`.
1599             if (srcEscapingMemRefs.count(memref) > 0 &&
1600                 (removeSrcNode || dstNode->getStoreOpCount(memref) > 0))
1601               continue;
1602 
1603             // Don't create a private memref if 'srcNode' has in edges on
1604             // 'memref' or 'dstNode' has out edges on 'memref'.
1605             if (mdg->getIncomingMemRefAccesses(srcId, memref) > 0 ||
1606                 mdg->getOutEdgeCount(dstId, memref) > 0)
1607               continue;
1608 
1609             // If 'srcNode' will be removed but it has out edges on 'memref' to
1610             // nodes other than 'dstNode', we have to preserve dependences and
1611             // cannot create a private memref.
1612             if (removeSrcNode &&
1613                 any_of(mdg->outEdges[srcId], [&](const auto &edge) {
1614                   return edge.value == memref && edge.id != dstId;
1615                 }))
1616               continue;
1617 
1618             // Create a private version of this memref.
1619             privateMemrefs.insert(memref);
1620           }
1621 
1622           // Fuse computation slice of 'srcLoopNest' into 'dstLoopNest'.
1623           fuseLoops(srcAffineForOp, dstAffineForOp, bestSlice);
1624           dstNodeChanged = true;
1625 
1626           LLVM_DEBUG(llvm::dbgs()
1627                      << "Fused src loop " << srcId << " into dst loop " << dstId
1628                      << " at depth " << bestDstLoopDepth << ":\n"
1629                      << dstAffineForOp << "\n");
1630 
1631           // Move 'dstAffineForOp' before 'insertPointInst' if needed.
1632           if (fusedLoopInsPoint != dstAffineForOp.getOperation())
1633             dstAffineForOp.getOperation()->moveBefore(fusedLoopInsPoint);
1634 
1635           // Update edges between 'srcNode' and 'dstNode'.
1636           mdg->updateEdges(srcNode->id, dstNode->id, privateMemrefs,
1637                            removeSrcNode);
1638 
1639           // Create private memrefs.
1640           if (!privateMemrefs.empty()) {
1641             // Gather stores for all the private-to-be memrefs.
1642             DenseMap<Value, SmallVector<Operation *, 4>> privateMemRefToStores;
1643             dstAffineForOp.walk([&](AffineWriteOpInterface storeOp) {
1644               Value storeMemRef = storeOp.getMemRef();
1645               if (privateMemrefs.count(storeMemRef) > 0)
1646                 privateMemRefToStores[storeMemRef].push_back(
1647                     storeOp.getOperation());
1648             });
1649 
1650             // Replace original memrefs with private memrefs. Note that all the
1651             // loads and stores on these memrefs will be replaced with a new
1652             // loads and stores. Any reference to the original ones becomes
1653             // invalid after this point.
1654             for (auto &memrefToStoresPair : privateMemRefToStores) {
1655               // TODO: Use union of memref write regions to compute
1656               // private memref footprint.
1657               SmallVector<Operation *, 4> &storesForMemref =
1658                   memrefToStoresPair.second;
1659               Value newMemRef = createPrivateMemRef(
1660                   dstAffineForOp, storesForMemref[0], bestDstLoopDepth,
1661                   fastMemorySpace, localBufSizeThreshold);
1662               // Create new node in dependence graph for 'newMemRef' alloc op.
1663               unsigned newMemRefNodeId =
1664                   mdg->addNode(newMemRef.getDefiningOp());
1665               // Add edge from 'newMemRef' node to dstNode.
1666               mdg->addEdge(newMemRefNodeId, dstId, newMemRef);
1667             }
1668             // One or more entries for 'newMemRef' alloc op are inserted into
1669             // the DenseMap mdg->nodes. Since an insertion may cause DenseMap to
1670             // reallocate, update dstNode.
1671             dstNode = mdg->getNode(dstId);
1672           }
1673 
1674           // Collect dst loop stats after memref privatization transformation.
1675           LoopNestStateCollector dstLoopCollector;
1676           dstLoopCollector.collect(dstAffineForOp.getOperation());
1677 
1678           // Clear and add back loads and stores.
1679           mdg->clearNodeLoadAndStores(dstNode->id);
1680           mdg->addToNode(dstId, dstLoopCollector.loadOpInsts,
1681                          dstLoopCollector.storeOpInsts);
1682 
1683           if (removeSrcNode) {
1684             LLVM_DEBUG(llvm::dbgs()
1685                        << "Removing src loop " << srcId << " after fusion\n");
1686             // srcNode is no longer valid after it is removed from mdg.
1687             srcAffineForOp.erase();
1688             mdg->removeNode(srcId);
1689             srcNode = nullptr;
1690           }
1691         }
1692       } while (dstNodeChanged);
1693     }
1694   }
1695 
1696   // Visits each node in the graph, and for each node, attempts to fuse it with
1697   // its sibling nodes (nodes which share a parent, but no dependence edges).
1698   void fuseSiblingNodes() {
1699     LLVM_DEBUG(llvm::dbgs() << "--- Sibling Fusion ---\n");
1700     init();
1701     while (!worklist.empty()) {
1702       unsigned dstId = worklist.back();
1703       worklist.pop_back();
1704 
1705       // Skip if this node was removed (fused into another node).
1706       if (mdg->nodes.count(dstId) == 0)
1707         continue;
1708       // Get 'dstNode' into which to attempt fusion.
1709       auto *dstNode = mdg->getNode(dstId);
1710       // Skip if 'dstNode' is not a loop nest.
1711       if (!isa<AffineForOp>(dstNode->op))
1712         continue;
1713       // Attempt to fuse 'dstNode' with its sibling nodes in the graph.
1714       fuseWithSiblingNodes(dstNode);
1715     }
1716   }
1717 
1718   // Attempt to fuse 'dstNode' with sibling nodes in the graph.
1719   void fuseWithSiblingNodes(Node *dstNode) {
1720     DenseSet<unsigned> visitedSibNodeIds;
1721     std::pair<unsigned, Value> idAndMemref;
1722     auto dstAffineForOp = cast<AffineForOp>(dstNode->op);
1723 
1724     while (findSiblingNodeToFuse(dstNode, &visitedSibNodeIds, &idAndMemref)) {
1725       unsigned sibId = idAndMemref.first;
1726       Value memref = idAndMemref.second;
1727       // TODO: Check that 'sibStoreOpInst' post-dominates all other
1728       // stores to the same memref in 'sibNode' loop nest.
1729       auto *sibNode = mdg->getNode(sibId);
1730       // Compute an operation list insertion point for the fused loop
1731       // nest which preserves dependences.
1732       assert(sibNode->op->getBlock() == dstNode->op->getBlock());
1733       Operation *insertPointInst =
1734           sibNode->op->isBeforeInBlock(dstNode->op)
1735               ? mdg->getFusedLoopNestInsertionPoint(sibNode->id, dstNode->id)
1736               : mdg->getFusedLoopNestInsertionPoint(dstNode->id, sibNode->id);
1737       if (insertPointInst == nullptr)
1738         continue;
1739 
1740       // Check if fusion would be profitable and at what depth.
1741 
1742       // Get unique 'sibNode' load op to 'memref'.
1743       SmallVector<Operation *, 2> sibLoadOpInsts;
1744       sibNode->getLoadOpsForMemref(memref, &sibLoadOpInsts);
1745       // Currently findSiblingNodeToFuse searches for siblings with one load.
1746       assert(sibLoadOpInsts.size() == 1);
1747       Operation *sibLoadOpInst = sibLoadOpInsts[0];
1748       assert(!sibNode->stores.empty());
1749       // TODO: Choose the store which postdominates all other stores.
1750       auto *sibStoreOpInst = sibNode->stores.back();
1751 
1752       // Gather 'dstNode' load ops to 'memref'.
1753       SmallVector<Operation *, 2> dstLoadOpInsts;
1754       dstNode->getLoadOpsForMemref(memref, &dstLoadOpInsts);
1755 
1756       SmallVector<AffineForOp, 4> dstLoopIVs;
1757       getLoopIVs(*dstLoadOpInsts[0], &dstLoopIVs);
1758       unsigned dstLoopDepthTest = dstLoopIVs.size();
1759       auto sibAffineForOp = cast<AffineForOp>(sibNode->op);
1760 
1761       // Compute loop depth and slice union for fusion.
1762       SmallVector<ComputationSliceState, 8> depthSliceUnions;
1763       depthSliceUnions.resize(dstLoopDepthTest);
1764       unsigned maxLegalFusionDepth = 0;
1765       FusionStrategy strategy(memref);
1766       for (unsigned i = 1; i <= dstLoopDepthTest; ++i) {
1767         FusionResult result = mlir::canFuseLoops(
1768             sibAffineForOp, dstAffineForOp,
1769             /*dstLoopDepth=*/i, &depthSliceUnions[i - 1], strategy);
1770 
1771         if (result.value == FusionResult::Success)
1772           maxLegalFusionDepth = i;
1773       }
1774 
1775       // Skip if fusion is not feasible at any loop depths.
1776       if (maxLegalFusionDepth == 0)
1777         continue;
1778 
1779       unsigned bestDstLoopDepth = maxLegalFusionDepth;
1780       if (!maximalFusion) {
1781         // Check if fusion would be profitable.
1782         if (!isFusionProfitable(sibLoadOpInst, sibStoreOpInst, dstAffineForOp,
1783                                 depthSliceUnions, maxLegalFusionDepth,
1784                                 &bestDstLoopDepth, computeToleranceThreshold))
1785           continue;
1786       }
1787 
1788       assert(bestDstLoopDepth > 0 && "Unexpected loop fusion depth");
1789       assert(!depthSliceUnions[bestDstLoopDepth - 1].isEmpty() &&
1790              "Fusion depth has no computed slice union");
1791       // Check if source loop is being inserted in the innermost
1792       // destination loop. Based on this, the fused loop may be optimized
1793       // further inside `fuseLoops`.
1794       bool isInnermostInsertion = (bestDstLoopDepth == dstLoopDepthTest);
1795       // Fuse computation slice of 'sibLoopNest' into 'dstLoopNest'.
1796       mlir::fuseLoops(sibAffineForOp, dstAffineForOp,
1797                       depthSliceUnions[bestDstLoopDepth - 1],
1798                       isInnermostInsertion);
1799 
1800       auto dstForInst = cast<AffineForOp>(dstNode->op);
1801       // Update operation position of fused loop nest (if needed).
1802       if (insertPointInst != dstForInst.getOperation()) {
1803         dstForInst->moveBefore(insertPointInst);
1804       }
1805       // Update data dependence graph state post fusion.
1806       updateStateAfterSiblingFusion(sibNode, dstNode);
1807     }
1808   }
1809 
1810   // Searches function argument uses and the graph from 'dstNode' looking for a
1811   // fusion candidate sibling node which shares no dependences with 'dstNode'
1812   // but which loads from the same memref. Returns true and sets
1813   // 'idAndMemrefToFuse' on success. Returns false otherwise.
1814   bool findSiblingNodeToFuse(Node *dstNode,
1815                              DenseSet<unsigned> *visitedSibNodeIds,
1816                              std::pair<unsigned, Value> *idAndMemrefToFuse) {
1817     // Returns true if 'sibNode' can be fused with 'dstNode' for input reuse
1818     // on 'memref'.
1819     auto canFuseWithSibNode = [&](Node *sibNode, Value memref) {
1820       // Skip if 'outEdge' is not a read-after-write dependence.
1821       // TODO: Remove restrict to single load op restriction.
1822       if (sibNode->getLoadOpCount(memref) != 1)
1823         return false;
1824       // Skip if there exists a path of dependent edges between
1825       // 'sibNode' and 'dstNode'.
1826       if (mdg->hasDependencePath(sibNode->id, dstNode->id) ||
1827           mdg->hasDependencePath(dstNode->id, sibNode->id))
1828         return false;
1829       // Skip sib node if it loads to (and stores from) the same memref on
1830       // which it also has an input dependence edge.
1831       DenseSet<Value> loadAndStoreMemrefSet;
1832       sibNode->getLoadAndStoreMemrefSet(&loadAndStoreMemrefSet);
1833       if (llvm::any_of(loadAndStoreMemrefSet, [=](Value memref) {
1834             return mdg->getIncomingMemRefAccesses(sibNode->id, memref) > 0;
1835           }))
1836         return false;
1837 
1838       // Check that all stores are to the same memref.
1839       DenseSet<Value> storeMemrefs;
1840       for (auto *storeOpInst : sibNode->stores) {
1841         storeMemrefs.insert(
1842             cast<AffineWriteOpInterface>(storeOpInst).getMemRef());
1843       }
1844       if (storeMemrefs.size() != 1)
1845         return false;
1846 
1847       // Skip if a memref value in one node is used by a non-affine memref
1848       // access that lies between 'dstNode' and 'sibNode'.
1849       if (hasNonAffineUsersOnThePath(dstNode->id, sibNode->id, mdg) ||
1850           hasNonAffineUsersOnThePath(sibNode->id, dstNode->id, mdg))
1851         return false;
1852       return true;
1853     };
1854 
1855     // Search for siblings which load the same memref function argument.
1856     auto fn = dstNode->op->getParentOfType<func::FuncOp>();
1857     for (unsigned i = 0, e = fn.getNumArguments(); i != e; ++i) {
1858       for (auto *user : fn.getArgument(i).getUsers()) {
1859         if (auto loadOp = dyn_cast<AffineReadOpInterface>(user)) {
1860           // Gather loops surrounding 'use'.
1861           SmallVector<AffineForOp, 4> loops;
1862           getLoopIVs(*user, &loops);
1863           // Skip 'use' if it is not within a loop nest.
1864           if (loops.empty())
1865             continue;
1866           Node *sibNode = mdg->getForOpNode(loops[0]);
1867           assert(sibNode != nullptr);
1868           // Skip 'use' if it not a sibling to 'dstNode'.
1869           if (sibNode->id == dstNode->id)
1870             continue;
1871           // Skip 'use' if it has been visited.
1872           if (visitedSibNodeIds->count(sibNode->id) > 0)
1873             continue;
1874           // Skip 'use' if it does not load from the same memref as 'dstNode'.
1875           auto memref = loadOp.getMemRef();
1876           if (dstNode->getLoadOpCount(memref) == 0)
1877             continue;
1878           // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1879           if (canFuseWithSibNode(sibNode, memref)) {
1880             visitedSibNodeIds->insert(sibNode->id);
1881             idAndMemrefToFuse->first = sibNode->id;
1882             idAndMemrefToFuse->second = memref;
1883             return true;
1884           }
1885         }
1886       }
1887     }
1888 
1889     // Search for siblings by following edges through an intermediate src node.
1890     // Collect candidate 'dstNode' input edges in 'inEdges'.
1891     SmallVector<MemRefDependenceGraph::Edge, 2> inEdges;
1892     mdg->forEachMemRefInputEdge(
1893         dstNode->id, [&](MemRefDependenceGraph::Edge inEdge) {
1894           // Add 'inEdge' if it is a read-after-write dependence.
1895           if (dstNode->getLoadOpCount(inEdge.value) > 0 &&
1896               mdg->getNode(inEdge.id)->getStoreOpCount(inEdge.value) > 0)
1897             inEdges.push_back(inEdge);
1898         });
1899 
1900     // Search for sibling nodes to fuse by visiting output edges from each input
1901     // edge in 'inEdges'.
1902     for (auto &inEdge : inEdges) {
1903       // Collect candidate output edges from each node 'inEdge.id' in 'inEdges'.
1904       SmallVector<MemRefDependenceGraph::Edge, 2> outEdges;
1905       mdg->forEachMemRefOutputEdge(
1906           inEdge.id, [&](MemRefDependenceGraph::Edge outEdge) {
1907             unsigned sibNodeId = outEdge.id;
1908             if (visitedSibNodeIds->count(sibNodeId) > 0)
1909               return;
1910             // Skip output edge if not a sibling using the same memref.
1911             if (outEdge.id == dstNode->id || outEdge.value != inEdge.value)
1912               return;
1913             auto *sibNode = mdg->getNode(sibNodeId);
1914             if (!isa<AffineForOp>(sibNode->op))
1915               return;
1916             // Check if 'sibNode/dstNode' can be input-reuse fused on 'memref'.
1917             if (canFuseWithSibNode(sibNode, outEdge.value)) {
1918               // Add candidate 'outEdge' to sibling node.
1919               outEdges.push_back(outEdge);
1920             }
1921           });
1922 
1923       // Add first candidate if any were returned.
1924       if (!outEdges.empty()) {
1925         visitedSibNodeIds->insert(outEdges[0].id);
1926         idAndMemrefToFuse->first = outEdges[0].id;
1927         idAndMemrefToFuse->second = outEdges[0].value;
1928         return true;
1929       }
1930     }
1931     return false;
1932   }
1933 
1934   /// Update data dependence graph state to reflect sibling fusion of 'sibNode'
1935   /// into 'dstNode'.
1936   void updateStateAfterSiblingFusion(Node *sibNode, Node *dstNode) {
1937     // Update 'sibNode' and 'dstNode' input/output edges to reflect fusion.
1938     mdg->updateEdges(sibNode->id, dstNode->id);
1939 
1940     // Collect dst loop stats after memref privatization transformation.
1941     auto dstForInst = cast<AffineForOp>(dstNode->op);
1942     LoopNestStateCollector dstLoopCollector;
1943     dstLoopCollector.collect(dstForInst.getOperation());
1944     // Clear and add back loads and stores
1945     mdg->clearNodeLoadAndStores(dstNode->id);
1946     mdg->addToNode(dstNode->id, dstLoopCollector.loadOpInsts,
1947                    dstLoopCollector.storeOpInsts);
1948     // Remove old sibling loop nest if it no longer has outgoing dependence
1949     // edges, and it does not write to a memref which escapes the
1950     // function.
1951     if (mdg->getOutEdgeCount(sibNode->id) == 0) {
1952       Operation *op = sibNode->op;
1953       mdg->removeNode(sibNode->id);
1954       op->erase();
1955     }
1956   }
1957 
1958   // Clean up any allocs with no users.
1959   void eraseUnusedMemRefAllocations() {
1960     for (auto &pair : mdg->memrefEdgeCount) {
1961       if (pair.second > 0)
1962         continue;
1963       auto memref = pair.first;
1964       // Skip if there exist other uses (return operation or function calls).
1965       if (!memref.use_empty())
1966         continue;
1967       // Use list expected to match the dep graph info.
1968       auto *op = memref.getDefiningOp();
1969       if (isa_and_nonnull<memref::AllocOp>(op))
1970         op->erase();
1971     }
1972   }
1973 };
1974 
1975 } // namespace
1976 
1977 void LoopFusion::runOnOperation() {
1978   MemRefDependenceGraph g;
1979   if (!g.init(getOperation()))
1980     return;
1981 
1982   Optional<unsigned> fastMemorySpaceOpt;
1983   if (fastMemorySpace.hasValue())
1984     fastMemorySpaceOpt = fastMemorySpace;
1985   unsigned localBufSizeThresholdBytes = localBufSizeThreshold * 1024;
1986   GreedyFusion fusion(&g, localBufSizeThresholdBytes, fastMemorySpaceOpt,
1987                       maximalFusion, computeToleranceThreshold);
1988 
1989   if (affineFusionMode == FusionMode::ProducerConsumer)
1990     fusion.runProducerConsumerFusionOnly();
1991   else if (affineFusionMode == FusionMode::Sibling)
1992     fusion.runSiblingFusionOnly();
1993   else
1994     fusion.runGreedyFusion();
1995 }
1996