-
Notifications
You must be signed in to change notification settings - Fork 15.4k
[mlir][Vector] add vector.insert canonicalization pattern to convert a chain of insertions to vector.from_elements #142944
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 7 commits
c511a4e
bba3d6c
9701de8
27bb005
b3e9850
bb8c827
ce818c1
8051673
7f8ccf0
376ad09
5b6edc9
d88b2ce
1560452
b7223d0
747cb4a
5bca4ee
e7824d1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3149,6 +3149,18 @@ LogicalResult InsertOp::verify() { | |
| return success(); | ||
| } | ||
|
|
||
| // Calculate the linearized position of the continuous chunk of elements to | ||
| // insert, based on the shape of the value to insert and the positions to insert | ||
| // at. | ||
| static int64_t calculateInsertPosition(VectorType destTy, | ||
| ArrayRef<int64_t> positions) { | ||
| llvm::SmallVector<int64_t> completePositions(destTy.getRank(), 0); | ||
| assert(positions.size() <= completePositions.size() && | ||
| "positions size must be less than or equal to destTy rank"); | ||
| copy(positions, completePositions.begin()); | ||
| return linearize(completePositions, computeStrides(destTy.getShape())); | ||
| } | ||
|
|
||
| namespace { | ||
|
|
||
| // If insertOp is only inserting unit dimensions it can be transformed to a | ||
|
|
@@ -3191,6 +3203,126 @@ class InsertSplatToSplat final : public OpRewritePattern<InsertOp> { | |
| } | ||
| }; | ||
|
|
||
| /// Pattern to optimize a chain of insertions. | ||
| /// | ||
| /// This pattern identifies chains of vector.insert operations that: | ||
| /// 1. Only insert values at static positions. | ||
| /// 2. Completely initialize all elements in the resulting vector. | ||
| /// 3. All intermediate insert operations have only one use. | ||
|
Comment on lines
+3342
to
+3344
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [nit] It would be helpful if you made references to these high level design points within the implementation (e.g. "Check Cond 1. (only static indices are used)").
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point! |
||
| /// | ||
| /// When these conditions are met, the entire chain can be replaced with a | ||
| /// single vector.from_elements operation. | ||
| /// | ||
| /// Example transformation: | ||
| /// %poison = ub.poison : vector<2xi32> | ||
| /// %0 = vector.insert %c1, %poison[0] : i32 into vector<2xi32> | ||
| /// %1 = vector.insert %c2, %0[1] : i32 into vector<2xi32> | ||
| /// -> | ||
| /// %result = vector.from_elements %c1, %c2 : vector<2xi32> | ||
| class InsertChainFullyInitialized final : public OpRewritePattern<InsertOp> { | ||
| public: | ||
| using OpRewritePattern::OpRewritePattern; | ||
| LogicalResult matchAndRewrite(InsertOp op, | ||
| PatternRewriter &rewriter) const override { | ||
|
|
||
| VectorType destTy = op.getDestVectorType(); | ||
| if (destTy.isScalable()) | ||
| return failure(); | ||
| // Check if the result is used as the dest operand of another vector.insert | ||
| // Only care about the last op in a chain of insertions. | ||
banach-space marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| for (Operation *user : op.getResult().getUsers()) | ||
| if (auto insertOp = dyn_cast<InsertOp>(user)) | ||
| if (insertOp.getDest() == op.getResult()) | ||
| return failure(); | ||
|
|
||
| InsertOp currentOp = op; | ||
| SmallVector<InsertOp> chainInsertOps; | ||
| while (currentOp) { | ||
| // Dynamic position is not supported. | ||
| if (currentOp.hasDynamicPosition()) | ||
| return failure(); | ||
|
|
||
| chainInsertOps.push_back(currentOp); | ||
| currentOp = currentOp.getDest().getDefiningOp<InsertOp>(); | ||
| // Check that intermediate inserts have only one use to avoid an explosion | ||
| // of vectors. | ||
banach-space marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (currentOp && !currentOp->hasOneUse()) | ||
| return failure(); | ||
banach-space marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| int64_t vectorSize = destTy.getNumElements(); | ||
| int64_t initializedCount = 0; | ||
| SmallVector<bool> initialized(vectorSize, false); | ||
yangtetris marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| SmallVector<int64_t> pendingInsertPos; | ||
| SmallVector<int64_t> pendingInsertSize; | ||
| SmallVector<Value> pendingInsertValues; | ||
|
|
||
| for (auto insertOp : chainInsertOps) { | ||
| // The insert op folder will fold an insert at poison index into a | ||
| // ub.poison, which truncates the insert chain's backward traversal. | ||
banach-space marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (is_contained(insertOp.getStaticPosition(), InsertOp::kPoisonIndex)) | ||
| return failure(); | ||
|
|
||
| // Calculate the linearized position for inserting elements. | ||
| int64_t insertBeginPosition = | ||
| calculateInsertPosition(destTy, insertOp.getStaticPosition()); | ||
|
|
||
| // The valueToStore operand may be a vector or a scalar. Need to handle | ||
| // both cases. | ||
| int64_t insertSize = 1; | ||
| if (auto srcVectorType = | ||
| llvm::dyn_cast<VectorType>(insertOp.getValueToStoreType())) | ||
| insertSize = srcVectorType.getNumElements(); | ||
|
|
||
| assert(insertBeginPosition + insertSize <= vectorSize && | ||
| "insert would overflow the vector"); | ||
|
|
||
| for (auto index : llvm::seq<int64_t>(insertBeginPosition, | ||
| insertBeginPosition + insertSize)) { | ||
| if (initialized[index]) | ||
| continue; | ||
banach-space marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| initialized[index] = true; | ||
| ++initializedCount; | ||
| } | ||
|
|
||
| // Defer the creation of ops before we can make sure the pattern can | ||
| // succeed. | ||
| pendingInsertPos.push_back(insertBeginPosition); | ||
| pendingInsertSize.push_back(insertSize); | ||
| pendingInsertValues.push_back(insertOp.getValueToStore()); | ||
|
|
||
| if (initializedCount == vectorSize) | ||
| break; | ||
| } | ||
|
|
||
| // Final check: all positions must be initialized | ||
| if (initializedCount != vectorSize) | ||
| return failure(); | ||
|
|
||
| SmallVector<Value> elements(vectorSize); | ||
| for (auto [insertBeginPosition, insertSize, valueToStore] : | ||
| llvm::reverse(llvm::zip(pendingInsertPos, pendingInsertSize, | ||
| pendingInsertValues))) { | ||
| if (auto srcVectorType = | ||
| llvm::dyn_cast<VectorType>(valueToStore.getType())) { | ||
| SmallVector<int64_t> strides = computeStrides(srcVectorType.getShape()); | ||
| // Get all elements from the vector in row-major order. | ||
| for (int64_t linearIdx = 0; linearIdx < insertSize; linearIdx++) { | ||
| SmallVector<int64_t> position = delinearize(linearIdx, strides); | ||
| Value extractedElement = rewriter.create<vector::ExtractOp>( | ||
yangtetris marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| op.getLoc(), valueToStore, position); | ||
| elements[insertBeginPosition + linearIdx] = extractedElement; | ||
| } | ||
| } else { | ||
| elements[insertBeginPosition] = valueToStore; | ||
| } | ||
| } | ||
|
|
||
| rewriter.replaceOpWithNewOp<vector::FromElementsOp>(op, destTy, elements); | ||
| return success(); | ||
| } | ||
| }; | ||
|
|
||
| } // namespace | ||
|
|
||
| static Attribute | ||
|
|
@@ -3217,13 +3349,9 @@ foldDenseElementsAttrDestInsertOp(InsertOp insertOp, Attribute srcAttr, | |
| !insertOp->hasOneUse()) | ||
| return {}; | ||
|
|
||
| // Calculate the linearized position of the continuous chunk of elements to | ||
| // insert. | ||
| llvm::SmallVector<int64_t> completePositions(destTy.getRank(), 0); | ||
| copy(insertOp.getStaticPosition(), completePositions.begin()); | ||
| // Calculate the linearized position for inserting elements. | ||
| int64_t insertBeginPosition = | ||
| linearize(completePositions, computeStrides(destTy.getShape())); | ||
|
|
||
| calculateInsertPosition(destTy, insertOp.getStaticPosition()); | ||
| SmallVector<Attribute> insertedValues; | ||
| Type destEltType = destTy.getElementType(); | ||
|
|
||
|
|
@@ -3256,7 +3384,8 @@ foldDenseElementsAttrDestInsertOp(InsertOp insertOp, Attribute srcAttr, | |
|
|
||
| void InsertOp::getCanonicalizationPatterns(RewritePatternSet &results, | ||
| MLIRContext *context) { | ||
| results.add<InsertToBroadcast, BroadcastFolder, InsertSplatToSplat>(context); | ||
| results.add<InsertToBroadcast, BroadcastFolder, InsertSplatToSplat, | ||
| InsertChainFullyInitialized>(context); | ||
| } | ||
|
|
||
| OpFoldResult vector::InsertOp::fold(FoldAdaptor adaptor) { | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.