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