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