Skip to content

[mlir][tensor] fix out-of-bound index in tensor.dim #85901

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

Merged
merged 3 commits into from
Mar 25, 2024
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
3 changes: 3 additions & 0 deletions mlir/lib/Dialect/Bufferization/IR/BufferizationOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,9 @@ struct FoldDimOfAllocTensorOp : public OpRewritePattern<tensor::DimOp> {
auto allocTensorOp = dimOp.getSource().getDefiningOp<AllocTensorOp>();
if (!allocTensorOp || !maybeConstantIndex)
return failure();
if (*maybeConstantIndex < 0 ||
*maybeConstantIndex >= allocTensorOp.getType().getRank())
return failure();
if (!allocTensorOp.getType().isDynamicDim(*maybeConstantIndex))
return failure();
rewriter.replaceOp(
Expand Down
23 changes: 23 additions & 0 deletions mlir/test/Dialect/Tensor/canonicalize.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -2367,3 +2367,26 @@ func.func @dim_of_reshape_undominated(%arg0: tensor<*xf32>, %arg1: tensor<?xinde
%dim = tensor.dim %reshape, %0 : tensor<*xf32>
return %dim : index
}

// -----

// Test case: This test fails to fold because the index of tensor.dim is out_of_bounds
// CHECK-LABEL: func @dim_out_of_bounds(
// CHECK: %[[IDX:.*]] = index.constant 28
// CHECK-NEXT: bufferization.alloc_tensor
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check the bufferization.alloc_tensor's operands like this:
// CHECK: %[[poison.*]]ub.poison
// CHECK-NEXT: bufferization.alloc_tensor(%[[poison]])

// CHECK-NEXT: %[[DIM:.*]] = tensor.dim %{{.*}}, %[[IDX]]
// CHECK-NEXT: memref.alloc
// CHECK-NEXT: memref.cast
// CHECK-NEXT: affine.vector_load %{{.*}}[{{.*}}, {{.*}}, symbol(%[[DIM]])]
// CHECK-NEXT: return
func.func @dim_out_of_bounds() -> vector<7xi32> {
%c1 = arith.constant 1 : index
%idx28 = index.constant 28
%c29 = arith.constant 29 : index
%3 = bufferization.alloc_tensor(%c29) : tensor<?xi16>
%dim = tensor.dim %3, %idx28 : tensor<?xi16>
%alloc_21 = memref.alloc(%c29) : memref<?x26x2xi32>
%16 = affine.vector_load %alloc_21[%c1, %c1, %dim] : memref<?x26x2xi32>, vector<7xi32>
return %16 : vector<7xi32>
}