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