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 srcRank = srcVecType ? srcVecType.getRank() : 0;
2505     auto dstVecType = op.getType().cast<VectorType>();
2506     unsigned dstRank = dstVecType.getRank();
2507     unsigned rankDiff = dstRank - srcRank;
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 < srcRank; i++) {
2513       if (srcVecType.getDimSize(i) != dstVecType.getDimSize(i + rankDiff)) {
2514         lowerDimMatch = false;
2515         break;
2516       }
2517     }
2518     Value source = broadcast.getSource();
2519     // If the inner dimensions don't match, it means we need to extract from the
2520     // source of the orignal broadcast and then broadcast the extracted value.
2521     // We also need to handle degenerated cases where the source is effectively
2522     // just a single scalar.
2523     bool isScalarSrc = (srcRank == 0 || srcVecType.getNumElements() == 1);
2524     if (!lowerDimMatch && !isScalarSrc) {
2525       source = rewriter.create<ExtractStridedSliceOp>(
2526           op->getLoc(), source,
2527           getI64SubArray(op.getOffsets(), /* dropFront=*/rankDiff),
2528           getI64SubArray(op.getSizes(), /* dropFront=*/rankDiff),
2529           getI64SubArray(op.getStrides(), /* dropFront=*/rankDiff));
2530     }
2531     rewriter.replaceOpWithNewOp<BroadcastOp>(op, op.getType(), source);
2532     return success();
2533   }
2534 };
2535 
2536 /// Pattern to rewrite an ExtractStridedSliceOp(SplatOp) to SplatOp.
2537 class StridedSliceSplat final : public OpRewritePattern<ExtractStridedSliceOp> {
2538 public:
2539   using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern;
2540 
2541   LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
2542                                 PatternRewriter &rewriter) const override {
2543     auto splat = op.getVector().getDefiningOp<SplatOp>();
2544     if (!splat)
2545       return failure();
2546     rewriter.replaceOpWithNewOp<SplatOp>(op, op.getType(), splat.getInput());
2547     return success();
2548   }
2549 };
2550 
2551 } // namespace
2552 
2553 void ExtractStridedSliceOp::getCanonicalizationPatterns(
2554     RewritePatternSet &results, MLIRContext *context) {
2555   // Pattern to rewrite a ExtractStridedSliceOp(ConstantMaskOp) ->
2556   // ConstantMaskOp and ExtractStridedSliceOp(ConstantOp) -> ConstantOp.
2557   results.add<StridedSliceConstantMaskFolder, StridedSliceConstantFolder,
2558               StridedSliceBroadcast, StridedSliceSplat>(context);
2559 }
2560 
2561 //===----------------------------------------------------------------------===//
2562 // TransferReadOp
2563 //===----------------------------------------------------------------------===//
2564 
2565 /// 1. Builder that sets padding to zero and an empty mask (variant with attrs).
2566 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2567                            VectorType vectorType, Value source,
2568                            ValueRange indices, AffineMapAttr permutationMapAttr,
2569                            /*optional*/ ArrayAttr inBoundsAttr) {
2570   Type elemType = source.getType().cast<ShapedType>().getElementType();
2571   Value padding = builder.create<arith::ConstantOp>(
2572       result.location, elemType, builder.getZeroAttr(elemType));
2573   build(builder, result, vectorType, source, indices, permutationMapAttr,
2574         padding, /*mask=*/Value(), inBoundsAttr);
2575 }
2576 
2577 /// 2. Builder that sets padding to zero an empty mask (variant without attrs).
2578 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2579                            VectorType vectorType, Value source,
2580                            ValueRange indices, AffineMap permutationMap,
2581                            Optional<ArrayRef<bool>> inBounds) {
2582   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
2583   auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
2584                           ? builder.getBoolArrayAttr(inBounds.getValue())
2585                           : ArrayAttr();
2586   build(builder, result, vectorType, source, indices, permutationMapAttr,
2587         inBoundsAttr);
2588 }
2589 
2590 /// 3. Builder that sets permutation map to 'getMinorIdentityMap'.
2591 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2592                            VectorType vectorType, Value source,
2593                            ValueRange indices, Value padding,
2594                            Optional<ArrayRef<bool>> inBounds) {
2595   AffineMap permutationMap = getTransferMinorIdentityMap(
2596       source.getType().cast<ShapedType>(), vectorType);
2597   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
2598   auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
2599                           ? builder.getBoolArrayAttr(inBounds.getValue())
2600                           : ArrayAttr();
2601   build(builder, result, vectorType, source, indices, permutationMapAttr,
2602         padding,
2603         /*mask=*/Value(), inBoundsAttr);
2604 }
2605 
2606 /// 4. Builder that sets padding to zero and permutation map to
2607 /// 'getMinorIdentityMap'.
2608 void TransferReadOp::build(OpBuilder &builder, OperationState &result,
2609                            VectorType vectorType, Value source,
2610                            ValueRange indices,
2611                            Optional<ArrayRef<bool>> inBounds) {
2612   Type elemType = source.getType().cast<ShapedType>().getElementType();
2613   Value padding = builder.create<arith::ConstantOp>(
2614       result.location, elemType, builder.getZeroAttr(elemType));
2615   build(builder, result, vectorType, source, indices, padding, inBounds);
2616 }
2617 
2618 template <typename EmitFun>
2619 static LogicalResult verifyPermutationMap(AffineMap permutationMap,
2620                                           EmitFun emitOpError) {
2621   SmallVector<bool, 8> seen(permutationMap.getNumInputs(), false);
2622   for (auto expr : permutationMap.getResults()) {
2623     auto dim = expr.dyn_cast<AffineDimExpr>();
2624     auto zero = expr.dyn_cast<AffineConstantExpr>();
2625     if (zero) {
2626       if (zero.getValue() != 0) {
2627         return emitOpError(
2628             "requires a projected permutation_map (at most one dim or the zero "
2629             "constant can appear in each result)");
2630       }
2631       continue;
2632     }
2633     if (!dim) {
2634       return emitOpError("requires a projected permutation_map (at most one "
2635                          "dim or the zero constant can appear in each result)");
2636     }
2637     if (seen[dim.getPosition()]) {
2638       return emitOpError(
2639           "requires a permutation_map that is a permutation (found one dim "
2640           "used more than once)");
2641     }
2642     seen[dim.getPosition()] = true;
2643   }
2644   return success();
2645 }
2646 
2647 static LogicalResult
2648 verifyTransferOp(VectorTransferOpInterface op, ShapedType shapedType,
2649                  VectorType vectorType, VectorType maskType,
2650                  AffineMap permutationMap, ArrayAttr inBounds) {
2651   if (op->hasAttr("masked")) {
2652     return op->emitOpError("masked attribute has been removed. "
2653                            "Use in_bounds instead.");
2654   }
2655 
2656   if (!shapedType.isa<MemRefType, RankedTensorType>())
2657     return op->emitOpError(
2658         "requires source to be a memref or ranked tensor type");
2659 
2660   auto elementType = shapedType.getElementType();
2661   DataLayout dataLayout = DataLayout::closest(op);
2662   if (auto vectorElementType = elementType.dyn_cast<VectorType>()) {
2663     // Memref or tensor has vector element type.
2664     unsigned sourceVecSize =
2665         dataLayout.getTypeSizeInBits(vectorElementType.getElementType()) *
2666         vectorElementType.getShape().back();
2667     unsigned resultVecSize =
2668         dataLayout.getTypeSizeInBits(vectorType.getElementType()) *
2669         vectorType.getShape().back();
2670     if (resultVecSize % sourceVecSize != 0)
2671       return op->emitOpError(
2672           "requires the bitwidth of the minor 1-D vector to be an integral "
2673           "multiple of the bitwidth of the minor 1-D vector of the source");
2674 
2675     unsigned sourceVecEltRank = vectorElementType.getRank();
2676     unsigned resultVecRank = vectorType.getRank();
2677     if (sourceVecEltRank > resultVecRank)
2678       return op->emitOpError(
2679           "requires source vector element and vector result ranks to match.");
2680     unsigned rankOffset = resultVecRank - sourceVecEltRank;
2681     // Check that permutation map results match 'rankOffset' of vector type.
2682     if (permutationMap.getNumResults() != rankOffset)
2683       return op->emitOpError("requires a permutation_map with result dims of "
2684                              "the same rank as the vector type");
2685 
2686     if (maskType)
2687       return op->emitOpError("does not support masks with vector element type");
2688   } else {
2689     // Memref or tensor has scalar element type.
2690     unsigned minorSize =
2691         vectorType.getRank() == 0 ? 1 : vectorType.getShape().back();
2692     unsigned resultVecSize =
2693         dataLayout.getTypeSizeInBits(vectorType.getElementType()) * minorSize;
2694     if (resultVecSize % dataLayout.getTypeSizeInBits(elementType) != 0)
2695       return op->emitOpError(
2696           "requires the bitwidth of the minor 1-D vector to be an integral "
2697           "multiple of the bitwidth of the source element type");
2698 
2699     // Check that permutation map results match rank of vector type.
2700     if (permutationMap.getNumResults() != vectorType.getRank())
2701       return op->emitOpError("requires a permutation_map with result dims of "
2702                              "the same rank as the vector type");
2703 
2704     VectorType expectedMaskType =
2705         vector::detail::transferMaskType(vectorType, permutationMap);
2706     if (maskType && expectedMaskType != maskType)
2707       return op->emitOpError("expects mask type consistent with permutation "
2708                              "map: ")
2709              << maskType;
2710   }
2711 
2712   if (permutationMap.getNumSymbols() != 0)
2713     return op->emitOpError("requires permutation_map without symbols");
2714 
2715   if (permutationMap.getNumInputs() != shapedType.getRank())
2716     return op->emitOpError("requires a permutation_map with input dims of the "
2717                            "same rank as the source type");
2718 
2719   if (inBounds) {
2720     if (permutationMap.getNumResults() != static_cast<int64_t>(inBounds.size()))
2721       return op->emitOpError("expects the optional in_bounds attr of same rank "
2722                              "as permutation_map results: ")
2723              << AffineMapAttr::get(permutationMap)
2724              << " vs inBounds of size: " << inBounds.size();
2725     for (unsigned int i = 0; i < permutationMap.getNumResults(); ++i)
2726       if (permutationMap.getResult(i).isa<AffineConstantExpr>() &&
2727           !inBounds.getValue()[i].cast<BoolAttr>().getValue())
2728         return op->emitOpError("requires broadcast dimensions to be in-bounds");
2729   }
2730 
2731   return success();
2732 }
2733 
2734 static void printTransferAttrs(OpAsmPrinter &p, VectorTransferOpInterface op) {
2735   SmallVector<StringRef, 3> elidedAttrs;
2736   elidedAttrs.push_back(TransferReadOp::getOperandSegmentSizeAttr());
2737   if (op.permutation_map().isMinorIdentity())
2738     elidedAttrs.push_back(op.getPermutationMapAttrStrName());
2739   bool elideInBounds = true;
2740   if (auto inBounds = op.in_bounds()) {
2741     for (auto attr : *inBounds) {
2742       if (attr.template cast<BoolAttr>().getValue()) {
2743         elideInBounds = false;
2744         break;
2745       }
2746     }
2747   }
2748   if (elideInBounds)
2749     elidedAttrs.push_back(op.getInBoundsAttrStrName());
2750   p.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
2751 }
2752 
2753 void TransferReadOp::print(OpAsmPrinter &p) {
2754   p << " " << getSource() << "[" << getIndices() << "], " << getPadding();
2755   if (getMask())
2756     p << ", " << getMask();
2757   printTransferAttrs(p, *this);
2758   p << " : " << getShapedType() << ", " << getVectorType();
2759 }
2760 
2761 ParseResult TransferReadOp::parse(OpAsmParser &parser, OperationState &result) {
2762   auto &builder = parser.getBuilder();
2763   SMLoc typesLoc;
2764   OpAsmParser::UnresolvedOperand sourceInfo;
2765   SmallVector<OpAsmParser::UnresolvedOperand, 8> indexInfo;
2766   OpAsmParser::UnresolvedOperand paddingInfo;
2767   SmallVector<Type, 2> types;
2768   OpAsmParser::UnresolvedOperand maskInfo;
2769   // Parsing with support for paddingValue.
2770   if (parser.parseOperand(sourceInfo) ||
2771       parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square) ||
2772       parser.parseComma() || parser.parseOperand(paddingInfo))
2773     return failure();
2774   ParseResult hasMask = parser.parseOptionalComma();
2775   if (hasMask.succeeded()) {
2776     parser.parseOperand(maskInfo);
2777   }
2778   if (parser.parseOptionalAttrDict(result.attributes) ||
2779       parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types))
2780     return failure();
2781   if (types.size() != 2)
2782     return parser.emitError(typesLoc, "requires two types");
2783   auto indexType = builder.getIndexType();
2784   auto shapedType = types[0].dyn_cast<ShapedType>();
2785   if (!shapedType || !shapedType.isa<MemRefType, RankedTensorType>())
2786     return parser.emitError(typesLoc, "requires memref or ranked tensor type");
2787   VectorType vectorType = types[1].dyn_cast<VectorType>();
2788   if (!vectorType)
2789     return parser.emitError(typesLoc, "requires vector type");
2790   auto permutationAttrName = TransferReadOp::getPermutationMapAttrStrName();
2791   Attribute mapAttr = result.attributes.get(permutationAttrName);
2792   if (!mapAttr) {
2793     auto permMap = getTransferMinorIdentityMap(shapedType, vectorType);
2794     // Update `mapAttr` that is used later to determine mask type.
2795     mapAttr = AffineMapAttr::get(permMap);
2796     result.attributes.set(permutationAttrName, mapAttr);
2797   }
2798   if (parser.resolveOperand(sourceInfo, shapedType, result.operands) ||
2799       parser.resolveOperands(indexInfo, indexType, result.operands) ||
2800       parser.resolveOperand(paddingInfo, shapedType.getElementType(),
2801                             result.operands))
2802     return failure();
2803   if (hasMask.succeeded()) {
2804     if (shapedType.getElementType().dyn_cast<VectorType>())
2805       return parser.emitError(
2806           maskInfo.location, "does not support masks with vector element type");
2807     auto map = mapAttr.dyn_cast<AffineMapAttr>().getValue();
2808     // Instead of adding the mask type as an op type, compute it based on the
2809     // vector type and the permutation map (to keep the type signature small).
2810     auto maskType = mlir::vector::detail::transferMaskType(vectorType, map);
2811     if (parser.resolveOperand(maskInfo, maskType, result.operands))
2812       return failure();
2813   }
2814   result.addAttribute(
2815       TransferReadOp::getOperandSegmentSizeAttr(),
2816       builder.getI32VectorAttr({1, static_cast<int32_t>(indexInfo.size()), 1,
2817                                 static_cast<int32_t>(hasMask.succeeded())}));
2818   return parser.addTypeToList(vectorType, result.types);
2819 }
2820 
2821 LogicalResult TransferReadOp::verify() {
2822   // Consistency of elemental types in source and vector.
2823   ShapedType shapedType = getShapedType();
2824   VectorType vectorType = getVectorType();
2825   VectorType maskType = getMaskType();
2826   auto paddingType = getPadding().getType();
2827   auto permutationMap = getPermutationMap();
2828   auto sourceElementType = shapedType.getElementType();
2829 
2830   if (static_cast<int64_t>(getIndices().size()) != shapedType.getRank())
2831     return emitOpError("requires ") << shapedType.getRank() << " indices";
2832 
2833   if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()),
2834                               shapedType, vectorType, maskType, permutationMap,
2835                               getInBounds() ? *getInBounds() : ArrayAttr())))
2836     return failure();
2837 
2838   if (auto sourceVectorElementType = sourceElementType.dyn_cast<VectorType>()) {
2839     // Source has vector element type.
2840     // Check that 'sourceVectorElementType' and 'paddingType' types match.
2841     if (sourceVectorElementType != paddingType)
2842       return emitOpError(
2843           "requires source element type and padding type to match.");
2844 
2845   } else {
2846     // Check that 'paddingType' is valid to store in a vector type.
2847     if (!VectorType::isValidElementType(paddingType))
2848       return emitOpError("requires valid padding vector elemental type");
2849 
2850     // Check that padding type and vector element types match.
2851     if (paddingType != sourceElementType)
2852       return emitOpError(
2853           "requires formal padding and source of the same elemental type");
2854   }
2855 
2856   return verifyPermutationMap(permutationMap,
2857                               [&](Twine t) { return emitOpError(t); });
2858 }
2859 
2860 /// This is a common class used for patterns of the form
2861 /// ```
2862 ///    someop(memrefcast) -> someop
2863 /// ```
2864 /// It folds the source of the memref.cast into the root operation directly.
2865 static LogicalResult foldMemRefCast(Operation *op) {
2866   bool folded = false;
2867   for (OpOperand &operand : op->getOpOperands()) {
2868     auto castOp = operand.get().getDefiningOp<memref::CastOp>();
2869     if (castOp && memref::CastOp::canFoldIntoConsumerOp(castOp)) {
2870       operand.set(castOp.getOperand());
2871       folded = true;
2872     }
2873   }
2874   return success(folded);
2875 }
2876 
2877 static LogicalResult foldTensorCast(Operation *op) {
2878   bool folded = false;
2879   for (OpOperand &operand : op->getOpOperands()) {
2880     auto castOp = operand.get().getDefiningOp<tensor::CastOp>();
2881     if (castOp && tensor::canFoldIntoConsumerOp(castOp)) {
2882       operand.set(castOp.getOperand());
2883       folded = true;
2884     }
2885   }
2886   return success(folded);
2887 }
2888 
2889 template <typename TransferOp>
2890 static bool isInBounds(TransferOp op, int64_t resultIdx, int64_t indicesIdx) {
2891   // TODO: support more aggressive createOrFold on:
2892   // `op.indices()[indicesIdx] + vectorType < dim(op.source(), indicesIdx)`
2893   if (op.getShapedType().isDynamicDim(indicesIdx))
2894     return false;
2895   Value index = op.getIndices()[indicesIdx];
2896   auto cstOp = index.getDefiningOp<arith::ConstantIndexOp>();
2897   if (!cstOp)
2898     return false;
2899 
2900   int64_t sourceSize = op.getShapedType().getDimSize(indicesIdx);
2901   int64_t vectorSize = op.getVectorType().getDimSize(resultIdx);
2902 
2903   return cstOp.value() + vectorSize <= sourceSize;
2904 }
2905 
2906 template <typename TransferOp>
2907 static LogicalResult foldTransferInBoundsAttribute(TransferOp op) {
2908   // TODO: support 0-d corner case.
2909   // TODO: Be less conservative.
2910   if (op.getTransferRank() == 0)
2911     return failure();
2912   AffineMap permutationMap = op.getPermutationMap();
2913   bool changed = false;
2914   SmallVector<bool, 4> newInBounds;
2915   newInBounds.reserve(op.getTransferRank());
2916   for (unsigned i = 0; i < op.getTransferRank(); ++i) {
2917     // Already marked as in-bounds, nothing to see here.
2918     if (op.isDimInBounds(i)) {
2919       newInBounds.push_back(true);
2920       continue;
2921     }
2922     // Currently out-of-bounds, check whether we can statically determine it is
2923     // inBounds.
2924     auto dimExpr = permutationMap.getResult(i).dyn_cast<AffineDimExpr>();
2925     assert(dimExpr && "Broadcast dims must be in-bounds");
2926     auto inBounds =
2927         isInBounds(op, /*resultIdx=*/i, /*indicesIdx=*/dimExpr.getPosition());
2928     newInBounds.push_back(inBounds);
2929     // We commit the pattern if it is "more inbounds".
2930     changed |= inBounds;
2931   }
2932   if (!changed)
2933     return failure();
2934   // OpBuilder is only used as a helper to build an I64ArrayAttr.
2935   OpBuilder b(op.getContext());
2936   op->setAttr(TransferOp::getInBoundsAttrStrName(),
2937               b.getBoolArrayAttr(newInBounds));
2938   return success();
2939 }
2940 
2941 ///  ```
2942 ///  %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
2943 ///    : vector<1x4xf32>, tensor<4x4xf32>
2944 ///  %0 = vector.transfer_read %w0[%c1, %c0], %cf0 {in_bounds = [true, true]}
2945 ///    : tensor<4x4xf32>, vector<1x4xf32>
2946 ///  ```
2947 ///  -> Folds into
2948 ///  ```
2949 ///  %v0
2950 ///  ```
2951 static Value foldRAW(TransferReadOp readOp) {
2952   if (!readOp.getShapedType().isa<RankedTensorType>())
2953     return {};
2954   auto defWrite = readOp.getSource().getDefiningOp<vector::TransferWriteOp>();
2955   while (defWrite) {
2956     if (checkSameValueRAW(defWrite, readOp))
2957       return defWrite.getVector();
2958     if (!isDisjointTransferIndices(
2959             cast<VectorTransferOpInterface>(defWrite.getOperation()),
2960             cast<VectorTransferOpInterface>(readOp.getOperation())))
2961       break;
2962     defWrite = defWrite.getSource().getDefiningOp<vector::TransferWriteOp>();
2963   }
2964   return {};
2965 }
2966 
2967 OpFoldResult TransferReadOp::fold(ArrayRef<Attribute>) {
2968   if (Value vec = foldRAW(*this))
2969     return vec;
2970   /// transfer_read(memrefcast) -> transfer_read
2971   if (succeeded(foldTransferInBoundsAttribute(*this)))
2972     return getResult();
2973   if (succeeded(foldMemRefCast(*this)))
2974     return getResult();
2975   if (succeeded(foldTensorCast(*this)))
2976     return getResult();
2977   return OpFoldResult();
2978 }
2979 
2980 Optional<SmallVector<int64_t, 4>> TransferReadOp::getShapeForUnroll() {
2981   return llvm::to_vector<4>(getVectorType().getShape());
2982 }
2983 
2984 void TransferReadOp::getEffects(
2985     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
2986         &effects) {
2987   if (getShapedType().isa<MemRefType>())
2988     effects.emplace_back(MemoryEffects::Read::get(), getSource(),
2989                          SideEffects::DefaultResource::get());
2990 }
2991 
2992 namespace {
2993 /// Fold transfer_reads of a tensor.extract_slice op. E.g.:
2994 ///
2995 /// ```
2996 /// %0 = tensor.extract_slice %t[%a, %b] [%c, %d] [1, 1]
2997 ///     : tensor<?x?xf32> to tensor<?x?xf32>
2998 /// %1 = vector.transfer_read %0[%e, %f], %cst {in_bounds = [true, true]}
2999 ///     : tensor<?x?xf32>, vector<4x5xf32>
3000 /// ```
3001 /// is rewritten to:
3002 /// ```
3003 /// %p0 = arith.addi %a, %e : index
3004 /// %p1 = arith.addi %b, %f : index
3005 /// %1 = vector.transfer_read %t[%p0, %p1], %cst {in_bounds = [true, true]}
3006 ///     : tensor<?x?xf32>, vector<4x5xf32>
3007 /// ```
3008 struct FoldExtractSliceIntoTransferRead
3009     : public OpRewritePattern<TransferReadOp> {
3010 public:
3011   using OpRewritePattern<TransferReadOp>::OpRewritePattern;
3012 
3013   LogicalResult matchAndRewrite(TransferReadOp xferOp,
3014                                 PatternRewriter &rewriter) const override {
3015     // TODO: support 0-d corner case.
3016     if (xferOp.getTransferRank() == 0)
3017       return failure();
3018     if (xferOp.hasOutOfBoundsDim())
3019       return failure();
3020     if (!xferOp.getPermutationMap().isIdentity())
3021       return failure();
3022     if (xferOp.getMask())
3023       return failure();
3024     auto extractOp = xferOp.getSource().getDefiningOp<tensor::ExtractSliceOp>();
3025     if (!extractOp)
3026       return failure();
3027     if (!extractOp.hasUnitStride())
3028       return failure();
3029 
3030     // Bail on illegal rank-reduction: we need to check that the rank-reduced
3031     // dims are exactly the leading dims. I.e. the following is illegal:
3032     // ```
3033     //    %0 = tensor.extract_slice %t[0,0,0][2,1,4][1,1,1] :
3034     //      tensor<2x1x4xf32> to tensor<2x4xf32>
3035     //    %1 = vector.transfer_read %0[0,0], %cst :
3036     //      tensor<2x4xf32>, vector<2x4xf32>
3037     // ```
3038     //
3039     // Cannot fold into:
3040     // ```
3041     //    %0 = vector.transfer_read %t[0,0,0], %cst :
3042     //      tensor<2x1x4xf32>, vector<2x4xf32>
3043     // ```
3044     // For this, check the trailing `vectorRank` dims of the extract_slice
3045     // result tensor match the trailing dims of the inferred result tensor.
3046     int64_t rankReduced =
3047         extractOp.getSourceType().getRank() - extractOp.getType().getRank();
3048     int64_t vectorRank = xferOp.getVectorType().getRank();
3049     RankedTensorType inferredDestTensorType =
3050         tensor::ExtractSliceOp::inferResultType(
3051             extractOp.getSourceType(), extractOp.getMixedOffsets(),
3052             extractOp.getMixedSizes(), extractOp.getMixedStrides());
3053     auto actualDestTensorShape = extractOp.getType().getShape();
3054     if (rankReduced > 0 &&
3055         actualDestTensorShape.take_back(vectorRank) !=
3056             inferredDestTensorType.getShape().take_back(vectorRank))
3057       return failure();
3058 
3059     SmallVector<Value> newIndices;
3060     // In case this is a rank-reducing ExtractSliceOp, copy rank-reduced
3061     // indices first.
3062     for (int64_t i = 0; i < rankReduced; ++i) {
3063       OpFoldResult offset = extractOp.getMixedOffsets()[i];
3064       newIndices.push_back(getValueOrCreateConstantIndexOp(
3065           rewriter, extractOp.getLoc(), offset));
3066     }
3067     for (const auto &it : llvm::enumerate(xferOp.getIndices())) {
3068       OpFoldResult offset =
3069           extractOp.getMixedOffsets()[it.index() + rankReduced];
3070       newIndices.push_back(rewriter.create<arith::AddIOp>(
3071           xferOp->getLoc(), it.value(),
3072           getValueOrCreateConstantIndexOp(rewriter, extractOp.getLoc(),
3073                                           offset)));
3074     }
3075     SmallVector<bool> inBounds(xferOp.getTransferRank(), true);
3076     rewriter.replaceOpWithNewOp<TransferReadOp>(
3077         xferOp, xferOp.getVectorType(), extractOp.source(), newIndices,
3078         xferOp.getPadding(), ArrayRef<bool>{inBounds});
3079 
3080     return success();
3081   }
3082 };
3083 } // namespace
3084 
3085 void TransferReadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3086                                                  MLIRContext *context) {
3087   results.add<FoldExtractSliceIntoTransferRead>(context);
3088 }
3089 
3090 //===----------------------------------------------------------------------===//
3091 // TransferWriteOp
3092 //===----------------------------------------------------------------------===//
3093 
3094 /// 1. Builder with type inference.
3095 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3096                             Value vector, Value dest, ValueRange indices,
3097                             AffineMapAttr permutationMapAttr,
3098                             /*optional*/ Value mask,
3099                             /*optional*/ ArrayAttr inBoundsAttr) {
3100   Type resultType = dest.getType().dyn_cast<RankedTensorType>();
3101   build(builder, result, resultType, vector, dest, indices, permutationMapAttr,
3102         mask, inBoundsAttr);
3103 }
3104 
3105 /// 2. Builder with type inference that sets an empty mask (variant with attrs).
3106 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3107                             Value vector, Value dest, ValueRange indices,
3108                             AffineMapAttr permutationMapAttr,
3109                             /*optional*/ ArrayAttr inBoundsAttr) {
3110   build(builder, result, vector, dest, indices, permutationMapAttr,
3111         /*mask=*/Value(), inBoundsAttr);
3112 }
3113 
3114 /// 3. Builder with type inference that sets an empty mask (variant without
3115 /// attrs)
3116 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3117                             Value vector, Value dest, ValueRange indices,
3118                             AffineMap permutationMap,
3119                             Optional<ArrayRef<bool>> inBounds) {
3120   auto permutationMapAttr = AffineMapAttr::get(permutationMap);
3121   auto inBoundsAttr = (inBounds && !inBounds.getValue().empty())
3122                           ? builder.getBoolArrayAttr(inBounds.getValue())
3123                           : ArrayAttr();
3124   build(builder, result, vector, dest, indices, permutationMapAttr,
3125         /*mask=*/Value(), inBoundsAttr);
3126 }
3127 
3128 /// 4. Builder with type inference that sets an empty mask and sets permutation
3129 ///    map to 'getMinorIdentityMap'.
3130 void TransferWriteOp::build(OpBuilder &builder, OperationState &result,
3131                             Value vector, Value dest, ValueRange indices,
3132                             Optional<ArrayRef<bool>> inBounds) {
3133   auto vectorType = vector.getType().cast<VectorType>();
3134   AffineMap permutationMap = getTransferMinorIdentityMap(
3135       dest.getType().cast<ShapedType>(), vectorType);
3136   build(builder, result, vector, dest, indices, permutationMap, inBounds);
3137 }
3138 
3139 ParseResult TransferWriteOp::parse(OpAsmParser &parser,
3140                                    OperationState &result) {
3141   auto &builder = parser.getBuilder();
3142   SMLoc typesLoc;
3143   OpAsmParser::UnresolvedOperand vectorInfo, sourceInfo;
3144   SmallVector<OpAsmParser::UnresolvedOperand, 8> indexInfo;
3145   SmallVector<Type, 2> types;
3146   OpAsmParser::UnresolvedOperand maskInfo;
3147   if (parser.parseOperand(vectorInfo) || parser.parseComma() ||
3148       parser.parseOperand(sourceInfo) ||
3149       parser.parseOperandList(indexInfo, OpAsmParser::Delimiter::Square))
3150     return failure();
3151   ParseResult hasMask = parser.parseOptionalComma();
3152   if (hasMask.succeeded() && parser.parseOperand(maskInfo))
3153     return failure();
3154   if (parser.parseOptionalAttrDict(result.attributes) ||
3155       parser.getCurrentLocation(&typesLoc) || parser.parseColonTypeList(types))
3156     return failure();
3157   if (types.size() != 2)
3158     return parser.emitError(typesLoc, "requires two types");
3159   auto indexType = builder.getIndexType();
3160   VectorType vectorType = types[0].dyn_cast<VectorType>();
3161   if (!vectorType)
3162     return parser.emitError(typesLoc, "requires vector type");
3163   ShapedType shapedType = types[1].dyn_cast<ShapedType>();
3164   if (!shapedType || !shapedType.isa<MemRefType, RankedTensorType>())
3165     return parser.emitError(typesLoc, "requires memref or ranked tensor type");
3166   auto permutationAttrName = TransferWriteOp::getPermutationMapAttrStrName();
3167   auto attr = result.attributes.get(permutationAttrName);
3168   if (!attr) {
3169     auto permMap = getTransferMinorIdentityMap(shapedType, vectorType);
3170     result.attributes.set(permutationAttrName, AffineMapAttr::get(permMap));
3171   }
3172   if (parser.resolveOperand(vectorInfo, vectorType, result.operands) ||
3173       parser.resolveOperand(sourceInfo, shapedType, result.operands) ||
3174       parser.resolveOperands(indexInfo, indexType, result.operands))
3175     return failure();
3176   if (hasMask.succeeded()) {
3177     if (shapedType.getElementType().dyn_cast<VectorType>())
3178       return parser.emitError(
3179           maskInfo.location, "does not support masks with vector element type");
3180     auto maskType = VectorType::get(vectorType.getShape(), builder.getI1Type());
3181     if (parser.resolveOperand(maskInfo, maskType, result.operands))
3182       return failure();
3183   }
3184   result.addAttribute(
3185       TransferWriteOp::getOperandSegmentSizeAttr(),
3186       builder.getI32VectorAttr({1, 1, static_cast<int32_t>(indexInfo.size()),
3187                                 static_cast<int32_t>(hasMask.succeeded())}));
3188   return failure(shapedType.isa<RankedTensorType>() &&
3189                  parser.addTypeToList(shapedType, result.types));
3190 }
3191 
3192 void TransferWriteOp::print(OpAsmPrinter &p) {
3193   p << " " << getVector() << ", " << getSource() << "[" << getIndices() << "]";
3194   if (getMask())
3195     p << ", " << getMask();
3196   printTransferAttrs(p, *this);
3197   p << " : " << getVectorType() << ", " << getShapedType();
3198 }
3199 
3200 LogicalResult TransferWriteOp::verify() {
3201   // Consistency of elemental types in shape and vector.
3202   ShapedType shapedType = getShapedType();
3203   VectorType vectorType = getVectorType();
3204   VectorType maskType = getMaskType();
3205   auto permutationMap = getPermutationMap();
3206 
3207   if (llvm::size(getIndices()) != shapedType.getRank())
3208     return emitOpError("requires ") << shapedType.getRank() << " indices";
3209 
3210   // We do not allow broadcast dimensions on TransferWriteOps for the moment,
3211   // as the semantics is unclear. This can be revisited later if necessary.
3212   if (hasBroadcastDim())
3213     return emitOpError("should not have broadcast dimensions");
3214 
3215   if (failed(verifyTransferOp(cast<VectorTransferOpInterface>(getOperation()),
3216                               shapedType, vectorType, maskType, permutationMap,
3217                               getInBounds() ? *getInBounds() : ArrayAttr())))
3218     return failure();
3219 
3220   return verifyPermutationMap(permutationMap,
3221                               [&](Twine t) { return emitOpError(t); });
3222 }
3223 
3224 /// Fold:
3225 /// ```
3226 ///    %t1 = ...
3227 ///    %v = vector.transfer_read %t0[%c0...], {in_bounds = [true...]} :
3228 ///      tensor<static_sizesxf32>, vector<static_sizesxf32>
3229 ///    %t2 = vector.transfer_write %v, %t1[%c0...] {in_bounds = [true...]} :
3230 ///      vector<static_sizesxf32>, tensor<static_sizesxf32>
3231 /// ```
3232 ///
3233 /// into:
3234 ///
3235 /// ```
3236 ///    %t0
3237 /// ```
3238 ///
3239 /// The producer of t1 may or may not be DCE'd depending on whether it is a
3240 /// block argument or has side effects.
3241 static LogicalResult foldReadInitWrite(TransferWriteOp write,
3242                                        ArrayRef<Attribute>,
3243                                        SmallVectorImpl<OpFoldResult> &results) {
3244   // TODO: support 0-d corner case.
3245   if (write.getTransferRank() == 0)
3246     return failure();
3247   auto rankedTensorType =
3248       write.getSource().getType().dyn_cast<RankedTensorType>();
3249   // If not operating on tensors, bail.
3250   if (!rankedTensorType)
3251     return failure();
3252   // If no read, bail.
3253   auto read = write.getVector().getDefiningOp<vector::TransferReadOp>();
3254   if (!read)
3255     return failure();
3256   // TODO: support 0-d corner case.
3257   if (read.getTransferRank() == 0)
3258     return failure();
3259   // For now, only accept minor identity. Future: composition is minor identity.
3260   if (!read.getPermutationMap().isMinorIdentity() ||
3261       !write.getPermutationMap().isMinorIdentity())
3262     return failure();
3263   // Bail on mismatching ranks.
3264   if (read.getTransferRank() != write.getTransferRank())
3265     return failure();
3266   // Bail on potential out-of-bounds accesses.
3267   if (read.hasOutOfBoundsDim() || write.hasOutOfBoundsDim())
3268     return failure();
3269   // Tensor types must be the same.
3270   if (read.getSource().getType() != rankedTensorType)
3271     return failure();
3272   // Vector types must be the same.
3273   if (read.getVectorType() != write.getVectorType())
3274     return failure();
3275   // Vector and Tensor shapes must match.
3276   if (read.getVectorType().getShape() != rankedTensorType.getShape())
3277     return failure();
3278   // If any index is nonzero.
3279   auto isNotConstantZero = [](Value v) {
3280     auto cstOp = v.getDefiningOp<arith::ConstantIndexOp>();
3281     return !cstOp || cstOp.value() != 0;
3282   };
3283   if (llvm::any_of(read.getIndices(), isNotConstantZero) ||
3284       llvm::any_of(write.getIndices(), isNotConstantZero))
3285     return failure();
3286   // Success.
3287   results.push_back(read.getSource());
3288   return success();
3289 }
3290 
3291 static bool checkSameValueWAR(vector::TransferReadOp read,
3292                               vector::TransferWriteOp write) {
3293   return read.getSource() == write.getSource() &&
3294          read.getIndices() == write.getIndices() &&
3295          read.getPermutationMap() == write.getPermutationMap() &&
3296          read.getVectorType() == write.getVectorType() && !read.getMask() &&
3297          !write.getMask();
3298 }
3299 /// Fold transfer_write write after read:
3300 /// ```
3301 ///    %t0 = ...
3302 ///    %v = vector.transfer_read %t0[%c0...] :
3303 ///      tensor<static_sizesxf32>, vector<static_sizesxf32>
3304 ///    %t1 = vector.transfer_write %v, %t0[%c0...] :
3305 ///      vector<static_sizesxf32>, tensor<static_sizesxf32>
3306 /// ```
3307 ///
3308 /// into:
3309 ///
3310 /// ```
3311 ///    %t0
3312 /// ```
3313 static LogicalResult foldWAR(TransferWriteOp write,
3314                              SmallVectorImpl<OpFoldResult> &results) {
3315   if (!write.getSource().getType().isa<RankedTensorType>())
3316     return failure();
3317   auto read = write.getVector().getDefiningOp<vector::TransferReadOp>();
3318   if (!read)
3319     return failure();
3320 
3321   if (!checkSameValueWAR(read, write))
3322     return failure();
3323   results.push_back(read.getSource());
3324   return success();
3325 }
3326 
3327 LogicalResult TransferWriteOp::fold(ArrayRef<Attribute> operands,
3328                                     SmallVectorImpl<OpFoldResult> &results) {
3329   if (succeeded(foldReadInitWrite(*this, operands, results)))
3330     return success();
3331   if (succeeded(foldWAR(*this, results)))
3332     return success();
3333   if (succeeded(foldTransferInBoundsAttribute(*this)))
3334     return success();
3335   return foldMemRefCast(*this);
3336 }
3337 
3338 Optional<SmallVector<int64_t, 4>> TransferWriteOp::getShapeForUnroll() {
3339   return llvm::to_vector<4>(getVectorType().getShape());
3340 }
3341 
3342 void TransferWriteOp::getEffects(
3343     SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
3344         &effects) {
3345   if (getShapedType().isa<MemRefType>())
3346     effects.emplace_back(MemoryEffects::Write::get(), getSource(),
3347                          SideEffects::DefaultResource::get());
3348 }
3349 
3350 namespace {
3351 /// Remove dead transfer write from the SSA chain so that it an be eliminated by
3352 /// DCE
3353 /// ```
3354 ///  %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
3355 ///    : vector<1x4xf32>, tensor<4x4xf32>
3356 ///  %w1 = vector.transfer_write %v0, %w0[%c2, %c0] {in_bounds = [true, true]}
3357 ///    : vector<1x4xf32>, tensor<4x4xf32>
3358 ///  %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]}
3359 ///    : vector<1x4xf32>, tensor<4x4xf32>
3360 /// ```
3361 ///
3362 /// into:
3363 ///
3364 /// ```
3365 ///  %w0 = vector.transfer_write %v0, %arg0[%c1, %c0] {in_bounds = [true, true]}
3366 ///    : vector<1x4xf32>, tensor<4x4xf32>
3367 ///  %w1 = vector.transfer_write %v0, %arg0[%c2, %c0] {in_bounds = [true, true]}
3368 ///    : vector<1x4xf32>, tensor<4x4xf32>
3369 ///  %w2 = vector.transfer_write %v1, %w1[%c1, %c0] {in_bounds = [true, true]}
3370 ///    : vector<1x4xf32>, tensor<4x4xf32>
3371 /// ```
3372 ///
3373 /// `%w0 = vector.transfer_write` op will be removed by DCE if it doesn't have
3374 /// any other uses.
3375 class FoldWaw final : public OpRewritePattern<TransferWriteOp> {
3376 public:
3377   using OpRewritePattern<TransferWriteOp>::OpRewritePattern;
3378   LogicalResult matchAndRewrite(TransferWriteOp writeOp,
3379                                 PatternRewriter &rewriter) const override {
3380     if (!writeOp.getShapedType().isa<RankedTensorType>())
3381       return failure();
3382     vector::TransferWriteOp writeToModify = writeOp;
3383 
3384     auto defWrite =
3385         writeOp.getSource().getDefiningOp<vector::TransferWriteOp>();
3386     while (defWrite) {
3387       if (checkSameValueWAW(writeOp, defWrite)) {
3388         writeToModify.getSourceMutable().assign(defWrite.getSource());
3389         return success();
3390       }
3391       if (!isDisjointTransferIndices(
3392               cast<VectorTransferOpInterface>(defWrite.getOperation()),
3393               cast<VectorTransferOpInterface>(writeOp.getOperation())))
3394         break;
3395       // If the previous write op doesn't have any other use we an safely look
3396       // at the previous store to see if it can be removed.
3397       if (!defWrite->hasOneUse())
3398         break;
3399       writeToModify = defWrite;
3400       defWrite = defWrite.getSource().getDefiningOp<vector::TransferWriteOp>();
3401     }
3402     return failure();
3403   }
3404 };
3405 
3406 /// Fold tensor.insert_slice into vector.transfer_write if the transfer_write
3407 /// could directly write to the insert_slice's destination. E.g.:
3408 ///
3409 /// ```
3410 /// %0 = vector.transfer_write %v, %t1[%c0, %c0] {in_bounds = [true, true]}
3411 ///     : vector<4x5xf32>, tensor<4x5xf32>
3412 /// %1 = tensor.insert_slice %0 into %t2[%a, %b] [4, 5] [1, 1]
3413 ///     : tensor<4x5xf32> into tensor<?x?xf32>
3414 /// ```
3415 /// is rewritten to:
3416 /// ```
3417 /// %1 = vector.transfer_write %v, %t2[%a, %b] {in_bounds = [true, true]}
3418 ///     : vector<4x5xf32>, tensor<?x?xf32>
3419 /// ```
3420 struct FoldInsertSliceIntoTransferWrite
3421     : public OpRewritePattern<tensor::InsertSliceOp> {
3422 public:
3423   using OpRewritePattern<tensor::InsertSliceOp>::OpRewritePattern;
3424 
3425   LogicalResult matchAndRewrite(tensor::InsertSliceOp insertOp,
3426                                 PatternRewriter &rewriter) const override {
3427     if (!insertOp.hasUnitStride())
3428       return failure();
3429 
3430     auto xferOp = insertOp.source().getDefiningOp<TransferWriteOp>();
3431     if (!xferOp)
3432       return failure();
3433     // TODO: support 0-d corner case.
3434     if (xferOp.getTransferRank() == 0)
3435       return failure();
3436 
3437     if (xferOp.hasOutOfBoundsDim())
3438       return failure();
3439     if (xferOp.getVectorType().getRank() != xferOp.getShapedType().getRank())
3440       return failure();
3441     if (xferOp.getMask())
3442       return failure();
3443     // Fold only if the TransferWriteOp completely overwrites the `source` with
3444     // a vector. I.e., the result of the TransferWriteOp is a new tensor whose
3445     // content is the data of the vector.
3446     if (!llvm::equal(xferOp.getVectorType().getShape(),
3447                      xferOp.getShapedType().getShape()))
3448       return failure();
3449     if (!xferOp.getPermutationMap().isIdentity())
3450       return failure();
3451 
3452     // Bail on illegal rank-reduction: we need to check that the rank-reduced
3453     // dims are exactly the leading dims. I.e. the following is illegal:
3454     // ```
3455     //    %0 = vector.transfer_write %v, %t[0,0], %cst :
3456     //      vector<2x4xf32>, tensor<2x4xf32>
3457     //    %1 = tensor.insert_slice %0 into %tt[0,0,0][2,1,4][1,1,1] :
3458     //      tensor<2x4xf32> into tensor<2x1x4xf32>
3459     // ```
3460     //
3461     // Cannot fold into:
3462     // ```
3463     //    %0 = vector.transfer_write %v, %t[0,0,0], %cst :
3464     //      vector<2x4xf32>, tensor<2x1x4xf32>
3465     // ```
3466     // For this, check the trailing `vectorRank` dims of the insert_slice result
3467     // tensor match the trailing dims of the inferred result tensor.
3468     int64_t rankReduced =
3469         insertOp.getType().getRank() - insertOp.getSourceType().getRank();
3470     int64_t vectorRank = xferOp.getVectorType().getRank();
3471     RankedTensorType inferredSourceTensorType =
3472         tensor::ExtractSliceOp::inferResultType(
3473             insertOp.getType(), insertOp.getMixedOffsets(),
3474             insertOp.getMixedSizes(), insertOp.getMixedStrides());
3475     auto actualSourceTensorShape = insertOp.getSourceType().getShape();
3476     if (rankReduced > 0 &&
3477         actualSourceTensorShape.take_back(vectorRank) !=
3478             inferredSourceTensorType.getShape().take_back(vectorRank))
3479       return failure();
3480 
3481     SmallVector<Value> indices = getValueOrCreateConstantIndexOp(
3482         rewriter, insertOp.getLoc(), insertOp.getMixedOffsets());
3483     SmallVector<bool> inBounds(xferOp.getTransferRank(), true);
3484     rewriter.replaceOpWithNewOp<TransferWriteOp>(insertOp, xferOp.getVector(),
3485                                                  insertOp.dest(), indices,
3486                                                  ArrayRef<bool>{inBounds});
3487     return success();
3488   }
3489 };
3490 } // namespace
3491 
3492 void TransferWriteOp::getCanonicalizationPatterns(RewritePatternSet &results,
3493                                                   MLIRContext *context) {
3494   results.add<FoldWaw, FoldInsertSliceIntoTransferWrite>(context);
3495 }
3496 
3497 //===----------------------------------------------------------------------===//
3498 // LoadOp
3499 //===----------------------------------------------------------------------===//
3500 
3501 static LogicalResult verifyLoadStoreMemRefLayout(Operation *op,
3502                                                  MemRefType memRefTy) {
3503   if (!isLastMemrefDimUnitStride(memRefTy))
3504     return op->emitOpError("most minor memref dim must have unit stride");
3505   return success();
3506 }
3507 
3508 LogicalResult vector::LoadOp::verify() {
3509   VectorType resVecTy = getVectorType();
3510   MemRefType memRefTy = getMemRefType();
3511 
3512   if (failed(verifyLoadStoreMemRefLayout(*this, memRefTy)))
3513     return failure();
3514 
3515   // Checks for vector memrefs.
3516   Type memElemTy = memRefTy.getElementType();
3517   if (auto memVecTy = memElemTy.dyn_cast<VectorType>()) {
3518     if (memVecTy != resVecTy)
3519       return emitOpError("base memref and result vector types should match");
3520     memElemTy = memVecTy.getElementType();
3521   }
3522 
3523   if (resVecTy.getElementType() != memElemTy)
3524     return emitOpError("base and result element types should match");
3525   if (llvm::size(getIndices()) != memRefTy.getRank())
3526     return emitOpError("requires ") << memRefTy.getRank() << " indices";
3527   return success();
3528 }
3529 
3530 OpFoldResult LoadOp::fold(ArrayRef<Attribute>) {
3531   if (succeeded(foldMemRefCast(*this)))
3532     return getResult();
3533   return OpFoldResult();
3534 }
3535 
3536 //===----------------------------------------------------------------------===//
3537 // StoreOp
3538 //===----------------------------------------------------------------------===//
3539 
3540 LogicalResult vector::StoreOp::verify() {
3541   VectorType valueVecTy = getVectorType();
3542   MemRefType memRefTy = getMemRefType();
3543 
3544   if (failed(verifyLoadStoreMemRefLayout(*this, memRefTy)))
3545     return failure();
3546 
3547   // Checks for vector memrefs.
3548   Type memElemTy = memRefTy.getElementType();
3549   if (auto memVecTy = memElemTy.dyn_cast<VectorType>()) {
3550     if (memVecTy != valueVecTy)
3551       return emitOpError(
3552           "base memref and valueToStore vector types should match");
3553     memElemTy = memVecTy.getElementType();
3554   }
3555 
3556   if (valueVecTy.getElementType() != memElemTy)
3557     return emitOpError("base and valueToStore element type should match");
3558   if (llvm::size(getIndices()) != memRefTy.getRank())
3559     return emitOpError("requires ") << memRefTy.getRank() << " indices";
3560   return success();
3561 }
3562 
3563 LogicalResult StoreOp::fold(ArrayRef<Attribute> operands,
3564                             SmallVectorImpl<OpFoldResult> &results) {
3565   return foldMemRefCast(*this);
3566 }
3567 
3568 //===----------------------------------------------------------------------===//
3569 // MaskedLoadOp
3570 //===----------------------------------------------------------------------===//
3571 
3572 LogicalResult MaskedLoadOp::verify() {
3573   VectorType maskVType = getMaskVectorType();
3574   VectorType passVType = getPassThruVectorType();
3575   VectorType resVType = getVectorType();
3576   MemRefType memType = getMemRefType();
3577 
3578   if (resVType.getElementType() != memType.getElementType())
3579     return emitOpError("base and result element type should match");
3580   if (llvm::size(getIndices()) != memType.getRank())
3581     return emitOpError("requires ") << memType.getRank() << " indices";
3582   if (resVType.getDimSize(0) != maskVType.getDimSize(0))
3583     return emitOpError("expected result dim to match mask dim");
3584   if (resVType != passVType)
3585     return emitOpError("expected pass_thru of same type as result type");
3586   return success();
3587 }
3588 
3589 namespace {
3590 class MaskedLoadFolder final : public OpRewritePattern<MaskedLoadOp> {
3591 public:
3592   using OpRewritePattern<MaskedLoadOp>::OpRewritePattern;
3593   LogicalResult matchAndRewrite(MaskedLoadOp load,
3594                                 PatternRewriter &rewriter) const override {
3595     switch (get1DMaskFormat(load.getMask())) {
3596     case MaskFormat::AllTrue:
3597       rewriter.replaceOpWithNewOp<vector::LoadOp>(
3598           load, load.getType(), load.getBase(), load.getIndices());
3599       return success();
3600     case MaskFormat::AllFalse:
3601       rewriter.replaceOp(load, load.getPassThru());
3602       return success();
3603     case MaskFormat::Unknown:
3604       return failure();
3605     }
3606     llvm_unreachable("Unexpected 1DMaskFormat on MaskedLoad");
3607   }
3608 };
3609 } // namespace
3610 
3611 void MaskedLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3612                                                MLIRContext *context) {
3613   results.add<MaskedLoadFolder>(context);
3614 }
3615 
3616 OpFoldResult MaskedLoadOp::fold(ArrayRef<Attribute>) {
3617   if (succeeded(foldMemRefCast(*this)))
3618     return getResult();
3619   return OpFoldResult();
3620 }
3621 
3622 //===----------------------------------------------------------------------===//
3623 // MaskedStoreOp
3624 //===----------------------------------------------------------------------===//
3625 
3626 LogicalResult MaskedStoreOp::verify() {
3627   VectorType maskVType = getMaskVectorType();
3628   VectorType valueVType = getVectorType();
3629   MemRefType memType = getMemRefType();
3630 
3631   if (valueVType.getElementType() != memType.getElementType())
3632     return emitOpError("base and valueToStore element type should match");
3633   if (llvm::size(getIndices()) != memType.getRank())
3634     return emitOpError("requires ") << memType.getRank() << " indices";
3635   if (valueVType.getDimSize(0) != maskVType.getDimSize(0))
3636     return emitOpError("expected valueToStore dim to match mask dim");
3637   return success();
3638 }
3639 
3640 namespace {
3641 class MaskedStoreFolder final : public OpRewritePattern<MaskedStoreOp> {
3642 public:
3643   using OpRewritePattern<MaskedStoreOp>::OpRewritePattern;
3644   LogicalResult matchAndRewrite(MaskedStoreOp store,
3645                                 PatternRewriter &rewriter) const override {
3646     switch (get1DMaskFormat(store.getMask())) {
3647     case MaskFormat::AllTrue:
3648       rewriter.replaceOpWithNewOp<vector::StoreOp>(
3649           store, store.getValueToStore(), store.getBase(), store.getIndices());
3650       return success();
3651     case MaskFormat::AllFalse:
3652       rewriter.eraseOp(store);
3653       return success();
3654     case MaskFormat::Unknown:
3655       return failure();
3656     }
3657     llvm_unreachable("Unexpected 1DMaskFormat on MaskedStore");
3658   }
3659 };
3660 } // namespace
3661 
3662 void MaskedStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
3663                                                 MLIRContext *context) {
3664   results.add<MaskedStoreFolder>(context);
3665 }
3666 
3667 LogicalResult MaskedStoreOp::fold(ArrayRef<Attribute> operands,
3668                                   SmallVectorImpl<OpFoldResult> &results) {
3669   return foldMemRefCast(*this);
3670 }
3671 
3672 //===----------------------------------------------------------------------===//
3673 // GatherOp
3674 //===----------------------------------------------------------------------===//
3675 
3676 LogicalResult GatherOp::verify() {
3677   VectorType indVType = getIndexVectorType();
3678   VectorType maskVType = getMaskVectorType();
3679   VectorType resVType = getVectorType();
3680   MemRefType memType = getMemRefType();
3681 
3682   if (resVType.getElementType() != memType.getElementType())
3683     return emitOpError("base and result element type should match");
3684   if (llvm::size(getIndices()) != memType.getRank())
3685     return emitOpError("requires ") << memType.getRank() << " indices";
3686   if (resVType.getDimSize(0) != indVType.getDimSize(0))
3687     return emitOpError("expected result dim to match indices dim");
3688   if (resVType.getDimSize(0) != maskVType.getDimSize(0))
3689     return emitOpError("expected result dim to match mask dim");
3690   if (resVType != getPassThruVectorType())
3691     return emitOpError("expected pass_thru of same type as result type");
3692   return success();
3693 }
3694 
3695 namespace {
3696 class GatherFolder final : public OpRewritePattern<GatherOp> {
3697 public:
3698   using OpRewritePattern<GatherOp>::OpRewritePattern;
3699   LogicalResult matchAndRewrite(GatherOp gather,
3700                                 PatternRewriter &rewriter) const override {
3701     switch (get1DMaskFormat(gather.getMask())) {
3702     case MaskFormat::AllTrue:
3703       return failure(); // no unmasked equivalent
3704     case MaskFormat::AllFalse:
3705       rewriter.replaceOp(gather, gather.getPassThru());
3706       return success();
3707     case MaskFormat::Unknown:
3708       return failure();
3709     }
3710     llvm_unreachable("Unexpected 1DMaskFormat on GatherFolder");
3711   }
3712 };
3713 } // namespace
3714 
3715 void GatherOp::getCanonicalizationPatterns(RewritePatternSet &results,
3716                                            MLIRContext *context) {
3717   results.add<GatherFolder>(context);
3718 }
3719 
3720 //===----------------------------------------------------------------------===//
3721 // ScatterOp
3722 //===----------------------------------------------------------------------===//
3723 
3724 LogicalResult ScatterOp::verify() {
3725   VectorType indVType = getIndexVectorType();
3726   VectorType maskVType = getMaskVectorType();
3727   VectorType valueVType = getVectorType();
3728   MemRefType memType = getMemRefType();
3729 
3730   if (valueVType.getElementType() != memType.getElementType())
3731     return emitOpError("base and valueToStore element type should match");
3732   if (llvm::size(getIndices()) != memType.getRank())
3733     return emitOpError("requires ") << memType.getRank() << " indices";
3734   if (valueVType.getDimSize(0) != indVType.getDimSize(0))
3735     return emitOpError("expected valueToStore dim to match indices dim");
3736   if (valueVType.getDimSize(0) != maskVType.getDimSize(0))
3737     return emitOpError("expected valueToStore dim to match mask dim");
3738   return success();
3739 }
3740 
3741 namespace {
3742 class ScatterFolder final : public OpRewritePattern<ScatterOp> {
3743 public:
3744   using OpRewritePattern<ScatterOp>::OpRewritePattern;
3745   LogicalResult matchAndRewrite(ScatterOp scatter,
3746                                 PatternRewriter &rewriter) const override {
3747     switch (get1DMaskFormat(scatter.getMask())) {
3748     case MaskFormat::AllTrue:
3749       return failure(); // no unmasked equivalent
3750     case MaskFormat::AllFalse:
3751       rewriter.eraseOp(scatter);
3752       return success();
3753     case MaskFormat::Unknown:
3754       return failure();
3755     }
3756     llvm_unreachable("Unexpected 1DMaskFormat on ScatterFolder");
3757   }
3758 };
3759 } // namespace
3760 
3761 void ScatterOp::getCanonicalizationPatterns(RewritePatternSet &results,
3762                                             MLIRContext *context) {
3763   results.add<ScatterFolder>(context);
3764 }
3765 
3766 //===----------------------------------------------------------------------===//
3767 // ExpandLoadOp
3768 //===----------------------------------------------------------------------===//
3769 
3770 LogicalResult ExpandLoadOp::verify() {
3771   VectorType maskVType = getMaskVectorType();
3772   VectorType passVType = getPassThruVectorType();
3773   VectorType resVType = getVectorType();
3774   MemRefType memType = getMemRefType();
3775 
3776   if (resVType.getElementType() != memType.getElementType())
3777     return emitOpError("base and result element type should match");
3778   if (llvm::size(getIndices()) != memType.getRank())
3779     return emitOpError("requires ") << memType.getRank() << " indices";
3780   if (resVType.getDimSize(0) != maskVType.getDimSize(0))
3781     return emitOpError("expected result dim to match mask dim");
3782   if (resVType != passVType)
3783     return emitOpError("expected pass_thru of same type as result type");
3784   return success();
3785 }
3786 
3787 namespace {
3788 class ExpandLoadFolder final : public OpRewritePattern<ExpandLoadOp> {
3789 public:
3790   using OpRewritePattern<ExpandLoadOp>::OpRewritePattern;
3791   LogicalResult matchAndRewrite(ExpandLoadOp expand,
3792                                 PatternRewriter &rewriter) const override {
3793     switch (get1DMaskFormat(expand.getMask())) {
3794     case MaskFormat::AllTrue:
3795       rewriter.replaceOpWithNewOp<vector::LoadOp>(
3796           expand, expand.getType(), expand.getBase(), expand.getIndices());
3797       return success();
3798     case MaskFormat::AllFalse:
3799       rewriter.replaceOp(expand, expand.getPassThru());
3800       return success();
3801     case MaskFormat::Unknown:
3802       return failure();
3803     }
3804     llvm_unreachable("Unexpected 1DMaskFormat on ExpandLoadFolder");
3805   }
3806 };
3807 } // namespace
3808 
3809 void ExpandLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
3810                                                MLIRContext *context) {
3811   results.add<ExpandLoadFolder>(context);
3812 }
3813 
3814 //===----------------------------------------------------------------------===//
3815 // CompressStoreOp
3816 //===----------------------------------------------------------------------===//
3817 
3818 LogicalResult CompressStoreOp::verify() {
3819   VectorType maskVType = getMaskVectorType();
3820   VectorType valueVType = getVectorType();
3821   MemRefType memType = getMemRefType();
3822 
3823   if (valueVType.getElementType() != memType.getElementType())
3824     return emitOpError("base and valueToStore element type should match");
3825   if (llvm::size(getIndices()) != memType.getRank())
3826     return emitOpError("requires ") << memType.getRank() << " indices";
3827   if (valueVType.getDimSize(0) != maskVType.getDimSize(0))
3828     return emitOpError("expected valueToStore dim to match mask dim");
3829   return success();
3830 }
3831 
3832 namespace {
3833 class CompressStoreFolder final : public OpRewritePattern<CompressStoreOp> {
3834 public:
3835   using OpRewritePattern<CompressStoreOp>::OpRewritePattern;
3836   LogicalResult matchAndRewrite(CompressStoreOp compress,
3837                                 PatternRewriter &rewriter) const override {
3838     switch (get1DMaskFormat(compress.getMask())) {
3839     case MaskFormat::AllTrue:
3840       rewriter.replaceOpWithNewOp<vector::StoreOp>(
3841           compress, compress.getValueToStore(), compress.getBase(),
3842           compress.getIndices());
3843       return success();
3844     case MaskFormat::AllFalse:
3845       rewriter.eraseOp(compress);
3846       return success();
3847     case MaskFormat::Unknown:
3848       return failure();
3849     }
3850     llvm_unreachable("Unexpected 1DMaskFormat on CompressStoreFolder");
3851   }
3852 };
3853 } // namespace
3854 
3855 void CompressStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
3856                                                   MLIRContext *context) {
3857   results.add<CompressStoreFolder>(context);
3858 }
3859 
3860 //===----------------------------------------------------------------------===//
3861 // ShapeCastOp
3862 //===----------------------------------------------------------------------===//
3863 
3864 /// Returns true if each element of 'a' is equal to the product of a contiguous
3865 /// sequence of the elements of 'b'. Returns false otherwise.
3866 static bool isValidShapeCast(ArrayRef<int64_t> a, ArrayRef<int64_t> b) {
3867   unsigned rankA = a.size();
3868   unsigned rankB = b.size();
3869   assert(rankA < rankB);
3870 
3871   unsigned i = 0;
3872   unsigned j = 0;
3873   while (i < rankA && j < rankB) {
3874     int64_t dimA = a[i];
3875     int64_t dimB = 1;
3876     while (dimB < dimA && j < rankB)
3877       dimB *= b[j++];
3878     if (dimA != dimB)
3879       break;
3880     ++i;
3881 
3882     // Handle the case when trailing dimensions are of size 1.
3883     // Include them into the contiguous sequence.
3884     auto isOne = [](int64_t v) { return v == 1; };
3885     if (i < rankA && llvm::all_of(a.slice(i), isOne))
3886       i = rankA;
3887     if (j < rankB && llvm::all_of(b.slice(j), isOne))
3888       j = rankB;
3889   }
3890 
3891   return i == rankA && j == rankB;
3892 }
3893 
3894 static LogicalResult verifyVectorShapeCast(Operation *op,
3895                                            VectorType sourceVectorType,
3896                                            VectorType resultVectorType) {
3897   // Check that element type is the same.
3898   if (sourceVectorType.getElementType() != resultVectorType.getElementType())
3899     return op->emitOpError("source/result vectors must have same element type");
3900   auto sourceShape = sourceVectorType.getShape();
3901   auto resultShape = resultVectorType.getShape();
3902 
3903   // Check that product of source dim sizes matches product of result dim sizes.
3904   int64_t sourceDimProduct = std::accumulate(
3905       sourceShape.begin(), sourceShape.end(), 1LL, std::multiplies<int64_t>{});
3906   int64_t resultDimProduct = std::accumulate(
3907       resultShape.begin(), resultShape.end(), 1LL, std::multiplies<int64_t>{});
3908   if (sourceDimProduct != resultDimProduct)
3909     return op->emitOpError("source/result number of elements must match");
3910 
3911   // Check that expanding/contracting rank cases.
3912   unsigned sourceRank = sourceVectorType.getRank();
3913   unsigned resultRank = resultVectorType.getRank();
3914   if (sourceRank < resultRank) {
3915     if (!isValidShapeCast(sourceShape, resultShape))
3916       return op->emitOpError("invalid shape cast");
3917   } else if (sourceRank > resultRank) {
3918     if (!isValidShapeCast(resultShape, sourceShape))
3919       return op->emitOpError("invalid shape cast");
3920   }
3921   return success();
3922 }
3923 
3924 LogicalResult ShapeCastOp::verify() {
3925   auto sourceVectorType = getSource().getType().dyn_cast_or_null<VectorType>();
3926   auto resultVectorType = getResult().getType().dyn_cast_or_null<VectorType>();
3927 
3928   // Check if source/result are of vector type.
3929   if (sourceVectorType && resultVectorType)
3930     return verifyVectorShapeCast(*this, sourceVectorType, resultVectorType);
3931 
3932   return success();
3933 }
3934 
3935 OpFoldResult ShapeCastOp::fold(ArrayRef<Attribute> operands) {
3936   // Nop shape cast.
3937   if (getSource().getType() == getResult().getType())
3938     return getSource();
3939 
3940   // Canceling shape casts.
3941   if (auto otherOp = getSource().getDefiningOp<ShapeCastOp>()) {
3942     if (getResult().getType() == otherOp.getSource().getType())
3943       return otherOp.getSource();
3944 
3945     // Only allows valid transitive folding.
3946     VectorType srcType = otherOp.getSource().getType().cast<VectorType>();
3947     VectorType resultType = getResult().getType().cast<VectorType>();
3948     if (srcType.getRank() < resultType.getRank()) {
3949       if (!isValidShapeCast(srcType.getShape(), resultType.getShape()))
3950         return {};
3951     } else if (srcType.getRank() > resultType.getRank()) {
3952       if (!isValidShapeCast(resultType.getShape(), srcType.getShape()))
3953         return {};
3954     } else {
3955       return {};
3956     }
3957 
3958     setOperand(otherOp.getSource());
3959     return getResult();
3960   }
3961   return {};
3962 }
3963 
3964 namespace {
3965 // Pattern to rewrite a ShapeCast(splat ConstantOp) -> ConstantOp.
3966 class ShapeCastConstantFolder final : public OpRewritePattern<ShapeCastOp> {
3967 public:
3968   using OpRewritePattern<ShapeCastOp>::OpRewritePattern;
3969 
3970   LogicalResult matchAndRewrite(ShapeCastOp shapeCastOp,
3971                                 PatternRewriter &rewriter) const override {
3972     auto constantOp =
3973         shapeCastOp.getSource().getDefiningOp<arith::ConstantOp>();
3974     if (!constantOp)
3975       return failure();
3976     // Only handle splat for now.
3977     auto dense = constantOp.getValue().dyn_cast<SplatElementsAttr>();
3978     if (!dense)
3979       return failure();
3980     auto newAttr =
3981         DenseElementsAttr::get(shapeCastOp.getType().cast<VectorType>(),
3982                                dense.getSplatValue<Attribute>());
3983     rewriter.replaceOpWithNewOp<arith::ConstantOp>(shapeCastOp, newAttr);
3984     return success();
3985   }
3986 };
3987 
3988 } // namespace
3989 
3990 void ShapeCastOp::getCanonicalizationPatterns(RewritePatternSet &results,
3991                                               MLIRContext *context) {
3992   // Pattern to rewrite a ShapeCastOp(ConstantOp) -> ConstantOp.
3993   results.add<ShapeCastConstantFolder>(context);
3994 }
3995 
3996 //===----------------------------------------------------------------------===//
3997 // VectorBitCastOp
3998 //===----------------------------------------------------------------------===//
3999 
4000 LogicalResult BitCastOp::verify() {
4001   auto sourceVectorType = getSourceVectorType();
4002   auto resultVectorType = getResultVectorType();
4003 
4004   for (int64_t i = 0, e = sourceVectorType.getRank() - 1; i < e; i++) {
4005     if (sourceVectorType.getDimSize(i) != resultVectorType.getDimSize(i))
4006       return emitOpError("dimension size mismatch at: ") << i;
4007   }
4008 
4009   DataLayout dataLayout = DataLayout::closest(*this);
4010   auto sourceElementBits =
4011       dataLayout.getTypeSizeInBits(sourceVectorType.getElementType());
4012   auto resultElementBits =
4013       dataLayout.getTypeSizeInBits(resultVectorType.getElementType());
4014 
4015   if (sourceVectorType.getRank() == 0) {
4016     if (sourceElementBits != resultElementBits)
4017       return emitOpError("source/result bitwidth of the 0-D vector element "
4018                             "types must be equal");
4019   } else if (sourceElementBits * sourceVectorType.getShape().back() !=
4020              resultElementBits * resultVectorType.getShape().back()) {
4021     return emitOpError(
4022         "source/result bitwidth of the minor 1-D vectors must be equal");
4023   }
4024 
4025   return success();
4026 }
4027 
4028 OpFoldResult BitCastOp::fold(ArrayRef<Attribute> operands) {
4029   // Nop cast.
4030   if (getSource().getType() == getResult().getType())
4031     return getSource();
4032 
4033   // Canceling bitcasts.
4034   if (auto otherOp = getSource().getDefiningOp<BitCastOp>())
4035     if (getResult().getType() == otherOp.getSource().getType())
4036       return otherOp.getSource();
4037 
4038   Attribute sourceConstant = operands.front();
4039   if (!sourceConstant)
4040     return {};
4041 
4042   Type srcElemType = getSourceVectorType().getElementType();
4043   Type dstElemType = getResultVectorType().getElementType();
4044 
4045   if (auto floatPack = sourceConstant.dyn_cast<DenseFPElementsAttr>()) {
4046     if (floatPack.isSplat()) {
4047       auto splat = floatPack.getSplatValue<FloatAttr>();
4048 
4049       // Casting fp16 into fp32.
4050       if (srcElemType.isF16() && dstElemType.isF32()) {
4051         uint32_t bits = static_cast<uint32_t>(
4052             splat.getValue().bitcastToAPInt().getZExtValue());
4053         // Duplicate the 16-bit pattern.
4054         bits = (bits << 16) | (bits & 0xffff);
4055         APInt intBits(32, bits);
4056         APFloat floatBits(llvm::APFloat::IEEEsingle(), intBits);
4057         return DenseElementsAttr::get(getResultVectorType(), floatBits);
4058       }
4059     }
4060   }
4061 
4062   return {};
4063 }
4064 
4065 //===----------------------------------------------------------------------===//
4066 // TypeCastOp
4067 //===----------------------------------------------------------------------===//
4068 
4069 static SmallVector<int64_t, 8> extractShape(MemRefType memRefType) {
4070   auto vectorType = memRefType.getElementType().dyn_cast<VectorType>();
4071   SmallVector<int64_t, 8> res(memRefType.getShape().begin(),
4072                               memRefType.getShape().end());
4073   if (vectorType)
4074     res.append(vectorType.getShape().begin(), vectorType.getShape().end());
4075   return res;
4076 }
4077 
4078 /// Build the canonical memRefType with a single vector.
4079 /// E.g. memref<4 x 5 x vector<6 x f32>> -> memref<vector<4 x 5 x 6 x f32>>.
4080 void TypeCastOp::build(OpBuilder &builder, OperationState &result,
4081                        Value source) {
4082   result.addOperands(source);
4083   MemRefType memRefType = source.getType().cast<MemRefType>();
4084   VectorType vectorType =
4085       VectorType::get(extractShape(memRefType),
4086                       getElementTypeOrSelf(getElementTypeOrSelf(memRefType)));
4087   result.addTypes(MemRefType::get({}, vectorType, MemRefLayoutAttrInterface(),
4088                                   memRefType.getMemorySpace()));
4089 }
4090 
4091 LogicalResult TypeCastOp::verify() {
4092   MemRefType canonicalType = canonicalizeStridedLayout(getMemRefType());
4093   if (!canonicalType.getLayout().isIdentity())
4094     return emitOpError("expects operand to be a memref with identity layout");
4095   if (!getResultMemRefType().getLayout().isIdentity())
4096     return emitOpError("expects result to be a memref with identity layout");
4097   if (getResultMemRefType().getMemorySpace() !=
4098       getMemRefType().getMemorySpace())
4099     return emitOpError("expects result in same memory space");
4100 
4101   auto sourceType = getMemRefType();
4102   auto resultType = getResultMemRefType();
4103   if (getElementTypeOrSelf(getElementTypeOrSelf(sourceType)) !=
4104       getElementTypeOrSelf(getElementTypeOrSelf(resultType)))
4105     return emitOpError(
4106                "expects result and operand with same underlying scalar type: ")
4107            << resultType;
4108   if (extractShape(sourceType) != extractShape(resultType))
4109     return emitOpError(
4110                "expects concatenated result and operand shapes to be equal: ")
4111            << resultType;
4112   return success();
4113 }
4114 
4115 //===----------------------------------------------------------------------===//
4116 // TransposeOp
4117 //===----------------------------------------------------------------------===//
4118 
4119 void vector::TransposeOp::build(OpBuilder &builder, OperationState &result,
4120                                 Value vector, ArrayRef<int64_t> transp) {
4121   VectorType vt = vector.getType().cast<VectorType>();
4122   SmallVector<int64_t, 4> transposedShape(vt.getRank());
4123   for (unsigned i = 0; i < transp.size(); ++i)
4124     transposedShape[i] = vt.getShape()[transp[i]];
4125 
4126   result.addOperands(vector);
4127   result.addTypes(VectorType::get(transposedShape, vt.getElementType()));
4128   result.addAttribute(getTranspAttrStrName(), builder.getI64ArrayAttr(transp));
4129 }
4130 
4131 // Eliminates transpose operations, which produce values identical to their
4132 // input values. This happens when the dimensions of the input vector remain in
4133 // their original order after the transpose operation.
4134 OpFoldResult vector::TransposeOp::fold(ArrayRef<Attribute> operands) {
4135   SmallVector<int64_t, 4> transp;
4136   getTransp(transp);
4137 
4138   // Check if the permutation of the dimensions contains sequential values:
4139   // {0, 1, 2, ...}.
4140   for (int64_t i = 0, e = transp.size(); i < e; i++) {
4141     if (transp[i] != i)
4142       return {};
4143   }
4144 
4145   return getVector();
4146 }
4147 
4148 LogicalResult vector::TransposeOp::verify() {
4149   VectorType vectorType = getVectorType();
4150   VectorType resultType = getResultType();
4151   int64_t rank = resultType.getRank();
4152   if (vectorType.getRank() != rank)
4153     return emitOpError("vector result rank mismatch: ") << rank;
4154   // Verify transposition array.
4155   auto transpAttr = getTransp().getValue();
4156   int64_t size = transpAttr.size();
4157   if (rank != size)
4158     return emitOpError("transposition length mismatch: ") << size;
4159   SmallVector<bool, 8> seen(rank, false);
4160   for (const auto &ta : llvm::enumerate(transpAttr)) {
4161     int64_t i = ta.value().cast<IntegerAttr>().getInt();
4162     if (i < 0 || i >= rank)
4163       return emitOpError("transposition index out of range: ") << i;
4164     if (seen[i])
4165       return emitOpError("duplicate position index: ") << i;
4166     seen[i] = true;
4167     if (resultType.getDimSize(ta.index()) != vectorType.getDimSize(i))
4168       return emitOpError("dimension size mismatch at: ") << i;
4169   }
4170   return success();
4171 }
4172 
4173 namespace {
4174 
4175 // Rewrites two back-to-back TransposeOp operations into a single TransposeOp.
4176 class TransposeFolder final : public OpRewritePattern<vector::TransposeOp> {
4177 public:
4178   using OpRewritePattern<vector::TransposeOp>::OpRewritePattern;
4179 
4180   LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
4181                                 PatternRewriter &rewriter) const override {
4182     // Wrapper around vector::TransposeOp::getTransp() for cleaner code.
4183     auto getPermutation = [](vector::TransposeOp transpose) {
4184       SmallVector<int64_t, 4> permutation;
4185       transpose.getTransp(permutation);
4186       return permutation;
4187     };
4188 
4189     // Composes two permutations: result[i] = permutation1[permutation2[i]].
4190     auto composePermutations = [](ArrayRef<int64_t> permutation1,
4191                                   ArrayRef<int64_t> permutation2) {
4192       SmallVector<int64_t, 4> result;
4193       for (auto index : permutation2)
4194         result.push_back(permutation1[index]);
4195       return result;
4196     };
4197 
4198     // Return if the input of 'transposeOp' is not defined by another transpose.
4199     vector::TransposeOp parentTransposeOp =
4200         transposeOp.getVector().getDefiningOp<vector::TransposeOp>();
4201     if (!parentTransposeOp)
4202       return failure();
4203 
4204     SmallVector<int64_t, 4> permutation = composePermutations(
4205         getPermutation(parentTransposeOp), getPermutation(transposeOp));
4206     // Replace 'transposeOp' with a new transpose operation.
4207     rewriter.replaceOpWithNewOp<vector::TransposeOp>(
4208         transposeOp, transposeOp.getResult().getType(),
4209         parentTransposeOp.getVector(),
4210         vector::getVectorSubscriptAttr(rewriter, permutation));
4211     return success();
4212   }
4213 };
4214 
4215 } // namespace
4216 
4217 void vector::TransposeOp::getCanonicalizationPatterns(
4218     RewritePatternSet &results, MLIRContext *context) {
4219   results.add<TransposeFolder>(context);
4220 }
4221 
4222 void vector::TransposeOp::getTransp(SmallVectorImpl<int64_t> &results) {
4223   populateFromInt64AttrArray(getTransp(), results);
4224 }
4225 
4226 //===----------------------------------------------------------------------===//
4227 // ConstantMaskOp
4228 //===----------------------------------------------------------------------===//
4229 
4230 LogicalResult ConstantMaskOp::verify() {
4231   auto resultType = getResult().getType().cast<VectorType>();
4232   // Check the corner case of 0-D vectors first.
4233   if (resultType.getRank() == 0) {
4234     if (getMaskDimSizes().size() != 1)
4235       return emitError("array attr must have length 1 for 0-D vectors");
4236     auto dim = getMaskDimSizes()[0].cast<IntegerAttr>().getInt();
4237     if (dim != 0 && dim != 1)
4238       return emitError("mask dim size must be either 0 or 1 for 0-D vectors");
4239     return success();
4240   }
4241 
4242   // Verify that array attr size matches the rank of the vector result.
4243   if (static_cast<int64_t>(getMaskDimSizes().size()) != resultType.getRank())
4244     return emitOpError(
4245         "must specify array attr of size equal vector result rank");
4246   // Verify that each array attr element is in bounds of corresponding vector
4247   // result dimension size.
4248   auto resultShape = resultType.getShape();
4249   SmallVector<int64_t, 4> maskDimSizes;
4250   for (const auto &it : llvm::enumerate(getMaskDimSizes())) {
4251     int64_t attrValue = it.value().cast<IntegerAttr>().getInt();
4252     if (attrValue < 0 || attrValue > resultShape[it.index()])
4253       return emitOpError(
4254           "array attr of size out of bounds of vector result dimension size");
4255     maskDimSizes.push_back(attrValue);
4256   }
4257   // Verify that if one mask dim size is zero, they all should be zero (because
4258   // the mask region is a conjunction of each mask dimension interval).
4259   bool anyZeros = llvm::is_contained(maskDimSizes, 0);
4260   bool allZeros = llvm::all_of(maskDimSizes, [](int64_t s) { return s == 0; });
4261   if (anyZeros && !allZeros)
4262     return emitOpError("expected all mask dim sizes to be zeros, "
4263                        "as a result of conjunction with zero mask dim");
4264   // Verify that if the mask type is scalable, dimensions should be zero because
4265   // constant scalable masks can only be defined for the "none set" or "all set"
4266   // cases, and there is no VLA way to define an "all set" case for
4267   // `vector.constant_mask`. In the future, a convention could be established
4268   // to decide if a specific dimension value could be considered as "all set".
4269   if (resultType.isScalable() &&
4270       getMaskDimSizes()[0].cast<IntegerAttr>().getInt() != 0)
4271     return emitOpError("expected mask dim sizes for scalable masks to be 0");
4272   return success();
4273 }
4274 
4275 //===----------------------------------------------------------------------===//
4276 // CreateMaskOp
4277 //===----------------------------------------------------------------------===//
4278 
4279 LogicalResult CreateMaskOp::verify() {
4280   auto vectorType = getResult().getType().cast<VectorType>();
4281   // Verify that an operand was specified for each result vector each dimension.
4282   if (vectorType.getRank() == 0) {
4283     if (getNumOperands() != 1)
4284       return emitOpError(
4285           "must specify exactly one operand for 0-D create_mask");
4286   } else if (getNumOperands() !=
4287              getResult().getType().cast<VectorType>().getRank()) {
4288     return emitOpError(
4289         "must specify an operand for each result vector dimension");
4290   }
4291   return success();
4292 }
4293 
4294 namespace {
4295 
4296 // Pattern to rewrite a CreateMaskOp with a ConstantMaskOp.
4297 class CreateMaskFolder final : public OpRewritePattern<CreateMaskOp> {
4298 public:
4299   using OpRewritePattern<CreateMaskOp>::OpRewritePattern;
4300 
4301   LogicalResult matchAndRewrite(CreateMaskOp createMaskOp,
4302                                 PatternRewriter &rewriter) const override {
4303     // Return if any of 'createMaskOp' operands are not defined by a constant.
4304     auto isNotDefByConstant = [](Value operand) {
4305       return !isa_and_nonnull<arith::ConstantIndexOp>(operand.getDefiningOp());
4306     };
4307     if (llvm::any_of(createMaskOp.operands(), isNotDefByConstant))
4308       return failure();
4309 
4310     // CreateMaskOp for scalable vectors can be folded only if all dimensions
4311     // are negative or zero.
4312     if (auto vType = createMaskOp.getType().dyn_cast<VectorType>()) {
4313       if (vType.isScalable())
4314         for (auto opDim : createMaskOp.getOperands()) {
4315           APInt intVal;
4316           if (matchPattern(opDim, m_ConstantInt(&intVal)) &&
4317               intVal.isStrictlyPositive())
4318             return failure();
4319         }
4320     }
4321 
4322     // Gather constant mask dimension sizes.
4323     SmallVector<int64_t, 4> maskDimSizes;
4324     for (auto it : llvm::zip(createMaskOp.operands(),
4325                              createMaskOp.getType().getShape())) {
4326       auto *defOp = std::get<0>(it).getDefiningOp();
4327       int64_t maxDimSize = std::get<1>(it);
4328       int64_t dimSize = cast<arith::ConstantIndexOp>(defOp).value();
4329       dimSize = std::min(dimSize, maxDimSize);
4330       // If one of dim sizes is zero, set all dims to zero.
4331       if (dimSize <= 0) {
4332         maskDimSizes.assign(createMaskOp.getType().getRank(), 0);
4333         break;
4334       }
4335       maskDimSizes.push_back(dimSize);
4336     }
4337     // Replace 'createMaskOp' with ConstantMaskOp.
4338     rewriter.replaceOpWithNewOp<ConstantMaskOp>(
4339         createMaskOp, createMaskOp.getResult().getType(),
4340         vector::getVectorSubscriptAttr(rewriter, maskDimSizes));
4341     return success();
4342   }
4343 };
4344 
4345 } // namespace
4346 
4347 void CreateMaskOp::getCanonicalizationPatterns(RewritePatternSet &results,
4348                                                MLIRContext *context) {
4349   results.add<CreateMaskFolder>(context);
4350 }
4351 
4352 //===----------------------------------------------------------------------===//
4353 // ScanOp
4354 //===----------------------------------------------------------------------===//
4355 
4356 LogicalResult ScanOp::verify() {
4357   VectorType srcType = getSourceType();
4358   VectorType initialType = getInitialValueType();
4359   // Check reduction dimension < rank.
4360   int64_t srcRank = srcType.getRank();
4361   int64_t reductionDim = getReductionDim();
4362   if (reductionDim >= srcRank)
4363     return emitOpError("reduction dimension ")
4364            << reductionDim << " has to be less than " << srcRank;
4365 
4366   // Check that rank(initial_value) = rank(src) - 1.
4367   int64_t initialValueRank = initialType.getRank();
4368   if (initialValueRank != srcRank - 1)
4369     return emitOpError("initial value rank ")
4370            << initialValueRank << " has to be equal to " << srcRank - 1;
4371 
4372   // Check shapes of initial value and src.
4373   ArrayRef<int64_t> srcShape = srcType.getShape();
4374   ArrayRef<int64_t> initialValueShapes = initialType.getShape();
4375   SmallVector<int64_t> expectedShape;
4376   for (int i = 0; i < srcRank; i++) {
4377     if (i != reductionDim)
4378       expectedShape.push_back(srcShape[i]);
4379   }
4380   if (llvm::any_of(llvm::zip(initialValueShapes, expectedShape),
4381                    [](std::tuple<int64_t, int64_t> s) {
4382                      return std::get<0>(s) != std::get<1>(s);
4383                    })) {
4384     return emitOpError("incompatible input/initial value shapes");
4385   }
4386 
4387   return success();
4388 }
4389 
4390 void mlir::vector::populateVectorToVectorCanonicalizationPatterns(
4391     RewritePatternSet &patterns) {
4392   patterns
4393       .add<CreateMaskFolder, MaskedLoadFolder, MaskedStoreFolder, GatherFolder,
4394            ScatterFolder, ExpandLoadFolder, CompressStoreFolder,
4395            StridedSliceConstantMaskFolder, TransposeFolder>(
4396           patterns.getContext());
4397 }
4398 
4399 //===----------------------------------------------------------------------===//
4400 // SplatOp
4401 //===----------------------------------------------------------------------===//
4402 
4403 OpFoldResult SplatOp::fold(ArrayRef<Attribute> operands) {
4404   auto constOperand = operands.front();
4405   if (!constOperand.isa_and_nonnull<IntegerAttr, FloatAttr>())
4406     return {};
4407 
4408   // SplatElementsAttr::get treats single value for second arg as being a splat.
4409   return SplatElementsAttr::get(getType(), {constOperand});
4410 }
4411 
4412 //===----------------------------------------------------------------------===//
4413 // TableGen'd op method definitions
4414 //===----------------------------------------------------------------------===//
4415 
4416 #define GET_OP_CLASSES
4417 #include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc"
4418