1 //===- Tiling.cpp - Implementation of linalg Tiling -----------------------===//
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 Tiling pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <utility>
14 
15 #include "PassDetail.h"
16 #include "mlir/Dialect/Linalg/IR/Linalg.h"
17 #include "mlir/Dialect/Linalg/Passes.h"
18 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
19 #include "mlir/Dialect/Linalg/Utils/Utils.h"
20 #include "mlir/Dialect/MemRef/IR/MemRef.h"
21 #include "mlir/Dialect/SCF/Transforms.h"
22 #include "mlir/Dialect/Tensor/IR/Tensor.h"
23 #include "mlir/IR/AffineExpr.h"
24 #include "mlir/IR/AffineMap.h"
25 #include "mlir/Transforms/FoldUtils.h"
26 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
27 
28 #include "llvm/Support/CommandLine.h"
29 
30 using namespace mlir;
31 using namespace mlir::linalg;
32 using namespace mlir::scf;
33 
34 #define DEBUG_TYPE "linalg-tiling"
35 
36 static bool isZero(Value v) {
37   if (auto cst = v.getDefiningOp<arith::ConstantIndexOp>())
38     return cst.value() == 0;
39   return false;
40 }
41 
42 using LoopIndexToRangeIndexMap = DenseMap<int, int>;
43 
44 // Creates a number of ranges equal to the number of non-zero in `tileSizes`.
45 // One for each loop of the LinalgOp that is tiled. The `tileSizes` argument has
46 // one entry per surrounding loop. It uses zero as the convention that a
47 // particular loop is not tiled. This convention simplifies implementations by
48 // avoiding affine map manipulations.
49 // The returned ranges correspond to the loop ranges, in the proper order, that
50 // are tiled and for which new loops will be created. Also the function returns
51 // a map from loop indices of the LinalgOp to the corresponding non-empty range
52 // indices of newly created loops.
53 static std::tuple<SmallVector<Range, 4>, LoopIndexToRangeIndexMap>
54 makeTiledLoopRanges(OpBuilder &b, Location loc, AffineMap map,
55                     ValueRange allShapeSizes, ValueRange allTileSizes) {
56   assert(allTileSizes.size() == map.getNumResults());
57   // Apply `map` to get shape sizes in loop order.
58   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
59   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
60 
61   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
62   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
63   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
64     if (isZero(tileSizes[idx - zerosCount])) {
65       shapeSizes.erase(shapeSizes.begin() + idx - zerosCount);
66       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
67       ++zerosCount;
68       continue;
69     }
70     loopIndexToRangeIndex[idx] = idx - zerosCount;
71   }
72 
73   // Create a new range with the applied tile sizes.
74   SmallVector<Range, 4> res;
75   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx)
76     res.push_back(Range{b.create<arith::ConstantIndexOp>(loc, 0),
77                         shapeSizes[idx], tileSizes[idx]});
78   return std::make_tuple(res, loopIndexToRangeIndex);
79 }
80 
81 // All indices returned by IndexOp should be invariant with respect to tiling.
82 // Therefore, if an operation is tiled, we have to transform the indices
83 // accordingly, i.e. offset them by the values of the corresponding induction
84 // variables that are captured implicitly in the body of the op.
85 //
86 // Example. `linalg.generic` before tiling:
87 //
88 // #id_2d = (i, j) -> (i, j)
89 // #pointwise_2d_trait = {
90 //   indexing_maps = [#id_2d, #id_2d],
91 //   iterator_types = ["parallel", "parallel"]
92 // }
93 // linalg.generic #pointwise_2d_trait %operand, %result {
94 //   ^bb0(%operand_in: f32, %result_in: f32):
95 //     %i = linalg.index 0 : index
96 //     %j = linalg.index 1 : index
97 //     <some operations that use %i, %j>
98 // }: memref<50x100xf32>, memref<50x100xf32>
99 //
100 // After tiling pass with tiles sizes 10 and 25:
101 //
102 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2)
103 //
104 // %c1 = arith.constant 1 : index
105 // %c0 = arith.constant 0 : index
106 // %c25 = arith.constant 25 : index
107 // %c10 = arith.constant 10 : index
108 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32>
109 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32>
110 // scf.for %k = %c0 to operand_dim_0 step %c10 {
111 //   scf.for %l = %c0 to operand_dim_1 step %c25 {
112 //     %4 = std.subview %operand[%k, %l][%c10, %c25][%c1, %c1]
113 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
114 //     %5 = std.subview %result[%k, %l][%c10, %c25][%c1, %c1]
115 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
116 //     linalg.generic pointwise_2d_trait %4, %5 {
117 //     ^bb0(%operand_in: f32, %result_in: f32):
118 //       %i = linalg.index 0 : index
119 //       %j = linalg.index 1 : index
120 //       // Indices `k` and `l` are implicitly captured in the body.
121 //       %transformed_i = arith.addi %i, %k : index // index `i` is offset by %k
122 //       %transformed_j = arith.addi %j, %l : index // index `j` is offset by %l
123 //       // Every use of %i, %j is replaced with %transformed_i, %transformed_j
124 //       <some operations that use %transformed_i, %transformed_j>
125 //     }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided>
126 //   }
127 // }
128 //
129 // TODO: Investigate whether mixing implicit and explicit indices
130 // does not lead to losing information.
131 static void
132 transformIndexOps(OpBuilder &b, LinalgOp op, SmallVectorImpl<Value> &ivs,
133                   const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
134   SmallVector<Value> allIvs(op.getNumLoops(), nullptr);
135   for (auto &en : enumerate(allIvs)) {
136     auto rangeIndex = loopIndexToRangeIndex.find(en.index());
137     if (rangeIndex == loopIndexToRangeIndex.end())
138       continue;
139     en.value() = ivs[rangeIndex->second];
140   }
141   addTileLoopIvsToIndexOpResults(b, op, allIvs);
142 }
143 
144 // Insert a tile `source` into the destination tensor `dest`. The position at
145 // which the tile is inserted (as well as size of tile) is taken from a given
146 // ExtractSliceOp `sliceOp`.
147 static Value insertSliceIntoTensor(OpBuilder &b, Location loc,
148                                    tensor::ExtractSliceOp sliceOp, Value source,
149                                    Value dest) {
150   return b.create<tensor::InsertSliceOp>(
151       loc, sliceOp.source().getType(), source, dest, sliceOp.offsets(),
152       sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(),
153       sliceOp.static_sizes(), sliceOp.static_strides());
154 }
155 
156 template <typename LoopTy>
157 static FailureOr<TiledLinalgOp>
158 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes,
159                  const LinalgTilingOptions &options) {
160   auto nLoops = op.getNumLoops();
161   // Initial tile sizes may be too big, only take the first nLoops.
162   tileSizes = tileSizes.take_front(nLoops);
163 
164   if (llvm::all_of(tileSizes, isZero)) {
165     TiledLinalgOp tiledOp;
166     tiledOp.op = cast<LinalgOp>(b.clone(*op.getOperation()));
167     tiledOp.tensorResults.assign(tiledOp.op->result_begin(),
168                                  tiledOp.op->result_end());
169     return tiledOp;
170   }
171 
172   // 1. Build the tiled loop ranges.
173   auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc());
174   AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap();
175   if (!shapeSizesToLoopsMap)
176     return failure();
177 
178   SmallVector<Range, 4> loopRanges;
179   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
180   std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges(
181       b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes);
182 
183   SmallVector<Attribute, 4> iteratorTypes;
184   for (const auto &attr :
185        enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) {
186     if (loopIndexToRangeIndex.count(attr.index()))
187       iteratorTypes.push_back(attr.value());
188   }
189   // If interchangeVector is empty, use the identity. Build the permutation map
190   // otherwise.
191   auto invPermutationMap =
192       AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext());
193   if (!options.interchangeVector.empty()) {
194     // Based on the pruned iterations (due to zero tile size), recompute the
195     // interchange vector.
196     SmallVector<unsigned, 4> interchangeVector;
197     interchangeVector.reserve(options.interchangeVector.size());
198     for (auto pos : options.interchangeVector) {
199       auto it = loopIndexToRangeIndex.find(pos);
200       if (it == loopIndexToRangeIndex.end())
201         continue;
202       interchangeVector.push_back(it->second);
203     }
204     // Interchange vector is guaranteed to be a permutation,
205     // `inversePermutation` must succeed.
206     invPermutationMap = inversePermutation(
207         AffineMap::getPermutationMap(interchangeVector, b.getContext()));
208     assert(invPermutationMap);
209     SmallVector<int64_t> permutation(interchangeVector.begin(),
210                                      interchangeVector.end());
211     applyPermutationToVector(loopRanges, permutation);
212     applyPermutationToVector(iteratorTypes, permutation);
213   }
214 
215   // 2. Create the tiled loops.
216   LinalgOp res = op;
217   SmallVector<Value, 4> ivs, tensorResults;
218   auto tiledLoopBodyBuilder =
219       [&](OpBuilder &b, Location loc, ValueRange localIvs,
220           ValueRange operandValuesToUse) -> scf::ValueVector {
221     ivs.assign(localIvs.begin(), localIvs.end());
222 
223     // When an `interchangeVector` is present, it has been applied to the
224     // loop ranges and the iterator types. Apply its inverse to the
225     // resulting loop `ivs` to match the op definition.
226     SmallVector<Value, 4> interchangedIvs;
227     if (!options.interchangeVector.empty())
228       interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs);
229     else
230       interchangedIvs.assign(ivs.begin(), ivs.end());
231 
232     // Tile the `operandValuesToUse` that either match the `op` operands
233     // themselves or the tile loop arguments forwarding them.
234     assert(operandValuesToUse.size() ==
235                static_cast<size_t>(op.getNumInputsAndOutputs()) &&
236            "expect the number of operands and inputs and outputs to match");
237     SmallVector<Value> valuesToTile = operandValuesToUse;
238     auto sizeBounds =
239         applyMapToValues(b, loc, shapeSizesToLoopsMap, allShapeSizes);
240     SmallVector<Value, 4> tiledOperands = makeTiledShapes(
241         b, loc, op, valuesToTile, interchangedIvs, tileSizes, sizeBounds);
242 
243     // TODO: use an interface/adaptor to avoid leaking position in
244     // `tiledOperands`.
245     SmallVector<Type, 4> resultTensorTypes;
246     for (OpOperand *opOperand : op.getOutputTensorOperands())
247       resultTensorTypes.push_back(
248           tiledOperands[opOperand->getOperandNumber()].getType());
249 
250     res = op.clone(b, loc, resultTensorTypes, tiledOperands);
251 
252     // Insert a insert_slice for each output tensor.
253     unsigned resultIdx = 0;
254     for (OpOperand *opOperand : op.getOutputTensorOperands()) {
255       // TODO: use an interface/adaptor to avoid leaking position in
256       // `tiledOperands`.
257       Value outputTensor = tiledOperands[opOperand->getOperandNumber()];
258       if (auto sliceOp = outputTensor.getDefiningOp<tensor::ExtractSliceOp>()) {
259         tensorResults.push_back(insertSliceIntoTensor(
260             b, loc, sliceOp, res->getResult(resultIdx), sliceOp.source()));
261       } else {
262         tensorResults.push_back(res->getResult(resultIdx));
263       }
264       ++resultIdx;
265     }
266     return scf::ValueVector(tensorResults.begin(), tensorResults.end());
267   };
268   GenerateLoopNest<LoopTy>::doit(b, op.getLoc(), loopRanges, op, iteratorTypes,
269                                  tiledLoopBodyBuilder, options.distribution,
270                                  options.distributionTypes);
271 
272   // 3. Transform IndexOp results w.r.t. the tiling.
273   transformIndexOps(b, res, ivs, loopIndexToRangeIndex);
274 
275   // 4. Gather the newly created loops and return them with the new op.
276   SmallVector<Operation *, 8> loops;
277   loops.reserve(ivs.size());
278   for (auto iv : ivs) {
279     if (iv.isa<BlockArgument>()) {
280       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
281       assert(loops.back() && "no owner found for induction variable!");
282     } else {
283       // TODO: Instead of doing this, try to recover the ops used instead of the
284       // loop.
285       loops.push_back(nullptr);
286     }
287   }
288 
289   // 5. Get the tensor results from the outermost loop if available. Otherwise
290   // use the previously captured `tensorResults`.
291   Operation *outermostLoop = nullptr;
292   for (Operation *loop : loops)
293     if ((outermostLoop = loop))
294       break;
295 
296   return TiledLinalgOp{
297       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
298 }
299 
300 template <typename LoopTy>
301 FailureOr<TiledLinalgOp> static tileLinalgOpImpl(
302     OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) {
303   OpBuilder::InsertionGuard g(b);
304   b.setInsertionPoint(op);
305 
306   if (!options.tileSizeComputationFunction)
307     return failure();
308 
309   // Enforce the convention that "tiling by zero" skips tiling a particular
310   // dimension. This convention is significantly simpler to handle instead of
311   // adjusting affine maps to account for missing dimensions.
312   auto nLoops = op.getNumLoops();
313   SmallVector<Value, 4> tileSizeVector =
314       options.tileSizeComputationFunction(b, op);
315   if (tileSizeVector.size() < nLoops) {
316     auto zero = b.create<arith::ConstantIndexOp>(op.getLoc(), 0);
317     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
318   }
319 
320   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
321 }
322 
323 FailureOr<TiledLinalgOp>
324 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
325                            const LinalgTilingOptions &options) {
326   switch (options.loopType) {
327   case LinalgTilingLoopType::Loops:
328     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
329   case LinalgTilingLoopType::ParallelLoops:
330     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
331   case LinalgTilingLoopType::TiledLoops:
332     return tileLinalgOpImpl<linalg::TiledLoopOp>(b, op, options);
333   default:;
334   }
335   return failure();
336 }
337 
338 /// Generate a loop nest around a given PadTensorOp (for tiling). `newPadOp`
339 /// and `loopNest` are output parameters that return the new (tiled) PadTensorOp
340 /// and the loop nest.
341 static LogicalResult tilePadTensorOp(OpBuilder &builder, PadTensorOp op,
342                                      PadTensorOp &newPadOp, LoopNest &loopNest,
343                                      const LinalgTilingOptions &options) {
344   Location loc = op.getLoc();
345   OpBuilder::InsertionGuard g(builder);
346   builder.setInsertionPoint(op);
347 
348   // Clone PadTensorOp so that the existing op can be replaced more easily.
349   newPadOp = cast<PadTensorOp>(builder.clone(*op.getOperation()));
350   // Get rank and tile sizes.
351   int64_t rank = op.getResultType().getRank();
352   SmallVector<Value> tileSizes =
353       options.tileSizeComputationFunction(builder, op);
354   assert(static_cast<int64_t>(tileSizes.size()) == rank);
355   // Compute lower and upper bounds of the loop nest.
356   SmallVector<Range> ranges = op.getIterationDomain(builder);
357   SmallVector<Value> lbs, dims, allDims, steps;
358   for (int64_t i = 0; i < rank; ++i) {
359     allDims.push_back(ranges[i].size);
360     if (!isZero(tileSizes[i])) {
361       lbs.push_back(ranges[i].offset);
362       dims.push_back(ranges[i].size);
363       steps.push_back(tileSizes[i]);
364     }
365   }
366   // Generate loop nest: One loop per dimension.
367   SmallVector<Value> destOperand = op.getDestinationOperands(builder);
368   loopNest = mlir::scf::buildLoopNest(
369       builder, loc, lbs, /*ubs=*/dims, steps, ValueRange(destOperand),
370       [&](OpBuilder &b, Location loc, ValueRange localIvs,
371           ValueRange iterArgs) -> scf::ValueVector {
372         // Compute offsets and sizes of ExtractSliceOp.
373         SmallVector<Value> offsets =
374             computeTileOffsets(b, loc, localIvs, tileSizes);
375         SmallVector<Value> sizes =
376             computeTileSizes(b, loc, localIvs, tileSizes, allDims);
377         // Create ExtractSliceOp: Extract a tile from the PadTensorOp.
378         // Note: The PadTensorOp is located outside of the loop nest. It is
379         // later moved inside by ExtractSliceOfPadTensorSwapPattern.
380         auto map = AffineMap::getMultiDimIdentityMap(rank, b.getContext());
381         Value tiledOutput =
382             makeTiledShape(b, loc, newPadOp->getResult(0), tileSizes, map,
383                            offsets, allDims, sizes);
384         auto sliceOp = tiledOutput.getDefiningOp<tensor::ExtractSliceOp>();
385         assert(sliceOp && "expected ExtractSliceOp");
386         // Insert the tile into the output tensor.
387         Value yieldValue =
388             insertSliceIntoTensor(b, loc, sliceOp, sliceOp, iterArgs[0]);
389         return scf::ValueVector({yieldValue});
390       });
391   return success();
392 }
393 
394 namespace {
395 struct PadTensorOpTilingPattern : public OpRewritePattern<PadTensorOp> {
396   PadTensorOpTilingPattern(MLIRContext *ctx, LinalgTilingOptions opt)
397       : OpRewritePattern<PadTensorOp>(ctx), options(std::move(opt)) {}
398 
399   LogicalResult matchAndRewrite(PadTensorOp op,
400                                 PatternRewriter &rewriter) const override {
401     if (op->hasAttr(LinalgTransforms::kLinalgTransformMarker))
402       return failure();
403     PadTensorOp newPadOp;
404     LoopNest loopNest;
405     if (failed(tilePadTensorOp(rewriter, op, newPadOp, loopNest, options)))
406       return failure();
407     newPadOp->setAttr(LinalgTransforms::kLinalgTransformMarker,
408                       rewriter.getUnitAttr());
409     // Replace all uses of the original PadTensorOp.
410     rewriter.replaceOp(op, loopNest.getResults()[0]);
411     return success();
412   }
413 
414   LinalgTilingOptions options;
415 };
416 } // namespace
417 
418 namespace {
419 /// Helper classes for type list expansion.
420 template <typename... OpTypes>
421 class CanonicalizationPatternList;
422 
423 template <>
424 class CanonicalizationPatternList<> {
425 public:
426   static void insert(RewritePatternSet &patterns) {}
427 };
428 
429 template <typename OpTy, typename... OpTypes>
430 class CanonicalizationPatternList<OpTy, OpTypes...> {
431 public:
432   static void insert(RewritePatternSet &patterns) {
433     OpTy::getCanonicalizationPatterns(patterns, patterns.getContext());
434     CanonicalizationPatternList<OpTypes...>::insert(patterns);
435   }
436 };
437 
438 /// Helper classes for type list expansion.
439 template <typename... OpTypes>
440 class RewritePatternList;
441 
442 template <>
443 class RewritePatternList<> {
444 public:
445   static void insert(RewritePatternSet &patterns,
446                      const LinalgTilingOptions &options) {}
447 };
448 
449 template <typename OpTy, typename... OpTypes>
450 class RewritePatternList<OpTy, OpTypes...> {
451 public:
452   static void insert(RewritePatternSet &patterns,
453                      const LinalgTilingOptions &options) {
454     auto *ctx = patterns.getContext();
455     patterns.add<LinalgTilingPattern<OpTy>>(
456         ctx, options,
457         LinalgTransformationFilter(ArrayRef<StringAttr>{},
458                                    StringAttr::get(ctx, "tiled")));
459     RewritePatternList<OpTypes...>::insert(patterns, options);
460   }
461 };
462 } // namespace
463 
464 RewritePatternSet
465 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
466   RewritePatternSet patterns(ctx);
467   populateLinalgTilingCanonicalizationPatterns(patterns);
468   return patterns;
469 }
470 
471 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
472     RewritePatternSet &patterns) {
473   auto *ctx = patterns.getContext();
474   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
475   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
476   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
477   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
478   arith::ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
479 
480   memref::SubViewOp::getCanonicalizationPatterns(patterns, ctx);
481   memref::ViewOp::getCanonicalizationPatterns(patterns, ctx);
482 
483   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
484   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
485 
486   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
487   tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, ctx);
488   tensor::InsertSliceOp::getCanonicalizationPatterns(patterns, ctx);
489 
490   InitTensorOp::getCanonicalizationPatterns(patterns, ctx);
491   PadTensorOp::getCanonicalizationPatterns(patterns, ctx);
492   ctx->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(patterns);
493 
494   CanonicalizationPatternList<
495 #define GET_OP_LIST
496 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
497       >::insert(patterns);
498 }
499 
500 /// Populate the given list with patterns that apply Linalg tiling.
501 static void insertTilingPatterns(RewritePatternSet &patterns,
502                                  const LinalgTilingOptions &options) {
503   RewritePatternList<GenericOp,
504 #define GET_OP_LIST
505 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
506                      >::insert(patterns, options);
507   patterns.add<PadTensorOpTilingPattern>(patterns.getContext(), options);
508 }
509 
510 static void applyExtractSliceOfPadTensorSwapPattern(FuncOp funcOp) {
511   MLIRContext *ctx = funcOp.getContext();
512   RewritePatternSet patterns(ctx);
513   patterns.add<ExtractSliceOfPadTensorSwapPattern>(patterns.getContext());
514   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
515   (void)applyPatternsAndFoldGreedily(
516       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
517 }
518 
519 namespace {
520 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
521   LinalgTilingPass() = default;
522   LinalgTilingPass(ArrayRef<int64_t> tileSizes, LinalgTilingLoopType loopType,
523                    ArrayRef<StringRef> distributionTypes) {
524     this->tileSizes = tileSizes;
525     this->loopType = "";
526     this->loopTypeEnum = loopType;
527     this->distributionTypes = llvm::to_vector<2>(llvm::map_range(
528         distributionTypes, [](StringRef ref) { return ref.str(); }));
529   }
530 
531   void runOnFunction() override {
532     FuncOp funcOp = getFunction();
533     LinalgTilingLoopType type =
534         llvm::StringSwitch<LinalgTilingLoopType>(loopType)
535             .Case("for", LinalgTilingLoopType::Loops)
536             .Case("affine", LinalgTilingLoopType::AffineLoops)
537             .Case("parallel", LinalgTilingLoopType::ParallelLoops)
538             .Case("tiled_loop", LinalgTilingLoopType::TiledLoops)
539             .Default(loopTypeEnum);
540     auto distTypes = llvm::to_vector<2>(llvm::map_range(
541         distributionTypes, [](std::string &str) { return StringRef(str); }));
542     auto options = LinalgTilingOptions()
543                        .setTileSizes(tileSizes)
544                        .setLoopType(type)
545                        .setDistributionTypes(distTypes);
546     MLIRContext *ctx = funcOp.getContext();
547     RewritePatternSet patterns(ctx);
548     insertTilingPatterns(patterns, options);
549     scf::populateSCFForLoopCanonicalizationPatterns(patterns);
550     (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
551     (void)applyPatternsAndFoldGreedily(
552         funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
553     // Drop the marker.
554     funcOp.walk([](LinalgOp op) {
555       op->removeAttr(LinalgTransforms::kLinalgTransformMarker);
556     });
557 
558     // Apply swap pattern after generating loop nest and running
559     // canonicalizations.
560     applyExtractSliceOfPadTensorSwapPattern(funcOp);
561   }
562 
563   LinalgTilingLoopType loopTypeEnum;
564 };
565 
566 } // namespace
567 
568 std::unique_ptr<OperationPass<FuncOp>>
569 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes,
570                              linalg::LinalgTilingLoopType loopType,
571                              ArrayRef<StringRef> distributionTypes) {
572   return std::make_unique<LinalgTilingPass>(tileSizes, loopType,
573                                             distributionTypes);
574 }
575