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/Affine/EDSC/Intrinsics.h"
15 #include "mlir/Dialect/Linalg/EDSC/FoldedIntrinsics.h"
16 #include "mlir/Dialect/Linalg/IR/LinalgTypes.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/SCF/EDSC/Builders.h"
21 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
22 #include "mlir/Dialect/Tensor/IR/Tensor.h"
23 #include "mlir/IR/AffineExpr.h"
24 #include "mlir/IR/AffineExprVisitor.h"
25 #include "mlir/IR/AffineMap.h"
26 #include "mlir/Transforms/FoldUtils.h"
27 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
28 
29 #include "llvm/Support/CommandLine.h"
30 
31 using namespace mlir;
32 using namespace mlir::edsc;
33 using namespace mlir::edsc::intrinsics;
34 using namespace mlir::linalg;
35 using namespace mlir::scf;
36 
37 
38 #define DEBUG_TYPE "linalg-tiling"
39 
40 static bool isZero(Value v) {
41   if (auto cst = v.getDefiningOp<ConstantIndexOp>())
42     return cst.getValue() == 0;
43   return false;
44 }
45 
46 using LoopIndexToRangeIndexMap = DenseMap<int, int>;
47 
48 // Creates a number of ranges equal to the number of non-zero in `tileSizes`.
49 // One for each loop of the LinalgOp that is tiled. The `tileSizes` argument has
50 // one entry per surrounding loop. It uses zero as the convention that a
51 // particular loop is not tiled. This convention simplifies implementations by
52 // avoiding affine map manipulations.
53 // The returned ranges correspond to the loop ranges, in the proper order, that
54 // are tiled and for which new loops will be created. Also the function returns
55 // a map from loop indices of the LinalgOp to the corresponding non-empty range
56 // indices of newly created loops.
57 static std::tuple<SmallVector<Range, 4>, LoopIndexToRangeIndexMap>
58 makeTiledLoopRanges(OpBuilder &b, Location loc, AffineMap map,
59                     ValueRange allShapeSizes, ValueRange allTileSizes) {
60   assert(allTileSizes.size() == map.getNumResults());
61   // Apply `map` to get shape sizes in loop order.
62   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
63   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
64 
65   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
66   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
67   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
68     if (isZero(tileSizes[idx - zerosCount])) {
69       shapeSizes.erase(shapeSizes.begin() + idx - zerosCount);
70       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
71       ++zerosCount;
72       continue;
73     }
74     loopIndexToRangeIndex[idx] = idx - zerosCount;
75   }
76 
77   // Create a new range with the applied tile sizes.
78   SmallVector<Range, 4> res;
79   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx)
80     res.push_back(
81         Range{std_constant_index(0), shapeSizes[idx], tileSizes[idx]});
82   return std::make_tuple(res, loopIndexToRangeIndex);
83 }
84 namespace {
85 
86 // Helper visitor to determine whether an AffineExpr is tiled.
87 // This is achieved by traversing every AffineDimExpr with position `pos` and
88 // checking whether the corresponding `tileSizes[pos]` is non-zero.
89 // This also enforces only positive coefficients occur in multiplications.
90 //
91 // Example:
92 //   `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0]
93 //
94 struct TileCheck : public AffineExprVisitor<TileCheck> {
95   TileCheck(ValueRange tileSizes) : isTiled(false), tileSizes(tileSizes) {}
96 
97   void visitDimExpr(AffineDimExpr expr) {
98     isTiled |= !isZero(tileSizes[expr.getPosition()]);
99   }
100   void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) {
101     visit(expr.getLHS());
102     visit(expr.getRHS());
103     if (expr.getKind() == mlir::AffineExprKind::Mul)
104       assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 &&
105              "nonpositive multiplying coefficient");
106   }
107   bool isTiled;
108   ValueRange tileSizes;
109 };
110 
111 } // namespace
112 
113 // IndexedGenericOp explicitly uses induction variables in the loop body. The
114 // values of the indices that are used in the loop body for any given access of
115 // input/output memref before `subview` op was applied should be invariant with
116 // respect to tiling.
117 //
118 // Therefore, if the operation is tiled, we have to transform the indices
119 // accordingly, i.e. offset them by the values of the corresponding induction
120 // variables that are captured implicitly in the body of the op.
121 //
122 // Example. `linalg.indexed_generic` before tiling:
123 //
124 // #id_2d = (i, j) -> (i, j)
125 // #pointwise_2d_trait = {
126 //   indexing_maps = [#id_2d, #id_2d],
127 //   iterator_types = ["parallel", "parallel"],
128 //   n_views = [1, 1]
129 // }
130 // linalg.indexed_generic #pointwise_2d_trait %operand, %result {
131 //   ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
132 //     <some operations that use %i, %j>
133 // }: memref<50x100xf32>, memref<50x100xf32>
134 //
135 // After tiling pass with tiles sizes 10 and 25:
136 //
137 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2)
138 //
139 // %c1 = constant 1 : index
140 // %c0 = constant 0 : index
141 // %c25 = constant 25 : index
142 // %c10 = constant 10 : index
143 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32>
144 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32>
145 // scf.for %k = %c0 to operand_dim_0 step %c10 {
146 //   scf.for %l = %c0 to operand_dim_1 step %c25 {
147 //     %4 = std.subview %operand[%k, %l][%c10, %c25][%c1, %c1]
148 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
149 //     %5 = std.subview %result[%k, %l][%c10, %c25][%c1, %c1]
150 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
151 //     linalg.indexed_generic pointwise_2d_trait %4, %5 {
152 //     ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
153 //       // Indices `k` and `l` are implicitly captured in the body.
154 //       %transformed_i = addi %i, %k : index // index `i` is offset by %k
155 //       %transformed_j = addi %j, %l : index // index `j` is offset by %l
156 //       // Every use of %i, %j is replaced with %transformed_i, %transformed_j
157 //       <some operations that use %transformed_i, %transformed_j>
158 //     }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided>
159 //   }
160 // }
161 //
162 // TODO: Investigate whether mixing implicit and explicit indices
163 // does not lead to losing information.
164 static void transformIndexedGenericOpIndices(
165     OpBuilder &b, LinalgOp op, SmallVectorImpl<Value> &ivs,
166     const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
167   auto indexedGenericOp = dyn_cast<IndexedGenericOp>(op.getOperation());
168   if (!indexedGenericOp)
169     return;
170 
171   // `linalg.indexed_generic` comes in two flavours. One has a region with a
172   // single block that defines the loop body. The other has a `fun` attribute
173   // that refers to an existing function symbol. The `fun` function call will be
174   // inserted in the loop body in that case.
175   //
176   // TODO: Add support for `linalg.indexed_generic` with `fun` attribute.
177   auto &region = indexedGenericOp.region();
178   if (region.empty()) {
179     indexedGenericOp.emitOpError("expected a region");
180     return;
181   }
182   auto &block = region.front();
183 
184   OpBuilder::InsertionGuard g(b);
185   b.setInsertionPointToStart(&block);
186   for (unsigned i = 0; i < indexedGenericOp.getNumLoops(); ++i) {
187     auto rangeIndex = loopIndexToRangeIndex.find(i);
188     if (rangeIndex == loopIndexToRangeIndex.end())
189       continue;
190     Value oldIndex = block.getArgument(i);
191     // Offset the index argument `i` by the value of the corresponding induction
192     // variable and replace all uses of the previous value.
193     Value newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex,
194                                       ivs[rangeIndex->second]);
195     for (auto &use : oldIndex.getUses()) {
196       if (use.getOwner() == newIndex.getDefiningOp())
197         continue;
198       use.set(newIndex);
199     }
200   }
201 }
202 
203 static bool isTiled(AffineExpr expr, ValueRange tileSizes) {
204   if (!expr)
205     return false;
206   TileCheck t(tileSizes);
207   t.visit(expr);
208   return t.isTiled;
209 }
210 
211 // Checks whether the `map  varies with respect to a non-zero `tileSize`.
212 static bool isTiled(AffineMap map, ValueRange tileSizes) {
213   if (!map)
214     return false;
215   for (unsigned r = 0; r < map.getNumResults(); ++r)
216     if (isTiled(map.getResult(r), tileSizes))
217       return true;
218   return false;
219 }
220 
221 static SmallVector<Value, 4>
222 makeTiledShapes(OpBuilder &b, Location loc, LinalgOp linalgOp,
223                 ArrayRef<Value> tiledOperands, AffineMap map, ValueRange ivs,
224                 ValueRange tileSizes, ValueRange allShapeSizes) {
225   assert(ivs.size() == static_cast<size_t>(llvm::count_if(
226                            llvm::make_range(tileSizes.begin(), tileSizes.end()),
227                            [](Value v) { return !isZero(v); })) &&
228          "expected as many ivs as non-zero sizes");
229 
230   using namespace edsc::op;
231 
232   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
233   // Construct (potentially temporary) mins and maxes on which to apply maps
234   // that define tile subshapes.
235   SmallVector<Value, 8> lbs, subShapeSizes;
236   for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) {
237     bool isTiled = !isZero(tileSizes[idx]);
238     lbs.push_back(isTiled ? ivs[idxIvs++] : (Value)std_constant_index(0));
239     // Before composing, we need to make range a closed interval.
240     Value size = isTiled ? tileSizes[idx] : shapeSizes[idx];
241     subShapeSizes.push_back(size - std_constant_index(1));
242   }
243 
244   SmallVector<Value, 4> res;
245   res.reserve(tiledOperands.size());
246   for (auto en : llvm::enumerate(tiledOperands)) {
247     Value shapedOp = en.value();
248     ShapedType shapedType = shapedOp.getType().cast<ShapedType>();
249     unsigned rank = shapedType.getRank();
250     AffineMap map = linalgOp.getIndexingMap(en.index());
251     // If the shape is not tiled, we can use it as is.
252     if (!isTiled(map, tileSizes)) {
253       res.push_back(shapedOp);
254       continue;
255     }
256 
257     // Construct a new subview / subtensor for the tile.
258     SmallVector<OpFoldResult, 4> offsets, sizes, strides;
259     offsets.reserve(rank);
260     sizes.reserve(rank);
261     strides.reserve(rank);
262     for (unsigned r = 0; r < rank; ++r) {
263       if (!isTiled(map.getSubMap({r}), tileSizes)) {
264         offsets.push_back(b.getIndexAttr(0));
265         sizes.push_back(std_dim(shapedOp, r).value);
266         strides.push_back(b.getIndexAttr(1));
267         continue;
268       }
269 
270       // Tiling creates a new slice at the proper index, the slice step is 1
271       // (i.e. the op does not subsample, stepping occurs in the loop).
272       auto m = map.getSubMap({r});
273       auto offset = applyMapToValues(b, loc, m, lbs).front();
274       offsets.push_back(offset);
275       auto closedIntSize = applyMapToValues(b, loc, m, subShapeSizes).front();
276       // Resulting size needs to be made half open interval again.
277       auto size = closedIntSize + std_constant_index(1);
278 
279       // The size of the subview / subtensor should be trimmed to avoid
280       // out-of-bounds accesses, unless we statically know the subshape size
281       // divides the shape size evenly.
282       int64_t shapeSize = shapedType.getDimSize(r);
283       auto sizeCst = size.getDefiningOp<ConstantIndexOp>();
284       if (ShapedType::isDynamic(shapeSize) || !sizeCst ||
285           (shapeSize % sizeCst.getValue()) != 0) {
286         // Compute min(size, dim - offset) to avoid out-of-bounds accesses.
287         auto minMap = AffineMap::get(
288             /*dimCount=*/3, /*symbolCount=*/0,
289             {getAffineDimExpr(/*position=*/0, b.getContext()),
290              getAffineDimExpr(/*position=*/1, b.getContext()) -
291                  getAffineDimExpr(/*position=*/2, b.getContext())},
292             b.getContext());
293         auto d = std_dim(shapedOp, r);
294         SmallVector<Value, 4> operands{size, d, offset};
295         fullyComposeAffineMapAndOperands(&minMap, &operands);
296         size = affine_min(b.getIndexType(), minMap, operands);
297       }
298 
299       sizes.push_back(size);
300       strides.push_back(b.getIndexAttr(1));
301     }
302 
303     if (shapedType.isa<MemRefType>())
304       res.push_back(
305           b.create<SubViewOp>(loc, shapedOp, offsets, sizes, strides));
306     else
307       res.push_back(
308           b.create<SubTensorOp>(loc, shapedOp, offsets, sizes, strides));
309   }
310 
311   return res;
312 }
313 
314 template <typename LoopTy>
315 static Optional<TiledLinalgOp>
316 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes,
317                  const LinalgTilingOptions &options) {
318   auto nLoops = op.getNumLoops();
319   // Initial tile sizes may be too big, only take the first nLoops.
320   tileSizes = tileSizes.take_front(nLoops);
321 
322   if (llvm::all_of(tileSizes, isZero))
323     return llvm::None;
324 
325   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
326     // For conv op only support tiling along batch dimension (which is the first
327     // loop).
328     if (convOp.padding() && !llvm::all_of(tileSizes.drop_front(), isZero))
329       return llvm::None;
330   }
331 
332   // 1. Build the tiled loop ranges.
333   auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc());
334   AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap();
335   if (!shapeSizesToLoopsMap)
336     return llvm::None;
337 
338   SmallVector<Range, 4> loopRanges;
339   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
340   std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges(
341       b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes);
342 
343   SmallVector<Attribute, 4> iteratorTypes;
344   for (auto attr :
345        enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) {
346     if (loopIndexToRangeIndex.count(attr.index()))
347       iteratorTypes.push_back(attr.value());
348   }
349   // If interchangeVector is empty, use the identity. Build the permutation map
350   // otherwise.
351   auto invPermutationMap =
352       AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext());
353   if (!options.interchangeVector.empty()) {
354     // Based on the pruned iterations (due to zero tile size), recompute the
355     // interchange vector.
356     SmallVector<unsigned, 4> interchangeVector;
357     interchangeVector.reserve(options.interchangeVector.size());
358     for (auto pos : options.interchangeVector) {
359       auto it = loopIndexToRangeIndex.find(pos);
360       if (it == loopIndexToRangeIndex.end())
361         continue;
362       interchangeVector.push_back(it->second);
363     }
364     // Interchange vector is guaranteed to be a permutation,
365     // `inversePermutation` must succeed.
366     invPermutationMap = inversePermutation(
367         AffineMap::getPermutationMap(interchangeVector, b.getContext()));
368     assert(invPermutationMap);
369     applyPermutationToVector(loopRanges, interchangeVector);
370     applyPermutationToVector(iteratorTypes, interchangeVector);
371   }
372 
373   // 2. Create the tiled loops.
374   LinalgOp res = op;
375   SmallVector<Value, 4> ivs, tensorResults;
376   auto outputTensors = op.getOutputTensors();
377   GenerateLoopNest<LoopTy>::doit(
378       loopRanges, /*iterArgInitValues*/ outputTensors, iteratorTypes,
379       [&](ValueRange localIvs, ValueRange iterArgs) -> scf::ValueVector {
380         auto &b = ScopedContext::getBuilderRef();
381         auto loc = ScopedContext::getLocation();
382         ivs.assign(localIvs.begin(), localIvs.end());
383 
384         // When an `interchangeVector` is present, it has been applied to the
385         // loop ranges and the iterator types. Apply its inverse to the
386         // resulting loop `ivs` to match the op definition.
387         SmallVector<Value, 4> interchangedIvs;
388         if (!options.interchangeVector.empty())
389           interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs);
390         else
391           interchangedIvs.assign(ivs.begin(), ivs.end());
392 
393         assert(op.getNumOutputTensors() == iterArgs.size() &&
394                "num output tensors must match number of loop iter arguments");
395 
396         auto operands = llvm::to_vector<4>(op.getInputs());
397         SmallVector<Value, 4> outputBuffers = op.getOutputBuffers();
398         // TODO: thanks to simplifying assumption we do not need to worry about
399         // order of output buffers and tensors: there is only ever one kind.
400         assert(outputBuffers.empty() || iterArgs.empty());
401         operands.append(outputBuffers.begin(), outputBuffers.end());
402         operands.append(iterArgs.begin(), iterArgs.end());
403         SmallVector<Value, 4> tiledOperands =
404             makeTiledShapes(b, loc, op, operands, shapeSizesToLoopsMap,
405                             interchangedIvs, tileSizes, allShapeSizes);
406         auto nonShapedOperands = op.getAssumedNonShapedOperands();
407         tiledOperands.append(nonShapedOperands.begin(),
408                              nonShapedOperands.end());
409 
410         // TODO: use an interface/adaptor to avoid leaking position in
411         // `tiledOperands`.
412         SmallVector<Type, 4> resultTensorTypes;
413         for (OpOperand *opOperand : op.getOutputTensorsOpOperands())
414           resultTensorTypes.push_back(
415               tiledOperands[opOperand->getOperandNumber()].getType());
416 
417         res = op.clone(b, loc, resultTensorTypes, tiledOperands);
418 
419         // Insert a subtensor_insert for each output tensor.
420         unsigned resultIdx = 0;
421         for (OpOperand *opOperand : op.getOutputTensorsOpOperands()) {
422           // TODO: use an interface/adaptor to avoid leaking position in
423           // `tiledOperands`.
424           Value outputTensor = tiledOperands[opOperand->getOperandNumber()];
425           if (auto subtensor = outputTensor.getDefiningOp<SubTensorOp>()) {
426             tensorResults.push_back(b.create<SubTensorInsertOp>(
427                 loc, subtensor.source().getType(), res->getResult(resultIdx),
428                 subtensor.source(), subtensor.offsets(), subtensor.sizes(),
429                 subtensor.strides(), subtensor.static_offsets(),
430                 subtensor.static_sizes(), subtensor.static_strides()));
431           } else {
432             tensorResults.push_back(res->getResult(resultIdx));
433           }
434           ++resultIdx;
435         }
436         return scf::ValueVector(tensorResults.begin(), tensorResults.end());
437       },
438       options.distribution);
439 
440   // 3. Transforms index arguments of `linalg.generic` w.r.t. to the tiling.
441   transformIndexedGenericOpIndices(b, res, ivs, loopIndexToRangeIndex);
442 
443   // 4. Gather the newly created loops and return them with the new op.
444   SmallVector<Operation *, 8> loops;
445   loops.reserve(ivs.size());
446   for (auto iv : ivs) {
447     if (iv.isa<BlockArgument>()) {
448       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
449       assert(loops.back() && "no owner found for induction variable!");
450     } else {
451       // TODO: Instead of doing this, try to recover the ops used instead of the
452       // loop.
453       loops.push_back(nullptr);
454     }
455   }
456 
457   // 5. Get the tensor results from the outermost loop if available. Otherwise
458   // use the previously captured `tensorResults`.
459   Operation *outermostLoop = nullptr;
460   for (Operation *loop : loops)
461     if ((outermostLoop = loop))
462       break;
463 
464   return TiledLinalgOp{
465       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
466 }
467 
468 template <typename LoopTy>
469 Optional<TiledLinalgOp> static tileLinalgOpImpl(
470     OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) {
471   OpBuilder::InsertionGuard g(b);
472   b.setInsertionPoint(op);
473   ScopedContext scope(b, op.getLoc());
474 
475   // Enforce the convention that "tiling by zero" skips tiling a particular
476   // dimension. This convention is significantly simpler to handle instead of
477   // adjusting affine maps to account for missing dimensions.
478   auto nLoops = op.getNumLoops();
479   SmallVector<Value, 4> tileSizeVector =
480       options.tileSizeComputationFunction(b, op);
481   if (tileSizeVector.size() < nLoops) {
482     auto zero = std_constant_index(0);
483     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
484   }
485 
486   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
487 }
488 
489 Optional<TiledLinalgOp>
490 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
491                            const LinalgTilingOptions &options) {
492   switch (options.loopType) {
493   case LinalgTilingLoopType::Loops:
494     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
495   case LinalgTilingLoopType::ParallelLoops:
496     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
497   default:;
498   }
499   return llvm::None;
500 }
501 
502 namespace {
503 /// Helper classes for type list expansion.
504 template <typename... OpTypes>
505 class CanonicalizationPatternList;
506 
507 template <>
508 class CanonicalizationPatternList<> {
509 public:
510   static void insert(OwningRewritePatternList &patterns, MLIRContext *ctx) {}
511 };
512 
513 template <typename OpTy, typename... OpTypes>
514 class CanonicalizationPatternList<OpTy, OpTypes...> {
515 public:
516   static void insert(OwningRewritePatternList &patterns, MLIRContext *ctx) {
517     OpTy::getCanonicalizationPatterns(patterns, ctx);
518     CanonicalizationPatternList<OpTypes...>::insert(patterns, ctx);
519   }
520 };
521 
522 /// Helper classes for type list expansion.
523 template <typename... OpTypes>
524 class RewritePatternList;
525 
526 template <>
527 class RewritePatternList<> {
528 public:
529   static void insert(OwningRewritePatternList &patterns,
530                      const LinalgTilingOptions &options, MLIRContext *ctx) {}
531 };
532 
533 template <typename OpTy, typename... OpTypes>
534 class RewritePatternList<OpTy, OpTypes...> {
535 public:
536   static void insert(OwningRewritePatternList &patterns,
537                      const LinalgTilingOptions &options, MLIRContext *ctx) {
538     patterns.insert<LinalgTilingPattern<OpTy>>(
539         ctx, options, LinalgMarker({}, Identifier::get("tiled", ctx)));
540     RewritePatternList<OpTypes...>::insert(patterns, options, ctx);
541   }
542 };
543 } // namespace
544 
545 OwningRewritePatternList
546 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
547   OwningRewritePatternList patterns;
548   populateLinalgTilingCanonicalizationPatterns(patterns, ctx);
549   return patterns;
550 }
551 
552 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
553     OwningRewritePatternList &patterns, MLIRContext *ctx) {
554   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
555   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
556   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
557   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
558   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
559   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
560   ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
561   SubTensorOp::getCanonicalizationPatterns(patterns, ctx);
562   SubViewOp::getCanonicalizationPatterns(patterns, ctx);
563   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
564   ViewOp::getCanonicalizationPatterns(patterns, ctx);
565   CanonicalizationPatternList<
566 #define GET_OP_LIST
567 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
568       >::insert(patterns, ctx);
569 }
570 
571 /// Populate the given list with patterns that apply Linalg tiling.
572 static void insertTilingPatterns(OwningRewritePatternList &patterns,
573                                  const LinalgTilingOptions &options,
574                                  MLIRContext *ctx) {
575   RewritePatternList<GenericOp, IndexedGenericOp,
576 #define GET_OP_LIST
577 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
578                      >::insert(patterns, options, ctx);
579 }
580 
581 static void applyTilingToLoopPatterns(LinalgTilingLoopType loopType,
582                                       FuncOp funcOp,
583                                       ArrayRef<int64_t> tileSizes) {
584   auto options =
585       LinalgTilingOptions().setTileSizes(tileSizes).setLoopType(loopType);
586   MLIRContext *ctx = funcOp.getContext();
587   OwningRewritePatternList patterns;
588   insertTilingPatterns(patterns, options, ctx);
589   applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
590   applyPatternsAndFoldGreedily(funcOp,
591                                getLinalgTilingCanonicalizationPatterns(ctx));
592   // Drop the marker.
593   funcOp.walk([](LinalgOp op) {
594     op.removeAttr(LinalgTransforms::kLinalgTransformMarker);
595   });
596 }
597 
598 namespace {
599 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
600   LinalgTilingPass() = default;
601   LinalgTilingPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; }
602 
603   void runOnFunction() override {
604     applyTilingToLoopPatterns(LinalgTilingLoopType::Loops, getFunction(),
605                               tileSizes);
606   }
607 };
608 
609 struct LinalgTilingToParallelLoopsPass
610     : public LinalgTilingToParallelLoopsBase<LinalgTilingToParallelLoopsPass> {
611   LinalgTilingToParallelLoopsPass() = default;
612   LinalgTilingToParallelLoopsPass(ArrayRef<int64_t> sizes) {
613     tileSizes = sizes;
614   }
615 
616   void runOnFunction() override {
617     applyTilingToLoopPatterns(LinalgTilingLoopType::ParallelLoops,
618                               getFunction(), tileSizes);
619   }
620 };
621 
622 } // namespace
623 
624 std::unique_ptr<OperationPass<FuncOp>>
625 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
626   return std::make_unique<LinalgTilingPass>(tileSizes);
627 }
628 
629 std::unique_ptr<OperationPass<FuncOp>>
630 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
631   return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes);
632 }
633