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