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