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 on tensors operations pass.
10 //
11 //===----------------------------------------------------------------------===//
12 #include "PassDetail.h"
13 #include "mlir/Dialect/Affine/IR/AffineOps.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
16 #include "mlir/Dialect/Linalg/Passes.h"
17 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
18 #include "mlir/Dialect/Linalg/Utils/Utils.h"
19 #include "mlir/IR/AffineExpr.h"
20 #include "mlir/IR/AffineMap.h"
21 #include "mlir/IR/PatternMatch.h"
22 #include "mlir/Support/LLVM.h"
23 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
24 
25 using namespace mlir;
26 using namespace mlir::linalg;
27 
28 /// Implementation of fusion of generic ops and indexed_generic ops.
29 // struct FuseGenericOpsOnTensors {
30 static bool areTensorOpsFusable(LinalgOp producer, LinalgOp consumer,
31                                 unsigned consumerIdx) {
32   // Producer and consumer must have tensor semantics.
33   if (!producer.hasTensorSemantics() || !consumer.hasTensorSemantics())
34     return false;
35 
36   // Verify that
37   // - the producer has all "parallel" iterator type.
38   if (producer.getNumParallelLoops() != producer.getNumLoops())
39     return false;
40 
41   // Get the consumer index map. The number of results of the consumer index
42   // map must match the number of loops of the producer.
43   AffineMap consumerIndexMap = consumer.getIndexingMap(consumerIdx);
44   if (consumerIndexMap.getNumResults() != producer.getNumLoops())
45     return false;
46 
47   // Finally the index_map for the result must be invertible. For now just
48   // verify it is a permutation.
49   AffineMap producerResultIndexMap = producer.getOutputIndexingMap(0);
50   return producerResultIndexMap.isPermutation();
51 }
52 
53 /// Append to `fusedOpIndexingMapAttrs` the indexing maps for the operands of
54 /// the `producer` to use in the fused operation given the indexing map of the
55 /// result of the producer in the consumer.
56 static void getIndexingMapOfProducerOperandsInFusedOp(
57     LinalgOp producer, AffineMap fusedConsumerArgIndexMap,
58     SmallVectorImpl<Attribute> &fusedOpIndexingMapAttrs) {
59   // The indexing map in the consumer op (fusedConsumerArgIndexMap) is a map
60   // from consumer loop -> consumer arg tensor index/producer result tensor
61   // index. The fused loop is same as the consumer loop. For each producer arg
62   // the indexing map to be computed is a map from consumer loop -> producer
63   // arg tensor index.
64 
65   AffineMap producerResultIndexMap = producer.getOutputIndexingMap(0);
66   // producerResultIndexMap is a map from producer loop -> tensor index.
67   // Compute the inverse to get map from tensor index -> producer loop.
68   // The inverse is a map from producer result tensor index -> producer loop.
69   AffineMap invProducerResultIndexMap =
70       inversePermutation(producerResultIndexMap);
71   assert(invProducerResultIndexMap &&
72          "expected producer result indexig map to be invertible");
73   for (unsigned argNum : llvm::seq<unsigned>(0, producer.getNumInputs())) {
74     // argMap is a map from producer loop -> producer arg tensor index.
75     AffineMap argMap = producer.getInputIndexingMap(argNum);
76 
77     // Compose argMap with invProducerResultIndexMap to get a map from
78     // producer result tensor index -> producer arg tensor index.
79     AffineMap t1 = argMap.compose(invProducerResultIndexMap);
80 
81     // Compose t1 with fusedConsumerArgIndexMap gives an indexing map from
82     // consumer loop/ fused loop -> producer arg tensor index.
83     AffineMap indexingMap = t1.compose(fusedConsumerArgIndexMap);
84     fusedOpIndexingMapAttrs.push_back(AffineMapAttr::get(indexingMap));
85   }
86 }
87 
88 /// Generate the region of the fused tensor operation. The region of the fused
89 /// op must be empty.
90 static void generateFusedTensorOpRegion(PatternRewriter &rewriter,
91                                         Operation *fusedOp, LinalgOp producer,
92                                         LinalgOp consumer,
93                                         AffineMap consumerToProducerLoopsMap,
94                                         unsigned consumerIdx, unsigned nloops) {
95   // Build the region of the fused op.
96   Block &producerBlock = producer.getOperation()->getRegion(0).front();
97   Block &consumerBlock = consumer.getOperation()->getRegion(0).front();
98   Block *fusedBlock = new Block();
99   fusedOp->getRegion(0).push_back(fusedBlock);
100   BlockAndValueMapping mapper;
101   OpBuilder::InsertionGuard guard(rewriter);
102   rewriter.setInsertionPointToStart(fusedBlock);
103 
104   // The block arguments are
105   // [index_0, index_1, ... ,
106   //   consumer_operand_0, ... , consumer_operand_(`consumerIdx`-1),
107   //   producer_operand_0, ... , producer_operand_(n-1)],
108   //   consumer_operand_(`consumerIdx`), .. consumer_operand_(m-1)]
109   // , where n is the number of producer's operand and m is the number
110   // consumer's operand.
111   // If both `numProducerIndices` and `numConsumerIndices` are zero, this is a
112   // generic op. In this case, there are no indices in block arguments.
113   unsigned numProducerIndices = isa<IndexedGenericOp>(producer.getOperation())
114                                     ? producer.getNumLoops()
115                                     : 0;
116   unsigned numConsumerIndices = isa<IndexedGenericOp>(consumer.getOperation())
117                                     ? consumer.getNumLoops()
118                                     : 0;
119   unsigned numFusedOpIndices =
120       (isa<IndexedGenericOp>(producer.getOperation()) ||
121        isa<IndexedGenericOp>(consumer.getOperation()))
122           ? std::max(producer.getNumLoops(), consumer.getNumLoops())
123           : 0;
124   // Firstly, add all the indices to the block arguments.
125   for (unsigned i = 0, e = numFusedOpIndices; i < e; ++i)
126     fusedBlock->addArgument(rewriter.getIndexType());
127   // Map the arguments for the unmodified args from the consumer.
128   for (auto consumerArg : llvm::enumerate(consumerBlock.getArguments())) {
129     if (consumerArg.index() == consumerIdx + numConsumerIndices) {
130       // Map the arguments for the args from the producer.
131       for (auto producerArg : llvm::enumerate(producerBlock.getArguments())) {
132         // If producer is an indexed_generic op, map the indices from consumer
133         // loop to producer loop (because the fusedOp is built based on
134         // consumer's perspective).
135         if (producerArg.index() < numProducerIndices) {
136           auto newIndex = rewriter.create<mlir::AffineApplyOp>(
137               producer.getLoc(),
138               consumerToProducerLoopsMap.getSubMap(producerArg.index()),
139               fusedBlock->getArguments().take_front(numFusedOpIndices));
140           mapper.map(producerArg.value(), newIndex);
141         } else {
142           mapper.map(producerArg.value(),
143                      fusedBlock->addArgument(producerArg.value().getType()));
144         }
145       }
146       continue;
147     }
148 
149     // If consumer is an indexed_generic op, map the indices to the block
150     // arguments directly. Otherwise, add the same type of argument and map to
151     // it.
152     if (consumerArg.index() < numConsumerIndices) {
153       mapper.map(consumerArg.value(),
154                  fusedBlock->getArgument(consumerArg.index()));
155     } else {
156       mapper.map(consumerArg.value(),
157                  fusedBlock->addArgument(consumerArg.value().getType()));
158     }
159   }
160 
161   // Add operations from producer (except the yield operation) to the fused
162   // op.
163   for (auto &op : producerBlock.getOperations()) {
164     if (auto yieldOp = dyn_cast<linalg::YieldOp>(op)) {
165       // Lookup the value the yield operation is mapped to.
166       Value yieldVal = yieldOp.getOperand(0);
167       if (Value clonedVal = mapper.lookupOrNull(yieldVal))
168         mapper.map(consumerBlock.getArgument(consumerIdx + numConsumerIndices),
169                    clonedVal);
170       continue;
171     }
172     rewriter.clone(op, mapper);
173   }
174   for (auto &op : consumerBlock.getOperations())
175     rewriter.clone(op, mapper);
176 }
177 
178 static Optional<SmallVector<Value, 1>>
179 fuseTensorOpsImpl(LinalgOp producer, LinalgOp consumer, unsigned consumerIdx,
180                   PatternRewriter &rewriter) {
181   if (!areTensorOpsFusable(producer, consumer, consumerIdx))
182     return llvm::None;
183 
184   unsigned numFusedOperands =
185       producer.getNumInputs() + consumer.getNumInputs() - 1;
186 
187   // Compute the fused operands list,
188   SmallVector<Value, 2> fusedOperands;
189   fusedOperands.reserve(numFusedOperands);
190   auto consumerOperands = consumer.getInputs();
191   auto producerOperands = producer.getInputs();
192   fusedOperands.assign(consumerOperands.begin(),
193                        std::next(consumerOperands.begin(), consumerIdx));
194   fusedOperands.append(producerOperands.begin(), producerOperands.end());
195   fusedOperands.append(std::next(consumerOperands.begin(), consumerIdx + 1),
196                        consumerOperands.end());
197 
198   // Compute indexing_maps for the fused operation. The indexing_maps for the
199   // operands of the consumers that arent fused are the same. The
200   // indexing_maps for the producers need to be computed based on the
201   // indexing_map of the operand at consumerIdx in the consumer.
202   SmallVector<Attribute, 4> fusedIndexMaps;
203   auto consumerIndexMaps = consumer.indexing_maps();
204   fusedIndexMaps.reserve(fusedOperands.size() + consumer.getNumOutputs());
205   fusedIndexMaps.assign(consumerIndexMaps.begin(),
206                         std::next(consumerIndexMaps.begin(), consumerIdx));
207   // Compute indexing maps for the producer args in the fused operation.
208   getIndexingMapOfProducerOperandsInFusedOp(
209       producer, consumer.getInputIndexingMap(consumerIdx), fusedIndexMaps);
210 
211   // Append the indexing maps for the remaining consumer operands.
212   fusedIndexMaps.append(std::next(consumerIndexMaps.begin(), consumerIdx + 1),
213                         consumerIndexMaps.end());
214 
215   // Generate the fused op.
216   // Tensor-level fusion is only on ops without initTensors and outputBuffers.
217   LinalgOp fusedOp;
218   if (isa<GenericOp>(producer.getOperation()) &&
219       isa<GenericOp>(consumer.getOperation())) {
220     fusedOp = rewriter
221                   .create<GenericOp>(consumer.getLoc(),
222                                      consumer.getOperation()->getResultTypes(),
223                                      /*inputs=*/fusedOperands,
224                                      /*outputBuffers=*/ValueRange{},
225                                      /*initTensors=*/ValueRange{},
226                                      rewriter.getArrayAttr(fusedIndexMaps),
227                                      consumer.iterator_types(),
228                                      /*doc=*/nullptr,
229                                      /*library_call=*/nullptr,
230                                      /*symbol_source=*/nullptr)
231                   .getOperation();
232   } else {
233     fusedOp =
234         rewriter
235             .create<IndexedGenericOp>(consumer.getLoc(),
236                                       consumer.getOperation()->getResultTypes(),
237                                       /*inputs=*/fusedOperands,
238                                       /*outputBuffers=*/ValueRange{},
239                                       /*initTensors=*/ValueRange{},
240                                       rewriter.getArrayAttr(fusedIndexMaps),
241                                       consumer.iterator_types(),
242                                       /*doc=*/nullptr,
243                                       /*library_call=*/nullptr,
244                                       /*symbol_source=*/nullptr)
245             .getOperation();
246   }
247 
248   // Construct an AffineMap from consumer loops to producer loops.
249   // consumer loop -> tensor index
250   AffineMap consumerResultIndexMap = consumer.getInputIndexingMap(consumerIdx);
251   // producer loop -> tensor index
252   AffineMap producerResultIndexMap = producer.getOutputIndexingMap(0);
253   // tensor index -> producer loop
254   AffineMap invProducerResultIndexMap =
255       inversePermutation(producerResultIndexMap);
256   assert(invProducerResultIndexMap &&
257          "expected producer result indexig map to be invertible");
258   // consumer loop -> producer loop
259   AffineMap consumerToProducerLoopsMap =
260       invProducerResultIndexMap.compose(consumerResultIndexMap);
261 
262   generateFusedTensorOpRegion(rewriter, fusedOp.getOperation(), producer,
263                               consumer, consumerToProducerLoopsMap, consumerIdx,
264                               consumer.getNumLoops());
265   return SmallVector<Value, 1>(fusedOp.getOperation()->getResults());
266 }
267 
268 /// Linearize the expressions in `sourceMap` based on the `reassociationMaps`
269 /// provided, given the shape of the source tensor that corresponds to the
270 /// `sourceMap`. Note that this implicitly assumes that the tensors dimensions
271 /// are "row-major" ordered logically.
272 ///
273 /// For example:
274 ///
275 /// %0 = op ... : tensor<?x?x4x5xf32>
276 /// with output index_map `affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>`
277 ///
278 /// and reshape:
279 /// %1 = linalg.tensor_reshape %0 [affine_map<(i, j, k, l) -> (i)>,
280 ///                                affine_map<(i, j, k, l) -> (j, k, l)>] :
281 ///        tensor<?x?x4x5xf32> into tensor<?x?xf32>
282 ///
283 /// would be rewritten into:
284 /// %0 = op ... : tensor<?x?x4x5xf32>
285 /// with output index_map
286 ///   `affine_map<(d0, d1, d2, d3) -> (d0, d1 * 20 + d2 * 5 + d3)>`
287 static AffineMap linearizeCollapsedDims(AffineMap sourceMap,
288                                         ArrayRef<int64_t> sourceShape,
289                                         ArrayRef<AffineMap> reassociationMaps) {
290   SmallVector<AffineExpr, 4> resultExprs;
291   resultExprs.reserve(reassociationMaps.size());
292   ArrayRef<AffineExpr> sourceExprs = sourceMap.getResults();
293   MLIRContext *context = sourceMap.getContext();
294 
295   // Compute the result exprs based on the reassociation maps.
296   for (AffineMap map : reassociationMaps) {
297     ArrayRef<AffineExpr> collapsedDims = map.getResults();
298     // Assume that they are in-order and contiguous (already checked in
299     // verifier).
300     assert(!collapsedDims.empty());
301     unsigned startDim =
302         collapsedDims.front().cast<AffineDimExpr>().getPosition();
303     AffineExpr linearizedExpr = makeCanonicalStridedLayoutExpr(
304         sourceShape.slice(startDim, collapsedDims.size()),
305         sourceExprs.slice(startDim, collapsedDims.size()), context);
306     resultExprs.push_back(linearizedExpr);
307   }
308   return AffineMap::get(sourceMap.getNumDims(), sourceMap.getNumSymbols(),
309                         resultExprs, context);
310 }
311 
312 /// Checks if the `reshapeOp` can be fused with it consumer (if `asProducer` is
313 /// true) or its producer (if `asProducer` is false) given the indexing map at
314 /// its use.
315 static bool isTensorReshapeOpFoldableByLinearization(TensorReshapeOp reshapeOp,
316                                                      AffineMap useIndexMap,
317                                                      bool asProducer) {
318   RankedTensorType returnType = reshapeOp.getResultType();
319   RankedTensorType operandType = reshapeOp.getSrcType();
320   // Reshape is fusable with its consumer (i.e. reshape as a producer) when its
321   // operand is of lesser rank than the result. Fusing when operand has higher
322   // rank will require use of mods and divs in the indexing maps of the fused op
323   // which would make it non-invertible. Similarly reshape is fused with its
324   // producer (i.e. reshape as consumer) only if the return type has lesser
325   // rank.
326   if ((asProducer && reshapeOp.getSrcType().hasStaticShape() &&
327        returnType.getRank() < operandType.getRank()) ||
328       (!asProducer && reshapeOp.getResultType().hasStaticShape() &&
329        operandType.getRank() < returnType.getRank()))
330     return false;
331   return useIndexMap.isPermutation();
332 }
333 
334 /// Based on the type of `op` create a linalg op of the same type, i.e. if `op`
335 /// is a linalg.generic operation, the create a `linalg.generic` operation with
336 /// the given `args`. Expects `op` to be `linalg.generic` or
337 /// `linalg.indexed_generic`.
338 template <typename... Args>
339 static LinalgOp createLinalgOpOfSameType(LinalgOp op, PatternRewriter &rewriter,
340                                          Args... args) {
341   if (isa<GenericOp>(op.getOperation()))
342     return cast<LinalgOp>(rewriter.create<GenericOp>(args...).getOperation());
343   if (isa<IndexedGenericOp>(op.getOperation()))
344     return cast<LinalgOp>(
345         rewriter.create<IndexedGenericOp>(args...).getOperation());
346   llvm_unreachable(
347       "expected only linalg.generic or linalg.indexed_generic ops");
348   return nullptr;
349 }
350 
351 /// Conditions for folding a generic/indexed-generic operation with a reshape op
352 /// by expanding the iteration space dimensionality for tensor operations. These
353 /// are preconditions assumed by `foldReshapeByDimExpansion` which implements
354 /// the following fusion pattern.
355 ///
356 ///  Consider
357 ///
358 ///  %c = linalg.generic ins(%a, %b : memref<?x?x?xf32>, memref<?x?xf32>)
359 ///         indexing_maps = [affine_map<(d0, d1, d2) -> (d1, d0, d2)>,
360 ///                          affine_map<(d0, d1, d2) -> (d1, d2)>,
361 ///                          affine_map<(d0, d1, d2) -> (d0, d2, d1)>]
362 ///  %d = linalg.tensor_reshape %c
363 ///         [affine_map<(d0, d1, d2, d3, d4, d5) -> (d0, d1)>,
364 ///          affine_map<(d0, d1, d2, d3, d4, d5) -> (d2)>,
365 ///          affine_map<(d0, d1, d2, d3, d4, d5) -> (d3, d4, d5)>]
366 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
367 ///
368 ///  The reshape can be folded into the `linalgOp` if the
369 ///  generic/indexed-generic op loop dimensionality is increased to match the
370 ///  result (operand) of the tensor_reshape when the reshape is expanding
371 ///  (folding). The indexing_map of the fused tensor in the `linalgOp` and the
372 ///  reassociation map helps compute the indexing maps of the modified op. For
373 ///  the above example, based on the reassociation map it can be concluded that
374 ///
375 ///  - The loop used to access the first dimension of the fused tensor is split
376 ///    into two.
377 ///  - The loop used to access the second dimension of the fused tensor is kept
378 ///    as is.
379 ///  - The loop used to access the third dimension of the fused tensor is split
380 ///    into three.
381 ///
382 ///  i.e. (e0, e1, e2, e3, e4) is the domain of the indexing map of the modified
383 ///  op, then
384 ///
385 ///   d0 -> e0, e1
386 ///   d1 -> e2, e3, e4
387 ///   d2 -> e5
388 ///
389 ///  substituting this, the generic op can be rewritten as
390 ///
391 ///  %d = linalg.generic ins(%0, %1 : )
392 ///        indexing_maps =
393 ///         [affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e0, e1, e5)>,
394 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e5)>,
395 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e0, e1, e5, e2, e3, e4)>]
396 ///
397 ///  Since operands to the linalg generic are now 5D, reshapes can be introduced
398 ///  to make it consistent
399 ///
400 ///  %0 = linalg.tensor_reshape %a
401 ///         [affine_map<(e0, e1, e2, e3, e4, e5) -> (e0, e1, e2),
402 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e3, e4),
403 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e5)]
404 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
405 ///  %1 = linalg.tensor_reshape %b
406 ///         [affine_map<(e0, e1, e2, e3) -> (e0, e1, e2),
407 ///          affine_map<(e0, e1, e2, e3) -> (e3)]
408 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?xf32>
409 ///
410 ///  The added reshapes are again expanding patterns, so they will get fused
411 ///  with its producers if possible.
412 static bool isFusableWithReshapeByDimExpansion(LinalgOp linalgOp,
413                                                unsigned fusedTensorIndex) {
414   // Is fusable only if:
415   // - The linalgOp is a generic op, or an indexed_generic.
416   // - All the indexing maps for operands in linalgOp are projected
417   //   permutations.
418   // - The indexing map at the position representing the fused tensor is a
419   //   permutation.
420   // - All the loops in linalgOp are parallel loops.
421   return isa<GenericOp, IndexedGenericOp>(linalgOp.getOperation()) &&
422          linalgOp.hasTensorSemantics() &&
423          llvm::all_of(linalgOp.indexing_maps().getValue().take_front(
424                           linalgOp.getNumInputs()),
425                       [](Attribute attr) {
426                         return attr.cast<AffineMapAttr>()
427                             .getValue()
428                             .isProjectedPermutation();
429                       }) &&
430          linalgOp.getIndexingMap(fusedTensorIndex).isPermutation() &&
431          llvm::all_of(linalgOp.iterator_types(), [](Attribute attr) {
432            return attr.cast<StringAttr>().getValue() ==
433                   getParallelIteratorTypeName();
434          });
435 }
436 
437 /// Implements the fusion of a tensor_reshape op and a generic/indexed_generic
438 /// op as explained in `isFusableWithReshapeByExpansion`. Assumes that those
439 /// conditions have been satisfied.
440 static Optional<SmallVector<Value, 1>>
441 fuseWithReshapeByExpansion(LinalgOp linalgOp, TensorReshapeOp reshapeOp,
442                            unsigned fusedTensorIndex,
443                            PatternRewriter &rewriter) {
444   assert(isFusableWithReshapeByDimExpansion(linalgOp, fusedTensorIndex) &&
445          "preconditions for fuse operation failed");
446   // Check if reshape is expanding or collapsing.
447   bool isExpanding =
448       reshapeOp.getSrcType().getRank() < reshapeOp.getResultType().getRank();
449   RankedTensorType expandedType =
450       isExpanding ? reshapeOp.getResultType() : reshapeOp.getSrcType();
451   RankedTensorType foldedType =
452       isExpanding ? reshapeOp.getSrcType() : reshapeOp.getResultType();
453   AffineMap fusedIndexMap = linalgOp.getIndexingMap(fusedTensorIndex);
454 
455   // The reshape is folding/expanding consecutive dimensions. Given the indexing
456   // map of the fused tensor find the number of dimensions each of the loops of
457   // the original op is expanded into. Also record the shape of the expanded
458   // dimensions.
459   ArrayRef<int64_t> expandedShape = expandedType.getShape();
460   SmallVector<unsigned, 4> numFoldedDims(foldedType.getRank(), 0);
461   SmallVector<SmallVector<int64_t, 4>, 4> expandedDimsShape(
462       foldedType.getRank());
463   auto reassociationMaps = reshapeOp.getReassociationMaps();
464   for (auto resultExpr : llvm::enumerate(fusedIndexMap.getResults())) {
465     unsigned pos = resultExpr.value().cast<AffineDimExpr>().getPosition();
466     AffineMap foldedDims = reassociationMaps[resultExpr.index()];
467     numFoldedDims[pos] = foldedDims.getNumResults();
468     ArrayRef<int64_t> shape = expandedShape.slice(
469         foldedDims.getResult(0).cast<AffineDimExpr>().getPosition(),
470         numFoldedDims[pos]);
471     expandedDimsShape[pos].assign(shape.begin(), shape.end());
472   }
473 
474   if (isa<IndexedGenericOp>(linalgOp.getOperation())) {
475     // For indexed generic op, the region contains arguments that represent the
476     // induction variable value of the loops. In the fused op these values are
477     // obtained by linearizing the expanded dimensions. For now just check that
478     // the extents used in the linearization (all the expanded dims except the
479     // front) are statically know. For dynamic case, we would need shape
480     // information on these dimensions to get these.
481     for (auto &expandedShape : expandedDimsShape) {
482       for (int64_t expandedDimShape : llvm::make_range(
483                std::next(expandedShape.begin()), expandedShape.end())) {
484         if (ShapedType::isDynamic(expandedDimShape)) {
485           linalgOp.emitError(
486               "unable to fuse indexed generic op where the expanded dim is "
487               "dynamic");
488           return llvm::None;
489         }
490       }
491     }
492   }
493 
494   // The remapping of the indices is then the prefix sum (inclusive) of the
495   // numFoldedDims.
496   SmallVector<unsigned, 4> remapping(numFoldedDims.size() + 1, 0);
497   unsigned sum = 0;
498   for (auto numFoldedDim : llvm::enumerate(numFoldedDims)) {
499     sum += numFoldedDim.value();
500     remapping[numFoldedDim.index() + 1] = sum;
501   }
502 
503   SmallVector<AffineMap, 4> expandedOpIndexingMaps;
504   // Compute the modified indexing maps by replacing every loop (AffineDimExpr)
505   // in the original indexing map with the sequence of loops that it is expanded
506   // to.
507   for (AffineMap indexingMap : linalgOp.getIndexingMaps()) {
508     SmallVector<AffineExpr, 4> newExprs;
509     for (AffineExpr expr : indexingMap.getResults()) {
510       unsigned pos = expr.cast<AffineDimExpr>().getPosition();
511       for (unsigned newPos :
512            llvm::seq<unsigned>(remapping[pos], remapping[pos + 1])) {
513         newExprs.push_back(rewriter.getAffineDimExpr(newPos));
514       }
515     }
516     expandedOpIndexingMaps.push_back(
517         AffineMap::get(remapping.back(), indexingMap.getNumSymbols(), newExprs,
518                        rewriter.getContext()));
519   }
520 
521   // The operands of the expanded op are computed by reshaping the original
522   // operands. The reshape depends on the ordering of the loop used to access
523   // the tensor in the original operation, and are expanded into as many
524   // dimensions as the loop is expanded into (as computed by `remapping`).
525   auto getReshapeInfo =
526       [&](AffineMap operandIndexingMap,
527           SmallVectorImpl<ReassociationIndices> &reassociation,
528           SmallVectorImpl<int64_t> &expandedOpOperandShape) {
529         unsigned reshapeDims = 0;
530         for (AffineExpr expr : operandIndexingMap.getResults()) {
531           unsigned origDim = expr.cast<AffineDimExpr>().getPosition();
532           auto foldedDims = llvm::seq<int64_t>(
533               reshapeDims, reshapeDims + numFoldedDims[origDim]);
534           reassociation.emplace_back(foldedDims.begin(), foldedDims.end());
535           expandedOpOperandShape.append(expandedDimsShape[origDim].begin(),
536                                         expandedDimsShape[origDim].end());
537           reshapeDims += numFoldedDims[origDim];
538         }
539       };
540   SmallVector<Value, 4> expandedOpOperands;
541   for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
542     if (operand.index() == fusedTensorIndex) {
543       expandedOpOperands.push_back(reshapeOp.src());
544       continue;
545     }
546     AffineMap indexingMap = linalgOp.getIndexingMap(operand.index());
547     SmallVector<ReassociationIndices, 4> reassociation;
548     SmallVector<int64_t, 4> expandedOperandShape;
549     getReshapeInfo(indexingMap, reassociation, expandedOperandShape);
550     Type expandedOperandType = RankedTensorType::get(
551         expandedOperandShape,
552         operand.value().getType().cast<ShapedType>().getElementType());
553     if (expandedOperandType != operand.value().getType()) {
554       expandedOpOperands.push_back(rewriter.create<TensorReshapeOp>(
555           linalgOp.getLoc(), expandedOperandType, operand.value(),
556           reassociation));
557     } else {
558       expandedOpOperands.push_back(operand.value());
559     }
560   }
561   SmallVector<Type, 1> resultTypes;
562   SmallVector<SmallVector<ReassociationIndices, 4>, 1> resultReassociation;
563   for (auto result : llvm::enumerate(linalgOp.getOperation()->getResults())) {
564     AffineMap indexingMap =
565         linalgOp.getIndexingMap(linalgOp.getNumInputs() + result.index());
566     SmallVector<ReassociationIndices, 4> reassociation;
567     SmallVector<int64_t, 4> expandedResultShape;
568     getReshapeInfo(indexingMap, reassociation, expandedResultShape);
569     resultTypes.push_back(RankedTensorType::get(
570         expandedResultShape,
571         result.value().getType().cast<ShapedType>().getElementType()));
572     resultReassociation.emplace_back(std::move(reassociation));
573   }
574 
575   // The iterator types of the expanded op are all parallel.
576   SmallVector<StringRef, 4> iteratorTypes(remapping.back(),
577                                           getParallelIteratorTypeName());
578 
579   LinalgOp fusedOp = createLinalgOpOfSameType(
580       linalgOp, rewriter, linalgOp.getLoc(), resultTypes,
581       /*inputs=*/expandedOpOperands,
582       /*outputBuffers=*/ValueRange{},
583       /*initTensors=*/ValueRange{}, expandedOpIndexingMaps, iteratorTypes);
584   Region &fusedRegion = fusedOp.getOperation()->getRegion(0);
585   Region &originalRegion = linalgOp.getOperation()->getRegion(0);
586 
587   if (isa<GenericOp>(linalgOp.getOperation())) {
588     rewriter.cloneRegionBefore(originalRegion, fusedRegion,
589                                fusedRegion.begin());
590   } else {
591     assert(isa<IndexedGenericOp>(linalgOp.getOperation()));
592     // Create an entry block in the fused Region with same number of arguments
593     // as the fused op
594     Block *fusedEntryBlock = new Block;
595     fusedRegion.push_back(fusedEntryBlock);
596     rewriter.cloneRegionBefore(originalRegion, fusedRegion, fusedRegion.end());
597 
598     // Merge the entry block of the fused op with the cloned blocks. For this
599     // compute the value for arguments of the region in the original operation
600     // in terms of the arguments of the fused op. Since the original operation
601     // is expanded, the expanded dimensions need to be folded back to get the
602     // replacement value for the arguments corresponding to interation index.
603     // For now this expects that all the loop ranges are constants, which is
604     // true if the shapes are all static. This has already been checked in the
605     // precondition.
606     using namespace edsc::op;
607     using namespace edsc::intrinsics;
608     OpBuilder::InsertionGuard guard(rewriter);
609     SmallVector<Value, 4> argReplacements(originalRegion.getNumArguments());
610     rewriter.setInsertionPointToStart(fusedEntryBlock);
611     edsc::ScopedContext scopedContext(rewriter, fusedOp.getLoc());
612     IndexType indexType = rewriter.getIndexType();
613     for (unsigned i : llvm::seq<unsigned>(0, numFoldedDims.size())) {
614       Value linearizedIndex = fusedEntryBlock->addArgument(indexType);
615       for (unsigned foldedDim = remapping[i] + 1; foldedDim != remapping[i + 1];
616            foldedDim++) {
617         int64_t expandedDimExtent =
618             expandedDimsShape[i][foldedDim - remapping[i]];
619         assert(!ShapedType::isDynamic(expandedDimExtent));
620         linearizedIndex =
621             linearizedIndex * std_constant_index(expandedDimExtent);
622         linearizedIndex =
623             linearizedIndex + fusedEntryBlock->addArgument(indexType);
624       }
625       argReplacements[i] = linearizedIndex;
626     }
627     for (unsigned i :
628          llvm::seq<unsigned>(numFoldedDims.size(), argReplacements.size())) {
629       argReplacements[i] =
630           fusedEntryBlock->addArgument(originalRegion.getArgument(i).getType());
631     }
632     rewriter.mergeBlocks(fusedEntryBlock->getNextNode(), fusedEntryBlock,
633                          argReplacements);
634   }
635 
636   // Reshape the result values to their original shape if this is a collapsing
637   // reshape folded into its consumer.
638   SmallVector<Value, 1> resultVals;
639   for (auto result : llvm::enumerate(linalgOp.getOperation()->getResults())) {
640     if (!isExpanding &&
641         resultTypes[result.index()] != result.value().getType()) {
642       resultVals.push_back(rewriter.create<TensorReshapeOp>(
643           linalgOp.getLoc(), result.value().getType(),
644           fusedOp.getOperation()->getResult(result.index()),
645           resultReassociation[result.index()]));
646     } else {
647       resultVals.push_back(fusedOp.getOperation()->getResult(result.index()));
648     }
649   }
650   // Assuming a single result.
651   return resultVals;
652 }
653 
654 namespace {
655 
656 /// Pattern to fold tensor_reshape op with its consumer by using the source of
657 /// the reshape op as the operand in the consumer (instead of the result of the
658 /// tensor_reshapeop) when the tensor_reshape op is collapsing. The
659 /// corresponding index map in the consumer needs to be modified to linearize
660 /// the folded dimension.
661 ///
662 /// For example,
663 ///
664 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
665 /// %0 = linalg.tensor_reshape %arg0
666 ///        [affine_map<(i, j, k, l) -> (i)>, affine_map<(i, j, k, l) -> (j, k)>,
667 ///         affine_map<(i, j, k, l) -> (l)>]
668 ///      tensor<?x?x?xf32> into tensor<?x?x4x?xf32>
669 /// %1 = linalg.generic { indexing_maps = [#map0, #map0, #map0], ... }
670 ///        ins(%0, %arg1 : tensor<?x?x4x?xf32>, tensor<?x?x4x?xf32>) ...
671 ///        -> tensor<?x?x4x?xf32>
672 ///
673 /// can be folded into
674 ///
675 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1 * 4 + d2, d3)>
676 /// #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
677 /// %0 = linalg.generic { indexing_maps = [#map0, #map1, #map1] ... }
678 ///        ins(%arg0, %arg1 : tensor<?x?x?xf32>, tensor<?x?x4x?xf32>) ...
679 ///        -> tensor<?x?x4x?xf32>
680 template <typename LinalgOpTy>
681 struct FoldProducerReshapeOpByLinearization
682     : public OpRewritePattern<LinalgOpTy> {
683   using OpRewritePattern<LinalgOpTy>::OpRewritePattern;
684 
685   LogicalResult matchAndRewrite(LinalgOpTy op,
686                                 PatternRewriter &rewriter) const override {
687     if (!op.hasTensorSemantics())
688       return failure();
689     LinalgOp linalgOp = cast<LinalgOp>(op.getOperation());
690     for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
691       TensorReshapeOp reshapeOp =
692           operand.value().getDefiningOp<TensorReshapeOp>();
693       if (!reshapeOp ||
694           !isTensorReshapeOpFoldableByLinearization(
695               reshapeOp, linalgOp.getInputIndexingMap(operand.index()),
696               /*asProducer =*/true))
697         continue;
698 
699       // Compute the fused operands list,
700       SmallVector<Value, 2> fusedOperands(linalgOp.getInputs());
701       fusedOperands[operand.index()] = reshapeOp.src();
702 
703       // Compute indexing_maps for the fused operation. The indexing_maps for
704       // the operands of the consumers that arent fused are the same.
705       SmallVector<AffineMap, 4> fusedIndexMaps = llvm::to_vector<4>(
706           op.indexing_maps().template getAsValueRange<AffineMapAttr>());
707 
708       // Accepted consumer maps are either identity or permutation.
709       auto invMap = inversePermutation(fusedIndexMaps[operand.index()]);
710 
711       // Compute the indexing map to use for the result of the producer.
712       AffineMap modifiedMap =
713           linearizeCollapsedDims(invMap, reshapeOp.getResultType().getShape(),
714                                  reshapeOp.getReassociationMaps());
715       for (AffineExpr expr : modifiedMap.getResults()) {
716         if (!expr.isPureAffine())
717           return failure();
718       }
719       fusedIndexMaps[operand.index()] = modifiedMap;
720 
721       // Further check that the resulting index maps can be fused and
722       // inverted. Without this the resultant op is not legal.
723       if (!inversePermutation(concatAffineMaps(fusedIndexMaps)))
724         return op.emitRemark("fused op loop bound computation failed");
725 
726       rewriter.startRootUpdate(op);
727       op.getOperation()->setOperands(fusedOperands);
728       op.indexing_mapsAttr(rewriter.getAffineMapArrayAttr(fusedIndexMaps));
729       rewriter.finalizeRootUpdate(op);
730       if (reshapeOp.use_empty())
731         rewriter.eraseOp(reshapeOp);
732       return success();
733     }
734     return op.emitRemark("no fusion candidates found");
735   }
736 };
737 
738 /// Pattern to fuse a tensor_reshape op with its consumer
739 /// generic/indexed_generic op, when the reshape op is collapsing
740 /// dimensions. The dimensionality of the loop in the consumer is expanded.
741 template <typename GenericOpTy>
742 struct FoldWithProducerReshapeOpByExpansion
743     : public OpRewritePattern<GenericOpTy> {
744   using OpRewritePattern<GenericOpTy>::OpRewritePattern;
745 
746   LogicalResult matchAndRewrite(GenericOpTy genericOp,
747                                 PatternRewriter &rewriter) const override {
748     LinalgOp linalgOp = cast<LinalgOp>(genericOp.getOperation());
749     for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
750       TensorReshapeOp reshapeOp =
751           operand.value().getDefiningOp<TensorReshapeOp>();
752       if (!reshapeOp)
753         continue;
754 
755       // Fold only if
756       // - The tensor reshape op is folding.
757       // - All constraints of fusing with reshape by expansion are met.
758       if (reshapeOp.getSrcType().getRank() <
759               reshapeOp.getResultType().getRank() ||
760           !isFusableWithReshapeByDimExpansion(linalgOp, operand.index()))
761         continue;
762 
763       Optional<SmallVector<Value, 1>> replacementValues =
764           fuseWithReshapeByExpansion(linalgOp, reshapeOp, operand.index(),
765                                      rewriter);
766       if (!replacementValues)
767         return failure();
768       rewriter.replaceOp(genericOp, replacementValues.getValue());
769       if (reshapeOp.use_empty())
770         rewriter.eraseOp(reshapeOp);
771       return success();
772     }
773     return failure();
774   }
775 };
776 
777 /// Pattern to fold tensor_reshape op with its producer. The corresponding index
778 /// map in the consumer needs to be modified to linearize the folded dimension.
779 struct FoldConsumerReshapeOpByLinearization
780     : public OpRewritePattern<TensorReshapeOp> {
781   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
782 
783   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
784                                 PatternRewriter &rewriter) const override {
785     LinalgOp producer = reshapeOp.src().getDefiningOp<LinalgOp>();
786     if (!producer ||
787         !isa<GenericOp, IndexedGenericOp>(producer.getOperation()) ||
788         !producer.hasTensorSemantics() || producer.getNumOutputs() != 1 ||
789         !isTensorReshapeOpFoldableByLinearization(
790             reshapeOp, producer.getOutputIndexingMap(0), /*asProducer =*/false))
791       return failure();
792     // The indexing_maps for the operands of the fused operation are same as
793     // those for the operands of the producer.
794     SmallVector<AffineMap, 4> fusedIndexMaps = llvm::to_vector<4>(
795         producer.indexing_maps().getAsValueRange<AffineMapAttr>());
796 
797     auto invMap = inversePermutation(producer.getOutputIndexingMap(0));
798 
799     // Compute the indexing map to use for the operand of the producer.
800     AffineMap modifiedMap =
801         linearizeCollapsedDims(invMap, reshapeOp.getSrcType().getShape(),
802                                reshapeOp.getReassociationMaps());
803     for (AffineExpr expr : modifiedMap.getResults()) {
804       if (!expr.isPureAffine())
805         return reshapeOp.emitRemark("fused op indexing map is not affine");
806     }
807     fusedIndexMaps.back() = modifiedMap;
808 
809     // Further check that the resulting index maps can be fused and
810     // inverted. Without this the resultant op is not legal.
811     if (!inversePermutation(concatAffineMaps(fusedIndexMaps)))
812       return reshapeOp.emitRemark("fused op loop bound computation failed");
813 
814     LinalgOp fusedOp = createLinalgOpOfSameType(
815         producer, rewriter, rewriter.getUnknownLoc(), reshapeOp.getResultType(),
816         /*inputs=*/producer.getInputs(),
817         /*outputBuffers=*/ValueRange{},
818         /*initTensors=*/ValueRange{}, // no init tensors for now.
819         rewriter.getAffineMapArrayAttr(fusedIndexMaps),
820         producer.iterator_types(),
821         /*doc=*/nullptr,
822         /*library_call=*/nullptr,
823         /*symbol_source=*/nullptr);
824     auto &fusedRegion = fusedOp.getOperation()->getRegion(0);
825     rewriter.cloneRegionBefore(producer.getOperation()->getRegion(0),
826                                fusedRegion, fusedRegion.begin());
827     rewriter.replaceOp(reshapeOp, fusedOp.getOperation()->getResults());
828     if (producer.use_empty())
829       rewriter.eraseOp(producer);
830     return success();
831   }
832 };
833 
834 /// Pattern to fold a tensor_reshape op with its producer generic op if the
835 /// tensor_reshape op is expanding, by expanding the dimensionality of the loop
836 /// in the producer op.
837 struct FoldReshapeWithGenericOpByExpansion
838     : public OpRewritePattern<TensorReshapeOp> {
839   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
840   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
841                                 PatternRewriter &rewriter) const override {
842     // Fold only if
843     // - The tensor reshape op is a expanding case.
844     // - All constraints of fusing with reshape by expansion are met.
845     if (reshapeOp.getSrcType().getRank() > reshapeOp.getResultType().getRank())
846       return failure();
847     LinalgOp producer = reshapeOp.src().getDefiningOp<LinalgOp>();
848     if (!producer || producer.getNumOutputs() != 1 ||
849         !isFusableWithReshapeByDimExpansion(producer, producer.getNumInputs()))
850       return failure();
851     Optional<SmallVector<Value, 1>> replacementValues =
852         fuseWithReshapeByExpansion(producer, reshapeOp, producer.getNumInputs(),
853                                    rewriter);
854     if (!replacementValues)
855       return failure();
856     rewriter.replaceOp(reshapeOp, replacementValues.getValue());
857     if (producer.use_empty())
858       rewriter.eraseOp(producer);
859     return success();
860   }
861 };
862 
863 /// Pattern to fold a GenericOp/IndexedGenericOp with a splat constant.
864 template <typename LinalgOpTy>
865 struct FoldSplatConstants : public OpRewritePattern<LinalgOpTy> {
866   using OpRewritePattern<LinalgOpTy>::OpRewritePattern;
867 
868   LogicalResult matchAndRewrite(LinalgOpTy op,
869                                 PatternRewriter &rewriter) const override {
870     if (!op.hasTensorSemantics())
871       return failure();
872     LinalgOp linalgOp = cast<LinalgOp>(op.getOperation());
873     for (auto operand : llvm::enumerate(linalgOp.getInputs())) {
874       ConstantOp constantOp = operand.value().getDefiningOp<ConstantOp>();
875       if (!constantOp ||
876           !constantOp.value().cast<DenseElementsAttr>().isSplat())
877         continue;
878 
879       // The indexing_maps for the operands of the fused operation are same as
880       // those for the operands of the linalgOp without the indexing map at
881       // operand.index()
882       SmallVector<AffineMap, 4> fusedIndexMaps = llvm::to_vector<4>(
883           linalgOp.indexing_maps().getAsValueRange<AffineMapAttr>());
884       fusedIndexMaps.erase(std::next(fusedIndexMaps.begin(), operand.index()));
885 
886       // The operands list is same as the linalgOp with the argument for
887       // constant index dropped.
888       SmallVector<Value, 4> fusedOperands(linalgOp.getInputs());
889       fusedOperands.erase(std::next(fusedOperands.begin(), operand.index()));
890 
891       // Create a constant scalar value from the splat constant.
892       Value scalarConstant = rewriter.create<ConstantOp>(
893           constantOp.getLoc(),
894           constantOp.value().cast<DenseElementsAttr>().getSplatValue());
895 
896       LinalgOp fusedOp = createLinalgOpOfSameType(
897           linalgOp, rewriter, rewriter.getUnknownLoc(),
898           linalgOp.getOperation()->getResultTypes(),
899           /*inputs=*/fusedOperands,
900           /*outputBuffers=*/ValueRange{},
901           /*initTensors=*/ValueRange{}, // no init tensors for now.
902           rewriter.getAffineMapArrayAttr(fusedIndexMaps),
903           linalgOp.iterator_types(),
904           /*doc=*/nullptr,
905           /*library_call=*/nullptr,
906           /*symbol_source=*/nullptr);
907 
908       // Map the block argument corresponding to the replaced argument with the
909       // scalar constant.
910       Region &linalgOpRegion = linalgOp.getOperation()->getRegion(0);
911       Block &entryBlock = *linalgOpRegion.begin();
912       unsigned argIndex = entryBlock.getNumArguments() -
913                           linalgOp.getNumInputs() + operand.index();
914       BlockAndValueMapping mapping;
915       mapping.map(entryBlock.getArgument(argIndex), scalarConstant);
916       Region &fusedRegion = fusedOp.getOperation()->getRegion(0);
917       rewriter.cloneRegionBefore(linalgOpRegion, fusedRegion,
918                                  fusedRegion.begin(), mapping);
919       rewriter.replaceOp(linalgOp, fusedOp.getOperation()->getResults());
920       if (constantOp.use_empty())
921         rewriter.eraseOp(constantOp);
922       return success();
923     }
924     return failure();
925   }
926 };
927 } // namespace
928 
929 Optional<SmallVector<Value, 1>>
930 mlir::linalg::fuseTensorOps(PatternRewriter &rewriter, Operation *consumer,
931                             unsigned consumerIdx) {
932   if (consumerIdx >= consumer->getNumOperands())
933     return llvm::None;
934   Operation *producer = consumer->getOperand(consumerIdx).getDefiningOp();
935   if (!producer || producer->getNumResults() != 1)
936     return llvm::None;
937 
938   // Fuse when consumer is GenericOp or IndexedGenericOp.
939   if (!isa<GenericOp, IndexedGenericOp>(consumer) ||
940       !isa<GenericOp, IndexedGenericOp>(producer))
941     return llvm::None;
942 
943   return fuseTensorOpsImpl(cast<LinalgOp>(producer), cast<LinalgOp>(consumer),
944                            consumerIdx, rewriter);
945 }
946 
947 namespace {
948 /// Patterns to fuse a generic op, with the producer of its operands.
949 template <typename LinalgOpTy>
950 struct FuseTensorOps : public OpRewritePattern<LinalgOpTy> {
951   using OpRewritePattern<LinalgOpTy>::OpRewritePattern;
952 
953   LogicalResult matchAndRewrite(LinalgOpTy op,
954                                 PatternRewriter &rewriter) const override {
955     // Find the first operand that is defined by another generic op on tensors.
956     for (auto operandNum :
957          llvm::seq<unsigned>(0, op.getOperation()->getNumOperands())) {
958       Operation *producer =
959           op.getOperation()->getOperand(operandNum).getDefiningOp();
960       if (!producer)
961         continue;
962       Optional<SmallVector<Value, 1>> fusedOpResults =
963           fuseTensorOps(rewriter, op, operandNum);
964       if (fusedOpResults) {
965         rewriter.replaceOp(op, *fusedOpResults);
966         if (producer->use_empty())
967           rewriter.eraseOp(producer);
968         return success();
969       }
970     }
971     return failure();
972   }
973 };
974 
975 /// Pass that fuses generic ops on tensors. Used only for testing.
976 struct FusionOfTensorOpsPass
977     : public LinalgFusionOfTensorOpsBase<FusionOfTensorOpsPass> {
978   void runOnOperation() override {
979     OwningRewritePatternList patterns;
980     Operation *op = getOperation();
981     populateLinalgTensorOpsFusionPatterns(op->getContext(), patterns);
982     applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns));
983   }
984 };
985 
986 /// Pass to test folding of reshape op with generic/indexed_generic ops by
987 /// linearization.
988 struct FoldReshapeOpsByLinearizationPass
989     : public LinalgFoldReshapeOpsByLinearizationBase<
990           FoldReshapeOpsByLinearizationPass> {
991   void runOnOperation() override {
992     OwningRewritePatternList patterns;
993     Operation *op = getOperation();
994     populateFoldReshapeOpsByLinearizationPatterns(op->getContext(), patterns);
995     applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns));
996   }
997 };
998 
999 } // namespace
1000 
1001 void mlir::populateFoldReshapeOpsByLinearizationPatterns(
1002     MLIRContext *context, OwningRewritePatternList &patterns) {
1003   patterns.insert<FoldProducerReshapeOpByLinearization<GenericOp>,
1004                   FoldProducerReshapeOpByLinearization<IndexedGenericOp>,
1005                   FoldConsumerReshapeOpByLinearization>(context);
1006 }
1007 
1008 void mlir::populateFoldReshapeOpsByExpansionPatterns(
1009     MLIRContext *context, OwningRewritePatternList &patterns) {
1010   patterns.insert<FoldReshapeWithGenericOpByExpansion,
1011                   FoldWithProducerReshapeOpByExpansion<GenericOp>,
1012                   FoldWithProducerReshapeOpByExpansion<IndexedGenericOp>>(
1013       context);
1014 }
1015 
1016 void mlir::populateLinalgTensorOpsFusionPatterns(
1017     MLIRContext *context, OwningRewritePatternList &patterns) {
1018   patterns.insert<FuseTensorOps<GenericOp>, FuseTensorOps<IndexedGenericOp>,
1019                   FoldSplatConstants<GenericOp>,
1020                   FoldSplatConstants<IndexedGenericOp>>(context);
1021   populateFoldReshapeOpsByExpansionPatterns(context, patterns);
1022   GenericOp::getCanonicalizationPatterns(patterns, context);
1023   IndexedGenericOp::getCanonicalizationPatterns(patterns, context);
1024   TensorReshapeOp::getCanonicalizationPatterns(patterns, context);
1025 }
1026 
1027 std::unique_ptr<Pass> mlir::createLinalgFusionOfTensorOpsPass() {
1028   return std::make_unique<FusionOfTensorOpsPass>();
1029 }
1030 
1031 std::unique_ptr<Pass> mlir::createFoldReshapeOpsByLinearizationPass() {
1032   return std::make_unique<FoldReshapeOpsByLinearizationPass>();
1033 }
1034