44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/Repeated.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/ADT/SmallVectorExtras.h"
49#include "llvm/ADT/StringSet.h"
50#include "llvm/Support/Casting.h"
56#include "mlir/Dialect/Vector/IR/VectorDialect.cpp.inc"
58#include "mlir/Dialect/Vector/IR/VectorEnums.cpp.inc"
71static std::optional<SmallVector<int64_t>>
77static std::optional<SmallVector<int64_t>>
87 if (
auto c = mask.getDefiningOp<arith::ConstantOp>()) {
91 if (
auto denseElts = llvm::dyn_cast<DenseIntElementsAttr>(c.getValue())) {
93 for (
bool b : denseElts.getValues<
bool>())
96 else if (!
b && val <= 0)
105 }
else if (
auto m = mask.getDefiningOp<ConstantMaskOp>()) {
110 auto shape = m.getType().getShape();
112 bool allFalse =
true;
113 for (
auto [maskIdx, dimSize] : llvm::zip_equal(masks,
shape)) {
114 if (maskIdx < dimSize)
123 }
else if (
auto m = mask.getDefiningOp<CreateMaskOp>()) {
127 auto maskOperands = m.getOperands();
128 for (
Value operand : maskOperands) {
129 if (
auto constantOp = operand.getDefiningOp<arith::ConstantOp>()) {
131 llvm::cast<IntegerAttr>(constantOp.getValue()).getInt();
144 vector::YieldOp::create(builder, loc);
150 switch (combiningKind) {
151 case CombiningKind::ADD:
152 case CombiningKind::MUL:
154 case CombiningKind::MINUI:
155 case CombiningKind::MINSI:
156 case CombiningKind::MAXUI:
157 case CombiningKind::MAXSI:
158 case CombiningKind::AND:
159 case CombiningKind::OR:
160 case CombiningKind::XOR:
162 case CombiningKind::MINNUMF:
163 case CombiningKind::MAXNUMF:
164 case CombiningKind::MINIMUMF:
165 case CombiningKind::MAXIMUMF:
166 case CombiningKind::MINIMUMNUMF:
167 case CombiningKind::MAXIMUMNUMF:
168 return llvm::isa<FloatType>(elementType);
198 VectorType vectorType) {
199 unsigned elementVectorRank = 0;
200 VectorType elementVectorType =
201 llvm::dyn_cast<VectorType>(shapedType.getElementType());
202 if (elementVectorType)
203 elementVectorRank += elementVectorType.getRank();
204 return vectorType.getRank() - elementVectorRank;
208 VectorType vectorType) {
211 if (shapedType.getRank() == 0 &&
217 shapedType.getRank(),
219 shapedType.getContext());
226 vector::TransferReadOp read) {
227 auto readMask = read.getMask();
228 auto writeMask = write.getMask();
234 bool couldBeSameSplat = readMask && (!writeMask || writeMask == readMask);
235 if (!couldBeSameSplat)
252 vector::TransferReadOp read) {
259 if (defWrite.isMasked() || read.isMasked())
261 return !defWrite.hasOutOfBoundsDim() &&
262 defWrite.getIndices() == read.getIndices() &&
263 defWrite.getVectorType() == read.getVectorType() &&
264 defWrite.getPermutationMap() == read.getPermutationMap() &&
265 ((!defWrite.getMask() && !read.getMask()) ||
270 vector::TransferWriteOp priorWrite) {
278 if (write.isMasked())
280 return priorWrite.getIndices() == write.getIndices() &&
281 priorWrite.getMask() == write.getMask() &&
282 priorWrite.getVectorType() == write.getVectorType() &&
283 priorWrite.getPermutationMap() == write.getPermutationMap();
287 VectorTransferOpInterface transferA, VectorTransferOpInterface transferB,
288 bool testDynamicValueUsingBounds) {
290 if (transferA.getVectorType() != transferB.getVectorType())
292 unsigned rankOffset = transferA.getLeadingShapedRank();
293 for (
unsigned i = 0, e = transferA.getIndices().size(); i < e; i++) {
294 Value indexA = transferA.getIndices()[i];
295 Value indexB = transferB.getIndices()[i];
299 if (i < rankOffset) {
302 if (cstIndexA.has_value() && cstIndexB.has_value()) {
303 if (*cstIndexA != *cstIndexB)
307 if (testDynamicValueUsingBounds) {
310 FailureOr<uint64_t> delta =
312 if (succeeded(delta) && *delta != 0)
315 FailureOr<bool> testEqual =
317 if (succeeded(testEqual) && !testEqual.value())
323 int64_t vectorDim = transferA.getVectorType().getDimSize(i - rankOffset);
324 if (cstIndexA.has_value() && cstIndexB.has_value()) {
325 int64_t distance = std::abs(*cstIndexA - *cstIndexB);
326 if (distance >= vectorDim)
330 if (testDynamicValueUsingBounds) {
333 FailureOr<int64_t> delta =
335 if (succeeded(delta) && std::abs(*delta) >= vectorDim)
338 FailureOr<int64_t> computeDelta =
340 if (succeeded(computeDelta)) {
341 if (std::abs(computeDelta.value()) >= vectorDim)
351 VectorTransferOpInterface transferB,
352 bool testDynamicValueUsingBounds) {
353 if (transferA.getBase() != transferB.getBase())
356 testDynamicValueUsingBounds);
366 for (
auto [posInDim, dimSize, offsetInDim] :
367 llvm::reverse(llvm::zip_equal(position,
shape, offsets))) {
369 if (posInDim < dimSize + offsetInDim)
373 posInDim = offsetInDim;
383 llvm::transform(values, std::back_inserter(ints), [](
Value value) {
385 assert(constOp &&
"Unexpected non-constant index");
386 return constOp.value();
396 foldResults, std::back_inserter(ints), [](
OpFoldResult foldResult) {
397 assert(isa<Attribute>(foldResult) &&
"Unexpected non-constant index");
398 return cast<IntegerAttr>(cast<Attribute>(foldResult)).getInt();
408 llvm::transform(foldResults, std::back_inserter(values),
410 if (
auto attr = dyn_cast<Attribute>(foldResult))
412 builder, loc, cast<IntegerAttr>(attr).getInt())
415 return cast<Value>(foldResult);
426 auto lhs =
mul.getLhs();
427 auto rhs =
mul.getRhs();
428 if (lhs.getDefiningOp<vector::VectorScaleOp>())
430 if (rhs.getDefiningOp<vector::VectorScaleOp>())
440 if (
auto intAttr = dyn_cast<IntegerAttr>(attr)) {
441 if (
auto intType = dyn_cast<IntegerType>(expectedType)) {
442 if (intAttr.getType() != expectedType)
443 return IntegerAttr::get(expectedType, intAttr.getInt());
449 if (
auto floatAttr = dyn_cast<FloatAttr>(attr)) {
450 auto intType = dyn_cast<IntegerType>(expectedType);
454 APFloat floatVal = floatAttr.getValue();
455 APInt intVal = floatVal.bitcastToAPInt();
456 return IntegerAttr::get(expectedType, intVal);
465 Type srcType, VectorType dstVectorType,
466 std::pair<VectorDim, VectorDim> *mismatchingDims) {
468 if (isa<VectorElementTypeInterface>(srcType) && dstVectorType &&
472 VectorType srcVectorType = llvm::dyn_cast<VectorType>(srcType);
476 int64_t srcRank = srcVectorType.getRank();
477 int64_t dstRank = dstVectorType.getRank();
478 if (srcRank > dstRank)
482 int64_t lead = dstRank - srcRank;
483 for (
int64_t dimIdx = 0; dimIdx < srcRank; ++dimIdx) {
486 bool foundMismatchingDims =
false;
489 int64_t srcDim = srcVectorType.getDimSize(dimIdx);
490 int64_t dstDim = dstVectorType.getDimSize(lead + dimIdx);
491 if (srcDim != 1 && srcDim != dstDim)
492 foundMismatchingDims =
true;
495 bool srcDimScalableFlag = srcVectorType.getScalableDims()[dimIdx];
496 bool dstDimScalableFlag = dstVectorType.getScalableDims()[lead + dimIdx];
497 if ((srcDim == 1 && srcDimScalableFlag && dstDim != 1) ||
500 (srcDimScalableFlag != dstDimScalableFlag &&
501 (srcDim != 1 || srcDimScalableFlag)))
502 foundMismatchingDims =
true;
504 if (foundMismatchingDims) {
505 if (mismatchingDims !=
nullptr) {
506 mismatchingDims->first.dim = srcDim;
507 mismatchingDims->first.isScalable = srcDimScalableFlag;
509 mismatchingDims->second.dim = dstDim;
510 mismatchingDims->second.isScalable = dstDimScalableFlag;
552struct VectorInlinerInterface :
public DialectInlinerInterface {
553 using DialectInlinerInterface::DialectInlinerInterface;
562void VectorDialect::initialize() {
563 addInterfaces<VectorInlinerInterface>();
565 declarePromisedInterfaces<memref::IndexedAccessOpInterface, LoadOp, StoreOp,
566 MaskedLoadOp, MaskedStoreOp, ExpandLoadOp,
568 declarePromisedInterfaces<bufferization::BufferizableOpInterface,
569 TransferReadOp, TransferWriteOp, GatherOp, MaskOp,
571 declarePromisedInterfaces<SubsetOpInterface, TransferReadOp,
573 declarePromisedInterface<SubsetExtractionOpInterface, TransferReadOp>();
574 declarePromisedInterface<SubsetInsertionOpInterface, TransferWriteOp>();
575 declarePromisedInterface<ConvertToLLVMPatternInterface, VectorDialect>();
586 return arith::ConstantOp::materialize(builder, value, type, loc);
602void vector::MultiDimReductionOp::build(
OpBuilder &builder,
606 arith::FastMathFlags fastMathFlags) {
608 for (
const auto &en : llvm::enumerate(reductionMask))
610 reductionDims.push_back(en.index());
611 build(builder,
result, kind, source,
acc, reductionDims, fastMathFlags);
614OpFoldResult MultiDimReductionOp::fold(FoldAdaptor adaptor) {
616 if (getReductionDims().empty())
621LogicalResult MultiDimReductionOp::verify() {
623 int64_t sourceRank = getSourceVectorType().getRank();
625 for (
int64_t dim : getReductionDims()) {
626 if (dim < 0 || dim >= sourceRank)
627 return emitOpError(
"reduction dimension out of range: ") << dim;
629 return emitOpError(
"duplicate reduction dimension: ") << dim;
630 isReduced[dim] =
true;
635 Type inferredReturnType;
636 auto sourceScalableDims = getSourceVectorType().getScalableDims();
637 for (
auto [dimIdx, dimSize] :
638 llvm::enumerate(getSourceVectorType().
getShape()))
639 if (!isReduced[dimIdx]) {
640 targetShape.push_back(dimSize);
641 scalableDims.push_back(sourceScalableDims[dimIdx]);
644 if (targetShape.empty())
645 inferredReturnType = getSourceVectorType().getElementType();
647 inferredReturnType = VectorType::get(
648 targetShape, getSourceVectorType().
getElementType(), scalableDims);
649 if (
getType() != inferredReturnType)
650 return emitOpError() <<
"destination type " <<
getType()
651 <<
" is incompatible with source type "
652 << getSourceVectorType();
658Type MultiDimReductionOp::getExpectedMaskType() {
659 auto vecType = getSourceVectorType();
660 return VectorType::get(vecType.getShape(),
661 IntegerType::get(vecType.getContext(), 1),
662 vecType.getScalableDims());
668std::optional<SmallVector<int64_t, 4>>
669MultiDimReductionOp::getIterationShapeToUnroll() {
670 return llvm::to_vector<4>(getSourceVectorType().
getShape());
679struct ElideUnitDimsInMultiDimReduction
683 LogicalResult matchAndRewrite(MultiDimReductionOp reductionOp,
684 PatternRewriter &rewriter)
const override {
685 ArrayRef<int64_t> shape = reductionOp.getSourceVectorType().getShape();
686 for (
const auto &dim :
enumerate(shape)) {
687 if (reductionOp.isReducedDim(dim.index()) && dim.value() != 1)
692 OpBuilder::InsertionGuard guard(rewriter);
695 if (reductionOp.isMasked()) {
697 rootOp = reductionOp.getMaskingOp();
698 mask = reductionOp.getMaskingOp().getMask();
700 rootOp = reductionOp;
703 Location loc = reductionOp.getLoc();
704 Value acc = reductionOp.getAcc();
706 if (
auto dstVecType = dyn_cast<VectorType>(reductionOp.getDestType())) {
708 VectorType newMaskType =
709 VectorType::get(dstVecType.getShape(), rewriter.
getI1Type(),
710 dstVecType.getScalableDims());
711 mask = vector::ShapeCastOp::create(rewriter, loc, newMaskType, mask);
713 cast = vector::ShapeCastOp::create(
714 rewriter, loc, reductionOp.getDestType(), reductionOp.getSource());
719 mask = vector::ExtractOp::create(rewriter, loc, mask);
720 cast = vector::ExtractOp::create(rewriter, loc, reductionOp.getSource());
725 acc, reductionOp.getFastmathAttr(), mask);
732void MultiDimReductionOp::getCanonicalizationPatterns(
734 results.
add<ElideUnitDimsInMultiDimReduction>(context);
743 arith::FastMathFlags fastMathFlags) {
749 arith::FastMathFlags fastMathFlags) {
751 llvm::cast<VectorType>(
vector.getType()).getElementType(), kind,
vector,
755LogicalResult ReductionOp::verify() {
757 int64_t rank = getSourceVectorType().getRank();
759 return emitOpError(
"unsupported reduction rank: ") << rank;
762 Type eltType = getResult().getType();
764 return emitOpError(
"unsupported reduction type '")
765 << eltType <<
"' for kind '" << stringifyCombiningKind(getKind())
774Type ReductionOp::getExpectedMaskType() {
775 auto vecType = getSourceVectorType();
776 return VectorType::get(vecType.getShape(),
777 IntegerType::get(vecType.getContext(), 1),
778 vecType.getScalableDims());
785 case arith::AtomicRMWKind::addf:
786 case arith::AtomicRMWKind::addi:
787 return vector::ReductionOp::create(builder,
vector.getLoc(),
788 CombiningKind::ADD,
vector);
789 case arith::AtomicRMWKind::mulf:
790 case arith::AtomicRMWKind::muli:
791 return vector::ReductionOp::create(builder,
vector.getLoc(),
792 CombiningKind::MUL,
vector);
793 case arith::AtomicRMWKind::minimumf:
794 return vector::ReductionOp::create(builder,
vector.getLoc(),
795 CombiningKind::MINIMUMF,
vector);
796 case arith::AtomicRMWKind::mins:
797 return vector::ReductionOp::create(builder,
vector.getLoc(),
798 CombiningKind::MINSI,
vector);
799 case arith::AtomicRMWKind::minu:
800 return vector::ReductionOp::create(builder,
vector.getLoc(),
801 CombiningKind::MINUI,
vector);
802 case arith::AtomicRMWKind::maximumf:
803 return vector::ReductionOp::create(builder,
vector.getLoc(),
804 CombiningKind::MAXIMUMF,
vector);
805 case arith::AtomicRMWKind::maxs:
806 return vector::ReductionOp::create(builder,
vector.getLoc(),
807 CombiningKind::MAXSI,
vector);
808 case arith::AtomicRMWKind::maxu:
809 return vector::ReductionOp::create(builder,
vector.getLoc(),
810 CombiningKind::MAXUI,
vector);
811 case arith::AtomicRMWKind::andi:
812 return vector::ReductionOp::create(builder,
vector.getLoc(),
813 CombiningKind::AND,
vector);
814 case arith::AtomicRMWKind::ori:
815 return vector::ReductionOp::create(builder,
vector.getLoc(),
816 CombiningKind::OR,
vector);
817 case arith::AtomicRMWKind::minnumf:
818 return vector::ReductionOp::create(builder,
vector.getLoc(),
819 CombiningKind::MINNUMF,
vector);
820 case arith::AtomicRMWKind::maxnumf:
821 return vector::ReductionOp::create(builder,
vector.getLoc(),
822 CombiningKind::MAXNUMF,
vector);
823 case arith::AtomicRMWKind::xori:
824 return vector::ReductionOp::create(builder,
vector.getLoc(),
825 CombiningKind::XOR,
vector);
836std::optional<SmallVector<int64_t, 4>>
837ReductionOp::getIterationShapeToUnroll() {
838 return llvm::to_vector<4>(getSourceVectorType().
getShape());
840std::optional<SmallVector<int64_t>> ReductionOp::getDefaultUnrollTargetShape() {
848 LogicalResult matchAndRewrite(ReductionOp reductionOp,
849 PatternRewriter &rewriter)
const override {
851 OpBuilder::InsertionGuard guard(rewriter);
853 cast<vector::MaskableOpInterface>(reductionOp.getOperation());
856 if (maskableOp.isMasked()) {
858 rootOp = maskableOp.getMaskingOp();
859 mask = maskableOp.getMaskingOp().getMask();
861 rootOp = reductionOp;
864 auto vectorType = reductionOp.getSourceVectorType();
865 if (vectorType.getRank() != 0 && vectorType.getDimSize(0) != 1)
868 Location loc = reductionOp.getLoc();
870 mask = ExtractOp::create(rewriter, loc, mask);
871 Value
result = ExtractOp::create(rewriter, loc, reductionOp.getVector());
873 if (Value acc = reductionOp.getAcc())
876 reductionOp.getFastmathAttr(), mask);
886 results.
add<ElideSingleElementReduction>(context);
900 getIndexingMapsAttrName(
result.name),
904 getIteratorTypesAttrName(
result.name),
907 return IteratorTypeAttr::get(builder.getContext(), t);
915 build(builder,
result, lhs, rhs,
acc, indexingMaps, iteratorTypes,
916 ContractionOp::getDefaultKind());
922 ArrayAttr iteratorTypes, CombiningKind kind,
923 arith::FastMathFlags fastMathFlags) {
926 result.addAttribute(getIndexingMapsAttrName(
result.name), indexingMaps);
927 result.addAttribute(getIteratorTypesAttrName(
result.name), iteratorTypes);
929 CombiningKindAttr::get(builder.
getContext(), kind));
930 if (fastMathFlags != arith::FastMathFlags::none)
932 getFastmathAttrName(
result.name),
933 arith::FastMathFlagsAttr::get(builder.
getContext(), fastMathFlags));
944 DictionaryAttr dictAttr;
958 result.attributes.append(dictAttr.getValue().begin(),
959 dictAttr.getValue().end());
965 auto iteratorTypes = dyn_cast_or_null<ArrayAttr>(
966 result.attributes.get(getIteratorTypesAttrName(
result.name)));
967 if (!iteratorTypes) {
969 <<
"expected " << getIteratorTypesAttrName(
result.name)
970 <<
" array attribute";
975 for (StringRef s : iteratorTypes.getAsValueRange<StringAttr>()) {
976 auto maybeIteratorType = symbolizeIteratorType(s);
977 if (!maybeIteratorType.has_value())
978 return parser.
emitError(loc) <<
"unexpected iterator_type (" << s <<
")";
980 iteratorTypeAttrs.push_back(
981 IteratorTypeAttr::get(parser.
getContext(), maybeIteratorType.value()));
983 result.attributes.set(getIteratorTypesAttrName(
result.name),
986 if (!
result.attributes.get(getKindAttrName(
result.name))) {
988 getKindAttrName(
result.name),
989 CombiningKindAttr::get(
result.getContext(),
990 ContractionOp::getDefaultKind()));
992 if (masksInfo.empty())
994 if (masksInfo.size() != 2)
996 "expected zero or exactly 2 vector mask operands");
997 auto lhsType = llvm::cast<VectorType>(types[0]);
998 auto rhsType = llvm::cast<VectorType>(types[1]);
1000 std::array<VectorType, 2> maskTypes = {
1010 auto attrNames = getTraitAttrNames();
1012 traitAttrsSet.insert_range(attrNames);
1013 NamedAttrList allAttrs(getOperation()->getRawDictionaryAttrs());
1014 getOperation()->getName().walkInherentAttrs(
1016 [&](StringRef name,
Attribute &attr) { allAttrs.append(name, attr); });
1018 for (
auto attr : allAttrs) {
1019 if (attr.getName() == getIteratorTypesAttrName()) {
1020 auto iteratorTypes =
1021 llvm::cast<ArrayAttr>(attr.getValue())
1022 .getAsValueRange<IteratorTypeAttr, IteratorType>();
1028 llvm::map_to_vector(iteratorTypes, [&](IteratorType t) ->
Attribute {
1029 return StringAttr::get(
getContext(), stringifyIteratorType(t));
1032 attrs.emplace_back(getIteratorTypesAttrName(),
1033 ArrayAttr::get(
getContext(), iteratorTypeNames));
1034 }
else if (traitAttrsSet.count(attr.getName().strref()) > 0) {
1036 if (attr.getName() == getFastmathAttrName() &&
1037 llvm::cast<arith::FastMathFlagsAttr>(attr.getValue()).getValue() ==
1038 arith::FastMathFlags::none)
1040 attrs.push_back(attr);
1044 auto dictAttr = DictionaryAttr::get(
getContext(), attrs);
1045 p <<
" " << dictAttr <<
" " << getLhs() <<
", ";
1046 p << getRhs() <<
", " << getAcc();
1049 p <<
" : " << getLhs().getType() <<
", " << getRhs().getType() <<
" into "
1054 const std::vector<std::pair<int64_t, int64_t>> &map) {
1055 for (
auto &dimPair : map) {
1056 if (dimPair.first < 0 || dimPair.first >= lhsType.getRank() ||
1057 dimPair.second < 0 || dimPair.second >= rhsType.getRank() ||
1058 lhsType.getDimSize(dimPair.first) != rhsType.getDimSize(dimPair.second))
1065 ContractionOp op, VectorType lhsType, VectorType rhsType,
Type accType,
1067 const std::vector<std::pair<int64_t, int64_t>> &contractingDimMap,
1068 const std::vector<std::pair<int64_t, int64_t>> &batchDimMap) {
1071 for (
auto &dimPair : contractingDimMap) {
1072 lhsContractingDimSet.insert(dimPair.first);
1073 rhsContractingDimSet.insert(dimPair.second);
1076 llvm::make_second_range(batchDimMap));
1080 for (
int64_t i = 0, e = lhsType.getRank(); i < e; ++i) {
1081 if (lhsContractingDimSet.count(i) > 0)
1083 expectedResultDims.push_back(lhsType.getDimSize(i));
1087 for (
int64_t i = 0, e = rhsType.getRank(); i < e; ++i) {
1088 if (rhsContractingDimSet.count(i) > 0 || rhsBatchDimSet.count(i) > 0)
1090 expectedResultDims.push_back(rhsType.getDimSize(i));
1094 if (resType != accType)
1095 return op.emitOpError(
"expected same accumulator and result type");
1098 if (expectedResultDims.empty()) {
1100 if (
auto resVectorType = llvm::dyn_cast<VectorType>(resType))
1101 if (resVectorType.getRank() != 0)
1102 return op.emitOpError(
"expected scalar or 0-D vector result when "
1103 "there are no batch or free dimensions");
1106 auto resVectorType = llvm::dyn_cast<VectorType>(resType);
1107 auto accVectorType = llvm::dyn_cast<VectorType>(accType);
1108 if (!resVectorType || !accVectorType)
1109 return op.emitOpError(
"invalid accumulator/result vector shape");
1115 AffineMap lhsMap = op.getIndexingMapsArray()[0];
1116 AffineMap rhsMap = op.getIndexingMapsArray()[1];
1118 return op.emitOpError(
1119 "expected all dimensions to be either a LHS or a RHS dimension");
1122 {std::make_pair(lhsType, lhsMap), std::make_pair(rhsType, rhsMap)}) {
1123 VectorType v = pair.first;
1124 auto map = pair.second;
1125 for (
unsigned idx = 0, e = v.getRank(); idx < e; ++idx) {
1126 unsigned pos = map.getDimPosition(idx);
1131 if (!llvm::all_of(extents, [](
AffineExpr e) {
return e; }))
1132 return op.emitOpError(
"expected all dimensions to get an extent as "
1133 "either a LHS or a RHS dimension");
1135 AffineMap resMap = op.getIndexingMapsArray()[2];
1140 assert(llvm::all_of(expectedMap.
getResults(),
1141 llvm::IsaPred<AffineConstantExpr>) &&
1142 "expected constant extent along all dimensions.");
1144 auto expectedShape =
1146 return cast<AffineConstantExpr>(e).getValue();
1149 VectorType::get(expectedShape, resVectorType.getElementType(),
1150 resVectorType.getScalableDims());
1151 if (resVectorType != expected || accVectorType != expected)
1152 return op.emitOpError(
1153 "invalid accumulator/result vector shape, expected: ")
1161static std::optional<int64_t>
1163 auto maps =
contract->getIndexingMapsArray();
1167 for (
auto [dim, attr] : llvm::enumerate(
contract->getIteratorTypes())) {
1168 auto iteratorType = cast<vector::IteratorTypeAttr>(attr).getValue();
1169 if (iteratorType == vector::IteratorType::reduction &&
1174 return std::nullopt;
1177LogicalResult ContractionOp::verify() {
1178 VectorType lhsType = getLhsType();
1179 VectorType rhsType = getRhsType();
1180 Type accType = getAccType();
1181 Type resType = getResultType();
1183 if (llvm::isa<IntegerType>(lhsType.getElementType())) {
1184 if (!lhsType.getElementType().isSignlessInteger())
1185 return emitOpError(
"only supports signless integer types");
1189 if (getIndexingMapsArray().size() != 3)
1190 return emitOpError(
"expected an indexing map for each vector operand");
1195 unsigned numIterators = getIteratorTypes().getValue().size();
1196 for (
const auto &it : llvm::enumerate(getIndexingMapsArray())) {
1197 auto index = it.index();
1198 auto map = it.value();
1199 if (map.getNumSymbols() != 0)
1200 return emitOpError(
"expected indexing map ")
1201 <<
index <<
" to have no symbols";
1202 auto vectorType = llvm::dyn_cast<VectorType>(getOperand(
index).
getType());
1203 unsigned rank = vectorType ? vectorType.getShape().size() : 0;
1206 if (map.getNumDims() != numIterators)
1207 return emitOpError(
"expected indexing map ")
1208 <<
index <<
" to have " << numIterators <<
" number of inputs";
1209 if (map.getNumResults() != rank)
1210 return emitOpError(
"expected indexing map ")
1211 <<
index <<
" to have " << rank <<
" number of outputs";
1212 if (!map.isProjectedPermutation())
1213 return emitOpError(
"expected indexing map ")
1214 <<
index <<
" to be a projected permutation of its inputs";
1219 if (dimIdx.has_value())
1220 return emitOpError(
"reduction dim at index ")
1221 << dimIdx.value() <<
" must appear in both LHS and RHS";
1223 auto contractingDimMap = getContractingDimMap();
1224 auto batchDimMap = getBatchDimMap();
1227 if (contractingDimMap.empty())
1228 return emitOpError(
"expected at least one contracting dimension pair");
1231 if (!
verifyDimMap(lhsType, rhsType, contractingDimMap))
1232 return emitOpError(
"invalid contracting dimension map");
1236 return emitOpError(
"invalid batch dimension map");
1240 contractingDimMap, batchDimMap)))
1243 if (!getKindAttr()) {
1244 return emitOpError(
"expected 'kind' attribute of type CombiningKind (e.g. "
1245 "'vector.kind<add>')");
1249 auto vectorType = llvm::dyn_cast<VectorType>(resType);
1250 auto elementType = vectorType ? vectorType.getElementType() : resType;
1252 return emitOpError(
"unsupported contraction type");
1255 return cast<IndexingMapOpInterface>(this->getOperation()).verifyImpl();
1262Type ContractionOp::getExpectedMaskType() {
1263 auto indexingMaps = this->getIndexingMapsArray();
1266 VectorType lhsType = this->getLhsType();
1267 VectorType rhsType = this->getRhsType();
1269 unsigned numVecDims = lhsIdxMap.
getNumDims();
1275 for (
auto [dimIdx, dimSize] : llvm::enumerate(lhsType.getShape())) {
1278 lhsType.getScalableDims()[dimIdx];
1280 for (
auto [dimIdx, dimSize] : llvm::enumerate(rhsType.getShape())) {
1283 rhsType.getScalableDims()[dimIdx];
1286 assert(ShapedType::isStaticShape(maskShape) &&
1287 "Mask shape couldn't be computed");
1289 return VectorType::get(maskShape,
1290 IntegerType::get(lhsType.getContext(), 1),
1291 maskShapeScalableDims);
1296 getIteratorTypesAttrName(), getKindAttrName(),
1297 getFastmathAttrName()};
1314static std::vector<std::pair<int64_t, int64_t>>
1316 bool oneSidedDim =
false) {
1319 std::vector<std::pair<int64_t, int64_t>> dimMap;
1320 for (
const auto &it : llvm::enumerate(iteratorTypes)) {
1321 auto iteratorType = llvm::cast<IteratorTypeAttr>(it.value()).getValue();
1322 if (iteratorType != targetIteratorType)
1328 bool isOneSidedDim = (lhsDim >= 0) != (rhsDim >= 0);
1329 bool isTwoSidedDim = lhsDim >= 0 && rhsDim >= 0;
1330 if (oneSidedDim ? isOneSidedDim : isTwoSidedDim)
1331 dimMap.emplace_back(lhsDim, rhsDim);
1336std::vector<std::pair<int64_t, int64_t>> ContractionOp::getContractingDimMap() {
1340std::vector<std::pair<int64_t, int64_t>> ContractionOp::getBatchDimMap() {
1344std::vector<std::pair<int64_t, int64_t>> ContractionOp::getFreeDimMap() {
1349void ContractionOp::getIterationBounds(
1351 auto lhsShape = getLhsType().getShape();
1352 auto resVectorType = llvm::dyn_cast<VectorType>(getResultType());
1354 for (
const auto &it : llvm::enumerate(getIteratorTypes())) {
1357 auto iteratorType = llvm::cast<IteratorTypeAttr>(it.value()).getValue();
1358 if (iteratorType == IteratorType::reduction) {
1361 assert(lhsDimIndex >= 0);
1362 iterationBounds.push_back(lhsShape[lhsDimIndex]);
1367 assert(resDimIndex >= 0);
1368 assert(resVectorType !=
nullptr);
1369 iterationBounds.push_back(resVectorType.getShape()[resDimIndex]);
1373void ContractionOp::getIterationIndexMap(
1375 unsigned numMaps = getIndexingMapsArray().size();
1376 iterationIndexMap.resize(numMaps);
1377 for (
const auto &it : llvm::enumerate(getIndexingMapsArray())) {
1378 auto index = it.index();
1379 auto map = it.value();
1380 for (
unsigned i = 0, e = map.getNumResults(); i < e; ++i) {
1381 auto dim = cast<AffineDimExpr>(map.getResult(i));
1382 iterationIndexMap[
index][dim.getPosition()] = i;
1390std::optional<SmallVector<int64_t, 4>>
1391ContractionOp::getIterationShapeToUnroll() {
1393 getIterationBounds(
shape);
1397std::optional<SmallVector<int64_t>>
1398ContractionOp::getDefaultUnrollTargetShape() {
1400 Type lhsType = this->getLhsType().getElementType();
1401 nativeShape[nativeShape.size() - 1] = lhsType.
isF16() ? 4 : 2;
1423template <
typename AddOpType>
1429 auto canonicalize = [&](
Value maybeContraction,
1430 Value otherOperand) -> vector::ContractionOp {
1431 vector::ContractionOp contractionOp =
1432 dyn_cast_or_null<vector::ContractionOp>(
1435 return vector::ContractionOp();
1436 if (
auto maybeZero = dyn_cast_or_null<arith::ConstantOp>(
1437 contractionOp.getAcc().getDefiningOp())) {
1438 if (maybeZero.getValue() ==
1439 rewriter.
getZeroAttr(contractionOp.getAcc().getType())) {
1441 bvm.
map(contractionOp.getAcc(), otherOperand);
1442 auto newContraction =
1443 cast<vector::ContractionOp>(rewriter.
clone(*contractionOp, bvm));
1444 rewriter.
replaceOp(addOp, newContraction.getResult());
1445 return newContraction;
1448 return vector::ContractionOp();
1451 Value a = addOp->getOperand(0),
b = addOp->getOperand(1);
1452 vector::ContractionOp
contract = canonicalize(a,
b);
1477 setResultRanges(getResult(), argRanges.front());
1482 auto vectorTy = cast<VectorType>(source.
getType());
1507 build(builder,
result, source, dynamicPos,
1512ExtractOp::inferReturnTypes(
MLIRContext *, std::optional<Location>,
1513 ExtractOp::Adaptor adaptor,
1515 auto vectorType = llvm::cast<VectorType>(adaptor.getSource().getType());
1516 if (
static_cast<int64_t>(adaptor.getStaticPosition().size()) ==
1517 vectorType.getRank()) {
1518 inferredReturnTypes.push_back(vectorType.getElementType());
1520 auto n = std::min<size_t>(adaptor.getStaticPosition().size(),
1521 vectorType.getRank());
1522 inferredReturnTypes.push_back(VectorType::get(
1523 vectorType.getShape().drop_front(n), vectorType.getElementType(),
1524 vectorType.getScalableDims().drop_front(n)));
1529LogicalResult vector::ExtractOp::verify() {
1530 if (
auto resTy = dyn_cast<VectorType>(getResult().
getType()))
1531 if (resTy.getRank() == 0)
1533 "expected a scalar instead of a 0-d vector as the result type");
1536 auto dynamicMarkersCount =
1537 llvm::count_if(getStaticPosition(), ShapedType::isDynamic);
1538 if (
static_cast<size_t>(dynamicMarkersCount) != getDynamicPosition().size())
1540 "mismatch between dynamic and static positions (kDynamic marker but no "
1541 "corresponding dynamic position) -- this can only happen due to an "
1542 "incorrect fold/rewrite");
1543 auto position = getMixedPosition();
1544 if (position.size() >
static_cast<unsigned>(getSourceVectorType().getRank()))
1546 "expected position attribute of rank no greater than vector rank");
1547 for (
auto [idx, pos] : llvm::enumerate(position)) {
1548 if (
auto attr = dyn_cast<Attribute>(pos)) {
1549 int64_t constIdx = cast<IntegerAttr>(attr).getInt();
1551 constIdx, kPoisonIndex, getSourceVectorType().getDimSize(idx))) {
1552 return emitOpError(
"expected position attribute #")
1554 <<
" to be a non-negative integer smaller than the "
1555 "corresponding vector dimension or poison (-1)";
1562template <
typename IntType>
1564 return llvm::map_to_vector<4>(
1565 arrayAttr.getAsRange<IntegerAttr>(),
1566 [](IntegerAttr attr) { return static_cast<IntType>(attr.getInt()); });
1583 if (!extractOp.getSource().getDefiningOp<ExtractOp>())
1587 ExtractOp currentOp = extractOp;
1588 while (ExtractOp nextOp = currentOp.getSource().getDefiningOp<ExtractOp>()) {
1591 globalPosition.insert(globalPosition.begin(), pos.begin(), pos.end());
1594 Value source = currentOp.getSource();
1595 extractOp->setOperands(
1596 llvm::to_vector(llvm::concat<Value>(
ValueRange(source), dynPos)));
1597 extractOp.setStaticPosition(staticPos);
1609class ExtractFromInsertTransposeChainState {
1611 ExtractFromInsertTransposeChainState(ExtractOp e);
1620 template <
typename ContainerA,
typename ContainerB>
1621 bool isContainedWithin(
const ContainerA &a,
const ContainerB &
b) {
1622 return a.size() <=
b.size() &&
1623 std::equal(a.begin(), a.begin() + a.size(),
b.begin());
1630 template <
typename ContainerA,
typename ContainerB>
1631 bool intersectsWhereNonNegative(
const ContainerA &a,
const ContainerB &
b) {
1632 for (
auto [elemA, elemB] : llvm::zip(a,
b)) {
1633 if (elemA < 0 || elemB < 0)
1644 return (sentinels == ArrayRef(extractPosition).drop_front(extractedRank));
1648 void updateStateForNextIteration(Value v) {
1655 LogicalResult handleTransposeOp();
1658 LogicalResult handleInsertOpWithMatchingPos(Value &res);
1673 LogicalResult handleInsertOpWithPrefixPos(Value &res);
1678 Value tryToFoldExtractOpInPlace(Value source);
1680 ExtractOp extractOp;
1682 int64_t extractedRank;
1684 InsertOp nextInsertOp;
1685 TransposeOp nextTransposeOp;
1695 SmallVector<int64_t> sentinels;
1696 SmallVector<int64_t> extractPosition;
1700ExtractFromInsertTransposeChainState::ExtractFromInsertTransposeChainState(
1702 : extractOp(e), vectorRank(extractOp.getSourceVectorType().getRank()),
1703 extractedRank(extractOp.getNumIndices()) {
1704 assert(vectorRank >= extractedRank &&
"Extracted position overflow");
1705 sentinels.reserve(vectorRank - extractedRank);
1706 for (
int64_t i = 0, e = vectorRank - extractedRank; i < e; ++i)
1707 sentinels.push_back(-(i + 1));
1709 extractOp.getStaticPosition().end());
1715LogicalResult ExtractFromInsertTransposeChainState::handleTransposeOp() {
1717 if (extractOp.hasDynamicPosition())
1720 if (!nextTransposeOp)
1723 if (nextTransposeOp.getResultVectorType().getRank() == 0)
1727 nextTransposeOp.getPermutation(), extractOp.getContext()));
1734ExtractFromInsertTransposeChainState::handleInsertOpWithMatchingPos(
1737 if (extractOp.hasDynamicPosition() || nextInsertOp.hasDynamicPosition())
1740 ArrayRef<int64_t> insertedPos = nextInsertOp.getStaticPosition();
1741 if (insertedPos != llvm::ArrayRef(
extractPosition).take_front(extractedRank))
1744 res = nextInsertOp.getValueToStore();
1753ExtractFromInsertTransposeChainState::handleInsertOpWithPrefixPos(Value &res) {
1755 if (extractOp.hasDynamicPosition() || nextInsertOp.hasDynamicPosition())
1758 ArrayRef<int64_t> insertedPos = nextInsertOp.getStaticPosition();
1768 res = nextInsertOp.getValueToStore();
1776Value ExtractFromInsertTransposeChainState::tryToFoldExtractOpInPlace(
1779 if (extractOp.hasDynamicPosition())
1783 bool nothingToFold = (source == extractOp.getSource());
1784 if (nothingToFold || !canFold())
1788 OpBuilder
b(extractOp.getContext());
1789 extractOp.setStaticPosition(
1791 extractOp.getSourceMutable().assign(source);
1792 return extractOp.getResult();
1796Value ExtractFromInsertTransposeChainState::fold() {
1798 if (extractOp.hasDynamicPosition())
1801 Value valueToExtractFrom = extractOp.getSource();
1802 updateStateForNextIteration(valueToExtractFrom);
1803 while (nextInsertOp || nextTransposeOp) {
1806 if (succeeded(handleTransposeOp())) {
1807 valueToExtractFrom = nextTransposeOp.getVector();
1808 updateStateForNextIteration(valueToExtractFrom);
1814 if (succeeded(handleInsertOpWithMatchingPos(
result)))
1819 if (succeeded(handleInsertOpWithPrefixPos(
result)))
1820 return tryToFoldExtractOpInPlace(
result);
1824 ArrayRef<int64_t> insertedPos = nextInsertOp.getStaticPosition();
1830 valueToExtractFrom = nextInsertOp.getDest();
1831 updateStateForNextIteration(valueToExtractFrom);
1834 return tryToFoldExtractOpInPlace(valueToExtractFrom);
1839 auto hasZeroDimVectorType = [](
Type type) ->
bool {
1840 auto vecType = dyn_cast<VectorType>(type);
1841 return vecType && vecType.getRank() == 0;
1851 if (isa<BroadcastOp>(op))
1854 auto shapeCast = dyn_cast<ShapeCastOp>(op);
1862 VectorType srcType = shapeCast.getSourceVectorType();
1864 uint64_t srcRank = srcType.getRank();
1866 return dstShape.size() >= srcRank && dstShape.take_back(srcRank) == srcShape;
1892 Operation *defOp = extractOp.getSource().getDefiningOp();
1899 if (extractOp.getType() == input.
getType())
1905 auto inputType = llvm::dyn_cast<VectorType>(input.
getType());
1906 auto extractType = llvm::dyn_cast<VectorType>(extractOp.getType());
1907 unsigned inputRank = inputType ? inputType.getRank() : 0;
1908 unsigned broadcastRank = extractOp.getSourceVectorType().getRank();
1909 unsigned extractRank = extractType ? extractType.getRank() : 0;
1912 if (extractRank > inputRank)
1916 assert(inputType &&
"input must be a vector type because of previous checks");
1925 extractType.getShape() != inputShape.take_back(extractRank))
1930 unsigned deltaOverall = inputRank - extractRank;
1931 unsigned deltaBroadcast = broadcastRank - inputRank;
1935 for (
auto [i, size] : llvm::enumerate(inputShape.take_front(deltaOverall))) {
1936 newPositions[i] = size == 1 ? zero : oldPositions[i + deltaBroadcast];
1939 extractOp->setOperands(
1940 llvm::to_vector(llvm::concat<Value>(
ValueRange(input), dynPos)));
1941 extractOp.setStaticPosition(staticPos);
1942 return extractOp.getResult();
1958 if (extractOp.hasDynamicPosition())
1961 auto shuffleOp = extractOp.getSource().getDefiningOp<ShuffleOp>();
1966 if (shuffleOp.getResultVectorType().getRank() != 1)
1969 int64_t inputVecSize = shuffleOp.getV1().getType().getShape()[0];
1970 auto shuffleMask = shuffleOp.getMask();
1971 int64_t extractIdx = extractOp.getStaticPosition()[0];
1972 int64_t shuffleIdx = shuffleMask[extractIdx];
1975 if (shuffleIdx < inputVecSize) {
1976 extractOp.setOperand(0, shuffleOp.getV1());
1977 extractOp.setStaticPosition({shuffleIdx});
1979 extractOp.setOperand(0, shuffleOp.getV2());
1980 extractOp.setStaticPosition({shuffleIdx - inputVecSize});
1983 return extractOp.getResult();
1989 if (extractOp.hasDynamicPosition())
1992 auto shapeCastOp = extractOp.getSource().getDefiningOp<vector::ShapeCastOp>();
1997 auto getDimReverse = [](VectorType type,
int64_t n) {
1998 return type.getShape().take_back(n + 1).front();
2001 llvm::isa<VectorType>(extractOp.getType())
2002 ? llvm::cast<VectorType>(extractOp.getType()).getRank()
2004 if (destinationRank > shapeCastOp.getSourceVectorType().getRank())
2006 if (destinationRank > 0) {
2007 auto destinationType =
2008 llvm::cast<VectorType>(extractOp.getResult().getType());
2009 for (
int64_t i = 0; i < destinationRank; i++) {
2013 if (getDimReverse(shapeCastOp.getSourceVectorType(), i) !=
2014 getDimReverse(destinationType, i))
2021 std::reverse(extractedPos.begin(), extractedPos.end());
2024 for (
int64_t i = 0, e = extractedPos.size(); i < e; i++) {
2025 strides.push_back(stride);
2027 getDimReverse(extractOp.getSourceVectorType(), i + destinationRank);
2035 shapeCastOp.getSourceVectorType().getRank() - destinationRank;
2037 for (
int64_t i = 0; i < numDimension; i++) {
2038 newStrides.push_back(stride);
2040 getDimReverse(shapeCastOp.getSourceVectorType(), i + destinationRank);
2042 std::reverse(newStrides.begin(), newStrides.end());
2046 extractOp.setStaticPosition(newPosition);
2047 extractOp.setOperand(0, shapeCastOp.getSource());
2048 return extractOp.getResult();
2054 if (extractOp.hasDynamicPosition())
2057 auto extractStridedSliceOp =
2058 extractOp.getSource().getDefiningOp<vector::ExtractStridedSliceOp>();
2059 if (!extractStridedSliceOp)
2068 if (extractStridedSliceOp.hasNonUnitStrides())
2074 while (!sliceOffsets.empty()) {
2075 size_t lastOffset = sliceOffsets.size() - 1;
2076 if (sliceOffsets.back() != 0 ||
2077 extractStridedSliceOp.getType().getDimSize(lastOffset) !=
2078 extractStridedSliceOp.getSourceVectorType().getDimSize(lastOffset))
2080 sliceOffsets.pop_back();
2082 unsigned destinationRank = 0;
2083 if (
auto vecType = llvm::dyn_cast<VectorType>(extractOp.getType()))
2084 destinationRank = vecType.getRank();
2087 if (destinationRank > extractStridedSliceOp.getSourceVectorType().getRank() -
2088 sliceOffsets.size())
2092 assert(extractedPos.size() >= sliceOffsets.size());
2093 for (
size_t i = 0, e = sliceOffsets.size(); i < e; i++)
2094 extractedPos[i] = extractedPos[i] + sliceOffsets[i];
2095 extractOp.getSourceMutable().assign(extractStridedSliceOp.getSource());
2099 extractOp.setStaticPosition(extractedPos);
2100 return extractOp.getResult();
2106 if (extractOp.hasDynamicPosition())
2110 llvm::isa<VectorType>(extractOp.getType())
2111 ? llvm::cast<VectorType>(extractOp.getType()).getRank()
2113 auto insertOp = extractOp.getSource().getDefiningOp<InsertStridedSliceOp>();
2123 int64_t insertRankDiff = insertOp.getDestVectorType().getRank() -
2124 insertOp.getSourceVectorType().getRank();
2125 if (destinationRank > insertOp.getSourceVectorType().getRank())
2130 if (llvm::any_of(insertOp.getStrides(), [](
Attribute attr) {
2131 return llvm::cast<IntegerAttr>(attr).getInt() != 1;
2134 bool disjoint =
false;
2136 for (
unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) {
2137 int64_t start = insertOffsets[dim];
2139 (dim < insertRankDiff)
2141 : insertOp.getSourceVectorType().getDimSize(dim - insertRankDiff);
2143 int64_t offset = extractOffsets[dim];
2145 if (start <= offset && offset < end) {
2146 if (dim >= insertRankDiff)
2147 offsetDiffs.push_back(offset - start);
2158 insertOp.getSourceVectorType().getRank() - destinationRank;
2159 for (
int64_t i = 0; i < destinationRank; i++) {
2160 if (insertOp.getSourceVectorType().getDimSize(i + srcRankDiff) !=
2161 insertOp.getDestVectorType().getDimSize(i + srcRankDiff +
2165 extractOp.getSourceMutable().assign(insertOp.getValueToStore());
2168 extractOp.setStaticPosition(offsetDiffs);
2169 return extractOp.getResult();
2173 insertOp = insertOp.getDest().getDefiningOp<InsertStridedSliceOp>();
2186 if (extractOp.hasDynamicPosition())
2190 auto fromElementsOp = extractOp.getSource().
getDefiningOp<FromElementsOp>();
2191 if (!fromElementsOp)
2195 auto vecType = llvm::cast<VectorType>(fromElementsOp.getType());
2196 if (vecType.isScalable())
2200 int64_t rank = vecType.getRank();
2202 if (extractOp.getType() != vecType.getElementType())
2205 "unexpected number of indices");
2210 for (
int i = rank - 1; i >= 0; --i) {
2211 flatIndex +=
indices[i] * stride;
2212 stride *= vecType.getDimSize(i);
2214 return fromElementsOp.getElements()[flatIndex];
2219template <
typename OpType,
typename AdaptorType>
2222 std::vector<int64_t> staticPosition = op.getStaticPosition().vec();
2223 OperandRange dynamicPosition = op.getDynamicPosition();
2226 if constexpr (std::is_same_v<OpType, ExtractOp>)
2227 vectorShape = op.getSourceVectorType().getShape();
2232 if (!dynamicPosition.size())
2239 bool opChange =
false;
2240 for (
unsigned i = 0, e = staticPosition.size(); i < e; ++i) {
2241 if (ShapedType::isStatic(staticPosition[i]))
2245 if (
auto attr = mlir::dyn_cast_if_present<IntegerAttr>(positionAttr)) {
2246 int64_t value = attr.getInt();
2250 staticPosition[i] = attr.getInt();
2255 operands.push_back(position);
2259 op.setStaticPosition(staticPosition);
2260 op.getOperation()->setOperands(operands);
2262 return op.getResult();
2272 if (!is_contained(staticPos, poisonVal))
2275 return ub::PoisonAttr::get(context);
2289 auto denseAttr = dyn_cast_if_present<DenseElementsAttr>(srcAttr);
2294 if (denseAttr.isSplat()) {
2296 if (
auto vecDstType = dyn_cast<VectorType>(extractOp.getType()))
2301 auto vecTy = cast<VectorType>(extractOp.getSourceVectorType());
2302 if (vecTy.isScalable())
2305 if (extractOp.hasDynamicPosition()) {
2320 copy(extractOp.getStaticPosition(), completePositions.begin());
2323 auto denseValuesBegin = denseAttr.value_begin<TypedAttr>() + startPos;
2326 if (
auto resVecTy = dyn_cast<VectorType>(extractOp.getType())) {
2328 denseValuesBegin, denseValuesBegin + resVecTy.getNumElements());
2331 newAttr = *denseValuesBegin;
2337OpFoldResult ExtractOp::fold(FoldAdaptor adaptor) {
2341 if (getNumIndices() == 0 && getSource().
getType() == getResult().
getType())
2348 SmallVector<Value> operands = {getSource()};
2352 getContext(), adaptor.getStaticPosition(), kPoisonIndex))
2358 if (
auto res = ExtractFromInsertTransposeChainState(*this).fold())
2373 return inplaceFolded;
2379class ExtractOpFromBroadcast final :
public OpRewritePattern<ExtractOp> {
2383 LogicalResult matchAndRewrite(ExtractOp extractOp,
2384 PatternRewriter &rewriter)
const override {
2387 VectorType outType = dyn_cast<VectorType>(extractOp.getType());
2393 BroadcastableToResult::Success)
2402class ExtractOpFromCreateMask final :
public OpRewritePattern<ExtractOp> {
2406 LogicalResult matchAndRewrite(ExtractOp extractOp,
2407 PatternRewriter &rewriter)
const override {
2409 extractOp.getSource().getDefiningOp<vector::CreateMaskOp>();
2413 VectorType extractedMaskType =
2414 llvm::dyn_cast<VectorType>(extractOp.getResult().getType());
2416 if (!extractedMaskType)
2419 auto maskOperands = createMaskOp.getOperands();
2420 ArrayRef<int64_t> extractOpPos = extractOp.getStaticPosition();
2421 VectorType maskType = createMaskOp.getVectorType();
2423 bool containsUnknownDims =
false;
2426 for (
size_t dimIdx = 0; !allFalse && dimIdx < extractOpPos.size();
2428 int64_t pos = extractOpPos[dimIdx];
2429 Value operand = maskOperands[dimIdx];
2430 auto constantOp = operand.
getDefiningOp<arith::ConstantOp>();
2433 containsUnknownDims =
true;
2437 int64_t createMaskBound =
2438 llvm::cast<IntegerAttr>(constantOp.getValue()).getInt();
2440 if (pos != ShapedType::kDynamic) {
2443 allFalse |= pos >= createMaskBound;
2444 }
else if (createMaskBound < maskType.getDimSize(dimIdx)) {
2448 containsUnknownDims =
true;
2455 }
else if (!containsUnknownDims) {
2457 extractOp, extractedMaskType,
2458 maskOperands.drop_front(extractOpPos.size()));
2467class ExtractOpFromConstantMask final :
public OpRewritePattern<ExtractOp> {
2471 LogicalResult matchAndRewrite(ExtractOp extractOp,
2472 PatternRewriter &rewriter)
const override {
2473 auto constantMaskOp =
2474 extractOp.getSource().getDefiningOp<vector::ConstantMaskOp>();
2475 if (!constantMaskOp)
2478 Type resultType = extractOp.getResult().getType();
2479 auto extractedMaskType = dyn_cast<VectorType>(resultType);
2481 ArrayRef<int64_t> extractOpPos = extractOp.getStaticPosition();
2482 ArrayRef<int64_t> maskDimSizes = constantMaskOp.getMaskDimSizes();
2484 VectorType maskType = constantMaskOp.getVectorType();
2487 for (
size_t dimIdx = 0; dimIdx < extractOpPos.size(); dimIdx++) {
2488 int64_t pos = extractOpPos[dimIdx];
2489 if (pos == ShapedType::kDynamic) {
2492 if (maskDimSizes[dimIdx] == maskType.getDimSize(dimIdx))
2501 if (pos >= maskDimSizes[dimIdx]) {
2502 if (extractedMaskType) {
2514 if (extractedMaskType) {
2518 extractOp, extractedMaskType,
2519 maskDimSizes.drop_front(extractOpPos.size()));
2532LogicalResult foldExtractFromShapeCastToShapeCast(ExtractOp extractOp,
2533 PatternRewriter &rewriter) {
2534 auto castOp = extractOp.getSource().getDefiningOp<ShapeCastOp>();
2538 VectorType sourceType = castOp.getSourceVectorType();
2539 auto targetType = dyn_cast<VectorType>(extractOp.getResult().getType());
2543 if (sourceType.getNumElements() != targetType.getNumElements())
2547 castOp.getSource());
2557LogicalResult foldExtractFromFromElements(ExtractOp extractOp,
2558 PatternRewriter &rewriter) {
2560 if (extractOp.hasDynamicPosition())
2564 auto resultType = dyn_cast<VectorType>(extractOp.getType());
2569 auto fromElementsOp = extractOp.getSource().getDefiningOp<FromElementsOp>();
2570 if (!fromElementsOp)
2572 VectorType inputType = fromElementsOp.getType();
2575 if (resultType.isScalable() || inputType.isScalable())
2580 SmallVector<int64_t> firstElementPos =
2581 llvm::to_vector(extractOp.getStaticPosition());
2582 firstElementPos.append(resultType.getRank(), 0);
2585 for (int64_t i = inputType.getRank() - 1; i >= 0; --i) {
2586 flatIndex += firstElementPos[i] * stride;
2587 stride *= inputType.getDimSize(i);
2592 extractOp, resultType,
2593 fromElementsOp.getElements().
slice(flatIndex,
2594 resultType.getNumElements()));
2606struct ExtractToShapeCast final : OpRewritePattern<vector::ExtractOp> {
2608 LogicalResult matchAndRewrite(vector::ExtractOp extractOp,
2609 PatternRewriter &rewriter)
const override {
2610 VectorType sourceType = extractOp.getSourceVectorType();
2611 VectorType outType = dyn_cast<VectorType>(extractOp.getType());
2615 if (sourceType.getNumElements() != outType.getNumElements())
2617 extractOp,
"extract to vector with fewer elements");
2621 if (llvm::any_of(extractOp.getMixedPosition(),
2622 [](OpFoldResult v) { return !isConstantIntValue(v, 0); }))
2624 "leaving for extract poison folder");
2627 extractOp.getSource());
2648struct FoldExtractFromInsertUnitDim final
2649 : OpRewritePattern<vector::ExtractOp> {
2652 LogicalResult matchAndRewrite(vector::ExtractOp extractOp,
2653 PatternRewriter &rewriter)
const override {
2654 if (extractOp.hasDynamicPosition())
2657 auto insertOp = extractOp.getSource().getDefiningOp<vector::InsertOp>();
2658 if (!insertOp || insertOp.hasDynamicPosition())
2661 ArrayRef<int64_t> extractPos = extractOp.getStaticPosition();
2662 ArrayRef<int64_t> insertPos = insertOp.getStaticPosition();
2665 if (extractPos.size() >= insertPos.size() ||
2666 extractPos != insertPos.take_front(extractPos.size()))
2672 auto srcVecType = extractOp.getSourceVectorType();
2673 for (int64_t i = extractPos.size(), e = srcVecType.getRank(); i < e; ++i)
2674 if (srcVecType.getDimSize(i) != 1)
2677 Value
inserted = insertOp.getValueToStore();
2678 Type extractedType = extractOp.getResult().getType();
2679 if (isa<VectorType>(
inserted.getType())) {
2686 extractOp, extractOp.getResult().
getType(),
2687 insertOp.getValueToStore());
2695void ExtractOp::getCanonicalizationPatterns(RewritePatternSet &results,
2696 MLIRContext *context) {
2697 results.
add<ExtractOpFromBroadcast, ExtractOpFromCreateMask,
2698 ExtractOpFromConstantMask, ExtractToShapeCast,
2699 FoldExtractFromInsertUnitDim>(context);
2700 results.
add(foldExtractFromShapeCastToShapeCast);
2701 results.
add(foldExtractFromFromElements);
2706 for (
auto attr : arrayAttr)
2707 results.push_back(llvm::cast<IntegerAttr>(attr).getInt());
2717std::optional<SmallVector<int64_t, 4>> FMAOp::getIterationShapeToUnroll() {
2728 if (operands.empty())
2731 return llvm::all_of(operands, [&](
Value operand) {
2733 return currentDef == defOp;
2751 auto fromElementsOp =
2752 toElementsOp.getSource().getDefiningOp<FromElementsOp>();
2753 if (!fromElementsOp)
2756 llvm::append_range(results, fromElementsOp.getElements());
2773 auto bcastOp = toElementsOp.getSource().getDefiningOp<BroadcastOp>();
2777 if (isa<VectorType>(bcastOp.getSource().getType()))
2780 auto resultVecType = cast<VectorType>(toElementsOp.getSource().getType());
2782 Value scalar = bcastOp.getSource();
2783 results.assign(resultVecType.getNumElements(), scalar);
2787LogicalResult ToElementsOp::fold(FoldAdaptor adaptor,
2788 SmallVectorImpl<OpFoldResult> &results) {
2793 if (
auto shapeCast = getSource().getDefiningOp<ShapeCastOp>()) {
2794 setOperand(shapeCast.getSource());
2802ToElementsOp::inferReturnTypes(MLIRContext *ctx, std::optional<Location> loc,
2803 ToElementsOp::Adaptor adaptor,
2804 SmallVectorImpl<Type> &inferredReturnTypes) {
2805 auto vecType = cast<VectorType>(adaptor.getSource().getType());
2806 Type elType = vecType.getElementType();
2807 inferredReturnTypes.append(vecType.getNumElements(), elType);
2829 auto bcastOp = toElementsOp.getSource().getDefiningOp<BroadcastOp>();
2834 auto srcType = dyn_cast<VectorType>(bcastOp.getSource().getType());
2838 auto dstType = cast<VectorType>(toElementsOp.getSource().getType());
2843 int64_t dstRank = dstShape.size();
2844 int64_t srcRank = srcShape.size();
2847 auto srcElems = vector::ToElementsOp::create(
2848 rewriter, toElementsOp.getLoc(), bcastOp.getSource());
2850 int64_t dstCount = llvm::product_of(dstShape);
2853 replacements.reserve(dstCount);
2878 for (
int64_t lin = 0; lin < dstCount; ++lin) {
2881 for (
int64_t k = 0; k < srcRank; ++k)
2882 srcIdx[k] = (srcShape[k] == 1) ? 0 : dstIdx[dstRank - srcRank + k];
2885 replacements.push_back(srcElems.getResult(srcLin));
2888 rewriter.
replaceOp(toElementsOp, replacements);
2893void ToElementsOp::getCanonicalizationPatterns(RewritePatternSet &results,
2894 MLIRContext *context) {
2895 results.
add<ToElementsOfBroadcast>(context);
2915 OperandRange fromElemsOperands = fromElementsOp.getElements();
2916 if (fromElemsOperands.empty())
2919 auto toElementsOp = fromElemsOperands[0].getDefiningOp<ToElementsOp>();
2927 Value toElementsInput = toElementsOp.getSource();
2928 if (fromElementsOp.getType() == toElementsInput.
getType() &&
2929 llvm::equal(fromElemsOperands, toElementsOp.getResults())) {
2930 return toElementsInput;
2950 if (llvm::any_of(elements, [](
Attribute attr) {
2956 auto resVecType = fromElementsOp.getResult().getType();
2957 auto resEltType = resVecType.getElementType();
2958 if (!resEltType.isIntOrIndexOrFloat() && !isa<ComplexType>(resEltType))
2963 auto convertedElements = llvm::map_to_vector(elements, [&](
Attribute attr) {
2970OpFoldResult FromElementsOp::fold(FoldAdaptor adaptor) {
2987 if (!llvm::all_equal(fromElementsOp.getElements()))
2990 fromElementsOp, fromElementsOp.getType(),
2991 fromElementsOp.getElements().front());
3019 LogicalResult matchAndRewrite(FromElementsOp fromElements,
3023 if (fromElements.getType().getNumElements() == 1)
3034 for (
auto [insertIndex, element] :
3035 llvm::enumerate(fromElements.getElements())) {
3038 auto extractOp = element.getDefiningOp<vector::ExtractOp>();
3041 "element not from vector.extract");
3046 if (insertIndex == 0) {
3047 source = extractOp.getSource();
3048 }
else if (extractOp.getSource() != source) {
3050 "element from different vector");
3054 int64_t rank = position.size();
3055 assert(rank == source.getType().getRank() &&
3056 "scalar extract must have full rank position");
3067 if (insertIndex == 0) {
3068 const int64_t numElms = fromElements.getType().getNumElements();
3071 while (
index > 0 && position[
index - 1] == 0 &&
3072 numSuffixElms < numElms) {
3073 numSuffixElms *= source.getType().getDimSize(
index - 1);
3076 if (numSuffixElms != numElms) {
3078 fromElements,
"elements do not form a suffix of source");
3080 expectedPosition = llvm::to_vector(position);
3081 combinedPosition = position.drop_back(rank -
index);
3085 else if (expectedPosition != position) {
3087 fromElements,
"elements not in ascending order (static order)");
3089 increment(expectedPosition, source.getType().getShape());
3092 auto extracted = rewriter.
createOrFold<vector::ExtractOp>(
3093 fromElements.getLoc(), source, combinedPosition);
3096 fromElements, fromElements.getType(), extracted);
3104 for (
int dim : llvm::reverse(llvm::seq<int>(0,
indices.size()))) {
3123void BroadcastOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
3125 setResultRanges(getResult(), argRanges.front());
3131std::optional<SmallVector<int64_t, 4>>
3132BroadcastOp::getIterationShapeToUnroll() {
3133 return llvm::to_vector<4>(getResultVectorType().
getShape());
3138static llvm::SetVector<int64_t>
3141 int64_t rankDiff = dstShape.size() - srcShape.size();
3144 for (
auto [s1, s2] :
3145 llvm::zip_equal(srcShape, dstShape.drop_front(rankDiff))) {
3147 assert(s1 == 1 &&
"expected \"dim-1\" broadcasting");
3155llvm::SetVector<int64_t> BroadcastOp::computeBroadcastedUnitDims() {
3157 auto srcVectorType = llvm::dyn_cast<VectorType>(getSourceType());
3160 return ::computeBroadcastedUnitDims(srcVectorType.getShape(),
3176Value BroadcastOp::createOrFoldBroadcastOp(
3177 OpBuilder &
b, Value value, ArrayRef<int64_t> dstShape,
3178 const llvm::SetVector<int64_t> &broadcastedDims) {
3179 assert(!dstShape.empty() &&
"unexpected empty dst shape");
3182 SmallVector<int64_t> checkShape;
3183 for (
int i = 0, e = dstShape.size(); i < e; ++i) {
3184 if (broadcastedDims.contains(i))
3186 checkShape.push_back(dstShape[i]);
3188 assert(broadcastedDims.size() == dstShape.size() - checkShape.size() &&
3189 "ill-formed broadcastedDims contains values not confined to "
3192 Location loc = value.
getLoc();
3194 VectorType srcVectorType = llvm::dyn_cast<VectorType>(value.
getType());
3195 VectorType dstVectorType = VectorType::get(dstShape, elementType);
3198 if (!srcVectorType) {
3199 assert(checkShape.empty() &&
3200 "ill-formed createOrFoldBroadcastOp arguments");
3201 return b.createOrFold<vector::BroadcastOp>(loc, dstVectorType, value);
3204 assert(srcVectorType.getShape().equals(checkShape) &&
3205 "ill-formed createOrFoldBroadcastOp arguments");
3215 SmallVector<int64_t> broadcastShape, permutation(dstShape.size(), -1);
3216 broadcastShape.reserve(dstShape.size());
3232 int64_t nextSrcShapeDim = broadcastedDims.size();
3233 for (int64_t i = 0, e = dstShape.size(); i < e; ++i) {
3234 if (broadcastedDims.contains(i)) {
3239 broadcastShape.push_back(dstShape[i]);
3240 permutation[i] = broadcastShape.size() - 1;
3246 permutation[i] = nextSrcShapeDim++;
3250 llvm::append_range(broadcastShape, srcVectorType.getShape());
3255 "unexpected \"dim-1\" broadcast");
3257 VectorType broadcastType = VectorType::get(broadcastShape, elementType);
3259 vector::BroadcastableToResult::Success &&
3260 "must be broadcastable");
3261 Value res =
b.createOrFold<vector::BroadcastOp>(loc, broadcastType, value);
3264 for (int64_t i = 0, e = permutation.size(); i < e; ++i)
3265 if (permutation[i] != i)
3266 return b.createOrFold<vector::TransposeOp>(loc, res, permutation);
3271LogicalResult BroadcastOp::verify() {
3272 std::pair<VectorDim, VectorDim> mismatchingDims;
3274 getSourceType(), getResultVectorType(), &mismatchingDims);
3275 if (res == BroadcastableToResult::Success)
3277 if (res == BroadcastableToResult::SourceRankHigher)
3278 return emitOpError(
"source rank higher than destination rank");
3279 if (res == BroadcastableToResult::DimensionMismatch) {
3280 return emitOpError(
"dimension mismatch (")
3281 << (mismatchingDims.first.isScalable ?
"[" :
"")
3282 << mismatchingDims.first.dim
3283 << (mismatchingDims.first.isScalable ?
"]" :
"") <<
" vs. "
3284 << (mismatchingDims.second.isScalable ?
"[" :
"")
3285 << mismatchingDims.second.dim
3286 << (mismatchingDims.second.isScalable ?
"]" :
"") <<
")";
3288 if (res == BroadcastableToResult::SourceTypeNotAVector)
3289 return emitOpError(
"source type is not a vector");
3290 llvm_unreachable(
"unexpected vector.broadcast op error");
3297 auto srcShapeCast = broadcastOp.getSource().getDefiningOp<ShapeCastOp>();
3301 VectorType srcType = srcShapeCast.getSourceVectorType();
3302 VectorType destType = broadcastOp.getResultVectorType();
3310 srcShapeCast.getResultVectorType().getShape();
3313 unsigned numTrailingDims = std::min(srcShape.size(), shapecastShape.size());
3314 if (!llvm::equal(srcShape.take_back(numTrailingDims),
3315 shapecastShape.take_back(numTrailingDims)))
3318 assert(all_of(srcShape.drop_back(numTrailingDims),
3319 [](
int64_t E) { return E == 1; }) &&
3320 all_of(shapecastShape.drop_back(numTrailingDims),
3321 [](
int64_t E) { return E == 1; }) &&
3322 "ill-formed shape_cast");
3324 broadcastOp.getSourceMutable().assign(srcShapeCast.getSource());
3328OpFoldResult BroadcastOp::fold(FoldAdaptor adaptor) {
3329 if (getSourceType() == getResultVectorType())
3334 if (!adaptor.getSource())
3336 auto vectorType = getResultVectorType();
3337 if (
auto attr = llvm::dyn_cast<IntegerAttr>(adaptor.getSource())) {
3338 if (vectorType.getElementType() != attr.getType())
3342 if (
auto attr = llvm::dyn_cast<FloatAttr>(adaptor.getSource())) {
3343 if (vectorType.getElementType() != attr.getType())
3347 if (
auto attr = llvm::dyn_cast<SplatElementsAttr>(adaptor.getSource()))
3357struct BroadcastFolder :
public OpRewritePattern<BroadcastOp> {
3360 LogicalResult matchAndRewrite(BroadcastOp broadcastOp,
3361 PatternRewriter &rewriter)
const override {
3362 auto srcBroadcast = broadcastOp.getSource().getDefiningOp<BroadcastOp>();
3366 broadcastOp.getResultVectorType(),
3367 srcBroadcast.getSource());
3380struct BroadcastToShapeCast final
3381 :
public OpRewritePattern<vector::BroadcastOp> {
3383 LogicalResult matchAndRewrite(vector::BroadcastOp
broadcast,
3384 PatternRewriter &rewriter)
const override {
3386 auto sourceType = dyn_cast<VectorType>(
broadcast.getSourceType());
3389 broadcast,
"source is a scalar, shape_cast doesn't support scalar");
3393 if (sourceType.getNumElements() != outType.getNumElements()) {
3395 broadcast,
"broadcast to a greater number of elements");
3405void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &results,
3406 MLIRContext *context) {
3407 results.
add<BroadcastFolder, BroadcastToShapeCast>(context);
3414LogicalResult ShuffleOp::verify() {
3415 VectorType resultType = getResultVectorType();
3416 VectorType v1Type = getV1VectorType();
3417 VectorType v2Type = getV2VectorType();
3419 int64_t resRank = resultType.getRank();
3420 int64_t v1Rank = v1Type.getRank();
3421 int64_t v2Rank = v2Type.getRank();
3422 bool wellFormed0DCase = v1Rank == 0 && v2Rank == 0 && resRank == 1;
3423 bool wellFormedNDCase = v1Rank == resRank && v2Rank == resRank;
3424 if (!wellFormed0DCase && !wellFormedNDCase)
3425 return emitOpError(
"rank mismatch");
3428 for (int64_t r = 1; r < v1Rank; ++r) {
3429 int64_t resDim = resultType.getDimSize(r);
3430 int64_t v1Dim = v1Type.getDimSize(r);
3431 int64_t v2Dim = v2Type.getDimSize(r);
3432 if (resDim != v1Dim || v1Dim != v2Dim)
3433 return emitOpError(
"dimension mismatch");
3436 ArrayRef<int64_t> mask = getMask();
3437 int64_t maskLength = mask.size();
3438 if (maskLength <= 0)
3439 return emitOpError(
"invalid mask length");
3440 if (maskLength != resultType.getDimSize(0))
3441 return emitOpError(
"mask length mismatch");
3443 int64_t indexSize = (v1Type.getRank() == 0 ? 1 : v1Type.getDimSize(0)) +
3444 (v2Type.getRank() == 0 ? 1 : v2Type.getDimSize(0));
3445 for (
auto [idx, maskPos] : llvm::enumerate(mask)) {
3447 return emitOpError(
"mask index #") << (idx + 1) <<
" out of range";
3453ShuffleOp::inferReturnTypes(MLIRContext *, std::optional<Location> loc,
3454 ShuffleOp::Adaptor adaptor,
3455 SmallVectorImpl<Type> &inferredReturnTypes) {
3456 auto v1Type = llvm::dyn_cast<VectorType>(adaptor.getV1().getType());
3460 auto v1Rank = v1Type.getRank();
3463 SmallVector<int64_t, 4> shape;
3464 shape.reserve(v1Rank);
3465 shape.push_back(std::max<size_t>(1, adaptor.getMask().size()));
3468 llvm::append_range(shape, v1Type.getShape().drop_front());
3469 inferredReturnTypes.push_back(
3470 VectorType::get(shape, v1Type.getElementType()));
3474template <
typename T>
3477 return idxArr.size() == width && llvm::all_of(idxArr, [&expected](T value) {
3478 return value == expected++;
3485 auto v1Type = op.getV1VectorType();
3486 auto v2Type = op.getV2VectorType();
3487 auto mask = op.getMask();
3500 if (!isV1Poison && !isV2Poison)
3503 int64_t v1Size = op.getV1VectorType().getDimSize(0);
3504 bool changed =
false;
3506 for (
int64_t &idx : newMask) {
3507 if (idx == ShuffleOp::kPoisonIndex)
3509 if ((isV1Poison && idx < v1Size) || (isV2Poison && idx >= v1Size)) {
3510 idx = ShuffleOp::kPoisonIndex;
3518 op.setMask(newMask);
3519 return op.getResult();
3528 return ub::PoisonAttr::get(context);
3535 auto v1Type = op.getV1VectorType();
3536 if (v1Type.getRank() != 1)
3548 auto v2DenseAttr = dyn_cast<DenseElementsAttr>(v2Attr);
3551 v2Elements = to_vector(v2DenseAttr.getValues<
Attribute>());
3552 poisonElement = v2Elements[0];
3555 auto v1DenseAttr = dyn_cast<DenseElementsAttr>(v1Attr);
3558 v1Elements = to_vector(v1DenseAttr.getValues<
Attribute>());
3559 poisonElement = v1Elements[0];
3564 int64_t v1Size = v1Type.getDimSize(0);
3565 for (
int64_t maskIdx : mask) {
3568 if (maskIdx == ShuffleOp::kPoisonIndex) {
3569 indexedElm = poisonElement;
3571 if (maskIdx < v1Size)
3572 indexedElm = isV1Poison ? poisonElement : v1Elements[maskIdx];
3574 indexedElm = isV2Poison ? poisonElement : v2Elements[maskIdx - v1Size];
3577 results.push_back(indexedElm);
3583OpFoldResult vector::ShuffleOp::fold(FoldAdaptor adaptor) {
3584 auto v1Type = getV1VectorType();
3586 assert(!v1Type.isScalable() && !getV2VectorType().isScalable() &&
3587 "Vector shuffle does not support scalable vectors");
3591 if (v1Type.getRank() == 0)
3599 Attribute v1Attr = adaptor.getV1(), v2Attr = adaptor.getV2();
3600 if (!v1Attr || !v2Attr)
3615struct Canonicalize0DShuffleOp :
public OpRewritePattern<ShuffleOp> {
3618 LogicalResult matchAndRewrite(ShuffleOp shuffleOp,
3619 PatternRewriter &rewriter)
const override {
3620 VectorType v1VectorType = shuffleOp.getV1VectorType();
3621 ArrayRef<int64_t> mask = shuffleOp.getMask();
3622 if (v1VectorType.getRank() > 0)
3624 if (mask.size() != 1)
3626 VectorType resType = VectorType::Builder(v1VectorType).setShape({1});
3644static Value getScalarSplatSource(Value value) {
3650 auto broadcast = dyn_cast<vector::BroadcastOp>(defOp);
3657 if (isa<VectorType>(
broadcast.getSourceType()))
3665class ShuffleSplat final :
public OpRewritePattern<ShuffleOp> {
3669 LogicalResult matchAndRewrite(ShuffleOp op,
3670 PatternRewriter &rewriter)
const override {
3671 Value splat = getScalarSplatSource(op.getV1());
3672 if (!splat || getScalarSplatSource(op.getV2()) != splat)
3682class ShuffleInterleave :
public OpRewritePattern<ShuffleOp> {
3686 LogicalResult matchAndRewrite(ShuffleOp op,
3687 PatternRewriter &rewriter)
const override {
3688 VectorType resultType = op.getResultVectorType();
3689 if (resultType.isScalable())
3691 op,
"ShuffleOp can't represent a scalable interleave");
3693 if (resultType.getRank() != 1)
3695 op,
"ShuffleOp can't represent an n-D interleave");
3697 VectorType sourceType = op.getV1VectorType();
3698 if (sourceType != op.getV2VectorType() ||
3699 sourceType.getNumElements() * 2 != resultType.getNumElements()) {
3701 op,
"ShuffleOp types don't match an interleave");
3704 ArrayRef<int64_t> shuffleMask = op.getMask();
3705 int64_t resultVectorSize = resultType.getNumElements();
3706 for (
int i = 0, e = resultVectorSize / 2; i < e; ++i) {
3707 int64_t maskValueA = shuffleMask[i * 2];
3708 int64_t maskValueB = shuffleMask[(i * 2) + 1];
3709 if (maskValueA != i || maskValueB != (resultVectorSize / 2) + i)
3711 "ShuffleOp mask not interleaving");
3727class FoldUnusedShuffleOperand final :
public OpRewritePattern<ShuffleOp> {
3731 LogicalResult matchAndRewrite(ShuffleOp op,
3732 PatternRewriter &rewriter)
const override {
3734 if (llvm::all_of(op.getMask(), [](int64_t mask) {
3735 return mask == ShuffleOp::kPoisonIndex;
3742 auto replaceOperandWithPoison = [&](OpOperand &operand) {
3745 Value poison = ub::PoisonOp::create(rewriter, op.getLoc(),
3754 int64_t leadingV1Size = op.getV1VectorType().getRank() > 0
3755 ? op.getV1VectorType().getDimSize(0)
3757 bool isV1Used = llvm::any_of(op.getMask(), [&](int64_t mask) {
3758 return mask != ShuffleOp::kPoisonIndex && mask < leadingV1Size;
3760 if (!isV1Used && succeeded(replaceOperandWithPoison(op.getV1Mutable())))
3764 bool isV2Used = llvm::any_of(op.getMask(), [&](int64_t mask) {
3765 return mask != ShuffleOp::kPoisonIndex && mask >= leadingV1Size;
3767 if (!isV2Used && succeeded(replaceOperandWithPoison(op.getV2Mutable())))
3775void ShuffleOp::getCanonicalizationPatterns(RewritePatternSet &results,
3776 MLIRContext *context) {
3777 results.
add<ShuffleSplat, ShuffleInterleave, Canonicalize0DShuffleOp,
3778 FoldUnusedShuffleOperand>(context);
3785void vector::InsertOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
3787 setResultRanges(getResult(), argRanges[0].rangeUnion(argRanges[1]));
3790void vector::InsertOp::build(OpBuilder &builder, OperationState &
result,
3791 Value source, Value dest) {
3792 auto vectorTy = cast<VectorType>(dest.
getType());
3793 build(builder,
result, source, dest,
3794 SmallVector<int64_t>(vectorTy.getRank(), 0));
3797void vector::InsertOp::build(OpBuilder &builder, OperationState &
result,
3798 Value source, Value dest, int64_t position) {
3799 build(builder,
result, source, dest, ArrayRef<int64_t>{position});
3802void vector::InsertOp::build(OpBuilder &builder, OperationState &
result,
3803 Value source, Value dest, OpFoldResult position) {
3804 build(builder,
result, source, dest, ArrayRef<OpFoldResult>{position});
3807void vector::InsertOp::build(OpBuilder &builder, OperationState &
result,
3808 Value source, Value dest,
3809 ArrayRef<int64_t> position) {
3810 SmallVector<OpFoldResult> posVals;
3811 posVals.reserve(position.size());
3812 llvm::transform(position, std::back_inserter(posVals),
3814 build(builder,
result, source, dest, posVals);
3817void vector::InsertOp::build(OpBuilder &builder, OperationState &
result,
3818 Value source, Value dest,
3819 ArrayRef<OpFoldResult> position) {
3820 SmallVector<int64_t> staticPos;
3821 SmallVector<Value> dynamicPos;
3823 build(builder,
result, source, dest, dynamicPos,
3827LogicalResult InsertOp::verify() {
3828 if (
auto srcTy = dyn_cast<VectorType>(getValueToStoreType()))
3829 if (srcTy.getRank() == 0)
3831 "expected a scalar instead of a 0-d vector as the source operand");
3833 SmallVector<OpFoldResult> position = getMixedPosition();
3834 auto destVectorType = getDestVectorType();
3835 if (position.size() >
static_cast<unsigned>(destVectorType.getRank()))
3837 "expected position attribute of rank no greater than dest vector rank");
3838 auto srcVectorType = llvm::dyn_cast<VectorType>(getValueToStoreType());
3839 if (srcVectorType &&
3840 (
static_cast<unsigned>(srcVectorType.getRank()) + position.size() !=
3841 static_cast<unsigned>(destVectorType.getRank())))
3842 return emitOpError(
"expected position attribute rank + source rank to "
3843 "match dest vector rank");
3844 if (!srcVectorType &&
3845 (position.size() !=
static_cast<unsigned>(destVectorType.getRank())))
3847 "expected position attribute rank to match the dest vector rank");
3848 for (
auto [idx, pos] : llvm::enumerate(position)) {
3849 if (
auto attr = dyn_cast<Attribute>(pos)) {
3850 int64_t constIdx = cast<IntegerAttr>(attr).getInt();
3852 destVectorType.getDimSize(idx))) {
3853 return emitOpError(
"expected position attribute #")
3855 <<
" to be a non-negative integer smaller than the "
3857 "dest vector dimension";
3870 assert(positions.size() <= completePositions.size() &&
3871 "positions size must be less than or equal to destTy rank");
3872 copy(positions, completePositions.begin());
3880class InsertToBroadcast final :
public OpRewritePattern<InsertOp> {
3884 LogicalResult matchAndRewrite(InsertOp insertOp,
3885 PatternRewriter &rewriter)
const override {
3887 llvm::dyn_cast<VectorType>(insertOp.getValueToStoreType());
3888 if (!srcVecType || insertOp.getDestVectorType().getNumElements() !=
3889 srcVecType.getNumElements())
3892 insertOp, insertOp.getDestVectorType(), insertOp.getValueToStore());
3898class InsertSplatToSplat final :
public OpRewritePattern<InsertOp> {
3902 LogicalResult matchAndRewrite(InsertOp op,
3903 PatternRewriter &rewriter)
const override {
3905 Value splat = getScalarSplatSource(op.getValueToStore());
3906 if (!splat || getScalarSplatSource(op.getDest()) != splat)
3934class InsertChainFullyInitialized final :
public OpRewritePattern<InsertOp> {
3937 LogicalResult matchAndRewrite(InsertOp op,
3938 PatternRewriter &rewriter)
const override {
3940 VectorType destTy = op.getDestVectorType();
3941 if (destTy.isScalable())
3944 for (Operation *user : op.getResult().getUsers())
3945 if (
auto insertOp = dyn_cast<InsertOp>(user))
3946 if (insertOp.getDest() == op.getResult())
3949 InsertOp currentOp = op;
3950 SmallVector<InsertOp> chainInsertOps;
3953 if (currentOp.hasDynamicPosition())
3956 chainInsertOps.push_back(currentOp);
3957 currentOp = currentOp.getDest().getDefiningOp<InsertOp>();
3960 if (currentOp && !currentOp->hasOneUse())
3964 int64_t vectorSize = destTy.getNumElements();
3965 int64_t initializedCount = 0;
3966 SmallVector<bool> initializedDestIdxs(vectorSize,
false);
3967 SmallVector<int64_t> pendingInsertPos;
3968 SmallVector<int64_t> pendingInsertSize;
3969 SmallVector<Value> pendingInsertValues;
3971 for (
auto insertOp : chainInsertOps) {
3973 if (is_contained(insertOp.getStaticPosition(), InsertOp::kPoisonIndex))
3977 int64_t insertBeginPosition =
3982 int64_t insertSize = 1;
3983 if (
auto srcVectorType =
3984 llvm::dyn_cast<VectorType>(insertOp.getValueToStoreType()))
3985 insertSize = srcVectorType.getNumElements();
3987 assert(insertBeginPosition + insertSize <= vectorSize &&
3988 "insert would overflow the vector");
3990 for (
auto index : llvm::seq<int64_t>(insertBeginPosition,
3991 insertBeginPosition + insertSize)) {
3992 if (initializedDestIdxs[index])
3994 initializedDestIdxs[index] =
true;
4000 pendingInsertPos.push_back(insertBeginPosition);
4001 pendingInsertSize.push_back(insertSize);
4002 pendingInsertValues.push_back(insertOp.getValueToStore());
4004 if (initializedCount == vectorSize)
4009 if (initializedCount != vectorSize)
4012 SmallVector<Value> elements(vectorSize);
4013 for (
auto [insertBeginPosition, insertSize, valueToStore] :
4014 llvm::reverse(llvm::zip(pendingInsertPos, pendingInsertSize,
4015 pendingInsertValues))) {
4016 auto srcVectorType = llvm::dyn_cast<VectorType>(valueToStore.getType());
4018 if (!srcVectorType) {
4019 elements[insertBeginPosition] = valueToStore;
4023 Repeated<Type> elementToInsertTypes(insertSize,
4024 srcVectorType.getElementType());
4026 auto elementsToInsert = vector::ToElementsOp::create(
4027 rewriter, op.getLoc(), elementToInsertTypes, valueToStore);
4028 for (int64_t linearIdx = 0; linearIdx < insertSize; linearIdx++) {
4029 elements[insertBeginPosition + linearIdx] =
4030 elementsToInsert.getResult(linearIdx);
4044 int64_t maxVectorSizeFoldThreshold) {
4045 if (insertOp.hasDynamicPosition())
4048 auto denseDst = llvm::dyn_cast_if_present<DenseElementsAttr>(dstAttr);
4056 VectorType destTy = insertOp.getDestVectorType();
4057 if (destTy.isScalable())
4061 if (destTy.getNumElements() > maxVectorSizeFoldThreshold &&
4062 !insertOp->hasOneUse())
4067 if (is_contained(insertOp.getStaticPosition(), InsertOp::kPoisonIndex))
4074 Type destEltType = destTy.getElementType();
4078 if (
auto denseSource = llvm::dyn_cast<DenseElementsAttr>(srcAttr)) {
4079 for (
auto value : denseSource.getValues<
Attribute>())
4085 auto allValues = llvm::to_vector(denseDst.getValues<
Attribute>());
4086 copy(insertedValues, allValues.begin() + insertBeginPosition);
4095 auto destInsert = insertOp.getDest().
getDefiningOp<InsertOp>();
4099 if (insertOp.getMixedPosition() != destInsert.getMixedPosition())
4102 insertOp.
setOperand(1, destInsert.getDest());
4103 return insertOp.getResult();
4106void InsertOp::getCanonicalizationPatterns(RewritePatternSet &results,
4107 MLIRContext *context) {
4108 results.
add<InsertToBroadcast, BroadcastFolder, InsertSplatToSplat,
4109 InsertChainFullyInitialized>(context);
4112OpFoldResult InsertOp::fold(FoldAdaptor adaptor) {
4115 constexpr int64_t vectorSizeFoldThreshold = 256;
4119 if (getNumIndices() == 0 && getValueToStoreType() ==
getType())
4120 return getValueToStore();
4124 SmallVector<Value> operands = {getValueToStore(), getDest()};
4130 getContext(), adaptor.getStaticPosition(), kPoisonIndex))
4133 *
this, adaptor.getValueToStore(), adaptor.getDest(),
4134 vectorSizeFoldThreshold)) {
4138 return inplaceFolded;
4145void InsertStridedSliceOp::build(OpBuilder &builder, OperationState &
result,
4146 Value source, Value dest,
4147 ArrayRef<int64_t> offsets,
4148 ArrayRef<int64_t> strides) {
4149 result.addOperands({source, dest});
4153 result.addAttribute(InsertStridedSliceOp::getOffsetsAttrName(
result.name),
4155 result.addAttribute(InsertStridedSliceOp::getStridesAttrName(
result.name),
4160template <
typename OpType>
4164 StringRef attrName) {
4165 if (arrayAttr.size() >
shape.size())
4166 return op.emitOpError(
"expected ")
4167 << attrName <<
" attribute of rank no greater than vector rank";
4174template <
typename OpType>
4178 bool halfOpen =
true) {
4179 for (
auto attr : arrayAttr) {
4180 auto val = llvm::cast<IntegerAttr>(attr).getInt();
4184 if (val < min || val >= upper)
4185 return op.emitOpError(
"expected ") << attrName <<
" to be confined to ["
4186 <<
min <<
", " << upper <<
")";
4194template <
typename OpType>
4199 for (
auto [
index, attrDimPair] :
4200 llvm::enumerate(llvm::zip_first(arrayAttr,
shape))) {
4201 int64_t val = llvm::cast<IntegerAttr>(std::get<0>(attrDimPair)).getInt();
4205 if (val < min || val >=
max)
4206 return op.emitOpError(
"expected ")
4207 << attrName <<
" dimension " <<
index <<
" to be confined to ["
4208 <<
min <<
", " <<
max <<
")";
4218template <
typename OpType>
4223 assert(arrayAttr1.size() <=
shape.size());
4224 assert(arrayAttr2.size() <=
shape.size());
4225 for (
auto [
index, it] :
4226 llvm::enumerate(llvm::zip(arrayAttr1, arrayAttr2,
shape))) {
4227 auto val1 = llvm::cast<IntegerAttr>(std::get<0>(it)).getInt();
4228 auto val2 = llvm::cast<IntegerAttr>(std::get<1>(it)).getInt();
4232 if (val1 + val2 < 0 || val1 + val2 >=
max)
4233 return op.emitOpError(
"expected sum(")
4234 << attrName1 <<
", " << attrName2 <<
") dimension " <<
index
4235 <<
" to be confined to [" <<
min <<
", " <<
max <<
")";
4243 return IntegerAttr::get(IntegerType::get(context, 64), APInt(64, v));
4245 return ArrayAttr::get(context, llvm::to_vector<8>(attrs));
4248LogicalResult InsertStridedSliceOp::verify() {
4249 auto sourceVectorType = getSourceVectorType();
4250 auto destVectorType = getDestVectorType();
4251 auto offsets = getOffsetsAttr();
4252 auto strides = getStridesAttr();
4253 if (offsets.size() !=
static_cast<unsigned>(destVectorType.getRank()))
4255 "expected offsets of same size as destination vector rank");
4256 if (strides.size() !=
static_cast<unsigned>(sourceVectorType.getRank()))
4257 return emitOpError(
"expected strides of same size as source vector rank");
4258 if (sourceVectorType.getRank() > destVectorType.getRank())
4260 "expected source rank to be no greater than destination rank");
4262 auto sourceShape = sourceVectorType.getShape();
4263 auto destShape = destVectorType.getShape();
4264 SmallVector<int64_t, 4> sourceShapeAsDestShape(
4265 destShape.size() - sourceShape.size(), 0);
4266 sourceShapeAsDestShape.append(sourceShape.begin(), sourceShape.end());
4267 auto offName = InsertStridedSliceOp::getOffsetsAttrName();
4268 auto stridesName = InsertStridedSliceOp::getStridesAttrName();
4277 offName,
"source vector shape",
4281 unsigned rankDiff = destShape.size() - sourceShape.size();
4282 for (
unsigned idx = 0; idx < sourceShape.size(); ++idx) {
4283 if (sourceVectorType.getScalableDims()[idx] !=
4284 destVectorType.getScalableDims()[idx + rankDiff]) {
4285 return emitOpError(
"mismatching scalable flags (at source vector idx=")
4288 if (sourceVectorType.getScalableDims()[idx]) {
4289 auto sourceSize = sourceShape[idx];
4290 auto destSize = destShape[idx + rankDiff];
4291 if (sourceSize != destSize) {
4292 return emitOpError(
"expected size at idx=")
4294 << (
" to match the corresponding base size from the input "
4296 << sourceSize << (
" vs ") << destSize << (
")");
4306class FoldInsertStridedSliceSplat final
4307 :
public OpRewritePattern<InsertStridedSliceOp> {
4311 LogicalResult matchAndRewrite(InsertStridedSliceOp insertStridedSliceOp,
4312 PatternRewriter &rewriter)
const override {
4314 auto dst = insertStridedSliceOp.getDest();
4315 auto splat = getScalarSplatSource(insertStridedSliceOp.getValueToStore());
4316 if (!splat || getScalarSplatSource(dst) != splat)
4319 rewriter.
replaceOp(insertStridedSliceOp, dst);
4326class FoldInsertStridedSliceOfExtract final
4327 :
public OpRewritePattern<InsertStridedSliceOp> {
4331 LogicalResult matchAndRewrite(InsertStridedSliceOp insertStridedSliceOp,
4332 PatternRewriter &rewriter)
const override {
4333 auto extractStridedSliceOp =
4334 insertStridedSliceOp.getValueToStore()
4335 .getDefiningOp<vector::ExtractStridedSliceOp>();
4337 if (!extractStridedSliceOp)
4340 if (extractStridedSliceOp.getOperand() != insertStridedSliceOp.getDest())
4344 if (extractStridedSliceOp.getStrides() !=
4345 insertStridedSliceOp.getStrides() ||
4346 extractStridedSliceOp.getOffsets() != insertStridedSliceOp.getOffsets())
4349 rewriter.
replaceOp(insertStridedSliceOp, insertStridedSliceOp.getDest());
4356class InsertStridedSliceConstantFolder final
4357 :
public OpRewritePattern<InsertStridedSliceOp> {
4363 static constexpr int64_t vectorSizeFoldThreshold = 256;
4365 LogicalResult matchAndRewrite(InsertStridedSliceOp op,
4366 PatternRewriter &rewriter)
const override {
4370 Attribute vectorDestCst;
4374 VectorType destTy = destVector.getType();
4375 if (destTy.isScalable())
4379 if (destTy.getNumElements() > vectorSizeFoldThreshold &&
4380 !destVector.hasOneUse())
4384 Attribute sourceCst;
4394 if (op.hasNonUnitStrides())
4397 VectorType sliceVecTy = sourceValue.getType();
4398 ArrayRef<int64_t> sliceShape = sliceVecTy.getShape();
4399 int64_t rankDifference = destTy.getRank() - sliceVecTy.getRank();
4400 SmallVector<int64_t, 4> offsets =
getI64SubArray(op.getOffsets());
4401 SmallVector<int64_t, 4> destStrides =
computeStrides(destTy.getShape());
4409 auto denseDest = llvm::cast<DenseElementsAttr>(vectorDestCst);
4410 auto denseSlice = llvm::cast<DenseElementsAttr>(sourceCst);
4411 auto sliceValuesIt = denseSlice.value_begin<Attribute>();
4412 auto newValues = llvm::to_vector(denseDest.getValues<Attribute>());
4413 SmallVector<int64_t> currDestPosition(offsets.begin(), offsets.end());
4414 MutableArrayRef<int64_t> currSlicePosition(
4415 currDestPosition.begin() + rankDifference, currDestPosition.end());
4416 ArrayRef<int64_t> sliceOffsets(offsets.begin() + rankDifference,
4419 int64_t linearizedPosition =
linearize(currDestPosition, destStrides);
4420 assert(linearizedPosition < destTy.getNumElements() &&
"Invalid index");
4421 assert(sliceValuesIt != denseSlice.value_end<Attribute>() &&
4422 "Invalid slice element");
4423 newValues[linearizedPosition] = *sliceValuesIt;
4436void vector::InsertStridedSliceOp::getCanonicalizationPatterns(
4437 RewritePatternSet &results, MLIRContext *context) {
4438 results.
add<FoldInsertStridedSliceSplat, FoldInsertStridedSliceOfExtract,
4439 InsertStridedSliceConstantFolder>(context);
4442OpFoldResult InsertStridedSliceOp::fold(FoldAdaptor adaptor) {
4443 if (getSourceVectorType() == getDestVectorType())
4444 return getValueToStore();
4453void OuterProductOp::build(OpBuilder &builder, OperationState &
result,
4454 Value
lhs, Value
rhs, Value acc) {
4459void OuterProductOp::print(OpAsmPrinter &p) {
4460 p <<
" " << getLhs() <<
", " << getRhs();
4462 p <<
", " << getAcc();
4463 SmallVector<NamedAttribute> attrs((*this)->getDiscardableAttrs());
4464 attrs.emplace_back(getKindAttrName(), getKindAttr());
4468 p <<
" : " << getLhs().getType() <<
", " << getRhs().getType();
4471ParseResult OuterProductOp::parse(OpAsmParser &parser, OperationState &
result) {
4472 SmallVector<OpAsmParser::UnresolvedOperand, 3> operandsInfo;
4479 if (operandsInfo.size() < 2)
4481 "expected at least 2 operands");
4482 VectorType vLHS = llvm::dyn_cast<VectorType>(tLHS);
4483 VectorType vRHS = llvm::dyn_cast<VectorType>(tRHS);
4486 "expected vector type for operand #1");
4490 if (vLHS.getRank() == 0)
4492 "expected 1-d vector for operand #1");
4493 if (vRHS && vRHS.getRank() == 0)
4495 "expected 1-d vector for operand #2");
4499 SmallVector<bool> scalableDimsRes{vLHS.getScalableDims()[0],
4500 vRHS.getScalableDims()[0]};
4501 resType = VectorType::get({vLHS.getDimSize(0), vRHS.getDimSize(0)},
4502 vLHS.getElementType(), scalableDimsRes);
4505 SmallVector<bool> scalableDimsRes{vLHS.getScalableDims()[0]};
4506 resType = VectorType::get({vLHS.getDimSize(0)}, vLHS.getElementType(),
4510 if (!
result.attributes.get(OuterProductOp::getKindAttrName(
result.name))) {
4511 result.attributes.append(
4512 OuterProductOp::getKindAttrName(
result.name),
4513 CombiningKindAttr::get(
result.getContext(),
4514 OuterProductOp::getDefaultKind()));
4520 (operandsInfo.size() > 2 &&
4525LogicalResult OuterProductOp::verify() {
4526 Type tRHS = getOperandTypeRHS();
4527 VectorType vLHS = getOperandVectorTypeLHS(),
4528 vRHS = llvm::dyn_cast<VectorType>(tRHS),
4529 vACC = getOperandVectorTypeACC(), vRES = getResultVectorType();
4531 if (vLHS.getRank() != 1)
4532 return emitOpError(
"expected 1-d vector for operand #1");
4536 if (vRHS.getRank() != 1)
4537 return emitOpError(
"expected 1-d vector for operand #2");
4538 if (vRES.getRank() != 2)
4539 return emitOpError(
"expected 2-d vector result");
4540 if (vLHS.getDimSize(0) != vRES.getDimSize(0))
4541 return emitOpError(
"expected #1 operand dim to match result dim #1");
4542 if (vRHS.getDimSize(0) != vRES.getDimSize(1))
4543 return emitOpError(
"expected #2 operand dim to match result dim #2");
4544 if (vLHS.isScalable() && !vRHS.isScalable()) {
4548 "expected either both or only #2 operand dim to be scalable");
4552 if (vRES.getRank() != 1)
4553 return emitOpError(
"expected 1-d vector result");
4554 if (vLHS.getDimSize(0) != vRES.getDimSize(0))
4555 return emitOpError(
"expected #1 operand dim to match result dim #1");
4558 if (vACC && vACC != vRES)
4559 return emitOpError(
"expected operand #3 of same type as result type");
4561 if (!getKindAttr()) {
4562 return emitOpError(
"expected 'kind' attribute of type CombiningKind (e.g. "
4563 "'vector.kind<add>')");
4568 return emitOpError(
"unsupported outerproduct type");
4577Type OuterProductOp::getExpectedMaskType() {
4578 auto vecType = this->getResultVectorType();
4579 return VectorType::get(vecType.getShape(),
4580 IntegerType::get(vecType.getContext(), 1),
4581 vecType.getScalableDims());
4595 assert(offsets.size() == sizes.size() && offsets.size() == strides.size());
4597 shape.reserve(vectorType.getRank());
4599 for (
unsigned e = offsets.size(); idx < e; ++idx)
4600 shape.push_back(llvm::cast<IntegerAttr>(sizes[idx]).getInt());
4601 for (
unsigned e = vectorType.getShape().size(); idx < e; ++idx)
4602 shape.push_back(vectorType.getShape()[idx]);
4604 return VectorType::get(
shape, vectorType.getElementType(),
4605 vectorType.getScalableDims());
4608void ExtractStridedSliceOp::build(OpBuilder &builder, OperationState &
result,
4609 Value source, ArrayRef<int64_t> offsets,
4610 ArrayRef<int64_t> sizes,
4611 ArrayRef<int64_t> strides) {
4612 result.addOperands(source);
4618 offsetsAttr, sizesAttr, stridesAttr));
4619 result.addAttribute(ExtractStridedSliceOp::getOffsetsAttrName(
result.name),
4621 result.addAttribute(ExtractStridedSliceOp::getSizesAttrName(
result.name),
4623 result.addAttribute(ExtractStridedSliceOp::getStridesAttrName(
result.name),
4627LogicalResult ExtractStridedSliceOp::verify() {
4628 auto type = getSourceVectorType();
4629 auto offsets = getOffsetsAttr();
4630 auto sizes = getSizesAttr();
4631 auto strides = getStridesAttr();
4632 if (offsets.size() != sizes.size() || offsets.size() != strides.size())
4634 "expected offsets, sizes and strides attributes of same size");
4636 auto shape = type.getShape();
4637 auto offName = getOffsetsAttrName();
4638 auto sizesName = getSizesAttrName();
4639 auto stridesName = getStridesAttrName();
4655 shape, offName, sizesName,
4660 offsets, sizes, strides);
4661 if (getResult().
getType() != resultType)
4662 return emitOpError(
"expected result type to be ") << resultType;
4664 for (
unsigned idx = 0; idx < sizes.size(); ++idx) {
4665 if (type.getScalableDims()[idx]) {
4666 auto inputDim = type.getShape()[idx];
4667 auto inputSize = llvm::cast<IntegerAttr>(sizes[idx]).getInt();
4668 if (inputDim != inputSize)
4669 return emitOpError(
"expected size at idx=")
4671 << (
" to match the corresponding base size from the input "
4673 << inputSize << (
" vs ") << inputDim << (
")");
4686 auto getElement = [](
ArrayAttr array,
int idx) {
4687 return llvm::cast<IntegerAttr>(array[idx]).getInt();
4689 ArrayAttr extractOffsets = op.getOffsets();
4692 auto insertOp = op.getSource().getDefiningOp<InsertStridedSliceOp>();
4694 if (op.getSourceVectorType().getRank() !=
4695 insertOp.getSourceVectorType().getRank())
4697 ArrayAttr insertOffsets = insertOp.getOffsets();
4698 ArrayAttr insertStrides = insertOp.getStrides();
4701 if (extractOffsets.size() > insertOffsets.size())
4703 bool patialoverlap =
false;
4704 bool disjoint =
false;
4706 for (
unsigned dim = 0, e = extractOffsets.size(); dim < e; ++dim) {
4707 if (getElement(
extractStrides, dim) != getElement(insertStrides, dim))
4709 int64_t start = getElement(insertOffsets, dim);
4710 int64_t end = start + insertOp.getSourceVectorType().getDimSize(dim);
4711 int64_t offset = getElement(extractOffsets, dim);
4712 int64_t size = getElement(extractSizes, dim);
4714 if (start <= offset && offset < end) {
4717 if (offset + size > end)
4718 patialoverlap =
true;
4719 offsetDiffs.push_back(offset - start);
4726 if (!disjoint && !patialoverlap) {
4727 op.setOperand(insertOp.getValueToStore());
4730 op.setOffsetsAttr(
b.getI64ArrayAttr(offsetDiffs));
4736 insertOp = insertOp.getDest().getDefiningOp<InsertStridedSliceOp>();
4751 auto dense = llvm::dyn_cast_if_present<DenseElementsAttr>(foldInput);
4756 if (op.hasNonUnitStrides())
4759 VectorType sourceVecTy = op.getSourceVectorType();
4763 VectorType sliceVecTy = op.getType();
4765 int64_t rank = sliceVecTy.getRank();
4777 const auto denseValuesBegin = dense.value_begin<
Attribute>();
4779 sliceValues.reserve(sliceVecTy.getNumElements());
4783 assert(linearizedPosition < sourceVecTy.getNumElements() &&
4785 sliceValues.push_back(*(denseValuesBegin + linearizedPosition));
4786 }
while (succeeded(
incSlicePosition(currSlicePosition, sliceShape, offsets)));
4788 assert(
static_cast<int64_t>(sliceValues.size()) ==
4789 sliceVecTy.getNumElements() &&
4790 "Invalid number of slice elements");
4794OpFoldResult ExtractStridedSliceOp::fold(FoldAdaptor adaptor) {
4795 if (getSourceVectorType() == getResult().
getType())
4802 llvm::dyn_cast_if_present<SplatElementsAttr>(adaptor.getSource()))
4809void ExtractStridedSliceOp::getOffsets(SmallVectorImpl<int64_t> &results) {
4831class StridedSliceFolder final
4832 :
public OpRewritePattern<ExtractStridedSliceOp> {
4834 using OpRewritePattern<ExtractStridedSliceOp>::OpRewritePattern;
4836 LogicalResult matchAndRewrite(ExtractStridedSliceOp secondOp,
4837 PatternRewriter &rewriter)
const override {
4838 auto firstOp = secondOp.getSource().getDefiningOp<ExtractStridedSliceOp>();
4842 if (secondOp.hasNonUnitStrides() || firstOp.hasNonUnitStrides())
4845 SmallVector<int64_t> firstOffsets =
getI64SubArray(firstOp.getOffsets());
4846 SmallVector<int64_t> firstSizes =
getI64SubArray(firstOp.getSizes());
4847 SmallVector<int64_t> secondOffsets =
getI64SubArray(secondOp.getOffsets());
4848 SmallVector<int64_t> secondSizes =
getI64SubArray(secondOp.getSizes());
4850 unsigned newRank = std::max(firstOffsets.size(), secondOffsets.size());
4851 SmallVector<int64_t> combinedOffsets(newRank, 0);
4852 SmallVector<int64_t> combinedSizes(newRank);
4853 ArrayRef<int64_t> firstSourceShape =
4854 firstOp.getSourceVectorType().getShape();
4855 for (
unsigned i = 0; i < newRank; ++i) {
4856 int64_t off1 = (i < firstOffsets.size()) ? firstOffsets[i] : 0;
4857 int64_t off2 = (i < secondOffsets.size()) ? secondOffsets[i] : 0;
4858 combinedOffsets[i] = off1 + off2;
4860 if (i < secondSizes.size()) {
4861 combinedSizes[i] = secondSizes[i];
4862 }
else if (i < firstSizes.size()) {
4863 combinedSizes[i] = firstSizes[i];
4865 combinedSizes[i] = firstSourceShape[i];
4869 SmallVector<int64_t> combinedStrides(newRank, 1);
4871 secondOp, firstOp.getSource(), combinedOffsets, combinedSizes,
4889class StridedSliceCreateMaskFolder final
4890 :
public OpRewritePattern<ExtractStridedSliceOp> {
4894 LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp,
4895 PatternRewriter &rewriter)
const override {
4896 Location loc = extractStridedSliceOp.getLoc();
4900 extractStridedSliceOp.getSource().getDefiningOp<CreateMaskOp>();
4904 if (extractStridedSliceOp.hasNonUnitStrides())
4907 SmallVector<Value> maskDimSizes(createMaskOp.getOperands());
4909 SmallVector<int64_t> sliceOffsets;
4912 SmallVector<int64_t> sliceSizes;
4916 SmallVector<Value> sliceMaskDimSizes;
4917 sliceMaskDimSizes.reserve(maskDimSizes.size());
4921 for (
auto [maskDimSize, sliceOffset, sliceSize] :
4922 llvm::zip(maskDimSizes, sliceOffsets, sliceSizes)) {
4926 IntegerAttr offsetAttr =
4928 Value offset = arith::ConstantOp::create(rewriter, loc, offsetAttr);
4929 Value sliceMaskDimSize =
4930 arith::SubIOp::create(rewriter, loc, maskDimSize, offset);
4931 sliceMaskDimSizes.push_back(sliceMaskDimSize);
4936 llvm::drop_begin(maskDimSizes, sliceMaskDimSizes.size()));
4940 extractStridedSliceOp, extractStridedSliceOp.getResult().
getType(),
4948class StridedSliceConstantMaskFolder final
4949 :
public OpRewritePattern<ExtractStridedSliceOp> {
4953 LogicalResult matchAndRewrite(ExtractStridedSliceOp extractStridedSliceOp,
4954 PatternRewriter &rewriter)
const override {
4957 auto *defOp = extractStridedSliceOp.getSource().getDefiningOp();
4958 auto constantMaskOp = dyn_cast_or_null<ConstantMaskOp>(defOp);
4959 if (!constantMaskOp)
4962 if (extractStridedSliceOp.hasNonUnitStrides())
4965 ArrayRef<int64_t> maskDimSizes = constantMaskOp.getMaskDimSizes();
4967 SmallVector<int64_t> sliceOffsets;
4970 SmallVector<int64_t> sliceSizes;
4974 SmallVector<int64_t> sliceMaskDimSizes;
4975 sliceMaskDimSizes.reserve(maskDimSizes.size());
4976 for (
auto [maskDimSize, sliceOffset, sliceSize] :
4977 llvm::zip(maskDimSizes, sliceOffsets, sliceSizes)) {
4978 int64_t sliceMaskDimSize = std::max(
4979 static_cast<int64_t
>(0),
4980 std::min(sliceOffset + sliceSize, maskDimSize) - sliceOffset);
4981 sliceMaskDimSizes.push_back(sliceMaskDimSize);
4984 if (sliceMaskDimSizes.size() < maskDimSizes.size())
4985 for (
size_t i = sliceMaskDimSizes.size(); i < maskDimSizes.size(); ++i)
4986 sliceMaskDimSizes.push_back(maskDimSizes[i]);
4989 if (llvm::is_contained(sliceMaskDimSizes, 0))
4990 sliceMaskDimSizes.assign(maskDimSizes.size(), 0);
4995 extractStridedSliceOp, extractStridedSliceOp.getResult().
getType(),
5003class StridedSliceBroadcast final
5004 :
public OpRewritePattern<ExtractStridedSliceOp> {
5008 LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
5009 PatternRewriter &rewriter)
const override {
5015 unsigned srcRank = srcVecType ? srcVecType.getRank() : 0;
5016 auto dstVecType = llvm::cast<VectorType>(op.getType());
5017 unsigned dstRank = dstVecType.getRank();
5018 unsigned rankDiff = dstRank - srcRank;
5022 bool needsSlice =
false;
5023 for (
unsigned i = 0; i < srcRank; i++) {
5024 if (srcVecType.getDimSize(i) != 1 &&
5025 srcVecType.getDimSize(i) != dstVecType.getDimSize(i + rankDiff)) {
5032 SmallVector<int64_t> offsets =
5034 SmallVector<int64_t> sizes =
5039 for (
unsigned i = 0; i < offsets.size(); i++) {
5040 if (srcVecType.getDimSize(i) == 1) {
5048 source = ExtractStridedSliceOp::create(
5049 rewriter, op->getLoc(), source, offsets, sizes,
5058class StridedSliceSplat final :
public OpRewritePattern<ExtractStridedSliceOp> {
5062 LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
5063 PatternRewriter &rewriter)
const override {
5065 Value splat = getScalarSplatSource(op.getSource());
5089class ContiguousExtractStridedSliceToExtract final
5090 :
public OpRewritePattern<ExtractStridedSliceOp> {
5094 LogicalResult matchAndRewrite(ExtractStridedSliceOp op,
5095 PatternRewriter &rewriter)
const override {
5096 if (op.hasNonUnitStrides())
5098 Value source = op.getOperand();
5099 auto sourceType = cast<VectorType>(source.
getType());
5100 if (sourceType.isScalable() || sourceType.getRank() == 0)
5109 for (numOffsets = sizes.size(); numOffsets > 0; --numOffsets) {
5110 if (sizes[numOffsets - 1] != sourceType.getDimSize(numOffsets - 1))
5117 if (numOffsets == 0)
5122 if (numOffsets == sourceType.getRank() &&
5123 static_cast<int>(sizes.size()) == sourceType.getRank())
5127 for (
int i = 0; i < numOffsets; ++i) {
5135 while (numOffsets <
static_cast<int>(sizes.size()) - 1 &&
5136 sizes[numOffsets] == 1) {
5141 auto extractOffsets = ArrayRef(offsets).take_front(numOffsets);
5142 Value extract = vector::ExtractOp::create(rewriter, op->getLoc(), source,
5151void ExtractStridedSliceOp::getCanonicalizationPatterns(
5152 RewritePatternSet &results, MLIRContext *context) {
5155 results.
add<StridedSliceFolder, StridedSliceCreateMaskFolder,
5156 StridedSliceConstantMaskFolder, StridedSliceBroadcast,
5157 StridedSliceSplat, ContiguousExtractStridedSliceToExtract>(
5167void TransferReadOp::build(OpBuilder &builder, OperationState &
result,
5168 VectorType vectorType, Value source,
5170 AffineMapAttr permutationMapAttr,
5173 Type elemType = llvm::cast<ShapedType>(source.
getType()).getElementType();
5175 padding = ub::PoisonOp::create(builder,
result.location, elemType);
5178 build(builder,
result, vectorType, source,
indices, permutationMapAttr,
5179 *padding, Value(), inBoundsAttr);
5187void TransferReadOp::build(OpBuilder &builder, OperationState &
result,
5188 VectorType vectorType, Value source,
5190 AffineMap permutationMap,
5191 std::optional<ArrayRef<bool>> inBounds) {
5192 if (!permutationMap)
5194 llvm::cast<ShapedType>(source.
getType()), vectorType);
5195 auto permutationMapAttr = AffineMapAttr::get(permutationMap);
5196 auto inBoundsAttr = (inBounds && !inBounds.value().empty())
5199 SmallVector<bool>(vectorType.getRank(),
false));
5201 build(builder,
result, vectorType, source,
indices, padding,
5202 permutationMapAttr, inBoundsAttr);
5208void TransferReadOp::build(OpBuilder &builder, OperationState &
result,
5209 VectorType vectorType, Value source,
5211 std::optional<ArrayRef<bool>> inBounds) {
5213 build(builder,
result, vectorType, source,
indices, padding,
5214 AffineMap(), inBounds);
5217template <
typename EmitFun>
5219 EmitFun emitOpError) {
5221 for (
auto expr : permutationMap.
getResults()) {
5222 auto dim = dyn_cast<AffineDimExpr>(expr);
5223 auto zero = dyn_cast<AffineConstantExpr>(expr);
5225 if (zero.getValue() != 0) {
5227 "requires a projected permutation_map (at most one dim or the zero "
5228 "constant can appear in each result)");
5233 return emitOpError(
"requires a projected permutation_map (at most one "
5234 "dim or the zero constant can appear in each result)");
5236 if (seen[dim.getPosition()]) {
5238 "requires a permutation_map that is a permutation (found one dim "
5239 "used more than once)");
5241 seen[dim.getPosition()] =
true;
5248 VectorType vectorType, VectorType maskType,
5249 VectorType inferredMaskType,
AffineMap permutationMap,
5251 if (op->hasDiscardableAttr(
"masked")) {
5252 return op->emitOpError(
"masked attribute has been removed. "
5253 "Use in_bounds instead.");
5256 if (!llvm::isa<MemRefType, RankedTensorType>(shapedType))
5257 return op->emitOpError(
5258 "requires source to be a memref or ranked tensor type");
5260 auto elementType = shapedType.getElementType();
5262 if (
auto vectorElementType = llvm::dyn_cast<VectorType>(elementType)) {
5264 unsigned sourceVecSize =
5266 vectorElementType.getShape().back();
5267 unsigned resultVecSize =
5269 vectorType.getShape().back();
5270 if (resultVecSize % sourceVecSize != 0)
5271 return op->emitOpError(
5272 "requires the bitwidth of the minor 1-D vector to be an integral "
5273 "multiple of the bitwidth of the minor 1-D vector of the source");
5275 unsigned sourceVecEltRank = vectorElementType.getRank();
5276 unsigned resultVecRank = vectorType.getRank();
5277 if (sourceVecEltRank > resultVecRank)
5278 return op->emitOpError(
5279 "requires source vector element and vector result ranks to match.");
5280 unsigned rankOffset = resultVecRank - sourceVecEltRank;
5283 return op->emitOpError(
"requires a permutation_map with result dims of "
5284 "the same rank as the vector type");
5287 return op->emitOpError(
"does not support masks with vector element type");
5290 unsigned minorSize =
5291 vectorType.getRank() == 0 ? 1 : vectorType.getShape().back();
5292 unsigned resultVecSize =
5295 return op->emitOpError(
5296 "requires the bitwidth of the minor 1-D vector to be an integral "
5297 "multiple of the bitwidth of the source element type");
5301 return op->emitOpError(
"requires a permutation_map with result dims of "
5302 "the same rank as the vector type");
5306 return op->emitOpError(
"requires permutation_map without symbols");
5308 if (permutationMap.
getNumInputs() != shapedType.getRank())
5309 return op->emitOpError(
"requires a permutation_map with input dims of the "
5310 "same rank as the source type");
5312 if (maskType && maskType != inferredMaskType)
5313 return op->emitOpError(
"inferred mask type (")
5314 << inferredMaskType <<
") and mask operand type (" << maskType
5318 return op->emitOpError(
"expects the in_bounds attr of same rank "
5319 "as permutation_map results: ")
5320 << AffineMapAttr::get(permutationMap)
5321 <<
" vs inBounds of size: " << inBounds.size();
5329 if (llvm::any_of(op.getInBoundsValues(), [](
bool b) { return b; }))
5330 attrs.emplace_back(op.getInBoundsAttrName(), op.getInBounds());
5331 if (!op.getPermutationMap().isMinorIdentity())
5332 attrs.emplace_back(op.getPermutationMapAttrName(),
5333 AffineMapAttr::get(op.getPermutationMap()));
5338void TransferReadOp::print(OpAsmPrinter &p) {
5341 p <<
", " << getMask();
5348 auto i1Type = IntegerType::get(permMap.
getContext(), 1);
5350 assert(invPermMap &&
"Inversed permutation map couldn't be computed");
5355 if (maskShape.empty())
5356 maskShape.push_back(1);
5361 return VectorType::get(maskShape, i1Type, scalableDims);
5378 if (hasMask.succeeded()) {
5385 if (types.size() != 2)
5386 return parser.
emitError(typesLoc,
"requires two types");
5388 auto shapedType = llvm::dyn_cast<ShapedType>(types[0]);
5389 if (!shapedType || !llvm::isa<MemRefType, RankedTensorType>(shapedType))
5390 return parser.
emitError(typesLoc,
"requires memref or ranked tensor type");
5391 VectorType vectorType = llvm::dyn_cast<VectorType>(types[1]);
5393 return parser.
emitError(typesLoc,
"requires vector type");
5394 auto permMapAttrName = TransferReadOp::getPermutationMapAttrName(
result.name);
5398 if (shapedType.getRank() <
5401 "expected a custom permutation_map when "
5402 "rank(source) != rank(destination)");
5404 result.attributes.set(permMapAttrName, AffineMapAttr::get(permMap));
5406 permMap = llvm::cast<AffineMapAttr>(permMapAttr).getValue();
5408 auto inBoundsAttrName = TransferReadOp::getInBoundsAttrName(
result.name);
5409 Attribute inBoundsAttr =
result.attributes.get(inBoundsAttrName);
5410 if (!inBoundsAttr) {
5411 result.addAttribute(inBoundsAttrName,
5420 if (hasMask.succeeded()) {
5421 if (llvm::dyn_cast<VectorType>(shapedType.getElementType()))
5423 maskInfo.
location,
"does not support masks with vector element type");
5426 "expected the same rank for the vector and the "
5427 "results of the permutation map");
5435 result.addAttribute(TransferReadOp::getOperandSegmentSizeAttr(),
5437 {1, static_cast<int32_t>(indexInfo.size()), 1,
5438 static_cast<int32_t>(hasMask.succeeded())}));
5442LogicalResult TransferReadOp::verify() {
5444 ShapedType shapedType = getShapedType();
5446 VectorType maskType = getMaskType();
5447 auto paddingType = getPadding().getType();
5448 auto permutationMap = getPermutationMap();
5449 VectorType inferredMaskType =
5452 auto sourceElementType = shapedType.getElementType();
5454 if (
static_cast<int64_t
>(
getIndices().size()) != shapedType.getRank())
5455 return emitOpError(
"requires ") << shapedType.getRank() <<
" indices";
5458 shapedType, vectorType, maskType,
5459 inferredMaskType, permutationMap, getInBounds())))
5462 if (
auto sourceVectorElementType =
5463 llvm::dyn_cast<VectorType>(sourceElementType)) {
5466 if (sourceVectorElementType != paddingType)
5468 "requires source element type and padding type to match.");
5472 if (!VectorType::isValidElementType(paddingType))
5473 return emitOpError(
"requires valid padding vector elemental type");
5476 if (paddingType != sourceElementType)
5478 "requires formal padding and source of the same elemental type");
5482 [&](Twine t) {
return emitOpError(t); });
5489Type TransferReadOp::getExpectedMaskType() {
5496VectorType TransferReadOp::getVectorType() {
return getResult().getType(); }
5498Value TransferReadOp::getVector() {
return getResult(); }
5500template <
typename TransferOp>
5504 if (op.getShapedType().isDynamicDim(indicesIdx))
5508 if (op.getVectorType().getScalableDims()[resultIdx])
5512 if (!cstOp.has_value())
5515 int64_t sourceSize = op.getShapedType().getDimSize(indicesIdx);
5516 int64_t vectorSize = op.getVectorType().getDimSize(resultIdx);
5522 int64_t maxStart = sourceSize - vectorSize;
5526 return *cstOp >= 0 && *cstOp <= maxStart;
5529template <
typename TransferOp>
5533 if (op.getTransferRank() == 0)
5536 bool changed =
false;
5538 newInBounds.reserve(op.getTransferRank());
5543 for (
unsigned i = 0; i < op.getTransferRank(); ++i) {
5545 if (op.isDimInBounds(i)) {
5546 newInBounds.push_back(
true);
5551 bool inBounds =
false;
5552 auto dimExpr = dyn_cast<AffineDimExpr>(permutationMap.
getResult(i));
5555 dimExpr.getPosition());
5556 nonBcastDims.push_back(i);
5559 newInBounds.push_back(inBounds);
5561 changed |= inBounds;
5567 bool allNonBcastDimsInBounds = llvm::all_of(
5568 nonBcastDims, [&newInBounds](
unsigned idx) {
return newInBounds[idx]; });
5569 if (allNonBcastDimsInBounds) {
5571 changed |= !newInBounds[idx];
5572 newInBounds[idx] =
true;
5580 op.setInBoundsAttr(
b.getBoolArrayAttr(newInBounds));
5584template <
typename TransferOp>
5586 auto mask = op.getMask();
5593 op.getMaskMutable().clear();
5601template <
typename TransferOp>
5603 VectorType vecType = op.getVectorType();
5604 if (vecType.getRank() != 1 || vecType.getShape()[0] != 1 ||
5605 vecType.isScalable())
5612 int64_t srcRank = op.getShapedType().getRank();
5618 op.setPermutationMapAttr(AffineMapAttr::get(minorIdentity));
5632static Value foldRAW(TransferReadOp readOp) {
5633 if (!llvm::isa<RankedTensorType>(readOp.getShapedType()))
5635 auto defWrite = readOp.getBase().getDefiningOp<vector::TransferWriteOp>();
5638 return defWrite.getVector();
5640 cast<VectorTransferOpInterface>(defWrite.getOperation()),
5641 cast<VectorTransferOpInterface>(readOp.getOperation())))
5643 defWrite = defWrite.getBase().getDefiningOp<vector::TransferWriteOp>();
5648OpFoldResult TransferReadOp::fold(FoldAdaptor) {
5649 if (Value vec = foldRAW(*
this))
5662 return OpFoldResult();
5668std::optional<SmallVector<int64_t, 4>>
5669TransferReadOp::getIterationShapeToUnroll() {
5673void TransferReadOp::getEffects(
5674 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
5676 if (llvm::isa<MemRefType>(getShapedType()))
5677 effects.emplace_back(MemoryEffects::Read::get(), &getBaseMutable(),
5678 SideEffects::DefaultResource::get());
5682 if (hasPureTensorSemantics())
5689static AffineMap inverseWithUnusedDims(AffineMap map) {
5691 "expected a projected permutation map");
5696 int64_t pos = cast<AffineDimExpr>(
result).getPosition();
5726struct TransferReadAfterWriteToBroadcast
5727 :
public OpRewritePattern<TransferReadOp> {
5730 LogicalResult matchAndRewrite(TransferReadOp readOp,
5731 PatternRewriter &rewriter)
const override {
5732 auto defWrite = readOp.getBase().getDefiningOp<vector::TransferWriteOp>();
5736 if (!readOp.hasPureTensorSemantics() || !defWrite.hasPureTensorSemantics())
5742 if (readOp.getMask() || defWrite.getMask() || readOp.isMasked())
5745 if (readOp.getIndices() != defWrite.getIndices())
5748 if (readOp.hasOutOfBoundsDim() || defWrite.hasOutOfBoundsDim())
5752 if (readOp.getTransferChunkAccessed() !=
5753 defWrite.getTransferChunkAccessed())
5760 AffineMap readMap = readOp.getPermutationMap();
5761 AffineMap writeMap = defWrite.getPermutationMap();
5762 AffineMap invWriteMap = inverseWithUnusedDims(writeMap);
5763 AffineMap composedMap = readMap.
compose(invWriteMap);
5777 int64_t numBroadcastedDims = broadcastedDims.size();
5778 auto invPerm = llvm::to_vector_of<int64_t>(broadcastedDims);
5780 for (
auto [idx, expr] : llvm::enumerate(composedMap.
getResults())) {
5781 if (
auto dim = dyn_cast<AffineDimExpr>(expr)) {
5782 int64_t effectiveDim = dim.getPosition() + numBroadcastedDims;
5783 invPerm[effectiveDim] = idx;
5788 VectorType readVecTy = readOp.getVectorType();
5790 auto broadcastedVecTy =
5792 readVecTy.getElementType(),
5795 Value vec = defWrite.getVector();
5796 Location loc = readOp.getLoc();
5797 vec = vector::BroadcastOp::create(rewriter, loc, broadcastedVecTy, vec);
5804void TransferReadOp::getCanonicalizationPatterns(RewritePatternSet &results,
5805 MLIRContext *context) {
5806 results.
add<TransferReadAfterWriteToBroadcast>(context);
5809FailureOr<std::optional<SmallVector<Value>>>
5810TransferReadOp::bubbleDownCasts(OpBuilder &builder) {
5811 if (!hasPureBufferSemantics())
5822void TransferWriteOp::build(OpBuilder &builder, OperationState &
result,
5824 AffineMapAttr permutationMapAttr,
5827 Type resultType = llvm::dyn_cast<RankedTensorType>(dest.
getType());
5828 build(builder,
result, resultType, vector, dest,
indices, permutationMapAttr,
5829 mask, inBoundsAttr);
5833void TransferWriteOp::build(OpBuilder &builder, OperationState &
result,
5835 AffineMapAttr permutationMapAttr,
5837 build(builder,
result, vector, dest,
indices, permutationMapAttr,
5838 Value(), inBoundsAttr);
5843void TransferWriteOp::build(OpBuilder &builder, OperationState &
result,
5845 AffineMap permutationMap,
5846 std::optional<ArrayRef<bool>> inBounds) {
5847 if (!permutationMap)
5850 llvm::cast<VectorType>(vector.
getType()));
5851 auto permutationMapAttr = AffineMapAttr::get(permutationMap);
5853 (inBounds && !inBounds.value().empty())
5856 llvm::cast<VectorType>(vector.
getType()).getRank(),
false));
5857 build(builder,
result, vector, dest,
indices, permutationMapAttr,
5858 Value(), inBoundsAttr);
5863void TransferWriteOp::build(OpBuilder &builder, OperationState &
result,
5865 std::optional<ArrayRef<bool>> inBounds) {
5870ParseResult TransferWriteOp::parse(OpAsmParser &parser,
5871 OperationState &
result) {
5874 OpAsmParser::UnresolvedOperand vectorInfo, sourceInfo;
5875 SmallVector<OpAsmParser::UnresolvedOperand, 8> indexInfo;
5876 SmallVector<Type, 2> types;
5877 OpAsmParser::UnresolvedOperand maskInfo;
5883 if (hasMask.succeeded() && parser.
parseOperand(maskInfo))
5888 if (types.size() != 2)
5889 return parser.
emitError(typesLoc,
"requires two types");
5891 VectorType vectorType = llvm::dyn_cast<VectorType>(types[0]);
5893 return parser.
emitError(typesLoc,
"requires vector type");
5894 ShapedType shapedType = llvm::dyn_cast<ShapedType>(types[1]);
5895 if (!shapedType || !llvm::isa<MemRefType, RankedTensorType>(shapedType))
5896 return parser.
emitError(typesLoc,
"requires memref or ranked tensor type");
5897 auto permMapAttrName =
5898 TransferWriteOp::getPermutationMapAttrName(
result.name);
5899 auto permMapAttr =
result.attributes.get(permMapAttrName);
5902 if (shapedType.getRank() <
5905 "expected a custom permutation_map when "
5906 "rank(source) != rank(destination)");
5908 result.attributes.set(permMapAttrName, AffineMapAttr::get(permMap));
5910 permMap = llvm::cast<AffineMapAttr>(permMapAttr).getValue();
5912 auto inBoundsAttrName = TransferWriteOp::getInBoundsAttrName(
result.name);
5913 Attribute inBoundsAttr =
result.attributes.get(inBoundsAttrName);
5914 if (!inBoundsAttr) {
5915 result.addAttribute(inBoundsAttrName,
5923 if (hasMask.succeeded()) {
5924 if (llvm::dyn_cast<VectorType>(shapedType.getElementType()))
5926 maskInfo.
location,
"does not support masks with vector element type");
5929 "expected the same rank for the vector and the "
5930 "results of the permutation map");
5936 result.addAttribute(TransferWriteOp::getOperandSegmentSizeAttr(),
5938 {1, 1, static_cast<int32_t>(indexInfo.size()),
5939 static_cast<int32_t>(hasMask.succeeded())}));
5940 return failure(llvm::isa<RankedTensorType>(shapedType) &&
5944void TransferWriteOp::print(OpAsmPrinter &p) {
5947 p <<
", " << getMask();
5952LogicalResult TransferWriteOp::verify() {
5954 ShapedType shapedType = getShapedType();
5956 VectorType maskType = getMaskType();
5957 auto permutationMap = getPermutationMap();
5958 VectorType inferredMaskType =
5962 if (llvm::size(
getIndices()) != shapedType.getRank())
5963 return emitOpError(
"requires ") << shapedType.getRank() <<
" indices";
5967 if (hasBroadcastDim())
5968 return emitOpError(
"should not have broadcast dimensions");
5971 shapedType, vectorType, maskType,
5972 inferredMaskType, permutationMap, getInBounds())))
5976 [&](Twine t) {
return emitOpError(t); });
5985Type TransferWriteOp::getExpectedMaskType() {
5992Value TransferWriteOp::getVector() {
return getOperand(0); }
5993VectorType TransferWriteOp::getVectorType() {
5994 return cast<VectorType>(getValueToStore().
getType());
6017static LogicalResult foldReadInitWrite(TransferWriteOp write,
6018 ArrayRef<Attribute>,
6019 SmallVectorImpl<OpFoldResult> &results) {
6021 if (write.getTransferRank() == 0)
6023 auto rankedTensorType =
6024 llvm::dyn_cast<RankedTensorType>(write.getBase().getType());
6026 if (!rankedTensorType)
6029 auto read = write.getVector().getDefiningOp<vector::TransferReadOp>();
6033 if (read.getTransferRank() == 0)
6036 if (!read.getPermutationMap().isMinorIdentity() ||
6037 !write.getPermutationMap().isMinorIdentity())
6040 if (read.getTransferRank() != write.getTransferRank())
6043 if (read.hasOutOfBoundsDim() || write.hasOutOfBoundsDim())
6047 if (read.getMask() || write.getMask() || write.isMasked())
6050 if (read.getBase().getType() != rankedTensorType)
6053 if (read.getVectorType() != write.getVectorType())
6056 if (read.getVectorType().getShape() != rankedTensorType.getShape())
6059 auto isNotConstantZero = [](Value v) {
6061 return !cstOp.has_value() || cstOp.value() != 0;
6063 if (llvm::any_of(read.getIndices(), isNotConstantZero) ||
6064 llvm::any_of(write.getIndices(), isNotConstantZero))
6067 results.push_back(read.getBase());
6071static bool checkSameValueWAR(vector::TransferReadOp read,
6072 vector::TransferWriteOp write) {
6073 return read.getBase() == write.getBase() &&
6074 read.getIndices() == write.getIndices() &&
6075 read.getPermutationMap() == write.getPermutationMap() &&
6076 read.getVectorType() == write.getVectorType() && !read.getMask() &&
6093static LogicalResult foldWAR(TransferWriteOp write,
6094 SmallVectorImpl<OpFoldResult> &results) {
6095 if (!llvm::isa<RankedTensorType>(write.getBase().getType()))
6097 auto read = write.getVector().getDefiningOp<vector::TransferReadOp>();
6101 if (!checkSameValueWAR(read, write))
6103 results.push_back(read.getBase());
6107LogicalResult TransferWriteOp::fold(FoldAdaptor adaptor,
6108 SmallVectorImpl<OpFoldResult> &results) {
6109 if (succeeded(foldReadInitWrite(*
this, adaptor.getOperands(), results)))
6111 if (succeeded(foldWAR(*
this, results)))
6125std::optional<SmallVector<int64_t, 4>>
6126TransferWriteOp::getIterationShapeToUnroll() {
6130void TransferWriteOp::getEffects(
6131 SmallVectorImpl<SideEffects::EffectInstance<MemoryEffects::Effect>>
6133 if (llvm::isa<MemRefType>(getShapedType()))
6134 effects.emplace_back(MemoryEffects::Write::get(), &getBaseMutable(),
6135 SideEffects::DefaultResource::get());
6139 if (hasPureTensorSemantics())
6169class FoldWaw final :
public OpRewritePattern<TransferWriteOp> {
6172 LogicalResult matchAndRewrite(TransferWriteOp writeOp,
6173 PatternRewriter &rewriter)
const override {
6174 if (!llvm::isa<RankedTensorType>(writeOp.getShapedType()))
6176 vector::TransferWriteOp writeToModify = writeOp;
6178 auto defWrite = writeOp.getBase().getDefiningOp<vector::TransferWriteOp>();
6182 writeToModify.getBaseMutable().assign(defWrite.getBase());
6187 cast<VectorTransferOpInterface>(defWrite.getOperation()),
6188 cast<VectorTransferOpInterface>(writeOp.getOperation())))
6192 if (!defWrite->hasOneUse())
6194 writeToModify = defWrite;
6195 defWrite = defWrite.getBase().getDefiningOp<vector::TransferWriteOp>();
6224struct SwapExtractSliceOfTransferWrite
6225 :
public OpRewritePattern<tensor::InsertSliceOp> {
6229 LogicalResult matchAndRewrite(tensor::InsertSliceOp insertOp,
6230 PatternRewriter &rewriter)
const override {
6231 if (!insertOp.hasUnitStride())
6234 insertOp.getSource().getDefiningOp<tensor::ExtractSliceOp>();
6235 if (!extractOp || !extractOp.hasUnitStride() || !extractOp->hasOneUse())
6237 auto transferOp = extractOp.getSource().getDefiningOp<TransferWriteOp>();
6238 if (!transferOp || !transferOp->hasOneUse())
6243 if (insertOp.getSourceType().getRank() != transferOp.getTransferRank()) {
6245 "use-def chain is rank-reducing");
6249 if (!extractOp.hasZeroOffset()) {
6251 "ExtractSliceOp has non-zero offset");
6255 if (!llvm::all_of(transferOp.getIndices(), [](Value value) {
6256 return getConstantIntValue(value) == static_cast<int64_t>(0);
6259 "TranferWriteOp has non-zero offset");
6263 if (insertOp.getMixedSizes().size() != extractOp.getMixedSizes().size()) {
6265 insertOp,
"InsertSliceOp and ExtractSliceOp ranks differ");
6268 for (
auto [insertSize, extractSize] :
6269 llvm::zip_equal(insertOp.getMixedSizes(), extractOp.getMixedSizes())) {
6272 insertOp,
"InsertSliceOp and ExtractSliceOp sizes differ");
6277 assert(transferOp.getVectorType().hasStaticShape() &&
6278 "expected vector to have a static shape");
6279 ArrayRef<int64_t>
vectorShape = transferOp.getVectorType().getShape();
6281 transferOp.getPermutationMap(), transferOp.getShapedType().getShape());
6282 if (transferOp.getMask() || !
vectorShape.equals(resultShape)) {
6284 insertOp,
"TransferWriteOp may not write the full tensor.");
6289 SmallVector<bool> newInBounds(
vectorShape.size(),
false);
6290 auto newExtractOp = tensor::ExtractSliceOp::create(
6291 rewriter, extractOp.getLoc(), insertOp.getSourceType(),
6292 insertOp.getDest(), insertOp.getMixedOffsets(),
6293 insertOp.getMixedSizes(), insertOp.getMixedStrides());
6294 auto newTransferWriteOp = TransferWriteOp::create(
6295 rewriter, transferOp.getLoc(), transferOp.getVector(),
6296 newExtractOp.getResult(), transferOp.getIndices(),
6297 transferOp.getPermutationMapAttr(),
6300 insertOp.getSourceMutable().assign(newTransferWriteOp.getResult());
6308void TransferWriteOp::getCanonicalizationPatterns(RewritePatternSet &results,
6309 MLIRContext *context) {
6310 results.
add<FoldWaw, SwapExtractSliceOfTransferWrite>(context);
6313FailureOr<std::optional<SmallVector<Value>>>
6314TransferWriteOp::bubbleDownCasts(OpBuilder &builder) {
6315 if (!hasPureBufferSemantics())
6329 result = dyn_cast<BoolAttr>(attr);
6332 "expected boolean attribute");
6336static void printBoolAttr(OpAsmPrinter &printer, Operation *, BoolAttr attr) {
6341 MemRefType memRefTy) {
6344 if (!vecTy.isScalable() &&
6345 (vecTy.getRank() == 0 || vecTy.getNumElements() == 1))
6347 return memRefTy.isLastDimUnitStride();
6350static LogicalResult verifyLoadStoreMemRefLayout(Operation *op,
6352 MemRefType memRefTy) {
6354 return op->
emitOpError(
"most minor memref dim must have unit stride");
6358LogicalResult vector::LoadOp::verify() {
6362 if (
failed(verifyLoadStoreMemRefLayout(*
this, resVecTy, memRefTy)))
6369 return emitOpError(
"memref strides must be non-negative");
6371 if (memRefTy.getRank() < resVecTy.getRank())
6373 "destination memref has lower rank than the result vector");
6376 Type memElemTy = memRefTy.getElementType();
6377 if (
auto memVecTy = llvm::dyn_cast<VectorType>(memElemTy)) {
6378 if (memVecTy != resVecTy)
6379 return emitOpError(
"base memref and result vector types should match");
6380 memElemTy = memVecTy.getElementType();
6383 if (resVecTy.getElementType() != memElemTy)
6384 return emitOpError(
"base and result element types should match");
6385 if (llvm::size(
getIndices()) != memRefTy.getRank())
6386 return emitOpError(
"requires ") << memRefTy.getRank() <<
" indices";
6390OpFoldResult LoadOp::fold(FoldAdaptor) {
6393 return OpFoldResult();
6396FailureOr<std::optional<SmallVector<Value>>>
6397LoadOp::bubbleDownCasts(OpBuilder &builder) {
6405std::optional<SmallVector<int64_t, 4>> LoadOp::getIterationShapeToUnroll() {
6413LogicalResult vector::StoreOp::verify() {
6417 if (
failed(verifyLoadStoreMemRefLayout(*
this, valueVecTy, memRefTy)))
6424 return emitOpError(
"memref strides must be non-negative");
6426 if (memRefTy.getRank() < valueVecTy.getRank())
6427 return emitOpError(
"source memref has lower rank than the vector to store");
6430 Type memElemTy = memRefTy.getElementType();
6431 if (
auto memVecTy = llvm::dyn_cast<VectorType>(memElemTy)) {
6432 if (memVecTy != valueVecTy)
6434 "base memref and valueToStore vector types should match");
6435 memElemTy = memVecTy.getElementType();
6438 if (valueVecTy.getElementType() != memElemTy)
6439 return emitOpError(
"base and valueToStore element type should match");
6440 if (llvm::size(
getIndices()) != memRefTy.getRank())
6441 return emitOpError(
"requires ") << memRefTy.getRank() <<
" indices";
6445LogicalResult StoreOp::fold(FoldAdaptor adaptor,
6446 SmallVectorImpl<OpFoldResult> &results) {
6450FailureOr<std::optional<SmallVector<Value>>>
6451StoreOp::bubbleDownCasts(OpBuilder &builder) {
6459std::optional<SmallVector<int64_t, 4>> StoreOp::getIterationShapeToUnroll() {
6467LogicalResult MaskedLoadOp::verify() {
6468 VectorType maskVType = getMaskVectorType();
6469 VectorType passVType = getPassThruVectorType();
6473 if (
failed(verifyLoadStoreMemRefLayout(*
this, resVType, memType)))
6480 return emitOpError(
"memref strides must be non-negative");
6485 if (llvm::size(
getIndices()) != memType.getRank())
6486 return emitOpError(
"requires ") << memType.getRank() <<
" indices";
6487 if (resVType.getShape() != maskVType.getShape())
6488 return emitOpError(
"expected result shape to match mask shape");
6489 if (resVType != passVType)
6490 return emitOpError(
"expected pass_thru of same type as result type");
6495class MaskedLoadFolder final :
public OpRewritePattern<MaskedLoadOp> {
6498 LogicalResult matchAndRewrite(MaskedLoadOp
load,
6499 PatternRewriter &rewriter)
const override {
6511 llvm_unreachable(
"Unexpected 1DMaskFormat on MaskedLoad");
6516void MaskedLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
6517 MLIRContext *context) {
6518 results.
add<MaskedLoadFolder>(context);
6521OpFoldResult MaskedLoadOp::fold(FoldAdaptor) {
6524 return OpFoldResult();
6527FailureOr<std::optional<SmallVector<Value>>>
6528MaskedLoadOp::bubbleDownCasts(OpBuilder &builder) {
6537LogicalResult MaskedStoreOp::verify() {
6538 VectorType maskVType = getMaskVectorType();
6542 if (
failed(verifyLoadStoreMemRefLayout(*
this, valueVType, memType)))
6549 return emitOpError(
"memref strides must be non-negative");
6554 if (llvm::size(
getIndices()) != memType.getRank())
6555 return emitOpError(
"requires ") << memType.getRank() <<
" indices";
6556 if (valueVType.getShape() != maskVType.getShape())
6557 return emitOpError(
"expected valueToStore shape to match mask shape");
6562class MaskedStoreFolder final :
public OpRewritePattern<MaskedStoreOp> {
6565 LogicalResult matchAndRewrite(MaskedStoreOp store,
6566 PatternRewriter &rewriter)
const override {
6570 store, store.getValueToStore(), store.getBase(), store.getIndices());
6578 llvm_unreachable(
"Unexpected 1DMaskFormat on MaskedStore");
6583void MaskedStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
6584 MLIRContext *context) {
6585 results.
add<MaskedStoreFolder>(context);
6588LogicalResult MaskedStoreOp::fold(FoldAdaptor adaptor,
6589 SmallVectorImpl<OpFoldResult> &results) {
6593FailureOr<std::optional<SmallVector<Value>>>
6594MaskedStoreOp::bubbleDownCasts(OpBuilder &builder) {
6603LogicalResult GatherOp::verify() {
6604 VectorType indVType = getIndexVectorType();
6605 VectorType maskVType = getMaskVectorType();
6607 ShapedType baseType = getBaseType();
6609 if (!llvm::isa<MemRefType, RankedTensorType>(baseType))
6610 return emitOpError(
"requires base to be a memref or ranked tensor type");
6615 if (
auto memRefType = dyn_cast<MemRefType>(baseType))
6617 return emitOpError(
"memref strides must be non-negative");
6622 if (llvm::size(getOffsets()) != baseType.getRank())
6623 return emitOpError(
"requires ") << baseType.getRank() <<
" indices";
6624 if (resVType.getShape() != indVType.getShape())
6625 return emitOpError(
"expected result dim to match indices dim");
6626 if (resVType.getShape() != maskVType.getShape())
6627 return emitOpError(
"expected result dim to match mask dim");
6628 if (resVType != getPassThruVectorType())
6629 return emitOpError(
"expected pass_thru of same type as result type");
6630 if (getAlignmentAttr() && !isa<MemRefType>(baseType)) {
6632 "alignment is only supported for memref bases, not tensor bases");
6641static LogicalResult isZeroBasedContiguousSeq(Value indexVec) {
6642 auto vecType = dyn_cast<VectorType>(indexVec.
getType());
6643 if (!vecType || vecType.getRank() != 1 || vecType.isScalable())
6649 DenseIntElementsAttr elements;
6654 llvm::equal(elements, llvm::seq<int64_t>(0, vecType.getNumElements())));
6660std::optional<SmallVector<int64_t, 4>> GatherOp::getIterationShapeToUnroll() {
6665class GatherFolder final :
public OpRewritePattern<GatherOp> {
6668 LogicalResult matchAndRewrite(GatherOp gather,
6669 PatternRewriter &rewriter)
const override {
6674 rewriter.
replaceOp(gather, gather.getPassThru());
6679 llvm_unreachable(
"Unexpected 1DMaskFormat on GatherFolder");
6685class FoldContiguousGather final :
public OpRewritePattern<GatherOp> {
6688 LogicalResult matchAndRewrite(GatherOp op,
6689 PatternRewriter &rewriter)
const override {
6690 if (!isa<MemRefType>(op.getBase().getType()))
6693 if (
failed(isZeroBasedContiguousSeq(op.getIndices())))
6697 op.getOffsets(), op.getMask(),
6704void GatherOp::getCanonicalizationPatterns(RewritePatternSet &results,
6705 MLIRContext *context) {
6706 results.
add<GatherFolder, FoldContiguousGather>(context);
6709FailureOr<std::optional<SmallVector<Value>>>
6710GatherOp::bubbleDownCasts(OpBuilder &builder) {
6719LogicalResult ScatterOp::verify() {
6720 VectorType indVType = getIndexVectorType();
6721 VectorType maskVType = getMaskVectorType();
6723 ShapedType baseType = getBaseType();
6725 if (!llvm::isa<MemRefType, RankedTensorType>(baseType))
6726 return emitOpError(
"requires base to be a memref or ranked tensor type");
6731 if (
auto memRefType = dyn_cast<MemRefType>(baseType))
6733 return emitOpError(
"memref strides must be non-negative");
6738 if (llvm::size(getOffsets()) != baseType.getRank())
6739 return emitOpError(
"requires ") << baseType.getRank() <<
" indices";
6740 if (valueVType.getShape() != indVType.getShape())
6741 return emitOpError(
"expected valueToStore dim to match indices dim");
6742 if (valueVType.getShape() != maskVType.getShape())
6743 return emitOpError(
"expected valueToStore dim to match mask dim");
6744 if (getAlignmentAttr() && !isa<MemRefType>(baseType)) {
6746 "alignment is only supported for memref bases, not tensor bases");
6751class ScatterFolder final :
public OpRewritePattern<ScatterOp> {
6754 LogicalResult matchAndRewrite(ScatterOp scatter,
6755 PatternRewriter &rewriter)
const override {
6756 ShapedType baseType = scatter.getBaseType();
6757 bool isMemRef = isa<MemRefType>(baseType);
6758 if (!isMemRef && !isa<RankedTensorType>(baseType))
6771 rewriter.
replaceOp(scatter, scatter.getBase());
6776 llvm_unreachable(
"Unexpected 1DMaskFormat on ScatterFolder");
6782class FoldContiguousScatter final :
public OpRewritePattern<ScatterOp> {
6785 LogicalResult matchAndRewrite(ScatterOp op,
6786 PatternRewriter &rewriter)
const override {
6789 if (!isa<MemRefType>(op.getBase().getType()))
6792 if (
failed(isZeroBasedContiguousSeq(op.getIndices())))
6796 op, op.getBase(), op.getOffsets(), op.getMask(), op.getValueToStore());
6802void ScatterOp::getCanonicalizationPatterns(RewritePatternSet &results,
6803 MLIRContext *context) {
6804 results.
add<ScatterFolder, FoldContiguousScatter>(context);
6807FailureOr<std::optional<SmallVector<Value>>>
6808ScatterOp::bubbleDownCasts(OpBuilder &builder) {
6817LogicalResult ExpandLoadOp::verify() {
6818 VectorType maskVType = getMaskVectorType();
6819 VectorType passVType = getPassThruVectorType();
6823 if (
failed(verifyLoadStoreMemRefLayout(*
this, resVType, memType)))
6830 return emitOpError(
"memref strides must be non-negative");
6835 if (llvm::size(
getIndices()) != memType.getRank())
6836 return emitOpError(
"requires ") << memType.getRank() <<
" indices";
6837 if (resVType.getShape() != maskVType.getShape())
6838 return emitOpError(
"expected result shape to match mask shape");
6839 if (resVType.getScalableDims() != maskVType.getScalableDims())
6841 "expected result scalable dims to match mask scalable dims");
6842 if (resVType != passVType)
6843 return emitOpError(
"expected pass_thru of same type as result type");
6848class ExpandLoadFolder final :
public OpRewritePattern<ExpandLoadOp> {
6851 LogicalResult matchAndRewrite(ExpandLoadOp expand,
6852 PatternRewriter &rewriter)
const override {
6856 expand, expand.getType(), expand.getBase(), expand.getIndices());
6859 rewriter.
replaceOp(expand, expand.getPassThru());
6864 llvm_unreachable(
"Unexpected 1DMaskFormat on ExpandLoadFolder");
6869void ExpandLoadOp::getCanonicalizationPatterns(RewritePatternSet &results,
6870 MLIRContext *context) {
6871 results.
add<ExpandLoadFolder>(context);
6874FailureOr<std::optional<SmallVector<Value>>>
6875ExpandLoadOp::bubbleDownCasts(OpBuilder &builder) {
6884LogicalResult CompressStoreOp::verify() {
6885 VectorType maskVType = getMaskVectorType();
6889 if (
failed(verifyLoadStoreMemRefLayout(*
this, valueVType, memType)))
6896 return emitOpError(
"memref strides must be non-negative");
6901 if (llvm::size(
getIndices()) != memType.getRank())
6902 return emitOpError(
"requires ") << memType.getRank() <<
" indices";
6903 if (valueVType.getShape() != maskVType.getShape())
6904 return emitOpError(
"expected valueToStore shape to match mask shape");
6905 if (valueVType.getScalableDims() != maskVType.getScalableDims())
6907 "expected valueToStore scalable dims to match mask scalable dims");
6912class CompressStoreFolder final :
public OpRewritePattern<CompressStoreOp> {
6915 LogicalResult matchAndRewrite(CompressStoreOp compress,
6916 PatternRewriter &rewriter)
const override {
6920 compress, compress.getValueToStore(), compress.getBase(),
6921 compress.getIndices());
6929 llvm_unreachable(
"Unexpected 1DMaskFormat on CompressStoreFolder");
6934void CompressStoreOp::getCanonicalizationPatterns(RewritePatternSet &results,
6935 MLIRContext *context) {
6936 results.
add<CompressStoreFolder>(context);
6939FailureOr<std::optional<SmallVector<Value>>>
6940CompressStoreOp::bubbleDownCasts(OpBuilder &builder) {
6949void ShapeCastOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
6951 setResultRanges(getResult(), argRanges.front());
6954LogicalResult ShapeCastOp::verify() {
6956 VectorType sourceType = getSourceVectorType();
6957 VectorType resultType = getResultVectorType();
6965 int64_t sourceNElms = sourceType.getNumElements();
6966 int64_t resultNElms = resultType.getNumElements();
6967 if (sourceNElms != resultNElms) {
6968 return emitOpError() <<
"has different number of elements at source ("
6969 << sourceNElms <<
") and result (" << resultNElms
6974 int64_t sourceNScalableDims = sourceType.getNumScalableDims();
6975 int64_t resultNScalableDims = resultType.getNumScalableDims();
6976 if (sourceNScalableDims != resultNScalableDims)
6977 return emitOpError() <<
"has different number of scalable dims at source ("
6978 << sourceNScalableDims <<
") and result ("
6979 << resultNScalableDims <<
")";
6990bool ShapeCastOp::isBroadcastLike() {
6991 auto srcType = getSourceVectorType();
6992 auto resType = getResultVectorType();
6995 std::pair<VectorDim, VectorDim> mismatchingDims;
6997 BroadcastableToResult::Success)
7004 size_t rankDiff = resType.getRank() - srcType.getRank();
7009 if (!llvm::all_of(resType.getShape().take_front(rankDiff),
7010 [](int64_t dim) { return dim == 1; }))
7014 return resType.getShape().take_back(srcType.getRank()) == srcType.getShape();
7021static bool isOrderPreserving(TransposeOp transpose) {
7022 ArrayRef<int64_t> permutation = transpose.getPermutation();
7023 VectorType sourceType = transpose.getSourceVectorType();
7024 ArrayRef<int64_t> inShape = sourceType.getShape();
7025 ArrayRef<bool> inDimIsScalable = sourceType.getScalableDims();
7026 auto isNonScalableUnitDim = [&](int64_t dim) {
7027 return inShape[dim] == 1 && !inDimIsScalable[dim];
7029 int64_t current = 0;
7030 for (
auto p : permutation) {
7031 if (!isNonScalableUnitDim(p)) {
7041OpFoldResult ShapeCastOp::fold(FoldAdaptor adaptor) {
7043 VectorType resultType =
getType();
7046 if (getSource().
getType() == resultType)
7050 if (
auto precedingShapeCast = getSource().getDefiningOp<ShapeCastOp>()) {
7051 setOperand(precedingShapeCast.getSource());
7056 if (
auto transpose = getSource().getDefiningOp<TransposeOp>()) {
7057 if (isOrderPreserving(transpose)) {
7058 setOperand(transpose.getVector());
7066 if (
auto bcastOp = getSource().getDefiningOp<BroadcastOp>()) {
7067 if (bcastOp.getSourceType() == resultType)
7068 return bcastOp.getSource();
7072 if (
auto denseAttr =
7073 dyn_cast_if_present<DenseElementsAttr>(adaptor.getSource()))
7074 return denseAttr.reshape(
getType());
7086std::optional<SmallVector<int64_t, 4>>
7087ShapeCastOp::getIterationShapeToUnroll() {
7088 return llvm::to_vector<4>(getResultVectorType().
getShape());
7091std::optional<SmallVector<int64_t>> ShapeCastOp::getDefaultUnrollTargetShape() {
7092 auto resultShape = this->getResultVectorType().getShape();
7095 if (resultShape.size() == 2 && resultShape[0] == 1 && resultShape[1] == 32) {
7096 return SmallVector<int64_t>{1, 16};
7098 if (resultShape.size() == 2 && resultShape[0] == 2 && resultShape[1] == 1) {
7099 return SmallVector<int64_t>{1, 1};
7103 auto sourceShape = this->getSourceVectorType().getShape();
7104 if (resultShape.size() == 3 && resultShape[0] == 8 && resultShape[1] == 1 &&
7105 resultShape[2] == 32) {
7106 return SmallVector<int64_t>{8, 1, 4};
7108 if (sourceShape.size() == 3 && resultShape.size() == 2 &&
7109 resultShape[0] == 4 && resultShape[1] == 4) {
7110 return SmallVector<int64_t>{2, 2};
7112 if (resultShape.size() == 3 && resultShape[0] == 2 && resultShape[1] == 8 &&
7113 resultShape[2] == 4) {
7114 return SmallVector<int64_t>{2, 2, 2};
7117 return SmallVector<int64_t>{2, 4};
7127static VectorType trimTrailingUnitDims(VectorType oldType) {
7128 ArrayRef<int64_t> oldShape = oldType.getShape();
7129 ArrayRef<int64_t> newShape = oldShape;
7131 ArrayRef<bool> oldScalableDims = oldType.getScalableDims();
7132 ArrayRef<bool> newScalableDims = oldScalableDims;
7134 while (!newShape.empty() && newShape.back() == 1 && !newScalableDims.back()) {
7135 newShape = newShape.drop_back(1);
7136 newScalableDims = newScalableDims.drop_back(1);
7141 if (newShape.empty()) {
7142 newShape = oldShape.take_back();
7143 newScalableDims = oldScalableDims.take_back();
7146 return VectorType::get(newShape, oldType.getElementType(), newScalableDims);
7155 ArrayRef<int64_t> oldShape = oldType.getShape();
7156 ArrayRef<int64_t> newShape = oldShape;
7158 ArrayRef<bool> oldScalableDims = oldType.getScalableDims();
7159 ArrayRef<bool> newScalableDims = oldScalableDims;
7161 while (!newShape.empty() && newShape.front() == 1 &&
7162 !newScalableDims.front()) {
7163 newShape = newShape.drop_front(1);
7164 newScalableDims = newScalableDims.drop_front(1);
7169 if (newShape.empty()) {
7170 newShape = oldShape.take_back();
7171 newScalableDims = oldScalableDims.take_back();
7174 return VectorType::get(newShape, oldType.getElementType(), newScalableDims);
7177enum class UnitDimSide { Leading, Trailing };
7200template <UnitDimS
ide S
ide>
7201class ShapeCastCreateMaskFolderBoundaryUnitDim final
7202 :
public OpRewritePattern<ShapeCastOp> {
7206 LogicalResult matchAndRewrite(ShapeCastOp shapeOp,
7207 PatternRewriter &rewriter)
const override {
7208 Value shapeOpSrc = shapeOp->getOperand(0);
7209 auto createMaskOp = shapeOpSrc.
getDefiningOp<vector::CreateMaskOp>();
7210 auto constantMaskOp = shapeOpSrc.
getDefiningOp<vector::ConstantMaskOp>();
7211 if (!createMaskOp && !constantMaskOp)
7214 VectorType shapeOpResTy = shapeOp.getResultVectorType();
7215 VectorType shapeOpSrcTy = shapeOp.getSourceVectorType();
7217 VectorType newVecType = (Side == UnitDimSide::Trailing)
7218 ? trimTrailingUnitDims(shapeOpSrcTy)
7221 if (newVecType != shapeOpResTy) {
7222 return (Side == UnitDimSide::Trailing)
7224 shapeOp,
"Non-trailing-unit-dim dropping shape_cast Op")
7226 shapeOp,
"Non-leading-unit-dim dropping shape_cast Op");
7229 auto numDimsToDrop = shapeOpSrcTy.getRank() - shapeOpResTy.getRank();
7232 if (!numDimsToDrop) {
7233 return (Side == UnitDimSide::Trailing)
7235 shapeOp,
"Non-trailing-unit-dim dropping shape_cast Op")
7237 shapeOp,
"Non-leading-unit-dim dropping shape_cast Op");
7241 auto maskOperands = createMaskOp.getOperands();
7243 auto maskOperandsToDrop = (Side == UnitDimSide::Trailing)
7244 ? maskOperands.take_back(numDimsToDrop)
7245 : maskOperands.take_front(numDimsToDrop);
7249 if (llvm::any_of(maskOperandsToDrop, [](Value maskDim) {
7251 return !cst || (cst.value() != 1);
7255 auto newMaskOperands = (Side == UnitDimSide::Trailing)
7256 ? maskOperands.drop_back(numDimsToDrop)
7257 : maskOperands.drop_front(numDimsToDrop);
7263 if (constantMaskOp) {
7264 auto maskDimSizes = constantMaskOp.getMaskDimSizes();
7266 ArrayRef<int64_t> maskDimSizesToDrop =
7267 (Side == UnitDimSide::Trailing)
7268 ? maskDimSizes.take_back(numDimsToDrop)
7269 : maskDimSizes.take_front(numDimsToDrop);
7273 if (llvm::any_of(maskDimSizesToDrop,
7274 [](int64_t dim) {
return dim != 1; }))
7277 ArrayRef<int64_t> newMaskDimSizes =
7278 (Side == UnitDimSide::Trailing)
7279 ? maskDimSizes.drop_back(numDimsToDrop)
7280 : maskDimSizes.drop_front(numDimsToDrop);
7291class ShapeCastBroadcastFolder final :
public OpRewritePattern<ShapeCastOp> {
7295 LogicalResult matchAndRewrite(ShapeCastOp shapeCastOp,
7296 PatternRewriter &rewriter)
const override {
7297 auto oldBcOp = shapeCastOp.getSource().getDefiningOp<vector::BroadcastOp>();
7307 VectorType resVectorType = shapeCastOp.getResultVectorType();
7311 if (resVectorType.getNumScalableDims() > 1)
7314 auto srcVectorType = dyn_cast<VectorType>(oldBcOp.getSourceType());
7315 bool srcIsScalar = !srcVectorType;
7319 BroadcastableToResult::Success) {
7330 VectorType oldBcVectorType = oldBcOp.getResultVectorType();
7331 int64_t srcRank = srcVectorType.getRank();
7332 int64_t oldBcRank = oldBcVectorType.getRank();
7333 int64_t resRank = resVectorType.getRank();
7334 ArrayRef<int64_t> srcShape = srcVectorType.getShape();
7335 ArrayRef<int64_t> oldBcShape = oldBcVectorType.getShape();
7336 ArrayRef<int64_t> resShape = resVectorType.getShape();
7337 ArrayRef<bool> srcScalable = srcVectorType.getScalableDims();
7338 ArrayRef<bool> oldBcScalable = oldBcVectorType.getScalableDims();
7339 ArrayRef<bool> resScalable = resVectorType.getScalableDims();
7344 int64_t oldBcStride = 1, resStride = 1;
7345 bool isOldBcStrideScalable =
false, isResStrideScalable =
false;
7346 for (int64_t i = 0; i < srcRank; ++i) {
7347 int64_t srcDim = srcRank - 1 - i;
7348 int64_t oldBcDim = oldBcRank - 1 - i;
7349 int64_t resDim = resRank - 1 - i;
7351 bool isUnitDim = srcShape[srcDim] == 1 && !srcScalable[srcDim];
7352 if (!isUnitDim && (oldBcStride != resStride ||
7353 isOldBcStrideScalable != isResStrideScalable)) {
7357 oldBcStride *= oldBcShape[oldBcDim];
7358 resStride *= resShape[resDim];
7359 isOldBcStrideScalable |= oldBcScalable[oldBcDim];
7360 isResStrideScalable |= resScalable[resDim];
7365 oldBcOp.getSource());
7384class FoldShapeCastOfFromElements final :
public OpRewritePattern<ShapeCastOp> {
7388 LogicalResult matchAndRewrite(ShapeCastOp shapeCastOp,
7389 PatternRewriter &rewriter)
const override {
7390 auto fromElements = shapeCastOp.getSource().getDefiningOp<FromElementsOp>();
7395 shapeCastOp, shapeCastOp.getResultVectorType(),
7396 fromElements.getElements());
7403void ShapeCastOp::getCanonicalizationPatterns(RewritePatternSet &results,
7404 MLIRContext *context) {
7405 results.
add<ShapeCastCreateMaskFolderBoundaryUnitDim<UnitDimSide::Leading>,
7406 ShapeCastCreateMaskFolderBoundaryUnitDim<UnitDimSide::Trailing>,
7407 ShapeCastBroadcastFolder, FoldShapeCastOfFromElements>(context);
7414LogicalResult BitCastOp::verify() {
7415 auto sourceVectorType = getSourceVectorType();
7416 auto resultVectorType = getResultVectorType();
7418 for (int64_t i = 0, e = sourceVectorType.getRank() - 1; i < e; i++) {
7419 if (sourceVectorType.getDimSize(i) != resultVectorType.getDimSize(i))
7420 return emitOpError(
"dimension size mismatch at: ") << i;
7423 DataLayout dataLayout = DataLayout::closest(*
this);
7424 auto sourceElementBits =
7426 auto resultElementBits =
7429 if (sourceVectorType.getRank() == 0) {
7430 if (sourceElementBits != resultElementBits)
7431 return emitOpError(
"source/result bitwidth of the 0-D vector element "
7432 "types must be equal");
7433 }
else if (sourceElementBits * sourceVectorType.getShape().back() !=
7434 resultElementBits * resultVectorType.getShape().back()) {
7436 "source/result bitwidth of the minor 1-D vectors must be equal");
7442OpFoldResult BitCastOp::fold(FoldAdaptor adaptor) {
7448 if (
auto otherOp = getSource().getDefiningOp<BitCastOp>()) {
7449 if (getResult().
getType() == otherOp.getSource().getType())
7450 return otherOp.getSource();
7452 setOperand(otherOp.getSource());
7456 Attribute sourceConstant = adaptor.getSource();
7457 if (!sourceConstant)
7460 Type srcElemType = getSourceVectorType().getElementType();
7461 Type dstElemType = getResultVectorType().getElementType();
7463 if (
auto floatPack = llvm::dyn_cast<DenseFPElementsAttr>(sourceConstant)) {
7464 if (floatPack.isSplat()) {
7465 auto splat = floatPack.getSplatValue<FloatAttr>();
7468 if (srcElemType.
isF16() && dstElemType.
isF32()) {
7469 uint32_t bits =
static_cast<uint32_t
>(
7470 splat.getValue().bitcastToAPInt().getZExtValue());
7472 bits = (bits << 16) | (bits & 0xffff);
7473 APInt intBits(32, bits);
7474 APFloat floatBits(llvm::APFloat::IEEEsingle(), intBits);
7480 if (
auto intPack = llvm::dyn_cast<DenseIntElementsAttr>(sourceConstant)) {
7481 if (intPack.isSplat()) {
7482 auto splat = intPack.getSplatValue<IntegerAttr>();
7484 if (llvm::isa<IntegerType>(dstElemType) && srcElemType.
isIntOrFloat()) {
7489 if (dstBitWidth > srcBitWidth && dstBitWidth % srcBitWidth == 0) {
7490 APInt intBits = splat.getValue().zext(dstBitWidth);
7493 for (uint64_t i = 0; i < dstBitWidth / srcBitWidth - 1; i++)
7494 intBits = (intBits << srcBitWidth) | intBits;
7507std::optional<SmallVector<int64_t, 4>> BitCastOp::getIterationShapeToUnroll() {
7508 return llvm::to_vector<4>(getResultVectorType().
getShape());
7511std::optional<SmallVector<int64_t>> BitCastOp::getDefaultUnrollTargetShape() {
7512 return SmallVector<int64_t>{4, 4};
7519static SmallVector<int64_t, 8> extractShape(MemRefType memRefType) {
7520 auto vectorType = llvm::dyn_cast<VectorType>(memRefType.getElementType());
7521 SmallVector<int64_t, 8> res(memRefType.getShape());
7523 res.append(vectorType.getShape().begin(), vectorType.getShape().end());
7529void TypeCastOp::build(OpBuilder &builder, OperationState &
result,
7531 result.addOperands(source);
7532 MemRefType memRefType = llvm::cast<MemRefType>(source.
getType());
7533 VectorType vectorType =
7534 VectorType::get(extractShape(memRefType),
7536 result.addTypes(MemRefType::get({}, vectorType, MemRefLayoutAttrInterface(),
7537 memRefType.getMemorySpace()));
7540LogicalResult TypeCastOp::verify() {
7541 MemRefType canonicalType =
getMemRefType().canonicalizeStridedLayout();
7542 if (!canonicalType.getLayout().isIdentity())
7543 return emitOpError(
"expects operand to be a memref with identity layout");
7544 if (!getResultMemRefType().getLayout().isIdentity())
7545 return emitOpError(
"expects result to be a memref with identity layout");
7546 if (getResultMemRefType().getMemorySpace() !=
7548 return emitOpError(
"expects result in same memory space");
7551 auto resultType = getResultMemRefType();
7555 "expects result and operand with same underlying scalar type: ")
7557 if (extractShape(sourceType) != extractShape(resultType))
7559 "expects concatenated result and operand shapes to be equal: ")
7568void vector::TransposeOp::build(OpBuilder &builder, OperationState &
result,
7569 Value vector, ArrayRef<int64_t> permutation) {
7570 VectorType vt = llvm::cast<VectorType>(vector.
getType());
7571 SmallVector<int64_t, 4> transposedShape(vt.getRank());
7572 SmallVector<bool, 4> transposedScalableDims(vt.getRank());
7573 for (
unsigned i = 0; i < permutation.size(); ++i) {
7574 transposedShape[i] = vt.getShape()[permutation[i]];
7575 transposedScalableDims[i] = vt.getScalableDims()[permutation[i]];
7578 result.addOperands(vector);
7579 result.addTypes(VectorType::get(transposedShape, vt.getElementType(),
7580 transposedScalableDims));
7581 result.addAttribute(TransposeOp::getPermutationAttrName(
result.name),
7585OpFoldResult vector::TransposeOp::fold(FoldAdaptor adaptor) {
7588 llvm::dyn_cast_if_present<SplatElementsAttr>(adaptor.getVector()))
7589 return splat.reshape(getResultVectorType());
7606 if (getSourceVectorType() == getResultVectorType() &&
7607 isOrderPreserving(*
this))
7613LogicalResult vector::TransposeOp::verify() {
7614 VectorType vectorType = getSourceVectorType();
7615 VectorType resultType = getResultVectorType();
7616 int64_t rank = resultType.getRank();
7617 if (vectorType.getRank() != rank)
7618 return emitOpError(
"vector result rank mismatch: ") << rank;
7620 ArrayRef<int64_t> perm = getPermutation();
7621 int64_t size = perm.size();
7623 return emitOpError(
"transposition length mismatch: ") << size;
7624 SmallVector<bool, 8> seen(rank,
false);
7625 for (
const auto &ta : llvm::enumerate(perm)) {
7626 if (ta.value() < 0 || ta.value() >= rank)
7627 return emitOpError(
"transposition index out of range: ") << ta.value();
7628 if (seen[ta.value()])
7629 return emitOpError(
"duplicate position index: ") << ta.value();
7630 seen[ta.value()] =
true;
7631 if (resultType.getDimSize(ta.index()) != vectorType.getDimSize(ta.value()))
7632 return emitOpError(
"dimension size mismatch at: ") << ta.value();
7637void TransposeOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
7639 setResultRanges(getResult(), argRanges.front());
7645std::optional<SmallVector<int64_t, 4>>
7646TransposeOp::getIterationShapeToUnroll() {
7647 return llvm::to_vector<4>(getResultVectorType().
getShape());
7650std::optional<SmallVector<int64_t>> TransposeOp::getDefaultUnrollTargetShape() {
7651 return SmallVector<int64_t>{1, 3, 4, 2};
7657class TransposeFolder final :
public OpRewritePattern<vector::TransposeOp> {
7661 LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
7662 PatternRewriter &rewriter)
const override {
7664 auto composePermutations = [](ArrayRef<int64_t> permutation1,
7665 ArrayRef<int64_t> permutation2) {
7666 SmallVector<int64_t, 4>
result;
7667 for (
auto index : permutation2)
7668 result.push_back(permutation1[index]);
7673 vector::TransposeOp parentTransposeOp =
7674 transposeOp.getVector().getDefiningOp<vector::TransposeOp>();
7675 if (!parentTransposeOp)
7678 SmallVector<int64_t, 4> permutation = composePermutations(
7679 parentTransposeOp.getPermutation(), transposeOp.getPermutation());
7682 transposeOp, transposeOp.getResult().
getType(),
7683 parentTransposeOp.getVector(), permutation);
7689class FoldTransposeSplat final :
public OpRewritePattern<TransposeOp> {
7693 LogicalResult matchAndRewrite(TransposeOp transposeOp,
7694 PatternRewriter &rewriter)
const override {
7695 Value splat = getScalarSplatSource(transposeOp.getVector());
7700 transposeOp, transposeOp.getResultVectorType(), splat);
7706class FoldTransposeCreateMask final :
public OpRewritePattern<TransposeOp> {
7710 LogicalResult matchAndRewrite(TransposeOp transpOp,
7711 PatternRewriter &rewriter)
const override {
7712 Value transposeSrc = transpOp.getVector();
7713 auto createMaskOp = transposeSrc.
getDefiningOp<vector::CreateMaskOp>();
7714 auto constantMaskOp = transposeSrc.
getDefiningOp<vector::ConstantMaskOp>();
7715 if (!createMaskOp && !constantMaskOp)
7720 ArrayRef<int64_t> permutation = transpOp.getPermutation();
7723 auto maskOperands = createMaskOp.getOperands();
7724 SmallVector<Value> newOperands(maskOperands.begin(), maskOperands.end());
7728 transpOp, transpOp.getResultVectorType(), newOperands);
7733 auto maskDimSizes = constantMaskOp.getMaskDimSizes();
7737 transpOp, transpOp.getResultVectorType(), newMaskDimSizes);
7743class FoldTransposeShapeCast final :
public OpRewritePattern<TransposeOp> {
7747 LogicalResult matchAndRewrite(TransposeOp transposeOp,
7748 PatternRewriter &rewriter)
const override {
7750 transposeOp.getVector().getDefiningOp<vector::ShapeCastOp>();
7753 if (!isOrderPreserving(transposeOp))
7756 VectorType resultType = transposeOp.getType();
7763 shapeCastOp.getSource());
7782class FoldTransposeFromElements final :
public OpRewritePattern<TransposeOp> {
7785 LogicalResult matchAndRewrite(vector::TransposeOp transposeOp,
7786 PatternRewriter &rewriter)
const override {
7787 auto fromElementsOp =
7788 transposeOp.getVector().getDefiningOp<vector::FromElementsOp>();
7789 if (!fromElementsOp)
7792 VectorType srcTy = fromElementsOp.getResult().getType();
7793 VectorType dstTy = transposeOp.getType();
7795 ArrayRef<int64_t> permutation = transposeOp.getPermutation();
7796 int64_t rank = srcTy.getRank();
7799 SmallVector<int64_t> inversePerm(rank, 0);
7800 for (int64_t i = 0; i < rank; ++i)
7801 inversePerm[permutation[i]] = i;
7803 ArrayRef<int64_t> srcShape = srcTy.getShape();
7804 ArrayRef<int64_t> dstShape = dstTy.getShape();
7805 SmallVector<int64_t> srcIdx(rank, 0);
7806 SmallVector<int64_t> dstIdx(rank, 0);
7810 auto elementsOld = fromElementsOp.getElements();
7811 SmallVector<Value> elementsNew;
7812 int64_t dstNumElements = dstTy.getNumElements();
7813 elementsNew.reserve(dstNumElements);
7817 for (int64_t linearIdx = 0; linearIdx < dstNumElements; ++linearIdx) {
7821 for (int64_t j = 0; j < rank; ++j)
7822 srcIdx[j] = dstIdx[inversePerm[j]];
7824 int64_t srcLin =
linearize(srcIdx, srcStrides);
7826 elementsNew.push_back(elementsOld[srcLin]);
7860class FoldTransposeBroadcast :
public OpRewritePattern<vector::TransposeOp> {
7863 FoldTransposeBroadcast(MLIRContext *context, PatternBenefit benefit = 1)
7864 : OpRewritePattern<vector::TransposeOp>(context, benefit) {}
7866 LogicalResult matchAndRewrite(vector::TransposeOp transpose,
7867 PatternRewriter &rewriter)
const override {
7873 "not preceded by a broadcast");
7876 auto inputType = dyn_cast<VectorType>(
broadcast.getSourceType());
7877 VectorType outputType = transpose.getResultVectorType();
7880 bool inputIsScalar = !inputType;
7881 if (inputIsScalar) {
7887 ArrayRef<int64_t> permutation = transpose.getPermutation();
7888 ArrayRef<int64_t> inputShape = inputType.getShape();
7889 int64_t inputRank = inputType.getRank();
7890 int64_t outputRank = transpose.getType().getRank();
7891 int64_t deltaRank = outputRank - inputRank;
7894 for (
int inputIndex = 0; inputIndex < inputRank; ++inputIndex) {
7895 bool notOne = inputShape[inputIndex] != 1;
7896 bool prevNotOne = (inputIndex != 0 && inputShape[inputIndex - 1] != 1);
7897 bool groupEndFound = notOne || prevNotOne;
7898 if (groupEndFound) {
7899 int high = inputIndex + deltaRank;
7903 for (
int i = low; i < high; ++i) {
7904 if (permutation[i] < low || permutation[i] >= high) {
7906 transpose,
"permutation not local to group");
7920 vector::BroadcastableToResult::Success &&
7921 "not broadcastable directly to transpose output");
7932void vector::TransposeOp::getCanonicalizationPatterns(
7933 RewritePatternSet &results, MLIRContext *context) {
7934 results.
add<FoldTransposeCreateMask, FoldTransposeShapeCast, TransposeFolder,
7935 FoldTransposeSplat, FoldTransposeFromElements,
7936 FoldTransposeBroadcast>(context);
7943void ConstantMaskOp::build(OpBuilder &builder, OperationState &
result,
7945 assert(kind == ConstantMaskKind::AllTrue ||
7946 kind == ConstantMaskKind::AllFalse);
7947 auto maskDimSizes = llvm::to_vector(type.getShape());
7948 if (maskDimSizes.empty())
7949 maskDimSizes.push_back(1);
7950 if (kind == ConstantMaskKind::AllFalse)
7951 maskDimSizes.assign(maskDimSizes.size(), 0);
7952 build(builder,
result, type, maskDimSizes);
7955LogicalResult ConstantMaskOp::verify() {
7956 auto resultType = llvm::cast<VectorType>(getResult().
getType());
7958 if (resultType.getRank() == 0) {
7959 if (getMaskDimSizes().size() != 1)
7960 return emitError(
"array attr must have length 1 for 0-D vectors");
7961 auto dim = getMaskDimSizes()[0];
7962 if (dim != 0 && dim != 1)
7963 return emitError(
"mask dim size must be either 0 or 1 for 0-D vectors");
7968 if (
static_cast<int64_t
>(getMaskDimSizes().size()) != resultType.getRank())
7970 "must specify array attr of size equal vector result rank");
7973 auto resultShape = resultType.getShape();
7974 auto resultScalableDims = resultType.getScalableDims();
7975 ArrayRef<int64_t> maskDimSizes = getMaskDimSizes();
7976 for (
const auto [index, maskDimSize] : llvm::enumerate(maskDimSizes)) {
7977 if (maskDimSize < 0 || maskDimSize > resultShape[index])
7979 "array attr of size out of bounds of vector result dimension size");
7980 if (resultScalableDims[index] && maskDimSize != 0 &&
7981 maskDimSize != resultShape[index])
7983 "only supports 'none set' or 'all set' scalable dimensions");
7987 bool anyZeros = llvm::is_contained(maskDimSizes, 0);
7988 bool allZeros = llvm::all_of(maskDimSizes, [](int64_t s) {
return s == 0; });
7989 if (anyZeros && !allZeros)
7990 return emitOpError(
"expected all mask dim sizes to be zeros, "
7991 "as a result of conjunction with zero mask dim");
7995bool ConstantMaskOp::isAllOnesMask() {
7998 if (resultType.getRank() == 0) {
7999 assert(getMaskDimSizes().size() == 1 &&
"invalid sizes for zero rank mask");
8000 return getMaskDimSizes()[0] == 1;
8002 for (
const auto [resultSize, maskDimSize] :
8003 llvm::zip_equal(resultType.getShape(), getMaskDimSizes())) {
8004 if (maskDimSize < resultSize)
8010OpFoldResult ConstantMaskOp::fold(FoldAdaptor adaptor) {
8011 ArrayRef<int64_t> bounds = getMaskDimSizes();
8014 auto createBoolSplat = [&](
bool x) {
8020 if (vectorSizes.empty()) {
8021 assert(bounds.size() == 1 &&
"invalid sizes for zero rank mask");
8022 return createBoolSplat(bounds[0] == 1);
8025 if (bounds == vectorSizes)
8026 return createBoolSplat(
true);
8027 if (llvm::all_of(bounds, [](int64_t x) {
return x == 0; }))
8028 return createBoolSplat(
false);
8029 return OpFoldResult();
8032std::optional<SmallVector<int64_t>>
8033ConstantMaskOp::getDefaultUnrollTargetShape() {
8041void CreateMaskOp::build(OpBuilder &builder, OperationState &
result,
8043 ArrayRef<OpFoldResult> mixedOperands) {
8044 SmallVector<Value> operands =
8046 build(builder,
result, type, operands);
8049LogicalResult CreateMaskOp::verify() {
8050 auto vectorType = llvm::cast<VectorType>(getResult().
getType());
8052 if (vectorType.getRank() == 0) {
8053 if (getNumOperands() != 1)
8055 "must specify exactly one operand for 0-D create_mask");
8056 }
else if (getNumOperands() !=
8057 llvm::cast<VectorType>(getResult().
getType()).getRank()) {
8059 "must specify an operand for each result vector dimension");
8064std::optional<SmallVector<int64_t>>
8065CreateMaskOp::getDefaultUnrollTargetShape() {
8094class CreateMaskFolder final :
public OpRewritePattern<CreateMaskOp> {
8098 LogicalResult matchAndRewrite(CreateMaskOp createMaskOp,
8099 PatternRewriter &rewriter)
const override {
8100 VectorType maskType = createMaskOp.getVectorType();
8101 ArrayRef<int64_t> maskTypeDimSizes = maskType.getShape();
8102 ArrayRef<bool> maskTypeDimScalableFlags = maskType.getScalableDims();
8105 constexpr std::array<int64_t, 1> rankZeroShape{1};
8106 constexpr std::array<bool, 1> rankZeroScalableDims{
false};
8107 if (maskType.getRank() == 0) {
8108 maskTypeDimSizes = rankZeroShape;
8109 maskTypeDimScalableFlags = rankZeroScalableDims;
8114 SmallVector<int64_t, 4> constantDims;
8115 for (
auto [i, dimSize] : llvm::enumerate(createMaskOp.getOperands())) {
8120 if (maskTypeDimScalableFlags[i] && intSize >= 0)
8122 constantDims.push_back(*intSize);
8126 if (vscaleMultiplier < maskTypeDimSizes[i])
8128 constantDims.push_back(*vscaleMultiplier);
8135 for (
auto [value, maskDimSize] : llvm::zip(constantDims, maskTypeDimSizes))
8136 value = std::clamp<int64_t>(value, 0, maskDimSize);
8139 if (llvm::is_contained(constantDims, 0))
8140 constantDims.assign(constantDims.size(), 0);
8151void CreateMaskOp::getCanonicalizationPatterns(RewritePatternSet &results,
8152 MLIRContext *context) {
8153 results.
add<CreateMaskFolder>(context);
8161 OpBuilder &builder, OperationState &
result, Value mask,
8162 Operation *maskableOp,
8163 function_ref<
void(OpBuilder &, Operation *)> maskRegionBuilder) {
8164 assert(maskRegionBuilder &&
8165 "builder callback for 'maskRegion' must be present");
8167 result.addOperands(mask);
8168 OpBuilder::InsertionGuard guard(builder);
8169 Region *maskRegion =
result.addRegion();
8171 maskRegionBuilder(builder, maskableOp);
8176 Value mask, Operation *maskableOp,
8177 function_ref<
void(OpBuilder &, Operation *)> maskRegionBuilder) {
8178 build(builder,
result, resultTypes, mask, Value(), maskableOp,
8184 Value mask, Value passthru, Operation *maskableOp,
8185 function_ref<
void(OpBuilder &, Operation *)> maskRegionBuilder) {
8186 build(builder,
result, mask, maskableOp, maskRegionBuilder);
8188 result.addOperands(passthru);
8189 result.addTypes(resultTypes);
8192ParseResult MaskOp::parse(OpAsmParser &parser, OperationState &
result) {
8194 result.regions.reserve(1);
8195 Region &maskRegion = *
result.addRegion();
8200 OpAsmParser::UnresolvedOperand mask;
8205 OpAsmParser::UnresolvedOperand passthru;
8207 if (parsePassthru.succeeded() && parser.
parseOperand(passthru))
8214 MaskOp::ensureTerminator(maskRegion, builder,
result.location);
8225 SmallVector<Type> resultTypes;
8228 result.types.append(resultTypes);
8234 if (parsePassthru.succeeded()) {
8235 if (resultTypes.empty())
8238 "expects a result if passthru operand is provided");
8247void mlir::vector::MaskOp::print(OpAsmPrinter &p) {
8248 p <<
" " << getMask();
8250 p <<
", " << getPassthru();
8254 Block *singleBlock = &getMaskRegion().getBlocks().front();
8260 getOperation()->getDiscardableAttrDictionary().getValue());
8262 p <<
" : " << getMask().getType();
8263 if (getNumResults() > 0)
8264 p <<
" -> " << getResultTypes();
8267void MaskOp::ensureTerminator(Region ®ion, Builder &builder, Location loc) {
8270 OpTrait::SingleBlockImplicitTerminator<vector::YieldOp>::Impl<
8271 MaskOp>::ensureTerminator(region, builder, loc);
8277 if (isa<vector::YieldOp>(block.
back()))
8285 OpTrait::SingleBlockImplicitTerminator<vector::YieldOp>::Impl<
8286 MaskOp>::ensureTerminator(region, builder, loc);
8292 Operation *maskedOp = &block.
front();
8293 opBuilder.setInsertionPointToEnd(&block);
8294 vector::YieldOp::create(opBuilder, loc, maskedOp->
getResults());
8297LogicalResult MaskOp::verify() {
8299 Block &block = getMaskRegion().getBlocks().
front();
8301 return emitOpError(
"expects a terminator within the mask region");
8304 if (numMaskRegionOps > 2)
8305 return emitOpError(
"expects only one operation to mask");
8308 auto terminator = dyn_cast<vector::YieldOp>(block.
back());
8310 return emitOpError(
"expects a terminator within the mask region");
8312 if (terminator->getNumOperands() != getNumResults())
8314 "expects number of results to match mask region yielded values");
8317 if (numMaskRegionOps == 1)
8320 auto maskableOp = dyn_cast<MaskableOpInterface>(block.
front());
8322 return emitOpError(
"expects a MaskableOpInterface within the mask region");
8326 return emitOpError(
"expects number of results to match maskable operation "
8327 "number of results");
8329 if (!llvm::equal(maskableOp->
getResults(), terminator.getOperands()))
8330 return emitOpError(
"expects all the results from the MaskableOpInterface "
8331 "to match all the values returned by the terminator");
8333 if (!llvm::equal(maskableOp->
getResultTypes(), getResultTypes()))
8335 "expects result type to match maskable operation result type");
8338 [](Type t) { return llvm::isa<VectorType>(t); }) > 1)
8339 return emitOpError(
"multiple vector results not supported");
8344 dyn_cast<VectorTransferOpInterface>(maskableOp.getOperation());
8345 if (transferOp && transferOp.getMask())
8347 "doesn't expect a mask operand for the masked transfer operation");
8353 isa<VectorType>(transferOp.getShapedType().getElementType()))
8354 return emitOpError(
"does not support masking a transfer operation on a "
8355 "source with vector element type");
8358 Type expectedMaskType = maskableOp.getExpectedMaskType();
8359 if (getMask().
getType() != expectedMaskType)
8360 return emitOpError(
"expects a ")
8361 << expectedMaskType <<
" mask for the maskable operation";
8364 Value passthru = getPassthru();
8366 if (!maskableOp.supportsPassthru())
8368 "doesn't expect a passthru argument for this maskable operation");
8371 return emitOpError(
"expects result when passthru argument is provided");
8374 return emitOpError(
"expects passthru type to match result type");
8394static LogicalResult foldEmptyMaskOp(MaskOp maskOp, MaskOp::FoldAdaptor adaptor,
8395 SmallVectorImpl<OpFoldResult> &results) {
8396 if (!maskOp.isEmpty() || maskOp.hasPassthru())
8399 Block *block = maskOp.getMaskBlock();
8400 auto terminator = cast<vector::YieldOp>(block->
front());
8401 if (terminator.getNumOperands() == 0)
8405 llvm::append_range(results, terminator.getOperands());
8409LogicalResult MaskOp::fold(FoldAdaptor adaptor,
8410 SmallVectorImpl<OpFoldResult> &results) {
8411 if (succeeded(foldEmptyMaskOp(*
this, adaptor, results)))
8421 Operation *maskableOp = getMaskableOp();
8427 llvm::append_range(results, maskableOp->
getResults());
8443class CanonializeEmptyMaskOp :
public OpRewritePattern<MaskOp> {
8446 LogicalResult matchAndRewrite(MaskOp maskOp,
8447 PatternRewriter &rewriter)
const override {
8448 if (!maskOp.isEmpty())
8451 if (!maskOp.hasPassthru())
8458 VectorType maskType = maskOp.getMask().getType();
8459 for (Type resultType : maskOp.getResultTypes()) {
8460 auto vecResultType = dyn_cast<VectorType>(resultType);
8461 if (!vecResultType || vecResultType.getShape() != maskType.getShape())
8465 Block *block = maskOp.getMaskBlock();
8466 auto terminator = cast<vector::YieldOp>(block->
front());
8467 assert(terminator.getNumOperands() == 1 &&
8468 "expected one result when passthru is provided");
8471 maskOp, maskOp.getResultTypes(), maskOp.getMask(),
8472 terminator.getOperand(0), maskOp.getPassthru());
8478void MaskOp::getCanonicalizationPatterns(RewritePatternSet &results,
8479 MLIRContext *context) {
8480 results.
add<CanonializeEmptyMaskOp>(context);
8486Operation *MaskOp::getMaskableOp() {
8487 Block *block = getMaskBlock();
8491 return &block->
front();
8495bool MaskOp::hasPassthru() {
return getPassthru() != Value(); }
8501LogicalResult ScanOp::verify() {
8502 VectorType srcType = getSourceType();
8503 VectorType initialType = getInitialValueType();
8505 int64_t srcRank = srcType.getRank();
8506 int64_t reductionDim = getReductionDim();
8507 if (reductionDim >= srcRank)
8508 return emitOpError(
"reduction dimension ")
8509 << reductionDim <<
" has to be less than " << srcRank;
8512 int64_t initialValueRank = initialType.getRank();
8513 if (initialValueRank != srcRank - 1)
8514 return emitOpError(
"initial value rank ")
8515 << initialValueRank <<
" has to be equal to " << srcRank - 1;
8518 ArrayRef<int64_t> srcShape = srcType.getShape();
8519 ArrayRef<int64_t> initialValueShapes = initialType.getShape();
8520 SmallVector<int64_t> expectedShape;
8521 for (
int i = 0; i < srcRank; i++) {
8522 if (i != reductionDim)
8523 expectedShape.push_back(srcShape[i]);
8525 if (!llvm::equal(initialValueShapes, expectedShape)) {
8526 return emitOpError(
"incompatible input/initial value shapes");
8530 Type eltType = getDestType().getElementType();
8532 return emitOpError(
"unsupported reduction type ")
8533 << eltType <<
" for kind '" << stringifyCombiningKind(getKind())
8540 RewritePatternSet &patterns, PatternBenefit benefit) {
8542 .
add<CreateMaskFolder, MaskedLoadFolder, MaskedStoreFolder, GatherFolder,
8543 ScatterFolder, ExpandLoadFolder, CompressStoreFolder,
8544 StridedSliceConstantMaskFolder, TransposeFolder>(
8549 CombiningKind kind, Value v1, Value acc,
8550 arith::FastMathFlagsAttr fastmath,
8557 case CombiningKind::ADD:
8559 result =
b.createOrFold<arith::AddIOp>(loc, v1, acc);
8560 else if (llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc))
8561 result =
b.createOrFold<arith::AddFOp>(loc, v1, acc, fastmath);
8563 llvm_unreachable(
"invalid value types for ADD reduction");
8565 case CombiningKind::AND:
8567 result =
b.createOrFold<arith::AndIOp>(loc, v1, acc);
8569 case CombiningKind::MAXNUMF:
8570 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8571 "expected float values");
8572 result =
b.createOrFold<arith::MaxNumFOp>(loc, v1, acc, fastmath);
8574 case CombiningKind::MAXIMUMNUMF:
8575 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8576 "expected float values");
8577 result =
b.createOrFold<arith::MaximumNumFOp>(loc, v1, acc, fastmath);
8579 case CombiningKind::MAXIMUMF:
8580 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8581 "expected float values");
8582 result =
b.createOrFold<arith::MaximumFOp>(loc, v1, acc, fastmath);
8584 case CombiningKind::MINNUMF:
8585 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8586 "expected float values");
8587 result =
b.createOrFold<arith::MinNumFOp>(loc, v1, acc, fastmath);
8589 case CombiningKind::MINIMUMNUMF:
8590 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8591 "expected float values");
8592 result =
b.createOrFold<arith::MinimumNumFOp>(loc, v1, acc, fastmath);
8594 case CombiningKind::MINIMUMF:
8595 assert(llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc) &&
8596 "expected float values");
8597 result =
b.createOrFold<arith::MinimumFOp>(loc, v1, acc, fastmath);
8599 case CombiningKind::MAXSI:
8601 result =
b.createOrFold<arith::MaxSIOp>(loc, v1, acc);
8603 case CombiningKind::MINSI:
8605 result =
b.createOrFold<arith::MinSIOp>(loc, v1, acc);
8607 case CombiningKind::MAXUI:
8609 result =
b.createOrFold<arith::MaxUIOp>(loc, v1, acc);
8611 case CombiningKind::MINUI:
8613 result =
b.createOrFold<arith::MinUIOp>(loc, v1, acc);
8615 case CombiningKind::MUL:
8617 result =
b.createOrFold<arith::MulIOp>(loc, v1, acc);
8618 else if (llvm::isa<FloatType>(t1) && llvm::isa<FloatType>(tAcc))
8619 result =
b.createOrFold<arith::MulFOp>(loc, v1, acc, fastmath);
8621 llvm_unreachable(
"invalid value types for MUL reduction");
8623 case CombiningKind::OR:
8625 result =
b.createOrFold<arith::OrIOp>(loc, v1, acc);
8627 case CombiningKind::XOR:
8629 result =
b.createOrFold<arith::XOrIOp>(loc, v1, acc);
8633 assert(
result &&
"unknown CombiningKind");
8641void StepOp::inferResultRanges(ArrayRef<ConstantIntRanges> argRanges,
8643 auto resultType = cast<VectorType>(
getType());
8644 if (resultType.isScalable()) {
8650 uint64_t maxIndex = resultType.getDimSize(0) - 1;
8651 APInt umin = APInt::getZero(bitwidth);
8652 APInt umax = APInt::getMaxValue(bitwidth).ugt(maxIndex)
8653 ? APInt(bitwidth, maxIndex)
8654 : APInt::getMaxValue(bitwidth);
8658std::optional<SmallVector<int64_t>> StepOp::getDefaultUnrollTargetShape() {
8659 return SmallVector<int64_t>{8};
8689struct StepCompareFolder :
public OpRewritePattern<StepOp> {
8692 LogicalResult matchAndRewrite(StepOp stepOp,
8693 PatternRewriter &rewriter)
const override {
8694 const int64_t stepSize = stepOp.getResult().getType().getNumElements();
8696 for (OpOperand &use : stepOp.getResult().getUses()) {
8697 auto cmpiOp = dyn_cast<arith::CmpIOp>(use.getOwner());
8702 const unsigned stepOperandNumber = use.getOperandNumber();
8703 if (stepOperandNumber != 0)
8707 unsigned constOperandNumber = 1;
8708 Value otherOperand = cmpiOp.getOperand(constOperandNumber);
8709 std::optional<int64_t> maybeConstValue =
8711 if (!maybeConstValue.has_value())
8714 int64_t constValue = maybeConstValue.value();
8715 arith::CmpIPredicate pred = cmpiOp.getPredicate();
8717 auto maybeSplat = [&]() -> std::optional<bool> {
8719 if ((pred == arith::CmpIPredicate::ult ||
8720 pred == arith::CmpIPredicate::uge) &&
8721 stepSize <= constValue)
8722 return pred == arith::CmpIPredicate::ult;
8725 if ((pred == arith::CmpIPredicate::ule ||
8726 pred == arith::CmpIPredicate::ugt) &&
8727 stepSize - 1 <= constValue) {
8728 return pred == arith::CmpIPredicate::ule;
8732 if ((pred == arith::CmpIPredicate::eq ||
8733 pred == arith::CmpIPredicate::ne) &&
8734 stepSize <= constValue)
8735 return pred == arith::CmpIPredicate::ne;
8737 return std::nullopt;
8740 if (!maybeSplat.has_value())
8745 auto type = dyn_cast<VectorType>(cmpiOp.getResult().getType());
8750 Value splat = mlir::arith::ConstantOp::create(rewriter, cmpiOp.getLoc(),
8762void StepOp::getCanonicalizationPatterns(RewritePatternSet &results,
8763 MLIRContext *context) {
8764 results.
add<StepCompareFolder>(context);
8774 Operation *maskableOp) {
8775 assert(maskableOp->
getBlock() &&
"MaskableOp must be inserted into a block");
8787 Operation *maskableOp, Value mask,
8792 return MaskOp::create(builder, maskableOp->
getLoc(),
8795 return MaskOp::create(builder, maskableOp->
getLoc(),
8808 Value newValue, Value passthru) {
8812 return arith::SelectOp::create(builder, newValue.
getLoc(), newValue.
getType(),
8813 mask, newValue, passthru);
8824struct InterleaveDeinterleaveFolder :
public OpRewritePattern<InterleaveOp> {
8827 LogicalResult matchAndRewrite(InterleaveOp interleaveOp,
8828 PatternRewriter &rewriter)
const override {
8829 auto lhsDefOp = interleaveOp.getLhs().getDefiningOp<DeinterleaveOp>();
8830 auto rhsDefOp = interleaveOp.getRhs().getDefiningOp<DeinterleaveOp>();
8831 if (!lhsDefOp || !rhsDefOp || lhsDefOp != rhsDefOp)
8833 for (
auto [idx, operand] : llvm::enumerate(interleaveOp.getOperands())) {
8834 if (cast<OpResult>(operand).getResultNumber() != idx)
8837 rewriter.
replaceOp(interleaveOp, lhsDefOp.getSource());
8843void InterleaveOp::getCanonicalizationPatterns(RewritePatternSet &results,
8844 MLIRContext *context) {
8845 results.
add<InterleaveDeinterleaveFolder>(context);
8848OpFoldResult InterleaveOp::fold(FoldAdaptor adaptor) {
8850 auto splat = dyn_cast_if_present<SplatElementsAttr>(adaptor.getLhs());
8851 if (!splat || adaptor.getLhs() != adaptor.getRhs())
8853 return SplatElementsAttr::get(getResultVectorType(),
8854 splat.getSplatValue<Attribute>());
8860std::optional<SmallVector<int64_t, 4>>
8861InterleaveOp::getIterationShapeToUnroll() {
8862 return llvm::to_vector<4>(getResultVectorType().
getShape());
8865std::optional<SmallVector<int64_t>>
8866InterleaveOp::getDefaultUnrollTargetShape() {
8877std::optional<SmallVector<int64_t, 4>>
8878DeinterleaveOp::getIterationShapeToUnroll() {
8879 return llvm::to_vector<4>(getResultVectorType().
getShape());
8881std::optional<SmallVector<int64_t>>
8882DeinterleaveOp::getDefaultUnrollTargetShape() {
8892struct SelectBroadcastCondition : OpRewritePattern<arith::SelectOp> {
8895 LogicalResult matchAndRewrite(arith::SelectOp select,
8896 PatternRewriter &rewriter)
const override {
8901 select.getConditionMutable().assign(
broadcast.getSource());
8908void VectorDialect::getCanonicalizationPatterns(
8909 RewritePatternSet &results)
const {
8917#define GET_ATTRDEF_CLASSES
8918#include "mlir/Dialect/Vector/IR/VectorAttributes.cpp.inc"
8920#define GET_OP_CLASSES
8921#include "mlir/Dialect/Vector/IR/VectorOps.cpp.inc"
static LogicalResult extractStrides(AffineExpr e, AffineExpr multiplicativeFactor, MutableArrayRef< AffineExpr > strides, AffineExpr &offset)
Takes a single AffineExpr e and populates the strides array with the strides expressions for each dim...
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static Value getBase(Value v)
Looks through known "view-like" ops to find the base memref.
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
static SmallVector< unsigned > extractPosition(ArrayRef< int64_t > indices)
Convert the value of a DenseI64ArrayAttr to a vector of unsigned indices.
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static ParseResult parseBoolAttr(OpAsmParser &parser, BoolAttr &result)
static void printBoolAttr(OpAsmPrinter &printer, Operation *, BoolAttr attr)
static std::optional< VectorShape > vectorShape(Type type)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static void contract(RootOrderingGraph &graph, ArrayRef< Value > cycle, const DenseMap< Value, unsigned > &parentDepths, DenseMap< Value, Value > &actualSource, DenseMap< Value, Value > &actualTarget)
Contracts the specified cycle in the given graph in-place.
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
static Value broadcast(Location loc, Value toBroadcast, unsigned numElements, const TypeConverter &typeConverter, ConversionPatternRewriter &rewriter)
Broadcasts the value to vector with numElements number of elements.
static VectorType getVectorType(Type scalarTy, const VectorizationStrategy *strategy)
Returns the vector type resulting from applying the provided vectorization strategy on the scalar typ...
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
static VectorType trimLeadingUnitDims(VectorType oldType, bool trimOnlyOneDim=false, bool allowRank0=false)
static MaskFormat getMaskFormat(Value mask)
Helper method to classify a mask value.
static OpFoldResult foldShuffleIdentityMask(ShuffleOp op)
Fold shuffle V1, V2, [0, 1, 2, 3] : <4xi32>, <2xi32> -> V1.
static LogicalResult foldExtractOpFromExtractChain(ExtractOp extractOp)
Fold the result of chains of ExtractOp in place by simply concatenating the positions.
static OpFoldResult foldFromElementsToElements(FromElementsOp fromElementsOp)
Folds vector.from_elements(vector.to_elements(vector)) into vector.
static bool hasZeroDimVectors(Operation *op)
Returns true if the operation has a 0-D vector type operand or result.
static void printTransferAttrs(OpAsmPrinter &p, VectorTransferOpInterface op)
static Value foldScalarExtractFromFromElements(ExtractOp extractOp)
Try to fold the extraction of a scalar from a vector defined by vector.from_elements.
static Attribute convertNumericAttr(Attribute attr, Type expectedType)
Converts numeric attributes to the expected type.
static Value foldExtractFromExtractStrided(ExtractOp extractOp)
Fold an ExtractOp from ExtractStridedSliceOp.
static llvm::SetVector< int64_t > computeBroadcastedUnitDims(ArrayRef< int64_t > srcShape, ArrayRef< int64_t > dstShape)
Return the dimensions of the result vector that were formerly ones in the source tensor and thus corr...
static Value foldExtractFromBroadcast(ExtractOp extractOp)
Fold extract(broadcast(X)) to either extract(X) or just X.
static LogicalResult foldToElementsFromElements(ToElementsOp toElementsOp, SmallVectorImpl< OpFoldResult > &results)
Folds vector.to_elements(vector.from_elements(e0, e1, ...)) into (e0, e1, ...).
static Attribute foldPoisonSrcExtractOp(Attribute srcAttr)
Fold a vector extract from is a poison source.
static std::optional< int64_t > getOneSidedReductionDim(vector::ContractionOp *contract)
static LogicalResult foldBroadcastOfShapeCast(BroadcastOp broadcastOp)
static OpFoldResult foldShufflePoisonInputs(MLIRContext *context, Attribute v1Attr, Attribute v2Attr)
Fold shuffle poison, poison -> poison.
static bool isSupportedCombiningKind(CombiningKind combiningKind, Type elementType)
static Attribute foldPoisonIndexInsertExtractOp(MLIRContext *context, ArrayRef< int64_t > staticPos, int64_t poisonVal)
Fold an insert or extract operation into an poison value when a poison index is found at any dimensio...
MaskFormat
Helper enum to classify mask value.
static ArrayAttr makeI64ArrayAttr(ArrayRef< int64_t > values, MLIRContext *context)
static unsigned getEffectiveVectorRankForXferOp(ShapedType shapedType, VectorType vectorType)
Returns the effective rank of the vector to read/write for Xfer Ops.
static OpFoldResult foldFromElementsToConstant(FromElementsOp fromElementsOp, ArrayRef< Attribute > elements)
Fold vector.from_elements to a constant when all operands are constants.
static LogicalResult incSlicePosition(MutableArrayRef< int64_t > position, ArrayRef< int64_t > shape, ArrayRef< int64_t > offsets)
static Value extractInsertFoldConstantOp(OpType op, AdaptorType adaptor, SmallVectorImpl< Value > &operands)
If the dynamic indices of extractOp or insertOp are in fact constants, then fold it.
static LogicalResult foldToElementsOfBroadcast(ToElementsOp toElementsOp, SmallVectorImpl< OpFoldResult > &results)
Folds vector.to_elements(vector.broadcast(x)) for the scalar case only.
static bool isStepIndexArray(ArrayRef< T > idxArr, uint64_t begin, size_t width)
static LogicalResult isIntegerArrayAttrConfinedToRange(OpType op, ArrayAttr arrayAttr, int64_t min, int64_t max, StringRef attrName, bool halfOpen=true)
static bool haveSameDefiningOp(OperandRange operands, Operation *defOp)
Returns true if all the operands are defined by defOp.
static int64_t getResultIndex(AffineMap map, AffineExpr targetExpr)
static LogicalResult isIntegerArrayAttrConfinedToShape(OpType op, ArrayAttr arrayAttr, ArrayRef< int64_t > shape, StringRef attrName, bool halfOpen=true, int64_t min=0)
static bool isSplatWriteConsistentWithMaskedRead(vector::TransferWriteOp write, vector::TransferReadOp read)
Check if write is of a constant splat and the masked read is padded with the same splat value – meani...
static LogicalResult isSumOfIntegerArrayAttrConfinedToShape(OpType op, ArrayAttr arrayAttr1, ArrayAttr arrayAttr2, ArrayRef< int64_t > shape, StringRef attrName1, StringRef attrName2, bool halfOpen=true, int64_t min=1)
static Attribute foldDenseElementsAttrDestInsertOp(InsertOp insertOp, Attribute srcAttr, Attribute dstAttr, int64_t maxVectorSizeFoldThreshold)
static LogicalResult foldTransferFullMask(TransferOp op)
static SmallVector< IntType > extractVector(ArrayAttr arrayAttr)
static bool isValidPositiveIndexOrPoison(int64_t index, int64_t poisonValue, int64_t maxIndex)
static OpFoldResult foldShuffleConstantInputs(ShuffleOp op, Attribute v1Attr, Attribute v2Attr)
Fold a shuffle of constant 1-D inputs by evaluating the mask.
static OpFoldResult foldExtractStridedSliceNonSplatConstant(ExtractStridedSliceOp op, Attribute foldInput)
static LogicalResult verifyPermutationMap(AffineMap permutationMap, EmitFun emitOpError)
static std::optional< SmallVector< int64_t > > getDefaultTargetMaskShapeForUnroll()
static LogicalResult rewriteFromElementsAsBroadcast(FromElementsOp fromElementsOp, PatternRewriter &rewriter)
Rewrite vector.from_elements as vector.broadcast if the elements are the same.
static Value foldInsertUseChain(InsertOp insertOp)
Folder to replace the dest operand of the insert op with the root dest of the insert op use chain.
static bool isBroadcastLike(Operation *op)
All BroadcastOps, as well as ShapeCastOps that only prepend 1s, are considered to be 'broadcastlike'.
static LogicalResult isIntegerArrayAttrSmallerThanShape(OpType op, ArrayAttr arrayAttr, ArrayRef< int64_t > shape, StringRef attrName)
static Value foldExtractFromShapeCast(ExtractOp extractOp)
static LogicalResult verifyTransferOp(VectorTransferOpInterface op, ShapedType shapedType, VectorType vectorType, VectorType maskType, VectorType inferredMaskType, AffineMap permutationMap, ArrayAttr inBounds)
static bool isInBounds(TransferOp op, int64_t resultIdx, int64_t indicesIdx)
static LogicalResult verifyOutputShape(ContractionOp op, VectorType lhsType, VectorType rhsType, Type accType, Type resType, const std::vector< std::pair< int64_t, int64_t > > &contractingDimMap, const std::vector< std::pair< int64_t, int64_t > > &batchDimMap)
static bool verifyDimMap(VectorType lhsType, VectorType rhsType, const std::vector< std::pair< int64_t, int64_t > > &map)
static Type inferStridedSliceOpResultType(VectorType vectorType, ArrayAttr offsets, ArrayAttr sizes, ArrayAttr strides)
static OpFoldResult foldShufflePoisonOperandToMask(ShuffleOp op)
If a shuffle operand is poison, replace all mask indices that reference it with kPoisonIndex.
static LogicalResult foldSize1TransferPermutationMap(TransferOp op)
When the vector type is vector<1xT>, the permutation map is irrelevant: the single vector lane always...
static std::optional< SmallVector< int64_t > > getDefaultTargetInterleaveShapeForUnroll()
static Value foldExtractFromShuffle(ExtractOp extractOp)
Fold extractOp coming from ShuffleOp.
static LogicalResult foldTransferInBoundsAttribute(TransferOp op)
static Value foldExtractStridedOpFromInsertChain(ExtractOp extractOp)
Fold extract_op fed from a chain of insertStridedSlice ops.
static int64_t calculateInsertPosition(VectorType destTy, ArrayRef< int64_t > positions)
static std::vector< std::pair< int64_t, int64_t > > getDimPairForIterTy(ContractionOp *contract, IteratorType targetIteratorType, bool oneSidedDim=false)
static Attribute foldDenseElementsAttrSrcExtractOp(ExtractOp extractOp, Attribute srcAttr)
Fold a vector extract extracting from a DenseElementsAttr.
static void populateFromInt64AttrArray(ArrayAttr arrayAttr, SmallVectorImpl< int64_t > &results)
Rewrite from_elements on multiple scalar extracts as a shape_cast on a single extract.
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
static AffineMap getMinorIdentityMap(unsigned dims, unsigned results, MLIRContext *context)
Returns an identity affine map (d0, ..., dn) -> (dp, ..., dn) on the most minor dimensions.
MLIRContext * getContext() const
bool isFunctionOfDim(unsigned position) const
Return true if any affine expression involves AffineDimExpr position.
bool isMinorIdentity() const
Returns true if this affine map is a minor identity, i.e.
unsigned getDimPosition(unsigned idx) const
Extracts the position of the dimensional expression at the given result, when the caller knows it is ...
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
bool isProjectedPermutation(bool allowZeroInResults=false) const
Returns true if the AffineMap represents a subset (i.e.
unsigned getNumSymbols() const
unsigned getNumDims() const
ArrayRef< AffineExpr > getResults() const
unsigned getNumResults() const
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
unsigned getNumInputs() const
AffineExpr getResult(unsigned idx) const
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
SmallVector< unsigned > getBroadcastDims() const
Returns the list of broadcast dimensions (i.e.
AffineMap compose(AffineMap map) const
Returns the AffineMap resulting from composing this with map.
@ Square
Square brackets surrounding zero or more operands.
virtual ParseResult parseColonTypeList(SmallVectorImpl< Type > &result)=0
Parse a colon followed by a type list, which must have at least one type.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
ParseResult parseKeywordType(const char *keyword, Type &result)
Parse a keyword followed by a type.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual void printAttribute(Attribute attr)
Base storage class appearing in an attribute.
Attributes are known-constant values of operations.
Dialect & getDialect() const
Get the dialect this attribute is registered to.
OpListType & getOperations()
static BoolAttr get(MLIRContext *context, bool value)
This class is a general helper class for creating context-global objects like types,...
IntegerAttr getIndexAttr(int64_t value)
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
IntegerAttr getIntegerAttr(Type type, int64_t value)
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
IntegerAttr getI64IntegerAttr(int64_t value)
IntegerType getIntegerType(unsigned width)
TypedAttr getZeroAttr(Type type)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
MLIRContext * getContext() const
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
ArrayAttr getBoolArrayAttr(ArrayRef< bool > values)
ArrayAttr getAffineMapArrayAttr(ArrayRef< AffineMap > values)
static ConstantIntRanges fromUnsigned(const APInt &umin, const APInt &umax)
Create an ConstantIntRanges with the unsigned minimum and maximum equal to umin and umax and the sign...
static unsigned getStorageBitwidth(Type type)
Return the bitwidth that should be used for integer ranges describing type.
The main mechanism for performing data layout queries.
static DataLayout closest(Operation *op)
Returns the layout of the closest parent operation carrying layout info.
llvm::TypeSize getTypeSizeInBits(Type t) const
Returns the size in bits of the given type in the current scope.
An attribute that represents a reference to a dense vector or tensor object.
std::enable_if_t<!std::is_base_of< Attribute, T >::value||std::is_same< Attribute, T >::value, T > getSplatValue() const
Return the splat value for this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
This is a utility class for mapping one set of IR entities to another.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
ParseResult parseTrailingOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None)
Parse zero or more trailing SSA comma-separated trailing operand references with a specified surround...
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printCustomOrGenericOp(Operation *op)=0
Prints the entire operation with the custom assembly form, if available, or the generic assembly form...
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Block * getInsertionBlock() const
Return the block the current insertion point belongs to.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
This class represents a single result from folding an operation.
This class implements the operand iterators for the Operation class.
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
void dropAllUses()
Drop all uses of results of this operation.
void setOperand(unsigned idx, Value value)
Block * getBlock()
Returns the operation block that contains this operation.
Location getLoc()
The source location the operation was defined or derived from.
operand_type_range getOperandTypes()
result_type_range getResultTypes()
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
result_range getResults()
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
T * allocate()
Allocate an instance of the provided type.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
static FailureOr< bool > areEqual(const Variable &var1, const Variable &var2)
Compute whether the given variables are equal.
static FailureOr< int64_t > computeConstantDelta(Value value1, Value value2, std::optional< int64_t > dim1=std::nullopt, std::optional< int64_t > dim2=std::nullopt)
Compute a constant delta between the given two values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
This is a builder type that keeps local references to arguments.
Builder & setElementType(Type newElementType)
Specialization of arith.constant op that returns an integer of index type.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto Speculatable
constexpr auto NotSpeculatable
FailureOr< int64_t > fullyComposeAndComputeConstantDelta(Value value1, Value value2)
Compute a constant delta of the given two values.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
FailureOr< std::optional< SmallVector< Value > > > bubbleDownInPlaceMemorySpaceCastImpl(OpOperand &operand, ValueRange results)
Tries to bubble-down inplace a MemorySpaceCastOpInterface operation referenced by operand.
bool hasNegativeStaticStride(MemRefType memRefTy)
Returns true if any stride of memRefTy is statically known to be negative.
LogicalResult foldMemRefCast(Operation *op, Value inner=nullptr)
This is a common utility used for patterns of the form "someop(memref.cast) -> someop".
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
MemRefType getMemRefType(T &&t)
Convenience method to abbreviate casting getType().
LogicalResult foldTensorCast(Operation *op)
Performs folding of any operand of op if it comes from a tensor::CastOp that can be folded.
detail::poison_attr_matcher m_Poison()
Matches a poison constant (any attribute implementing PoisonAttrInterface).
Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, Value v1, Value acc, arith::FastMathFlagsAttr fastmath=nullptr, Value mask=nullptr)
Returns the result value of reducing two scalar/vector values with the corresponding arith operation.
ArrayAttr getVectorSubscriptAttr(Builder &b, ArrayRef< int64_t > values)
Returns an integer array attribute containing the given values using the integer type required for su...
Operation * maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, Value passthru=Value())
Creates a vector.mask operation around a maskable operation.
void buildTerminatedBody(OpBuilder &builder, Location loc)
Default callback to build a region with a 'vector.yield' terminator with no arguments.
std::optional< int64_t > getConstantVscaleMultiplier(Value value)
If value is a constant multiple of vector.vscale (e.g.
AffineMap getTransferMinorIdentityMap(ShapedType shapedType, VectorType vectorType)
Build the default minor identity map suitable for a vector transfer.
bool checkSameValueRAW(TransferWriteOp defWrite, TransferReadOp read)
Return true if the transfer_write fully writes the data accessed by the transfer_read.
ConstantMaskKind
Predefined constant_mask kinds.
BroadcastableToResult isBroadcastableTo(Type srcType, VectorType dstVectorType, std::pair< VectorDim, VectorDim > *mismatchingDims=nullptr)
Return whether srcType can be broadcast to dstVectorType under the semantics of the vector....
VectorType inferTransferOpMaskType(VectorType vecType, AffineMap permMap)
Infers the mask type for a transfer op given its vector type and permutation map.
Value selectPassthru(OpBuilder &builder, Value mask, Value newValue, Value passthru)
Creates a vector select operation that picks values from newValue or passthru for each result vector ...
bool isDisjointTransferIndices(VectorTransferOpInterface transferA, VectorTransferOpInterface transferB, bool testDynamicValueUsingBounds=false)
Return true if we can prove that the transfer operations access disjoint memory, without requring the...
bool isDisjointTransferSet(VectorTransferOpInterface transferA, VectorTransferOpInterface transferB, bool testDynamicValueUsingBounds=false)
Return true if we can prove that the transfer operations access disjoint memory, requiring the operat...
bool checkSameValueWAW(TransferWriteOp write, TransferWriteOp priorWrite)
Return true if the write op fully over-write the priorWrite transfer_write op.
SmallVector< int64_t > getAsIntegers(ArrayRef< Value > values)
Returns the integer numbers in values.
void populateVectorToVectorCanonicalizationPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of vector-to-vector canonicalization patterns.
bool isValidLoadStoreMemRefLayout(VectorType vecTy, MemRefType memRefTy)
Returns true if memRefTy has a valid layout for a vector.load/store of vecTy: the most minor memref d...
void createMaskOpRegion(OpBuilder &builder, Operation *maskableOp)
Create the vector.yield-ended region of a vector.mask op with maskableOp as masked operation.
SmallVector< Value > getAsValues(OpBuilder &builder, Location loc, ArrayRef< OpFoldResult > foldResults)
Convert foldResults into Values.
Value getVectorReductionOp(arith::AtomicRMWKind op, OpBuilder &builder, Location loc, Value vector)
Returns the value obtained by reducing the vector into a scalar using the operation kind associated w...
BroadcastableToResult
Models whether srcType can be broadcast to dstVectorType under the semantics of the vector....
IntegerType getVectorSubscriptType(Builder &builder)
Returns the integer type required for subscripts in the vector dialect.
Include the generated interface declarations.
AffineMap simplifyAffineMap(AffineMap map)
Simplifies an affine map by simplifying its underlying AffineExpr results.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
llvm::function_ref< void(Value, const ConstantIntRanges &)> SetIntRangeFn
The type of the setResultRanges callback provided to ops implementing InferIntRangeInterface.
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
bool isEqualConstantIntOrValue(OpFoldResult ofr1, OpFoldResult ofr2)
Return true if ofr1 and ofr2 are the same integer constant attribute values or the same SSA value.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
SmallVector< T > applyPermutation(ArrayRef< T > input, ArrayRef< int64_t > permutation)
SmallVector< int64_t > delinearize(int64_t linearIndex, ArrayRef< int64_t > strides)
Given the strides together with a linear index in the dimension space, return the vector-space offset...
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
AffineMap inversePermutation(AffineMap map)
Returns a map of codomain to domain dimensions such that the first codomain dimension for a particula...
StorageUniquer::StorageAllocator AttributeStorageAllocator
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
SmallVector< int64_t > getI64SubArray(ArrayAttr arrayAttr, unsigned dropFront=0, unsigned dropBack=0)
Helper to return a subset of arrayAttr as a vector of int64_t.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
AffineMap compressUnusedDims(AffineMap map)
Drop the dims that are not used.
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
LogicalResult verifyElementTypesMatch(Operation *op, ShapedType lhs, ShapedType rhs, StringRef lhsName, StringRef rhsName)
Verify that two shaped types have matching element types.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
SmallVector< T > applyPermutationMap(AffineMap map, llvm::ArrayRef< T > source)
Apply a permutation from map to source and return the result.
llvm::SmallBitVector getUnusedDimsBitVector(ArrayRef< AffineMap > maps)
int64_t linearize(ArrayRef< int64_t > offsets, ArrayRef< int64_t > basis)
Return the linearized index of 'offsets' w.r.t.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
void applyPermutationToVector(SmallVector< T, N > &inVec, ArrayRef< int64_t > permutation)
Apply the permutation defined by permutation to inVec.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
llvm::function_ref< Fn > function_ref
std::pair< SmallVector< int64_t >, SmallVector< Value > > decomposeMixedValues(ArrayRef< OpFoldResult > mixedValues)
Decompose a vector of mixed static or dynamic values into the corresponding pair of arrays.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
Return a fused vector::ContractionOp which represents a patterns such as:
LogicalResult matchAndRewrite(AddOpType addOp, PatternRewriter &rewriter) const override
Canonicalize vector.to_elements(vector.broadcast(v)) where v is a vector.
LogicalResult matchAndRewrite(ToElementsOp toElementsOp, PatternRewriter &rewriter) const override
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern Base
Type alias to allow derived classes to inherit constructors with using Base::Base;.
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This represents an operation in an abstracted form, suitable for use with the builder APIs.
static BitmaskEnumStorage * construct(AttributeStorageAllocator &allocator, const KeyTy &key)
bool operator==(const KeyTy &key) const
BitmaskEnumStorage(KeyTy val)