1 //===- Tiling.cpp - Implementation of tiling using TilingInterface -------===// 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 tiling using TilingInterface. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Dialect/SCF/Transforms/TileUsingInterface.h" 14 15 #include "mlir/Dialect/Affine/IR/AffineOps.h" 16 #include "mlir/Dialect/Arith/IR/Arith.h" 17 #include "mlir/Dialect/Arith/Utils/Utils.h" 18 #include "mlir/Dialect/Func/IR/FuncOps.h" 19 #include "mlir/Dialect/SCF/Utils/Utils.h" 20 #include "mlir/Dialect/Tensor/IR/Tensor.h" 21 #include "mlir/Dialect/Utils/IndexingUtils.h" 22 #include "mlir/IR/Matchers.h" 23 #include "mlir/IR/PatternMatch.h" 24 #include "mlir/Interfaces/DestinationStyleOpInterface.h" 25 #include "mlir/Interfaces/TilingInterface.h" 26 #include "llvm/Support/Debug.h" 27 #include <optional> 28 29 #define DEBUG_TYPE "tile-using-interface" 30 31 using namespace mlir; 32 33 scf::SCFTilingOptions & 34 scf::SCFTilingOptions::setTileSizes(ArrayRef<OpFoldResult> ts) { 35 assert(!tileSizeComputationFunction && "tile sizes already set"); 36 auto tileSizes = llvm::to_vector(ts); 37 tileSizeComputationFunction = [tileSizes](OpBuilder &b, Operation *op) { 38 return tileSizes; 39 }; 40 return *this; 41 } 42 43 /// Helper method to adjust the interchange vector to match the iteration 44 /// domain. 45 static SmallVector<int64_t> 46 fillInterchangeVector(ArrayRef<int64_t> interchangeVector, 47 size_t iterationDomainSize) { 48 SmallVector<int64_t> filledVector = llvm::to_vector(interchangeVector); 49 if (filledVector.size() < iterationDomainSize) { 50 auto range = llvm::seq<int64_t>(filledVector.size(), iterationDomainSize); 51 filledVector.append(range.begin(), range.end()); 52 } 53 if (filledVector.size() > iterationDomainSize) 54 filledVector.resize(iterationDomainSize); 55 return filledVector; 56 } 57 58 /// Convert a list of ops of type `SrcOpTy` to list of `Operation *`. 59 template <typename SrcOpTy> 60 static SmallVector<Operation *> getAsOperations(ArrayRef<SrcOpTy> ops) { 61 return llvm::to_vector( 62 llvm::map_range(ops, [](auto op) -> Operation * { return op; })); 63 } 64 template <typename SrcOpTy> 65 static SmallVector<Operation *> 66 getAsOperations(const SmallVector<SrcOpTy> &ops) { 67 return getAsOperations(ArrayRef<SrcOpTy>(ops)); 68 } 69 70 /// Convert a list of `Operation *` to a list of `DstOpTy. 71 template <typename DstOpTy> 72 static SmallVector<DstOpTy> castToTypedOperations(ArrayRef<Operation *> ops) { 73 return llvm::to_vector( 74 llvm::map_range(ops, [](Operation *op) { return cast<DstOpTy>(op); })); 75 } 76 template <typename DstOpTy> 77 static SmallVector<DstOpTy> 78 castToTypedOperations(const SmallVector<Operation *> &ops) { 79 return castToTypedOperations<DstOpTy>(ArrayRef<Operation *>(ops)); 80 } 81 82 //===----------------------------------------------------------------------===// 83 // tileUsingSCFForOp implementation. 84 //===----------------------------------------------------------------------===// 85 86 // Check if `stride` evenly divides the trip count `size - offset`. 87 static bool tileDividesIterationDomain(Range loopRange) { 88 std::optional<int64_t> offsetAsInt = getConstantIntValue(loopRange.offset); 89 if (!offsetAsInt) 90 return false; 91 std::optional<int64_t> sizeAsInt = getConstantIntValue(loopRange.size); 92 if (!sizeAsInt) 93 return false; 94 std::optional<int64_t> strideAsInt = getConstantIntValue(loopRange.stride); 95 if (!strideAsInt) 96 return false; 97 return ((sizeAsInt.value() - offsetAsInt.value()) % strideAsInt.value() == 0); 98 } 99 100 /// Returns the bounded tile size given the current `iv`, `loopRange` and 101 /// `tileSize`, i.e., `min(tileSize, range.end() - iv)`. 102 static OpFoldResult getBoundedTileSize(OpBuilder &b, Location loc, 103 Range loopRange, Value iv, 104 OpFoldResult tileSize) { 105 std::optional<int64_t> ts = getConstantIntValue(tileSize); 106 if (ts && ts.value() == 1) 107 return tileSize; 108 109 if (tileDividesIterationDomain( 110 Range{loopRange.offset, loopRange.size, tileSize})) 111 return tileSize; 112 113 // The tile size to use (to avoid out of bounds access) is minimum of 114 // `tileSize` and `ub - iv`, where `iv` is the induction variable of the tiled 115 // loop. 116 AffineExpr s0, s1, d0; 117 bindDims(b.getContext(), d0); 118 bindSymbols(b.getContext(), s0, s1); 119 AffineMap minMap = AffineMap::get(1, 2, {s0, s1 - d0}, b.getContext()); 120 Value size = getValueOrCreateConstantIndexOp(b, loc, loopRange.size); 121 return affine::makeComposedFoldedAffineMin( 122 b, loc, minMap, SmallVector<OpFoldResult>{iv, tileSize, size}); 123 } 124 125 /// Clones the operation and updates the destination if the operation 126 /// implements the `DestinationStyleOpInterface`. 127 static Operation *cloneOpAndUpdateDestinationArgs(RewriterBase &rewriter, 128 Operation *op, 129 ValueRange newDestArgs) { 130 Operation *clonedOp = rewriter.clone(*op); 131 if (auto destinationStyleOp = 132 dyn_cast<DestinationStyleOpInterface>(clonedOp)) { 133 destinationStyleOp.getDpsInitsMutable().assign(newDestArgs); 134 } 135 return clonedOp; 136 } 137 138 /// Generate an empty loop nest that represents the tiled loop nest shell. 139 /// - `loopRanges` specifies the lb, ub and step of the untiled iteration space. 140 /// - `tileSizes` is the tile sizes to use. Zero represent untiled loops. 141 /// - In `offsets` and `sizes` return the multi-dimensional offset and size of 142 /// the 143 /// tile processed within the inner most loop. 144 static SmallVector<scf::ForOp> generateTileLoopNest( 145 OpBuilder &builder, Location loc, ArrayRef<Range> loopRanges, 146 ArrayRef<OpFoldResult> tileSizes, SmallVector<OpFoldResult> &offsets, 147 SmallVector<OpFoldResult> &sizes) { 148 assert(!loopRanges.empty() && "expected at least one loop range"); 149 assert(loopRanges.size() == tileSizes.size() && 150 "expected as many tile sizes as loop ranges"); 151 OpBuilder::InsertionGuard guard(builder); 152 SmallVector<scf::ForOp> loops; 153 offsets.resize(loopRanges.size()); 154 sizes.resize(loopRanges.size()); 155 156 for (auto loopRange : llvm::enumerate(loopRanges)) { 157 Value offset = 158 getValueOrCreateConstantIndexOp(builder, loc, loopRange.value().offset); 159 Value size = 160 getValueOrCreateConstantIndexOp(builder, loc, loopRange.value().size); 161 Value tileSize = getValueOrCreateConstantIndexOp( 162 builder, loc, tileSizes[loopRange.index()]); 163 // No loops if tile size is zero. Set offset and size to the loop 164 // offset and size. 165 if (matchPattern(tileSize, m_Zero())) { 166 offsets[loopRange.index()] = offset; 167 sizes[loopRange.index()] = size; 168 continue; 169 } 170 171 auto loop = builder.create<scf::ForOp>( 172 loc, offset, size, tileSize, ValueRange{}, 173 [&](OpBuilder &bodyBuilder, Location bodyLoc, Value iv, 174 ValueRange /*iterArgs*/) { 175 sizes[loopRange.index()] = getBoundedTileSize( 176 bodyBuilder, bodyLoc, loopRange.value(), iv, tileSize); 177 builder.create<scf::YieldOp>(loc); 178 }); 179 offsets[loopRange.index()] = loop.getInductionVar(); 180 loops.push_back(loop); 181 builder.setInsertionPoint(loop.getBody()->getTerminator()); 182 } 183 return loops; 184 } 185 186 /// For a value to be yielded (`yieldedValue`) from within a loop nest `loops`, 187 /// construct the destructive update pattern that inserts the yielded 188 /// value into a destination tensor provided by `initValue` at offset 189 /// `tileOffsets` and size `tileSizes`. For example, 190 /// 191 /// ```mlir 192 /// scf.for %iv0 = ... { 193 /// %0 = tiled_op 194 /// } 195 /// ``` 196 /// 197 /// is transformed to 198 /// 199 /// ```mlir 200 /// scf.for %iv0 = ... iter_args(%arg = %0) { 201 /// %1 = tensor.extract_slice %arg 202 /// %2 = tiled_op 203 /// %3 = tensor.insert_slice %2 into %arg 204 /// scf.yield %3 205 /// } 206 /// ``` 207 /// TODO: This API can be cleaned up by using `SubsetExtractOpInterface`. 208 static SmallVector<Value> 209 yieldTiledValues(RewriterBase &rewriter, ValueRange initValues, 210 ValueRange yieldedValues, 211 ArrayRef<SmallVector<OpFoldResult>> tileOffsetsList, 212 ArrayRef<SmallVector<OpFoldResult>> tileSizesList, 213 MutableArrayRef<scf::ForOp> loops) { 214 NewYieldValuesFn yieldValueFn = 215 [&](OpBuilder &b, Location loc, 216 ArrayRef<BlockArgument> newBBArgs) -> SmallVector<Value> { 217 SmallVector<Value> inserts; 218 for (const auto &yieldedValue : llvm::enumerate(yieldedValues)) { 219 ArrayRef<OpFoldResult> tileOffsets = 220 tileOffsetsList[yieldedValue.index()]; 221 ArrayRef<OpFoldResult> tileSizes = tileSizesList[yieldedValue.index()]; 222 SmallVector<OpFoldResult> tileStrides(tileOffsets.size(), 223 b.getIndexAttr(1)); 224 Value insert = b.create<tensor::InsertSliceOp>( 225 loc, yieldedValue.value(), newBBArgs[yieldedValue.index()], 226 tileOffsets, tileSizes, tileStrides); 227 inserts.push_back(insert); 228 } 229 return inserts; 230 }; 231 232 SmallVector<scf::ForOp> newLoops = 233 replaceLoopNestWithNewYields(rewriter, loops, initValues, yieldValueFn, 234 /*replaceIterOperandsUsesInLoop =*/false); 235 for (const auto &loop : llvm::enumerate(loops)) { 236 loops[loop.index()] = newLoops[loop.index()]; 237 } 238 return llvm::to_vector(llvm::map_range( 239 loops.front().getResults().take_back(yieldedValues.size()), 240 [](OpResult r) -> Value { return r; })); 241 } 242 243 /// If the tiled operation is destination passing style, update the 244 /// slice of the destination used (which refers to the untiled destination) 245 /// to use the corresponding region argument of the innermost loop. 246 /// 247 /// ```mlir 248 /// %0 = 249 /// scf.for %iv0 = ... iter_args(%arg = %0) { 250 /// %1 = tensor.extract_slice %0 251 /// %2 = tiled_op 252 /// %3 = tensor.insert_slice %2 into %arg 253 /// scf.yield %3 254 /// } 255 /// ``` 256 /// 257 /// is transformed to 258 /// 259 /// ```mlir 260 /// scf.for %iv0 = ... iter_args(%arg = %0) { 261 /// %1 = tensor.extract_slice %arg 262 /// %2 = tiled_op 263 /// %3 = tensor.insert_slice %2 into %arg 264 /// scf.yield %3 265 /// } 266 /// ``` 267 static void 268 updateDestinationOperandsForTiledOp(OpBuilder &builder, 269 ValueRange tiledOpDestinationValues, 270 ValueRange bbArgsList) { 271 for (const auto &destValue : llvm::enumerate(tiledOpDestinationValues)) { 272 auto sliceOp = destValue.value().getDefiningOp<tensor::ExtractSliceOp>(); 273 if (!sliceOp) 274 continue; 275 sliceOp.setOperand(0, bbArgsList[destValue.index()]); 276 } 277 } 278 279 /// Helper method to yield the values of the tiled op, as well as 280 /// update the destination operands of the tiled op, if it is 281 /// a destination passing style op. 282 static SmallVector<Value> 283 yieldTiledValues(RewriterBase &rewriter, ArrayRef<Value> initValues, 284 TilingResult tilingResult, 285 ArrayRef<SmallVector<OpFoldResult>> tileOffsetsList, 286 ArrayRef<SmallVector<OpFoldResult>> tileSizesList, 287 MutableArrayRef<scf::ForOp> loops) { 288 SmallVector<Value> replacements = 289 yieldTiledValues(rewriter, initValues, tilingResult.tiledValues, 290 tileOffsetsList, tileSizesList, loops); 291 for (auto tiledOp : tilingResult.tiledOps) { 292 if (auto dstOp = dyn_cast<DestinationStyleOpInterface>(tiledOp)) { 293 auto innerMostLoop = loops.back(); 294 SmallVector<Value> tiledOpDestinationTensors = 295 llvm::to_vector(dstOp.getDpsInits()); 296 updateDestinationOperandsForTiledOp(rewriter, tiledOpDestinationTensors, 297 innerMostLoop.getRegionIterArgs()); 298 } 299 } 300 return replacements; 301 } 302 303 /// Implementation of tiling transformation of `op` that implements the 304 /// `TilingInterface` using `scf.for` to iterate over the tiles. 305 FailureOr<scf::SCFTilingResult> 306 mlir::scf::tileUsingSCFForOp(RewriterBase &rewriter, TilingInterface op, 307 const scf::SCFTilingOptions &options) { 308 OpBuilder::InsertionGuard guard(rewriter); 309 rewriter.setInsertionPointAfter(op); 310 311 if (!options.tileSizeComputationFunction) { 312 return rewriter.notifyMatchFailure( 313 op, "missing tile size computation function"); 314 } 315 316 // 1. Get the range of the loops that are represented by the operation. 317 SmallVector<Range> iterationDomain = op.getIterationDomain(rewriter); 318 size_t numLoops = iterationDomain.size(); 319 if (numLoops == 0) { 320 return rewriter.notifyMatchFailure( 321 op, "unable to tile op with no iteration domain"); 322 } 323 324 // 2. Materialize the tile sizes. Enforce the convention that "tiling by zero" 325 // skips tiling a particular dimension. This convention is significantly 326 // simpler to handle instead of adjusting affine maps to account for missing 327 // dimensions. 328 SmallVector<OpFoldResult> tileSizeVector = 329 options.tileSizeComputationFunction(rewriter, op); 330 if (tileSizeVector.size() < iterationDomain.size()) { 331 auto zero = rewriter.getIndexAttr(0); 332 tileSizeVector.append(numLoops - tileSizeVector.size(), zero); 333 } 334 335 SmallVector<OpFoldResult> offsets, sizes; 336 SmallVector<scf::ForOp> forLoops; 337 { 338 // If there is an interchange specified, permute the iteration domain and 339 // the tile sizes. 340 SmallVector<int64_t> interchangeVector; 341 if (!options.interchangeVector.empty()) { 342 interchangeVector = fillInterchangeVector(options.interchangeVector, 343 iterationDomain.size()); 344 } 345 if (!interchangeVector.empty()) { 346 if (!isPermutationVector(interchangeVector)) { 347 return rewriter.notifyMatchFailure( 348 op, "invalid intechange vector, not a permutation of the entire " 349 "iteration space"); 350 } 351 352 applyPermutationToVector(iterationDomain, interchangeVector); 353 applyPermutationToVector(tileSizeVector, interchangeVector); 354 } 355 356 // 3. Materialize an empty loop nest that iterates over the tiles. These 357 // loops for now do not return any values even if the original operation has 358 // results. 359 forLoops = generateTileLoopNest(rewriter, op.getLoc(), iterationDomain, 360 tileSizeVector, offsets, sizes); 361 362 if (!interchangeVector.empty()) { 363 auto inversePermutation = invertPermutationVector(interchangeVector); 364 applyPermutationToVector(offsets, inversePermutation); 365 applyPermutationToVector(sizes, inversePermutation); 366 } 367 } 368 369 LLVM_DEBUG({ 370 if (!forLoops.empty()) { 371 llvm::dbgs() << "LoopNest shell :\n"; 372 forLoops.front().dump(); 373 llvm::dbgs() << "\n"; 374 } 375 }); 376 377 // 4. Generate the tiled implementation within the inner most loop. 378 if (!forLoops.empty()) 379 rewriter.setInsertionPoint(forLoops.back().getBody()->getTerminator()); 380 FailureOr<TilingResult> tiledImplementation = 381 op.getTiledImplementation(rewriter, offsets, sizes); 382 383 if (op->getNumResults() == 0) { 384 return scf::SCFTilingResult{ 385 tiledImplementation->tiledOps, getAsOperations(forLoops), {}}; 386 } 387 388 // If loops are empty, the tiled op is used as the replacement for the untiled 389 // op. 390 if (forLoops.empty()) { 391 return scf::SCFTilingResult{tiledImplementation->tiledOps, 392 getAsOperations(forLoops), 393 tiledImplementation->tiledValues}; 394 } 395 396 // 5. Yield all the results of the tiled operation. The surrounding loop 397 // nest is modified to insert a destructive update pattern to yield 398 // from the loop nest values to replace the untiled op with. 399 int64_t numResults = op->getNumResults(); 400 SmallVector<SmallVector<OpFoldResult>> resultOffsetsList(numResults), 401 resultSizesList(numResults); 402 for (const auto &result : llvm::enumerate(op->getResults())) { 403 if (failed(op.getResultTilePosition(rewriter, result.index(), offsets, 404 sizes, 405 resultOffsetsList[result.index()], 406 resultSizesList[result.index()]))) { 407 return rewriter.notifyMatchFailure( 408 op, "failed to get slice of result produced"); 409 } 410 } 411 412 SmallVector<Value> destinationTensors; 413 if (failed(tensor::getOrCreateDestinations(rewriter, op.getLoc(), op, 414 destinationTensors))) 415 return rewriter.notifyMatchFailure(op, "failed to get destinations"); 416 417 SmallVector<Value> replacements = yieldTiledValues( 418 rewriter, destinationTensors, tiledImplementation.value(), 419 resultOffsetsList, resultSizesList, forLoops); 420 LLVM_DEBUG({ 421 if (!forLoops.empty()) { 422 llvm::dbgs() << "After tiled implementation :\n"; 423 forLoops.front().dump(); 424 llvm::dbgs() << "\n"; 425 } 426 }); 427 return scf::SCFTilingResult{tiledImplementation->tiledOps, 428 getAsOperations(forLoops), replacements}; 429 } 430 431 FailureOr<scf::SCFReductionTilingResult> 432 mlir::scf::tileReductionUsingScf(RewriterBase &b, 433 PartialReductionOpInterface op, 434 ArrayRef<OpFoldResult> tileSizes) { 435 Location loc = op.getLoc(); 436 // Ops implementing PartialReductionOpInterface are expected to implement 437 // TilingInterface. 438 auto tilingInterfaceOp = cast<TilingInterface>(op.getOperation()); 439 SmallVector<Range> iterationDomain = tilingInterfaceOp.getIterationDomain(b); 440 auto tileSizesVector = llvm::to_vector(tileSizes); 441 if (tileSizesVector.size() < iterationDomain.size()) { 442 auto zero = b.getIndexAttr(0); 443 tileSizesVector.append(iterationDomain.size() - tileSizesVector.size(), 444 zero); 445 } 446 if (op->getNumResults() != 1) 447 return b.notifyMatchFailure( 448 op, "don't support ops with multiple results for now"); 449 SmallVector<utils::IteratorType> iterators = 450 tilingInterfaceOp.getLoopIteratorTypes(); 451 452 SmallVector<int> reductionDims; 453 for (auto [idx, iteratorType] : 454 llvm::enumerate(tilingInterfaceOp.getLoopIteratorTypes())) { 455 if (iteratorType == utils::IteratorType::reduction) 456 reductionDims.push_back(idx); 457 } 458 459 // 1. create the inital tensor value. 460 FailureOr<Operation *> identityTensor = 461 op.generateInitialTensorForPartialReduction(b, loc, tileSizesVector, 462 reductionDims); 463 if (failed(identityTensor)) 464 return b.notifyMatchFailure(op, 465 "cannot create a tensor of identity value."); 466 // 2. Create the nested loops. 467 SmallVector<OpFoldResult> offsets, sizes; 468 SmallVector<scf::ForOp> loops = generateTileLoopNest( 469 b, loc, iterationDomain, tileSizesVector, offsets, sizes); 470 471 // 3. Generate the tiled implementation within the inner most loop. 472 b.setInsertionPoint(loops.back().getBody()->getTerminator()); 473 Operation *parallelOp = op.tileToPartialReduction( 474 b, loc, (*identityTensor)->getResults(), offsets, sizes, reductionDims); 475 476 SmallVector<OpFoldResult> resultSizesList; 477 for (size_t i = 0; i < offsets.size(); i++) 478 resultSizesList.push_back( 479 tensor::getMixedSize(b, loc, parallelOp->getResult(0), i)); 480 SmallVector<OpFoldResult> outOffsets(offsets.size(), b.getIndexAttr(0)); 481 SmallVector<Value> replacements = yieldTiledValues( 482 b, (*identityTensor)->getResults(), parallelOp->getResults(), outOffsets, 483 resultSizesList, loops); 484 485 auto dstOp = cast<DestinationStyleOpInterface>(parallelOp); 486 auto innerMostLoop = loops.back(); 487 SmallVector<Value> destinationTensors = llvm::to_vector(dstOp.getDpsInits()); 488 assert(destinationTensors.size() == 489 innerMostLoop.getRegionIterArgs().size() && 490 "unexpected number of outputs"); 491 updateDestinationOperandsForTiledOp(b, destinationTensors, 492 innerMostLoop.getRegionIterArgs()); 493 494 // 4. Apply the merge reduction to combine all the partial values. 495 b.setInsertionPointAfter(*loops.begin()); 496 Operation *mergeOp = op.mergeReductions(b, loc, replacements, reductionDims); 497 b.replaceOp(op, mergeOp->getResults()); 498 499 SCFReductionTilingResult results; 500 results.initialOp = *identityTensor; 501 results.loops = std::move(loops); 502 results.parallelTiledOp = parallelOp; 503 results.mergeOp = mergeOp; 504 return results; 505 } 506 507 //===----------------------------------------------------------------------===// 508 // tileConsumerAndFuseProducerGreedilyUsingSCFForOp implementation. 509 //===----------------------------------------------------------------------===// 510 511 /// Return the untiled producer whose slice is used in a tiled consumer. The 512 /// method traverses the tile loop nest (`loops`) if needed, and returns the 513 /// `iter_args` of the outer most that is encountered. Traversing the iter_args 514 /// indicates that this is a destination operand of the consumer. If there was 515 /// no loop traversal needed, the second value of the returned tuple is empty. 516 static std::tuple<OpResult, std::optional<OpOperand *>> 517 getUntiledProducerFromSliceSource(OpOperand *source, 518 ArrayRef<scf::ForOp> loops) { 519 std::optional<OpOperand *> destinationIterArg; 520 auto loopIt = loops.rbegin(); 521 while (auto iterArg = dyn_cast<BlockArgument>(source->get())) { 522 scf::ForOp loop = *loopIt; 523 if (iterArg.getOwner()->getParentOp() != loop) 524 break; 525 source = &loop.getOpOperandForRegionIterArg(iterArg); 526 loopIt++; 527 } 528 if (loopIt == loops.rend()) 529 destinationIterArg = source; 530 return {dyn_cast<OpResult>(source->get()), destinationIterArg}; 531 } 532 533 /// Implementation of fusing producer of a single slice by computing the 534 /// slice of the producer in-place. 535 std::optional<scf::SCFFuseProducerOfSliceResult> 536 mlir::scf::tileAndFuseProducerOfSlice(RewriterBase &rewriter, 537 tensor::ExtractSliceOp candidateSliceOp, 538 MutableArrayRef<scf::ForOp> loops) { 539 // 1. Get the producer of the source (potentially walking through 540 // `iter_args` of nested `scf.for`) 541 auto [fusableProducer, destinationInitArg] = 542 getUntiledProducerFromSliceSource(&candidateSliceOp.getSourceMutable(), 543 loops); 544 if (!fusableProducer) 545 return std::nullopt; 546 547 // 2. Generate the tiled implementation of the producer of the source 548 OpBuilder::InsertionGuard g(rewriter); 549 rewriter.setInsertionPoint(candidateSliceOp); 550 FailureOr<TilingResult> tileAndFuseResult = 551 tensor::replaceExtractSliceWithTiledProducer(rewriter, candidateSliceOp, 552 fusableProducer); 553 if (failed(tileAndFuseResult)) 554 return std::nullopt; 555 rewriter.replaceAllUsesWith(candidateSliceOp, 556 tileAndFuseResult->tiledValues[0]); 557 558 // 3. If the slice is for a destination operand, for example, 559 // 560 // ```mlir 561 // %0 = linalg.init 562 // %1 = linalg.fill .. outs(%0 : ) 563 // %2 = scf.for .. iter_args(%arg0 = %1) { 564 // %3 = scf.for .. iter_args(%arg1 = %arg0) { 565 // %4 = tensor.extract_slice %arg1 [..] 566 // .. = linalg.matmul .. outs(%4 : ) 567 // } 568 // } 569 // ``` 570 // 571 // the IR is currently 572 // 573 // ``` 574 // %0 = linalg.init 575 // %1 = linalg.fill 576 // %2 = scf.for .. iter_args(%arg0 = %1 /* incorrect value */ ) { 577 // %3 = scf.for .. iter_args(%arg1 = %arg0) { 578 // %4 = tensor.extract_slice %0 /*incorrect value */ [..] 579 // %5 = linalg.fill .. outs(%4 : ) 580 // .. = linalg.matmul .. outs(%5 : ) 581 // } 582 // } 583 // ``` 584 // 585 // The untiled `linalg.fill` is still used as the `init_value` since it 586 // was originally a destination operand of the untiled `linalg.matmul`. 587 // When fusing an operand that is a destination operand. 588 // - Update the iter_arg of the outer most loop to use the destination 589 // of the untiled producer. 590 // - Update the destination of the slice of the tiled producer generated 591 // to use the same basic block argument as the slice that was used to 592 // generate inplace the tiled implementation of the producer. 593 // With this the IR will be. 594 // 595 // ``` 596 // %0 = linalg.init 597 // %1 = scf.for .. iter_args(%arg0 = %0 /* corrected value */ ) { 598 // %2 = scf.for .. iter_args(%arg1 = %arg0) { 599 // %3 = tensor.extract_slice %arg1 /* corrected value */ [..] 600 // %4 = linalg.fill .. outs(%3 : ) 601 // .. = linalg.matmul .. outs(%4 : ) 602 // } 603 // } 604 // ``` 605 // TODO: This can be modeled better if the `DestinationStyleOpInterface`. 606 // Update to use that when it does become available. 607 scf::ForOp outerMostLoop = loops.front(); 608 if (destinationInitArg && 609 (*destinationInitArg)->getOwner() == outerMostLoop) { 610 unsigned iterArgNumber = 611 outerMostLoop.getResultForOpOperand(**destinationInitArg) 612 .getResultNumber(); 613 int64_t resultNumber = fusableProducer.getResultNumber(); 614 if (auto dstOp = 615 dyn_cast<DestinationStyleOpInterface>(fusableProducer.getOwner())) { 616 (*destinationInitArg) 617 ->set(dstOp.getTiedOpOperand(fusableProducer)->get()); 618 } 619 for (auto tileAndFusedOp : tileAndFuseResult->tiledOps) { 620 auto dstOp = dyn_cast<DestinationStyleOpInterface>(tileAndFusedOp); 621 if (!dstOp) 622 continue; 623 scf::ForOp innerMostLoop = loops.back(); 624 updateDestinationOperandsForTiledOp( 625 rewriter, dstOp.getDpsInitOperand(resultNumber)->get(), 626 innerMostLoop.getRegionIterArgs()[iterArgNumber]); 627 } 628 } 629 return scf::SCFFuseProducerOfSliceResult{fusableProducer, 630 tileAndFuseResult->tiledValues[0], 631 tileAndFuseResult->tiledOps}; 632 } 633 634 /// Reconstruct the fused producer from within the tiled-and-fused code. 635 void mlir::scf::yieldReplacementForFusedProducer( 636 RewriterBase &rewriter, tensor::ExtractSliceOp sliceOp, 637 scf::SCFFuseProducerOfSliceResult fusedProducerInfo, 638 MutableArrayRef<scf::ForOp> loops) { 639 auto [fusableProducer, fusedProducerValue, tileAndFusedOps] = 640 fusedProducerInfo; 641 SmallVector<Value> initValues; 642 FailureOr<Value> initValue = tensor::getOrCreateDestination( 643 rewriter, fusableProducer.getOwner()->getLoc(), fusableProducer); 644 if (succeeded(initValue)) { 645 SmallVector<OpFoldResult> resultOffsets = sliceOp.getMixedOffsets(); 646 SmallVector<OpFoldResult> resultSizes = sliceOp.getMixedSizes(); 647 SmallVector<Value> yieldedVals = 648 yieldTiledValues(rewriter, initValue.value(), fusedProducerValue, 649 resultOffsets, resultSizes, loops); 650 } 651 for (auto tileAndFusedOp : tileAndFusedOps) { 652 auto dstStyleProducer = 653 dyn_cast<DestinationStyleOpInterface>(tileAndFusedOp); 654 if (!dstStyleProducer) 655 continue; 656 Value dstValue = 657 dstStyleProducer.getDpsInitOperand(fusableProducer.getResultNumber()) 658 ->get(); 659 updateDestinationOperandsForTiledOp( 660 rewriter, dstValue, loops.back().getRegionIterArgs().back()); 661 } 662 } 663 664 /// Implementation of tile consumer and fuse producer greedily. 665 FailureOr<scf::SCFTileAndFuseResult> 666 mlir::scf::tileConsumerAndFuseProducerGreedilyUsingSCFForOp( 667 RewriterBase &rewriter, TilingInterface consumer, 668 const scf::SCFTileAndFuseOptions &options) { 669 // This transformation is only valid for ops that return values (i.e. not 670 // valid to use with operations that have memref operands). 671 if (!consumer->getNumResults()) { 672 return rewriter.notifyMatchFailure( 673 consumer, "invalid pattern for op with no results"); 674 } 675 676 // 1. First tile the consumer. 677 SmallVector<scf::ForOp> forLoops; 678 SetVector<Operation *> fusedProducers, tiledAndFusedOps; 679 DenseMap<Value, Value> replacements; 680 llvm::SmallDenseMap<Value, int64_t> yieldedValueToResultNumber; 681 { 682 FailureOr<scf::SCFTilingResult> tilingResult = 683 tileUsingSCFForOp(rewriter, consumer, options.tilingOptions); 684 if (failed(tilingResult)) 685 return rewriter.notifyMatchFailure(consumer, "failed to tile consumer"); 686 for (auto *tiledOp : tilingResult->tiledOps) 687 tiledAndFusedOps.insert(tiledOp); 688 forLoops = castToTypedOperations<scf::ForOp>(tilingResult->loops); 689 for (auto [index, origValue, replacement] : 690 llvm::enumerate(consumer->getResults(), tilingResult->replacements)) { 691 replacements[origValue] = replacement; 692 yieldedValueToResultNumber[tilingResult->tiledOps.back()->getResult( 693 index)] = index; 694 } 695 } 696 697 // If there are no loops generated, fusion is immaterial. 698 if (forLoops.empty()) { 699 return scf::SCFTileAndFuseResult{fusedProducers, tiledAndFusedOps, 700 getAsOperations(forLoops), replacements}; 701 } 702 703 // 2. Typically, the operands of the tiled operation are slices of the 704 // operands of the untiled operation. These are expressed in IR using 705 // `tensor.extract_slice` operations with source being the operands of the 706 // untiled operation. Create a worklist of these `tensor.extract_slice` 707 // operations. If the producers of the source of the `tensor.extract_slice` 708 // can be tiled such that the tiled value is generated in-place, that 709 // effectively tiles + fuses the operations. 710 auto addCandidateSlices = [](Operation *fusedOp, 711 std::deque<tensor::ExtractSliceOp> &candidates) { 712 for (Value operand : fusedOp->getOperands()) 713 if (auto sliceOp = operand.getDefiningOp<tensor::ExtractSliceOp>()) 714 candidates.push_back(sliceOp); 715 }; 716 717 std::deque<tensor::ExtractSliceOp> candidates; 718 addCandidateSlices(tiledAndFusedOps.back(), candidates); 719 OpBuilder::InsertionGuard g(rewriter); 720 while (!candidates.empty()) { 721 // Traverse the slices in BFS fashion. 722 tensor::ExtractSliceOp candidateSliceOp = candidates.front(); 723 candidates.pop_front(); 724 725 // The operands of the fused producer might themselved be slices of 726 // values produced by operations that implement the `TilingInterface`. 727 // Add these operations to the worklist. 728 std::optional<scf::SCFFuseProducerOfSliceResult> fusedResult = 729 tileAndFuseProducerOfSlice(rewriter, candidateSliceOp, forLoops); 730 if (!fusedResult) 731 continue; 732 733 if (Operation *tiledAndFusedOp = 734 fusedResult->tiledAndFusedProducer.getDefiningOp()) { 735 fusedProducers.insert(fusedResult->origProducer.getDefiningOp()); 736 tiledAndFusedOps.insert(tiledAndFusedOp); 737 addCandidateSlices(tiledAndFusedOp, candidates); 738 } 739 } 740 return scf::SCFTileAndFuseResult{fusedProducers, tiledAndFusedOps, 741 getAsOperations(forLoops), replacements}; 742 } 743 744 //===----------------------------------------------------------------------===// 745 // tileUsingSCFForAllOp implementation. 746 //===----------------------------------------------------------------------===// 747 748 FailureOr<scf::SCFTilingResult> 749 mlir::scf::tileUsingSCFForallOp(RewriterBase &rewriter, TilingInterface op, 750 const scf::SCFTilingOptions &options) { 751 Location loc = op->getLoc(); 752 OpBuilder::InsertionGuard g(rewriter); 753 754 // 1. Get the range of loops that are represented by the operation. 755 SmallVector<Range> loopRanges = op.getIterationDomain(rewriter); 756 if (loopRanges.empty()) 757 return op->emitOpError("expected non-empty loop ranges"); 758 auto hasStrideOne = [](Range r) { return !isConstantIntValue(r.stride, 1); }; 759 if (llvm::any_of(loopRanges, hasStrideOne)) 760 return op->emitOpError("only stride-1 supported atm"); 761 762 // 2. Get the tile sizes. If tile size is 0, it is not tiled and distributed. 763 // To make it easier, pad the tile sizes to loopRanges.size with value 0. 764 SmallVector<OpFoldResult> tileSizeVector = 765 options.tileSizeComputationFunction(rewriter, op); 766 tileSizeVector.resize(loopRanges.size(), rewriter.getIndexAttr(0)); 767 768 // 3. Build the offsets, sizes and steps for the tile and distributed loops. 769 SmallVector<OpFoldResult> lbs, ubs, steps; 770 for (auto [tileSize, loopRange] : llvm::zip(tileSizeVector, loopRanges)) { 771 if (isConstantIntValue(tileSize, 0)) 772 continue; 773 lbs.push_back(loopRange.offset); 774 ubs.push_back(loopRange.size); 775 steps.push_back(tileSize); 776 } 777 778 // 4. Gather destination tensors. 779 SmallVector<Value> dest; 780 if (failed(tensor::getOrCreateDestinations(rewriter, loc, op, dest))) 781 return op->emitOpError("failed to get destination tensors"); 782 783 // 5. Build the device mapping attribute. 784 std::optional<ArrayAttr> mappingAttr; 785 if (!options.mappingVector.empty()) { 786 mappingAttr = rewriter.getArrayAttr(ArrayRef(options.mappingVector)); 787 } 788 789 // 6. Create the ForallOp. We don't use the lambda body-builder 790 // version because we require the use of RewriterBase in the body, so we 791 // manually move the insertion point to the body below. 792 auto forallOp = 793 rewriter.create<scf::ForallOp>(loc, lbs, ubs, steps, dest, mappingAttr); 794 795 // 7. Get the tile offset and sizes. 796 rewriter.setInsertionPoint(forallOp.getTerminator()); 797 SmallVector<OpFoldResult> tiledOffsets, tiledSizes; 798 ValueRange ivs = forallOp.getInductionVars(); 799 { 800 int materializedLoopNum = 0; 801 for (auto [tileSize, loopRange] : llvm::zip(tileSizeVector, loopRanges)) { 802 if (isConstantIntValue(tileSize, 0)) { 803 tiledOffsets.push_back(loopRange.offset); 804 tiledSizes.push_back(loopRange.size); 805 continue; 806 } 807 Value iv = ivs[materializedLoopNum++]; 808 tiledOffsets.push_back(iv); 809 tiledSizes.push_back( 810 getBoundedTileSize(rewriter, loc, loopRange, iv, tileSize)); 811 } 812 } 813 814 // 8. Tile the operation. Clone the operation to allow fix up of destination 815 // operands. 816 ArrayRef<BlockArgument> destBbArgs = forallOp.getOutputBlockArguments(); 817 Operation *clonedOp = 818 cloneOpAndUpdateDestinationArgs(rewriter, op, destBbArgs); 819 FailureOr<TilingResult> tilingResult = 820 cast<TilingInterface>(clonedOp).getTiledImplementation( 821 rewriter, tiledOffsets, tiledSizes); 822 if (failed(tilingResult)) 823 return clonedOp->emitError("failed to tile op: "); 824 rewriter.eraseOp(clonedOp); 825 826 // 9. Parallel insert back into the result tensor. 827 for (auto [index, tiledValue, destBBArg] : 828 llvm::enumerate(tilingResult->tiledValues, destBbArgs)) { 829 // 9.a. Partial subset information is inserted just before the terminator. 830 rewriter.setInsertionPoint(forallOp.getTerminator()); 831 832 SmallVector<OpFoldResult> resultOffsets, resultSizes; 833 if (failed(op.getResultTilePosition(rewriter, index, tiledOffsets, 834 tiledSizes, resultOffsets, 835 resultSizes))) { 836 return op->emitOpError("output offsets couldn't be calculated"); 837 } 838 839 SmallVector<OpFoldResult> strides(resultSizes.size(), 840 rewriter.getIndexAttr(1)); 841 // 9.b. Parallel insertions are inserted at the end of the combining 842 // terminator. 843 rewriter.setInsertionPointToEnd(forallOp.getTerminator().getBody()); 844 rewriter.create<tensor::ParallelInsertSliceOp>( 845 loc, tiledValue, destBBArg, resultOffsets, resultSizes, strides); 846 } 847 848 // 10. Return the tiling result. 849 return scf::SCFTilingResult{ 850 tilingResult->tiledOps, 851 {forallOp.getOperation()}, 852 llvm::map_to_vector(forallOp.getResults(), 853 [](auto val) -> Value { return val; })}; 854 } 855 856 //===----------------------------------------------------------------------===// 857 // lowerToLoopsUsingSCFForOp implementation. 858 //===----------------------------------------------------------------------===// 859 860 FailureOr<SmallVector<scf::ForOp>> 861 mlir::scf::lowerToLoopsUsingSCFForOp(RewriterBase &rewriter, 862 TilingInterface op) { 863 // TODO: Handle cases where the op has results if needed. 864 if (op->getNumResults() > 0) { 865 return rewriter.notifyMatchFailure( 866 op, "unable to lower to loops operations with return values"); 867 } 868 869 SmallVector<Range> domain = op.getIterationDomain(rewriter); 870 SmallVector<Value> ivs; 871 SmallVector<scf::ForOp> loops; 872 Location loc = op.getLoc(); 873 for (auto loopRange : domain) { 874 Value offsetVal = 875 getValueOrCreateConstantIndexOp(rewriter, loc, loopRange.offset); 876 Value sizeVal = 877 getValueOrCreateConstantIndexOp(rewriter, loc, loopRange.size); 878 Value strideVal = 879 getValueOrCreateConstantIndexOp(rewriter, loc, loopRange.stride); 880 auto loop = rewriter.create<scf::ForOp>(op.getLoc(), offsetVal, sizeVal, 881 strideVal, ValueRange{}); 882 loops.push_back(loop); 883 ivs.push_back(loop.getInductionVar()); 884 rewriter.setInsertionPoint(loop.getBody()->getTerminator()); 885 } 886 if (failed(op.generateScalarImplementation(rewriter, op.getLoc(), ivs))) { 887 return failure(); 888 } 889 return loops; 890 } 891