//! Canonical binary64 adapter. Host f64 is a bit carrier only; arithmetic and //! comparisons use SoftF64. Integer conversions and ties-even rounding use bits. use fpmath::SoftF64 as F; use prometeu_bytecode::{TRAP_DIV_ZERO, TRAP_NON_FINITE, TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE}; pub(crate) const PI_BITS: u64 = 0x4009_21fb_5444_2d18; pub(crate) const TAU_BITS: u64 = 0x4019_21fb_5444_2d18; const PI_2_BITS: u64 = 0x3ff9_21fb_5444_2d18; const SIGN: u64 = 1 << 63; const MAG: u64 = !SIGN; const EXP: u64 = 0x7ff0_0000_0000_0000; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct NumericError { pub code: u32, pub argument: Option, } impl NumericError { pub(crate) fn new(code: u32) -> Self { Self { code, argument: None } } } pub(crate) type Result = std::result::Result; pub(crate) fn finite(x: f64) -> bool { x.to_bits() & EXP != EXP } pub(crate) fn check_inputs(values: &[f64]) -> Result<()> { for (argument, &value) in values.iter().enumerate() { if !finite(value) { return Err(NumericError { code: TRAP_NON_FINITE, argument: Some(argument) }); } } Ok(()) } fn soft(x: f64) -> F { F::from_bits(x.to_bits()) } fn output(x: F) -> Result { let bits = x.to_bits(); if bits & EXP == EXP { Err(NumericError::new(TRAP_NUMERIC_RANGE)) } else { Ok(f64::from_bits(bits)) } } pub(crate) fn zero(x: f64) -> bool { x.to_bits() & MAG == 0 } pub(crate) fn cmp(a: f64, b: f64) -> std::cmp::Ordering { // All callers check finitude first. Both zeros compare equal. soft(a).partial_cmp(&soft(b)).expect("finite binary64 comparison") } pub(crate) fn abs(x: f64) -> f64 { f64::from_bits(x.to_bits() & MAG) } pub(crate) fn neg(x: f64) -> Result { check_inputs(&[x])?; Ok(f64::from_bits(x.to_bits() ^ SIGN)) } pub(crate) fn min(a: f64, b: f64) -> f64 { if zero(a) && zero(b) { f64::from_bits(a.to_bits() | b.to_bits()) } else if cmp(a, b).is_gt() { b } else { a } } pub(crate) fn max(a: f64, b: f64) -> f64 { if zero(a) && zero(b) { f64::from_bits(a.to_bits() & b.to_bits()) } else if cmp(a, b).is_lt() { b } else { a } } pub(crate) fn clamp(value: f64, lo: f64, hi: f64) -> Result { check_inputs(&[value, lo, hi])?; if cmp(lo, hi).is_gt() { return Err(NumericError::new(TRAP_NUMERIC_DOMAIN)); } Ok(min(max(value, lo), hi)) } pub(crate) fn add(a: f64, b: f64) -> Result { check_inputs(&[a, b])?; output(soft(a) + soft(b)) } pub(crate) fn sub(a: f64, b: f64) -> Result { check_inputs(&[a, b])?; output(soft(a) - soft(b)) } pub(crate) fn mul(a: f64, b: f64) -> Result { check_inputs(&[a, b])?; output(soft(a) * soft(b)) } pub(crate) fn div(a: f64, b: f64) -> Result { check_inputs(&[a, b])?; if zero(b) { return Err(NumericError::new(TRAP_DIV_ZERO)); } output(soft(a) / soft(b)) } pub(crate) fn sqrt(x: f64) -> Result { check_inputs(&[x])?; if !zero(x) && x.to_bits() & SIGN != 0 { return Err(NumericError::new(TRAP_NUMERIC_DOMAIN)); } output(fpmath::sqrt(soft(x))) } pub(crate) fn sin(x: f64) -> Result { check_inputs(&[x])?; output(fpmath::sin(soft(x))) } pub(crate) fn cos(x: f64) -> Result { check_inputs(&[x])?; output(fpmath::cos(soft(x))) } pub(crate) fn atan2(y: f64, x: f64) -> Result { check_inputs(&[y, x])?; let sign_y = y.to_bits() & SIGN; if zero(y) { if zero(x) { return Err(NumericError::new(TRAP_NUMERIC_DOMAIN)); } return Ok(f64::from_bits(sign_y | if x.to_bits() & SIGN != 0 { PI_BITS } else { 0 })); } if zero(x) { return Ok(f64::from_bits(sign_y | PI_2_BITS)); } output(fpmath::atan2(soft(y), soft(x))) } pub(crate) fn floor(x: f64) -> Result { check_inputs(&[x])?; output(fpmath::floor(soft(x))) } pub(crate) fn ceil(x: f64) -> Result { check_inputs(&[x])?; output(fpmath::ceil(soft(x))) } pub(crate) fn trunc(x: f64) -> Result { check_inputs(&[x])?; output(fpmath::trunc(soft(x))) } pub(crate) fn round(x: f64) -> Result { check_inputs(&[x])?; let bits = x.to_bits(); let sign = bits & SIGN; let magnitude = bits & MAG; let exponent = ((magnitude >> 52) as i32) - 1023; let rounded = if exponent >= 52 { magnitude } else if exponent < -1 { 0 } else if exponent == -1 { // Exactly +/-0.5 ties to signed zero, all larger magnitudes to +/-1. if magnitude == 0x3fe0_0000_0000_0000 { 0 } else { 0x3ff0_0000_0000_0000 } } else { let shift = 52 - exponent; let unit = 1u64 << shift; let remainder = magnitude & (unit - 1); let half = unit >> 1; let integral = magnitude & !(unit - 1); integral + if remainder > half || (remainder == half && integral & unit != 0) { unit } else { 0 } }; Ok(f64::from_bits(sign | rounded)) } pub(crate) fn from_i64(value: i64) -> f64 { let magnitude = value.unsigned_abs(); if magnitude == 0 { return f64::from_bits(0); } let sign = if value < 0 { SIGN } else { 0 }; let mut exponent = 63 - magnitude.leading_zeros(); let mut significand = if exponent <= 52 { magnitude << (52 - exponent) } else { let shift = exponent - 52; let unit = 1u64 << shift; let mut sig = magnitude >> shift; let rem = magnitude & (unit - 1); if rem > unit / 2 || (rem == unit / 2 && sig & 1 != 0) { sig += 1; } sig }; if significand == 1u64 << 53 { significand >>= 1; exponent += 1; } f64::from_bits(sign | (u64::from(exponent + 1023) << 52) | (significand & ((1 << 52) - 1))) } pub(crate) fn to_i64(x: f64, width: u32) -> Result { check_inputs(&[x])?; let bits = x.to_bits(); let exponent = ((bits & EXP) >> 52) as i32 - 1023; if exponent < 0 { return Ok(0); } if exponent > 63 { return Err(NumericError::new(TRAP_NUMERIC_RANGE)); } let significand = (bits & ((1 << 52) - 1)) | (1 << 52); let magnitude = if exponent >= 52 { significand << (exponent - 52) } else { significand >> (52 - exponent) }; let negative = bits & SIGN != 0; let limit = 1u64 << (width - 1); if magnitude > limit || (magnitude == limit && !negative) { return Err(NumericError::new(TRAP_NUMERIC_RANGE)); } // unsigned magnitude handles exactly -2^63 without an intermediate overflow. Ok(if negative { magnitude.wrapping_neg() as i64 } else { magnitude as i64 }) } pub(crate) fn dot(a: [f64; 4]) -> Result { check_inputs(&a)?; let p1 = mul(a[0], a[2])?; let p2 = mul(a[1], a[3])?; add(p1, p2) } pub(crate) fn length(x: f64, y: f64) -> Result { check_inputs(&[x, y])?; let ax = abs(x); let ay = abs(y); let m = max(ax, ay); let n = min(ax, ay); if zero(m) { return Ok(f64::from_bits(0)); } let r = div(n, m)?; let q = mul(r, r)?; let s = add(f64::from_bits(0x3ff0_0000_0000_0000), q)?; let t = sqrt(s)?; mul(m, t) } fn promoted(value: &prometeu_bytecode::Value) -> Option { use prometeu_bytecode::Value; match value { Value::Int32(v) => Some(from_i64(i64::from(*v))), Value::Int64(v) => Some(from_i64(*v)), Value::Float(v) => Some(*v), _ => None, } } pub(crate) fn opcode_binary( op: prometeu_bytecode::isa::core::CoreOpCode, a: &prometeu_bytecode::Value, b: &prometeu_bytecode::Value, ) -> Result { use prometeu_bytecode::isa::core::CoreOpCode as Op; use prometeu_bytecode::{TRAP_TYPE, Value}; if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) { let (Some(a), Some(b)) = (promoted(a), promoted(b)) else { return Err(NumericError::new(TRAP_TYPE)); }; return Ok(Value::Float(match op { Op::Add => add(a, b)?, Op::Sub => sub(a, b)?, Op::Mul => mul(a, b)?, Op::Div => div(a, b)?, _ => unreachable!(), })); } let (a, b, narrow) = match (a, b) { (Value::Int32(a), Value::Int32(b)) => (i64::from(*a), i64::from(*b), true), (Value::Int32(a), Value::Int64(b)) => (i64::from(*a), *b, false), (Value::Int64(a), Value::Int32(b)) => (*a, i64::from(*b), false), (Value::Int64(a), Value::Int64(b)) => (*a, *b, false), _ => return Err(NumericError::new(TRAP_TYPE)), }; if op == Op::Div && b == 0 { return Err(NumericError::new(TRAP_DIV_ZERO)); } if narrow { let (a, b) = (a as i32, b as i32); return Ok(Value::Int32(match op { Op::Add => a.wrapping_add(b), Op::Sub => a.wrapping_sub(b), Op::Mul => a.wrapping_mul(b), Op::Div => a.wrapping_div(b), _ => unreachable!(), })); } Ok(Value::Int64(match op { Op::Add => a.wrapping_add(b), Op::Sub => a.wrapping_sub(b), Op::Mul => a.wrapping_mul(b), Op::Div => a.wrapping_div(b), _ => unreachable!(), })) } pub(crate) fn compare_values( a: &prometeu_bytecode::Value, b: &prometeu_bytecode::Value, ) -> Result> { use prometeu_bytecode::Value; if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) { let (Some(a), Some(b)) = (promoted(a), promoted(b)) else { return Ok(None); }; check_inputs(&[a, b])?; Ok(Some(cmp(a, b))) } else { Ok(a.partial_cmp(b)) } } pub(crate) fn equal_values( a: &prometeu_bytecode::Value, b: &prometeu_bytecode::Value, ) -> Result { use prometeu_bytecode::Value; if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) { Ok(compare_values(a, b)? == Some(std::cmp::Ordering::Equal)) } else { Ok(a == b) } }