1 //===----------------------------------------------------------------------===// 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 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 10 #include "mlir/Dialect/StandardOps/Utils/Utils.h" 11 #include "mlir/Dialect/Tensor/IR/Tensor.h" 12 #include "mlir/Dialect/Utils/ReshapeOpsUtils.h" 13 #include "mlir/Dialect/Utils/StaticValueUtils.h" 14 #include "mlir/IR/BlockAndValueMapping.h" 15 #include "mlir/IR/Builders.h" 16 #include "mlir/IR/BuiltinAttributeInterfaces.h" 17 #include "mlir/IR/Matchers.h" 18 #include "mlir/IR/PatternMatch.h" 19 #include "mlir/IR/TypeUtilities.h" 20 #include "llvm/ADT/STLExtras.h" 21 22 using namespace mlir; 23 using namespace mlir::tensor; 24 25 /// Materialize a single constant operation from a given attribute value with 26 /// the desired resultant type. 27 Operation *TensorDialect::materializeConstant(OpBuilder &builder, 28 Attribute value, Type type, 29 Location loc) { 30 if (arith::ConstantOp::isBuildableWith(value, type)) 31 return builder.create<arith::ConstantOp>(loc, value, type); 32 if (ConstantOp::isBuildableWith(value, type)) 33 return builder.create<ConstantOp>(loc, value, type); 34 return nullptr; 35 } 36 37 //===----------------------------------------------------------------------===// 38 // CastOp 39 //===----------------------------------------------------------------------===// 40 41 /// Returns true if `target` is a ranked tensor type that preserves static 42 /// information available in the `source` ranked tensor type. 43 bool mlir::tensor::preservesStaticInformation(Type source, Type target) { 44 auto sourceType = source.dyn_cast<RankedTensorType>(); 45 auto targetType = target.dyn_cast<RankedTensorType>(); 46 47 // Requires RankedTensorType. 48 if (!sourceType || !targetType) 49 return false; 50 51 // Requires same elemental type. 52 if (sourceType.getElementType() != targetType.getElementType()) 53 return false; 54 55 // Requires same rank. 56 if (sourceType.getRank() != targetType.getRank()) 57 return false; 58 59 // If cast is towards more static sizes along any dimension, don't fold. 60 for (auto t : llvm::zip(sourceType.getShape(), targetType.getShape())) { 61 if (!ShapedType::isDynamic(std::get<0>(t)) && 62 ShapedType::isDynamic(std::get<1>(t))) 63 return false; 64 } 65 66 return true; 67 } 68 69 /// Determines whether tensor::CastOp casts to a more dynamic version of the 70 /// source tensor. This is useful to fold a tensor.cast into a consuming op and 71 /// implement canonicalization patterns for ops in different dialects that may 72 /// consume the results of tensor.cast operations. Such foldable tensor.cast 73 /// operations are typically inserted as `slice` ops and are canonicalized, 74 /// to preserve the type compatibility of their uses. 75 /// 76 /// Returns true when all conditions are met: 77 /// 1. source and result are ranked tensors with same element type and rank. 78 /// 2. the tensor type has more static information than the result 79 /// 80 /// Example: 81 /// ```mlir 82 /// %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32> 83 /// %2 = consumer %1 ... : tensor<?x?xf32> ... 84 /// ``` 85 /// 86 /// folds into: 87 /// 88 /// ```mlir 89 /// %2 = consumer %0 ... : tensor<8x16xf32> ... 90 /// ``` 91 bool mlir::tensor::canFoldIntoConsumerOp(CastOp castOp) { 92 if (!castOp) 93 return false; 94 95 // Can fold if the source of cast has at least as much static information as 96 // its results. 97 return preservesStaticInformation(castOp.getType(), 98 castOp.source().getType()); 99 } 100 101 /// Performs folding of any operand of `op` if it comes from a tensor::CastOp 102 /// that can be folded. 103 LogicalResult mlir::tensor::foldTensorCast(Operation *op) { 104 bool folded = false; 105 for (OpOperand &operand : op->getOpOperands()) { 106 auto castOp = operand.get().getDefiningOp<tensor::CastOp>(); 107 if (castOp && tensor::canFoldIntoConsumerOp(castOp)) { 108 operand.set(castOp.getOperand()); 109 folded = true; 110 } 111 } 112 return success(folded); 113 } 114 115 bool CastOp::areCastCompatible(TypeRange inputs, TypeRange outputs) { 116 if (inputs.size() != 1 || outputs.size() != 1) 117 return false; 118 Type a = inputs.front(), b = outputs.front(); 119 auto aT = a.dyn_cast<TensorType>(); 120 auto bT = b.dyn_cast<TensorType>(); 121 if (!aT || !bT) 122 return false; 123 124 if (aT.getElementType() != bT.getElementType()) 125 return false; 126 127 return succeeded(verifyCompatibleShape(aT, bT)); 128 } 129 130 /// Compute a TensorType that has the joined shape knowledge of the two 131 /// given TensorTypes. The element types need to match. 132 static TensorType joinShapes(TensorType one, TensorType two) { 133 assert(one.getElementType() == two.getElementType()); 134 135 if (!one.hasRank()) 136 return two; 137 if (!two.hasRank()) 138 return one; 139 140 int64_t rank = one.getRank(); 141 if (rank != two.getRank()) 142 return {}; 143 144 SmallVector<int64_t, 4> join; 145 join.reserve(rank); 146 for (int64_t i = 0; i < rank; ++i) { 147 if (one.isDynamicDim(i)) { 148 join.push_back(two.getDimSize(i)); 149 continue; 150 } 151 if (two.isDynamicDim(i)) { 152 join.push_back(one.getDimSize(i)); 153 continue; 154 } 155 if (one.getDimSize(i) != two.getDimSize(i)) 156 return {}; 157 join.push_back(one.getDimSize(i)); 158 } 159 return RankedTensorType::get(join, one.getElementType()); 160 } 161 162 namespace { 163 164 /// Replaces chains of two tensor.cast operations by a single tensor.cast 165 /// operation if doing so does not remove runtime constraints. 166 struct ChainedTensorCast : public OpRewritePattern<CastOp> { 167 using OpRewritePattern<CastOp>::OpRewritePattern; 168 169 LogicalResult matchAndRewrite(CastOp tensorCast, 170 PatternRewriter &rewriter) const final { 171 auto tensorCastOperand = tensorCast.getOperand().getDefiningOp<CastOp>(); 172 173 if (!tensorCastOperand) 174 return failure(); 175 176 auto sourceType = 177 tensorCastOperand.getOperand().getType().cast<TensorType>(); 178 auto intermediateType = tensorCastOperand.getType().cast<TensorType>(); 179 auto resultType = tensorCast.getType().cast<TensorType>(); 180 181 // We can remove the intermediate cast if joining all three produces the 182 // same result as just joining the source and result shapes. 183 auto firstJoin = 184 joinShapes(joinShapes(sourceType, intermediateType), resultType); 185 186 // The join might not exist if the cast sequence would fail at runtime. 187 if (!firstJoin) 188 return failure(); 189 190 // The newJoin always exists if the above join exists, it might just contain 191 // less information. If so, we cannot drop the intermediate cast, as doing 192 // so would remove runtime checks. 193 auto newJoin = joinShapes(sourceType, resultType); 194 if (firstJoin != newJoin) 195 return failure(); 196 197 rewriter.replaceOpWithNewOp<CastOp>(tensorCast, resultType, 198 tensorCastOperand.getOperand()); 199 return success(); 200 } 201 }; 202 203 } // namespace 204 205 void CastOp::getCanonicalizationPatterns(RewritePatternSet &results, 206 MLIRContext *context) { 207 results.add<ChainedTensorCast>(context); 208 } 209 210 //===----------------------------------------------------------------------===// 211 // DimOp 212 //===----------------------------------------------------------------------===// 213 214 void DimOp::build(OpBuilder &builder, OperationState &result, Value source, 215 int64_t index) { 216 auto loc = result.location; 217 Value indexValue = builder.create<arith::ConstantIndexOp>(loc, index); 218 build(builder, result, source, indexValue); 219 } 220 221 Optional<int64_t> DimOp::getConstantIndex() { 222 if (auto constantOp = index().getDefiningOp<arith::ConstantOp>()) 223 return constantOp.getValue().cast<IntegerAttr>().getInt(); 224 return {}; 225 } 226 227 static LogicalResult verify(DimOp op) { 228 // Assume unknown index to be in range. 229 Optional<int64_t> index = op.getConstantIndex(); 230 if (!index.hasValue()) 231 return success(); 232 233 // Check that constant index is not knowingly out of range. 234 auto type = op.source().getType(); 235 if (auto tensorType = type.dyn_cast<RankedTensorType>()) { 236 if (index.getValue() >= tensorType.getRank()) 237 return op.emitOpError("index is out of range"); 238 } else if (type.isa<UnrankedTensorType>()) { 239 // Assume index to be in range. 240 } else { 241 llvm_unreachable("expected operand with tensor type"); 242 } 243 return success(); 244 } 245 246 OpFoldResult DimOp::fold(ArrayRef<Attribute> operands) { 247 // All forms of folding require a known index. 248 auto index = operands[1].dyn_cast_or_null<IntegerAttr>(); 249 if (!index) 250 return {}; 251 252 // Folding for unranked types (UnrankedTensorType) is not supported. 253 auto tensorType = source().getType().dyn_cast<RankedTensorType>(); 254 if (!tensorType) 255 return {}; 256 257 // Fold if the shape extent along the given index is known. 258 if (!tensorType.isDynamicDim(index.getInt())) { 259 Builder builder(getContext()); 260 return builder.getIndexAttr(tensorType.getShape()[index.getInt()]); 261 } 262 263 Operation *definingOp = source().getDefiningOp(); 264 265 // Fold dim to the operand of tensor.generate. 266 if (auto fromElements = dyn_cast_or_null<tensor::GenerateOp>(definingOp)) { 267 auto resultType = 268 fromElements.getResult().getType().cast<RankedTensorType>(); 269 // The case where the type encodes the size of the dimension is handled 270 // above. 271 assert(ShapedType::isDynamic(resultType.getShape()[index.getInt()])); 272 273 // Find the operand of the fromElements that corresponds to this index. 274 auto dynExtents = fromElements.dynamicExtents().begin(); 275 for (auto dim : resultType.getShape().take_front(index.getInt())) 276 if (ShapedType::isDynamic(dim)) 277 dynExtents++; 278 279 return Value{*dynExtents}; 280 } 281 282 // The size at the given index is now known to be a dynamic size. 283 unsigned unsignedIndex = index.getValue().getZExtValue(); 284 285 if (auto sliceOp = dyn_cast_or_null<tensor::ExtractSliceOp>(definingOp)) { 286 // Fold only for non-rank reduced ops. For the rank-reduced version, rely on 287 // `resolve-shaped-type-result-dims` pass. 288 if (sliceOp.getType().getRank() == sliceOp.getSourceType().getRank() && 289 sliceOp.isDynamicSize(unsignedIndex)) { 290 return {sliceOp.getDynamicSize(unsignedIndex)}; 291 } 292 } 293 294 // dim(cast) -> dim 295 if (succeeded(foldTensorCast(*this))) 296 return getResult(); 297 298 return {}; 299 } 300 301 namespace { 302 /// Fold dim of a cast into the dim of the source of the tensor cast. 303 struct DimOfCastOp : public OpRewritePattern<DimOp> { 304 using OpRewritePattern<DimOp>::OpRewritePattern; 305 306 LogicalResult matchAndRewrite(DimOp dimOp, 307 PatternRewriter &rewriter) const override { 308 auto castOp = dimOp.source().getDefiningOp<CastOp>(); 309 if (!castOp) 310 return failure(); 311 Value newSource = castOp.getOperand(); 312 rewriter.replaceOpWithNewOp<DimOp>(dimOp, newSource, dimOp.index()); 313 return success(); 314 } 315 }; 316 } // namespace 317 318 void DimOp::getCanonicalizationPatterns(RewritePatternSet &results, 319 MLIRContext *context) { 320 results.add<DimOfCastOp>(context); 321 } 322 323 //===----------------------------------------------------------------------===// 324 // ExtractOp 325 //===----------------------------------------------------------------------===// 326 327 static LogicalResult verify(ExtractOp op) { 328 // Verify the # indices match if we have a ranked type. 329 if (auto tensorType = op.tensor().getType().dyn_cast<RankedTensorType>()) 330 if (tensorType.getRank() != static_cast<int64_t>(op.indices().size())) 331 return op.emitOpError("incorrect number of indices for extract_element"); 332 333 return success(); 334 } 335 336 OpFoldResult ExtractOp::fold(ArrayRef<Attribute> operands) { 337 // The tensor operand must be a known constant. 338 Attribute tensor = operands.front(); 339 if (!tensor) 340 return {}; 341 // If this is a splat elements attribute, simply return the value. All of the 342 // elements of a splat attribute are the same. 343 if (auto splatTensor = tensor.dyn_cast<SplatElementsAttr>()) 344 return splatTensor.getSplatValue<Attribute>(); 345 346 // Otherwise, collect the constant indices into the tensor. 347 SmallVector<uint64_t, 8> indices; 348 for (Attribute indice : llvm::drop_begin(operands, 1)) { 349 if (!indice || !indice.isa<IntegerAttr>()) 350 return {}; 351 indices.push_back(indice.cast<IntegerAttr>().getInt()); 352 } 353 354 // If this is an elements attribute, query the value at the given indices. 355 auto elementsAttr = tensor.dyn_cast<ElementsAttr>(); 356 if (elementsAttr && elementsAttr.isValidIndex(indices)) 357 return elementsAttr.getValues<Attribute>()[indices]; 358 return {}; 359 } 360 361 //===----------------------------------------------------------------------===// 362 // FromElementsOp 363 //===----------------------------------------------------------------------===// 364 365 void FromElementsOp::build(OpBuilder &builder, OperationState &result, 366 Type resultType, ValueRange elements) { 367 result.addOperands(elements); 368 result.addTypes(resultType); 369 } 370 371 void FromElementsOp::build(OpBuilder &builder, OperationState &result, 372 ValueRange elements) { 373 assert(!elements.empty() && "expected at least one element"); 374 Type resultType = RankedTensorType::get( 375 {static_cast<int64_t>(elements.size())}, elements.front().getType()); 376 build(builder, result, resultType, elements); 377 } 378 379 OpFoldResult FromElementsOp::fold(ArrayRef<Attribute> operands) { 380 if (!llvm::is_contained(operands, nullptr)) 381 return DenseElementsAttr::get(getType(), operands); 382 return {}; 383 } 384 385 namespace { 386 387 // Canonicalizes the pattern of the form 388 // 389 // %tensor = tensor.from_elements(%element) : (i32) -> tensor<1xi32> 390 // %extracted_element = tensor.extract %tensor[%c0] : tensor<1xi32> 391 // 392 // to just %element. 393 struct ExtractElementFromTensorFromElements 394 : public OpRewritePattern<tensor::ExtractOp> { 395 using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern; 396 397 LogicalResult matchAndRewrite(tensor::ExtractOp extract, 398 PatternRewriter &rewriter) const final { 399 auto tensorFromElements = extract.tensor().getDefiningOp<FromElementsOp>(); 400 if (!tensorFromElements) 401 return failure(); 402 auto tensorType = tensorFromElements.getType().cast<RankedTensorType>(); 403 auto rank = tensorType.getRank(); 404 if (rank == 0) { 405 rewriter.replaceOp(extract, tensorFromElements.getOperand(0)); 406 return success(); 407 } 408 SmallVector<APInt, 3> indices(rank); 409 int64_t flatIndex = 0; 410 int64_t stride = 1; 411 for (int i = rank - 1; i >= 0; --i) { 412 APInt index; 413 if (!matchPattern(extract.indices()[i], m_ConstantInt(&index))) 414 return failure(); 415 if (i < rank - 1) 416 stride *= tensorType.getDimSize(i); 417 flatIndex += index.getSExtValue() * stride; 418 } 419 // Prevent out of bounds accesses. This can happen in invalid code that will 420 // never execute. 421 if (tensorFromElements->getNumOperands() <= flatIndex || flatIndex < 0) 422 return failure(); 423 rewriter.replaceOp(extract, tensorFromElements.getOperand(flatIndex)); 424 return success(); 425 } 426 }; 427 428 } // namespace 429 430 void FromElementsOp::getCanonicalizationPatterns(RewritePatternSet &results, 431 MLIRContext *context) { 432 results.add<ExtractElementFromTensorFromElements>(context); 433 } 434 435 //===----------------------------------------------------------------------===// 436 // InsertOp 437 //===----------------------------------------------------------------------===// 438 439 static LogicalResult verify(InsertOp op) { 440 // Verify the # indices match if we have a ranked type. 441 if (auto destType = op.dest().getType().dyn_cast<RankedTensorType>()) 442 if (destType.getRank() != static_cast<int64_t>(op.indices().size())) 443 return op.emitOpError("incorrect number of indices"); 444 return success(); 445 } 446 447 OpFoldResult InsertOp::fold(ArrayRef<Attribute> operands) { 448 Attribute scalar = operands[0]; 449 Attribute dest = operands[1]; 450 if (scalar && dest) 451 if (auto splatDest = dest.dyn_cast<SplatElementsAttr>()) 452 if (scalar == splatDest.getSplatValue<Attribute>()) 453 return dest; 454 return {}; 455 } 456 457 //===----------------------------------------------------------------------===// 458 // GenerateOp 459 //===----------------------------------------------------------------------===// 460 461 static LogicalResult verify(GenerateOp op) { 462 // Ensure that the tensor type has as many dynamic dimensions as are specified 463 // by the operands. 464 RankedTensorType resultTy = op.getType().cast<RankedTensorType>(); 465 if (op.getNumOperands() != resultTy.getNumDynamicDims()) 466 return op.emitError("must have as many index operands as dynamic extents " 467 "in the result type"); 468 469 // Ensure that region arguments span the index space. 470 if (!llvm::all_of(op.body().getArgumentTypes(), 471 [](Type ty) { return ty.isIndex(); })) 472 return op.emitError("all body arguments must be index"); 473 if (op.body().getNumArguments() != resultTy.getRank()) 474 return op.emitError("must have one body argument per input dimension"); 475 476 // Ensure that the region yields an element of the right type. 477 auto yieldOp = 478 llvm::cast<YieldOp>(op.body().getBlocks().front().getTerminator()); 479 480 if (yieldOp.value().getType() != resultTy.getElementType()) 481 return op.emitOpError( 482 "body must be terminated with a `yield` operation of the tensor " 483 "element type"); 484 485 return success(); 486 } 487 488 void GenerateOp::build( 489 OpBuilder &b, OperationState &result, Type resultTy, 490 ValueRange dynamicExtents, 491 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilder) { 492 build(b, result, resultTy, dynamicExtents); 493 494 // Build and populate body. 495 OpBuilder::InsertionGuard guard(b); 496 Region *bodyRegion = result.regions.front().get(); 497 auto rank = resultTy.cast<RankedTensorType>().getRank(); 498 SmallVector<Type, 2> argumentTypes(rank, b.getIndexType()); 499 SmallVector<Location, 2> argumentLocs(rank, result.location); 500 Block *bodyBlock = 501 b.createBlock(bodyRegion, bodyRegion->end(), argumentTypes, argumentLocs); 502 bodyBuilder(b, result.location, bodyBlock->getArguments()); 503 } 504 505 namespace { 506 507 /// Canonicalizes tensor.generate operations with a constant 508 /// operand into the equivalent operation with the operand expressed in the 509 /// result type, instead. We also insert a type cast to make sure that the 510 /// resulting IR is still well-typed. 511 struct StaticTensorGenerate : public OpRewritePattern<GenerateOp> { 512 using OpRewritePattern<GenerateOp>::OpRewritePattern; 513 514 LogicalResult matchAndRewrite(GenerateOp tensorFromElements, 515 PatternRewriter &rewriter) const final { 516 auto resultType = 517 tensorFromElements.getResult().getType().cast<RankedTensorType>(); 518 519 if (resultType.hasStaticShape()) 520 return failure(); 521 522 SmallVector<Value, 4> newOperands; 523 SmallVector<int64_t, 4> newShape; 524 auto operandsIt = tensorFromElements.dynamicExtents().begin(); 525 526 for (int64_t dim : resultType.getShape()) { 527 if (!ShapedType::isDynamic(dim)) { 528 newShape.push_back(dim); 529 continue; 530 } 531 APInt index; 532 if (!matchPattern(*operandsIt, m_ConstantInt(&index))) { 533 newShape.push_back(ShapedType::kDynamicSize); 534 newOperands.push_back(*operandsIt++); 535 continue; 536 } 537 newShape.push_back(index.getSExtValue()); 538 operandsIt++; 539 } 540 541 if (newOperands.size() == tensorFromElements.dynamicExtents().size()) 542 return failure(); 543 544 auto loc = tensorFromElements.getLoc(); 545 auto newOp = rewriter.create<GenerateOp>( 546 loc, RankedTensorType::get(newShape, resultType.getElementType()), 547 newOperands); 548 rewriter.inlineRegionBefore(tensorFromElements.body(), newOp.body(), 549 newOp.body().begin()); 550 rewriter.replaceOpWithNewOp<tensor::CastOp>(tensorFromElements, resultType, 551 newOp); 552 return success(); 553 } 554 }; 555 556 /// Canonicalizes the pattern of the form 557 /// 558 /// %tensor = tensor.generate %x { 559 /// ^bb0(%arg0: index): 560 /// <computation> 561 /// yield %1 : index 562 /// } : tensor<?xindex> 563 /// %extracted_element = tensor.extract %tensor[%c0] : tensor<?xi32> 564 /// 565 /// to just <computation> with %arg0 replaced by %c0. We only do this if the 566 /// tensor.generate operation has no side-effects. 567 struct ExtractFromTensorGenerate : public OpRewritePattern<tensor::ExtractOp> { 568 using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern; 569 570 LogicalResult matchAndRewrite(tensor::ExtractOp extract, 571 PatternRewriter &rewriter) const final { 572 auto tensorFromElements = extract.tensor().getDefiningOp<GenerateOp>(); 573 if (!tensorFromElements || !wouldOpBeTriviallyDead(tensorFromElements)) 574 return failure(); 575 576 BlockAndValueMapping mapping; 577 Block *body = tensorFromElements.getBody(); 578 mapping.map(body->getArguments(), extract.indices()); 579 for (auto &op : body->without_terminator()) 580 rewriter.clone(op, mapping); 581 582 auto yield = cast<YieldOp>(body->getTerminator()); 583 584 rewriter.replaceOp(extract, mapping.lookupOrDefault(yield.value())); 585 return success(); 586 } 587 }; 588 589 /// Canonicalizes the pattern of the form 590 /// 591 /// %val = tensor.cast %source : : tensor<?xi32> to tensor<2xi32> 592 /// %extracted_element = tensor.extract %val[%c0] : tensor<2xi32> 593 /// 594 /// to 595 /// 596 /// %extracted_element = tensor.extract %source[%c0] : tensor<?xi32> 597 struct ExtractFromTensorCast : public OpRewritePattern<tensor::ExtractOp> { 598 using OpRewritePattern<tensor::ExtractOp>::OpRewritePattern; 599 600 LogicalResult matchAndRewrite(tensor::ExtractOp extract, 601 PatternRewriter &rewriter) const final { 602 auto tensorCast = extract.tensor().getDefiningOp<tensor::CastOp>(); 603 if (!tensorCast) 604 return failure(); 605 606 rewriter.replaceOpWithNewOp<tensor::ExtractOp>(extract, tensorCast.source(), 607 extract.indices()); 608 return success(); 609 } 610 }; 611 612 } // namespace 613 614 void GenerateOp::getCanonicalizationPatterns(RewritePatternSet &results, 615 MLIRContext *context) { 616 // TODO: Move extract patterns to tensor::ExtractOp. 617 results.add<ExtractFromTensorGenerate, ExtractFromTensorCast, 618 StaticTensorGenerate>(context); 619 } 620 621 //===----------------------------------------------------------------------===// 622 // RankOp 623 //===----------------------------------------------------------------------===// 624 625 OpFoldResult RankOp::fold(ArrayRef<Attribute> operands) { 626 // Constant fold rank when the rank of the operand is known. 627 auto type = getOperand().getType(); 628 auto shapedType = type.dyn_cast<ShapedType>(); 629 if (shapedType && shapedType.hasRank()) 630 return IntegerAttr::get(IndexType::get(getContext()), shapedType.getRank()); 631 return IntegerAttr(); 632 } 633 634 //===----------------------------------------------------------------------===// 635 // ReshapeOp 636 //===----------------------------------------------------------------------===// 637 638 static int64_t getNumElements(ShapedType type) { 639 int64_t numElements = 1; 640 for (auto dim : type.getShape()) 641 numElements *= dim; 642 return numElements; 643 } 644 645 static LogicalResult verify(ReshapeOp op) { 646 TensorType operandType = op.source().getType().cast<TensorType>(); 647 TensorType resultType = op.result().getType().cast<TensorType>(); 648 649 if (operandType.getElementType() != resultType.getElementType()) 650 return op.emitOpError("element types of source and destination tensor " 651 "types should be the same"); 652 653 int64_t shapeSize = 654 op.shape().getType().cast<RankedTensorType>().getDimSize(0); 655 auto resultRankedType = resultType.dyn_cast<RankedTensorType>(); 656 auto operandRankedType = operandType.dyn_cast<RankedTensorType>(); 657 658 if (resultRankedType) { 659 if (operandRankedType && resultRankedType.hasStaticShape() && 660 operandRankedType.hasStaticShape()) { 661 if (getNumElements(operandRankedType) != getNumElements(resultRankedType)) 662 return op.emitOpError("source and destination tensor should have the " 663 "same number of elements"); 664 } 665 if (ShapedType::isDynamic(shapeSize)) 666 return op.emitOpError("cannot use shape operand with dynamic length to " 667 "reshape to statically-ranked tensor type"); 668 if (shapeSize != resultRankedType.getRank()) 669 return op.emitOpError( 670 "length of shape operand differs from the result's tensor rank"); 671 } 672 return success(); 673 } 674 675 //===----------------------------------------------------------------------===// 676 // Reassociative reshape ops 677 //===----------------------------------------------------------------------===// 678 679 SmallVector<AffineMap, 4> CollapseShapeOp::getReassociationMaps() { 680 return getSymbolLessAffineMaps(getReassociationExprs()); 681 } 682 SmallVector<ReassociationExprs, 4> CollapseShapeOp::getReassociationExprs() { 683 return convertReassociationIndicesToExprs(getContext(), 684 getReassociationIndices()); 685 } 686 687 SmallVector<AffineMap, 4> ExpandShapeOp::getReassociationMaps() { 688 return getSymbolLessAffineMaps(getReassociationExprs()); 689 } 690 SmallVector<ReassociationExprs, 4> ExpandShapeOp::getReassociationExprs() { 691 return convertReassociationIndicesToExprs(getContext(), 692 getReassociationIndices()); 693 } 694 695 static void print(OpAsmPrinter &p, ExpandShapeOp op) { 696 ::mlir::printReshapeOp<ExpandShapeOp>(p, op); 697 } 698 699 static void print(OpAsmPrinter &p, CollapseShapeOp op) { 700 ::mlir::printReshapeOp<CollapseShapeOp>(p, op); 701 } 702 703 /// Compute the RankedTensorType obtained by applying `reassociation` to `type`. 704 static RankedTensorType 705 computeTensorReshapeCollapsedType(RankedTensorType type, 706 ArrayRef<AffineMap> reassociation) { 707 auto shape = type.getShape(); 708 SmallVector<int64_t, 4> newShape; 709 newShape.reserve(reassociation.size()); 710 711 // Use the fact that reassociation is valid to simplify the logic: only use 712 // each map's rank. 713 assert(isReassociationValid(reassociation) && "invalid reassociation"); 714 unsigned currentDim = 0; 715 for (AffineMap m : reassociation) { 716 unsigned dim = m.getNumResults(); 717 auto band = shape.slice(currentDim, dim); 718 int64_t size = 1; 719 if (llvm::is_contained(band, ShapedType::kDynamicSize)) 720 size = ShapedType::kDynamicSize; 721 else 722 for (unsigned d = 0; d < dim; ++d) 723 size *= shape[currentDim + d]; 724 newShape.push_back(size); 725 currentDim += dim; 726 } 727 728 return RankedTensorType::get(newShape, type.getElementType()); 729 } 730 731 void CollapseShapeOp::build(OpBuilder &b, OperationState &result, Value src, 732 ArrayRef<ReassociationIndices> reassociation, 733 ArrayRef<NamedAttribute> attrs) { 734 auto resultType = computeTensorReshapeCollapsedType( 735 src.getType().cast<RankedTensorType>(), 736 getSymbolLessAffineMaps( 737 convertReassociationIndicesToExprs(b.getContext(), reassociation))); 738 build(b, result, resultType, src, attrs); 739 result.addAttribute(getReassociationAttrName(), 740 getReassociationIndicesAttribute(b, reassociation)); 741 } 742 743 void ExpandShapeOp::build(OpBuilder &b, OperationState &result, Value src, 744 ArrayRef<ReassociationIndices> reassociation, 745 ArrayRef<NamedAttribute> attrs) { 746 auto resultType = computeTensorReshapeCollapsedType( 747 src.getType().cast<RankedTensorType>(), 748 getSymbolLessAffineMaps( 749 convertReassociationIndicesToExprs(b.getContext(), reassociation))); 750 build(b, result, resultType, src, attrs); 751 result.addAttribute(getReassociationAttrName(), 752 getReassociationIndicesAttribute(b, reassociation)); 753 } 754 755 template <typename TensorReshapeOp, bool isExpansion = std::is_same< 756 TensorReshapeOp, ExpandShapeOp>::value> 757 static LogicalResult verifyTensorReshapeOp(TensorReshapeOp op, 758 RankedTensorType expandedType, 759 RankedTensorType collapsedType) { 760 if (failed( 761 verifyReshapeLikeTypes(op, expandedType, collapsedType, isExpansion))) 762 return failure(); 763 764 auto maps = op.getReassociationMaps(); 765 RankedTensorType expectedType = 766 computeTensorReshapeCollapsedType(expandedType, maps); 767 if (collapsedType != expectedType) 768 return op.emitOpError("expected collapsed type to be ") 769 << expectedType << ", but got " << collapsedType; 770 return success(); 771 } 772 773 static LogicalResult verify(ExpandShapeOp op) { 774 return verifyTensorReshapeOp(op, op.getResultType(), op.getSrcType()); 775 } 776 777 static LogicalResult verify(CollapseShapeOp op) { 778 return verifyTensorReshapeOp(op, op.getSrcType(), op.getResultType()); 779 } 780 781 namespace { 782 /// Reshape of a splat constant can be replaced with a constant of the result 783 /// type. 784 template <typename TensorReshapeOp> 785 struct FoldReshapeWithConstant : OpRewritePattern<TensorReshapeOp> { 786 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 787 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 788 PatternRewriter &rewriter) const override { 789 DenseElementsAttr attr; 790 if (!matchPattern(reshapeOp.src(), m_Constant(&attr))) 791 return failure(); 792 if (!attr || !attr.isSplat()) 793 return failure(); 794 DenseElementsAttr newAttr = DenseElementsAttr::getFromRawBuffer( 795 reshapeOp.getResultType(), attr.getRawData(), true); 796 rewriter.replaceOpWithNewOp<arith::ConstantOp>(reshapeOp, newAttr); 797 return success(); 798 } 799 }; 800 801 /// Reshape of a FromElements can be replaced with a FromElements of the result 802 /// type 803 template <typename TensorReshapeOp> 804 struct FoldReshapeWithFromElements : OpRewritePattern<TensorReshapeOp> { 805 using OpRewritePattern<TensorReshapeOp>::OpRewritePattern; 806 LogicalResult matchAndRewrite(TensorReshapeOp reshapeOp, 807 PatternRewriter &rewriter) const override { 808 auto fromElements = 809 reshapeOp.src().template getDefiningOp<FromElementsOp>(); 810 if (!fromElements) 811 return failure(); 812 813 auto shapedTy = reshapeOp.getType().template cast<ShapedType>(); 814 815 if (!shapedTy.hasStaticShape()) 816 return failure(); 817 818 rewriter.replaceOpWithNewOp<FromElementsOp>(reshapeOp, reshapeOp.getType(), 819 fromElements.elements()); 820 return success(); 821 } 822 }; 823 824 } // namespace 825 826 void ExpandShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 827 MLIRContext *context) { 828 results.add<CollapseReshapeOps<ExpandShapeOp>, 829 CollapseMixedReshapeOps<ExpandShapeOp, CollapseShapeOp>, 830 FoldReshapeWithConstant<ExpandShapeOp>, 831 FoldReshapeWithFromElements<ExpandShapeOp>>(context); 832 } 833 834 void CollapseShapeOp::getCanonicalizationPatterns(RewritePatternSet &results, 835 MLIRContext *context) { 836 results.add<CollapseReshapeOps<CollapseShapeOp>, 837 CollapseMixedReshapeOps<CollapseShapeOp, ExpandShapeOp>, 838 FoldReshapeWithConstant<CollapseShapeOp>, 839 FoldReshapeWithFromElements<CollapseShapeOp>>(context); 840 } 841 842 OpFoldResult ExpandShapeOp::fold(ArrayRef<Attribute> operands) { 843 return foldReshapeOp<ExpandShapeOp, CollapseShapeOp>(*this, operands); 844 } 845 OpFoldResult CollapseShapeOp::fold(ArrayRef<Attribute> operands) { 846 return foldReshapeOp<CollapseShapeOp, ExpandShapeOp>(*this, operands); 847 } 848 849 //===----------------------------------------------------------------------===// 850 // ExtractSliceOp 851 //===----------------------------------------------------------------------===// 852 853 /// An extract_slice op result type can be fully inferred from the source type 854 /// and the static representation of offsets, sizes and strides. Special 855 /// sentinels encode the dynamic case. 856 RankedTensorType ExtractSliceOp::inferResultType( 857 RankedTensorType sourceRankedTensorType, ArrayRef<int64_t> staticOffsets, 858 ArrayRef<int64_t> staticSizes, ArrayRef<int64_t> staticStrides) { 859 // An extract_slice op may specify only a leading subset of offset/sizes/ 860 // strides in which case we complete with offset=0, sizes from memref type and 861 // strides=1. 862 unsigned rank = sourceRankedTensorType.getRank(); 863 (void)rank; 864 assert(staticSizes.size() == rank && 865 "unexpected staticSizes not equal to rank of source"); 866 return RankedTensorType::get(staticSizes, 867 sourceRankedTensorType.getElementType()); 868 } 869 870 RankedTensorType ExtractSliceOp::inferResultType( 871 RankedTensorType sourceRankedTensorType, ArrayRef<OpFoldResult> offsets, 872 ArrayRef<OpFoldResult> sizes, ArrayRef<OpFoldResult> strides) { 873 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 874 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 875 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 876 ShapedType::kDynamicStrideOrOffset); 877 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 878 ShapedType::kDynamicSize); 879 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 880 ShapedType::kDynamicStrideOrOffset); 881 return ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets, 882 staticSizes, staticStrides); 883 } 884 885 /// An extract_slice op result type can be fully inferred from the source type 886 /// and the static representation of offsets, sizes and strides. Special 887 /// sentinels encode the dynamic case. 888 RankedTensorType ExtractSliceOp::inferRankReducedResultType( 889 unsigned resultRank, RankedTensorType sourceRankedTensorType, 890 ArrayRef<int64_t> offsets, ArrayRef<int64_t> sizes, 891 ArrayRef<int64_t> strides) { 892 auto inferredType = 893 inferResultType(sourceRankedTensorType, offsets, sizes, strides) 894 .cast<RankedTensorType>(); 895 int rankDiff = inferredType.getRank() - resultRank; 896 if (rankDiff > 0) { 897 auto shape = inferredType.getShape(); 898 llvm::SmallDenseSet<unsigned> dimsToProject; 899 mlir::getPositionsOfShapeOne(rankDiff, shape, dimsToProject); 900 SmallVector<int64_t> projectedShape; 901 for (unsigned pos = 0, e = shape.size(); pos < e; ++pos) 902 if (!dimsToProject.contains(pos)) 903 projectedShape.push_back(shape[pos]); 904 inferredType = 905 RankedTensorType::get(projectedShape, inferredType.getElementType()); 906 } 907 return inferredType; 908 } 909 910 RankedTensorType ExtractSliceOp::inferRankReducedResultType( 911 unsigned resultRank, RankedTensorType sourceRankedTensorType, 912 ArrayRef<OpFoldResult> offsets, ArrayRef<OpFoldResult> sizes, 913 ArrayRef<OpFoldResult> strides) { 914 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 915 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 916 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 917 ShapedType::kDynamicStrideOrOffset); 918 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 919 ShapedType::kDynamicSize); 920 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 921 ShapedType::kDynamicStrideOrOffset); 922 return ExtractSliceOp::inferRankReducedResultType( 923 resultRank, sourceRankedTensorType, staticOffsets, staticSizes, 924 staticStrides); 925 } 926 927 /// Build an ExtractSliceOp with mixed static and dynamic entries and custom 928 /// result type. If the type passed is nullptr, it is inferred. 929 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, 930 RankedTensorType resultType, Value source, 931 ArrayRef<OpFoldResult> offsets, 932 ArrayRef<OpFoldResult> sizes, 933 ArrayRef<OpFoldResult> strides, 934 ArrayRef<NamedAttribute> attrs) { 935 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 936 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 937 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 938 ShapedType::kDynamicStrideOrOffset); 939 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 940 ShapedType::kDynamicSize); 941 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 942 ShapedType::kDynamicStrideOrOffset); 943 auto sourceRankedTensorType = source.getType().cast<RankedTensorType>(); 944 // Structuring implementation this way avoids duplication between builders. 945 if (!resultType) { 946 resultType = 947 ExtractSliceOp::inferResultType(sourceRankedTensorType, staticOffsets, 948 staticSizes, staticStrides) 949 .cast<RankedTensorType>(); 950 } 951 build(b, result, resultType, source, dynamicOffsets, dynamicSizes, 952 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 953 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 954 result.addAttributes(attrs); 955 } 956 957 /// Build an ExtractSliceOp with mixed static and dynamic entries and inferred 958 /// result type. 959 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source, 960 ArrayRef<OpFoldResult> offsets, 961 ArrayRef<OpFoldResult> sizes, 962 ArrayRef<OpFoldResult> strides, 963 ArrayRef<NamedAttribute> attrs) { 964 build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs); 965 } 966 967 /// Build an ExtractSliceOp with dynamic entries and custom result type. If the 968 /// type passed is nullptr, it is inferred. 969 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, 970 RankedTensorType resultType, Value source, 971 ValueRange offsets, ValueRange sizes, 972 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 973 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 974 llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; })); 975 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 976 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 977 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 978 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 979 build(b, result, resultType, source, offsetValues, sizeValues, strideValues); 980 } 981 982 /// Build an ExtractSliceOp with dynamic entries and inferred result type. 983 void ExtractSliceOp::build(OpBuilder &b, OperationState &result, Value source, 984 ValueRange offsets, ValueRange sizes, 985 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 986 build(b, result, RankedTensorType(), source, offsets, sizes, strides, attrs); 987 } 988 989 template <typename OpTy> 990 static LogicalResult produceSliceErrorMsg(SliceVerificationResult result, 991 OpTy op, Type expectedType) { 992 auto memrefType = expectedType.cast<ShapedType>(); 993 switch (result) { 994 case SliceVerificationResult::Success: 995 return success(); 996 case SliceVerificationResult::RankTooLarge: 997 return op.emitError("expected rank to be smaller or equal to ") 998 << "the other rank. "; 999 case SliceVerificationResult::SizeMismatch: 1000 return op.emitError("expected type to be ") 1001 << expectedType << " or a rank-reduced version. (size mismatch) "; 1002 case SliceVerificationResult::ElemTypeMismatch: 1003 return op.emitError("expected element type to be ") 1004 << memrefType.getElementType(); 1005 default: 1006 llvm_unreachable("unexpected extract_slice op verification result"); 1007 } 1008 } 1009 1010 /// Verifier for ExtractSliceOp. 1011 static LogicalResult verify(ExtractSliceOp op) { 1012 // Verify result type against inferred type. 1013 auto expectedType = 1014 ExtractSliceOp::inferResultType(op.getSourceType(), op.getMixedOffsets(), 1015 op.getMixedSizes(), op.getMixedStrides()); 1016 auto result = 1017 isRankReducedType(expectedType.cast<ShapedType>(), op.getType()); 1018 return produceSliceErrorMsg(result, op, expectedType); 1019 } 1020 1021 /// Infer the canonical type of the result of an extract_slice op. Returns a 1022 /// type with rank `resultRank` that is either the rank of the rank-reduced 1023 /// type, or the non-rank-reduced type. 1024 static RankedTensorType 1025 getCanonicalSliceResultType(unsigned resultRank, RankedTensorType sourceType, 1026 ArrayRef<OpFoldResult> mixedOffsets, 1027 ArrayRef<OpFoldResult> mixedSizes, 1028 ArrayRef<OpFoldResult> mixedStrides) { 1029 auto resultType = 1030 ExtractSliceOp::inferRankReducedResultType( 1031 resultRank, sourceType, mixedOffsets, mixedSizes, mixedStrides) 1032 .cast<RankedTensorType>(); 1033 if (resultType.getRank() != resultRank) { 1034 resultType = ExtractSliceOp::inferResultType(sourceType, mixedOffsets, 1035 mixedSizes, mixedStrides) 1036 .cast<RankedTensorType>(); 1037 } 1038 return resultType; 1039 } 1040 1041 llvm::SmallDenseSet<unsigned> ExtractSliceOp::getDroppedDims() { 1042 llvm::SmallDenseSet<unsigned> droppedDims; 1043 ArrayRef<int64_t> resultShape = getType().getShape(); 1044 SmallVector<OpFoldResult> mixedSizes = getMixedSizes(); 1045 unsigned shapePos = 0; 1046 for (const auto &size : enumerate(mixedSizes)) { 1047 Optional<int64_t> sizeVal = getConstantIntValue(size.value()); 1048 // If the size is not 1, or if the current matched dimension of the result 1049 // is the same static shape as the size value (which is 1), then the 1050 // dimension is preserved. 1051 if (!sizeVal || sizeVal.getValue() != 1 || 1052 (shapePos < resultShape.size() && resultShape[shapePos] == 1)) { 1053 shapePos++; 1054 continue; 1055 } 1056 droppedDims.insert(size.index()); 1057 } 1058 return droppedDims; 1059 } 1060 1061 LogicalResult ExtractSliceOp::reifyResultShapes( 1062 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) { 1063 reifiedReturnShapes.resize(1); 1064 reifiedReturnShapes[0].reserve(getType().getRank()); 1065 SmallVector<OpFoldResult> mixedSizes = getMixedSizes(); 1066 llvm::SmallDenseSet<unsigned> droppedDims = getDroppedDims(); 1067 Location loc = getLoc(); 1068 for (const auto &size : enumerate(mixedSizes)) { 1069 if (droppedDims.count(size.index())) 1070 continue; 1071 if (auto attr = size.value().dyn_cast<Attribute>()) { 1072 reifiedReturnShapes[0].push_back(builder.create<arith::ConstantIndexOp>( 1073 loc, attr.cast<IntegerAttr>().getInt())); 1074 continue; 1075 } 1076 reifiedReturnShapes[0].push_back(size.value().get<Value>()); 1077 } 1078 return success(); 1079 } 1080 1081 namespace { 1082 /// Pattern to rewrite an extract_slice op with tensor::Cast arguments. 1083 /// This essentially pushes memref_cast past its consuming slice when 1084 /// `canFoldIntoConsumerOp` is true. 1085 /// 1086 /// Example: 1087 /// ``` 1088 /// %0 = tensor.cast %V : tensor<16x16xf32> to tensor<?x?xf32> 1089 /// %1 = tensor.extract_slice %0[0, 0][3, 4][1, 1] : tensor<?x?xf32> to 1090 /// tensor<3x4xf32> 1091 /// ``` 1092 /// is rewritten into: 1093 /// ``` 1094 /// %0 = tensor.extract_slice %V[0, 0][3, 4][1, 1] : tensor<16x16xf32> to 1095 /// tensor<3x4xf32> %1 = tensor.cast %0: tensor<3x4xf32> to tensor<3x4xf32> 1096 /// ``` 1097 class ExtractSliceOpCastFolder final : public OpRewritePattern<ExtractSliceOp> { 1098 public: 1099 using OpRewritePattern<ExtractSliceOp>::OpRewritePattern; 1100 1101 LogicalResult matchAndRewrite(ExtractSliceOp sliceOp, 1102 PatternRewriter &rewriter) const override { 1103 // Any constant operand, just return to let SubViewOpConstantFolder kick in. 1104 if (llvm::any_of(sliceOp.getOperands(), [](Value operand) { 1105 return matchPattern(operand, matchConstantIndex()); 1106 })) 1107 return failure(); 1108 1109 auto castOp = sliceOp.source().getDefiningOp<tensor::CastOp>(); 1110 if (!castOp) 1111 return failure(); 1112 1113 if (!canFoldIntoConsumerOp(castOp)) 1114 return failure(); 1115 1116 /// Deduce the type of the result to use for the canonicalized operation. 1117 RankedTensorType resultType = getCanonicalSliceResultType( 1118 sliceOp.getType().getRank(), sliceOp.getSourceType(), 1119 sliceOp.getMixedOffsets(), sliceOp.getMixedSizes(), 1120 sliceOp.getMixedStrides()); 1121 Value newSlice = rewriter.create<ExtractSliceOp>( 1122 sliceOp.getLoc(), resultType, castOp.source(), sliceOp.offsets(), 1123 sliceOp.sizes(), sliceOp.strides(), sliceOp.static_offsets(), 1124 sliceOp.static_sizes(), sliceOp.static_strides()); 1125 rewriter.replaceOpWithNewOp<tensor::CastOp>(sliceOp, sliceOp.getType(), 1126 newSlice); 1127 return success(); 1128 } 1129 }; 1130 } // namespace 1131 1132 /// Return the canonical type of the result of an extract_slice op. 1133 struct SliceReturnTypeCanonicalizer { 1134 RankedTensorType operator()(ExtractSliceOp op, 1135 ArrayRef<OpFoldResult> mixedOffsets, 1136 ArrayRef<OpFoldResult> mixedSizes, 1137 ArrayRef<OpFoldResult> mixedStrides) { 1138 return getCanonicalSliceResultType(op.getType().getRank(), 1139 op.getSourceType(), mixedOffsets, 1140 mixedSizes, mixedStrides); 1141 } 1142 }; 1143 1144 /// A canonicalizer wrapper to replace ExtractSliceOps. 1145 struct SliceCanonicalizer { 1146 void operator()(PatternRewriter &rewriter, ExtractSliceOp op, 1147 ExtractSliceOp newOp) { 1148 Value replacement = newOp.getResult(); 1149 if (replacement.getType() != op.getType()) 1150 replacement = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(), 1151 replacement); 1152 rewriter.replaceOp(op, replacement); 1153 } 1154 }; 1155 1156 void ExtractSliceOp::getCanonicalizationPatterns(RewritePatternSet &results, 1157 MLIRContext *context) { 1158 results.add< 1159 OpWithOffsetSizesAndStridesConstantArgumentFolder< 1160 ExtractSliceOp, SliceReturnTypeCanonicalizer, SliceCanonicalizer>, 1161 ExtractSliceOpCastFolder>(context); 1162 } 1163 1164 // 1165 static LogicalResult 1166 foldIdentityOffsetSizeAndStrideOpInterface(OffsetSizeAndStrideOpInterface op, 1167 ShapedType shapedType) { 1168 OpBuilder b(op.getContext()); 1169 for (OpFoldResult ofr : op.getMixedOffsets()) 1170 if (getConstantIntValue(ofr) != static_cast<int64_t>(0)) 1171 return failure(); 1172 // Rank-reducing noops only need to inspect the leading dimensions: llvm::zip 1173 // is appropriate. 1174 auto shape = shapedType.getShape(); 1175 for (auto it : llvm::zip(op.getMixedSizes(), shape)) 1176 if (getConstantIntValue(std::get<0>(it)) != std::get<1>(it)) 1177 return failure(); 1178 for (OpFoldResult ofr : op.getMixedStrides()) 1179 if (getConstantIntValue(ofr) != static_cast<int64_t>(1)) 1180 return failure(); 1181 return success(); 1182 } 1183 1184 /// If we have an ExtractSliceOp consuming an InsertSliceOp with the same slice, 1185 /// we can return the InsertSliceOp's source directly. 1186 // TODO: This only checks the immediate producer; extend to go up the 1187 // insert/extract chain if the slices are disjoint. 1188 static Value foldExtractAfterInsertSlice(ExtractSliceOp extractOp) { 1189 auto insertOp = extractOp.source().getDefiningOp<InsertSliceOp>(); 1190 1191 auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; }; 1192 if (insertOp && insertOp.source().getType() == extractOp.getType() && 1193 insertOp.isSameAs(extractOp, isSame)) 1194 return insertOp.source(); 1195 1196 return {}; 1197 } 1198 1199 OpFoldResult ExtractSliceOp::fold(ArrayRef<Attribute>) { 1200 if (getSourceType() == getType() && 1201 succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType()))) 1202 return this->source(); 1203 if (Value slice = foldExtractAfterInsertSlice(*this)) 1204 return slice; 1205 return OpFoldResult(); 1206 } 1207 1208 Value mlir::tensor::createCanonicalRankReducingExtractSliceOp( 1209 OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType) { 1210 auto rankedTensorType = tensor.getType().cast<RankedTensorType>(); 1211 unsigned rank = rankedTensorType.getRank(); 1212 auto shape = rankedTensorType.getShape(); 1213 SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0)); 1214 SmallVector<OpFoldResult> sizes; 1215 for (unsigned i = 0, e = rank; i < e; ++i) { 1216 OpFoldResult dim; 1217 if (rankedTensorType.isDynamicDim(i)) 1218 dim = b.createOrFold<tensor::DimOp>( 1219 loc, tensor, b.create<arith::ConstantIndexOp>(loc, i)); 1220 else 1221 dim = b.getIndexAttr(shape[i]); 1222 sizes.push_back(dim); 1223 } 1224 SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1)); 1225 return b.createOrFold<tensor::ExtractSliceOp>(loc, targetType, tensor, 1226 offsets, sizes, strides); 1227 } 1228 1229 //===----------------------------------------------------------------------===// 1230 // InsertSliceOp 1231 //===----------------------------------------------------------------------===// 1232 1233 // Build a InsertSliceOp with mixed static and dynamic entries. 1234 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1235 Value dest, ArrayRef<OpFoldResult> offsets, 1236 ArrayRef<OpFoldResult> sizes, 1237 ArrayRef<OpFoldResult> strides, 1238 ArrayRef<NamedAttribute> attrs) { 1239 SmallVector<int64_t> staticOffsets, staticSizes, staticStrides; 1240 SmallVector<Value> dynamicOffsets, dynamicSizes, dynamicStrides; 1241 dispatchIndexOpFoldResults(offsets, dynamicOffsets, staticOffsets, 1242 ShapedType::kDynamicStrideOrOffset); 1243 dispatchIndexOpFoldResults(sizes, dynamicSizes, staticSizes, 1244 ShapedType::kDynamicSize); 1245 dispatchIndexOpFoldResults(strides, dynamicStrides, staticStrides, 1246 ShapedType::kDynamicStrideOrOffset); 1247 build(b, result, dest.getType(), source, dest, dynamicOffsets, dynamicSizes, 1248 dynamicStrides, b.getI64ArrayAttr(staticOffsets), 1249 b.getI64ArrayAttr(staticSizes), b.getI64ArrayAttr(staticStrides)); 1250 result.addAttributes(attrs); 1251 } 1252 1253 // Build a InsertSliceOp with dynamic entries. 1254 void InsertSliceOp::build(OpBuilder &b, OperationState &result, Value source, 1255 Value dest, ValueRange offsets, ValueRange sizes, 1256 ValueRange strides, ArrayRef<NamedAttribute> attrs) { 1257 SmallVector<OpFoldResult> offsetValues = llvm::to_vector<4>( 1258 llvm::map_range(offsets, [](Value v) -> OpFoldResult { return v; })); 1259 SmallVector<OpFoldResult> sizeValues = llvm::to_vector<4>( 1260 llvm::map_range(sizes, [](Value v) -> OpFoldResult { return v; })); 1261 SmallVector<OpFoldResult> strideValues = llvm::to_vector<4>( 1262 llvm::map_range(strides, [](Value v) -> OpFoldResult { return v; })); 1263 build(b, result, source, dest, offsetValues, sizeValues, strideValues); 1264 } 1265 1266 /// Verifier for InsertSliceOp. 1267 static LogicalResult verify(InsertSliceOp op) { 1268 // insert_slice is the inverse of extract_slice, use the same type inference. 1269 auto expectedType = ExtractSliceOp::inferRankReducedResultType( 1270 op.getSourceType().getRank(), op.getType(), 1271 extractFromI64ArrayAttr(op.static_offsets()), 1272 extractFromI64ArrayAttr(op.static_sizes()), 1273 extractFromI64ArrayAttr(op.static_strides())); 1274 auto result = 1275 isRankReducedType(expectedType.cast<ShapedType>(), op.getSourceType()); 1276 return produceSliceErrorMsg(result, op, expectedType); 1277 } 1278 1279 /// If we have two consecutive InsertSliceOp writing to the same slice, we 1280 /// can mutate the second InsertSliceOp's destination to the first one's. 1281 /// 1282 /// Example: 1283 /// 1284 /// ```mlir 1285 /// %0 = tensor.insert_slice %slice0 into %input[0, 0] [64, 64] [1, 1] 1286 /// %1 = tensor.insert_slice %slice1 into %0[0, 0] [64, 64] [1, 1] 1287 /// ``` 1288 /// 1289 /// folds into: 1290 /// 1291 /// ```mlir 1292 /// %1 = tensor.insert_slice %slice1 into %input[0, 0] [64, 64] [1, 1] 1293 /// ``` 1294 static LogicalResult foldInsertAfterInsertSlice(InsertSliceOp insertOp) { 1295 auto prevInsertOp = insertOp.dest().getDefiningOp<InsertSliceOp>(); 1296 1297 auto isSame = [](OpFoldResult a, OpFoldResult b) { return a == b; }; 1298 if (!prevInsertOp || 1299 prevInsertOp.source().getType() != insertOp.source().getType() || 1300 !prevInsertOp.isSameAs(insertOp, isSame)) 1301 return failure(); 1302 1303 insertOp.destMutable().assign(prevInsertOp.dest()); 1304 return success(); 1305 } 1306 1307 OpFoldResult InsertSliceOp::fold(ArrayRef<Attribute>) { 1308 if (getSourceType().hasStaticShape() && getType().hasStaticShape() && 1309 getSourceType() == getType() && 1310 succeeded(foldIdentityOffsetSizeAndStrideOpInterface(*this, getType()))) 1311 return this->source(); 1312 if (succeeded(foldInsertAfterInsertSlice(*this))) 1313 return getResult(); 1314 return OpFoldResult(); 1315 } 1316 1317 LogicalResult InsertSliceOp::reifyResultShapes( 1318 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) { 1319 reifiedReturnShapes.resize(1, SmallVector<Value>(getType().getRank())); 1320 for (auto dim : llvm::seq<int64_t>(0, getType().getRank())) { 1321 reifiedReturnShapes[0][dim] = 1322 builder.createOrFold<tensor::DimOp>(getLoc(), dest(), dim); 1323 } 1324 return success(); 1325 } 1326 1327 namespace { 1328 /// Pattern to rewrite a insert_slice op with constant arguments. 1329 class InsertSliceOpConstantArgumentFolder final 1330 : public OpRewritePattern<InsertSliceOp> { 1331 public: 1332 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1333 1334 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1335 PatternRewriter &rewriter) const override { 1336 // No constant operand, just return. 1337 if (llvm::none_of(insertSliceOp.getOperands(), [](Value operand) { 1338 return matchPattern(operand, matchConstantIndex()); 1339 })) 1340 return failure(); 1341 1342 // At least one of offsets/sizes/strides is a new constant. 1343 // Form the new list of operands and constant attributes from the 1344 // existing. 1345 SmallVector<OpFoldResult> mixedOffsets(insertSliceOp.getMixedOffsets()); 1346 SmallVector<OpFoldResult> mixedSizes(insertSliceOp.getMixedSizes()); 1347 SmallVector<OpFoldResult> mixedStrides(insertSliceOp.getMixedStrides()); 1348 canonicalizeSubViewPart(mixedOffsets, ShapedType::isDynamicStrideOrOffset); 1349 canonicalizeSubViewPart(mixedSizes, ShapedType::isDynamic); 1350 canonicalizeSubViewPart(mixedStrides, ShapedType::isDynamicStrideOrOffset); 1351 1352 // Create the new op in canonical form. 1353 auto sourceType = ExtractSliceOp::inferRankReducedResultType( 1354 insertSliceOp.getSourceType().getRank(), insertSliceOp.getType(), 1355 mixedOffsets, mixedSizes, mixedStrides); 1356 Value toInsert = insertSliceOp.source(); 1357 if (sourceType != insertSliceOp.getSourceType()) 1358 toInsert = rewriter.create<tensor::CastOp>(insertSliceOp.getLoc(), 1359 sourceType, toInsert); 1360 rewriter.replaceOpWithNewOp<InsertSliceOp>( 1361 insertSliceOp, toInsert, insertSliceOp.dest(), mixedOffsets, mixedSizes, 1362 mixedStrides); 1363 return success(); 1364 } 1365 }; 1366 1367 /// Fold tensor_casts with insert_slice operations. If the source or destination 1368 /// tensor is a tensor_cast that removes static type information, the cast is 1369 /// folded into the insert_slice operation. E.g.: 1370 /// 1371 /// ```mlir 1372 /// %1 = tensor.cast %0 : tensor<8x16xf32> to tensor<?x?xf32> 1373 /// %2 = tensor.insert_slice %1 into ... : tensor<?x?xf32> into ... 1374 /// ``` 1375 /// 1376 /// folds into: 1377 /// 1378 /// ```mlir 1379 /// %2 = tensor.insert_slice %0 into ... : tensor<8x16xf32> into ... 1380 /// ``` 1381 /// 1382 /// Note: When folding a cast on the destination tensor, the result of the 1383 /// insert_slice operation is casted to ensure that the type of the result did 1384 /// not change. 1385 struct InsertSliceOpCastFolder final : public OpRewritePattern<InsertSliceOp> { 1386 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1387 1388 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1389 PatternRewriter &rewriter) const override { 1390 if (llvm::any_of(insertSliceOp.getOperands(), [](Value operand) { 1391 return matchPattern(operand, matchConstantIndex()); 1392 })) 1393 return failure(); 1394 1395 auto getSourceOfCastOp = [](Value v) -> Optional<Value> { 1396 auto castOp = v.getDefiningOp<tensor::CastOp>(); 1397 if (!castOp || !canFoldIntoConsumerOp(castOp)) 1398 return llvm::None; 1399 return castOp.source(); 1400 }; 1401 Optional<Value> sourceCastSource = 1402 getSourceOfCastOp(insertSliceOp.source()); 1403 Optional<Value> destCastSource = getSourceOfCastOp(insertSliceOp.dest()); 1404 if (!sourceCastSource && !destCastSource) 1405 return failure(); 1406 1407 Value replacement = rewriter.create<InsertSliceOp>( 1408 insertSliceOp.getLoc(), 1409 (sourceCastSource ? *sourceCastSource : insertSliceOp.source()), 1410 (destCastSource ? *destCastSource : insertSliceOp.dest()), 1411 insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(), 1412 insertSliceOp.getMixedStrides()); 1413 1414 if (replacement.getType() != insertSliceOp.getType()) { 1415 replacement = rewriter.create<tensor::CastOp>( 1416 insertSliceOp.getLoc(), insertSliceOp.getType(), replacement); 1417 } 1418 rewriter.replaceOp(insertSliceOp, replacement); 1419 return success(); 1420 } 1421 }; 1422 1423 /// If additional static type information can be deduced from a insert_slice's 1424 /// size operands, insert an explicit cast of the op's source operand. This 1425 /// enables other canonicalization patterns that are matching for tensor_cast 1426 /// ops such as `ForOpTensorCastFolder` in SCF. 1427 /// 1428 /// Example: 1429 /// 1430 /// ```mlir 1431 /// %r = tensor.insert_slice %0 into %1[...] [64, 64] [1, 1] 1432 /// : tensor<?x?xf32> into ... 1433 /// ``` 1434 /// 1435 /// folds into: 1436 /// 1437 /// ```mlir 1438 /// %tmp = tensor.cast %0 : tensor<?x?xf32> to tensor<64x64xf32> 1439 /// %r = tensor.insert_slice %tmp into %1[...] [64, 64] [1, 1] 1440 /// : tensor<64x64xf32> into ... 1441 /// ``` 1442 struct InsertSliceOpSourceCastInserter final 1443 : public OpRewritePattern<InsertSliceOp> { 1444 using OpRewritePattern<InsertSliceOp>::OpRewritePattern; 1445 1446 LogicalResult matchAndRewrite(InsertSliceOp insertSliceOp, 1447 PatternRewriter &rewriter) const override { 1448 RankedTensorType srcType = insertSliceOp.getSourceType(); 1449 if (srcType.getRank() != insertSliceOp.getType().getRank()) 1450 return failure(); 1451 SmallVector<int64_t> newSrcShape(srcType.getShape().begin(), 1452 srcType.getShape().end()); 1453 for (int64_t i = 0; i < srcType.getRank(); ++i) { 1454 if (Optional<int64_t> constInt = 1455 getConstantIntValue(insertSliceOp.getMixedSizes()[i])) 1456 newSrcShape[i] = *constInt; 1457 } 1458 1459 RankedTensorType newSrcType = 1460 RankedTensorType::get(newSrcShape, srcType.getElementType()); 1461 if (srcType == newSrcType || 1462 !preservesStaticInformation(srcType, newSrcType) || 1463 !tensor::CastOp::areCastCompatible(srcType, newSrcType)) 1464 return failure(); 1465 1466 // newSrcType is: 1467 // 1) Different from srcType. 1468 // 2) "More static" than srcType. 1469 // 3) Cast-compatible with srcType. 1470 // Insert the cast. 1471 Value cast = rewriter.create<tensor::CastOp>( 1472 insertSliceOp.getLoc(), newSrcType, insertSliceOp.source()); 1473 rewriter.replaceOpWithNewOp<InsertSliceOp>( 1474 insertSliceOp, cast, insertSliceOp.dest(), 1475 insertSliceOp.getMixedOffsets(), insertSliceOp.getMixedSizes(), 1476 insertSliceOp.getMixedStrides()); 1477 return success(); 1478 } 1479 }; 1480 } // namespace 1481 1482 void InsertSliceOp::getCanonicalizationPatterns(RewritePatternSet &results, 1483 MLIRContext *context) { 1484 results.add<InsertSliceOpConstantArgumentFolder, InsertSliceOpCastFolder, 1485 InsertSliceOpSourceCastInserter>(context); 1486 } 1487 1488 Value mlir::tensor::createCanonicalRankReducingInsertSliceOp(OpBuilder &b, 1489 Location loc, 1490 Value tensor, 1491 Value dest) { 1492 auto rankedTensorType = dest.getType().cast<RankedTensorType>(); 1493 unsigned rank = rankedTensorType.getRank(); 1494 auto shape = rankedTensorType.getShape(); 1495 SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0)); 1496 SmallVector<OpFoldResult> sizes; 1497 for (unsigned i = 0, e = rank; i < e; ++i) { 1498 OpFoldResult dim; 1499 if (rankedTensorType.isDynamicDim(i)) 1500 dim = b.createOrFold<tensor::DimOp>( 1501 loc, dest, b.create<arith::ConstantIndexOp>(loc, i)); 1502 else 1503 dim = b.getIndexAttr(shape[i]); 1504 sizes.push_back(dim); 1505 } 1506 SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1)); 1507 return b.createOrFold<tensor::InsertSliceOp>(loc, tensor, dest, offsets, 1508 sizes, strides); 1509 } 1510 1511 //===----------------------------------------------------------------------===// 1512 // PadOp 1513 //===----------------------------------------------------------------------===// 1514 1515 // TODO: Replace custom<InferType> directive with AllTypesMatch as soon as it 1516 // supports optional types. 1517 void printInferType(OpAsmPrinter &printer, Operation *op, Value optOperand, 1518 Type typeToInfer, Type typeToInferFrom) {} 1519 1520 ParseResult parseInferType(OpAsmParser &parser, 1521 Optional<OpAsmParser::OperandType> optOperand, 1522 Type &typeToInfer, Type typeToInferFrom) { 1523 if (optOperand) 1524 typeToInfer = typeToInferFrom; 1525 return success(); 1526 } 1527 1528 static LogicalResult verify(PadOp op) { 1529 auto sourceType = op.source().getType().cast<RankedTensorType>(); 1530 auto resultType = op.result().getType().cast<RankedTensorType>(); 1531 auto expectedType = PadOp::inferResultType( 1532 sourceType, extractFromI64ArrayAttr(op.static_low()), 1533 extractFromI64ArrayAttr(op.static_high())); 1534 for (int i = 0, e = sourceType.getRank(); i < e; ++i) { 1535 if (resultType.getDimSize(i) == expectedType.getDimSize(i)) 1536 continue; 1537 if (expectedType.isDynamicDim(i)) 1538 continue; 1539 return op.emitError("specified type ") 1540 << resultType << " does not match the inferred type " 1541 << expectedType; 1542 } 1543 1544 auto ®ion = op.region(); 1545 unsigned rank = resultType.getRank(); 1546 Block &block = region.front(); 1547 if (block.getNumArguments() != rank) 1548 return op.emitError("expected the block to have ") << rank << " arguments"; 1549 1550 // Note: the number and type of yield values are checked in the YieldOp. 1551 for (const auto &en : llvm::enumerate(block.getArgumentTypes())) { 1552 if (!en.value().isIndex()) 1553 return op.emitOpError("expected block argument ") 1554 << (en.index() + 1) << " to be an index"; 1555 } 1556 1557 // Ensure that the region yields an element of the right type. 1558 auto yieldOp = llvm::cast<YieldOp>(block.getTerminator()); 1559 if (yieldOp.value().getType() != 1560 op.getType().cast<ShapedType>().getElementType()) 1561 return op.emitOpError("expected yield type to match shape element type"); 1562 1563 return success(); 1564 } 1565 1566 RankedTensorType PadOp::inferResultType(RankedTensorType sourceType, 1567 ArrayRef<int64_t> staticLow, 1568 ArrayRef<int64_t> staticHigh, 1569 ArrayRef<int64_t> resultShape) { 1570 unsigned rank = sourceType.getRank(); 1571 assert(staticLow.size() == rank && "unexpected staticLow size mismatch"); 1572 assert(staticHigh.size() == rank && "unexpected staticHigh size mismatch"); 1573 assert((resultShape.empty() || resultShape.size() == rank) && 1574 "unexpected resultShape size mismatch"); 1575 1576 SmallVector<int64_t, 4> inferredShape; 1577 for (auto i : llvm::seq<unsigned>(0, rank)) { 1578 if (sourceType.isDynamicDim(i) || 1579 staticLow[i] == ShapedType::kDynamicSize || 1580 staticHigh[i] == ShapedType::kDynamicSize) { 1581 inferredShape.push_back(resultShape.empty() ? ShapedType::kDynamicSize 1582 : resultShape[i]); 1583 } else { 1584 int64_t size = sourceType.getDimSize(i) + staticLow[i] + staticHigh[i]; 1585 assert((resultShape.empty() || size == resultShape[i] || 1586 resultShape[i] == ShapedType::kDynamicSize) && 1587 "mismatch between inferred shape and result shape"); 1588 inferredShape.push_back(size); 1589 } 1590 } 1591 1592 return RankedTensorType::get(inferredShape, sourceType.getElementType()); 1593 } 1594 1595 void PadOp::build(OpBuilder &b, OperationState &result, Value source, 1596 ArrayRef<int64_t> staticLow, ArrayRef<int64_t> staticHigh, 1597 ValueRange low, ValueRange high, bool nofold, 1598 ArrayRef<NamedAttribute> attrs) { 1599 auto sourceType = source.getType().cast<RankedTensorType>(); 1600 auto resultType = inferResultType(sourceType, staticLow, staticHigh); 1601 build(b, result, resultType, source, low, high, b.getI64ArrayAttr(staticLow), 1602 b.getI64ArrayAttr(staticHigh), nofold ? b.getUnitAttr() : UnitAttr()); 1603 result.addAttributes(attrs); 1604 } 1605 1606 void PadOp::build(OpBuilder &b, OperationState &result, Value source, 1607 ValueRange low, ValueRange high, bool nofold, 1608 ArrayRef<NamedAttribute> attrs) { 1609 auto sourceType = source.getType().cast<RankedTensorType>(); 1610 unsigned rank = sourceType.getRank(); 1611 SmallVector<int64_t, 4> staticVector(rank, ShapedType::kDynamicSize); 1612 build(b, result, source, staticVector, staticVector, low, high, nofold, 1613 attrs); 1614 } 1615 1616 void PadOp::build(OpBuilder &b, OperationState &result, Type resultType, 1617 Value source, ArrayRef<OpFoldResult> low, 1618 ArrayRef<OpFoldResult> high, bool nofold, 1619 ArrayRef<NamedAttribute> attrs) { 1620 assert(resultType.isa<RankedTensorType>()); 1621 auto sourceType = source.getType().cast<RankedTensorType>(); 1622 SmallVector<Value, 4> dynamicLow, dynamicHigh; 1623 SmallVector<int64_t, 4> staticLow, staticHigh; 1624 // staticLow and staticHigh have full information of the padding config. 1625 // This will grow staticLow and staticHigh with 1 value. If the config is 1626 // dynamic (ie not a constant), dynamicLow and dynamicHigh will grow with 1 1627 // value as well. 1628 dispatchIndexOpFoldResults(low, dynamicLow, staticLow, 1629 ShapedType::kDynamicSize); 1630 dispatchIndexOpFoldResults(high, dynamicHigh, staticHigh, 1631 ShapedType::kDynamicSize); 1632 if (!resultType) { 1633 resultType = PadOp::inferResultType(sourceType, staticLow, staticHigh); 1634 } 1635 build(b, result, resultType, source, dynamicLow, dynamicHigh, 1636 b.getI64ArrayAttr(staticLow), b.getI64ArrayAttr(staticHigh), 1637 nofold ? b.getUnitAttr() : UnitAttr()); 1638 result.addAttributes(attrs); 1639 } 1640 1641 namespace { 1642 // Folds tensor.pad when padding is static zeros and the attribute 1643 // doesn't request otherwise. 1644 struct FoldStaticZeroPadding : public OpRewritePattern<PadOp> { 1645 using OpRewritePattern<PadOp>::OpRewritePattern; 1646 1647 LogicalResult matchAndRewrite(PadOp padTensorOp, 1648 PatternRewriter &rewriter) const override { 1649 if (!padTensorOp.hasZeroLowPad() || !padTensorOp.hasZeroHighPad()) 1650 return failure(); 1651 if (padTensorOp.nofold()) 1652 return failure(); 1653 rewriter.replaceOpWithNewOp<tensor::CastOp>( 1654 padTensorOp, padTensorOp.result().getType(), padTensorOp.source()); 1655 return success(); 1656 } 1657 }; 1658 1659 // Fold CastOp into PadOp when adding static information. 1660 struct FoldSourceTensorCast : public OpRewritePattern<PadOp> { 1661 using OpRewritePattern<PadOp>::OpRewritePattern; 1662 1663 LogicalResult matchAndRewrite(PadOp padTensorOp, 1664 PatternRewriter &rewriter) const override { 1665 auto castOp = padTensorOp.source().getDefiningOp<tensor::CastOp>(); 1666 if (!tensor::canFoldIntoConsumerOp(castOp)) 1667 return failure(); 1668 1669 auto newResultType = PadOp::inferResultType( 1670 castOp.source().getType().cast<RankedTensorType>(), 1671 extractFromI64ArrayAttr(padTensorOp.static_low()), 1672 extractFromI64ArrayAttr(padTensorOp.static_high()), 1673 padTensorOp.getResultType().getShape()); 1674 1675 if (newResultType == padTensorOp.getResultType()) { 1676 rewriter.updateRootInPlace(padTensorOp, [&]() { 1677 padTensorOp.sourceMutable().assign(castOp.source()); 1678 }); 1679 } else { 1680 auto newOp = rewriter.create<PadOp>( 1681 padTensorOp->getLoc(), newResultType, padTensorOp.source(), 1682 padTensorOp.low(), padTensorOp.high(), padTensorOp.static_low(), 1683 padTensorOp.static_high(), padTensorOp.nofold()); 1684 BlockAndValueMapping mapper; 1685 padTensorOp.getRegion().cloneInto(&newOp.getRegion(), mapper); 1686 1687 rewriter.replaceOpWithNewOp<tensor::CastOp>( 1688 padTensorOp, padTensorOp.getResultType(), newOp); 1689 } 1690 return success(); 1691 } 1692 }; 1693 1694 // Fold CastOp using the result of PadOp back into the latter if it adds 1695 // static information. 1696 struct FoldTargetTensorCast : public OpRewritePattern<PadOp> { 1697 using OpRewritePattern<PadOp>::OpRewritePattern; 1698 1699 LogicalResult matchAndRewrite(PadOp padTensorOp, 1700 PatternRewriter &rewriter) const override { 1701 if (!padTensorOp.result().hasOneUse()) 1702 return failure(); 1703 auto tensorCastOp = 1704 dyn_cast<tensor::CastOp>(*padTensorOp->getUsers().begin()); 1705 if (!tensorCastOp) 1706 return failure(); 1707 if (!tensor::preservesStaticInformation(padTensorOp.result().getType(), 1708 tensorCastOp.dest().getType())) 1709 return failure(); 1710 1711 auto replacementOp = rewriter.create<PadOp>( 1712 padTensorOp.getLoc(), tensorCastOp.dest().getType(), 1713 padTensorOp.source(), padTensorOp.low(), padTensorOp.high(), 1714 padTensorOp.static_low(), padTensorOp.static_high(), 1715 padTensorOp.nofold()); 1716 replacementOp.region().takeBody(padTensorOp.region()); 1717 1718 rewriter.replaceOp(padTensorOp, replacementOp.result()); 1719 rewriter.replaceOp(tensorCastOp, replacementOp.result()); 1720 return success(); 1721 } 1722 }; 1723 } // namespace 1724 1725 void PadOp::getCanonicalizationPatterns(RewritePatternSet &results, 1726 MLIRContext *context) { 1727 results 1728 .add<FoldStaticZeroPadding, FoldSourceTensorCast, FoldTargetTensorCast>( 1729 context); 1730 } 1731 1732 /// Return the padding value of the PadOp if it constant. In this context, 1733 /// "constant" means an actual constant or "defined outside of the block". 1734 /// 1735 /// Values are considered constant in three cases: 1736 /// - A ConstantLike value. 1737 /// - A basic block argument from a different block. 1738 /// - A value defined outside of the block. 1739 /// 1740 /// If the padding value is not constant, an empty Value is returned. 1741 Value PadOp::getConstantPaddingValue() { 1742 auto yieldOp = dyn_cast<YieldOp>(getRegion().front().getTerminator()); 1743 if (!yieldOp) 1744 return {}; 1745 Value padValue = yieldOp.value(); 1746 // Check if yield value is a constant. 1747 if (matchPattern(padValue, m_Constant())) 1748 return padValue; 1749 // Check if yield value is defined inside the PadOp block. 1750 if (padValue.getParentBlock() == &getRegion().front()) 1751 return {}; 1752 // Else: Yield value defined outside of the PadOp block. 1753 return padValue; 1754 } 1755 1756 OpFoldResult PadOp::fold(ArrayRef<Attribute>) { 1757 if (getResultType().hasStaticShape() && getResultType() == getSourceType() && 1758 !nofold()) 1759 return source(); 1760 return {}; 1761 } 1762 1763 //===----------------------------------------------------------------------===// 1764 // TableGen'd op method definitions 1765 //===----------------------------------------------------------------------===// 1766 1767 #define GET_OP_CLASSES 1768 #include "mlir/Dialect/Tensor/IR/TensorOps.cpp.inc" 1769