diff --git a/Cargo.lock b/Cargo.lock index c62c47dfe3b..0bb44bd4eb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -825,8 +825,11 @@ dependencies = [ name = "celox-testbench" version = "0.12.0" dependencies = [ + "celox-backend-x86", "celox-design", "celox-heap", + "celox-sir", + "celox-state-layout", "num-bigint", "num-traits", "serde", diff --git a/crates/celox-runtime/src/simulation/activation.rs b/crates/celox-runtime/src/simulation/activation.rs index 7f9b0803fd4..3555e9b2deb 100644 --- a/crates/celox-runtime/src/simulation/activation.rs +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -254,7 +254,7 @@ impl SimulationState { } } } - let live_cancelled = cancelled + let live_cancelled: Vec = cancelled .iter() .enumerate() .filter_map(|(id, &cancelled)| { diff --git a/crates/celox-runtime/src/testbench.rs b/crates/celox-runtime/src/testbench.rs index 058643a6e30..010ebafc6b9 100644 --- a/crates/celox-runtime/src/testbench.rs +++ b/crates/celox-runtime/src/testbench.rs @@ -284,39 +284,6 @@ fn bind_statement( .into_iter() .map(|statement| bind_statement(backend, statement)) .collect::>>()?; - // A constant loop that only waits does not need a host wakeup at - // each iteration. clock_gen keeps running while this process - // sleeps; the induction variable is scoped to the empty body. - if !inclusive - && !reverse - && step == 1 - && step_op.is_none() - && let (Some(0), Some(iterations)) = (constant_bound(&start), constant_bound(&end)) - && let [ - GenericTestbenchStatement::ClockNext { - clock_event, - count, - period, - }, - ] = body.as_slice() - && let Some(count) = match count { - GenericClockCount::Static(n) => Some(*n), - GenericClockCount::Dynamic(expr) => expr.constant_u64(), - } - && count != 0 - && iterations != 0 - && loop_var.as_ref().is_none_or(|(_, width, signed)| { - let bits = width.saturating_sub(usize::from(*signed)); - bits >= 64 || iterations < (1u64 << bits) - }) - && let Some(count) = iterations.checked_mul(count) - { - return Some(GenericTestbenchStatement::ClockNext { - clock_event: *clock_event, - count: GenericClockCount::Static(count), - period: *period, - }); - } Some(GenericTestbenchStatement::For { loop_var: loop_var.map(|(signal, width, signed)| { (backend.resolve_signal(&signal.address), width, signed) @@ -405,25 +372,6 @@ fn bind_statement( } } -fn constant_bound(bound: &ExecutableLoopBound) -> Option { - match bound { - GenericLoopBound::Static(value) => u64::try_from(*value).ok(), - GenericLoopBound::Dynamic { - expr, - width, - signed, - } if *width <= 64 => { - let value = expr.constant_u64()?; - if *signed && (*width == 0 || value >> (*width - 1) != 0) { - None - } else { - Some(value) - } - } - _ => None, - } -} - pub fn bind_testbench_program( backend: &B, program: TestbenchProgram, @@ -443,6 +391,37 @@ pub fn bind_testbench_program( hardware.sort_unstable_by_key(|range| (range.start, range.end)); hardware.dedup(); let backend = &Binding { backend, hardware }; + let kernels = program + .kernels() + .iter() + .map(|kernel| celox_testbench::TestbenchKernel { + entry: kernel.entry, + resume: backend.resolve_signal(&kernel.resume), + status: backend.resolve_signal(&kernel.status), + request: backend.resolve_signal(&kernel.request), + requests: kernel + .requests + .iter() + .map(|request| match request { + celox_testbench::KernelRequest::Statement(site) => { + celox_testbench::KernelRequest::Statement(*site) + } + celox_testbench::KernelRequest::Settle => { + celox_testbench::KernelRequest::Settle + } + celox_testbench::KernelRequest::Written { address, width } => { + celox_testbench::KernelRequest::Written { + address: backend.resolve_signal(address), + width: *width, + } + } + celox_testbench::KernelRequest::Error(message) => { + celox_testbench::KernelRequest::Error(message.clone()) + } + }) + .collect(), + }) + .collect(); let lengths = program.process_lengths().to_vec(); if lengths .iter() @@ -509,6 +488,7 @@ pub fn bind_testbench_program( .collect(); Some( ExecutableTestbench::from_processes(processes, random_seed) + .with_kernels(kernels) .with_clocks(clocks) .with_private_signals(private_signals) .with_component_runtime( diff --git a/crates/celox-testbench/Cargo.toml b/crates/celox-testbench/Cargo.toml index 866bf086d7d..f964b9e843b 100644 --- a/crates/celox-testbench/Cargo.toml +++ b/crates/celox-testbench/Cargo.toml @@ -11,10 +11,15 @@ rust-version.workspace = true [dependencies] celox-design = { workspace = true } +celox-sir = { workspace = true } celox-heap = { workspace = true } num-bigint = { workspace = true } num-traits = { workspace = true } serde = { workspace = true } +[target.'cfg(target_arch = "x86_64")'.dev-dependencies] +celox-backend-x86 = { workspace = true } +celox-state-layout = { workspace = true } + [lints] workspace = true diff --git a/crates/celox-testbench/src/expression.rs b/crates/celox-testbench/src/expression.rs new file mode 100644 index 00000000000..32d1a5ee85b --- /dev/null +++ b/crates/celox-testbench/src/expression.rs @@ -0,0 +1,46 @@ +//! A binding to an expression compiled as an ordinary SIR kernel. +//! Machine code is owned by the simulator backend and its program image. +use crate::{ExprBytecode, ExprOpcode as Opcode, ExpressionKernel}; + +#[derive(Clone, Debug)] +pub struct CompiledExpr { + bytecode: ExprBytecode, + observes_hardware: bool, +} +impl CompiledExpr { + pub fn new(bytecode: ExprBytecode) -> Self { + Self { + bytecode, + observes_hardware: true, + } + } + pub fn bytecode(&self) -> &ExprBytecode { + &self.bytecode + } + pub fn kernel(&self) -> Option<&ExpressionKernel> { + self.bytecode.kernel() + } + pub fn classify_hardware_access(mut self, mut hardware: impl FnMut(usize) -> bool) -> Self { + self.observes_hardware = self.bytecode.ops().iter().any(|op| match op { + Opcode::LoadU64 { location, .. } + | Opcode::LoadWide { location, .. } + | Opcode::LoadIndexed { location, .. } + | Opcode::LoadBitSelect { location, .. } + | Opcode::LoadString { location, .. } + | Opcode::StoreString { location, .. } + | Opcode::StoreU64 { location, .. } => hardware(*location), + _ => false, + }); + self + } + pub fn observes_hardware(&self) -> bool { + self.observes_hardware + } + /// Literal folding for conservative binding-time overlap checks. General + /// constant folding belongs to the shared SIR optimizer. + pub fn constant_u64(&self) -> Option { + self.kernel() + .and_then(|kernel| kernel.constant) + .or_else(|| self.bytecode.literal_u64()) + } +} diff --git a/crates/celox-testbench/src/expression_tests.rs b/crates/celox-testbench/src/expression_tests.rs new file mode 100644 index 00000000000..37b9065256c --- /dev/null +++ b/crates/celox-testbench/src/expression_tests.rs @@ -0,0 +1,52 @@ +use crate::lowering::native_tests::evaluate; +use crate::{ExprOpcode as TbOpcode, TestbenchOperator as Op}; +use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp}; + +#[test] +fn deep_expression_compiles_without_a_runtime_operand_stack() { + for depth in [1, 8, 9, 32, 128, 129, 256] { + let mut ops: Vec<_> = (1..=depth).map(TbOpcode::ConstU64).collect(); + ops.extend((1..depth).map(|_| TbOpcode::BinOp(Op::Add))); + + assert_eq!( + evaluate(ops, &[]), + num_bigint::BigUint::from(depth * (depth + 1) / 2) + ); + } +} + +#[test] +fn floating_bytecode_keeps_precision_and_numeric_conversions() { + for (precision, expected) in [ + (FloatPrecision::F32, 16777216), + (FloatPrecision::F64, 16777217), + ] { + let ops = vec![ + TbOpcode::ConstU64(16777216), + TbOpcode::FloatUnary { + op: FloatUnaryOp::FromUnsigned { width: 32 }, + precision, + }, + TbOpcode::ConstU64(1), + TbOpcode::FloatUnary { + op: FloatUnaryOp::FromUnsigned { width: 32 }, + precision, + }, + TbOpcode::FloatBinary { + op: FloatBinaryOp::Add, + precision, + }, + TbOpcode::FloatUnary { + op: FloatUnaryOp::ToUnsigned { + width: 32, + round: true, + }, + precision, + }, + ]; + assert_eq!( + evaluate(ops, &[]), + num_bigint::BigUint::from(expected as u64) + ); + } +} diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index b5f5a840fa3..5a347dc915b 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -8,13 +8,18 @@ use num_bigint::BigUint; use serde::{Deserialize, Serialize}; use std::path::PathBuf; +mod expression; +#[cfg(all(test, target_arch = "x86_64"))] +mod expression_tests; mod format; -mod vm; +pub mod lowering; +mod value; +pub use expression::CompiledExpr; pub use format::{ DisplayFormatArg, FieldSpec, MAX_FIELD_WIDTH, format_display_arg, format_sized_display_arg, format_sv_display_arg, format_veryl_display_arg, pad_veryl_field, }; -pub use vm::{CompiledExpr, TestbenchValue}; +pub use value::TestbenchValue; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct StateLocation { @@ -281,8 +286,25 @@ pub struct TestbenchClock { pub period: u64, } +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum KernelRequest { + Statement(usize), + Settle, + Written { address: A, width: usize }, + Error(String), +} +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestbenchKernel { + pub entry: usize, + pub resume: A, + pub status: A, + pub request: A, + pub requests: Vec>, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TestbenchProgram { + kernels: Vec>, statements: Vec>, process_lengths: Vec, clocks: Vec>, @@ -297,6 +319,7 @@ pub struct TestbenchProgram { impl Default for TestbenchProgram { fn default() -> Self { Self { + kernels: Vec::new(), statements: Vec::new(), process_lengths: Vec::new(), clocks: Vec::new(), @@ -311,8 +334,16 @@ impl Default for TestbenchProgram { } impl TestbenchProgram { + pub fn kernels(&self) -> &[TestbenchKernel] { + &self.kernels + } + pub fn set_kernels(&mut self, kernels: Vec>) { + self.kernels = kernels; + } + pub fn new(statements: Vec>) -> Self { Self { + kernels: Vec::new(), process_lengths: vec![statements.len()], clocks: Vec::new(), private_variables: Vec::new(), @@ -353,6 +384,13 @@ impl TestbenchProgram { &self.private_variables } + pub fn processes(&self) -> impl Iterator]> { + self.process_lengths.iter().scan(0, |offset, &length| { + let start = *offset; + *offset += length; + Some(&self.statements[start..*offset]) + }) + } pub fn process_lengths(&self) -> &[usize] { &self.process_lengths } @@ -367,6 +405,14 @@ impl TestbenchProgram { self } + pub fn statements_mut(&mut self) -> &mut [SemanticStatement] { + &mut self.statements + } + + pub fn component_bindings_mut(&mut self) -> &mut [SemanticComponentBinding] { + &mut self.component_bindings + } + pub fn statements(&self) -> &[SemanticStatement] { &self.statements } @@ -555,15 +601,66 @@ pub enum ExprOpcode { } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(bound(serialize = "L: Serialize", deserialize = "L: Deserialize<'de>"))] pub struct ExprBytecode { ops: Vec>, + #[serde(default)] + kernel: Option>, } impl ExprBytecode { pub fn new(ops: Vec>) -> Self { - Self { ops } + Self { ops, kernel: None } } + pub fn kernel(&self) -> Option<&ExpressionKernel> { + self.kernel.as_ref() + } + pub fn set_kernel(&mut self, kernel: ExpressionKernel) { + self.kernel = Some(kernel); + } + + /// Fold literal casts without executing a testbench expression. + pub fn literal_u64(&self) -> Option { + let [ExprOpcode::ConstU64(value), rest @ ..] = self.ops.as_slice() else { + return None; + }; + let mut value = *value; + for op in rest { + let ExprOpcode::Resize { + source_width, + target_width, + signed, + } = op + else { + return None; + }; + if *source_width > 64 || *target_width > 64 { + return None; + } + let mask = |width: usize| { + if width >= 64 { + u64::MAX + } else { + (1u64 << width) - 1 + } + }; + if *source_width == 0 { + value = if value & 1 != 0 { + mask(*target_width) + } else { + 0 + }; + } else { + value &= mask(*source_width); + if *signed && *target_width > *source_width && value >> (source_width - 1) != 0 { + value |= !mask(*source_width); + } + value &= mask(*target_width); + } + } + Some(value) + } pub fn ops(&self) -> &[ExprOpcode] { &self.ops } @@ -573,6 +670,17 @@ impl ExprBytecode { } } +/// A native expression entry point and its ordinary state result slot. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExpressionKernel { + pub constant: Option, + pub entry: usize, + pub result: L, + pub width: usize, + pub is_string: bool, + pub writes: Vec<(L, usize)>, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct BindError { pub address: A, @@ -599,6 +707,7 @@ pub type ExecutableStatement = TestbenchStatement< pub type ExecutableComponentBinding = ComponentBinding; pub struct ExecutableTestbench { + kernels: Vec>, statements: Vec>, process_lengths: Vec, clocks: Vec>, @@ -611,6 +720,14 @@ pub struct ExecutableTestbench { } impl ExecutableTestbench { + pub fn kernels(&self) -> &[TestbenchKernel] { + &self.kernels + } + pub fn with_kernels(mut self, kernels: Vec>) -> Self { + self.kernels = kernels; + self + } + pub fn new(statements: Vec>, random_seed: u64) -> Self { Self::new_with_random_seed(statements, Some(random_seed)) } @@ -620,6 +737,7 @@ impl ExecutableTestbench { random_seed: Option, ) -> Self { Self { + kernels: Vec::new(), process_lengths: vec![statements.len()], clocks: Vec::new(), private_signals: Vec::new(), @@ -718,21 +836,21 @@ impl ExecutableTestbench { } } -impl ExprBytecode> { - pub fn bind_with( +impl ExprBytecode { + pub fn try_map_locations( self, - mut resolve: impl FnMut(&A) -> Option, - ) -> Result> { + mut map: impl FnMut(L) -> Result, + ) -> Result, E> { let mut ops = Vec::with_capacity(self.ops.len()); for op in self.ops { let bound = match op { ExprOpcode::ConstString(value) => ExprOpcode::ConstString(value), ExprOpcode::LoadString { location, elements } => ExprOpcode::LoadString { - location: bind_location(location, &mut resolve)?, + location: map(location)?, elements, }, ExprOpcode::StoreString { location } => ExprOpcode::StoreString { - location: bind_location(location, &mut resolve)?, + location: map(location)?, }, ExprOpcode::ConstU64(value) => ExprOpcode::ConstU64(value), ExprOpcode::ConstWide(value) => ExprOpcode::ConstWide(value), @@ -741,7 +859,7 @@ impl ExprBytecode> { byte_size, mask, } => ExprOpcode::LoadU64 { - location: bind_location(location, &mut resolve)?, + location: map(location)?, byte_size, mask, }, @@ -750,7 +868,7 @@ impl ExprBytecode> { byte_size, width, } => ExprOpcode::LoadWide { - location: bind_location(location, &mut resolve)?, + location: map(location)?, byte_size, width, }, @@ -810,7 +928,7 @@ impl ExprBytecode> { base_bit_offset, element_width, } => ExprOpcode::LoadIndexed { - location: bind_location(location, &mut resolve)?, + location: map(location)?, stride_bits, base_bit_offset, element_width, @@ -820,7 +938,7 @@ impl ExprBytecode> { base_byte_size, select_width, } => ExprOpcode::LoadBitSelect { - location: bind_location(location, &mut resolve)?, + location: map(location)?, base_byte_size, select_width, }, @@ -828,13 +946,39 @@ impl ExprBytecode> { location, byte_size, } => ExprOpcode::StoreU64 { - location: bind_location(location, &mut resolve)?, + location: map(location)?, byte_size, }, }; ops.push(bound); } - Ok(ExprBytecode::new(ops)) + let kernel = self + .kernel + .map(|kernel| -> Result<_, E> { + Ok(ExpressionKernel { + constant: kernel.constant, + entry: kernel.entry, + result: map(kernel.result)?, + width: kernel.width, + is_string: kernel.is_string, + writes: kernel + .writes + .into_iter() + .map(|(location, size)| Ok((map(location)?, size))) + .collect::>()?, + }) + }) + .transpose()?; + Ok(ExprBytecode { ops, kernel }) + } +} + +impl ExprBytecode> { + pub fn bind_with( + self, + mut resolve: impl FnMut(&A) -> Option, + ) -> Result> { + self.try_map_locations(|location| bind_location(location, &mut resolve)) } } @@ -933,3 +1077,5 @@ mod tests { assert!(matches!(statement, SemanticStatement::If { .. })); } } + +mod visit; diff --git a/crates/celox-testbench/src/lowering.rs b/crates/celox-testbench/src/lowering.rs new file mode 100644 index 00000000000..2130b85a62c --- /dev/null +++ b/crates/celox-testbench/src/lowering.rs @@ -0,0 +1,711 @@ +//! Lower testbench expressions into the same SIR operations as HDL processes. +//! Widths remain explicit through native instruction selection, including +//! values wider than a host register. Strings use the existing heap ABI. +use crate::{ExprBytecode, ExprOpcode, StateLocation, TestbenchOperator as Op}; +use celox_design::{BinaryOp, UnaryOp}; +use celox_sir::{ + RegisterId, SIRBuilder, SIRInstruction as Inst, SIROffset, SIRTerminator, SIRValue, +}; +use num_bigint::BigUint; + +#[derive(Clone, Copy, Debug)] +pub struct Value { + pub register: RegisterId, + pub string: bool, +} + +pub struct Expressions<'a, A> { + pub builder: &'a mut SIRBuilder, +} +impl Expressions<'_, A> { + fn bits(&mut self, width: usize, value: impl Into) -> Value { + let register = self.builder.alloc_bit(width.max(1), false); + self.builder.emit(Inst::Imm(register, SIRValue::new(value))); + Value { + register, + string: false, + } + } + fn unary(&mut self, op: UnaryOp, value: Value, width: usize, signed: bool) -> Value { + let register = self.builder.alloc_bit(width.max(1), signed); + if op == UnaryOp::Ident && width < self.builder.register(&value.register).width() { + self.builder + .emit(Inst::Slice(register, value.register, 0, width.max(1))); + } else { + self.builder.emit(Inst::Unary(register, op, value.register)); + } + Value { + register, + string: false, + } + } + fn binary(&mut self, op: BinaryOp, lhs: Value, rhs: Value, width: usize) -> Value { + let register = self.builder.alloc_bit(width.max(1), false); + self.builder + .emit(Inst::Binary(register, lhs.register, op, rhs.register)); + Value { + register, + string: false, + } + } + fn resize(&mut self, value: Value, source: usize, target: usize, signed: bool) -> Value { + if target == 0 { + return self.bits(1, 0u8); + } + if source == 0 { + let value = self.unary(UnaryOp::Ident, value, 1, false); + let value = self.unary(UnaryOp::Ident, value, target, false); + return self.unary(UnaryOp::Minus, value, target, false); + } + let value = self.unary(UnaryOp::Ident, value, source, signed); + let value = self.unary(UnaryOp::Ident, value, target, false); + if signed && target > source { + let shift = self.bits(64, (target - source) as u64); + let value = self.binary(BinaryOp::Shl, value, shift, target); + self.binary(BinaryOp::Sar, value, shift, target) + } else { + value + } + } + fn heap(&mut self, operation: u64, args: &[Value]) -> Value { + let op = self.bits(64, operation); + let zero = self.bits(64, 0u8); + let mut inputs = vec![op.register]; + inputs.extend(args.iter().map(|arg| arg.register)); + inputs.resize(4, zero.register); + let register = self.builder.alloc_bit(64, false); + self.builder.emit(Inst::ExternCall { + dst: Some(register), + func: celox_sir::extern_abi::HEAP_HELPER_ID, + args: inputs, + }); + Value { + register, + string: true, + } + } + fn pop(stack: &mut Vec) -> Result { + stack + .pop() + .ok_or_else(|| "testbench expression stack underflow".into()) + } + pub fn compile( + &mut self, + expression: &ExprBytecode>, + ) -> Result { + let mut stack = Vec::new(); + self.block(expression.ops(), &mut stack)?; + if stack.len() != 1 { + return Err("testbench expression must produce one value".into()); + } + let value = Self::pop(&mut stack)?; + if value.string { + let width = self.builder.register(&value.register).width(); + let mut value = self.resize(value, width, celox_design::HANDLE_WIDTH, false); + value.string = true; + Ok(value) + } else { + Ok(value) + } + } + fn block( + &mut self, + code: &[ExprOpcode>], + stack: &mut Vec, + ) -> Result<(), String> { + let mut cursor = 0; + while cursor < code.len() { + let instruction = &code[cursor]; + cursor += 1; + let value = match instruction { + ExprOpcode::ConstU64(value) => self.bits(64, *value), + ExprOpcode::ConstWide(value) => { + self.bits((value.bits() as usize).max(65), value.clone()) + } + ExprOpcode::LoadU64 { + location, + byte_size, + mask, + } => { + let register = self.builder.alloc_bit((byte_size * 8).max(1), false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + byte_size * 8, + )); + let value = Value { + register, + string: false, + }; + let mask = self.bits(64, *mask); + self.binary(BinaryOp::And, value, mask, 64) + } + ExprOpcode::LoadWide { + location, width, .. + } => { + let register = self.builder.alloc_bit((*width).max(1), false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + *width, + )); + Value { + register, + string: false, + } + } + ExprOpcode::BinOp(op) => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + let width = self + .builder + .register(&lhs.register) + .width() + .max(self.builder.register(&rhs.register).width()); + self.operation(*op, lhs, rhs, width, width, width, false, false)? + } + ExprOpcode::TypedBinOp { + op, + lhs_width, + rhs_width, + result_width, + lhs_signed, + rhs_signed, + } => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + self.operation( + *op, + lhs, + rhs, + *lhs_width, + *rhs_width, + *result_width, + *lhs_signed, + *rhs_signed, + )? + } + ExprOpcode::TypedUnary { + op, + operand_width, + result_width, + } => { + let operand = Self::pop(stack)?; + let operand = self.resize(operand, *operand_width, *operand_width, false); + let (op, invert) = match op { + Op::Add => (UnaryOp::Ident, false), + Op::Sub => (UnaryOp::Minus, false), + Op::LogicNot => (UnaryOp::LogicNot, false), + Op::BitNot => (UnaryOp::BitNot, false), + Op::BitAnd => (UnaryOp::And, false), + Op::BitNand => (UnaryOp::And, true), + Op::BitOr => (UnaryOp::Or, false), + Op::BitNor => (UnaryOp::Or, true), + Op::BitXor => (UnaryOp::Xor, false), + Op::BitXnor => (UnaryOp::Xor, true), + _ => return Err("invalid testbench unary operator".into()), + }; + let value = self.unary(op, operand, *result_width, false); + if invert { + self.unary(UnaryOp::LogicNot, value, 1, false) + } else { + value + } + } + ExprOpcode::FloatBinary { op, precision } => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + let lhs = self.resize(lhs, precision.width(), precision.width(), false); + let rhs = self.resize(rhs, precision.width(), precision.width(), false); + let op = BinaryOp::Float { + op: *op, + precision: *precision, + }; + let width = match op { + BinaryOp::Float { + op: + celox_design::FloatBinaryOp::Eq + | celox_design::FloatBinaryOp::Ne + | celox_design::FloatBinaryOp::Lt + | celox_design::FloatBinaryOp::Le + | celox_design::FloatBinaryOp::Gt + | celox_design::FloatBinaryOp::Ge, + .. + } => 1, + _ => precision.width(), + }; + self.binary(op, lhs, rhs, width) + } + ExprOpcode::FloatUnary { op, precision } => { + let value = Self::pop(stack)?; + let input_width = match op { + celox_design::FloatUnaryOp::FromSigned { width } + | celox_design::FloatUnaryOp::FromUnsigned { width } => *width, + _ => precision.width(), + }; + let value = self.resize(value, input_width, input_width, false); + let op = UnaryOp::Float { + op: *op, + precision: *precision, + }; + self.unary(op, value, op.result_width(precision.width()), false) + } + ExprOpcode::Resize { + source_width, + target_width, + signed, + } => { + let value = Self::pop(stack)?; + self.resize(value, *source_width, *target_width, *signed) + } + ExprOpcode::ConcatPart { + part_width, + result_width, + } => { + let rhs = Self::pop(stack)?; + let lhs = Self::pop(stack)?; + if *part_width >= *result_width { + self.resize(rhs, *part_width, *result_width, false) + } else { + let rhs = self.resize(rhs, *part_width, *part_width, false); + let lhs = self.resize( + lhs, + self.builder.register(&lhs.register).width(), + result_width - part_width, + false, + ); + let register = self.builder.alloc_bit((*result_width).max(1), false); + self.builder + .emit(Inst::Concat(register, vec![lhs.register, rhs.register])); + Value { + register, + string: false, + } + } + } + ExprOpcode::Ternary { then_len, else_len } => { + let condition = Self::pop(stack)?; + let end = cursor + .checked_add(*then_len) + .and_then(|x| x.checked_add(*else_len)) + .filter(|x| *x <= code.len()) + .ok_or("invalid testbench conditional lengths")?; + let yes = self.builder.new_block(); + let no = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: condition.register, + true_block: (yes, vec![]), + false_block: (no, vec![]), + }); + self.builder.switch_to_block(yes); + let mut left = stack.clone(); + self.block(&code[cursor..cursor + then_len], &mut left)?; + let yes_end = self.builder.current_block(); + self.builder.seal_block(SIRTerminator::Return); + self.builder.switch_to_block(no); + let mut right = stack.clone(); + self.block(&code[cursor + then_len..end], &mut right)?; + if left.len() != right.len() || left.len() != stack.len() + 1 { + return Err("testbench conditional stack mismatch".into()); + } + let no_end = self.builder.current_block(); + self.builder.seal_block(SIRTerminator::Return); + let mut params = Vec::new(); + let mut merged = Vec::new(); + for (l, r) in left.iter().zip(&right) { + if l.string != r.string { + return Err("testbench conditional value kind mismatch".into()); + } + let width = self + .builder + .register(&l.register) + .width() + .max(self.builder.register(&r.register).width()); + let register = self.builder.alloc_bit(width, false); + params.push(register); + merged.push(Value { + register, + string: l.string, + }); + } + let join = self.builder.new_block_with(params); + for (block, values) in [(yes_end, left), (no_end, right)] { + self.builder.switch_to_block(block); + let values = values + .into_iter() + .zip(&merged) + .map(|(value, target)| { + self.unary( + UnaryOp::Ident, + value, + self.builder.register(&target.register).width(), + false, + ) + .register + }) + .collect(); + self.builder.seal_block(SIRTerminator::Jump(join, values)); + } + self.builder.switch_to_block(join); + *stack = merged; + cursor = end; + continue; + } + ExprOpcode::LoadIndexed { + location, + stride_bits, + base_bit_offset, + element_width, + } => { + let index = Self::pop(stack)?; + let stride = self.bits(64, *stride_bits as u64); + let offset = self.binary(BinaryOp::Mul, index, stride, 64); + let base = self.bits(64, (location.byte_offset * 8 + base_bit_offset) as u64); + let offset = self.binary(BinaryOp::Add, offset, base, 64); + let register = self.builder.alloc_bit((*element_width).max(1), false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Dynamic(offset.register), + *element_width, + )); + Value { + register, + string: false, + } + } + ExprOpcode::LoadBitSelect { + location, + base_byte_size, + select_width, + } => { + // Select from the value, not from an unchecked dynamic + // memory address. A selection may extend past the object. + let offset = Self::pop(stack)?; + let width = base_byte_size.saturating_mul(8); + if width == 0 || *select_width == 0 { + self.bits((*select_width).max(1), 0u8) + } else { + let register = self.builder.alloc_bit(width, false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + width, + )); + let value = Value { + register, + string: false, + }; + let value = self.binary(BinaryOp::Shr, value, offset, width); + self.resize(value, width, *select_width, false) + } + } + ExprOpcode::StoreU64 { + location, + byte_size, + } => { + let value = Self::pop(stack)?; + self.builder.emit(Inst::Store( + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + byte_size * 8, + value.register, + vec![], + vec![], + )); + continue; + } + ExprOpcode::ConstString(bytes) => { + let mut value = self.heap(celox_heap::ops::NEW, &[]); + for chunk in bytes.chunks(8) { + let bits = chunk + .iter() + .fold(0u64, |v, byte| (v << 8) | u64::from(*byte)); + let bits = self.bits(64, bits); + let count = self.bits(64, chunk.len() as u64); + value = self.heap(celox_heap::ops::APPEND_BYTES, &[value, bits, count]); + } + self.heap(celox_heap::ops::FREEZE, &[value]) + } + ExprOpcode::LoadString { location, elements } => { + let offset = Self::pop(stack)?; + let shift = self.bits(64, celox_design::HANDLE_WIDTH.trailing_zeros() as u64); + let index = self.binary(BinaryOp::Shr, offset, shift, 64); + let limit = self.bits(64, *elements as u64); + let valid = self.binary(BinaryOp::LtU, index, limit, 1); + let present = self.builder.new_block(); + let absent = self.builder.new_block(); + let result = self.builder.alloc_bit(celox_design::HANDLE_WIDTH, false); + let join = self.builder.new_block_with(vec![result]); + self.builder.seal_block(SIRTerminator::Branch { + cond: valid.register, + true_block: (present, vec![]), + false_block: (absent, vec![]), + }); + self.builder.switch_to_block(present); + let shift = self.bits(64, celox_design::HANDLE_WIDTH.trailing_zeros() as u64); + let offset = self.binary(BinaryOp::Shl, index, shift, 64); + let base = self.bits(64, (location.byte_offset * 8) as u64); + let offset = self.binary(BinaryOp::Add, offset, base, 64); + let register = self.builder.alloc_bit(celox_design::HANDLE_WIDTH, false); + self.builder.emit(Inst::Load( + register, + location.address.clone(), + SIROffset::Dynamic(offset.register), + celox_design::HANDLE_WIDTH, + )); + self.builder + .seal_block(SIRTerminator::Jump(join, vec![register])); + self.builder.switch_to_block(absent); + let zero = self.bits(celox_design::HANDLE_WIDTH, 0u8); + self.builder + .seal_block(SIRTerminator::Jump(join, vec![zero.register])); + self.builder.switch_to_block(join); + Value { + register: result, + string: true, + } + } + ExprOpcode::StoreString { location } => { + let value = Self::pop(stack)?; + let width = self.builder.register(&value.register).width(); + let value = self.resize(value, width, celox_design::HANDLE_WIDTH, false); + self.builder.emit(Inst::Store( + location.address.clone(), + SIROffset::Static(location.byte_offset * 8), + celox_design::HANDLE_WIDTH, + value.register, + vec![], + vec![], + )); + continue; + } + }; + stack.push(value); + } + Ok(()) + } + fn operation( + &mut self, + op: Op, + mut lhs: Value, + mut rhs: Value, + lw: usize, + rw: usize, + width: usize, + ls: bool, + rs: bool, + ) -> Result { + if lhs.string && rhs.string { + lhs = self.heap(celox_heap::ops::COMPARE, &[lhs, rhs]); + rhs = self.bits(64, 0u8); + return self.operation( + op, + Value { + string: false, + ..lhs + }, + rhs, + 64, + 64, + 1, + true, + true, + ); + } + lhs = self.resize(lhs, lw, lw, ls); + rhs = self.resize(rhs, rw, rw, rs); + let signed = ls && rs; + if op == Op::Pow { + let mut result = self.bits(width, 1u8); + let mut factor = self.resize(lhs, lw, width, false); + for bit in 0..rw { + let predicate = self.builder.alloc_bit(1, false); + self.builder + .emit(Inst::Slice(predicate, rhs.register, bit, 1)); + let product = self.binary(BinaryOp::Mul, result, factor, width); + let register = self.builder.alloc_bit(width.max(1), false); + self.builder.emit(Inst::Mux( + register, + predicate, + product.register, + result.register, + )); + result = Value { + register, + string: false, + }; + if bit + 1 < rw { + factor = self.binary(BinaryOp::Mul, factor, factor, width); + } + } + return Ok(result); + } + let (binary, boolean, invert) = match op { + Op::Add => (BinaryOp::Add, false, false), + Op::Sub => (BinaryOp::Sub, false, false), + Op::Mul => (BinaryOp::Mul, false, false), + Op::Div => ( + if signed { + BinaryOp::DivS + } else { + BinaryOp::DivU + }, + false, + false, + ), + Op::Rem => ( + if signed { + BinaryOp::RemS + } else { + BinaryOp::RemU + }, + false, + false, + ), + Op::BitAnd | Op::BitNand => (BinaryOp::And, false, op == Op::BitNand), + Op::BitOr | Op::BitNor => (BinaryOp::Or, false, op == Op::BitNor), + Op::BitXor | Op::BitXnor => (BinaryOp::Xor, false, op == Op::BitXnor), + Op::LogicShiftL | Op::ArithShiftL => (BinaryOp::Shl, false, false), + Op::LogicShiftR => (BinaryOp::Shr, false, false), + Op::ArithShiftR => (if ls { BinaryOp::Sar } else { BinaryOp::Shr }, false, false), + Op::Eq | Op::EqWildcard => (BinaryOp::Eq, true, false), + Op::Ne | Op::NeWildcard => (BinaryOp::Ne, true, false), + Op::Less => ( + if signed { BinaryOp::LtS } else { BinaryOp::LtU }, + true, + false, + ), + Op::LessEq => ( + if signed { BinaryOp::LeS } else { BinaryOp::LeU }, + true, + false, + ), + Op::Greater => ( + if signed { BinaryOp::GtS } else { BinaryOp::GtU }, + true, + false, + ), + Op::GreaterEq => ( + if signed { BinaryOp::GeS } else { BinaryOp::GeU }, + true, + false, + ), + Op::LogicAnd => (BinaryOp::LogicAnd, true, false), + Op::LogicOr => (BinaryOp::LogicOr, true, false), + _ => return Err("invalid testbench binary operator".into()), + }; + let result = self.binary(binary, lhs, rhs, if boolean { 1 } else { width }); + Ok(if invert { + self.unary(UnaryOp::BitNot, result, width, false) + } else { + result + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn lower(ops: Vec>>) -> celox_sir::ExecutionUnit { + let mut builder = SIRBuilder::new(); + let value = Expressions { + builder: &mut builder, + } + .compile(&ExprBytecode::new(ops)) + .unwrap(); + let width = builder.register(&value.register).width(); + builder.emit(Inst::Store( + 0, + SIROffset::Static(0), + width, + value.register, + vec![], + vec![], + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let unit = celox_sir::ExecutionUnit { + entry_block_id: celox_sir::BlockId(0), + blocks, + register_map, + }; + unit.verify_result().unwrap(); + unit + } + #[test] + fn wide_arithmetic_uses_sir_instead_of_value_callbacks() { + let unit = lower(vec![ + ExprOpcode::ConstWide(BigUint::from(1u8) << 170), + ExprOpcode::ConstU64(37), + ExprOpcode::TypedBinOp { + op: Op::Mul, + lhs_width: 192, + rhs_width: 192, + result_width: 192, + lhs_signed: false, + rhs_signed: false, + }, + ]); + assert!(unit.blocks.values().flat_map(|b|&b.instructions).any(|i|matches!(i,Inst::Binary(dst,_,BinaryOp::Mul,_) if unit.register_map[dst].width()==192))); + assert!( + !unit + .blocks + .values() + .flat_map(|b| &b.instructions) + .any(|i| matches!(i, Inst::ExternCall { .. })) + ); + } + #[test] + fn floating_point_uses_the_shared_sir_operator() { + let unit = lower(vec![ + ExprOpcode::ConstU64(1.5f64.to_bits()), + ExprOpcode::ConstU64(2.0f64.to_bits()), + ExprOpcode::FloatBinary { + op: celox_design::FloatBinaryOp::Mul, + precision: celox_design::FloatPrecision::F64, + }, + ]); + assert!( + unit.blocks + .values() + .flat_map(|b| &b.instructions) + .any(|i| matches!(i, Inst::Binary(_, _, BinaryOp::Float { .. }, _))) + ); + } + #[test] + fn strings_use_the_existing_hdl_heap_abi() { + let unit = lower(vec![ExprOpcode::ConstString(b"native testbench".to_vec())]); + assert!( + unit.blocks + .values() + .flat_map(|b| &b.instructions) + .filter_map(|i| if let Inst::ExternCall { func, .. } = i { + Some(*func) + } else { + None + }) + .all(|id| id == celox_sir::extern_abi::HEAP_HELPER_ID) + ); + } + #[test] + fn conditional_side_effects_remain_in_separate_blocks() { + let unit = lower(vec![ + ExprOpcode::ConstU64(1), + ExprOpcode::Ternary { + then_len: 1, + else_len: 1, + }, + ExprOpcode::ConstWide(BigUint::from(1u8) << 127), + ExprOpcode::ConstU64(42), + ]); + assert_eq!(unit.blocks.len(), 4); + } +} + +#[cfg(all(test, target_arch = "x86_64"))] +#[path = "lowering_native_tests.rs"] +pub(crate) mod native_tests; diff --git a/crates/celox-testbench/src/lowering_native_tests.rs b/crates/celox-testbench/src/lowering_native_tests.rs new file mode 100644 index 00000000000..5ed6e4459d7 --- /dev/null +++ b/crates/celox-testbench/src/lowering_native_tests.rs @@ -0,0 +1,369 @@ +//! Execute lowered expressions through the HDL native pipeline. +use super::*; +use celox_backend_x86::native::{emit, jit_mem::JitCode, scalar_pipeline}; +use celox_design::{InstanceId, RegionedStateAddr, STABLE_REGION, StateAddr, StateObjectId}; +use celox_state_layout::{ + LayoutInput, LayoutSource, MemoryLayout, MemoryLayoutMode, StateObjectLayout, +}; + +struct Objects(Vec>); +impl LayoutSource for Objects { + fn layout_input(&self, _: MemoryLayoutMode) -> LayoutInput { + LayoutInput { + state_objects: self.0.clone(), + working_addresses: vec![], + sparse_addresses: vec![], + unpacked_arrays: Default::default(), + requirements: Default::default(), + ff_referenced_addresses: Default::default(), + num_events: 0, + runtime_event_sites: vec![], + lane_writers: Default::default(), + access_rank: Default::default(), + } + } +} +fn address(id: u32) -> StateAddr { + StateAddr { + instance_id: InstanceId(0), + var_id: StateObjectId(id), + } +} +pub(crate) fn evaluate(ops: Vec>>, input: &[u8]) -> BigUint { + evaluate_with_state(ops, input).0 +} +fn evaluate_with_state( + ops: Vec>>, + input: &[u8], +) -> (BigUint, Vec) { + let mut builder = SIRBuilder::new(); + let result = Expressions { + builder: &mut builder, + } + .compile(&ExprBytecode::new(ops)) + .unwrap(); + let width = builder.register(&result.register).width(); + builder.emit(Inst::Store( + 0, + SIROffset::Static(0), + width, + result.register, + vec![], + vec![], + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let unit = celox_sir::ExecutionUnit { + entry_block_id: celox_sir::BlockId(0), + blocks, + register_map, + } + .into_map_addr(&mut |id| RegionedStateAddr::from_absolute_addr(STABLE_REGION, address(id))); + let source = Objects(vec![ + StateObjectLayout { + address: address(0), + width, + is_4state: false, + }, + StateObjectLayout { + address: address(1), + width: (input.len() * 8).max(64), + is_4state: false, + }, + ]); + let layout = MemoryLayout::build(&source, false, MemoryLayoutMode::Packed); + let prepared = + scalar_pipeline::prepare_scalar_eu(&unit, &layout, false, "testbench-expression").unwrap(); + let code = emit::emit( + &prepared.function, + &prepared.allocation, + prepared.spill_frame_size, + ) + .unwrap(); + let jit = JitCode::new(&code.code).unwrap(); + let mut state = vec![0u128; (code.required_state_size as usize).div_ceil(16)]; + // The aligned allocation includes the complete native spill arena. Both + // semantic objects were allocated by the ordinary HDL state layout. + let bytes = unsafe { + std::slice::from_raw_parts_mut(state.as_mut_ptr().cast::(), state.len() * 16) + }; + let table = [celox_sir::float::evaluate as *const () as usize]; + let pointer = table.as_ptr().wrapping_add(1) as u64; + let header = celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET; + bytes[header..header + 8].copy_from_slice(&pointer.to_le_bytes()); + let offset = layout.offsets[&address(1)]; + bytes[offset..offset + input.len()].copy_from_slice(input); + unsafe { + (jit.fn_ptr)(bytes.as_mut_ptr()); + } + let offset = layout.offsets[&address(0)]; + ( + BigUint::from_bytes_le(&bytes[offset..offset + width.div_ceil(8)]), + bytes[layout.offsets[&address(1)]..layout.offsets[&address(1)] + input.len()].to_vec(), + ) +} +fn operation(op: Op, width: usize, signed: bool) -> ExprOpcode> { + ExprOpcode::TypedBinOp { + op, + lhs_width: width, + rhs_width: width, + result_width: width, + lhs_signed: signed, + rhs_signed: signed, + } +} +#[test] +fn wide_native_multiply_preserves_high_limbs() { + let lhs = (BigUint::from(1u8) << 171) + BigUint::from(17u8); + let rhs = (BigUint::from(1u8) << 67) + BigUint::from(3u8); + let expected = (&lhs * &rhs) & ((BigUint::from(1u8) << 256) - BigUint::from(1u8)); + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstWide(lhs), + ExprOpcode::ConstWide(rhs), + operation(Op::Mul, 256, false) + ], + &[] + ), + expected + ); +} +#[test] +fn native_signed_division_and_comparison() { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(0xf9), + ExprOpcode::ConstU64(2), + operation(Op::Div, 8, true) + ], + &[] + ), + BigUint::from(0xfdu8) + ); + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(0xf9), + ExprOpcode::ConstU64(2), + operation(Op::Less, 8, true) + ], + &[] + ), + BigUint::from(1u8) + ); +} +#[test] +fn native_float_multiply() { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(1.5f64.to_bits()), + ExprOpcode::ConstU64((-2.0f64).to_bits()), + ExprOpcode::FloatBinary { + op: celox_design::FloatBinaryOp::Mul, + precision: celox_design::FloatPrecision::F64 + } + ], + &[] + ), + BigUint::from((-3.0f64).to_bits()) + ); +} +#[test] +fn bit_selection_does_not_read_the_next_object() { + for shift in [4, 8, 63, 64, 65, u64::MAX] { + let expected = if shift == 4 { 0xau8 } else { 0 }; + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(shift), + ExprOpcode::LoadBitSelect { + location: StateLocation { + address: 1, + byte_offset: 0 + }, + base_byte_size: 1, + select_width: 8 + } + ], + &[0xa5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff] + ), + BigUint::from(expected) + ); + } +} +#[test] +fn out_of_bounds_string_index_returns_empty_handle() { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(u64::MAX), + ExprOpcode::LoadString { + location: StateLocation { + address: 1, + byte_offset: 0 + }, + elements: 1 + } + ], + &[0xff; 8] + ), + BigUint::ZERO + ); +} + +#[test] +fn native_typed_arithmetic_matches_expression_contract() { + use crate::value::eval_typed_binop; + for width in [1usize, 8, 33, 64, 65, 129] { + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + for (lhs, rhs) in [ + (mask.clone(), BigUint::from(2u8)), + (BigUint::from(7u8), BigUint::ZERO), + ] { + for signed in [false, true] { + for op in [ + Op::Add, + Op::Sub, + Op::Mul, + Op::Div, + Op::Rem, + Op::Eq, + Op::Ne, + Op::Less, + Op::LessEq, + Op::Greater, + Op::GreaterEq, + Op::BitAnd, + Op::BitOr, + Op::BitXor, + Op::BitNand, + Op::BitNor, + Op::BitXnor, + Op::LogicAnd, + Op::LogicOr, + Op::LogicShiftL, + Op::LogicShiftR, + Op::ArithShiftR, + ] { + let expected = eval_typed_binop( + crate::TestbenchValue::Wide(lhs.clone()), + op, + crate::TestbenchValue::Wide(rhs.clone()), + width, + width, + width, + signed, + signed, + ) + .to_biguint(); + let actual = evaluate( + vec![ + ExprOpcode::ConstWide(lhs.clone()), + ExprOpcode::ConstWide(rhs.clone()), + operation(op, width, signed), + ], + &[], + ); + assert_eq!( + actual, expected, + "{op:?}, width={width}, signed={signed}, lhs={lhs}, rhs={rhs}" + ); + } + } + } + } +} + +#[test] +fn conditional_kernel_writes_only_the_selected_branch() { + let loc = |byte_offset| StateLocation { + address: 1, + byte_offset, + }; + let ops = vec![ + ExprOpcode::ConstU64(100), + ExprOpcode::LoadU64 { + location: loc(0), + byte_size: 1, + mask: 1, + }, + ExprOpcode::Ternary { + then_len: 4, + else_len: 4, + }, + ExprOpcode::ConstU64(11), + ExprOpcode::StoreU64 { + location: loc(1), + byte_size: 1, + }, + ExprOpcode::ConstU64(20), + ExprOpcode::Resize { + source_width: 8, + target_width: 129, + signed: false, + }, + ExprOpcode::ConstU64(22), + ExprOpcode::StoreU64 { + location: loc(2), + byte_size: 1, + }, + ExprOpcode::ConstU64(30), + ExprOpcode::Resize { + source_width: 8, + target_width: 129, + signed: false, + }, + ExprOpcode::BinOp(Op::Add), + ]; + for condition in [0, 1] { + let (value, state) = evaluate_with_state(ops.clone(), &[condition, 0, 0]); + assert_eq!( + value, + BigUint::from(if condition == 1 { 120u64 } else { 130 }) + ); + assert_eq!( + state, + if condition == 1 { + vec![1, 11, 0] + } else { + vec![0, 0, 22] + } + ); + } +} + +#[test] +fn string_handles_use_the_shared_heap_width() { + let location = StateLocation { + address: 1, + byte_offset: 0, + }; + let input = [0x12, 0, 0, 0, 0x34, 0, 0, 0]; + for (index, expected) in [(0, 0x12u8), (1, 0x34), (2, 0)] { + assert_eq!( + evaluate( + vec![ + ExprOpcode::ConstU64(index * celox_design::HANDLE_WIDTH as u64), + ExprOpcode::LoadString { + location, + elements: 2 + }, + ], + &input + ), + BigUint::from(expected) + ); + } + let (_, state) = evaluate_with_state( + vec![ + ExprOpcode::ConstU64(0x56), + ExprOpcode::StoreString { location }, + ExprOpcode::ConstU64(0), + ], + &input, + ); + assert_eq!(state, [0x56, 0, 0, 0, 0x34, 0, 0, 0]); +} diff --git a/crates/celox-testbench/src/value.rs b/crates/celox-testbench/src/value.rs new file mode 100644 index 00000000000..e0f96483624 --- /dev/null +++ b/crates/celox-testbench/src/value.rs @@ -0,0 +1,51 @@ +use num_bigint::BigUint; + +/// Testbench value: integer bits or a dynamically sized byte string. +#[derive(Clone, Debug)] +pub enum TestbenchValue { + U64(u64), + Wide(BigUint), + String(Vec), +} + +impl TestbenchValue { + #[inline] + pub fn to_u64(&self) -> u64 { + match self { + TestbenchValue::String(v) => v + .iter() + .rev() + .take(8) + .enumerate() + .fold(0, |value, (i, byte)| value | (u64::from(*byte) << (i * 8))), + TestbenchValue::U64(v) => *v, + TestbenchValue::Wide(v) => { + let digits = v.to_u64_digits(); + digits.first().copied().unwrap_or(0) + } + } + } + + #[inline] + pub fn is_zero(&self) -> bool { + match self { + TestbenchValue::String(v) => v.is_empty(), + TestbenchValue::U64(v) => *v == 0, + TestbenchValue::Wide(v) => *v == BigUint::ZERO, + } + } + + #[inline] + pub fn to_biguint(&self) -> BigUint { + match self { + TestbenchValue::String(v) => BigUint::from_bytes_be(v), + TestbenchValue::U64(v) => BigUint::from(*v), + TestbenchValue::Wide(v) => v.clone(), + } + } +} + +#[cfg(test)] +mod arithmetic_oracle; +#[cfg(test)] +pub(crate) use arithmetic_oracle::eval_typed_binop; diff --git a/crates/celox-testbench/src/value/arithmetic_oracle.rs b/crates/celox-testbench/src/value/arithmetic_oracle.rs new file mode 100644 index 00000000000..afbd71f18cb --- /dev/null +++ b/crates/celox-testbench/src/value/arithmetic_oracle.rs @@ -0,0 +1,326 @@ +//! Test-only arithmetic oracle for native lowering differential tests. +use super::TestbenchValue; +use crate::TestbenchOperator as Op; +use num_bigint::{BigInt, BigUint, Sign}; +use num_traits::ToPrimitive as _; + +pub(crate) fn width_mask(width: usize) -> BigUint { + if width == 0 { + BigUint::ZERO + } else { + (BigUint::from(1u8) << width) - BigUint::from(1u8) + } +} + +#[inline] +pub(crate) fn width_mask_u64(width: usize) -> u64 { + match width { + 0 => 0, + 1..=63 => (1u64 << width) - 1, + _ => u64::MAX, + } +} + +#[inline] +pub(crate) fn signed_i128(value: u64, width: usize) -> i128 { + let value = value & width_mask_u64(width); + if width == 0 || width >= 64 { + (value as i64) as i128 + } else if value & (1u64 << (width - 1)) == 0 { + value as i128 + } else { + value as i128 - (1i128 << width) + } +} + +pub(crate) fn normalized_bits(value: &TestbenchValue, width: usize) -> BigUint { + value.to_biguint() & width_mask(width) +} + +pub(crate) fn tb_value_from_bits(value: BigUint, width: usize) -> TestbenchValue { + let value = value & width_mask(width); + if width <= 64 { + TestbenchValue::U64(value.to_u64().unwrap_or(0)) + } else { + TestbenchValue::Wide(value) + } +} + +pub(crate) fn signed_bigint(value: &TestbenchValue, width: usize) -> BigInt { + let raw = normalized_bits(value, width); + if width == 0 || !raw.bit((width - 1) as u64) { + BigInt::from(raw) + } else { + BigInt::from(raw) - (BigInt::from(1u8) << width) + } +} + +pub(crate) fn signed_bits(value: BigInt, width: usize) -> BigUint { + if width == 0 { + return BigUint::ZERO; + } + let modulus = BigUint::from(1u8) << width; + match value.sign() { + Sign::Minus => { + let magnitude = (-value).to_biguint().unwrap_or_default() % &modulus; + if magnitude == BigUint::ZERO { + BigUint::ZERO + } else { + modulus - magnitude + } + } + _ => value.to_biguint().unwrap_or_default() % modulus, + } +} + +pub(crate) fn eval_typed_binop_u64( + l: u64, + op: Op, + r: u64, + lhs_width: usize, + rhs_width: usize, + result_width: usize, + lhs_signed: bool, + rhs_signed: bool, +) -> u64 { + let l = l & width_mask_u64(lhs_width); + let r = r & width_mask_u64(rhs_width); + let result_mask = width_mask_u64(result_width); + let signed = lhs_signed && rhs_signed; + let bool_value = |value: bool| u64::from(value); + + match op { + Op::Eq | Op::EqWildcard => bool_value(l == r), + Op::Ne | Op::NeWildcard => bool_value(l != r), + Op::Less if signed => bool_value(signed_i128(l, lhs_width) < signed_i128(r, rhs_width)), + Op::Less => bool_value(l < r), + Op::LessEq if signed => bool_value(signed_i128(l, lhs_width) <= signed_i128(r, rhs_width)), + Op::LessEq => bool_value(l <= r), + Op::Greater if signed => bool_value(signed_i128(l, lhs_width) > signed_i128(r, rhs_width)), + Op::Greater => bool_value(l > r), + Op::GreaterEq if signed => { + bool_value(signed_i128(l, lhs_width) >= signed_i128(r, rhs_width)) + } + Op::GreaterEq => bool_value(l >= r), + Op::LogicAnd => bool_value(l != 0 && r != 0), + Op::LogicOr => bool_value(l != 0 || r != 0), + Op::Add => l.wrapping_add(r) & result_mask, + Op::Sub => l.wrapping_sub(r) & result_mask, + Op::Mul => l.wrapping_mul(r) & result_mask, + Op::Div if signed => { + let divisor = signed_i128(r, rhs_width); + if divisor == 0 { + 0 + } else { + (signed_i128(l, lhs_width) / divisor) as u64 & result_mask + } + } + Op::Div => l.checked_div(r).unwrap_or(0) & result_mask, + Op::Rem if signed => { + let divisor = signed_i128(r, rhs_width); + if divisor == 0 { + 0 + } else { + (signed_i128(l, lhs_width) % divisor) as u64 & result_mask + } + } + Op::Rem => l.checked_rem(r).unwrap_or(0) & result_mask, + Op::Pow => { + let mut exponent = r; + let mut base = l & result_mask; + let mut value = 1u64 & result_mask; + while exponent != 0 { + if exponent & 1 != 0 { + value = ((value as u128 * base as u128) as u64) & result_mask; + } + exponent >>= 1; + if exponent != 0 { + base = ((base as u128 * base as u128) as u64) & result_mask; + } + } + value + } + Op::BitAnd => (l & r) & result_mask, + Op::BitOr => (l | r) & result_mask, + Op::BitXor => (l ^ r) & result_mask, + Op::BitXnor => (!(l ^ r)) & result_mask, + Op::BitNand => (!(l & r)) & result_mask, + Op::BitNor => (!(l | r)) & result_mask, + Op::LogicShiftL | Op::ArithShiftL => { + if r >= result_width as u64 { + 0 + } else { + l.wrapping_shl(r as u32) & result_mask + } + } + Op::LogicShiftR => { + if r >= result_width as u64 { + 0 + } else { + (l >> r) & result_mask + } + } + Op::ArithShiftR if lhs_signed => { + let value = signed_i128(l, lhs_width); + if r >= result_width as u64 { + if value < 0 { result_mask } else { 0 } + } else { + ((value >> r) as u64) & result_mask + } + } + Op::ArithShiftR => { + if r >= result_width as u64 { + 0 + } else { + (l >> r) & result_mask + } + } + _ => unreachable!("operator is not a source-language binary op: {op:?}"), + } +} + +pub(crate) fn eval_typed_binop( + l: TestbenchValue, + op: Op, + r: TestbenchValue, + lhs_width: usize, + rhs_width: usize, + result_width: usize, + lhs_signed: bool, + rhs_signed: bool, +) -> TestbenchValue { + if let (TestbenchValue::U64(l), TestbenchValue::U64(r)) = (&l, &r) + && lhs_width <= 64 + && rhs_width <= 64 + && result_width <= 64 + { + return TestbenchValue::U64(eval_typed_binop_u64( + *l, + op, + *r, + lhs_width, + rhs_width, + result_width, + lhs_signed, + rhs_signed, + )); + } + let lb = normalized_bits(&l, lhs_width); + let rb = normalized_bits(&r, rhs_width); + let signed = lhs_signed && rhs_signed; + + let comparison = |value: bool| TestbenchValue::U64(u64::from(value)); + match op { + Op::Eq | Op::EqWildcard => comparison(lb == rb), + Op::Ne | Op::NeWildcard => comparison(lb != rb), + Op::Less if signed => { + comparison(signed_bigint(&l, lhs_width) < signed_bigint(&r, rhs_width)) + } + Op::Less => comparison(lb < rb), + Op::LessEq if signed => { + comparison(signed_bigint(&l, lhs_width) <= signed_bigint(&r, rhs_width)) + } + Op::LessEq => comparison(lb <= rb), + Op::Greater if signed => { + comparison(signed_bigint(&l, lhs_width) > signed_bigint(&r, rhs_width)) + } + Op::Greater => comparison(lb > rb), + Op::GreaterEq if signed => { + comparison(signed_bigint(&l, lhs_width) >= signed_bigint(&r, rhs_width)) + } + Op::GreaterEq => comparison(lb >= rb), + Op::LogicAnd => comparison(lb != BigUint::ZERO && rb != BigUint::ZERO), + Op::LogicOr => comparison(lb != BigUint::ZERO || rb != BigUint::ZERO), + Op::Add => tb_value_from_bits(lb + rb, result_width), + Op::Sub => tb_value_from_bits( + signed_bits(BigInt::from(lb) - BigInt::from(rb), result_width), + result_width, + ), + Op::Mul => tb_value_from_bits(lb * rb, result_width), + Op::Div if signed => { + let divisor = signed_bigint(&r, rhs_width); + if divisor == BigInt::from(0u8) { + TestbenchValue::U64(0) + } else { + let quotient = signed_bigint(&l, lhs_width) / divisor; + tb_value_from_bits(signed_bits(quotient, result_width), result_width) + } + } + Op::Div => { + if rb == BigUint::ZERO { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb / rb, result_width) + } + } + Op::Rem if signed => { + let divisor = signed_bigint(&r, rhs_width); + if divisor == BigInt::from(0u8) { + TestbenchValue::U64(0) + } else { + let remainder = signed_bigint(&l, lhs_width) % divisor; + tb_value_from_bits(signed_bits(remainder, result_width), result_width) + } + } + Op::Rem => { + if rb == BigUint::ZERO { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb % rb, result_width) + } + } + Op::Pow => { + if result_width == 0 { + TestbenchValue::U64(0) + } else { + let modulus = BigUint::from(1u8) << result_width; + tb_value_from_bits(lb.modpow(&rb, &modulus), result_width) + } + } + Op::BitAnd => tb_value_from_bits(lb & rb, result_width), + Op::BitOr => tb_value_from_bits(lb | rb, result_width), + Op::BitXor => tb_value_from_bits(lb ^ rb, result_width), + Op::BitXnor => tb_value_from_bits((lb ^ rb) ^ width_mask(result_width), result_width), + Op::LogicShiftL | Op::ArithShiftL => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + if shift >= result_width { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb << shift, result_width) + } + } + Op::LogicShiftR => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + if shift >= result_width { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb >> shift, result_width) + } + } + Op::ArithShiftR if lhs_signed => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + let value = signed_bigint(&l, lhs_width); + let shifted = if shift >= result_width { + if value.sign() == Sign::Minus { + BigInt::from(-1) + } else { + BigInt::from(0) + } + } else { + value >> shift + }; + tb_value_from_bits(signed_bits(shifted, result_width), result_width) + } + Op::ArithShiftR => { + let shift = rb.to_usize().unwrap_or(usize::MAX); + if shift >= result_width { + TestbenchValue::U64(0) + } else { + tb_value_from_bits(lb >> shift, result_width) + } + } + Op::BitNand => tb_value_from_bits((lb & rb) ^ width_mask(result_width), result_width), + Op::BitNor => tb_value_from_bits((lb | rb) ^ width_mask(result_width), result_width), + _ => unreachable!("operator is not a source-language binary op: {op:?}"), + } +} diff --git a/crates/celox-testbench/src/visit.rs b/crates/celox-testbench/src/visit.rs new file mode 100644 index 00000000000..5bf18035c28 --- /dev/null +++ b/crates/celox-testbench/src/visit.rs @@ -0,0 +1,204 @@ +//! Compiler traversal of expressions in a semantic testbench. +use crate::*; +impl TestbenchProgram { + pub fn try_visit_expressions( + &mut self, + mut visit: impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + fn target( + value: &mut TestbenchTarget, ExprBytecode>>, + visit: &mut impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + if let Some(selection) = &mut value.selection { + visit(&mut selection.offset)?; + } + Ok(()) + } + fn message( + value: &mut Option>>, + visit: &mut impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + if let Some(AssertMessage::Formatted { args, .. } | AssertMessage::DynamicArgs(args)) = + value + { + for argument in args { + visit(&mut argument.expr)?; + } + } + Ok(()) + } + fn block( + statements: &mut [SemanticStatement], + visit: &mut impl FnMut(&mut ExprBytecode>) -> Result<(), E>, + ) -> Result<(), E> { + for statement in statements { + match statement { + TestbenchStatement::ClockNext { count, .. } + | TestbenchStatement::ResetAssert { + duration: count, .. + } => { + if let ClockCount::Dynamic(expr) = count { + visit(expr)?; + } + } + TestbenchStatement::Assert { + expr, + message: value, + .. + } => { + visit(expr)?; + message(value, visit)?; + } + TestbenchStatement::Display { message: value, .. } => message(value, visit)?, + TestbenchStatement::If { + expr, + then_block, + else_block, + } => { + visit(expr)?; + block(then_block, visit)?; + block(else_block, visit)?; + } + TestbenchStatement::For { + start, end, body, .. + } => { + for bound in [start, end] { + if let LoopBound::Dynamic { expr, .. } = bound { + visit(expr)?; + } + } + block(body, visit)?; + } + TestbenchStatement::Assign { dst, expr } => { + visit(expr)?; + target(dst, visit)?; + } + TestbenchStatement::RandomSeed { value, .. } => visit(value)?, + TestbenchStatement::RandomGet { ret, .. } + | TestbenchStatement::RandomGetSeed { ret, .. } => { + if let Some(ret) = ret { + target(ret, visit)?; + } + } + TestbenchStatement::RandomGetRange { min, max, ret, .. } => { + visit(min)?; + visit(max)?; + if let Some(ret) = ret { + target(ret, visit)?; + } + } + TestbenchStatement::ComponentMethod { args, ret, .. } => { + for arg in args { + visit(&mut arg.expr)?; + } + if let Some(ret) = ret { + target(ret, visit)?; + } + } + TestbenchStatement::Break + | TestbenchStatement::Finish + | TestbenchStatement::WriteMemory { .. } => {} + } + } + Ok(()) + } + block(&mut self.statements, &mut visit)?; + for binding in &mut self.component_bindings { + for connection in &mut binding.connections { + if let Some(input) = &mut connection.input { + visit(input)?; + } + if let Some(input) = &mut connection.input_target { + target(input, &mut visit)?; + } + if let Some(output) = &mut connection.output { + target(output, &mut visit)?; + } + } + } + Ok(()) + } +} + +impl TestbenchProgram { + /// Fuse pure constant clock waits before assigning native request sites. + pub fn fold_clock_waits(&mut self) { + fn constant(expr: &ExprBytecode>) -> Option { + expr.kernel() + .and_then(|kernel| kernel.constant) + .or_else(|| expr.literal_u64()) + } + fn bound(bound: &LoopBound>>) -> Option { + match bound { + LoopBound::Static(value) => Some(*value as u64), + LoopBound::Dynamic { + expr, + width, + signed, + } if *width <= 64 => { + let value = constant(expr)?; + (!*signed || (*width != 0 && value >> (width - 1) == 0)).then_some(value) + } + _ => None, + } + } + fn block(statements: &mut [SemanticStatement]) { + for statement in statements { + match statement { + TestbenchStatement::If { + then_block, + else_block, + .. + } => { + block(then_block); + block(else_block); + } + TestbenchStatement::For { + loop_var, + start, + end, + inclusive, + step, + step_op, + reverse, + body, + } => { + block(body); + if !*inclusive + && !*reverse + && *step == 1 + && step_op.is_none() + && let (Some(0), Some(iterations)) = (bound(start), bound(end)) + && let [ + TestbenchStatement::ClockNext { + clock_event, + count, + period, + }, + ] = body.as_slice() + && let Some(count) = match count { + ClockCount::Static(count) => Some(*count), + ClockCount::Dynamic(expr) => constant(expr), + } + && count != 0 + && iterations != 0 + && loop_var.as_ref().is_none_or(|(_, width, signed)| { + let bits = width.saturating_sub(usize::from(*signed)); + bits >= 64 || iterations < (1u64 << bits) + }) + && let Some(count) = iterations.checked_mul(count) + { + *statement = TestbenchStatement::ClockNext { + clock_event: *clock_event, + count: ClockCount::Static(count), + period: *period, + }; + } + } + _ => {} + } + } + } + block(&mut self.statements); + } +} diff --git a/crates/celox-testbench/src/vm.rs b/crates/celox-testbench/src/vm.rs deleted file mode 100644 index 291c45a81ce..00000000000 --- a/crates/celox-testbench/src/vm.rs +++ /dev/null @@ -1,1191 +0,0 @@ -use num_bigint::{BigInt, BigUint, Sign}; -use num_traits::ToPrimitive as _; - -use crate::{ExprBytecode, ExprOpcode as TbOpcode, TestbenchOperator as Op}; - -// ── Bytecode VM ──────────────────────────────────────────────────────── - -/// A compiled expression: flat bytecode evaluated on a stack VM. -#[derive(Clone, Debug)] -pub struct CompiledExpr { - bytecode: ExprBytecode, - observes_hardware: bool, -} - -/// Stack value: integer bits or a dynamically sized byte string. -#[derive(Clone, Debug)] -pub enum TestbenchValue { - U64(u64), - Wide(BigUint), - String(Vec), -} - -// Most expressions need only two or three operands. Keep their stack local; -// deeply nested expressions can still spill without imposing a depth limit. -struct ValueStack { - inline: [Option; 8], - len: usize, - spill: Vec, -} - -impl ValueStack { - fn new() -> Self { - Self { - inline: [const { None }; 8], - len: 0, - spill: Vec::new(), - } - } - - fn push(&mut self, value: TestbenchValue) { - if self.len < self.inline.len() { - self.inline[self.len] = Some(value); - } else { - self.spill.push(value); - } - self.len += 1; - } - - fn pop(&mut self) -> Option { - self.len = self.len.checked_sub(1)?; - if self.len < self.inline.len() { - self.inline[self.len].take() - } else { - self.spill.pop() - } - } - - fn last_mut(&mut self) -> Option<&mut TestbenchValue> { - if self.len <= self.inline.len() { - self.inline.get_mut(self.len.checked_sub(1)?)?.as_mut() - } else { - self.spill.last_mut() - } - } -} - -impl TestbenchValue { - #[inline] - pub fn to_u64(&self) -> u64 { - match self { - TestbenchValue::String(v) => v - .iter() - .rev() - .take(8) - .enumerate() - .fold(0, |value, (i, byte)| value | (u64::from(*byte) << (i * 8))), - TestbenchValue::U64(v) => *v, - TestbenchValue::Wide(v) => { - let digits = v.to_u64_digits(); - digits.first().copied().unwrap_or(0) - } - } - } - - #[inline] - pub fn is_zero(&self) -> bool { - match self { - TestbenchValue::String(v) => v.is_empty(), - TestbenchValue::U64(v) => *v == 0, - TestbenchValue::Wide(v) => *v == BigUint::ZERO, - } - } - - #[inline] - pub fn to_biguint(&self) -> BigUint { - match self { - TestbenchValue::String(v) => BigUint::from_bytes_be(v), - TestbenchValue::U64(v) => BigUint::from(*v), - TestbenchValue::Wide(v) => v.clone(), - } - } -} - -impl CompiledExpr { - pub fn new(bytecode: ExprBytecode) -> Self { - Self { - bytecode, - observes_hardware: true, - } - } - - /// Classify reads after binding against the hardware's state objects. - /// Include stores conservatively: a function expression can overwrite - /// an RTL result as well as read it. - pub fn classify_hardware_access(mut self, mut hardware: impl FnMut(usize) -> bool) -> Self { - self.observes_hardware = self.bytecode.ops().iter().any(|op| match op { - TbOpcode::LoadU64 { location, .. } - | TbOpcode::LoadWide { location, .. } - | TbOpcode::LoadIndexed { location, .. } - | TbOpcode::LoadBitSelect { location, .. } - | TbOpcode::LoadString { location, .. } - | TbOpcode::StoreString { location, .. } - | TbOpcode::StoreU64 { location, .. } => hardware(*location), - _ => false, - }); - self - } - - /// Whether evaluating this expression can observe an RTL-written object. - /// Unclassified expressions conservatively return true. - pub fn observes_hardware(&self) -> bool { - self.observes_hardware - } - - /// Evaluate against raw simulator memory, returning the result as u64. - /// For wide results, returns the low 64 bits. - pub fn eval_u64(&self, memory: *mut u8) -> u64 { - self.eval(memory).to_u64() - } - - /// Evaluate and return the full `TestbenchValue` (preserves wide results). - pub fn eval_value(&self, memory: *mut u8) -> TestbenchValue { - self.eval(memory) - } - - pub fn eval_bool(&self, memory: *mut u8) -> bool { - !self.eval(memory).is_zero() - } - - /// Returns the value when this expression does not read simulator memory. - pub fn constant_u64(&self) -> Option { - if self.bytecode.ops().iter().any(|op| { - matches!( - op, - TbOpcode::StoreString { .. } - | TbOpcode::LoadString { .. } - | TbOpcode::LoadU64 { .. } - | TbOpcode::LoadWide { .. } - | TbOpcode::LoadIndexed { .. } - | TbOpcode::LoadBitSelect { .. } - | TbOpcode::StoreU64 { .. } - ) - }) { - return None; - } - Some(self.eval_u64(std::ptr::null_mut())) - } - - /// Core evaluation loop. Uses `TestbenchValue` to handle both u64 and wide - /// signals on a single stack. The common case (all ≤64-bit operands) - /// stays in the `TestbenchValue::U64` variant and never allocates. - fn eval(&self, memory: *mut u8) -> TestbenchValue { - self.eval_value_with_write_observer(memory, |_, _| {}) - } - - /// Evaluate with a notification for each executed memory write. Expression - /// function calls can store arguments and results; ordinary reads do not - /// notify the observer or require a retained mutable view of the image. - pub fn eval_value_with_write_observer( - &self, - memory: *mut u8, - on_write: impl FnMut(usize, usize), - ) -> TestbenchValue { - self.eval_with_heap(memory, None, on_write) - } - - fn eval_leaf(&self, memory: *mut u8) -> Option { - match self.bytecode.ops() { - [TbOpcode::ConstU64(value)] => Some(TestbenchValue::U64(*value)), - [ - TbOpcode::LoadU64 { - location, - byte_size, - mask, - }, - ] => { - // SAFETY: bound bytecode addresses valid simulator memory. - Some(TestbenchValue::U64( - unsafe { read_le_u64(memory.add(*location), *byte_size) } & mask, - )) - } - _ => None, - } - } - - /// Evaluate with the simulator's heap, which string variables refer to. - /// Without a heap, string variables read as `""` and string stores are - /// dropped instead of writing a handle no heap knows. - pub fn eval_with_heap( - &self, - memory: *mut u8, - mut heap: Option<&mut celox_heap::Heap>, - mut on_write: impl FnMut(usize, usize), - ) -> TestbenchValue { - if let Some(value) = self.eval_leaf(memory) { - return value; - } - let mut stack = ValueStack::new(); - let mut pc: usize = 0; - let ops = self.bytecode.ops(); - - while pc < ops.len() { - self.exec_at(ops, &mut pc, &mut stack, memory, &mut heap, &mut on_write); - } - stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: stack empty after evaluation"); - TestbenchValue::U64(0) - }) - } - - /// Execute the opcode at `pc` and advance `pc` past it. - /// Handles all opcodes including `Ternary` (with recursive sub-block - /// evaluation), so there is no separate `step()` function. - fn exec_at( - &self, - ops: &[TbOpcode], - pc: &mut usize, - stack: &mut ValueStack, - memory: *mut u8, - heap: &mut Option<&mut celox_heap::Heap>, - on_write: &mut impl FnMut(usize, usize), - ) { - match &ops[*pc] { - TbOpcode::ConstString(value) => { - stack.push(TestbenchValue::String(value.clone())); - *pc += 1; - } - TbOpcode::LoadString { location, elements } => { - let index = stack.pop().expect("string element offset").to_u64() as usize - / celox_design::HANDLE_WIDTH; - let value = match heap { - Some(heap) if index < *elements => { - let offset = location + index * celox_heap::HANDLE_BYTES; - // SAFETY: bound bytecode addresses a handle slot of - // `elements` handles in this memory image. - let handle = unsafe { read_handle(memory, offset) }; - heap.string(handle).to_vec() - } - _ => Vec::new(), - }; - stack.push(TestbenchValue::String(value)); - *pc += 1; - } - TbOpcode::StoreString { location } => { - let TestbenchValue::String(value) = stack.pop().expect("string store value") else { - unreachable!("string store requires a string value"); - }; - if let Some(heap) = heap { - let handle = heap.intern(&value); - // SAFETY: bound bytecode addresses a handle slot in this - // memory image. - unsafe { - std::ptr::copy_nonoverlapping( - handle.to_le_bytes().as_ptr(), - memory.add(*location), - celox_heap::HANDLE_BYTES, - ); - } - on_write(*location, celox_heap::HANDLE_BYTES); - } - *pc += 1; - } - TbOpcode::ConstU64(v) => { - stack.push(TestbenchValue::U64(*v)); - *pc += 1; - } - TbOpcode::ConstWide(v) => { - stack.push(TestbenchValue::Wide(v.clone())); - *pc += 1; - } - TbOpcode::LoadU64 { - location, - byte_size, - mask, - } => { - // SAFETY: caller guarantees `memory` is valid simulator memory - let val = unsafe { read_le_u64(memory.add(*location), *byte_size) } & mask; - stack.push(TestbenchValue::U64(val)); - *pc += 1; - } - TbOpcode::LoadWide { - location, - byte_size, - width, - } => { - let val = unsafe { read_le_wide(memory.add(*location), *byte_size, *width) }; - stack.push(TestbenchValue::Wide(val)); - *pc += 1; - } - TbOpcode::BinOp(op) => { - let r = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: BinOp rhs underflow"); - TestbenchValue::U64(0) - }); - let l = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: BinOp lhs underflow"); - TestbenchValue::U64(0) - }); - stack.push(eval_binop(l, *op, r)); - *pc += 1; - } - TbOpcode::FloatBinary { op, precision } => { - let r = stack.pop().unwrap_or(TestbenchValue::U64(0)); - let l = stack.pop().unwrap_or(TestbenchValue::U64(0)); - stack.push(TestbenchValue::U64(celox_design::eval_float_binary( - *op, - *precision, - l.to_u64(), - r.to_u64(), - ))); - *pc += 1; - } - TbOpcode::FloatUnary { op, precision } => { - if let Some(top) = stack.last_mut() { - *top = TestbenchValue::U64(celox_design::eval_float_unary( - *op, - *precision, - top.to_u64(), - )); - } - *pc += 1; - } - TbOpcode::TypedBinOp { - op, - lhs_width, - rhs_width, - result_width, - lhs_signed, - rhs_signed, - } => { - let r = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: TypedBinOp rhs underflow"); - TestbenchValue::U64(0) - }); - let l = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: TypedBinOp lhs underflow"); - TestbenchValue::U64(0) - }); - stack.push(eval_typed_binop( - l, - *op, - r, - *lhs_width, - *rhs_width, - *result_width, - *lhs_signed, - *rhs_signed, - )); - *pc += 1; - } - TbOpcode::TypedUnary { - op, - operand_width, - result_width, - } => { - if let Some(top) = stack.last_mut() { - *top = eval_typed_unop(*op, top, *operand_width, *result_width); - } else { - debug_assert!(false, "testbench bytecode: TypedUnary underflow"); - } - *pc += 1; - } - TbOpcode::Resize { - source_width, - target_width, - signed, - } => { - if let Some(top) = stack.last_mut() { - *top = resize_tb_value(top, *source_width, *target_width, *signed); - } else { - debug_assert!(false, "testbench bytecode: Resize underflow"); - } - *pc += 1; - } - TbOpcode::ConcatPart { - part_width, - result_width, - } => { - let part = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: ConcatPart value underflow"); - TestbenchValue::U64(0) - }); - let accumulator = stack.pop().unwrap_or_else(|| { - debug_assert!( - false, - "testbench bytecode: ConcatPart accumulator underflow" - ); - TestbenchValue::U64(0) - }); - if let (TestbenchValue::U64(accumulator), TestbenchValue::U64(part)) = - (&accumulator, &part) - && *result_width <= 64 - { - let shifted = if *part_width >= 64 { - 0 - } else { - accumulator << part_width - }; - stack.push(TestbenchValue::U64( - shifted | (part & width_mask_u64(*part_width)), - )); - } else { - let value = (accumulator.to_biguint() << part_width) - | normalized_bits(&part, *part_width); - stack.push(tb_value_from_bits(value, *result_width)); - } - *pc += 1; - } - TbOpcode::Ternary { then_len, else_len } => { - let cond = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: Ternary cond underflow"); - TestbenchValue::U64(0) - }); - *pc += 1; // skip past Ternary opcode - if !cond.is_zero() { - let then_end = *pc + then_len; - while *pc < then_end { - self.exec_at(ops, pc, stack, memory, heap, on_write); - } - *pc += else_len; // skip else block - } else { - *pc += then_len; // skip then block - let else_end = *pc + else_len; - while *pc < else_end { - self.exec_at(ops, pc, stack, memory, heap, on_write); - } - } - } - TbOpcode::LoadIndexed { - location, - stride_bits, - base_bit_offset, - element_width, - } => { - let idx = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: LoadIndexed underflow"); - TestbenchValue::U64(0) - }); - let i = idx.to_u64() as usize; - let bit_offset = base_bit_offset.saturating_add(i.saturating_mul(*stride_bits)); - let val = unsafe { read_bits(memory.add(*location), bit_offset, *element_width) }; - stack.push(val); - *pc += 1; - } - TbOpcode::LoadBitSelect { - location, - base_byte_size, - select_width, - } => { - let bit_idx = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: LoadBitSelect underflow"); - TestbenchValue::U64(0) - }); - let shift = bit_idx.to_u64() as usize; - if *base_byte_size <= 8 && *select_width <= 64 { - let full_val = unsafe { read_le_u64(memory.add(*location), *base_byte_size) }; - let mask = if *select_width == 64 { - u64::MAX - } else { - (1u64 << select_width) - 1 - }; - stack.push(TestbenchValue::U64((full_val >> shift) & mask)); - } else { - let full_width = base_byte_size.saturating_mul(8); - let full_val = - unsafe { read_le_wide(memory.add(*location), *base_byte_size, full_width) }; - let val = (full_val >> shift) & width_mask(*select_width); - stack.push(tb_value_from_bits(val, *select_width)); - } - *pc += 1; - } - TbOpcode::StoreU64 { - location, - byte_size, - } => { - let val = stack.pop().unwrap_or_else(|| { - debug_assert!(false, "testbench bytecode: StoreU64 underflow"); - TestbenchValue::U64(0) - }); - let v = val.to_u64(); - let bytes = v.to_le_bytes(); - let n = (*byte_size).min(8); - unsafe { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), memory.add(*location), n); - } - on_write(*location, n); - *pc += 1; - } - } - } -} - -/// # Safety -/// `ptr` must be valid for `byte_size` bytes of read access. -#[inline(always)] -unsafe fn read_le_u64(ptr: *const u8, byte_size: usize) -> u64 { - let mut buf = [0u8; 8]; - unsafe { - std::ptr::copy_nonoverlapping(ptr, buf.as_mut_ptr(), byte_size.min(8)); - } - u64::from_le_bytes(buf) -} - -/// # Safety -/// `ptr` must be valid for `byte_size` bytes of read access. -unsafe fn read_le_wide(ptr: *const u8, byte_size: usize, width: usize) -> BigUint { - let mut buf = vec![0u8; byte_size]; - unsafe { - std::ptr::copy_nonoverlapping(ptr, buf.as_mut_ptr(), byte_size); - } - let mut val = BigUint::from_bytes_le(&buf); - let extra_bits = byte_size * 8 - width; - if extra_bits > 0 { - val &= (BigUint::from(1u32) << width) - BigUint::from(1u32); - } - val -} - -/// # Safety -/// `ptr` must be valid for the byte span containing `bit_offset..bit_offset + width`. -unsafe fn read_bits(ptr: *const u8, bit_offset: usize, width: usize) -> TestbenchValue { - let byte_offset = bit_offset / 8; - let sub = bit_offset % 8; - let span_width = sub.saturating_add(width); - let byte_size = span_width.div_ceil(8); - if span_width <= 64 { - let value = unsafe { read_le_u64(ptr.add(byte_offset), byte_size) } >> sub; - TestbenchValue::U64(value & width_mask_u64(width)) - } else { - let value = unsafe { read_le_wide(ptr.add(byte_offset), byte_size, span_width) } >> sub; - tb_value_from_bits(value & width_mask(width), width) - } -} - -// ── Typed evaluation ─────────────────────────────────────────────────── - -/// Binary operation on `TestbenchValue`. When both operands are `U64` the fast -/// path runs entirely in registers; otherwise we promote to `BigUint`. -#[inline] -fn eval_binop(l: TestbenchValue, op: Op, r: TestbenchValue) -> TestbenchValue { - match (&l, &r) { - (TestbenchValue::String(l), TestbenchValue::String(r)) => { - let result = match op { - Op::Eq => l == r, - Op::Ne => l != r, - Op::Less => l < r, - Op::LessEq => l <= r, - Op::Greater => l > r, - Op::GreaterEq => l >= r, - _ => unreachable!("invalid string operator: {op:?}"), - }; - TestbenchValue::U64(u64::from(result)) - } - (TestbenchValue::U64(lv), TestbenchValue::U64(rv)) => { - TestbenchValue::U64(eval_binop_u64(*lv, op, *rv)) - } - _ => { - let lv = l.to_biguint(); - let rv = r.to_biguint(); - // Comparison / logic ops always return u64 - match op { - Op::Eq - | Op::Ne - | Op::Less - | Op::LessEq - | Op::Greater - | Op::GreaterEq - | Op::LogicAnd - | Op::LogicOr => TestbenchValue::U64(eval_binop_wide_cmp(&lv, op, &rv)), - _ => TestbenchValue::Wide(eval_binop_wide(lv, op, rv)), - } - } - } -} - -fn width_mask(width: usize) -> BigUint { - if width == 0 { - BigUint::ZERO - } else { - (BigUint::from(1u8) << width) - BigUint::from(1u8) - } -} - -#[inline] -fn width_mask_u64(width: usize) -> u64 { - match width { - 0 => 0, - 1..=63 => (1u64 << width) - 1, - _ => u64::MAX, - } -} - -#[inline] -fn signed_i128(value: u64, width: usize) -> i128 { - let value = value & width_mask_u64(width); - if width == 0 || width >= 64 { - (value as i64) as i128 - } else if value & (1u64 << (width - 1)) == 0 { - value as i128 - } else { - value as i128 - (1i128 << width) - } -} - -fn normalized_bits(value: &TestbenchValue, width: usize) -> BigUint { - value.to_biguint() & width_mask(width) -} - -fn tb_value_from_bits(value: BigUint, width: usize) -> TestbenchValue { - let value = value & width_mask(width); - if width <= 64 { - TestbenchValue::U64(value.to_u64().unwrap_or(0)) - } else { - TestbenchValue::Wide(value) - } -} - -fn signed_bigint(value: &TestbenchValue, width: usize) -> BigInt { - let raw = normalized_bits(value, width); - if width == 0 || !raw.bit((width - 1) as u64) { - BigInt::from(raw) - } else { - BigInt::from(raw) - (BigInt::from(1u8) << width) - } -} - -fn signed_bits(value: BigInt, width: usize) -> BigUint { - if width == 0 { - return BigUint::ZERO; - } - let modulus = BigUint::from(1u8) << width; - match value.sign() { - Sign::Minus => { - let magnitude = (-value).to_biguint().unwrap_or_default() % &modulus; - if magnitude == BigUint::ZERO { - BigUint::ZERO - } else { - modulus - magnitude - } - } - _ => value.to_biguint().unwrap_or_default() % modulus, - } -} - -fn resize_tb_value( - value: &TestbenchValue, - source_width: usize, - target_width: usize, - signed: bool, -) -> TestbenchValue { - if target_width == 0 { - return TestbenchValue::U64(0); - } - if source_width == 0 { - let fill = if value.to_u64() & 1 == 0 { - BigUint::ZERO - } else { - width_mask(target_width) - }; - return tb_value_from_bits(fill, target_width); - } - - if let TestbenchValue::U64(value) = value - && source_width <= 64 - && target_width <= 64 - { - let mut value = value & width_mask_u64(source_width); - if target_width > source_width && signed && value & (1u64 << (source_width - 1)) != 0 { - value |= width_mask_u64(target_width) ^ width_mask_u64(source_width); - } - return TestbenchValue::U64(value & width_mask_u64(target_width)); - } - - let mut value = normalized_bits(value, source_width); - if target_width > source_width && signed && value.bit((source_width - 1) as u64) { - value |= width_mask(target_width) ^ width_mask(source_width); - } - tb_value_from_bits(value, target_width) -} - -fn eval_typed_binop_u64( - l: u64, - op: Op, - r: u64, - lhs_width: usize, - rhs_width: usize, - result_width: usize, - lhs_signed: bool, - rhs_signed: bool, -) -> u64 { - let l = l & width_mask_u64(lhs_width); - let r = r & width_mask_u64(rhs_width); - let result_mask = width_mask_u64(result_width); - let signed = lhs_signed && rhs_signed; - let bool_value = |value: bool| u64::from(value); - - match op { - Op::Eq | Op::EqWildcard => bool_value(l == r), - Op::Ne | Op::NeWildcard => bool_value(l != r), - Op::Less if signed => bool_value(signed_i128(l, lhs_width) < signed_i128(r, rhs_width)), - Op::Less => bool_value(l < r), - Op::LessEq if signed => bool_value(signed_i128(l, lhs_width) <= signed_i128(r, rhs_width)), - Op::LessEq => bool_value(l <= r), - Op::Greater if signed => bool_value(signed_i128(l, lhs_width) > signed_i128(r, rhs_width)), - Op::Greater => bool_value(l > r), - Op::GreaterEq if signed => { - bool_value(signed_i128(l, lhs_width) >= signed_i128(r, rhs_width)) - } - Op::GreaterEq => bool_value(l >= r), - Op::LogicAnd => bool_value(l != 0 && r != 0), - Op::LogicOr => bool_value(l != 0 || r != 0), - Op::Add => l.wrapping_add(r) & result_mask, - Op::Sub => l.wrapping_sub(r) & result_mask, - Op::Mul => l.wrapping_mul(r) & result_mask, - Op::Div if signed => { - let divisor = signed_i128(r, rhs_width); - if divisor == 0 { - 0 - } else { - (signed_i128(l, lhs_width) / divisor) as u64 & result_mask - } - } - Op::Div => l.checked_div(r).unwrap_or(0) & result_mask, - Op::Rem if signed => { - let divisor = signed_i128(r, rhs_width); - if divisor == 0 { - 0 - } else { - (signed_i128(l, lhs_width) % divisor) as u64 & result_mask - } - } - Op::Rem => l.checked_rem(r).unwrap_or(0) & result_mask, - Op::Pow => { - let mut exponent = r; - let mut base = l & result_mask; - let mut value = 1u64 & result_mask; - while exponent != 0 { - if exponent & 1 != 0 { - value = ((value as u128 * base as u128) as u64) & result_mask; - } - exponent >>= 1; - if exponent != 0 { - base = ((base as u128 * base as u128) as u64) & result_mask; - } - } - value - } - Op::BitAnd => (l & r) & result_mask, - Op::BitOr => (l | r) & result_mask, - Op::BitXor => (l ^ r) & result_mask, - Op::BitXnor => (!(l ^ r)) & result_mask, - Op::BitNand => (!(l & r)) & result_mask, - Op::BitNor => (!(l | r)) & result_mask, - Op::LogicShiftL | Op::ArithShiftL => { - if r >= result_width as u64 { - 0 - } else { - l.wrapping_shl(r as u32) & result_mask - } - } - Op::LogicShiftR => { - if r >= result_width as u64 { - 0 - } else { - (l >> r) & result_mask - } - } - Op::ArithShiftR if lhs_signed => { - let value = signed_i128(l, lhs_width); - if r >= result_width as u64 { - if value < 0 { result_mask } else { 0 } - } else { - ((value >> r) as u64) & result_mask - } - } - Op::ArithShiftR => { - if r >= result_width as u64 { - 0 - } else { - (l >> r) & result_mask - } - } - _ => unreachable!("operator is not a source-language binary op: {op:?}"), - } -} - -fn eval_typed_binop( - l: TestbenchValue, - op: Op, - r: TestbenchValue, - lhs_width: usize, - rhs_width: usize, - result_width: usize, - lhs_signed: bool, - rhs_signed: bool, -) -> TestbenchValue { - if let (TestbenchValue::U64(l), TestbenchValue::U64(r)) = (&l, &r) - && lhs_width <= 64 - && rhs_width <= 64 - && result_width <= 64 - { - return TestbenchValue::U64(eval_typed_binop_u64( - *l, - op, - *r, - lhs_width, - rhs_width, - result_width, - lhs_signed, - rhs_signed, - )); - } - let lb = normalized_bits(&l, lhs_width); - let rb = normalized_bits(&r, rhs_width); - let signed = lhs_signed && rhs_signed; - - let comparison = |value: bool| TestbenchValue::U64(u64::from(value)); - match op { - Op::Eq | Op::EqWildcard => comparison(lb == rb), - Op::Ne | Op::NeWildcard => comparison(lb != rb), - Op::Less if signed => { - comparison(signed_bigint(&l, lhs_width) < signed_bigint(&r, rhs_width)) - } - Op::Less => comparison(lb < rb), - Op::LessEq if signed => { - comparison(signed_bigint(&l, lhs_width) <= signed_bigint(&r, rhs_width)) - } - Op::LessEq => comparison(lb <= rb), - Op::Greater if signed => { - comparison(signed_bigint(&l, lhs_width) > signed_bigint(&r, rhs_width)) - } - Op::Greater => comparison(lb > rb), - Op::GreaterEq if signed => { - comparison(signed_bigint(&l, lhs_width) >= signed_bigint(&r, rhs_width)) - } - Op::GreaterEq => comparison(lb >= rb), - Op::LogicAnd => comparison(lb != BigUint::ZERO && rb != BigUint::ZERO), - Op::LogicOr => comparison(lb != BigUint::ZERO || rb != BigUint::ZERO), - Op::Add => tb_value_from_bits(lb + rb, result_width), - Op::Sub => tb_value_from_bits( - signed_bits(BigInt::from(lb) - BigInt::from(rb), result_width), - result_width, - ), - Op::Mul => tb_value_from_bits(lb * rb, result_width), - Op::Div if signed => { - let divisor = signed_bigint(&r, rhs_width); - if divisor == BigInt::from(0u8) { - TestbenchValue::U64(0) - } else { - let quotient = signed_bigint(&l, lhs_width) / divisor; - tb_value_from_bits(signed_bits(quotient, result_width), result_width) - } - } - Op::Div => { - if rb == BigUint::ZERO { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb / rb, result_width) - } - } - Op::Rem if signed => { - let divisor = signed_bigint(&r, rhs_width); - if divisor == BigInt::from(0u8) { - TestbenchValue::U64(0) - } else { - let remainder = signed_bigint(&l, lhs_width) % divisor; - tb_value_from_bits(signed_bits(remainder, result_width), result_width) - } - } - Op::Rem => { - if rb == BigUint::ZERO { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb % rb, result_width) - } - } - Op::Pow => { - if result_width == 0 { - TestbenchValue::U64(0) - } else { - let modulus = BigUint::from(1u8) << result_width; - tb_value_from_bits(lb.modpow(&rb, &modulus), result_width) - } - } - Op::BitAnd => tb_value_from_bits(lb & rb, result_width), - Op::BitOr => tb_value_from_bits(lb | rb, result_width), - Op::BitXor => tb_value_from_bits(lb ^ rb, result_width), - Op::BitXnor => tb_value_from_bits((lb ^ rb) ^ width_mask(result_width), result_width), - Op::LogicShiftL | Op::ArithShiftL => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - if shift >= result_width { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb << shift, result_width) - } - } - Op::LogicShiftR => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - if shift >= result_width { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb >> shift, result_width) - } - } - Op::ArithShiftR if lhs_signed => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - let value = signed_bigint(&l, lhs_width); - let shifted = if shift >= result_width { - if value.sign() == Sign::Minus { - BigInt::from(-1) - } else { - BigInt::from(0) - } - } else { - value >> shift - }; - tb_value_from_bits(signed_bits(shifted, result_width), result_width) - } - Op::ArithShiftR => { - let shift = rb.to_usize().unwrap_or(usize::MAX); - if shift >= result_width { - TestbenchValue::U64(0) - } else { - tb_value_from_bits(lb >> shift, result_width) - } - } - Op::BitNand => tb_value_from_bits((lb & rb) ^ width_mask(result_width), result_width), - Op::BitNor => tb_value_from_bits((lb | rb) ^ width_mask(result_width), result_width), - _ => unreachable!("operator is not a source-language binary op: {op:?}"), - } -} - -fn eval_typed_unop( - op: Op, - value: &TestbenchValue, - operand_width: usize, - result_width: usize, -) -> TestbenchValue { - if let TestbenchValue::U64(value) = value - && operand_width <= 64 - && result_width <= 64 - { - let bits = value & width_mask_u64(operand_width); - let value = match op { - Op::LogicNot => u64::from(bits == 0), - Op::BitAnd => u64::from(bits == width_mask_u64(operand_width)), - Op::BitNand => u64::from(bits != width_mask_u64(operand_width)), - Op::BitOr => u64::from(bits != 0), - Op::BitNor => u64::from(bits == 0), - Op::BitXor => u64::from(!bits.count_ones().is_multiple_of(2)), - Op::BitXnor => u64::from(bits.count_ones().is_multiple_of(2)), - Op::Add => bits & width_mask_u64(result_width), - Op::Sub => bits.wrapping_neg() & width_mask_u64(result_width), - Op::BitNot => !bits & width_mask_u64(result_width), - _ => unreachable!("operator is not a source-language unary op: {op:?}"), - }; - return TestbenchValue::U64(value); - } - - let bits = normalized_bits(value, operand_width); - let reduced = match op { - Op::LogicNot => Some(bits == BigUint::ZERO), - Op::BitAnd => Some(bits == width_mask(operand_width)), - Op::BitNand => Some(bits != width_mask(operand_width)), - Op::BitOr => Some(bits != BigUint::ZERO), - Op::BitNor => Some(bits == BigUint::ZERO), - Op::BitXor | Op::BitXnor => { - let odd = bits.iter_u64_digits().map(u64::count_ones).sum::() % 2 != 0; - Some(if matches!(op, Op::BitXor) { odd } else { !odd }) - } - _ => None, - }; - if let Some(value) = reduced { - return TestbenchValue::U64(u64::from(value)); - } - - match op { - Op::Add => tb_value_from_bits(bits, result_width), - Op::Sub => tb_value_from_bits(signed_bits(-BigInt::from(bits), result_width), result_width), - Op::BitNot => tb_value_from_bits(bits ^ width_mask(operand_width), result_width), - _ => unreachable!("operator is not a source-language unary op: {op:?}"), - } -} - -#[inline] -fn eval_binop_u64(l: u64, op: Op, r: u64) -> u64 { - match op { - Op::Add => l.wrapping_add(r), - Op::Sub => l.wrapping_sub(r), - Op::Mul => l.wrapping_mul(r), - Op::Div => l.checked_div(r).unwrap_or(0), - Op::Rem => l.checked_rem(r).unwrap_or(0), - Op::BitAnd => l & r, - Op::BitOr => l | r, - Op::BitXor => l ^ r, - Op::LogicShiftL => { - if r >= 64 { - 0 - } else { - l << r - } - } - Op::LogicShiftR => { - if r >= 64 { - 0 - } else { - l >> r - } - } - Op::ArithShiftL => { - if r >= 64 { - 0 - } else { - l << r - } - } - Op::ArithShiftR => { - if r >= 64 { - ((l as i64) >> 63) as u64 - } else { - ((l as i64) >> r) as u64 - } - } - Op::Eq => (l == r) as u64, - Op::Ne => (l != r) as u64, - Op::Less => (l < r) as u64, - Op::LessEq => (l <= r) as u64, - Op::Greater => (l > r) as u64, - Op::GreaterEq => (l >= r) as u64, - Op::LogicAnd => ((l != 0) && (r != 0)) as u64, - Op::LogicOr => ((l != 0) || (r != 0)) as u64, - _ => unreachable!("operator is not testbench bytecode plumbing: {op:?}"), - } -} - -fn eval_binop_wide(l: BigUint, op: Op, r: BigUint) -> BigUint { - match op { - Op::Add => l + r, - Op::Sub => { - if l >= r { - l - r - } else { - BigUint::ZERO - } - } - Op::Mul => l * r, - Op::Div => { - if r == BigUint::ZERO { - BigUint::ZERO - } else { - l / r - } - } - Op::Rem => { - if r == BigUint::ZERO { - BigUint::ZERO - } else { - l % r - } - } - Op::BitAnd => l & r, - Op::BitOr => l | r, - Op::BitXor => l ^ r, - Op::LogicShiftL => { - let s: u64 = (&r).try_into().unwrap_or(256); - l << s - } - Op::LogicShiftR => { - let s: u64 = (&r).try_into().unwrap_or(256); - l >> s - } - _ => unreachable!("operator is not wide testbench bytecode plumbing: {op:?}"), - } -} - -fn eval_binop_wide_cmp(l: &BigUint, op: Op, r: &BigUint) -> u64 { - match op { - Op::Eq => (l == r) as u64, - Op::Ne => (l != r) as u64, - Op::Less => (l < r) as u64, - Op::LessEq => (l <= r) as u64, - Op::Greater => (l > r) as u64, - Op::GreaterEq => (l >= r) as u64, - Op::LogicAnd => ((*l != BigUint::ZERO) && (*r != BigUint::ZERO)) as u64, - Op::LogicOr => ((*l != BigUint::ZERO) || (*r != BigUint::ZERO)) as u64, - _ => unreachable!("operator is not testbench comparison plumbing: {op:?}"), - } -} - -/// Read the handle stored at `offset`. -/// -/// # Safety -/// -/// `memory + offset` must be valid for reading a handle. -unsafe fn read_handle(memory: *const u8, offset: usize) -> celox_heap::Handle { - let mut bytes = [0; celox_heap::HANDLE_BYTES]; - // SAFETY: guaranteed by the caller. - unsafe { - std::ptr::copy_nonoverlapping(memory.add(offset), bytes.as_mut_ptr(), bytes.len()); - } - celox_heap::Handle::from_le_bytes(bytes) -} - -#[cfg(test)] -mod float_tests { - use super::*; - use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp}; - - #[test] - fn expression_stack_spills_and_returns_to_inline_operands() { - for depth in [1, 8, 9, 32, 128] { - let mut ops: Vec<_> = (1..=depth).map(TbOpcode::ConstU64).collect(); - ops.extend((1..depth).map(|_| TbOpcode::BinOp(Op::Add))); - let expression = CompiledExpr::new(ExprBytecode::new(ops)); - assert_eq!( - expression.eval_u64(std::ptr::null_mut()), - depth * (depth + 1) / 2 - ); - } - let mut stack = ValueStack::new(); - for i in 0..20 { - stack.push(TestbenchValue::String(vec![i])); - } - for i in (0..20).rev() { - let Some(TestbenchValue::String(bytes)) = stack.last_mut() else { - panic!() - }; - bytes.push(i); - let Some(TestbenchValue::String(bytes)) = stack.pop() else { - panic!() - }; - assert_eq!(bytes, [i, i]); - } - assert!(stack.pop().is_none()); - assert!(stack.last_mut().is_none()); - assert!(stack.inline.iter().all(Option::is_none)); - } - - #[test] - fn floating_bytecode_keeps_precision_and_numeric_conversions() { - for (precision, expected) in [ - (FloatPrecision::F32, 16777216), - (FloatPrecision::F64, 16777217), - ] { - let expression = CompiledExpr::new(ExprBytecode::new(vec![ - TbOpcode::ConstU64(16777216), - TbOpcode::FloatUnary { - op: FloatUnaryOp::FromUnsigned { width: 32 }, - precision, - }, - TbOpcode::ConstU64(1), - TbOpcode::FloatUnary { - op: FloatUnaryOp::FromUnsigned { width: 32 }, - precision, - }, - TbOpcode::FloatBinary { - op: FloatBinaryOp::Add, - precision, - }, - TbOpcode::FloatUnary { - op: FloatUnaryOp::ToUnsigned { - width: 32, - round: true, - }, - precision, - }, - ])); - assert_eq!(expression.eval_u64(std::ptr::null_mut()), expected); - } - } -} diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 1140e4ac56d..ac0fd63b341 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -11,7 +11,7 @@ use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; // Concurrent assertion kernels suspend into Observed and Reactive regions. -const CONTAINER_VERSION: u16 = 52; +const CONTAINER_VERSION: u16 = 53; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/component.rs b/crates/celox/src/component.rs index 71356d5fc44..7e363ec1405 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -43,6 +43,10 @@ struct LiveInput { port: u32, expr: CompiledExpr, mask_source: Option>, + // Direct input bindings permit a chain of bitwise complements. Preserve + // the source payload under X/Z at the component ABI, even though HDL + // evaluation may canonicalize those unobservable payload bits. + invert_unknown_payload: bool, width: usize, } @@ -302,20 +306,22 @@ fn take_output_writes(component: &mut LiveComponent) -> Vec { fn stage_component_inputs(component: &mut LiveComponent, backend: &mut B) { for input in &component.inputs { - let value = eval_backend_expr(backend, &input.expr).to_biguint(); - let mask_xz = input - .mask_source - .as_ref() - .map(|source| { - let (_, mut mask) = backend.get_four_state(source.signal); - if let Some(selection) = &source.selection { - let offset = eval_backend_expr(backend, &selection.offset).to_u64() as usize; - mask >>= offset; - mask &= width_mask(selection.width); - } - mask - }) - .unwrap_or_default(); + let mut value = eval_backend_expr(backend, &input.expr).to_biguint(); + let mask_xz = if let Some(source) = &input.mask_source { + let (mut raw, mut mask) = backend.get_four_state(source.signal); + if let Some(selection) = &source.selection { + let offset = eval_backend_expr(backend, &selection.offset).to_u64() as usize; + raw = (raw >> offset) & width_mask(selection.width); + mask = (mask >> offset) & width_mask(selection.width); + } + if input.invert_unknown_payload { + raw ^= &mask; + } + value = (value & (width_mask(input.width) ^ &mask)) | (raw & &mask); + mask + } else { + num_bigint::BigUint::ZERO + }; let mut words: Vec<_> = value.iter_u64_digits().collect(); let mut mask_words: Vec<_> = mask_xz.iter_u64_digits().collect(); words.resize(input.width.div_ceil(64).max(1), 0); @@ -463,6 +469,33 @@ impl ComponentRuntime { port, expr: expr.clone(), mask_source: binding.input_target.clone(), + invert_unknown_payload: expr + .bytecode() + .ops() + .iter() + .rev() + .take_while(|op| { + matches!( + op, + celox_testbench::ExprOpcode::Resize { .. } + | celox_testbench::ExprOpcode::TypedUnary { + op: celox_testbench::TestbenchOperator::BitNot, + .. + } + ) + }) + .filter(|op| { + matches!( + op, + celox_testbench::ExprOpcode::TypedUnary { + op: celox_testbench::TestbenchOperator::BitNot, + .. + } + ) + }) + .count() + % 2 + != 0, width: connection.width as usize, }); if connection.is_clock || connection.is_reset { diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index c8e46388fbe..d0c490bd8cd 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -1,6 +1,4 @@ -use crate::HashMap; -#[cfg(feature = "host-runtime")] -use crate::HashSet; +use crate::{HashMap, HashSet}; pub use celox_design::PortTypeKind; pub(crate) use celox_design::{ AbsoluteAddrBase, BitAccess, InstanceId, ModuleId, RegionedAbsoluteAddrBase, @@ -109,6 +107,73 @@ impl std::ops::Deref for RuntimeDesign { } impl RuntimeDesign { + /// Add compiler-owned storage after source hierarchy projection. The slot + /// remains an ordinary state object for layout, roots, images and snapshots. + pub(crate) fn allocate_testbench_slot( + &mut self, + width: usize, + is_string: bool, + ) -> AbsoluteAddr { + let instance_id = *self + .instances + .keys() + .min() + .expect("testbench root instance"); + let object = self + .semantic + .state_objects + .keys() + .map(|a| a.var_id.0) + .max() + .unwrap_or(0) + + 1; + let source = self + .variables + .values() + .map(|v| v.source_id.0) + .max() + .unwrap_or(0) + + 1; + let address = AbsoluteAddr { + instance_id, + var_id: celox_design::StateObjectId(object), + }; + let source_id = SourceVarId(source); + let path = vec![format!("__celox_tb_{object}")]; + self.semantic.state_objects.insert( + address, + celox_design::VariableMetadata { + width: width.max(1), + is_4state: false, + kind: celox_design::DomainKind::Other, + type_kind: celox_design::PortTypeKind::Bit, + array_dims: vec![], + value_kind: if is_string { + celox_design::ValueKind::StrRef + } else { + Default::default() + }, + }, + ); + self.variables.insert( + address, + RuntimeVariable { + address, + source_id, + path: path.clone(), + var_kind: VariableKind::Variable, + signed: false, + packed_dims: vec![width.max(1)], + unpacked_ranges: vec![], + }, + ); + let instance = self.instances.get_mut(&instance_id).unwrap(); + instance.state_addresses.push(address); + instance.source_variables.insert(source_id, address); + // Compiler storage is deliberately absent from source lookup and VCD. + address + } + fn from_projection( semantic: celox_design::ElaboratedDesign, frontend: FrontendLookup, @@ -460,7 +525,6 @@ pub struct RuntimeProgram { pub testbench: Option>, /// Objects accessed by RTL before optimization. Retained so host-side /// testbench writes can distinguish private variables from hardware. - #[cfg(feature = "host-runtime")] pub(crate) rtl_accesses: HashSet, } @@ -845,7 +909,15 @@ fn rebuild_rtl_writes(program: &mut OptimizedSir) { .iter() .flat_map(|parallel| parallel.units().map(|unit| &unit.unit)), ) - .chain(&program.sir.processes) + .chain( + program + .sir + .processes + .iter() + .zip(&program.runtime.runtime_schema.processes) + .filter(|(_, slots)| slots.kind != celox_design::ProcessKind::Callable) + .map(|(unit, _)| unit), + ) { for block in unit.blocks.values() { for instruction in &block.instructions { @@ -1169,7 +1241,6 @@ impl RuntimeProgram { scheduled: celox_frontend_core::ScheduledRtl, ) -> Result<(SirProgram, Self), DesignProjectionError> { let design = RuntimeDesign::from_projection(scheduled.design, scheduled.frontend_lookup)?; - #[cfg(feature = "host-runtime")] let rtl_accesses = { let mut rtl_accesses = HashSet::default(); for unit in scheduled @@ -1212,7 +1283,6 @@ impl RuntimeProgram { design, runtime_schema: scheduled.runtime_schema, testbench: None, - #[cfg(feature = "host-runtime")] rtl_accesses, }, )) diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 646d3e33a05..5651b7fd33e 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -369,7 +369,7 @@ pub(crate) fn project_scheduled_rtl( diagnostics, )?; scheduled.scheduled.inject_triggers(); - let testbench = if let Some(testbench_source) = testbench_source { + let mut testbench = if let Some(testbench_source) = testbench_source { testbench_source.component_libraries = component_libraries; testbench_source.component_file_base = component_file_base; crate::testbench_compile::project_observability( @@ -386,10 +386,18 @@ pub(crate) fn project_scheduled_rtl( } else { None }; - let (sir, mut runtime) = + let (mut sir, mut runtime) = RuntimeProgram::from_scheduled(scheduled.scheduled).map_err(|error| { ParserError::illegal_context("runtime design projection", error.to_string(), None) })?; + if let Some(testbench) = &mut testbench { + crate::testbench_compile::lower_expressions(&mut sir, &mut runtime, testbench) + .and_then(|()| { + testbench.fold_clock_waits(); + crate::testbench_compile::lower_processes(&mut sir, &mut runtime, testbench) + }) + .map_err(|error| ParserError::illegal_context("testbench SIR lowering", error, None))?; + } runtime.testbench = testbench; dump_addr_map_if_requested(&runtime, diagnostics); Ok((sir, runtime)) diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index ca90b98db52..663dc69f43c 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -146,7 +146,9 @@ mod host { pub(crate) declaration_phase: bool, pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, - pub(crate) component_simulation: Option>, + // Temporarily detached while advancing the simulator. Keep the queue + // in place instead of copying its entire state at every clock edge. + pub(crate) component_simulation: Option>>, runtime_event_read_seq: Arc, runtime_event_drain_active: Arc, pub(super) comb_observer_snapshots: Vec, @@ -1580,6 +1582,17 @@ mod host { ) -> Vec { let queue = Arc::clone(&self.pending_host_events); let mut pending = queue.lock().unwrap(); + // Most clock boundaries produce no reports. Preserve queued host + // records, losses and deferred string snapshots, but avoid the + // collector and formatter when neither queue has any new work. + if pending.events.is_empty() + && pending.missed == 0 + && pending.deferred.waiting.is_empty() + && self.runtime_event_read_seq.load(Ordering::Acquire) + == self.runtime_event_write_seq() + { + return Vec::new(); + } pending.extend( self.collect_backend_runtime_events(), self.backend.layout().runtime_event_capacity, diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index bc349a8953d..fdfc0c6984c 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1,9 +1,9 @@ //! Native testbench execution for Veryl `#[test]` modules. //! -//! Testbench expressions are compiled to a flat bytecode (`TbOpcode`) and -//! evaluated by a stack-based VM that reads directly from the simulator's -//! memory buffer. Signals ≤64 bits use native `u64` arithmetic with zero -//! heap allocation; wider signals fall back to `BigUint`. +//! Processes and expressions execute generated host machine code. Persistent +//! continuations retain ordinary state slots across clock waits. Expressions +//! and loop arithmetic use the shared SIR backend; host requests provide timing, +//! diagnostics and external component services. use crate::HashMap; use crate::RuntimeErrorCode; @@ -20,19 +20,16 @@ pub use celox_testbench::SourceLocation; use celox_testbench::{ DisplayFormatArg, ExecutableArgument, ExecutableAssertMessage, ExecutableClockCount, ExecutableLoopBound, ExecutableStatement, ExecutableTestbench, FieldSpec, - TestbenchOperator as Op, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, - TestbenchValue as TbValue, format_veryl_display_arg, pad_veryl_field, + TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, TestbenchValue as TbValue, + format_veryl_display_arg, pad_veryl_field, }; -use num_bigint::{BigInt, BigUint, Sign}; -use num_traits::ToPrimitive as _; +use num_bigint::BigUint; use rand::{RngExt as _, SeedableRng as _}; use rand_pcg::Pcg64; use std::sync::atomic::{AtomicU64, Ordering}; -use std::{ - cell::RefCell, - future::Future, - task::{Context, Poll, Waker}, -}; +use std::task::Poll; + +mod native; // ── Public types ─────────────────────────────────────────────────────── @@ -85,8 +82,6 @@ enum TestbenchEvaluationError { #[source] source: RuntimeErrorCode, }, - #[error("dynamic signed for-loop bound exceeds host i128")] - SignedLoopBoundOutOfRange, } pub(crate) type TestbenchStatement = ExecutableStatement<::Event, SignalRef>; @@ -115,16 +110,32 @@ fn eval_backend_expr_tracked( backend: &mut B, expr: &celox_testbench::CompiledExpr, ) -> (TbValue, Vec<(usize, usize)>) { - // This pointer is used only during evaluation, never exposed to a host. - // Observe VM stores explicitly instead of disabling tracking for reads; - // they are marked once the heap is no longer borrowed. + let kernel = expr + .kernel() + .expect("expression was compiled before state layout"); + backend + .run_process(kernel.entry) + .unwrap_or_else(|error| panic!("testbench expression kernel: {error}")); let (memory, _) = backend.memory_as_ptr(); - let mut writes = Vec::new(); - let value = expr.eval_with_heap( - memory.cast_mut(), - Some(backend.heap_mut()), - |offset, len| writes.push((offset, len)), - ); + // The kernel result is an ordinary, layout-owned state slot. + let bytes = + unsafe { std::slice::from_raw_parts(memory.add(kernel.result), kernel.width.div_ceil(8)) }; + let value = if kernel.is_string { + let handle = + celox_heap::Handle::from_le_bytes(bytes.try_into().expect("string handle width")); + TbValue::String(backend.heap().string(handle as celox_heap::Handle).to_vec()) + } else if kernel.width <= 64 { + let mut value = [0u8; 8]; + value[..bytes.len()].copy_from_slice(bytes); + TbValue::U64(u64::from_le_bytes(value)) + } else { + TbValue::Wide(BigUint::from_bytes_le(bytes)) + }; + let writes = kernel + .writes + .iter() + .map(|(offset, size)| (*offset, *size)) + .collect::>(); if let Some(trace) = backend.layout().trace.as_ref() { for &(offset, len) in &writes { // SAFETY: bound bytecode writes valid locations in this image, and @@ -525,21 +536,14 @@ fn sign_extend_random(raw: u64, width: u32) -> i64 { enum ExecResult { Continue, - Break, Finished, Fail(String), } -impl ExecResult { - fn should_stop(&self) -> bool { - !matches!(self, ExecResult::Continue) - } -} - impl From for TestResult { fn from(r: ExecResult) -> Self { match r { - ExecResult::Continue | ExecResult::Break | ExecResult::Finished => TestResult::Pass, + ExecResult::Continue | ExecResult::Finished => TestResult::Pass, ExecResult::Fail(m) => TestResult::Fail(m), } } @@ -560,177 +564,6 @@ fn eval_clock_count( }) } -fn eval_loop_bound( - sim: &mut Simulator, - bound: &LoopBound, -) -> Result { - match bound { - // Unsigned Veryl constants are represented as typed Dynamic bytecode; - // Static retains signed induction-variable semantics. - LoopBound::Static(v) => Ok(EvaluatedLoopBound::Signed(*v as i128)), - LoopBound::Dynamic { - expr, - width, - signed, - } => { - settle_testbench_expr(sim, expr) - .map_err(|source| TestbenchEvaluationError::EvalComb { source })?; - let value = eval_expr(sim, expr); - if *signed { - decode_signed_loop_bound(value, *width) - } else { - match value { - TbValue::String(_) => unreachable!("string loop bound"), - TbValue::U64(v) => match usize::try_from(v) { - Ok(v) => Ok(EvaluatedLoopBound::Unsigned(v)), - Err(_) => Ok(EvaluatedLoopBound::UnsignedWide(BigUint::from(v))), - }, - TbValue::Wide(v) => match v.to_usize() { - Some(v) => Ok(EvaluatedLoopBound::Unsigned(v)), - None => Ok(EvaluatedLoopBound::UnsignedWide(v)), - }, - } - } - } - } -} - -enum EvaluatedLoopBound { - Unsigned(usize), - UnsignedWide(BigUint), - Signed(i128), - SignedWide(BigInt), -} - -fn decode_signed_loop_bound( - value: TbValue, - width: usize, -) -> Result { - let width = width.max(1); - match value { - TbValue::String(_) => unreachable!("string loop bound"), - TbValue::U64(v) => { - let raw = if width >= 64 { - v as u128 - } else { - (v as u128) & ((1u128 << width) - 1) - }; - Ok(EvaluatedLoopBound::Signed(sign_extend_u128(raw, width))) - } - TbValue::Wide(v) => { - if width > 128 { - let signed = sign_extend_biguint(v, width); - return Ok(match signed.to_i128() { - Some(v) => EvaluatedLoopBound::Signed(v), - None => EvaluatedLoopBound::SignedWide(signed), - }); - } - let raw = v - .to_u128() - .ok_or(TestbenchEvaluationError::SignedLoopBoundOutOfRange)?; - Ok(EvaluatedLoopBound::Signed(sign_extend_u128(raw, width))) - } - } -} - -fn sign_extend_u128(raw: u128, width: usize) -> i128 { - let width = width.max(1); - if width >= 128 { - raw as i128 - } else { - let sign_bit = 1u128 << (width - 1); - if raw & sign_bit == 0 { - raw as i128 - } else { - raw as i128 - ((1u128 << width) as i128) - } - } -} - -fn truncate_i128_to_width(value: i128, width: usize, signed: bool) -> i128 { - let width = width.max(1); - if width >= 128 { - return value; - } - let raw = (value as u128) & ((1u128 << width) - 1); - if signed { - sign_extend_u128(raw, width) - } else { - raw as i128 - } -} - -fn truncate_bigint_to_width(value: BigInt, width: usize, signed: bool) -> BigInt { - let width = width.max(1); - let modulus = BigInt::from(1u8) << width; - let mut wrapped = value % &modulus; - if wrapped.sign() == Sign::Minus { - wrapped += &modulus; - } - if signed && wrapped >= (BigInt::from(1u8) << (width - 1)) { - wrapped - modulus - } else { - wrapped - } -} - -fn advance_bigint_counter( - current: &BigInt, - step: usize, - step_op: Option, - reverse: bool, - width: usize, - signed: bool, -) -> BigInt { - let step_value = BigInt::from(step); - let raw = if reverse { - current - &step_value - } else { - match step_op { - Some(Op::Mul) => current * &step_value, - Some(Op::BitOr) => current | &step_value, - Some(Op::BitXor) => current ^ &step_value, - Some(Op::LogicShiftL | Op::ArithShiftL) => { - if step >= width.max(1) { - BigInt::from(0u8) - } else { - current << step - } - } - _ => current + &step_value, - } - }; - truncate_bigint_to_width(raw, width, signed) -} - -fn truncate_usize_to_width(value: usize, width: usize) -> usize { - if width >= usize::BITS as usize { - value - } else if width == 0 { - 0 - } else { - value & ((1usize << width) - 1) - } -} - -fn sign_extend_biguint(raw: BigUint, width: usize) -> BigInt { - let width = width.max(1); - let sign_bit = BigUint::from(1u8) << (width - 1); - if raw < sign_bit { - BigInt::from(raw) - } else { - BigInt::from(raw) - (BigInt::from(1u8) << width) - } -} - -fn mask_to_width(value: BigUint, width: usize) -> BigUint { - if width == 0 { - BigUint::from(0u8) - } else { - value & ((BigUint::from(1u8) << width) - BigUint::from(1u8)) - } -} - fn width_mask(width: usize) -> BigUint { if width == 0 { BigUint::from(0u8) @@ -739,35 +572,6 @@ fn width_mask(width: usize) -> BigUint { } } -fn sim_set_i128( - sim: &mut crate::Simulator, - sig: SignalRef, - width: usize, - value: i128, -) { - if width <= 64 { - sim_set_u64(sim, sig, value as u64); - } else if value >= 0 { - write_testbench_signal(sim, sig, |sim| { - sim.set_wide(sig, BigUint::from(value as u128)) - }); - } else { - let modulus = BigUint::from(1u8) << width; - let mag = BigUint::from(value.unsigned_abs()); - write_testbench_signal(sim, sig, |sim| sim.set_wide(sig, modulus - mag)); - } -} - -fn sim_set_biguint(sim: &mut crate::Simulator, sig: SignalRef, value: BigUint) { - if sig.width <= 64 { - sim_set_u64(sim, sig, value.to_u64().unwrap_or(0)); - } else { - write_testbench_signal(sim, sig, |sim| { - sim.set_wide(sig, mask_to_width(value, sig.width)) - }); - } -} - fn random_value_for_destination( value: u64, source_width: u32, @@ -801,428 +605,6 @@ fn sim_set_random_target( sim_set_target(sim, target, TbValue::Wide(value)); } -fn sim_set_bigint( - sim: &mut crate::Simulator, - sig: SignalRef, - width: usize, - value: BigInt, -) { - if width <= 128 { - sim_set_i128(sim, sig, width, value.try_into().unwrap_or(0)); - return; - } - if value.sign() != Sign::Minus { - sim_set_biguint( - sim, - sig, - value.try_into().unwrap_or_else(|_| BigUint::from(0u8)), - ); - } else { - let modulus = BigUint::from(1u8) << width; - sim_set_biguint(sim, sig, modulus - value.magnitude().clone()); - } -} - -fn as_bigint_bound(bound: &EvaluatedLoopBound) -> Option { - match bound { - EvaluatedLoopBound::Unsigned(v) => Some(BigInt::from(*v)), - EvaluatedLoopBound::UnsignedWide(v) => Some(BigInt::from(v.clone())), - EvaluatedLoopBound::Signed(v) => Some(BigInt::from(*v)), - EvaluatedLoopBound::SignedWide(v) => Some(v.clone()), - } -} - -fn exec_for_loop( - sim: &mut Simulator, - loop_var: &Option<(SignalRef, usize, bool)>, - start: &LoopBound, - end: &LoopBound, - inclusive: bool, - step: usize, - step_op: Option, - reverse: bool, - mut exec_body: impl FnMut(&mut Simulator) -> ExecResult, -) -> ExecResult { - let sim = RefCell::new(sim); - let mut future = std::pin::pin!(exec_for_loop_async( - &sim, - loop_var, - start, - end, - inclusive, - step, - step_op, - reverse, - || std::future::ready(exec_body(&mut sim.borrow_mut())), - )); - match future - .as_mut() - .poll(&mut Context::from_waker(Waker::noop())) - { - Poll::Ready(result) => result, - Poll::Pending => unreachable!("synchronous loop body cannot suspend"), - } -} - -async fn exec_for_loop_async>( - sim: &RefCell<&mut Simulator>, - loop_var: &Option<(SignalRef, usize, bool)>, - start: &LoopBound, - end: &LoopBound, - inclusive: bool, - step: usize, - step_op: Option, - reverse: bool, - mut exec_body: impl FnMut() -> F, -) -> ExecResult { - let continuation_bound = if reverse { start } else { end }; - let (bound_width, bound_signed) = match continuation_bound { - LoopBound::Static(value) => ( - (usize::BITS as usize - value.leading_zeros() as usize).max(32), - true, - ), - LoopBound::Dynamic { width, signed, .. } => (*width, *signed), - }; - let (counter_width, counter_signed) = loop_var - .as_ref() - .map_or((usize::BITS as usize, true), |(_, width, signed)| { - (*width, *signed) - }); - let comparison_signed = counter_signed && bound_signed; - let unsigned_value = |value: i128, width: usize| { - let mask = if width >= u128::BITS as usize { - u128::MAX - } else { - (1u128 << width.max(1)) - 1 - }; - (value as u128) & mask - }; - let in_range = |value: i128, limit: i128| { - if comparison_signed { - if reverse { - value >= limit - } else if inclusive { - value <= limit - } else { - value < limit - } - } else { - let value = unsigned_value(value, counter_width); - let limit = unsigned_value(limit, bound_width); - if reverse { - value >= limit - } else if inclusive { - value <= limit - } else { - value < limit - } - } - }; - - let mut start = match eval_loop_bound(&mut sim.borrow_mut(), start) { - Ok(v) => v, - Err(error) => return ExecResult::Fail(error.to_string()), - }; - let mut end = match eval_loop_bound(&mut sim.borrow_mut(), end) { - Ok(v) => v, - Err(error) => return ExecResult::Fail(error.to_string()), - }; - - let initially_wide = matches!(start, EvaluatedLoopBound::UnsignedWide(_)) - || matches!(end, EvaluatedLoopBound::UnsignedWide(_)) - || matches!(start, EvaluatedLoopBound::SignedWide(_)) - || matches!(end, EvaluatedLoopBound::SignedWide(_)); - if let Some((_, width, true)) = loop_var.as_ref() - && !initially_wide - { - let width = (*width).max(1); - let unsigned_max = if width <= usize::BITS as usize { - Some((1usize << (width - 1)) - 1) - } else { - None - }; - let unsigned_value = |bound: &EvaluatedLoopBound| match bound { - EvaluatedLoopBound::Unsigned(value) => Some(*value), - _ => None, - }; - let start_out_of_range = unsigned_max - .zip(unsigned_value(&start)) - .is_some_and(|(max, value)| value > max); - let end_out_of_range = - unsigned_max - .zip(unsigned_value(&end)) - .is_some_and(|(max, value)| { - value > max && !(!inclusive && value == max.saturating_add(1)) - }); - if start_out_of_range || end_out_of_range { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - start = match start { - EvaluatedLoopBound::Unsigned(value) => EvaluatedLoopBound::Signed(value as i128), - other => other, - }; - end = match end { - EvaluatedLoopBound::Unsigned(value) => EvaluatedLoopBound::Signed(value as i128), - other => other, - }; - } - - let has_unsigned_wide = matches!(start, EvaluatedLoopBound::UnsignedWide(_)) - || matches!(end, EvaluatedLoopBound::UnsignedWide(_)); - let has_signed_wide = matches!(start, EvaluatedLoopBound::SignedWide(_)) - || matches!(end, EvaluatedLoopBound::SignedWide(_)); - if has_unsigned_wide || has_signed_wide { - let start = as_bigint_bound(&start).expect("big loop bound"); - let end = as_bigint_bound(&end).expect("big loop bound"); - let mut step_body = |i: BigInt| { - if let Some((sig, width, _)) = loop_var { - sim_set_bigint(&mut sim.borrow_mut(), *sig, *width, i); - } - exec_body() - }; - if reverse { - if inclusive { - if end < start { - return ExecResult::Continue; - } - if end == start { - let (width, signed) = loop_var - .as_ref() - .map_or((usize::BITS as usize, false), |(_, width, signed)| { - (*width, *signed) - }); - let current = truncate_bigint_to_width(end, width, signed); - let result = step_body(current.clone()).await; - if matches!(result, ExecResult::Break) { - return ExecResult::Continue; - } - if result.should_stop() { - return result; - } - let next = - advance_bigint_counter(¤t, step, step_op, reverse, width, signed); - return if next >= current { - ExecResult::Fail("non-progressing stepped for loop".to_string()) - } else { - ExecResult::Continue - }; - } - } else if end <= start { - return ExecResult::Continue; - } - } else if inclusive { - if start > end { - return ExecResult::Continue; - } - if start == end { - let (width, signed) = loop_var - .as_ref() - .map_or((usize::BITS as usize, false), |(_, width, signed)| { - (*width, *signed) - }); - let current = truncate_bigint_to_width(start, width, signed); - let result = step_body(current.clone()).await; - if matches!(result, ExecResult::Break) { - return ExecResult::Continue; - } - if result.should_stop() { - return result; - } - let next = advance_bigint_counter(¤t, step, step_op, reverse, width, signed); - return if next <= current { - ExecResult::Fail("non-progressing stepped for loop".to_string()) - } else { - ExecResult::Continue - }; - } - } else if start >= end { - return ExecResult::Continue; - } - return ExecResult::Fail(if loop_var.as_ref().is_some_and(|(_, _, signed)| *signed) { - "dynamic signed for-loop bound exceeds host i128".to_string() - } else { - "dynamic for-loop bound exceeds host usize".to_string() - }); - } - - let (start_signed, end_signed) = match (start, end) { - (EvaluatedLoopBound::Unsigned(start), EvaluatedLoopBound::Unsigned(end)) => { - (None, Some((start, end))) - } - (EvaluatedLoopBound::Signed(start), EvaluatedLoopBound::Signed(end)) => { - (Some((start, end)), None) - } - (EvaluatedLoopBound::Signed(start), EvaluatedLoopBound::Unsigned(end)) => { - (Some((start, end as i128)), None) - } - (EvaluatedLoopBound::Unsigned(start), EvaluatedLoopBound::Signed(end)) => { - (Some((start as i128, end)), None) - } - _ => unreachable!("wide loop bounds handled above"), - }; - - if let Some((start, end)) = start_signed { - let truncate_counter = |value| { - loop_var.as_ref().map_or(value, |(_, width, signed)| { - truncate_i128_to_width(value, *width, *signed) - }) - }; - let mut step_body = |i: i128| { - if let Some((sig, width, _)) = loop_var { - sim_set_i128(&mut sim.borrow_mut(), *sig, *width, i); - } - exec_body() - }; - - let step_i = step as i128; - if reverse { - let mut i = truncate_counter(if inclusive { end } else { end.wrapping_sub(1) }); - while in_range(i, start) { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = truncate_counter(i.wrapping_sub(step_i)); - if next >= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } else if let Some(op) = step_op { - let mut i = truncate_counter(start); - while in_range(i, end) { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let new_i = match op { - Op::Mul => i.wrapping_mul(step_i), - Op::BitOr => i | step_i, - Op::BitXor => i ^ step_i, - Op::LogicShiftL | Op::ArithShiftL => { - if step >= i128::BITS as usize { - 0 - } else { - i.checked_shl(step as u32).unwrap_or(0) - } - } - _ => i.wrapping_add(step_i), - }; - let new_i = truncate_counter(new_i); - if new_i <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = new_i; - } - } else { - let mut i = truncate_counter(start); - while in_range(i, end) { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = i.wrapping_add(step_i); - let next = truncate_counter(next); - if next <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } - - return ExecResult::Continue; - } - - let (start, end) = end_signed.expect("unsigned loop bounds expected"); - let truncate_counter = |value| { - loop_var.as_ref().map_or(value, |(_, width, _)| { - truncate_usize_to_width(value, *width) - }) - }; - - let mut step_body = |i: usize| { - if let Some((sig, _, _)) = loop_var { - sim_set_u64(&mut sim.borrow_mut(), *sig, i as u64); - } - exec_body() - }; - - if reverse { - let mut i = truncate_counter(if inclusive { end } else { end.wrapping_sub(1) }); - while i >= start { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = truncate_counter(i.wrapping_sub(step)); - if next >= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } else if let Some(op) = step_op { - let mut i = truncate_counter(start); - while if inclusive { i <= end } else { i < end } { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let new_i = match op { - Op::Mul => i.wrapping_mul(step), - Op::BitOr => i | step, - Op::BitXor => i ^ step, - Op::LogicShiftL | Op::ArithShiftL => { - if step >= usize::BITS as usize { - 0 - } else { - i << step - } - } - _ => i.wrapping_add(step), - }; - let new_i = truncate_counter(new_i); - if new_i <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = new_i; - } - } else { - let mut i = truncate_counter(start); - while if inclusive { i <= end } else { i < end } { - let r = step_body(i).await; - if matches!(r, ExecResult::Break) { - return ExecResult::Continue; - } - if r.should_stop() { - return r; - } - let next = i.wrapping_add(step); - let next = truncate_counter(next); - if next <= i { - return ExecResult::Fail("non-progressing stepped for loop".to_string()); - } - i = next; - } - } - - ExecResult::Continue -} - pub(crate) fn run_testbench( sim: &mut Simulator, testbench: &CompiledTestbench, @@ -1270,7 +652,7 @@ fn run_testbench_limited( sim.component_simulation = sim .components .has_scheduled_components() - .then(|| crate::simulation::simulation_state(sim)); + .then(|| Box::new(crate::simulation::simulation_state(sim))); let mut ctx = DetailedExecContext { assertions: Vec::new(), current_time: 0, @@ -1314,7 +696,7 @@ fn run_testbench_limited( TestResult::Fail(combined.join("\n")) } } - ExecResult::Continue | ExecResult::Break | ExecResult::Finished => { + ExecResult::Continue | ExecResult::Finished => { if !failed_messages.is_empty() { TestResult::Fail(failed_messages.join("\n")) } else if require_finish && !finished { @@ -1418,7 +800,7 @@ pub(crate) fn run_testbench_detailed( sim.component_simulation = sim .components .has_scheduled_components() - .then(|| crate::simulation::simulation_state(sim)); + .then(|| Box::new(crate::simulation::simulation_state(sim))); let mut ctx = DetailedExecContext { assertions: Vec::new(), current_time: 0, @@ -1434,7 +816,7 @@ pub(crate) fn run_testbench_detailed( }; let mut error = match result { ExecResult::Fail(message) => Some(message), - ExecResult::Continue | ExecResult::Break | ExecResult::Finished => None, + ExecResult::Continue | ExecResult::Finished => None, }; if let Err(message) = sim.components.finish(ctx.simulation_time()) && error.is_none() @@ -1646,9 +1028,6 @@ fn drain_runtime_assertions( } } -// Futures retain each process's control stack (including evaluated loop bounds) -// while no simulator borrow is held. Only this deterministic scheduler polls -// them; no threads, executor, or background work are involved. struct ProcessWait { clock: Event, remaining: u64, @@ -1657,129 +1036,6 @@ struct ProcessWait { reset: Option<(SignalRef, Option, u8)>, } -async fn exec_process<'a, B: SimBackend>( - sim: &'a RefCell<&mut Simulator>, - ctx: &'a RefCell<&mut DetailedExecContext>, - wait: &'a RefCell>>, - reset_edges: &'a RefCell>, - stmts: &'a [TestbenchStatement], -) -> ExecResult { - for stmt in stmts { - let result = match stmt { - GenericTestbenchStatement::ClockNext { - clock_event, - count, - period, - } => { - let count = match eval_clock_count(&mut sim.borrow_mut(), count) { - Ok(count) => count, - Err(error) => return ExecResult::Fail(error.to_string()), - }; - *wait.borrow_mut() = (count != 0).then_some(ProcessWait { - clock: *clock_event, - remaining: count, - reset: None, - period: *period, - resume_at: None, - }); - std::future::poll_fn(|_| { - if wait.borrow().is_none() { - Poll::Ready(()) - } else { - Poll::Pending - } - }) - .await; - ExecResult::Continue - } - GenericTestbenchStatement::ResetAssert { - reset_signal, - reset_event, - clock_event, - duration, - assert_value, - deassert_value, - period, - } => { - let duration = match eval_clock_count(&mut sim.borrow_mut(), duration) { - Ok(count) => count.max(1), - Err(error) => return ExecResult::Fail(error.to_string()), - }; - sim_set_u64(&mut sim.borrow_mut(), *reset_signal, (*assert_value).into()); - if let Some(event) = reset_event { - reset_edges.borrow_mut().push((*event, *assert_value)); - } - *wait.borrow_mut() = Some(ProcessWait { - clock: *clock_event, - remaining: duration, - period: *period, - resume_at: None, - reset: Some((*reset_signal, *reset_event, *deassert_value)), - }); - std::future::poll_fn(|_| { - if wait.borrow().is_none() { - Poll::Ready(()) - } else { - Poll::Pending - } - }) - .await; - ExecResult::Continue - } - GenericTestbenchStatement::If { - expr, - then_block, - else_block, - } => { - let condition = { - let mut sim = sim.borrow_mut(); - if let Err(error) = settle_testbench_expr(&mut sim, expr) { - return ExecResult::Fail(format!("eval_comb: {error}")); - } - !eval_expr(&mut sim, expr).is_zero() - }; - let block = if condition { then_block } else { else_block }; - if block.is_empty() { - ExecResult::Continue - } else { - Box::pin(exec_process(sim, ctx, wait, reset_edges, block)).await - } - } - GenericTestbenchStatement::For { - loop_var, - start, - end, - inclusive, - step, - step_op, - reverse, - body, - } => { - // Break recursive future sizing at the loop, once per loop - // invocation. Its body future stays inline across iterations; - // boxing the body instead allocates on every simulated cycle. - Box::pin(exec_for_loop_async( - sim, - loop_var, - start, - end, - *inclusive, - *step, - *step_op, - *reverse, - || exec_process(sim, ctx, wait, reset_edges, body), - )) - .await - } - _ => exec_one_detailed(&mut sim.borrow_mut(), stmt, &mut ctx.borrow_mut()), - }; - if !matches!(result, ExecResult::Continue) { - return result; - } - } - ExecResult::Continue -} - struct ProcessClock { event: Event, period: u64, @@ -1833,18 +1089,25 @@ fn exec_testbench( testbench: &CompiledTestbench, ctx: &mut DetailedExecContext, ) -> ExecResult { - let blocks: Vec<_> = testbench - .processes() - .filter(|block| !block.is_empty()) - .collect(); + let blocks: Vec<_> = testbench.processes().collect(); let clocks = initialize_process_clocks(sim, testbench); // One process on one clock spends time only in that clock's periods, so // stepping them in place is the whole schedule. - if blocks.is_empty() || (blocks.len() == 1 && clocks.len() <= 1) { - return exec_detailed(sim, testbench.statements(), ctx); + if blocks.is_empty() { + return ExecResult::Continue; + } + if blocks.len() == 1 && clocks.len() <= 1 { + let mut process = match native::Process::::compile(blocks[0], &testbench.kernels()[0]) { + Ok(process) => process, + Err(error) => return ExecResult::Fail(format!("testbench compilation: {error}")), + }; + return match process.resume(sim, ctx, &mut None, &mut Vec::new(), false) { + Poll::Ready(result) => result, + Poll::Pending => unreachable!("synchronous clock execution cannot suspend"), + }; } // Suspended processes keep their temporaries outside state memory, so - // only the poll loop collects, with those temporaries as roots. + // only the scheduler loop collects, with those temporaries as roots. let blocked = std::mem::replace(&mut sim.heap_safepoints_blocked, true); let result = exec_processes(sim, testbench, ctx, &blocks); sim.heap_safepoints_blocked = blocked; @@ -1866,23 +1129,17 @@ fn exec_processes( .map(|&signal| sim.backend.get_four_state(signal)) .collect(); let mut locals = vec![initial_locals; blocks.len()]; - let sim = RefCell::new(sim); - let ctx = RefCell::new(ctx); - let waits: Vec<_> = blocks.iter().map(|_| RefCell::new(None)).collect(); - let reset_edges = RefCell::new(Vec::new()); - let mut processes: Vec<_> = blocks + let mut waits: Vec>> = blocks.iter().map(|_| None).collect(); + let mut reset_edges = Vec::new(); + let mut processes = match blocks .iter() - .zip(&waits) - .map(|(block, wait)| { - Some(Box::pin(exec_process( - &sim, - &ctx, - wait, - &reset_edges, - block, - ))) - }) - .collect(); + .zip(testbench.kernels()) + .map(|(block, kernel)| native::Process::::compile(block, kernel).map(Some)) + .collect::, _>>() + { + Ok(processes) => processes, + Err(error) => return ExecResult::Fail(format!("testbench compilation: {error}")), + }; // Every clock generator runs from time 0, whether or not a process // waits on it. let mut clocks: Vec> = testbench @@ -1900,21 +1157,19 @@ fn exec_processes( // their clock's next edge is still in the future. Rebasing after the // writes would silently absorb the asynchronous transition. { - let mut sim = sim.borrow_mut(); if sim.dirty - && let Err(error) = settle_testbench(&mut sim) + && let Err(error) = settle_testbench(sim) { return ExecResult::Fail(format!("eval_comb: {error}")); } let mut state = sim .component_simulation .take() - .unwrap_or_else(|| crate::simulation::simulation_state(&sim)); + .unwrap_or_else(|| Box::new(crate::simulation::simulation_state(sim))); state.synchronize_event_values(&sim.backend); sim.component_simulation = Some(state); } let mut now = 0; - let mut task_context = Context::from_waker(Waker::noop()); // Reuse per-slot batches instead of allocating on each rising and falling // edge; their capacities can grow when a wait introduces another clock. let mut falling = Vec::with_capacity(clocks.len()); @@ -1923,18 +1178,16 @@ fn exec_processes( let mut events = Vec::with_capacity(clocks.len() + waits.len()); let mut moves = Vec::with_capacity(clocks.len()); loop { - ctx.borrow_mut().scheduler_time = Some(now); - let draining = ctx.borrow().at_tick_limit(); + ctx.scheduler_time = Some(now); + let draining = ctx.at_tick_limit(); if draining { - ctx.borrow_mut().tick_limit_reached = true; + ctx.tick_limit_reached = true; // Stop starting work, but finish edges/releases already scheduled // by the final permitted tick before returning the simulator state. if clocks.iter().all(|clock| clock.falling_edge.is_none()) - && waits.iter().all(|wait| { - wait.borrow() - .as_ref() - .is_none_or(|wait| wait.resume_at.is_none()) - }) + && waits + .iter() + .all(|wait| wait.as_ref().is_none_or(|wait| wait.resume_at.is_none())) { return ExecResult::Finished; } @@ -1950,52 +1203,52 @@ fn exec_processes( None } })); - for wait in &waits { - let mut wait = wait.borrow_mut(); + for wait in &mut waits { if let Some(pending) = wait.as_ref() && pending.resume_at == Some(now) { if let Some((signal, event, value)) = pending.reset { - sim_set_u64(&mut sim.borrow_mut(), signal, value.into()); + sim_set_u64(sim, signal, value.into()); if let Some(event) = event { - reset_edges.borrow_mut().push((event, value)); + reset_edges.push((event, value)); } } *wait = None; } } - // Poll only ready processes, in declaration order, until their next - // wait, completion, or a global stop. No simulator borrow crosses await. + // Resume ready processes in declaration order until their next wait, + // completion, or a global stop. Each native call returns before another + // process or a clock domain can run. let mut stopped = false; - for ((process, wait), locals) in processes.iter_mut().zip(&waits).zip(&mut locals) { - if draining || wait.borrow().is_some() { + for ((process, wait), locals) in processes.iter_mut().zip(&mut waits).zip(&mut locals) { + if draining || wait.is_some() { continue; } - let Some(future) = process else { continue }; + let Some(executable) = process else { continue }; for (&signal, (value, mask)) in testbench.private_signals().iter().zip(locals.iter()) { - write_testbench_signal(&mut sim.borrow_mut(), signal, |sim| { + write_testbench_signal(sim, signal, |sim| { sim.set_four_state(signal, value.clone(), mask.clone()); }); } - let result = future.as_mut().poll(&mut task_context); + let result = executable.resume(sim, ctx, wait, &mut reset_edges, true); for (&signal, value) in testbench.private_signals().iter().zip(locals.iter_mut()) { - *value = sim.borrow().backend.get_four_state(signal); + *value = sim.backend.get_four_state(signal); } match result { - Poll::Ready(ExecResult::Continue | ExecResult::Break) => *process = None, + Poll::Ready(ExecResult::Continue) => *process = None, Poll::Ready(ExecResult::Finished) => { stopped = true; break; } Poll::Ready(result) => return result, - Poll::Pending => debug_assert!(wait.borrow().is_some()), + Poll::Pending => debug_assert!(wait.is_some()), } } // No process is running, so every string handle is in state memory or // in a suspended process's saved temporaries. - collect_testbench_heap(&mut sim.borrow_mut(), testbench.private_signals(), &locals); + collect_testbench_heap(sim, testbench.private_signals(), &locals); for wait in &waits { - if let Some(wait) = wait.borrow().as_ref() + if let Some(wait) = wait.as_ref() && wait.remaining != 0 { if let Some(clock) = clocks @@ -2023,7 +1276,6 @@ fn exec_processes( { resets.clear(); resets.extend(waits.iter().filter_map(|wait| { - let wait = wait.borrow(); let wait = wait.as_ref()?; wait.reset.map(|(_, event, _)| (wait.clock, event)) })); @@ -2033,15 +1285,15 @@ fn exec_processes( .iter() .map(|&event| (event, 0)) .chain(fired.iter().map(|&event| (event, 1))) - .chain(reset_edges.borrow_mut().drain(..)), + .chain(reset_edges.drain(..)), ); let result = step_process_events( - &mut sim.borrow_mut(), + sim, &events, &resets, now, !fired.is_empty(), - &mut ctx.borrow_mut(), + ctx, &mut moves, ); if !matches!(result, ExecResult::Continue) { @@ -2056,8 +1308,8 @@ fn exec_processes( clock.falling_edge = Some(now + clock.period - clock.period / 2); } } - for wait in &waits { - if let Some(wait) = wait.borrow_mut().as_mut() + for wait in &mut waits { + if let Some(wait) = wait.as_mut() && wait.remaining != 0 && let Some(clock) = clocks .iter() @@ -2079,13 +1331,13 @@ fn exec_processes( } let next_edge = clocks .iter() - .filter(|_| !ctx.borrow().at_tick_limit()) + .filter(|_| !ctx.at_tick_limit()) .map(|clock| clock.next_edge) .min(); let next_falling = clocks.iter().filter_map(|clock| clock.falling_edge).min(); let next_resume = waits .iter() - .filter_map(|wait| wait.borrow().as_ref().and_then(|wait| wait.resume_at)) + .filter_map(|wait| wait.as_ref().and_then(|wait| wait.resume_at)) .min(); if let Some(next) = [next_edge, next_falling, next_resume] .into_iter() @@ -2093,8 +1345,8 @@ fn exec_processes( .min() { now = next; - } else if ctx.borrow().at_tick_limit() { - ctx.borrow_mut().tick_limit_reached = true; + } else if ctx.at_tick_limit() { + ctx.tick_limit_reached = true; return ExecResult::Finished; } else { unreachable!("a live process has a pending wait"); @@ -2114,7 +1366,7 @@ fn step_process_events( let mut state = sim .component_simulation .take() - .unwrap_or_else(|| crate::simulation::simulation_state(sim)); + .unwrap_or_else(|| Box::new(crate::simulation::simulation_state(sim))); let edges = sim.event_edges(); let schema = &sim.program.runtime_schema; // Plain RTL needs simultaneous edge evaluation, not the timed process @@ -2213,30 +1465,6 @@ fn step_process_events( ExecResult::Continue } -/// Like [`exec`] but collects assertion results into `ctx` instead of -/// short-circuiting on the first failure. -fn exec_detailed( - sim: &mut Simulator, - stmts: &[TestbenchStatement], - ctx: &mut DetailedExecContext, -) -> ExecResult { - for stmt in stmts { - let r = exec_one_detailed(sim, stmt, ctx); - // Only a single process runs here, so between statements every string - // handle is in state memory. - sim.maybe_collect_heap([]); - // Stop on control-flow transfers or hard errors. Assertion failures that - // are allowed to continue return `Continue` and are recorded in `ctx`. - if matches!( - r, - ExecResult::Break | ExecResult::Finished | ExecResult::Fail(_) - ) { - return r; - } - } - ExecResult::Continue -} - fn exec_one_detailed( sim: &mut Simulator, stmt: &TestbenchStatement, @@ -2420,52 +1648,11 @@ fn exec_one_detailed( forward_display(&rendered, *newline); ExecResult::Continue } - GenericTestbenchStatement::If { - expr, - then_block, - else_block, - } => { - if let Err(e) = settle_testbench_expr(sim, expr) { - return ExecResult::Fail(format!("eval_comb: {e}")); - } - if !eval_expr(sim, expr).is_zero() { - exec_detailed(sim, then_block, ctx) - } else { - exec_detailed(sim, else_block, ctx) - } - } - GenericTestbenchStatement::For { - loop_var, - start, - end, - inclusive, - step, - step_op, - reverse, - body, - } => exec_for_loop( - sim, - loop_var, - start, - end, - *inclusive, - *step, - *step_op, - *reverse, - |sim| exec_detailed(sim, body, ctx), - ), - GenericTestbenchStatement::Assign { dst, expr } => { - let settle = if dst.selection.is_some() { - settle_testbench(sim) - } else { - settle_testbench_expr(sim, expr) - }; - if let Err(e) = settle { - return ExecResult::Fail(format!("eval_comb: {e}")); - } - let val = eval_expr(sim, expr); - sim_set_target(sim, dst, val); - ExecResult::Continue + GenericTestbenchStatement::If { .. } + | GenericTestbenchStatement::For { .. } + | GenericTestbenchStatement::Assign { .. } + | GenericTestbenchStatement::Break => { + unreachable!("statement is compiled into the process kernel") } GenericTestbenchStatement::WriteMemory { signal, writes } => { if let Err(e) = settle_testbench(sim) { @@ -2601,7 +1788,6 @@ fn exec_one_detailed( ); ExecResult::Continue } - GenericTestbenchStatement::Break => ExecResult::Break, GenericTestbenchStatement::Finish => ExecResult::Finished, } } @@ -2999,7 +2185,7 @@ mod tests { var q: logic<32>; inst dut: Counter(clk, q); initial { - for _i in 0..8 { clk.next(1); } + for _i in 0..(2 * (2 + 2)) { clk.next(1); } $assert(q == 8); $finish(); } @@ -3023,53 +2209,93 @@ mod tests { } #[test] - fn expression_stores_invalidate_settled_hardware() { - use celox_testbench::{CompiledExpr, ExprBytecode, ExprOpcode}; + fn compiled_reads_share_settlement_until_the_next_hardware_write() { let mut sim = Simulator::builder( - "module Top(a: input logic<8>, q: output logic<8>) { assign q = a + 1; }", + r#" + #[test(Top)] module Top { + var a: logic<8>; var q: logic<8>; + var x: logic<8>; var y: logic<8>; var z: logic<8>; + assign q = a + 1; + initial { + a = 1; + x = q; + y = q; + a = 7; + z = q; + $assert(x == 2 && y == 2 && z == 8); + $finish(); + } + } + "#, "Top", ) + .build() + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + let settlements = tb.kernels()[0] + .requests + .iter() + .filter(|request| matches!(request, celox_testbench::KernelRequest::Settle)) + .count(); + assert_eq!(settlements, 2); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + + #[test] + fn compiled_kernel_stores_invalidate_settled_hardware() { + let mut sim = Simulator::builder( + r#" + #[test(Top)] module Top { + var a: logic<8>; var q: logic<8>; + assign q = a + 1; + initial { a = 7; $finish(); } + } + "#, + "Top", + ) + .dead_store_policy(crate::DeadStorePolicy::Off) .build_interpreter() .unwrap(); - let a = sim.signal("a"); let q = sim.signal("q"); + let tb = compile_initial_testbench(&sim).unwrap(); settle_testbench(&mut sim).unwrap(); - let pure = CompiledExpr::new(ExprBytecode::new(vec![ExprOpcode::ConstU64(42)])); - assert_eq!(eval_expr(&mut sim, &pure).to_u64(), 42); + let GenericTestbenchStatement::Assign { expr, .. } = &tb.statements()[0] else { + panic!("assignment") + }; + assert_eq!(eval_expr(&mut sim, expr).to_u64(), 7); assert!(!sim.dirty); - let store = CompiledExpr::new(ExprBytecode::new(vec![ - ExprOpcode::ConstU64(7), - ExprOpcode::StoreU64 { - location: a.offset, - byte_size: 1, - }, - ExprOpcode::ConstU64(7), - ])); - assert_eq!(eval_expr(&mut sim, &store).to_u64(), 7); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); assert!(sim.dirty); settle_testbench(&mut sim).unwrap(); assert_eq!(sim.get_as::(q), 8); } #[test] - fn expression_stores_notify_vcd_without_exposing_memory() { + fn compiled_kernel_stores_notify_vcd_without_exposing_memory() { let dir = tempfile::tempdir().unwrap(); - let mut sim = Simulator::builder("module Top (a: input logic<8>) {}", "Top") - .vcd(dir.path().join("expression.vcd")) - .build() - .unwrap(); + let mut sim = Simulator::builder( + r#" + #[test(Top)] module Top {var a: logic<8>; initial {a=7; $finish();}} + "#, + "Top", + ) + .vcd(dir.path().join("expression.vcd")) + .build() + .unwrap(); let a = sim.signal("a"); - let expr = celox_testbench::CompiledExpr::new(celox_testbench::ExprBytecode::new(vec![ - celox_testbench::ExprOpcode::ConstU64(7), - celox_testbench::ExprOpcode::StoreU64 { - location: a.offset, - byte_size: 1, - }, - celox_testbench::ExprOpcode::ConstU64(7), - ])); + let tb = compile_initial_testbench(&sim).unwrap(); sim.dump(0); let before = sim.vcd_statistics().unwrap(); - assert_eq!(eval_expr(&mut sim, &expr).to_u64(), 7); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); assert_eq!(sim.get_as::(a), 7); sim.dump(1); let after = sim.vcd_statistics().unwrap(); @@ -3131,4 +2357,23 @@ mod tests { } ); } + #[test] + fn zero_tick_limit_does_not_evaluate_compiled_control_flow() { + let source = r#" + #[test(Top)] module Top { + var touched: u32; + function touch() -> u32 { touched = 1; return 1; } + initial { if touch() == 1 { $finish(); } } + } + "#; + let mut sim = Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(); + let touched = sim.signal("touched"); + let program = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &program, 0); + assert!(result.tick_limit_reached); + assert_eq!(result.ticks, 0); + assert_eq!(sim.get_as::(touched), 0); + } } diff --git a/crates/celox/src/testbench/native.rs b/crates/celox/src/testbench/native.rs new file mode 100644 index 00000000000..d4712786d6d --- /dev/null +++ b/crates/celox/src/testbench/native.rs @@ -0,0 +1,165 @@ +//! Invoke ordinary compiled SIR processes and service their suspension requests. +use super::*; +use celox_design::{HostRequestKind, ProcessStatus}; +use celox_testbench::{KernelRequest, TestbenchKernel}; + +pub(super) struct Process<'a, B: SimBackend> { + kernel: &'a TestbenchKernel, + sites: Vec<&'a TestbenchStatement>, + started: bool, +} +impl<'a, B: SimBackend> Process<'a, B> { + pub(super) fn compile( + statements: &'a [TestbenchStatement], + kernel: &'a TestbenchKernel, + ) -> Result { + fn collect<'a, B: SimBackend>( + statements: &'a [TestbenchStatement], + sites: &mut Vec<&'a TestbenchStatement>, + ) { + for statement in statements { + sites.push(statement); + match statement { + GenericTestbenchStatement::If { + then_block, + else_block, + .. + } => { + collect::(then_block, sites); + collect::(else_block, sites); + } + GenericTestbenchStatement::For { body, .. } => collect::(body, sites), + _ => {} + } + } + } + let mut sites = Vec::new(); + collect::(statements, &mut sites); + Ok(Self { + kernel, + sites, + started: false, + }) + } + pub(super) fn resume( + &mut self, + sim: &mut Simulator, + ctx: &mut DetailedExecContext, + wait: &mut Option>, + reset_edges: &mut Vec<(B::Event, u8)>, + scheduled: bool, + ) -> Poll { + if !self.started { + sim.backend.set(self.kernel.resume, 0u16); + self.started = true; + } + loop { + if !scheduled && ctx.at_tick_limit() { + ctx.tick_limit_reached = true; + return Poll::Ready(ExecResult::Finished); + } + if let Err(error) = sim.backend.run_process(self.kernel.entry) { + return Poll::Ready(ExecResult::Fail(format!("testbench kernel: {error}"))); + } + let status = ProcessStatus::from_code(sim.backend.get_as::(self.kernel.status)); + if status == Some(ProcessStatus::Done) { + return Poll::Ready(ExecResult::Continue); + } + if status != Some(ProcessStatus::HostRequest) { + return Poll::Ready(ExecResult::Fail(format!( + "invalid testbench kernel status: {status:?}" + ))); + } + let encoded = sim.backend.get_as::(self.kernel.request); + let Some((HostRequestKind::Testbench, index)) = HostRequestKind::decode(encoded) else { + return Poll::Ready(ExecResult::Fail("invalid testbench host request".into())); + }; + let Some(request) = self.kernel.requests.get(index as usize) else { + return Poll::Ready(ExecResult::Fail( + "testbench host request out of range".into(), + )); + }; + match request { + KernelRequest::Settle => { + if let Err(error) = settle_testbench(sim) { + return Poll::Ready(ExecResult::Fail(format!("eval_comb: {error}"))); + } + } + KernelRequest::Written { address, width } => { + let bytes = width.div_ceil(8); + sim.backend.mark_settle_range(address.offset, bytes); + sim.dirty |= !private_testbench_range(sim, address.offset, bytes); + } + KernelRequest::Error(message) => { + return Poll::Ready(ExecResult::Fail(message.clone())); + } + KernelRequest::Statement(site) => { + let statement = self.sites[*site]; + if scheduled { + match statement { + GenericTestbenchStatement::ClockNext { + clock_event, + count, + period, + } => { + let count = match eval_clock_count(sim, count) { + Ok(count) => count, + Err(error) => { + return Poll::Ready(ExecResult::Fail(error.to_string())); + } + }; + if count != 0 { + *wait = Some(ProcessWait { + clock: *clock_event, + remaining: count, + period: *period, + resume_at: None, + reset: None, + }); + return Poll::Pending; + } + continue; + } + GenericTestbenchStatement::ResetAssert { + reset_signal, + reset_event, + clock_event, + duration, + period, + assert_value, + deassert_value, + } => { + let count = match eval_clock_count(sim, duration) { + Ok(count) => count.max(1), + Err(error) => { + return Poll::Ready(ExecResult::Fail(error.to_string())); + } + }; + sim_set_u64(sim, *reset_signal, (*assert_value).into()); + if let Some(event) = reset_event { + reset_edges.push((*event, *assert_value)); + } + *wait = Some(ProcessWait { + clock: *clock_event, + remaining: count, + period: *period, + resume_at: None, + reset: Some((*reset_signal, *reset_event, *deassert_value)), + }); + return Poll::Pending; + } + _ => {} + } + } + let result = exec_one_detailed(sim, statement, ctx); + if !matches!(result, ExecResult::Continue) { + return Poll::Ready(result); + } + } + } + if !scheduled { + sim.maybe_collect_heap([]); + } + } + } +} diff --git a/crates/celox/src/testbench_compile.rs b/crates/celox/src/testbench_compile.rs index d24f9981047..e25015e3b9f 100644 --- a/crates/celox/src/testbench_compile.rs +++ b/crates/celox/src/testbench_compile.rs @@ -27,3 +27,133 @@ pub(crate) fn compile_semantic_testbench( random_seed, ) } + +/// Compile every expression at the ordinary pre-layout SIR boundary. Runtime +/// bindings carry entry indices and result slots, never executable bytecode. +pub(crate) fn lower_expressions( + sir: &mut crate::ir::SirProgram, + runtime: &mut crate::ir::RuntimeProgram, + program: &mut TestbenchProgram, +) -> Result<(), String> { + use celox_design::{ProcessKind, ProcessSlots, RegionedStateAddr, STABLE_REGION}; + use celox_sir::{BlockId, ExecutionUnit, SIRBuilder, SIRInstruction, SIROffset, SIRTerminator}; + use celox_testbench::{ExprOpcode, ExpressionKernel, StateLocation}; + let control = ProcessSlots { + kind: ProcessKind::Callable, + requires_timed_simulation: false, + const_delays: false, + program: None, + resume: runtime.design.allocate_testbench_slot(16, false), + status: runtime.design.allocate_testbench_slot(8, false), + delay: runtime.design.allocate_testbench_slot(64, false), + }; + for slot in [control.resume, control.status, control.delay] { + runtime.runtime_schema.testbench_read_roots.insert(slot); + } + program.try_visit_expressions(|expression| { + let mut builder = SIRBuilder::new(); + let value = celox_testbench::lowering::Expressions { + builder: &mut builder, + } + .compile(expression)?; + let width = builder.register(&value.register).width(); + let result = runtime.design.allocate_testbench_slot(width, value.string); + runtime.runtime_schema.testbench_read_roots.insert(result); + builder.emit(SIRInstruction::Store( + result, + SIROffset::Static(0), + width, + value.register, + vec![], + vec![], + )); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + let mut unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + .into_map_addr(&mut |address| { + RegionedStateAddr::from_absolute_addr(STABLE_REGION, address) + }); + memory::normalize(&mut unit, &runtime.design); + unit.verify_result().map_err(|error| error.to_string())?; + let mut writes = Vec::new(); + for op in expression.ops() { + match op { + ExprOpcode::StoreU64 { + location, + byte_size, + } => writes.push((*location, *byte_size)), + ExprOpcode::StoreString { location } => { + writes.push((*location, celox_heap::HANDLE_BYTES)) + } + _ => {} + } + } + let constant = if width <= 64 + && !value.string + && writes.is_empty() + && !unit + .blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!( + inst, + SIRInstruction::Load(..) | SIRInstruction::ExternCall { .. } + ) + }) { + celox_sir_opt::optimizer::optimize_merged_chain( + &mut unit, + std::sync::Arc::new(Default::default()), + |_, _, _| true, + false, + false, + &Default::default(), + || false, + ) + .map_err(|error| error.to_string())?; + let constants = celox_sir::analysis::collect_unique_exact_u64_constants(&unit); + unit.blocks + .values() + .flat_map(|block| &block.instructions) + .find_map(|inst| match inst { + SIRInstruction::Store(address, _, _, value, _, _) + if address.absolute_addr() == result => + { + constants.get(value).map(|value| value.value) + } + _ => None, + }) + } else { + None + }; + let entry = sir.processes.len(); + sir.processes.push(unit); + runtime.runtime_schema.processes.push(control); + runtime + .runtime_schema + .process_origins + .push(Default::default()); + runtime.runtime_schema.process_frames.push(None); + expression.set_kernel(ExpressionKernel { + constant, + entry, + result: StateLocation { + address: result, + byte_offset: 0, + }, + width, + is_string: value.string, + writes, + }); + Ok(()) + }) +} + +mod process; +pub(crate) use process::lower as lower_processes; + +mod memory; diff --git a/crates/celox/src/testbench_compile/memory.rs b/crates/celox/src/testbench_compile/memory.rs new file mode 100644 index 00000000000..ed1c19be800 --- /dev/null +++ b/crates/celox/src/testbench_compile/memory.rs @@ -0,0 +1,155 @@ +//! Preserve unpacked element addressing when consuming flattened TB offsets. +use crate::HashMap; +use crate::ir::{AbsoluteAddr, RuntimeDesign}; +use celox_design::{BinaryOp, RegionedStateAddr, UnaryOp}; +use celox_sir::{ + ExecutionUnit, RegisterId, RegisterType, SIRInstruction as Inst, SIROffset, SIRValue, +}; + +pub(super) fn normalize(unit: &mut ExecutionUnit, design: &RuntimeDesign) { + let elements: HashMap = design + .state_objects + .iter() + .filter(|(_, info)| !info.array_dims.is_empty()) + .map(|(address, info)| { + ( + *address, + info.width / info.array_dims.iter().product::(), + ) + }) + .collect(); + let mut next = unit.register_map.keys().map(|reg| reg.0).max().unwrap_or(0) + 1; + let mut alloc = |width| { + let register = RegisterId(next); + next += 1; + unit.register_map.insert( + register, + RegisterType::Bit { + width, + signed: false, + }, + ); + register + }; + for block in unit.blocks.values_mut() { + let old = std::mem::take(&mut block.instructions); + for instruction in old { + let (address, offset, width) = match &instruction { + Inst::Load(_, address, offset, width) + | Inst::Store(address, offset, width, _, _, _) => { + (*address, offset.clone(), *width) + } + _ => { + block.instructions.push(instruction); + continue; + } + }; + let Some(&element_width) = elements.get(&address.absolute_addr()) else { + block.instructions.push(instruction); + continue; + }; + let static_start = if let SIROffset::Static(start) = offset { + Some(start) + } else { + None + }; + let start = match offset { + SIROffset::Dynamic(value) => value, + SIROffset::Static(offset) => { + if width == 0 || offset / element_width == (offset + width - 1) / element_width + { + block.instructions.push(instruction); + continue; + } + let reg = alloc(64); + block + .instructions + .push(Inst::Imm(reg, SIRValue::new(offset as u64))); + reg + } + _ => { + block.instructions.push(instruction); + continue; + } + }; + let stride = alloc(64); + block + .instructions + .push(Inst::Imm(stride, SIRValue::new(element_width as u64))); + let mut parts = Vec::new(); + let mut bit = 0; + while bit < width { + // Source packed selections are confined to their unpacked + // element; wider accesses select complete unpacked elements. + let available = static_start.map_or(element_width, |start| { + element_width - (start + bit) % element_width + }); + let count = available.min(width - bit); + let offset = if bit == 0 { + start + } else { + let add = alloc(64); + block + .instructions + .push(Inst::Imm(add, SIRValue::new(bit as u64))); + let sum = alloc(64); + block + .instructions + .push(Inst::Binary(sum, start, BinaryOp::Add, add)); + sum + }; + let index = alloc(64); + block + .instructions + .push(Inst::Binary(index, offset, BinaryOp::DivU, stride)); + let within = alloc(64); + block + .instructions + .push(Inst::Binary(within, offset, BinaryOp::RemU, stride)); + let offset = SIROffset::Element { + index, + element_width, + bit_offset: 0, + dynamic_bit_offset: Some(within), + }; + let part = alloc(count); + match &instruction { + Inst::Load(..) => { + block + .instructions + .push(Inst::Load(part, address, offset, count)); + parts.push(part); + } + Inst::Store(_, _, _, value, triggers, probes) => { + block + .instructions + .push(Inst::Slice(part, *value, bit, count)); + block.instructions.push(Inst::Store( + address, + offset, + count, + part, + triggers.clone(), + probes.clone(), + )); + } + _ => unreachable!(), + } + bit += count; + } + if let Inst::Load(result, ..) = instruction { + let value = if parts.len() == 1 { + parts[0] + } else { + let value = alloc(width); + parts.reverse(); + block.instructions.push(Inst::Concat(value, parts)); + value + }; + block + .instructions + .push(Inst::Unary(result, UnaryOp::Ident, value)); + } + } + } +} diff --git a/crates/celox/src/testbench_compile/process.rs b/crates/celox/src/testbench_compile/process.rs new file mode 100644 index 00000000000..cf9bc7bdf31 --- /dev/null +++ b/crates/celox/src/testbench_compile/process.rs @@ -0,0 +1,567 @@ +//! Veryl statements lowered with the same resumable SIR builder as SV. +use crate::ir::{AbsoluteAddr as Addr, RuntimeProgram, SirProgram}; +use celox_design::{ + BinaryOp, ProcessKind, ProcessSlots, RegionedVarAddrBase, STABLE_REGION, UnaryOp, +}; +use celox_frontend_core::process::ProcessKernelBuilder; +use celox_sir::{ + BlockId, RegisterId, SIRInstruction as Inst, SIROffset, SIRTerminator as Term, SIRValue, +}; +use celox_testbench::*; +use num_bigint::BigUint; + +type Expr = ExprBytecode>; +fn stable(var_id: Addr) -> RegionedVarAddrBase { + RegionedVarAddrBase { + region: STABLE_REGION, + var_id, + } +} +struct Lower<'a> { + runtime: &'a mut RuntimeProgram, + kernel: ProcessKernelBuilder, + requests: Vec>, + site: usize, + external_observers: bool, + settled: bool, +} +impl Lower<'_> { + fn slot(&mut self, width: usize, string: bool) -> Addr { + let address = self.runtime.design.allocate_testbench_slot(width, string); + self.runtime + .runtime_schema + .testbench_read_roots + .insert(address); + address + } + fn imm(&mut self, width: usize, value: impl Into) -> RegisterId { + let reg = self.kernel.builder().alloc_bit(width.max(1), false); + self.kernel.builder().emit(Inst::Imm( + reg, + SIRValue::new( + value.into() & ((BigUint::from(1u8) << width.max(1)) - BigUint::from(1u8)), + ), + )); + reg + } + fn load(&mut self, address: Addr, width: usize, signed: bool) -> RegisterId { + let reg = self.kernel.builder().alloc_bit(width.max(1), signed); + self.kernel.builder().emit(Inst::Load( + reg, + stable(address), + SIROffset::Static(0), + width.max(1), + )); + reg + } + fn store(&mut self, address: Addr, width: usize, value: RegisterId) { + self.kernel.builder().emit(Inst::Store( + stable(address), + SIROffset::Static(0), + width.max(1), + value, + vec![], + vec![], + )); + } + fn cast(&mut self, value: RegisterId, width: usize, signed: bool) -> RegisterId { + let source = self.kernel.builder().register(&value).width(); + let extend = self.kernel.builder().register(&value).is_signed() && width > source; + let reg = self.kernel.builder().alloc_bit(width.max(1), signed); + if width < source { + self.kernel + .builder() + .emit(Inst::Slice(reg, value, 0, width.max(1))); + } else { + self.kernel + .builder() + .emit(Inst::Unary(reg, UnaryOp::Ident, value)); + } + if extend { + let shift = self.imm(64, (width - source) as u64); + let reg = self.binary(BinaryOp::Shl, reg, shift, width); + let reg = self.binary(BinaryOp::Sar, reg, shift, width); + let typed = self.kernel.builder().alloc_bit(width.max(1), signed); + self.kernel + .builder() + .emit(Inst::Unary(typed, UnaryOp::Ident, reg)); + typed + } else { + reg + } + } + fn binary( + &mut self, + op: BinaryOp, + mut l: RegisterId, + mut r: RegisterId, + width: usize, + ) -> RegisterId { + if matches!( + op, + BinaryOp::Eq + | BinaryOp::Ne + | BinaryOp::LtS + | BinaryOp::LtU + | BinaryOp::LeS + | BinaryOp::LeU + | BinaryOp::GtS + | BinaryOp::GtU + | BinaryOp::GeS + | BinaryOp::GeU + ) { + let signed = matches!( + op, + BinaryOp::LtS | BinaryOp::LeS | BinaryOp::GtS | BinaryOp::GeS + ); + let lw = self.kernel.builder().register(&l).width(); + let rw = self.kernel.builder().register(&r).width(); + l = self.cast(l, lw, signed); + r = self.cast(r, rw, signed); + l = self.cast(l, lw.max(rw), signed); + r = self.cast(r, lw.max(rw), signed); + } + let reg = self.kernel.builder().alloc_bit(width.max(1), false); + self.kernel.builder().emit(Inst::Binary(reg, l, op, r)); + reg + } + fn request(&mut self, request: KernelRequest) -> Result<(), String> { + self.settled = matches!(request, KernelRequest::Settle); + let index = self.requests.len(); + self.requests.push(request); + self.kernel + .host_request(celox_design::HostRequestKind::Testbench, index as u32) + .map_err(|e| e.to_string()) + } + fn expression(&mut self, expr: &Expr) -> Result { + let expr = expr.clone().try_map_locations(|location| { + Ok::<_, String>(StateLocation { + address: stable(location.address), + byte_offset: location.byte_offset, + }) + })?; + let value = lowering::Expressions { + builder: self.kernel.builder(), + } + .compile(&expr)?; + let writes: Vec<_> = expr + .ops() + .iter() + .filter_map(|op| { + let address = match op { + ExprOpcode::StoreU64 { location, .. } + | ExprOpcode::StoreString { location } => location.address.var_id, + _ => return None, + }; + self.writes_observable(address).then_some(address) + }) + .collect(); + if writes.is_empty() { + return Ok(value); + } + // Host requests resume through a fresh kernel entry. Preserve the + // expression result in layout-owned state across that boundary. + let width = self.kernel.builder().register(&value.register).width(); + let saved = self.slot(width, value.string); + self.store(saved, width, value.register); + for address in writes { + let width = self.runtime.design.state_objects[&address].width; + self.request(KernelRequest::Written { address, width })?; + } + Ok(lowering::Value { + register: self.load(saved, width, false), + string: value.string, + }) + } + fn writes_observable(&self, address: Addr) -> bool { + self.external_observers || self.runtime.rtl_accesses.contains(&address) + } + fn observes(&self, expr: &Expr) -> bool { + self.external_observers + || expr.ops().iter().any(|op| match op { + ExprOpcode::LoadU64 { location, .. } + | ExprOpcode::LoadWide { location, .. } + | ExprOpcode::LoadIndexed { location, .. } + | ExprOpcode::LoadBitSelect { location, .. } + | ExprOpcode::LoadString { location, .. } => { + self.runtime.rtl_accesses.contains(&location.address) + } + _ => false, + }) + } + fn settled_expression(&mut self, expr: &Expr) -> Result { + // Reads within one straight-line segment see the same settled DUT. + // A write, host service or control-flow boundary invalidates this fact. + if self.observes(expr) && (!self.settled || self.external_observers) { + self.request(KernelRequest::Settle)?; + } + self.expression(expr) + } + fn block( + &mut self, + body: &[SemanticStatement], + break_to: Option, + ) -> Result<(), String> { + for statement in body { + let site = self.site; + self.site += 1; + if !self.kernel.builder().has_open_block() { + let dead = self.kernel.builder().new_block(); + self.kernel.builder().switch_to_block(dead); + } + match statement { + TestbenchStatement::If { + expr, + then_block, + else_block, + } => { + let cond = self.settled_expression(expr)?.register; + let yes = self.kernel.builder().new_block(); + let no = self.kernel.builder().new_block(); + let join = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond, + true_block: (yes, vec![]), + false_block: (no, vec![]), + }); + for (block, body) in [(yes, then_block), (no, else_block)] { + self.kernel.builder().switch_to_block(block); + self.settled = false; + self.block(body, break_to)?; + if self.kernel.builder().has_open_block() { + self.kernel.builder().seal_block(Term::Jump(join, vec![])); + } + } + self.kernel.builder().switch_to_block(join); + self.settled = false; + } + TestbenchStatement::Assign { dst, expr } => { + let expression = self.settled_expression(expr)?; + let value = self.cast(expression.register, dst.width, false); + let saved = if dst.selection.is_some() { + let saved = self.slot(dst.width, expression.string); + self.store(saved, dst.width, value); + Some(saved) + } else { + None + }; + let offset = if let Some(selection) = &dst.selection { + SIROffset::Dynamic(self.expression(&selection.offset)?.register) + } else { + SIROffset::Static(0) + }; + let value = saved.map_or(value, |saved| self.load(saved, dst.width, false)); + self.kernel.builder().emit(Inst::Store( + stable(dst.signal.address), + offset, + dst.width, + value, + vec![], + vec![], + )); + if self.writes_observable(dst.signal.address) { + self.request(KernelRequest::Written { + address: dst.signal.address, + width: dst.signal.width, + })?; + } + } + TestbenchStatement::For { + loop_var, + start, + end, + inclusive, + step, + step_op, + reverse, + body, + } => { + self.for_loop( + *loop_var, start, end, *inclusive, *step, *step_op, *reverse, body, + break_to, + )?; + } + TestbenchStatement::Break => { + if let Some(target) = break_to { + self.kernel.builder().seal_block(Term::Jump(target, vec![])); + } else { + self.kernel.complete(); + } + } + _ => self.request(KernelRequest::Statement(site))?, + } + } + Ok(()) + } + fn bound(&mut self, bound: &LoopBound) -> Result<(RegisterId, usize, bool), String> { + Ok(match bound { + LoopBound::Static(value) => { + let width = (usize::BITS as usize - value.leading_zeros() as usize).max(32); + let value = self.imm(width, *value as u64); + (self.cast(value, width, true), width, true) + } + LoopBound::Dynamic { + expr, + width, + signed, + } => { + let value = self.settled_expression(expr)?.register; + (self.cast(value, *width, *signed), *width, *signed) + } + }) + } + fn bound_fits( + &mut self, + value: RegisterId, + width: usize, + signed: bool, + extra: bool, + ) -> RegisterId { + let source = self.kernel.builder().register(&value).clone(); + let common = source.width().max(width + 1); + let value = self.cast(value, common, source.is_signed()); + let max = (BigUint::from(1u8) << (width - usize::from(signed))) - BigUint::from(1u8) + + BigUint::from(u8::from(extra)); + let max = self.imm(common, max); + let upper = self.binary( + if source.is_signed() { + BinaryOp::LeS + } else { + BinaryOp::LeU + }, + value, + max, + 1, + ); + if source.is_signed() { + let min = if signed { + (BigUint::from(1u8) << common) - (BigUint::from(1u8) << (width - 1)) + } else { + BigUint::ZERO + }; + let min = self.imm(common, min); + let lower = self.binary(BinaryOp::GeS, value, min, 1); + self.binary(BinaryOp::And, upper, lower, 1) + } else { + upper + } + } + #[allow(clippy::too_many_arguments)] + fn for_loop( + &mut self, + variable: Option<(SemanticSignal, usize, bool)>, + start: &LoopBound, + end: &LoopBound, + inclusive: bool, + step: usize, + step_op: Option, + reverse: bool, + body: &[SemanticStatement], + _outer_break: Option, + ) -> Result<(), String> { + let (first, fw, fs) = self.bound(start)?; + // A bound can call host services: save the first value across them. + let first_slot = self.slot(fw, false); + self.store(first_slot, fw, first); + let (last, lw, ls) = self.bound(end)?; + let first = self.load(first_slot, fw, fs); + let (width, signed) = variable.map_or((fw.max(lw).max(64), fs || ls), |(_, w, s)| (w, s)); + // A fixed-width induction variable cannot traverse an unrepresentable + // endpoint. Diagnose that before entering an otherwise enormous loop. + let singleton = if inclusive && fw.max(lw) > 64 { + let equal = self.binary(BinaryOp::Eq, first, last, 1); + let max = self.imm(fw.max(lw), u64::MAX); + let wide = self.binary(BinaryOp::GtU, first, max, 1); + self.binary(BinaryOp::And, equal, wide, 1) + } else { + self.imm(1, 0u8) + }; + let mode_slot = self.slot(1, false); + self.store(mode_slot, 1, singleton); + let remaining_slot = self.slot(1, false); + let one = self.imm(1, 1u8); + self.store(remaining_slot, 1, one); + if variable.is_some() { + let first_fits = self.bound_fits(first, width, signed, false); + let last_fits = self.bound_fits(last, width, signed, !inclusive); + let fits = self.binary(BinaryOp::And, first_fits, last_fits, 1); + let fits = self.binary(BinaryOp::Or, fits, singleton, 1); + let valid = self.kernel.builder().new_block(); + let invalid = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond: fits, + true_block: (valid, vec![]), + false_block: (invalid, vec![]), + }); + self.kernel.builder().switch_to_block(invalid); + self.request(KernelRequest::Error( + "non-progressing stepped for loop".into(), + ))?; + self.kernel.complete(); + self.kernel.builder().switch_to_block(valid); + } + let limit_width = if reverse { fw } else { lw }; + let limit_signed = if reverse { fs } else { ls }; + let current_slot = self.slot(width, false); + let limit_slot = self.slot(limit_width, false); + self.store(limit_slot, limit_width, if reverse { first } else { last }); + let current = if reverse && !inclusive { + let one = self.imm(lw, 1u8); + self.binary(BinaryOp::Sub, last, one, lw) + } else if reverse { + last + } else { + first + }; + let current = self.cast(current, width, signed); + self.store(current_slot, width, current); + let check = self.kernel.builder().new_block(); + let body_entry = self.kernel.builder().new_block(); + let advance = self.kernel.builder().new_block(); + let exit = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Jump(check, vec![])); + self.kernel.builder().switch_to_block(check); + let current = self.load(current_slot, width, signed); + let limit = self.load(limit_slot, limit_width, limit_signed); + let cmp = match (reverse, inclusive, signed && limit_signed) { + (true, _, true) => BinaryOp::GeS, + (true, _, false) => BinaryOp::GeU, + (false, true, true) => BinaryOp::LeS, + (false, true, false) => BinaryOp::LeU, + (false, false, true) => BinaryOp::LtS, + (false, false, false) => BinaryOp::LtU, + }; + let cond = self.binary(cmp, current, limit, 1); + let mode = self.load(mode_slot, 1, false); + let remaining = self.load(remaining_slot, 1, false); + let selected = self.kernel.builder().alloc_bit(1, false); + self.kernel + .builder() + .emit(Inst::Mux(selected, mode, remaining, cond)); + let cond = selected; + self.kernel.builder().seal_block(Term::Branch { + cond, + true_block: (body_entry, vec![]), + false_block: (exit, vec![]), + }); + self.kernel.builder().switch_to_block(body_entry); + self.settled = false; + if let Some((var, _, _)) = variable { + self.store(var.address, width, current); + } + self.block(body, Some(exit))?; + if self.kernel.builder().has_open_block() { + self.kernel + .builder() + .seal_block(Term::Jump(advance, vec![])); + } + self.kernel.builder().switch_to_block(advance); + let current = self.load(current_slot, width, signed); + let step = self.imm(width, step as u64); + let op = if reverse { + BinaryOp::Sub + } else { + match step_op { + Some(TestbenchOperator::Mul) => BinaryOp::Mul, + Some(TestbenchOperator::BitOr) => BinaryOp::Or, + Some(TestbenchOperator::BitXor) => BinaryOp::Xor, + Some(TestbenchOperator::LogicShiftL | TestbenchOperator::ArithShiftL) => { + BinaryOp::Shl + } + _ => BinaryOp::Add, + } + }; + let next = self.binary(op, current, step, width); + let next = self.cast(next, width, signed); + let progress = self.binary( + match (reverse, signed) { + (true, true) => BinaryOp::LtS, + (true, false) => BinaryOp::LtU, + (false, true) => BinaryOp::GtS, + (false, false) => BinaryOp::GtU, + }, + next, + current, + 1, + ); + self.store(current_slot, width, next); + let zero = self.imm(1, 0u8); + self.store(remaining_slot, 1, zero); + let failure = self.kernel.builder().new_block(); + self.kernel.builder().seal_block(Term::Branch { + cond: progress, + true_block: (check, vec![]), + false_block: (failure, vec![]), + }); + self.kernel.builder().switch_to_block(failure); + self.request(KernelRequest::Error( + "non-progressing stepped for loop".into(), + ))?; + self.kernel.complete(); + self.kernel.builder().switch_to_block(exit); + self.settled = false; + Ok(()) + } +} + +pub(crate) fn lower( + sir: &mut SirProgram, + runtime: &mut RuntimeProgram, + program: &mut TestbenchProgram, +) -> Result<(), String> { + let mut kernels = Vec::new(); + let external_observers = !program.component_bindings().is_empty() + || !runtime.runtime_schema.persistent_comb_state.is_empty() + || !runtime.runtime_schema.comb_observers.is_empty() + || runtime + .runtime_schema + .processes + .iter() + .any(|p| p.kind != ProcessKind::Callable); + for body in program.processes() { + let slots = ProcessSlots { + kind: ProcessKind::Callable, + requires_timed_simulation: false, + const_delays: false, + program: None, + resume: runtime.design.allocate_testbench_slot(16, false), + status: runtime.design.allocate_testbench_slot(8, false), + delay: runtime.design.allocate_testbench_slot(64, false), + }; + for slot in [slots.resume, slots.status, slots.delay] { + runtime.runtime_schema.testbench_read_roots.insert(slot); + } + let mut lower = Lower { + runtime, + kernel: ProcessKernelBuilder::new(slots), + requests: vec![], + site: 0, + external_observers, + settled: false, + }; + lower.block(body, None)?; + let entry = sir.processes.len(); + let mut unit = lower.kernel.build().into_map_addr(&mut |address| { + celox_design::RegionedStateAddr::from_absolute_addr(address.region, address.var_id) + }); + super::memory::normalize(&mut unit, &lower.runtime.design); + unit.verify_result().map_err(|error| error.to_string())?; + sir.processes.push(unit); + lower.runtime.runtime_schema.processes.push(slots); + lower.runtime.runtime_schema.process_frames.push(None); + lower + .runtime + .runtime_schema + .process_origins + .push(Default::default()); + kernels.push(TestbenchKernel { + entry, + resume: slots.resume, + status: slots.status, + request: slots.delay, + requests: lower.requests, + }); + } + program.set_kernels(kernels); + Ok(()) +} diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index 61cef16d016..2b8f3c0659a 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -2030,7 +2030,7 @@ fn test_for_loop_dynamic_wide_signed_bound_small_value_still_runs() { } #[test] -fn test_expression_vm_preserves_width_signedness_and_casts() { +fn test_compiled_expression_preserves_width_signedness_and_casts() { let code = r#" #[test(t)] module t { @@ -2118,7 +2118,7 @@ fn test_expression_vm_preserves_width_signedness_and_casts() { } #[test] -fn test_expression_vm_preserves_wide_fixed_width_semantics() { +fn test_compiled_expression_preserves_wide_fixed_width_semantics() { let code = r#" #[test(t)] module t { diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index 574530a26d4..9082907cae6 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -388,3 +388,34 @@ fn unsupported_string_operations_are_rejected() { ); } } + +#[test] +fn compiled_conditions_collect_temporary_string_arguments() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let values: Vec = (0..1500) + .map(|index| format!("temporary {index}")) + .collect(); + let conditions: String = values + .iter() + .map(|value| format!("if nonempty(\"{value}\") {{ }}\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + function nonempty(value: input string) -> logic {{ return value != ""; }} + initial {{ {conditions} $finish(); }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let all_values: usize = values.iter().map(String::len).sum(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index 9a414b2ff7c..ec791707758 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -266,6 +266,20 @@ A running simulator retains the elaborated design, source lookup, runtime schema bound testbench bytecode, and compiled backend. The backend owns the finalized layout. Frontend and optimizer state are discarded after compilation. +Veryl testbench expressions and resumable processes lower to SIR before +optimization and state layout, using the same process builder and code-generation +backends as SystemVerilog. Integer operations, including wide values, use normal +SIR instruction selection. Strings and floating-point operations use the shared +heap and numeric ABI. There is no separate testbench VM, assembler or Cranelift +compiler. Tiered execution promotes the DUT and testbench kernels together. + +The compiled process stores its continuation before requesting a clock/reset +wait or a host service such as display, assertions, random generation or component +calls. The Veryl event scheduler resumes these kernels and retains clock order, +private process state, tick limits and heap roots. This does not change +`clock_gen` or `clock.next` timing. Compiler-only builds retain the same lowering +and serialized kernel metadata without requiring a host JIT. + ## Public API boundary The Rust `celox` crate is a facade over the compiler and runtime components. The diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index 304d2ff25a1..02e4698d614 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -189,7 +189,7 @@ for. | `celox-backend-cranelift` | Cranelift translation and JIT construction | Frontend or x86-specific MIR | | `celox-backend-wasm` | WebAssembly module generation | Host runtime behavior | | `celox-heap` | Dynamic values referenced by handles from state memory, and their collection | Root discovery, layouts, or scheduling | -| `celox-testbench` | Source-independent testbench bytecode and values | Veryl AST traversal or simulator memory ownership | +| `celox-testbench` | Source-independent testbench contracts, values and expression lowering to shared SIR | Veryl AST traversal or simulator memory ownership | | `celox-runtime` | Events, timed scheduling, VCD output, testbench execution, and backend contracts | Frontend, SIR optimization, or concrete backend internals | | `celox` | Public API, compilation orchestration, and backend selection | New reusable compiler algorithms | diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index f1e67d56bca..6d579c650bc 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -26,16 +26,16 @@ crates=( celox-frontend-sdk celox-macros celox-ts-gen - celox-testbench celox-sir celox-state-layout celox-slt celox-backend-cranelift celox-backend-wasm celox-frontend-core - celox-runtime celox-sir-opt celox-backend-x86 + celox-testbench + celox-runtime celox-backend-arm64 celox-frontend-sv celox-frontend-veryl