1 //===- Tiling.cpp - Implementation of linalg Tiling -----------------------===//
2 //
3 // Part of the MLIR 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 "mlir/Dialect/Linalg/EDSC/Builders.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15 #include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
16 #include "mlir/Dialect/Linalg/Passes.h"
17 #include "mlir/Dialect/Linalg/Utils/Intrinsics.h"
18 #include "mlir/Dialect/Linalg/Utils/Utils.h"
19 #include "mlir/Dialect/LoopOps/LoopOps.h"
20 #include "mlir/EDSC/Helpers.h"
21 #include "mlir/IR/AffineExpr.h"
22 #include "mlir/IR/AffineExprVisitor.h"
23 #include "mlir/IR/AffineMap.h"
24 #include "mlir/IR/OpImplementation.h"
25 #include "mlir/Pass/Pass.h"
26 #include "mlir/Support/LLVM.h"
27 #include "mlir/Support/STLExtras.h"
28 #include "mlir/Transforms/FoldUtils.h"
29 
30 #include "llvm/Support/CommandLine.h"
31 
32 using namespace mlir;
33 using namespace mlir::edsc;
34 using namespace mlir::edsc::intrinsics;
35 using namespace mlir::linalg;
36 using namespace mlir::linalg::intrinsics;
37 using namespace mlir::loop;
38 
39 #define DEBUG_TYPE "linalg-tiling"
40 
41 static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options");
42 static llvm::cl::list<unsigned>
43     clTileSizes("linalg-tile-sizes",
44                 llvm::cl::desc("Tile sizes by which to tile linalg operations"),
45                 llvm::cl::ZeroOrMore, llvm::cl::MiscFlags::CommaSeparated,
46                 llvm::cl::cat(clOptionsCategory));
47 
48 static bool isZero(Value v) {
49   return isa_and_nonnull<ConstantIndexOp>(v.getDefiningOp()) &&
50          cast<ConstantIndexOp>(v.getDefiningOp()).getValue() == 0;
51 }
52 
53 using LoopIndexToRangeIndexMap = DenseMap<int, int>;
54 
55 // Creates a number of ranges equal to the number of non-zero in `tileSizes`.
56 // One for each loop of the LinalgOp that is tiled. The `tileSizes` argument has
57 // one entry per surrounding loop. It uses zero as the convention that a
58 // particular loop is not tiled. This convention simplifies implementations by
59 // avoiding affine map manipulations.
60 // The returned ranges correspond to the loop ranges, in the proper order, that
61 // are tiled and for which new loops will be created. Also the function returns
62 // a map from loop indices of the LinalgOp to the corresponding non-empty range
63 // indices of newly created loops.
64 static std::tuple<SmallVector<SubViewOp::Range, 4>, LoopIndexToRangeIndexMap>
65 makeTiledLoopRanges(OpBuilder &b, Location loc, AffineMap map,
66                     ArrayRef<Value> allViewSizes, ArrayRef<Value> allTileSizes,
67                     OperationFolder *folder) {
68   assert(allTileSizes.size() == map.getNumResults());
69   // Apply `map` to get view sizes in loop order.
70   auto viewSizes = applyMapToValues(b, loc, map, allViewSizes, folder);
71   SmallVector<Value, 4> tileSizes(allTileSizes.begin(), allTileSizes.end());
72 
73   // Traverse the tile sizes, which are in loop order, erase zeros everywhere.
74   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
75   for (int idx = 0, e = tileSizes.size(), zerosCount = 0; idx < e; ++idx) {
76     if (isZero(tileSizes[idx - zerosCount])) {
77       viewSizes.erase(viewSizes.begin() + idx - zerosCount);
78       tileSizes.erase(tileSizes.begin() + idx - zerosCount);
79       ++zerosCount;
80       continue;
81     }
82     loopIndexToRangeIndex[idx] = idx - zerosCount;
83   }
84 
85   // Create a new range with the applied tile sizes.
86   SmallVector<SubViewOp::Range, 4> res;
87   for (unsigned idx = 0, e = tileSizes.size(); idx < e; ++idx) {
88     res.push_back(SubViewOp::Range{constant_index(folder, 0), viewSizes[idx],
89                                    tileSizes[idx]});
90   }
91   return std::make_tuple(res, loopIndexToRangeIndex);
92 }
93 
94 namespace {
95 
96 // Helper visitor to determine whether an AffineExpr is tiled.
97 // This is achieved by traversing every AffineDimExpr with position `pos` and
98 // checking whether the corresponding `tileSizes[pos]` is non-zero.
99 // This also enforces only positive coefficients occur in multiplications.
100 //
101 // Example:
102 //   `d0 + 2 * d1 + d3` is tiled by [0, 0, 0, 2] but not by [0, 0, 2, 0]
103 //
104 struct TileCheck : public AffineExprVisitor<TileCheck> {
105   TileCheck(ArrayRef<Value> tileSizes) : isTiled(false), tileSizes(tileSizes) {}
106 
107   void visitDimExpr(AffineDimExpr expr) {
108     isTiled |= !isZero(tileSizes[expr.getPosition()]);
109   }
110   void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) {
111     visit(expr.getLHS());
112     visit(expr.getRHS());
113     if (expr.getKind() == mlir::AffineExprKind::Mul)
114       assert(expr.getRHS().cast<AffineConstantExpr>().getValue() > 0 &&
115              "nonpositive multiplying coefficient");
116   }
117   bool isTiled;
118   ArrayRef<Value> tileSizes;
119 };
120 
121 } // namespace
122 
123 // IndexedGenericOp explicitly uses induction variables in the loop body. The
124 // values of the indices that are used in the loop body for any given access of
125 // input/output memref before `subview` op was applied should be invariant with
126 // respect to tiling.
127 //
128 // Therefore, if the operation is tiled, we have to transform the indices
129 // accordingly, i.e. offset them by the values of the corresponding induction
130 // variables that are captured implicitly in the body of the op.
131 //
132 // Example. `linalg.indexed_generic` before tiling:
133 //
134 // #id_2d = (i, j) -> (i, j)
135 // #pointwise_2d_trait = {
136 //   indexing_maps = [#id_2d, #id_2d],
137 //   iterator_types = ["parallel", "parallel"],
138 //   n_views = [1, 1]
139 // }
140 // linalg.indexed_generic #pointwise_2d_trait %operand, %result {
141 //   ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
142 //     <some operations that use %i, %j>
143 // }: memref<50x100xf32>, memref<50x100xf32>
144 //
145 // After tiling pass with tiles sizes 10 and 25:
146 //
147 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2)
148 //
149 // %c1 = constant 1 : index
150 // %c0 = constant 0 : index
151 // %c25 = constant 25 : index
152 // %c10 = constant 10 : index
153 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32>
154 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32>
155 // loop.for %k = %c0 to operand_dim_0 step %c10 {
156 //   loop.for %l = %c0 to operand_dim_1 step %c25 {
157 //     %4 = std.subview %operand[%k, %l][%c10, %c25][%c1, %c1]
158 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
159 //     %5 = std.subview %result[%k, %l][%c10, %c25][%c1, %c1]
160 //       : memref<50x100xf32> to memref<?x?xf32, #strided>
161 //     linalg.indexed_generic pointwise_2d_trait %4, %5 {
162 //     ^bb0(%i: index, %j: index, %operand_in: f32, %result_in: f32):
163 //       // Indices `k` and `l` are implicitly captured in the body.
164 //       %transformed_i = addi %i, %k : index // index `i` is offset by %k
165 //       %transformed_j = addi %j, %l : index // index `j` is offset by %l
166 //       // Every use of %i, %j is replaced with %transformed_i, %transformed_j
167 //       <some operations that use %transformed_i, %transformed_j>
168 //     }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided>
169 //   }
170 // }
171 //
172 // TODO(pifon, ntv): Investigate whether mixing implicit and explicit indices
173 // does not lead to losing information.
174 static void transformIndexedGenericOpIndices(
175     OpBuilder &b, LinalgOp op, ArrayRef<ValueHandle *> pivs,
176     const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) {
177   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
178   auto indexedGenericOp = dyn_cast<IndexedGenericOp>(op.getOperation());
179   if (!indexedGenericOp)
180     return;
181 
182   // `linalg.indexed_generic` comes in two flavours. One has a region with a
183   // single block that defines the loop body. The other has a `fun` attribute
184   // that refers to an existing function symbol. The `fun` function call will be
185   // inserted in the loop body in that case.
186   //
187   // TODO(pifon): Add support for `linalg.indexed_generic` with `fun` attribute.
188   auto &region = indexedGenericOp.region();
189   if (region.empty()) {
190     indexedGenericOp.emitOpError("expected a region");
191     return;
192   }
193   auto &block = region.getBlocks().front();
194 
195   OpBuilder::InsertionGuard g(b);
196   b.setInsertionPointToStart(&block);
197   for (unsigned i = 0; i < indexedGenericOp.getNumLoops(); ++i) {
198     auto rangeIndex = loopIndexToRangeIndex.find(i);
199     if (rangeIndex == loopIndexToRangeIndex.end())
200       continue;
201     Value oldIndex = block.getArgument(i);
202     // Offset the index argument `i` by the value of the corresponding induction
203     // variable and replace all uses of the previous value.
204     Value newIndex = b.create<AddIOp>(indexedGenericOp.getLoc(), oldIndex,
205                                       pivs[rangeIndex->second]->getValue());
206     for (auto &use : oldIndex.getUses()) {
207       if (use.getOwner() == newIndex.getDefiningOp())
208         continue;
209       use.set(newIndex);
210     }
211   }
212 }
213 
214 static bool isTiled(AffineExpr expr, ArrayRef<Value> tileSizes) {
215   if (!expr)
216     return false;
217   TileCheck t(tileSizes);
218   t.visit(expr);
219   return t.isTiled;
220 }
221 
222 // Checks whether the view with index `viewIndex` within `linalgOp` varies with
223 // respect to a non-zero `tileSize`.
224 static bool isTiled(AffineMap map, ArrayRef<Value> tileSizes) {
225   if (!map)
226     return false;
227   for (unsigned r = 0; r < map.getNumResults(); ++r)
228     if (isTiled(map.getResult(r), tileSizes))
229       return true;
230   return false;
231 }
232 
233 static SmallVector<Value, 4>
234 makeTiledViews(OpBuilder &b, Location loc, LinalgOp linalgOp,
235                ArrayRef<Value> ivs, ArrayRef<Value> tileSizes,
236                ArrayRef<Value> viewSizes, OperationFolder *folder) {
237   assert(linalgOp.hasBufferSemantics() &&
238          "expected linalg op with buffer semantics");
239   assert(ivs.size() == static_cast<size_t>(llvm::count_if(
240                            llvm::make_range(tileSizes.begin(), tileSizes.end()),
241                            [](Value v) { return !isZero(v); })) &&
242          "expected as many ivs as non-zero sizes");
243 
244   using edsc::intrinsics::select;
245   using edsc::op::operator+;
246   using edsc::op::operator<;
247 
248   // Construct (potentially temporary) mins and maxes on which to apply maps
249   // that define tile subviews.
250   SmallVector<Value, 8> lbs, subViewSizes;
251   for (unsigned idx = 0, idxIvs = 0, e = tileSizes.size(); idx < e; ++idx) {
252     bool isTiled = !isZero(tileSizes[idx]);
253     lbs.push_back(isTiled ? ivs[idxIvs++] : (Value)constant_index(folder, 0));
254     subViewSizes.push_back(isTiled ? tileSizes[idx] : viewSizes[idx]);
255   }
256 
257   auto *op = linalgOp.getOperation();
258 
259   SmallVector<Value, 4> res;
260   res.reserve(op->getNumOperands());
261   auto viewIteratorBegin = linalgOp.getInputsAndOutputBuffers().begin();
262   for (unsigned viewIndex = 0; viewIndex < linalgOp.getNumInputsAndOutputs();
263        ++viewIndex) {
264     Value view = *(viewIteratorBegin + viewIndex);
265     unsigned rank = view.getType().cast<MemRefType>().getRank();
266     auto map = loopToOperandRangesMaps(linalgOp)[viewIndex];
267     // If the view is not tiled, we can use it as is.
268     if (!isTiled(map, tileSizes)) {
269       res.push_back(view);
270       continue;
271     }
272 
273     // Construct a new subview for the tile.
274     SmallVector<Value, 4> offsets, sizes, strides;
275     offsets.reserve(rank);
276     sizes.reserve(rank);
277     strides.reserve(rank);
278     for (unsigned r = 0; r < rank; ++r) {
279       if (!isTiled(map.getSubMap({r}), tileSizes)) {
280         offsets.push_back(constant_index(folder, 0));
281         sizes.push_back(dim(view, r));
282         strides.push_back(constant_index(folder, 1));
283         continue;
284       }
285 
286       // Tiling creates a new slice at the proper index, the slice step is 1
287       // (i.e. the slice view does not subsample, stepping occurs in the loop).
288       auto m = map.getSubMap({r});
289       auto offset = applyMapToValues(b, loc, m, lbs, folder).front();
290       offsets.push_back(offset);
291       auto size = applyMapToValues(b, loc, m, subViewSizes, folder).front();
292       sizes.push_back(size);
293       strides.push_back(constant_index(folder, 1));
294     }
295     // TODO(b/144419024) Atm std.subview is not guaranteed in-bounds. Depending
296     // on the semantics we attach to it, we may need to use min(size, dim) here
297     // and canonicalize later.
298     res.push_back(b.create<SubViewOp>(loc, view, offsets, sizes, strides));
299   }
300 
301   // Traverse the mins/maxes and erase those that don't have uses left.
302   // This is a special type of folding that we only apply when `folder` is
303   // defined.
304   if (folder)
305     for (auto v : llvm::concat<Value>(lbs, subViewSizes))
306       if (v.use_empty())
307         v.getDefiningOp()->erase();
308 
309   return res;
310 }
311 
312 Optional<TiledLinalgOp>
313 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op, ArrayRef<Value> tileSizes,
314                            ArrayRef<unsigned> permutation,
315                            OperationFolder *folder) {
316   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
317   // 1. Enforce the convention that "tiling by zero" skips tiling a particular
318   // dimension. This convention is significantly simpler to handle instead of
319   // adjusting affine maps to account for missing dimensions.
320   assert(op.getNumParallelLoops() + op.getNumReductionLoops() +
321                  op.getNumWindowLoops() ==
322              tileSizes.size() &&
323          "expected matching number of tile sizes and loops");
324 
325   // If permutation is empty, use the identity. Build the permutation map
326   // otherwise.
327   auto invPermutationMap = AffineMap::getMultiDimIdentityMap(
328       tileSizes.size(), ScopedContext::getContext());
329   if (!permutation.empty())
330     invPermutationMap = inversePermutation(
331         AffineMap::getPermutationMap(permutation, ScopedContext::getContext()));
332 
333   OpBuilder::InsertionGuard g(b);
334   b.setInsertionPoint(op);
335   ScopedContext scope(b, op.getLoc());
336   // 2. Build the tiled loop ranges.
337   auto viewSizes = getViewSizes(b, op);
338   // The flattened loopToOperandRangesMaps is expected to be an invertible
339   // permutation map (asserted in the inverse calculation).
340   auto viewSizesToLoopsMap =
341       inversePermutation(concatAffineMaps(loopToOperandRangesMaps(op)));
342   assert(viewSizesToLoopsMap && "expected invertible map");
343 
344   SmallVector<SubViewOp::Range, 4> loopRanges;
345   LoopIndexToRangeIndexMap loopIndexToRangeIndex;
346   std::tie(loopRanges, loopIndexToRangeIndex) =
347       makeTiledLoopRanges(b, scope.getLocation(), viewSizesToLoopsMap,
348                           viewSizes, tileSizes, folder);
349   if (!permutation.empty())
350     applyPermutationToVector(loopRanges, permutation);
351 
352   // 3. Create the tiled loops.
353   LinalgOp res = op;
354   SmallVector<IndexHandle, 4> ivs(loopRanges.size());
355   auto pivs = makeHandlePointers(MutableArrayRef<IndexHandle>(ivs));
356   LoopNestRangeBuilder(pivs, loopRanges)([&] {
357     auto b = ScopedContext::getBuilder();
358     auto loc = ScopedContext::getLocation();
359     SmallVector<Value, 4> ivValues(ivs.begin(), ivs.end());
360 
361     // If we have to apply a permutation to the tiled loop nest, we have to
362     // reorder the induction variables This permutation is the right one
363     // assuming that loopRanges have previously been permuted by
364     // (i,j,k)->(k,i,j) So this permutation should be the inversePermutation of
365     // that one: (d0,d1,d2)->(d2,d0,d1)
366     if (!permutation.empty())
367       ivValues = applyMapToValues(b, loc, invPermutationMap, ivValues, folder);
368 
369     auto views =
370         makeTiledViews(b, loc, op, ivValues, tileSizes, viewSizes, folder);
371     auto operands = getAssumedNonViewOperands(op);
372     views.append(operands.begin(), operands.end());
373     res = op.clone(b, loc, views);
374   });
375 
376   // 4. Transforms index arguments of `linalg.generic` w.r.t. to the tiling.
377   transformIndexedGenericOpIndices(b, res, pivs, loopIndexToRangeIndex);
378 
379   // 5. Gather the newly created loops and return them with the new op.
380   SmallVector<ForOp, 8> loops;
381   loops.reserve(ivs.size());
382   for (auto iv : ivs)
383     loops.push_back(loop::getForInductionVarOwner(iv));
384 
385   return TiledLinalgOp{res, loops};
386 }
387 
388 Optional<TiledLinalgOp> mlir::linalg::tileLinalgOp(
389     OpBuilder &b, LinalgOp op, ArrayRef<int64_t> tileSizes,
390     ArrayRef<unsigned> permutation, OperationFolder *folder) {
391   assert(op.hasBufferSemantics() && "expected linalg op with buffer semantics");
392   if (tileSizes.empty())
393     return llvm::None;
394 
395   // The following uses the convention that "tiling by zero" skips tiling a
396   // particular dimension. This convention is significantly simpler to handle
397   // instead of adjusting affine maps to account for missing dimensions.
398   auto nLoops = op.getNumParallelLoops() + op.getNumReductionLoops() +
399                 op.getNumWindowLoops();
400   tileSizes = tileSizes.take_front(nLoops);
401   // If only 0 tilings are left, then return.
402   if (llvm::all_of(tileSizes, [](int64_t v) { return v == 0; }))
403     return llvm::None;
404 
405   // Create a builder for tile size constants.
406   OpBuilder::InsertionGuard g(b);
407   b.setInsertionPoint(op);
408   ScopedContext scope(b, op.getLoc());
409 
410   // Materialize concrete tile size values to pass the generic tiling function.
411   SmallVector<Value, 8> tileSizeValues;
412   tileSizeValues.reserve(tileSizes.size());
413   for (auto ts : tileSizes)
414     tileSizeValues.push_back(constant_index(folder, ts));
415   // Pad tile sizes with zero values to enforce our convention.
416   if (tileSizeValues.size() < nLoops) {
417     for (unsigned i = tileSizeValues.size(); i < nLoops; ++i)
418       tileSizeValues.push_back(constant_index(folder, 0));
419   }
420 
421   return tileLinalgOp(b, op, tileSizeValues, permutation, folder);
422 }
423 
424 static void tileLinalgOps(FuncOp f, ArrayRef<int64_t> tileSizes) {
425   OpBuilder b(f);
426   OperationFolder folder(f.getContext());
427   f.walk([tileSizes, &b, &folder](LinalgOp op) {
428     if (!op.hasBufferSemantics())
429       return;
430     auto opLoopsPair =
431         tileLinalgOp(b, op, tileSizes, /*permutation=*/{}, &folder);
432     // If tiling occurred successfully, erase old op.
433     if (opLoopsPair)
434       op.erase();
435   });
436   f.walk([](LinalgOp op) {
437     if (!op.getOperation()->hasNoSideEffect())
438       return;
439     if (op.getOperation()->use_empty())
440       op.erase();
441   });
442 }
443 
444 namespace {
445 struct LinalgTilingPass : public FunctionPass<LinalgTilingPass> {
446   LinalgTilingPass() = default;
447   LinalgTilingPass(ArrayRef<int64_t> sizes);
448 
449   void runOnFunction() override { tileLinalgOps(getFunction(), tileSizes); }
450 
451   SmallVector<int64_t, 8> tileSizes;
452 };
453 } // namespace
454 
455 LinalgTilingPass::LinalgTilingPass(ArrayRef<int64_t> sizes) {
456   this->tileSizes.assign(sizes.begin(), sizes.end());
457 }
458 
459 std::unique_ptr<OpPassBase<FuncOp>>
460 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) {
461   return std::make_unique<LinalgTilingPass>(tileSizes);
462 }
463 
464 static PassRegistration<LinalgTilingPass>
465     pass("linalg-tile", "Tile operations in the linalg dialect", [] {
466       auto pass = std::make_unique<LinalgTilingPass>();
467       pass->tileSizes.assign(clTileSizes.begin(), clTileSizes.end());
468       return pass;
469     });
470