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