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