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 using folded_affine_min = FoldedValueBuilder<AffineMinOp>;
38 
39 #define DEBUG_TYPE "linalg-tiling"
40 
41 static bool isZero(Value v) {
42   if (auto cst = v.getDefiningOp<ConstantIndexOp>())
43     return cst.getValue() == 0;
44   return false;
45 }
46 
47 using LoopIndexToRangeIndexMap = DenseMap<int, int>;
48 
49 // Creates a number of ranges equal to the number of non-zero in `tileSizes`.
50 // One for each loop of the LinalgOp that is tiled. The `tileSizes` argument has
51 // one entry per surrounding loop. It uses zero as the convention that a
52 // particular loop is not tiled. This convention simplifies implementations by
53 // avoiding affine map manipulations.
54 // The returned ranges correspond to the loop ranges, in the proper order, that
55 // are tiled and for which new loops will be created. Also the function returns
56 // a map from loop indices of the LinalgOp to the corresponding non-empty range
57 // indices of newly created loops.
58 static std::tuple<SmallVector<Range, 4>, LoopIndexToRangeIndexMap>
59 makeTiledLoopRanges(OpBuilder &b, Location loc, AffineMap map,
60                     ValueRange allShapeSizes, ValueRange allTileSizes) {
61   assert(allTileSizes.size() == map.getNumResults());
62   // Apply `map` to get shape sizes in loop order.
63   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
64   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
65 
66   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
67   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
68   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
69     if (isZero(tileSizes[idx - zerosCount])) {
70       shapeSizes.erase(shapeSizes.begin() + idx - zerosCount);
71       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
72       ++zerosCount;
73       continue;
74     }
75     loopIndexToRangeIndex[idx] = idx - zerosCount;
76   }
77 
78   // Create a new range with the applied tile sizes.
79   SmallVector<Range, 4> res;
80   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx)
81     res.push_back(
82         Range{std_constant_index(0), shapeSizes[idx], tileSizes[idx]});
83   return std::make_tuple(res, loopIndexToRangeIndex);
84 }
85 namespace {
86 
87 // Helper visitor to determine whether an AffineExpr is tiled.
88 // This is achieved by traversing every AffineDimExpr with position `pos` and
89 // checking whether the corresponding `tileSizes[pos]` is non-zero.
90 // This also enforces only positive coefficients occur in multiplications.
91 //
92 // Example:
93 //   `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0]
94 //
95 struct TileCheck : public AffineExprVisitor<TileCheck> {
96   TileCheck(ValueRange tileSizes) : isTiled(false), tileSizes(tileSizes) {}
97 
98   void visitDimExpr(AffineDimExpr expr) {
99     isTiled |= !isZero(tileSizes[expr.getPosition()]);
100   }
101   void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) {
102     visit(expr.getLHS());
103     visit(expr.getRHS());
104     if (expr.getKind() == mlir::AffineExprKind::Mul)
105       assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 &&
106              "nonpositive multiplying coefficient");
107   }
108   bool isTiled;
109   ValueRange tileSizes;
110 };
111 
112 } // namespace
113 
114 // IndexedGenericOp explicitly uses induction variables in the loop body. The
115 // values of the indices that are used in the loop body for any given access of
116 // input/output memref before `subview` op was applied should be invariant with
117 // respect to tiling.
118 //
119 // Therefore, if the operation is tiled, we have to transform the indices
120 // accordingly, i.e. offset them by the values of the corresponding induction
121 // variables that are captured implicitly in the body of the op.
122 //
123 // Example. `linalg.indexed_generic` before tiling:
124 //
125 // #id_2d = (i, j) -> (i, j)
126 // #pointwise_2d_trait = {
127 //   indexing_maps = [#id_2d, #id_2d],
128 //   iterator_types = ["parallel", "parallel"],
129 //   n_views = [1, 1]
130 // }
131 // linalg.indexed_generic #pointwise_2d_trait %operand, %result {
132 //   ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
133 //     <some operations that use %i, %j>
134 // }: memref<50x100xf32>, memref<50x100xf32>
135 //
136 // After tiling pass with tiles sizes 10 and 25:
137 //
138 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2)
139 //
140 // %c1 = constant 1 : index
141 // %c0 = constant 0 : index
142 // %c25 = constant 25 : index
143 // %c10 = constant 10 : index
144 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32>
145 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32>
146 // scf.for %k = %c0 to operand_dim_0 step %c10 {
147 //   scf.for %l = %c0 to operand_dim_1 step %c25 {
148 //     %4 = std.subview %operand[%k, %l][%c10, %c25][%c1, %c1]
149 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
150 //     %5 = std.subview %result[%k, %l][%c10, %c25][%c1, %c1]
151 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
152 //     linalg.indexed_generic pointwise_2d_trait %4, %5 {
153 //     ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
154 //       // Indices `k` and `l` are implicitly captured in the body.
155 //       %transformed_i = addi %i, %k : index // index `i` is offset by %k
156 //       %transformed_j = addi %j, %l : index // index `j` is offset by %l
157 //       // Every use of %i, %j is replaced with %transformed_i, %transformed_j
158 //       <some operations that use %transformed_i, %transformed_j>
159 //     }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided>
160 //   }
161 // }
162 //
163 // TODO: Investigate whether mixing implicit and explicit indices
164 // does not lead to losing information.
165 static void transformIndexedGenericOpIndices(
166     OpBuilder &b, LinalgOp op, SmallVectorImpl<Value> &ivs,
167     const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
168   auto indexedGenericOp = dyn_cast<IndexedGenericOp>(op.getOperation());
169   if (!indexedGenericOp)
170     return;
171 
172   // `linalg.indexed_generic` comes in two flavours. One has a region with a
173   // single block that defines the loop body. The other has a `fun` attribute
174   // that refers to an existing function symbol. The `fun` function call will be
175   // inserted in the loop body in that case.
176   //
177   // TODO: Add support for `linalg.indexed_generic` with `fun` attribute.
178   auto &region = indexedGenericOp.region();
179   if (region.empty()) {
180     indexedGenericOp.emitOpError("expected a region");
181     return;
182   }
183   auto &block = region.front();
184 
185   OpBuilder::InsertionGuard g(b);
186   b.setInsertionPointToStart(&block);
187   for (unsigned i = 0; i < indexedGenericOp.getNumLoops(); ++i) {
188     auto rangeIndex = loopIndexToRangeIndex.find(i);
189     if (rangeIndex == loopIndexToRangeIndex.end())
190       continue;
191     Value oldIndex = block.getArgument(i);
192     // Offset the index argument `i` by the value of the corresponding induction
193     // variable and replace all uses of the previous value.
194     Value newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex,
195                                       ivs[rangeIndex->second]);
196     for (auto &use : oldIndex.getUses()) {
197       if (use.getOwner() == newIndex.getDefiningOp())
198         continue;
199       use.set(newIndex);
200     }
201   }
202 }
203 
204 static bool isTiled(AffineExpr expr, ValueRange tileSizes) {
205   if (!expr)
206     return false;
207   TileCheck t(tileSizes);
208   t.visit(expr);
209   return t.isTiled;
210 }
211 
212 // Checks whether the `map  varies with respect to a non-zero `tileSize`.
213 static bool isTiled(AffineMap map, ValueRange tileSizes) {
214   if (!map)
215     return false;
216   for (unsigned r = 0; r < map.getNumResults(); ++r)
217     if (isTiled(map.getResult(r), tileSizes))
218       return true;
219   return false;
220 }
221 
222 static SmallVector<Value, 4>
223 makeTiledShapes(OpBuilder &b, Location loc, LinalgOp linalgOp,
224                 ArrayRef<Value> tiledOperands, AffineMap map, ValueRange ivs,
225                 ValueRange tileSizes, ValueRange allShapeSizes) {
226   assert(ivs.size() == static_cast<size_t>(llvm::count_if(
227                            llvm::make_range(tileSizes.begin(), tileSizes.end()),
228                            [](Value v) { return !isZero(v); })) &&
229          "expected as many ivs as non-zero sizes");
230 
231   using namespace edsc::op;
232 
233   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
234   // Construct (potentially temporary) mins and maxes on which to apply maps
235   // that define tile subshapes.
236   SmallVector<Value, 8> lbs, subShapeSizes;
237   for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) {
238     bool isTiled = !isZero(tileSizes[idx]);
239     lbs.push_back(isTiled ? ivs[idxIvs++] : (Value)std_constant_index(0));
240     // Before composing, we need to make range a closed interval.
241     Value size = isTiled ? tileSizes[idx] : shapeSizes[idx];
242     subShapeSizes.push_back(size - std_constant_index(1));
243   }
244 
245   SmallVector<Value, 4> res;
246   res.reserve(tiledOperands.size());
247   for (auto en : llvm::enumerate(tiledOperands)) {
248     Value shapedOp = en.value();
249     ShapedType shapedType = shapedOp.getType().cast<ShapedType>();
250     unsigned rank = shapedType.getRank();
251     AffineMap map = linalgOp.getIndexingMap(en.index());
252     // If the shape is not tiled, we can use it as is.
253     if (!isTiled(map, tileSizes)) {
254       res.push_back(shapedOp);
255       continue;
256     }
257 
258     // Construct a new subview / subtensor for the tile.
259     SmallVector<Value, 4> offsets, sizes, strides;
260     offsets.reserve(rank);
261     sizes.reserve(rank);
262     strides.reserve(rank);
263     for (unsigned r = 0; r < rank; ++r) {
264       if (!isTiled(map.getSubMap({r}), tileSizes)) {
265         offsets.push_back(std_constant_index(0));
266         sizes.push_back(std_dim(shapedOp, r));
267         strides.push_back(std_constant_index(1));
268         continue;
269       }
270 
271       // Tiling creates a new slice at the proper index, the slice step is 1
272       // (i.e. the op does not subsample, stepping occurs in the loop).
273       auto m = map.getSubMap({r});
274       auto offset = applyMapToValues(b, loc, m, lbs).front();
275       offsets.push_back(offset);
276       auto closedIntSize = applyMapToValues(b, loc, m, subShapeSizes).front();
277       // Resulting size needs to be made half open interval again.
278       auto size = closedIntSize + std_constant_index(1);
279 
280       // The size of the subview / subtensor should be trimmed to avoid
281       // out-of-bounds accesses, unless we statically know the subshape size
282       // divides the shape size evenly.
283       int64_t shapeSize = shapedType.getDimSize(r);
284       auto sizeCst = size.getDefiningOp<ConstantIndexOp>();
285       if (ShapedType::isDynamic(shapeSize) || !sizeCst ||
286           (shapeSize % sizeCst.getValue()) != 0) {
287         // Compute min(size, dim - offset) to avoid out-of-bounds accesses.
288         auto minMap = AffineMap::get(
289             /*dimCount=*/3, /*symbolCount=*/0,
290             {getAffineDimExpr(/*position=*/0, b.getContext()),
291              getAffineDimExpr(/*position=*/1, b.getContext()) -
292                  getAffineDimExpr(/*position=*/2, b.getContext())},
293             b.getContext());
294         auto d = std_dim(shapedOp, r);
295         size =
296             affine_min(b.getIndexType(), minMap, ValueRange{size, d, offset});
297       }
298 
299       sizes.push_back(size);
300       strides.push_back(std_constant_index(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