Skip to content

Commit c2c881f

Browse files
authored
[mlir][tosa] Fix integer-to-boolean cast folder (#150370)
According to the TOSA spec, casting to boolean should produce true if the input is non-zero, and false otherwise — i.e., `out = (in != 0) ? true : false`. Previous behavior incorrectly relied on truncation, which could yield incorrect results for non-zero values whose least significant bit is zero. Fixes #150302.
1 parent f45e6a2 commit c2c881f

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

mlir/lib/Dialect/Tosa/IR/TosaCanonicalizations.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1302,9 +1302,11 @@ OpFoldResult CastOp::fold(FoldAdaptor adaptor) {
13021302
auto intVal = operand.getSplatValue<APInt>();
13031303
auto bitwidth = outETy.getIntOrFloatBitWidth();
13041304

1305-
if (trunc) {
1305+
// i1 types are boolean in TOSA
1306+
if (outETy.isInteger(1)) {
1307+
intVal = APInt(bitwidth, intVal.isZero() ? 0 : 1);
1308+
} else if (trunc) {
13061309
intVal = intVal.trunc(bitwidth);
1307-
// i1 types are boolean in TOSA
13081310
} else if (unsignIn || inIntType.isInteger(1)) {
13091311
intVal = intVal.zext(bitwidth);
13101312
} else {

mlir/test/Dialect/Tosa/canonicalize.mlir

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1349,3 +1349,14 @@ func.func @test_fold_i1_to_i32_cast() -> tensor<i32> {
13491349
%1 = "tosa.cast"(%0) : (tensor<i1>) -> tensor<i32>
13501350
return %1 : tensor<i32>
13511351
}
1352+
1353+
// -----
1354+
1355+
// CHECK-LABEL: @test_fold_i32_to_i1_cast
1356+
// CHECK: %[[OUT:.*]] = "tosa.const"() <{values = dense<true> : tensor<i1>}> : () -> tensor<i1>
1357+
// CHECK: return %[[OUT]] : tensor<i1>
1358+
func.func @test_fold_i32_to_i1_cast() -> tensor<i1> {
1359+
%0 = "tosa.const"() <{values = dense<10> : tensor<i32>}> : () -> tensor<i32>
1360+
%1 = "tosa.cast"(%0) : (tensor<i32>) -> tensor<i1>
1361+
return %1 : tensor<i1>
1362+
}

0 commit comments

Comments
 (0)