Skip to content

Commit

Permalink
[MLIR][Tensor] Perform shape inference via in-place modification (NFC) (
Browse files Browse the repository at this point in the history
llvm#111593)

This is more efficient to avoid a clone that is immediately removed. 
Also guard the insertion of a cast on the result on whether the
destination type changed.
  • Loading branch information
joker-eph authored Oct 9, 2024
1 parent e2dc50c commit 275a2b0
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions mlir/lib/Dialect/Tensor/IR/TensorOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4332,21 +4332,25 @@ LogicalResult PackOp::canonicalize(PackOp packOp, PatternRewriter &rewriter) {
rewriter.create<tensor::CastOp>(loc, newSrcType, packOp.getSource());
}
Value dest = packOp.getDest();
if (destShape != packOp.getDestType().getShape()) {
RankedTensorType originalResultType = packOp.getDestType();
bool needUpdateDestType = (destShape != originalResultType.getShape());
if (needUpdateDestType) {
auto newDestType = packOp.getDestType().clone(destShape);
dest =
rewriter.create<tensor::CastOp>(loc, newDestType, packOp.getDest());
}
auto clonedPackOp = cast<PackOp>(rewriter.clone(*packOp));
Value res = clonedPackOp.getResult();
rewriter.startOpModification(clonedPackOp);
clonedPackOp.getSourceMutable().assign(source);
clonedPackOp.getDestMutable().assign(dest);
res.setType(dest.getType());
rewriter.finalizeOpModification(clonedPackOp);

rewriter.replaceOpWithNewOp<tensor::CastOp>(
packOp, packOp.getResult().getType(), clonedPackOp);
rewriter.modifyOpInPlace(packOp, [&] {
packOp.getSourceMutable().assign(source);
packOp.getDestMutable().assign(dest);
packOp.getResult().setType(cast<RankedTensorType>(dest.getType()));
});
// Insert a cast if needed
if (needUpdateDestType) {
rewriter.setInsertionPointAfter(packOp);
auto castOp =
rewriter.create<tensor::CastOp>(loc, originalResultType, packOp);
rewriter.replaceAllUsesExcept(packOp, castOp, castOp);
}
return success();
}

Expand Down

0 comments on commit 275a2b0

Please sign in to comment.