42 unsigned vectorLength;
43 bool enableVLAVectorization;
44 bool enableSIMDIndex32;
54static bool isInvariantValue(
Value val,
Block *block) {
55 if (
auto arg = dyn_cast<BlockArgument>(val))
56 return isInvariantArg(arg, block);
77static bool hasKnownNonUnitStride(
Value mem) {
89 if (toCoords.getLevel() >= cooStart)
94 auto memTp = dyn_cast<MemRefType>(mem.
getType());
99 if (
failed(memTp.getStridesAndOffset(strides, offset)))
101 return !strides.empty() && !ShapedType::isDynamic(strides.back()) &&
106static VectorType vectorType(VL vl,
Type etp) {
107 return VectorType::get(vl.vectorLength, etp, vl.enableVLAVectorization);
111static VectorType vectorType(VL vl,
Value mem) {
118 VectorType mtp = vectorType(vl, rewriter.
getI1Type());
123 IntegerAttr loInt, hiInt, stepInt;
127 if (((hiInt.getInt() - loInt.getInt()) % stepInt.getInt()) == 0) {
129 return vector::BroadcastOp::create(rewriter, loc, mtp, trueVal);
143 return vector::CreateMaskOp::create(rewriter, loc, mtp, end);
150 VectorType vtp = vectorType(vl, val.
getType());
151 return vector::BroadcastOp::create(rewriter, val.
getLoc(), vtp, val);
160 VectorType vtp = vectorType(vl, mem);
162 if (llvm::isa<VectorType>(idxs.back().getType())) {
164 Value indexVec = idxs.back();
166 return vector::GatherOp::create(rewriter, loc, vtp, mem, scalarArgs,
167 indexVec, vmask, pass);
169 return vector::MaskedLoadOp::create(rewriter, loc, vtp, mem, idxs, vmask,
179 if (llvm::isa<VectorType>(idxs.back().getType())) {
181 Value indexVec = idxs.back();
183 vector::ScatterOp::create(rewriter, loc,
nullptr, mem,
184 scalarArgs, indexVec, vmask, rhs);
187 vector::MaskedStoreOp::create(rewriter, loc, mem, idxs, vmask, rhs);
192static bool isVectorizableReduction(
Value red,
Value iter,
193 vector::CombiningKind &kind) {
195 kind = vector::CombiningKind::ADD;
196 return addf->getOperand(0) == iter || addf->getOperand(1) == iter;
199 kind = vector::CombiningKind::ADD;
200 return addi->getOperand(0) == iter || addi->getOperand(1) == iter;
203 kind = vector::CombiningKind::ADD;
204 return subf->getOperand(0) == iter;
207 kind = vector::CombiningKind::ADD;
208 return subi->getOperand(0) == iter;
211 kind = vector::CombiningKind::MUL;
212 return mulf->getOperand(0) == iter || mulf->getOperand(1) == iter;
215 kind = vector::CombiningKind::MUL;
216 return muli->getOperand(0) == iter || muli->getOperand(1) == iter;
219 kind = vector::CombiningKind::AND;
220 return andi->getOperand(0) == iter || andi->getOperand(1) == iter;
223 kind = vector::CombiningKind::OR;
224 return ori->getOperand(0) == iter || ori->getOperand(1) == iter;
227 kind = vector::CombiningKind::XOR;
228 return xori->getOperand(0) == iter || xori->getOperand(1) == iter;
241 vector::CombiningKind kind;
242 if (!isVectorizableReduction(red, iter, kind))
243 llvm_unreachable(
"unknown reduction");
245 case vector::CombiningKind::ADD:
246 case vector::CombiningKind::XOR:
248 return vector::InsertOp::create(rewriter, loc, r,
251 case vector::CombiningKind::MUL:
253 return vector::InsertOp::create(rewriter, loc, r,
256 case vector::CombiningKind::AND:
257 case vector::CombiningKind::OR:
259 return vector::BroadcastOp::create(rewriter, loc, vtp, r);
263 llvm_unreachable(
"unknown reduction kind");
285static bool vectorizeSubscripts(
PatternRewriter &rewriter, scf::ForOp forOp,
289 unsigned dim = subs.size();
291 for (
auto sub : subs) {
292 bool innermost = ++d == dim;
298 if (isInvariantValue(sub, block)) {
310 if (
auto arg = llvm::dyn_cast<BlockArgument>(sub)) {
311 if (isInvariantArg(arg, block) == innermost)
320 if (
auto icast = cast.getDefiningOp<arith::IndexCastOp>())
321 cast = icast->getOperand(0);
322 else if (
auto ecast = cast.getDefiningOp<arith::ExtUIOp>())
323 cast = ecast->getOperand(0);
340 if (
auto load = cast.getDefiningOp<memref::LoadOp>()) {
343 if (hasKnownNonUnitStride(
load.getMemRef()))
349 genVectorLoad(rewriter, loc, vl,
load.getMemRef(), idxs2, vmask);
350 Type etp = llvm::cast<VectorType>(vload.
getType()).getElementType();
351 if (!llvm::isa<IndexType>(etp)) {
353 vload = arith::ExtUIOp::create(
354 rewriter, loc, vectorType(vl, rewriter.
getI32Type()), vload);
356 vload = arith::ExtUIOp::create(
357 rewriter, loc, vectorType(vl, rewriter.
getI64Type()), vload);
359 idxs.push_back(vload);
366 if (
auto load = cast.getDefiningOp<arith::AddIOp>()) {
370 if (!isInvariantValue(inv, block)) {
372 idx =
load.getOperand(0);
375 if (isInvariantValue(inv, block)) {
376 if (
auto arg = llvm::dyn_cast<BlockArgument>(idx)) {
377 if (isInvariantArg(arg, block) || !innermost)
381 arith::AddIOp::create(rewriter, forOp.getLoc(), inv, idx));
392 if (auto x = dyn_cast<xxx>(def)) { \
394 vexp = xxx::create(rewriter, loc, ValueRange{vx}, x.getProperties(), \
395 x->getDiscardableAttrDictionary().getValue()); \
400#define TYPEDUNAOP(xxx) \
401 if (auto x = dyn_cast<xxx>(def)) { \
403 VectorType vtp = vectorType(vl, x.getType()); \
404 vexp = xxx::create(rewriter, loc, TypeRange{vtp}, ValueRange{vx}, \
406 x->getDiscardableAttrDictionary().getValue()); \
412 if (auto x = dyn_cast<xxx>(def)) { \
414 vexp = xxx::create(rewriter, loc, ValueRange{vx, vy}, x.getProperties(), \
415 x->getDiscardableAttrDictionary().getValue()); \
426static bool vectorizeExpr(
PatternRewriter &rewriter, scf::ForOp forOp, VL vl,
430 if (!VectorType::isValidElementType(exp.
getType()))
433 if (
auto arg = llvm::dyn_cast<BlockArgument>(exp)) {
434 if (arg == forOp.getInductionVar()) {
438 VectorType vtp = vectorType(vl, arg.
getType());
439 Value veci = vector::BroadcastOp::create(rewriter, loc, vtp, arg);
440 Value incr = vector::StepOp::create(rewriter, loc, vtp);
441 vexp = arith::AddIOp::create(rewriter, loc, veci, incr);
449 vexp = genVectorInvariantValue(rewriter, vl, exp);
457 vexp = genVectorInvariantValue(rewriter, vl, exp);
466 if (
auto load = dyn_cast<memref::LoadOp>(def)) {
467 if (hasKnownNonUnitStride(
load.getMemRef()))
469 auto subs =
load.getIndices();
471 if (vectorizeSubscripts(rewriter, forOp, vl, subs, codegen, vmask, idxs)) {
473 vexp = genVectorLoad(rewriter, loc, vl,
load.getMemRef(), idxs, vmask);
487 if (vectorizeExpr(rewriter, forOp, vl, def->
getOperand(0), codegen, vmask,
514 if (vectorizeExpr(rewriter, forOp, vl, def->
getOperand(0), codegen, vmask,
516 vectorizeExpr(rewriter, forOp, vl, def->
getOperand(1), codegen, vmask,
522 if (isa<arith::ShLIOp>(def) || isa<arith::ShRUIOp>(def) ||
523 isa<arith::ShRSIOp>(def)) {
525 if (!isInvariantValue(shiftFactor, block))
532 BINOP(arith::DivSIOp)
533 BINOP(arith::DivUIOp)
542 BINOP(arith::ShRUIOp)
543 BINOP(arith::ShRSIOp)
558static bool vectorizeStmt(
PatternRewriter &rewriter, scf::ForOp forOp, VL vl,
569 scf::YieldOp yield = cast<scf::YieldOp>(block.
getTerminator());
570 auto &last = *++block.
rbegin();
584 if (vl.enableVLAVectorization) {
586 vector::VectorScaleOp::create(rewriter, loc, rewriter.
getIndexType());
587 step = arith::MulIOp::create(rewriter, loc, vscale, step);
589 if (!yield.getResults().empty()) {
590 Value init = forOp.getInitArgs()[0];
591 VectorType vtp = vectorType(vl, init.
getType());
592 Value vinit = genVectorReducInit(rewriter, loc, yield->getOperand(0),
593 forOp.getRegionIterArg(0), init, vtp);
595 scf::ForOp::create(rewriter, loc, forOp.getLowerBound(),
596 forOp.getUpperBound(), step, vinit,
597 nullptr, forOp.getUnsignedCmp());
598 forOpNew->setDiscardableAttr(
606 vmask = genVectorMask(rewriter, loc, vl, forOp.getInductionVar(),
607 forOp.getLowerBound(), forOp.getUpperBound(), step);
612 if (!yield.getResults().empty()) {
614 if (yield->getNumOperands() != 1)
616 Value red = yield->getOperand(0);
617 Value iter = forOp.getRegionIterArg(0);
618 vector::CombiningKind kind;
620 if (isVectorizableReduction(red, iter, kind) &&
621 vectorizeExpr(rewriter, forOp, vl, red, codegen, vmask, vrhs)) {
623 Value partial = forOpNew.getResult(0);
624 Value vpass = genVectorInvariantValue(rewriter, vl, iter);
625 Value vred = arith::SelectOp::create(rewriter, loc, vmask, vrhs, vpass);
626 scf::YieldOp::create(rewriter, loc, vred);
628 Value vres = vector::ReductionOp::create(rewriter, loc, kind, partial);
634 forOpNew.getInductionVar());
636 forOpNew.getRegionIterArg(0));
641 }
else if (
auto store = dyn_cast<memref::StoreOp>(last)) {
643 if (hasKnownNonUnitStride(store.getMemRef()))
645 auto subs = store.getIndices();
647 Value rhs = store.getValue();
649 if (vectorizeSubscripts(rewriter, forOp, vl, subs, codegen, vmask, idxs) &&
650 vectorizeExpr(rewriter, forOp, vl, rhs, codegen, vmask, vrhs)) {
652 genVectorStore(rewriter, loc, store.getMemRef(), idxs, vmask, vrhs);
659 assert(!codegen &&
"cannot call codegen when analysis failed");
666 using OpRewritePattern<scf::ForOp>::OpRewritePattern;
668 ForOpRewriter(MLIRContext *context,
unsigned vectorLength,
669 bool enableVLAVectorization,
bool enableSIMDIndex32)
670 : OpRewritePattern(context),
671 vl{vectorLength, enableVLAVectorization, enableSIMDIndex32} {}
673 LogicalResult matchAndRewrite(scf::ForOp op,
674 PatternRewriter &rewriter)
const override {
678 if (!op.getRegion().hasOneBlock() || !
isOneInteger(op.getStep()) ||
682 if (vectorizeStmt(rewriter, op, vl,
false) &&
683 vectorizeStmt(rewriter, op, vl,
true))
695 if (
auto forOp = redOp.getVector().getDefiningOp<scf::ForOp>()) {
696 if (forOp->hasDiscardableAttr(
698 rewriter.
replaceOp(op, redOp.getVector());
711struct ReducChainBroadcastRewriter
714 using OpRewritePattern<vector::BroadcastOp>::OpRewritePattern;
716 LogicalResult matchAndRewrite(vector::BroadcastOp op,
717 PatternRewriter &rewriter)
const override {
718 return cleanReducChain(rewriter, op, op.getSource());
727struct ReducChainInsertRewriter :
public OpRewritePattern<vector::InsertOp> {
729 using OpRewritePattern<vector::InsertOp>::OpRewritePattern;
731 LogicalResult matchAndRewrite(vector::InsertOp op,
732 PatternRewriter &rewriter)
const override {
733 return cleanReducChain(rewriter, op, op.getValueToStore());
744 unsigned vectorLength,
745 bool enableVLAVectorization,
746 bool enableSIMDIndex32) {
747 assert(vectorLength > 0);
749 patterns.
add<ForOpRewriter>(patterns.
getContext(), vectorLength,
750 enableVLAVectorization, enableSIMDIndex32);
751 patterns.
add<ReducChainInsertRewriter, ReducChainBroadcastRewriter>(
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
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 AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
This class represents an argument of a Block.
Block * getOwner() const
Returns the block that owns this argument.
Block represents an ordered list of Operations.
OpListType & getOperations()
Operation * getTerminator()
Get the terminator operation of this block.
reverse_iterator rbegin()
AffineExpr getAffineSymbolExpr(unsigned position)
AffineExpr getAffineDimExpr(unsigned position)
MLIRContext * getContext() const
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
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...
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
Block * getBlock()
Returns the operation block that contains this operation.
unsigned getNumOperands()
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.
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.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
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.
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.
static constexpr llvm::StringLiteral getLoopEmitterLoopAttrName()
A wrapper around RankedTensorType, which has three goals:
Level getLvlRank() const
Returns the level-rank.
Level getAoSCOOStart() const
Returns the starting level of this sparse tensor type for a trailing COO region that spans at least t...
Value constantIndex(OpBuilder &builder, Location loc, int64_t i)
Generates a constant of index type.
Value constantZero(OpBuilder &builder, Location loc, Type tp)
Generates a 0-valued constant of the given type.
Value constantOne(OpBuilder &builder, Location loc, Type tp)
Generates a 1-valued constant of the given type.
Value constantI1(OpBuilder &builder, Location loc, bool b)
Generates a constant of i1 type.
uint64_t Level
The type of level identifiers and level-ranks.
MemRefType getMemRefType(T &&t)
Convenience method to abbreviate casting getType().
SparseTensorType getSparseTensorType(Value val)
Convenience methods to obtain a SparseTensorType from a Value.
void populateVectorStepLoweringPatterns(RewritePatternSet &patterns, unsigned indexBitwidth=64, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
void populateSparseVectorizationPatterns(RewritePatternSet &patterns, unsigned vectorLength, bool enableVLAVectorization, bool enableSIMDIndex32)
Populates the given patterns list with vectorization rules.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
bool isOneInteger(OpFoldResult v)
Return true if v is an IntegerAttr with value 1.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...