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