Issue 233369
Summary [MLIR][Arith] Canonicalizing truncf of sitofp/uitofp removes an observable rounding step
Labels mlir
Assignees
Reporter Cerulime
    ## Summary

`--canonicalize` rewrites `arith.truncf(arith.sitofp(x))` and `arith.truncf(arith.uitofp(x))` to a single integer-to-float conversion without checking whether the intermediate conversion is exact. Removing that rounding step can change the result.

For `x = 2^60 + 2^36 + 1`, converting `i64 -> f64 -> f32` produces the f32 bit pattern **`0x5D800000`**. Canonicalization changes both conversion sequences to `i64 -> f32`, producing **`0x5D800001`** instead.

This reproduces with standalone `mlir-opt` and `mlir-runner`, using standard MLIR dialects. Both pipelines verify, lower, and execute successfully; adding `--canonicalize` is the only difference between them.

## Reproducer

Save as `repro.mlir`:

```mlir
module {
  func.func @signed_conversion(%x: i64) -> f32 {
    %wide = arith.sitofp %x : i64 to f64
    %narrow = arith.truncf %wide : f64 to f32
    return %narrow : f32
  }

  func.func @unsigned_conversion(%x: i64) -> f32 {
 %wide = arith.uitofp %x : i64 to f64
    %narrow = arith.truncf %wide : f64 to f32
    return %narrow : f32
  }

  func.func @main() {
    // 2^60 + 2^36 + 1.
    %x = arith.constant 1152921573326323713 : i64
    %signed = func.call @signed_conversion(%x) : (i64) -> f32
    %signed_bits = arith.bitcast %signed : f32 to i32
    vector.print %signed_bits : i32
 %unsigned = func.call @unsigned_conversion(%x) : (i64) -> f32
 %unsigned_bits = arith.bitcast %unsigned : f32 to i32
    vector.print %unsigned_bits : i32
    return
  }
}
```

## Commands

Set `MLIR_BUILD` to the existing LLVM/MLIR build directory. The commands below use `~/llvm-project/build` and run in Bash.

```bash
export MLIR_BUILD="$HOME/llvm-project/build"
export PATH="$MLIR_BUILD/bin:$PATH"

# Verify the input and inspect the canonicalized IR.
mlir-opt repro.mlir -o /dev/null
mlir-opt repro.mlir --canonicalize -o canonicalized.mlir

# Baseline: lower the two conversions as written.
mlir-opt repro.mlir \
  --convert-vector-to-llvm \
 --convert-arith-to-llvm \
  --convert-func-to-llvm \
 --reconcile-unrealized-casts \
  -o baseline.llvm.mlir

# Canonicalized: use the identical lowering pipeline after canonicalization.
mlir-opt repro.mlir \
  --canonicalize \
  --convert-vector-to-llvm \
 --convert-arith-to-llvm \
  --convert-func-to-llvm \
 --reconcile-unrealized-casts \
  -o canonicalized.llvm.mlir

mlir-runner baseline.llvm.mlir -O0 -e main \
  --entry-point-result=void \
 --shared-libs="$MLIR_BUILD/lib/libmlir_c_runner_utils.so,$MLIR_BUILD/lib/libmlir_runner_utils.so"
mlir-runner canonicalized.llvm.mlir -O0 -e main \
  --entry-point-result=void \
 --shared-libs="$MLIR_BUILD/lib/libmlir_c_runner_utils.so,$MLIR_BUILD/lib/libmlir_runner_utils.so"
```

## Actual behavior

All commands exit with code `0`. The baseline execution prints:

```text
1568669696
1568669696
```

The canonicalized execution prints:

```text
1568669697
1568669697
```

The first line is the signed conversion; the second is the unsigned conversion. The integers are the exact f32 bit patterns, avoiding decimal floating-point formatting differences.

The relevant functions in `canonicalized.mlir` are:

```mlir
func.func @signed_conversion(%arg0: i64) -> f32 {
  %0 = arith.sitofp %arg0 : i64 to f32
  return %0 : f32
}
func.func @unsigned_conversion(%arg0: i64) -> f32 {
  %0 = arith.uitofp %arg0 : i64 to f32
  return %0 : f32
}
```

The baseline LLVM-dialect IR retains `llvm.sitofp` / `llvm.uitofp` to f64 followed by `llvm.fptrunc` to f32. The canonicalized LLVM-dialect IR contains only the direct conversions to f32.

## Expected behavior

Canonicalization should preserve the two-step result, `1568669696` (`0x5D800000`), for both functions.

