1 //===- ElementwiseOpFusion.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/Matchers.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Support/LLVM.h"
24 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
25 
26 using namespace mlir;
27 using namespace mlir::linalg;
28 
29 /// Append to `fusedOpIndexingMapAttrs` the indexing maps for the operands of
30 /// the `producer` to use in the fused operation given the indexing map of the
31 /// result of the producer in the consumer.
32 static AffineMap getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
33     OpOperand *producerOpOperand, AffineMap producerResultIndexMap,
34     AffineMap fusedConsumerArgIndexMap) {
35   // The indexing map in the consumer op (fusedConsumerArgIndexMap) is a map
36   // from consumer loop -> consumer arg tensor index/producer result tensor
37   // index. The fused loop is same as the consumer loop. For each producer arg
38   // the indexing map to be computed is a map from consumer loop -> producer
39   // arg tensor index.
40   // producerResultIndexMap is a map from producer loop -> tensor index.
41   // Compute the inverse to get map from tensor index -> producer loop.
42   // The inverse is a map from producer result tensor index -> producer loop.
43   AffineMap invProducerResultIndexMap =
44       inversePermutation(producerResultIndexMap);
45   assert(invProducerResultIndexMap &&
46          "expected producer result indexig map to be invertible");
47 
48   LinalgOp producer = cast<LinalgOp>(producerOpOperand->getOwner());
49   // argMap is a map from producer loop -> producer arg tensor index.
50   AffineMap argMap = producer.getTiedIndexingMap(producerOpOperand);
51 
52   // Compose argMap with invProducerResultIndexMap to get a map from
53   // producer result tensor index -> producer arg tensor index.
54   AffineMap t1 = argMap.compose(invProducerResultIndexMap);
55 
56   // Compose t1 with fusedConsumerArgIndexMap gives an indexing map from
57   // consumer loop/ fused loop -> producer arg tensor index.
58   return t1.compose(fusedConsumerArgIndexMap);
59 }
60 
61 /// Conditions for elementwise fusion of generic operations.
62 static bool areElementwiseOpsFusable(GenericOp producer, GenericOp consumer,
63                                      OpOperand *consumerOpOperand) {
64   // Producer and consumer must have tensor semantics.
65   if (!producer.hasTensorSemantics() || !consumer.hasTensorSemantics())
66     return false;
67 
68   // Verify that
69   // - the producer has all "parallel" iterator type.
70   if (producer.getNumParallelLoops() != producer.getNumLoops())
71     return false;
72 
73   // Only allow fusing the producer of an input operand for now.
74   // TODO: allow fusing the producer of an output operand.
75   if (!consumer.isInputTensor(consumerOpOperand))
76     return false;
77 
78   // Get the consumer index map. The number of results of the consumer index
79   // map must match the number of loops of the producer.
80   AffineMap consumerIndexMap = consumer.getTiedIndexingMap(consumerOpOperand);
81   if (consumerIndexMap.getNumResults() != producer.getNumLoops())
82     return false;
83 
84   // Currently support only operations with single result.
85   if (producer.getNumOutputs() != 1)
86     return false;
87 
88   // Finally the index_map for the result must be invertible. For now just
89   // verify it is a permutation.
90   AffineMap producerResultIndexMap =
91       producer.getTiedIndexingMap(producer.getOutputOperand(0));
92   if (!producerResultIndexMap.isPermutation())
93     return false;
94 
95   // Ensure that the fusion does not remove size information required to
96   // get the loop bounds. For non-reduction generics, this is trivially the
97   // case due to the output operand. For reductions, we need to check that after
98   // the fusion, each loop dimension has at least one input that defines it.
99   if ((consumer.getNumReductionLoops())) {
100     llvm::BitVector coveredDims(consumer.getNumLoops(), false);
101 
102     auto addToCoveredDims = [&](AffineMap map) {
103       for (auto result : map.getResults())
104         if (auto dimExpr = result.dyn_cast<AffineDimExpr>())
105           coveredDims[dimExpr.getPosition()] = true;
106     };
107 
108     for (auto pair :
109          llvm::zip(consumer->getOperands(), consumer.getIndexingMaps())) {
110       Value operand = std::get<0>(pair);
111       if (operand == consumerOpOperand->get())
112         continue;
113       AffineMap operandMap = std::get<1>(pair);
114       addToCoveredDims(operandMap);
115     }
116 
117     for (OpOperand *operand : producer.getInputOperands()) {
118       AffineMap newIndexingMap =
119           getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
120               operand, producerResultIndexMap, consumerIndexMap);
121       addToCoveredDims(newIndexingMap);
122     }
123     if (!coveredDims.all())
124       return false;
125   }
126 
127   return true;
128 }
129 
130 /// Generate the region of the fused tensor operation. The region of the fused
131 /// op must be empty.
132 static void
133 generateFusedElementwiseOpRegion(PatternRewriter &rewriter, GenericOp fusedOp,
134                                  AffineMap consumerToProducerLoopsMap,
135                                  OpOperand *consumerOpOperand,
136                                  unsigned nloops) {
137   auto producer = cast<GenericOp>(consumerOpOperand->get().getDefiningOp());
138   auto consumer = cast<GenericOp>(consumerOpOperand->getOwner());
139   // Build the region of the fused op.
140   Block &producerBlock = producer->getRegion(0).front();
141   Block &consumerBlock = consumer->getRegion(0).front();
142   Block *fusedBlock = new Block();
143   fusedOp.region().push_back(fusedBlock);
144   BlockAndValueMapping mapper;
145   OpBuilder::InsertionGuard guard(rewriter);
146   rewriter.setInsertionPointToStart(fusedBlock);
147 
148   // 2. Add an index operation for every fused loop dimension and use the
149   // `consumerToProducerLoopsMap` to map the producer indices.
150   if (producer.hasIndexSemantics()) {
151     // Add an index operation for every fused loop dimension.
152     unsigned numFusedOpLoops =
153         std::max(producer.getNumLoops(), consumer.getNumLoops());
154     SmallVector<Value> fusedIndices;
155     fusedIndices.reserve(numFusedOpLoops);
156     llvm::transform(llvm::seq<uint64_t>(0, numFusedOpLoops),
157                     std::back_inserter(fusedIndices), [&](uint64_t dim) {
158                       return rewriter.create<IndexOp>(producer.getLoc(), dim);
159                     });
160     for (IndexOp indexOp :
161          llvm::make_early_inc_range(producerBlock.getOps<IndexOp>())) {
162       Value newIndex = rewriter.create<mlir::AffineApplyOp>(
163           producer.getLoc(),
164           consumerToProducerLoopsMap.getSubMap(indexOp.dim()), fusedIndices);
165       mapper.map(indexOp.getResult(), newIndex);
166     }
167   }
168   // TODO: allow fusing the producer of an output operand.
169   assert(consumer.isInputTensor(consumerOpOperand) &&
170          "expected producer of input operand");
171   // 3. Consumer input operands up to consumerIdx (exclusive).
172   for (BlockArgument bbArg : consumerBlock.getArguments().take_front(
173            consumerOpOperand->getOperandNumber())) // input assumption.
174     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
175 
176   // Replacing consumerIdx requires getting the cloned, yielded, value from
177   // the (cloned) producer block. This happens in step 9.
178 
179   // 4. Splice in producer's input operands.
180   for (BlockArgument bbArg :
181        producerBlock.getArguments().take_front(producer.getNumInputs()))
182     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
183 
184   // 4.b. Producer output operand/map that is fused needs to be mapped to the
185   // producer bbArg if it is an "initTensor" (i.e. its value is actually read).
186   assert(producer->getNumResults() == 1 && "expected single result producer");
187   if (producer.isInitTensor(producer.getOutputOperand(0))) {
188     BlockArgument bbArg = producerBlock.getArguments()
189                               .drop_front(producer.getNumInputs())
190                               // TODO: bbArg index of
191                               .front();
192     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
193   }
194   // 5. Remaining consumer's input operands (drop past index `consumerIdx`).
195   for (BlockArgument bbArg :
196        consumerBlock.getArguments()
197            .take_front(consumer.getNumInputs())
198            .drop_front(consumerOpOperand->getOperandNumber() + 1))
199     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
200   // 6. All of consumer's output operands.
201   for (BlockArgument bbArg :
202        consumerBlock.getArguments().take_back(consumer.getNumOutputs()))
203     mapper.map(bbArg, fusedBlock->addArgument(bbArg.getType()));
204   // 7. All of producer's output operands except the one fused.
205   // TODO: allow fusion of multi-result producers.
206   assert(producer->getNumResults() == 1 && "expected single result producer");
207 
208   // 8. Clone all producer operations except for the yield and index operations
209   // to the fused operation.
210   for (auto &op : producerBlock.without_terminator()) {
211     if (!isa<IndexOp>(op))
212       rewriter.clone(op, mapper);
213   }
214   // 9. Now we can map the consumerBlock's `consumerIdx` block argument. Just
215   // forward the yield operand.
216   auto yieldOp = cast<linalg::YieldOp>(producerBlock.getTerminator());
217   // TODO: allow fusion of multi-result producers.
218   assert(producer->getNumResults() == 1 && "expected single result producer");
219   unsigned producerResultNumber = 0;
220   Value replacement =
221       mapper.lookupOrDefault(yieldOp.getOperand(producerResultNumber));
222   // Sanity checks, if replacement is not already in the mapper then it must be
223   // produced outside.
224   if (replacement == yieldOp.getOperand(producerResultNumber)) {
225     if (auto bb = replacement.dyn_cast<BlockArgument>())
226       assert(bb.getOwner() != &producerBlock &&
227              "yielded block argument must have been mapped");
228     else
229       assert(!producer->isAncestor(replacement.getDefiningOp()) &&
230              "yielded value must have been mapped");
231   }
232   mapper.map(consumerBlock.getArgument(consumerOpOperand->getOperandNumber()),
233              replacement);
234   // 10. Clone operations from the consumer to the fused op.
235   for (auto &op : consumerBlock.getOperations())
236     rewriter.clone(op, mapper);
237 
238   // Sanity checks.
239   assert(fusedBlock->getNumArguments() == fusedOp.getNumOperands() &&
240          "Ill-formed GenericOp region");
241 }
242 
243 static Optional<SmallVector<Value>>
244 fuseElementwiseOpsImpl(GenericOp producer, OpOperand *consumerOpOperand,
245                        const ControlElementwiseOpsFusionFn &controlFn,
246                        PatternRewriter &rewriter) {
247   auto consumer = cast<GenericOp>(consumerOpOperand->getOwner());
248   if (!areElementwiseOpsFusable(producer, consumer, consumerOpOperand) ||
249       !controlFn(producer->getResult(0), *consumerOpOperand))
250     return llvm::None;
251 
252   // TODO: allow fusing the producer of an output operand.
253   assert(consumer.isInputTensor(consumerOpOperand) &&
254          "expected producer of input operand");
255 
256   // Compute the fused operands list and indexing maps.
257   SmallVector<Value> fusedOperands;
258   SmallVector<AffineMap> fusedIndexMaps;
259   fusedOperands.reserve(producer->getNumOperands() +
260                         consumer->getNumOperands());
261   fusedIndexMaps.reserve(producer->getNumOperands() +
262                          consumer->getNumOperands());
263   // In the following, numbering matches that of `generateFusedTensorOpRegion`.
264   // 3. Consumer input operands/maps up to consumerIdx (exclusive).
265   SmallVector<OpOperand *> consumerInputs = consumer.getInputOperands();
266   SmallVector<OpOperand *>::iterator it =
267       llvm::find(consumerInputs, consumerOpOperand);
268   assert(it != consumerInputs.end() && "expected to find the consumer operand");
269   for (OpOperand *opOperand : llvm::make_range(consumerInputs.begin(), it)) {
270     fusedOperands.push_back(opOperand->get());
271     fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand));
272   }
273   // 4. Splice in producer's input operands/maps.
274   assert(producer->getNumResults() == 1 && "expected single result producer");
275   AffineMap producerResultIndexMap =
276       producer.getTiedIndexingMap(producer.getOutputOperand(0));
277   for (OpOperand *opOperand : producer.getInputOperands()) {
278     fusedOperands.push_back(opOperand->get());
279     // Compute indexing maps for the producer args in the fused operation.
280     AffineMap map = getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
281         opOperand, producerResultIndexMap,
282         consumer.getTiedIndexingMap(consumerOpOperand));
283     fusedIndexMaps.push_back(map);
284   }
285   // 4.b. Producer output operand/map that is fused needs to be passed if it is
286   // an "initTensor" (i.e. its value is actually read).
287   assert(producer->getNumResults() == 1 && "expected single result producer");
288   if (producer.isInitTensor(producer.getOutputOperand(0))) {
289     fusedOperands.push_back(producer.getOutputOperand(0)->get());
290     // Compute indexing maps for the producer args in the fused operation.
291     AffineMap map = getIndexingMapOfProducerOperandsInCoordinatesOfFusedOp(
292         producer.getOutputOperand(0), producerResultIndexMap,
293         consumer.getTiedIndexingMap(consumerOpOperand));
294     fusedIndexMaps.push_back(map);
295   }
296   // 5. Remaining consumer's input operands/maps (drop past index
297   // `consumerIdx`).
298   for (OpOperand *opOperand :
299        llvm::make_range(std::next(it), consumerInputs.end())) {
300     fusedOperands.push_back(opOperand->get());
301     fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand));
302   }
303   // 6. All of consumer's output operands (skip operands: added by the builder).
304   for (OpOperand *opOperand : consumer.getOutputOperands())
305     fusedIndexMaps.push_back(consumer.getTiedIndexingMap(opOperand));
306   // 7. All of producer's output operands/maps except the one fused.
307   // TODO: allow fusion of multi-result producers.
308   assert(producer->getNumResults() == 1 && "expected single result producer");
309 
310   // Generate the fused op.
311   SmallVector<Value> consumerOutputs = consumer.getOutputOperands();
312   auto fusedOp = rewriter.create<GenericOp>(
313       consumer.getLoc(), consumer->getResultTypes(),
314       /*inputs=*/fusedOperands,
315       // TODO: handle outputs.
316       consumerOutputs, rewriter.getAffineMapArrayAttr(fusedIndexMaps),
317       consumer.iterator_types(),
318       /*doc=*/nullptr,
319       /*library_call=*/nullptr);
320 
321   // Construct an AffineMap from consumer loops to producer loops.
322   // consumer loop -> tensor index
323   AffineMap consumerResultIndexMap =
324       consumer.getTiedIndexingMap(consumerOpOperand);
325   // tensor index -> producer loop
326   AffineMap invProducerResultIndexMap =
327       inversePermutation(producerResultIndexMap);
328   assert(invProducerResultIndexMap &&
329          "expected producer result indexig map to be invertible");
330   // consumer loop -> producer loop
331   AffineMap consumerToProducerLoopsMap =
332       invProducerResultIndexMap.compose(consumerResultIndexMap);
333 
334   generateFusedElementwiseOpRegion(rewriter, fusedOp,
335                                    consumerToProducerLoopsMap,
336                                    consumerOpOperand, consumer.getNumLoops());
337   return SmallVector<Value>(fusedOp->getResults());
338 }
339 
340 /// Linearize the expressions in `sourceMap` based on the `reassociationMaps`
341 /// provided, given the shape of the source tensor that corresponds to the
342 /// `sourceMap`. Note that this implicitly assumes that the tensors dimensions
343 /// are "row-major" ordered logically.
344 ///
345 /// For example:
346 ///
347 /// %0 = op ... : tensor<?x?x4x5xf32>
348 /// with output index_map `affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>`
349 ///
350 /// and reshape:
351 /// %1 = linalg.tensor_collapse_shape %0 [[0], [0, 1, 2]] :
352 ///        tensor<?x?x4x5xf32> into tensor<?x?xf32>
353 ///
354 /// would be rewritten into:
355 /// %0 = op ... : tensor<?x?x4x5xf32>
356 /// with output index_map
357 ///   `affine_map<(d0, d1, d2, d3) -> (d0, d1 * 20 + d2 * 5 + d3)>`
358 template <typename TensorReshapeOp>
359 static AffineMap linearizeCollapsedDims(AffineMap sourceMap,
360                                         TensorReshapeOp reshapeOp) {
361   constexpr bool isExpanding =
362       std::is_same<TensorReshapeOp, TensorExpandShapeOp>::value;
363   ArrayRef<int64_t> sourceShape =
364       (isExpanding ? reshapeOp.getResultType().getShape()
365                    : reshapeOp.getSrcType().getShape());
366   SmallVector<AffineExpr> resultExprs;
367   ArrayRef<AffineExpr> sourceExprs = sourceMap.getResults();
368   MLIRContext *context = sourceMap.getContext();
369 
370   // Compute the result exprs based on the reassociation maps.
371   for (auto &indices : reshapeOp.getReassociationIndices()) {
372     // Assume that they are in-order and contiguous (already checked in
373     // verifier).
374     assert(!indices.empty());
375     SmallVector<int64_t> sizes;
376     SmallVector<AffineExpr> dimExprs;
377     for (auto en : llvm::zip(sourceShape.slice(indices[0], indices.size()),
378                              sourceExprs.slice(indices[0], indices.size()))) {
379       if (std::get<0>(en) == 1)
380         continue;
381       sizes.push_back(std::get<0>(en));
382       dimExprs.push_back(std::get<1>(en));
383     }
384     AffineExpr linearizedExpr =
385         makeCanonicalStridedLayoutExpr(sizes, dimExprs, context);
386     resultExprs.push_back(linearizedExpr);
387   }
388   return AffineMap::inferFromExprList({resultExprs}).front();
389 }
390 
391 // TensorExpandShapeOp is fusable with its consumer (i.e. reshape as a
392 // producer). Fusing when operand has higher rank will require use of mods and
393 // divs in the indexing maps of the fused op which would make it non-invertible.
394 static bool isTensorReshapeOpFoldableByLinearization(
395     TensorExpandShapeOp expandOp, AffineMap useIndexMap, bool asProducer) {
396   if (!asProducer)
397     return false;
398   return useIndexMap.isPermutation();
399 }
400 
401 // TensorCollapseShapeOp is fusable with its producer (i.e. reshape as a
402 // consumer).
403 static bool isTensorReshapeOpFoldableByLinearization(
404     TensorCollapseShapeOp collapseOp, AffineMap useIndexMap, bool asProducer) {
405   if (asProducer)
406     return false;
407   return useIndexMap.isPermutation();
408 }
409 
410 /// Check if the reshape operation is only expansion into/collapsing of
411 /// unit-dimension.
412 template <typename TensorReshapeOp>
413 static bool isUnitDimExpansionOnly(TensorReshapeOp reshapeOp) {
414   constexpr bool isExpanding =
415       std::is_same<TensorReshapeOp, TensorExpandShapeOp>::value;
416   ArrayRef<int64_t> expandedShape =
417       (isExpanding ? reshapeOp.getResultType().getShape()
418                    : reshapeOp.getSrcType().getShape());
419   for (auto &indices : reshapeOp.getReassociationIndices()) {
420     unsigned numUnitDims = 0;
421     for (int64_t position : indices)
422       if (expandedShape[position] == 1)
423         numUnitDims++;
424     if (numUnitDims != indices.size() - 1)
425       return false;
426   }
427   return true;
428 }
429 
430 /// Conditions for folding a generic operation with a reshape op by expanding
431 /// the iteration space dimensionality for tensor operations. These are
432 /// preconditions assumed by `foldReshapeByDimExpansion` which implements the
433 /// following fusion pattern.
434 ///
435 ///  Consider
436 ///
437 ///  %c = linalg.generic ins(%a, %b : memref<?x?x?xf32>, memref<?x?xf32>)
438 ///         indexing_maps = [affine_map<(d0, d1, d2) -> (d1, d0, d2)>,
439 ///                          affine_map<(d0, d1, d2) -> (d1, d2)>,
440 ///                          affine_map<(d0, d1, d2) -> (d0, d2, d1)>]
441 ///  %d = linalg.tensor_expand_shape %c [[0, 1], [2], [3, 4, 5]]
442 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
443 ///
444 ///  The reshape can be folded into the `genericOp` if its loop dimensionality
445 ///  is increased to match the result (operand) of the tensor_expand_shape.
446 ///  The indexing_map of the fused tensor in the `genericOp` and the
447 ///  reassociation map helps compute the indexing maps of the modified op.
448 ///  For the above example, based on the reassociation map it
449 ///  can be concluded that
450 ///
451 ///  - The loop used to access the first dimension of the fused tensor is split
452 ///    into two.
453 ///  - The loop used to access the second dimension of the fused tensor is kept
454 ///    as is.
455 ///  - The loop used to access the third dimension of the fused tensor is split
456 ///    into three.
457 ///
458 ///  i.e. (e0, e1, e2, e3, e4) is the domain of the indexing map of the modified
459 ///  op, then
460 ///
461 ///   d0 -> e0, e1
462 ///   d1 -> e2, e3, e4
463 ///   d2 -> e5
464 ///
465 ///  substituting this, the generic op can be rewritten as
466 ///
467 ///  %d = linalg.generic ins(%0, %1 : )
468 ///        indexing_maps =
469 ///         [affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e0, e1, e5)>,
470 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e2, e3, e4, e5)>,
471 ///          affine_map<(e0, e1, e2, e3, e4, e5) -> (e0, e1, e5, e2, e3, e4)>]
472 ///
473 ///  Since operands to the linalg generic are now 5D, reshapes can be introduced
474 ///  to make it consistent
475 ///
476 ///  %0 = linalg.tensor_expand_shape %a [[0, 1, 2], [3, 4], [5]]
477 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?x?x?xf32>
478 ///  %1 = linalg.tensor_expand_shape %b [[0, 1, 2], [3]]
479 ///       : tensor<?x?x?xf32> into tensor<?x?x?x?xf32>
480 ///
481 ///  The added reshapes are again expanding patterns, so they will get fused
482 ///  with its producers if possible.
483 static bool isFusableWithReshapeByDimExpansion(GenericOp genericOp,
484                                                OpOperand *fusableOpOperand) {
485   // Is fusable only if:
486   // - All the indexing maps for operands and results are projected
487   //   permutations.
488   // - The fused tensor is not a scalar.
489   // - All the loops are parallel loops.
490   return genericOp.hasTensorSemantics() &&
491          llvm::all_of(genericOp.indexing_maps().getValue(),
492                       [](Attribute attr) {
493                         return attr.cast<AffineMapAttr>()
494                             .getValue()
495                             .isProjectedPermutation();
496                       }) &&
497          genericOp.getTiedIndexingMap(fusableOpOperand).getNumResults() > 0 &&
498          llvm::all_of(genericOp.iterator_types(), [](Attribute attr) {
499            return attr.cast<StringAttr>().getValue() ==
500                   getParallelIteratorTypeName();
501          });
502 }
503 
504 namespace {
505 /// Information needed to expand a generic operation to fold the reshape with
506 /// it.
507 class ExpansionInfo {
508 public:
509   // Computes the mapping from original dimensions of the op to the dimensions
510   // of the expanded op given the `indexingMap` of the fused operand/result of
511   // the generic op, the `reassocationMaps` of the reshape op and the shape of
512   // the expanded op.
513   LogicalResult compute(LinalgOp linalgOp, OpOperand *fusableOpOperand,
514                         ArrayRef<AffineMap> reassociationMaps,
515                         ArrayRef<int64_t> expandedShape,
516                         PatternRewriter &rewriter);
517   unsigned getOrigOpNumDims() const { return reassociation.size(); }
518   unsigned getExpandedOpNumDims() const { return expandedOpNumDims; }
519   ReassociationIndicesRef getExpandedDims(unsigned i) const {
520     return reassociation[i];
521   }
522   ArrayRef<int64_t> getExpandedShapeOfDim(unsigned i) const {
523     return expandedShapeMap[i];
524   }
525 
526 private:
527   /// Reassociation from the dimensions in the original operation to the
528   /// dimension of the expanded operation.
529   SmallVector<ReassociationIndices> reassociation;
530   /// Mapping from extent of loops in the original operation, to the extent of
531   /// loops in the expanded operation.
532   SmallVector<SmallVector<int64_t>> expandedShapeMap;
533   unsigned expandedOpNumDims;
534 };
535 } // namespace
536 
537 LogicalResult ExpansionInfo::compute(LinalgOp linalgOp,
538                                      OpOperand *fusableOpOperand,
539                                      ArrayRef<AffineMap> reassociationMaps,
540                                      ArrayRef<int64_t> expandedShape,
541                                      PatternRewriter &rewriter) {
542   if (reassociationMaps.empty())
543     return failure();
544   AffineMap fusedIndexMap = linalgOp.getTiedIndexingMap(fusableOpOperand);
545 
546   Optional<SmallVector<int64_t, 4>> originalLoopRange =
547       linalgOp.getStaticLoopRanges();
548   if (!originalLoopRange)
549     return rewriter.notifyMatchFailure(linalgOp, "unable to find loop range");
550 
551   reassociation.clear();
552   expandedShapeMap.clear();
553   // Compute the number of dimension in the expanded op that correspond to each
554   // dimension of the original op.
555   SmallVector<unsigned> numExpandedDims(fusedIndexMap.getNumDims(), 1);
556   expandedShapeMap.resize(fusedIndexMap.getNumDims());
557   for (auto resultExpr : llvm::enumerate(fusedIndexMap.getResults())) {
558     unsigned pos = resultExpr.value().cast<AffineDimExpr>().getPosition();
559     AffineMap foldedDims = reassociationMaps[resultExpr.index()];
560     numExpandedDims[pos] = foldedDims.getNumResults();
561     ArrayRef<int64_t> shape =
562         expandedShape.slice(foldedDims.getDimPosition(0), numExpandedDims[pos]);
563     expandedShapeMap[pos].assign(shape.begin(), shape.end());
564   }
565   // The remaining dimensions remain the same.
566   for (unsigned i : llvm::seq<unsigned>(0, fusedIndexMap.getNumDims()))
567     if (expandedShapeMap[i].empty())
568       expandedShapeMap[i] = {(*originalLoopRange)[i]};
569 
570   // Compute reassociation map from the original op to the expanded op.
571   unsigned sum = 0;
572   reassociation.reserve(fusedIndexMap.getNumDims());
573   for (auto numFoldedDim : llvm::enumerate(numExpandedDims)) {
574     auto seq = llvm::seq<int64_t>(sum, sum + numFoldedDim.value());
575     reassociation.emplace_back(seq.begin(), seq.end());
576     sum += numFoldedDim.value();
577   }
578   expandedOpNumDims = sum;
579   return success();
580 }
581 
582 /// Epanding the body of a linalg operation requires adaptations of the accessed
583 /// loop indices. Specifically, access of indices in the original operation need
584 /// to be replaced with linearizations of indices in the expanded op. That
585 /// requires the shape of the expanded dimensions to be static (at least all but
586 /// the most significant). For now check that these are all statically sized.
587 /// Note that this could be extended to handle dynamic case, but the
588 /// implementation below uses `affine.apply` which seems to have issues when the
589 /// shapes are not static.
590 LogicalResult isGenericOpExpandable(GenericOp genericOp,
591                                     const ExpansionInfo &expansionInfo,
592                                     PatternRewriter &rewriter) {
593   if (!genericOp.hasIndexSemantics())
594     return success();
595   for (unsigned i : llvm::seq<unsigned>(0, expansionInfo.getOrigOpNumDims())) {
596     ArrayRef<int64_t> expandedShape = expansionInfo.getExpandedShapeOfDim(i);
597     if (expandedShape.size() == 1)
598       continue;
599     for (int64_t shape : expandedShape.drop_front()) {
600       if (ShapedType::isDynamic(shape)) {
601         return rewriter.notifyMatchFailure(
602             genericOp, "cannot expand due to index semantics and dynamic dims");
603       }
604     }
605   }
606   return success();
607 }
608 
609 /// Return the indexing map to use in the expanded op for a given the
610 /// `indexingMap` of the original operation.
611 static AffineMap
612 getIndexingMapInExpandedOp(OpBuilder &builder, AffineMap indexingMap,
613                            const ExpansionInfo &expansionInfo) {
614   SmallVector<AffineExpr> newExprs;
615   for (AffineExpr expr : indexingMap.getResults()) {
616     unsigned pos = expr.cast<AffineDimExpr>().getPosition();
617     SmallVector<AffineExpr, 4> expandedExprs = llvm::to_vector<4>(
618         llvm::map_range(expansionInfo.getExpandedDims(pos), [&](int64_t v) {
619           return builder.getAffineDimExpr(static_cast<unsigned>(v));
620         }));
621     newExprs.append(expandedExprs.begin(), expandedExprs.end());
622   }
623   return AffineMap::get(expansionInfo.getExpandedOpNumDims(),
624                         indexingMap.getNumSymbols(), newExprs,
625                         builder.getContext());
626 }
627 
628 /// Return the type of the operand/result to use in the expanded op given the
629 /// type in the original op.
630 static RankedTensorType getExpandedType(RankedTensorType originalType,
631                                         AffineMap indexingMap,
632                                         const ExpansionInfo &expansionInfo) {
633   SmallVector<int64_t> expandedShape;
634   for (AffineExpr expr : indexingMap.getResults()) {
635     unsigned dim = expr.cast<AffineDimExpr>().getPosition();
636     auto dimExpansion = expansionInfo.getExpandedShapeOfDim(dim);
637     expandedShape.append(dimExpansion.begin(), dimExpansion.end());
638   }
639   return RankedTensorType::get(expandedShape, originalType.getElementType());
640 }
641 
642 /// Returns the reassociation maps to use in the `linalg.tensor_expand_shape`
643 /// operation to convert the operands of the original operation to operands of
644 /// the expanded operation. The same method is used to compute the
645 /// `linalg.tensor_collapse_shape` used to collapse the result of the expanded
646 /// op to get the value that can replace all uses of the results of the original
647 /// op.
648 static SmallVector<ReassociationIndices>
649 getReassociationForExpansion(AffineMap indexingMap,
650                              const ExpansionInfo &expansionInfo) {
651   SmallVector<ReassociationIndices> reassociation;
652   unsigned numReshapeDims = 0;
653   for (AffineExpr expr : indexingMap.getResults()) {
654     unsigned dim = expr.cast<AffineDimExpr>().getPosition();
655     auto numExpandedDims = expansionInfo.getExpandedDims(dim).size();
656     SmallVector<int64_t, 2> indices = llvm::to_vector<2>(
657         llvm::seq<int64_t>(numReshapeDims, numReshapeDims + numExpandedDims));
658     reassociation.emplace_back(std::move(indices));
659     numReshapeDims += numExpandedDims;
660   }
661   return reassociation;
662 }
663 
664 /// Update the body of an expanded linalg operation having index semantics. The
665 /// indices of the original operation need to be recovered by linearizing the
666 /// indices of the correspoding dimensions of the expanded operation. For now it
667 /// is assumed that the shapes of the expanded operation needed for
668 /// linearization are static.
669 static void updateExpandedGenericOpRegion(PatternRewriter &rewriter,
670                                           Location loc, Region &fusedRegion,
671                                           const ExpansionInfo &expansionInfo) {
672   // Replace the original indices by the linearization of the expanded indices.
673   for (IndexOp indexOp :
674        llvm::make_early_inc_range(fusedRegion.front().getOps<IndexOp>())) {
675     ArrayRef<int64_t> expandedDims =
676         expansionInfo.getExpandedDims(indexOp.dim());
677     assert(!expandedDims.empty() && "expected valid expansion info");
678 
679     // Skip index operations that are not affected by the expansion.
680     if (expandedDims.size() == 1 &&
681         expandedDims.front() == (int64_t)indexOp.dim())
682       continue;
683 
684     // Linearize the expanded indices of the original index dimension.
685     OpBuilder::InsertionGuard guard(rewriter);
686     rewriter.setInsertionPointAfter(indexOp);
687     ArrayRef<int64_t> expandedDimsShape =
688         expansionInfo.getExpandedShapeOfDim(indexOp.dim()).drop_front();
689     SmallVector<Value> expandedIndices;
690     expandedIndices.reserve(expandedDims.size() - 1);
691     llvm::transform(
692         expandedDims.drop_front(), std::back_inserter(expandedIndices),
693         [&](int64_t dim) { return rewriter.create<IndexOp>(loc, dim); });
694     Value newIndex = rewriter.create<IndexOp>(loc, expandedDims.front());
695     for (auto it : llvm::zip(expandedDimsShape, expandedIndices)) {
696       assert(!ShapedType::isDynamic(std::get<0>(it)));
697       AffineExpr idx, acc;
698       bindDims(rewriter.getContext(), idx, acc);
699       newIndex = rewriter.create<AffineApplyOp>(
700           indexOp.getLoc(), idx + acc * std::get<0>(it),
701           ValueRange{std::get<1>(it), newIndex});
702     }
703     rewriter.replaceOp(indexOp, newIndex);
704   }
705 }
706 
707 /// Implements the fusion of a tensor_collapse_shape or a tensor_expand_shape op
708 /// and a generic op as explained in `isFusableWithReshapeByExpansion`. Assumes
709 /// that those conditions have been satisfied.
710 static Optional<SmallVector<Value>>
711 fuseWithReshapeByExpansion(GenericOp genericOp, Operation *reshapeOp,
712                            OpOperand *fusableOpOperand,
713                            PatternRewriter &rewriter) {
714   assert(isFusableWithReshapeByDimExpansion(genericOp, fusableOpOperand) &&
715          "preconditions for fuse operation failed");
716   // Check if reshape is expanding or collapsing.
717   auto expandingReshapeOp = dyn_cast<TensorExpandShapeOp>(*reshapeOp);
718   auto collapsingReshapeOp = dyn_cast<TensorCollapseShapeOp>(*reshapeOp);
719   bool isExpanding = (expandingReshapeOp != nullptr);
720   RankedTensorType expandedType = isExpanding
721                                       ? expandingReshapeOp.getResultType()
722                                       : collapsingReshapeOp.getSrcType();
723 
724   ExpansionInfo expansionInfo;
725   if (failed(expansionInfo.compute(
726           genericOp, fusableOpOperand,
727           isExpanding ? expandingReshapeOp.getReassociationMaps()
728                       : collapsingReshapeOp.getReassociationMaps(),
729           expandedType.getShape(), rewriter)))
730     return llvm::None;
731 
732   if (failed(isGenericOpExpandable(genericOp, expansionInfo, rewriter)))
733     return llvm::None;
734 
735   SmallVector<AffineMap, 4> expandedOpIndexingMaps = llvm::to_vector<4>(
736       llvm::map_range(genericOp.getIndexingMaps(), [&](AffineMap m) {
737         return getIndexingMapInExpandedOp(rewriter, m, expansionInfo);
738       }));
739 
740   SmallVector<Value> expandedOpOperands;
741   expandedOpOperands.reserve(genericOp.getNumInputs());
742   for (OpOperand *opOperand : genericOp.getInputOperands()) {
743     if (opOperand == fusableOpOperand) {
744       expandedOpOperands.push_back(isExpanding ? expandingReshapeOp.src()
745                                                : collapsingReshapeOp.src());
746       continue;
747     }
748     if (genericOp.isInputTensor(opOperand)) {
749       AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
750       RankedTensorType expandedOperandType =
751           getExpandedType(opOperand->get().getType().cast<RankedTensorType>(),
752                           indexingMap, expansionInfo);
753       if (expandedOperandType != opOperand->get().getType()) {
754         // Reshape the operand to get the right type.
755         SmallVector<ReassociationIndices> reassociation =
756             getReassociationForExpansion(indexingMap, expansionInfo);
757         expandedOpOperands.push_back(rewriter.create<TensorExpandShapeOp>(
758             genericOp.getLoc(), expandedOperandType, opOperand->get(),
759             reassociation));
760         continue;
761       }
762     }
763     expandedOpOperands.push_back(opOperand->get());
764   }
765 
766   Location loc = genericOp.getLoc();
767   SmallVector<Value> outputs;
768   for (OpOperand *opOperand : genericOp.getOutputOperands()) {
769     AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
770     RankedTensorType expandedOutputType =
771         getExpandedType(opOperand->get().getType().cast<RankedTensorType>(),
772                         indexingMap, expansionInfo);
773     if (expandedOutputType != opOperand->get().getType()) {
774       SmallVector<ReassociationIndices> reassociation =
775           getReassociationForExpansion(indexingMap, expansionInfo);
776       outputs.push_back(rewriter.create<TensorExpandShapeOp>(
777           genericOp.getLoc(), expandedOutputType, opOperand->get(),
778           reassociation));
779     }
780   }
781 
782   // The iterator types of the expanded op are all parallel.
783   SmallVector<StringRef> iteratorTypes(expansionInfo.getExpandedOpNumDims(),
784                                        getParallelIteratorTypeName());
785 
786   TypeRange resultTypes = ValueRange(outputs).getTypes();
787   auto fusedOp =
788       rewriter.create<GenericOp>(genericOp.getLoc(), resultTypes,
789                                  /*inputs=*/expandedOpOperands, outputs,
790                                  expandedOpIndexingMaps, iteratorTypes);
791   Region &fusedRegion = fusedOp->getRegion(0);
792   Region &originalRegion = genericOp->getRegion(0);
793   rewriter.cloneRegionBefore(originalRegion, fusedRegion, fusedRegion.begin());
794 
795   // Update the index accesses after the expansion.
796   updateExpandedGenericOpRegion(rewriter, loc, fusedRegion, expansionInfo);
797 
798   // Reshape the result values to their original shape if this is a collapsing
799   // reshape folded into its consumer.
800   SmallVector<Value> resultVals;
801   for (OpResult opResult : genericOp->getOpResults()) {
802     int64_t resultNumber = opResult.getResultNumber();
803     if (!isExpanding && resultTypes[resultNumber] != opResult.getType()) {
804       SmallVector<ReassociationIndices> reassociation =
805           getReassociationForExpansion(
806               genericOp.getTiedIndexingMap(
807                   genericOp.getOutputOperand(resultNumber)),
808               expansionInfo);
809       resultVals.push_back(rewriter.create<TensorCollapseShapeOp>(
810           genericOp.getLoc(), opResult.getType(),
811           fusedOp->getResult(resultNumber), reassociation));
812     } else {
813       resultVals.push_back(fusedOp->getResult(resultNumber));
814     }
815   }
816   // Assuming a single result.
817   return resultVals;
818 }
819 
820 namespace {
821 
822 /// Pattern to fold tensor_expand_shape op with its consumer by using the source
823 /// of the reshape op as the operand in the consumer (instead of the result of
824 /// the tensor_collapse_shape). The corresponding index map in the consumer
825 /// needs to be modified to linearize the folded dimension.
826 ///
827 /// For example,
828 ///
829 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
830 /// %0 = linalg.tensor_expand_shape %arg0 [[0], [1, 2], [3]]
831 ///      tensor<?x?x?xf32> into tensor<?x?x4x?xf32>
832 /// %1 = linalg.generic { indexing_maps = [#map0, #map0, #map0], ... }
833 ///        ins(%0, %arg1 : tensor<?x?x4x?xf32>, tensor<?x?x4x?xf32>) ...
834 ///        -> tensor<?x?x4x?xf32>
835 ///
836 /// can be folded into
837 ///
838 /// #map0 = affine_map<(d0, d1, d2, d3) -> (d0, d1 * 4 + d2, d3)>
839 /// #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
840 /// %0 = linalg.generic { indexing_maps = [#map0, #map1, #map1] ... }
841 ///        ins(%arg0, %arg1 : tensor<?x?x?xf32>, tensor<?x?x4x?xf32>) ...
842 ///        -> tensor<?x?x4x?xf32>
843 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp>
844 struct FoldProducerReshapeOpByLinearization
845     : public OpRewritePattern<GenericOp> {
846   using OpRewritePattern<GenericOp>::OpRewritePattern;
847 
848   LogicalResult matchAndRewrite(GenericOp genericOp,
849                                 PatternRewriter &rewriter) const override {
850     if (!genericOp.hasTensorSemantics())
851       return failure();
852     SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands();
853     for (auto en : llvm::enumerate(inputOperands)) {
854       auto reshapeOp = en.value()->get().getDefiningOp<TensorReshapeOp>();
855       if (!reshapeOp)
856         continue;
857 
858       if (!isTensorReshapeOpFoldableByLinearization(
859               reshapeOp, genericOp.getTiedIndexingMap(en.value()),
860               /*asProducer =*/true) ||
861           (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp)))
862         continue;
863 
864       // Compute the fused operands list,
865       SmallVector<Value> fusedOperands = genericOp.getInputOperands();
866       fusedOperands[en.index()] = reshapeOp.src();
867       SmallVector<Value> outputOperands = genericOp.getOutputOperands();
868       llvm::append_range(fusedOperands, outputOperands);
869 
870       // Compute indexing_maps for the fused operation. The indexing_maps for
871       // the operands of the consumers that arent fused are the same.
872       SmallVector<AffineMap> fusedIndexMaps = genericOp.getIndexingMaps();
873 
874       // Accepted consumer maps are either identity or permutation.
875       auto invMap = inversePermutation(fusedIndexMaps[en.index()]);
876 
877       // Compute the indexing map to use for the result of the producer.
878       AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp);
879       // The modified map cannot have symbols.
880       if (modifiedMap.getNumSymbols())
881         return failure();
882       for (AffineExpr expr : modifiedMap.getResults()) {
883         if (!expr.isPureAffine())
884           return failure();
885       }
886       fusedIndexMaps[en.index()] = modifiedMap;
887 
888       // Further check that the resulting index maps can be fused and
889       // inverted. Without this the resultant op is not legal.
890       if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
891         return rewriter.notifyMatchFailure(
892             genericOp, "fused op loop bound computation failed");
893       }
894 
895       rewriter.startRootUpdate(genericOp);
896       genericOp->setOperands(fusedOperands);
897       genericOp.indexing_mapsAttr(
898           rewriter.getAffineMapArrayAttr(fusedIndexMaps));
899       rewriter.finalizeRootUpdate(genericOp);
900       return success();
901     }
902     return failure();
903   }
904 };
905 
906 static SmallVector<ReassociationIndices>
907 getReassociationIndices(ArrayRef<AffineMap> maps) {
908   SmallVector<ReassociationIndices> reassociation;
909   for (AffineMap map : maps) {
910     ReassociationIndices indices;
911     for (unsigned i = 0, e = map.getNumResults(); i < e; i++) {
912       unsigned pos = map.getResult(i).cast<AffineDimExpr>().getPosition();
913       indices.push_back(pos);
914     }
915     reassociation.push_back(indices);
916   }
917   return reassociation;
918 }
919 
920 /// Pattern to move rank reducing reshape after an elementwise linalg generic
921 /// op. This is useful to expose more fusion opportunities between named ops and
922 /// generic ops. This can only be done if there is no broadcast or permuation
923 /// within the dimensions we need to merge.
924 ///
925 /// For example,
926 ///
927 ///  %0 = linalg.tensor_expand_shape %A [[0, 1], [2]]
928 ///      : tensor<12544x16xf32> into tensor<112x112x16xf32>
929 ///  %2 = linalg.generic {indexing_maps = [
930 ///    affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
931 ///    affine_map<(d0, d1, d2) -> (d2)>,
932 ///    affine_map<(d0, d1, d2) -> (d0, d1, d2)>], iterator_types =
933 ///    ["parallel", "parallel", "parallel"]} {
934 ///  } -> tensor<112x112x16xf32>
935 ///
936 ///  into
937 ///
938 ///  %2 = linalg.generic {indexing_maps = [
939 ///    affine_map<(d0, d1) -> (d0, d1)>,
940 ///    affine_map<(d0, d1) -> (d1)>,
941 ///    affine_map<(d0, d1) -> (d0, d1)>],
942 ///    iterator_types = ["parallel", "parallel"]} ins(%arg0, %arg1
943 ///    : tensor<12544x16xf32>, tensor<16xf32>) outs(%1 : tensor<12544x16xf32>) {
944 ///  } -> tensor<12544x16xf32>
945 ///  %3 = linalg.tensor_expand_shape %2 [[0, 1], [2]]
946 ///    : tensor<12544x16xf32> into tensor<112x112x16xf32>
947 struct PushExpandingReshape : public OpRewritePattern<GenericOp> {
948   using OpRewritePattern<GenericOp>::OpRewritePattern;
949 
950   LogicalResult matchAndRewrite(GenericOp genericOp,
951                                 PatternRewriter &rewriter) const override {
952     // Only apply to elementwise linalg on tensor.
953     if (!genericOp.hasTensorSemantics() ||
954         genericOp.getNumParallelLoops() != genericOp.getNumLoops())
955       return failure();
956     // Only support identity output maps. It could be extended to permuations if
957     // needed.
958     if (llvm::any_of(genericOp.getOutputOperands(), [&](OpOperand *opOperand) {
959           return !genericOp.getTiedIndexingMap(opOperand).isIdentity();
960         }))
961       return failure();
962     int64_t destRank = genericOp.getNumParallelLoops();
963     SmallVector<Value> newOperands = genericOp.getInputOperands();
964     TensorExpandShapeOp reshapeFound;
965     // 1. Look for tensor_expand_shape operands and figure out save the
966     // dimensions merged.
967     SmallVector<OpOperand *> inputOperands = genericOp.getInputOperands();
968     for (auto en : llvm::enumerate(inputOperands)) {
969       auto reshapeOp =
970           en.value()->get().template getDefiningOp<TensorExpandShapeOp>();
971       if (!reshapeOp)
972         continue;
973       // TODO: We could support non-identity map as long as the merged
974       // dimensions are still contiguous.
975       if (!genericOp.getTiedIndexingMap(en.value()).isIdentity())
976         continue;
977       if (reshapeFound) {
978         // Only support a second reshape op if it has the same reassociate maps.
979         if (reshapeFound.getReassociationMaps() ==
980             reshapeOp.getReassociationMaps())
981           newOperands[en.index()] = reshapeOp.src();
982         continue;
983       }
984       reshapeFound = reshapeOp;
985       newOperands[en.index()] = reshapeOp.src();
986     }
987     if (!reshapeFound)
988       return failure();
989 
990     // Calculate the reassociation indices and rassociated reverse map.
991     SmallVector<ReassociationIndices> reassociation =
992         getReassociationIndices(reshapeFound.getReassociationMaps());
993     SmallVector<unsigned> remap(destRank);
994     for (auto &indices : llvm::enumerate(reassociation)) {
995       for (int64_t index : indices.value()) {
996         remap[index] = indices.index();
997       }
998     }
999     // 2. Verify that we can merge the dimensions in the linalg and that we
1000     // don't need to create new reshapes operands. Inserting new reshape
1001     // operands would defeat the purpose of the transformation.
1002     for (auto en : llvm::enumerate(inputOperands)) {
1003       if (en.value()->get() == newOperands[en.index()]) {
1004         AffineMap map = genericOp.getTiedIndexingMap(en.value());
1005         for (unsigned i : llvm::seq(unsigned(0), map.getNumResults())) {
1006           if (reassociation[remap[map.getDimPosition(i)]].size() > 1)
1007             return failure();
1008         }
1009       }
1010     }
1011 
1012     // 3. Calculate the affine map remapping and the reassociation to apply to
1013     // output tensors.
1014     SmallVector<AffineMap> newMaps;
1015     unsigned newRank = reassociation.size();
1016     for (auto map : genericOp.getIndexingMaps()) {
1017       SmallVector<AffineExpr> newExprs;
1018       for (auto expr : map.getResults()) {
1019         unsigned position = expr.template cast<AffineDimExpr>().getPosition();
1020         // Skip dimension merged except for the last of the group.
1021         if (reassociation[remap[position]].back() == position) {
1022           newExprs.push_back(
1023               getAffineDimExpr(remap[position], genericOp.getContext()));
1024         }
1025       }
1026       newMaps.push_back(
1027           AffineMap::get(newRank, 0, newExprs, genericOp.getContext()));
1028     }
1029 
1030     // 4. Reshape the output tensors.
1031     SmallVector<Value> newOutputs;
1032     SmallVector<Type> newOutputTypes;
1033     for (auto output : genericOp.outputs()) {
1034       auto newOutputType = RankedTensorType::get(
1035           reshapeFound.getSrcType().getShape(),
1036           output.getType().template cast<RankedTensorType>().getElementType());
1037       Value newOutput = rewriter.create<TensorCollapseShapeOp>(
1038           genericOp->getLoc(), newOutputType, output, reassociation);
1039       newOutputTypes.push_back(newOutputType);
1040       newOutputs.push_back(newOutput);
1041     }
1042     // 5. Create a new generic op with lowerer rank.
1043     SmallVector<StringRef> iteratorTypes(newRank,
1044                                          getParallelIteratorTypeName());
1045     auto newOp = rewriter.create<GenericOp>(genericOp->getLoc(), newOutputTypes,
1046                                             newOperands, newOutputs, newMaps,
1047                                             iteratorTypes);
1048     rewriter.inlineRegionBefore(genericOp.region(), newOp.region(),
1049                                 newOp.region().begin());
1050     // 6. Reshape the so that the type matches the uses.
1051     SmallVector<Value> newResults;
1052     for (auto result : llvm::enumerate(newOp->getResults())) {
1053       newResults.push_back(rewriter.create<TensorExpandShapeOp>(
1054           genericOp->getLoc(), genericOp.getOutputTensorTypes()[result.index()],
1055           result.value(), reassociation));
1056     }
1057     rewriter.replaceOp(genericOp, newResults);
1058     return success();
1059   }
1060 };
1061 
1062 /// Pattern to fuse a tensor_collapse_shape op with its consumer generic op,
1063 /// when the reshape op is collapsing dimensions. The dimensionality of the loop
1064 /// in the consumer is expanded.
1065 class FoldWithProducerReshapeOpByExpansion
1066     : public OpRewritePattern<GenericOp> {
1067 public:
1068   FoldWithProducerReshapeOpByExpansion(
1069       MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes,
1070       PatternBenefit benefit = 1)
1071       : OpRewritePattern<GenericOp>(context, benefit),
1072         controlFoldingReshapes(foldReshapes) {}
1073 
1074   LogicalResult matchAndRewrite(GenericOp genericOp,
1075                                 PatternRewriter &rewriter) const override {
1076     for (OpOperand *opOperand : genericOp.getInputTensorOperands()) {
1077       TensorCollapseShapeOp reshapeOp =
1078           opOperand->get().getDefiningOp<TensorCollapseShapeOp>();
1079       if (!reshapeOp)
1080         continue;
1081       // Fold only if
1082       // - The tensor reshape op is folding.
1083       // - All constraints of fusing with reshape by expansion are met.
1084       if (!isFusableWithReshapeByDimExpansion(genericOp, opOperand) ||
1085           (!controlFoldingReshapes(reshapeOp->getResult(0), *opOperand)))
1086         continue;
1087 
1088       Optional<SmallVector<Value>> replacementValues =
1089           fuseWithReshapeByExpansion(genericOp, reshapeOp, opOperand, rewriter);
1090       if (!replacementValues)
1091         return failure();
1092       rewriter.replaceOp(genericOp, replacementValues.getValue());
1093       return success();
1094     }
1095     return failure();
1096   }
1097 
1098 private:
1099   ControlElementwiseOpsFusionFn controlFoldingReshapes;
1100 };
1101 
1102 /// Pattern to fold tensor_collapse_shape or tensor_expand_shape op with its
1103 /// producer. The corresponding index map in the consumer needs to be modified
1104 /// to linearize the folded dimension.
1105 template <bool foldUnitDimReshapesOnly, typename TensorReshapeOp>
1106 struct FoldConsumerReshapeOpByLinearization
1107     : public OpRewritePattern<TensorReshapeOp> {
1108   using OpRewritePattern<TensorReshapeOp>::OpRewritePattern;
1109 
1110   LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp,
1111                                 PatternRewriter &rewriter) const override {
1112     GenericOp producer = reshapeOp.src().template getDefiningOp<GenericOp>();
1113     if (!producer || !producer.hasTensorSemantics() ||
1114         producer.getNumOutputs() != 1 ||
1115         !isTensorReshapeOpFoldableByLinearization(
1116             reshapeOp,
1117             producer.getTiedIndexingMap(producer.getOutputOperand(0)),
1118             /*asProducer =*/false) ||
1119         (foldUnitDimReshapesOnly && !isUnitDimExpansionOnly(reshapeOp)))
1120       return failure();
1121     // The indexing_maps for the operands of the fused operation are same as
1122     // those for the operands of the producer.
1123     SmallVector<AffineMap> fusedIndexMaps = producer.getIndexingMaps();
1124 
1125     auto invMap = inversePermutation(
1126         producer.getTiedIndexingMap(producer.getOutputOperand(0)));
1127 
1128     // Compute the indexing map to use for the operand of the producer.
1129     AffineMap modifiedMap = linearizeCollapsedDims(invMap, reshapeOp);
1130     for (AffineExpr expr : modifiedMap.getResults()) {
1131       if (!expr.isPureAffine()) {
1132         return rewriter.notifyMatchFailure(
1133             producer, "fused op indexing map is not affine");
1134       }
1135     }
1136     fusedIndexMaps.back() = modifiedMap;
1137 
1138     // Further check that the resulting index maps can be fused and
1139     // inverted. Without this the resultant op is not legal.
1140     if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
1141       return rewriter.notifyMatchFailure(
1142           producer, "fused op loop bound computation failed");
1143     }
1144 
1145     Location loc = producer.getLoc();
1146     SmallVector<Value> inputOperands = producer.getInputOperands();
1147     Value output = rewriter.create<TensorReshapeOp>(
1148         loc, producer.getOutputOperand(0)->get(),
1149         reshapeOp.getReassociationExprs());
1150     auto fusedOp = rewriter.create<GenericOp>(
1151         loc, reshapeOp.getResultType(),
1152         /*inputs=*/inputOperands,
1153         // TODO: handle outputs.
1154         /*outputs=*/output, rewriter.getAffineMapArrayAttr(fusedIndexMaps),
1155         producer.iterator_types(),
1156         /*doc=*/nullptr,
1157         /*library_call=*/nullptr);
1158     auto &fusedRegion = fusedOp->getRegion(0);
1159     rewriter.cloneRegionBefore(producer->getRegion(0), fusedRegion,
1160                                fusedRegion.begin());
1161     rewriter.replaceOp(reshapeOp, fusedOp->getResults());
1162     return success();
1163   }
1164 };
1165 
1166 /// Pattern to fold a tensor_expand_shape op with its producer generic op
1167 /// by expanding the dimensionality of the loop in the producer op.
1168 struct FoldReshapeWithGenericOpByExpansion
1169     : public OpRewritePattern<TensorExpandShapeOp> {
1170 
1171   FoldReshapeWithGenericOpByExpansion(
1172       MLIRContext *context, ControlElementwiseOpsFusionFn foldReshapes,
1173       PatternBenefit benefit = 1)
1174       : OpRewritePattern<TensorExpandShapeOp>(context, benefit),
1175         controlFoldingReshapes(foldReshapes) {}
1176 
1177   LogicalResult matchAndRewrite(TensorExpandShapeOp reshapeOp,
1178                                 PatternRewriter &rewriter) const override {
1179     // Fold only if all constraints of fusing with reshape by expansion are met.
1180     GenericOp producer = reshapeOp.src().getDefiningOp<GenericOp>();
1181     if (!producer || producer.getNumOutputs() != 1 ||
1182         !isFusableWithReshapeByDimExpansion(producer,
1183                                             producer.getOutputOperand(0)) ||
1184         !controlFoldingReshapes(producer->getResult(0),
1185                                 reshapeOp->getOpOperand(0)))
1186       return failure();
1187     Optional<SmallVector<Value>> replacementValues = fuseWithReshapeByExpansion(
1188         producer, reshapeOp, producer.getOutputOperand(0), rewriter);
1189     if (!replacementValues)
1190       return failure();
1191     rewriter.replaceOp(reshapeOp, replacementValues.getValue());
1192     return success();
1193   }
1194 
1195 private:
1196   ControlElementwiseOpsFusionFn controlFoldingReshapes;
1197 };
1198 
1199 /// Pattern to fold a generic op with a splat constant/scalar constant. Does not
1200 /// handle cases where the constant is not single-valued.
1201 class FoldScalarOrSplatConstant : public OpRewritePattern<GenericOp> {
1202 public:
1203   FoldScalarOrSplatConstant(MLIRContext *context,
1204                             ControlElementwiseOpsFusionFn &fun,
1205                             PatternBenefit benefit = 1)
1206       : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {}
1207 
1208   LogicalResult matchAndRewrite(GenericOp genericOp,
1209                                 PatternRewriter &rewriter) const override {
1210     if (!genericOp.hasTensorSemantics())
1211       return failure();
1212     for (OpOperand *opOperand : genericOp.getInputOperands()) {
1213       Operation *def = opOperand->get().getDefiningOp();
1214       Attribute constantAttr;
1215       auto isScalarOrSplatConstantOp = [&constantAttr](Operation *def) -> bool {
1216         {
1217           DenseElementsAttr splatAttr;
1218           if (matchPattern(def, m_Constant<DenseElementsAttr>(&splatAttr)) &&
1219               splatAttr.isSplat() &&
1220               splatAttr.getType().getElementType().isIntOrFloat()) {
1221             constantAttr = splatAttr.getSplatValue<Attribute>();
1222             return true;
1223           }
1224         }
1225         {
1226           IntegerAttr intAttr;
1227           if (matchPattern(def, m_Constant<IntegerAttr>(&intAttr))) {
1228             constantAttr = intAttr;
1229             return true;
1230           }
1231         }
1232         {
1233           FloatAttr floatAttr;
1234           if (matchPattern(def, m_Constant<FloatAttr>(&floatAttr))) {
1235             constantAttr = floatAttr;
1236             return true;
1237           }
1238         }
1239         return false;
1240       };
1241 
1242       auto resultValue = opOperand->get().dyn_cast<OpResult>();
1243       if (!def || !resultValue || !isScalarOrSplatConstantOp(def) ||
1244           !controlFn(resultValue, *opOperand))
1245         continue;
1246 
1247       // The operands and the indexing_maps of the fused operation the same as
1248       // the operands and indexing_maps of the generic operations with the
1249       // values at the constant index dropped.
1250       SmallVector<AffineMap> fusedIndexMaps;
1251       SmallVector<Value> fusedOperands;
1252       SmallVector<Location> fusedLocs{genericOp.getLoc()};
1253       fusedIndexMaps.reserve(genericOp.getNumInputsAndOutputs());
1254       fusedOperands.reserve(genericOp.getNumInputs());
1255       fusedLocs.reserve(fusedLocs.size() + genericOp.getNumInputs());
1256       for (OpOperand *inputOperand : genericOp.getInputOperands()) {
1257         if (inputOperand == opOperand)
1258           continue;
1259         Value inputValue = inputOperand->get();
1260         fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(inputOperand));
1261         fusedOperands.push_back(inputValue);
1262         fusedLocs.push_back(inputValue.getLoc());
1263       }
1264       for (OpOperand *outputOperand : genericOp.getOutputOperands())
1265         fusedIndexMaps.push_back(genericOp.getTiedIndexingMap(outputOperand));
1266 
1267       // Check if the operation shapes to loops map is computable.
1268       if (!inversePermutation(concatAffineMaps(fusedIndexMaps))) {
1269         return rewriter.notifyMatchFailure(
1270             genericOp, "fused op loop bound computation failed");
1271       }
1272 
1273       // Create a constant scalar value from the splat constant.
1274       Value scalarConstant = rewriter.create<arith::ConstantOp>(
1275           def->getLoc(), constantAttr, constantAttr.getType());
1276 
1277       SmallVector<Value> outputOperands = genericOp.getOutputOperands();
1278       auto fusedOp = rewriter.create<GenericOp>(
1279           rewriter.getFusedLoc(fusedLocs), genericOp->getResultTypes(),
1280           /*inputs=*/fusedOperands,
1281           /*outputs=*/outputOperands,
1282           rewriter.getAffineMapArrayAttr(fusedIndexMaps),
1283           genericOp.iterator_types(),
1284           /*doc=*/nullptr,
1285           /*library_call=*/nullptr);
1286 
1287       // Map the block argument corresponding to the replaced argument with the
1288       // scalar constant.
1289       Region &region = genericOp->getRegion(0);
1290       Block &entryBlock = *region.begin();
1291       BlockAndValueMapping mapping;
1292       mapping.map(entryBlock.getArgument(opOperand->getOperandNumber()),
1293                   scalarConstant);
1294       Region &fusedRegion = fusedOp->getRegion(0);
1295       rewriter.cloneRegionBefore(region, fusedRegion, fusedRegion.begin(),
1296                                  mapping);
1297       rewriter.replaceOp(genericOp, fusedOp->getResults());
1298       return success();
1299     }
1300     return failure();
1301   }
1302 
1303 private:
1304   ControlElementwiseOpsFusionFn controlFn;
1305 };
1306 
1307 /// Base class for constant folding linalg.generic ops with N inputs, 1 output,
1308 /// and permutation indexing maps.
1309 ///
1310 /// `ConcreteType` should provide methods with signatures
1311 ///
1312 /// ```c++
1313 ///   bool matchIndexingMaps(GenericOp genericOp) const;
1314 ///   RegionComputationFn getRegionComputeFn(GenericOp) const;
1315 /// ```
1316 ///
1317 /// The latter inspects the region and returns the computation inside as a
1318 /// functor. The functor will be invoked with constant elements for all inputs
1319 /// and should return the corresponding computea constant element for output.
1320 template <typename ConcreteType>
1321 class FoldConstantBase : public OpRewritePattern<GenericOp> {
1322 public:
1323   struct APIntOrFloat {
1324     Optional<APInt> apInt;
1325     Optional<APFloat> apFloat;
1326   };
1327   struct APIntOrFloatArray {
1328     SmallVector<APInt> apInts;
1329     SmallVector<APFloat> apFloats;
1330   };
1331   using RegionComputationFn =
1332       std::function<APIntOrFloat(const APIntOrFloatArray &)>;
1333 
1334   FoldConstantBase(MLIRContext *context,
1335                    const ControlElementwiseOpsFusionFn &controlFn,
1336                    PatternBenefit benefit = 1)
1337       : OpRewritePattern<GenericOp>(context, benefit), controlFn(controlFn) {}
1338 
1339   LogicalResult matchAndRewrite(GenericOp genericOp,
1340                                 PatternRewriter &rewriter) const override {
1341     if (genericOp.hasBufferSemantics())
1342       return failure();
1343 
1344     // Only support ops generating one output for now.
1345     if (genericOp.getNumOutputs() != 1)
1346       return failure();
1347 
1348     auto outputType = genericOp.getResultTypes().front().dyn_cast<ShapedType>();
1349     // Require the output types to be static give we are generating constants.
1350     if (!outputType || !outputType.hasStaticShape())
1351       return failure();
1352 
1353     if (!llvm::all_of(genericOp.getInputOperands(), [](OpOperand *operand) {
1354           return operand->get().getType().isa<ShapedType>();
1355         }))
1356       return failure();
1357 
1358     // Make sure all element types are the same.
1359     auto getOperandElementType = [](OpOperand *operand) {
1360       return operand->get().getType().cast<ShapedType>().getElementType();
1361     };
1362     if (!llvm::is_splat(llvm::map_range(genericOp.getInputAndOutputOperands(),
1363                                         getOperandElementType)))
1364       return failure();
1365 
1366     // We can only handle the case where we have int/float elements.
1367     auto elementType = outputType.getElementType();
1368     if (!elementType.isIntOrFloat())
1369       return failure();
1370 
1371     // Require all indexing maps to be permutations for now. This is common and
1372     // it simplifies input/output access greatly: we can do the data shuffling
1373     // entirely in the compiler, without needing to turn all indices into
1374     // Values, and then do affine apply on them, and then match back the
1375     // constant again.
1376     if (!llvm::all_of(genericOp.getIndexingMaps(),
1377                       [](AffineMap map) { return map.isPermutation(); }))
1378       return failure();
1379 
1380     for (OpOperand *operand : genericOp.getOutputOperands()) {
1381       if (genericOp.payloadUsesValueFromOperand(operand))
1382         return failure();
1383     }
1384 
1385     // Further check the indexing maps are okay for the ConcreteType.
1386     if (!static_cast<const ConcreteType *>(this)->matchIndexingMaps(genericOp))
1387       return failure();
1388 
1389     // Defer to the concrete type to check the region and discover the
1390     // computation inside.
1391     RegionComputationFn computeFn =
1392         static_cast<const ConcreteType *>(this)->getRegionComputeFn(genericOp);
1393     if (!computeFn)
1394       return failure();
1395 
1396     // All inputs should be constants.
1397     int numInputs = genericOp.getNumInputs();
1398     SmallVector<DenseIntOrFPElementsAttr> inputValues(numInputs);
1399     for (auto operand : llvm::enumerate(genericOp.getInputOperands())) {
1400       if (!matchPattern(operand.value()->get(),
1401                         m_Constant(&inputValues[operand.index()])))
1402         return failure();
1403     }
1404 
1405     // Identified this as a potential candidate for folding. Now check the
1406     // policy to see whether we are allowed to proceed.
1407     for (int i = 0; i < numInputs; ++i) {
1408       OpOperand *consumer = genericOp.getInputOperand(i);
1409       OpResult producer = consumer->get().cast<OpResult>();
1410       if (!controlFn(producer, *consumer))
1411         return failure();
1412     }
1413 
1414     auto linalgOp = cast<LinalgOp>(genericOp.getOperation());
1415     SmallVector<int64_t, 4> loopBounds = linalgOp.computeStaticLoopSizes();
1416     int64_t numElements = outputType.getNumElements();
1417 
1418     // Use APInt/APFloat instead of Attribute here for constructing the output.
1419     // This helps to avoid blowing up compiler memory usage: Attributes would
1420     // unify the following cases but they have lifetime as the MLIRContext.
1421     SmallVector<APInt> intOutputValues;
1422     SmallVector<APFloat> fpOutputValues;
1423     if (elementType.template isa<FloatType>())
1424       fpOutputValues.resize(numElements, APFloat(0.f));
1425     else
1426       intOutputValues.resize(numElements);
1427 
1428     // Return the constant dim positions from the given permutation map.
1429     auto getDimPositions = [](AffineMap map) {
1430       SmallVector<unsigned> dims;
1431       dims.reserve(map.getNumResults());
1432       for (AffineExpr result : map.getResults()) {
1433         dims.push_back(result.cast<AffineDimExpr>().getPosition());
1434       }
1435       return dims;
1436     };
1437 
1438     SmallVector<SmallVector<unsigned>> inputDims;
1439     for (int i = 0; i < numInputs; ++i)
1440       inputDims.push_back(getDimPositions(genericOp.getIndexingMaps()[i]));
1441     auto outputDims = getDimPositions(genericOp.getIndexingMaps().back());
1442     auto outputShape = outputType.getShape();
1443 
1444     // Allocate small vectors for index delinearization. Initial values do not
1445     // matter here as they will be overwritten later.
1446     SmallVector<uint64_t> indices(loopBounds.size(), 0);
1447     SmallVector<uint64_t> dstIndices(loopBounds.size(), 0);
1448     SmallVector<SmallVector<uint64_t>> srcIndices(
1449         numInputs, SmallVector<uint64_t>(loopBounds.size(), 0));
1450     SmallVector<uint64_t> srcLinearIndices(numInputs, 0);
1451     uint64_t dstLinearIndex = 0;
1452 
1453     // Allocate spaces for compute function inputs. Initial values do not matter
1454     // here as they will be overwritten later.
1455     APIntOrFloatArray computeFnInputs;
1456 
1457     auto inputShapes = llvm::to_vector<4>(
1458         llvm::map_range(genericOp.getInputOperands(), [](OpOperand *operand) {
1459           return operand->get().getType().cast<ShapedType>().getShape();
1460         }));
1461 
1462     // Given a `linearIndex`, remap it to a linear index to access linalg op
1463     // inputs/ouputs. This mutates `indices`, `srcIndices`, `dstIndices`,
1464     // `srcLinearIndices`, `dstLinearIndex` in place.
1465     auto computeRemappedLinearIndex = [&](int linearIndex) {
1466       int totalCount = linearIndex;
1467       for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
1468         indices[dim] = totalCount % loopBounds[dim];
1469         totalCount /= loopBounds[dim];
1470       }
1471 
1472       for (int dim = loopBounds.size() - 1; dim >= 0; --dim) {
1473         for (int i = 0; i < numInputs; ++i)
1474           srcIndices[i][dim] = indices[inputDims[i][dim]];
1475         dstIndices[dim] = indices[outputDims[dim]];
1476       }
1477 
1478       dstLinearIndex = dstIndices.front();
1479       for (int i = 0; i < numInputs; ++i)
1480         srcLinearIndices[i] = srcIndices[i].front();
1481 
1482       for (int dim = 1; dim < outputType.getRank(); ++dim) {
1483         dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim];
1484         for (int i = 0; i < numInputs; ++i)
1485           srcLinearIndices[i] =
1486               srcLinearIndices[i] * inputShapes[i][dim] + srcIndices[i][dim];
1487       }
1488     };
1489 
1490     bool isFloat = elementType.isa<FloatType>();
1491     if (isFloat) {
1492       SmallVector<DenseElementsAttr::iterator_range<APFloat>> inFpRanges;
1493       for (int i = 0; i < numInputs; ++i)
1494         inFpRanges.push_back(inputValues[i].getValues<APFloat>());
1495 
1496       computeFnInputs.apFloats.resize(numInputs, APFloat(0.f));
1497 
1498       // Transpose the input constant. Because we don't know its rank in
1499       // advance, we need to loop over the range [0, element count) and
1500       // delinearize the index.
1501       for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
1502         computeRemappedLinearIndex(linearIndex);
1503 
1504         // Collect constant elements for all inputs at this loop iteration.
1505         for (int i = 0; i < numInputs; ++i)
1506           computeFnInputs.apFloats[i] = inFpRanges[i][srcLinearIndices[i]];
1507 
1508         // Invoke the computation to get the corresponding constant output
1509         // element.
1510         fpOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apFloat;
1511       }
1512     } else {
1513       SmallVector<DenseElementsAttr::iterator_range<APInt>> inIntRanges;
1514       for (int i = 0; i < numInputs; ++i)
1515         inIntRanges.push_back(inputValues[i].getValues<APInt>());
1516 
1517       computeFnInputs.apInts.resize(numInputs);
1518 
1519       // Transpose the input constant. Because we don't know its rank in
1520       // advance, we need to loop over the range [0, element count) and
1521       // delinearize the index.
1522       for (int linearIndex = 0; linearIndex < numElements; ++linearIndex) {
1523         computeRemappedLinearIndex(linearIndex);
1524 
1525         // Collect constant elements for all inputs at this loop iteration.
1526         for (int i = 0; i < numInputs; ++i)
1527           computeFnInputs.apInts[i] = inIntRanges[i][srcLinearIndices[i]];
1528 
1529         // Invoke the computation to get the corresponding constant output
1530         // element.
1531         intOutputValues[dstLinearIndex] = *computeFn(computeFnInputs).apInt;
1532       }
1533     }
1534 
1535     DenseElementsAttr outputAttr =
1536         isFloat ? DenseElementsAttr::get(outputType, fpOutputValues)
1537                 : DenseElementsAttr::get(outputType, intOutputValues);
1538 
1539     rewriter.replaceOpWithNewOp<ConstantOp>(genericOp, outputAttr);
1540     return success();
1541   }
1542 
1543 private:
1544   ControlElementwiseOpsFusionFn controlFn;
1545 };
1546 
1547 // Folds linalg.generic ops that are actually transposes on constant values.
1548 struct FoldConstantTranspose : public FoldConstantBase<FoldConstantTranspose> {
1549   using FoldConstantBase::FoldConstantBase;
1550 
1551   bool matchIndexingMaps(GenericOp genericOp) const {
1552     // We should have one input and one output.
1553     return genericOp.getIndexingMaps().size() == 2;
1554   }
1555 
1556   RegionComputationFn getRegionComputeFn(GenericOp genericOp) const {
1557     // Make sure the region only contains a yield op.
1558     Block &body = genericOp.region().front();
1559     if (!llvm::hasSingleElement(body))
1560       return nullptr;
1561     auto yieldOp = dyn_cast<linalg::YieldOp>(body.getTerminator());
1562     if (!yieldOp)
1563       return nullptr;
1564 
1565     // The yield op should return the block argument corresponds to the input.
1566     for (Value yieldVal : yieldOp.values()) {
1567       auto yieldArg = yieldVal.dyn_cast<BlockArgument>();
1568       if (!yieldArg || yieldArg.getOwner() != &body)
1569         return nullptr;
1570       if (yieldArg.getArgNumber() != 0)
1571         return nullptr;
1572     }
1573 
1574     // No computation; just return the orginal value.
1575     return [](const APIntOrFloatArray &inputs) {
1576       if (inputs.apFloats.empty())
1577         return APIntOrFloat{inputs.apInts.front(), llvm::None};
1578       return APIntOrFloat{llvm::None, inputs.apFloats.front()};
1579     };
1580   }
1581 
1582   ControlElementwiseOpsFusionFn controlFn;
1583 };
1584 
1585 } // namespace
1586 
1587 static Optional<SmallVector<Value>>
1588 fuseElementwiseOps(PatternRewriter &rewriter, OpOperand *consumerOpOperand,
1589                    GenericOp producer,
1590                    const ControlElementwiseOpsFusionFn &controlFn) {
1591   if (producer->getNumResults() != 1)
1592     return llvm::None;
1593 
1594   return fuseElementwiseOpsImpl(producer, consumerOpOperand, controlFn,
1595                                 rewriter);
1596 }
1597 
1598 bool mlir::linalg::skipUnitDimReshape(const OpResult &producer,
1599                                       OpOperand &consumer) {
1600   if (auto producerCollapseOp =
1601           dyn_cast<linalg::TensorCollapseShapeOp>(producer.getOwner())) {
1602     return !isUnitDimExpansionOnly(producerCollapseOp);
1603   }
1604   if (auto consumerExpandOp =
1605           dyn_cast<linalg::TensorExpandShapeOp>(consumer.getOwner())) {
1606     return !isUnitDimExpansionOnly(consumerExpandOp);
1607   }
1608   return true;
1609 }
1610 
1611 namespace {
1612 /// Patterns to fuse a generic op, with the producer of its operands.
1613 class FuseElementwiseOps : public OpRewritePattern<GenericOp> {
1614 public:
1615   FuseElementwiseOps(MLIRContext *context, ControlElementwiseOpsFusionFn &fun,
1616                      PatternBenefit benefit = 1)
1617       : OpRewritePattern<GenericOp>(context, benefit), controlFn(fun) {}
1618 
1619   LogicalResult matchAndRewrite(GenericOp genericOp,
1620                                 PatternRewriter &rewriter) const override {
1621     // Find the first operand that is defined by another generic op on tensors.
1622     for (OpOperand *opOperand : genericOp.getInputAndOutputOperands()) {
1623       auto producer =
1624           dyn_cast_or_null<GenericOp>(opOperand->get().getDefiningOp());
1625       if (!producer || !producer.hasTensorSemantics())
1626         continue;
1627       Optional<SmallVector<Value>> fusedOpResults =
1628           fuseElementwiseOps(rewriter, opOperand, producer, controlFn);
1629       if (fusedOpResults) {
1630         rewriter.replaceOp(genericOp, *fusedOpResults);
1631         return success();
1632       }
1633     }
1634     return failure();
1635   }
1636 
1637 private:
1638   ControlElementwiseOpsFusionFn controlFn;
1639 };
1640 
1641 /// Pass that fuses generic ops on tensors. Used only for testing.
1642 struct LinalgElementwiseOpFusionPass
1643     : public LinalgElementwiseOpFusionBase<LinalgElementwiseOpFusionPass> {
1644   void runOnOperation() override {
1645     Operation *op = getOperation();
1646     RewritePatternSet patterns(op->getContext());
1647     ControlElementwiseOpsFusionFn allowFoldingFn =
1648         [](const OpResult &producer, const OpOperand &consumer) {
1649           return true;
1650         };
1651     populateElementwiseOpsFusionPatterns(
1652         patterns,
1653         LinalgElementwiseFusionOptions().setControlFoldingReshapes(
1654             allowFoldingUnitDimReshapes ? allowFoldingFn : skipUnitDimReshape));
1655 
1656     // Use TopDownTraversal for compile time reasons
1657     GreedyRewriteConfig grc;
1658     grc.useTopDownTraversal = true;
1659     (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns),
1660                                        grc);
1661   }
1662 };
1663 
1664 /// Pass to test folding of reshape ops with generic ops by linearization.
1665 struct FoldReshapeOpsByLinearizationPass
1666     : public LinalgFoldReshapeOpsByLinearizationBase<
1667           FoldReshapeOpsByLinearizationPass> {
1668   void runOnOperation() override {
1669     Operation *op = getOperation();
1670     RewritePatternSet patterns(op->getContext());
1671     populateFoldReshapeOpsByLinearizationPatterns(patterns);
1672     if (allowFoldingUnitDimReshapes) {
1673       populateFoldUnitDimsReshapeOpsByLinearizationPatterns(patterns);
1674     }
1675     (void)applyPatternsAndFoldGreedily(op->getRegions(), std::move(patterns));
1676   }
1677 };
1678 
1679 /// Forces `outs` operands of linalg operations to use `linalg.init_tensor` if
1680 /// the value of the `outs` operand is not used within the op.  This is only
1681 /// implemented for `linalg.generic` operations for now, but should hold for all
1682 /// linalg structured ops.
1683 struct RemoveOutsDependency : public OpRewritePattern<GenericOp> {
1684   using OpRewritePattern<GenericOp>::OpRewritePattern;
1685 
1686   LogicalResult matchAndRewrite(GenericOp op,
1687                                 PatternRewriter &rewriter) const override {
1688     rewriter.startRootUpdate(op);
1689     bool modifiedOutput = false;
1690     Location loc = op.getLoc();
1691     for (OpOperand *opOperand : op.getOutputOperands()) {
1692       if (!op.payloadUsesValueFromOperand(opOperand)) {
1693         Value operandVal = opOperand->get();
1694         auto operandType = operandVal.getType().dyn_cast<RankedTensorType>();
1695         if (!operandType)
1696           continue;
1697 
1698         // If outs is already an `init_tensor` operation, nothing to do.
1699         auto definingOp = operandVal.getDefiningOp<InitTensorOp>();
1700         if (definingOp)
1701           continue;
1702         modifiedOutput = true;
1703         SmallVector<Value> dynamicDims;
1704         for (auto dim : llvm::enumerate(operandType.getShape())) {
1705           if (dim.value() != ShapedType::kDynamicSize)
1706             continue;
1707           dynamicDims.push_back(rewriter.createOrFold<tensor::DimOp>(
1708               loc, operandVal, dim.index()));
1709         }
1710         Value initTensor = rewriter.create<InitTensorOp>(
1711             loc, dynamicDims, operandType.getShape(),
1712             operandType.getElementType());
1713         op->setOperand(opOperand->getOperandNumber(), initTensor);
1714       }
1715     }
1716     if (!modifiedOutput) {
1717       rewriter.cancelRootUpdate(op);
1718       return failure();
1719     }
1720     rewriter.finalizeRootUpdate(op);
1721     return success();
1722   }
1723 };
1724 
1725 } // namespace
1726 
1727 void mlir::linalg::populateFoldReshapeOpsByLinearizationPatterns(
1728     RewritePatternSet &patterns) {
1729   patterns
1730       .add<FoldProducerReshapeOpByLinearization<false, TensorCollapseShapeOp>,
1731            FoldProducerReshapeOpByLinearization<false, TensorExpandShapeOp>,
1732            FoldConsumerReshapeOpByLinearization<false, TensorCollapseShapeOp>,
1733            FoldConsumerReshapeOpByLinearization<false, TensorExpandShapeOp>>(
1734           patterns.getContext());
1735 }
1736 
1737 void mlir::linalg::populateFoldUnitDimsReshapeOpsByLinearizationPatterns(
1738     RewritePatternSet &patterns) {
1739   patterns
1740       .add<FoldProducerReshapeOpByLinearization<true, TensorCollapseShapeOp>,
1741            FoldProducerReshapeOpByLinearization<true, TensorExpandShapeOp>,
1742            FoldConsumerReshapeOpByLinearization<true, TensorCollapseShapeOp>,
1743            FoldConsumerReshapeOpByLinearization<true, TensorExpandShapeOp>>(
1744           patterns.getContext());
1745 }
1746 
1747 void mlir::linalg::populateFoldReshapeOpsByExpansionPatterns(
1748     RewritePatternSet &patterns,
1749     ControlElementwiseOpsFusionFn controlFoldingReshapes) {
1750   patterns.add<FoldReshapeWithGenericOpByExpansion>(patterns.getContext(),
1751                                                     controlFoldingReshapes);
1752   patterns.add<FoldWithProducerReshapeOpByExpansion>(patterns.getContext(),
1753                                                      controlFoldingReshapes);
1754 }
1755 
1756 void mlir::linalg::populateElementwiseOpsFusionPatterns(
1757     RewritePatternSet &patterns, LinalgElementwiseFusionOptions options) {
1758   auto *context = patterns.getContext();
1759   patterns.add<FuseElementwiseOps, FoldScalarOrSplatConstant,
1760                FoldConstantTranspose>(context,
1761                                       options.controlElementwiseOpsFusionFn);
1762   patterns.add<RemoveOutsDependency>(context);
1763   populateFoldReshapeOpsByExpansionPatterns(patterns,
1764                                             options.controlFoldingReshapesFn);
1765   AffineApplyOp::getCanonicalizationPatterns(patterns, context);
1766   GenericOp::getCanonicalizationPatterns(patterns, context);
1767   TensorExpandShapeOp::getCanonicalizationPatterns(patterns, context);
1768   TensorCollapseShapeOp::getCanonicalizationPatterns(patterns, context);
1769   context->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(
1770       patterns);
1771 }
1772 
1773 void mlir::linalg::populatePushReshapeOpsPatterns(RewritePatternSet &patterns) {
1774   auto *context = patterns.getContext();
1775   patterns.add<PushExpandingReshape>(context);
1776 }
1777 
1778 std::unique_ptr<Pass> mlir::createLinalgElementwiseOpFusionPass() {
1779   return std::make_unique<LinalgElementwiseOpFusionPass>();
1780 }
1781 
1782 std::unique_ptr<Pass> mlir::createFoldReshapeOpsByLinearizationPass() {
1783   return std::make_unique<FoldReshapeOpsByLinearizationPass>();
1784 }
1785