From ffa17a0f2e8946aee8d7a2baab1909b8bfc30f19 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:44:30 +0000 Subject: [PATCH] perf(compiler): keep FP zero, infinite and Half operands in compiled code, and admit FMA3, F16C and AVX2 with live YMM state --- crates/stela-boot-core/src/topology.rs | 14 +- crates/stela-boot-core/src/topology/tests.rs | 36 ++ crates/stela-boot/src/engine/interrupts.rs | 5 +- .../src/x86_64/simd/arithmetic.rs | 36 +- .../src/x86_64/simd/comparison.rs | 74 +++- .../stela-compiler/src/x86_64/simd/fused.rs | 56 ++- .../src/x86_64/simd/fused/tests.rs | 308 ++++++++++++++++ .../src/x86_64/simd/numerical.rs | 13 +- .../src/x86_64/simd/precision.rs | 94 +++-- .../src/floating/arithmetic/tests/native.rs | 11 +- crates/stela-engine/src/floating/tests.rs | 1 + .../src/floating/tests/changed_native.rs | 340 ++++++++++++++++++ .../src/memory/domain/native_target.rs | 27 +- .../stela-engine/src/platform/cpu/system.rs | 45 ++- .../src/platform/cpu/system/tests.rs | 38 ++ crates/stela-engine/tests/blocks.rs | 225 ++++++++++++ 16 files changed, 1225 insertions(+), 98 deletions(-) create mode 100644 crates/stela-compiler/src/x86_64/simd/fused/tests.rs create mode 100644 crates/stela-engine/src/floating/tests/changed_native.rs diff --git a/crates/stela-boot-core/src/topology.rs b/crates/stela-boot-core/src/topology.rs index 5bc87d4aea..b8eeaba3ac 100644 --- a/crates/stela-boot-core/src/topology.rs +++ b/crates/stela-boot-core/src/topology.rs @@ -343,6 +343,11 @@ pub fn common_native_target( const AVX: u32 = 1 << 28; const BMI1: u32 = 1 << 3; const BMI2: u32 = 1 << 8; + const FMA: u32 = 1 << 12; + const F16C: u32 = 1 << 29; + const AVX2: u32 = 1 << 5; + /// XCR0's SSE and AVX bits: the OS saves XMM and YMM state. + const XCR0_YMM: u64 = 0x6; /// AMD's first family whose PDEP and PEXT are not microcoded (Zen 3). const FAST_PDEP_FAMILY: u32 = 0x19; if observations.is_empty() || observations.len() > MAX_CORES { @@ -355,6 +360,9 @@ pub fn common_native_target( // VEX-encoded scalar GPR extensions, which use no extended state: // Intel's Pentium and Celeron parts without AVX fault on them. let mut vex = true; + // VEX vector recipes: AVX hardware whose XMM and YMM state the + // installed worker's XCR0 enables, which the interrupt entries save. + let mut ymm = true; // AMD's Zen 1 and Zen 2, and Hygon's Zen-derived cores, microcode PDEP // and PEXT; the display family tells them apart. let mut fast_pdep = true; @@ -384,6 +392,7 @@ pub fn common_native_target( let vendor = [vendor.ebx, vendor.edx, vendor.ecx]; atomic16 &= TargetCpu::atomic_load16_guaranteed(vendor, basic.ecx); vex &= vendor != TargetCpu::INTEL_VENDOR || basic.ecx & AVX != 0; + ymm &= basic.ecx & AVX != 0 && snapshot.xcr0_valid && snapshot.xcr0 & XCR0_YMM == XCR0_YMM; let base_family = (basic.eax >> 8) & 0xf; let family = if base_family == 0xf { base_family + ((basic.eax >> 20) & 0xff) @@ -417,6 +426,9 @@ pub fn common_native_target( (bmi2, TargetCpu::with_bmi2), (bmi2 && fast_pdep, TargetCpu::with_fast_pdep), (ecx & MOVBE != 0, TargetCpu::with_movbe), + (ymm && ecx & FMA != 0, TargetCpu::with_fma), + (ymm && ecx & F16C != 0, TargetCpu::with_f16c), + (ymm && structured_ebx & AVX2 != 0, TargetCpu::with_avx2), ] { if present { target = with(target); @@ -425,7 +437,7 @@ pub fn common_native_target( Ok(target) } -/// The initial native executor uses legacy XMM state only. It +/// The native executor's floor is legacy XMM state. It /// derives this floor on each physical core rather than borrowing the /// BSP's CPUID or firmware OSXSAVE state. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/stela-boot-core/src/topology/tests.rs b/crates/stela-boot-core/src/topology/tests.rs index c2693688e4..c41fa58c38 100644 --- a/crates/stela-boot-core/src/topology/tests.rs +++ b/crates/stela-boot-core/src/topology/tests.rs @@ -627,6 +627,42 @@ fn common_target_keeps_only_features_present_on_every_assigned_worker() { } } +/// FMA3, F16C and AVX2 need AVX hardware whose YMM state every installed +/// worker's XCR0 enables, as the interrupt entries save it. +#[test] +fn common_target_keeps_vex_vector_recipes_only_with_every_worker_ymm_state() { + use stela_compiler::TargetCpu; + const AVX2: u32 = 1 << 5; + let mut rich = target_snapshot(TargetCpu::AMD_VENDOR); + rich.records[2].ebx |= AVX2; + rich.xcr0 = 0x7; + rich.xcr0_valid = true; + let vector = TargetCpu::Baseline.with_fma().with_f16c().with_avx2(); + assert!(common_native_target(&[&rich]).unwrap().supports(vector)); + assert!( + !common_native_target(&[&rich]) + .unwrap() + .supports(TargetCpu::Avx512f) + ); + let mut legacy_state = rich; + legacy_state.xcr0 = 0x3; + let mut unobserved = rich; + unobserved.xcr0_valid = false; + let mut without_avx = rich; + without_avx.records[0].ecx &= !(1 << 28); + for worker in [legacy_state, unobserved, without_avx] { + let common = common_native_target(&[&rich, &worker]).unwrap(); + for excluded in [TargetCpu::Fma, TargetCpu::F16c, TargetCpu::Avx2] { + assert!(!common.supports(excluded)); + } + } + let mut without_avx2 = rich; + without_avx2.records[2].ebx &= !AVX2; + let common = common_native_target(&[&rich, &without_avx2]).unwrap(); + assert!(common.supports(TargetCpu::Baseline.with_fma().with_f16c())); + assert!(!common.supports(TargetCpu::Avx2)); +} + /// BMI1 and BMI2 need VEX decoding, which an Intel worker without AVX /// lacks, and fast PDEP a Zen 3 or later AMD core on every worker. #[test] diff --git a/crates/stela-boot/src/engine/interrupts.rs b/crates/stela-boot/src/engine/interrupts.rs index a01a43dc0a..52ab7dc792 100644 --- a/crates/stela-boot/src/engine/interrupts.rs +++ b/crates/stela-boot/src/engine/interrupts.rs @@ -370,8 +370,9 @@ pub(crate) unsafe fn install(handler: Handler) { } /// Turn AVX on where this CPU has it, which firmware leaves off, so host -/// code that detects AVX or F16C through XCR0 finds it usable. The translator -/// admits no AVX target; the entry stubs save the enabled state whatever it is. +/// code that detects AVX or F16C through XCR0 finds it usable, and so that +/// translated blocks may use FMA3, F16C and AVX2. The entry stubs save the +/// enabled state whatever it is. /// /// # Safety /// Ring 0 with interrupts masked, on a CPU whose extended state nothing has diff --git a/crates/stela-compiler/src/x86_64/simd/arithmetic.rs b/crates/stela-compiler/src/x86_64/simd/arithmetic.rs index b105503c90..bd8f0ac388 100644 --- a/crates/stela-compiler/src/x86_64/simd/arithmetic.rs +++ b/crates/stela-compiler/src/x86_64/simd/arithmetic.rs @@ -236,6 +236,18 @@ fn accepts_zero(operation: BinaryOperation) -> bool { } } +/// A scalar FDIV's zero dividend over a normal divisor: the quotient is +/// an exact signed zero, with no status, whatever FPCR holds. Code divides +/// zero often (a ratio or an animation's progress at its start), and each +/// one would otherwise leave compiled code. A zero quotient from a normal +/// dividend underflowed, which the host's status rejects; the divisor's +/// range check still sends a zero or infinite divisor to the helper. +fn zero_quotient(operand: &Operand) -> bool { + operand.operation == BinaryOperation::Divide + && operand.shape == Shape::Scalar + && matches!(operand.inputs, Inputs::Elementwise { .. }) +} + /// The left source, whose register the operation overwrote, for the /// out-of-line zero-product check: still unchanged in the frame. fn product_left(operand: &Operand) -> u8 { @@ -300,6 +312,20 @@ fn sticky_path(code: &mut Code, operand: &Operand, entry: Entry, target: TargetC let inline_end = code.checkpoint(); let done = jump(code); let cold = code.checkpoint(); + if zero_quotient(operand) { + // A zero quotient may be exact: the full path tells, from the + // dividend, rather than the helper. + let mut full = full; + full.push(rejected); + return StickyPath { + full, + helper: vec![], + done, + cold, + inline_end, + crossing: vec![], + }; + } let mut crossing = vec![rejected]; if !zero_product(operand.operation) { return StickyPath { @@ -368,16 +394,16 @@ fn emit_scalar( test_control(code, FPCR_EXCEPTION_ENABLE_MASK); helper.push(branch(code, Condition::NotZero)); let right = prepare_inputs(code, operand); - for right in [LEFT_VECTOR, right] { - if accepts_zero(operand.operation) { + for source in [LEFT_VECTOR, right] { + if accepts_zero(operand.operation) || (source == LEFT_VECTOR && zero_quotient(operand)) { helper.push(scalar_range_or_zero( code, operand.format, - right, + source, INPUT_MINIMUM_EXPONENT, )); } else { - exponent_range(code, operand.format, right, INPUT_MINIMUM_EXPONENT); + exponent_range(code, operand.format, source, INPUT_MINIMUM_EXPONENT); helper.push(branch(code, Condition::AboveOrEqual)); } } @@ -392,7 +418,7 @@ fn emit_scalar( restore_environment(code); // Caller environment and stack are restored before every branch from here. helper.push(reject_other_status(code)); - let success = if accepts_zero(operand.operation) { + let success = if accepts_zero(operand.operation) || zero_quotient(operand) { helper.push(scalar_range_or_zero( code, operand.format, diff --git a/crates/stela-compiler/src/x86_64/simd/comparison.rs b/crates/stela-compiler/src/x86_64/simd/comparison.rs index 6689a2898d..ec524da54d 100644 --- a/crates/stela-compiler/src/x86_64/simd/comparison.rs +++ b/crates/stela-compiler/src/x86_64/simd/comparison.rs @@ -33,6 +33,8 @@ const TEMP_VECTOR: u8 = 7; const SIGN_BITS: u8 = 1; const HALF_SIGN_SHIFT: u8 = u16::BITS as u8 - SIGN_BITS; const SINGLE_SIGN_SHIFT: u8 = u32::BITS as u8 - SIGN_BITS; +/// Moves a Half's sign to the top of a dword. +const HALF_SIGN_TO_DWORD_TOP: u8 = (u32::BITS - u16::BITS) as u8; const COMPARE_EQUAL: u8 = 0; const COMPARE_LESS: u8 = 1; const COMPARE_LESS_EQUAL: u8 = 2; @@ -149,12 +151,25 @@ fn equal_zero(code: &mut Code, format: Format, value: u8, zero: u8, temporary: u } fn vector_zero_guard(code: &mut Code, format: Format, shape: Shape, helper: &mut Vec) { + prepare_vector_input_range(code, format); + vector_zero_or_normal_guard(code, format, shape, LEFT_VECTOR, helper); +} + +/// Send `source` to the helper unless every active lane is normal, a zero +/// or an infinity, after [`prepare_vector_input_range`]. Uses TEMP_VECTOR +/// and MERGE_VECTOR. +fn vector_zero_or_normal_guard( + code: &mut Code, + format: Format, + shape: Shape, + source: u8, + helper: &mut Vec, +) { // The shared range leaves per-lane normal validity in EXPONENT_VECTOR. // OR fraction-zero validity into it: only zeros/infinities are newly // admitted, and none can change host MXCSR or guest FPSR. - prepare_vector_input_range(code, format); - vector_exponent_range(code, format, shape, LEFT_VECTOR); - packed(code, Host::MoveAligned, TEMP_VECTOR, LEFT_VECTOR); + vector_exponent_range(code, format, shape, source); + packed(code, Host::MoveAligned, TEMP_VECTOR, source); shift_left(format).emit( code, TEMP_VECTOR, @@ -189,6 +204,22 @@ fn half_order_key(code: &mut Code, vector: u8) { packed(code, Host::Xor, vector, TEMP_VECTOR); } +/// `register` takes the low Half of `vector` as a signed integer of its +/// magnitude: both zeros become 0, and finite values and infinities keep +/// their order. Uses EDX. +fn half_signed_magnitude(code: &mut Code, register: Gpr, vector: u8) { + const MAGNITUDE: i32 = 0x7fff; + let mut asm = code.asm(); + asm.movd_from_xmm(register, vector); + asm.mov(Size::Dword, Gpr::Rdx, register); + asm.alu_imm32(Alu::And, Size::Dword, register, MAGNITUDE); + // EDX becomes all ones for a negative value, then negates the magnitude. + asm.shift_imm(ShiftOp::Shl, Size::Dword, Gpr::Rdx, HALF_SIGN_TO_DWORD_TOP); + asm.shift_imm(ShiftOp::Sar, Size::Dword, Gpr::Rdx, SINGLE_SIGN_SHIFT); + asm.alu(Alu::Xor, Size::Dword, register, Gpr::Rdx); + asm.alu(Alu::Sub, Size::Dword, register, Gpr::Rdx); +} + /// EAX takes EDX's flags when `condition` holds. fn select_flags(code: &mut Code, condition: Cond) { code.asm().cmov(condition, Size::Dword, Gpr::Rax, Gpr::Rdx); @@ -237,22 +268,16 @@ fn emit_flags(code: &mut Code, format: Format, left: u8, right: CompareSource, p read_vector(code, left, LEFT_VECTOR); if let CompareSource::Register(right) = right { read_vector(code, right, RIGHT_VECTOR); - // The half order key holds for normal values alone. UCOMIS orders - // zeros and infinities with no host or guest flag. + // UCOMIS, and the signed magnitudes of Half values, order zeros of + // either sign and infinities with no host or guest flag; NaNs and + // subnormals take the helper. for source in [LEFT_VECTOR, RIGHT_VECTOR] { - if format == Format::Half { - scalar_normal_guard(code, format, source, &mut helper); - } else { - scalar_zero_guard(code, format, source, &mut helper); - } + scalar_zero_guard(code, format, source, &mut helper); } if format == Format::Half { - half_order_key(code, LEFT_VECTOR); - half_order_key(code, RIGHT_VECTOR); - let mut asm = code.asm(); - asm.movd_from_xmm(Gpr::Rax, LEFT_VECTOR); - asm.movd_from_xmm(Gpr::Rcx, RIGHT_VECTOR); - asm.alu(Alu::Cmp, Size::Word, Gpr::Rax, Gpr::Rcx); + half_signed_magnitude(code, Gpr::Rax, LEFT_VECTOR); + half_signed_magnitude(code, Gpr::Rcx, RIGHT_VECTOR); + code.asm().alu(Alu::Cmp, Size::Dword, Gpr::Rax, Gpr::Rcx); } else if format == Format::Double { code.asm().ucomisd(LEFT_VECTOR, Rm::Xmm(RIGHT_VECTOR)); } else { @@ -515,15 +540,26 @@ fn emit_predicate(code: &mut Code, operand: &Operand, pc: GuestAddress) { if merge { packed(code, Host::MoveAligned, MERGE_VECTOR, LEFT_VECTOR); } + // CMPSS/CMPPS order zeros of either sign and infinities as Arm + // does, without a status; NaNs (IOC) and subnormals (FZ) take the + // helper. The Half order key holds for normal values alone. if shape == Shape::Scalar { for source in [LEFT_VECTOR, RIGHT_VECTOR] { - scalar_normal_guard(code, format, source, &mut helper); + if format == Format::Half { + scalar_normal_guard(code, format, source, &mut helper); + } else { + scalar_zero_guard(code, format, source, &mut helper); + } } } else { prepare_vector_input_range(code, format); for source in [LEFT_VECTOR, RIGHT_VECTOR] { - vector_exponent_range(code, format, shape, source); - helper.push(branch(code, Condition::NotZero)); + if format == Format::Half { + vector_exponent_range(code, format, shape, source); + helper.push(branch(code, Condition::NotZero)); + } else { + vector_zero_or_normal_guard(code, format, shape, source, &mut helper); + } } } } else { diff --git a/crates/stela-compiler/src/x86_64/simd/fused.rs b/crates/stela-compiler/src/x86_64/simd/fused.rs index a6c2c97c14..6c7fe0a964 100644 --- a/crates/stela-compiler/src/x86_64/simd/fused.rs +++ b/crates/stela-compiler/src/x86_64/simd/fused.rs @@ -3,11 +3,11 @@ use super::super::isa::ShiftOpcode; use super::numerical::{ ArithmeticOpcode, ColdSplit, Condition, Entry, FusedOpcode, INPUT_MINIMUM_EXPONENT, Input, RESULT_MINIMUM_EXPONENT, ZeroProduct, branch, clear_scalar, commit_inexact, emit_fma, - emit_opcode, environment, exponent_range, jump, prepare_vector_input_range, - prepare_vector_result_range, read_inputs, read_numerical_right, read_numerical_vector, - reject_other_status, reject_product_status, resolve, restore_environment, - restore_environment_with_product, save_product_status, sticky_inexact, sticky_result_check, - test_control, vector_normal_or_zero_range, zero_product_check, + emit_opcode, environment, jump, prepare_vector_input_range, prepare_vector_result_range, + read_inputs, read_numerical_right, read_numerical_vector, reject_other_status, + reject_product_status, resolve, restore_environment, restore_environment_with_product, + save_product_status, scalar_range_or_zero, sticky_inexact, sticky_result_check, test_control, + vector_normal_or_zero_range, zero_product_check, }; use super::{Host, commit, packed}; use crate::x86_64::asm::Code; @@ -22,6 +22,12 @@ use crate::{ use alloc::vec; use alloc::vec::Vec; mod half; +#[cfg(all( + test, + target_arch = "x86_64", + any(target_os = "macos", target_os = "linux") +))] +mod tests; const LEFT: u8 = 0; const RIGHT: u8 = 1; @@ -115,14 +121,21 @@ pub(in crate::x86_64) fn emit( if operand.shape != Shape::Scalar { prepare_vector_input_range(code, operand.format); } + // A zero input or lane is exact on both sides: FPMulAdd and the host's + // FMA follow IEEE 754's signed-zero sums under the installed rounding + // (an exact zero sum is +0, -0 rounding toward minus infinity, and a sum + // of two zeros of one sign keeps it), a zero product adds exactly, and + // the excluded infinities keep 0 x inf out. A zero is not subnormal, so + // FZ and FIZ flush nothing, and neither side raises status for it. for source in [LEFT, RIGHT, ADDEND] { - let condition = if operand.shape == Shape::Scalar { - exponent_range(code, operand.format, source, INPUT_MINIMUM_EXPONENT); - Condition::AboveOrEqual + if operand.shape == Shape::Scalar { + helper.push(scalar_range_or_zero( + code, + operand.format, + source, + INPUT_MINIMUM_EXPONENT, + )); } else { - // A zero lane is exact on both sides: FPMulAdd and the host's - // FMA follow IEEE 754's signed-zero sums under the installed - // rounding, and the excluded infinities keep 0 x inf out. vector_normal_or_zero_range( code, operand.format, @@ -130,9 +143,8 @@ pub(in crate::x86_64) fn emit( source, ZERO_RANGE_SCRATCH, ); - Condition::NotZero - }; - helper.push(branch(code, condition)); + helper.push(branch(code, Condition::NotZero)); + } } let merge = if native_fma { ADDEND @@ -164,9 +176,16 @@ pub(in crate::x86_64) fn emit( helper.push(reject_product_status(code)); } helper.push(reject_other_status(code)); - let success_condition = if operand.shape == Shape::Scalar { - exponent_range(code, operand.format, LEFT, RESULT_MINIMUM_EXPONENT); - Condition::Below + let success = if operand.shape == Shape::Scalar { + // An exact zero result raised no status; a nonzero one rounded to + // zero raised underflow, which went to the helper above. + helper.push(scalar_range_or_zero( + code, + operand.format, + LEFT, + RESULT_MINIMUM_EXPONENT, + )); + jump(code) } else { prepare_vector_result_range(code); // A zero result is exact: one that underflowed raised the host's @@ -178,9 +197,8 @@ pub(in crate::x86_64) fn emit( LEFT, ZERO_RANGE_SCRATCH, ); - Condition::Zero + branch(code, Condition::Zero) }; - let success = branch(code, success_condition); let helper_start = code.len(); super::super::block::direct_exit(code, pc, ExitKind::FloatingPoint); let success_start = code.len(); diff --git a/crates/stela-compiler/src/x86_64/simd/fused/tests.rs b/crates/stela-compiler/src/x86_64/simd/fused/tests.rs new file mode 100644 index 0000000000..43eba92d02 --- /dev/null +++ b/crates/stela-compiler/src/x86_64/simd/fused/tests.rs @@ -0,0 +1,308 @@ +//! Scalar FMADD, FMSUB, FNMADD and FNMSUB on the host against the reference +//! `FPMulAdd` (`aarch64::floating::fused`), with FPSR.IXC clear and set. +use crate::{ + GuestAddress, GuestState, Lifter, TargetCpu, + aarch64::{ + Decoder, + floating::{ + FPCR_DN, FPCR_FZ, FPCR_NEP, FPCR_ROUNDING_SHIFT, Format, + fused::{FusedOperation, evaluate}, + }, + }, + block::ExitKind, +}; +use alloc::vec::Vec; +use core::ffi::c_void; +unsafe extern "C" { + fn mmap( + address: *mut c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut c_void; + fn mprotect(address: *mut c_void, bytes: usize, protection: i32) -> i32; + fn munmap(address: *mut c_void, bytes: usize) -> i32; +} +#[cfg(target_os = "macos")] +const MAP_ANONYMOUS: i32 = 0x1000; +#[cfg(target_os = "linux")] +const MAP_ANONYMOUS: i32 = 0x20; +const PAGE: usize = 4096; +const IXC: u32 = 1 << 4; +const PC: GuestAddress = GuestAddress(0x1000); +const UPPER: u64 = 0xa5a5_5a5a_c3c3_3c3c; +/// Vd, Vn, Vm and Va. +const D: u8 = 3; +const N: u8 = 4; +const M: u8 = 5; +const A: u8 = 6; + +#[repr(C)] +#[derive(Debug, PartialEq, Eq)] +struct Exit { + pc: u64, + kind: u64, +} + +/// The block of the instruction at [`PC`], run on the host. +struct Native { + page: *mut c_void, + bytes: usize, +} + +impl Native { + fn new(code: &[u8]) -> Self { + let bytes = code.len().next_multiple_of(PAGE); + // SAFETY: private anonymous memory, RX after the copy; Drop unmaps it. + unsafe { + let page = mmap(core::ptr::null_mut(), bytes, 3, 2 | MAP_ANONYMOUS, -1, 0); + assert_ne!(page as usize, usize::MAX); + core::ptr::copy_nonoverlapping(code.as_ptr(), page.cast(), code.len()); + assert_eq!(mprotect(page, bytes, 5), 0); + Self { page, bytes } + } + } + + fn run(&self, state: &mut GuestState) -> Exit { + // SAFETY: the block has the frame ABI and writes only `state` and its + // own stack slots. + unsafe { + let entry: unsafe extern "sysv64" fn(*mut GuestState) -> Exit = + core::mem::transmute(self.page); + entry(state) + } + } +} + +impl Drop for Native { + fn drop(&mut self) { + // SAFETY: unique mapping; every run returned. + assert_eq!(unsafe { munmap(self.page, self.bytes) }, 0); + } +} + +fn word(format: Format, operation: FusedOperation) -> u32 { + let (o1, o0) = match operation { + FusedOperation::Add => (0, 0), + FusedOperation::Subtract => (0, 1), + FusedOperation::NegatedAdd => (1, 0), + FusedOperation::NegatedSubtract => (1, 1), + }; + let kind = u32::from(format == Format::Double); + 0x1f00_0000 + | kind << 22 + | o1 << 21 + | u32::from(M) << 16 + | o0 << 15 + | u32::from(A) << 10 + | u32::from(N) << 5 + | u32::from(D) +} + +fn single(value: f32) -> u64 { + u64::from(value.to_bits()) +} + +/// Inputs of every class the full path takes or declines: signed zeros, +/// normals near 1, the smallest and largest normals, a subnormal, an +/// infinity and a NaN. +fn inputs(format: Format) -> Vec { + match format { + Format::Single => [ + 0.0, + -0.0, + 1.5, + -2.25, + 3.0, + 1.0e-3, + f32::MIN_POSITIVE, + f32::MAX, + -f32::MAX, + 1.0e-40, + f32::INFINITY, + f32::NAN, + ] + .map(single) + .to_vec(), + Format::Double => [ + 0.0, + -0.0, + 1.5, + -2.25, + 3.0, + 1.0e-3, + f64::MIN_POSITIVE, + f64::MAX, + -f64::MAX, + 1.0e-310, + f64::INFINITY, + f64::NAN, + ] + .map(f64::to_bits) + .to_vec(), + Format::Half => unreachable!("S/D only"), + } +} + +/// Every completed operation's result and status are the reference's; every +/// other one exits to the helper at its PC with the state unchanged. Zero +/// inputs and exact zero results complete in the block with IXC clear. +#[test] +fn scalar_fused_forms_match_fp_mul_add_in_every_control() { + let targets = [TargetCpu::Baseline, TargetCpu::detect()]; + let mut completed_zero = [0usize; 2]; + let mut cases = 0; + for (index, &target) in targets.iter().enumerate() { + for format in [Format::Single, Format::Double] { + for operation in [ + FusedOperation::Add, + FusedOperation::Subtract, + FusedOperation::NegatedAdd, + FusedOperation::NegatedSubtract, + ] { + let instruction = Decoder.lift(PC, word(format, operation)).unwrap(); + let fallthrough = GuestAddress(PC.0 + 4); + let code = crate::x86_64::block::emit_for_target( + core::slice::from_ref(&instruction), + None, + fallthrough, + target, + crate::x86_64::MemoryChecks::DEFAULT, + ) + .x86_64_code; + let native = Native::new(&code); + let values = inputs(format); + for rounding in 0..4 { + for flags in [0, FPCR_FZ, FPCR_DN, FPCR_NEP] { + let fpcr = rounding << FPCR_ROUNDING_SHIFT | flags; + for &addend in &values { + for &left in &values { + for &right in &values[..8] { + for fpsr in [0, IXC] { + let mut state = GuestState { + fpcr, + fpsr, + ..GuestState::default() + }; + state.v[usize::from(N)] = [left, UPPER]; + state.v[usize::from(M)] = [right, UPPER]; + state.v[usize::from(A)] = [addend, UPPER]; + state.v[usize::from(D)] = [UPPER, UPPER]; + let before = state.clone(); + let exit = native.run(&mut state); + let case = ( + target, format, operation, fpcr, fpsr, addend, left, + right, + ); + cases += 1; + if exit.kind == ExitKind::FloatingPoint as u64 { + assert_eq!(exit.pc, PC.0, "{case:x?}"); + assert_eq!(state, before, "{case:x?}"); + continue; + } + assert_eq!( + exit, + Exit { + pc: fallthrough.0, + kind: ExitKind::Fallthrough as u64 + }, + "{case:x?}" + ); + let outcome = + evaluate(format, operation, fpcr, addend, left, right) + .unwrap(); + let mut expected = before.clone(); + let upper = if flags == FPCR_NEP { + [addend, UPPER] + } else { + [0, 0] + }; + let mask = if format == Format::Single { + u64::from(u32::MAX) + } else { + u64::MAX + }; + expected.v[usize::from(D)] = + [outcome.bits | (upper[0] & !mask), upper[1]]; + expected.fpsr |= outcome.exceptions; + assert_eq!(state, expected, "{case:x?}"); + let zero = + |bits: u64| bits & mask & !(mask ^ mask >> 1) == 0; + if fpsr == 0 && (zero(addend) || zero(left) || zero(right)) + { + completed_zero[index] += 1; + } + } + } + } + } + } + } + } + } + } + assert!(cases > 0); + // Zero inputs no longer take the helper with IXC clear, on either host + // recipe. + for (target, completed) in targets.iter().zip(completed_zero) { + assert!(completed > 1000, "{target:?}: {completed}"); + } +} + +/// The FMADDs seen most at helper exits complete in their block with FPSR +/// clear: a product with a zero addend, a zero product, and normal sums. +#[test] +fn common_fused_multiply_adds_stay_in_the_block_with_ixc_clear() { + // fmadd s0, s2, s0, s1; fmadd d3, d4, d0, d3; fmadd d0, d3, d0, d2 + for (word, format) in [ + (0x1f00_0440_u32, Format::Single), + (0x1f40_0c83, Format::Double), + (0x1f40_0860, Format::Double), + ] { + let instruction = Decoder.lift(PC, word).unwrap(); + let fallthrough = GuestAddress(PC.0 + 4); + let (d, n, m, a) = ( + word as usize & 31, + (word >> 5) as usize & 31, + (word >> 16) as usize & 31, + (word >> 10) as usize & 31, + ); + for target in [TargetCpu::Baseline, TargetCpu::detect()] { + let code = crate::x86_64::block::emit_for_target( + core::slice::from_ref(&instruction), + None, + fallthrough, + target, + crate::x86_64::MemoryChecks::DEFAULT, + ) + .x86_64_code; + let native = Native::new(&code); + let encode = |value: f64| match format { + Format::Single => single(value as f32), + _ => value.to_bits(), + }; + for (left, right, addend) in [(1.5, 2.0, 0.0), (0.0, 3.0, 1.25), (1.5, 2.0, 0.25)] { + let mut state = GuestState::default(); + state.v[n][0] = encode(left); + state.v[m][0] = encode(right); + state.v[a][0] = encode(addend); + let (left, right, addend) = (state.v[n][0], state.v[m][0], state.v[a][0]); + let exit = native.run(&mut state); + assert_eq!( + exit, + Exit { + pc: fallthrough.0, + kind: ExitKind::Fallthrough as u64 + }, + "{word:08x} {target:?}" + ); + let outcome = + evaluate(format, FusedOperation::Add, 0, addend, left, right).unwrap(); + assert_eq!(state.v[d], [outcome.bits, 0], "{word:08x} {target:?}"); + assert_eq!(state.fpsr, outcome.exceptions); + } + } + } +} diff --git a/crates/stela-compiler/src/x86_64/simd/numerical.rs b/crates/stela-compiler/src/x86_64/simd/numerical.rs index 4c09d1c401..f37f21f2ec 100644 --- a/crates/stela-compiler/src/x86_64/simd/numerical.rs +++ b/crates/stela-compiler/src/x86_64/simd/numerical.rs @@ -854,7 +854,7 @@ fn vector_exponent_range_impl( vector_validity_mask(code, format, shape); } -/// Accept only normal S/D values and signed zeros. The range constants +/// Accept only normal values and signed zeros. The range constants /// remain live in XMM4/5; XMM3 and `scratch` are classifier scratch. Unlike a zero /// fraction test, clearing just the sign rejects infinities and subnormals. pub(super) fn vector_normal_or_zero_range( @@ -864,7 +864,6 @@ pub(super) fn vector_normal_or_zero_range( source: u8, scratch: u8, ) { - assert!(format != Format::Half); assert!( ![ source, @@ -877,16 +876,16 @@ pub(super) fn vector_normal_or_zero_range( ); vector_exponent_validity(code, format, source, false); packed(code, Host::MoveAligned, VALIDITY_VECTOR, source); - let left = if format == Format::Double { - ShiftOpcode::LeftQword - } else { - ShiftOpcode::LeftDword + let (left, equal) = match format { + Format::Double => (ShiftOpcode::LeftQword, Host::EqualDword), + Format::Single => (ShiftOpcode::LeftDword, Host::EqualDword), + Format::Half => (ShiftOpcode::LeftWord, Host::EqualWord), }; left.emit(code, VALIDITY_VECTOR, SIGN_BITS); // The result-range lower bound is one rather than zero. Use an independent // zero so output classification still recognizes both signed zeros. packed(code, Host::Xor, scratch, scratch); - packed(code, Host::EqualDword, VALIDITY_VECTOR, scratch); + packed(code, equal, VALIDITY_VECTOR, scratch); if format == Format::Double { packed_imm( code, diff --git a/crates/stela-compiler/src/x86_64/simd/precision.rs b/crates/stela-compiler/src/x86_64/simd/precision.rs index bdcbb0ab4f..419c7997cf 100644 --- a/crates/stela-compiler/src/x86_64/simd/precision.rs +++ b/crates/stela-compiler/src/x86_64/simd/precision.rs @@ -7,7 +7,8 @@ use super::numerical::{ RESULT_MINIMUM_EXPONENT, Rounding, branch, clear_scalar, commit_inexact, environment_round, exponent_range, jump, prepare_half_result_range, prepare_vector_input_range, prepare_vector_result_range, read_numerical_vector, reject_other_status, resolve, - restore_environment, single_vector_arithmetic, test_control, vector_exponent_range, + restore_environment, scalar_range_or_zero, single_vector_arithmetic, test_control, + vector_exponent_range, vector_normal_or_zero_range, }; use super::{Host, commit, encode::guest, packed, read_vector, vector_offset}; use crate::x86_64::asm::FloatLanes; @@ -34,6 +35,8 @@ const SOURCE_VECTOR: u8 = 1; const JAM_VECTOR: u8 = 6; /// The low Half of a scalar narrowing, ahead of its merge into old Vd. const HALF_LANE_VECTOR: u8 = 6; +/// The zero classifier's scratch in vector Half narrowing. +const NARROW_ZERO_SCRATCH: u8 = 7; /// VCVTPS2PH's immediate: round by MXCSR.RC. const CONVERT_USING_MXCSR: u8 = 1 << 2; const COMPARE_EQUAL: u8 = 0; @@ -174,8 +177,21 @@ fn emit_scalar( // Precision conversions merge old Vd, unlike binary arithmetic's Vn merge. read_vector(code, operand.destination, RESULT_VECTOR); if source == Format::Half { + // A zero widens to the zero of its sign, exactly and without status. + code.asm().movd_from_xmm(Rax, SOURCE_VECTOR); + code.asm().test_imm(Size::Dword, Rax, HALF_MAGNITUDE as i32); + let zero = branch(code, Condition::Zero); half_normal_guard(code, &mut helper); half_to_single(code); + let widened = jump(code); + let zero_start = code.len(); + resolve(code, zero, zero_start); + let mut asm = code.asm(); + asm.alu_imm32(Alu::And, Size::Dword, Rax, HALF_SIGN as i32); + asm.shift_imm(ShiftOp::Shl, Size::Dword, Rax, HALF_TO_SINGLE_SIGN_SHIFT); + asm.movd_to_xmm(SOURCE_VECTOR, Rax); + let joined = code.len(); + resolve(code, widened, joined); if destination == Format::Double { code.asm().cvtss2sd(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); } else { @@ -186,30 +202,35 @@ fn emit_scalar( crate::TargetCpu::Baseline, ); } + } else if destination == Format::Double { + // Normal or zero S→D is exact, unaffected by ambient RC/DAZ/FTZ/masks, + // and raises neither Intel Invalid nor Denormal, nor any FPSR status + // (a zero is no denormal input, whatever FZ holds). Preserve MXCSR. + helper.push(scalar_range_or_zero( + code, + source, + SOURCE_VECTOR, + INPUT_MINIMUM_EXPONENT, + )); + code.asm().cvtss2sd(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); } else { exponent_range(code, source, SOURCE_VECTOR, INPUT_MINIMUM_EXPONENT); helper.push(branch(code, Condition::AboveOrEqual)); - if destination == Format::Double { - // Normal S→D is exact, unaffected by ambient RC/DAZ/FTZ/masks, - // and raises neither Intel Invalid nor Denormal. Preserve MXCSR. - code.asm().cvtss2sd(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); - } else { - environment_round( - code, - if rounding == PrecisionRounding::ToOdd { - Rounding::Zero - } else { - Rounding::Fpcr - }, - ); - code.asm().cvtsd2ss(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); - restore_environment(code); - helper.push(reject_other_status(code)); - exponent_range(code, destination, RESULT_VECTOR, RESULT_MINIMUM_EXPONENT); - helper.push(branch(code, Condition::AboveOrEqual)); + environment_round( + code, if rounding == PrecisionRounding::ToOdd { - scalar_odd_jam(code); - } + Rounding::Zero + } else { + Rounding::Fpcr + }, + ); + code.asm().cvtsd2ss(RESULT_VECTOR, Rm::Xmm(SOURCE_VECTOR)); + restore_environment(code); + helper.push(reject_other_status(code)); + exponent_range(code, destination, RESULT_VECTOR, RESULT_MINIMUM_EXPONENT); + helper.push(branch(code, Condition::AboveOrEqual)); + if rounding == PrecisionRounding::ToOdd { + scalar_odd_jam(code); } } helper_section(code, &helper, pc); @@ -485,8 +506,8 @@ pub(super) fn half_narrowing_supported(mode: PrecisionMode, target: TargetCpu) - } } -/// Narrow to Half under the guards of the Half arithmetic path: normal inputs, -/// and a helper for other status or a result below exponent 2, so x86's +/// Narrow to Half under the guards of the Half arithmetic path: normal inputs +/// (and zero vector lanes), and a helper for other status or a result below exponent 2, so x86's /// tininess rule never decides a guest result. FPCR.AHP selects a format the /// host lacks. fn emit_narrow_half( @@ -509,9 +530,17 @@ fn emit_narrow_half( helper.push(branch(code, Condition::AboveOrEqual)); clear_scalar(code, source, SOURCE_VECTOR); } else { + // A zero lane narrows to the zero of its sign, exactly and without + // status on both sides; FZ and FIZ flush no zero. read_numerical_vector(code, Shape::Vector128, operand.source, SOURCE_VECTOR); prepare_vector_input_range(code, Format::Single); - vector_exponent_range(code, Format::Single, Shape::Vector128, SOURCE_VECTOR); + vector_normal_or_zero_range( + code, + Format::Single, + Shape::Vector128, + SOURCE_VECTOR, + NARROW_ZERO_SCRATCH, + ); helper.push(branch(code, Condition::NotZero)); } let result = if scalar.is_some() { @@ -537,12 +566,19 @@ fn emit_narrow_half( helper.push(reject_other_status(code)); prepare_vector_input_range(code, Format::Half); prepare_half_result_range(code); - let shape = if scalar.is_some() { - Shape::Scalar + if scalar.is_some() { + vector_exponent_range(code, Format::Half, Shape::Scalar, result); } else { - Shape::Vector64 - }; - vector_exponent_range(code, Format::Half, shape, result); + // A zero result came from a zero lane: a nonzero one rounded to zero + // raised underflow, which took the helper above. + vector_normal_or_zero_range( + code, + Format::Half, + Shape::Vector64, + result, + NARROW_ZERO_SCRATCH, + ); + } helper.push(branch(code, Condition::NotZero)); helper_section(code, &helper, pc); commit_inexact(code); diff --git a/crates/stela-engine/src/floating/arithmetic/tests/native.rs b/crates/stela-engine/src/floating/arithmetic/tests/native.rs index 81f4434f60..9ceabaf3c9 100644 --- a/crates/stela-engine/src/floating/arithmetic/tests/native.rs +++ b/crates/stela-engine/src/floating/arithmetic/tests/native.rs @@ -176,15 +176,22 @@ fn native_domain(state: &GuestState, operand: &Operand) -> bool { let maximum = exponent_mask(format) >> fraction_bits(format); let zero = |raw| raw & !sign_mask(format) == 0; let allows_zero = operand.operation != BinaryOperation::Divide; + // A scalar quotient of a zero dividend over a normal divisor is an exact + // signed zero, which compiled code completes. + let zero_quotient = operand.operation == BinaryOperation::Divide + && operand.shape == Shape::Scalar + && matches!(operand.inputs, Inputs::Elementwise { .. }); (0..operand.shape.lane_count(format)).all(|lane| { let (a, b) = inputs(state, operand, lane); let valid = |raw| (1..maximum).contains(&exponent(raw)) || allows_zero && zero(raw); - if !valid(a) || !valid(b) { + let zero_dividend = zero_quotient && zero(a); + if !(valid(a) || zero_dividend) || !valid(b) { return false; } let outcome = evaluate(format, operand.operation, state.fpcr, a, b).unwrap(); outcome.exceptions & !INEXACT == 0 - && ((2..maximum).contains(&exponent(outcome.bits)) || allows_zero && zero(outcome.bits)) + && ((2..maximum).contains(&exponent(outcome.bits)) + || (allows_zero || zero_dividend) && zero(outcome.bits)) }) } diff --git a/crates/stela-engine/src/floating/tests.rs b/crates/stela-engine/src/floating/tests.rs index 6f68bbb749..aab95290b2 100644 --- a/crates/stela-engine/src/floating/tests.rs +++ b/crates/stela-engine/src/floating/tests.rs @@ -1454,6 +1454,7 @@ fn vector_self_comparisons_accept_zeros_and_infinities_without_fp_status() { } #[cfg(all(feature = "std", target_arch = "x86_64"))] +mod changed_native; mod fused_native; mod half_conversion_native; mod traps; diff --git a/crates/stela-engine/src/floating/tests/changed_native.rs b/crates/stela-engine/src/floating/tests/changed_native.rs new file mode 100644 index 0000000000..57cb1c6742 --- /dev/null +++ b/crates/stela-engine/src/floating/tests/changed_native.rs @@ -0,0 +1,340 @@ +//! Emitted comparison and conversion blocks against the exact software +//! completion, over special values, mixed lanes and FPCR modes: every +//! compiled result must equal [`complete`]'s, and every helper exit must +//! leave the state untouched. +use super::super::*; +use crate::execution::platform::Mapping; +use stela_compiler::{ + GuestAddress, TargetCpu, + aarch64::{FloatingPointOperation, floating::*}, + block::{BlockProfile, CompilationPlan, ExitKind, Features}, +}; + +const PC: u64 = 0x1000; +const PREFIX: u32 = 0x9100_0508; // ADD X8,X8,#1 +const SUFFIX: u32 = 0x9100_0529; // ADD X9,X9,#1 +const Q: u32 = 1 << 30; +const SZ: u32 = 1 << 22; + +fn specials(format: Format) -> Vec { + let (sign, quiet, exponent_shift) = match format { + Format::Half => (0x8000u64, 0x0200u64, 10), + Format::Single => (0x8000_0000, 0x0040_0000, 23), + Format::Double => (0x8000_0000_0000_0000, 0x0008_0000_0000_0000, 52), + }; + let infinity = (sign - 1) & !((1u64 << exponent_shift) - 1); + let one = match format { + Format::Half => 0x3c00, + Format::Single => 0x3f80_0000, + Format::Double => 0x3ff0_0000_0000_0000, + }; + let minimum_normal = 1u64 << exponent_shift; + let positive = [ + 0, + infinity, + infinity | quiet, + infinity | 1, + 1, + minimum_normal - 1, + minimum_normal, + one, + one + 1, + one | (1 << (exponent_shift - 1)), + infinity - 1, + one + (2 << exponent_shift), + ]; + positive + .iter() + .flat_map(|&value| [value, value | sign]) + .collect() +} + +fn targets() -> Vec { + let host = stela_compiler::x86_64::modeled::host(); + [TargetCpu::Baseline, host] + .into_iter() + .filter(|target| host.supports(*target)) + .collect() +} + +fn compile(word: u32, target: TargetCpu) -> Mapping { + let source: Vec<_> = [PREFIX, word, SUFFIX] + .into_iter() + .flat_map(u32::to_le_bytes) + .collect(); + let block = CompilationPlan::new( + &source, + GuestAddress(PC), + &stela_compiler::Options::new(BlockProfile::new(Features::SYSTEM_MODE), target), + ) + .unwrap() + .compile() + .unwrap(); + Mapping::new(&stela_compiler::x86_64::pinned::entered( + &block.native.x86_64_code, + )) + .unwrap() +} + +fn mxcsr() -> u32 { + let mut value = 0; + // SAFETY: valid writable output on this baseline SSE2 host. + unsafe { + core::arch::asm!("stmxcsr [{p}]", p = in(reg) &mut value, options(nostack, preserves_flags)); + } + value +} + +/// Run `mapping` on `state` and check it against [`complete`]. Returns +/// whether the block completed the instruction itself. +fn check( + word: u32, + mapping: &Mapping, + operation: &FloatingPointOperation, + input: &GuestState, +) -> bool { + let mut state = input.clone(); + let before = mxcsr(); + // SAFETY: this host's owned RX image holds three non-memory instructions + // under the one-pointer block ABI; the state is private. + let exit = unsafe { mapping.call_block(&mut state) }.unwrap(); + assert_eq!(mxcsr(), before, "MXCSR {word:#010x}"); + let mut expected = input.clone(); + expected.x[8] += 1; + let native = exit.kind == ExitKind::Fallthrough as u64; + if native { + // The block may end after the instruction, before the suffix. + assert!([PC + 8, PC + 12].contains(&exit.next_pc), "{word:#010x}"); + if exit.next_pc == PC + 12 { + expected.x[9] += 1; + } + let completed = complete(&mut expected, operation); + assert!( + completed.is_ok(), + "{word:#010x} completed natively under an unsupported control: {input:x?}" + ); + } else { + assert_eq!(exit.kind, ExitKind::FloatingPoint as u64, "{word:#010x}"); + assert_eq!(exit.next_pc, PC + 4, "{word:#010x}"); + } + assert_eq!( + state, expected, + "{word:#010x} native={native} fpcr={:#x} input v1={:x?} v2={:x?} v0={:x?} nzcv={:#x}", + input.fpcr, input.v[1], input.v[2], input.v[0], input.nzcv + ); + native +} + +const MODES: [u32; 9] = [ + 0, + FPCR_FZ, + FPCR_FZ16, + FPCR_AH, + FPCR_DN, + FPCR_FIZ, + FPCR_AH | FPCR_FZ | FPCR_FIZ, + FPCR_FZ | FPCR_FZ16 | FPCR_DN | FPCR_AH | FPCR_NEP, + FPCR_NEP | (3 << FPCR_ROUNDING_SHIFT), +]; + +/// Fill `register` with `values`, lane `i` taking `values[i % len]`. +fn fill(state: &mut GuestState, register: u8, format: Format, values: &[u64]) { + let lanes = 128 / format.bits(); + for lane in 0..lanes { + write_lane( + &mut state.v[usize::from(register)], + format.bits(), + lane, + values[lane as usize % values.len()], + ); + } +} + +/// Run every word over every ordered pair of special values in its first +/// lane, the remaining lanes holding the pairs that follow, under every +/// mode, with and without IXC, on every target. Returns (native, helper). +fn sweep(words: &[(u32, Format)]) -> (usize, usize) { + let mut counts = (0, 0); + for target in targets() { + for &(word, format) in words { + let operation = FloatingPointOperation::decode(word).unwrap().unwrap(); + let mapping = compile(word, target); + let values = specials(format); + let count = values.len(); + for left in 0..count { + for right in 0..count { + let lanes = 128 / format.bits() as usize; + let lefts: Vec<_> = (0..lanes).map(|i| values[(left + i) % count]).collect(); + let rights: Vec<_> = (0..lanes) + .map(|i| values[(right + 3 * i) % count]) + .collect(); + for &mode in &MODES { + for (fpsr, nzcv) in [(0, 0x6000_0000), (INEXACT, 0x9000_0000)] { + let mut state = GuestState { + x: std::array::from_fn(|i| 0x1234_5678_0000_0000 | i as u64), + v: std::array::from_fn(|i| { + [0x0123_4567_89ab_cdef ^ i as u64, 0xfedc_ba98_7654_3210] + }), + fpcr: mode, + fpsr, + nzcv, + ..Default::default() + }; + fill(&mut state, 1, format, &lefts); + fill(&mut state, 2, format, &rights); + if check(word, &mapping, &operation, &state) { + counts.0 += 1; + } else { + counts.1 += 1; + } + } + } + } + } + } + } + counts +} + +fn vector_forms(single_double: &[u32], half: &[u32]) -> Vec<(u32, Format)> { + let mut words = Vec::new(); + for &base in single_double { + words.push((base, Format::Single)); + words.push((base | Q, Format::Single)); + words.push((base | Q | SZ, Format::Double)); + } + for &base in half { + words.push((base, Format::Half)); + words.push((base | Q, Format::Half)); + } + words +} + +#[test] +fn vector_register_and_zero_comparisons_match_completion() { + // FCMEQ, FCMGE, FCMGT, FACGE, FACGT Vd,Vn,Vm with Rd=0, Rn=1, Rm=2. + let register = vector_forms( + &[ + 0x0e22_e420, + 0x2e22_e420, + 0x2ea2_e420, + 0x2e22_ec20, + 0x2ea2_ec20, + ], + &[ + 0x0e42_2420, + 0x2e42_2420, + 0x2ec2_2420, + 0x2e42_2c20, + 0x2ec2_2c20, + ], + ); + // FCMGT, FCMEQ, FCMLT, FCMGE, FCMLE Vd,Vn,#0. + let zero = vector_forms( + &[ + 0x0ea0_c820, + 0x0ea0_d820, + 0x0ea0_e820, + 0x2ea0_c820, + 0x2ea0_d820, + ], + &[ + 0x0ef8_c820, + 0x0ef8_d820, + 0x0ef8_e820, + 0x2ef8_c820, + 0x2ef8_d820, + ], + ); + let (native, helper) = sweep(&[register, zero].concat()); + assert!(native > 0 && helper > 0, "{native} {helper}"); +} + +#[test] +fn scalar_predicate_comparisons_match_completion() { + let mut words = Vec::new(); + for base in [ + 0x5e22_e420u32, + 0x7e22_e420, + 0x7ea2_e420, + 0x7e22_ec20, + 0x7ea2_ec20, + ] { + words.push((base, Format::Single)); + words.push((base | SZ, Format::Double)); + } + for base in [ + 0x5e42_2420u32, + 0x7e42_2420, + 0x7ec2_2420, + 0x7e42_2c20, + 0x7ec2_2c20, + ] { + words.push((base, Format::Half)); + } + // Zero forms: FCMGT, FCMEQ, FCMLT, FCMGE, FCMLE Sd/Dd,Sn/Dn,#0, and Half. + for base in [ + 0x5ea0_c820u32, + 0x5ea0_d820, + 0x5ea0_e820, + 0x7ea0_c820, + 0x7ea0_d820, + ] { + words.push((base, Format::Single)); + words.push((base | SZ, Format::Double)); + } + for base in [ + 0x5ef8_c820u32, + 0x5ef8_d820, + 0x5ef8_e820, + 0x7ef8_c820, + 0x7ef8_d820, + ] { + words.push((base, Format::Half)); + } + let (native, helper) = sweep(&words); + assert!(native > 0 && helper > 0, "{native} {helper}"); +} + +#[test] +fn flag_comparisons_match_completion() { + let mut words = Vec::new(); + for (format, kind) in [(Format::Single, 0), (Format::Double, 1), (Format::Half, 3)] { + let base = 0x1e20_0000 | kind << 22; + // FCMP/FCMPE Sn,Sm and #0.0 with Rn=1, Rm=2. + for opc in [0x00, 0x08, 0x10, 0x18] { + let right = if opc & 0x08 == 0 { 2 << 16 } else { 0 }; + words.push((base | 0x2000 | right | 1 << 5 | opc, format)); + } + // FCCMP/FCCMPE with conditions EQ, GE, LT, HI and fallback NZCV 0b0110. + for condition in [0x0u32, 0xa, 0xb, 0x8] { + for signaling in [0, 0x10] { + words.push(( + base | 0x0400 | 2 << 16 | condition << 12 | 1 << 5 | signaling | 6, + format, + )); + } + } + } + let (native, helper) = sweep(&words); + assert!(native > 0 && helper > 0, "{native} {helper}"); +} + +#[test] +fn half_conversions_match_completion() { + let words = [ + // FCVT S0,H1; FCVT D0,H1 (the left source is V1). + (0x1ee2_4020, Format::Half), + (0x1ee2_c020, Format::Half), + // FCVTN V0.4H,V1.4S; FCVTN2 V0.8H,V1.4S. + (0x0e21_6820, Format::Single), + (0x4e21_6820, Format::Single), + // FCVT H0,S1; FCVT H0,D1; FCVTL V0.4S,V1.4H; FCVTL2. + (0x1e23_c020, Format::Single), + (0x1e63_c020, Format::Double), + (0x0e21_7820, Format::Half), + (0x4e21_7820, Format::Half), + ]; + let (native, helper) = sweep(&words); + assert!(native > 0 && helper > 0, "{native} {helper}"); +} diff --git a/crates/stela-engine/src/memory/domain/native_target.rs b/crates/stela-engine/src/memory/domain/native_target.rs index 9fb861db1c..8c4600edd4 100644 --- a/crates/stela-engine/src/memory/domain/native_target.rs +++ b/crates/stela-engine/src/memory/domain/native_target.rs @@ -1,7 +1,8 @@ //! A conservative limit, never CPU or memory execution permission. Keep the -//! legacy XMM and scalar GPR recipes both sides have, which is what blocks -//! compile for; wider state and DIT cannot be enabled by a caller-provided -//! declaration. +//! legacy XMM, scalar GPR and VEX vector recipes both sides have, which is +//! what blocks compile for. The current side's VEX recipes already need its +//! live YMM state, so a limit only removes them; AVX-512 state and DIT +//! cannot be enabled by a caller-provided declaration. use stela_compiler::TargetCpu; pub(in crate::memory) fn restrict(actual: TargetCpu, limit: TargetCpu) -> TargetCpu { @@ -27,6 +28,11 @@ pub(in crate::memory) fn restrict(actual: TargetCpu, limit: TargetCpu) -> Target (TargetCpu::Bmi2, TargetCpu::with_bmi2), (TargetCpu::FastPdep, TargetCpu::with_fast_pdep), (TargetCpu::Movbe, TargetCpu::with_movbe), + // VEX vector recipes, which the current side admits only with + // OS-enabled YMM state. + (TargetCpu::Fma, TargetCpu::with_fma), + (TargetCpu::F16c, TargetCpu::with_f16c), + (TargetCpu::Avx2, TargetCpu::with_avx2), ] { if actual.supports(capability) && limit.supports(capability) { target = with(target); @@ -102,14 +108,13 @@ mod tests { .with_data_independent_timing(); let common = restrict(rich, rich); assert!(!common.data_independent_timing()); - for excluded in [ - TargetCpu::Fma, - TargetCpu::F16c, - TargetCpu::Avx2, - TargetCpu::Avx512f, - TargetCpu::Doit, - TargetCpu::LineAtomic, - ] { + // VEX vector recipes stay only where both sides have them. + for kept in [TargetCpu::Fma, TargetCpu::F16c, TargetCpu::Avx2] { + assert!(common.supports(kept)); + assert!(!restrict(TargetCpu::X86_64_V2, rich).supports(kept)); + assert!(!restrict(rich, TargetCpu::X86_64_V2).supports(kept)); + } + for excluded in [TargetCpu::Avx512f, TargetCpu::Doit, TargetCpu::LineAtomic] { assert!(!common.supports(excluded)); } // Scalar GPR extensions use no extended state. diff --git a/crates/stela-engine/src/platform/cpu/system.rs b/crates/stela-engine/src/platform/cpu/system.rs index 34b763c2f0..4c459a23fc 100644 --- a/crates/stela-engine/src/platform/cpu/system.rs +++ b/crates/stela-engine/src/platform/cpu/system.rs @@ -82,6 +82,16 @@ const CPUID_MOVBE: u32 = 1 << 22; const CPUID_AVX: u32 = 1 << 28; const CPUID_BMI1: u32 = 1 << 3; const CPUID_BMI2: u32 = 1 << 8; +/// CPUID.1:ECX FMA3 and F16C, and CPUID.7.0:EBX AVX2: VEX vector recipes, +/// which also need the OS to enable YMM state ([`XCR0_YMM`]). +const CPUID_FMA: u32 = 1 << 12; +const CPUID_F16C: u32 = 1 << 29; +const CPUID_AVX2: u32 = 1 << 5; +/// CR4.OSXSAVE, which makes XGETBV and XCR0 usable. +const CR4_OSXSAVE: u64 = 1 << 18; +/// XCR0's SSE and AVX bits: XMM and YMM state, which the host's interrupt +/// entries save whenever XCR0 enables it. +const XCR0_YMM: u64 = 0x6; /// AMD's first family whose PDEP and PEXT are not microcoded (Zen 3). const FAST_PDEP_FAMILY: u32 = 0x19; #[cfg(any( @@ -96,7 +106,9 @@ const CPUID1_ECX_READ: u32 = CPUID_PCLMULQDQ | CPUID_POPCNT | CPUID_AES | CPUID_MOVBE - | CPUID_AVX; + | CPUID_AVX + | CPUID_FMA + | CPUID_F16C; const CPUID_SHA: u32 = 1 << 29; const CPUID_GFNI: u32 = 1 << 8; const CPUID_LZCNT: u32 = 1 << 5; @@ -109,6 +121,8 @@ struct NativeControls { cr4: u64, efer: u64, flags: u64, + /// XCR0, or zero without CR4.OSXSAVE. + xcr0: u64, } fn privilege(cs: u16, flags: u64) -> Result<(), Refusal> { @@ -209,7 +223,24 @@ impl Observation { if TargetCpu::atomic_load16_guaranteed(d.vendor, d.cpuid1_ecx) { target = target.with_atomic_load16(); } - // No AVX, FMA, cache-line atomicity or DOIT recipe is admitted. + // VEX vector recipes: AVX hardware whose YMM state this core's + // XCR0 enables. Blocks use VEX.128 forms, and their few VEX.256 + // sequences end with VZEROUPPER; interrupt entries save the state. + if c.cr4 & CR4_OSXSAVE != 0 + && c.xcr0 & XCR0_YMM == XCR0_YMM + && d.cpuid1_ecx & CPUID_AVX != 0 + { + if d.cpuid1_ecx & CPUID_FMA != 0 { + target = target.with_fma(); + } + if d.cpuid1_ecx & CPUID_F16C != 0 { + target = target.with_f16c(); + } + if d.cpuid7_ebx & CPUID_AVX2 != 0 { + target = target.with_avx2(); + } + } + // No AVX-512, cache-line atomicity or DOIT recipe is admitted. Ok(target) } } @@ -417,6 +448,7 @@ impl NativeSystemTarget { || current.controls.cr4 != self.observed.controls.cr4 || current.controls.efer != self.observed.controls.efer || current.controls.cs != self.observed.controls.cs + || current.controls.xcr0 != self.observed.controls.xcr0 { return Err(Refusal::Controls); } @@ -504,7 +536,7 @@ fn enumerate(mut cpuid: impl FnMut(u32, u32) -> Cpuid) -> Result<(CpuDeclaration cpuid1_edx: basic.edx & (CPUID_FLOOR_EDX | (1 << 8)), extended_ecx: ext.ecx & CPUID_LZCNT, extended_edx: ext.edx & CPUID_LONG_NX, - cpuid7_ebx: leaf7.ebx & (CPUID_SHA | CPUID_BMI1 | CPUID_BMI2), + cpuid7_ebx: leaf7.ebx & (CPUID_SHA | CPUID_BMI1 | CPUID_BMI2 | CPUID_AVX2), cpuid7_ecx: leaf7.ecx & ((1 << 16) | CPUID_GFNI), family: display_family(basic.eax), identity: probe, @@ -565,6 +597,12 @@ fn controls(cs: u16, flags: u64, apic_id: u32) -> NativeControls { asm!("rdmsr", in("ecx") 0xc000_0080u32, out("eax") low, out("edx") high, options(nostack, preserves_flags)); } + let xcr0 = if cr4 & CR4_OSXSAVE != 0 { + // SAFETY: CR4.OSXSAVE makes XGETBV with ECX 0 defined. + unsafe { core::arch::x86_64::_xgetbv(0) } + } else { + 0 + }; NativeControls { apic_id, cs, @@ -572,6 +610,7 @@ fn controls(cs: u16, flags: u64, apic_id: u32) -> NativeControls { cr4, flags, efer: u64::from(low) | u64::from(high) << 32, + xcr0, } } diff --git a/crates/stela-engine/src/platform/cpu/system/tests.rs b/crates/stela-engine/src/platform/cpu/system/tests.rs index fc97acc1cc..b79a466fde 100644 --- a/crates/stela-engine/src/platform/cpu/system/tests.rs +++ b/crates/stela-engine/src/platform/cpu/system/tests.rs @@ -19,10 +19,48 @@ fn baseline() -> Observation { cr4: CR4_REQUIRED, efer: EFER_REQUIRED, flags: 0, + xcr0: 0, }, } } +/// FMA3, F16C and AVX2 need AVX hardware and YMM state that this core's +/// XCR0 enables, behind CR4.OSXSAVE; a later change of XCR0 refuses entry. +#[test] +fn vex_vector_recipes_require_live_ymm_state() { + let mut actual = baseline(); + actual.declarations.vendor = TargetCpu::AMD_VENDOR; + actual.declarations.cpuid1_ecx = CPUID_AVX | CPUID_FMA | CPUID_F16C; + actual.declarations.cpuid7_ebx = CPUID_AVX2; + let vector = TargetCpu::Baseline.with_fma().with_f16c().with_avx2(); + assert!(!actual.target().unwrap().supports(TargetCpu::Fma)); + actual.controls.xcr0 = 0x7; + assert!(!actual.target().unwrap().supports(TargetCpu::Fma)); + actual.controls.cr4 |= CR4_OSXSAVE; + let target = actual.target().unwrap(); + assert!(target.supports(vector)); + assert!(!target.supports(TargetCpu::Avx512f)); + let proof = NativeSystemTarget { + observed: actual, + lease: None, + target, + }; + assert_eq!(proof.revalidate_observation(actual), Ok(())); + let mut legacy_state = actual; + legacy_state.controls.xcr0 = 0x3; + assert!(!legacy_state.target().unwrap().supports(TargetCpu::Fma)); + assert_eq!( + proof.revalidate_observation(legacy_state), + Err(Refusal::TargetChanged) + ); + let mut wider = actual; + wider.controls.xcr0 = 0xe7; + assert_eq!(proof.revalidate_observation(wider), Err(Refusal::Controls)); + actual.declarations.cpuid1_ecx &= !CPUID_AVX; + assert!(!actual.target().unwrap().supports(TargetCpu::Fma)); + assert!(!actual.target().unwrap().supports(TargetCpu::Avx2)); +} + #[test] fn optional_legacy_extensions_require_live_declarations_without_osxsave() { let mut actual = baseline(); diff --git a/crates/stela-engine/tests/blocks.rs b/crates/stela-engine/tests/blocks.rs index 24358c8f0c..eb9f324d88 100644 --- a/crates/stela-engine/tests/blocks.rs +++ b/crates/stela-engine/tests/blocks.rs @@ -76,6 +76,67 @@ mod numerical { expected.v[d] = value; } + /// A zero dividend over a normal divisor, and a zero widened from S to + /// D, complete in compiled code with the exact signed zero and no + /// status, on the full path (FPSR.IXC clear) and on the sticky one; + /// a zero divisor still takes the helper, which raises DZC. + #[test] + fn zero_dividends_and_zero_widenings_stay_in_compiled_code() -> Result<()> { + use stela_compiler::aarch64::floating::{DIVIDE_BY_ZERO, FPCR_FZ}; + const FDIV_S0_S1_S2: u32 = 0x1e22_1820; + const FCVT_D3_S1: u32 = 0x1e22_c023; + const THREE: u64 = 0x4040_0000; + let cache = tempfile::tempdir()?; + let mut runtime = BlockRuntime::new_for_target( + 76, + cache.path().into(), + BlockProfile::ORDINARY, + TargetCpu::Baseline, + ); + runtime.register_code( + GuestAddress(BASE), + words(&[ADD_ONE, FDIV_S0_S1_S2, FCVT_D3_S1, ADD_ONE, RET]), + )?; + for (zero, wide) in [(0u64, 0u64), (0x8000_0000, 0x8000_0000_0000_0000)] { + for (fpcr, fpsr) in [(0, 0), (0, INEXACT), (FPCR_FZ, 0), (FPCR_NEP, INEXACT)] { + let mut thread = input(false); + thread.registers.fpcr = fpcr; + thread.registers.fpsr = fpsr; + thread.registers.v[1][0] = 0xdead_beef_0000_0000 | zero; + thread.registers.v[2][0] = 0x89ab_cdef_0000_0000 | THREE; + let mut expected = thread.registers.clone(); + expected.x[0] += 2; + publish(&mut expected, 0, 1, zero, 32); + let old = expected.v[3]; + expected.v[3] = if fpcr & FPCR_NEP != 0 { + [wide, old[1]] + } else { + [wide, 0] + }; + // SAFETY: the test program reads and writes only its own registered guest data, and nothing + // else mutates it. + let done = unsafe { runtime.run(&mut thread, Some(GuestAddress(STOP)), 8)? }; + assert_eq!(done.reason, StopReason::StopAddress); + assert_eq!( + done.floating_point_helpers, 0, + "{zero:#x} {fpcr:#x} {fpsr:#x}" + ); + assert_eq!(thread.registers, expected, "{zero:#x} {fpcr:#x} {fpsr:#x}"); + } + } + let mut thread = input(false); + thread.registers.fpsr = 0; + thread.registers.v[1][0] = THREE; + thread.registers.v[2][0] = 0; + // SAFETY: as above. + let done = unsafe { runtime.run(&mut thread, Some(GuestAddress(STOP)), 8)? }; + assert_eq!(done.reason, StopReason::StopAddress); + assert_eq!(done.floating_point_helpers, 1); + assert_eq!(thread.registers.fpsr, DIVIDE_BY_ZERO); + assert_eq!(thread.registers.v[0][0], 0x7f80_0000); + Ok(()) + } + #[test] fn packed_truncation_retires_from_native_status_when_flush_has_no_effect() -> Result<()> { use stela_compiler::aarch64::floating::{ @@ -450,6 +511,170 @@ mod numerical { } Ok(()) } + + /// Run `program` once with `target` and once with the baseline target, + /// whose helper completes every listed FP word exactly, and return both + /// final states with the native run's helper count. + fn against_helper( + program: &[u32], + target: TargetCpu, + thread: &ThreadState, + ) -> Result<(GuestState, GuestState, usize)> { + let mut states = Vec::new(); + let mut helpers = 0; + for (index, target) in [target, TargetCpu::Baseline].into_iter().enumerate() { + let cache = tempfile::tempdir()?; + let mut runtime = BlockRuntime::new_for_target( + 77, + cache.path().into(), + BlockProfile::ORDINARY, + target, + ); + runtime.register_code(GuestAddress(BASE), words(program))?; + let mut run = thread.clone(); + // SAFETY: the program only operates on its own registered code and state. + let report = unsafe { runtime.run(&mut run, Some(GuestAddress(STOP)), 8)? }; + assert_eq!(report.reason, StopReason::StopAddress); + if index == 0 { + helpers = report.floating_point_helpers; + } + states.push(run.registers); + } + let reference = states.pop().unwrap(); + Ok((states.pop().unwrap(), reference, helpers)) + } + + /// Vector FMLA and FMLS of S and D lanes, with normal and zero lanes, + /// finish in compiled code with FMA3 on the full path (FPSR.IXC clear) + /// and on the sticky one, with the helper's exact results and status. + #[test] + fn vector_fused_products_stay_in_compiled_code_with_fma3() -> Result<()> { + let target = TargetCpu::detect(); + if !target.supports(TargetCpu::Fma) { + return Ok(()); + } + // FMLA V0.4S,V1.4S,V2.4S; FMLS V3.4S,V1.4S,V2.4S; FMLA V5.2D,V6.2D,V7.2D. + let program = [ADD_ONE, 0x4e22_cc20, 0x4ea2_cc23, 0x4e67_ccc5, ADD_ONE, RET]; + let singles = |lanes: [u32; 4]| { + [ + u64::from(lanes[0]) | u64::from(lanes[1]) << 32, + u64::from(lanes[2]) | u64::from(lanes[3]) << 32, + ] + }; + for fpsr in [0, INEXACT] { + for rounding in 0..4 { + let mut thread = input(false); + thread.registers.fpsr = fpsr; + thread.registers.fpcr = rounding << ROUNDING_SHIFT; + thread.registers.v[0] = singles([0x3f80_0000, 0xbf2a_aaab, 0, 0x4049_0fdb]); + thread.registers.v[1] = singles([0x3eaa_aaab, 0x3f35_04f3, 0x8000_0000, 0]); + thread.registers.v[2] = singles([0x3dcc_cccd, 0xc0a0_0000, 0x3f80_0000, 0]); + thread.registers.v[3] = singles([0x4120_0000, 0, 0x3e4c_cccd, 0x8000_0000]); + thread.registers.v[5] = [0x3fd5_5555_5555_5555, 0]; + thread.registers.v[6] = [0x3fb9_9999_9999_999a, 0x4000_0000_0000_0000]; + thread.registers.v[7] = [0xbff0_0000_0000_0001, 0x8000_0000_0000_0000]; + let (native, reference, helpers) = against_helper(&program, target, &thread)?; + assert_eq!(helpers, 0, "{fpsr:#x} {rounding}"); + assert_eq!(native, reference, "{fpsr:#x} {rounding}"); + assert_eq!(native.fpsr & INEXACT, INEXACT); + } + } + Ok(()) + } + + /// Vector ordered comparisons order zero and infinite lanes in compiled + /// code; a NaN (IOC) or a subnormal (FZ) lane still takes the helper. + #[test] + fn vector_comparisons_keep_zero_and_infinite_lanes_compiled() -> Result<()> { + // FCMGE V4.4S,V7.4S,V18.4S; FCMGT V5.2D,V6.2D,V8.2D; FACGE V9.4S,V7.4S,V18.4S. + let program = [ADD_ONE, 0x6e32_e4e4, 0x6ee8_e4c5, 0x6e32_ece9, ADD_ONE, RET]; + let cases = [ + ([0x8000_0000_0000_0000, 0xff80_0000_7f80_0000], 0, false), + ([0x3f80_0000_7f80_0000, 0x0000_0000_bf80_0000], 0, false), + ([0x7fc0_0000_0000_0000, 0], INVALID, true), + ([0x0000_0001_0000_0000, 0], 0, true), + ]; + for (left, status, exceptional) in cases { + let mut thread = input(false); + thread.registers.fpsr = 0; + thread.registers.v[7] = left; + thread.registers.v[18] = [0x0000_0000_8000_0000, 0x7f80_0000_ff80_0000]; + thread.registers.v[6] = [0x7ff0_0000_0000_0000, 0x8000_0000_0000_0000]; + thread.registers.v[8] = [0x3ff0_0000_0000_0000, 0]; + let (native, reference, helpers) = + against_helper(&program, TargetCpu::detect(), &thread)?; + // FCMGE and FACGE both read the exceptional lane. + assert_eq!(helpers, 2 * usize::from(exceptional), "{left:x?}"); + assert_eq!(native, reference, "{left:x?}"); + assert_eq!(native.fpsr, status, "{left:x?}"); + } + Ok(()) + } + + /// Half FCMP orders zeros of either sign and infinities in compiled + /// code, and FCVT widens a zero Half there; a NaN or a subnormal still + /// takes the helper. + #[test] + fn half_compares_and_widening_keep_zeros_and_infinities_compiled() -> Result<()> { + // FCMP H2,H0; CSET X5,GE; FCVT S4,H4; FCVT D6,H6. + let program = [ + ADD_ONE, + 0x1ee0_2040, + 0x9a9f_b7e5, + 0x1ee2_4084, + 0x1ee2_c0c6, + ADD_ONE, + RET, + ]; + let cases = [ + (0x8000, 0x0000, 0x8000, 0), + (0x0000, 0x8000, 0x0000, 0), + (0xfc00, 0x3c00, 0xc000, 0), + (0x7c00, 0x7c00, 0xbc00, 0), + (0x3c00, 0xfbff, 0x3555, 0), + (0x7e00, 0x3c00, 0x0000, 1), + (0x0001, 0x3c00, 0x0000, 1), + ]; + for (left, right, widened, helpers) in cases { + for fpcr in [0, FPCR_NEP] { + let mut thread = input(false); + thread.registers.fpcr = fpcr; + thread.registers.fpsr = 0; + thread.registers.v[2][0] = 0xdead_0000 | left; + thread.registers.v[0][0] = 0xbeef_0000 | right; + thread.registers.v[4][0] = 0x1234_0000 | widened; + thread.registers.v[6][0] = 0x5678_0000 | widened; + let (native, reference, count) = + against_helper(&program, TargetCpu::detect(), &thread)?; + assert_eq!(count, helpers, "{left:#x} {right:#x} {widened:#x}"); + assert_eq!(native, reference, "{left:#x} {right:#x} {widened:#x}"); + } + } + Ok(()) + } + + /// FCVTN and FCVTN2 from S to H narrow zero lanes in compiled code with + /// F16C, with the helper's results. + #[test] + fn half_narrowing_keeps_zero_lanes_compiled_with_f16c() -> Result<()> { + let target = TargetCpu::detect(); + if !target.supports(TargetCpu::F16c) { + return Ok(()); + } + // FCVTN V3.4H,V4.4S; FCVTN2 V3.8H,V5.4S. + let program = [ADD_ONE, 0x0e21_6883, 0x4e21_68a3, ADD_ONE, RET]; + for fpsr in [0, INEXACT] { + let mut thread = input(false); + thread.registers.fpsr = fpsr; + thread.registers.v[4] = [0x8000_0000_3f80_0000, 0x3eaa_aaab_0000_0000]; + thread.registers.v[5] = [0, 0xc120_0000_8000_0000]; + let (native, reference, helpers) = against_helper(&program, target, &thread)?; + assert_eq!(helpers, 0, "{fpsr:#x}"); + assert_eq!(native, reference, "{fpsr:#x}"); + assert_eq!(native.v[3], [0x3555_0000_8000_3c00, 0xc900_8000_0000_0000]); + } + Ok(()) + } } #[test]