The [Arith dialect description](https://github.com/llvm/llvm-project/blob/5850dbecdef88c693578862b610a4b9aeb91840d/mlir/include/mlir/Dialect/Arith/IR/ArithBase.td#L33-L38) specifies round-to-nearest, ties-to-even for internal folding and canonicalization when no rounding mode is explicit. Runtime behavior without an explicit mode is delegated to the backend; the observed execution on this x86-64 host uses round-to-nearest, ties-to-even and demonstrates the mismatch.

At this input magnitude, the f64 spacing is `2^8`, and the f32 spacing is `2^37`:

| Conversion sequence | Rounding steps | Final f32 bits |
| --- | --- | --- |
| Original `i64 -> f64 -> f32` | f64 rounds `x` to `2^60 + 2^36`; this is exactly halfway between adjacent f32 values, so ties-to-even selects `2^60` | `0x5D800000` |
| Rewritten `i64 -> f32` | `x` is one integer above that midpoint, so direct rounding selects `2^60 + 2^37` | `0x5D800001` |

The result changes by one f32 ULP. The positive input has the same value under signed and unsigned interpretation, so the same counterexample applies to both patterns.

## Why the input is valid

The integer constant fits in signed i64. Both integer-to-float conversions and the f64-to-f32 truncations operate on finite, in-range values. The program has no fast-math flags or `nneg` assumption, and no application memory accesses or uninitialized values. The f32-to-i32 bitcasts preserve bitwidth and only expose the computed bits.

Input verification and verification after canonicalization both succeed with the default checks enabled.

## Root cause

[`TruncFSIToFPToSIToFP` and `TruncFUIToFPToUIToFP`](https://github.com/llvm/llvm-project/blob/5850dbecdef88c693578862b610a4b9aeb91840d/mlir/lib/Dialect/Arith/IR/ArithCanonicalization.td#L524-L534) check only that the `truncf` rounding-mode attribute is absent:

```tablegen
def TruncFSIToFPToSIToFP :
 Pat<(Arith_TruncFOp:$tr (Arith_SIToFPOp:$fp $x), $rmf, $fmf),
 (Arith_SIToFPOp $x),
        [(Constraint<CPred<"$0 == nullptr">, "default rounding mode"> $rmf)]>;

def TruncFUIToFPToUIToFP :
 Pat<(Arith_TruncFOp:$tr (Arith_UIToFPOp:$fp $x, $nneg), $rmf, $fmf),
 (Arith_UIToFPOp $x, $nneg),
        [(Constraint<CPred<"$0 == nullptr">, "default rounding mode"> $rmf)]>;
```

They are registered by [`arith::TruncFOp::getCanonicalizationPatterns`](https://github.com/llvm/llvm-project/blob/5850dbecdef88c693578862b610a4b9aeb91840d/mlir/lib/Dialect/Arith/IR/ArithOps.cpp#L2160-L2168). Neither pattern proves that the intermediate integer-to-float conversion is exact. Default rounding does not make two successive rounded conversions equivalent to a single conversion.

LLVM InstCombine already guards the corresponding rewrite with [`isKnownExactCastIntToFP`](https://github.com/llvm/llvm-project/blob/5850dbecdef88c693578862b610a4b9aeb91840d/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp#L2492-L2497), which checks whether the first conversion can round.

## Candidate fix

Conservatively require the intermediate integer-to-float conversion to be known exact before applying either pattern. This can use the source integer's value range and the intermediate floating-point precision; otherwise retain the two conversions.

The existing [`truncSitofp` and `truncUitofp` tests](https://github.com/llvm/llvm-project/blob/5850dbecdef88c693578862b610a4b9aeb91840d/mlir/test/Dialect/Arith/canonicalize.mlir#L1470-L1507) cover `i32 -> f64 -> f32`, where the f64 intermediate represents every input integer exactly. Those safe folds should remain covered. Add negative folding coverage for `i64 -> f64 -> f32` for both signed and unsigned casts, plus an execution case around the midpoint used above.

No compiler fix was implemented or tested with a rebuilt compiler.

## Environment

* Tools: `~/llvm-project/build/bin/mlir-opt` and `~/llvm-project/build/bin/mlir-runner` from the same standalone LLVM/MLIR build.
* Build revision recorded in `build/include/llvm/Support/VCSRevision.h`: `5850dbecdef88c693578862b610a4b9aeb91840d`; the source checkout is at the same revision.
* Tool version: `LLVM version 24.0.0git`, optimized build with assertions.
* CMake configuration: `RelWithDebInfo`, `LLVM_ENABLE_ASSERTIONS=ON`, `LLVM_ENABLE_PROJECTS=mlir`, `MLIR_ENABLE_EXECUTION_ENGINE=ON`.
* Host: Ubuntu 24.04.2 LTS, Linux `6.8.0-139-generic`, x86-64.
* The reproducer was verified, canonicalized, lowered, and executed using the existing build. No compiler source modification or compiler rebuild was performed.

Assisted-by: OpenAI Codex

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to