1 //===- VectorOps.cpp - MLIR Vector Dialect Operations ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements convenience types for working with super-vectorization 10 // operations, in particular super-vector loads and stores. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Dialect/Vector/IR/VectorOps.h" 15 16 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 17 #include "mlir/Dialect/Arithmetic/Utils/Utils.h" 18 #include "mlir/Dialect/MemRef/IR/MemRef.h" 19 #include "mlir/Dialect/Tensor/IR/Tensor.h" 20 #include "mlir/Dialect/Utils/IndexingUtils.h" 21 #include "mlir/Dialect/Utils/StructuredOpsUtils.h" 22 #include "mlir/IR/AffineExpr.h" 23 #include "mlir/IR/AffineMap.h" 24 #include "mlir/IR/BlockAndValueMapping.h" 25 #include "mlir/IR/Builders.h" 26 #include "mlir/IR/BuiltinOps.h" 27 #include "mlir/IR/BuiltinTypes.h" 28 #include "mlir/IR/DialectImplementation.h" 29 #include "mlir/IR/OpImplementation.h" 30 #include "mlir/IR/PatternMatch.h" 31 #include "mlir/IR/TypeUtilities.h" 32 #include "mlir/Support/LLVM.h" 33 #include "mlir/Support/MathExtras.h" 34 #include "llvm/ADT/StringSet.h" 35 #include "llvm/ADT/bit.h" 36 #include <numeric> 37 38 #include "mlir/Dialect/Vector/IR/VectorOpsDialect.cpp.inc" 39 // Pull in all enum type and utility function definitions. 40 #include "mlir/Dialect/Vector/IR/VectorOpsEnums.cpp.inc" 41 42 using namespace mlir; 43 using namespace mlir::vector; 44 45 /// Helper enum to classify mask value. 46 enum class MaskFormat { 47 AllTrue = 0, 48 AllFalse = 1, 49 Unknown = 2, 50 }; 51 52 /// Helper method to classify a 1-D mask value. Currently, the method 53 /// looks "under the hood" of a constant value with dense attributes 54 /// and a constant mask operation (since the client may be called at 55 /// various stages during progressive lowering). 56 static MaskFormat get1DMaskFormat(Value mask) { 57 if (auto c = mask.getDefiningOp<arith::ConstantOp>()) { 58 // Inspect constant dense values. We count up for bits that 59 // are set, count down for bits that are cleared, and bail 60 // when a mix is detected. 61 if (auto denseElts = c.getValue().dyn_cast<DenseIntElementsAttr>()) { 62 int64_t val = 0; 63 for (bool b : denseElts.getValues<bool>()) 64 if (b && val >= 0) 65 val++; 66 else if (!b && val <= 0) 67 val--; 68 else 69 return MaskFormat::Unknown; 70 if (val > 0) 71 return MaskFormat::AllTrue; 72 if (val < 0) 73 return MaskFormat::AllFalse; 74 } 75 } else if (auto m = mask.getDefiningOp<ConstantMaskOp>()) { 76 // Inspect constant mask index. If the index exceeds the 77 // dimension size, all bits are set. If the index is zero 78 // or less, no bits are set. 79 ArrayAttr masks = m.mask_dim_sizes(); 80 assert(masks.size() == 1); 81 int64_t i = masks[0].cast<IntegerAttr>().getInt(); 82 int64_t u = m.getType().getDimSize(0); 83 if (i >= u) 84 return MaskFormat::AllTrue; 85 if (i <= 0) 86 return MaskFormat::AllFalse; 87 } 88 return MaskFormat::Unknown; 89 } 90 91 // Helper for verifying combining kinds in contractions and reductions. 92 static bool isSupportedCombiningKind(CombiningKind combiningKind, 93 Type elementType) { 94 switch (combiningKind) { 95 case CombiningKind::ADD: 96 case CombiningKind::MUL: 97 return elementType.isIntOrIndexOrFloat(); 98 case CombiningKind::MINUI: 99 case CombiningKind::MINSI: 100 case CombiningKind::MAXUI: 101 case CombiningKind::MAXSI: 102 case CombiningKind::AND: 103 case CombiningKind::OR: 104 case CombiningKind::XOR: 105 return elementType.isIntOrIndex(); 106 case CombiningKind::MINF: 107 case CombiningKind::MAXF: 108 return elementType.isa<FloatType>(); 109 } 110 return false; 111 } 112 113 /// Return true if the last dimension of the MemRefType has unit stride. Also 114 /// return true for memrefs with no strides. 115 bool mlir::vector::isLastMemrefDimUnitStride(MemRefType type) { 116 int64_t offset; 117 SmallVector<int64_t> strides; 118 auto successStrides = getStridesAndOffset(type, strides, offset); 119 return succeeded(successStrides) && (strides.empty() || strides.back() == 1); 120 } 121 122 AffineMap mlir::vector::getTransferMinorIdentityMap(ShapedType shapedType, 123 VectorType vectorType) { 124 int64_t elementVectorRank = 0; 125 VectorType elementVectorType = 126 shapedType.getElementType().dyn_cast<VectorType>(); 127 if (elementVectorType) 128 elementVectorRank += elementVectorType.getRank(); 129 // 0-d transfers are to/from tensor<t>/memref<t> and vector<1xt>. 130 // TODO: replace once we have 0-d vectors. 131 if (shapedType.getRank() == 0 && 132 vectorType.getShape() == ArrayRef<int64_t>{1}) 133 return AffineMap::get( 134 /*numDims=*/0, /*numSymbols=*/0, 135 getAffineConstantExpr(0, shapedType.getContext())); 136 return AffineMap::getMinorIdentityMap( 137 shapedType.getRank(), vectorType.getRank() - elementVectorRank, 138 shapedType.getContext()); 139 } 140 141 bool mlir::vector::checkSameValueRAW(vector::TransferWriteOp defWrite, 142 vector::TransferReadOp read) { 143 return !defWrite.hasOutOfBoundsDim() && !defWrite.mask() && !read.mask() && 144 defWrite.indices() == read.indices() && 145 defWrite.getVectorType() == read.getVectorType() && 146 defWrite.permutation_map() == read.permutation_map(); 147 } 148 149 bool mlir::vector::checkSameValueWAW(vector::TransferWriteOp write, 150 vector::TransferWriteOp priorWrite) { 151 return priorWrite.indices() == write.indices() && 152 priorWrite.mask() == write.mask() && 153 priorWrite.getVectorType() == write.getVectorType() && 154 priorWrite.permutation_map() == write.permutation_map(); 155 } 156 157 bool mlir::vector::isDisjointTransferIndices( 158 VectorTransferOpInterface transferA, VectorTransferOpInterface transferB) { 159 // For simplicity only look at transfer of same type. 160 if (transferA.getVectorType() != transferB.getVectorType()) 161 return false; 162 unsigned rankOffset = transferA.getLeadingShapedRank(); 163 for (unsigned i = 0, e = transferA.indices().size(); i < e; i++) { 164 auto indexA = transferA.indices()[i].getDefiningOp<arith::ConstantOp>(); 165 auto indexB = transferB.indices()[i].getDefiningOp<arith::ConstantOp>(); 166 // If any of the indices are dynamic we cannot prove anything. 167 if (!indexA || !indexB) 168 continue; 169 170 if (i < rankOffset) { 171 // For leading dimensions, if we can prove that index are different we 172 // know we are accessing disjoint slices. 173 if (indexA.getValue().cast<IntegerAttr>().getInt() != 174 indexB.getValue().cast<IntegerAttr>().getInt()) 175 return true; 176 } else { 177 // For this dimension, we slice a part of the memref we need to make sure 178 // the intervals accessed don't overlap. 179 int64_t distance = 180 std::abs(indexA.getValue().cast<IntegerAttr>().getInt() - 181 indexB.getValue().cast<IntegerAttr>().getInt()); 182 if (distance >= transferA.getVectorType().getDimSize(i - rankOffset)) 183 return true; 184 } 185 } 186 return false; 187 } 188 189 bool mlir::vector::isDisjointTransferSet(VectorTransferOpInterface transferA, 190 VectorTransferOpInterface transferB) { 191 if (transferA.source() != transferB.source()) 192 return false; 193 return isDisjointTransferIndices(transferA, transferB); 194 } 195 196 //===----------------------------------------------------------------------===// 197 // CombiningKindAttr 198 //===----------------------------------------------------------------------===// 199 200 namespace mlir { 201 namespace vector { 202 namespace detail { 203 struct BitmaskEnumStorage : public AttributeStorage { 204 using KeyTy = uint64_t; 205 206 BitmaskEnumStorage(KeyTy val) : value(val) {} 207 208 bool operator==(const KeyTy &key) const { return value == key; } 209 210 static BitmaskEnumStorage *construct(AttributeStorageAllocator &allocator, 211 const KeyTy &key) { 212 return new (allocator.allocate<BitmaskEnumStorage>()) 213 BitmaskEnumStorage(key); 214 } 215 216 KeyTy value = 0; 217 }; 218 } // namespace detail 219 } // namespace vector 220 } // namespace mlir 221 222 CombiningKindAttr CombiningKindAttr::get(CombiningKind kind, 223 MLIRContext *context) { 224 return Base::get(context, static_cast<uint64_t>(kind)); 225 } 226 227 CombiningKind CombiningKindAttr::getKind() const { 228 return static_cast<CombiningKind>(getImpl()->value); 229 } 230 231 static constexpr const CombiningKind combiningKindsList[] = { 232 // clang-format off 233 CombiningKind::ADD, 234 CombiningKind::MUL, 235 CombiningKind::MINUI, 236 CombiningKind::MINSI, 237 CombiningKind::MINF, 238 CombiningKind::MAXUI, 239 CombiningKind::MAXSI, 240 CombiningKind::MAXF, 241 CombiningKind::AND, 242 CombiningKind::OR, 243 CombiningKind::XOR, 244 // clang-format on 245 }; 246 247 void CombiningKindAttr::print(AsmPrinter &printer) const { 248 printer << "<"; 249 auto kinds = llvm::make_filter_range(combiningKindsList, [&](auto kind) { 250 return bitEnumContains(this->getKind(), kind); 251 }); 252 llvm::interleaveComma(kinds, printer, 253 [&](auto kind) { printer << stringifyEnum(kind); }); 254 printer << ">"; 255 } 256 257 Attribute CombiningKindAttr::parse(AsmParser &parser, Type type) { 258 if (failed(parser.parseLess())) 259 return {}; 260 261 StringRef elemName; 262 if (failed(parser.parseKeyword(&elemName))) 263 return {}; 264 265 auto kind = symbolizeCombiningKind(elemName); 266 if (!kind) { 267 parser.emitError(parser.getNameLoc(), "Unknown combining kind: ") 268 << elemName; 269 return {}; 270 } 271 272 if (failed(parser.parseGreater())) 273 return {}; 274 275 return CombiningKindAttr::get(kind.getValue(), parser.getContext()); 276 } 277 278 Attribute VectorDialect::parseAttribute(DialectAsmParser &parser, 279 Type type) const { 280 StringRef attrKind; 281 if (parser.parseKeyword(&attrKind)) 282 return {}; 283 284 if (attrKind == "kind") 285 return CombiningKindAttr::parse(parser, {}); 286 287 parser.emitError(parser.getNameLoc(), "Unknown attribute type: ") << attrKind; 288 return {}; 289 } 290 291 void VectorDialect::printAttribute(Attribute attr, 292 DialectAsmPrinter &os) const { 293 if (auto ck = attr.dyn_cast<CombiningKindAttr>()) { 294 os << "kind"; 295 ck.print(os); 296 return; 297 } 298 llvm_unreachable("Unknown attribute type"); 299 } 300 301 //===----------------------------------------------------------------------===// 302 // VectorDialect 303 //===----------------------------------------------------------------------===// 304 305 void VectorDialect::initialize() { 306 addAttributes<CombiningKindAttr>(); 307 308 addOperations< 309 #define GET_OP_LIST 310 #include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc" 311 >(); 312 } 313 314 /// Materialize a single constant operation from a given attribute value with 315 /// the desired resultant type. 316 Operation *VectorDialect::materializeConstant(OpBuilder &builder, 317 Attribute value, Type type, 318 Location loc) { 319 return builder.create<arith::ConstantOp>(loc, type, value); 320 } 321 322 IntegerType vector::getVectorSubscriptType(Builder &builder) { 323 return builder.getIntegerType(64); 324 } 325 326 ArrayAttr vector::getVectorSubscriptAttr(Builder &builder, 327 ArrayRef<int64_t> values) { 328 return builder.getI64ArrayAttr(values); 329 } 330 331 //===----------------------------------------------------------------------===// 332 // MultiDimReductionOp 333 //===----------------------------------------------------------------------===// 334 335 void vector::MultiDimReductionOp::build(OpBuilder &builder, 336 OperationState &result, Value source, 337 ArrayRef<bool> reductionMask, 338 CombiningKind kind) { 339 SmallVector<int64_t> reductionDims; 340 for (const auto &en : llvm::enumerate(reductionMask)) 341 if (en.value()) 342 reductionDims.push_back(en.index()); 343 build(builder, result, kind, source, builder.getI64ArrayAttr(reductionDims)); 344 } 345 346 LogicalResult MultiDimReductionOp::inferReturnTypes( 347 MLIRContext *, Optional<Location>, ValueRange operands, 348 DictionaryAttr attributes, RegionRange, 349 SmallVectorImpl<Type> &inferredReturnTypes) { 350 MultiDimReductionOp::Adaptor op(operands, attributes); 351 auto vectorType = op.source().getType().cast<VectorType>(); 352 SmallVector<int64_t> targetShape; 353 for (auto it : llvm::enumerate(vectorType.getShape())) 354 if (!llvm::any_of(op.reduction_dims().getValue(), [&](Attribute attr) { 355 return attr.cast<IntegerAttr>().getValue() == it.index(); 356 })) 357 targetShape.push_back(it.value()); 358 // TODO: update to also allow 0-d vectors when available. 359 if (targetShape.empty()) 360 inferredReturnTypes.push_back(vectorType.getElementType()); 361 else 362 inferredReturnTypes.push_back( 363 VectorType::get(targetShape, vectorType.getElementType())); 364 return success(); 365 } 366 367 OpFoldResult MultiDimReductionOp::fold(ArrayRef<Attribute> operands) { 368 // Single parallel dim, this is a noop. 369 if (getSourceVectorType().getRank() == 1 && !isReducedDim(0)) 370 return source(); 371 return {}; 372 } 373 374 //===----------------------------------------------------------------------===// 375 // ReductionOp 376 //===----------------------------------------------------------------------===// 377 378 void vector::ReductionOp::build(OpBuilder &builder, OperationState &result, 379 CombiningKind kind, Value vector) { 380 build(builder, result, kind, vector, /*acc=*/Value()); 381 } 382 383 void vector::ReductionOp::build(OpBuilder &builder, OperationState &result, 384 CombiningKind kind, Value vector, Value acc) { 385 build(builder, result, vector.getType().cast<VectorType>().getElementType(), 386 kind, vector, acc); 387 } 388 389 LogicalResult ReductionOp::verify() { 390 // Verify for 1-D vector. 391 int64_t rank = getVectorType().getRank(); 392 if (rank != 1) 393 return emitOpError("unsupported reduction rank: ") << rank; 394 395 // Verify supported reduction kind. 396 Type eltType = dest().getType(); 397 if (!isSupportedCombiningKind(kind(), eltType)) 398 return emitOpError("unsupported reduction type '") 399 << eltType << "' for kind '" << stringifyCombiningKind(kind()) 400 << "'"; 401 402 // Verify optional accumulator. 403 if (acc()) { 404 if (kind() != CombiningKind::ADD && kind() != CombiningKind::MUL) 405 return emitOpError("no accumulator for reduction kind: ") 406 << stringifyCombiningKind(kind()); 407 if (!eltType.isa<FloatType>()) 408 return emitOpError("no accumulator for type: ") << eltType; 409 } 410 411 return success(); 412 } 413 414 ParseResult ReductionOp::parse(OpAsmParser &parser, OperationState &result) { 415 SmallVector<OpAsmParser::OperandType, 2> operandsInfo; 416 Type redType; 417 Type resType; 418 CombiningKindAttr kindAttr; 419 if (parser.parseCustomAttributeWithFallback(kindAttr, Type{}, "kind", 420 result.attributes) || 421 parser.parseComma() || parser.parseOperandList(operandsInfo) || 422 parser.parseColonType(redType) || 423 parser.parseKeywordType("into", resType) || 424 (!operandsInfo.empty() && 425 parser.resolveOperand(operandsInfo[0], redType, result.operands)) || 426 (operandsInfo.size() > 1 && 427 parser.resolveOperand(operandsInfo[1], resType, result.operands)) || 428 parser.addTypeToList(resType, result.types)) 429 return failure(); 430 if (operandsInfo.empty() || operandsInfo.size() > 2) 431 return parser.emitError(parser.getNameLoc(), 432 "unsupported number of operands"); 433 return success(); 434 } 435 436 void ReductionOp::print(OpAsmPrinter &p) { 437 p << " "; 438 kindAttr().print(p); 439 p << ", " << vector(); 440 if (acc()) 441 p << ", " << acc(); 442 p << " : " << vector().getType() << " into " << dest().getType(); 443 } 444 445 Value mlir::vector::getVectorReductionOp(arith::AtomicRMWKind op, 446 OpBuilder &builder, Location loc, 447 Value vector) { 448 switch (op) { 449 case arith::AtomicRMWKind::addf: 450 case arith::AtomicRMWKind::addi: 451 return builder.create<vector::ReductionOp>(vector.getLoc(), 452 CombiningKind::ADD, vector); 453 case arith::AtomicRMWKind::mulf: 454 case arith::AtomicRMWKind::muli: 455 return builder.create<vector::ReductionOp>(vector.getLoc(), 456 CombiningKind::MUL, vector); 457 case arith::AtomicRMWKind::minf: 458 return builder.create<vector::ReductionOp>(vector.getLoc(), 459 CombiningKind::MINF, vector); 460 case arith::AtomicRMWKind::mins: 461 return builder.create<vector::ReductionOp>(vector.getLoc(), 462 CombiningKind::MINSI, vector); 463 case arith::AtomicRMWKind::minu: 464 return builder.create<vector::ReductionOp>(vector.getLoc(), 465 CombiningKind::MINUI, vector); 466 case arith::AtomicRMWKind::maxf: 467 return builder.create<vector::ReductionOp>(vector.getLoc(), 468 CombiningKind::MAXF, vector); 469 case arith::AtomicRMWKind::maxs: 470 return builder.create<vector::ReductionOp>(vector.getLoc(), 471 CombiningKind::MAXSI, vector); 472 case arith::AtomicRMWKind::maxu: 473 return builder.create<vector::ReductionOp>(vector.getLoc(), 474 CombiningKind::MAXUI, vector); 475 // TODO: Add remaining reduction operations. 476 default: 477 (void)emitOptionalError(loc, "Reduction operation type not supported"); 478 break; 479 } 480 return nullptr; 481 } 482 483 //===----------------------------------------------------------------------===// 484 // ContractionOp 485 //===----------------------------------------------------------------------===// 486 487 void vector::ContractionOp::build(OpBuilder &builder, OperationState &result, 488 Value lhs, Value rhs, Value acc, 489 ArrayRef<ArrayRef<AffineExpr>> indexingExprs, 490 ArrayRef<StringRef> iteratorTypes) { 491 result.addOperands({lhs, rhs, acc}); 492 result.addTypes(acc.getType()); 493 result.addAttribute(::mlir::getIndexingMapsAttrName(), 494 builder.getAffineMapArrayAttr( 495 AffineMap::inferFromExprList(indexingExprs))); 496 result.addAttribute(::mlir::getIteratorTypesAttrName(), 497 builder.getStrArrayAttr(iteratorTypes)); 498 } 499 500 void vector::ContractionOp::build(OpBuilder &builder, OperationState &result, 501 Value lhs, Value rhs, Value acc, 502 ArrayAttr indexingMaps, 503 ArrayAttr iteratorTypes) { 504 build(builder, result, lhs, rhs, acc, indexingMaps, iteratorTypes, 505 ContractionOp::getDefaultKind()); 506 } 507 508 void vector::ContractionOp::build(OpBuilder &builder, OperationState &result, 509 Value lhs, Value rhs, Value acc, 510 ArrayAttr indexingMaps, 511 ArrayAttr iteratorTypes, CombiningKind kind) { 512 result.addOperands({lhs, rhs, acc}); 513 result.addTypes(acc.getType()); 514 result.addAttribute(::mlir::getIndexingMapsAttrName(), indexingMaps); 515 result.addAttribute(::mlir::getIteratorTypesAttrName(), iteratorTypes); 516 result.addAttribute(ContractionOp::getKindAttrStrName(), 517 CombiningKindAttr::get(kind, builder.getContext())); 518 } 519 520 ParseResult ContractionOp::parse(OpAsmParser &parser, OperationState &result) { 521 OpAsmParser::OperandType lhsInfo; 522 OpAsmParser::OperandType rhsInfo; 523 OpAsmParser::OperandType accInfo; 524 SmallVector<OpAsmParser::OperandType, 2> masksInfo; 525 SmallVector<Type, 2> types; 526 Type resultType; 527 auto loc = parser.getCurrentLocation(); 528 DictionaryAttr dictAttr; 529 // TODO: Unify linalg op attribute parsing. 530 if (parser.parseAttribute(dictAttr, "_", result.attributes) || 531 parser.parseOperand(lhsInfo) || parser.parseComma() || 532 parser.parseOperand(rhsInfo) || parser.parseComma() || 533 parser.parseOperand(accInfo) || 534 parser.parseTrailingOperandList(masksInfo) || 535 parser.parseOptionalAttrDict(result.attributes) || 536 parser.parseColonTypeList(types) || 537 parser.parseKeywordType("into", resultType) || 538 parser.resolveOperand(lhsInfo, types[0], result.operands) || 539 parser.resolveOperand(rhsInfo, types[1], result.operands) || 540 parser.resolveOperand(accInfo, resultType, result.operands) || 541 parser.addTypeToList(resultType, result.types)) 542 return failure(); 543 result.attributes.assign(dictAttr.getValue().begin(), 544 dictAttr.getValue().end()); 545 if (!result.attributes.get(ContractionOp::getKindAttrStrName())) { 546 result.addAttribute(ContractionOp::getKindAttrStrName(), 547 CombiningKindAttr::get(ContractionOp::getDefaultKind(), 548 result.getContext())); 549 } 550 if (masksInfo.empty()) 551 return success(); 552 if (masksInfo.size() != 2) 553 return parser.emitError(parser.getNameLoc(), 554 "expected zero or exactly 2 vector mask operands"); 555 auto lhsType = types[0].cast<VectorType>(); 556 auto rhsType = types[1].cast<VectorType>(); 557 auto maskElementType = parser.getBuilder().getI1Type(); 558 std::array<Type, 2> maskTypes = { 559 VectorType::Builder(lhsType).setElementType(maskElementType), 560 VectorType::Builder(rhsType).setElementType(maskElementType)}; 561 if (parser.resolveOperands(masksInfo, maskTypes, loc, result.operands)) 562 return failure(); 563 return success(); 564 } 565 566 void ContractionOp::print(OpAsmPrinter &p) { 567 // TODO: Unify printing code with linalg ops. 568 auto attrNames = getTraitAttrNames(); 569 llvm::StringSet<> traitAttrsSet; 570 traitAttrsSet.insert(attrNames.begin(), attrNames.end()); 571 SmallVector<NamedAttribute, 8> attrs; 572 for (auto attr : (*this)->getAttrs()) 573 if (traitAttrsSet.count(attr.getName().strref()) > 0) 574 attrs.push_back(attr); 575 576 auto dictAttr = DictionaryAttr::get(getContext(), attrs); 577 p << " " << dictAttr << " " << lhs() << ", "; 578 p << rhs() << ", " << acc(); 579 if (masks().size() == 2) 580 p << ", " << masks(); 581 582 p.printOptionalAttrDict((*this)->getAttrs(), attrNames); 583 p << " : " << lhs().getType() << ", " << rhs().getType() << " into " 584 << getResultType(); 585 } 586 587 static bool verifyDimMap(VectorType lhsType, VectorType rhsType, 588 const std::vector<std::pair<int64_t, int64_t>> &map) { 589 for (auto &dimPair : map) { 590 if (dimPair.first < 0 || dimPair.first >= lhsType.getRank() || 591 dimPair.second < 0 || dimPair.second >= rhsType.getRank() || 592 lhsType.getDimSize(dimPair.first) != rhsType.getDimSize(dimPair.second)) 593 return false; 594 } 595 return true; 596 } 597 598 static LogicalResult verifyOutputShape( 599 ContractionOp op, VectorType lhsType, VectorType rhsType, Type accType, 600 Type resType, 601 const std::vector<std::pair<int64_t, int64_t>> &contractingDimMap, 602 const std::vector<std::pair<int64_t, int64_t>> &batchDimMap) { 603 DenseSet<int64_t> lhsContractingDimSet; 604 DenseSet<int64_t> rhsContractingDimSet; 605 for (auto &dimPair : contractingDimMap) { 606 lhsContractingDimSet.insert(dimPair.first); 607 rhsContractingDimSet.insert(dimPair.second); 608 } 609 DenseSet<int64_t> rhsBatchDimSet; 610 for (auto &dimPair : batchDimMap) 611 rhsBatchDimSet.insert(dimPair.second); 612 613 // Add free and batch dimensions from 'lhsType' to 'expectedResultDims'. 614 SmallVector<int64_t, 4> expectedResultDims; 615 for (int64_t i = 0, e = lhsType.getRank(); i < e; ++i) { 616 if (lhsContractingDimSet.count(i) > 0) 617 continue; 618 expectedResultDims.push_back(lhsType.getDimSize(i)); 619 } 620 621 // Add free dimensions from 'rhsType' to 'expectedResultDims'. 622 for (int64_t i = 0, e = rhsType.getRank(); i < e; ++i) { 623 if (rhsContractingDimSet.count(i) > 0 || rhsBatchDimSet.count(i) > 0) 624 continue; 625 expectedResultDims.push_back(rhsType.getDimSize(i)); 626 } 627 628 // Verify 'expectedResultDims'. 629 if (expectedResultDims.empty()) { 630 // No batch or free dimension implies a scalar result. 631 if (resType.isa<VectorType>() || accType.isa<VectorType>()) 632 return op.emitOpError("invalid accumulator/result vector shape"); 633 } else { 634 // At least one batch or free dimension implies a vector result. 635 auto resVectorType = resType.dyn_cast<VectorType>(); 636 auto accVectorType = accType.dyn_cast<VectorType>(); 637 if (!resVectorType || !accVectorType) 638 return op.emitOpError("invalid accumulator/result vector shape"); 639 640 // Infer expected result vector type. Lhs + rhs map and lhs + rhs vector 641 // types fully define the result vector type. This assumes the affine maps 642 // are well-formed, which must have been verified already. 643 MLIRContext *ctx = op.getContext(); 644 AffineMap lhsMap = op.getIndexingMaps()[0]; 645 AffineMap rhsMap = op.getIndexingMaps()[1]; 646 SmallVector<AffineExpr, 4> extents(lhsMap.getNumInputs()); 647 for (auto pair : 648 {std::make_pair(lhsType, lhsMap), std::make_pair(rhsType, rhsMap)}) { 649 VectorType v = pair.first; 650 auto map = pair.second; 651 for (unsigned idx = 0, e = v.getRank(); idx < e; ++idx) { 652 unsigned pos = map.getDimPosition(idx); 653 if (!extents[pos]) 654 extents[pos] = getAffineConstantExpr(v.getShape()[idx], ctx); 655 } 656 } 657 assert(llvm::all_of(extents, [](AffineExpr e) { return e; }) && 658 "expected extent along all dimensions."); 659 660 AffineMap resMap = op.getIndexingMaps()[2]; 661 auto extentsMap = AffineMap::get(/*dimCount=*/extents.size(), 662 /*symCount=*/0, extents, ctx); 663 // Compose the resMap with the extentsMap, which is a constant map. 664 AffineMap expectedMap = simplifyAffineMap(resMap.compose(extentsMap)); 665 assert(llvm::all_of( 666 expectedMap.getResults(), 667 [](AffineExpr e) { return e.isa<AffineConstantExpr>(); }) && 668 "expected constant extent along all dimensions."); 669 // Extract the expected shape and build the type. 670 auto expectedShape = llvm::to_vector<4>( 671 llvm::map_range(expectedMap.getResults(), [](AffineExpr e) { 672 return e.cast<AffineConstantExpr>().getValue(); 673 })); 674 auto expected = 675 VectorType::get(expectedShape, resVectorType.getElementType()); 676 if (resVectorType != expected || accVectorType != expected) 677 return op.emitOpError( 678 "invalid accumulator/result vector shape, expected: ") 679 << expected; 680 } 681 return success(); 682 } 683 684 LogicalResult ContractionOp::verify() { 685 auto lhsType = getLhsType(); 686 auto rhsType = getRhsType(); 687 auto accType = getAccType(); 688 auto resType = getResultType(); 689 690 // Verify that an indexing map was specified for each vector operand. 691 if (indexing_maps().size() != 3) 692 return emitOpError("expected an indexing map for each vector operand"); 693 694 // Verify that each index map has 'numIterators' inputs, no symbols, and 695 // that the number of map outputs equals the rank of its associated 696 // vector operand. 697 unsigned numIterators = iterator_types().getValue().size(); 698 for (const auto &it : llvm::enumerate(indexing_maps())) { 699 auto index = it.index(); 700 auto map = it.value(); 701 if (map.getNumSymbols() != 0) 702 return emitOpError("expected indexing map ") 703 << index << " to have no symbols"; 704 auto vectorType = getOperand(index).getType().dyn_cast<VectorType>(); 705 unsigned rank = vectorType ? vectorType.getShape().size() : 0; 706 // Verify that the map has the right number of inputs, outputs, and indices. 707 // This also correctly accounts for (..) -> () for rank-0 results. 708 if (map.getNumDims() != numIterators) 709 return emitOpError("expected indexing map ") 710 << index << " to have " << numIterators << " number of inputs"; 711 if (map.getNumResults() != rank) 712 return emitOpError("expected indexing map ") 713 << index << " to have " << rank << " number of outputs"; 714 if (!map.isProjectedPermutation()) 715 return emitOpError("expected indexing map ") 716 << index << " to be a projected permutation of its inputs"; 717 } 718 719 auto contractingDimMap = getContractingDimMap(); 720 auto batchDimMap = getBatchDimMap(); 721 722 // Verify at least one contracting dimension pair was specified. 723 if (contractingDimMap.empty()) 724 return emitOpError("expected at least one contracting dimension pair"); 725 726 // Verify contracting dimension map was properly constructed. 727 if (!verifyDimMap(lhsType, rhsType, contractingDimMap)) 728 return emitOpError("invalid contracting dimension map"); 729 730 // Verify batch dimension map was properly constructed. 731 if (!verifyDimMap(lhsType, rhsType, batchDimMap)) 732 return emitOpError("invalid batch dimension map"); 733 734 // Verify 'accType' and 'resType' shape. 735 if (failed(verifyOutputShape(*this, lhsType, rhsType, accType, resType, 736 contractingDimMap, batchDimMap))) 737 return failure(); 738 739 // Verify that either two vector masks are set or none are set. 740 auto lhsMaskType = getLHSVectorMaskType(); 741 auto rhsMaskType = getRHSVectorMaskType(); 742 if ((lhsMaskType && !rhsMaskType) || (!lhsMaskType && rhsMaskType)) 743 return emitOpError("invalid number of vector masks specified"); 744 if (lhsMaskType && rhsMaskType) { 745 // Verify mask rank == argument rank. 746 if (lhsMaskType.getShape().size() != lhsType.getShape().size() || 747 rhsMaskType.getShape().size() != rhsType.getShape().size()) 748 return emitOpError("invalid vector mask rank"); 749 } 750 751 // Verify supported combining kind. 752 auto vectorType = resType.dyn_cast<VectorType>(); 753 auto elementType = vectorType ? vectorType.getElementType() : resType; 754 if (!isSupportedCombiningKind(kind(), elementType)) 755 return emitOpError("unsupported contraction type"); 756 757 return success(); 758 } 759 760 ArrayRef<StringRef> ContractionOp::getTraitAttrNames() { 761 static constexpr StringRef names[3] = {::mlir::getIndexingMapsAttrName(), 762 ::mlir::getIteratorTypesAttrName(), 763 ContractionOp::getKindAttrStrName()}; 764 return llvm::makeArrayRef(names); 765 } 766 767 static int64_t getResultIndex(AffineMap map, AffineExpr targetExpr) { 768 for (int64_t i = 0, e = map.getNumResults(); i < e; ++i) 769 if (targetExpr == map.getResult(i)) 770 return i; 771 return -1; 772 } 773 774 static std::vector<std::pair<int64_t, int64_t>> 775 getDimMap(ArrayRef<AffineMap> indexingMaps, ArrayAttr iteratorTypes, 776 StringRef targetIteratorTypeName, MLIRContext *context) { 777 std::vector<std::pair<int64_t, int64_t>> dimMap; 778 for (const auto &it : llvm::enumerate(iteratorTypes)) { 779 auto iteratorTypeName = it.value().cast<StringAttr>().getValue(); 780 if (iteratorTypeName != targetIteratorTypeName) 781 continue; 782 // Search lhs/rhs map results for 'targetExpr'. 783 auto targetExpr = getAffineDimExpr(it.index(), context); 784 int64_t lhsDim = getResultIndex(indexingMaps[0], targetExpr); 785 int64_t rhsDim = getResultIndex(indexingMaps[1], targetExpr); 786 if (lhsDim >= 0 && rhsDim >= 0) 787 dimMap.emplace_back(lhsDim, rhsDim); 788 } 789 return dimMap; 790 } 791 792 void ContractionOp::getIterationBounds( 793 SmallVectorImpl<int64_t> &iterationBounds) { 794 auto lhsShape = getLhsType().getShape(); 795 auto resVectorType = getResultType().dyn_cast<VectorType>(); 796 SmallVector<AffineMap, 4> indexingMaps(getIndexingMaps()); 797 SmallVector<int64_t, 2> iterationShape; 798 for (const auto &it : llvm::enumerate(iterator_types())) { 799 // Search lhs/rhs map results for 'targetExpr'. 800 auto targetExpr = getAffineDimExpr(it.index(), getContext()); 801 auto iteratorTypeName = it.value().cast<StringAttr>().getValue(); 802 if (iteratorTypeName == getReductionIteratorTypeName()) { 803 // Get reduction dim size from lhs shape (same size in rhsShape). 804 int64_t lhsDimIndex = getResultIndex(indexingMaps[0], targetExpr); 805 assert(lhsDimIndex >= 0); 806 iterationBounds.push_back(lhsShape[lhsDimIndex]); 807 continue; 808 } 809 // Get parallel dimension size from result shape. 810 int64_t resDimIndex = getResultIndex(indexingMaps[2], targetExpr); 811 assert(resDimIndex >= 0); 812 assert(resVectorType != nullptr); 813 iterationBounds.push_back(resVectorType.getShape()[resDimIndex]); 814 } 815 } 816 817 void ContractionOp::getIterationIndexMap( 818 std::vector<DenseMap<int64_t, int64_t>> &iterationIndexMap) { 819 unsigned numMaps = indexing_maps().size(); 820 iterationIndexMap.resize(numMaps); 821 for (const auto &it : llvm::enumerate(indexing_maps())) { 822 auto index = it.index(); 823 auto map = it.value(); 824 for (unsigned i = 0, e = map.getNumResults(); i < e; ++i) { 825 auto dim = map.getResult(i).cast<AffineDimExpr>(); 826 iterationIndexMap[index][dim.getPosition()] = i; 827 } 828 } 829 } 830 831 std::vector<std::pair<int64_t, int64_t>> ContractionOp::getContractingDimMap() { 832 SmallVector<AffineMap, 4> indexingMaps(getIndexingMaps()); 833 return getDimMap(indexingMaps, iterator_types(), 834 getReductionIteratorTypeName(), getContext()); 835 } 836 837 std::vector<std::pair<int64_t, int64_t>> ContractionOp::getBatchDimMap() { 838 SmallVector<AffineMap, 4> indexingMaps(getIndexingMaps()); 839 return getDimMap(indexingMaps, iterator_types(), 840 getParallelIteratorTypeName(), getContext()); 841 } 842 843 Optional<SmallVector<int64_t, 4>> ContractionOp::getShapeForUnroll() { 844 SmallVector<int64_t, 4> shape; 845 getIterationBounds(shape); 846 return shape; 847 } 848 849 /// Return a fused vector::ContractionOp which represents a patterns such as: 850 /// 851 /// ```mlir 852 /// %c0 = vector.constant 0: ... 853 /// %c = vector.contract %a, %b, %c0: ... 854 /// %e = add %c, %d: ... 855 /// ``` 856 /// 857 /// by: 858 /// 859 /// ```mlir 860 /// %e = vector.contract %a, %b, %d: ... 861 /// ``` 862 /// 863 /// Return null if the canonicalization does not apply. 864 // TODO: This should be a folding of Add into Contract in core but while they 865 // live in different dialects, it is not possible without unnatural 866 // dependencies. 867 template <typename AddOpType> 868 struct CanonicalizeContractAdd : public OpRewritePattern<AddOpType> { 869 using OpRewritePattern<AddOpType>::OpRewritePattern; 870 871 LogicalResult matchAndRewrite(AddOpType addOp, 872 PatternRewriter &rewriter) const override { 873 auto canonicalize = [&](Value maybeContraction, 874 Value otherOperand) -> vector::ContractionOp { 875 vector::ContractionOp contractionOp = 876 dyn_cast_or_null<vector::ContractionOp>( 877 maybeContraction.getDefiningOp()); 878 if (!contractionOp) 879 return vector::ContractionOp(); 880 if (auto maybeZero = dyn_cast_or_null<arith::ConstantOp>( 881 contractionOp.acc().getDefiningOp())) { 882 if (maybeZero.getValue() == 883 rewriter.getZeroAttr(contractionOp.acc().getType())) { 884 BlockAndValueMapping bvm; 885 bvm.map(contractionOp.acc(), otherOperand); 886 auto newContraction = 887 cast<vector::ContractionOp>(rewriter.clone(*contractionOp, bvm)); 888 rewriter.replaceOp(addOp, newContraction.getResult()); 889 return newContraction; 890 } 891 } 892 return vector::ContractionOp(); 893 }; 894 895 Value a = addOp->getOperand(0), b = addOp->getOperand(1); 896 vector::ContractionOp contract = canonicalize(a, b); 897 contract = contract ? contract : canonicalize(b, a); 898 return contract ? success() : failure(); 899 } 900 }; 901 902 void ContractionOp::getCanonicalizationPatterns(RewritePatternSet &results, 903 MLIRContext *context) { 904 results.add<CanonicalizeContractAdd<arith::AddIOp>, 905 CanonicalizeContractAdd<arith::AddFOp>>(context); 906 } 907 908 //===----------------------------------------------------------------------===// 909 // ExtractElementOp 910 //===----------------------------------------------------------------------===// 911 912 void vector::ExtractElementOp::build(OpBuilder &builder, OperationState &result, 913 Value source) { 914 result.addOperands({source}); 915 result.addTypes(source.getType().cast<VectorType>().getElementType()); 916 } 917 918 void vector::ExtractElementOp::build(OpBuilder &builder, OperationState &result, 919 Value source, Value position) { 920 result.addOperands({source, position}); 921 result.addTypes(source.getType().cast<VectorType>().getElementType()); 922 } 923 924 LogicalResult vector::ExtractElementOp::verify() { 925 VectorType vectorType = getVectorType(); 926 if (vectorType.getRank() == 0) { 927 if (position()) 928 return emitOpError("expected position to be empty with 0-D vector"); 929 return success(); 930 } 931 if (vectorType.getRank() != 1) 932 return emitOpError("unexpected >1 vector rank"); 933 if (!position()) 934 return emitOpError("expected position for 1-D vector"); 935 return success(); 936 } 937 938 //===----------------------------------------------------------------------===// 939 // ExtractOp 940 //===----------------------------------------------------------------------===// 941 942 void vector::ExtractOp::build(OpBuilder &builder, OperationState &result, 943 Value source, ArrayRef<int64_t> position) { 944 build(builder, result, source, getVectorSubscriptAttr(builder, position)); 945 } 946 947 // Convenience builder which assumes the values are constant indices. 948 void vector::ExtractOp::build(OpBuilder &builder, OperationState &result, 949 Value source, ValueRange position) { 950 SmallVector<int64_t, 4> positionConstants = 951 llvm::to_vector<4>(llvm::map_range(position, [](Value pos) { 952 return pos.getDefiningOp<arith::ConstantIndexOp>().value(); 953 })); 954 build(builder, result, source, positionConstants); 955 } 956 957 LogicalResult 958 ExtractOp::inferReturnTypes(MLIRContext *, Optional<Location>, 959 ValueRange operands, DictionaryAttr attributes, 960 RegionRange, 961 SmallVectorImpl<Type> &inferredReturnTypes) { 962 ExtractOp::Adaptor op(operands, attributes); 963 auto vectorType = op.vector().getType().cast<VectorType>(); 964 if (static_cast<int64_t>(op.position().size()) == vectorType.getRank()) { 965 inferredReturnTypes.push_back(vectorType.getElementType()); 966 } else { 967 auto n = std::min<size_t>(op.position().size(), vectorType.getRank() - 1); 968 inferredReturnTypes.push_back(VectorType::get( 969 vectorType.getShape().drop_front(n), vectorType.getElementType())); 970 } 971 return success(); 972 } 973 974 bool ExtractOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) { 975 // Allow extracting 1-element vectors instead of scalars. 976 auto isCompatible = [](TypeRange l, TypeRange r) { 977 auto vectorType = l.front().dyn_cast<VectorType>(); 978 return vectorType && vectorType.getShape().equals({1}) && 979 vectorType.getElementType() == r.front(); 980 }; 981 if (l.size() == 1 && r.size() == 1 && 982 (isCompatible(l, r) || isCompatible(r, l))) 983 return true; 984 return l == r; 985 } 986 987 LogicalResult vector::ExtractOp::verify() { 988 auto positionAttr = position().getValue(); 989 if (positionAttr.size() > static_cast<unsigned>(getVectorType().getRank())) 990 return emitOpError( 991 "expected position attribute of rank smaller than vector rank"); 992 for (const auto &en : llvm::enumerate(positionAttr)) { 993 auto attr = en.value().dyn_cast<IntegerAttr>(); 994 if (!attr || attr.getInt() < 0 || 995 attr.getInt() >= getVectorType().getDimSize(en.index())) 996 return emitOpError("expected position attribute #") 997 << (en.index() + 1) 998 << " to be a non-negative integer smaller than the corresponding " 999 "vector dimension"; 1000 } 1001 return success(); 1002 } 1003 1004 template <typename IntType> 1005 static SmallVector<IntType> extractVector(ArrayAttr arrayAttr) { 1006 return llvm::to_vector<4>(llvm::map_range( 1007 arrayAttr.getAsRange<IntegerAttr>(), 1008 [](IntegerAttr attr) { return static_cast<IntType>(attr.getInt()); })); 1009 } 1010 1011 /// Fold the result of chains of ExtractOp in place by simply concatenating the 1012 /// positions. 1013 static LogicalResult foldExtractOpFromExtractChain(ExtractOp extractOp) { 1014 if (!extractOp.vector().getDefiningOp<ExtractOp>()) 1015 return failure(); 1016 1017 SmallVector<int64_t, 4> globalPosition; 1018 ExtractOp currentOp = extractOp; 1019 auto extrPos = extractVector<int64_t>(currentOp.position()); 1020 globalPosition.append(extrPos.rbegin(), extrPos.rend()); 1021 while (ExtractOp nextOp = currentOp.vector().getDefiningOp<ExtractOp>()) { 1022 currentOp = nextOp; 1023 auto extrPos = extractVector<int64_t>(currentOp.position()); 1024 globalPosition.append(extrPos.rbegin(), extrPos.rend()); 1025 } 1026 extractOp.setOperand(currentOp.vector()); 1027 // OpBuilder is only used as a helper to build an I64ArrayAttr. 1028 OpBuilder b(extractOp.getContext()); 1029 std::reverse(globalPosition.begin(), globalPosition.end()); 1030 extractOp->setAttr(ExtractOp::getPositionAttrStrName(), 1031 b.getI64ArrayAttr(globalPosition)); 1032 return success(); 1033 } 1034 1035 namespace { 1036 /// Fold an ExtractOp that is fed by a chain of InsertOps and TransposeOps. 1037 /// Walk back a chain of InsertOp/TransposeOp until we hit a match. 1038 /// Compose TransposeOp permutations as we walk back. 1039 /// This helper class keeps an updated extraction position `extractPosition` 1040 /// with extra trailing sentinels. 1041 /// The sentinels encode the internal transposition status of the result vector. 1042 /// As we iterate, extractPosition is permuted and updated. 1043 class ExtractFromInsertTransposeChainState { 1044 public: 1045 ExtractFromInsertTransposeChainState(ExtractOp e); 1046 1047 /// Iterate over producing insert and transpose ops until we find a fold. 1048 Value fold(); 1049 1050 private: 1051 /// Return true if the vector at position `a` is contained within the vector 1052 /// at position `b`. Under insert/extract semantics, this is the same as `a` 1053 /// is a prefix of `b`. 1054 template <typename ContainerA, typename ContainerB> 1055 bool isContainedWithin(const ContainerA &a, const ContainerB &b) { 1056 return a.size() <= b.size() && 1057 std::equal(a.begin(), a.begin() + a.size(), b.begin()); 1058 } 1059 1060 /// Return true if the vector at position `a` intersects the vector at 1061 /// position `b`. Under insert/extract semantics, this is the same as equality 1062 /// of all entries of `a` that are >=0 with the corresponding entries of b. 1063 /// Comparison is on the common prefix (i.e. zip). 1064 template <typename ContainerA, typename ContainerB> 1065 bool intersectsWhereNonNegative(const ContainerA &a, const ContainerB &b) { 1066 for (auto it : llvm::zip(a, b)) { 1067 if (std::get<0>(it) < 0 || std::get<0>(it) < 0) 1068 continue; 1069 if (std::get<0>(it) != std::get<1>(it)) 1070 return false; 1071 } 1072 return true; 1073 } 1074 1075 /// Folding is only possible in the absence of an internal permutation in the 1076 /// result vector. 1077 bool canFold() { 1078 return (sentinels == 1079 makeArrayRef(extractPosition).drop_front(extractedRank)); 1080 } 1081 1082 // Helper to get the next defining op of interest. 1083 void updateStateForNextIteration(Value v) { 1084 nextInsertOp = v.getDefiningOp<vector::InsertOp>(); 1085 nextTransposeOp = v.getDefiningOp<vector::TransposeOp>(); 1086 }; 1087 1088 // Case 1. If we hit a transpose, just compose the map and iterate. 1089 // Invariant: insert + transpose do not change rank, we can always compose. 1090 LogicalResult handleTransposeOp(); 1091 1092 // Case 2: the insert position matches extractPosition exactly, early return. 1093 LogicalResult handleInsertOpWithMatchingPos(Value &res); 1094 1095 /// Case 3: if the insert position is a prefix of extractPosition, extract a 1096 /// portion of the source of the insert. 1097 /// Example: 1098 /// ``` 1099 /// %ins = vector.insert %source, %vest[1]: vector<3x4> into vector<2x3x4x5> 1100 /// // extractPosition == [1, 2, 3] 1101 /// %ext = vector.extract %ins[1, 0]: vector<3x4x5> 1102 /// // can fold to vector.extract %source[0, 3] 1103 /// %ext = vector.extract %source[3]: vector<5x6> 1104 /// ``` 1105 /// To traverse through %source, we need to set the leading dims to 0 and 1106 /// drop the extra leading dims. 1107 /// This method updates the internal state. 1108 LogicalResult handleInsertOpWithPrefixPos(Value &res); 1109 1110 /// Try to fold in place to extract(source, extractPosition) and return the 1111 /// folded result. Return null if folding is not possible (e.g. due to an 1112 /// internal tranposition in the result). 1113 Value tryToFoldExtractOpInPlace(Value source); 1114 1115 ExtractOp extractOp; 1116 int64_t vectorRank; 1117 int64_t extractedRank; 1118 1119 InsertOp nextInsertOp; 1120 TransposeOp nextTransposeOp; 1121 1122 /// Sentinel values that encode the internal permutation status of the result. 1123 /// They are set to (-1, ... , -k) at the beginning and appended to 1124 /// `extractPosition`. 1125 /// In the end, the tail of `extractPosition` must be exactly `sentinels` to 1126 /// ensure that there is no internal transposition. 1127 /// Internal transposition cannot be accounted for with a folding pattern. 1128 // TODO: We could relax the internal transposition with an extra transposition 1129 // operation in a future canonicalizer. 1130 SmallVector<int64_t> sentinels; 1131 SmallVector<int64_t> extractPosition; 1132 }; 1133 } // namespace 1134 1135 ExtractFromInsertTransposeChainState::ExtractFromInsertTransposeChainState( 1136 ExtractOp e) 1137 : extractOp(e), vectorRank(extractOp.getVectorType().getRank()), 1138 extractedRank(extractOp.position().size()) { 1139 assert(vectorRank >= extractedRank && "extracted pos overflow"); 1140 sentinels.reserve(vectorRank - extractedRank); 1141 for (int64_t i = 0, e = vectorRank - extractedRank; i < e; ++i) 1142 sentinels.push_back(-(i + 1)); 1143 extractPosition = extractVector<int64_t>(extractOp.position()); 1144 llvm::append_range(extractPosition, sentinels); 1145 } 1146 1147 // Case 1. If we hit a transpose, just compose the map and iterate. 1148 // Invariant: insert + transpose do not change rank, we can always compose. 1149 LogicalResult ExtractFromInsertTransposeChainState::handleTransposeOp() { 1150 if (!nextTransposeOp) 1151 return failure(); 1152 auto permutation = extractVector<unsigned>(nextTransposeOp.transp()); 1153 AffineMap m = inversePermutation( 1154 AffineMap::getPermutationMap(permutation, extractOp.getContext())); 1155 extractPosition = applyPermutationMap(m, makeArrayRef(extractPosition)); 1156 return success(); 1157 } 1158 1159 // Case 2: the insert position matches extractPosition exactly, early return. 1160 LogicalResult 1161 ExtractFromInsertTransposeChainState::handleInsertOpWithMatchingPos( 1162 Value &res) { 1163 auto insertedPos = extractVector<int64_t>(nextInsertOp.position()); 1164 if (makeArrayRef(insertedPos) != 1165 llvm::makeArrayRef(extractPosition).take_front(extractedRank)) 1166 return failure(); 1167 // Case 2.a. early-exit fold. 1168 res = nextInsertOp.source(); 1169 // Case 2.b. if internal transposition is present, canFold will be false. 1170 return success(); 1171 } 1172 1173 /// Case 3: if inserted position is a prefix of extractPosition, 1174 /// extract a portion of the source of the insertion. 1175 /// This method updates the internal state. 1176 LogicalResult 1177 ExtractFromInsertTransposeChainState::handleInsertOpWithPrefixPos(Value &res) { 1178 auto insertedPos = extractVector<int64_t>(nextInsertOp.position()); 1179 if (!isContainedWithin(insertedPos, extractPosition)) 1180 return failure(); 1181 // Set leading dims to zero. 1182 std::fill_n(extractPosition.begin(), insertedPos.size(), 0); 1183 // Drop extra leading dims. 1184 extractPosition.erase(extractPosition.begin(), 1185 extractPosition.begin() + insertedPos.size()); 1186 extractedRank = extractPosition.size() - sentinels.size(); 1187 // Case 3.a. early-exit fold (break and delegate to post-while path). 1188 res = nextInsertOp.source(); 1189 // Case 3.b. if internal transposition is present, canFold will be false. 1190 return success(); 1191 } 1192 1193 /// Try to fold in place to extract(source, extractPosition) and return the 1194 /// folded result. Return null if folding is not possible (e.g. due to an 1195 /// internal tranposition in the result). 1196 Value ExtractFromInsertTransposeChainState::tryToFoldExtractOpInPlace( 1197 Value source) { 1198 // If we can't fold (either internal transposition, or nothing to fold), bail. 1199 bool nothingToFold = (source == extractOp.vector()); 1200 if (nothingToFold || !canFold()) 1201 return Value(); 1202 // Otherwise, fold by updating the op inplace and return its result. 1203 OpBuilder b(extractOp.getContext()); 1204 extractOp->setAttr( 1205 extractOp.positionAttrName(), 1206 b.getI64ArrayAttr( 1207 makeArrayRef(extractPosition).take_front(extractedRank))); 1208 extractOp.vectorMutable().assign(source); 1209 return extractOp.getResult(); 1210 } 1211 1212 /// Iterate over producing insert and transpose ops until we find a fold. 1213 Value ExtractFromInsertTransposeChainState::fold() { 1214 Value valueToExtractFrom = extractOp.vector(); 1215 updateStateForNextIteration(valueToExtractFrom); 1216 while (nextInsertOp || nextTransposeOp) { 1217 // Case 1. If we hit a transpose, just compose the map and iterate. 1218 // Invariant: insert + transpose do not change rank, we can always compose. 1219 if (succeeded(handleTransposeOp())) { 1220 valueToExtractFrom = nextTransposeOp.vector(); 1221 updateStateForNextIteration(valueToExtractFrom); 1222 continue; 1223 } 1224 1225 Value result; 1226 // Case 2: the position match exactly. 1227 if (succeeded(handleInsertOpWithMatchingPos(result))) 1228 return result; 1229 1230 // Case 3: if the inserted position is a prefix of extractPosition, we can 1231 // just extract a portion of the source of the insert. 1232 if (succeeded(handleInsertOpWithPrefixPos(result))) 1233 return tryToFoldExtractOpInPlace(result); 1234 1235 // Case 4: extractPositionRef intersects insertedPosRef on non-sentinel 1236 // values. This is a more difficult case and we bail. 1237 auto insertedPos = extractVector<int64_t>(nextInsertOp.position()); 1238 if (isContainedWithin(extractPosition, insertedPos) || 1239 intersectsWhereNonNegative(extractPosition, insertedPos)) 1240 return Value(); 1241 1242 // Case 5: No intersection, we forward the extract to insertOp.dest(). 1243 valueToExtractFrom = nextInsertOp.dest(); 1244 updateStateForNextIteration(valueToExtractFrom); 1245 } 1246 // If after all this we can fold, go for it. 1247 return tryToFoldExtractOpInPlace(valueToExtractFrom); 1248 } 1249 1250 /// Fold extractOp with scalar result coming from BroadcastOp or SplatOp. 1251 static Value foldExtractFromBroadcast(ExtractOp extractOp) { 1252 Operation *defOp = extractOp.vector().getDefiningOp(); 1253 if (!defOp || !isa<vector::BroadcastOp, SplatOp>(defOp)) 1254 return Value(); 1255 Value source = defOp->getOperand(0); 1256 if (extractOp.getType() == source.getType()) 1257 return source; 1258 auto getRank = [](Type type) { 1259 return type.isa<VectorType>() ? type.cast<VectorType>().getRank() : 0; 1260 }; 1261 unsigned broadcastSrcRank = getRank(source.getType()); 1262 unsigned extractResultRank = getRank(extractOp.getType()); 1263 if (extractResultRank < broadcastSrcRank) { 1264 auto extractPos = extractVector<int64_t>(extractOp.position()); 1265 unsigned rankDiff = broadcastSrcRank - extractResultRank; 1266 extractPos.erase( 1267 extractPos.begin(), 1268 std::next(extractPos.begin(), extractPos.size() - rankDiff)); 1269 extractOp.setOperand(source); 1270 // OpBuilder is only used as a helper to build an I64ArrayAttr. 1271 OpBuilder b(extractOp.getContext()); 1272 extractOp->setAttr(ExtractOp::getPositionAttrStrName(), 1273 b.getI64ArrayAttr(extractPos)); 1274 return extractOp.getResult(); 1275 } 1276 return Value(); 1277 } 1278 1279 // Fold extractOp with source coming from ShapeCast op. 1280 static Value foldExtractFromShapeCast(ExtractOp extractOp) { 1281 auto shapeCastOp = extractOp.vector().getDefiningOp<vector::ShapeCastOp>(); 1282 if (!shapeCastOp) 1283 return Value(); 1284 // Get the nth dimension size starting from lowest dimension. 1285 auto getDimReverse = [](VectorType type, int64_t n) { 1286 return type.getShape().take_back(n + 1).front(); 1287 }; 1288 int64_t destinationRank = 1289 extractOp.getType().isa<VectorType>() 1290 ? extractOp.getType().cast<VectorType>().getRank() 1291 : 0; 1292 if (destinationRank > shapeCastOp.getSourceVectorType().getRank()) 1293 return Value(); 1294 if (destinationRank > 0) { 1295 auto destinationType = extractOp.getResult().getType().cast<VectorType>(); 1296 for (int64_t i = 0; i < destinationRank; i++) { 1297 // The lowest dimension of of the destination must match the lowest 1298 // dimension of the shapecast op source. 1299 // TODO: This case could be support in a canonicalization pattern. 1300 if (getDimReverse(shapeCastOp.getSourceVectorType(), i) != 1301 getDimReverse(destinationType, i)) 1302 return Value(); 1303 } 1304 } 1305 // Extract the strides associated with the extract op vector source. Then use 1306 // this to calculate a linearized position for the extract. 1307 auto extractedPos = extractVector<int64_t>(extractOp.position()); 1308 std::reverse(extractedPos.begin(), extractedPos.end()); 1309 SmallVector<int64_t, 4> strides; 1310 int64_t stride = 1; 1311 for (int64_t i = 0, e = extractedPos.size(); i < e; i++) { 1312 strides.push_back(stride); 1313 stride *= getDimReverse(extractOp.getVectorType(), i + destinationRank); 1314 } 1315 1316 int64_t position = linearize(extractedPos, strides); 1317 // Then extract the strides associated to the shapeCast op vector source and 1318 // delinearize the position using those strides. 1319 SmallVector<int64_t, 4> newStrides; 1320 int64_t numDimension = 1321 shapeCastOp.getSourceVectorType().getRank() - destinationRank; 1322 stride = 1; 1323 for (int64_t i = 0; i < numDimension; i++) { 1324 newStrides.push_back(stride); 1325 stride *= 1326 getDimReverse(shapeCastOp.getSourceVectorType(), i + destinationRank); 1327 } 1328 std::reverse(newStrides.begin(), newStrides.end()); 1329 SmallVector<int64_t, 4> newPosition = delinearize(newStrides, position); 1330 // OpBuilder is only used as a helper to build an I64ArrayAttr. 1331 OpBuilder b(extractOp.getContext()); 1332 extractOp->setAttr(ExtractOp::getPositionAttrStrName(), 1333 b.getI64ArrayAttr(newPosition)); 1334 extractOp.setOperand(shapeCastOp.source()); 1335 return extractOp.getResult(); 1336 } 1337 1338 /// Fold an ExtractOp from ExtractStridedSliceOp. 1339 static Value foldExtractFromExtractStrided(ExtractOp extractOp) { 1340 auto extractStridedSliceOp = 1341 extractOp.vector().getDefiningOp<vector::ExtractStridedSliceOp>(); 1342 if (!extractStridedSliceOp) 1343 return Value(); 1344 // Return if 'extractStridedSliceOp' has non-unit strides. 1345 if (extractStridedSliceOp.hasNonUnitStrides()) 1346 return Value(); 1347 1348 // Trim offsets for dimensions fully extracted. 1349 auto sliceOffsets = extractVector<int64_t>(extractStridedSliceOp.offsets()); 1350 while (!sliceOffsets.empty()) { 1351 size_t lastOffset = sliceOffsets.size() - 1; 1352 if (sliceOffsets.back() != 0 || 1353 extractStridedSliceOp.getType().getDimSize(lastOffset) != 1354 extractStridedSliceOp.getVectorType().getDimSize(lastOffset)) 1355 break; 1356 sliceOffsets.pop_back(); 1357 } 1358 unsigned destinationRank = 0; 1359 if (auto vecType = extractOp.getType().dyn_cast<VectorType>()) 1360 destinationRank = vecType.getRank(); 1361 // The dimensions of the result need to be untouched by the 1362 // extractStridedSlice op. 1363 if (destinationRank > 1364 extractStridedSliceOp.getVectorType().getRank() - sliceOffsets.size()) 1365 return Value(); 1366 auto extractedPos = extractVector<int64_t>(extractOp.position()); 1367 assert(extractedPos.size() >= sliceOffsets.size()); 1368 for (size_t i = 0, e = sliceOffsets.size(); i < e; i++) 1369 extractedPos[i] = extractedPos[i] + sliceOffsets[i]; 1370 extractOp.vectorMutable().assign(extractStridedSliceOp.vector()); 1371 // OpBuilder is only used as a helper to build an I64ArrayAttr. 1372 OpBuilder b(extractOp.getContext()); 1373 extractOp->setAttr(ExtractOp::getPositionAttrStrName(), 1374 b.getI64ArrayAttr(extractedPos)); 1375 return extractOp.getResult(); 1376 } 1377 1378 /// Fold extract_op fed from a chain of insertStridedSlice ops. 1379 static Value foldExtractStridedOpFromInsertChain(ExtractOp op) { 1380 int64_t destinationRank = op.getType().isa<VectorType>() 1381 ? op.getType().cast<VectorType>().getRank() 1382 : 0; 1383 auto insertOp = op.vector().getDefiningOp<InsertStridedSliceOp>(); 1384 while (insertOp) { 1385 int64_t insertRankDiff = insertOp.getDestVectorType().getRank() - 1386 insertOp.getSourceVectorType().getRank(); 1387 if (destinationRank > insertOp.getSourceVectorType().getRank()) 1388 return Value(); 1389 auto insertOffsets = extractVector<int64_t>(insertOp.offsets()); 1390 auto extractOffsets = extractVector<int64_t>(op.position()); 1391 1392 if (llvm::any_of(insertOp.strides(), [](Attribute attr) { 1393 return attr.cast<IntegerAttr>().getInt() != 1; 1394 })) 1395 return Value(); 1396 bool disjoint = false; 1397 SmallVector<int64_t, 4> offsetDiffs; 1398 for (unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) { 1399 int64_t start = insertOffsets[dim]; 1400 int64_t size = 1401 (dim < insertRankDiff) 1402 ? 1 1403 : insertOp.getSourceVectorType().getDimSize(dim - insertRankDiff); 1404 int64_t end = start + size; 1405 int64_t offset = extractOffsets[dim]; 1406 // Check if the start of the extract offset is in the interval inserted. 1407 if (start <= offset && offset < end) { 1408 if (dim >= insertRankDiff) 1409 offsetDiffs.push_back(offset - start); 1410 continue; 1411 } 1412 disjoint = true; 1413 break; 1414 } 1415 // The extract element chunk overlap with the vector inserted. 1416 if (!disjoint) { 1417 // If any of the inner dimensions are only partially inserted we have a 1418 // partial overlap. 1419 int64_t srcRankDiff = 1420 insertOp.getSourceVectorType().getRank() - destinationRank; 1421 for (int64_t i = 0; i < destinationRank; i++) { 1422 if (insertOp.getSourceVectorType().getDimSize(i + srcRankDiff) != 1423 insertOp.getDestVectorType().getDimSize(i + srcRankDiff + 1424 insertRankDiff)) 1425 return Value(); 1426 } 1427 op.vectorMutable().assign(insertOp.source()); 1428 // OpBuilder is only used as a helper to build an I64ArrayAttr. 1429 OpBuilder b(op.getContext()); 1430 op->setAttr(ExtractOp::getPositionAttrStrName(), 1431 b.getI64ArrayAttr(offsetDiffs)); 1432 return op.getResult(); 1433 } 1434 // If the chunk extracted is disjoint from the chunk inserted, keep 1435 // looking in the insert chain. 1436 insertOp = insertOp.dest().getDefiningOp<InsertStridedSliceOp>(); 1437 } 1438 return Value(); 1439 } 1440 1441 OpFoldResult ExtractOp::fold(ArrayRef<Attribute>) { 1442 if (position().empty()) 1443 return vector(); 1444 if (succeeded(foldExtractOpFromExtractChain(*this))) 1445 return getResult(); 1446 if (auto res = ExtractFromInsertTransposeChainState(*this).fold()) 1447 return res; 1448 if (auto res = foldExtractFromBroadcast(*this)) 1449 return res; 1450 if (auto res = foldExtractFromShapeCast(*this)) 1451 return res; 1452 if (auto val = foldExtractFromExtractStrided(*this)) 1453 return val; 1454 if (auto val = foldExtractStridedOpFromInsertChain(*this)) 1455 return val; 1456 return OpFoldResult(); 1457 } 1458 1459 namespace { 1460 1461 // Pattern to rewrite a ExtractOp(Broadcast) -> Broadcast. 1462 class ExtractOpFromBroadcast final : public OpRewritePattern<ExtractOp> { 1463 public: 1464 using OpRewritePattern<ExtractOp>::OpRewritePattern; 1465 1466 LogicalResult matchAndRewrite(ExtractOp extractOp, 1467 PatternRewriter &rewriter) const override { 1468 Operation *defOp = extractOp.vector().getDefiningOp(); 1469 if (!defOp || !isa<vector::BroadcastOp, SplatOp>(defOp)) 1470 return failure(); 1471 Value source = defOp->getOperand(0); 1472 if (extractOp.getType() == source.getType()) 1473 return failure(); 1474 auto getRank = [](Type type) { 1475 return type.isa<VectorType>() ? type.cast<VectorType>().getRank() : 0; 1476 }; 1477 unsigned broadcastSrcRank = getRank(source.getType()); 1478 unsigned extractResultRank = getRank(extractOp.getType()); 1479 // We only consider the case where the rank of the source is smaller than 1480 // the rank of the extract dst. The other cases are handled in the folding 1481 // patterns. 1482 if (extractResultRank <= broadcastSrcRank) 1483 return failure(); 1484 rewriter.replaceOpWithNewOp<vector::BroadcastOp>( 1485 extractOp, extractOp.getType(), source); 1486 return success(); 1487 } 1488 }; 1489 1490 // Pattern to rewrite a ExtractOp(splat ConstantOp) -> ConstantOp. 1491 class ExtractOpConstantFolder final : public OpRewritePattern<ExtractOp> { 1492 public: 1493 using OpRewritePattern<ExtractOp>::OpRewritePattern; 1494 1495 LogicalResult matchAndRewrite(ExtractOp extractOp, 1496 PatternRewriter &rewriter) const override { 1497 // Return if 'extractStridedSliceOp' operand is not defined by a 1498 // ConstantOp. 1499 auto constantOp = extractOp.vector().getDefiningOp<arith::ConstantOp>(); 1500 if (!constantOp) 1501 return failure(); 1502 auto dense = constantOp.getValue().dyn_cast<SplatElementsAttr>(); 1503 if (!dense) 1504 return failure(); 1505 Attribute newAttr = dense.getSplatValue<Attribute>(); 1506 if (auto vecDstType = extractOp.getType().dyn_cast<VectorType>()) 1507 newAttr = DenseElementsAttr::get(vecDstType, newAttr); 1508 rewriter.replaceOpWithNewOp<arith::ConstantOp>(extractOp, newAttr); 1509 return success(); 1510 } 1511 }; 1512 1513 } // namespace 1514 1515 void ExtractOp::getCanonicalizationPatterns(RewritePatternSet &results, 1516 MLIRContext *context) { 1517 results.add<ExtractOpConstantFolder, ExtractOpFromBroadcast>(context); 1518 } 1519 1520 static void populateFromInt64AttrArray(ArrayAttr arrayAttr, 1521 SmallVectorImpl<int64_t> &results) { 1522 for (auto attr : arrayAttr) 1523 results.push_back(attr.cast<IntegerAttr>().getInt()); 1524 } 1525 1526 //===----------------------------------------------------------------------===// 1527 // ExtractMapOp 1528 //===----------------------------------------------------------------------===// 1529 1530 void ExtractMapOp::build(OpBuilder &builder, OperationState &result, 1531 Value vector, ValueRange ids, 1532 ArrayRef<int64_t> multiplicity, 1533 AffineMap permutationMap) { 1534 assert(ids.size() == multiplicity.size() && 1535 ids.size() == permutationMap.getNumResults()); 1536 assert(permutationMap.isProjectedPermutation()); 1537 VectorType type = vector.getType().cast<VectorType>(); 1538 SmallVector<int64_t, 4> newShape(type.getShape().begin(), 1539 type.getShape().end()); 1540 for (unsigned i = 0, e = permutationMap.getNumResults(); i < e; i++) { 1541 AffineExpr expr = permutationMap.getResult(i); 1542 auto dim = expr.cast<AffineDimExpr>(); 1543 newShape[dim.getPosition()] = newShape[dim.getPosition()] / multiplicity[i]; 1544 } 1545 VectorType resultType = VectorType::get(newShape, type.getElementType()); 1546 ExtractMapOp::build(builder, result, resultType, vector, ids); 1547 } 1548 1549 LogicalResult ExtractMapOp::verify() { 1550 if (getSourceVectorType().getRank() != getResultType().getRank()) 1551 return emitOpError("expected source and destination vectors of same rank"); 1552 unsigned numId = 0; 1553 for (unsigned i = 0, e = getSourceVectorType().getRank(); i < e; ++i) { 1554 if (getSourceVectorType().getDimSize(i) % getResultType().getDimSize(i) != 1555 0) 1556 return emitOpError("source vector dimensions must be a multiple of " 1557 "destination vector dimensions"); 1558 if (getSourceVectorType().getDimSize(i) != getResultType().getDimSize(i)) 1559 numId++; 1560 } 1561 if (numId != ids().size()) 1562 return emitOpError("expected number of ids must match the number of " 1563 "dimensions distributed"); 1564 return success(); 1565 } 1566 1567 OpFoldResult ExtractMapOp::fold(ArrayRef<Attribute> operands) { 1568 auto insert = vector().getDefiningOp<vector::InsertMapOp>(); 1569 if (insert == nullptr || getType() != insert.vector().getType() || 1570 ids() != insert.ids()) 1571 return {}; 1572 return insert.vector(); 1573 } 1574 1575 void ExtractMapOp::getMultiplicity(SmallVectorImpl<int64_t> &multiplicity) { 1576 assert(multiplicity.empty()); 1577 for (unsigned i = 0, e = getSourceVectorType().getRank(); i < e; i++) { 1578 if (getSourceVectorType().getDimSize(i) != getResultType().getDimSize(i)) 1579 multiplicity.push_back(getSourceVectorType().getDimSize(i) / 1580 getResultType().getDimSize(i)); 1581 } 1582 } 1583 1584 template <typename MapOp> 1585 AffineMap calculateImplicitMap(MapOp op) { 1586 SmallVector<AffineExpr, 4> perm; 1587 // Check which dimension have a multiplicity greater than 1 and associated 1588 // them to the IDs in order. 1589 for (unsigned i = 0, e = op.getSourceVectorType().getRank(); i < e; i++) { 1590 if (op.getSourceVectorType().getDimSize(i) != 1591 op.getResultType().getDimSize(i)) 1592 perm.push_back(getAffineDimExpr(i, op.getContext())); 1593 } 1594 auto map = AffineMap::get(op.getSourceVectorType().getRank(), 0, perm, 1595 op.getContext()); 1596 return map; 1597 } 1598 1599 AffineMap ExtractMapOp::map() { return calculateImplicitMap(*this); } 1600 1601 //===----------------------------------------------------------------------===// 1602 // FmaOp 1603 //===----------------------------------------------------------------------===// 1604 1605 Optional<SmallVector<int64_t, 4>> FMAOp::getShapeForUnroll() { 1606 return llvm::to_vector<4>(getVectorType().getShape()); 1607 } 1608 1609 //===----------------------------------------------------------------------===// 1610 // BroadcastOp 1611 //===----------------------------------------------------------------------===// 1612 1613 BroadcastableToResult 1614 mlir::vector::isBroadcastableTo(Type srcType, VectorType dstVectorType, 1615 std::pair<int, int> *mismatchingDims) { 1616 // Broadcast scalar to vector of the same element type. 1617 if (srcType.isIntOrIndexOrFloat() && dstVectorType && 1618 getElementTypeOrSelf(srcType) == getElementTypeOrSelf(dstVectorType)) 1619 return BroadcastableToResult::Success; 1620 // From now on, only vectors broadcast. 1621 VectorType srcVectorType = srcType.dyn_cast<VectorType>(); 1622 if (!srcVectorType) 1623 return BroadcastableToResult::SourceTypeNotAVector; 1624 1625 int64_t srcRank = srcVectorType.getRank(); 1626 int64_t dstRank = dstVectorType.getRank(); 1627 if (srcRank > dstRank) 1628 return BroadcastableToResult::SourceRankHigher; 1629 // Source has an exact match or singleton value for all trailing dimensions 1630 // (all leading dimensions are simply duplicated). 1631 int64_t lead = dstRank - srcRank; 1632 for (int64_t r = 0; r < srcRank; ++r) { 1633 int64_t srcDim = srcVectorType.getDimSize(r); 1634 int64_t dstDim = dstVectorType.getDimSize(lead + r); 1635 if (srcDim != 1 && srcDim != dstDim) { 1636 if (mismatchingDims) { 1637 mismatchingDims->first = srcDim; 1638 mismatchingDims->second = dstDim; 1639 } 1640 return BroadcastableToResult::DimensionMismatch; 1641 } 1642 } 1643 1644 return BroadcastableToResult::Success; 1645 } 1646 1647 LogicalResult BroadcastOp::verify() { 1648 std::pair<int, int> mismatchingDims; 1649 BroadcastableToResult res = 1650 isBroadcastableTo(getSourceType(), getVectorType(), &mismatchingDims); 1651 if (res == BroadcastableToResult::Success) 1652 return success(); 1653 if (res == BroadcastableToResult::SourceRankHigher) 1654 return emitOpError("source rank higher than destination rank"); 1655 if (res == BroadcastableToResult::DimensionMismatch) 1656 return emitOpError("dimension mismatch (") 1657 << mismatchingDims.first << " vs. " << mismatchingDims.second << ")"; 1658 if (res == BroadcastableToResult::SourceTypeNotAVector) 1659 return emitOpError("source type is not a vector"); 1660 llvm_unreachable("unexpected vector.broadcast op error"); 1661 } 1662 1663 OpFoldResult BroadcastOp::fold(ArrayRef<Attribute> operands) { 1664 if (getSourceType() == getVectorType()) 1665 return source(); 1666 if (!operands[0]) 1667 return {}; 1668 auto vectorType = getVectorType(); 1669 if (operands[0].getType().isIntOrIndexOrFloat()) 1670 return DenseElementsAttr::get(vectorType, operands[0]); 1671 if (auto attr = operands[0].dyn_cast<SplatElementsAttr>()) 1672 return DenseElementsAttr::get(vectorType, attr.getSplatValue<Attribute>()); 1673 return {}; 1674 } 1675 1676 namespace { 1677 1678 // Fold broadcast1(broadcast2(x)) into broadcast1(x). 1679 struct BroadcastFolder : public OpRewritePattern<BroadcastOp> { 1680 using OpRewritePattern<BroadcastOp>::OpRewritePattern; 1681 1682 LogicalResult matchAndRewrite(BroadcastOp broadcastOp, 1683 PatternRewriter &rewriter) const override { 1684 auto srcBroadcast = broadcastOp.source().getDefiningOp<BroadcastOp>(); 1685 if (!srcBroadcast) 1686 return failure(); 1687 rewriter.replaceOpWithNewOp<BroadcastOp>( 1688 broadcastOp, broadcastOp.getVectorType(), srcBroadcast.source()); 1689 return success(); 1690 } 1691 }; 1692 } // namespace 1693 1694 void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &results, 1695 MLIRContext *context) { 1696 // BroadcastToShapeCast is not a default canonicalization, it is opt-in by 1697 // calling `populateCastAwayVectorLeadingOneDimPatterns` 1698 results.add<BroadcastFolder>(context); 1699 } 1700 1701 //===----------------------------------------------------------------------===// 1702 // ShuffleOp 1703 //===----------------------------------------------------------------------===// 1704 1705 void ShuffleOp::build(OpBuilder &builder, OperationState &result, Value v1, 1706 Value v2, ArrayRef<int64_t> mask) { 1707 build(builder, result, v1, v2, getVectorSubscriptAttr(builder, mask)); 1708 } 1709 1710 LogicalResult ShuffleOp::verify() { 1711 VectorType resultType = getVectorType(); 1712 VectorType v1Type = getV1VectorType(); 1713 VectorType v2Type = getV2VectorType(); 1714 // Verify ranks. 1715 int64_t resRank = resultType.getRank(); 1716 int64_t v1Rank = v1Type.getRank(); 1717 int64_t v2Rank = v2Type.getRank(); 1718 if (resRank != v1Rank || v1Rank != v2Rank) 1719 return emitOpError("rank mismatch"); 1720 // Verify all but leading dimension sizes. 1721 for (int64_t r = 1; r < v1Rank; ++r) { 1722 int64_t resDim = resultType.getDimSize(r); 1723 int64_t v1Dim = v1Type.getDimSize(r); 1724 int64_t v2Dim = v2Type.getDimSize(r); 1725 if (resDim != v1Dim || v1Dim != v2Dim) 1726 return emitOpError("dimension mismatch"); 1727 } 1728 // Verify mask length. 1729 auto maskAttr = mask().getValue(); 1730 int64_t maskLength = maskAttr.size(); 1731 if (maskLength <= 0) 1732 return emitOpError("invalid mask length"); 1733 if (maskLength != resultType.getDimSize(0)) 1734 return emitOpError("mask length mismatch"); 1735 // Verify all indices. 1736 int64_t indexSize = v1Type.getDimSize(0) + v2Type.getDimSize(0); 1737 for (const auto &en : llvm::enumerate(maskAttr)) { 1738 auto attr = en.value().dyn_cast<IntegerAttr>(); 1739 if (!attr || attr.getInt() < 0 || attr.getInt() >= indexSize) 1740 return emitOpError("mask index #") << (en.index() + 1) << " out of range"; 1741 } 1742 return success(); 1743 } 1744 1745 LogicalResult 1746 ShuffleOp::inferReturnTypes(MLIRContext *, Optional<Location>, 1747 ValueRange operands, DictionaryAttr attributes, 1748 RegionRange, 1749 SmallVectorImpl<Type> &inferredReturnTypes) { 1750 ShuffleOp::Adaptor op(operands, attributes); 1751 auto v1Type = op.v1().getType().cast<VectorType>(); 1752 // Construct resulting type: leading dimension matches mask length, 1753 // all trailing dimensions match the operands. 1754 SmallVector<int64_t, 4> shape; 1755 shape.reserve(v1Type.getRank()); 1756 shape.push_back(std::max<size_t>(1, op.mask().size())); 1757 llvm::append_range(shape, v1Type.getShape().drop_front()); 1758 inferredReturnTypes.push_back( 1759 VectorType::get(shape, v1Type.getElementType())); 1760 return success(); 1761 } 1762 1763 OpFoldResult vector::ShuffleOp::fold(ArrayRef<Attribute> operands) { 1764 Attribute lhs = operands.front(), rhs = operands.back(); 1765 if (!lhs || !rhs) 1766 return {}; 1767 1768 auto lhsType = lhs.getType().cast<VectorType>(); 1769 // Only support 1-D for now to avoid complicated n-D DenseElementsAttr 1770 // manipulation. 1771 if (lhsType.getRank() != 1) 1772 return {}; 1773 int64_t lhsSize = lhsType.getDimSize(0); 1774 1775 SmallVector<Attribute> results; 1776 auto lhsElements = lhs.cast<DenseElementsAttr>().getValues<Attribute>(); 1777 auto rhsElements = rhs.cast<DenseElementsAttr>().getValues<Attribute>(); 1778 for (const auto &index : this->mask().getAsValueRange<IntegerAttr>()) { 1779 int64_t i = index.getZExtValue(); 1780 if (i >= lhsSize) { 1781 results.push_back(rhsElements[i - lhsSize]); 1782 } else { 1783 results.push_back(lhsElements[i]); 1784 } 1785 } 1786 1787 return DenseElementsAttr::get(getVectorType(), results); 1788 } 1789 1790 //===----------------------------------------------------------------------===// 1791 // InsertElementOp 1792 //===----------------------------------------------------------------------===// 1793 1794 void InsertElementOp::build(OpBuilder &builder, OperationState &result, 1795 Value source, Value dest) { 1796 build(builder, result, source, dest, {}); 1797 } 1798 1799 LogicalResult InsertElementOp::verify() { 1800 auto dstVectorType = getDestVectorType(); 1801 if (dstVectorType.getRank() == 0) { 1802 if (position()) 1803 return emitOpError("expected position to be empty with 0-D vector"); 1804 return success(); 1805 } 1806 if (dstVectorType.getRank() != 1) 1807 return emitOpError("unexpected >1 vector rank"); 1808 if (!position()) 1809 return emitOpError("expected position for 1-D vector"); 1810 return success(); 1811 } 1812 1813 //===----------------------------------------------------------------------===// 1814 // InsertOp 1815 //===----------------------------------------------------------------------===// 1816 1817 void InsertOp::build(OpBuilder &builder, OperationState &result, Value source, 1818 Value dest, ArrayRef<int64_t> position) { 1819 result.addOperands({source, dest}); 1820 auto positionAttr = getVectorSubscriptAttr(builder, position); 1821 result.addTypes(dest.getType()); 1822 result.addAttribute(getPositionAttrStrName(), positionAttr); 1823 } 1824 1825 // Convenience builder which assumes the values are constant indices. 1826 void InsertOp::build(OpBuilder &builder, OperationState &result, Value source, 1827 Value dest, ValueRange position) { 1828 SmallVector<int64_t, 4> positionConstants = 1829 llvm::to_vector<4>(llvm::map_range(position, [](Value pos) { 1830 return pos.getDefiningOp<arith::ConstantIndexOp>().value(); 1831 })); 1832 build(builder, result, source, dest, positionConstants); 1833 } 1834 1835 LogicalResult InsertOp::verify() { 1836 auto positionAttr = position().getValue(); 1837 auto destVectorType = getDestVectorType(); 1838 if (positionAttr.size() > static_cast<unsigned>(destVectorType.getRank())) 1839 return emitOpError( 1840 "expected position attribute of rank smaller than dest vector rank"); 1841 auto srcVectorType = getSourceType().dyn_cast<VectorType>(); 1842 if (srcVectorType && 1843 (static_cast<unsigned>(srcVectorType.getRank()) + positionAttr.size() != 1844 static_cast<unsigned>(destVectorType.getRank()))) 1845 return emitOpError("expected position attribute rank + source rank to " 1846 "match dest vector rank"); 1847 if (!srcVectorType && 1848 (positionAttr.size() != static_cast<unsigned>(destVectorType.getRank()))) 1849 return emitOpError( 1850 "expected position attribute rank to match the dest vector rank"); 1851 for (const auto &en : llvm::enumerate(positionAttr)) { 1852 auto attr = en.value().dyn_cast<IntegerAttr>(); 1853 if (!attr || attr.getInt() < 0 || 1854 attr.getInt() >= destVectorType.getDimSize(en.index())) 1855 return emitOpError("expected position attribute #") 1856 << (en.index() + 1) 1857 << " to be a non-negative integer smaller than the corresponding " 1858 "dest vector dimension"; 1859 } 1860 return success(); 1861 } 1862 1863 namespace { 1864 1865 // If insertOp is only inserting unit dimensions it can be transformed to a 1866 // broadcast. 1867 class InsertToBroadcast final : public OpRewritePattern<InsertOp> { 1868 public: 1869 using OpRewritePattern<InsertOp>::OpRewritePattern; 1870 1871 LogicalResult matchAndRewrite(InsertOp insertOp, 1872 PatternRewriter &rewriter) const override { 1873 auto srcVecType = insertOp.getSourceType().dyn_cast<VectorType>(); 1874 if (!srcVecType || insertOp.getDestVectorType().getNumElements() != 1875 srcVecType.getNumElements()) 1876 return failure(); 1877 rewriter.replaceOpWithNewOp<BroadcastOp>( 1878 insertOp, insertOp.getDestVectorType(), insertOp.source()); 1879 return success(); 1880 } 1881 }; 1882 1883 } // namespace 1884 1885 void InsertOp::getCanonicalizationPatterns(RewritePatternSet &results, 1886 MLIRContext *context) { 1887 results.add<InsertToBroadcast, BroadcastFolder>(context); 1888 } 1889 1890 // Eliminates insert operations that produce values identical to their source 1891 // value. This happens when the source and destination vectors have identical 1892 // sizes. 1893 OpFoldResult vector::InsertOp::fold(ArrayRef<Attribute> operands) { 1894 if (position().empty()) 1895 return source(); 1896 return {}; 1897 } 1898 1899 //===----------------------------------------------------------------------===// 1900 // InsertMapOp 1901 //===----------------------------------------------------------------------===// 1902 1903 LogicalResult InsertMapOp::verify() { 1904 if (getSourceVectorType().getRank() != getResultType().getRank()) 1905 return emitOpError("expected source and destination vectors of same rank"); 1906 unsigned numId = 0; 1907 for (unsigned i = 0, e = getResultType().getRank(); i < e; i++) { 1908 if (getResultType().getDimSize(i) % getSourceVectorType().getDimSize(i) != 1909 0) 1910 return emitOpError( 1911 "destination vector size must be a multiple of source vector size"); 1912 if (getResultType().getDimSize(i) != getSourceVectorType().getDimSize(i)) 1913 numId++; 1914 } 1915 if (numId != ids().size()) 1916 return emitOpError("expected number of ids must match the number of " 1917 "dimensions distributed"); 1918 return success(); 1919 } 1920 1921 AffineMap InsertMapOp::map() { return calculateImplicitMap(*this); } 1922 1923 //===----------------------------------------------------------------------===// 1924 // InsertStridedSliceOp 1925 //===----------------------------------------------------------------------===// 1926 1927 void InsertStridedSliceOp::build(OpBuilder &builder, OperationState &result, 1928 Value source, Value dest, 1929 ArrayRef<int64_t> offsets, 1930 ArrayRef<int64_t> strides) { 1931 result.addOperands({source, dest}); 1932 auto offsetsAttr = getVectorSubscriptAttr(builder, offsets); 1933 auto stridesAttr = getVectorSubscriptAttr(builder, strides); 1934 result.addTypes(dest.getType()); 1935 result.addAttribute(getOffsetsAttrStrName(), offsetsAttr); 1936 result.addAttribute(getStridesAttrStrName(), stridesAttr); 1937 } 1938 1939 // TODO: Should be moved to Tablegen Confined attributes. 1940 template <typename OpType> 1941 static LogicalResult isIntegerArrayAttrSmallerThanShape(OpType op, 1942 ArrayAttr arrayAttr, 1943 ArrayRef<int64_t> shape, 1944 StringRef attrName) { 1945 if (arrayAttr.size() > shape.size()) 1946 return op.emitOpError("expected ") 1947 << attrName << " attribute of rank smaller than vector rank"; 1948 return success(); 1949 } 1950 1951 // Returns true if all integers in `arrayAttr` are in the half-open [min, max} 1952 // interval. If `halfOpen` is true then the admissible interval is [min, max). 1953 // Otherwise, the admissible interval is [min, max]. 1954 template <typename OpType> 1955 static LogicalResult 1956 isIntegerArrayAttrConfinedToRange(OpType op, ArrayAttr arrayAttr, int64_t min, 1957 int64_t max, StringRef attrName, 1958 bool halfOpen = true) { 1959 for (auto attr : arrayAttr) { 1960 auto val = attr.cast<IntegerAttr>().getInt(); 1961 auto upper = max; 1962 if (!halfOpen) 1963 upper += 1; 1964 if (val < min || val >= upper) 1965 return op.emitOpError("expected ") << attrName << " to be confined to [" 1966 << min << ", " << upper << ")"; 1967 } 1968 return success(); 1969 } 1970 1971 // Returns true if all integers in `arrayAttr` are in the half-open [min, max} 1972 // interval. If `halfOpen` is true then the admissible interval is [min, max). 1973 // Otherwise, the admissible interval is [min, max]. 1974 template <typename OpType> 1975 static LogicalResult 1976 isIntegerArrayAttrConfinedToShape(OpType op, ArrayAttr arrayAttr, 1977 ArrayRef<int64_t> shape, StringRef attrName, 1978 bool halfOpen = true, int64_t min = 0) { 1979 assert(arrayAttr.size() <= shape.size()); 1980 unsigned index = 0; 1981 for (auto it : llvm::zip(arrayAttr, shape)) { 1982 auto val = std::get<0>(it).cast<IntegerAttr>().getInt(); 1983 auto max = std::get<1>(it); 1984 if (!halfOpen) 1985 max += 1; 1986 if (val < min || val >= max) 1987 return op.emitOpError("expected ") 1988 << attrName << " dimension " << index << " to be confined to [" 1989 << min << ", " << max << ")"; 1990 ++index; 1991 } 1992 return success(); 1993 } 1994 1995 // Returns true if all integers in `arrayAttr` are in the interval [min, max}. 1996 // interval. If `halfOpen` is true then the admissible interval is [min, max). 1997 // Otherwise, the admissible interval is [min, max]. 1998 template <typename OpType> 1999 static LogicalResult isSumOfIntegerArrayAttrConfinedToShape( 2000 OpType op, ArrayAttr arrayAttr1, ArrayAttr arrayAttr2, 2001 ArrayRef<int64_t> shape, StringRef attrName1, StringRef attrName2, 2002 bool halfOpen = true, int64_t min = 1) { 2003 assert(arrayAttr1.size() <= shape.size()); 2004 assert(arrayAttr2.size() <= shape.size()); 2005 unsigned index = 0; 2006 for (auto it : llvm::zip(arrayAttr1, arrayAttr2, shape)) { 2007 auto val1 = std::get<0>(it).cast<IntegerAttr>().getInt(); 2008 auto val2 = std::get<1>(it).cast<IntegerAttr>().getInt(); 2009 auto max = std::get<2>(it); 2010 if (!halfOpen) 2011 max += 1; 2012 if (val1 + val2 < 0 || val1 + val2 >= max) 2013 return op.emitOpError("expected sum(") 2014 << attrName1 << ", " << attrName2 << ") dimension " << index 2015 << " to be confined to [" << min << ", " << max << ")"; 2016 ++index; 2017 } 2018 return success(); 2019 } 2020 2021 static ArrayAttr makeI64ArrayAttr(ArrayRef<int64_t> values, 2022 MLIRContext *context) { 2023 auto attrs = llvm::map_range(values, [context](int64_t v) -> Attribute { 2024 return IntegerAttr::get(IntegerType::get(context, 64), APInt(64, v)); 2025 }); 2026 return ArrayAttr::get(context, llvm::to_vector<8>(attrs)); 2027 } 2028 2029 LogicalResult InsertStridedSliceOp::verify() { 2030 auto sourceVectorType = getSourceVectorType(); 2031 auto destVectorType = getDestVectorType(); 2032 auto offsets = offsetsAttr(); 2033 auto strides = stridesAttr(); 2034 if (offsets.size() != static_cast<unsigned>(destVectorType.getRank())) 2035 return emitOpError( 2036 "expected offsets of same size as destination vector rank"); 2037 if (strides.size() != static_cast<unsigned>(sourceVectorType.getRank())) 2038 return emitOpError("expected strides of same size as source vector rank"); 2039 if (sourceVectorType.getRank() > destVectorType.getRank()) 2040 return emitOpError( 2041 "expected source rank to be smaller than destination rank"); 2042 2043 auto sourceShape = sourceVectorType.getShape(); 2044 auto destShape = destVectorType.getShape(); 2045 SmallVector<int64_t, 4> sourceShapeAsDestShape( 2046 destShape.size() - sourceShape.size(), 0); 2047 sourceShapeAsDestShape.append(sourceShape.begin(), sourceShape.end()); 2048 auto offName = InsertStridedSliceOp::getOffsetsAttrName(); 2049 auto stridesName = InsertStridedSliceOp::getStridesAttrName(); 2050 if (failed(isIntegerArrayAttrConfinedToShape(*this, offsets, destShape, 2051 offName)) || 2052 failed(isIntegerArrayAttrConfinedToRange(*this, strides, 1, 1, 2053 stridesName, 2054 /*halfOpen=*/false)) || 2055 failed(isSumOfIntegerArrayAttrConfinedToShape( 2056 *this, offsets, 2057 makeI64ArrayAttr(sourceShapeAsDestShape, getContext()), destShape, 2058 offName, "source vector shape", 2059 /*halfOpen=*/false, /*min=*/1))) 2060 return failure(); 2061 2062 return success(); 2063 } 2064 2065 OpFoldResult InsertStridedSliceOp::fold(ArrayRef<Attribute> operands) { 2066 if (getSourceVectorType() == getDestVectorType()) 2067 return source(); 2068 return {}; 2069 } 2070 2071 //===----------------------------------------------------------------------===// 2072 // OuterProductOp 2073 //===----------------------------------------------------------------------===// 2074 2075 /// Build an op without mask, use the type of `acc` as the return type. 2076 void OuterProductOp::build(OpBuilder &builder, OperationState &result, 2077 Value lhs, Value rhs, Value acc) { 2078 result.addOperands({lhs, rhs, acc}); 2079 result.addTypes(acc.getType()); 2080 } 2081 2082 void OuterProductOp::print(OpAsmPrinter &p) { 2083 p << " " << lhs() << ", " << rhs(); 2084 if (!acc().empty()) { 2085 p << ", " << acc(); 2086 p.printOptionalAttrDict((*this)->getAttrs()); 2087 } 2088 p << " : " << lhs().getType() << ", " << rhs().getType(); 2089 } 2090 2091 ParseResult OuterProductOp::parse(OpAsmParser &parser, OperationState &result) { 2092 SmallVector<OpAsmParser::OperandType, 3> operandsInfo; 2093 Type tLHS, tRHS; 2094 if (parser.parseOperandList(operandsInfo) || 2095 parser.parseOptionalAttrDict(result.attributes) || 2096 parser.parseColonType(tLHS) || parser.parseComma() || 2097 parser.parseType(tRHS)) 2098 return failure(); 2099 if (operandsInfo.size() < 2) 2100 return parser.emitError(parser.getNameLoc(), 2101 "expected at least 2 operands"); 2102 VectorType vLHS = tLHS.dyn_cast<VectorType>(); 2103 VectorType vRHS = tRHS.dyn_cast<VectorType>(); 2104 if (!vLHS) 2105 return parser.emitError(parser.getNameLoc(), 2106 "expected vector type for operand #1"); 2107 VectorType resType = 2108 vRHS ? VectorType::get({vLHS.getDimSize(0), vRHS.getDimSize(0)}, 2109 vLHS.getElementType()) 2110 : VectorType::get({vLHS.getDimSize(0)}, vLHS.getElementType()); 2111 2112 if (!result.attributes.get(OuterProductOp::getKindAttrStrName())) { 2113 result.attributes.append( 2114 OuterProductOp::getKindAttrStrName(), 2115 CombiningKindAttr::get(OuterProductOp::getDefaultKind(), 2116 result.getContext())); 2117 } 2118 2119 return failure( 2120 parser.resolveOperand(operandsInfo[0], tLHS, result.operands) || 2121 parser.resolveOperand(operandsInfo[1], tRHS, result.operands) || 2122 (operandsInfo.size() > 2 && 2123 parser.resolveOperand(operandsInfo[2], resType, result.operands)) || 2124 parser.addTypeToList(resType, result.types)); 2125 } 2126 2127 LogicalResult OuterProductOp::verify() { 2128 Type tRHS = getOperandTypeRHS(); 2129 VectorType vLHS = getOperandVectorTypeLHS(), 2130 vRHS = tRHS.dyn_cast<VectorType>(), 2131 vACC = getOperandVectorTypeACC(), vRES = getVectorType(); 2132 2133 if (vLHS.getRank() != 1) 2134 return emitOpError("expected 1-d vector for operand #1"); 2135 2136 if (vRHS) { 2137 // Proper OUTER operation. 2138 if (vRHS.getRank() != 1) 2139 return emitOpError("expected 1-d vector for operand #2"); 2140 if (vRES.getRank() != 2) 2141 return emitOpError("expected 2-d vector result"); 2142 if (vLHS.getDimSize(0) != vRES.getDimSize(0)) 2143 return emitOpError("expected #1 operand dim to match result dim #1"); 2144 if (vRHS.getDimSize(0) != vRES.getDimSize(1)) 2145 return emitOpError("expected #2 operand dim to match result dim #2"); 2146 } else { 2147 // An AXPY operation. 2148 if (vRES.getRank() != 1) 2149 return emitOpError("expected 1-d vector result"); 2150 if (vLHS.getDimSize(0) != vRES.getDimSize(0)) 2151 return emitOpError("expected #1 operand dim to match result dim #1"); 2152 } 2153 2154 if (vACC && vACC != vRES) 2155 return emitOpError("expected operand #3 of same type as result type"); 2156 2157 // Verify supported combining kind. 2158 if (!isSupportedCombiningKind(kind(), vRES.getElementType())) 2159 return emitOpError("unsupported outerproduct type"); 2160 2161 return success(); 2162 } 2163 2164 //===----------------------------------------------------------------------===// 2165 // ReshapeOp 2166 //===----------------------------------------------------------------------===// 2167 2168 LogicalResult ReshapeOp::verify() { 2169 // Verify that rank(numInputs/outputs) + numFixedVec dim matches vec rank. 2170 auto inputVectorType = getInputVectorType(); 2171 auto outputVectorType = getOutputVectorType(); 2172 int64_t inputShapeRank = getNumInputShapeSizes(); 2173 int64_t outputShapeRank = getNumOutputShapeSizes(); 2174 SmallVector<int64_t, 4> fixedVectorSizes; 2175 getFixedVectorSizes(fixedVectorSizes); 2176 int64_t numFixedVectorSizes = fixedVectorSizes.size(); 2177 2178 if (inputVectorType.getRank() != inputShapeRank + numFixedVectorSizes) 2179 return emitError("invalid input shape for vector type ") 2180 << inputVectorType; 2181 2182 if (outputVectorType.getRank() != outputShapeRank + numFixedVectorSizes) 2183 return emitError("invalid output shape for vector type ") 2184 << outputVectorType; 2185 2186 // Verify that the 'fixedVectorSizes' match an input/output vector shape 2187 // suffix. 2188 unsigned inputVectorRank = inputVectorType.getRank(); 2189 for (unsigned i = 0; i < numFixedVectorSizes; ++i) { 2190 unsigned index = inputVectorRank - numFixedVectorSizes - i; 2191 if (fixedVectorSizes[i] != inputVectorType.getShape()[index]) 2192 return emitError("fixed vector size must match input vector for dim ") 2193 << i; 2194 } 2195 2196 unsigned outputVectorRank = outputVectorType.getRank(); 2197 for (unsigned i = 0; i < numFixedVectorSizes; ++i) { 2198 unsigned index = outputVectorRank - numFixedVectorSizes - i; 2199 if (fixedVectorSizes[i] != outputVectorType.getShape()[index]) 2200 return emitError("fixed vector size must match output vector for dim ") 2201 << i; 2202 } 2203 2204 // If all shape operands are produced by constant ops, verify that product 2205 // of dimensions for input/output shape match. 2206 auto isDefByConstant = [](Value operand) { 2207 return isa_and_nonnull<arith::ConstantIndexOp>(operand.getDefiningOp()); 2208 }; 2209 if (llvm::all_of(input_shape(), isDefByConstant) && 2210 llvm::all_of(output_shape(), isDefByConstant)) { 2211 int64_t numInputElements = 1; 2212 for (auto operand : input_shape()) 2213 numInputElements *= 2214 cast<arith::ConstantIndexOp>(operand.getDefiningOp()).value(); 2215 int64_t numOutputElements = 1; 2216 for (auto operand : output_shape()) 2217 numOutputElements *= 2218 cast<arith::ConstantIndexOp>(operand.getDefiningOp()).value(); 2219 if (numInputElements != numOutputElements) 2220 return emitError("product of input and output shape sizes must match"); 2221 } 2222 return success(); 2223 } 2224 2225 void ReshapeOp::getFixedVectorSizes(SmallVectorImpl<int64_t> &results) { 2226 populateFromInt64AttrArray(fixed_vector_sizes(), results); 2227 } 2228 2229 //===----------------------------------------------------------------------===// 2230 // ExtractStridedSliceOp 2231 //===----------------------------------------------------------------------===// 2232 2233 // Inference works as follows: 2234 // 1. Add 'sizes' from prefix of dims in 'offsets'. 2235 // 2. Add sizes from 'vectorType' for remaining dims. 2236 static Type inferStridedSliceOpResultType(VectorType vectorType, 2237 ArrayAttr offsets, ArrayAttr sizes, 2238 ArrayAttr strides) { 2239 assert(offsets.size() == sizes.size() && offsets.size() == strides.size()); 2240 SmallVector<int64_t, 4> shape; 2241 shape.reserve(vectorType.getRank()); 2242 unsigned idx = 0; 2243 for (unsigned e = offsets.size(); idx < e; ++idx) 2244 shape.push_back(sizes[idx].cast<IntegerAttr>().getInt()); 2245 for (unsigned e = vectorType.getShape().size(); idx < e; ++idx) 2246 shape.push_back(vectorType.getShape()[idx]); 2247 2248 return VectorType::get(shape, vectorType.getElementType()); 2249 } 2250 2251 void ExtractStridedSliceOp::build(OpBuilder &builder, OperationState &result, 2252 Value source, ArrayRef<int64_t> offsets, 2253 ArrayRef<int64_t> sizes, 2254 ArrayRef<int64_t> strides) { 2255 result.addOperands(source); 2256 auto offsetsAttr = getVectorSubscriptAttr(builder, offsets); 2257 auto sizesAttr = getVectorSubscriptAttr(builder, sizes); 2258 auto stridesAttr = getVectorSubscriptAttr(builder, strides); 2259 result.addTypes( 2260 inferStridedSliceOpResultType(source.getType().cast<VectorType>(), 2261 offsetsAttr, sizesAttr, stridesAttr)); 2262 result.addAttribute(getOffsetsAttrStrName(), offsetsAttr); 2263 result.addAttribute(getSizesAttrStrName(), sizesAttr); 2264 result.addAttribute(getStridesAttrStrName(), stridesAttr); 2265 } 2266 2267 LogicalResult ExtractStridedSliceOp::verify() { 2268 auto type = getVectorType(); 2269 auto offsets = offsetsAttr(); 2270 auto sizes = sizesAttr(); 2271 auto strides = stridesAttr(); 2272 if (offsets.size() != sizes.size() || offsets.size() != strides.size()) 2273 return emitOpError("expected offsets, sizes and strides attributes of same size"); 2274 2275 auto shape = type.getShape(); 2276 auto offName = getOffsetsAttrName(); 2277 auto sizesName = getSizesAttrName(); 2278 auto stridesName = getStridesAttrName(); 2279 if (failed(isIntegerArrayAttrSmallerThanShape(*this, offsets, shape, offName)) || 2280 failed(isIntegerArrayAttrSmallerThanShape(*this, sizes, shape, sizesName)) || 2281 failed(isIntegerArrayAttrSmallerThanShape(*this, strides, shape, 2282 stridesName)) || 2283 failed(isIntegerArrayAttrConfinedToShape(*this, offsets, shape, offName)) || 2284 failed(isIntegerArrayAttrConfinedToShape(*this, sizes, shape, sizesName, 2285 /*halfOpen=*/false, 2286 /*min=*/1)) || 2287 failed(isIntegerArrayAttrConfinedToRange(*this, strides, 1, 1, stridesName, 2288 /*halfOpen=*/false)) || 2289 failed(isSumOfIntegerArrayAttrConfinedToShape(*this, offsets, sizes, shape, 2290 offName, sizesName, 2291 /*halfOpen=*/false))) 2292 return failure(); 2293 2294 auto resultType = 2295 inferStridedSliceOpResultType(getVectorType(), offsets, sizes, strides); 2296 if (getResult().getType() != resultType) 2297 return emitOpError("expected result type to be ") << resultType; 2298 2299 return success(); 2300 } 2301 2302 // When the source of ExtractStrided comes from a chain of InsertStrided ops try 2303 // to use the source of the InsertStrided ops if we can detect that the 2304 // extracted vector is a subset of one of the vector inserted. 2305 static LogicalResult 2306 foldExtractStridedOpFromInsertChain(ExtractStridedSliceOp op) { 2307 // Helper to extract integer out of ArrayAttr. 2308 auto getElement = [](ArrayAttr array, int idx) { 2309 return array[idx].cast<IntegerAttr>().getInt(); 2310 }; 2311 ArrayAttr extractOffsets = op.offsets(); 2312 ArrayAttr extractStrides = op.strides(); 2313 ArrayAttr extractSizes = op.sizes(); 2314 auto insertOp = op.vector().getDefiningOp<InsertStridedSliceOp>(); 2315 while (insertOp) { 2316 if (op.getVectorType().getRank() != 2317 insertOp.getSourceVectorType().getRank()) 2318 return failure(); 2319 ArrayAttr insertOffsets = insertOp.offsets(); 2320 ArrayAttr insertStrides = insertOp.strides(); 2321 // If the rank of extract is greater than the rank of insert, we are likely 2322 // extracting a partial chunk of the vector inserted. 2323 if (extractOffsets.size() > insertOffsets.size()) 2324 return failure(); 2325 bool patialoverlap = false; 2326 bool disjoint = false; 2327 SmallVector<int64_t, 4> offsetDiffs; 2328 for (unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) { 2329 if (getElement(extractStrides, dim) != getElement(insertStrides, dim)) 2330 return failure(); 2331 int64_t start = getElement(insertOffsets, dim); 2332 int64_t end = start + insertOp.getSourceVectorType().getDimSize(dim); 2333 int64_t offset = getElement(extractOffsets, dim); 2334 int64_t size = getElement(extractSizes, dim); 2335 // Check if the start of the extract offset is in the interval inserted. 2336 if (start <= offset && offset < end) { 2337 // If the extract interval overlaps but is not fully included we may 2338 // have a partial overlap that will prevent any folding. 2339 if (offset + size > end) 2340 patialoverlap = true; 2341 offsetDiffs.push_back(offset - start); 2342 continue; 2343 } 2344 disjoint = true; 2345 break; 2346 } 2347 // The extract element chunk is a subset of the insert element. 2348 if (!disjoint && !patialoverlap) { 2349 op.setOperand(insertOp.source()); 2350 // OpBuilder is only used as a helper to build an I64ArrayAttr. 2351 OpBuilder b(op.getContext()); 2352 op->setAttr(ExtractStridedSliceOp::getOffsetsAttrStrName(), 2353 b.getI64ArrayAttr(offsetDiffs)); 2354 return success(); 2355 } 2356 // If the chunk extracted is disjoint from the chunk inserted, keep looking 2357 // in the insert chain. 2358 if (disjoint) 2359 insertOp = insertOp.dest().getDefiningOp<InsertStridedSliceOp>(); 2360 else { 2361 // The extracted vector partially overlap the inserted vector, we cannot 2362 // fold. 2363 return failure(); 2364 } 2365 } 2366 return failure(); 2367 } 2368 2369 OpFoldResult ExtractStridedSliceOp::fold(ArrayRef<Attribute> operands) { 2370 if (getVectorType() == getResult().getType()) 2371 return vector(); 2372 if (succeeded(foldExtractStridedOpFromInsertChain(*this))) 2373 return getResult(); 2374 return {}; 2375 } 2376 2377 void ExtractStridedSliceOp::getOffsets(SmallVectorImpl<int64_t> &results) { 2378 populateFromInt64AttrArray(offsets(), results); 2379 } 2380 2381 namespace { 2382 2383 // Pattern to rewrite an ExtractStridedSliceOp(ConstantMaskOp) to 2384 // ConstantMaskOp. 2385 class StridedSliceConstantMaskFolder final 2386 : public OpRewritePattern<ExtractStridedSliceOp> { 2387 public: 2388 using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern; 2389 2390 LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp, 2391 PatternRewriter &rewriter) const override { 2392 // Return if 'extractStridedSliceOp' operand is not defined by a 2393 // ConstantMaskOp. 2394 auto *defOp = extractStridedSliceOp.vector().getDefiningOp(); 2395 auto constantMaskOp = dyn_cast_or_null<ConstantMaskOp>(defOp); 2396 if (!constantMaskOp) 2397 return failure(); 2398 // Return if 'extractStridedSliceOp' has non-unit strides. 2399 if (extractStridedSliceOp.hasNonUnitStrides()) 2400 return failure(); 2401 // Gather constant mask dimension sizes. 2402 SmallVector<int64_t, 4> maskDimSizes; 2403 populateFromInt64AttrArray(constantMaskOp.mask_dim_sizes(), maskDimSizes); 2404 // Gather strided slice offsets and sizes. 2405 SmallVector<int64_t, 4> sliceOffsets; 2406 populateFromInt64AttrArray(extractStridedSliceOp.offsets(), sliceOffsets); 2407 SmallVector<int64_t, 4> sliceSizes; 2408 populateFromInt64AttrArray(extractStridedSliceOp.sizes(), sliceSizes); 2409 2410 // Compute slice of vector mask region. 2411 SmallVector<int64_t, 4> sliceMaskDimSizes; 2412 assert(sliceOffsets.size() == maskDimSizes.size()); 2413 for (auto it : llvm::zip(maskDimSizes, sliceOffsets, sliceSizes)) { 2414 int64_t maskDimSize = std::get<0>(it); 2415 int64_t sliceOffset = std::get<1>(it); 2416 int64_t sliceSize = std::get<2>(it); 2417 int64_t sliceMaskDimSize = std::max( 2418 static_cast<int64_t>(0), 2419 std::min(sliceOffset + sliceSize, maskDimSize) - sliceOffset); 2420 sliceMaskDimSizes.push_back(sliceMaskDimSize); 2421 } 2422 // If any of 'sliceMaskDimSizes' are zero, then set all to zero (masked 2423 // region is a conjunction of mask dim intervals). 2424 if (llvm::is_contained(sliceMaskDimSizes, 0)) 2425 sliceMaskDimSizes.assign(maskDimSizes.size(), 0); 2426 2427 // Replace 'extractStridedSliceOp' with ConstantMaskOp with sliced mask 2428 // region. 2429 rewriter.replaceOpWithNewOp<ConstantMaskOp>( 2430 extractStridedSliceOp, extractStridedSliceOp.getResult().getType(), 2431 vector::getVectorSubscriptAttr(rewriter, sliceMaskDimSizes)); 2432 return success(); 2433 } 2434 }; 2435 2436 // Pattern to rewrite a ExtractStridedSliceOp(splat ConstantOp) -> ConstantOp. 2437 class StridedSliceConstantFolder final 2438 : public OpRewritePattern<ExtractStridedSliceOp> { 2439 public: 2440 using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern; 2441 2442 LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp, 2443 PatternRewriter &rewriter) const override { 2444 // Return if 'extractStridedSliceOp' operand is not defined by a 2445 // ConstantOp. 2446 auto constantOp = 2447 extractStridedSliceOp.vector().getDefiningOp<arith::ConstantOp>(); 2448 if (!constantOp) 2449 return failure(); 2450 auto dense = constantOp.getValue().dyn_cast<SplatElementsAttr>(); 2451 if (!dense) 2452 return failure(); 2453 auto newAttr = DenseElementsAttr::get(extractStridedSliceOp.getType(), 2454 dense.getSplatValue<Attribute>()); 2455 rewriter.replaceOpWithNewOp<arith::ConstantOp>(extractStridedSliceOp, 2456 newAttr); 2457 return success(); 2458 } 2459 }; 2460 2461 // Pattern to rewrite an ExtractStridedSliceOp(BroadcastOp) to 2462 // BroadcastOp(ExtractStrideSliceOp). 2463 class StridedSliceBroadcast final 2464 : public OpRewritePattern<ExtractStridedSliceOp> { 2465 public: 2466 using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern; 2467 2468 LogicalResult matchAndRewrite(ExtractStridedSliceOp op, 2469 PatternRewriter &rewriter) const override { 2470 auto broadcast = op.vector().getDefiningOp<BroadcastOp>(); 2471 if (!broadcast) 2472 return failure(); 2473 auto srcVecType = broadcast.source().getType().dyn_cast<VectorType>(); 2474 unsigned srcRrank = srcVecType ? srcVecType.getRank() : 0; 2475 auto dstVecType = op.getType().cast<VectorType>(); 2476 unsigned dstRank = dstVecType.getRank(); 2477 unsigned rankDiff = dstRank - srcRrank; 2478 // Check if the most inner dimensions of the source of the broadcast are the 2479 // same as the destination of the extract. If this is the case we can just 2480 // use a broadcast as the original dimensions are untouched. 2481 bool lowerDimMatch = true; 2482 for (unsigned i = 0; i < srcRrank; i++) { 2483 if (srcVecType.getDimSize(i) != dstVecType.getDimSize(i + rankDiff)) { 2484 lowerDimMatch = false; 2485 break; 2486 } 2487 } 2488 Value source = broadcast.source(); 2489 if (!lowerDimMatch) { 2490 // The inner dimensions don't match, it means we need to extract from the 2491 // source of the orignal broadcast and then broadcast the extracted value. 2492 source = rewriter.create<ExtractStridedSliceOp>( 2493 op->getLoc(), source, 2494 getI64SubArray(op.offsets(), /* dropFront=*/rankDiff), 2495 getI64SubArray(op.sizes(), /* dropFront=*/rankDiff), 2496 getI64SubArray(op.strides(), /* dropFront=*/rankDiff)); 2497 } 2498 rewriter.replaceOpWithNewOp<BroadcastOp>(op, op.getType(), source); 2499 return success(); 2500 } 2501 }; 2502 2503 /// Pattern to rewrite an ExtractStridedSliceOp(SplatOp) to SplatOp. 2504 class StridedSliceSplat final : public OpRewritePattern<ExtractStridedSliceOp> { 2505 public: 2506 using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern; 2507 2508 LogicalResult matchAndRewrite(ExtractStridedSliceOp op, 2509 PatternRewriter &rewriter) const override { 2510 auto splat = op.vector().getDefiningOp<SplatOp>(); 2511 if (!splat) 2512 return failure(); 2513 rewriter.replaceOpWithNewOp<SplatOp>(op, op.getType(), splat.input()); 2514 return success(); 2515 } 2516 }; 2517 2518 } // namespace 2519 2520 void ExtractStridedSliceOp::getCanonicalizationPatterns( 2521 RewritePatternSet &results, MLIRContext *context) { 2522 // Pattern to rewrite a ExtractStridedSliceOp(ConstantMaskOp) -> 2523 // ConstantMaskOp and ExtractStridedSliceOp(ConstantOp) -> ConstantOp. 2524 results.add<StridedSliceConstantMaskFolder, StridedSliceConstantFolder, 2525 StridedSliceBroadcast, StridedSliceSplat>(context); 2526 } 2527 2528 //===----------------------------------------------------------------------===// 2529 // TransferReadOp 2530 //===----------------------------------------------------------------------===// 2531 2532 /// 1. Builder that sets padding to zero and an empty mask (variant with attrs). 2533 void TransferReadOp::build(OpBuilder &builder, OperationState &result, 2534 VectorType vectorType, Value source, 2535 ValueRange indices, AffineMapAttr permutationMapAttr, 2536 /*optional*/ ArrayAttr inBoundsAttr) { 2537 Type elemType = source.getType().cast<ShapedType>().getElementType(); 2538 Value padding = builder.create<arith::ConstantOp>( 2539 result.location, elemType, builder.getZeroAttr(elemType)); 2540 build(builder, result, vectorType, source, indices, permutationMapAttr, 2541 padding, /*mask=*/Value(), inBoundsAttr); 2542 } 2543 2544 /// 2. Builder that sets padding to zero an empty mask (variant without attrs). 2545 void TransferReadOp::build(OpBuilder &builder, OperationState &result, 2546 VectorType vectorType, Value source, 2547 ValueRange indices, AffineMap permutationMap, 2548 Optional<ArrayRef<bool>> inBounds) { 2549 auto permutationMapAttr = AffineMapAttr::get(permutationMap); 2550 auto inBoundsAttr = (inBounds && !inBounds.getValue().empty()) 2551 ? builder.getBoolArrayAttr(inBounds.getValue()) 2552 : ArrayAttr(); 2553 build(builder, result, vectorType, source, indices, permutationMapAttr, 2554 inBoundsAttr); 2555 } 2556 2557 /// 3. Builder that sets permutation map to 'getMinorIdentityMap'. 2558 void TransferReadOp::build(OpBuilder &builder, OperationState &result, 2559 VectorType vectorType, Value source, 2560 ValueRange indices, Value padding, 2561 Optional<ArrayRef<bool>> inBounds) { 2562 AffineMap permutationMap = getTransferMinorIdentityMap( 2563 source.getType().cast<ShapedType>(), vectorType); 2564 auto permutationMapAttr = AffineMapAttr::get(permutationMap); 2565 auto inBoundsAttr = (inBounds && !inBounds.getValue().empty()) 2566 ? builder.getBoolArrayAttr(inBounds.getValue()) 2567 : ArrayAttr(); 2568 build(builder, result, vectorType, source, indices, permutationMapAttr, 2569 padding, 2570 /*mask=*/Value(), inBoundsAttr); 2571 } 2572 2573 /// 4. Builder that sets padding to zero and permutation map to 2574 /// 'getMinorIdentityMap'. 2575 void TransferReadOp::build(OpBuilder &builder, OperationState &result, 2576 VectorType vectorType, Value source, 2577 ValueRange indices, 2578 Optional<ArrayRef<bool>> inBounds) { 2579 Type elemType = source.getType().cast<ShapedType>().getElementType(); 2580 Value padding = builder.create<arith::ConstantOp>( 2581 result.location, elemType, builder.getZeroAttr(elemType)); 2582 build(builder, result, vectorType, source, indices, padding, inBounds); 2583 } 2584 2585 template <typename EmitFun> 2586 static LogicalResult verifyPermutationMap(AffineMap permutationMap, 2587 EmitFun emitOpError) { 2588 SmallVector<bool, 8> seen(permutationMap.getNumInputs(), false); 2589 for (auto expr : permutationMap.getResults()) { 2590 auto dim = expr.dyn_cast<AffineDimExpr>(); 2591 auto zero = expr.dyn_cast<AffineConstantExpr>(); 2592 if (zero) { 2593 if (zero.getValue() != 0) { 2594 return emitOpError( 2595 "requires a projected permutation_map (at most one dim or the zero " 2596 "constant can appear in each result)"); 2597 } 2598 continue; 2599 } 2600 if (!dim) { 2601 return emitOpError("requires a projected permutation_map (at most one " 2602 "dim or the zero constant can appear in each result)"); 2603 } 2604 if (seen[dim.getPosition()]) { 2605 return emitOpError( 2606 "requires a permutation_map that is a permutation (found one dim " 2607 "used more than once)"); 2608 } 2609 seen[dim.getPosition()] = true; 2610 } 2611 return success(); 2612 } 2613 2614 static LogicalResult 2615 verifyTransferOp(VectorTransferOpInterface op, ShapedType shapedType, 2616 VectorType vectorType, VectorType maskType, 2617 AffineMap permutationMap, ArrayAttr inBounds) { 2618 if (op->hasAttr("masked")) { 2619 return op->emitOpError("masked attribute has been removed. " 2620 "Use in_bounds instead."); 2621 } 2622 2623 if (!shapedType.isa<MemRefType, RankedTensorType>()) 2624 return op->emitOpError( 2625 "requires source to be a memref or ranked tensor type"); 2626 2627 auto elementType = shapedType.getElementType(); 2628 DataLayout dataLayout = DataLayout::closest(op); 2629 if (auto vectorElementType = elementType.dyn_cast<VectorType>()) { 2630 // Memref or tensor has vector element type. 2631 unsigned sourceVecSize = 2632 dataLayout.getTypeSizeInBits(vectorElementType.getElementType()) * 2633 vectorElementType.getShape().back(); 2634 unsigned resultVecSize = 2635 dataLayout.getTypeSizeInBits(vectorType.getElementType()) * 2636 vectorType.getShape().back(); 2637 if (resultVecSize % sourceVecSize != 0) 2638 return op->emitOpError( 2639 "requires the bitwidth of the minor 1-D vector to be an integral " 2640 "multiple of the bitwidth of the minor 1-D vector of the source"); 2641 2642 unsigned sourceVecEltRank = vectorElementType.getRank(); 2643 unsigned resultVecRank = vectorType.getRank(); 2644 if (sourceVecEltRank > resultVecRank) 2645 return op->emitOpError( 2646 "requires source vector element and vector result ranks to match."); 2647 unsigned rankOffset = resultVecRank - sourceVecEltRank; 2648 // Check that permutation map results match 'rankOffset' of vector type. 2649 if (permutationMap.getNumResults() != rankOffset) 2650 return op->emitOpError("requires a permutation_map with result dims of " 2651 "the same rank as the vector type"); 2652 2653 if (maskType) 2654 return op->emitOpError("does not support masks with vector element type"); 2655 } else { 2656 // Memref or tensor has scalar element type. 2657 unsigned minorSize = 2658 vectorType.getRank() == 0 ? 1 : vectorType.getShape().back(); 2659 unsigned resultVecSize = 2660 dataLayout.getTypeSizeInBits(vectorType.getElementType()) * minorSize; 2661 if (resultVecSize % dataLayout.getTypeSizeInBits(elementType) != 0) 2662 return op->emitOpError( 2663 "requires the bitwidth of the minor 1-D vector to be an integral " 2664 "multiple of the bitwidth of the source element type"); 2665 2666 // Check that permutation map results match rank of vector type. 2667 if (permutationMap.getNumResults() != vectorType.getRank()) 2668 return op->emitOpError("requires a permutation_map with result dims of " 2669 "the same rank as the vector type"); 2670 2671 VectorType expectedMaskType = 2672 vector::detail::transferMaskType(vectorType, permutationMap); 2673 if (maskType && expectedMaskType != maskType) 2674 return op->emitOpError("expects mask type consistent with permutation " 2675 "map: ") 2676 << maskType; 2677 } 2678 2679 if (permutationMap.getNumSymbols() != 0) 2680 return op->emitOpError("requires permutation_map without symbols"); 2681 2682 if (permutationMap.getNumInputs() != shapedType.getRank()) 2683 return op->emitOpError("requires a permutation_map with input dims of the " 2684 "same rank as the source type"); 2685 2686 if (inBounds) { 2687 if (permutationMap.getNumResults() != static_cast<int64_t>(inBounds.size())) 2688 return op->emitOpError("expects the optional in_bounds attr of same rank " 2689 "as permutation_map results: ") 2690 << AffineMapAttr::get(permutationMap) 2691 << " vs inBounds of size: " << inBounds.size(); 2692 for (unsigned int i = 0; i < permutationMap.getNumResults(); ++i) 2693 if (permutationMap.getResult(i).isa<AffineConstantExpr>() && 2694 !inBounds.getValue()[i].cast<BoolAttr>().getValue()) 2695 return op->emitOpError("requires broadcast dimensions to be in-bounds"); 2696 } 2697 2698 return success(); 2699 } 2700 2701 static void printTransferAttrs(OpAsmPrinter &p, VectorTransferOpInterface op) { 2702 SmallVector<StringRef, 3> elidedAttrs; 2703 elidedAttrs.push_back(TransferReadOp::getOperandSegmentSizeAttr()); 2704 if (op.permutation_map().isMinorIdentity()) 2705 elidedAttrs.push_back(op.getPermutationMapAttrStrName()); 2706 bool elideInBounds = true; 2707 if (auto inBounds = op.in_bounds()) { 2708 for (auto attr : *inBounds) { 2709 if (attr.template cast<BoolAttr>().getValue()) { 2710 elideInBounds = false; 2711 break; 2712 } 2713 } 2714 } 2715 if (elideInBounds) 2716 elidedAttrs.push_back(op.getInBoundsAttrStrName()); 2717 p.printOptionalAttrDict(op->getAttrs(), elidedAttrs); 2718 } 2719 2720 void TransferReadOp::print(OpAsmPrinter &p) { 2721 p << " " << source() << "[" << indices() << "], " << padding(); 2722 if (mask()) 2723 p << ", " << mask(); 2724 printTransferAttrs(p, *this); 2725 p << " : " << getShapedType() << ", " << getVectorType(); 2726 } 2727 2728 ParseResult TransferReadOp::parse(OpAsmParser &parser, OperationState &result) { 2729 auto &builder = parser.getBuilder(); 2730 SMLoc typesLoc; 2731 OpAsmParser::OperandType sourceInfo; 2732 SmallVector<OpAsmParser::OperandType, 8> indexInfo; 2733 OpAsmParser::OperandType paddingInfo; 2734 SmallVector<Type, 2> types; 2735 OpAsmParser::OperandType maskInfo; 2736 // Parsing with support for paddingValue. 2737 if (parser.parseOperand(sourceInfo) || 2738 parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) || 2739 parser.parseComma() || parser.parseOperand(paddingInfo)) 2740 return failure(); 2741 ParseResult hasMask = parser.parseOptionalComma(); 2742 if (hasMask.succeeded()) { 2743 parser.parseOperand(maskInfo); 2744 } 2745 if (parser.parseOptionalAttrDict(result.attributes) || 2746 parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types)) 2747 return failure(); 2748 if (types.size() != 2) 2749 return parser.emitError(typesLoc, "requires two types"); 2750 auto indexType = builder.getIndexType(); 2751 auto shapedType = types[0].dyn_cast<ShapedType>(); 2752 if (!shapedType || !shapedType.isa<MemRefType, RankedTensorType>()) 2753 return parser.emitError(typesLoc, "requires memref or ranked tensor type"); 2754 VectorType vectorType = types[1].dyn_cast<VectorType>(); 2755 if (!vectorType) 2756 return parser.emitError(typesLoc, "requires vector type"); 2757 auto permutationAttrName = TransferReadOp::getPermutationMapAttrStrName(); 2758 Attribute mapAttr = result.attributes.get(permutationAttrName); 2759 if (!mapAttr) { 2760 auto permMap = getTransferMinorIdentityMap(shapedType, vectorType); 2761 // Update `mapAttr` that is used later to determine mask type. 2762 mapAttr = AffineMapAttr::get(permMap); 2763 result.attributes.set(permutationAttrName, mapAttr); 2764 } 2765 if (parser.resolveOperand(sourceInfo, shapedType, result.operands) || 2766 parser.resolveOperands(indexInfo, indexType, result.operands) || 2767 parser.resolveOperand(paddingInfo, shapedType.getElementType(), 2768 result.operands)) 2769 return failure(); 2770 if (hasMask.succeeded()) { 2771 if (shapedType.getElementType().dyn_cast<VectorType>()) 2772 return parser.emitError( 2773 maskInfo.location, "does not support masks with vector element type"); 2774 auto map = mapAttr.dyn_cast<AffineMapAttr>().getValue(); 2775 // Instead of adding the mask type as an op type, compute it based on the 2776 // vector type and the permutation map (to keep the type signature small). 2777 auto maskType = mlir::vector::detail::transferMaskType(vectorType, map); 2778 if (parser.resolveOperand(maskInfo, maskType, result.operands)) 2779 return failure(); 2780 } 2781 result.addAttribute( 2782 TransferReadOp::getOperandSegmentSizeAttr(), 2783 builder.getI32VectorAttr({1, static_cast<int32_t>(indexInfo.size()), 1, 2784 static_cast<int32_t>(hasMask.succeeded())})); 2785 return parser.addTypeToList(vectorType, result.types); 2786 } 2787 2788 LogicalResult TransferReadOp::verify() { 2789 // Consistency of elemental types in source and vector. 2790 ShapedType shapedType = getShapedType(); 2791 VectorType vectorType = getVectorType(); 2792 VectorType maskType = getMaskType(); 2793 auto paddingType = padding().getType(); 2794 auto permutationMap = permutation_map(); 2795 auto sourceElementType = shapedType.getElementType(); 2796 2797 if (static_cast<int64_t>(indices().size()) != shapedType.getRank()) 2798 return emitOpError("requires ") << shapedType.getRank() << " indices"; 2799 2800 if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()), 2801 shapedType, vectorType, maskType, permutationMap, 2802 in_bounds() ? *in_bounds() : ArrayAttr()))) 2803 return failure(); 2804 2805 if (auto sourceVectorElementType = sourceElementType.dyn_cast<VectorType>()) { 2806 // Source has vector element type. 2807 // Check that 'sourceVectorElementType' and 'paddingType' types match. 2808 if (sourceVectorElementType != paddingType) 2809 return emitOpError( 2810 "requires source element type and padding type to match."); 2811 2812 } else { 2813 // Check that 'paddingType' is valid to store in a vector type. 2814 if (!VectorType::isValidElementType(paddingType)) 2815 return emitOpError("requires valid padding vector elemental type"); 2816 2817 // Check that padding type and vector element types match. 2818 if (paddingType != sourceElementType) 2819 return emitOpError( 2820 "requires formal padding and source of the same elemental type"); 2821 } 2822 2823 return verifyPermutationMap(permutationMap, 2824 [&](Twine t) { return emitOpError(t); }); 2825 } 2826 2827 /// This is a common class used for patterns of the form 2828 /// ``` 2829 /// someop(memrefcast) -> someop 2830 /// ``` 2831 /// It folds the source of the memref.cast into the root operation directly. 2832 static LogicalResult foldMemRefCast(Operation *op) { 2833 bool folded = false; 2834 for (OpOperand &operand : op->getOpOperands()) { 2835 auto castOp = operand.get().getDefiningOp<memref::CastOp>(); 2836 if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) { 2837 operand.set(castOp.getOperand()); 2838 folded = true; 2839 } 2840 } 2841 return success(folded); 2842 } 2843 2844 static LogicalResult foldTensorCast(Operation *op) { 2845 bool folded = false; 2846 for (OpOperand &operand : op->getOpOperands()) { 2847 auto castOp = operand.get().getDefiningOp<tensor::CastOp>(); 2848 if (castOp && tensor::canFoldIntoConsumerOp(castOp)) { 2849 operand.set(castOp.getOperand()); 2850 folded = true; 2851 } 2852 } 2853 return success(folded); 2854 } 2855 2856 template <typename TransferOp> 2857 static bool isInBounds(TransferOp op, int64_t resultIdx, int64_t indicesIdx) { 2858 // TODO: support more aggressive createOrFold on: 2859 // `op.indices()[indicesIdx] + vectorType < dim(op.source(), indicesIdx)` 2860 if (op.getShapedType().isDynamicDim(indicesIdx)) 2861 return false; 2862 Value index = op.indices()[indicesIdx]; 2863 auto cstOp = index.getDefiningOp<arith::ConstantIndexOp>(); 2864 if (!cstOp) 2865 return false; 2866 2867 int64_t sourceSize = op.getShapedType().getDimSize(indicesIdx); 2868 int64_t vectorSize = op.getVectorType().getDimSize(resultIdx); 2869 2870 return cstOp.value() + vectorSize <= sourceSize; 2871 } 2872 2873 template <typename TransferOp> 2874 static LogicalResult foldTransferInBoundsAttribute(TransferOp op) { 2875 // TODO: support 0-d corner case. 2876 // TODO: Be less conservative. 2877 if (op.getTransferRank() == 0) 2878 return failure(); 2879 AffineMap permutationMap = op.permutation_map(); 2880 bool changed = false; 2881 SmallVector<bool, 4> newInBounds; 2882 newInBounds.reserve(op.getTransferRank()); 2883 for (unsigned i = 0; i < op.getTransferRank(); ++i) { 2884 // Already marked as in-bounds, nothing to see here. 2885 if (op.isDimInBounds(i)) { 2886 newInBounds.push_back(true); 2887 continue; 2888 } 2889 // Currently out-of-bounds, check whether we can statically determine it is 2890 // inBounds. 2891 auto dimExpr = permutationMap.getResult(i).dyn_cast<AffineDimExpr>(); 2892 assert(dimExpr && "Broadcast dims must be in-bounds"); 2893 auto inBounds = 2894 isInBounds(op, /*resultIdx=*/i, /*indicesIdx=*/dimExpr.getPosition()); 2895 newInBounds.push_back(inBounds); 2896 // We commit the pattern if it is "more inbounds". 2897 changed |= inBounds; 2898 } 2899 if (!changed) 2900 return failure(); 2901 // OpBuilder is only used as a helper to build an I64ArrayAttr. 2902 OpBuilder b(op.getContext()); 2903 op->setAttr(TransferOp::getInBoundsAttrStrName(), 2904 b.getBoolArrayAttr(newInBounds)); 2905 return success(); 2906 } 2907 2908 /// ``` 2909 /// %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]} 2910 /// : vector<1x4xf32>, tensor<4x4xf32> 2911 /// %0 = vector.transfer_read %w0[%c1, %c0], %cf0 {in_bounds = [true, true]} 2912 /// : tensor<4x4xf32>, vector<1x4xf32> 2913 /// ``` 2914 /// -> Folds into 2915 /// ``` 2916 /// %v0 2917 /// ``` 2918 static Value foldRAW(TransferReadOp readOp) { 2919 if (!readOp.getShapedType().isa<RankedTensorType>()) 2920 return {}; 2921 auto defWrite = readOp.source().getDefiningOp<vector::TransferWriteOp>(); 2922 while (defWrite) { 2923 if (checkSameValueRAW(defWrite, readOp)) 2924 return defWrite.vector(); 2925 if (!isDisjointTransferIndices( 2926 cast<VectorTransferOpInterface>(defWrite.getOperation()), 2927 cast<VectorTransferOpInterface>(readOp.getOperation()))) 2928 break; 2929 defWrite = defWrite.source().getDefiningOp<vector::TransferWriteOp>(); 2930 } 2931 return {}; 2932 } 2933 2934 OpFoldResult TransferReadOp::fold(ArrayRef<Attribute>) { 2935 if (Value vec = foldRAW(*this)) 2936 return vec; 2937 /// transfer_read(memrefcast) -> transfer_read 2938 if (succeeded(foldTransferInBoundsAttribute(*this))) 2939 return getResult(); 2940 if (succeeded(foldMemRefCast(*this))) 2941 return getResult(); 2942 if (succeeded(foldTensorCast(*this))) 2943 return getResult(); 2944 return OpFoldResult(); 2945 } 2946 2947 Optional<SmallVector<int64_t, 4>> TransferReadOp::getShapeForUnroll() { 2948 return llvm::to_vector<4>(getVectorType().getShape()); 2949 } 2950 2951 void TransferReadOp::getEffects( 2952 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> 2953 &effects) { 2954 if (getShapedType().isa<MemRefType>()) 2955 effects.emplace_back(MemoryEffects::Read::get(), source(), 2956 SideEffects::DefaultResource::get()); 2957 } 2958 2959 namespace { 2960 /// Fold transfer_reads of a tensor.extract_slice op. E.g.: 2961 /// 2962 /// ``` 2963 /// %0 = tensor.extract_slice %t[%a, %b] [%c, %d] [1, 1] 2964 /// : tensor<?x?xf32> to tensor<?x?xf32> 2965 /// %1 = vector.transfer_read %0[%e, %f], %cst {in_bounds = [true, true]} 2966 /// : tensor<?x?xf32>, vector<4x5xf32> 2967 /// ``` 2968 /// is rewritten to: 2969 /// ``` 2970 /// %p0 = arith.addi %a, %e : index 2971 /// %p1 = arith.addi %b, %f : index 2972 /// %1 = vector.transfer_read %t[%p0, %p1], %cst {in_bounds = [true, true]} 2973 /// : tensor<?x?xf32>, vector<4x5xf32> 2974 /// ``` 2975 struct FoldExtractSliceIntoTransferRead 2976 : public OpRewritePattern<TransferReadOp> { 2977 public: 2978 using OpRewritePattern<TransferReadOp>::OpRewritePattern; 2979 2980 LogicalResult matchAndRewrite(TransferReadOp xferOp, 2981 PatternRewriter &rewriter) const override { 2982 // TODO: support 0-d corner case. 2983 if (xferOp.getTransferRank() == 0) 2984 return failure(); 2985 if (xferOp.hasOutOfBoundsDim()) 2986 return failure(); 2987 if (!xferOp.permutation_map().isIdentity()) 2988 return failure(); 2989 if (xferOp.mask()) 2990 return failure(); 2991 auto extractOp = xferOp.source().getDefiningOp<tensor::ExtractSliceOp>(); 2992 if (!extractOp) 2993 return failure(); 2994 if (!extractOp.hasUnitStride()) 2995 return failure(); 2996 2997 // Bail on illegal rank-reduction: we need to check that the rank-reduced 2998 // dims are exactly the leading dims. I.e. the following is illegal: 2999 // ``` 3000 // %0 = tensor.extract_slice %t[0,0,0][2,1,4][1,1,1] : 3001 // tensor<2x1x4xf32> to tensor<2x4xf32> 3002 // %1 = vector.transfer_read %0[0,0], %cst : 3003 // tensor<2x4xf32>, vector<2x4xf32> 3004 // ``` 3005 // 3006 // Cannot fold into: 3007 // ``` 3008 // %0 = vector.transfer_read %t[0,0,0], %cst : 3009 // tensor<2x1x4xf32>, vector<2x4xf32> 3010 // ``` 3011 // For this, check the trailing `vectorRank` dims of the extract_slice 3012 // result tensor match the trailing dims of the inferred result tensor. 3013 int64_t rankReduced = 3014 extractOp.getSourceType().getRank() - extractOp.getType().getRank(); 3015 int64_t vectorRank = xferOp.getVectorType().getRank(); 3016 RankedTensorType inferredDestTensorType = 3017 tensor::ExtractSliceOp::inferResultType( 3018 extractOp.getSourceType(), extractOp.getMixedOffsets(), 3019 extractOp.getMixedSizes(), extractOp.getMixedStrides()); 3020 auto actualDestTensorShape = extractOp.getType().getShape(); 3021 if (rankReduced > 0 && 3022 actualDestTensorShape.take_back(vectorRank) != 3023 inferredDestTensorType.getShape().take_back(vectorRank)) 3024 return failure(); 3025 3026 SmallVector<Value> newIndices; 3027 // In case this is a rank-reducing ExtractSliceOp, copy rank-reduced 3028 // indices first. 3029 for (int64_t i = 0; i < rankReduced; ++i) { 3030 OpFoldResult offset = extractOp.getMixedOffsets()[i]; 3031 newIndices.push_back(getValueOrCreateConstantIndexOp( 3032 rewriter, extractOp.getLoc(), offset)); 3033 } 3034 for (const auto &it : llvm::enumerate(xferOp.indices())) { 3035 OpFoldResult offset = 3036 extractOp.getMixedOffsets()[it.index() + rankReduced]; 3037 newIndices.push_back(rewriter.create<arith::AddIOp>( 3038 xferOp->getLoc(), it.value(), 3039 getValueOrCreateConstantIndexOp(rewriter, extractOp.getLoc(), 3040 offset))); 3041 } 3042 SmallVector<bool> inBounds(xferOp.getTransferRank(), true); 3043 rewriter.replaceOpWithNewOp<TransferReadOp>( 3044 xferOp, xferOp.getVectorType(), extractOp.source(), newIndices, 3045 xferOp.padding(), ArrayRef<bool>{inBounds}); 3046 3047 return success(); 3048 } 3049 }; 3050 } // namespace 3051 3052 void TransferReadOp::getCanonicalizationPatterns(RewritePatternSet &results, 3053 MLIRContext *context) { 3054 results.add<FoldExtractSliceIntoTransferRead>(context); 3055 } 3056 3057 //===----------------------------------------------------------------------===// 3058 // TransferWriteOp 3059 //===----------------------------------------------------------------------===// 3060 3061 /// 1. Builder with type inference. 3062 void TransferWriteOp::build(OpBuilder &builder, OperationState &result, 3063 Value vector, Value dest, ValueRange indices, 3064 AffineMapAttr permutationMapAttr, 3065 /*optional*/ Value mask, 3066 /*optional*/ ArrayAttr inBoundsAttr) { 3067 Type resultType = dest.getType().dyn_cast<RankedTensorType>(); 3068 build(builder, result, resultType, vector, dest, indices, permutationMapAttr, 3069 mask, inBoundsAttr); 3070 } 3071 3072 /// 2. Builder with type inference that sets an empty mask (variant with attrs). 3073 void TransferWriteOp::build(OpBuilder &builder, OperationState &result, 3074 Value vector, Value dest, ValueRange indices, 3075 AffineMapAttr permutationMapAttr, 3076 /*optional*/ ArrayAttr inBoundsAttr) { 3077 build(builder, result, vector, dest, indices, permutationMapAttr, 3078 /*mask=*/Value(), inBoundsAttr); 3079 } 3080 3081 /// 3. Builder with type inference that sets an empty mask (variant without 3082 /// attrs) 3083 void TransferWriteOp::build(OpBuilder &builder, OperationState &result, 3084 Value vector, Value dest, ValueRange indices, 3085 AffineMap permutationMap, 3086 Optional<ArrayRef<bool>> inBounds) { 3087 auto permutationMapAttr = AffineMapAttr::get(permutationMap); 3088 auto inBoundsAttr = (inBounds && !inBounds.getValue().empty()) 3089 ? builder.getBoolArrayAttr(inBounds.getValue()) 3090 : ArrayAttr(); 3091 build(builder, result, vector, dest, indices, permutationMapAttr, 3092 /*mask=*/Value(), inBoundsAttr); 3093 } 3094 3095 /// 4. Builder with type inference that sets an empty mask and sets permutation 3096 /// map to 'getMinorIdentityMap'. 3097 void TransferWriteOp::build(OpBuilder &builder, OperationState &result, 3098 Value vector, Value dest, ValueRange indices, 3099 Optional<ArrayRef<bool>> inBounds) { 3100 auto vectorType = vector.getType().cast<VectorType>(); 3101 AffineMap permutationMap = getTransferMinorIdentityMap( 3102 dest.getType().cast<ShapedType>(), vectorType); 3103 build(builder, result, vector, dest, indices, permutationMap, inBounds); 3104 } 3105 3106 ParseResult TransferWriteOp::parse(OpAsmParser &parser, 3107 OperationState &result) { 3108 auto &builder = parser.getBuilder(); 3109 SMLoc typesLoc; 3110 OpAsmParser::OperandType vectorInfo, sourceInfo; 3111 SmallVector<OpAsmParser::OperandType, 8> indexInfo; 3112 SmallVector<Type, 2> types; 3113 OpAsmParser::OperandType maskInfo; 3114 if (parser.parseOperand(vectorInfo) || parser.parseComma() || 3115 parser.parseOperand(sourceInfo) || 3116 parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square)) 3117 return failure(); 3118 ParseResult hasMask = parser.parseOptionalComma(); 3119 if (hasMask.succeeded() && parser.parseOperand(maskInfo)) 3120 return failure(); 3121 if (parser.parseOptionalAttrDict(result.attributes) || 3122 parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types)) 3123 return failure(); 3124 if (types.size() != 2) 3125 return parser.emitError(typesLoc, "requires two types"); 3126 auto indexType = builder.getIndexType(); 3127 VectorType vectorType = types[0].dyn_cast<VectorType>(); 3128 if (!vectorType) 3129 return parser.emitError(typesLoc, "requires vector type"); 3130 ShapedType shapedType = types[1].dyn_cast<ShapedType>(); 3131 if (!shapedType || !shapedType.isa<MemRefType, RankedTensorType>()) 3132 return parser.emitError(typesLoc, "requires memref or ranked tensor type"); 3133 auto permutationAttrName = TransferWriteOp::getPermutationMapAttrStrName(); 3134 auto attr = result.attributes.get(permutationAttrName); 3135 if (!attr) { 3136 auto permMap = getTransferMinorIdentityMap(shapedType, vectorType); 3137 result.attributes.set(permutationAttrName, AffineMapAttr::get(permMap)); 3138 } 3139 if (parser.resolveOperand(vectorInfo, vectorType, result.operands) || 3140 parser.resolveOperand(sourceInfo, shapedType, result.operands) || 3141 parser.resolveOperands(indexInfo, indexType, result.operands)) 3142 return failure(); 3143 if (hasMask.succeeded()) { 3144 if (shapedType.getElementType().dyn_cast<VectorType>()) 3145 return parser.emitError( 3146 maskInfo.location, "does not support masks with vector element type"); 3147 auto maskType = VectorType::get(vectorType.getShape(), builder.getI1Type()); 3148 if (parser.resolveOperand(maskInfo, maskType, result.operands)) 3149 return failure(); 3150 } 3151 result.addAttribute( 3152 TransferWriteOp::getOperandSegmentSizeAttr(), 3153 builder.getI32VectorAttr({1, 1, static_cast<int32_t>(indexInfo.size()), 3154 static_cast<int32_t>(hasMask.succeeded())})); 3155 return failure(shapedType.isa<RankedTensorType>() && 3156 parser.addTypeToList(shapedType, result.types)); 3157 } 3158 3159 void TransferWriteOp::print(OpAsmPrinter &p) { 3160 p << " " << vector() << ", " << source() << "[" << indices() << "]"; 3161 if (mask()) 3162 p << ", " << mask(); 3163 printTransferAttrs(p, *this); 3164 p << " : " << getVectorType() << ", " << getShapedType(); 3165 } 3166 3167 LogicalResult TransferWriteOp::verify() { 3168 // Consistency of elemental types in shape and vector. 3169 ShapedType shapedType = getShapedType(); 3170 VectorType vectorType = getVectorType(); 3171 VectorType maskType = getMaskType(); 3172 auto permutationMap = permutation_map(); 3173 3174 if (llvm::size(indices()) != shapedType.getRank()) 3175 return emitOpError("requires ") << shapedType.getRank() << " indices"; 3176 3177 // We do not allow broadcast dimensions on TransferWriteOps for the moment, 3178 // as the semantics is unclear. This can be revisited later if necessary. 3179 if (hasBroadcastDim()) 3180 return emitOpError("should not have broadcast dimensions"); 3181 3182 if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()), 3183 shapedType, vectorType, maskType, permutationMap, 3184 in_bounds() ? *in_bounds() : ArrayAttr()))) 3185 return failure(); 3186 3187 return verifyPermutationMap(permutationMap, 3188 [&](Twine t) { return emitOpError(t); }); 3189 } 3190 3191 /// Fold: 3192 /// ``` 3193 /// %t1 = ... 3194 /// %v = vector.transfer_read %t0[%c0...], {in_bounds = [true...]} : 3195 /// tensor<static_sizesxf32>, vector<static_sizesxf32> 3196 /// %t2 = vector.transfer_write %v, %t1[%c0...] {in_bounds = [true...]} : 3197 /// vector<static_sizesxf32>, tensor<static_sizesxf32> 3198 /// ``` 3199 /// 3200 /// into: 3201 /// 3202 /// ``` 3203 /// %t0 3204 /// ``` 3205 /// 3206 /// The producer of t1 may or may not be DCE'd depending on whether it is a 3207 /// block argument or has side effects. 3208 static LogicalResult foldReadInitWrite(TransferWriteOp write, 3209 ArrayRef<Attribute>, 3210 SmallVectorImpl<OpFoldResult> &results) { 3211 // TODO: support 0-d corner case. 3212 if (write.getTransferRank() == 0) 3213 return failure(); 3214 auto rankedTensorType = write.source().getType().dyn_cast<RankedTensorType>(); 3215 // If not operating on tensors, bail. 3216 if (!rankedTensorType) 3217 return failure(); 3218 // If no read, bail. 3219 auto read = write.vector().getDefiningOp<vector::TransferReadOp>(); 3220 if (!read) 3221 return failure(); 3222 // TODO: support 0-d corner case. 3223 if (read.getTransferRank() == 0) 3224 return failure(); 3225 // For now, only accept minor identity. Future: composition is minor identity. 3226 if (!read.permutation_map().isMinorIdentity() || 3227 !write.permutation_map().isMinorIdentity()) 3228 return failure(); 3229 // Bail on mismatching ranks. 3230 if (read.getTransferRank() != write.getTransferRank()) 3231 return failure(); 3232 // Bail on potential out-of-bounds accesses. 3233 if (read.hasOutOfBoundsDim() || write.hasOutOfBoundsDim()) 3234 return failure(); 3235 // Tensor types must be the same. 3236 if (read.source().getType() != rankedTensorType) 3237 return failure(); 3238 // Vector types must be the same. 3239 if (read.getVectorType() != write.getVectorType()) 3240 return failure(); 3241 // Vector and Tensor shapes must match. 3242 if (read.getVectorType().getShape() != rankedTensorType.getShape()) 3243 return failure(); 3244 // If any index is nonzero. 3245 auto isNotConstantZero = [](Value v) { 3246 auto cstOp = v.getDefiningOp<arith::ConstantIndexOp>(); 3247 return !cstOp || cstOp.value() != 0; 3248 }; 3249 if (llvm::any_of(read.indices(), isNotConstantZero) || 3250 llvm::any_of(write.indices(), isNotConstantZero)) 3251 return failure(); 3252 // Success. 3253 results.push_back(read.source()); 3254 return success(); 3255 } 3256 3257 static bool checkSameValueWAR(vector::TransferReadOp read, 3258 vector::TransferWriteOp write) { 3259 return read.source() == write.source() && read.indices() == write.indices() && 3260 read.permutation_map() == write.permutation_map() && 3261 read.getVectorType() == write.getVectorType() && !read.mask() && 3262 !write.mask(); 3263 } 3264 /// Fold transfer_write write after read: 3265 /// ``` 3266 /// %t0 = ... 3267 /// %v = vector.transfer_read %t0[%c0...] : 3268 /// tensor<static_sizesxf32>, vector<static_sizesxf32> 3269 /// %t1 = vector.transfer_write %v, %t0[%c0...] : 3270 /// vector<static_sizesxf32>, tensor<static_sizesxf32> 3271 /// ``` 3272 /// 3273 /// into: 3274 /// 3275 /// ``` 3276 /// %t0 3277 /// ``` 3278 static LogicalResult foldWAR(TransferWriteOp write, 3279 SmallVectorImpl<OpFoldResult> &results) { 3280 if (!write.source().getType().isa<RankedTensorType>()) 3281 return failure(); 3282 auto read = write.vector().getDefiningOp<vector::TransferReadOp>(); 3283 if (!read) 3284 return failure(); 3285 3286 if (!checkSameValueWAR(read, write)) 3287 return failure(); 3288 results.push_back(read.source()); 3289 return success(); 3290 } 3291 3292 LogicalResult TransferWriteOp::fold(ArrayRef<Attribute> operands, 3293 SmallVectorImpl<OpFoldResult> &results) { 3294 if (succeeded(foldReadInitWrite(*this, operands, results))) 3295 return success(); 3296 if (succeeded(foldWAR(*this, results))) 3297 return success(); 3298 if (succeeded(foldTransferInBoundsAttribute(*this))) 3299 return success(); 3300 return foldMemRefCast(*this); 3301 } 3302 3303 Optional<SmallVector<int64_t, 4>> TransferWriteOp::getShapeForUnroll() { 3304 return llvm::to_vector<4>(getVectorType().getShape()); 3305 } 3306 3307 void TransferWriteOp::getEffects( 3308 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>> 3309 &effects) { 3310 if (getShapedType().isa<MemRefType>()) 3311 effects.emplace_back(MemoryEffects::Write::get(), source(), 3312 SideEffects::DefaultResource::get()); 3313 } 3314 3315 namespace { 3316 /// Remove dead transfer write from the SSA chain so that it an be eliminated by 3317 /// DCE 3318 /// ``` 3319 /// %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]} 3320 /// : vector<1x4xf32>, tensor<4x4xf32> 3321 /// %w1 = vector.transfer_write %v0, %w0[%c2, %c0] {in_bounds = [true, true]} 3322 /// : vector<1x4xf32>, tensor<4x4xf32> 3323 /// %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]} 3324 /// : vector<1x4xf32>, tensor<4x4xf32> 3325 /// ``` 3326 /// 3327 /// into: 3328 /// 3329 /// ``` 3330 /// %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]} 3331 /// : vector<1x4xf32>, tensor<4x4xf32> 3332 /// %w1 = vector.transfer_write %v0, %arg0[%c2, %c0] {in_bounds = [true, true]} 3333 /// : vector<1x4xf32>, tensor<4x4xf32> 3334 /// %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]} 3335 /// : vector<1x4xf32>, tensor<4x4xf32> 3336 /// ``` 3337 /// 3338 /// `%w0 = vector.transfer_write` op will be removed by DCE if it doesn't have 3339 /// any other uses. 3340 class FoldWaw final : public OpRewritePattern<TransferWriteOp> { 3341 public: 3342 using OpRewritePattern<TransferWriteOp>::OpRewritePattern; 3343 LogicalResult matchAndRewrite(TransferWriteOp writeOp, 3344 PatternRewriter &rewriter) const override { 3345 if (!writeOp.getShapedType().isa<RankedTensorType>()) 3346 return failure(); 3347 vector::TransferWriteOp writeToModify = writeOp; 3348 3349 auto defWrite = writeOp.source().getDefiningOp<vector::TransferWriteOp>(); 3350 while (defWrite) { 3351 if (checkSameValueWAW(writeOp, defWrite)) { 3352 writeToModify.sourceMutable().assign(defWrite.source()); 3353 return success(); 3354 } 3355 if (!isDisjointTransferIndices( 3356 cast<VectorTransferOpInterface>(defWrite.getOperation()), 3357 cast<VectorTransferOpInterface>(writeOp.getOperation()))) 3358 break; 3359 // If the previous write op doesn't have any other use we an safely look 3360 // at the previous store to see if it can be removed. 3361 if (!defWrite->hasOneUse()) 3362 break; 3363 writeToModify = defWrite; 3364 defWrite = defWrite.source().getDefiningOp<vector::TransferWriteOp>(); 3365 } 3366 return failure(); 3367 } 3368 }; 3369 3370 /// Fold tensor.insert_slice into vector.transfer_write if the transfer_write 3371 /// could directly write to the insert_slice's destination. E.g.: 3372 /// 3373 /// ``` 3374 /// %0 = vector.transfer_write %v, %t1[%c0, %c0] {in_bounds = [true, true]} 3375 /// : vector<4x5xf32>, tensor<4x5xf32> 3376 /// %1 = tensor.insert_slice %0 into %t2[%a, %b] [4, 5] [1, 1] 3377 /// : tensor<4x5xf32> into tensor<?x?xf32> 3378 /// ``` 3379 /// is rewritten to: 3380 /// ``` 3381 /// %1 = vector.transfer_write %v, %t2[%a, %b] {in_bounds = [true, true]} 3382 /// : vector<4x5xf32>, tensor<?x?xf32> 3383 /// ``` 3384 struct FoldInsertSliceIntoTransferWrite 3385 : public OpRewritePattern<tensor::InsertSliceOp> { 3386 public: 3387 using OpRewritePattern<tensor::InsertSliceOp>::OpRewritePattern; 3388 3389 LogicalResult matchAndRewrite(tensor::InsertSliceOp insertOp, 3390 PatternRewriter &rewriter) const override { 3391 if (!insertOp.hasUnitStride()) 3392 return failure(); 3393 3394 auto xferOp = insertOp.source().getDefiningOp<TransferWriteOp>(); 3395 if (!xferOp) 3396 return failure(); 3397 // TODO: support 0-d corner case. 3398 if (xferOp.getTransferRank() == 0) 3399 return failure(); 3400 3401 if (xferOp.hasOutOfBoundsDim()) 3402 return failure(); 3403 if (xferOp.getVectorType().getRank() != xferOp.getShapedType().getRank()) 3404 return failure(); 3405 if (xferOp.mask()) 3406 return failure(); 3407 // Fold only if the TransferWriteOp completely overwrites the `source` with 3408 // a vector. I.e., the result of the TransferWriteOp is a new tensor whose 3409 // content is the data of the vector. 3410 if (!llvm::equal(xferOp.getVectorType().getShape(), 3411 xferOp.getShapedType().getShape())) 3412 return failure(); 3413 if (!xferOp.permutation_map().isIdentity()) 3414 return failure(); 3415 3416 // Bail on illegal rank-reduction: we need to check that the rank-reduced 3417 // dims are exactly the leading dims. I.e. the following is illegal: 3418 // ``` 3419 // %0 = vector.transfer_write %v, %t[0,0], %cst : 3420 // vector<2x4xf32>, tensor<2x4xf32> 3421 // %1 = tensor.insert_slice %0 into %tt[0,0,0][2,1,4][1,1,1] : 3422 // tensor<2x4xf32> into tensor<2x1x4xf32> 3423 // ``` 3424 // 3425 // Cannot fold into: 3426 // ``` 3427 // %0 = vector.transfer_write %v, %t[0,0,0], %cst : 3428 // vector<2x4xf32>, tensor<2x1x4xf32> 3429 // ``` 3430 // For this, check the trailing `vectorRank` dims of the insert_slice result 3431 // tensor match the trailing dims of the inferred result tensor. 3432 int64_t rankReduced = 3433 insertOp.getType().getRank() - insertOp.getSourceType().getRank(); 3434 int64_t vectorRank = xferOp.getVectorType().getRank(); 3435 RankedTensorType inferredSourceTensorType = 3436 tensor::ExtractSliceOp::inferResultType( 3437 insertOp.getType(), insertOp.getMixedOffsets(), 3438 insertOp.getMixedSizes(), insertOp.getMixedStrides()); 3439 auto actualSourceTensorShape = insertOp.getSourceType().getShape(); 3440 if (rankReduced > 0 && 3441 actualSourceTensorShape.take_back(vectorRank) != 3442 inferredSourceTensorType.getShape().take_back(vectorRank)) 3443 return failure(); 3444 3445 SmallVector<Value> indices = getValueOrCreateConstantIndexOp( 3446 rewriter, insertOp.getLoc(), insertOp.getMixedOffsets()); 3447 SmallVector<bool> inBounds(xferOp.getTransferRank(), true); 3448 rewriter.replaceOpWithNewOp<TransferWriteOp>(insertOp, xferOp.vector(), 3449 insertOp.dest(), indices, 3450 ArrayRef<bool>{inBounds}); 3451 return success(); 3452 } 3453 }; 3454 } // namespace 3455 3456 void TransferWriteOp::getCanonicalizationPatterns(RewritePatternSet &results, 3457 MLIRContext *context) { 3458 results.add<FoldWaw, FoldInsertSliceIntoTransferWrite>(context); 3459 } 3460 3461 //===----------------------------------------------------------------------===// 3462 // LoadOp 3463 //===----------------------------------------------------------------------===// 3464 3465 static LogicalResult verifyLoadStoreMemRefLayout(Operation *op, 3466 MemRefType memRefTy) { 3467 if (!isLastMemrefDimUnitStride(memRefTy)) 3468 return op->emitOpError("most minor memref dim must have unit stride"); 3469 return success(); 3470 } 3471 3472 LogicalResult vector::LoadOp::verify() { 3473 VectorType resVecTy = getVectorType(); 3474 MemRefType memRefTy = getMemRefType(); 3475 3476 if (failed(verifyLoadStoreMemRefLayout(*this, memRefTy))) 3477 return failure(); 3478 3479 // Checks for vector memrefs. 3480 Type memElemTy = memRefTy.getElementType(); 3481 if (auto memVecTy = memElemTy.dyn_cast<VectorType>()) { 3482 if (memVecTy != resVecTy) 3483 return emitOpError("base memref and result vector types should match"); 3484 memElemTy = memVecTy.getElementType(); 3485 } 3486 3487 if (resVecTy.getElementType() != memElemTy) 3488 return emitOpError("base and result element types should match"); 3489 if (llvm::size(indices()) != memRefTy.getRank()) 3490 return emitOpError("requires ") << memRefTy.getRank() << " indices"; 3491 return success(); 3492 } 3493 3494 OpFoldResult LoadOp::fold(ArrayRef<Attribute>) { 3495 if (succeeded(foldMemRefCast(*this))) 3496 return getResult(); 3497 return OpFoldResult(); 3498 } 3499 3500 //===----------------------------------------------------------------------===// 3501 // StoreOp 3502 //===----------------------------------------------------------------------===// 3503 3504 LogicalResult vector::StoreOp::verify() { 3505 VectorType valueVecTy = getVectorType(); 3506 MemRefType memRefTy = getMemRefType(); 3507 3508 if (failed(verifyLoadStoreMemRefLayout(*this, memRefTy))) 3509 return failure(); 3510 3511 // Checks for vector memrefs. 3512 Type memElemTy = memRefTy.getElementType(); 3513 if (auto memVecTy = memElemTy.dyn_cast<VectorType>()) { 3514 if (memVecTy != valueVecTy) 3515 return emitOpError( 3516 "base memref and valueToStore vector types should match"); 3517 memElemTy = memVecTy.getElementType(); 3518 } 3519 3520 if (valueVecTy.getElementType() != memElemTy) 3521 return emitOpError("base and valueToStore element type should match"); 3522 if (llvm::size(indices()) != memRefTy.getRank()) 3523 return emitOpError("requires ") << memRefTy.getRank() << " indices"; 3524 return success(); 3525 } 3526 3527 LogicalResult StoreOp::fold(ArrayRef<Attribute> operands, 3528 SmallVectorImpl<OpFoldResult> &results) { 3529 return foldMemRefCast(*this); 3530 } 3531 3532 //===----------------------------------------------------------------------===// 3533 // MaskedLoadOp 3534 //===----------------------------------------------------------------------===// 3535 3536 LogicalResult MaskedLoadOp::verify() { 3537 VectorType maskVType = getMaskVectorType(); 3538 VectorType passVType = getPassThruVectorType(); 3539 VectorType resVType = getVectorType(); 3540 MemRefType memType = getMemRefType(); 3541 3542 if (resVType.getElementType() != memType.getElementType()) 3543 return emitOpError("base and result element type should match"); 3544 if (llvm::size(indices()) != memType.getRank()) 3545 return emitOpError("requires ") << memType.getRank() << " indices"; 3546 if (resVType.getDimSize(0) != maskVType.getDimSize(0)) 3547 return emitOpError("expected result dim to match mask dim"); 3548 if (resVType != passVType) 3549 return emitOpError("expected pass_thru of same type as result type"); 3550 return success(); 3551 } 3552 3553 namespace { 3554 class MaskedLoadFolder final : public OpRewritePattern<MaskedLoadOp> { 3555 public: 3556 using OpRewritePattern<MaskedLoadOp>::OpRewritePattern; 3557 LogicalResult matchAndRewrite(MaskedLoadOp load, 3558 PatternRewriter &rewriter) const override { 3559 switch (get1DMaskFormat(load.mask())) { 3560 case MaskFormat::AllTrue: 3561 rewriter.replaceOpWithNewOp<vector::LoadOp>(load, load.getType(), 3562 load.base(), load.indices()); 3563 return success(); 3564 case MaskFormat::AllFalse: 3565 rewriter.replaceOp(load, load.pass_thru()); 3566 return success(); 3567 case MaskFormat::Unknown: 3568 return failure(); 3569 } 3570 llvm_unreachable("Unexpected 1DMaskFormat on MaskedLoad"); 3571 } 3572 }; 3573 } // namespace 3574 3575 void MaskedLoadOp::getCanonicalizationPatterns(RewritePatternSet &results, 3576 MLIRContext *context) { 3577 results.add<MaskedLoadFolder>(context); 3578 } 3579 3580 OpFoldResult MaskedLoadOp::fold(ArrayRef<Attribute>) { 3581 if (succeeded(foldMemRefCast(*this))) 3582 return getResult(); 3583 return OpFoldResult(); 3584 } 3585 3586 //===----------------------------------------------------------------------===// 3587 // MaskedStoreOp 3588 //===----------------------------------------------------------------------===// 3589 3590 LogicalResult MaskedStoreOp::verify() { 3591 VectorType maskVType = getMaskVectorType(); 3592 VectorType valueVType = getVectorType(); 3593 MemRefType memType = getMemRefType(); 3594 3595 if (valueVType.getElementType() != memType.getElementType()) 3596 return emitOpError("base and valueToStore element type should match"); 3597 if (llvm::size(indices()) != memType.getRank()) 3598 return emitOpError("requires ") << memType.getRank() << " indices"; 3599 if (valueVType.getDimSize(0) != maskVType.getDimSize(0)) 3600 return emitOpError("expected valueToStore dim to match mask dim"); 3601 return success(); 3602 } 3603 3604 namespace { 3605 class MaskedStoreFolder final : public OpRewritePattern<MaskedStoreOp> { 3606 public: 3607 using OpRewritePattern<MaskedStoreOp>::OpRewritePattern; 3608 LogicalResult matchAndRewrite(MaskedStoreOp store, 3609 PatternRewriter &rewriter) const override { 3610 switch (get1DMaskFormat(store.mask())) { 3611 case MaskFormat::AllTrue: 3612 rewriter.replaceOpWithNewOp<vector::StoreOp>( 3613 store, store.valueToStore(), store.base(), store.indices()); 3614 return success(); 3615 case MaskFormat::AllFalse: 3616 rewriter.eraseOp(store); 3617 return success(); 3618 case MaskFormat::Unknown: 3619 return failure(); 3620 } 3621 llvm_unreachable("Unexpected 1DMaskFormat on MaskedStore"); 3622 } 3623 }; 3624 } // namespace 3625 3626 void MaskedStoreOp::getCanonicalizationPatterns(RewritePatternSet &results, 3627 MLIRContext *context) { 3628 results.add<MaskedStoreFolder>(context); 3629 } 3630 3631 LogicalResult MaskedStoreOp::fold(ArrayRef<Attribute> operands, 3632 SmallVectorImpl<OpFoldResult> &results) { 3633 return foldMemRefCast(*this); 3634 } 3635 3636 //===----------------------------------------------------------------------===// 3637 // GatherOp 3638 //===----------------------------------------------------------------------===// 3639 3640 LogicalResult GatherOp::verify() { 3641 VectorType indVType = getIndexVectorType(); 3642 VectorType maskVType = getMaskVectorType(); 3643 VectorType resVType = getVectorType(); 3644 MemRefType memType = getMemRefType(); 3645 3646 if (resVType.getElementType() != memType.getElementType()) 3647 return emitOpError("base and result element type should match"); 3648 if (llvm::size(indices()) != memType.getRank()) 3649 return emitOpError("requires ") << memType.getRank() << " indices"; 3650 if (resVType.getDimSize(0) != indVType.getDimSize(0)) 3651 return emitOpError("expected result dim to match indices dim"); 3652 if (resVType.getDimSize(0) != maskVType.getDimSize(0)) 3653 return emitOpError("expected result dim to match mask dim"); 3654 if (resVType != getPassThruVectorType()) 3655 return emitOpError("expected pass_thru of same type as result type"); 3656 return success(); 3657 } 3658 3659 namespace { 3660 class GatherFolder final : public OpRewritePattern<GatherOp> { 3661 public: 3662 using OpRewritePattern<GatherOp>::OpRewritePattern; 3663 LogicalResult matchAndRewrite(GatherOp gather, 3664 PatternRewriter &rewriter) const override { 3665 switch (get1DMaskFormat(gather.mask())) { 3666 case MaskFormat::AllTrue: 3667 return failure(); // no unmasked equivalent 3668 case MaskFormat::AllFalse: 3669 rewriter.replaceOp(gather, gather.pass_thru()); 3670 return success(); 3671 case MaskFormat::Unknown: 3672 return failure(); 3673 } 3674 llvm_unreachable("Unexpected 1DMaskFormat on GatherFolder"); 3675 } 3676 }; 3677 } // namespace 3678 3679 void GatherOp::getCanonicalizationPatterns(RewritePatternSet &results, 3680 MLIRContext *context) { 3681 results.add<GatherFolder>(context); 3682 } 3683 3684 //===----------------------------------------------------------------------===// 3685 // ScatterOp 3686 //===----------------------------------------------------------------------===// 3687 3688 LogicalResult ScatterOp::verify() { 3689 VectorType indVType = getIndexVectorType(); 3690 VectorType maskVType = getMaskVectorType(); 3691 VectorType valueVType = getVectorType(); 3692 MemRefType memType = getMemRefType(); 3693 3694 if (valueVType.getElementType() != memType.getElementType()) 3695 return emitOpError("base and valueToStore element type should match"); 3696 if (llvm::size(indices()) != memType.getRank()) 3697 return emitOpError("requires ") << memType.getRank() << " indices"; 3698 if (valueVType.getDimSize(0) != indVType.getDimSize(0)) 3699 return emitOpError("expected valueToStore dim to match indices dim"); 3700 if (valueVType.getDimSize(0) != maskVType.getDimSize(0)) 3701 return emitOpError("expected valueToStore dim to match mask dim"); 3702 return success(); 3703 } 3704 3705 namespace { 3706 class ScatterFolder final : public OpRewritePattern<ScatterOp> { 3707 public: 3708 using OpRewritePattern<ScatterOp>::OpRewritePattern; 3709 LogicalResult matchAndRewrite(ScatterOp scatter, 3710 PatternRewriter &rewriter) const override { 3711 switch (get1DMaskFormat(scatter.mask())) { 3712 case MaskFormat::AllTrue: 3713 return failure(); // no unmasked equivalent 3714 case MaskFormat::AllFalse: 3715 rewriter.eraseOp(scatter); 3716 return success(); 3717 case MaskFormat::Unknown: 3718 return failure(); 3719 } 3720 llvm_unreachable("Unexpected 1DMaskFormat on ScatterFolder"); 3721 } 3722 }; 3723 } // namespace 3724 3725 void ScatterOp::getCanonicalizationPatterns(RewritePatternSet &results, 3726 MLIRContext *context) { 3727 results.add<ScatterFolder>(context); 3728 } 3729 3730 //===----------------------------------------------------------------------===// 3731 // ExpandLoadOp 3732 //===----------------------------------------------------------------------===// 3733 3734 LogicalResult ExpandLoadOp::verify() { 3735 VectorType maskVType = getMaskVectorType(); 3736 VectorType passVType = getPassThruVectorType(); 3737 VectorType resVType = getVectorType(); 3738 MemRefType memType = getMemRefType(); 3739 3740 if (resVType.getElementType() != memType.getElementType()) 3741 return emitOpError("base and result element type should match"); 3742 if (llvm::size(indices()) != memType.getRank()) 3743 return emitOpError("requires ") << memType.getRank() << " indices"; 3744 if (resVType.getDimSize(0) != maskVType.getDimSize(0)) 3745 return emitOpError("expected result dim to match mask dim"); 3746 if (resVType != passVType) 3747 return emitOpError("expected pass_thru of same type as result type"); 3748 return success(); 3749 } 3750 3751 namespace { 3752 class ExpandLoadFolder final : public OpRewritePattern<ExpandLoadOp> { 3753 public: 3754 using OpRewritePattern<ExpandLoadOp>::OpRewritePattern; 3755 LogicalResult matchAndRewrite(ExpandLoadOp expand, 3756 PatternRewriter &rewriter) const override { 3757 switch (get1DMaskFormat(expand.mask())) { 3758 case MaskFormat::AllTrue: 3759 rewriter.replaceOpWithNewOp<vector::LoadOp>( 3760 expand, expand.getType(), expand.base(), expand.indices()); 3761 return success(); 3762 case MaskFormat::AllFalse: 3763 rewriter.replaceOp(expand, expand.pass_thru()); 3764 return success(); 3765 case MaskFormat::Unknown: 3766 return failure(); 3767 } 3768 llvm_unreachable("Unexpected 1DMaskFormat on ExpandLoadFolder"); 3769 } 3770 }; 3771 } // namespace 3772 3773 void ExpandLoadOp::getCanonicalizationPatterns(RewritePatternSet &results, 3774 MLIRContext *context) { 3775 results.add<ExpandLoadFolder>(context); 3776 } 3777 3778 //===----------------------------------------------------------------------===// 3779 // CompressStoreOp 3780 //===----------------------------------------------------------------------===// 3781 3782 LogicalResult CompressStoreOp::verify() { 3783 VectorType maskVType = getMaskVectorType(); 3784 VectorType valueVType = getVectorType(); 3785 MemRefType memType = getMemRefType(); 3786 3787 if (valueVType.getElementType() != memType.getElementType()) 3788 return emitOpError("base and valueToStore element type should match"); 3789 if (llvm::size(indices()) != memType.getRank()) 3790 return emitOpError("requires ") << memType.getRank() << " indices"; 3791 if (valueVType.getDimSize(0) != maskVType.getDimSize(0)) 3792 return emitOpError("expected valueToStore dim to match mask dim"); 3793 return success(); 3794 } 3795 3796 namespace { 3797 class CompressStoreFolder final : public OpRewritePattern<CompressStoreOp> { 3798 public: 3799 using OpRewritePattern<CompressStoreOp>::OpRewritePattern; 3800 LogicalResult matchAndRewrite(CompressStoreOp compress, 3801 PatternRewriter &rewriter) const override { 3802 switch (get1DMaskFormat(compress.mask())) { 3803 case MaskFormat::AllTrue: 3804 rewriter.replaceOpWithNewOp<vector::StoreOp>( 3805 compress, compress.valueToStore(), compress.base(), 3806 compress.indices()); 3807 return success(); 3808 case MaskFormat::AllFalse: 3809 rewriter.eraseOp(compress); 3810 return success(); 3811 case MaskFormat::Unknown: 3812 return failure(); 3813 } 3814 llvm_unreachable("Unexpected 1DMaskFormat on CompressStoreFolder"); 3815 } 3816 }; 3817 } // namespace 3818 3819 void CompressStoreOp::getCanonicalizationPatterns(RewritePatternSet &results, 3820 MLIRContext *context) { 3821 results.add<CompressStoreFolder>(context); 3822 } 3823 3824 //===----------------------------------------------------------------------===// 3825 // ShapeCastOp 3826 //===----------------------------------------------------------------------===// 3827 3828 /// Returns true if each element of 'a' is equal to the product of a contiguous 3829 /// sequence of the elements of 'b'. Returns false otherwise. 3830 static bool isValidShapeCast(ArrayRef<int64_t> a, ArrayRef<int64_t> b) { 3831 unsigned rankA = a.size(); 3832 unsigned rankB = b.size(); 3833 assert(rankA < rankB); 3834 3835 unsigned i = 0; 3836 unsigned j = 0; 3837 while (i < rankA && j < rankB) { 3838 int64_t dimA = a[i]; 3839 int64_t dimB = 1; 3840 while (dimB < dimA && j < rankB) 3841 dimB *= b[j++]; 3842 if (dimA != dimB) 3843 break; 3844 ++i; 3845 3846 // Handle the case when trailing dimensions are of size 1. 3847 // Include them into the contiguous sequence. 3848 auto isOne = [](int64_t v) { return v == 1; }; 3849 if (i < rankA && llvm::all_of(a.slice(i), isOne)) 3850 i = rankA; 3851 if (j < rankB && llvm::all_of(b.slice(j), isOne)) 3852 j = rankB; 3853 } 3854 3855 return i == rankA && j == rankB; 3856 } 3857 3858 static LogicalResult verifyVectorShapeCast(Operation *op, 3859 VectorType sourceVectorType, 3860 VectorType resultVectorType) { 3861 // Check that element type is the same. 3862 if (sourceVectorType.getElementType() != resultVectorType.getElementType()) 3863 return op->emitOpError("source/result vectors must have same element type"); 3864 auto sourceShape = sourceVectorType.getShape(); 3865 auto resultShape = resultVectorType.getShape(); 3866 3867 // Check that product of source dim sizes matches product of result dim sizes. 3868 int64_t sourceDimProduct = std::accumulate( 3869 sourceShape.begin(), sourceShape.end(), 1LL, std::multiplies<int64_t>{}); 3870 int64_t resultDimProduct = std::accumulate( 3871 resultShape.begin(), resultShape.end(), 1LL, std::multiplies<int64_t>{}); 3872 if (sourceDimProduct != resultDimProduct) 3873 return op->emitOpError("source/result number of elements must match"); 3874 3875 // Check that expanding/contracting rank cases. 3876 unsigned sourceRank = sourceVectorType.getRank(); 3877 unsigned resultRank = resultVectorType.getRank(); 3878 if (sourceRank < resultRank) { 3879 if (!isValidShapeCast(sourceShape, resultShape)) 3880 return op->emitOpError("invalid shape cast"); 3881 } else if (sourceRank > resultRank) { 3882 if (!isValidShapeCast(resultShape, sourceShape)) 3883 return op->emitOpError("invalid shape cast"); 3884 } 3885 return success(); 3886 } 3887 3888 LogicalResult ShapeCastOp::verify() { 3889 auto sourceVectorType = source().getType().dyn_cast_or_null<VectorType>(); 3890 auto resultVectorType = result().getType().dyn_cast_or_null<VectorType>(); 3891 3892 // Check if source/result are of vector type. 3893 if (sourceVectorType && resultVectorType) 3894 return verifyVectorShapeCast(*this, sourceVectorType, resultVectorType); 3895 3896 return success(); 3897 } 3898 3899 OpFoldResult ShapeCastOp::fold(ArrayRef<Attribute> operands) { 3900 // Nop shape cast. 3901 if (source().getType() == result().getType()) 3902 return source(); 3903 3904 // Canceling shape casts. 3905 if (auto otherOp = source().getDefiningOp<ShapeCastOp>()) { 3906 if (result().getType() == otherOp.source().getType()) 3907 return otherOp.source(); 3908 3909 // Only allows valid transitive folding. 3910 VectorType srcType = otherOp.source().getType().cast<VectorType>(); 3911 VectorType resultType = getResult().getType().cast<VectorType>(); 3912 if (srcType.getRank() < resultType.getRank()) { 3913 if (!isValidShapeCast(srcType.getShape(), resultType.getShape())) 3914 return {}; 3915 } else if (srcType.getRank() > resultType.getRank()) { 3916 if (!isValidShapeCast(resultType.getShape(), srcType.getShape())) 3917 return {}; 3918 } else { 3919 return {}; 3920 } 3921 3922 setOperand(otherOp.source()); 3923 return getResult(); 3924 } 3925 return {}; 3926 } 3927 3928 namespace { 3929 // Pattern to rewrite a ShapeCast(splat ConstantOp) -> ConstantOp. 3930 class ShapeCastConstantFolder final : public OpRewritePattern<ShapeCastOp> { 3931 public: 3932 using OpRewritePattern<ShapeCastOp>::OpRewritePattern; 3933 3934 LogicalResult matchAndRewrite(ShapeCastOp shapeCastOp, 3935 PatternRewriter &rewriter) const override { 3936 auto constantOp = shapeCastOp.source().getDefiningOp<arith::ConstantOp>(); 3937 if (!constantOp) 3938 return failure(); 3939 // Only handle splat for now. 3940 auto dense = constantOp.getValue().dyn_cast<SplatElementsAttr>(); 3941 if (!dense) 3942 return failure(); 3943 auto newAttr = 3944 DenseElementsAttr::get(shapeCastOp.getType().cast<VectorType>(), 3945 dense.getSplatValue<Attribute>()); 3946 rewriter.replaceOpWithNewOp<arith::ConstantOp>(shapeCastOp, newAttr); 3947 return success(); 3948 } 3949 }; 3950 3951 } // namespace 3952 3953 void ShapeCastOp::getCanonicalizationPatterns(RewritePatternSet &results, 3954 MLIRContext *context) { 3955 // Pattern to rewrite a ShapeCastOp(ConstantOp) -> ConstantOp. 3956 results.add<ShapeCastConstantFolder>(context); 3957 } 3958 3959 //===----------------------------------------------------------------------===// 3960 // VectorBitCastOp 3961 //===----------------------------------------------------------------------===// 3962 3963 LogicalResult BitCastOp::verify() { 3964 auto sourceVectorType = getSourceVectorType(); 3965 auto resultVectorType = getResultVectorType(); 3966 3967 for (int64_t i = 0, e = sourceVectorType.getRank() - 1; i < e; i++) { 3968 if (sourceVectorType.getDimSize(i) != resultVectorType.getDimSize(i)) 3969 return emitOpError("dimension size mismatch at: ") << i; 3970 } 3971 3972 DataLayout dataLayout = DataLayout::closest(*this); 3973 auto sourceElementBits = 3974 dataLayout.getTypeSizeInBits(sourceVectorType.getElementType()); 3975 auto resultElementBits = 3976 dataLayout.getTypeSizeInBits(resultVectorType.getElementType()); 3977 3978 if (sourceVectorType.getRank() == 0) { 3979 if (sourceElementBits != resultElementBits) 3980 return emitOpError("source/result bitwidth of the 0-D vector element " 3981 "types must be equal"); 3982 } else if (sourceElementBits * sourceVectorType.getShape().back() != 3983 resultElementBits * resultVectorType.getShape().back()) { 3984 return emitOpError( 3985 "source/result bitwidth of the minor 1-D vectors must be equal"); 3986 } 3987 3988 return success(); 3989 } 3990 3991 OpFoldResult BitCastOp::fold(ArrayRef<Attribute> operands) { 3992 // Nop cast. 3993 if (source().getType() == result().getType()) 3994 return source(); 3995 3996 // Canceling bitcasts. 3997 if (auto otherOp = source().getDefiningOp<BitCastOp>()) 3998 if (result().getType() == otherOp.source().getType()) 3999 return otherOp.source(); 4000 4001 Attribute sourceConstant = operands.front(); 4002 if (!sourceConstant) 4003 return {}; 4004 4005 Type srcElemType = getSourceVectorType().getElementType(); 4006 Type dstElemType = getResultVectorType().getElementType(); 4007 4008 if (auto floatPack = sourceConstant.dyn_cast<DenseFPElementsAttr>()) { 4009 if (floatPack.isSplat()) { 4010 auto splat = floatPack.getSplatValue<FloatAttr>(); 4011 4012 // Casting fp16 into fp32. 4013 if (srcElemType.isF16() && dstElemType.isF32()) { 4014 uint32_t bits = static_cast<uint32_t>( 4015 splat.getValue().bitcastToAPInt().getZExtValue()); 4016 // Duplicate the 16-bit pattern. 4017 bits = (bits << 16) | (bits & 0xffff); 4018 APInt intBits(32, bits); 4019 APFloat floatBits(llvm::APFloat::IEEEsingle(), intBits); 4020 return DenseElementsAttr::get(getResultVectorType(), floatBits); 4021 } 4022 } 4023 } 4024 4025 return {}; 4026 } 4027 4028 //===----------------------------------------------------------------------===// 4029 // TypeCastOp 4030 //===----------------------------------------------------------------------===// 4031 4032 static SmallVector<int64_t, 8> extractShape(MemRefType memRefType) { 4033 auto vectorType = memRefType.getElementType().dyn_cast<VectorType>(); 4034 SmallVector<int64_t, 8> res(memRefType.getShape().begin(), 4035 memRefType.getShape().end()); 4036 if (vectorType) 4037 res.append(vectorType.getShape().begin(), vectorType.getShape().end()); 4038 return res; 4039 } 4040 4041 /// Build the canonical memRefType with a single vector. 4042 /// E.g. memref<4 x 5 x vector<6 x f32>> -> memref<vector<4 x 5 x 6 x f32>>. 4043 void TypeCastOp::build(OpBuilder &builder, OperationState &result, 4044 Value source) { 4045 result.addOperands(source); 4046 MemRefType memRefType = source.getType().cast<MemRefType>(); 4047 VectorType vectorType = 4048 VectorType::get(extractShape(memRefType), 4049 getElementTypeOrSelf(getElementTypeOrSelf(memRefType))); 4050 result.addTypes(MemRefType::get({}, vectorType, MemRefLayoutAttrInterface(), 4051 memRefType.getMemorySpace())); 4052 } 4053 4054 LogicalResult TypeCastOp::verify() { 4055 MemRefType canonicalType = canonicalizeStridedLayout(getMemRefType()); 4056 if (!canonicalType.getLayout().isIdentity()) 4057 return emitOpError("expects operand to be a memref with identity layout"); 4058 if (!getResultMemRefType().getLayout().isIdentity()) 4059 return emitOpError("expects result to be a memref with identity layout"); 4060 if (getResultMemRefType().getMemorySpace() != 4061 getMemRefType().getMemorySpace()) 4062 return emitOpError("expects result in same memory space"); 4063 4064 auto sourceType = getMemRefType(); 4065 auto resultType = getResultMemRefType(); 4066 if (getElementTypeOrSelf(getElementTypeOrSelf(sourceType)) != 4067 getElementTypeOrSelf(getElementTypeOrSelf(resultType))) 4068 return emitOpError( 4069 "expects result and operand with same underlying scalar type: ") 4070 << resultType; 4071 if (extractShape(sourceType) != extractShape(resultType)) 4072 return emitOpError( 4073 "expects concatenated result and operand shapes to be equal: ") 4074 << resultType; 4075 return success(); 4076 } 4077 4078 //===----------------------------------------------------------------------===// 4079 // TransposeOp 4080 //===----------------------------------------------------------------------===// 4081 4082 void vector::TransposeOp::build(OpBuilder &builder, OperationState &result, 4083 Value vector, ArrayRef<int64_t> transp) { 4084 VectorType vt = vector.getType().cast<VectorType>(); 4085 SmallVector<int64_t, 4> transposedShape(vt.getRank()); 4086 for (unsigned i = 0; i < transp.size(); ++i) 4087 transposedShape[i] = vt.getShape()[transp[i]]; 4088 4089 result.addOperands(vector); 4090 result.addTypes(VectorType::get(transposedShape, vt.getElementType())); 4091 result.addAttribute(getTranspAttrStrName(), builder.getI64ArrayAttr(transp)); 4092 } 4093 4094 // Eliminates transpose operations, which produce values identical to their 4095 // input values. This happens when the dimensions of the input vector remain in 4096 // their original order after the transpose operation. 4097 OpFoldResult vector::TransposeOp::fold(ArrayRef<Attribute> operands) { 4098 SmallVector<int64_t, 4> transp; 4099 getTransp(transp); 4100 4101 // Check if the permutation of the dimensions contains sequential values: 4102 // {0, 1, 2, ...}. 4103 for (int64_t i = 0, e = transp.size(); i < e; i++) { 4104 if (transp[i] != i) 4105 return {}; 4106 } 4107 4108 return vector(); 4109 } 4110 4111 LogicalResult vector::TransposeOp::verify() { 4112 VectorType vectorType = getVectorType(); 4113 VectorType resultType = getResultType(); 4114 int64_t rank = resultType.getRank(); 4115 if (vectorType.getRank() != rank) 4116 return emitOpError("vector result rank mismatch: ") << rank; 4117 // Verify transposition array. 4118 auto transpAttr = transp().getValue(); 4119 int64_t size = transpAttr.size(); 4120 if (rank != size) 4121 return emitOpError("transposition length mismatch: ") << size; 4122 SmallVector<bool, 8> seen(rank, false); 4123 for (const auto &ta : llvm::enumerate(transpAttr)) { 4124 int64_t i = ta.value().cast<IntegerAttr>().getInt(); 4125 if (i < 0 || i >= rank) 4126 return emitOpError("transposition index out of range: ") << i; 4127 if (seen[i]) 4128 return emitOpError("duplicate position index: ") << i; 4129 seen[i] = true; 4130 if (resultType.getDimSize(ta.index()) != vectorType.getDimSize(i)) 4131 return emitOpError("dimension size mismatch at: ") << i; 4132 } 4133 return success(); 4134 } 4135 4136 namespace { 4137 4138 // Rewrites two back-to-back TransposeOp operations into a single TransposeOp. 4139 class TransposeFolder final : public OpRewritePattern<vector::TransposeOp> { 4140 public: 4141 using OpRewritePattern<vector::TransposeOp>::OpRewritePattern; 4142 4143 LogicalResult matchAndRewrite(vector::TransposeOp transposeOp, 4144 PatternRewriter &rewriter) const override { 4145 // Wrapper around vector::TransposeOp::getTransp() for cleaner code. 4146 auto getPermutation = [](vector::TransposeOp transpose) { 4147 SmallVector<int64_t, 4> permutation; 4148 transpose.getTransp(permutation); 4149 return permutation; 4150 }; 4151 4152 // Composes two permutations: result[i] = permutation1[permutation2[i]]. 4153 auto composePermutations = [](ArrayRef<int64_t> permutation1, 4154 ArrayRef<int64_t> permutation2) { 4155 SmallVector<int64_t, 4> result; 4156 for (auto index : permutation2) 4157 result.push_back(permutation1[index]); 4158 return result; 4159 }; 4160 4161 // Return if the input of 'transposeOp' is not defined by another transpose. 4162 vector::TransposeOp parentTransposeOp = 4163 transposeOp.vector().getDefiningOp<vector::TransposeOp>(); 4164 if (!parentTransposeOp) 4165 return failure(); 4166 4167 SmallVector<int64_t, 4> permutation = composePermutations( 4168 getPermutation(parentTransposeOp), getPermutation(transposeOp)); 4169 // Replace 'transposeOp' with a new transpose operation. 4170 rewriter.replaceOpWithNewOp<vector::TransposeOp>( 4171 transposeOp, transposeOp.getResult().getType(), 4172 parentTransposeOp.vector(), 4173 vector::getVectorSubscriptAttr(rewriter, permutation)); 4174 return success(); 4175 } 4176 }; 4177 4178 } // namespace 4179 4180 void vector::TransposeOp::getCanonicalizationPatterns( 4181 RewritePatternSet &results, MLIRContext *context) { 4182 results.add<TransposeFolder>(context); 4183 } 4184 4185 void vector::TransposeOp::getTransp(SmallVectorImpl<int64_t> &results) { 4186 populateFromInt64AttrArray(transp(), results); 4187 } 4188 4189 //===----------------------------------------------------------------------===// 4190 // ConstantMaskOp 4191 //===----------------------------------------------------------------------===// 4192 4193 LogicalResult ConstantMaskOp::verify() { 4194 auto resultType = getResult().getType().cast<VectorType>(); 4195 // Check the corner case of 0-D vectors first. 4196 if (resultType.getRank() == 0) { 4197 if (mask_dim_sizes().size() != 1) 4198 return emitError("array attr must have length 1 for 0-D vectors"); 4199 auto dim = mask_dim_sizes()[0].cast<IntegerAttr>().getInt(); 4200 if (dim != 0 && dim != 1) 4201 return emitError("mask dim size must be either 0 or 1 for 0-D vectors"); 4202 return success(); 4203 } 4204 4205 // Verify that array attr size matches the rank of the vector result. 4206 if (static_cast<int64_t>(mask_dim_sizes().size()) != resultType.getRank()) 4207 return emitOpError( 4208 "must specify array attr of size equal vector result rank"); 4209 // Verify that each array attr element is in bounds of corresponding vector 4210 // result dimension size. 4211 auto resultShape = resultType.getShape(); 4212 SmallVector<int64_t, 4> maskDimSizes; 4213 for (const auto &it : llvm::enumerate(mask_dim_sizes())) { 4214 int64_t attrValue = it.value().cast<IntegerAttr>().getInt(); 4215 if (attrValue < 0 || attrValue > resultShape[it.index()]) 4216 return emitOpError( 4217 "array attr of size out of bounds of vector result dimension size"); 4218 maskDimSizes.push_back(attrValue); 4219 } 4220 // Verify that if one mask dim size is zero, they all should be zero (because 4221 // the mask region is a conjunction of each mask dimension interval). 4222 bool anyZeros = llvm::is_contained(maskDimSizes, 0); 4223 bool allZeros = llvm::all_of(maskDimSizes, [](int64_t s) { return s == 0; }); 4224 if (anyZeros && !allZeros) 4225 return emitOpError("expected all mask dim sizes to be zeros, " 4226 "as a result of conjunction with zero mask dim"); 4227 return success(); 4228 } 4229 4230 //===----------------------------------------------------------------------===// 4231 // CreateMaskOp 4232 //===----------------------------------------------------------------------===// 4233 4234 LogicalResult CreateMaskOp::verify() { 4235 auto vectorType = getResult().getType().cast<VectorType>(); 4236 // Verify that an operand was specified for each result vector each dimension. 4237 if (vectorType.getRank() == 0) { 4238 if (getNumOperands() != 1) 4239 return emitOpError( 4240 "must specify exactly one operand for 0-D create_mask"); 4241 } else if (getNumOperands() != 4242 getResult().getType().cast<VectorType>().getRank()) { 4243 return emitOpError( 4244 "must specify an operand for each result vector dimension"); 4245 } 4246 return success(); 4247 } 4248 4249 namespace { 4250 4251 // Pattern to rewrite a CreateMaskOp with a ConstantMaskOp. 4252 class CreateMaskFolder final : public OpRewritePattern<CreateMaskOp> { 4253 public: 4254 using OpRewritePattern<CreateMaskOp>::OpRewritePattern; 4255 4256 LogicalResult matchAndRewrite(CreateMaskOp createMaskOp, 4257 PatternRewriter &rewriter) const override { 4258 // Return if any of 'createMaskOp' operands are not defined by a constant. 4259 auto isNotDefByConstant = [](Value operand) { 4260 return !isa_and_nonnull<arith::ConstantIndexOp>(operand.getDefiningOp()); 4261 }; 4262 if (llvm::any_of(createMaskOp.operands(), isNotDefByConstant)) 4263 return failure(); 4264 // Gather constant mask dimension sizes. 4265 SmallVector<int64_t, 4> maskDimSizes; 4266 for (auto it : llvm::zip(createMaskOp.operands(), 4267 createMaskOp.getType().getShape())) { 4268 auto *defOp = std::get<0>(it).getDefiningOp(); 4269 int64_t maxDimSize = std::get<1>(it); 4270 int64_t dimSize = cast<arith::ConstantIndexOp>(defOp).value(); 4271 dimSize = std::min(dimSize, maxDimSize); 4272 // If one of dim sizes is zero, set all dims to zero. 4273 if (dimSize <= 0) { 4274 maskDimSizes.assign(createMaskOp.getType().getRank(), 0); 4275 break; 4276 } 4277 maskDimSizes.push_back(dimSize); 4278 } 4279 // Replace 'createMaskOp' with ConstantMaskOp. 4280 rewriter.replaceOpWithNewOp<ConstantMaskOp>( 4281 createMaskOp, createMaskOp.getResult().getType(), 4282 vector::getVectorSubscriptAttr(rewriter, maskDimSizes)); 4283 return success(); 4284 } 4285 }; 4286 4287 } // namespace 4288 4289 void CreateMaskOp::getCanonicalizationPatterns(RewritePatternSet &results, 4290 MLIRContext *context) { 4291 results.add<CreateMaskFolder>(context); 4292 } 4293 4294 //===----------------------------------------------------------------------===// 4295 // ScanOp 4296 //===----------------------------------------------------------------------===// 4297 4298 LogicalResult ScanOp::verify() { 4299 VectorType srcType = getSourceType(); 4300 VectorType initialType = getInitialValueType(); 4301 // Check reduction dimension < rank. 4302 int64_t srcRank = srcType.getRank(); 4303 int64_t reductionDim = reduction_dim(); 4304 if (reductionDim >= srcRank) 4305 return emitOpError("reduction dimension ") 4306 << reductionDim << " has to be less than " << srcRank; 4307 4308 // Check that rank(initial_value) = rank(src) - 1. 4309 int64_t initialValueRank = initialType.getRank(); 4310 if (initialValueRank != srcRank - 1) 4311 return emitOpError("initial value rank ") 4312 << initialValueRank << " has to be equal to " << srcRank - 1; 4313 4314 // Check shapes of initial value and src. 4315 ArrayRef<int64_t> srcShape = srcType.getShape(); 4316 ArrayRef<int64_t> initialValueShapes = initialType.getShape(); 4317 SmallVector<int64_t> expectedShape; 4318 for (int i = 0; i < srcRank; i++) { 4319 if (i != reductionDim) 4320 expectedShape.push_back(srcShape[i]); 4321 } 4322 if (llvm::any_of(llvm::zip(initialValueShapes, expectedShape), 4323 [](std::tuple<int64_t, int64_t> s) { 4324 return std::get<0>(s) != std::get<1>(s); 4325 })) { 4326 return emitOpError("incompatible input/initial value shapes"); 4327 } 4328 4329 return success(); 4330 } 4331 4332 void mlir::vector::populateVectorToVectorCanonicalizationPatterns( 4333 RewritePatternSet &patterns) { 4334 patterns 4335 .add<CreateMaskFolder, MaskedLoadFolder, MaskedStoreFolder, GatherFolder, 4336 ScatterFolder, ExpandLoadFolder, CompressStoreFolder, 4337 StridedSliceConstantMaskFolder, TransposeFolder>( 4338 patterns.getContext()); 4339 } 4340 4341 //===----------------------------------------------------------------------===// 4342 // SplatOp 4343 //===----------------------------------------------------------------------===// 4344 4345 OpFoldResult SplatOp::fold(ArrayRef<Attribute> operands) { 4346 auto constOperand = operands.front(); 4347 if (!constOperand.isa_and_nonnull<IntegerAttr, FloatAttr>()) 4348 return {}; 4349 4350 // SplatElementsAttr::get treats single value for second arg as being a splat. 4351 return SplatElementsAttr::get(getType(), {constOperand}); 4352 } 4353 4354 //===----------------------------------------------------------------------===// 4355 // TableGen'd op method definitions 4356 //===----------------------------------------------------------------------===// 4357 4358 #define GET_OP_CLASSES 4359 #include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc" 4360