1 //===- Fusion.cpp - Implementation of linalg 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 the linalg dialect Fusion pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
14 #include "mlir/Dialect/Affine/IR/AffineOps.h"
15 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
18 #include "mlir/Dialect/Linalg/Passes.h"
19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
20 #include "mlir/Dialect/Linalg/Utils/Utils.h"
21 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
22 #include "mlir/Dialect/Tensor/IR/Tensor.h"
23 #include "mlir/IR/AffineExpr.h"
24 #include "mlir/IR/AffineMap.h"
25 #include "mlir/IR/Dominance.h"
26 #include "mlir/Support/LLVM.h"
27 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
28 #include "mlir/Transforms/RegionUtils.h"
29 #include "llvm/ADT/MapVector.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 
33 #include <set>
34 
35 #define DEBUG_TYPE "linalg-fusion"
36 
37 using namespace mlir;
38 using namespace mlir::edsc;
39 using namespace mlir::edsc::intrinsics;
40 using namespace mlir::linalg;
41 
42 using llvm::dbgs;
43 
44 /// Implements a simple high-level fusion pass on linalg structured operations.
45 ///
46 /// In each block, linalg ops are processed in reverse textual order.
47 /// Given a linalg op `O`, fusion occurs by:
48 ///   1. inspecting the linalg ops that write into the views read by `O`. There
49 ///      are 2 cases:
50 ///      a) buffer case: use the SSA value of the views and a simple alias
51 ///         analysis on subview ops to determine producer-consumer dependences;
52 ///      b) tensor case: use SSA use-def chains on subtensor ops;
53 ///   2. greedily fuse the linalg ops that produce the subview/subtensor.
54 ///   3. inspect the fused ops and determine whether they have other remaining
55 ///      LinalgOp uses. If not, then erase the original producing linalg op.
56 ///
57 /// More advanced use cases, analyses as well as profitability heuristics are
58 /// left for future work.
59 
60 // Fill `offset`, `sizes` and `strides` used to iterate over the shape indexed
61 // by `permutationMap`.
62 static void inferShapeComponents(AffineMap permutationMap,
63                                  ArrayRef<Range> loopRanges,
64                                  SmallVectorImpl<Value> &offsets,
65                                  SmallVectorImpl<Value> &sizes,
66                                  SmallVectorImpl<Value> &strides) {
67   assert(permutationMap.isProjectedPermutation() &&
68          "expected some subset of a permutation map");
69   SmallVector<Range, 4> shapeRanges(permutationMap.getNumResults());
70   unsigned idx = 0;
71   for (AffineExpr e : permutationMap.getResults()) {
72     // loopToOperandRangesMaps are permutations-only, just swap indices.
73     unsigned loopPos = e.cast<AffineDimExpr>().getPosition();
74     shapeRanges[idx++] = loopRanges[loopPos];
75   }
76   // Construct a new subshape for the tile.
77   unsigned rank = shapeRanges.size();
78   offsets.reserve(rank);
79   sizes.reserve(rank);
80   strides.reserve(rank);
81   for (auto r : shapeRanges) {
82     offsets.push_back(r.offset);
83     sizes.push_back(r.size);
84     strides.push_back(r.stride);
85   }
86 }
87 
88 // Return a cloned version of `op` that operates on `loopRanges`, assumed to be
89 // a subset of the original loop ranges of `op`.
90 // This is achieved by applying the `loopToOperandRangesMaps` permutation maps
91 // to the `loopRanges` in order to obtain view ranges.
92 static LinalgOp cloneWithLoopRanges(OpBuilder &b, Location loc, LinalgOp op,
93                                     ArrayRef<Range> loopRanges) {
94   SmallVector<Value, 8> clonedShapes;
95   clonedShapes.reserve(op.getNumShapedOperands());
96 
97   // Iterate over the shape operands in order.
98   // Extract the subranges from the linearized ranges.
99   for (auto en : llvm::enumerate(op.getShapedOperands())) {
100     unsigned shapedOperandIdx = en.index();
101     AffineMap map = op.getIndexingMap(shapedOperandIdx);
102     LLVM_DEBUG(llvm::dbgs() << "shapedOperandIdx: " << shapedOperandIdx
103                             << " with indexingMap: " << map << "\n");
104     SmallVector<Value, 4> offsets, sizes, strides;
105     inferShapeComponents(map, loopRanges, offsets, sizes, strides);
106     Value shape = en.value();
107     Value sub = shape.getType().isa<MemRefType>()
108                     ? b.create<SubViewOp>(loc, shape, offsets, sizes, strides)
109                           .getResult()
110                     : b.create<SubTensorOp>(loc, shape, offsets, sizes, strides)
111                           .getResult();
112     clonedShapes.push_back(sub);
113   }
114   // Append the other operands.
115   auto operands = op.getAssumedNonShapedOperands();
116   clonedShapes.append(operands.begin(), operands.end());
117 
118   // Iterate over the results in order.
119   // Extract the subtensor type from the linearized range.
120   // Since we do not enforce any canonicalizations on the fly, this is always
121   // fully dynamic at construction time.
122   SmallVector<Type, 4> resultTypes;
123   resultTypes.reserve(op->getNumResults());
124   for (RankedTensorType t : op.getOutputTensorTypes()) {
125     unsigned rank = t.getRank();
126     SmallVector<int64_t, 4> staticOffsetsVector(
127         rank, ShapedType::kDynamicStrideOrOffset);
128     SmallVector<int64_t, 4> staticSizesVector(rank, ShapedType::kDynamicSize);
129     SmallVector<int64_t, 4> staticStridesVector(
130         rank, ShapedType::kDynamicStrideOrOffset);
131     resultTypes.push_back(SubTensorOp::inferResultType(
132         t.cast<RankedTensorType>(), staticOffsetsVector, staticSizesVector,
133         staticStridesVector));
134   }
135 
136   Operation *clonedOp = op.clone(b, loc, resultTypes, clonedShapes);
137   // When the producer is an IndexedGenericOp, we have to transform its block
138   // IV arguments according to the tiling of the consumer, i.e. offset them by
139   // the values computed in `loopRanges`.
140   if (auto indexedGenericOp = dyn_cast<IndexedGenericOp>(clonedOp)) {
141     auto &block = indexedGenericOp.region().front();
142     OpBuilder::InsertionGuard g(b);
143     b.setInsertionPointToStart(&block);
144     for (unsigned i = 0, e = indexedGenericOp.getNumLoops(); i < e; ++i) {
145       Value oldIndex = block.getArgument(i);
146       // TODO: replace by an affine_apply.
147       AddIOp newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex,
148                                          loopRanges[i].offset);
149       oldIndex.replaceAllUsesExcept(newIndex,
150                                     SmallPtrSet<Operation *, 1>{newIndex});
151     }
152   }
153 
154   return clonedOp;
155 }
156 
157 struct ShapeDimension {
158   Value shape;
159   unsigned dimension;
160 };
161 
162 // Given an `op`, returns the first (`shape`, `dimension`) pair that identifies
163 // the loop range at `loopDepth`. The semantics of the loopToOperandRangesMaps
164 // guarantees at least one such dimension is found. If multiple candidates exist
165 // they must agree by construction (i.e. have the same size) and we just return
166 // the first one.
167 static ShapeDimension
168 getShapeDefiningLoopRange(LinalgOp op, unsigned loopDepth,
169                           bool fromSubViewOpOnly = false) {
170   auto maps = op.indexing_maps();
171   // Iterate over the inputs and outputs in order.
172   // Extract the subranges from the linearized ranges.
173   for (auto en : llvm::enumerate(op.getShapedOperands())) {
174     // The method `getRangeFromOperandShape` requires using SubViewOp or
175     // SubTensorOps. If the value isnt defined from there continue.
176     // todo: The method should be adapted to get the values from
177     // `ViewInterface`. The interface needs a `getOrCreateRanges` method which
178     // currently returns a `linalg.range`. The fix here is to move this op to
179     // `std` dialect and add the method to `ViewInterface`.
180     if (fromSubViewOpOnly &&
181         !isa_and_nonnull<SubViewOp, SubTensorOp>(en.value().getDefiningOp()))
182       continue;
183 
184     unsigned idx = en.index();
185     auto map = maps[idx].cast<AffineMapAttr>().getValue();
186     LLVM_DEBUG(llvm::dbgs()
187                << "getShapeDefiningLoopRange I/O idx: " << idx << "\n");
188     LLVM_DEBUG(llvm::dbgs()
189                << "getShapeDefiningLoopRange map: " << map << "\n");
190     Value shape = en.value();
191     SmallVector<Value, 8> shapeRanges(map.getNumResults(), nullptr);
192     for (auto en2 : llvm::enumerate(map.getResults())) {
193       auto dimExpr = en2.value().dyn_cast<AffineDimExpr>();
194       if (!dimExpr)
195         continue;
196       if (loopDepth == en2.value().cast<AffineDimExpr>().getPosition()) {
197         LLVM_DEBUG(llvm::dbgs() << "getShapeDefiningLoopRange loopDepth: "
198                                 << loopDepth << "\n");
199         LLVM_DEBUG(llvm::dbgs()
200                    << "getShapeDefiningLoopRange shape: " << shape << "\n");
201         return ShapeDimension{shape, static_cast<unsigned>(en2.index())};
202       }
203     }
204   }
205   llvm_unreachable("Expect to be able to extract a shape defining loop range");
206 }
207 
208 /// Fuse the producer by cloning the `producer`. The `fusedLoopsAndRanges`
209 /// provides the loop range information for the fused loops. The rest are
210 /// obtained from the producer itself, since they are not tiled + fused.
211 static LinalgOp fuse(OpBuilder &b, LinalgOp producer,
212                      const DenseMap<unsigned, Range> &fusedLoopsAndRanges) {
213 
214   unsigned nPar = producer.getNumParallelLoops();
215   unsigned nRed = producer.getNumReductionLoops();
216   unsigned nWin = producer.getNumWindowLoops();
217   SmallVector<Range, 8> loopRanges(nPar + nRed + nWin);
218   for (auto fusedLoops : fusedLoopsAndRanges)
219     loopRanges[fusedLoops.first] = fusedLoops.second;
220 
221   // Iterate over all dimensions. For the dimensions not identified by the
222   // producer map for `producerIdx`, we need to explicitly compute the shape
223   // that defines the loop ranges using the `producer`.
224   for (unsigned i = 0, nLoops = loopRanges.size(); i < nLoops; ++i) {
225     if (loopRanges[i].offset)
226       LLVM_DEBUG(llvm::dbgs()
227                  << "existing LoopRange: " << loopRanges[i] << "\n");
228     else {
229       auto shapeDim = getShapeDefiningLoopRange(producer, i);
230       loopRanges[i] = Range{std_constant_index(0),
231                             std_dim(shapeDim.shape, shapeDim.dimension),
232                             std_constant_index(1)};
233       LLVM_DEBUG(llvm::dbgs() << "new LoopRange: " << loopRanges[i] << "\n");
234     }
235   }
236 
237   return cloneWithLoopRanges(b, producer.getLoc(), producer, loopRanges);
238 }
239 
240 /// Get the loop range for a dimension `dim` based on the `shapedOperand`. It is
241 /// expected to be defined by a subview op or a subtensor op.
242 static Range getRangeFromOperandShape(OpBuilder &b, Location loc,
243                                       Value shapedOperand, unsigned dim) {
244   Operation *shapeProducingOp = shapedOperand.getDefiningOp();
245   if (auto subViewOp = dyn_cast<SubViewOp>(shapeProducingOp))
246     return subViewOp.getOrCreateRanges(b, loc)[dim];
247   if (auto subTensorOp = dyn_cast<SubTensorOp>(shapeProducingOp))
248     return subTensorOp.getOrCreateRanges(b, loc)[dim];
249   llvm_unreachable("SubviewOp or SubTensorOp expected");
250 }
251 
252 /// Fuses the producer of `producerIdx` into the loop immediately enclosing
253 /// `consumer`. This is achieved by "recomputing" the `producer` at the time it
254 /// is needed just before the `consumer.
255 ///
256 /// Depending on the type of `consumer.getShapedOperand(consumerIdx)`, there are
257 /// 2 cases:
258 ///   1. Buffer case: `producerIdx` is the index of the buffer in
259 ///      `producer.getOutputBuffers()`.
260 ///   2. Tensor case: `producerIdx` is the index of the tensor in
261 ///      `producer.getResults()`.
262 static LinalgOp fuse(OpBuilder &b, LinalgOp producerOp, AffineMap producerMap,
263                      OpOperand &consumerOpOperand) {
264   LLVM_DEBUG(llvm::dbgs() << "Producer map: " << producerMap << "\n");
265   DenseMap<unsigned, Range> fusedLoopsAndRanges;
266   Value shapedOperand = consumerOpOperand.get();
267   for (auto en : llvm::enumerate(producerMap.getResults())) {
268     unsigned posInProducerLoop = en.value().cast<AffineDimExpr>().getPosition();
269     fusedLoopsAndRanges[posInProducerLoop] = getRangeFromOperandShape(
270         b, consumerOpOperand.getOwner()->getLoc(), shapedOperand, en.index());
271   }
272   return fuse(b, producerOp, fusedLoopsAndRanges);
273 }
274 
275 // Encode structural fusion safety preconditions.
276 // Some of these will be lifted in the future with better analysis.
277 static bool isStructurallyFusableProducer(LinalgOp producer, Value consumedView,
278                                           LinalgOp consumer) {
279   assert(producer.hasBufferSemantics() &&
280          "expected linalg op with buffer semantics");
281   assert(consumer.hasBufferSemantics() &&
282          "expected linalg op with buffer semantics");
283   if (producer.getNumOutputs() != 1) {
284     LLVM_DEBUG(llvm::dbgs() << "\nNot structurally fusable (multi-output)");
285     return false;
286   }
287   // Only fuse when the producer block dominates.
288   DominanceInfo dom(producer.getOperation());
289   if (!dom.dominates(producer->getBlock(), consumer->getBlock())) {
290     LLVM_DEBUG(
291         llvm::dbgs()
292         << "\nNot structurally fusable (producer block does not dominate)");
293     return false;
294   }
295   return true;
296 }
297 
298 bool mlir::linalg::isProducerLastWriteOfView(const LinalgDependenceGraph &graph,
299                                              LinalgOp consumer,
300                                              Value consumedView,
301                                              LinalgOp producer) {
302   assert(producer.hasBufferSemantics() &&
303          "expected linalg op with buffer semantics");
304   assert(consumer.hasBufferSemantics() &&
305          "expected linalg op with buffer semantics");
306   // Make some simple structural checks that alleviate the need for more
307   // complex analyses.
308   if (!isStructurallyFusableProducer(producer, consumedView, consumer)) {
309     LLVM_DEBUG(llvm::dbgs() << "\n***Not static last write due to structure:\t"
310                             << *producer.getOperation());
311     return false;
312   }
313   // Check for any interleaved write to consumedView.
314   if (!graph.findCoveringWrites(producer, consumer, consumedView).empty()) {
315     LLVM_DEBUG(llvm::dbgs() << "\n***Not fusable due to interleaved write:\t"
316                             << *producer.getOperation());
317     return false;
318   }
319   return true;
320 }
321 
322 bool mlir::linalg::isFusableInto(const LinalgDependenceGraph &graph,
323                                  LinalgOp consumer, Value consumedView,
324                                  LinalgOp producer) {
325   assert(producer.hasBufferSemantics() &&
326          "expected linalg op with buffer semantics");
327   assert(consumer.hasBufferSemantics() &&
328          "expected linalg op with buffer semantics");
329   if (!isProducerLastWriteOfView(graph, consumer, consumedView, producer))
330     return false;
331   // Check for any fusion-preventing dependence to any shape read/written that
332   // would violate dependences.
333   if (!graph.findCoveringDependences(producer, consumer).empty()) {
334     LLVM_DEBUG(llvm::dbgs()
335                << "\n***Not fusable due to an interleaved dependence:\t"
336                << *producer.getOperation());
337     return false;
338   }
339   if (auto convOp = dyn_cast<linalg::ConvOp>(producer.getOperation())) {
340     // TODO: add a level of indirection to linalg.generic.
341     if (convOp.padding())
342       return false;
343   }
344   if (auto convOp = dyn_cast<linalg::ConvOp>(consumer.getOperation())) {
345     // TODO: add a level of indirection to linalg.generic.
346     if (convOp.padding())
347       return false;
348   }
349   return true;
350 }
351 
352 /// For `consumer` with buffer semantics, find the Linalg operation on buffers
353 /// that is the last writer of `consumerOpOperand`. For now the fusable
354 /// dependence is returned as an instance of the `dependenceGraph`.
355 static Optional<LinalgDependenceGraph::LinalgDependenceGraphElem>
356 findFusableProducer(OpOperand &consumerOpOperand,
357                     const LinalgDependenceGraph &dependenceGraph) {
358   LinalgOp consumerOp = dyn_cast<LinalgOp>(consumerOpOperand.getOwner());
359   if (!consumerOp)
360     return {};
361 
362   // Only consider RAW and WAW atm.
363   for (auto depType : {
364            LinalgDependenceGraph::DependenceType::RAW,
365            LinalgDependenceGraph::DependenceType::WAW,
366        }) {
367     for (auto dependence : llvm::make_filter_range(
368              dependenceGraph.getDependencesInto(consumerOp, depType),
369              [&](LinalgDependenceGraph::LinalgDependenceGraphElem elem) {
370                Value v = elem.getIndexingValue();
371                Optional<unsigned> operandNum =
372                    elem.getIndexingOpViewOperandNum();
373                return isa<LinalgOp>(elem.getDependentOp()) &&
374                       v == consumerOpOperand.get() && operandNum &&
375                       operandNum.getValue() ==
376                           consumerOpOperand.getOperandNumber();
377              })) {
378       // Consumer consumes this view, `isStructurallyFusableProducer` also
379       // checks whether it is a strict subview of the producer view.
380       auto producer = cast<LinalgOp>(dependence.getDependentOp());
381       LLVM_DEBUG(llvm::dbgs()
382                  << "\n"
383                  << LinalgDependenceGraph::getDependenceTypeStr(depType)
384                  << "producer: " << *dependence.getDependentOp()
385                  << " view: " << dependence.getDependentValue() << "\n");
386 
387       // If the producer and consumer have tensor semantics, the only dependence
388       // between them is through a RAW dependence and they are fusable by
389       // construction. For buffer semantics need additional checks.
390       if (producer.hasBufferSemantics() && consumerOp.hasBufferSemantics() &&
391           isFusableInto(dependenceGraph, consumerOp, consumerOpOperand.get(),
392                         producer))
393         return dependence;
394       if (producer.hasTensorSemantics() && consumerOp.hasTensorSemantics()) {
395         assert(dependence.dependenceType ==
396                LinalgDependenceGraph::DependenceType::RAW);
397         return dependence;
398       }
399     }
400   }
401   return {};
402 }
403 
404 Optional<FusionInfo>
405 mlir::linalg::fuseProducerOfBuffer(OpBuilder &b, OpOperand &consumerOpOperand,
406                                    const LinalgDependenceGraph &graph) {
407   Optional<LinalgDependenceGraph::LinalgDependenceGraphElem> fusableDependence =
408       findFusableProducer(consumerOpOperand, graph);
409   if (!fusableDependence)
410     return llvm::None;
411 
412   LinalgOp producerOp = dyn_cast<LinalgOp>(fusableDependence->getDependentOp());
413   if (!producerOp)
414     return llvm::None;
415 
416   // If producer is already in the same block as consumer, we are done.
417   if (consumerOpOperand.get().getParentBlock() ==
418       fusableDependence->getDependentValue().getParentBlock())
419     return llvm::None;
420 
421   Optional<AffineMap> producerMap =
422       fusableDependence->getDependentOpViewIndexingMap();
423   if (!producerMap)
424     return llvm::None;
425 
426   // Must be a subview or a slice to guarantee there are loops we can fuse
427   // into.
428   auto subView = consumerOpOperand.get().getDefiningOp<SubViewOp>();
429   auto slice = consumerOpOperand.get().getDefiningOp<SliceOp>();
430   if (!subView && !slice) {
431     LLVM_DEBUG(llvm::dbgs() << "\nNot fusable (not a subview or slice)");
432     return llvm::None;
433   }
434 
435   // Fuse `producer` just before `consumer`.
436   OpBuilder::InsertionGuard g(b);
437   b.setInsertionPoint(consumerOpOperand.getOwner());
438   ScopedContext scope(b, consumerOpOperand.getOwner()->getLoc());
439   LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: "
440                           << *consumerOpOperand.getOwner() << "\n");
441 
442   auto fusedProducer = fuse(b, producerOp, *producerMap, consumerOpOperand);
443   return FusionInfo{producerOp, fusedProducer};
444 }
445 
446 /// Walk back use-def chain through scf::For yields.
447 /// Sets `producer` and `outputIndex` if it finds a producer LinalgOp
448 
449 // TODO(ravishankarm, ntv): This can be moved into the dependence graphs
450 // dependence tracking since the dependence tracking is similar to what is done
451 // w.r.t to buffers.
452 static void getProducerOfTensor(Value tensor, OpResult &opResult) {
453   if (!tensor.getType().isa<RankedTensorType>())
454     return;
455 
456   while (true) {
457     LLVM_DEBUG(llvm::dbgs() << "\ngetProducerOfTensor: " << tensor);
458     if (auto linalgOp = tensor.getDefiningOp<LinalgOp>()) {
459       opResult = tensor.cast<OpResult>();
460       return;
461     }
462     if (auto subTensorOp = tensor.getDefiningOp<SubTensorOp>()) {
463       tensor = subTensorOp.source();
464       continue;
465     }
466     if (auto blockArg = tensor.dyn_cast<BlockArgument>()) {
467       if (auto forOp = blockArg.getDefiningOp<scf::ForOp>()) {
468         tensor = *(forOp.getIterOperands().begin() + blockArg.getArgNumber());
469         continue;
470       }
471     }
472     return;
473   }
474 }
475 
476 Optional<FusionInfo>
477 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpOperand &consumerOpOperand) {
478   Value inputTensor = consumerOpOperand.get();
479   OpResult producerOpResult;
480   getProducerOfTensor(inputTensor, producerOpResult);
481   if (!producerOpResult) {
482     LLVM_DEBUG(llvm::dbgs() << "\nUnable to find producer");
483     return {};
484   }
485   return fuseProducerOfTensor(b, producerOpResult, consumerOpOperand);
486 }
487 
488 Optional<FusionInfo>
489 mlir::linalg::fuseProducerOfTensor(OpBuilder &b, OpResult producerOpResult,
490                                    OpOperand &consumerOpOperand) {
491   auto producerOp = dyn_cast<LinalgOp>(producerOpResult.getOwner());
492   if (!producerOp)
493     return llvm::None;
494 
495   LinalgOp consumerOp = dyn_cast<LinalgOp>(consumerOpOperand.getOwner());
496   if (!consumerOp)
497     return llvm::None;
498 
499   Value inputTensor = consumerOpOperand.get();
500 
501   // Must be a subtensor to guarantee there are loops we can fuse into.
502   auto subTensor = inputTensor.getDefiningOp<SubTensorOp>();
503   if (!subTensor) {
504     LLVM_DEBUG(llvm::dbgs()
505                << "\nNot fusable, not a subtensor: " << inputTensor);
506     return {};
507   }
508 
509   // If producer is already in the same block as consumer, we are done.
510   if (consumerOpOperand.get().getParentBlock() ==
511       producerOpResult.getParentBlock())
512     return {};
513 
514   // Insert fused `producer` just before `consumer`.
515   OpBuilder::InsertionGuard g(b);
516   b.setInsertionPoint(consumerOp);
517   ScopedContext scope(b, consumerOp->getLoc());
518   LLVM_DEBUG(llvm::dbgs() << "Fuse into consumer: " << *consumerOp << "\n");
519   LinalgOp fusedProducer =
520       fuse(b, producerOp,
521            producerOp.getOutputIndexingMap(producerOpResult.getResultNumber()),
522            consumerOpOperand);
523 
524   // Replace use.
525   // Canonicalizations are not guaranteed to have happened before constructing
526   // `fusedProducer`. In the tensor case this can result in temporary type
527   // mismatches. Insert a `tensor.cast` op to propagate the transformation
528   // invariant that types are compatible.
529   Value def = fusedProducer->getResult(producerOpResult.getResultNumber());
530   Type consumerType = consumerOpOperand.get().getType();
531   if (consumerType != def.getType())
532     def = b.create<tensor::CastOp>(fusedProducer.getLoc(), consumerType, def);
533   consumerOpOperand.set(def);
534   return FusionInfo{cast<LinalgOp>(producerOpResult.getOwner()), fusedProducer};
535 }
536 
537 /// Prune all dimensions that are of reduction iterator type from `map`.
538 static AffineMap pruneReductionDimsFromMap(ArrayRef<Attribute> iteratorTypes,
539                                            AffineMap map) {
540   SmallVector<unsigned, 2> projectedDims;
541   for (auto attr : llvm::enumerate(iteratorTypes)) {
542     if (!isParallelIterator(attr.value()))
543       projectedDims.push_back(attr.index());
544   }
545   return getProjectedMap(map, projectedDims);
546 }
547 
548 /// Returns the mapping from iterations in the consumer that write to the same
549 /// location as the iterations in the producer. To do so use
550 /// - indexing map of the fused view in the consumer : consumerIndexMap
551 /// - indexing map of the fused view in the producer : producerIndexMap
552 ///     consumerLoopToProducerLoop =
553 ///       inverse(producerIndexMap).compose(consumerIndexMap)
554 static Optional<AffineMap> getConsumerLoopToProducerLoopMap(
555     LinalgDependenceGraph::LinalgDependenceGraphElem dependence) {
556   auto producer = dyn_cast<LinalgOp>(dependence.getDependentOp());
557   if (!producer)
558     return None;
559 
560   Optional<AffineMap> producerIndexingMap =
561       dependence.getDependentOpViewIndexingMap();
562   Optional<AffineMap> consumerIndexingMap =
563       dependence.getIndexingOpViewIndexingMap();
564   if (!producerIndexingMap || !consumerIndexingMap)
565     return None;
566 
567   AffineMap prunedProducerIndexingMap = pruneReductionDimsFromMap(
568       producer.iterator_types().getValue(), *producerIndexingMap);
569   if (!prunedProducerIndexingMap.isPermutation())
570     return None;
571 
572   if (consumerIndexingMap->getNumResults() !=
573       prunedProducerIndexingMap.getNumResults())
574     return None;
575 
576   LLVM_DEBUG({
577     llvm::dbgs() << "\t producerMap : ";
578     producerIndexingMap->print(llvm::dbgs());
579     llvm::dbgs() << "  pruned : ";
580     prunedProducerIndexingMap.print(llvm::dbgs());
581     llvm::dbgs() << "\n";
582     llvm::dbgs() << "\t consumerMap : ";
583     consumerIndexingMap->print(llvm::dbgs());
584     llvm::dbgs() << "\n";
585   });
586 
587   AffineMap invProducerIndexMap = inversePermutation(prunedProducerIndexingMap);
588   if (!invProducerIndexMap)
589     return None;
590 
591   return invProducerIndexMap.compose(*consumerIndexingMap);
592 }
593 
594 /// Given a projected permutation `map`, returns true if the map changes the
595 /// order in which the fused loop dimension appear.
596 static bool doesTransposeAccess(AffineMap map,
597                                 const std::set<unsigned> &fusableLoops) {
598   Optional<unsigned> lastFusableLoop;
599   for (unsigned pos : llvm::map_range(map.getResults(), [](AffineExpr expr) {
600          return expr.cast<AffineDimExpr>().getPosition();
601        })) {
602     if (!fusableLoops.count(pos))
603       continue;
604     if (!lastFusableLoop) {
605       lastFusableLoop = pos;
606       continue;
607     }
608     if (pos <= lastFusableLoop.getValue())
609       return true;
610     lastFusableLoop = pos;
611   }
612   return false;
613 }
614 
615 /// Returns the positions of the loop in `op` that can be tiled based on the
616 /// operations that are to be fused with it. For example, in a
617 ///
618 ///   linalg.matmul ins(%a, %b : ...) outs(%c : ...)
619 ///
620 /// if the producer of %a needs to be fused with this op, only the `i` loop of
621 /// the matmul can be tiled while fusing. If producer of %a, and %b are to be
622 /// fused, then no loops can be tiled while fusing. The conditions used are:
623 /// 1. Only parallel loops can be used for tile + fuse. Find the number of
624 ///    common outer parallel loops between the op and its producers being fused.
625 /// 2. Of the parallel loops only some can be fused. Only those loops can be
626 ///    fused such where the fusable loops iteration space only touches one tile
627 ///    of the fused operation. This is because the producer (which is writing
628 ///    the fused subview) has update semantics.
629 ///
630 /// Since an inverse computation is needed, we need to consider the projection
631 /// of the producerIndexMap w.r.t the parallel loops.  The actual fusable loops
632 /// are the dimensions of the consumerLoopToProducerLoop map that correspond to
633 /// parallel loops and appear in the result of the map
634 ///
635 /// Example 1:
636 ///   linalg.fill(%c, %cst)
637 ///   linalg.matmul ins(%a, %b) outs(%c)
638 ///     Number of parallel loops : 2
639 ///     producerIndexMap = affine_map<(i, j) ->(i , j)>
640 ///     consumerIndexMap = affine_map<(i, j, k) -> (i, j)>
641 ///     consumerLoopToProducerLoop = affine_map<(i, j, k) -> (i, j)>
642 ///     Fused dimensions : i, j
643 ///
644 /// Example 2:
645 ///   linalg.matmul ins(%a, %b) outs(%c)
646 ///   linalg.generic {indexing_maps = [affine_map<(i, j) -> (j, i)>, ...
647 ///                   iterator_types = ["parallel", "parallel"]}
648 ///     ins(%c) ...
649 ///
650 ///     Number of parallel loops = 2:
651 ///     producerIndexMap (projected to parallel loops) =
652 ///       affine_map<(i, j) -> (i, j)>
653 ///     consumerLoopToProducerLoop2 = affine_map<(i, j) -> (j, i)>
654 ///     Fused dimensions : i, j
655 ///
656 /// Example 3:
657 ///   linalg.copy(%s, %b)
658 ///   linalg.matmul ins(%a, %b) outs(%c)
659 ///
660 ///   Number of parallel loops = 2
661 ///   produceIndexMap : affine_map<(i, j) -> (i, j)>
662 ///   consumerLoopToProduceLoops = affine_map<(i, j, k) -> (k, j)>
663 ///     submap with only parallel loops = affine_map<(i, j) -> (j)>
664 ///   Fused dimensions : j
665 static std::set<unsigned>
666 collectFusableLoops(ArrayRef<LinalgOp> ops,
667                     const FusableOpDependencesTy &fusableDependences) {
668   assert(!ops.empty());
669   auto getNumOuterParallelLoops = [](LinalgOp linalgOp) {
670     return linalgOp.iterator_types()
671         .getValue()
672         .take_while([](Attribute attr) -> bool {
673           return attr.cast<StringAttr>().getValue() ==
674                  getParallelIteratorTypeName();
675         })
676         .size();
677   };
678 
679   size_t numOuterParallelLoops = getNumOuterParallelLoops(ops.back());
680   for (auto op : ops.drop_back()) {
681     numOuterParallelLoops =
682         std::min(numOuterParallelLoops, getNumOuterParallelLoops(op));
683   }
684 
685   std::set<unsigned> fusableLoops;
686   auto range = llvm::seq<unsigned>(0, numOuterParallelLoops);
687   fusableLoops.insert(range.begin(), range.end());
688 
689   for (auto op : reverse(ops)) {
690     for (auto dependence : fusableDependences.lookup(op)) {
691       LLVM_DEBUG({
692         llvm::dbgs() << "\t fusable :";
693         for (unsigned i : fusableLoops)
694           llvm::dbgs() << " " << i;
695         llvm::dbgs() << "\n";
696       });
697 
698       Optional<AffineMap> consumerLoopToProducerLoop =
699           getConsumerLoopToProducerLoopMap(dependence);
700       if (!consumerLoopToProducerLoop) {
701         op.emitRemark("failed to get map from consumer loop to producer loop");
702         return {};
703       }
704       // todo: This condition is only an implementation limitation. When fusing
705       // the operation, if the accesses in the producer/consumer are transposes
706       // of each other, the loop bounds for the tiled producer can be
707       // manipulated accordingly. This requires some additional bookkeeping in
708       // the implementation of tile+fuse that is deferred to later.
709       if (doesTransposeAccess(*consumerLoopToProducerLoop, fusableLoops)) {
710         op.emitRemark("unhandled fusion when fusion requires permutation");
711         return {};
712       }
713 
714       std::set<unsigned> candidates;
715       for (AffineExpr expr : consumerLoopToProducerLoop->getResults()) {
716         unsigned position = expr.cast<AffineDimExpr>().getPosition();
717         if (fusableLoops.count(position))
718           candidates.insert(position);
719       }
720       LLVM_DEBUG({
721         llvm::dbgs() << "\t candidates :";
722         for (unsigned i : candidates)
723           llvm::dbgs() << " " << i;
724         llvm::dbgs() << "\n";
725       });
726       if (candidates.empty())
727         return {};
728       std::swap(candidates, fusableLoops);
729     }
730   }
731 
732   return fusableLoops;
733 }
734 
735 // /// For `consumer` with tensor semantics, find the Linalg operation on
736 // tensors
737 // /// producer the operand at position `consumerIdx`. This is a simple use-def
738 // /// chain using the SSA value, but returned as an element of the
739 // /// `LinalgDependenceGraphElem` to use the same analysis for both tensors and
740 // /// buffers.
741 // static Optional<LinalgDependenceGraph::LinalgDependenceGraphElem>
742 // findFusableProducerForTensorOp(OpOperand &consumerOpOperand) {
743 //   // For now only looking for cases where the operand is produced by another
744 //   // Linalg structured operation.
745 //   LinalgOp consumer = cast<LinalgOp>(consumerOpOperand.getOwner());
746 //   if (!consumer || !consumer.hasTensorSemantics())
747 //     return llvm::None;
748 //   unsigned consumerIdx = consumerOpOperand.getOperandNumber();
749 //   Value value = consumerOpOperand.get();
750 //   if (auto linalgOp = value.getDefiningOp<LinalgOp>()) {
751 //     return LinalgDependenceGraph::LinalgDependenceGraphElem{
752 //         &(linalgOp
753 //               .getOutputOpOperands()[value.cast<OpResult>().getResultNumber()]),
754 //         &(consumer.getInputOpOperands()[consumerIdx]),
755 //         LinalgDependenceGraph::DependenceType::RAW};
756 //   }
757 //   return llvm::None;
758 // }
759 
760 // static Optional<LinalgDependenceGraph::LinalgDependenceGraphElem>
761 // findFusableProducer(OpOperand &consumerOpOperand,
762 //                     const LinalgDependenceGraph &dependenceGraph) {
763 //   LinalgOp consumer = cast<LinalgOp>(consumerOpOperand.getOwner());
764 //   if (!consumer)
765 //     return llvm::None;
766 //   if (consumer.hasBufferSemantics())
767 //     return findFusableProducerForBufferOp(consumerOpOperand,
768 //     dependenceGraph);
769 //   if (consumer.hasTensorSemantics())
770 //     return findFusableProducerForTensorOp(consumerOpOperand);
771 //   return llvm::None;
772 // }
773 
774 /// Find all dependences that are fusable.
775 FusableOpDependencesTy mlir::linalg::findAllFusableDependences(
776     ArrayRef<LinalgOp> ops, const LinalgDependenceGraph &dependenceGraph) {
777   FusableOpDependencesTy fusableDependences;
778   DenseMap<Operation *, SmallVector<AffineMap, 1>> fusedProducerIndexingMap;
779   for (LinalgOp op : reverse(ops)) {
780     for (OpOperand &opOperand : op.getShapedOpOperands()) {
781       Optional<LinalgDependenceGraph::LinalgDependenceGraphElem>
782           fusableDependence = findFusableProducer(opOperand, dependenceGraph);
783       if (!fusableDependence)
784         continue;
785       LinalgOp producerOp =
786           dyn_cast<LinalgOp>(fusableDependence->getDependentOp());
787       if (!producerOp)
788         continue;
789       // Do not fuse dependences that are to operations not in the same basic
790       // block. This avoid moving fused operations across loops that might
791       // themselves carry dependency making the fusion illegal.
792       if (producerOp->getBlock() != op->getBlock())
793         continue;
794 
795       // Make sure that the indexing map of the view used for fusion in the
796       // producer is a projected permutation.
797       Optional<AffineMap> producerMap =
798           fusableDependence->getDependentOpViewIndexingMap();
799       Optional<AffineMap> consumerMap =
800           fusableDependence->getIndexingOpViewIndexingMap();
801       assert(
802           consumerMap &&
803           "unable to find indexing map of operand/result of indexing OpView");
804       fusedProducerIndexingMap[producerOp.getOperation()].push_back(
805           *consumerMap);
806       if (!producerMap || !producerMap->isProjectedPermutation() ||
807           !consumerMap->isProjectedPermutation())
808         continue;
809 
810       fusableDependences[producerOp.getOperation()].push_back(
811           *fusableDependence);
812     }
813   }
814   // TODO: Currently fusion would not be legal if the fusable dependence is to
815   // the same producer but different indexing map in the consumer. Fix this, but
816   // in the meanwhile disallow such a fusion.
817   for (auto useIndexingMapsList : fusedProducerIndexingMap) {
818     AffineMap map1 = useIndexingMapsList.second.front();
819     for (AffineMap map2 :
820          ArrayRef<AffineMap>(useIndexingMapsList.second).drop_front()) {
821       if (map1 != map2) {
822         fusableDependences.erase(useIndexingMapsList.first);
823         break;
824       }
825     }
826   }
827   return fusableDependences;
828 }
829 
830 /// Tile the fused loops in the root operation, by setting the tile sizes for
831 /// all other loops to zero (those will be tiled later).
832 static Optional<TiledLinalgOp> tileRootOperation(
833     OpBuilder &builder, LinalgOp op, ArrayRef<Value> tileSizeVector,
834     const LinalgTilingOptions &options, const std::set<unsigned> &fusedLoops) {
835   SmallVector<Value, 4> tileSizes(tileSizeVector.begin(), tileSizeVector.end());
836   auto zero = std_constant_index(0);
837   for (unsigned i = 0, e = tileSizes.size(); i != e; ++i)
838     if (!fusedLoops.count(i))
839       tileSizes[i] = zero;
840   LinalgTilingOptions tileFusedLoopsOptions = options;
841   tileFusedLoopsOptions.setTileSizes(tileSizes);
842   return tileLinalgOp(builder, op, tileFusedLoopsOptions);
843 }
844 
845 /// Fuse the operations in `fusionCandidates` with `tiledOp`. Latter is expected
846 /// to be a tiled operation such that it is valid to fuse all operations in
847 /// `fusionCandidates`, i.e. move the operation within the inter-tile loops of
848 /// `tiledOp`.
849 static SmallVector<LinalgOp, 1>
850 fuseOperations(OpBuilder &builder, LinalgOp rootOp, LinalgOp tiledOp,
851                ArrayRef<LinalgOp> fusionCandidates,
852                const FusableOpDependencesTy &fusableDependences,
853                const std::set<unsigned> &fusedLoops) {
854   OpBuilder::InsertionGuard guard(builder);
855   builder.setInsertionPoint(tiledOp);
856   DenseMap<unsigned, Range> fusedLoopsAndRanges;
857   for (unsigned loop : fusedLoops) {
858     ShapeDimension shapeDim = getShapeDefiningLoopRange(tiledOp, loop, true);
859     fusedLoopsAndRanges[loop] = getRangeFromOperandShape(
860         builder, tiledOp.getLoc(), shapeDim.shape, shapeDim.dimension);
861   }
862 
863   SmallVector<LinalgOp, 1> fusedOps(fusionCandidates.size());
864   DenseMap<Operation *, LinalgOp> origOpToFusedOp;
865   origOpToFusedOp[rootOp.getOperation()] = tiledOp;
866   for (auto candidate : enumerate(llvm::reverse(fusionCandidates))) {
867     LinalgOp origOp = candidate.value();
868     LinalgOp fusedOp = fuse(builder, origOp, fusedLoopsAndRanges);
869     origOpToFusedOp[origOp.getOperation()] = fusedOp;
870     fusedOps[fusionCandidates.size() - candidate.index() - 1] = fusedOp;
871     // If the producer consumer operations are linalg operations on tensors, the
872     // dependence is due to value produced (as a return tensor) by the producer
873     // and used in the consumer. The returned value of the fused op needs to be
874     // made the operand of the tiled/fused consumer operation. By construction
875     // the value returned by the producer is the value used by the consumer.
876     for (auto &dependence : fusableDependences.lookup(origOp.getOperation())) {
877       if (origOp.hasTensorSemantics() &&
878           dependence.dependenceType ==
879               LinalgDependenceGraph::DependenceType::RAW) {
880         unsigned resultIndex =
881             dependence.getDependentOpViewResultNum().getValue();
882         LinalgOp consumer = origOpToFusedOp.lookup(dependence.getIndexingOp());
883         if (!consumer)
884           continue;
885         Value replacementValue = fusedOp.getOperation()->getResult(resultIndex);
886         consumer.getOperation()->setOperand(
887             dependence.getIndexingOpViewOperandNum().getValue(),
888             replacementValue);
889       }
890     }
891     builder.setInsertionPoint(fusedOp);
892   }
893   return fusedOps;
894 }
895 
896 template <typename LoopType>
897 static Optional<TiledAndFusedLinalgOps>
898 tileAndFuseLinalgOpsImpl(OpBuilder &builder, ArrayRef<LinalgOp> ops,
899                          const LinalgDependenceGraph &dependenceGraph,
900                          const LinalgTilingOptions &tilingOptions) {
901   if (ops.size() < 2)
902     return llvm::None;
903   LinalgOp rootOp = ops.back();
904   if (!llvm::all_of(
905           ops,
906           [](LinalgOp linalgOp) { return linalgOp.hasBufferSemantics(); }) &&
907       !llvm::all_of(ops, [](LinalgOp linalgOp) {
908         return linalgOp.hasTensorSemantics();
909       })) {
910     rootOp.emitError(
911         "unable to fuse operations that have tensor semantics with operations "
912         "that have buffer semantics and viceversa.");
913     return llvm::None;
914   }
915   // TODO: Support interchange with tile + fuse. This might actually help do
916   // better fusion.
917   if (!tilingOptions.interchangeVector.empty()) {
918     rootOp.emitRemark("unable to handle tile and fuse with interchange");
919     return llvm::None;
920   }
921 
922   OpBuilder::InsertionGuard guard(builder);
923   builder.setInsertionPoint(rootOp);
924   ScopedContext scope(builder, rootOp.getLoc());
925 
926   // Find all the producers.
927   FusableOpDependencesTy fusableDependences =
928       findAllFusableDependences(ops, dependenceGraph);
929   if (fusableDependences.empty())
930     return llvm::None;
931 
932   TiledAndFusedLinalgOps ret;
933   // Find the loops that can be tiled and fused.
934   ret.fusedLoopDims = collectFusableLoops(ops, fusableDependences);
935 
936   // If there are no fusable dependences or there are no tile+fusable loops,
937   // just return.
938   if (ret.fusedLoopDims.empty()) {
939     return llvm::None;
940   }
941 
942   // Tile the fused loops in the last operation in the list.
943   SmallVector<Value, 4> tileSizeVector =
944       tilingOptions.tileSizeComputationFunction(builder, rootOp);
945   Optional<TiledLinalgOp> tiledRootOp = tileRootOperation(
946       builder, rootOp, tileSizeVector, tilingOptions, ret.fusedLoopDims);
947   if (!tiledRootOp) {
948     rootOp.emitRemark("failed to tile the fused loops");
949     return llvm::None;
950   }
951   ret.op = tiledRootOp->op;
952   ret.fusedLoops.assign(tiledRootOp->loops.begin(), tiledRootOp->loops.end());
953 
954   // Fuse the other operations into the fused inter-tile loops produced above.
955   ret.fusedProducers = fuseOperations(builder, rootOp, ret.op, ops.drop_back(),
956                                       fusableDependences, ret.fusedLoopDims);
957 
958   return ret;
959 }
960 
961 Optional<TiledAndFusedLinalgOps>
962 mlir::linalg::tileAndFuseLinalgOps(OpBuilder &builder, ArrayRef<LinalgOp> ops,
963                                    const LinalgDependenceGraph &dependenceGraph,
964                                    const LinalgTilingOptions &tilingOptions) {
965   switch (tilingOptions.loopType) {
966   case LinalgTilingLoopType::Loops:
967     return tileAndFuseLinalgOpsImpl<scf::ForOp>(builder, ops, dependenceGraph,
968                                                 tilingOptions);
969   case LinalgTilingLoopType::ParallelLoops:
970     return tileAndFuseLinalgOpsImpl<scf::ParallelOp>(
971         builder, ops, dependenceGraph, tilingOptions);
972   default:;
973   }
974   return llvm::None;
975 }
976