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