diff --git a/crates/celox-backend-arm64/src/isel/extern_call.rs b/crates/celox-backend-arm64/src/isel/extern_call.rs index 0762769bb20..90275d538e4 100644 --- a/crates/celox-backend-arm64/src/isel/extern_call.rs +++ b/crates/celox-backend-arm64/src/isel/extern_call.rs @@ -167,3 +167,57 @@ pub(super) fn lower_float( }); define_extern_result(ctx, block, dst, result); } + +// Native FP operations keep the existing payload register/ABI convention. +pub(super) fn lower_native_float_binary( + ctx: &mut ISelContext, + block: &mut MBlock, + dst: RegisterId, + lhs: RegisterId, + rhs: RegisterId, + op: celox_sir::FloatBinaryOp, + precision: celox_sir::FloatPrecision, +) -> bool { + if matches!( + op, + celox_sir::FloatBinaryOp::Rem | celox_sir::FloatBinaryOp::Pow + ) { + return false; + } + let result = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::FloatBinary { + dst: result, + lhs: ctx.reg_map.get(lhs), + rhs: ctx.reg_map.get(rhs), + op, + precision, + }); + define_extern_result(ctx, block, dst, result); + true +} +pub(super) fn lower_native_float_unary( + ctx: &mut ISelContext, + block: &mut MBlock, + dst: RegisterId, + src: RegisterId, + op: celox_sir::FloatUnaryOp, + precision: celox_sir::FloatPrecision, +) -> bool { + if !matches!( + op, + celox_sir::FloatUnaryOp::Neg + | celox_sir::FloatUnaryOp::ToBool + | celox_sir::FloatUnaryOp::Convert { .. } + ) { + return false; + } + let result = ctx.alloc_vreg(SpillDesc::transient()); + block.push(MInst::FloatUnary { + dst: result, + src: ctx.reg_map.get(src), + op, + precision, + }); + define_extern_result(ctx, block, dst, result); + true +} diff --git a/crates/celox-backend-arm64/src/isel/instruction.rs b/crates/celox-backend-arm64/src/isel/instruction.rs index fc826bb6ca3..d29adb87c54 100644 --- a/crates/celox-backend-arm64/src/isel/instruction.rs +++ b/crates/celox-backend-arm64/src/isel/instruction.rs @@ -1993,6 +1993,11 @@ pub(super) fn lower_instruction( SIRInstruction::Binary(dst, lhs, op, rhs) => { if let BinaryOp::Float { op, precision } = op { + if extern_call::lower_native_float_binary( + ctx, block, *dst, *lhs, *rhs, *op, *precision, + ) { + return; + } extern_call::lower_float( ctx, block, @@ -2793,6 +2798,9 @@ pub(super) fn lower_instruction( SIRInstruction::Unary(dst, op, src) => { if let UnaryOp::Float { op, precision } = op { + if extern_call::lower_native_float_unary(ctx, block, *dst, *src, *op, *precision) { + return; + } extern_call::lower_float( ctx, block, diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index 403ea737368..3456a2c8be1 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -1,3 +1,4 @@ +mod floating; mod partial_load; mod reductions; mod shifts; diff --git a/crates/celox-backend-arm64/src/isel/tests/floating.rs b/crates/celox-backend-arm64/src/isel/tests/floating.rs new file mode 100644 index 00000000000..6e8cea9c54b --- /dev/null +++ b/crates/celox-backend-arm64/src/isel/tests/floating.rs @@ -0,0 +1,223 @@ +use super::*; +use celox_sir::{FloatBinaryOp as F, FloatPrecision as P, FloatUnaryOp as U}; + +fn float_unit( + op: SIRInstruction, + precision: P, +) -> (ExecutionUnit, MemoryLayout) { + let absolute = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId::default(), + }; + let address = RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, absolute); + let mut unit = scalar_store_unit(address, false); + let width = match precision { + P::F32 => 32, + P::F64 => 64, + }; + for ty in unit.register_map.values_mut() { + *ty = RegisterType::Bit { + width, + signed: false, + }; + } + let result_width = match &op { + SIRInstruction::Binary( + _, + _, + BinaryOp::Float { + op: F::Eq | F::Ne | F::Lt | F::Le | F::Gt | F::Ge, + .. + }, + _, + ) + | SIRInstruction::Unary(_, UnaryOp::Float { op: U::ToBool, .. }, _) => 1, + SIRInstruction::Unary( + _, + UnaryOp::Float { + op: U::Convert { to: P::F32 }, + .. + }, + _, + ) => 32, + SIRInstruction::Unary( + _, + UnaryOp::Float { + op: U::Convert { to: P::F64 }, + .. + }, + _, + ) => 64, + _ => width, + }; + unit.register_map.insert( + RegisterId(2), + RegisterType::Bit { + width: result_width, + signed: false, + }, + ); + let block = unit.blocks.get_mut(&SirBlockId(0)).unwrap(); + block.instructions[0] = SIRInstruction::Imm( + RegisterId(0), + SIRValue::new(match precision { + P::F32 => 1.5f32.to_bits() as u64, + P::F64 => 1.5f64.to_bits(), + }), + ); + block.instructions[1] = SIRInstruction::Imm( + RegisterId(1), + SIRValue::new(match precision { + P::F32 => 2.0f32.to_bits() as u64, + P::F64 => 2.0f64.to_bits(), + }), + ); + block.instructions[2] = op; + block.instructions[3] = SIRInstruction::Store( + address, + SIROffset::Static(0), + result_width, + RegisterId(2), + Vec::new(), + Vec::new(), + ); + (unit, layout_for(absolute, 64, false)) +} + +#[test] +fn basic_float_operations_select_native_mir_and_emit_without_helpers() { + for precision in [P::F32, P::F64] { + for op in [ + F::Add, + F::Sub, + F::Mul, + F::Div, + F::Eq, + F::Ne, + F::Lt, + F::Le, + F::Gt, + F::Ge, + ] { + let (unit, layout) = float_unit( + SIRInstruction::Binary( + RegisterId(2), + RegisterId(0), + BinaryOp::Float { op, precision }, + RegisterId(1), + ), + precision, + ); + let mir = lower_execution_unit(&unit, &layout, false); + assert!( + mir.blocks.iter().flat_map(|b| &b.insts).any( + |i| matches!(i, MInst::FloatBinary { op: selected, .. } if *selected == op) + ) + ); + assert!( + !mir.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| matches!(i, MInst::CallExtern { .. })) + ); + let code = crate::scalar::emit_prepared_eu( + &unit, + &layout, + false, + "eval_comb", + false, + None, + || false, + ) + .unwrap(); + let opcode = match op { + F::Add => 0x1e21_2800, + F::Sub => 0x1e21_3800, + F::Mul => 0x1e21_0800, + F::Div => 0x1e21_1800, + _ => 0x1e21_2000, + } | if precision == P::F64 { 0x0040_0000 } else { 0 }; + assert!( + code.code + .as_chunks::<4>() + .0 + .iter() + .any(|word| u32::from_le_bytes(*word) == opcode), + "missing {op:?}.{precision:?} opcode" + ); + #[cfg(all(target_arch = "aarch64", target_os = "linux"))] + { + let jit = crate::jit_mem::JitCode::new(&code.code).unwrap(); + let mut state = vec![0u8; layout.merged_total_size]; + assert_eq!(unsafe { jit.call(&mut state) }, 0); + let a = if precision == P::F32 { + 1.5f32.to_bits() as u64 + } else { + 1.5f64.to_bits() + }; + let b = if precision == P::F32 { + 2.0f32.to_bits() as u64 + } else { + 2.0f64.to_bits() + }; + assert_eq!( + u64::from_le_bytes(state[..8].try_into().unwrap()), + celox_design::eval_float_binary(op, precision, a, b) + ); + } + } + for op in [ + U::Neg, + U::ToBool, + U::Convert { to: P::F32 }, + U::Convert { to: P::F64 }, + ] { + let (unit, layout) = float_unit( + SIRInstruction::Unary( + RegisterId(2), + UnaryOp::Float { op, precision }, + RegisterId(0), + ), + precision, + ); + let mir = lower_execution_unit(&unit, &layout, false); + assert!( + mir.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| matches!(i, MInst::FloatUnary { .. })) + ); + let code = crate::scalar::emit_prepared_eu( + &unit, + &layout, + false, + "eval_comb", + false, + None, + || false, + ) + .unwrap(); + assert!(!code.code.is_empty()); + } + } +} + +#[test] +fn complex_float_operations_keep_helper_calls() { + for op in [F::Rem, F::Pow] { + let (unit, layout) = float_unit( + SIRInstruction::Binary( + RegisterId(2), + RegisterId(0), + BinaryOp::Float { + op, + precision: P::F64, + }, + RegisterId(1), + ), + P::F64, + ); + let mir = lower_execution_unit(&unit, &layout, false); + assert!(mir.blocks.iter().flat_map(|b| &b.insts).any(|i| matches!(i, MInst::CallExtern { func, .. } if *func == celox_sir::float::FLOAT_HELPER_ID))); + } +} diff --git a/crates/celox-backend-arm64/src/mir.rs b/crates/celox-backend-arm64/src/mir.rs index 5192b5090e8..c576398d764 100644 --- a/crates/celox-backend-arm64/src/mir.rs +++ b/crates/celox-backend-arm64/src/mir.rs @@ -285,6 +285,21 @@ impl SparseCommitDescriptor { /// Word-level AArch64 operations before physical-register substitution. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum MInst { + /// IEEE payloads use ordinary virtual registers; emission stages operands + /// through caller-clobbered SIMD scratch registers for native FP execution. + FloatBinary { + dst: VReg, + lhs: VReg, + rhs: VReg, + op: celox_sir::FloatBinaryOp, + precision: celox_sir::FloatPrecision, + }, + FloatUnary { + dst: VReg, + src: VReg, + op: celox_sir::FloatUnaryOp, + precision: celox_sir::FloatPrecision, + }, Mov { dst: VReg, src: VReg, @@ -686,7 +701,9 @@ pub(crate) enum MInst { impl MInst { pub(crate) fn def(&self) -> Option { match self { - Self::Mov { dst, .. } + Self::FloatBinary { dst, .. } + | Self::FloatUnary { dst, .. } + | Self::Mov { dst, .. } | Self::Mov32 { dst, .. } | Self::LoadImm { dst, .. } | Self::BitExtract { dst, .. } @@ -771,7 +788,9 @@ impl MInst { pub(crate) fn def_mut(&mut self) -> Option<&mut VReg> { match self { Self::CallExtern { dst, .. } => dst.as_mut(), - Self::Mov { dst, .. } + Self::FloatBinary { dst, .. } + | Self::FloatUnary { dst, .. } + | Self::Mov { dst, .. } | Self::Mov32 { dst, .. } | Self::LoadImm { dst, .. } | Self::BitExtract { dst, .. } @@ -883,7 +902,8 @@ impl MInst { | Self::ReleaseStorePtrIndexed { ptr, index, src, .. } => vec![*ptr, *index, *src], - Self::Add { lhs, rhs, .. } + Self::FloatBinary { lhs, rhs, .. } + | Self::Add { lhs, rhs, .. } | Self::Add32 { lhs, rhs, .. } | Self::Sub { lhs, rhs, .. } | Self::Sub32 { lhs, rhs, .. } @@ -905,7 +925,8 @@ impl MInst { | Self::URem { lhs, rhs, .. } | Self::SDiv { lhs, rhs, .. } | Self::SRem { lhs, rhs, .. } => vec![*lhs, *rhs], - Self::BitExtract { src, .. } + Self::FloatUnary { src, .. } + | Self::BitExtract { src, .. } | Self::AndImm { src, .. } | Self::AndImm32 { src, .. } | Self::OrImm { src, .. } @@ -1019,7 +1040,8 @@ impl MInst { rewrite(index); rewrite(src); } - Self::Add { lhs, rhs, .. } + Self::FloatBinary { lhs, rhs, .. } + | Self::Add { lhs, rhs, .. } | Self::Add32 { lhs, rhs, .. } | Self::Sub { lhs, rhs, .. } | Self::Sub32 { lhs, rhs, .. } @@ -1044,7 +1066,8 @@ impl MInst { rewrite(lhs); rewrite(rhs); } - Self::BitExtract { src, .. } + Self::FloatUnary { src, .. } + | Self::BitExtract { src, .. } | Self::AndImm { src, .. } | Self::AndImm32 { src, .. } | Self::OrImm { src, .. } diff --git a/crates/celox-backend-arm64/src/scalar.rs b/crates/celox-backend-arm64/src/scalar.rs index 6a8a4268034..9ad56a21387 100644 --- a/crates/celox-backend-arm64/src/scalar.rs +++ b/crates/celox-backend-arm64/src/scalar.rs @@ -650,6 +650,90 @@ fn emit_instruction( let is_next = |target| next_block.is_some_and(|next| labels[&next] == labels[&target]); match instruction { MInst::CallExtern { .. } => unreachable!("the block loop emits extern calls"), + MInst::FloatBinary { + dst, + lhs, + rhs, + op, + precision, + } => { + use celox_sir::{FloatBinaryOp as F, FloatPrecision as P}; + let (dst, lhs, rhs) = ( + resolve(assignment, *dst)?, + resolve(assignment, *lhs)?, + resolve(assignment, *rhs)?, + ); + // v0/v1 are caller-clobbered scratch; persistent loop state uses v29/v31. + match precision { + P::F32 => { + dynasm!(ops ; .arch aarch64 ; fmov s0, W(lhs) ; fmov s1, W(rhs)); + match op { + F::Add => dynasm!(ops ; .arch aarch64 ; fadd s0, s0, s1), + F::Sub => dynasm!(ops ; .arch aarch64 ; fsub s0, s0, s1), + F::Mul => dynasm!(ops ; .arch aarch64 ; fmul s0, s0, s1), + F::Div => dynasm!(ops ; .arch aarch64 ; fdiv s0, s0, s1), + _ => dynasm!(ops ; .arch aarch64 ; fcmp s0, s1), + } + } + P::F64 => { + dynasm!(ops ; .arch aarch64 ; fmov d0, X(lhs) ; fmov d1, X(rhs)); + match op { + F::Add => dynasm!(ops ; .arch aarch64 ; fadd d0, d0, d1), + F::Sub => dynasm!(ops ; .arch aarch64 ; fsub d0, d0, d1), + F::Mul => dynasm!(ops ; .arch aarch64 ; fmul d0, d0, d1), + F::Div => dynasm!(ops ; .arch aarch64 ; fdiv d0, d0, d1), + _ => dynasm!(ops ; .arch aarch64 ; fcmp d0, d1), + } + } + } + match op { + F::Eq => dynasm!(ops ; .arch aarch64 ; cset X(dst), eq), + F::Ne => dynasm!(ops ; .arch aarch64 ; cset X(dst), ne), + // FCMP unordered has NZCV=0011: MI/LS/GT/GE all reject NaN. + F::Lt => dynasm!(ops ; .arch aarch64 ; cset X(dst), mi), + F::Le => dynasm!(ops ; .arch aarch64 ; cset X(dst), ls), + F::Gt => dynasm!(ops ; .arch aarch64 ; cset X(dst), gt), + F::Ge => dynasm!(ops ; .arch aarch64 ; cset X(dst), ge), + F::Add | F::Sub | F::Mul | F::Div => match precision { + P::F32 => dynasm!(ops ; .arch aarch64 ; fmov W(dst), s0), + P::F64 => dynasm!(ops ; .arch aarch64 ; fmov X(dst), d0), + }, + F::Rem | F::Pow => unreachable!("complex float operations use helpers"), + } + } + MInst::FloatUnary { + dst, + src, + op, + precision, + } => { + use celox_sir::{FloatPrecision as P, FloatUnaryOp as F}; + let (dst, src) = (resolve(assignment, *dst)?, resolve(assignment, *src)?); + match precision { + P::F32 => dynasm!(ops ; .arch aarch64 ; fmov s0, W(src)), + P::F64 => dynasm!(ops ; .arch aarch64 ; fmov d0, X(src)), + } + match (op, precision) { + (F::Neg, P::F32) => dynasm!(ops ; .arch aarch64 ; fneg s0, s0), + (F::Neg, P::F64) => dynasm!(ops ; .arch aarch64 ; fneg d0, d0), + (F::ToBool, P::F32) => dynasm!(ops ; .arch aarch64 ; fcmp s0, #0.0), + (F::ToBool, P::F64) => dynasm!(ops ; .arch aarch64 ; fcmp d0, #0.0), + (F::Convert { to: P::F64 }, P::F32) => dynasm!(ops ; .arch aarch64 ; fcvt d0, s0), + (F::Convert { to: P::F32 }, P::F64) => dynasm!(ops ; .arch aarch64 ; fcvt s0, d0), + (F::Convert { .. }, _) => {} + _ => unreachable!("integer float conversions use helpers"), + } + match op { + F::ToBool => dynasm!(ops ; .arch aarch64 ; cset X(dst), ne), + _ => match match op { + F::Convert { to } => to, + _ => precision, + } { + P::F32 => dynasm!(ops ; .arch aarch64 ; fmov W(dst), s0), + P::F64 => dynasm!(ops ; .arch aarch64 ; fmov X(dst), d0), + }, + } + } MInst::Mov { dst, src } => { let (dst, src) = (resolve(assignment, *dst)?, resolve(assignment, *src)?); if dst != src { diff --git a/crates/celox-backend-cranelift/src/translator/arith.rs b/crates/celox-backend-cranelift/src/translator/arith.rs index e887df70db5..3cc7fa957dd 100644 --- a/crates/celox-backend-cranelift/src/translator/arith.rs +++ b/crates/celox-backend-cranelift/src/translator/arith.rs @@ -304,7 +304,8 @@ impl SIRTranslator { *dst, *lhs, Some(*rhs), - celox_sir::float::binary_code(*op, *precision), + super::core::FloatOperation::Binary(*op), + *precision, ); return; } @@ -1407,7 +1408,8 @@ impl SIRTranslator { *dst, *rhs, None, - celox_sir::float::unary_code(*op, *precision), + super::core::FloatOperation::Unary(*op), + *precision, ); return; } diff --git a/crates/celox-backend-cranelift/src/translator/core.rs b/crates/celox-backend-cranelift/src/translator/core.rs index f782f05885d..9b475b61111 100644 --- a/crates/celox-backend-cranelift/src/translator/core.rs +++ b/crates/celox-backend-cranelift/src/translator/core.rs @@ -12,6 +12,13 @@ use crate::{ }; use super::MemoryLayout; +use celox_sir::{FloatBinaryOp as FB, FloatPrecision, FloatUnaryOp as FU}; + +#[derive(Clone, Copy)] +pub(super) enum FloatOperation { + Binary(FB), + Unary(FU), +} /// Pre-load trigger signal values at function entry for register-based /// edge detection. Only needed when `emit_triggers` is enabled (Simulation mode). @@ -518,10 +525,14 @@ impl SIRTranslator { dst: RegisterId, lhs: RegisterId, rhs: Option, - code: u64, + op: FloatOperation, + precision: FloatPrecision, ) { let a = state.regs[&lhs].first_value(state.builder); - let a = if matches!(code & 255, 34 | 35) { + let a = if matches!( + op, + FloatOperation::Unary(FU::FromSigned { .. } | FU::FromUnsigned { .. }) + ) { if let Some(mask) = state.regs[&lhs].first_mask(state.builder) { let known = state.builder.ins().bnot(mask); state.builder.ins().band(a, known) @@ -547,6 +558,106 @@ impl SIRTranslator { } else { state.builder.ins().iconst(types::I64, 0) }; + if !matches!( + op, + FloatOperation::Binary(FB::Rem | FB::Pow) + | FloatOperation::Unary(FU::ToSigned { .. } | FU::ToUnsigned { .. }) + ) { + let ty = if precision == FloatPrecision::F64 { + types::F64 + } else { + types::F32 + }; + let result = if let FloatOperation::Unary( + FU::FromSigned { width } | FU::FromUnsigned { width }, + ) = op + { + let mut integer = a; + if width < 64 { + integer = state.builder.ins().ishl_imm_u(integer, (64 - width) as i64); + integer = if matches!(op, FloatOperation::Unary(FU::FromSigned { .. })) { + state.builder.ins().sshr_imm_u(integer, (64 - width) as i64) + } else { + state.builder.ins().ushr_imm_u(integer, (64 - width) as i64) + }; + } + if matches!(op, FloatOperation::Unary(FU::FromSigned { .. })) { + state.builder.ins().fcvt_from_sint(ty, integer) + } else { + state.builder.ins().fcvt_from_uint(ty, integer) + } + } else { + let float_bits = |builder: &mut FunctionBuilder, bits| { + let bits = if ty == types::F32 { + builder.ins().ireduce(types::I32, bits) + } else { + bits + }; + builder.ins().bitcast(ty, MemFlags::new(), bits) + }; + let a = float_bits(state.builder, a); + let b = float_bits(state.builder, b); + match op { + FloatOperation::Binary(FB::Add) => state.builder.ins().fadd(a, b), + FloatOperation::Binary(FB::Sub) => state.builder.ins().fsub(a, b), + FloatOperation::Binary(FB::Mul) => state.builder.ins().fmul(a, b), + FloatOperation::Binary(FB::Div) => state.builder.ins().fdiv(a, b), + FloatOperation::Binary( + comparison @ (FB::Eq | FB::Ne | FB::Lt | FB::Le | FB::Gt | FB::Ge), + ) => { + let condition = match comparison { + FB::Eq => FloatCC::Equal, + FB::Ne => FloatCC::NotEqual, + FB::Lt => FloatCC::LessThan, + FB::Le => FloatCC::LessThanOrEqual, + FB::Gt => FloatCC::GreaterThan, + FB::Ge => FloatCC::GreaterThanOrEqual, + _ => unreachable!(), + }; + state.builder.ins().fcmp(condition, a, b) + } + FloatOperation::Unary(FU::Neg) => state.builder.ins().fneg(a), + FloatOperation::Unary(FU::ToBool) => { + let zero = if ty == types::F32 { + state.builder.ins().f32const(0.0) + } else { + state.builder.ins().f64const(0.0) + }; + state.builder.ins().fcmp(FloatCC::NotEqual, a, zero) + } + FloatOperation::Unary(FU::Convert { + to: FloatPrecision::F32, + }) if ty == types::F64 => state.builder.ins().fdemote(types::F32, a), + FloatOperation::Unary(FU::Convert { + to: FloatPrecision::F64, + }) if ty == types::F32 => state.builder.ins().fpromote(types::F64, a), + FloatOperation::Unary(FU::Convert { .. }) => a, + _ => unreachable!("known floating operation"), + } + }; + let result_ty = state.builder.func.dfg.value_type(result); + let result = if result_ty == types::F32 { + let raw = state + .builder + .ins() + .bitcast(types::I32, MemFlags::new(), result); + state.builder.ins().uextend(types::I64, raw) + } else if result_ty == types::F64 { + state + .builder + .ins() + .bitcast(types::I64, MemFlags::new(), result) + } else { + state.builder.ins().uextend(types::I64, result) + }; + let value = self.extern_call_result(state, dst, result); + state.regs.insert(dst, value); + return; + } + let code = match op { + FloatOperation::Binary(op) => celox_sir::float::binary_code(op, precision), + FloatOperation::Unary(op) => celox_sir::float::unary_code(op, precision), + }; let c = state.builder.ins().iconst(types::I64, code as i64); let address = state.builder.ins().iconst( types::I64, diff --git a/crates/celox-backend-wasm/src/lib.rs b/crates/celox-backend-wasm/src/lib.rs index aee519a5087..0aa506964df 100644 --- a/crates/celox-backend-wasm/src/lib.rs +++ b/crates/celox-backend-wasm/src/lib.rs @@ -6677,6 +6677,16 @@ mod bit_count_tests { f64::MAX.to_bits() }, ]); + for &value in &inputs { + for op in [ + U::Neg, + U::ToBool, + U::Convert { to: P::F32 }, + U::Convert { to: P::F64 }, + ] { + cases.push((op, p, p.width(), value, 0)); + } + } for width in [1, 3, 8, 32, 64] { for round in [false, true] { for &value in &inputs { @@ -6776,6 +6786,14 @@ mod bit_count_tests { for four_state in [false, true] { for (op, a, b, expected) in [ (F::Add, 1.25, 2.5, 3.75), + (F::Sub, 2.5, 1.25, 1.25), + (F::Add, f64::NAN, 1.0, f64::NAN), + (F::Eq, f64::NAN, 1.0, 0.0), + (F::Ne, f64::NAN, 1.0, 1.0), + (F::Lt, f64::NAN, 1.0, 0.0), + (F::Le, -0.0, 0.0, 1.0), + (F::Gt, -0.0, 0.0, 0.0), + (F::Ge, -0.0, 0.0, 1.0), (F::Div, 1.0, 0.0, f64::INFINITY), (F::Mul, -0.0, 2.0, -0.0), ] { @@ -6833,14 +6851,47 @@ mod bit_count_tests { register_map, }; let layout = layout(width, four_state); + let options = CompileOptions { + four_state, + emit_triggers: false, + cranelift: CraneliftOptions::default(), + }; + let mut engine = JitEngine::new(layout.clone(), &options).unwrap(); + let mut clif = String::new(); + engine + .compile_units(std::slice::from_ref(&unit), Some(&mut clif), None, None) + .unwrap(); + assert!( + !clif.contains("call_indirect"), + "basic FP operation used a helper: {clif}" + ); for output in [ run_cranelift(&unit, &layout, four_state), run_wasm(&unit, &layout, four_state), ] { - assert_eq!( - read_bits_at(&output, OUTPUT_OFFSET, 0, width), - BigUint::from(bits(expected)) - ); + let actual = read_bits_at(&output, OUTPUT_OFFSET, 0, width) + .to_u64_digits() + .first() + .copied() + .unwrap_or(0); + if expected.is_nan() { + assert!(if precision == P::F32 { + f32::from_bits(actual as u32).is_nan() + } else { + f64::from_bits(actual).is_nan() + }); + } else { + let comparison = + matches!(op, F::Eq | F::Ne | F::Lt | F::Le | F::Gt | F::Ge); + assert_eq!( + actual, + if comparison { + expected as u64 + } else { + bits(expected) + } + ); + } } } } diff --git a/crates/celox-backend-x86/src/backend/native/emit.rs b/crates/celox-backend-x86/src/backend/native/emit.rs index f7297669f95..39a76440b4e 100644 --- a/crates/celox-backend-x86/src/backend/native/emit.rs +++ b/crates/celox-backend-x86/src/backend/native/emit.rs @@ -15,6 +15,7 @@ mod arithmetic; mod control_flow; mod diagnostics; mod extern_call; +mod floating; mod folded_operands; mod instruction; mod memory; diff --git a/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs b/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs index 24303771977..e1e5f41606c 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/diagnostics.rs @@ -36,7 +36,9 @@ pub(super) fn log_mir_stats(label: &str, stage: &str, func: &crate::native::mir: phi += block.phis.len(); for inst in &block.insts { match inst { - MInst::X86Simd(X86SimdInst::Zero128 { .. }) + MInst::FloatBinary { .. } + | MInst::FloatUnary { .. } + | MInst::X86Simd(X86SimdInst::Zero128 { .. }) | MInst::X86Simd(X86SimdInst::Pack128 { .. }) | MInst::X86Simd(X86SimdInst::Binary128 { .. }) => alu += 1, MInst::X86Simd(X86SimdInst::Scratch128 { .. }) => {} diff --git a/crates/celox-backend-x86/src/backend/native/emit/floating.rs b/crates/celox-backend-x86/src/backend/native/emit/floating.rs new file mode 100644 index 00000000000..d1311784bf9 --- /dev/null +++ b/crates/celox-backend-x86/src/backend/native/emit/floating.rs @@ -0,0 +1,104 @@ +//! Scalar SSE2 floating point. GPR payloads are the storage ABI; XMM0/1 +//! are ephemeral, with clobbers declared in x86_slp::clobbers_xmm. +use super::*; +use celox_sir::{FloatBinaryOp as B, FloatPrecision as P, FloatUnaryOp as U}; + +pub(super) fn emit_binary( + asm: &mut EmitAssembler, + assignment: &AssignmentMap, + dst: VReg, + lhs: VReg, + rhs: VReg, + op: B, + precision: P, +) -> Result<(), IcedError> { + let (lhs, rhs) = if matches!(op, B::Gt | B::Ge) { + (rhs, lhs) + } else { + (lhs, rhs) + }; + asm.movq(xmm0, preg_to_reg64(resolve(assignment, lhs)))?; + asm.movq(xmm1, preg_to_reg64(resolve(assignment, rhs)))?; + let predicate = match op { + B::Eq => Some(0), + B::Ne => Some(4), + B::Lt | B::Gt => Some(1), + B::Le | B::Ge => Some(2), + _ => None, + }; + if let Some(predicate) = predicate { + match precision { + P::F32 => asm.cmpss(xmm0, xmm1, predicate)?, + P::F64 => asm.cmpsd_3(xmm0, xmm1, predicate)?, + } + let output = preg_to_reg32(resolve(assignment, dst)); + asm.movd(output, xmm0)?; + asm.and(output, 1)?; + } else { + match (op, precision) { + (B::Add, P::F32) => asm.addss(xmm0, xmm1)?, + (B::Add, P::F64) => asm.addsd(xmm0, xmm1)?, + (B::Sub, P::F32) => asm.subss(xmm0, xmm1)?, + (B::Sub, P::F64) => asm.subsd(xmm0, xmm1)?, + (B::Mul, P::F32) => asm.mulss(xmm0, xmm1)?, + (B::Mul, P::F64) => asm.mulsd(xmm0, xmm1)?, + (B::Div, P::F32) => asm.divss(xmm0, xmm1)?, + (B::Div, P::F64) => asm.divsd(xmm0, xmm1)?, + _ => unreachable!("unsupported native scalar FP binary operation"), + } + match precision { + P::F32 => asm.movd(preg_to_reg32(resolve(assignment, dst)), xmm0)?, + P::F64 => asm.movq(preg_to_reg64(resolve(assignment, dst)), xmm0)?, + } + } + Ok(()) +} + +pub(super) fn emit_unary( + asm: &mut EmitAssembler, + assignment: &AssignmentMap, + dst: VReg, + src: VReg, + op: U, + precision: P, +) -> Result<(), IcedError> { + let input = preg_to_reg64(resolve(assignment, src)); + let output = preg_to_reg64(resolve(assignment, dst)); + match op { + U::Neg => { + if precision == P::F32 { + let output = preg_to_reg32(resolve(assignment, dst)); + asm.mov(output, preg_to_reg32(resolve(assignment, src)))?; + asm.btc(output, 31)?; + } else { + asm.mov(output, input)?; + asm.btc(output, 63)?; + } + } + U::ToBool => { + asm.movq(xmm0, input)?; + asm.pxor(xmm1, xmm1)?; + match precision { + P::F32 => asm.cmpss(xmm0, xmm1, 4)?, + P::F64 => asm.cmpsd_3(xmm0, xmm1, 4)?, + } + let output = preg_to_reg32(resolve(assignment, dst)); + asm.movd(output, xmm0)?; + asm.and(output, 1)?; + } + U::Convert { to } => { + asm.movq(xmm0, input)?; + match (precision, to) { + (P::F32, P::F64) => asm.cvtss2sd(xmm0, xmm0)?, + (P::F64, P::F32) => asm.cvtsd2ss(xmm0, xmm0)?, + _ => {} + } + match to { + P::F32 => asm.movd(preg_to_reg32(resolve(assignment, dst)), xmm0)?, + P::F64 => asm.movq(output, xmm0)?, + } + } + _ => unreachable!("unsupported native scalar FP unary operation"), + } + Ok(()) +} diff --git a/crates/celox-backend-x86/src/backend/native/emit/instruction.rs b/crates/celox-backend-x86/src/backend/native/emit/instruction.rs index 3df0f78a792..021643a28eb 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/instruction.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/instruction.rs @@ -14,6 +14,23 @@ pub(super) fn emit_inst( let context = asm.context; let mut bound_continuation = false; match inst { + MInst::FloatBinary { + dst, + lhs, + rhs, + op, + precision, + } => { + floating::emit_binary(asm, assignment, *dst, *lhs, *rhs, *op, *precision)?; + } + MInst::FloatUnary { + dst, + src, + op, + precision, + } => { + floating::emit_unary(asm, assignment, *dst, *src, *op, *precision)?; + } MInst::ExternArg { index, src } => { extern_call::emit_extern_arg(asm, *index, preg_to_reg64(resolve(assignment, *src)))?; } diff --git a/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs b/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs index 259e46e30cb..1823a0f87de 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/extern_call.rs @@ -132,6 +132,56 @@ pub(super) fn lower_float( rhs: Option, code: u64, ) { + use celox_sir::{FloatBinaryOp as B, FloatPrecision as P, FloatUnaryOp as U}; + let precision = if code & 256 == 0 { P::F32 } else { P::F64 }; + let opcode = code & 255; + let binary = match opcode { + 0 => Some(B::Add), + 1 => Some(B::Sub), + 2 => Some(B::Mul), + 3 => Some(B::Div), + 6 => Some(B::Eq), + 7 => Some(B::Ne), + 8 => Some(B::Lt), + 9 => Some(B::Le), + 10 => Some(B::Gt), + 11 => Some(B::Ge), + _ => None, + }; + let unary = match opcode { + 32 => Some(U::Neg), + 33 => Some(U::ToBool), + 38 => Some(U::Convert { to: P::F32 }), + 39 => Some(U::Convert { to: P::F64 }), + _ => None, + }; + if let Some(op) = binary { + block.push(MInst::FloatBinary { + dst: ctx.reg_map.get(dst), + lhs: ctx.reg_map.get(lhs), + rhs: ctx.reg_map.get(rhs.expect("binary FP SIR operand")), + op, + precision, + }); + } else if let Some(op) = unary { + block.push(MInst::FloatUnary { + dst: ctx.reg_map.get(dst), + src: ctx.reg_map.get(lhs), + op, + precision, + }); + } + if binary.is_some() || unary.is_some() { + if ctx.four_state { + let zero = ctx.alloc_vreg(SpillDesc::remat(0)); + block.push(MInst::LoadImm { + dst: zero, + value: 0, + }); + ctx.set_mask(dst, zero); + } + return; + } let a = ctx.reg_map.get(lhs); let a = if ctx.four_state && matches!(code & 255, 34 | 35) { let mask = ctx.get_mask(lhs, block); diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs index 2b17451218e..0f84c576ace 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/floating.rs @@ -123,7 +123,7 @@ fn float_helpers_preserve_live_registers_and_narrow_mux_results() { .flat_map(|block| &block.insts) .filter(|inst| matches!(inst, MInst::CallExtern { .. })) .count(), - 3 + 1 ); let allocation = regalloc::run_regalloc(&mut function).unwrap(); assert!( @@ -167,3 +167,185 @@ fn float_helpers_preserve_live_registers_and_narrow_mux_results() { } } } + +#[test] +fn scalar_float_mir_executes_without_helper_for_ieee_edges() { + use celox_design::{eval_float_binary, eval_float_unary}; + let binary = [ + F::Add, + F::Sub, + F::Mul, + F::Div, + F::Eq, + F::Ne, + F::Lt, + F::Le, + F::Gt, + F::Ge, + ]; + for precision in [P::F32, P::F64] { + let width = precision.width(); + let unary = [ + U::Neg, + U::ToBool, + U::Convert { to: P::F32 }, + U::Convert { to: P::F64 }, + ]; + for four_state in [false, true] { + let abs = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: VarId::default(), + }; + let addr = RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, abs); + let mut layout = empty_layout(); + const BASE: usize = 64; + let slots = 2 + binary.len() + unary.len(); + layout.four_state = four_state; + layout.offsets.insert(abs, BASE); + layout.widths.insert(abs, slots * 64); + layout.is_4states.insert(abs, false); + layout.total_size = BASE + slots * 8; + layout.merged_total_size = layout.total_size; + layout.scratch_base_offset = layout.total_size; + let bit = |width| RegisterType::Bit { + width, + signed: false, + }; + let mut types = [(RegisterId(0), bit(width)), (RegisterId(1), bit(width))] + .into_iter() + .collect::>(); + let mut instructions = vec![ + SIRInstruction::Load(RegisterId(0), addr, SIROffset::Static(0), width), + SIRInstruction::Load(RegisterId(1), addr, SIROffset::Static(64), width), + ]; + for (index, op) in binary.iter().copied().enumerate() { + let reg = RegisterId(index + 2); + let result_width = if index >= 4 { 1 } else { width }; + types.insert(reg, bit(result_width)); + instructions.push(SIRInstruction::Binary( + reg, + RegisterId(0), + BinaryOp::Float { op, precision }, + RegisterId(1), + )); + instructions.push(SIRInstruction::Store( + addr, + SIROffset::Static((index + 2) * 64), + result_width, + reg, + vec![], + vec![], + )); + } + for (index, op) in unary.iter().copied().enumerate() { + let slot = index + 2 + binary.len(); + let reg = RegisterId(slot); + let result_width = match op { + U::ToBool => 1, + U::Convert { to } => to.width(), + _ => width, + }; + types.insert(reg, bit(result_width)); + instructions.push(SIRInstruction::Unary( + reg, + UnaryOp::Float { op, precision }, + RegisterId(0), + )); + instructions.push(SIRInstruction::Store( + addr, + SIROffset::Static(slot * 64), + result_width, + reg, + vec![], + vec![], + )); + } + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + register_map: types, + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions, + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + }; + unit.verify(); + let mut function = lower_execution_unit(&unit, &layout, four_state); + mir_legalize::legalize(&mut function); + mir_opt::optimize(&mut function); + assert_eq!( + function + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| matches!(i, MInst::FloatBinary { .. })) + .count(), + binary.len() + ); + assert!( + !function + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| matches!(i, MInst::CallExtern { .. })) + ); + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + mir_opt::post_regalloc_peephole(&mut function, &allocation.assignment); + let emitted = emit::emit( + &function, + &allocation.assignment, + allocation.spill_frame_size, + ) + .unwrap(); + let jit = JitCode::new(&emitted.code).unwrap(); + let payload = |x: f64| match precision { + P::F32 => (x as f32).to_bits() as u64, + P::F64 => x.to_bits(), + }; + let mut values = [ + 0.0, + -0.0, + 1.5, + -2.25, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + ] + .map(payload) + .to_vec(); + values.extend(match precision { + P::F32 => vec![1, 0x7f7fffff, 0x7fc12345], + P::F64 => vec![1, 0x7fefffffffffffff, 0x7ff8123456789abc], + }); + for &a in &values { + for &b in &values { + let mut memory = vec![0u8; emitted.required_state_size as usize]; + memory[BASE..BASE + 8].copy_from_slice(&a.to_le_bytes()); + memory[BASE + 8..BASE + 16].copy_from_slice(&b.to_le_bytes()); + // No extern-function header: a hidden helper call would crash. + assert_eq!(unsafe { jit.call(&mut memory) }, 0); + for (index, expected) in binary + .iter() + .map(|&op| eval_float_binary(op, precision, a, b)) + .chain(unary.iter().map(|&op| eval_float_unary(op, precision, a))) + .enumerate() + { + let offset = BASE + (index + 2) * 8; + let actual = + u64::from_le_bytes(memory[offset..offset + 8].try_into().unwrap()); + assert_eq!( + actual, expected, + "{precision:?} four_state={four_state} op={index} a={a:x} b={b:x}" + ); + } + } + } + } + } +} diff --git a/crates/celox-backend-x86/src/backend/native/memory_effect.rs b/crates/celox-backend-x86/src/backend/native/memory_effect.rs index f24379cb523..5016f24fd1b 100644 --- a/crates/celox-backend-x86/src/backend/native/memory_effect.rs +++ b/crates/celox-backend-x86/src/backend/native/memory_effect.rs @@ -233,7 +233,9 @@ pub(crate) fn reads(inst: &MInst) -> MemoryEffects { MInst::ExternArg { .. } | MInst::CallExtern { .. } | MInst::ExternResult { .. } => { MemoryEffects::unknown(UnknownMemory::Direct(BaseReg::SimState)) } - MInst::X86Simd(X86SimdInst::Scratch128 { .. }) + MInst::FloatBinary { .. } + | MInst::FloatUnary { .. } + | MInst::X86Simd(X86SimdInst::Scratch128 { .. }) | MInst::X86Simd(X86SimdInst::Zero128 { .. }) | MInst::X86Simd(X86SimdInst::Pack128 { .. }) | MInst::X86Simd(X86SimdInst::Binary128 { .. }) => MemoryEffects::NONE, @@ -327,7 +329,9 @@ pub(crate) fn writes(inst: &MInst) -> MemoryEffects { MInst::ExternArg { .. } | MInst::CallExtern { .. } | MInst::ExternResult { .. } => { MemoryEffects::unknown(UnknownMemory::Direct(BaseReg::SimState)) } - MInst::X86Simd(X86SimdInst::Scratch128 { .. }) + MInst::FloatBinary { .. } + | MInst::FloatUnary { .. } + | MInst::X86Simd(X86SimdInst::Scratch128 { .. }) | MInst::X86Simd(X86SimdInst::Zero128 { .. }) | MInst::X86Simd(X86SimdInst::Pack128 { .. }) | MInst::X86Simd(X86SimdInst::Binary128 { .. }) diff --git a/crates/celox-backend-x86/src/backend/native/mir.rs b/crates/celox-backend-x86/src/backend/native/mir.rs index 473fc171ba8..2787230575d 100644 --- a/crates/celox-backend-x86/src/backend/native/mir.rs +++ b/crates/celox-backend-x86/src/backend/native/mir.rs @@ -702,6 +702,21 @@ pub const SPARSE_SUMMARY_GROUP: usize = 4; /// handles x86-64's 2-operand constraint by inserting mov when needed. #[derive(Debug, Clone, PartialEq, Eq)] pub enum MInst { + /// Scalar IEEE operation on raw GPR payloads. Emission uses XMM0/XMM1; + /// their clobbers are visible to vector allocation and spill caching. + FloatBinary { + dst: VReg, + lhs: VReg, + rhs: VReg, + op: celox_sir::FloatBinaryOp, + precision: celox_sir::FloatPrecision, + }, + FloatUnary { + dst: VReg, + src: VReg, + op: celox_sir::FloatUnaryOp, + precision: celox_sir::FloatPrecision, + }, /// Explicit target-specific SIMD instruction with its own register class. X86Simd(X86SimdInst), @@ -1112,6 +1127,19 @@ pub enum MInst { impl fmt::Display for MInst { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + MInst::FloatBinary { + dst, + lhs, + rhs, + op, + precision, + } => write!(f, "{dst} = fp.{op:?}.{precision:?} {lhs}, {rhs}"), + MInst::FloatUnary { + dst, + src, + op, + precision, + } => write!(f, "{dst} = fp.{op:?}.{precision:?} {src}"), MInst::X86Simd(X86SimdInst::Scratch128 { dst }) => { write!(f, "{dst} = x86.scratch.v128") } @@ -1511,7 +1539,9 @@ impl MInst { /// Returns the destination VReg, if any. pub fn def(&self) -> Option { match self { - MInst::Mov { dst, .. } + MInst::FloatBinary { dst, .. } + | MInst::FloatUnary { dst, .. } + | MInst::Mov { dst, .. } | MInst::Mov32 { dst, .. } | MInst::LoadImm { dst, .. } | MInst::Scratch { dst } @@ -1601,7 +1631,9 @@ impl MInst { /// silently omit a defining opcode while still compiling successfully. pub fn def_mut(&mut self) -> Option<&mut VReg> { match self { - MInst::Mov { dst, .. } + MInst::FloatBinary { dst, .. } + | MInst::FloatUnary { dst, .. } + | MInst::Mov { dst, .. } | MInst::Mov32 { dst, .. } | MInst::LoadImm { dst, .. } | MInst::Scratch { dst } @@ -1688,7 +1720,9 @@ impl MInst { /// Returns the VRegs used by this instruction (max 3, no heap allocation). pub fn uses(&self) -> Uses { match self { - MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => Uses::one(*src), + MInst::FloatUnary { src, .. } | MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => { + Uses::one(*src) + } MInst::X86Simd(X86SimdInst::Pack128 { low, high, .. }) => Uses::two(*low, *high), MInst::LoadImm { .. } | MInst::X86Simd(X86SimdInst::Scratch128 { .. }) @@ -1732,7 +1766,8 @@ impl MInst { MInst::ReleaseStorePtrIndexed { ptr, index, src, .. } => Uses::three(*ptr, *index, *src), - MInst::Add { lhs, rhs, .. } + MInst::FloatBinary { lhs, rhs, .. } + | MInst::Add { lhs, rhs, .. } | MInst::Add32 { lhs, rhs, .. } | MInst::Sub { lhs, rhs, .. } | MInst::Sub32 { lhs, rhs, .. } @@ -1824,7 +1859,7 @@ impl MInst { /// Replace all occurrences of `old` with `new` in the use operands. pub fn rewrite_use(&mut self, old: VReg, new: VReg) { match self { - MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => { + MInst::FloatUnary { src, .. } | MInst::Mov { src, .. } | MInst::Mov32 { src, .. } => { if *src == old { *src = new; } @@ -1930,7 +1965,8 @@ impl MInst { *src = new; } } - MInst::Add { lhs, rhs, .. } + MInst::FloatBinary { lhs, rhs, .. } + | MInst::Add { lhs, rhs, .. } | MInst::Add32 { lhs, rhs, .. } | MInst::Sub { lhs, rhs, .. } | MInst::Sub32 { lhs, rhs, .. } diff --git a/crates/celox-backend-x86/src/backend/native/mir_verify.rs b/crates/celox-backend-x86/src/backend/native/mir_verify.rs index e08e314c566..379450301a4 100644 --- a/crates/celox-backend-x86/src/backend/native/mir_verify.rs +++ b/crates/celox-backend-x86/src/backend/native/mir_verify.rs @@ -323,6 +323,23 @@ fn verify_instruction_constraints( inst: &MInst, ) -> Result<(), MirVerifyError> { match inst { + MInst::FloatBinary { + op: celox_sir::FloatBinaryOp::Rem | celox_sir::FloatBinaryOp::Pow, + .. + } + | MInst::FloatUnary { + op: + celox_sir::FloatUnaryOp::FromSigned { .. } + | celox_sir::FloatUnaryOp::FromUnsigned { .. } + | celox_sir::FloatUnaryOp::ToSigned { .. } + | celox_sir::FloatUnaryOp::ToUnsigned { .. }, + .. + } => Err(MirVerifyError::instruction( + "OPCODE.FLOAT_NATIVE", + block, + index, + "floating-point operation requires helper lowering", + )), MInst::ShrImm { imm, .. } | MInst::ShlImm { imm, .. } | MInst::SarImm { imm, .. } if *imm >= 64 => { diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs b/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs index d7fc74597ec..adc1c89eee3 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/schedule.rs @@ -1217,6 +1217,7 @@ fn unconstrained_schedulable_at( /// cannot silently turn it into a scheduling barrier (or make it movable). fn is_pressure_schedulable_kind(inst: &MInst) -> bool { match inst { + MInst::FloatBinary { .. } | MInst::FloatUnary { .. } => true, MInst::Mov { .. } | MInst::X86Simd(_) | MInst::Mov32 { .. } diff --git a/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs b/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs index ce76e3107b7..9d794451cb2 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc/unified.rs @@ -369,6 +369,8 @@ fn next_use_bucket(next_use: u32) -> &'static str { fn inst_opcode(inst: &MInst) -> &'static str { match inst { + MInst::FloatBinary { .. } => "float_binary", + MInst::FloatUnary { .. } => "float_unary", MInst::X86Simd(X86SimdInst::Scratch128 { .. }) => "x86_scratch_v128", MInst::X86Simd(X86SimdInst::Zero128 { .. }) => "x86_zero_v128", MInst::X86Simd(X86SimdInst::Pack128 { .. }) => "x86_pack_v2i64", diff --git a/crates/celox-backend-x86/src/backend/native/x86_slp.rs b/crates/celox-backend-x86/src/backend/native/x86_slp.rs index ec24af8c894..7c1728aa1cc 100644 --- a/crates/celox-backend-x86/src/backend/native/x86_slp.rs +++ b/crates/celox-backend-x86/src/backend/native/x86_slp.rs @@ -870,6 +870,7 @@ fn blocks_vector_live_range(inst: &MInst, shift_encoding: VariableShiftEncoding) pub(crate) fn clobbers_xmm(inst: &MInst, register: X86PhysVec) -> bool { match inst { + MInst::FloatBinary { .. } | MInst::FloatUnary { .. } => register.0 <= 1, MInst::PackedLaneCompare { .. } => register.0 <= 5, MInst::PackedByteAffineCompare { .. } => register.0 <= 4, MInst::MemCopy { .. } => register.0 == 0, @@ -885,6 +886,50 @@ mod tests { use super::*; use crate::native::mir::{BlockId, MBlock, PhiNode, SpillDesc, VRegAllocator}; + #[test] + fn float_temporaries_do_not_clobber_live_simd_values() { + let mut scalar = VRegAllocator::new(); + let input = scalar.alloc(); + let output = scalar.alloc(); + let mut func = MFunction::new(scalar, vec![SpillDesc::transient(); 2]); + let vectors = (0..9).map(|_| func.alloc_x86_vec()).collect::>(); + let mut block = MBlock::new(BlockId(0)); + for &dst in &vectors { + block.push(MInst::X86Simd(X86SimdInst::Zero128 { dst })); + } + block.push(MInst::LoadImm { + dst: input, + value: 1.5f64.to_bits(), + }); + block.push(MInst::FloatBinary { + dst: output, + lhs: input, + rhs: input, + op: celox_sir::FloatBinaryOp::Add, + precision: celox_sir::FloatPrecision::F64, + }); + for (index, &src) in vectors.iter().enumerate() { + block.push(MInst::X86Simd(X86SimdInst::Store128 { + base: BaseReg::SimState, + offset: (index * 16) as i32, + src, + })); + } + block.push(MInst::Return); + func.blocks.push(block); + for tick_loop in [false, true] { + let allocation = allocate(&func, 0, tick_loop); + for (_, location) in allocation.assignments { + if let X86VectorLocation::Register(register) = location { + assert!(register.0 > 1, "FP clobbers must exclude XMM0/1"); + } + } + if !tick_loop { + assert!(allocation.spilled_values >= 2); + } + } + } + #[test] fn shared_adjacent_load_pair_becomes_one_vector_value() { let mut scalar = VRegAllocator::new(); diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 45e824749e0..d11a1ca6c1d 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -61,6 +61,9 @@ pub enum FrontendError { // from the source-facing hierarchy. The runtime image records their addresses. const FORCE_ENABLE: &str = "@force-enable:"; const FORCE_VALUE: &str = "@force-value:"; +/// The prefix of the variables `$event[k]` that hold the value of an event +/// expression, and of their copies of process-local operands. +const EVENT_PREFIX: &str = "$event["; #[derive(Clone)] struct SvVariable { @@ -107,9 +110,14 @@ impl SvVariable { } /// A hidden variable other than the time slot, whose value the lowered - /// code computes. The time slot is state the scheduler writes. + /// code computes. The time slot is state the scheduler writes, and an + /// event expression's variables are state its process and its + /// continuous assignment share. fn is_scratch(&self) -> bool { - self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() + self.hidden + && self.path != [TIME_SLOT] + && self.force_control.is_none() + && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -128,6 +136,9 @@ pub(crate) struct LoweredSvModule { package_variables: Vec<(SourceVarId, String, String)>, /// The hidden `(copy, signal)` event copies of [`FfEventVars`]. event_copies: Vec<(SourceVarId, SourceVarId)>, + /// The continuous assignments of the event expressions the processes + /// wait on, by their hidden target `$event[k]`. + event_assignments: Vec<(SourceVarId, Vec)>, } #[derive(Clone)] @@ -1536,6 +1547,7 @@ fn prepare_external_hierarchy_collecting( package_variables: Vec::new(), // The foreign module's own combinational blocks carry its copies. event_copies: Vec::new(), + event_assignments: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -2880,6 +2892,7 @@ fn lower_module_with_overrides( wait_sites, nba_sites, host_request_sites, + event_assignments, ) = lower_initial_processes( module, &mut variables, @@ -3007,6 +3020,7 @@ fn lower_module_with_overrides( instances, package_variables, event_copies: event_vars.copies, + event_assignments, }) } @@ -3389,6 +3403,9 @@ pub(crate) fn attach_instance_glue( .insert(*id, pm.variables[id].to_symbolic_variable()); } } + // An event expression is one more continuous assignment to a hidden + // buffer the processes watch. + port_assignments.extend(lowered.event_assignments.iter().cloned()); let (comb_blocks, arena, created, comb_observers, comb_sites) = lower_comb_processes( &lowered.source, &port_assignments, @@ -3734,19 +3751,12 @@ fn lower_initial_processes( Vec>, Vec>, Vec>, + Vec<(SourceVarId, Vec)>, ), sv::AnalyzerError, > { if module.initial_processes().is_empty() { - return Ok(( - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - )); + return Ok(Default::default()); } let mut values = Vec::new(); let mut declaration_values = Vec::new(); @@ -3814,6 +3824,7 @@ fn lower_initial_processes( Vec::new(), Vec::new(), Vec::new(), + Vec::new(), )); } @@ -3916,6 +3927,7 @@ fn lower_initial_processes( wait_sites, nba_sites, host_request_sites, + std::mem::take(&mut pm.event_assignments), )) } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index bf950285f04..860fdbc1da6 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4467,14 +4467,29 @@ impl Ff<'_, '_> { /// `@(items)` (IEEE 1800-2023 9.4.2): the process waits for an /// occurrence of any item, which the runtime detects on the watched /// signals themselves, so nothing is left to check when it resumes. + /// + /// An item other than a variable of the module is watched through the + /// variable `$event[k]` of a continuous assignment of the expression: + /// each update of its value is an occurrence, and an edge is one of the + /// least significant bit of the expression (Table 9-2). Before it + /// suspends, the process copies the process-local operands the + /// assignment reads and stores the expression's value, which the event + /// control samples as it begins. fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { let mut terms = Vec::new(); + let mut samples = Vec::new(); for item in items { - let id = match &item.expr { - sv::ir::Expr::Ident(name) => self.m.id(name).filter(|&id| !self.m.is_hidden(id)), - _ => None, - } - .ok_or_else(|| unsupported("event expression other than a variable"))?; + let expr = self.propagate(&item.expr); + let id = match &expr { + sv::ir::Expr::Ident(name) => match self.m.id(name) { + Some(id) if !self.m.is_hidden(id) => id, + Some(_) => self.event_expression(&expr, &mut samples)?, + // A constant never changes. + None if self.m.constants.contains_key(name) => continue, + None => return Err(unsupported(format!("event expression `{name}`"))), + }, + _ => self.event_expression(&expr, &mut samples)?, + }; match item.edge { sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), sv::ir::EventEdge::Pos => terms.push((id, CounterKind::Rises)), @@ -4485,6 +4500,9 @@ impl Ff<'_, '_> { } } } + for (target, value) in samples { + self.assign(&sv::ir::LValue::Ident(target), &value)?; + } let site = self.wait_site(terms); self.with_kernel(|kernel| -> Result<(), ProcessKernelError> { kernel.suspend_wait(site)?; @@ -4498,6 +4516,116 @@ impl Ff<'_, '_> { .map_err(kernel_error) } + /// The variable `$event[k]` of a new event expression `expr`, with its + /// continuous assignment added to the module. `samples` gets the + /// assignments the process makes before it suspends: the copies of the + /// process-local operands, then `$event[k]` itself. + fn event_expression( + &mut self, + expr: &sv::ir::Expr, + samples: &mut Vec<(String, sv::ir::Expr)>, + ) -> Result { + if let Some(name) = impure_call(self.m, expr) { + return Err(unsupported(format!( + "impure call `{name}` in an event expression" + ))); + } + // A real expression keeps its payload bits, so a change too small + // to survive an integer conversion still wakes the process. + let float = self.m.expr_float_precision(expr); + let width = match float { + Some(celox_sir::FloatPrecision::F64) => 64, + Some(celox_sir::FloatPrecision::F32) => 32, + None => sv_expr_natural_width( + &self.m.typed_calls(expr), + self.m.variables, + self.m.name_to_id, + self.m.constants, + self.m.parameter_types, + ) + .ok_or_else(|| unsupported("event expression of unknown width"))?, + }; + let signed = self.expr_signed(expr); + let mut names = HashSet::default(); + expr_idents(expr, &mut names); + let mut locals: Vec<_> = names + .into_iter() + .filter_map(|name| { + let id = self.m.id(&name)?; + self.m.is_hidden(id).then_some((name, id)) + }) + .collect(); + locals.sort_unstable(); + // Another call can copy a new argument into a static formal while + // the process waits, which a copy taken now would not see. + if locals.iter().any(|&(_, id)| self.is_static_task_formal(id)) { + return Err(unsupported( + "event expression reading a static task argument", + )); + } + let index = self.m.next_event_index(); + let (event, event_name) = self.m.event_variable( + index, + None, + SvVariable { + float, + path: Vec::new(), + width, + signed, + is_4state: float.is_none(), + packed_ranges: vec![(width as i128 - 1, 0)], + array_dims: Vec::new(), + unpacked_ranges: Vec::new(), + domain_kind: DomainKind::Other, + kind: VariableKind::Variable, + type_kind: if float.is_some() { + PortTypeKind::Bit + } else { + PortTypeKind::Logic + }, + source: None, + hidden: true, + force_control: None, + }, + ); + let mut renames = HashMap::default(); + for (position, (name, id)) in locals.into_iter().enumerate() { + let variable = self.m.var(id).clone(); + let (copy, copy_name) = + self.m + .event_variable(index, Some(format!("arg[{position}]")), variable); + if let Some(width) = self.element_widths.get(&stable(id)).copied() { + self.element_widths.insert(stable(copy), width); + self.element_widths.insert(working(copy), width); + } + samples.push((copy_name.clone(), sv::ir::Expr::Ident(name.clone()))); + renames.insert(name, copy_name); + } + let value = rename_idents(expr, &renames); + samples.push((event_name.clone(), value.clone())); + self.m.event_assignments.push(( + event, + vec![sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(event_name), + rhs: value, + nonblocking: false, + }], + )); + Ok(event) + } + + /// Whether `id` is a static formal of a task, which keeps one + /// module-wide address for every call. + fn is_static_task_formal(&self, id: SourceVarId) -> bool { + self.m.subroutines.values().any(|subroutine| { + subroutine.is_task + && subroutine.params.iter().any(|param| { + !subroutine.automatic_locals.contains(¶m.name) + && self.m.id(¶m.name) == Some(id) + }) + }) + } + /// `wait (condition)` (IEEE 1800-2023 9.4.3): the process goes on at once /// if the condition holds, and otherwise checks it again whenever a /// variable it reads changes. @@ -4509,16 +4637,10 @@ impl Ff<'_, '_> { // in, but hidden local storage has no observable change counters yet. // Do not compile a wait that would silently miss that wakeup, including // dependencies read indirectly by a function in the condition. - if self.m.subroutines.values().any(|subroutine| { - subroutine.is_task - && subroutine.params.iter().any(|param| { - !subroutine.automatic_locals.contains(¶m.name) - && names.iter().any(|name| { - self.m.id(name).is_some_and(|id| { - self.m.is_hidden(id) && Some(id) == self.m.id(¶m.name) - }) - }) - }) + if names.iter().any(|name| { + self.m + .id(name) + .is_some_and(|id| self.m.is_hidden(id) && self.is_static_task_formal(id)) }) { return Err(unsupported("wait condition reading a static task argument")); } @@ -4669,6 +4791,226 @@ fn subroutine_reads(pm: &ProcModule<'_>, expr: &sv::ir::Expr, names: &mut HashSe } } +/// The name of a call in `expr` that has an effect or reads the state of the +/// simulation, directly or through the functions it calls: an event +/// expression must be a value of the variables it reads. +fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { + let mut pending = vec![expr.clone()]; + let mut visited = HashSet::default(); + while let Some(expr) = pending.pop() { + let callees = std::cell::RefCell::new(Vec::new()); + expr_calls(&expr, &|callee| { + callees.borrow_mut().push(callee.clone()); + false + }); + for callee in callees.into_inner() { + let name = match callee { + sv::ir::Callee::System(function) => { + if function.reads_simulation_state() { + return Some(function.name().to_string()); + } + continue; + } + sv::ir::Callee::Subroutine(name) => name, + }; + if !visited.insert(name.clone()) { + continue; + } + if let Some(import) = pm.dpi_imports.get(&name) { + if !import.is_pure() { + return Some(name); + } + continue; + } + let Some(subroutine) = pm.subroutine(&name) else { + return Some(name); + }; + if subroutine.is_task + || subroutine + .params + .iter() + .any(|param| param.direction.is_written()) + { + return Some(name); + } + pending.extend( + subroutine + .params + .iter() + .filter_map(|param| param.default.clone()), + ); + // Only the function's own variables may be written. + let local = + |lvalue: &sv::ir::LValue| pm.id(lvalue.name()).is_some_and(|id| pm.is_hidden(id)); + let mut effect = false; + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { lhs, .. } => effect |= !local(lhs), + sv::ir::Stmt::AssignConcat { parts, .. } => effect |= !parts.iter().all(local), + sv::ir::Stmt::Call { + name, + args, + arg_order, + } => pending.push(sv::ir::Expr::Call { + callee: sv::ir::Callee::Subroutine(name.clone()), + args: args.clone(), + arg_order: arg_order.clone(), + }), + sv::ir::Stmt::SystemTask { .. } + | sv::ir::Stmt::Delay { .. } + | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::Wait(_) => effect = true, + _ => {} + }); + stmt.clone().visit_mut( + &mut |expr| pending.push(expr.clone()), + &mut |_| {}, + &mut |_| {}, + ); + } + if effect { + return Some(name); + } + } + } + None +} + +/// `expr` with the identifiers in `renames` replaced. +fn rename_idents(expr: &sv::ir::Expr, renames: &HashMap) -> sv::ir::Expr { + fn constant(expr: &sv::ir::ConstExpr, renames: &HashMap) -> sv::ir::ConstExpr { + use sv::ir::ConstExpr; + let go = |expr: &ConstExpr| Box::new(constant(expr, renames)); + match expr { + ConstExpr::Ident(name) => ConstExpr::Ident(renames.get(name).unwrap_or(name).clone()), + ConstExpr::Literal(_) => expr.clone(), + ConstExpr::SelectRange { + expr, + msb, + lsb, + signed, + } => ConstExpr::SelectRange { + expr: go(expr), + msb: go(msb), + lsb: go(lsb), + signed: *signed, + }, + ConstExpr::Select { expr, bit } => ConstExpr::Select { + expr: go(expr), + bit: go(bit), + }, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), + site: *site, + args: args.iter().map(|arg| constant(arg, renames)).collect(), + }, + ConstExpr::Resize { + expr, + width, + signed, + } => ConstExpr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + ConstExpr::Unary { op, expr } => ConstExpr::Unary { + op: *op, + expr: go(expr), + }, + ConstExpr::Binary { left, op, right } => ConstExpr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => ConstExpr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, + } + } + use sv::ir::Expr; + let go = |expr: &Expr| Box::new(rename_idents(expr, renames)); + match expr { + Expr::Ident(name) => Expr::Ident(renames.get(name).unwrap_or(name).clone()), + Expr::Literal(_) => expr.clone(), + Expr::Select { + expr, + msb, + lsb, + signed, + } => Expr::Select { + expr: go(expr), + msb: constant(msb, renames), + lsb: constant(lsb, renames), + signed: *signed, + }, + Expr::Concat(parts) => Expr::Concat( + parts + .iter() + .map(|part| rename_idents(part, renames)) + .collect(), + ), + Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { + count: constant(count, renames), + parts: parts + .iter() + .map(|part| rename_idents(part, renames)) + .collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + Expr::Unary { op, expr } => Expr::Unary { + op: *op, + expr: go(expr), + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + callee: callee.clone(), + args: args + .iter() + .map(|arg| arg.as_ref().map(|arg| rename_idents(arg, renames))) + .collect(), + arg_order: arg_order.clone(), + }, + Expr::Inside { expr, items } => Expr::Inside { + expr: go(expr), + items: items + .iter() + .map(|item| item.map(&mut |operand| rename_idents(operand, renames))) + .collect(), + }, + } +} + /// The names of the user subroutines `expr` calls. fn collect_call_names(expr: &sv::ir::Expr, names: &mut Vec) { let called = std::cell::RefCell::new(Vec::new()); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index f491b0efeba..68eec7b2149 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -43,6 +43,9 @@ pub(super) struct ProcModule<'a> { pub runtime_event_sites: Vec, /// Runtime errors (fatal assertions) of the module, by local code. pub runtime_errors: HashMap>, + /// The continuous assignments `$event[k] = expr` of the event + /// expressions the module's processes wait on, by target. + pub event_assignments: Vec<(SourceVarId, Vec)>, /// The declared bounds of each unpacked dimension, by variable. unpacked_bounds: HashMap>, /// Where the warnings found while lowering go. A process lowered more @@ -190,6 +193,7 @@ impl<'a> ProcModule<'a> { capture_counter: 0, runtime_event_sites: Vec::new(), runtime_errors: HashMap::default(), + event_assignments: Vec::new(), unpacked_bounds, warnings, } @@ -728,6 +732,47 @@ impl<'a> ProcModule<'a> { id } + /// A module-scope variable of event expression `index` with the shape + /// of `variable`: `$event[index]` itself for `slot == None`, otherwise + /// its copy `$event[index].slot`. Like a process slot it is no signal of + /// the design, but state that persists while processes wait. + pub fn event_variable( + &mut self, + index: usize, + slot: Option, + variable: SvVariable, + ) -> (SourceVarId, String) { + let path: Vec<_> = std::iter::once(format!("{EVENT_PREFIX}{index}]")) + .chain(slot) + .collect(); + let name = path.join("."); + let id = next_var_id(&mut self.next_id); + self.variables.insert( + id, + SvVariable { + path, + domain_kind: DomainKind::Other, + kind: VariableKind::Variable, + source: None, + hidden: true, + force_control: None, + ..variable + }, + ); + self.name_to_id.insert(name.clone(), id); + (id, name) + } + + /// The index of the next event expression of the module. + pub fn next_event_index(&self) -> usize { + (0..) + .take_while(|index| { + self.name_to_id + .contains_key(&format!("{EVENT_PREFIX}{index}]")) + }) + .count() + } + pub fn subroutine(&self, name: &str) -> Option<&sv::ir::Subroutine> { self.subroutines.get(name) } @@ -840,7 +885,7 @@ impl<'a> ProcModule<'a> { /// `expr` with each user function call replaced by a literal of its /// return type. - fn typed_calls(&self, expr: &sv::ir::Expr) -> sv::ir::Expr { + pub fn typed_calls(&self, expr: &sv::ir::Expr) -> sv::ir::Expr { use sv::ir::Expr; let go = |expr: &Expr| self.typed_calls(expr); match expr { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index c546db6d4e5..9f4de8c4bac 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -53,6 +53,13 @@ enum Job { loops: Vec<(String, i128, i128)>, start: usize, }, + /// The end of the statement an `@*` controls, which starts at `start` + /// of the output; `sensitivity` is where its constant-folded branches + /// start in the builder's sensitivity body. + ImplicitEvent { + start: usize, + sensitivity: usize, + }, AssertionThen { condition: Expr, keyword: String, @@ -211,8 +218,15 @@ impl BodyBuilder<'_, '_, '_> { jobs.push(Job::Enter(*body)); } StatementKind::Timing { control, body } => { - let timing = self.native_timing_control(*control)?; - output.push(timing); + if self.implicit_event_control(*control)? { + jobs.push(Job::ImplicitEvent { + start: output.len(), + sensitivity: self.sensitivity_body.len(), + }); + } else { + let timing = self.native_timing_control(*control)?; + output.push(timing); + } jobs.push(Job::Enter(*body)); } // Explicit typed assignments/calls/assertions/unsupported @@ -243,6 +257,13 @@ impl BodyBuilder<'_, '_, '_> { _ => output.extend(self.native_statement_leaf(&native.statement(id).kind)?), }, Job::EndScope => self.pop_scope(), + Job::ImplicitEvent { start, sensitivity } => { + let wait = timing::implicit_event( + &output[start..], + &self.sensitivity_body[sensitivity..], + ); + output.insert(start, wait); + } Job::AssertionThen { condition, keyword, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index 949d5cf551b..70494ce65d2 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -50,12 +50,30 @@ impl BodyBuilder<'_, '_, '_> { Ok(Stmt::WaitEvent(result)) } EventControl::Named(_) => Err(unsupported("named event")), - EventControl::Wildcard => Err(unsupported("`@*` event control in a process")), + // The statement it controls gives its event expression. + EventControl::Wildcard => Err(crate::ast::timing::disagreement()), } } } } + /// Whether `id` is `@*` (or `@(*)`), whose event expression the + /// statement it controls determines (see [`implicit_event`]). + pub(super) fn implicit_event_control( + &self, + id: TimingControlId, + ) -> Result { + let control = self.tree.declarations().timing_control(id); + if !matches!( + control.kind, + TimingControlKind::Event(EventControl::Wildcard) + ) { + return Ok(false); + } + self.allow_timing("event control")?; + Ok(true) + } + fn native_delay(&self, mut value: ExprId, parenthesized: bool) -> Result { let native = self.tree.declarations(); if parenthesized { @@ -105,3 +123,169 @@ impl BodyBuilder<'_, '_, '_> { } } } + +/// The wait of an `@*` that controls the statement lowered to `body`, with +/// the branches constant folding removed from it in `removed`: an event of +/// any change of each variable the statement reads (IEEE 1800-2023 +/// 9.4.2.2). That is every identifier in an expression, a subroutine +/// argument or a left-hand-side index, but not in a timing control (a +/// delay, wait or event control) and not an assignment target itself. Names that turn out not to +/// denote a variable, such as parameters, never change. +pub(super) fn implicit_event(body: &[Stmt], removed: &[Stmt]) -> Stmt { + fn constant(expr: &ConstExpr, names: &mut Vec) { + match expr { + ConstExpr::Ident(name) => push(name, names), + ConstExpr::Literal(_) => {} + ConstExpr::Select { expr, bit } => { + constant(expr, names); + constant(bit, names); + } + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + constant(expr, names); + constant(msb, names); + constant(lsb, names); + } + ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => constant(expr, names), + ConstExpr::Function { args, .. } => args.iter().for_each(|arg| constant(arg, names)), + ConstExpr::Binary { left, right, .. } => { + constant(left, names); + constant(right, names); + } + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => { + constant(condition, names); + constant(then_expr, names); + constant(else_expr, names); + } + } + } + fn expression(expr: &Expr, names: &mut Vec) { + match expr { + Expr::Ident(name) => push(name, names), + Expr::Literal(_) => {} + Expr::Select { expr, msb, lsb, .. } => { + expression(expr, names); + constant(msb, names); + constant(lsb, names); + } + Expr::Concat(parts) => parts.iter().for_each(|part| expression(part, names)), + Expr::RepeatConcat { count, parts } => { + constant(count, names); + parts.iter().for_each(|part| expression(part, names)); + } + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => expression(expr, names), + Expr::Binary { left, right, .. } => { + expression(left, names); + expression(right, names); + } + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + expression(condition, names); + expression(then_expr, names); + expression(else_expr, names); + } + // A function's own reads are not part of the event expression. + Expr::Call { args, .. } => args.iter().flatten().for_each(|arg| expression(arg, names)), + Expr::Inside { expr, items } => { + expression(expr, names); + for item in items { + item.exprs() + .into_iter() + .for_each(|operand| expression(operand, names)); + } + } + } + } + fn target(lvalue: &LValue, names: &mut Vec) { + if let LValue::Select { + msb, + lsb, + array_slice_width, + .. + } = lvalue + { + constant(msb, names); + constant(lsb, names); + if let Some(width) = array_slice_width { + constant(width, names); + } + } + } + fn push(name: &str, names: &mut Vec) { + if !names.iter().any(|known| known == name) { + names.push(name.to_string()); + } + } + let mut names = Vec::new(); + for stmt in body.iter().chain(removed) { + stmt.walk(&mut |stmt| match stmt { + Stmt::Assign { lhs, rhs, .. } => { + target(lhs, &mut names); + expression(rhs, &mut names); + } + Stmt::AssignConcat { parts, rhs, .. } => { + parts.iter().for_each(|part| target(part, &mut names)); + expression(rhs, &mut names); + } + Stmt::If { condition, .. } => expression(condition, &mut names), + Stmt::Case { + selector, items, .. + } => { + expression(selector, &mut names); + for label in items.iter().flat_map(|item| &item.labels) { + match label { + CaseLabel::Value(value) => expression(value, &mut names), + CaseLabel::Range { low, high } => { + expression(low, &mut names); + expression(high, &mut names); + } + } + } + } + Stmt::Loop { + kind, condition, .. + } => { + if let LoopKind::Repeat(count) = kind { + expression(count, &mut names); + } + if let Some(condition) = condition { + expression(condition, &mut names); + } + } + Stmt::Return(value) => value.iter().for_each(|value| expression(value, &mut names)), + Stmt::Call { args, .. } => args + .iter() + .flatten() + .for_each(|arg| expression(arg, &mut names)), + Stmt::Eval(expr) => expression(expr, &mut names), + Stmt::SystemTask { args, .. } => { + for arg in args { + if let SystemTaskArg::Expr(expr) = arg { + expression(expr, &mut names); + } + } + } + Stmt::Local { init, .. } => init.iter().for_each(|init| expression(init, &mut names)), + Stmt::Break + | Stmt::Continue + | Stmt::Delay { .. } + | Stmt::WaitEvent(_) + | Stmt::Wait(_) => {} + }); + } + Stmt::WaitEvent( + names + .into_iter() + .map(|name| EventItemBase { + edge: EventEdge::Any, + expr: Expr::Ident(name), + }) + .collect(), + ) +} diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs index 8e46fa7574d..4b10b9bf4e1 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs @@ -115,7 +115,6 @@ fn native_timing_event_membership_and_delay_roles_are_authoritative() { fn native_timing_preserves_existing_restrictions_including_ff_iff_validation() { for (body, diagnostic) in [ ("initial @(a iff en) q=1;", "iff-qualified event"), - ("initial @* q=1;", "`@*` event control"), ("always_comb #1 q=d;", "delay control"), ("always_ff @(edge clk) q<=d;", "always_ff event expression"), ( diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 5ee22548d72..7f81f933cb9 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3510,10 +3510,6 @@ fn rejects_unimplemented_timing_constructs() { ), ("initial begin : b disable b; end", "disable statement"), ("initial #1.5;", "delay value"), - ( - "logic a; initial @* a = 1;", - "`@*` event control in a process", - ), ( "logic a, y; always_latch y <= a;", "nonblocking assignment inside always_latch", @@ -3590,6 +3586,36 @@ fn analyzes_timing_controls_in_initial_blocks() { analyze_source(code, Path::new("timing.sv")).expect("timing controls in an initial block"); } +/// `@*` in a process waits on the variables its statement reads (IEEE +/// 1800-2023 9.4.2.2): right-hand sides, conditions, arguments and +/// left-hand-side indices, but not assignment targets or timing controls. +#[test] +fn implicit_event_controls_wait_on_the_reads_of_their_statement() { + let code = "module Top(input logic [7:0] a, b, c, d, i, output logic [7:0] y, z);\n\ + initial forever @* begin if (c > 0) y = a; else y = b; z[i] = 1; @(d); #(d); end\n\ + endmodule"; + let ir = analyze_source(code, Path::new("implicit.sv")).expect("`@*` in a process"); + let mut waits = Vec::new(); + for process in ir.modules()[0].initial_processes() { + for stmt in process.body() { + stmt.walk(&mut |stmt| { + if let ir::Stmt::WaitEvent(items) = stmt { + waits.push( + items + .iter() + .map(|item| match &item.expr { + ir::Expr::Ident(name) => name.clone(), + expr => panic!("unexpected event expression {expr:?}"), + }) + .collect::>(), + ); + } + }); + } + } + assert_eq!(waits, [vec!["c", "a", "b", "i"], vec!["d"]]); +} + #[test] fn analyzes_veryl_emitted_fifo_with_runtime_casts() { analyze_source( diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index efa5278592b..20c306de17f 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -426,6 +426,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | Group | Stage | Tool | Cases | Reason | | --- | --- | --- | ---: | --- | | `sv_icarus_automatic_task_arrays` | execute | icarus | 1 | Icarus 13.0 shares an automatic task's unpacked local array across overlapping calls. IEEE 1800-2023 13.3.1–13.3.2 require separate storage for each activation. The [pre-exclusion result](verification/repros/sv_timed_task_arrays_icarus.json) retains the first call returning 31 instead of 11. The scalar activation case remains enabled for Icarus. | +| `sv_icarus_expression_event_sample` | execute | icarus | 1 | Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (`a = 1; @(a ^ b);`). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression, and the write came before the event control. Verilator 5.052 agrees with the expected value. The [pre-exclusion result](verification/repros/sv_expression_event_sample_icarus.json) is retained. | +| `sv_verilator_implicit_event_in_process` | compile | verilator | 1 | Verilator 5.052 rejects `@*` in an `initial forever` ("Unsupported: Event control with implicit sensitivity (@*) in this context"); IEEE 1800-2023 9.4.2.2 permits it in any procedural timing control. Icarus 13.0 passes the case. The [pre-exclusion diagnostic](verification/repros/sv_implicit_event_in_process_verilator.json) is retained. | | `sv_icarus_genvar_dimensions` | execute | icarus | 1 | Icarus 13.0 returns 0 for `$dimensions` of a generated loop index's implicit integer localparam; IEEE 1800-2023 27.4 and 20.7 require one packed dimension. Celox and Verilator pass the unchanged assertions. The [standalone reproducer and pre-exclusion result](verification/repros/sv_genvar_dimensions.json) retain the observed disagreement. | | `sv_icarus_constant_array_queries` | compile | icarus | 1 | Icarus 13.0 rejects array queries of variables in constant expressions and typedef operands; IEEE 1800-2023 20.7 permits them. Verilator passes. | | `sv_icarus_runtime_array_queries` | execute | icarus | 1 | Icarus 13.0 aborts on a runtime dimension argument. A standalone reproducer also rejects an integer variable as the dimension. IEEE 1800-2023 20.7 permits querying fixed-size dimensions with runtime expressions. | diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 0d8d2319726..c6c9106baca 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1056,3 +1056,161 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (top Top) (run_to_finish) (assert_eq count 8)) + +(case expression_events_see_pulses_within_a_time_slot + ; IEEE 1800-2023 9.4.2: each change of the expression's value is an + ; event, also one the slot undoes before it ends. The waits begin after + ; time 0, where Icarus 13.0 reports an event of a new expression. + (source "expression_pulse.sv" #" + module Top(output bit [7:0] count, output bit hit); + bit a, b; + initial begin #1; forever begin @(a ^ b); count = count + 8'd1; end end + initial begin #1; @(a ^ b); hit = 1; end + initial begin #2; a = 1; #0; a = 0; #1; b = 1; a = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 0) + (run_until 2) + (assert_eq count 2 "the expression rose and fell at time 2") + (assert_eq hit 1) + (run_until 3) + (assert_eq count 2 "a and b changed together, so a ^ b did not change")) + +(case real_expression_events_see_fractional_changes + ; IEEE 1800-2023 9.4.2: a change of a real expression's value is an + ; event, also one that converting the value to an integer would lose. + (source "real_expression_event.sv" #" + module Top(output bit [7:0] count); + real r; + initial begin #1; forever begin @(r * 2.0); count = count + 8'd1; end end + initial begin #2; r = 0.125; #1; r = 0.25; #1; r = 0.25; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 0) + (run_until 3) + (assert_eq count 2 "r * 2.0 went to 0.25 and then to 0.5") + (run_until 4) + (assert_eq count 2 "writing the same value is no change")) + +(case bit_select_edges_follow_the_selected_bit + ; Table 9-2 judges an edge on the least significant bit of the + ; expression: of `v[3]`, not of `v`. + (source "bit_select_edge.sv" #" + module Top(output bit [7:0] selected, whole); + bit [3:0] v; + initial forever begin @(posedge v[3]); selected = selected + 8'd1; end + initial forever begin @(posedge v); whole = whole + 8'd1; end + initial begin #1; v = 4'b1000; #1; v = 4'b0000; #1; v = 4'b1000; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq selected 1) + (assert_eq whole 0) + (run_until 3) + (assert_eq selected 2) + (assert_eq whole 0)) + +(case part_select_events_see_pulses_of_the_selected_bits + (source "part_select_pulse.sv" #" + module Top(output bit [7:0] count); + bit [3:0] v; + initial forever begin @(v[2:1]); count = count + 8'd1; end + initial begin #1; v[1] = 1; #0; v[1] = 0; #1; v[3] = 1; v[0] = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 2 "v[2:1] went to 1 and back") + (run_until 2) + (assert_eq count 2 "bits outside the select are no events")) + +(case variable_index_events_follow_the_index + ; The value of `q[i]` changes when the index does, too. + (source "variable_index_event.sv" #" + module Top(output bit [7:0] count); + bit [3:0] q; + bit [1:0] i; + initial forever begin @(q[i]); count = count + 8'd1; end + initial begin #1; q[0] = 1; #1; i = 1; #1; q[0] = 0; #1; q[1] = 1; #1; i = 2; end + endmodule + "#) + (top Top) + (run_until 1) (assert_eq count 1) + (run_until 2) (assert_eq count 2 "q[1] differs from q[0]") + (run_until 3) (assert_eq count 2 "q[0] is not selected") + (run_until 4) (assert_eq count 3) + (run_until 5) (assert_eq count 4)) + +(case pure_function_events_change_with_the_result + (source "function_event.sv" #" + module Top(output bit [7:0] count); + bit [3:0] v; + function automatic bit [1:0] middle(bit [3:0] x); + return x[2:1]; + endfunction + initial begin #1; forever begin @(middle(v)); count = count + 8'd1; end end + initial begin #2; v = 4'b0010; #1; v = 4'b1011; #1; v = 4'b1101; end + endmodule + "#) + (top Top) + (run_until 2) (assert_eq count 1) + (run_until 3) (assert_eq count 1 "the result stayed 1") + (run_until 4) (assert_eq count 2)) + +(case event_expressions_read_automatic_task_locals + ; Each call waits on `q[i]` with its own `i`, sampled when the event + ; control begins: the second call does not wake because `q[1]` differs + ; from the `q[0]` the first one waited on. + (source "task_local_event.sv" #" + module Top(output int first, second); + bit [3:0] q; + task automatic await(input int i, output int at); + @(q[i]); + at = $time; + endtask + initial begin #2; await(0, first); await(1, second); end + initial begin #3; q[0] = 1; #3; q[1] = 1; end + endmodule + "#) + (top Top) + (run_until 3) (assert_eq first 3) (assert_eq second 0) + (run_until 5) (assert_eq second 0) + (run_until 6) (assert_eq second 6)) + +(case event_controls_sample_the_expression_when_they_begin + ; IEEE 1800-2023 9.4.2: the process's own write before the event + ; control is no event of it. + (source "event_sample.sv" #" + module Top(output bit hit); + bit a, b; + initial begin #1; a = 1; @(a ^ b); hit = 1; end + initial begin #2; b = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq hit 0) + (run_until 2) + (assert_eq hit 1)) + +(case implicit_event_controls_in_processes_wait_on_their_reads + ; IEEE 1800-2023 9.4.2.2: `@*` waits on the variables the statement it + ; controls reads, not on those it writes. + (source "implicit_event.sv" #" + module Top(output bit [7:0] y, z, count); + bit [7:0] a, b; + initial forever @* begin y = a + b; count = count + 8'd1; end + always @* begin #1; z = a; end + initial begin #2; a = 3; #2; b = 4; end + endmodule + "#) + (top Top) + (run_until 1) (assert_eq count 0) (assert_eq y 0) + (run_until 2) (assert_eq count 1) (assert_eq y 3) + (run_until 3) (assert_eq z 3) + (run_until 4) (assert_eq count 2) (assert_eq y 7) (assert_eq z 3)) diff --git a/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json b/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json new file mode 100644 index 00000000000..4032154b841 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json @@ -0,0 +1,34 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "timing::event_controls_sample_the_expression_when_they_begin at 1179:3: assert_eq hit: expected 0x0, got 0x1", + "expectation": "Simulation", + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "mismatch": 1, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "note": "Focused failure before the exclusion. The design writes a = 1 and then waits on @(a ^ b); Icarus 13.0 wakes the process at that time, Verilator 5.052 does not. IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression, and the change of a happened before the event control executed. A standalone probe also wakes in Icarus, and a new event expression reports an event at time 0 there." +} diff --git a/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json b/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json new file mode 100644 index 00000000000..e9d9e676a8f --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json @@ -0,0 +1,34 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /source_0.sv:4:23: Unsupported: Event control with implicit sensitivity (@*) in this context; use an explicit sensitivity list instead\n 4 | initial forever @* begin y = a + b; count = count + 8'd1; end\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Warning-ZERODLY: /testbench.sv:73:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 73 | if (t1 > $time) #(t1 - $time);\n | ^\n ... For warning description see https://verilator.org/warn/ZERODLY?v=5.052\n ... Use \"/* verilator lint_off ZERODLY */\" and lint_on around source to disable this message.\n%Warning-ZERODLY: /testbench.sv:114:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 114 | if (t2 > $time) #(t2 - $time);\n | ^\n%Warning-ZERODLY: /testbench.sv:155:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 155 | if (t3 > $time) #(t3 - $time);\n | ^\n%Warning-ZERODLY: /testbench.sv:185:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 185 | if (t4 > $time) #(t4 - $time);\n | ^\n%Warning-INFINITELOOP: /source_0.sv:4:15: Infinite loop (condition always true)\n 4 | initial forever @* begin y = a + b; count = count + 8'd1; end\n | ^~~~~~~\n ... For warning description see https://verilator.org/warn/INFINITELOOP?v=5.052\n ... Use \"/* verilator lint_off INFINITELOOP */\" and lint_on around source to disable this message.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "compile_error": 1, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "note": "Focused failure before the exclusion. Verilator 5.052 rejects @* in an initial forever. A standalone always @* whose body has a delay compiles but does not terminate in Verilator, so the case cannot avoid the construct. Icarus 13.0 passes the case." +} diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index c6d6d4d721b..df08045c942 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::bit_select_edges_follow_the_selected_bit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -44,6 +55,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -242,6 +264,62 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_wake_on_rising_and_falling_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_expression_event_sample_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_expression_event_sample", + "observed_version": "Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "upstream": [] + }, + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_expressions_read_automatic_task_locals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::expression_events_see_pulses_within_a_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -319,6 +397,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -352,6 +441,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::long_process_loops_finish_within_one_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::min_typ_max_delays_wait_the_typical_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -385,6 +496,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_assignments_in_processes_update_in_the_nba_region", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -407,6 +529,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::part_select_events_see_pulses_of_the_selected_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -429,6 +562,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::pure_function_events_change_with_the_result", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -440,6 +584,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::real_expression_events_see_fractional_changes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -539,6 +694,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_actuals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_subroutines", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_functions_report_the_time_in_the_caller_unit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_literal_delays_accept_all_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Icarus 13.0 shares an unpacked local array across overlapping calls of an automatic task, including with an explicit automatic declaration. IEEE 1800-2023 13.3.1 and 13.3.2 require separate storage for each activation. The first call returns 31 instead of 11 after the second call overwrites its array; scalar task locals remain independent.", @@ -562,6 +761,61 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_scalar_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_four_state_storage_survives_suspension", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_in_edge_always_rearms_after_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_nested_copyback_wait_and_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_static_formals_remain_shared", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -595,6 +849,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_index_events_follow_the_index", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 0023e7b62c5..49ce5c92e65 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1492,6 +1492,40 @@ ] } }, + { + "id": "sv_icarus_expression_event_sample", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "upstream": [], + "evidence": [ + "verification/repros/sv_expression_event_sample_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::event_controls_sample_the_expression_when_they_begin" + ] + } + }, + { + "id": "sv_verilator_implicit_event_in_process", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_implicit_event_in_process_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::implicit_event_controls_in_processes_wait_on_their_reads" + ] + } + }, { "id": "sv_verilator_dist_uniform_seed_width", "category": "simulator_compile_limitation", diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index cb48ee4a4a3..6058dfc509d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::bit_select_edges_follow_the_selected_bit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -44,6 +55,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -242,6 +264,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_wake_on_rising_and_falling_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_expressions_read_automatic_task_locals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::expression_events_see_pulses_within_a_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -319,6 +385,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_implicit_event_in_process_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_implicit_event_in_process", + "observed_version": "Verilator 5.052", + "phase": "compile", + "reason": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "upstream": [] + }, + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -352,6 +441,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::long_process_loops_finish_within_one_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::min_typ_max_delays_wait_the_typical_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -385,6 +496,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_assignments_in_processes_update_in_the_nba_region", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -407,6 +529,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::part_select_events_see_pulses_of_the_selected_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -429,6 +562,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::pure_function_events_change_with_the_result", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -440,6 +584,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::real_expression_events_see_fractional_changes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -539,6 +694,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_actuals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_subroutines", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Verilator 5.052 evaluates an always_comb that reads $time again when the clocking event of the suite testbench fires, although no variable it reads has changed: at 3 ns y is 3 instead of 0. IEEE 1800-2023 9.2.2.2.1 makes always_comb sensitive to the variables it reads, and $time (20.3.1) is none. A standalone probe prints y=0 in Icarus 13.0 and Verilator without a clocking block, and y=3 in Verilator with one.", @@ -562,6 +739,83 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_literal_delays_accept_all_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_scalar_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::timed_task_four_state_storage_survives_suspension", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_in_edge_always_rearms_after_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_nested_copyback_wait_and_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_static_formals_remain_shared", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "four-state expectations", @@ -595,6 +849,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_index_events_follow_the_index", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 957479e3b3f..2e76af89cd5 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -85,37 +85,23 @@ timed_cases! { fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; fn inactive_time_directives_do_not_change_scheduler_units = "timing::inactive_time_directives_do_not_change_scheduler_units"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_concatenation_publishes_one_event_update = "timing::blocking_concatenation_publishes_one_event_update"; fn finite_active_feedback_preserves_convergence = "timing::finite_active_feedback_preserves_convergence"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn pure_function_rhs_preserves_distinct_write_times = "timing::pure_function_rhs_preserves_distinct_write_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn conditional_writes_preserve_distinct_activation_times = "timing::conditional_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn case_writes_preserve_distinct_activation_times = "timing::case_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_repeat_writes_preserve_distinct_activation_times = "timing::constant_repeat_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn separate_comb_assignments_preserve_selected_dependencies = "timing::separate_comb_assignments_preserve_selected_dependencies"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_for_writes_preserve_distinct_activation_times = "timing::constant_for_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_tasks_preserve_distinct_activation_times = "timing::untimed_tasks_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_task_copyback_preserves_distinct_activation_times = "timing::untimed_task_copyback_preserves_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn statically_satisfied_waits_preserve_distinct_activation_times = "timing::statically_satisfied_waits_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn nba_woken_waiters_sample_before_continuations = "timing::nba_woken_waiters_sample_before_continuations"; fn negative_repeat_counts_do_not_run_the_body = "timing::negative_repeat_counts_do_not_run_the_body"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_ff_woken_waiters_sample_before_continuations = "timing::blocking_ff_woken_waiters_sample_before_continuations"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn direct_blocking_ff_woken_waiters_sample_before_continuations = "timing::direct_blocking_ff_woken_waiters_sample_before_continuations"; fn constant_variable_initializers_do_not_invent_clock_edges = "timing::constant_variable_initializers_do_not_invent_clock_edges"; fn repeated_active_edges_share_one_nba_batch = "timing::repeated_active_edges_share_one_nba_batch"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn false_wait_preserves_separate_hierarchical_write_times = "timing::false_wait_preserves_separate_hierarchical_write_times"; fn always_timed_task_without_inline_timing_executes = "timing::always_timed_task_without_inline_timing_executes"; fn constant_comb_if_discards_unreachable_pulse_branch = "timing::constant_comb_if_discards_unreachable_pulse_branch"; @@ -133,6 +119,15 @@ timed_cases! { fn long_process_loops_finish_within_one_time_slot = "timing::long_process_loops_finish_within_one_time_slot"; fn initial_blocks_run_at_time_zero = "timing::initial_blocks_run_at_time_zero"; fn host_edges_after_time_zero_clock_flip_flops = "timing::host_edges_after_time_zero_clock_flip_flops"; + fn expression_events_see_pulses_within_a_time_slot = "timing::expression_events_see_pulses_within_a_time_slot"; + fn real_expression_events_see_fractional_changes = "timing::real_expression_events_see_fractional_changes"; + fn bit_select_edges_follow_the_selected_bit = "timing::bit_select_edges_follow_the_selected_bit"; + fn part_select_events_see_pulses_of_the_selected_bits = "timing::part_select_events_see_pulses_of_the_selected_bits"; + fn variable_index_events_follow_the_index = "timing::variable_index_events_follow_the_index"; + fn pure_function_events_change_with_the_result = "timing::pure_function_events_change_with_the_result"; + fn event_expressions_read_automatic_task_locals = "timing::event_expressions_read_automatic_task_locals"; + fn event_controls_sample_the_expression_when_they_begin = "timing::event_controls_sample_the_expression_when_they_begin"; + fn implicit_event_controls_in_processes_wait_on_their_reads = "timing::implicit_event_controls_in_processes_wait_on_their_reads"; } #[test] @@ -223,3 +218,115 @@ fn time_literal_delays_round_at_scope_precision() { sim.run_until(2800).unwrap(); assert_eq!(sim.get(coarse), 1u8.into()); } + +/// The variables of an event expression, `$event[k]` and its copies of +/// process-local operands, are state like the process slots: a state file +/// keeps them, while the signal listing and the waveform leave them out. +#[test] +fn event_expression_variables_are_hidden_state() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("events.vcd"); + let design = |dump: &str| { + format!( + r#" + module Top(output bit [7:0] count); + bit a; + task automatic await(input bit i); @(a ^ i); endtask + {dump} + initial forever begin await(1); count = count + 8'd1; end + initial begin #1; a = 1; end + endmodule + "# + ) + }; + let traced = design(&format!( + r#"initial begin $dumpfile("{}"); $dumpvars(0, Top); end"#, + path.display() + )); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(traced.as_str(), std::path::Path::new("events.sv"))], + "Top", + ) + .build() + .unwrap(); + simulation.run_until(2000).unwrap(); + assert_eq!(simulation.get(simulation.signal("count")), 1u8.into()); + simulation.flush_vcd().unwrap(); + let waveform = std::fs::read_to_string(&path).unwrap(); + assert!(waveform.contains(" count $end"), "{waveform}"); + assert!(!waveform.contains("$event"), "{waveform}"); + + let plain = design(""); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(plain.as_str(), std::path::Path::new("events.sv"))], + "Top", + ) + .build() + .unwrap(); + simulation.run_until(2000).unwrap(); + assert!( + simulation + .named_signals() + .iter() + .all(|signal| !signal.name.starts_with('$')), + "{:?}", + simulation + .named_signals() + .iter() + .map(|signal| &signal.name) + .collect::>() + ); + let state = simulation.save_state().unwrap(); + // A store of the process does not make the variable a counted signal. + assert!( + !state + .objects + .iter() + .any(|object| object.path.starts_with("$counter[$event")), + "{:?}", + state.objects + ); + for name in ["$event[0]", "$event[0].arg[0]", "$initial[0].status"] { + assert!( + state + .objects + .iter() + .any(|object| object.path == name && object.role == celox::StateRole::State), + "{name}: {:?}", + state.objects + ); + } +} + +#[test] +fn event_expressions_with_effects_are_rejected() { + for (event, construct) in [ + ( + "count_up(a)", + "impure call `count_up` in an event expression", + ), + ("$time", "impure call `$time` in an event expression"), + ("a ^ x", "event expression reading a static task argument"), + ] { + let source = format!( + r#" + module Top; + bit a; + int calls; + function automatic bit count_up(input bit v); calls++; return v; endfunction + task t(input bit x); @({event}); endtask + initial t(0); + endmodule + "# + ); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("effects.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("`@({event})` must be rejected")) + .to_string(); + assert!(error.contains(construct), "{event}: {error}"); + } +} diff --git a/crates/celox/tests/native_mir.rs b/crates/celox/tests/native_mir.rs index 989e8cbf515..85664ec41d3 100644 --- a/crates/celox/tests/native_mir.rs +++ b/crates/celox/tests/native_mir.rs @@ -159,3 +159,77 @@ fn trace_contains_the_exact_fused_native_pipeline() { "trace must not independently re-lower source execution units" ); } + +/// FP ports keep the test free of integer-conversion helpers: the complete +/// frontend -> optimized SIR -> MIR path must preserve numeric FP operations. +#[test] +fn scalar_float_arithmetic_stays_explicit_in_mir() { + for (ty, precision) in [("f32", "F32"), ("f64", "F64")] { + for optimize in [false, true] { + let source = format!( + r#"module Top(a: input {ty}, b: input {ty}, + y_add: output {ty}, y_sub: output {ty}, + y_mul: output {ty}, y_div: output {ty}, + y_neg: output {ty}, y_lt: output bit, y_ne: output bit) {{ + assign y_add = a + b; + assign y_sub = a - b; + assign y_mul = a * b; + assign y_div = a / b; + assign y_neg = -a; + assign y_lt = a <: b; + assign y_ne = a != b; + }}"# + ); + let result = SimulatorBuilder::new(&source, "Top") + .optimize(optimize) + .trace_mir() + .build_with_trace(); + if let Err(error) = &result.res { + panic!("FP source compilation failed: {error:?}"); + } + let mir = result.trace.mir.as_deref().expect("native MIR trace"); + for op in ["Add", "Sub", "Mul", "Div", "Neg", "Lt", "Ne"] { + assert!( + mir.contains(&format!("fp.{op}.{precision}")) + || (mir.contains(&format!("op: {op},")) + && mir.contains(&format!("precision: {precision},"))), + "missing {op} ({ty}, optimize={optimize}):\n{mir}" + ); + } + assert!( + !mir.contains("extern") && !mir.contains("CallExtern"), + "unexpected FP helper:\n{mir}" + ); + let mut sim = result.unwrap(); + let a = sim.signal("a"); + let b = sim.signal("b"); + let bits = |x: f64| { + if ty == "f32" { + (x as f32).to_bits() as u64 + } else { + x.to_bits() + } + }; + sim.modify(|io| { + io.set(a, bits(3.5)); + io.set(b, bits(-2.0)); + }) + .unwrap(); + for (name, expected) in [ + ("y_add", 1.5), + ("y_sub", 5.5), + ("y_mul", -7.0), + ("y_div", -1.75), + ("y_neg", -3.5), + ] { + assert_eq!( + sim.get(sim.signal(name)), + bits(expected).into(), + "{name} ({ty})" + ); + } + assert_eq!(sim.get(sim.signal("y_lt")), 0u32.into()); + assert_eq!(sim.get(sim.signal("y_ne")), 1u32.into()); + } + } +}