Skip to content
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

[StableHLO] Merge reshape(reshape(x)) #14759

Merged
merged 1 commit into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,31 @@ struct ReshapeOpCanon final : OpRewritePattern<mlir::stablehlo::ReshapeOp> {
}
};

struct MergeConsecutiveReshapes final
: OpRewritePattern<mlir::stablehlo::ReshapeOp> {
using OpRewritePattern::OpRewritePattern;

LogicalResult matchAndRewrite(mlir::stablehlo::ReshapeOp op,
PatternRewriter &rewriter) const override {
// Fold noop reshape.
auto operand = op.getOperand();
if (op.getType() == operand.getType()) {
rewriter.replaceOp(op, op.getOperand());
return success();
}

// Fold reshape(reshape(x)).
auto reshapeOp = operand.getDefiningOp<mlir::stablehlo::ReshapeOp>();
if (!reshapeOp) {
return rewriter.notifyMatchFailure(
op, "requires defining op of operand to be Reshape");
}

op.setOperand(reshapeOp->getOperand(0));
return success();
}
};

struct TransposeIsReshape final
: OpRewritePattern<mlir::stablehlo::TransposeOp> {
using OpRewritePattern::OpRewritePattern;
Expand Down Expand Up @@ -1156,7 +1181,7 @@ void populateCanonicalizationPatterns(MLIRContext *context,
NoopReduceOpCanon, EmptyReduceOpCanon,
// Shape manipulation(-ish) ops.
ConcatenateOpCanon, ConvertOpCanon, DynamicReshapeOpCanon, GatherOpCanon,
ReshapeOpCanon, TransposeIsReshape,
ReshapeOpCanon, MergeConsecutiveReshapes, TransposeIsReshape,
// Types.
ZeroExtentTensorCanon>(context, benefit);
patterns->add<ReorderElementwiseAndShapeOp>(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,17 @@ func.func @reshape(%arg0: tensor<1xf32>)

// -----

// CHECK-LABEL: @merge_consecutive_reshapes
// CHECK-SAME: %[[ARG0:[a-zA-Z0-9$._-]+]]
func.func @merge_consecutive_reshapes(%arg0: tensor<4x4xi32>) -> tensor<16xi32> {
%0 = stablehlo.reshape %arg0 : (tensor<4x4xi32>) -> tensor<2x8xi32>
%1 = stablehlo.reshape %0 : (tensor<2x8xi32>) -> tensor<16xi32>
// CHECK: [[R0:%.+]] = stablehlo.reshape %[[ARG0]] : (tensor<4x4xi32>) -> tensor<16xi32>
return %1 : tensor<16xi32>
}

// -----

// CHECK-LABEL: func.func @transpose
// CHECK-SAME: ([[ARG0:%.+]]: tensor<2xf32>, [[ARG1:%.+]]: tensor<3x2xf32>, [[ARG2:%.+]]: tensor<f32>)
func.func @transpose(%arg0: tensor<2xf32>, %arg1: tensor<3x2xf32>, %arg2: tensor<f32>)
Expand Down
Loading