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