1 //===- DropUnitDims.cpp - Pass to drop use of unit-extent for broadcasting ===//
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 patterns/pass to remove usage of unit-extent dimensions
10 // to specify broadcasting in favor of more canonical representation of the
11 // computation
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "PassDetail.h"
16 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
17 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
18 #include "mlir/Dialect/Linalg/Passes.h"
19 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
20 #include "mlir/Dialect/Linalg/Utils/Utils.h"
21 #include "mlir/Dialect/Tensor/IR/Tensor.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/AffineMap.h"
24 #include "mlir/IR/BuiltinTypes.h"
25 #include "mlir/Transforms/FoldUtils.h"
26 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 
30 #define DEBUG_TYPE "linalg-drop-unit-dims"
31 
32 using namespace mlir;
33 using namespace mlir::linalg;
34 
35 /// Implements a pass that canonicalizes the uses of unit-extent dimensions for
36 /// broadcasting. For example,
37 ///
38 /// ```mlir
39 /// #accesses = [
40 ///   affine_map<(d0, d1) -> (0, d1)>,
41 ///   affine_map<(d0, d1) -> (d0, 0)>,
42 ///   affine_map<(d0, d1) -> (d0, d1)>
43 /// ]
44 ///
45 /// #trait = {
46 ///   args_in = 2,
47 ///   args_out = 1,
48 ///   indexing_maps = #accesses,
49 ///   iterator_types = ["parallel", "parallel"],
50 ///   library_call = "some_external_fn"
51 /// }
52 ///
53 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
54 /// tensor<5x5xf32>
55 /// {
56 ///   %0 = linalg.tensor_reshape %arg0 [affine_map<(d0, d1) -> (d0, d1)>] :
57 ///        tensor<5xf32> into tensor<1x5xf32>
58 ///   %1 = linalg.tensor_reshape %arg1 [affine_map<(d0, d1) -> (d0, d1)>] :
59 ///        tensor<5xf32> into tensor<5x1xf32>
60 ///   %2 = linalg.generic #trait %0, %1 {
61 ///        ^bb0(%arg2: f32, %arg3: f32):
62 ///          %3 = addf %arg2, %arg3 : f32
63 ///          linalg.yield %3 : f32
64 ///        } : tensor<1x5xf32>, tensor<5x1xf32> -> tensor<5x5xf32>
65 ///   return %2 : tensor<5x5xf32>
66 /// }
67 ///
68 /// would canonicalize to
69 ///
70 /// ```mlir
71 /// #accesses = [
72 ///   affine_map<(d0, d1) -> (d1)>,
73 ///   affine_map<(d0, d1) -> (d0)>,
74 ///   affine_map<(d0, d1) -> (d0, d1)>
75 /// ]
76 ///
77 /// #trait = {
78 ///   args_in = 2,
79 ///   args_out = 1,
80 ///   indexing_maps = #accesses,
81 ///   iterator_types = ["parallel", "parallel"],
82 ///   library_call = "some_external_fn"
83 /// }
84 ///
85 /// func @broadcast_test(%arg0 : tensor<5xf32>, %arg1 : tensor<5xf32>) ->
86 /// tensor<5x5xf32>
87 /// {
88 ///   %0 = linalg.generic #trait %arg0, %arg1 {
89 ///        ^bb0(%arg2: f32, %arg3: f32):
90 ///          %3 = addf %arg2, %arg3 : f32
91 ///          linalg.yield %3 : f32
92 ///        } : tensor<5xf32>, tensor<5xf32> -> tensor<5x5xf32>
93 ///   return %0 : tensor<5x5xf32>
94 /// }
95 
96 /// Given dims of the iteration space of a structured op that are known to be
97 /// single trip count (`unitDims`), return the indexing maps to use in the
98 /// canonicalized op with these dims removed, given the original `indexingMaps`.
99 static ArrayAttr replaceUnitDims(DenseSet<unsigned> &unitDims,
100                                  ArrayRef<AffineMap> indexingMaps,
101                                  MLIRContext *context) {
102   if (indexingMaps.empty())
103     return nullptr;
104   unsigned numIterationDims = indexingMaps.front().getNumDims();
105   unsigned numSymbols = indexingMaps.front().getNumSymbols();
106 
107   // Compute the replacement for each dim expr.
108   SmallVector<AffineExpr, 4> dimReplacements;
109   dimReplacements.reserve(numIterationDims);
110   unsigned numKeptDims = 0;
111   for (unsigned dim : llvm::seq<unsigned>(0, numIterationDims)) {
112     if (unitDims.count(dim))
113       dimReplacements.push_back(getAffineConstantExpr(0, context));
114     else
115       dimReplacements.push_back(getAffineDimExpr(numKeptDims++, context));
116   }
117 
118   // Symbols remain the same.
119   SmallVector<AffineExpr, 4> symReplacements;
120   symReplacements.reserve(numSymbols);
121   for (unsigned symbol : llvm::seq<unsigned>(0, numSymbols))
122     symReplacements.push_back(getAffineSymbolExpr(symbol, context));
123 
124   SmallVector<AffineMap, 4> newIndexingMaps;
125   newIndexingMaps.reserve(indexingMaps.size());
126   for (AffineMap operandMap : indexingMaps) {
127     // Expected indexing maps to have no symbols.
128     if (operandMap.getNumSymbols())
129       return nullptr;
130     newIndexingMaps.push_back(simplifyAffineMap(
131         operandMap.replaceDimsAndSymbols(dimReplacements, symReplacements,
132                                          numIterationDims - unitDims.size(),
133                                          numSymbols)));
134   }
135 
136   // Check that the new index maps are invertible. If not, something went
137   // wrong, so abort.
138   if (!inversePermutation(concatAffineMaps(newIndexingMaps)))
139     return nullptr;
140   return ArrayAttr::get(context,
141                         llvm::to_vector<4>(llvm::map_range(
142                             newIndexingMaps, [](AffineMap map) -> Attribute {
143                               return AffineMapAttr::get(map);
144                             })));
145 }
146 
147 /// Update the index accesses of linalg operations having index semantics.
148 static void replaceUnitDimIndexOps(GenericOp genericOp,
149                                    const DenseSet<unsigned> &unitDims,
150                                    PatternRewriter &rewriter) {
151   assert(genericOp->getNumRegions() == 1 &&
152          genericOp->getRegion(0).getBlocks().size() == 1 &&
153          "expected generic operation to have one block.");
154   Block &block = genericOp->getRegion(0).front();
155 
156   for (IndexOp indexOp : llvm::make_early_inc_range(block.getOps<IndexOp>())) {
157     OpBuilder::InsertionGuard guard(rewriter);
158     rewriter.setInsertionPoint(indexOp);
159     if (unitDims.count(indexOp.dim()) != 0) {
160       rewriter.replaceOpWithNewOp<ConstantIndexOp>(indexOp, 0);
161     } else {
162       // Update the dimension of the index operation if needed.
163       unsigned droppedDims = llvm::count_if(
164           unitDims, [&](unsigned dim) { return dim < indexOp.dim(); });
165       if (droppedDims != 0)
166         rewriter.replaceOpWithNewOp<IndexOp>(indexOp,
167                                              indexOp.dim() - droppedDims);
168     }
169   }
170 }
171 
172 namespace {
173 /// Pattern to fold unit-trip count loops in GenericOps.
174 struct FoldUnitDimLoops : public OpRewritePattern<GenericOp> {
175   using OpRewritePattern<GenericOp>::OpRewritePattern;
176   LogicalResult matchAndRewrite(GenericOp genericOp,
177                                 PatternRewriter &rewriter) const override {
178     SmallVector<AffineMap, 4> indexingMaps = genericOp.getIndexingMaps();
179     if (indexingMaps.empty())
180       return failure();
181 
182     // Check if any of the iteration dimensions are unit-trip count. They will
183     // end up being unit-trip count if they are used to index into a unit-dim
184     // tensor/memref.
185     AffineMap invertedMap = inversePermutation(concatAffineMaps(indexingMaps));
186     if (!invertedMap)
187       return failure();
188     SmallVector<int64_t> dims = genericOp.getStaticShape();
189 
190     // Find all the reduction iterators. Those need some special consideration
191     // (see below).
192     auto getLoopDimsOfType =
193         [&](StringRef iteratorTypeName) -> SmallVector<unsigned, 4> {
194       SmallVector<AffineExpr> dimExprs;
195       getDimsOfType(genericOp, iteratorTypeName, dimExprs);
196       return llvm::to_vector<4>(llvm::map_range(dimExprs, [](AffineExpr expr) {
197         return expr.cast<AffineDimExpr>().getPosition();
198       }));
199     };
200     auto reductionDims = getLoopDimsOfType(getReductionIteratorTypeName());
201 
202     DenseSet<unsigned> unitDims;
203     SmallVector<unsigned, 4> unitDimsReductionLoops;
204     ArrayAttr iteratorTypes = genericOp.iterator_types();
205     for (auto expr : enumerate(invertedMap.getResults())) {
206       if (AffineDimExpr dimExpr = expr.value().dyn_cast<AffineDimExpr>())
207         if (dims[dimExpr.getPosition()] == 1) {
208           if (isParallelIterator(iteratorTypes[expr.index()]))
209             unitDims.insert(expr.index());
210           else if (isReductionIterator(iteratorTypes[expr.index()]))
211             unitDimsReductionLoops.push_back(expr.index());
212         }
213     }
214 
215     // Reduction loops can be dropped if there is at least one other reduction
216     // loop that is not dropped. This accounts for the initial value read in the
217     // reduction loop.
218     if (!unitDimsReductionLoops.empty() && reductionDims.size() > 1) {
219       if (unitDimsReductionLoops.size() == reductionDims.size())
220         unitDims.insert(reductionDims.begin(), std::prev(reductionDims.end()));
221       else
222         unitDims.insert(unitDimsReductionLoops.begin(),
223                         unitDimsReductionLoops.end());
224     }
225 
226     if (unitDims.empty())
227       return failure();
228 
229     // Compute the modified indexing maps.
230     MLIRContext *context = rewriter.getContext();
231     ArrayAttr newIndexingMapAttr =
232         replaceUnitDims(unitDims, indexingMaps, context);
233     if (!newIndexingMapAttr)
234       return genericOp.emitError("unable to compute modified indexing_maps");
235 
236     // Compute the iterator types of the modified op by dropping the one-trip
237     // count loops.
238     SmallVector<Attribute, 4> newIteratorTypes;
239     for (auto attr : llvm::enumerate(iteratorTypes)) {
240       if (!unitDims.count(attr.index()))
241         newIteratorTypes.push_back(attr.value());
242     }
243 
244     rewriter.startRootUpdate(genericOp);
245     genericOp.indexing_mapsAttr(newIndexingMapAttr);
246     genericOp.iterator_typesAttr(ArrayAttr::get(context, newIteratorTypes));
247     replaceUnitDimIndexOps(genericOp, unitDims, rewriter);
248     rewriter.finalizeRootUpdate(genericOp);
249     return success();
250   }
251 };
252 
253 struct UnitExtentReplacementInfo {
254   Type type;
255   AffineMap indexMap;
256   ArrayAttr reassociation;
257 };
258 } // namespace
259 
260 /// Utility function for replacing operands/results to a linalg generic
261 /// operation with unit-extent dimensions. These can be replaced with
262 /// an operand/result with the unit-extent dimension removed. This is only done
263 /// if the indexing map used to access that didimensionmension has a
264 /// AffineConstantExpr of value 0. Given the `type` of an result/operand of a
265 /// Linalg op, and its `indexMap` the utility function returns:
266 /// - the new type with dimensions of size 1 removed.
267 /// - modified index map that can be used to access the replaced result/operand
268 /// - the reassociation that converts from the original tensor type to the
269 ///   modified tensor type.
270 static UnitExtentReplacementInfo replaceUnitExtents(GenericOp genericOp,
271                                                     OpOperand *opOperand,
272                                                     MLIRContext *context) {
273   AffineMap indexingMap = genericOp.getTiedIndexingMap(opOperand);
274   ArrayRef<int64_t> shape = genericOp.getShape(opOperand);
275   ArrayRef<AffineExpr> exprs = indexingMap.getResults();
276   SmallVector<AffineExpr> reassociations;
277   SmallVector<Attribute> reassociationMaps;
278   SmallVector<AffineExpr> newIndexExprs;
279   SmallVector<int64_t> newShape;
280 
281   int64_t origRank = genericOp.getRank(opOperand);
282   AffineExpr zeroExpr = getAffineConstantExpr(0, context);
283   auto isUnitExtent = [&](int64_t dim) -> bool {
284     return shape[dim] == 1 && exprs[dim] == zeroExpr;
285   };
286 
287   int64_t dim = 0;
288   // Fold dimensions that are unit-extent at the beginning of the tensor.
289   while (dim < origRank && isUnitExtent(dim))
290     reassociations.push_back(getAffineDimExpr(dim++, context));
291   while (dim < origRank) {
292     reassociations.push_back(getAffineDimExpr(dim, context));
293     newIndexExprs.push_back(exprs[dim]);
294     newShape.push_back(shape[dim]);
295     // Fold all following dimensions that are unit-extent.
296     while (dim + 1 < origRank && isUnitExtent(dim + 1)) {
297       ++dim;
298       reassociations.push_back(getAffineDimExpr(dim, context));
299     }
300     reassociationMaps.push_back(AffineMapAttr::get(AffineMap::get(
301         origRank, /*symbolCount = */ 0, reassociations, context)));
302     reassociations.clear();
303     ++dim;
304   }
305   // Compute the tensor or scalar replacement type.
306   Type actualType = opOperand->get().getType();
307   Type elementType = getElementTypeOrSelf(opOperand->get());
308   Type replacementType;
309   if (elementType == opOperand->get().getType()) {
310     replacementType = elementType;
311   } else if (actualType.isa<RankedTensorType>()) {
312     replacementType = RankedTensorType::get(newShape, elementType);
313   } else if (actualType.isa<MemRefType>()) {
314     assert(actualType.cast<MemRefType>().getAffineMaps().empty() &&
315            "unsupported strided memrefs");
316     replacementType = MemRefType::get(newShape, elementType);
317   }
318   assert(replacementType && "unsupported shaped type");
319   UnitExtentReplacementInfo info = {replacementType,
320                                     AffineMap::get(indexingMap.getNumDims(),
321                                                    indexingMap.getNumSymbols(),
322                                                    newIndexExprs, context),
323                                     ArrayAttr::get(context, reassociationMaps)};
324   return info;
325 }
326 
327 namespace {
328 
329 SmallVector<ReassociationExprs, 2>
330 convertAffineMapArrayToExprs(ArrayAttr affineMapArrayAttr) {
331   SmallVector<ReassociationExprs, 2> reassociationExprs;
332   for (auto attr : affineMapArrayAttr)
333     reassociationExprs.push_back(
334         llvm::to_vector<4>(attr.cast<AffineMapAttr>().getValue().getResults()));
335   return reassociationExprs;
336 }
337 
338 /// Pattern to replace tensor/buffer operands/results that are unit extents.
339 struct ReplaceUnitExtents : public OpRewritePattern<GenericOp> {
340   using OpRewritePattern<GenericOp>::OpRewritePattern;
341 
342   // Return the original value if the type is unchanged, or reshape it. Return a
343   // nullptr if this is an unsupported type.
344   Value maybeExpand(Value result, Type origResultType,
345                     ArrayAttr reassociationMap, Location loc,
346                     PatternRewriter &rewriter) const {
347     if (origResultType == result.getType())
348       return result;
349     if (origResultType.isa<RankedTensorType>()) {
350       return rewriter.create<linalg::TensorExpandShapeOp>(
351           loc, origResultType, result,
352           convertAffineMapArrayToExprs(reassociationMap));
353     }
354     if (origResultType.isa<MemRefType>()) {
355       return rewriter.create<linalg::ExpandShapeOp>(
356           loc, origResultType, result,
357           convertAffineMapArrayToExprs(reassociationMap));
358     }
359     return nullptr;
360   };
361 
362   // Return the original value if the type is unchanged, or reshape it. Return a
363   // nullptr if this is an unsupported type.
364   Value maybeCollapse(Value operand, Type newInputOutputType,
365                       ArrayAttr reassociationMap, Location loc,
366                       PatternRewriter &rewriter) const {
367     auto operandType = operand.getType();
368     if (operandType == newInputOutputType)
369       return operand;
370     if (operandType.isa<MemRefType>()) {
371       return rewriter.create<linalg::CollapseShapeOp>(
372           loc, newInputOutputType, operand,
373           convertAffineMapArrayToExprs(reassociationMap));
374     }
375     if (operandType.isa<RankedTensorType>()) {
376       return rewriter.create<linalg::TensorCollapseShapeOp>(
377           loc, newInputOutputType, operand,
378           convertAffineMapArrayToExprs(reassociationMap));
379     }
380     return nullptr;
381   };
382 
383   LogicalResult matchAndRewrite(GenericOp genericOp,
384                                 PatternRewriter &rewriter) const override {
385     MLIRContext *context = rewriter.getContext();
386     Location loc = genericOp.getLoc();
387 
388     SmallVector<AffineMap> newIndexingMaps;
389     SmallVector<ArrayAttr> reassociationMaps;
390     SmallVector<Type> newInputOutputTypes;
391     bool doCanonicalization = false;
392     for (OpOperand *opOperand : genericOp.getInputAndOutputOperands()) {
393       UnitExtentReplacementInfo replacementInfo =
394           replaceUnitExtents(genericOp, opOperand, context);
395       reassociationMaps.push_back(replacementInfo.reassociation);
396       newIndexingMaps.push_back(replacementInfo.indexMap);
397       newInputOutputTypes.push_back(replacementInfo.type);
398       doCanonicalization |= replacementInfo.type != opOperand->get().getType();
399     }
400 
401     // If the indexing maps of the result operation are not invertible (i.e. not
402     // legal), abort.
403     if (!doCanonicalization ||
404         !inversePermutation(concatAffineMaps(newIndexingMaps)))
405       return failure();
406 
407     // If any operand type change, insert a reshape to convert from the original
408     // type to the new type.
409     // TODO: get rid of flattenedIdx which assumes operand order and contiguity.
410     unsigned flattenedIdx = 0;
411     auto insertReshapes = [&](ValueRange values) {
412       SmallVector<Value, 4> res;
413       res.reserve(values.size());
414       for (auto operand : values) {
415         auto reshapedValue =
416             maybeCollapse(operand, newInputOutputTypes[flattenedIdx],
417                           reassociationMaps[flattenedIdx], loc, rewriter);
418         assert(reshapedValue &&
419                "expected ranked MemRef or Tensor operand type");
420         res.push_back(reshapedValue);
421         ++flattenedIdx;
422       }
423       return res;
424     };
425 
426     SmallVector<Value, 4> newInputs = insertReshapes(genericOp.inputs());
427     SmallVector<Value, 4> newOutputs = insertReshapes(genericOp.outputs());
428 
429     // If any result type changes, insert a reshape to convert from the original
430     // type to the new type.
431     SmallVector<Type, 4> resultTypes;
432     resultTypes.reserve(genericOp.getNumResults());
433     for (unsigned i : llvm::seq<unsigned>(0, genericOp.getNumResults()))
434       resultTypes.push_back(newInputOutputTypes[i + genericOp.getNumInputs()]);
435     GenericOp replacementOp = rewriter.create<GenericOp>(
436         loc, resultTypes, newInputs, newOutputs, newIndexingMaps,
437         llvm::to_vector<4>(
438             genericOp.iterator_types().template getAsValueRange<StringAttr>()));
439     rewriter.inlineRegionBefore(genericOp.region(), replacementOp.region(),
440                                 replacementOp.region().begin());
441 
442     // If any result tensor has a modified shape, then add reshape to recover
443     // the original shape.
444     SmallVector<Value, 4> resultReplacements;
445     for (auto result : llvm::enumerate(replacementOp.getResults())) {
446       unsigned index = result.index() + replacementOp.getNumInputs();
447       auto origResultType = genericOp.getResult(result.index()).getType();
448 
449       auto newResult = maybeExpand(result.value(), origResultType,
450                                    reassociationMaps[index], loc, rewriter);
451       assert(newResult &&
452              "unexpected output type other than ranked MemRef or Tensor");
453       resultReplacements.push_back(newResult);
454     }
455     rewriter.replaceOp(genericOp, resultReplacements);
456     return success();
457   }
458 };
459 } // namespace
460 
461 /// Get the reassociation maps to fold the result of a extract_slice (or source
462 /// of a insert_slice) operation with given offsets, and sizes to its
463 /// rank-reduced version. This is only done for the cases where the size is 1
464 /// and offset is 0. Strictly speaking the offset 0 is not required in general,
465 /// but non-zero offsets are not handled by SPIR-V backend at this point (and
466 /// potentially cannot be handled).
467 static Optional<SmallVector<ReassociationIndices>>
468 getReassociationMapForFoldingUnitDims(ArrayRef<OpFoldResult> mixedSizes) {
469   SmallVector<ReassociationIndices> reassociation;
470   ReassociationIndices curr;
471   for (auto it : llvm::enumerate(mixedSizes)) {
472     auto dim = it.index();
473     auto size = it.value();
474     curr.push_back(dim);
475     auto attr = size.dyn_cast<Attribute>();
476     if (attr && attr.cast<IntegerAttr>().getInt() == 1)
477       continue;
478     reassociation.emplace_back(ReassociationIndices{});
479     std::swap(reassociation.back(), curr);
480   }
481   // When the reassociations are not empty, then fold the remaining
482   // unit-dimensions into the last dimension.  If the reassociations so far is
483   // empty, then leave it emtpy. This will fold everything to a rank-0 tensor.
484   if (!curr.empty() && !reassociation.empty())
485     reassociation.back().append(curr.begin(), curr.end());
486   return reassociation;
487 }
488 
489 namespace {
490 /// Convert `extract_slice` operations to rank-reduced versions.
491 struct UseRankReducedExtractSliceOp
492     : public OpRewritePattern<tensor::ExtractSliceOp> {
493   using OpRewritePattern<tensor::ExtractSliceOp>::OpRewritePattern;
494 
495   LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp,
496                                 PatternRewriter &rewriter) const override {
497     RankedTensorType resultType = sliceOp.getType();
498     SmallVector<OpFoldResult> offsets = sliceOp.getMixedOffsets();
499     SmallVector<OpFoldResult> sizes = sliceOp.getMixedSizes();
500     SmallVector<OpFoldResult> strides = sliceOp.getMixedStrides();
501     auto reassociation = getReassociationMapForFoldingUnitDims(sizes);
502     if (!reassociation ||
503         reassociation->size() == static_cast<size_t>(resultType.getRank()))
504       return failure();
505     auto rankReducedType = tensor::ExtractSliceOp::inferRankReducedResultType(
506                                reassociation->size(), sliceOp.getSourceType(),
507                                offsets, sizes, strides)
508                                .cast<RankedTensorType>();
509 
510     Location loc = sliceOp.getLoc();
511     Value newSlice = rewriter.create<tensor::ExtractSliceOp>(
512         loc, rankReducedType, sliceOp.source(), offsets, sizes, strides);
513     rewriter.replaceOpWithNewOp<TensorExpandShapeOp>(sliceOp, resultType,
514                                                      newSlice, *reassociation);
515     return success();
516   }
517 };
518 
519 /// Convert `insert_slice` operations to rank-reduced versions.
520 struct UseRankReducedInsertSliceOp
521     : public OpRewritePattern<tensor::InsertSliceOp> {
522   using OpRewritePattern<tensor::InsertSliceOp>::OpRewritePattern;
523 
524   LogicalResult matchAndRewrite(tensor::InsertSliceOp insertOp,
525                                 PatternRewriter &rewriter) const override {
526     RankedTensorType sourceType = insertOp.getSourceType();
527     SmallVector<OpFoldResult> offsets = insertOp.getMixedOffsets();
528     SmallVector<OpFoldResult> sizes = insertOp.getMixedSizes();
529     SmallVector<OpFoldResult> strides = insertOp.getMixedStrides();
530     auto reassociation = getReassociationMapForFoldingUnitDims(sizes);
531     if (!reassociation ||
532         reassociation->size() == static_cast<size_t>(sourceType.getRank()))
533       return failure();
534     Location loc = insertOp.getLoc();
535     auto reshapedSource = rewriter.create<TensorCollapseShapeOp>(
536         loc, insertOp.source(), *reassociation);
537     rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
538         insertOp, reshapedSource, insertOp.dest(), insertOp.getMixedOffsets(),
539         insertOp.getMixedSizes(), insertOp.getMixedStrides());
540     return success();
541   }
542 };
543 } // namespace
544 
545 /// Patterns that are used to canonicalize the use of unit-extent dims for
546 /// broadcasting.
547 void mlir::linalg::populateFoldUnitExtentDimsPatterns(
548     RewritePatternSet &patterns) {
549   auto *context = patterns.getContext();
550   patterns.add<FoldUnitDimLoops, ReplaceUnitExtents,
551                UseRankReducedExtractSliceOp, UseRankReducedInsertSliceOp>(
552       context);
553   TensorCollapseShapeOp::getCanonicalizationPatterns(patterns, context);
554   TensorExpandShapeOp::getCanonicalizationPatterns(patterns, context);
555 }
556 
557 namespace {
558 /// Pass that removes unit-extent dims within generic ops.
559 struct LinalgFoldUnitExtentDimsPass
560     : public LinalgFoldUnitExtentDimsBase<LinalgFoldUnitExtentDimsPass> {
561   void runOnFunction() override {
562     FuncOp funcOp = getFunction();
563     MLIRContext *context = funcOp.getContext();
564     RewritePatternSet patterns(context);
565     if (foldOneTripLoopsOnly)
566       patterns.add<FoldUnitDimLoops>(context);
567     else
568       populateFoldUnitExtentDimsPatterns(patterns);
569     (void)applyPatternsAndFoldGreedily(funcOp.getBody(), std::move(patterns));
570   }
571 };
572 } // namespace
573 
574 std::unique_ptr<OperationPass<FuncOp>>
575 mlir::createLinalgFoldUnitExtentDimsPass() {
576   return std::make_unique<LinalgFoldUnitExtentDimsPass>();
577 }
578