Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

cranelift: don't emit FEAT_FP16 instructions without the feature, and support f16 in the interpreter (#14436)

Dsecurity4561b1211d4e
diff --git a/cranelift/codegen/src/ir/immediates.rs b/cranelift/codegen/src/ir/immediates.rs
index 314e7cdd1f..38045619d6 100644
--- a/cranelift/codegen/src/ir/immediates.rs
+++ b/cranelift/codegen/src/ir/immediates.rs
@@ -855,6 +855,111 @@ ieee_float! {
rust_type_not_stable = rust_type_not_stable,
}
+impl Ieee16 {
+ /// Widen to `f32`. Exact: every binary16 is representable in binary32.
+ pub fn to_f32(self) -> f32 {
+ let bits = u32::from(self.bits());
+ let sign = (bits & 0x8000) << 16;
+ let exponent = (bits >> 10) & 0x1f;
+ let significand = bits & 0x03ff;
+
+ let (f32_exponent, f32_significand) = match exponent {
+ 0 if significand == 0 => return f32::from_bits(sign),
+ // A subnormal is `significand * 2^-24`.
+ 0 => {
+ let msb = significand.ilog2();
+ ((msb + 103) << 23, (significand - (1 << msb)) << (23 - msb))
+ }
+ 0x1f => (0x7f80_0000, (significand << 13) & 0x007f_ffff),
+ _ => ((exponent + 112) << 23, significand << 13),
+ };
+ let quiet = if exponent == 0x1f && f32_significand != 0 {
+ 0x0040_0000
+ } else {
+ 0
+ };
+ f32::from_bits(sign | f32_exponent | f32_significand | quiet)
+ }
+
+ /// Narrow from `f32`, rounding to nearest with ties to even.
+ pub fn from_f32_rne(x: f32) -> Self {
+ let bits = x.to_bits();
+ let sign = ((bits >> 16) & 0x8000) as u16;
+ let exponent = ((bits >> 23) & 0xff) as i32;
+ let significand = bits & 0x007f_ffff;
+
+ match exponent {
+ 0xff => Self::infinity_or_nan(sign, significand != 0, (significand >> 13) as u64),
+ // Zero or subnormal: no implicit one, and too small to matter.
+ 0 => Self::with_bits(sign),
+ _ => Self::from_parts(sign, exponent - 127, u64::from(significand | 1 << 23), 23),
+ }
+ }
+
+ /// Narrow from `f64`. Must not go via `f32`, which rounds twice.
+ pub fn from_f64_rne(x: f64) -> Self {
+ let bits = x.to_bits();
+ let sign = ((bits >> 48) & 0x8000) as u16;
+ let exponent = ((bits >> 52) & 0x7ff) as i32;
+ let significand = bits & 0x000f_ffff_ffff_ffff;
+
+ match exponent {
+ 0x7ff => Self::infinity_or_nan(sign, significand != 0, significand >> 42),
+ 0 => Self::with_bits(sign),
+ _ => Self::from_parts(sign, exponent - 1023, significand | 1 << 52, 52),
+ }
+ }
+
+ fn infinity_or_nan(sign: u16, is_nan: bool, payload: u64) -> Self {
+ if !is_nan {
+ return Self::with_bits(sign | 0x7c00);
+ }
+ Self::with_bits(sign | 0x7c00 | (payload as u16 & 0x03ff) | 0x0200)
+ }
+
+ /// Round `significand * 2^(unbiased - significand_bits)` to binary16.
+ fn from_parts(sign: u16, unbiased: i32, significand: u64, significand_bits: u32) -> Self {
+ if unbiased > 15 {
+ return Self::with_bits(sign | 0x7c00);
+ }
+
+ if unbiased >= -14 {
+ // Ordinary. Drop enough to leave the implicit one plus 10 bits.
+ let drop = significand_bits - 10;
+ let mut half_significand = ((significand >> drop) & 0x3ff) as u16;
+ let remainder = significand & ((1 << drop) - 1);
+ let halfway = 1 << (drop - 1);
+ let mut half_exponent = (unbiased + 15) as u16;
+ if remainder > halfway || (remainder == halfway && half_significand & 1 == 1) {
+ half_significand += 1;
+ if half_significand == 0x400 {
+ // The carry may overflow the exponent.
+ half_significand = 0;
+ half_exponent += 1;
+ if half_exponent >= 0x1f {
+ return Self::with_bits(sign | 0x7c00);
+ }
+ }
+ }
+ return Self::with_bits(sign | (half_exponent << 10) | half_significand);
+ }
+
+ if unbiased < -25 {
+ return Self::with_bits(sign);
+ }
+
+ // A binary16 subnormal is `m * 2^-24`.
+ let shift = (significand_bits as i32 - unbiased - 24) as u32;
+ let mut m = (significand >> shift) as u16;
+ let remainder = significand & ((1 << shift) - 1);
+ let halfway = 1 << (shift - 1);
+ if remainder > halfway || (remainder == halfway && m & 1 == 1) {
+ m += 1;
+ }
+ Self::with_bits(sign | m)
+ }
+}
+
ieee_float! {
name = Ieee32,
bits = 32,
@@ -1442,6 +1547,198 @@ mod tests {
);
}
+ /// Known bit patterns, so a widening bug that round-trips is still caught.
+ #[test]
+ fn to_f32_known_values_ieee16() {
+ let cases = [
+ (0x0000, 0x0000_0000), // +0
+ (0x8000, 0x8000_0000), // -0
+ (0x3c00, 0x3f80_0000), // 1
+ (0xbc00, 0xbf80_0000), // -1
+ (0x7bff, 0x477f_e000), // 65504, the largest finite value
+ (0x7c00, 0x7f80_0000), // infinity
+ (0x0400, 0x3880_0000), // 2^-14, smallest normal
+ (0x0001, 0x3380_0000), // 2^-24, smallest subnormal
+ (0x03ff, 0x387f_c000), // 1023 * 2^-24, largest subnormal
+ (0x0200, 0x3800_0000), // 2^-15
+ ];
+ for (input, expected) in cases {
+ assert_eq!(
+ Ieee16::with_bits(input).to_f32().to_bits(),
+ expected,
+ "bits = {input:#06x}"
+ );
+ }
+ }
+
+ /// Every midpoint must round to the neighbour with an even significand.
+ #[test]
+ fn every_tie_rounds_to_even_ieee16() {
+ for bits in 0..u16::MAX {
+ let (lo, hi) = (Ieee16::with_bits(bits), Ieee16::with_bits(bits + 1));
+ // Skip the pairs that straddle an infinity or a NaN encoding.
+ if lo.is_nan() || hi.is_nan() || (lo.bits() & 0x7fff) == 0x7bff {
+ continue;
+ }
+ let even = if bits & 1 == 0 { lo } else { hi };
+
+ let (a, b) = (lo.to_f32(), hi.to_f32());
+ let mid = (a + b) / 2.0;
+ assert_eq!(
+ Ieee16::from_f32_rne(mid),
+ even,
+ "midpoint of {:#06x} and {:#06x}",
+ bits,
+ bits + 1
+ );
+
+ // Which side is nearer depends on the sign, so only check the
+ // non-negative half.
+ if bits < 0x8000 {
+ let up = f32::from_bits(mid.to_bits() + 1);
+ let down = f32::from_bits(mid.to_bits() - 1);
+ assert_eq!(Ieee16::from_f32_rne(up), hi, "{bits:#06x} up");
+ assert_eq!(Ieee16::from_f32_rne(down), lo, "{bits:#06x} down");
+ }
+ }
+ }
+
+ /// Round-tripping is the identity, except a NaN comes back quieted.
+ #[test]
+ fn round_trip_is_identity_ieee16() {
+ for bits in 0..=u16::MAX {
+ let original = Ieee16::with_bits(bits);
+ let back = Ieee16::from_f32_rne(original.to_f32());
+ let expected = if original.is_nan() {
+ Ieee16::with_bits(bits | 0x0200)
+ } else {
+ original
+ };
+ assert_eq!(back, expected, "bits = {bits:#06x}");
+ }
+ }
+
+ /// An `f64` that is exactly an `f32` must narrow the same way either way.
+ #[test]
+ fn from_f64_rne_agrees_ieee16() {
+ for bits in 0..u16::MAX {
+ let value = Ieee16::with_bits(bits);
+ if value.is_nan() {
+ continue;
+ }
+ let as_f64 = f64::from(value.to_f32());
+ assert_eq!(
+ Ieee16::from_f64_rne(as_f64),
+ Ieee16::from_f32_rne(value.to_f32()),
+ "bits = {bits:#06x}"
+ );
+ }
+ }
+
+ /// The same trap for a fused multiply-add: the exact product and sum needs
+ /// more than 24 bits.
+ #[test]
+ fn fma_does_not_double_round_ieee16() {
+ let (x, y, z) = (
+ f64::from(Ieee16::with_bits(0x520b).to_f32()),
+ f64::from(Ieee16::with_bits(0x00e9).to_f32()),
+ f64::from(Ieee16::with_bits(0x2ff6).to_f32()),
+ );
+ // Exact in f64: the product needs 22 bits, the sum under 34. Not
+ // `mul_add`, which is not correct on every target.
+ let exact = x * y + z;
+ assert_eq!(Ieee16::from_f64_rne(exact).bits(), 0x3001);
+ assert_eq!(Ieee16::from_f32_rne(exact as f32).bits(), 0x3000);
+ }
+
+ /// A subnormal source has no implicit one, but every binary32 and binary64
+ /// subnormal is far below the smallest binary16 subnormal.
+ #[test]
+ fn subnormal_source_rounds_to_zero_ieee16() {
+ for bits in [0x0000_0001, 0x003f_ffff, 0x007f_ffff, 0x807f_ffff] {
+ let x = f32::from_bits(bits);
+ let expected = if bits >> 31 == 1 { 0x8000 } else { 0x0000 };
+ assert_eq!(
+ Ieee16::from_f32_rne(x).bits(),
+ expected,
+ "bits = {bits:#010x}"
+ );
+ }
+ for bits in [
+ 0x0000_0000_0000_0001,
+ 0x000f_ffff_ffff_ffff,
+ 0x800f_ffff_ffff_ffff,
+ ] {
+ let x = f64::from_bits(bits);
+ let expected = if bits >> 63 == 1 { 0x8000 } else { 0x0000 };
+ assert_eq!(
+ Ieee16::from_f64_rne(x).bits(),
+ expected,
+ "bits = {bits:#018x}"
+ );
+ }
+ // Zero itself, including both signs.
+ assert_eq!(Ieee16::from_f32_rne(0.0).bits(), 0x0000);
+ assert_eq!(Ieee16::from_f32_rne(-0.0).bits(), 0x8000);
+ assert_eq!(Ieee16::from_f64_rne(0.0).bits(), 0x0000);
+ assert_eq!(Ieee16::from_f64_rne(-0.0).bits(), 0x8000);
+ }
+
+ /// Narrowing an `f64` through `f32` can pick the wrong side of a midpoint.
+ #[test]
+ fn f64_narrowing_does_not_double_round_ieee16() {
+ let just_past = 1.0 + 2f64.powi(-11) + 2f64.powi(-40);
+ assert_eq!(Ieee16::from_f64_rne(just_past).bits(), 0x3c01);
+ assert_eq!(Ieee16::from_f64_rne(-just_past).bits(), 0xbc01);
+ assert_eq!(Ieee16::from_f32_rne(just_past as f32).bits(), 0x3c00);
+ }
+
+ #[test]
+ fn overflow_boundaries_ieee16() {
+ assert_eq!(Ieee16::from_f32_rne(65504.0).bits(), 0x7bff);
+ assert_eq!(Ieee16::from_f32_rne(65519.0).bits(), 0x7bff);
+ // The tie between 65504 and infinity rounds to even, which overflows.
+ assert_eq!(Ieee16::from_f32_rne(65520.0).bits(), 0x7c00);
+ assert_eq!(Ieee16::from_f32_rne(65536.0).bits(), 0x7c00);
+ assert_eq!(Ieee16::from_f32_rne(f32::INFINITY).bits(), 0x7c00);
+ assert_eq!(Ieee16::from_f32_rne(-f32::INFINITY).bits(), 0xfc00);
+ assert_eq!(Ieee16::from_f32_rne(1e30).bits(), 0x7c00);
+ }
+
+ #[test]
+ fn underflow_boundaries_ieee16() {
+ assert_eq!(Ieee16::from_f32_rne(2f32.powi(-14)).bits(), 0x0400);
+ assert_eq!(Ieee16::from_f32_rne(2f32.powi(-15)).bits(), 0x0200);
+ assert_eq!(Ieee16::from_f32_rne(2f32.powi(-24)).bits(), 0x0001);
+ // 2^-25 is the tie between zero and the smallest subnormal.
+ assert_eq!(Ieee16::from_f32_rne(2f32.powi(-25)).bits(), 0x0000);
+ assert_eq!(Ieee16::from_f32_rne(2f32.powi(-26)).bits(), 0x0000);
+ assert_eq!(Ieee16::from_f32_rne(0.0).bits(), 0x0000);
+ assert_eq!(Ieee16::from_f32_rne(-0.0).bits(), 0x8000);
+ }
+
+ #[test]
+ fn subnormal_rounds_up_to_smallest_normal_ieee16() {
+ assert_eq!(
+ Ieee16::from_f32_rne(Ieee16::with_bits(0x03ff).to_f32()).bits(),
+ 0x03ff
+ );
+ // The midpoint between 0x03ff and 0x0400. 1023 is odd, so the tie
+ // rounds up to the smallest normal.
+ assert_eq!(
+ Ieee16::from_f32_rne(f32::from_bits(0x387f_e000)).bits(),
+ 0x0400
+ );
+ }
+
+ #[test]
+ fn nan_is_quieted_ieee16() {
+ for input in [f32::NAN, -f32::NAN, f32::from_bits(0x7f80_0001)] {
+ let out = Ieee16::from_f32_rne(input);
+ assert!(out.is_nan(), "input = {input:e}");
+ }
+ }
+
#[test]
fn format_ieee32() {
assert_eq!(Ieee32::with_float(0.0).to_string(), "0.0");
diff --git a/cranelift/codegen/src/isa/aarch64/inst.isle b/cranelift/codegen/src/isa/aarch64/inst.isle
index 281ab5d80a..ea1e985d98 100644
--- a/cranelift/codegen/src/isa/aarch64/inst.isle
+++ b/cranelift/codegen/src/isa/aarch64/inst.isle
@@ -4609,6 +4609,17 @@
;; Helper for generating `fcopysign` instruction sequences.
(attr fcopy_sign (veri chain))
(decl fcopy_sign (Reg Reg Type) Reg)
+
+;; `fcopysign` on `f16` only moves the sign bit, so do it in integer registers:
+;; exact, and no FEAT_FP16 required.
+(rule 2 (fcopy_sign x y $F16)
+ (let ((x_bits Reg (mov_from_vec x 0 (ScalarSize.Size16)))
+ (y_bits Reg (mov_from_vec y 0 (ScalarSize.Size16)))
+ (magnitude Reg (and_imm $I32 x_bits (u64_into_imm_logic $I32 0x7fff)))
+ (sign Reg (and_imm $I32 y_bits (u64_into_imm_logic $I32 0x8000)))
+ (result Reg (orr $I32 magnitude sign)))
+ (mov_to_fpu result (ScalarSize.Size16))))
+
(rule 1 (fcopy_sign x y (ty_scalar_float ty))
(let ((dst WritableReg (temp_writable_reg $F64))
(tmp Reg (fpu_rri (fpu_op_ri_ushr (ty_bits ty) (max_shift ty)) y))
diff --git a/cranelift/codegen/src/isa/aarch64/lower.isle b/cranelift/codegen/src/isa/aarch64/lower.isle
index ebcca3d327..de5a653354 100644
--- a/cranelift/codegen/src/isa/aarch64/lower.isle
+++ b/cranelift/codegen/src/isa/aarch64/lower.isle
@@ -482,72 +482,117 @@
(rule -1 (lower (fadd ty @ (multi_lane _ _) rn rm))
(vec_rrr (VecALUOp.Fadd) rn rm (vector_size ty)))
-(rule (lower (fadd (ty_scalar_float ty) rn rm))
- (fpu_rrr (FPUOp2.Add) rn rm (scalar_size ty)))
+(rule 1 (lower (fadd $F16 rn rm))
+ (if-let true (use_fp16))
+ (fpu_rrr (FPUOp2.Add) rn rm (ScalarSize.Size16)))
+(rule (lower (fadd $F32 rn rm))
+ (fpu_rrr (FPUOp2.Add) rn rm (ScalarSize.Size32)))
+(rule (lower (fadd $F64 rn rm))
+ (fpu_rrr (FPUOp2.Add) rn rm (ScalarSize.Size64)))
;;;; Rules for `fsub` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (fsub ty @ (multi_lane _ _) rn rm))
(vec_rrr (VecALUOp.Fsub) rn rm (vector_size ty)))
-(rule fsub (lower (fsub (ty_scalar_float ty) rn rm))
- (fpu_rrr (FPUOp2.Sub) rn rm (scalar_size ty)))
+(rule 1 (lower (fsub $F16 rn rm))
+ (if-let true (use_fp16))
+ (fpu_rrr (FPUOp2.Sub) rn rm (ScalarSize.Size16)))
+(rule fsub (lower (fsub $F32 rn rm))
+ (fpu_rrr (FPUOp2.Sub) rn rm (ScalarSize.Size32)))
+(rule fsub64 (lower (fsub $F64 rn rm))
+ (fpu_rrr (FPUOp2.Sub) rn rm (ScalarSize.Size64)))
;;;; Rules for `fmul` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (fmul ty @ (multi_lane _ _) rn rm))
(vec_rrr (VecALUOp.Fmul) rn rm (vector_size ty)))
-(rule (lower (fmul (ty_scalar_float ty) rn rm))
- (fpu_rrr (FPUOp2.Mul) rn rm (scalar_size ty)))
+(rule 1 (lower (fmul $F16 rn rm))
+ (if-let true (use_fp16))
+ (fpu_rrr (FPUOp2.Mul) rn rm (ScalarSize.Size16)))
+(rule (lower (fmul $F32 rn rm))
+ (fpu_rrr (FPUOp2.Mul) rn rm (ScalarSize.Size32)))
+(rule (lower (fmul $F64 rn rm))
+ (fpu_rrr (FPUOp2.Mul) rn rm (ScalarSize.Size64)))
;;;; Rules for `fdiv` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (fdiv ty @ (multi_lane _ _) rn rm))
(vec_rrr (VecALUOp.Fdiv) rn rm (vector_size ty)))
-(rule (lower (fdiv (ty_scalar_float ty) rn rm))
- (fpu_rrr (FPUOp2.Div) rn rm (scalar_size ty)))
+(rule 1 (lower (fdiv $F16 rn rm))
+ (if-let true (use_fp16))
+ (fpu_rrr (FPUOp2.Div) rn rm (ScalarSize.Size16)))
+(rule (lower (fdiv $F32 rn rm))
+ (fpu_rrr (FPUOp2.Div) rn rm (ScalarSize.Size32)))
+(rule (lower (fdiv $F64 rn rm))
+ (fpu_rrr (FPUOp2.Div) rn rm (ScalarSize.Size64)))
;;;; Rules for `fmin` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (fmin ty @ (multi_lane _ _) rn rm))
(vec_rrr (VecALUOp.Fmin) rn rm (vector_size ty)))
-(rule (lower (fmin (ty_scalar_float ty) rn rm))
- (fpu_rrr (FPUOp2.Min) rn rm (scalar_size ty)))
+(rule 1 (lower (fmin $F16 rn rm))
+ (if-let true (use_fp16))
+ (fpu_rrr (FPUOp2.Min) rn rm (ScalarSize.Size16)))
+(rule (lower (fmin $F32 rn rm))
+ (fpu_rrr (FPUOp2.Min) rn rm (ScalarSize.Size32)))
+(rule (lower (fmin $F64 rn rm))
+ (fpu_rrr (FPUOp2.Min) rn rm (ScalarSize.Size64)))
;;;; Rules for `fmax` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (fmax ty @ (multi_lane _ _) rn rm))
(vec_rrr (VecALUOp.Fmax) rn rm (vector_size ty)))
-(rule (lower (fmax (ty_scalar_float ty) rn rm))
- (fpu_rrr (FPUOp2.Max) rn rm (scalar_size ty)))
+(rule 1 (lower (fmax $F16 rn rm))
+ (if-let true (use_fp16))
+ (fpu_rrr (FPUOp2.Max) rn rm (ScalarSize.Size16)))
+(rule (lower (fmax $F32 rn rm))
+ (fpu_rrr (FPUOp2.Max) rn rm (ScalarSize.Size32)))
+(rule (lower (fmax $F64 rn rm))
+ (fpu_rrr (FPUOp2.Max) rn rm (ScalarSize.Size64)))
;;;; Rules for `sqrt` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (sqrt ty @ (multi_lane _ _) x))
(vec_misc (VecMisc2.Fsqrt) x (vector_size ty)))
-(rule (lower (sqrt (ty_scalar_float ty) x))
- (fpu_rr (FPUOp1.Sqrt) x (scalar_size ty)))
+(rule 1 (lower (sqrt $F16 x))
+ (if-let true (use_fp16))
+ (fpu_rr (FPUOp1.Sqrt) x (ScalarSize.Size16)))
+(rule (lower (sqrt $F32 x))
+ (fpu_rr (FPUOp1.Sqrt) x (ScalarSize.Size32)))
+(rule (lower (sqrt $F64 x))
+ (fpu_rr (FPUOp1.Sqrt) x (ScalarSize.Size64)))
;;;; Rules for `fneg` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (fneg ty @ (multi_lane _ _) x))
(vec_misc (VecMisc2.Fneg) x (vector_size ty)))
-(rule (lower (fneg (ty_scalar_float ty) x))
- (fpu_rr (FPUOp1.Neg) x (scalar_size ty)))
+(rule 1 (lower (fneg $F16 x))
+ (if-let true (use_fp16))
+ (fpu_rr (FPUOp1.Neg) x (ScalarSize.Size16)))
+(rule (lower (fneg $F32 x))
+ (fpu_rr (FPUOp1.Neg) x (ScalarSize.Size32)))
+(rule (lower (fneg $F64 x))
+ (fpu_rr (FPUOp1.Neg) x (ScalarSize.Size64)))
;;;; Rules for `fabs` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(rule -1 (lower (fabs ty @ (multi_lane _ _) x))
(vec_misc (VecMisc2.Fabs) x (vector_size ty)))
-(rule (lower (fabs (ty_scalar_float ty) x))
- (fpu_rr (FPUOp1.Abs) x (scalar_size ty)))
+(rule 1 (lower (fabs $F16 x))
+ (if-let true (use_fp16))
+ (fpu_rr (FPUOp1.Abs) x (ScalarSize.Size16)))
+(rule (lower (fabs $F32 x))
+ (fpu_rr (FPUOp1.Abs) x (ScalarSize.Size32)))
+(rule (lower (fabs $F64 x))
+ (fpu_rr (FPUOp1.Abs) x (ScalarSize.Size64)))
;;;; Rules for `fpromote` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
@@ -615,17 +660,18 @@
;; * fnmadd r = -(a * b) - c / multiply, then negate, then subtract
;; * fmsub r = -(a * b) + c / multiply, then negate, then add
;; * fnmsub r = a * b - c / multiply, then subtract
+;; `partial` so that unsupported cases fail at the top level rather than panicking
(attr fmadd (tag vector))
-(decl fmadd (Type Value Value Value) Reg)
+(decl partial fmadd (Type Value Value Value) Reg)
(attr fnmadd (tag vector))
-(decl fnmadd (Type Value Value Value) Reg)
+(decl partial fnmadd (Type Value Value Value) Reg)
(attr fmsub (tag vector))
-(decl fmsub (Type Value Value Value) Reg)
+(decl partial fmsub (Type Value Value Value) Reg)
(attr fnmsub (tag vector))
-(decl fnmsub (Type Value Value Value) Reg)
+(decl partial fnmsub (Type Value Value Value) Reg)
;; Switch `fm{add,sub}` to `fnm{add,sub}` if one of the operands are negated
;; instruction instead
@@ -635,14 +681,22 @@
(rule 3 (fnmsub ty x (fneg _ y) z) (fnmadd ty x y z))
;; Scalar cases
-(rule 0 (fmadd (ty_scalar_float ty) x y z) (fpu_rrrr (FPUOp3.MAdd) (scalar_size ty) x y z))
-(rule 0 (fnmadd (ty_scalar_float ty) x y z) (fpu_rrrr (FPUOp3.NMAdd) (scalar_size ty) x y z))
-(rule 0 (fmsub (ty_scalar_float ty) x y z) (fpu_rrrr (FPUOp3.MSub) (scalar_size ty) x y z))
-(rule 0 (fnmsub (ty_scalar_float ty) x y z) (fpu_rrrr (FPUOp3.NMSub) (scalar_size ty) x y z))
+(rule 1 (fmadd $F16 x y z) (if-let true (use_fp16)) (fpu_rrrr (FPUOp3.MAdd) (ScalarSize.Size16) x y z))
+(rule 1 (fnmadd $F16 x y z) (if-let true (use_fp16)) (fpu_rrrr (FPUOp3.NMAdd) (ScalarSize.Size16) x y z))
+(rule 1 (fmsub $F16 x y z) (if-let true (use_fp16)) (fpu_rrrr (FPUOp3.MSub) (ScalarSize.Size16) x y z))
+(rule 1 (fnmsub $F16 x y z) (if-let true (use_fp16)) (fpu_rrrr (FPUOp3.NMSub) (ScalarSize.Size16) x y z))
+(rule -1 (fmadd $F32 x y z) (fpu_rrrr (FPUOp3.MAdd) (ScalarSize.Size32) x y z))
+(rule -1 (fnmadd $F32 x y z) (fpu_rrrr (FPUOp3.NMAdd) (ScalarSize.Size32) x y z))
+(rule -1 (fmsub $F32 x y z) (fpu_rrrr (FPUOp3.MSub) (ScalarSize.Size32) x y z))
+(rule -1 (fnmsub $F32 x y z) (fpu_rrrr (FPUOp3.NMSub) (ScalarSize.Size32) x y z))
+(rule -1 (fmadd $F64 x y z) (fpu_rrrr (FPUOp3.MAdd) (ScalarSize.Size64) x y z))
+(rule -1 (fnmadd $F64 x y z) (fpu_rrrr (FPUOp3.NMAdd) (ScalarSize.Size64) x y z))
+(rule -1 (fmsub $F64 x y z) (fpu_rrrr (FPUOp3.MSub) (ScalarSize.Size64) x y z))
+(rule -1 (fnmsub $F64 x y z) (fpu_rrrr (FPUOp3.NMSub) (ScalarSize.Size64) x y z))
;; Vector cases
-(rule 1 (fmadd ty @ (multi_lane _ _) x y z) (lower_fmla (VecALUModOp.Fmla) x y z (vector_size ty)))
-(rule 1 (fmsub ty @ (multi_lane _ _) x y z) (lower_fmla (VecALUModOp.Fmls) x y z (vector_size ty)))
+(rule 0 (fmadd ty @ (multi_lane _ _) x y z) (lower_fmla (VecALUModOp.Fmla) x y z (vector_size ty)))
+(rule 0 (fmsub ty @ (multi_lane _ _) x y z) (lower_fmla (VecALUModOp.Fmls) x y z (vector_size ty)))
;; Lowers a fused-multiply-add operation handling various forms of the
;; instruction to get maximal coverage of what's available on AArch64.
@@ -1280,7 +1334,12 @@
;; per-lane mask of either all ones or zeroes. rather than 0 or 1.
(rule 1 (lower (uextend (fits_in_64 _) (icmp _ cond x @ (value_type (ty_int _)) y)))
(lower_cond_result_bool (emit_icmp cond x y)))
-(rule 1 (lower (uextend (fits_in_64 _) (fcmp _ cond x @ (value_type (ty_scalar_float _)) y)))
+(rule 2 (lower (uextend (fits_in_64 _) (fcmp _ cond x @ (value_type $F16) y)))
+ (if-let true (use_fp16))
+ (lower_cond_result_bool (emit_fcmp cond x y)))
+(rule 1 (lower (uextend (fits_in_64 _) (fcmp _ cond x @ (value_type $F32) y)))
+ (lower_cond_result_bool (emit_fcmp cond x y)))
+(rule 1 (lower (uextend (fits_in_64 _) (fcmp _ cond x @ (value_type $F64) y)))
(lower_cond_result_bool (emit_fcmp cond x y)))
;; Conversion to 128-bit needs a zero-extension of the lower bits and the upper
@@ -2178,7 +2237,12 @@
(vec_size VectorSize (vector_size ty)))
(value_reg (float_cmp_zero_swap cond rn vec_size))))
-(rule 0 (lower (fcmp _ cond x @ (value_type (ty_scalar_float _)) y))
+(rule 5 (lower (fcmp _ cond x @ (value_type $F16) y))
+ (if-let true (use_fp16))
+ (lower_cond_result_bool (emit_fcmp cond x y)))
+(rule 0 (lower (fcmp _ cond x @ (value_type $F32) y))
+ (lower_cond_result_bool (emit_fcmp cond x y)))
+(rule 0 (lower (fcmp _ cond x @ (value_type $F64) y))
(lower_cond_result_bool (emit_fcmp cond x y)))
(rule -1 (lower (fcmp _ cond x @ (value_type in_ty) y))
diff --git a/cranelift/filetests/filetests/isa/aarch64/f16-arith.clif b/cranelift/filetests/filetests/isa/aarch64/f16-arith.clif
new file mode 100644
index 0000000000..9cf9d8511d
--- /dev/null
+++ b/cranelift/filetests/filetests/isa/aarch64/f16-arith.clif
@@ -0,0 +1,70 @@
+test compile precise-output
+set unwind_info=false
+target aarch64 has_fp16
+
+function %fadd_f16(f16, f16) -> f16 {
+block0(v0: f16, v1: f16):
+ v2 = fadd v0, v1
+ return v2
+}
+
+; VCode:
+; block0:
+; fadd h0, h0, h1
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fadd h0, h0, h1
+; ret
+
+function %fmul_f16(f16, f16) -> f16 {
+block0(v0: f16, v1: f16):
+ v2 = fmul v0, v1
+ return v2
+}
+
+; VCode:
+; block0:
+; fmul h0, h0, h1
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fmul h0, h0, h1
+; ret
+
+function %fabs_f16(f16) -> f16 {
+block0(v0: f16):
+ v1 = fabs v0
+ return v1
+}
+
+; VCode:
+; block0:
+; fabs h0, h0
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fabs h0, h0
+; ret
+
+function %fcmp_f16(f16, f16) -> i8 {
+block0(v0: f16, v1: f16):
+ v2 = fcmp ne v0, v1
+ return v2
+}
+
+; VCode:
+; block0:
+; fcmp h0, h1
+; cset x0, ne
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fcmp h0, h1
+; cset x0, ne
+; ret
+
diff --git a/cranelift/filetests/filetests/isa/aarch64/fcopysign-f16-fp16.clif b/cranelift/filetests/filetests/isa/aarch64/fcopysign-f16-fp16.clif
new file mode 100644
index 0000000000..73e4189d98
--- /dev/null
+++ b/cranelift/filetests/filetests/isa/aarch64/fcopysign-f16-fp16.clif
@@ -0,0 +1,30 @@
+test compile precise-output
+set unwind_info=false
+target aarch64 has_fp16
+
+function %fcopysign_f16(f16, f16) -> f16 {
+block0(v0: f16, v1: f16):
+ v2 = fcopysign v0, v1
+ return v2
+}
+
+; VCode:
+; block0:
+; umov w3, v0.h[0]
+; umov w5, v1.h[0]
+; and w7, w3, #32767
+; and w9, w5, #32768
+; orr w11, w7, w9
+; fmov h0, w11
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; umov w3, v0.h[0]
+; umov w5, v1.h[0]
+; and w7, w3, #0x7fff
+; and w9, w5, #0x8000
+; orr w11, w7, w9
+; fmov h0, w11
+; ret
+
diff --git a/cranelift/filetests/filetests/isa/aarch64/fcopysign-f16.clif b/cranelift/filetests/filetests/isa/aarch64/fcopysign-f16.clif
new file mode 100644
index 0000000000..e366129b1d
--- /dev/null
+++ b/cranelift/filetests/filetests/isa/aarch64/fcopysign-f16.clif
@@ -0,0 +1,32 @@
+test compile precise-output
+set unwind_info=false
+target aarch64
+
+;; `fmov s0, w11` is S-sized, not `fmov h0`: `mov_to_fpu` downgrades Size16 to
+;; Size32 when FEAT_FP16 is off, so no half-precision instruction is used.
+function %fcopysign_f16(f16, f16) -> f16 {
+block0(v0: f16, v1: f16):
+ v2 = fcopysign v0, v1
+ return v2
+}
+
+; VCode:
+; block0:
+; umov w3, v0.h[0]
+; umov w5, v1.h[0]
+; and w7, w3, #32767
+; and w9, w5, #32768
+; orr w11, w7, w9
+; fmov s0, w11
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; umov w3, v0.h[0]
+; umov w5, v1.h[0]
+; and w7, w3, #0x7fff
+; and w9, w5, #0x8000
+; orr w11, w7, w9
+; fmov s0, w11
+; ret
+
diff --git a/cranelift/filetests/filetests/isa/aarch64/fma-f16-fp16.clif b/cranelift/filetests/filetests/isa/aarch64/fma-f16-fp16.clif
new file mode 100644
index 0000000000..3b582a9f07
--- /dev/null
+++ b/cranelift/filetests/filetests/isa/aarch64/fma-f16-fp16.clif
@@ -0,0 +1,72 @@
+test compile precise-output
+set unwind_info=false
+target aarch64 has_fp16
+
+function %fma(f16, f16, f16) -> f16 {
+block0(v0: f16, v1: f16, v2: f16):
+ v3 = fma v0, v1, v2
+ return v3
+}
+
+; VCode:
+; block0:
+; fmadd h0, h0, h1, h2
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fmadd h0, h0, h1, h2
+; ret
+
+function %fmsub(f16, f16, f16) -> f16 {
+block0(v0: f16, v1: f16, v2: f16):
+ v3 = fneg v2
+ v4 = fma v0, v1, v3
+ return v4
+}
+
+; VCode:
+; block0:
+; fnmsub h0, h0, h1, h2
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fnmsub h0, h0, h1, h2
+; ret
+
+function %fnmsub(f16, f16, f16) -> f16 {
+block0(v0: f16, v1: f16, v2: f16):
+ v3 = fneg v0
+ v4 = fma v3, v1, v2
+ return v4
+}
+
+; VCode:
+; block0:
+; fmsub h0, h0, h1, h2
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fmsub h0, h0, h1, h2
+; ret
+
+function %fnmadd(f16, f16, f16) -> f16 {
+block0(v0: f16, v1: f16, v2: f16):
+ v3 = fneg v0
+ v4 = fneg v2
+ v5 = fma v3, v1, v4
+ return v5
+}
+
+; VCode:
+; block0:
+; fnmadd h0, h0, h1, h2
+; ret
+;
+; Disassembled:
+; block0: ; offset 0x0
+; fnmadd h0, h0, h1, h2
+; ret
+
diff --git a/cranelift/filetests/filetests/isa/aarch64/fma-f16.clif b/cranelift/filetests/filetests/isa/aarch64/fma-f16.clif
index eb6c0bc9bf..860d24db42 100644
--- a/cranelift/filetests/filetests/isa/aarch64/fma-f16.clif
+++ b/cranelift/filetests/filetests/isa/aarch64/fma-f16.clif
@@ -1,6 +1,6 @@
test compile precise-output
set unwind_info=false
-target aarch64
+target aarch64 has_fp16
function %f0(f16, f16, f16) -> f16 {
block0(v0: f16, v1: f16, v2: f16):
diff --git a/cranelift/filetests/filetests/runtests/f16-arithmetic.clif b/cranelift/filetests/filetests/runtests/f16-arithmetic.clif
index 9663cd63b1..d5ca040c34 100644
--- a/cranelift/filetests/filetests/runtests/f16-arithmetic.clif
+++ b/cranelift/filetests/filetests/runtests/f16-arithmetic.clif
@@ -1,3 +1,4 @@
+test interpret
test run
target riscv64 has_zfhmin has_zfh
diff --git a/cranelift/filetests/filetests/runtests/f16-conversions.clif b/cranelift/filetests/filetests/runtests/f16-conversions.clif
index 54e0fa6cd7..ab03e47790 100644
--- a/cranelift/filetests/filetests/runtests/f16-conversions.clif
+++ b/cranelift/filetests/filetests/runtests/f16-conversions.clif
@@ -1,3 +1,4 @@
+test interpret
test run
target riscv64 has_zfhmin
@@ -33,6 +34,9 @@ block0(v0: f64):
v1 = fdemote.f16 v0
return v1
}
-
; run: %fdemote_f64_f16(0x1.003p0) == 0x1.004p0
; run: %fdemote_f64_f16(-Inf) == -Inf
+; Just past the midpoint 0x1.002p0. Narrowing via f32 rounds it exactly onto
+; that midpoint, and ties-to-even then picks 0x1.000p0.
+; run: %fdemote_f64_f16(0x1.0020000001p0) == 0x1.004p0
+; run: %fdemote_f64_f16(-0x1.0020000001p0) == -0x1.004p0
diff --git a/cranelift/filetests/filetests/runtests/f16-fma.clif b/cranelift/filetests/filetests/runtests/f16-fma.clif
index ad97f3327c..74e5a664e5 100644
--- a/cranelift/filetests/filetests/runtests/f16-fma.clif
+++ b/cranelift/filetests/filetests/runtests/f16-fma.clif
@@ -1,3 +1,4 @@
+test interpret
test run
target riscv64 has_zfhmin has_zfh
@@ -7,6 +8,8 @@ block0(v0: f16, v1: f16, v2: f16):
return v3
}
; run: %fmadd(0x7.0, 0x8.0, 0x9.0) == 0x1.040p6
+; Rounding to f32 before narrowing would give 0x1.0000p-3 here.
+; run: %fmadd(0x1.82cp5, 0x1.d20p-17, 0x1.fd8p-4) == 0x1.004p-3
diff --git a/cranelift/filetests/filetests/runtests/f16-interpret.clif b/cranelift/filetests/filetests/runtests/f16-interpret.clif
new file mode 100644
index 0000000000..0d06e7ccbd
--- /dev/null
+++ b/cranelift/filetests/filetests/runtests/f16-interpret.clif
@@ -0,0 +1,53 @@
+test interpret
+
+function %fcvt_from_sint(i32) -> f16 {
+block0(v0: i32):
+ v1 = fcvt_from_sint.f16 v0
+ return v1
+}
+; run: %fcvt_from_sint(0) == 0x0.0
+; run: %fcvt_from_sint(1) == 0x1.000p0
+; run: %fcvt_from_sint(-1) == -0x1.000p0
+; run: %fcvt_from_sint(2048) == 0x1.000p11
+
+function %fcvt_to_sint(f16) -> i32 {
+block0(v0: f16):
+ v1 = fcvt_to_sint.i32 v0
+ return v1
+}
+; run: %fcvt_to_sint(0x1.000p0) == 1
+; run: %fcvt_to_sint(-0x1.000p0) == -1
+; run: %fcvt_to_sint(0x1.000p11) == 2048
+
+function %fcmp_ne(f16, f16) -> i8 {
+block0(v0: f16, v1: f16):
+ v2 = fcmp ne v0, v1
+ return v2
+}
+; run: %fcmp_ne(0x1.000p0, 0x1.000p0) == 0
+; run: %fcmp_ne(0x1.000p0, 0x2.000p0) == 1
+; run: %fcmp_ne(NaN:0x1, NaN:0x1) == 1
+
+function %fcmp_unord(f16, f16) -> i8 {
+block0(v0: f16, v1: f16):
+ v2 = fcmp uno v0, v1
+ return v2
+}
+; run: %fcmp_unord(NaN:0x1, 0x1.000p0) == 1
+; run: %fcmp_unord(0x1.000p0, 0x2.000p0) == 0
+
+function %fmin(f16, f16) -> f16 {
+block0(v0: f16, v1: f16):
+ v2 = fmin v0, v1
+ return v2
+}
+; run: %fmin(0x1.000p0, 0x2.000p0) == 0x1.000p0
+; run: %fmin(0x1.000p0, 0x1.000p0) == 0x1.000p0
+
+function %fmax(f16, f16) -> f16 {
+block0(v0: f16, v1: f16):
+ v2 = fmax v0, v1
+ return v2
+}
+; run: %fmax(0x1.000p0, 0x2.000p0) == 0x2.000p0
+; run: %fmax(-0x0.0, 0x0.0) == 0x0.0
diff --git a/cranelift/interpreter/src/step.rs b/cranelift/interpreter/src/step.rs
index 8e4c5bd1de..9c57a92117 100644
--- a/cranelift/interpreter/src/step.rs
+++ b/cranelift/interpreter/src/step.rs
@@ -7,6 +7,7 @@ use crate::state::{InterpreterFunctionRef, MemoryError, State};
use crate::value::{DataValueExt, ValueConversionKind, ValueError, ValueResult};
use cranelift_codegen::data_value::DataValue;
use cranelift_codegen::ir::condcodes::{FloatCC, IntCC};
+use cranelift_codegen::ir::immediates::Ieee16;
use cranelift_codegen::ir::{
AbiParam, AtomicRmwOp, Block, BlockArg, BlockCall, Endianness, ExternalName, FuncRef, Function,
InstructionData, Opcode, TrapCode, Type, Value as ValueRef, types,
@@ -1125,6 +1126,14 @@ where
)?;
let bits = |x: DataValue| -> ValueResult<u64> {
Ok(match ctrl_ty.lane_type() {
+ types::F16 => {
+ let v = if inst.opcode() == Opcode::FcvtFromUint {
+ x.into_int_unsigned()? as f32
+ } else {
+ x.into_int_signed()? as f32
+ };
+ Ieee16::from_f32_rne(v).bits() as u64
+ }
types::F32 => (if inst.opcode() == Opcode::FcvtFromUint {
x.into_int_unsigned()? as f32
} else {
diff --git a/cranelift/interpreter/src/value.rs b/cranelift/interpreter/src/value.rs
index a6987e24d9..dee0da96f3 100644
--- a/cranelift/interpreter/src/value.rs
+++ b/cranelift/interpreter/src/value.rs
@@ -254,6 +254,15 @@ macro_rules! bitop {
};
}
+/// f16 arithmetic runs in f32: `to_f32` is exact and `from_f32_rne` rounds once.
+fn f16_binop(a: Ieee16, b: Ieee16, f: impl Fn(f32, f32) -> f32) -> DataValue {
+ DataValue::F16(Ieee16::from_f32_rne(f(a.to_f32(), b.to_f32())))
+}
+
+fn f16_unop(a: Ieee16, f: impl Fn(f32) -> f32) -> DataValue {
+ DataValue::F16(Ieee16::from_f32_rne(f(a.to_f32())))
+}
+
impl DataValueExt for DataValue {
fn int(n: i128, ty: Type) -> ValueResult<Self> {
if ty.is_vector() {
@@ -294,6 +303,7 @@ impl DataValueExt for DataValue {
fn float(bits: u64, ty: Type) -> ValueResult<Self> {
match ty {
+ types::F16 => Ok(DataValue::F16(Ieee16::with_bits(u16::try_from(bits)?))),
types::F32 => Ok(DataValue::F32(Ieee32::with_bits(u32::try_from(bits)?))),
types::F64 => Ok(DataValue::F64(Ieee64::with_bits(bits))),
_ => Err(ValueError::InvalidType(ValueTypeClass::Float, ty)),
@@ -302,6 +312,7 @@ impl DataValueExt for DataValue {
fn into_float(self) -> ValueResult<f64> {
match self {
+ DataValue::F16(n) => Ok(n.to_f32() as f64),
DataValue::F32(n) => Ok(n.as_f32() as f64),
DataValue::F64(n) => Ok(n.as_f64()),
_ => Err(ValueError::InvalidType(ValueTypeClass::Float, self.ty())),
@@ -317,6 +328,7 @@ impl DataValueExt for DataValue {
fn is_nan(&self) -> ValueResult<bool> {
match self {
+ DataValue::F16(f) => Ok(f.is_nan()),
DataValue::F32(f) => Ok(f.is_nan()),
DataValue::F64(f) => Ok(f.is_nan()),
_ => Err(ValueError::InvalidType(ValueTypeClass::Float, self.ty())),
@@ -404,6 +416,8 @@ impl DataValueExt for DataValue {
(DataValue::F32(n), types::I32) => DataValue::I32(n.bits() as i32),
(DataValue::F64(n), types::I64) => DataValue::I64(n.bits() as i64),
(DataValue::F128(n), types::I128) => DataValue::I128(n.bits() as i128),
+ (DataValue::F16(n), types::F32) => DataValue::F32(n.to_f32().into()),
+ (DataValue::F16(n), types::F64) => DataValue::F64(f64::from(n.to_f32()).into()),
(DataValue::F32(n), types::F64) => DataValue::F64((n.as_f32() as f64).into()),
(dv, t) if (t.is_int() || t.is_float()) && dv.ty() == t => dv,
(dv, _) => unimplemented!("conversion: {} -> {:?}", dv.ty(), kind),
@@ -464,6 +478,8 @@ impl DataValueExt for DataValue {
},
ValueConversionKind::RoundNearestEven(ty) => match (self, ty) {
(DataValue::F64(n), types::F32) => DataValue::F32(Ieee32::from(n.as_f64() as f32)),
+ (DataValue::F32(n), types::F16) => DataValue::F16(Ieee16::from_f32_rne(n.as_f32())),
+ (DataValue::F64(n), types::F16) => DataValue::F16(Ieee16::from_f64_rne(n.as_f64())),
(s, _) => unimplemented!("conversion: {} -> {:?}", s.ty(), kind),
},
ValueConversionKind::ToBoolean => match self.ty() {
@@ -490,6 +506,7 @@ impl DataValueExt for DataValue {
fn is_negative(&self) -> ValueResult<bool> {
match self {
+ DataValue::F16(f) => Ok(f.is_negative()),
DataValue::F32(f) => Ok(f.is_negative()),
DataValue::F64(f) => Ok(f.is_negative()),
_ => Err(ValueError::InvalidType(ValueTypeClass::Float, self.ty())),
@@ -539,6 +556,9 @@ impl DataValueExt for DataValue {
fn add(self, other: Self) -> ValueResult<Self> {
if self.is_float() {
+ if let (DataValue::F16(a), DataValue::F16(b)) = (&self, &other) {
+ return Ok(f16_binop(*a, *b, |x, y| x + y));
+ }
binary_match!(+(self, other); [F32, F64])
} else {
binary_match!(wrapping_add(&self, &other); [I8, I16, I32, I64, I128])
@@ -547,6 +567,9 @@ impl DataValueExt for DataValue {
fn sub(self, other: Self) -> ValueResult<Self> {
if self.is_float() {
+ if let (DataValue::F16(a), DataValue::F16(b)) = (&self, &other) {
+ return Ok(f16_binop(*a, *b, |x, y| x - y));
+ }
binary_match!(-(self, other); [F32, F64])
} else {
binary_match!(wrapping_sub(&self, &other); [I8, I16, I32, I64, I128])
@@ -555,6 +578,9 @@ impl DataValueExt for DataValue {
fn mul(self, other: Self) -> ValueResult<Self> {
if self.is_float() {
+ if let (DataValue::F16(a), DataValue::F16(b)) = (&self, &other) {
+ return Ok(f16_binop(*a, *b, |x, y| x * y));
+ }
binary_match!(*(self, other); [F32, F64])
} else {
binary_match!(wrapping_mul(&self, &other); [I8, I16, I32, I64, I128])
@@ -563,6 +589,9 @@ impl DataValueExt for DataValue {
fn sdiv(self, other: Self) -> ValueResult<Self> {
if self.is_float() {
+ if let (DataValue::F16(a), DataValue::F16(b)) = (&self, &other) {
+ return Ok(f16_binop(*a, *b, |x, y| x / y));
+ }
return binary_match!(/(self, other); [F32, F64]);
}
@@ -583,6 +612,9 @@ impl DataValueExt for DataValue {
fn udiv(self, other: Self) -> ValueResult<Self> {
if self.is_float() {
+ if let (DataValue::F16(a), DataValue::F16(b)) = (&self, &other) {
+ return Ok(f16_binop(*a, *b, |x, y| x / y));
+ }
return binary_match!(/(self, other); [F32, F64]);
}
@@ -622,11 +654,31 @@ impl DataValueExt for DataValue {
}
fn sqrt(self) -> ValueResult<Self> {
+ if let DataValue::F16(a) = &self {
+ return Ok(f16_unop(*a, f32::sqrt));
+ }
unary_match!(sqrt(&self); [F32, F64]; [Ieee32, Ieee64])
}
fn fma(self, b: Self, c: Self) -> ValueResult<Self> {
match (self, b, c) {
+ (DataValue::F16(a), DataValue::F16(b), DataValue::F16(c)) => {
+ // f64, not f32: a fused multiply-add must see the unrounded
+ // product and sum, which needs more than 24 bits.
+ let (x, y, z) = (a.to_f32() as f64, b.to_f32() as f64, c.to_f32() as f64);
+
+ #[cfg(all(target_arch = "x86_64", target_os = "windows", target_env = "gnu"))]
+ let res = libm::fma(x, y, z);
+
+ #[cfg(not(all(
+ target_arch = "x86_64",
+ target_os = "windows",
+ target_env = "gnu"
+ )))]
+ let res = x.mul_add(y, z);
+
+ Ok(DataValue::F16(Ieee16::from_f64_rne(res)))
+ }
(DataValue::F32(a), DataValue::F32(b), DataValue::F32(c)) => {
// The `fma` function for `x86_64-pc-windows-gnu` is incorrect. Use `libm`'s instead.
// See: https://github.com/bytecodealliance/wasmtime/issues/4512
@@ -660,7 +712,7 @@ impl DataValueExt for DataValue {
}
fn abs(self) -> ValueResult<Self> {
- unary_match!(abs(&self); [F32, F64])
+ unary_match!(abs(&self); [F16, F32, F64])
}
fn sadd_checked(self, other: Self) -> ValueResult<Option<Self>> {
@@ -696,26 +748,38 @@ impl DataValueExt for DataValue {
}
fn neg(self) -> ValueResult<Self> {
- unary_match!(neg(&self); [F32, F64])
+ unary_match!(neg(&self); [F16, F32, F64])
}
fn copysign(self, sign: Self) -> ValueResult<Self> {
- binary_match!(copysign(&self, &sign); [F32, F64])
+ binary_match!(copysign(&self, &sign); [F16, F32, F64])
}
fn ceil(self) -> ValueResult<Self> {
+ if let DataValue::F16(a) = &self {
+ return Ok(f16_unop(*a, f32::ceil));
+ }
unary_match!(ceil(&self); [F32, F64])
}
fn floor(self) -> ValueResult<Self> {
+ if let DataValue::F16(a) = &self {
+ return Ok(f16_unop(*a, f32::floor));
+ }
unary_match!(floor(&self); [F32, F64])
}
fn trunc(self) -> ValueResult<Self> {
+ if let DataValue::F16(a) = &self {
+ return Ok(f16_unop(*a, f32::trunc));
+ }
unary_match!(trunc(&self); [F32, F64])
}
fn nearest(self) -> ValueResult<Self> {
+ if let DataValue::F16(a) = &self {
+ return Ok(f16_unop(*a, f32::round_ties_even));
+ }
unary_match!(round_ties_even(&self); [F32, F64])
}