Issue 235732
Summary [RISCV][Zfbfmin] Scalar sitofp/uitofp i32/i64 -> bfloat also double-rounds through f32 (fcvt.s.w/l + fcvt.bf16.s)
Labels new issue
Assignees
Reporter leidian977
    #235612 reports the double rounding for Zvfbfmin **vector** conversions
(`vfcvt.f.x.v` + `vfncvtbf16.f.f.w`). The **scalar** Zfbfmin path has the
same bug via a separate lowering: integer -> f32 (`fcvt.s.w` / `fcvt.s.l`,
rounded) followed by f32 -> bf16 (`fcvt.bf16.s`, rounded again), so any fix
for the vector case should cover this path too.

### Reproduction

```llvm
; scalar-bf16.ll
define bfloat @i32_to_bf16(i32 %x) {
  %r = sitofp i32 %x to bfloat
  ret bfloat %r
}

define bfloat @i64_to_bf16(i64 %x) {
  %r = sitofp i64 %x to bfloat
  ret bfloat %r
}
```

```
$ llc -mtriple=riscv64 -mattr=+zfbfmin scalar-bf16.ll -o - | grep fcvt
	fcvt.s.w	fa5, a0
	fcvt.bf16.s	fa0, fa5
	fcvt.s.l	fa5, a0
	fcvt.bf16.s	fa0, fa5
```

The same counterexample from the issue applies unchanged: `x = 16842753`
(2^24 + 2^16 + 1) rounds to f32 exactly on the bf16 midpoint, and the second
rounding goes to even the wrong way — `(bfloat)16842753` yields `0x4B80`
instead of the correctly rounded `0x4B81`.

### Additional data points from testing the surrounding surface

While reproducing, I checked the neighbouring scalar/vector conversion paths
on trunk (`cc2acc33a5b2`) and found one more independent defect worth a
separate look:

**`sitofp/uitofp i128 -> bfloat` crashes llc with an assertion when Zfbfmin
is enabled:**

```llvm
define bfloat @f(i128 %x) {
  %r = sitofp i128 %x to bfloat
  ret bfloat %r
}
```

```
$ llc -mtriple=riscv64 -mattr=+zfbfmin i128-bf16.ll
llc: LegalizeIntegerTypes.cpp:5986: Assertion `LC != RTLIB::UNKNOWN_LIBCALL &&
"Don't know how to expand this XINT_TO_FP!"' failed.
```

Root cause: `RuntimeLibcalls.td` defines `SINTTOFP_I64_BF16` /
`UINTTOFP_I64_BF16` but no `SINTTOFP_I128_BF16` / `UINTTOFP_I128_BF16`, so
`ExpandIntOp_XINT_TO_FP` has no libcall to reach when the i128 operand is
expanded. i128 -> f32/f16/f64 all compile fine; only the bf16 target hits the
gap. (Related: #70933 / #71658 propose adding the i128->bf16 libcalls, and
#233660 just fixed the analogous AArch64 crash, but only in the AArch64
lowering.)

Everything else I probed was correct: f64 -> bf16 uses round-to-odd
(`vfncvt.rod.f.f.w`), f32 -> bf16 is single-step, i8/i16 -> bf16 go through
an exact f32 intermediate, and — worth noting for the fix — integer -> f16
through f32 is *always* safe because f32's 24-bit significand covers every
f16 rounding breakpoint (max 65520 < 2^24), so any fix only needs to treat
bf16 targets, not f16.

Verified bit-exactly with Python (`struct`/`fractions`) and by inspecting
the emitted asm.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to