21#include "llvm/ADT/SmallVectorExtras.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/SmallVectorExtras.h"
30#define DEBUG_TYPE "vector-transfer-split"
38 VectorTransferOpInterface xferOp) {
39 assert(xferOp.getPermutationMap().isMinorIdentity() &&
40 "Expected minor identity map");
42 xferOp.zipResultAndIndexing([&](
int64_t resultIdx,
int64_t indicesIdx) {
46 if (xferOp.isDimInBounds(resultIdx))
50 int64_t vectorSize = xferOp.getVectorType().getDimSize(resultIdx);
52 b, loc,
b.getAffineDimExpr(0) +
b.getAffineConstantExpr(vectorSize),
53 {xferOp.getIndices()[indicesIdx]});
58 if (maybeCstSum && maybeCstDimSz && *maybeCstSum <= *maybeCstDimSz)
61 arith::CmpIOp::create(
b, loc, arith::CmpIPredicate::sle,
66 inBoundsCond = arith::AndIOp::create(
b, loc, inBoundsCond, cond);
107splitFullAndPartialTransferPrecondition(VectorTransferOpInterface xferOp) {
109 if (xferOp.getTransferRank() == 0)
113 if (!xferOp.getPermutationMap().isMinorIdentity())
116 if (!xferOp.hasOutOfBoundsDim())
121 if (isa<scf::IfOp>(xferOp->getParentOp()))
124 if (cast<vector::MaskableOpInterface>(xferOp.getOperation()).isMasked())
138static MemRefType getCastCompatibleMemRefType(MemRefType aT, MemRefType bT) {
139 if (memref::CastOp::areCastCompatible(aT, bT))
141 if (aT.getRank() != bT.getRank())
145 if (
failed(aT.getStridesAndOffset(aStrides, aOffset)) ||
146 failed(bT.getStridesAndOffset(bStrides, bOffset)) ||
147 aStrides.size() != bStrides.size())
153 resStrides(bT.getRank(), 0);
154 for (
int64_t idx = 0, e = aT.getRank(); idx < e; ++idx) {
156 (aShape[idx] == bShape[idx]) ? aShape[idx] : ShapedType::kDynamic;
158 (aStrides[idx] == bStrides[idx]) ? aStrides[idx] : ShapedType::kDynamic;
160 resOffset = (aOffset == bOffset) ? aOffset : ShapedType::kDynamic;
161 return MemRefType::get(
162 resShape, aT.getElementType(),
163 StridedLayoutAttr::get(aT.getContext(), resOffset, resStrides));
170 MemRefType compatibleMemRefType) {
171 MemRefType sourceType = cast<MemRefType>(
memref.getType());
173 if (sourceType.getMemorySpace() != compatibleMemRefType.getMemorySpace()) {
174 sourceType = MemRefType::get(
175 sourceType.getShape(), sourceType.getElementType(),
176 sourceType.getLayout(), compatibleMemRefType.getMemorySpace());
178 memref::MemorySpaceCastOp::create(
b,
memref.getLoc(), sourceType, res);
180 if (sourceType == compatibleMemRefType)
182 return memref::CastOp::create(
b,
memref.getLoc(), compatibleMemRefType, res);
188static std::pair<Value, Value>
189createSubViewIntersection(
RewriterBase &
b, VectorTransferOpInterface xferOp,
192 int64_t memrefRank = xferOp.getShapedType().getRank();
194 assert(memrefRank == cast<MemRefType>(alloc.
getType()).getRank() &&
195 "Expected memref rank to match the alloc rank");
197 xferOp.getIndices().take_front(xferOp.getLeadingShapedRank());
199 sizes.append(leadingIndices.begin(), leadingIndices.end());
200 auto isaWrite = isa<vector::TransferWriteOp>(xferOp);
201 xferOp.zipResultAndIndexing([&](
int64_t resultIdx,
int64_t indicesIdx) {
204 memref::DimOp::create(
b, xferOp.getLoc(), xferOp.getBase(), indicesIdx);
205 Value dimAlloc = memref::DimOp::create(
b, loc, alloc, resultIdx);
206 Value index = xferOp.getIndices()[indicesIdx];
213 affine::AffineMinOp::create(
b, loc,
index.getType(), maps[0],
215 sizes.push_back(affineMin);
222 auto copySrc = memref::SubViewOp::create(
223 b, loc, isaWrite ? alloc : xferOp.getBase(), srcIndices, sizes, strides);
224 auto copyDest = memref::SubViewOp::create(
225 b, loc, isaWrite ? xferOp.getBase() : alloc, destIndices, sizes, strides);
226 return std::make_pair(copySrc, copyDest);
251createFullPartialMemRefCopy(
RewriterBase &
b, vector::TransferReadOp xferOp,
253 MemRefType compatibleMemRefType,
Value alloc) {
257 return scf::IfOp::create(
258 b, loc, inBoundsCond,
260 Value res = castToCompatibleMemRefType(
b,
memref, compatibleMemRefType);
262 llvm::append_range(viewAndIndices, xferOp.getIndices());
263 scf::YieldOp::create(
b, loc, viewAndIndices);
268 Value padding = vector::BroadcastOp::create(
269 b, loc, xferOp.getVectorType(), xferOp.getPadding());
270 memref::StoreOp::create(
272 vector::TypeCastOp::create(
273 b, loc, MemRefType::get({}, padding.
getType()), alloc));
277 std::pair<Value, Value> copyArgs = createSubViewIntersection(
278 rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
280 memref::CopyOp::create(
b, loc, copyArgs.first, copyArgs.second);
282 castToCompatibleMemRefType(
b, alloc, compatibleMemRefType);
284 viewAndIndices.insert(viewAndIndices.end(), xferOp.getTransferRank(),
286 scf::YieldOp::create(
b, loc, viewAndIndices);
309static scf::IfOp createFullPartialVectorTransferRead(
311 Value inBoundsCond, MemRefType compatibleMemRefType,
Value alloc) {
313 scf::IfOp fullPartialIfOp;
316 return scf::IfOp::create(
317 b, loc, inBoundsCond,
319 Value res = castToCompatibleMemRefType(
b,
memref, compatibleMemRefType);
321 llvm::append_range(viewAndIndices, xferOp.getIndices());
322 scf::YieldOp::create(
b, loc, viewAndIndices);
325 Operation *newXfer =
b.clone(*xferOp.getOperation());
326 Value vector = cast<VectorTransferOpInterface>(newXfer).getVector();
327 memref::StoreOp::create(
329 vector::TypeCastOp::create(
330 b, loc, MemRefType::get({},
vector.getType()), alloc));
333 castToCompatibleMemRefType(
b, alloc, compatibleMemRefType);
335 viewAndIndices.insert(viewAndIndices.end(), xferOp.getTransferRank(),
337 scf::YieldOp::create(
b, loc, viewAndIndices);
357getLocationToWriteFullVec(
RewriterBase &
b, vector::TransferWriteOp xferOp,
359 MemRefType compatibleMemRefType,
Value alloc) {
363 return scf::IfOp::create(
364 b, loc, inBoundsCond,
367 castToCompatibleMemRefType(
b,
memref, compatibleMemRefType);
369 llvm::append_range(viewAndIndices, xferOp.getIndices());
370 scf::YieldOp::create(
b, loc, viewAndIndices);
374 castToCompatibleMemRefType(
b, alloc, compatibleMemRefType);
376 viewAndIndices.insert(viewAndIndices.end(),
377 xferOp.getTransferRank(), zero);
378 scf::YieldOp::create(
b, loc, viewAndIndices);
397 vector::TransferWriteOp xferOp,
400 auto notInBounds = arith::XOrIOp::create(
404 std::pair<Value, Value> copyArgs = createSubViewIntersection(
405 rewriter, cast<VectorTransferOpInterface>(xferOp.getOperation()),
407 memref::CopyOp::create(
b, loc, copyArgs.first, copyArgs.second);
424static void createFullPartialVectorTransferWrite(
RewriterBase &
b,
425 vector::TransferWriteOp xferOp,
429 auto notInBounds = arith::XOrIOp::create(
435 vector::TypeCastOp::create(
436 b, loc, MemRefType::get({}, xferOp.getVector().
getType()), alloc),
438 mapping.
map(xferOp.getVector(),
load);
439 b.clone(*xferOp.getOperation(), mapping);
454 if (!isa<scf::ForOp, affine::AffineForOp>(parent))
457 assert(scope &&
"Expected op to be inside automatic allocation scope");
521LogicalResult mlir::vector::splitFullAndPartialTransfer(
524 if (
options.vectorTransferSplit == VectorTransferSplit::None)
528 auto inBoundsAttr =
b.getBoolArrayAttr(bools);
529 if (
options.vectorTransferSplit == VectorTransferSplit::ForceInBounds) {
530 b.modifyOpInPlace(xferOp, [&]() {
531 xferOp->setInherentAttr(
b.getStringAttr(xferOp.getInBoundsAttrName()),
540 assert(succeeded(splitFullAndPartialTransferPrecondition(xferOp)) &&
541 "Expected splitFullAndPartialTransferPrecondition to hold");
543 auto xferReadOp = dyn_cast<vector::TransferReadOp>(xferOp.getOperation());
544 auto xferWriteOp = dyn_cast<vector::TransferWriteOp>(xferOp.getOperation());
546 if (!(xferReadOp || xferWriteOp))
548 if (xferWriteOp && xferWriteOp.getMask())
550 if (xferReadOp && xferReadOp.getMask())
555 b.setInsertionPoint(xferOp);
557 b, cast<VectorTransferOpInterface>(xferOp.getOperation()));
565 Operation *scope = getAutomaticAllocationScope(xferOp);
567 "AutomaticAllocationScope with >1 regions");
569 auto shape = xferOp.getVectorType().getShape();
570 Type elementType = xferOp.getVectorType().getElementType();
571 alloc = memref::AllocaOp::create(
b, scope->
getLoc(),
572 MemRefType::get(
shape, elementType),
576 MemRefType compatibleMemRefType =
577 getCastCompatibleMemRefType(cast<MemRefType>(xferOp.getShapedType()),
578 cast<MemRefType>(alloc.
getType()));
579 if (!compatibleMemRefType)
584 returnTypes[0] = compatibleMemRefType;
586 if (
auto xferReadOp =
587 dyn_cast<vector::TransferReadOp>(xferOp.getOperation())) {
589 scf::IfOp fullPartialIfOp =
590 options.vectorTransferSplit == VectorTransferSplit::VectorTransfer
591 ? createFullPartialVectorTransferRead(
b, xferReadOp, returnTypes,
593 compatibleMemRefType, alloc)
594 : createFullPartialMemRefCopy(
b, xferReadOp, returnTypes,
595 inBoundsCond, compatibleMemRefType,
598 *ifOp = fullPartialIfOp;
601 for (
unsigned i = 0, e = returnTypes.size(); i != e; ++i)
602 xferReadOp.setOperand(i, fullPartialIfOp.getResult(i));
604 b.modifyOpInPlace(xferOp, [&]() {
605 xferOp->setInherentAttr(b.getStringAttr(xferOp.getInBoundsAttrName()),
612 auto xferWriteOp = cast<vector::TransferWriteOp>(xferOp.getOperation());
615 auto memrefAndIndices = getLocationToWriteFullVec(
616 b, xferWriteOp, returnTypes, inBoundsCond, compatibleMemRefType, alloc);
622 mapping.
map(xferWriteOp.getBase(), memrefAndIndices.front());
623 mapping.
map(xferWriteOp.getIndices(), memrefAndIndices.drop_front());
624 auto *
clone =
b.clone(*xferWriteOp, mapping);
625 clone->setInherentAttr(xferWriteOp.getInBoundsAttrName(), inBoundsAttr);
629 if (
options.vectorTransferSplit == VectorTransferSplit::VectorTransfer)
630 createFullPartialVectorTransferWrite(
b, xferWriteOp, inBoundsCond, alloc);
632 createFullPartialMemRefCopy(
b, xferWriteOp, inBoundsCond, alloc);
643 using FilterConstraintType =
644 std::function<LogicalResult(VectorTransferOpInterface op)>;
646 explicit VectorTransferFullPartialRewriter(
647 MLIRContext *context,
648 VectorTransformsOptions options = VectorTransformsOptions(),
649 FilterConstraintType filter =
650 [](VectorTransferOpInterface op) {
return success(); },
651 PatternBenefit benefit = 1)
652 : RewritePattern(MatchAnyOpTypeTag(), benefit, context), options(options),
653 filter(std::move(filter)) {}
656 LogicalResult matchAndRewrite(Operation *op,
657 PatternRewriter &rewriter)
const override;
660 VectorTransformsOptions options;
661 FilterConstraintType filter;
666LogicalResult VectorTransferFullPartialRewriter::matchAndRewrite(
668 auto xferOp = dyn_cast<VectorTransferOpInterface>(op);
669 if (!xferOp ||
failed(splitFullAndPartialTransferPrecondition(xferOp)) ||
672 return splitFullAndPartialTransfer(rewriter, xferOp,
options);
677 patterns.
add<VectorTransferFullPartialRewriter>(patterns.
getContext(),
static llvm::ManagedStatic< PassManagerOptions > options
static Value createInBoundsCond(RewriterBase &b, VectorTransferOpInterface xferOp)
Build the condition to ensure that a particular VectorTransferOpInterface is in-bounds.
Base type for affine expression.
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...
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 coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
This class represents a single result from folding an operation.
A trait of region holding operations that define a new scope for automatic allocations,...
Operation is the basic unit of execution within MLIR.
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
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.
RewritePattern is the common base class for all DAG to DAG replacements.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over 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.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
OpFoldResult makeComposedFoldedAffineApply(OpBuilder &b, Location loc, AffineMap map, ArrayRef< OpFoldResult > operands, bool composeAffineMin=false)
Constructs an AffineApplyOp that applies map to operands after composing the map with the maps of any...
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given memref value.
SmallVector< Value > ValueVector
An owning vector of values, handy to return from functions.
void populateVectorTransferFullPartialPatterns(RewritePatternSet &patterns, const VectorTransformsOptions &options)
Populate patterns with the following patterns.
Include the generated interface declarations.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.