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