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/MemRef/EDSC/Intrinsics.h" 21 #include "mlir/Dialect/MemRef/IR/MemRef.h" 22 #include "mlir/Dialect/SCF/EDSC/Builders.h" 23 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h" 24 #include "mlir/Dialect/Tensor/IR/Tensor.h" 25 #include "mlir/IR/AffineExpr.h" 26 #include "mlir/IR/AffineMap.h" 27 #include "mlir/Transforms/FoldUtils.h" 28 #include "mlir/Transforms/GreedyPatternRewriteDriver.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::scf; 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 85 // All indices returned by IndexOp should be invariant with respect to tiling. 86 // Therefore, if an operation is tiled, we have to transform the indices 87 // accordingly, i.e. offset them by the values of the corresponding induction 88 // variables that are captured implicitly in the body of the op. 89 // 90 // Example. `linalg.generic` before tiling: 91 // 92 // #id_2d = (i, j) -> (i, j) 93 // #pointwise_2d_trait = { 94 // indexing_maps = [#id_2d, #id_2d], 95 // iterator_types = ["parallel", "parallel"] 96 // } 97 // linalg.generic #pointwise_2d_trait %operand, %result { 98 // ^bb0(%operand_in: f32, %result_in: f32): 99 // %i = linalg.index 0 : index 100 // %j = linalg.index 1 : index 101 // <some operations that use %i, %j> 102 // }: memref<50x100xf32>, memref<50x100xf32> 103 // 104 // After tiling pass with tiles sizes 10 and 25: 105 // 106 // #strided = (i, j)[s0, s1, s2] -> (i * s1 + s0 + j * s2) 107 // 108 // %c1 = constant 1 : index 109 // %c0 = constant 0 : index 110 // %c25 = constant 25 : index 111 // %c10 = constant 10 : index 112 // operand_dim_0 = dim %operand, 0 : memref<50x100xf32> 113 // operand_dim_1 = dim %operand, 1 : memref<50x100xf32> 114 // scf.for %k = %c0 to operand_dim_0 step %c10 { 115 // scf.for %l = %c0 to operand_dim_1 step %c25 { 116 // %4 = std.subview %operand[%k, %l][%c10, %c25][%c1, %c1] 117 // : memref<50x100xf32> to memref<?x?xf32, #strided> 118 // %5 = std.subview %result[%k, %l][%c10, %c25][%c1, %c1] 119 // : memref<50x100xf32> to memref<?x?xf32, #strided> 120 // linalg.generic pointwise_2d_trait %4, %5 { 121 // ^bb0(%operand_in: f32, %result_in: f32): 122 // %i = linalg.index 0 : index 123 // %j = linalg.index 1 : index 124 // // Indices `k` and `l` are implicitly captured in the body. 125 // %transformed_i = addi %i, %k : index // index `i` is offset by %k 126 // %transformed_j = addi %j, %l : index // index `j` is offset by %l 127 // // Every use of %i, %j is replaced with %transformed_i, %transformed_j 128 // <some operations that use %transformed_i, %transformed_j> 129 // }: memref<?x?xf32, #strided>, memref<?x?xf32, #strided> 130 // } 131 // } 132 // 133 // TODO: Investigate whether mixing implicit and explicit indices 134 // does not lead to losing information. 135 static void 136 transformIndexOps(OpBuilder &b, LinalgOp op, SmallVectorImpl<Value> &ivs, 137 const LoopIndexToRangeIndexMap &loopIndexToRangeIndex) { 138 // Skip operations that have no region attached. 139 if (op->getNumRegions() == 0) 140 return; 141 assert(op->getNumRegions() == 1 && op->getRegion(0).getBlocks().size() == 1 && 142 "expected linalg operation to have one block."); 143 Block &block = op->getRegion(0).front(); 144 145 for (IndexOp indexOp : block.getOps<linalg::IndexOp>()) { 146 auto rangeIndex = loopIndexToRangeIndex.find(indexOp.dim()); 147 if (rangeIndex == loopIndexToRangeIndex.end()) 148 continue; 149 // Offset the index by the value of the corresponding induction variable and 150 // replace all uses of the previous value. 151 OpBuilder::InsertionGuard g(b); 152 b.setInsertionPointAfter(indexOp); 153 AffineExpr index, iv; 154 bindDims(b.getContext(), index, iv); 155 AffineApplyOp applyOp = b.create<AffineApplyOp>( 156 indexOp.getLoc(), index + iv, 157 ValueRange{indexOp.getResult(), ivs[rangeIndex->second]}); 158 indexOp.getResult().replaceAllUsesExcept( 159 applyOp.getResult(), SmallPtrSet<Operation *, 1>{applyOp}); 160 } 161 } 162 163 template <typename LoopTy> 164 static Optional<TiledLinalgOp> 165 tileLinalgOpImpl(OpBuilder &b, LinalgOp op, ValueRange tileSizes, 166 const LinalgTilingOptions &options) { 167 auto nLoops = op.getNumLoops(); 168 // Initial tile sizes may be too big, only take the first nLoops. 169 tileSizes = tileSizes.take_front(nLoops); 170 171 if (llvm::all_of(tileSizes, isZero)) 172 return llvm::None; 173 174 // Canonicalize indexed generic operations before tiling. 175 if (isa<IndexedGenericOp>(op)) 176 return llvm::None; 177 178 if (auto convOp = dyn_cast<linalg::ConvOp>(op.getOperation())) { 179 // For conv op only support tiling along batch dimension (which is the first 180 // loop). 181 if (convOp.padding() && !llvm::all_of(tileSizes.drop_front(), isZero)) 182 return llvm::None; 183 } 184 185 // 1. Build the tiled loop ranges. 186 auto allShapeSizes = op.createFlatListOfOperandDims(b, op.getLoc()); 187 AffineMap shapeSizesToLoopsMap = op.getShapesToLoopsMap(); 188 if (!shapeSizesToLoopsMap) 189 return llvm::None; 190 191 SmallVector<Range, 4> loopRanges; 192 LoopIndexToRangeIndexMap loopIndexToRangeIndex; 193 std::tie(loopRanges, loopIndexToRangeIndex) = makeTiledLoopRanges( 194 b, op.getLoc(), shapeSizesToLoopsMap, allShapeSizes, tileSizes); 195 196 SmallVector<Attribute, 4> iteratorTypes; 197 for (auto attr : 198 enumerate(op.iterator_types().cast<ArrayAttr>().getValue())) { 199 if (loopIndexToRangeIndex.count(attr.index())) 200 iteratorTypes.push_back(attr.value()); 201 } 202 // If interchangeVector is empty, use the identity. Build the permutation map 203 // otherwise. 204 auto invPermutationMap = 205 AffineMap::getMultiDimIdentityMap(tileSizes.size(), b.getContext()); 206 if (!options.interchangeVector.empty()) { 207 // Based on the pruned iterations (due to zero tile size), recompute the 208 // interchange vector. 209 SmallVector<unsigned, 4> interchangeVector; 210 interchangeVector.reserve(options.interchangeVector.size()); 211 for (auto pos : options.interchangeVector) { 212 auto it = loopIndexToRangeIndex.find(pos); 213 if (it == loopIndexToRangeIndex.end()) 214 continue; 215 interchangeVector.push_back(it->second); 216 } 217 // Interchange vector is guaranteed to be a permutation, 218 // `inversePermutation` must succeed. 219 invPermutationMap = inversePermutation( 220 AffineMap::getPermutationMap(interchangeVector, b.getContext())); 221 assert(invPermutationMap); 222 applyPermutationToVector(loopRanges, interchangeVector); 223 applyPermutationToVector(iteratorTypes, interchangeVector); 224 } 225 226 // 2. Create the tiled loops. 227 LinalgOp res = op; 228 SmallVector<Value, 4> ivs, tensorResults; 229 GenerateLoopNest<LoopTy>::doit( 230 loopRanges, op, iteratorTypes, 231 [&](ValueRange localIvs, ValueRange iterArgs) -> scf::ValueVector { 232 auto &b = ScopedContext::getBuilderRef(); 233 auto loc = ScopedContext::getLocation(); 234 ivs.assign(localIvs.begin(), localIvs.end()); 235 236 // When an `interchangeVector` is present, it has been applied to the 237 // loop ranges and the iterator types. Apply its inverse to the 238 // resulting loop `ivs` to match the op definition. 239 SmallVector<Value, 4> interchangedIvs; 240 if (!options.interchangeVector.empty()) 241 interchangedIvs = applyMapToValues(b, loc, invPermutationMap, ivs); 242 else 243 interchangedIvs.assign(ivs.begin(), ivs.end()); 244 245 assert(op.getNumOutputTensors() == iterArgs.size() && 246 "num output tensors must match number of loop iter arguments"); 247 248 auto operands = llvm::to_vector<4>(op.getInputs()); 249 SmallVector<Value, 4> outputBuffers = op.getOutputBuffers(); 250 // TODO: thanks to simplifying assumption we do not need to worry about 251 // order of output buffers and tensors: there is only ever one kind. 252 assert(outputBuffers.empty() || iterArgs.empty()); 253 operands.append(outputBuffers.begin(), outputBuffers.end()); 254 operands.append(iterArgs.begin(), iterArgs.end()); 255 auto sizeBounds = 256 applyMapToValues(b, loc, shapeSizesToLoopsMap, allShapeSizes); 257 SmallVector<Value, 4> tiledOperands = makeTiledShapes( 258 b, loc, op, operands, interchangedIvs, tileSizes, sizeBounds); 259 auto nonShapedOperands = op.getAssumedNonShapedOperands(); 260 tiledOperands.append(nonShapedOperands.begin(), 261 nonShapedOperands.end()); 262 263 // TODO: use an interface/adaptor to avoid leaking position in 264 // `tiledOperands`. 265 SmallVector<Type, 4> resultTensorTypes; 266 for (OpOperand *opOperand : op.getOutputTensorsOpOperands()) 267 resultTensorTypes.push_back( 268 tiledOperands[opOperand->getOperandNumber()].getType()); 269 270 res = op.clone(b, loc, resultTensorTypes, tiledOperands); 271 272 // Insert a subtensor_insert for each output tensor. 273 unsigned resultIdx = 0; 274 for (OpOperand *opOperand : op.getOutputTensorsOpOperands()) { 275 // TODO: use an interface/adaptor to avoid leaking position in 276 // `tiledOperands`. 277 Value outputTensor = tiledOperands[opOperand->getOperandNumber()]; 278 if (auto subtensor = outputTensor.getDefiningOp<SubTensorOp>()) { 279 tensorResults.push_back(b.create<SubTensorInsertOp>( 280 loc, subtensor.source().getType(), res->getResult(resultIdx), 281 subtensor.source(), subtensor.offsets(), subtensor.sizes(), 282 subtensor.strides(), subtensor.static_offsets(), 283 subtensor.static_sizes(), subtensor.static_strides())); 284 } else { 285 tensorResults.push_back(res->getResult(resultIdx)); 286 } 287 ++resultIdx; 288 } 289 return scf::ValueVector(tensorResults.begin(), tensorResults.end()); 290 }, 291 options.distribution); 292 293 // 3. Transform IndexOp results w.r.t. the tiling. 294 transformIndexOps(b, res, ivs, loopIndexToRangeIndex); 295 296 // 4. Gather the newly created loops and return them with the new op. 297 SmallVector<Operation *, 8> loops; 298 loops.reserve(ivs.size()); 299 for (auto iv : ivs) { 300 if (iv.isa<BlockArgument>()) { 301 loops.push_back(iv.cast<BlockArgument>().getOwner()->getParentOp()); 302 assert(loops.back() && "no owner found for induction variable!"); 303 } else { 304 // TODO: Instead of doing this, try to recover the ops used instead of the 305 // loop. 306 loops.push_back(nullptr); 307 } 308 } 309 310 // 5. Get the tensor results from the outermost loop if available. Otherwise 311 // use the previously captured `tensorResults`. 312 Operation *outermostLoop = nullptr; 313 for (Operation *loop : loops) 314 if ((outermostLoop = loop)) 315 break; 316 317 return TiledLinalgOp{ 318 res, loops, outermostLoop ? outermostLoop->getResults() : tensorResults}; 319 } 320 321 template <typename LoopTy> 322 Optional<TiledLinalgOp> static tileLinalgOpImpl( 323 OpBuilder &b, LinalgOp op, const LinalgTilingOptions &options) { 324 OpBuilder::InsertionGuard g(b); 325 b.setInsertionPoint(op); 326 ScopedContext scope(b, op.getLoc()); 327 328 if (!options.tileSizeComputationFunction) 329 return llvm::None; 330 331 // Enforce the convention that "tiling by zero" skips tiling a particular 332 // dimension. This convention is significantly simpler to handle instead of 333 // adjusting affine maps to account for missing dimensions. 334 auto nLoops = op.getNumLoops(); 335 SmallVector<Value, 4> tileSizeVector = 336 options.tileSizeComputationFunction(b, op); 337 if (tileSizeVector.size() < nLoops) { 338 auto zero = std_constant_index(0); 339 tileSizeVector.append(nLoops - tileSizeVector.size(), zero); 340 } 341 342 return tileLinalgOpImpl<LoopTy>(b, op, tileSizeVector, options); 343 } 344 345 Optional<TiledLinalgOp> 346 mlir::linalg::tileLinalgOp(OpBuilder &b, LinalgOp op, 347 const LinalgTilingOptions &options) { 348 switch (options.loopType) { 349 case LinalgTilingLoopType::Loops: 350 return tileLinalgOpImpl<scf::ForOp>(b, op, options); 351 case LinalgTilingLoopType::ParallelLoops: 352 return tileLinalgOpImpl<scf::ParallelOp>(b, op, options); 353 case LinalgTilingLoopType::TiledLoops: 354 return tileLinalgOpImpl<linalg::TiledLoopOp>(b, op, options); 355 default:; 356 } 357 return llvm::None; 358 } 359 360 namespace { 361 /// Helper classes for type list expansion. 362 template <typename... OpTypes> 363 class CanonicalizationPatternList; 364 365 template <> 366 class CanonicalizationPatternList<> { 367 public: 368 static void insert(RewritePatternSet &patterns) {} 369 }; 370 371 template <typename OpTy, typename... OpTypes> 372 class CanonicalizationPatternList<OpTy, OpTypes...> { 373 public: 374 static void insert(RewritePatternSet &patterns) { 375 OpTy::getCanonicalizationPatterns(patterns, patterns.getContext()); 376 CanonicalizationPatternList<OpTypes...>::insert(patterns); 377 } 378 }; 379 380 /// Helper classes for type list expansion. 381 template <typename... OpTypes> 382 class RewritePatternList; 383 384 template <> 385 class RewritePatternList<> { 386 public: 387 static void insert(RewritePatternSet &patterns, 388 const LinalgTilingOptions &options) {} 389 }; 390 391 template <typename OpTy, typename... OpTypes> 392 class RewritePatternList<OpTy, OpTypes...> { 393 public: 394 static void insert(RewritePatternSet &patterns, 395 const LinalgTilingOptions &options) { 396 auto *ctx = patterns.getContext(); 397 patterns.add<LinalgTilingPattern<OpTy>>( 398 ctx, options, 399 LinalgTransformationFilter(ArrayRef<Identifier>{}, 400 Identifier::get("tiled", ctx))); 401 RewritePatternList<OpTypes...>::insert(patterns, options); 402 } 403 }; 404 } // namespace 405 406 RewritePatternSet 407 mlir::linalg::getLinalgTilingCanonicalizationPatterns(MLIRContext *ctx) { 408 RewritePatternSet patterns(ctx); 409 populateLinalgTilingCanonicalizationPatterns(patterns); 410 return patterns; 411 } 412 413 void mlir::linalg::populateLinalgTilingCanonicalizationPatterns( 414 RewritePatternSet &patterns) { 415 auto *ctx = patterns.getContext(); 416 AffineApplyOp::getCanonicalizationPatterns(patterns, ctx); 417 AffineForOp::getCanonicalizationPatterns(patterns, ctx); 418 AffineMinOp::getCanonicalizationPatterns(patterns, ctx); 419 AffineMaxOp::getCanonicalizationPatterns(patterns, ctx); 420 scf::ForOp::getCanonicalizationPatterns(patterns, ctx); 421 scf::ParallelOp::getCanonicalizationPatterns(patterns, ctx); 422 ConstantIndexOp::getCanonicalizationPatterns(patterns, ctx); 423 SubTensorOp::getCanonicalizationPatterns(patterns, ctx); 424 memref::SubViewOp::getCanonicalizationPatterns(patterns, ctx); 425 tensor::CastOp::getCanonicalizationPatterns(patterns, ctx); 426 memref::ViewOp::getCanonicalizationPatterns(patterns, ctx); 427 CanonicalizationPatternList< 428 #define GET_OP_LIST 429 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc" 430 >::insert(patterns); 431 } 432 433 /// Populate the given list with patterns that apply Linalg tiling. 434 static void insertTilingPatterns(RewritePatternSet &patterns, 435 const LinalgTilingOptions &options) { 436 RewritePatternList<GenericOp, 437 #define GET_OP_LIST 438 #include "mlir/Dialect/Linalg/IR/LinalgStructuredOps.cpp.inc" 439 >::insert(patterns, options); 440 } 441 442 static void applyTilingToLoopPatterns(LinalgTilingLoopType loopType, 443 FuncOp funcOp, 444 ArrayRef<int64_t> tileSizes) { 445 auto options = 446 LinalgTilingOptions().setTileSizes(tileSizes).setLoopType(loopType); 447 MLIRContext *ctx = funcOp.getContext(); 448 RewritePatternSet patterns(ctx); 449 insertTilingPatterns(patterns, options); 450 (void)applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); 451 (void)applyPatternsAndFoldGreedily( 452 funcOp, getLinalgTilingCanonicalizationPatterns(ctx)); 453 // Drop the marker. 454 funcOp.walk([](LinalgOp op) { 455 op->removeAttr(LinalgTransforms::kLinalgTransformMarker); 456 }); 457 } 458 459 namespace { 460 struct LinalgTilingPass : public LinalgTilingBase<LinalgTilingPass> { 461 LinalgTilingPass() = default; 462 LinalgTilingPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; } 463 464 void runOnFunction() override { 465 applyTilingToLoopPatterns(LinalgTilingLoopType::Loops, getFunction(), 466 tileSizes); 467 } 468 }; 469 470 struct LinalgTilingToParallelLoopsPass 471 : public LinalgTilingToParallelLoopsBase<LinalgTilingToParallelLoopsPass> { 472 LinalgTilingToParallelLoopsPass() = default; 473 LinalgTilingToParallelLoopsPass(ArrayRef<int64_t> sizes) { 474 tileSizes = sizes; 475 } 476 477 void runOnFunction() override { 478 applyTilingToLoopPatterns(LinalgTilingLoopType::ParallelLoops, 479 getFunction(), tileSizes); 480 } 481 }; 482 483 struct LinalgTilingToTiledLoopsPass 484 : public LinalgTilingToTiledLoopsBase<LinalgTilingToTiledLoopsPass> { 485 LinalgTilingToTiledLoopsPass() = default; 486 LinalgTilingToTiledLoopsPass(ArrayRef<int64_t> sizes) { tileSizes = sizes; } 487 488 void runOnFunction() override { 489 applyTilingToLoopPatterns(LinalgTilingLoopType::TiledLoops, getFunction(), 490 tileSizes); 491 } 492 }; 493 494 } // namespace 495 496 std::unique_ptr<OperationPass<FuncOp>> 497 mlir::createLinalgTilingPass(ArrayRef<int64_t> tileSizes) { 498 return std::make_unique<LinalgTilingPass>(tileSizes); 499 } 500 501 std::unique_ptr<OperationPass<FuncOp>> 502 mlir::createLinalgTilingToParallelLoopsPass(ArrayRef<int64_t> tileSizes) { 503 return std::make_unique<LinalgTilingToParallelLoopsPass>(tileSizes); 504 } 505 506 std::unique_ptr<OperationPass<FuncOp>> 507 mlir::createLinalgTilingToTiledLoopPass(ArrayRef<int64_t> tileSizes) { 508 return std::make_unique<LinalgTilingToTiledLoopsPass>(tileSizes); 509 } 510