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