From bd61ea0cac727fffe42e3d135ab915d515b2d52b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 9 Nov 2026 20:25:39 -0800 Subject: [PATCH] Lowering: a half NaN constant held widened keeps its bits FloatFmt::widen_bits took a half constant through f64 and back to f32, and the host's float conversions quiet a signalling NaN: a half constant 0xfd21 was held as 0xffa42000's quieted twin and stored as 0xff21. Metal keeps the constant's bits (sfold_precise on the M3: a signalling half NaN beside a run value reads 0xfd21, m3-max-12857, where MoltenVK read 0xff21 before and after the fold). A NaN now widens bit for bit: its sign, and its payload moved up 13 bits. Test lower::arith::tests::narrow::a_half_nan_constant_widens_with_its_bits: every half NaN pattern widens to a NaN that narrow_bits takes back to the pattern (to run). (cherry picked from commit f5ca0e73479f07761820d8c60a383f2accef6e92) --- crates/metal2vulkan/src/lower/arith/legal.rs | 6 +++++- crates/metal2vulkan/src/lower/arith/tests/narrow.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/metal2vulkan/src/lower/arith/legal.rs b/crates/metal2vulkan/src/lower/arith/legal.rs index 0f64d00f3..0073da763 100644 --- a/crates/metal2vulkan/src/lower/arith/legal.rs +++ b/crates/metal2vulkan/src/lower/arith/legal.rs @@ -131,9 +131,13 @@ impl FloatFmt { } } - /// The container bits of this format's bits `b` (exact: the same value). + /// The container bits of this format's bits `b` (exact: the same value, and a NaN its sign + /// and payload, a signalling one not quieted). pub fn widen_bits(self, b: u64) -> u64 { match self { + FloatFmt::Half if b & 0x7C00 == 0x7C00 && b & 0x3FF != 0 => { + ((b & 0x8000) << 16) | 0x7F80_0000 | ((b & 0x3FF) << 13) + } FloatFmt::Half => u64::from((f16_to_f64(b as u16) as f32).to_bits()), FloatFmt::BFloat => (b & 0xFFFF) << 16, _ => b, diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index ba7e212c1..ae47a63d1 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -2467,3 +2467,16 @@ fn a_half_decode_is_the_devices_widening_in_every_form() { } } } + +/// A `half` constant held widened keeps every NaN's sign and payload, a signalling one not +/// quieted (the host's float conversions would quiet it), so its store narrows to its own bits. +#[test] +fn a_half_nan_constant_widens_with_its_bits() { + assert_eq!(FloatFmt::Half.widen_bits(0xfd21), 0xffa4_2000); + assert_eq!(FloatFmt::Half.widen_bits(0x7e00), 0x7fc0_0000); + for b in (0x7c01..=0x7fffu64).chain(0xfc01..=0xffff) { + let w = FloatFmt::Half.widen_bits(b); + assert!(f32::from_bits(w as u32).is_nan(), "{b:#06x}"); + assert_eq!(FloatFmt::Half.narrow_bits(w), b, "{b:#06x}"); + } +}