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 = [&](OpBuilder &b, Location loc,
231                                   ValueRange localIvs,
232                                   ValueRange iterArgs) -> 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     assert(op.getOutputTensorOperands().size() == iterArgs.size() &&
245            "num output tensors must match number of loop iter arguments");
246 
247     SmallVector<Value> operands = op.getInputOperands();
248     SmallVector<Value> outputBuffers = op.getOutputBufferOperands();
249     // TODO: thanks to simplifying assumption we do not need to worry about
250     // order of output buffers and tensors: there is only ever one kind.
251     assert(outputBuffers.empty() || iterArgs.empty());
252     operands.append(outputBuffers.begin(), outputBuffers.end());
253     operands.append(iterArgs.begin(), iterArgs.end());
254     auto sizeBounds =
255         applyMapToValues(b, loc, shapeSizesToLoopsMap, allShapeSizes);
256     SmallVector<Value, 4> tiledOperands = makeTiledShapes(
257         b, loc, op, operands, interchangedIvs, tileSizes, sizeBounds);
258 
259     // TODO: use an interface/adaptor to avoid leaking position in
260     // `tiledOperands`.
261     SmallVector<Type, 4> resultTensorTypes;
262     for (OpOperand *opOperand : op.getOutputTensorOperands())
263       resultTensorTypes.push_back(
264           tiledOperands[opOperand->getOperandNumber()].getType());
265 
266     res = op.clone(b, loc, resultTensorTypes, tiledOperands);
267 
268     // Insert a insert_slice for each output tensor.
269     unsigned resultIdx = 0;
270     for (OpOperand *opOperand : op.getOutputTensorOperands()) {
271       // TODO: use an interface/adaptor to avoid leaking position in
272       // `tiledOperands`.
273       Value outputTensor = tiledOperands[opOperand->getOperandNumber()];
274       if (auto sliceOp = outputTensor.getDefiningOp<tensor::ExtractSliceOp>()) {
275         tensorResults.push_back(insertSliceIntoTensor(
276             b, loc, sliceOp, res->getResult(resultIdx), sliceOp.source()));
277       } else {
278         tensorResults.push_back(res->getResult(resultIdx));
279       }
280       ++resultIdx;
281     }
282     return scf::ValueVector(tensorResults.begin(), tensorResults.end());
283   };
284   GenerateLoopNest<LoopTy>::doit(b, op.getLoc(), loopRanges, op, iteratorTypes,
285                                  tiledLoopBodyBuilder, options.distribution,
286                                  options.distributionTypes);
287 
288   // 3. Transform IndexOp results w.r.t. the tiling.
289   transformIndexOps(b, res, ivs, loopIndexToRangeIndex);
290 
291   // 4. Gather the newly created loops and return them with the new op.
292   SmallVector<Operation *, 8> loops;
293   loops.reserve(ivs.size());
294   for (auto iv : ivs) {
295     if (iv.isa<BlockArgument>()) {
296       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
297       assert(loops.back() && "no owner found for induction variable!");
298     } else {
299       // TODO: Instead of doing this, try to recover the ops used instead of the
300       // loop.
301       loops.push_back(nullptr);
302     }
303   }
304 
305   // 5. Get the tensor results from the outermost loop if available. Otherwise
306   // use the previously captured `tensorResults`.
307   Operation *outermostLoop = nullptr;
308   for (Operation *loop : loops)
309     if ((outermostLoop = loop))
310       break;
311 
312   return TiledLinalgOp{
313       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
314 }
315 
316 template <typename LoopTy>
317 Optional<TiledLinalgOp> static tileLinalgOpImpl(
318     OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) {
319   OpBuilder::InsertionGuard g(b);
320   b.setInsertionPoint(op);
321 
322   if (!options.tileSizeComputationFunction)
323     return llvm::None;
324 
325   // Enforce the convention that "tiling by zero" skips tiling a particular
326   // dimension. This convention is significantly simpler to handle instead of
327   // adjusting affine maps to account for missing dimensions.
328   auto nLoops = op.getNumLoops();
329   SmallVector<Value, 4> tileSizeVector =
330       options.tileSizeComputationFunction(b, op);
331   if (tileSizeVector.size() < nLoops) {
332     auto zero = b.create<ConstantIndexOp>(op.getLoc(), 0);
333     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
334   }
335 
336   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
337 }
338 
339 Optional<TiledLinalgOp>
340 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
341                            const LinalgTilingOptions &options) {
342   switch (options.loopType) {
343   case LinalgTilingLoopType::Loops:
344     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
345   case LinalgTilingLoopType::ParallelLoops:
346     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
347   case LinalgTilingLoopType::TiledLoops:
348     return tileLinalgOpImpl<linalg::TiledLoopOp>(b, op, options);
349   default:;
350   }
351   return llvm::None;
352 }
353 
354 /// Generate a loop nest around a given PadTensorOp (for tiling). `newPadOp`
355 /// and `loopNest` are output parameters that return the new (tiled) PadTensorOp
356 /// and the loop nest.
357 static LogicalResult tilePadTensorOp(OpBuilder &builder, PadTensorOp op,
358                                      PadTensorOp &newPadOp, LoopNest &loopNest,
359                                      const LinalgTilingOptions &options) {
360   Location loc = op.getLoc();
361   OpBuilder::InsertionGuard g(builder);
362   builder.setInsertionPoint(op);
363 
364   // Clone PadTensorOp so that the existing op can be replaced more easily.
365   newPadOp = cast<PadTensorOp>(builder.clone(*op.getOperation()));
366   // Get rank and tile sizes.
367   int64_t rank = op.getResultType().getRank();
368   SmallVector<Value> tileSizes =
369       options.tileSizeComputationFunction(builder, op);
370   assert(static_cast<int64_t>(tileSizes.size()) == rank);
371   // Compute lower and upper bounds of the loop nest.
372   SmallVector<Range> ranges = op.getLoopBounds(builder);
373   SmallVector<Value> lbs, dims, steps;
374   for (int64_t i = 0; i < rank; ++i) {
375     if (!isZero(tileSizes[i])) {
376       lbs.push_back(ranges[i].offset);
377       dims.push_back(ranges[i].size);
378       steps.push_back(tileSizes[i]);
379     }
380   }
381   // Generate loop nest: One loop per dimension.
382   SmallVector<Value> destOperand = op.getDestinationOperands(builder);
383   loopNest = mlir::scf::buildLoopNest(
384       builder, loc, lbs, /*ubs=*/dims, steps, ValueRange(destOperand),
385       [&](OpBuilder &b, Location loc, ValueRange localIvs,
386           ValueRange iterArgs) -> scf::ValueVector {
387         // Compute offsets and sizes of ExtractSliceOp.
388         SmallVector<Value> offsets =
389             computeTileOffsets(b, loc, localIvs, tileSizes);
390         SmallVector<Value> sizes =
391             computeTileSizes(b, loc, localIvs, tileSizes, dims);
392         // Create ExtractSliceOp: Extract a tile from the PadTensorOp.
393         // Note: The PadTensorOp is located outside of the loop nest. It is
394         // later moved inside by ExtractSliceOfPadTensorSwapPattern.
395         auto map = AffineMap::getMultiDimIdentityMap(rank, b.getContext());
396         Value tiledOutput = makeTiledShape(b, loc, newPadOp->getResult(0),
397                                            tileSizes, map, offsets, sizes);
398         auto sliceOp = tiledOutput.getDefiningOp<tensor::ExtractSliceOp>();
399         assert(sliceOp && "expected ExtractSliceOp");
400         // Insert the tile into the output tensor.
401         Value yieldValue =
402             insertSliceIntoTensor(b, loc, sliceOp, sliceOp, iterArgs[0]);
403         return scf::ValueVector({yieldValue});
404       });
405   return success();
406 }
407 
408 namespace {
409 struct PadTensorOpTilingPattern : public OpRewritePattern<PadTensorOp> {
410   PadTensorOpTilingPattern(MLIRContext *ctx, LinalgTilingOptions opt)
411       : OpRewritePattern<PadTensorOp>(ctx), options(opt) {}
412 
413   LogicalResult matchAndRewrite(PadTensorOp op,
414                                 PatternRewriter &rewriter) const override {
415     if (op->hasAttr(LinalgTransforms::kLinalgTransformMarker))
416       return failure();
417     PadTensorOp newPadOp;
418     LoopNest loopNest;
419     if (failed(tilePadTensorOp(rewriter, op, newPadOp, loopNest, options)))
420       return failure();
421     newPadOp->setAttr(LinalgTransforms::kLinalgTransformMarker,
422                       rewriter.getUnitAttr());
423     // Replace all uses of the original PadTensorOp.
424     rewriter.replaceOp(op, loopNest.getResults()[0]);
425     return success();
426   }
427 
428   LinalgTilingOptions options;
429 };
430 } // namespace
431 
432 namespace {
433 /// Helper classes for type list expansion.
434 template <typename... OpTypes>
435 class CanonicalizationPatternList;
436 
437 template <>
438 class CanonicalizationPatternList<> {
439 public:
440   static void insert(RewritePatternSet &patterns) {}
441 };
442 
443 template <typename OpTy, typename... OpTypes>
444 class CanonicalizationPatternList<OpTy, OpTypes...> {
445 public:
446   static void insert(RewritePatternSet &patterns) {
447     OpTy::getCanonicalizationPatterns(patterns, patterns.getContext());
448     CanonicalizationPatternList<OpTypes...>::insert(patterns);
449   }
450 };
451 
452 /// Helper classes for type list expansion.
453 template <typename... OpTypes>
454 class RewritePatternList;
455 
456 template <>
457 class RewritePatternList<> {
458 public:
459   static void insert(RewritePatternSet &patterns,
460                      const LinalgTilingOptions &options) {}
461 };
462 
463 template <typename OpTy, typename... OpTypes>
464 class RewritePatternList<OpTy, OpTypes...> {
465 public:
466   static void insert(RewritePatternSet &patterns,
467                      const LinalgTilingOptions &options) {
468     auto *ctx = patterns.getContext();
469     patterns.add<LinalgTilingPattern<OpTy>>(
470         ctx, options,
471         LinalgTransformationFilter(ArrayRef<Identifier>{},
472                                    Identifier::get("tiled", ctx)));
473     RewritePatternList<OpTypes...>::insert(patterns, options);
474   }
475 };
476 } // namespace
477 
478 RewritePatternSet
479 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
480   RewritePatternSet patterns(ctx);
481   populateLinalgTilingCanonicalizationPatterns(patterns);
482   return patterns;
483 }
484 
485 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
486     RewritePatternSet &patterns) {
487   auto *ctx = patterns.getContext();
488   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
489   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
490   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
491   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
492   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
493   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
494   ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
495   tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, ctx);
496   tensor::InsertSliceOp::getCanonicalizationPatterns(patterns, ctx);
497   memref::SubViewOp::getCanonicalizationPatterns(patterns, ctx);
498   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
499   memref::ViewOp::getCanonicalizationPatterns(patterns, ctx);
500   PadTensorOp::getCanonicalizationPatterns(patterns, ctx);
501   ctx->getLoadedDialect<LinalgDialect>()->getCanonicalizationPatterns(patterns);
502   CanonicalizationPatternList<
503 #define GET_OP_LIST
504 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
505       >::insert(patterns);
506 }
507 
508 /// Populate the given list with patterns that apply Linalg tiling.
509 static void insertTilingPatterns(RewritePatternSet &patterns,
510                                  const LinalgTilingOptions &options) {
511   RewritePatternList<GenericOp,
512 #define GET_OP_LIST
513 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
514                      >::insert(patterns, options);
515   patterns.add<PadTensorOpTilingPattern>(patterns.getContext(), options);
516 }
517 
518 static void applyExtractSliceOfPadTensorSwapPattern(FuncOp funcOp) {
519   MLIRContext *ctx = funcOp.getContext();
520   RewritePatternSet patterns(ctx);
521   patterns.add<ExtractSliceOfPadTensorSwapPattern>(patterns.getContext());
522   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
523   (void)applyPatternsAndFoldGreedily(
524       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
525 }
526 
527 static void
528 applyTilingToLoopPatterns(LinalgTilingLoopType loopType, FuncOp funcOp,
529                           ArrayRef<int64_t> tileSizes,
530                           ArrayRef<StringRef> distributionTypes = {}) {
531   auto options = LinalgTilingOptions()
532                      .setTileSizes(tileSizes)
533                      .setLoopType(loopType)
534                      .setDistributionTypes(distributionTypes);
535   MLIRContext *ctx = funcOp.getContext();
536   RewritePatternSet patterns(ctx);
537   insertTilingPatterns(patterns, options);
538   scf::populateSCFForLoopCanonicalizationPatterns(patterns);
539   (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
540   (void)applyPatternsAndFoldGreedily(
541       funcOp, getLinalgTilingCanonicalizationPatterns(ctx));
542   // Drop the marker.
543   funcOp.walk([](LinalgOp op) {
544     op->removeAttr(LinalgTransforms::kLinalgTransformMarker);
545   });
546 
547   // Apply swap pattern after generating loop nest and running
548   // canonicalizations.
549   applyExtractSliceOfPadTensorSwapPattern(funcOp);
550 }
551 
552 namespace {
553 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
554   LinalgTilingPass() = default;
555   LinalgTilingPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; }
556 
557   void runOnFunction() override {
558     applyTilingToLoopPatterns(LinalgTilingLoopType::Loops, getFunction(),
559                               tileSizes);
560   }
561 };
562 
563 struct LinalgTilingToParallelLoopsPass
564     : public LinalgTilingToParallelLoopsBase<LinalgTilingToParallelLoopsPass> {
565   LinalgTilingToParallelLoopsPass() = default;
566   LinalgTilingToParallelLoopsPass(ArrayRef<int64_t> sizes) {
567     tileSizes = sizes;
568   }
569 
570   void runOnFunction() override {
571     applyTilingToLoopPatterns(LinalgTilingLoopType::ParallelLoops,
572                               getFunction(), tileSizes);
573   }
574 };
575 
576 struct LinalgTilingToTiledLoopsPass
577     : public LinalgTilingToTiledLoopsBase<LinalgTilingToTiledLoopsPass> {
578   LinalgTilingToTiledLoopsPass() = default;
579   LinalgTilingToTiledLoopsPass(ArrayRef<int64_t> sizes,
580                                ArrayRef<StringRef> types) {
581     tileSizes = sizes;
582     distributionTypes = llvm::to_vector<2>(
583         llvm::map_range(types, [](StringRef ref) { return ref.str(); }));
584   }
585 
586   void runOnFunction() override {
587     applyTilingToLoopPatterns(
588         LinalgTilingLoopType::TiledLoops, getFunction(), tileSizes,
589         llvm::to_vector<2>(
590             llvm::map_range(distributionTypes,
591                             [](std::string &str) { return StringRef(str); })));
592   }
593 };
594 
595 } // namespace
596 
597 std::unique_ptr<OperationPass<FuncOp>>
598 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
599   return std::make_unique<LinalgTilingPass>(tileSizes);
600 }
601 
602 std::unique_ptr<OperationPass<FuncOp>>
603 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
604   return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes);
605 }
606 
607 std::unique_ptr<OperationPass<FuncOp>>
608 mlir::createLinalgTilingToTiledLoopPass(ArrayRef<int64_t> tileSizes,
609                                         ArrayRef<StringRef> distributionTypes) {
610   return std::make_unique<LinalgTilingToTiledLoopsPass>(tileSizes,
611                                                         distributionTypes);
612 }
613