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