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                 ValueRange operands, AffineMap map, ValueRange ivs,
225                 ValueRange tileSizes, ValueRange allShapeSizes) {
226   assert(operands.size() == linalgOp.getShapedOperands().size());
227   assert(ivs.size() == static_cast<size_t>(llvm::count_if(
228                            llvm::make_range(tileSizes.begin(), tileSizes.end()),
229                            [](Value v) { return !isZero(v); })) &&
230          "expected as many ivs as non-zero sizes");
231 
232   using namespace edsc::op;
233 
234   auto shapeSizes = applyMapToValues(b, loc, map, allShapeSizes);
235   // Construct (potentially temporary) mins and maxes on which to apply maps
236   // that define tile subshapes.
237   SmallVector<Value, 8> lbs, subShapeSizes;
238   for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) {
239     bool isTiled = !isZero(tileSizes[idx]);
240     lbs.push_back(isTiled ? ivs[idxIvs++] : (Value)std_constant_index(0));
241     // Before composing, we need to make range a closed interval.
242     Value size = isTiled ? tileSizes[idx] : shapeSizes[idx];
243     subShapeSizes.push_back(size - std_constant_index(1));
244   }
245 
246   auto *op = linalgOp.getOperation();
247 
248   SmallVector<Value, 4> res;
249   res.reserve(op->getNumOperands());
250   for (auto en : llvm::enumerate(operands)) {
251     Value shapedOp = en.value();
252     ShapedType shapedType = shapedOp.getType().cast<ShapedType>();
253     unsigned rank = shapedType.getRank();
254     AffineMap map = linalgOp.getIndexingMap(en.index());
255     // If the shape is not tiled, we can use it as is.
256     if (!isTiled(map, tileSizes)) {
257       res.push_back(shapedOp);
258       continue;
259     }
260 
261     // Construct a new subview / subtensor for the tile.
262     SmallVector<Value, 4> offsets, sizes, strides;
263     offsets.reserve(rank);
264     sizes.reserve(rank);
265     strides.reserve(rank);
266     for (unsigned r = 0; r < rank; ++r) {
267       if (!isTiled(map.getSubMap({r}), tileSizes)) {
268         offsets.push_back(std_constant_index(0));
269         sizes.push_back(std_dim(shapedOp, r));
270         strides.push_back(std_constant_index(1));
271         continue;
272       }
273 
274       // Tiling creates a new slice at the proper index, the slice step is 1
275       // (i.e. the op does not subsample, stepping occurs in the loop).
276       auto m = map.getSubMap({r});
277       auto offset = applyMapToValues(b, loc, m, lbs).front();
278       offsets.push_back(offset);
279       auto closedIntSize = applyMapToValues(b, loc, m, subShapeSizes).front();
280       // Resulting size needs to be made half open interval again.
281       auto size = closedIntSize + std_constant_index(1);
282 
283       // The size of the subview / subtensor should be trimmed to avoid
284       // out-of-bounds accesses, unless we statically know the subshape size
285       // divides the shape size evenly.
286       int64_t shapeSize = shapedType.getDimSize(r);
287       auto sizeCst = size.getDefiningOp<ConstantIndexOp>();
288       if (ShapedType::isDynamic(shapeSize) || !sizeCst ||
289           (shapeSize % sizeCst.getValue()) != 0) {
290         // Compute min(size, dim - offset) to avoid out-of-bounds accesses.
291         auto minMap = AffineMap::get(
292             /*dimCount=*/3, /*symbolCount=*/0,
293             {getAffineDimExpr(/*position=*/0, b.getContext()),
294              getAffineDimExpr(/*position=*/1, b.getContext()) -
295                  getAffineDimExpr(/*position=*/2, b.getContext())},
296             b.getContext());
297         auto d = std_dim(shapedOp, r);
298         size =
299             affine_min(b.getIndexType(), minMap, ValueRange{size, d, offset});
300       }
301 
302       sizes.push_back(size);
303       strides.push_back(std_constant_index(1));
304     }
305 
306     if (shapedType.isa<MemRefType>())
307       res.push_back(
308           b.create<SubViewOp>(loc, shapedOp, offsets, sizes, strides));
309     else
310       res.push_back(
311           b.create<SubTensorOp>(loc, shapedOp, offsets, sizes, strides));
312   }
313 
314   return res;
315 }
316 
317 template <typename LoopTy>
318 static Optional<TiledLinalgOp>
319 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes,
320                  const LinalgTilingOptions &options) {
321   auto nLoops = op.getNumLoops();
322   // Initial tile sizes may be too big, only take the first nLoops.
323   tileSizes = tileSizes.take_front(nLoops);
324 
325   if (llvm::all_of(tileSizes, isZero))
326     return llvm::None;
327 
328   if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) {
329     // For conv op only support tiling along batch dimension (which is the first
330     // loop).
331     if (convOp.padding() && !llvm::all_of(tileSizes.drop_front(), isZero))
332       return llvm::None;
333   }
334 
335   // 1. Build the tiled loop ranges.
336   auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc());
337   AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap();
338   if (!shapeSizesToLoopsMap)
339     return llvm::None;
340 
341   SmallVector<Range, 4> loopRanges;
342   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
343   std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges(
344       b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes);
345   SmallVector<Attribute, 4> iteratorTypes;
346   for (auto attr :
347        enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) {
348     if (loopIndexToRangeIndex.count(attr.index()))
349       iteratorTypes.push_back(attr.value());
350   }
351   // If interchangeVector is empty, use the identity. Build the permutation map
352   // otherwise.
353   auto invPermutationMap =
354       AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext());
355   if (!options.interchangeVector.empty()) {
356     // Based on the pruned iterations (due to zero tile size), recompute the
357     // interchange vector.
358     SmallVector<unsigned, 4> interchangeVector;
359     interchangeVector.reserve(options.interchangeVector.size());
360     for (auto pos : options.interchangeVector) {
361       auto it = loopIndexToRangeIndex.find(pos);
362       if (it == loopIndexToRangeIndex.end())
363         continue;
364       interchangeVector.push_back(it->second);
365     }
366     // Interchange vector is guaranteed to be a permutation,
367     // `inversePermutation` must succeed.
368     invPermutationMap = inversePermutation(
369         AffineMap::getPermutationMap(interchangeVector, b.getContext()));
370     assert(invPermutationMap);
371     applyPermutationToVector(loopRanges, interchangeVector);
372     applyPermutationToVector(iteratorTypes, interchangeVector);
373   }
374 
375   // 2. Create the tiled loops.
376   LinalgOp res = op;
377   SmallVector<Value, 4> ivs, tensorResults;
378   auto outputTensors = op.getOutputTensors();
379   GenerateLoopNest<LoopTy>::doit(
380       loopRanges, /*iterArgInitValues*/ outputTensors, iteratorTypes,
381       [&](ValueRange localIvs, ValueRange iterArgs) -> scf::ValueVector {
382         auto &b = ScopedContext::getBuilderRef();
383         auto loc = ScopedContext::getLocation();
384         ivs.assign(localIvs.begin(), localIvs.end());
385 
386         // When an `interchangeVector` is present, it has been applied to the
387         // loop ranges and the iterator types. Apply its inverse to the
388         // resulting loop `ivs` to match the op definition.
389         SmallVector<Value, 4> interchangedIvs;
390         if (!options.interchangeVector.empty())
391           interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs);
392         else
393           interchangedIvs.assign(ivs.begin(), ivs.end());
394 
395         assert(op.getNumOutputTensors() == iterArgs.size() &&
396                "num output tensors must match number of loop iter arguments");
397 
398         auto operands = llvm::to_vector<4>(op.getInputs());
399         SmallVector<Value, 4> outputBuffers = op.getOutputBuffers();
400         // TODO: thanks to simplifying assumption we do not need to worry about
401         // order of output buffers and tensors: there is only ever one kind.
402         assert(outputBuffers.empty() || iterArgs.empty());
403         operands.append(outputBuffers.begin(), outputBuffers.end());
404         operands.append(iterArgs.begin(), iterArgs.end());
405         SmallVector<Value, 4> tiledOperands =
406             makeTiledShapes(b, loc, op, operands, shapeSizesToLoopsMap,
407                             interchangedIvs, tileSizes, allShapeSizes);
408         auto nonShapedOperands = op.getAssumedNonShapedOperands();
409         tiledOperands.append(nonShapedOperands.begin(),
410                              nonShapedOperands.end());
411 
412         // TODO: use an interface/adaptor to avoid leaking position in
413         // `tiledOperands`.
414         SmallVector<Type, 4> resultTensorTypes;
415         for (OpOperand *opOperand : op.getOutputTensorsOpOperands())
416           resultTensorTypes.push_back(
417               tiledOperands[opOperand->getOperandNumber()].getType());
418 
419         res = op.clone(b, loc, resultTensorTypes, tiledOperands);
420 
421         // Insert a subtensor_insert for each output tensor.
422         unsigned resultIdx = 0;
423         for (OpOperand *opOperand : op.getOutputTensorsOpOperands()) {
424           // TODO: use an interface/adaptor to avoid leaking position in
425           // `tiledOperands`.
426           Value outputTensor = tiledOperands[opOperand->getOperandNumber()];
427           if (auto subtensor = outputTensor.getDefiningOp<SubTensorOp>()) {
428             tensorResults.push_back(b.create<SubTensorInsertOp>(
429                 loc, subtensor.source().getType(), res->getResult(resultIdx),
430                 subtensor.source(), subtensor.offsets(), subtensor.sizes(),
431                 subtensor.strides(), subtensor.static_offsets(),
432                 subtensor.static_sizes(), subtensor.static_strides()));
433           } else {
434             tensorResults.push_back(res->getResult(resultIdx));
435           }
436           ++resultIdx;
437         }
438         return scf::ValueVector(tensorResults.begin(), tensorResults.end());
439       },
440       options.distribution);
441 
442   // 3. Transforms index arguments of `linalg.generic` w.r.t. to the tiling.
443   transformIndexedGenericOpIndices(b, res, ivs, loopIndexToRangeIndex);
444 
445   // 4. Gather the newly created loops and return them with the new op.
446   SmallVector<Operation *, 8> loops;
447   loops.reserve(ivs.size());
448   for (auto iv : ivs) {
449     if (iv.isa<BlockArgument>()) {
450       loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp());
451       assert(loops.back() && "no owner found for induction variable!");
452     } else {
453       // TODO: Instead of doing this, try to recover the ops used instead of the
454       // loop.
455       loops.push_back(nullptr);
456     }
457   }
458 
459   // 5. Get the tensor results from the outermost loop if available. Otherwise
460   // use the previously captured `tensorResults`.
461   Operation *outermostLoop = nullptr;
462   for (Operation *loop : loops)
463     if ((outermostLoop = loop))
464       break;
465 
466   return TiledLinalgOp{
467       res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults};
468 }
469 
470 template <typename LoopTy>
471 Optional<TiledLinalgOp> static tileLinalgOpImpl(
472     OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) {
473   OpBuilder::InsertionGuard g(b);
474   b.setInsertionPoint(op);
475   ScopedContext scope(b, op.getLoc());
476 
477   // Enforce the convention that "tiling by zero" skips tiling a particular
478   // dimension. This convention is significantly simpler to handle instead of
479   // adjusting affine maps to account for missing dimensions.
480   auto nLoops = op.getNumLoops();
481   SmallVector<Value, 4> tileSizeVector =
482       options.tileSizeComputationFunction(b, op);
483   if (tileSizeVector.size() < nLoops) {
484     auto zero = std_constant_index(0);
485     tileSizeVector.append(nLoops - tileSizeVector.size(), zero);
486   }
487 
488   return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options);
489 }
490 
491 Optional<TiledLinalgOp>
492 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op,
493                            const LinalgTilingOptions &options) {
494   switch (options.loopType) {
495   case LinalgTilingLoopType::Loops:
496     return tileLinalgOpImpl<scf::ForOp>(b, op, options);
497   case LinalgTilingLoopType::ParallelLoops:
498     return tileLinalgOpImpl<scf::ParallelOp>(b, op, options);
499   default:;
500   }
501   return llvm::None;
502 }
503 
504 namespace {
505 /// Helper classes for type list expansion.
506 template <typename... OpTypes>
507 class CanonicalizationPatternList;
508 
509 template <>
510 class CanonicalizationPatternList<> {
511 public:
512   static void insert(OwningRewritePatternList &patterns, MLIRContext *ctx) {}
513 };
514 
515 template <typename OpTy, typename... OpTypes>
516 class CanonicalizationPatternList<OpTy, OpTypes...> {
517 public:
518   static void insert(OwningRewritePatternList &patterns, MLIRContext *ctx) {
519     OpTy::getCanonicalizationPatterns(patterns, ctx);
520     CanonicalizationPatternList<OpTypes...>::insert(patterns, ctx);
521   }
522 };
523 
524 /// Helper classes for type list expansion.
525 template <typename... OpTypes>
526 class RewritePatternList;
527 
528 template <>
529 class RewritePatternList<> {
530 public:
531   static void insert(OwningRewritePatternList &patterns,
532                      const LinalgTilingOptions &options, MLIRContext *ctx) {}
533 };
534 
535 template <typename OpTy, typename... OpTypes>
536 class RewritePatternList<OpTy, OpTypes...> {
537 public:
538   static void insert(OwningRewritePatternList &patterns,
539                      const LinalgTilingOptions &options, MLIRContext *ctx) {
540     patterns.insert<LinalgTilingPattern<OpTy>>(
541         ctx, options, LinalgMarker({}, Identifier::get("tiled", ctx)));
542     RewritePatternList<OpTypes...>::insert(patterns, options, ctx);
543   }
544 };
545 } // namespace
546 
547 OwningRewritePatternList
548 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) {
549   OwningRewritePatternList patterns;
550   populateLinalgTilingCanonicalizationPatterns(patterns, ctx);
551   return patterns;
552 }
553 
554 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns(
555     OwningRewritePatternList &patterns, MLIRContext *ctx) {
556   AffineApplyOp::getCanonicalizationPatterns(patterns, ctx);
557   AffineForOp::getCanonicalizationPatterns(patterns, ctx);
558   AffineMinOp::getCanonicalizationPatterns(patterns, ctx);
559   AffineMaxOp::getCanonicalizationPatterns(patterns, ctx);
560   scf::ForOp::getCanonicalizationPatterns(patterns, ctx);
561   scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx);
562   ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx);
563   SubTensorOp::getCanonicalizationPatterns(patterns, ctx);
564   SubViewOp::getCanonicalizationPatterns(patterns, ctx);
565   tensor::CastOp::getCanonicalizationPatterns(patterns, ctx);
566   ViewOp::getCanonicalizationPatterns(patterns, ctx);
567   CanonicalizationPatternList<
568 #define GET_OP_LIST
569 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
570       >::insert(patterns, ctx);
571 }
572 
573 /// Populate the given list with patterns that apply Linalg tiling.
574 static void insertTilingPatterns(OwningRewritePatternList &patterns,
575                                  const LinalgTilingOptions &options,
576                                  MLIRContext *ctx) {
577   RewritePatternList<
578 #define GET_OP_LIST
579 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc"
580       >::insert(patterns, options, ctx);
581 }
582 
583 static void applyTilingToLoopPatterns(LinalgTilingLoopType loopType,
584                                       FuncOp funcOp,
585                                       ArrayRef<int64_t> tileSizes) {
586   auto options =
587       LinalgTilingOptions().setTileSizes(tileSizes).setLoopType(loopType);
588   MLIRContext *ctx = funcOp.getContext();
589   OwningRewritePatternList patterns;
590   insertTilingPatterns(patterns, options, ctx);
591   applyPatternsAndFoldGreedily(funcOp, std::move(patterns));
592   applyPatternsAndFoldGreedily(funcOp,
593                                getLinalgTilingCanonicalizationPatterns(ctx));
594   // Drop the marker.
595   funcOp.walk([](LinalgOp op) {
596     op.removeAttr(LinalgTransforms::kLinalgTransformMarker);
597   });
598 }
599 
600 namespace {
601 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> {
602   LinalgTilingPass() = default;
603   LinalgTilingPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; }
604 
605   void runOnFunction() override {
606     applyTilingToLoopPatterns(LinalgTilingLoopType::Loops, getFunction(),
607                               tileSizes);
608   }
609 };
610 
611 struct LinalgTilingToParallelLoopsPass
612     : public LinalgTilingToParallelLoopsBase<LinalgTilingToParallelLoopsPass> {
613   LinalgTilingToParallelLoopsPass() = default;
614   LinalgTilingToParallelLoopsPass(ArrayRef<int64_t> sizes) {
615     tileSizes = sizes;
616   }
617 
618   void runOnFunction() override {
619     applyTilingToLoopPatterns(LinalgTilingLoopType::ParallelLoops,
620                               getFunction(), tileSizes);
621   }
622 };
623 
624 } // namespace
625 
626 std::unique_ptr<OperationPass<FuncOp>>
627 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
628   return std::make_unique<LinalgTilingPass>(tileSizes);
629 }
630 
631 std::unique_ptr<OperationPass<FuncOp>>
632 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) {
633   return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes);
634 }
635