diff --git a/crates/celox-backend-arm64/src/isel/instruction.rs b/crates/celox-backend-arm64/src/isel/instruction.rs index e233dceacbb..2cc6e9efbef 100644 --- a/crates/celox-backend-arm64/src/isel/instruction.rs +++ b/crates/celox-backend-arm64/src/isel/instruction.rs @@ -341,12 +341,25 @@ pub(super) fn lower_instruction( let chunk_vreg = ctx.alloc_vreg(SpillDesc::sim_state( *addr, bit_pos, chunk_bits, false, )); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + chunk_vreg + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: chunk_vreg, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != chunk_vreg { + ctx.emit_and_imm( + block, + chunk_vreg, + raw, + mask_for_width(chunk_bits), + ); + } chunks.push((chunk_vreg, chunk_bits)); bit_pos += chunk_bits; remaining -= chunk_bits; @@ -366,12 +379,20 @@ pub(super) fn lower_instruction( let chunk_byte_off = ctx.mask_byte_offset(addr, m_bit_pos); let chunk_size = ISelContext::op_size_for_width(chunk_bits); let mv = ctx.alloc_vreg(SpillDesc::transient()); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + mv + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: mv, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != mv { + ctx.emit_and_imm(block, mv, raw, mask_for_width(chunk_bits)); + } mchunks.push((mv, chunk_bits)); m_bit_pos += chunk_bits; m_remaining -= chunk_bits; diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index 3e2569fc504..45edb81ff51 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -1,3 +1,4 @@ +mod partial_load; mod shifts; mod strided; diff --git a/crates/celox-backend-arm64/src/isel/tests/partial_load.rs b/crates/celox-backend-arm64/src/isel/tests/partial_load.rs new file mode 100644 index 00000000000..cda6f3aac36 --- /dev/null +++ b/crates/celox-backend-arm64/src/isel/tests/partial_load.rs @@ -0,0 +1,121 @@ +//! A rounded wide load must not import padding or neighbouring value/mask bytes. +use super::*; + +#[test] +fn rounded_wide_value_loads_keep_adjacent_bits_out_of_comparisons() { + check(false); +} +#[test] +fn rounded_wide_mask_loads_keep_adjacent_bits_out_of_comparisons() { + check(true); +} + +fn check(four_state: bool) { + for width in [100usize, 65, 72, 73, 80, 81, 96, 97, 113, 127, 128] { + let input = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId(0), + }; + let output = AbsoluteAddr { + var_id: StateObjectId(1), + ..input + }; + let address = |absolute| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, absolute); + let loaded = RegisterId(0); + let zero = RegisterId(1); + let equal = RegisterId(2); + let widened = RegisterId(3); + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load(loaded, address(input), SIROffset::Static(0), width), + SIRInstruction::Imm(zero, SIRValue::new(0u8)), + SIRInstruction::Unary(widened, UnaryOp::Ident, zero), + SIRInstruction::Binary(equal, loaded, BinaryOp::Eq, widened), + SIRInstruction::Store( + address(output), + SIROffset::Static(0), + 1, + equal, + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: [(loaded, width), (zero, 8), (widened, width), (equal, 1)] + .into_iter() + .map(|(r, width)| { + ( + r, + if four_state { + RegisterType::Logic { width } + } else { + RegisterType::Bit { + width, + signed: false, + } + }, + ) + }) + .collect(), + }; + let mut layout = layout_for(input, width, four_state); + layout.offsets.insert(output, 64); + layout.widths.insert(output, 1); + layout.is_4states.insert(output, four_state); + layout.total_size = 96; + layout.working_base_offset = 96; + layout.sparse_base_offset = 96; + layout.sparse_active_bits_offset = 96; + layout.merged_total_size = 96; + layout.triggered_bits_offset = 96; + layout.scratch_base_offset = 96; + let image = crate::scalar::emit_prepared_eu( + &unit, + &layout, + four_state, + "wide_load", + false, + None, + || false, + ) + .unwrap(); + assert!(!image.code.is_empty()); + #[cfg(all(target_arch = "aarch64", target_os = "linux"))] + { + let jit = crate::jit_mem::JitCode::new(&image.code).unwrap(); + let mut state = vec![0xa5u8; 96]; + for bit in 0..width { + state[bit / 8] &= !(1 << (bit % 8)); + if four_state { + state[width.div_ceil(8) + bit / 8] &= !(1 << (bit % 8)); + } + } + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[64] & 1, 1, "width={width} four_state={four_state}"); + if four_state { + assert_eq!(state[65] & 1, 0, "width={width} mask"); + } + let high = width - 1; + state[high / 8] |= 1 << (high % 8); + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[64] & 1, 0, "width={width} last value bit"); + if four_state { + assert_eq!(state[65] & 1, 0, "width={width} known mismatch"); + state[width.div_ceil(8) + high / 8] |= 1 << (high % 8); + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[64] & 1, 1, "width={width} X value"); + assert_eq!(state[65] & 1, 1, "width={width} last mask bit"); + } + } + } +} diff --git a/crates/celox-backend-x86/src/backend/native/isel/instruction.rs b/crates/celox-backend-x86/src/backend/native/isel/instruction.rs index 9a92bb5e317..2d2ae803fdd 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/instruction.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/instruction.rs @@ -345,12 +345,25 @@ pub(super) fn lower_instruction( let chunk_vreg = ctx.alloc_vreg(SpillDesc::sim_state( *addr, bit_pos, chunk_bits, false, )); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + chunk_vreg + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: chunk_vreg, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != chunk_vreg { + ctx.emit_and_imm( + block, + chunk_vreg, + raw, + mask_for_width(chunk_bits), + ); + } chunks.push((chunk_vreg, chunk_bits)); bit_pos += chunk_bits; remaining -= chunk_bits; @@ -370,12 +383,20 @@ pub(super) fn lower_instruction( let chunk_byte_off = ctx.mask_byte_offset(addr, m_bit_pos); let chunk_size = ISelContext::op_size_for_width(chunk_bits); let mv = ctx.alloc_vreg(SpillDesc::transient()); + let raw = if matches!(chunk_bits, 8 | 16 | 32 | 64) { + mv + } else { + ctx.alloc_vreg(SpillDesc::transient()) + }; block.push(MInst::Load { - dst: mv, + dst: raw, base: BaseReg::SimState, offset: chunk_byte_off, size: chunk_size, }); + if raw != mv { + ctx.emit_and_imm(block, mv, raw, mask_for_width(chunk_bits)); + } mchunks.push((mv, chunk_bits)); m_bit_pos += chunk_bits; m_remaining -= chunk_bits; diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs index 34de1b057ce..99bfdcafea3 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs @@ -1538,6 +1538,116 @@ fn four_state_sar_uses_sign_fill_past_the_logical_source_words() { } } +#[test] +fn widened_zero_compares_equal_to_a_zero_wide_load() { + for four_state in [false, true] { + let a = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: VarId(0), + }; + let o = AbsoluteAddr { + instance_id: InstanceId(0), + var_id: VarId(1), + }; + let address = |a| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, a); + let [loaded, zero, widened, equal, result] = std::array::from_fn(RegisterId); + let unit = ExecutionUnit { + entry_block_id: SirBlockId(0), + blocks: [( + SirBlockId(0), + BasicBlock { + id: SirBlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load(loaded, address(a), SIROffset::Static(0), 100), + SIRInstruction::Imm(zero, SIRValue::new(0u8)), + SIRInstruction::Unary(widened, UnaryOp::Ident, zero), + SIRInstruction::Binary(equal, loaded, BinaryOp::Eq, widened), + SIRInstruction::Unary(result, UnaryOp::ToTwoState, equal), + SIRInstruction::Store( + address(o), + SIROffset::Static(0), + 1, + result, + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map: [ + (loaded, RegisterType::Logic { width: 100 }), + ( + zero, + RegisterType::Bit { + width: 32, + signed: false, + }, + ), + ( + widened, + RegisterType::Bit { + width: 100, + signed: false, + }, + ), + (equal, RegisterType::Logic { width: 1 }), + ( + result, + RegisterType::Bit { + width: 1, + signed: false, + }, + ), + ] + .into_iter() + .collect(), + }; + unit.verify(); + let mut layout = empty_layout(); + let output_offset = if four_state { 32 } else { 16 }; + let state_size = output_offset + 1; + layout.four_state = four_state; + layout.offsets = [(a, 0), (o, output_offset)].into_iter().collect(); + layout.widths = [(a, 100), (o, 1)].into_iter().collect(); + layout.is_4states = [(a, four_state), (o, false)].into_iter().collect(); + layout.total_size = state_size; + layout.working_base_offset = state_size; + layout.sparse_base_offset = state_size; + layout.merged_total_size = state_size; + layout.triggered_bits_offset = state_size; + layout.scratch_base_offset = state_size; + let mut function = lower_execution_unit(&unit, &layout, four_state); + mir_legalize::legalize(&mut function); + mir_opt::optimize(&mut function); + let allocation = regalloc::run_regalloc(&mut function).unwrap(); + mir_opt::post_regalloc_peephole(&mut function, &allocation.assignment); + function.verify(); + let emitted = emit::emit( + &function, + &allocation.assignment, + allocation.spill_frame_size, + ) + .unwrap(); + let jit = JitCode::new(&emitted.code).unwrap(); + let mut state = vec![0u8; state_size]; + state[12] = 0xf0; + if four_state { + state[25] = 0xf0; + state[26] = 6; + state[28] = 0xff; + } else { + state[13] = 6; + state[15] = 0xff; + } + assert_eq!(unsafe { jit.call(&mut state) }, 0); + assert_eq!(state[output_offset] & 1, 1, "four_state={four_state}"); + } +} + #[test] fn loaded_slices_survive_bulk_writes_across_padded_array_elements() { for commit in [false, true] { diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 1de57c16f22..caeff3d09ef 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -61,6 +61,17 @@ pub enum RuntimeEventKind { AssertFatal, /// `$finish` executed by the design (IEEE 1800-2023 20.2). Finish, + /// An assertion of a testbench process that held, reported so a test + /// run can list every assertion it checked. + AssertPass, +} + +/// Where a runtime event site is written, for test reports. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventLocation { + pub file: String, + pub line: u32, + pub column: u32, } /// How a runtime event site sizes its formatted arguments. @@ -86,6 +97,9 @@ pub struct RuntimeEventSite { pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, + /// The source position of a testbench assertion, for test reports. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub location: Option, } /// A function in the host's C ABI that the design calls, such as a @@ -235,12 +249,27 @@ pub enum ProcessStatus { /// [`ProcessSlots::clock`]. The runtime generates those edges: the clock /// toggles every half period from the first wait on it, and the process /// resumes one period after the last counted edge, before the edge that - /// follows. + /// follows. [`ProcessSlots::release`] names a write the runtime makes + /// when the wait is over, even if the process is not resumed. WaitClock, + /// The process needs the host: [`ProcessSlots::delay`] holds the index + /// of the [`HostRequest`] among the process's requests. The host serves + /// it through the process's scratch state and resumes the process at + /// once. + Host, + /// The process stored to design state and continues with a read of it: + /// the runtime settles the combinational logic and resumes the process + /// at once, before any other process runs. + Settle, + /// Return control to drain events without evaluating combinational logic. + Yield, /// An event occurred while sampling queued drives; resume its body after the batch. Ready, - /// Resume this process immediately, charging the current time-slot budget. - Yield, + /// End a sequential testbench after publishing writes and captured edges + /// from the current round. No later process or generated clock runs. + /// Veryl testbenches use this completion boundary; HDL `$finish` uses + /// [`Self::Finish`] and suppresses all subsequent publication. + FinishAfterPublication, } impl ProcessStatus { @@ -255,8 +284,11 @@ impl ProcessStatus { Self::Wait => 4, Self::Pending => 5, Self::WaitClock => 6, - Self::Ready => 11, + Self::Host => 7, + Self::Settle => 8, Self::Yield => 10, + Self::Ready => 11, + Self::FinishAfterPublication => 12, } } @@ -269,8 +301,11 @@ impl ProcessStatus { 4 => Some(Self::Wait), 5 => Some(Self::Pending), 6 => Some(Self::WaitClock), - 11 => Some(Self::Ready), + 7 => Some(Self::Host), + 8 => Some(Self::Settle), 10 => Some(Self::Yield), + 11 => Some(Self::Ready), + 12 => Some(Self::FinishAfterPublication), _ => None, } } @@ -294,44 +329,261 @@ impl ProcessClock { } } +/// A write the runtime makes for a process when a clock wait is over, such +/// as the release of a reset the process asserted for some cycles. It is +/// made even when the process is not resumed afterwards. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ProcessRelease { + pub signal: A, + pub value: u64, + /// The clock the released signal is a reset of, when the wait counted + /// its edges: a host component in that clock domain takes reset cycles + /// while the signal is held. + pub clock: Option, +} + +impl ProcessRelease { + pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessRelease { + ProcessRelease { + signal: map(self.signal), + value: self.value, + clock: self.clock.map(&mut map), + } + } +} + +/// A value a host request passes or returns through the process's scratch +/// state. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct HostValue { + pub signal: A, + pub width: usize, + pub signed: bool, + /// The value is the bytes of a string, most significant first. + pub is_string: bool, +} + +impl HostValue { + pub fn map(self, map: impl FnOnce(A) -> B) -> HostValue { + HostValue { + signal: map(self.signal), + width: self.width, + signed: self.signed, + is_string: self.is_string, + } + } +} + +/// What a process asks the host for with [`ProcessStatus::Host`]. Inputs are +/// read from, and results written to, scratch state of the process. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum HostRequest { + /// Seed the random stream `handle` from `value`. + RandomSeed { + handle: String, + value: HostValue, + }, + /// A random value of the result's width from the stream `handle`. + RandomGet { + handle: String, + result: HostValue, + }, + /// A random value between `min` and `max` from the stream `handle`. + RandomGetRange { + handle: String, + min: HostValue, + max: HostValue, + result: HostValue, + }, + /// The seed of the stream `handle`. + RandomGetSeed { + handle: String, + result: HostValue, + }, + /// Call `method` of the external component `instance` with `args`. + Component { + instance: String, + method: String, + args: Vec>, + result: Option>, + /// The declared width of the result, which the component must + /// return exactly. + declared_width: Option, + /// Whether a result wider than 64 bits is an error, because the + /// expression form of the call carries at most 64 bits. + strict: bool, + }, + /// Open a testbench file, replacing any previously open file of this handle. + FileOpen { + handle: String, + path: HostValue, + append: bool, + }, + /// Write formatted bytes to an open testbench file, without a newline. + FileWrite { + handle: String, + template: Option, + args: Vec>, + }, + FileFlush { + handle: String, + }, + FileClose { + handle: String, + }, +} + +impl HostRequest { + pub fn map(self, mut map: impl FnMut(A) -> B) -> HostRequest { + match self { + Self::FileOpen { + handle, + path, + append, + } => HostRequest::FileOpen { + handle, + path: path.map(&mut map), + append, + }, + Self::FileWrite { + handle, + template, + args, + } => HostRequest::FileWrite { + handle, + template, + args: args.into_iter().map(|arg| arg.map(&mut map)).collect(), + }, + Self::FileFlush { handle } => HostRequest::FileFlush { handle }, + Self::FileClose { handle } => HostRequest::FileClose { handle }, + Self::RandomSeed { handle, value } => HostRequest::RandomSeed { + handle, + value: value.map(&mut map), + }, + Self::RandomGet { handle, result } => HostRequest::RandomGet { + handle, + result: result.map(&mut map), + }, + Self::RandomGetRange { + handle, + min, + max, + result, + } => HostRequest::RandomGetRange { + handle, + min: min.map(&mut map), + max: max.map(&mut map), + result: result.map(&mut map), + }, + Self::RandomGetSeed { handle, result } => HostRequest::RandomGetSeed { + handle, + result: result.map(&mut map), + }, + Self::Component { + instance, + method, + args, + result, + declared_width, + strict, + } => HostRequest::Component { + instance, + method, + args: args.into_iter().map(|arg| arg.map(&mut map)).collect(), + result: result.map(|result| result.map(&mut map)), + declared_width, + strict, + }, + } + } +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to /// find where it stopped; before returning it stores the next resume point, /// a [`ProcessStatus`] code in `status` and, for a delay or a clock wait, the /// number of time units or edges in `delay`; a clock wait also stores the -/// index into `clocks` in `clock`. The slots are ordinary two-state state -/// objects, so checkpoints capture a suspended process. +/// index into `clocks` in `clock` and, when the wait ends with a write, one +/// plus the index into `releases` in `release`; a host request stores its +/// index into `host_requests` in `delay`. The slots are ordinary two-state +/// state objects, so checkpoints capture a suspended process. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { + /// Optional two-state flag: no design store since this kernel's last + /// combinational settle. Missing flags conservatively require a settle. + #[serde(default = "Option::default")] + pub comb_clean: Option, pub resume: A, pub status: A, pub delay: A, pub clock: A, + pub release: A, /// The clocks the process may wait on, in the order its kernel numbers /// them. #[serde(default = "Vec::new")] pub clocks: Vec>, + /// The writes a clock wait of the process may end with. + #[serde(default = "Vec::new")] + pub releases: Vec>, + /// The host requests the process may make. + #[serde(default = "Vec::new")] + pub host_requests: Vec>, } impl ProcessSlots { + /// Slots for a process without clocks, releases or host requests. + pub fn new(resume: A, status: A, delay: A, clock: A, release: A) -> Self { + Self { + comb_clean: None, + resume, + status, + delay, + clock, + release, + clocks: Vec::new(), + releases: Vec::new(), + host_requests: Vec::new(), + } + } + pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots { ProcessSlots { + comb_clean: self.comb_clean.map(&mut map), resume: map(self.resume), status: map(self.status), delay: map(self.delay), clock: map(self.clock), + release: map(self.release), clocks: self .clocks .into_iter() .map(|clock| clock.map(&mut map)) .collect(), + releases: self + .releases + .into_iter() + .map(|release| release.map(&mut map)) + .collect(), + host_requests: self + .host_requests + .into_iter() + .map(|request| request.map(&mut map)) + .collect(), } } /// The control slots, without the clock signals. pub fn iter(&self) -> impl Iterator { - [&self.resume, &self.status, &self.delay, &self.clock].into_iter() + [ + &self.resume, + &self.status, + &self.delay, + &self.clock, + &self.release, + ] + .into_iter() + .chain(self.comb_clean.iter()) } } @@ -341,6 +593,36 @@ pub const PROCESS_STATUS_WIDTH: usize = 8; pub const PROCESS_DELAY_WIDTH: usize = 64; /// Width of [`ProcessSlots::clock`]. pub const PROCESS_CLOCK_WIDTH: usize = 32; +/// Width of [`ProcessSlots::release`]. +pub const PROCESS_RELEASE_WIDTH: usize = 32; + +/// Serialize hash maps and sets in key order, so an artifact that embeds +/// them has one byte representation however the map was built. +pub mod serde_sorted { + use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; + use serde::{Serialize, Serializer}; + + pub fn map(map: &HashMap, serializer: S) -> Result + where + K: Ord + Serialize, + V: Serialize, + S: Serializer, + { + let mut entries: Vec<(&K, &V)> = map.iter().collect(); + entries.sort_by(|a, b| a.0.cmp(b.0)); + serializer.collect_map(entries) + } + + pub fn set(set: &HashSet, serializer: S) -> Result + where + T: Ord + Serialize, + S: Serializer, + { + let mut items: Vec<&T> = set.iter().collect(); + items.sort(); + serializer.collect_seq(items) + } +} pub const PROCESS_EVENT_COUNTER_WIDTH: usize = 32; @@ -400,6 +682,9 @@ pub struct RuntimeSchema { pub live_signals: HashSet, /// Control slots of the process kernels, in kernel order. pub processes: Vec>, + /// Index of the first kernel in `processes` that runs a Veryl testbench; + /// it and the kernels after it are the testbench's, not the design's. + pub testbench_kernels: Option, pub process_event_counters: Vec>, /// FF domains with blocking stores or finish effects in the active region. pub active_ff_events: HashSet, @@ -419,6 +704,7 @@ impl Default for RuntimeSchema { dead_store_policy: DeadStorePolicy::Off, live_signals: HashSet::default(), processes: Vec::new(), + testbench_kernels: None, process_event_counters: Vec::new(), active_ff_events: HashSet::default(), } @@ -436,12 +722,14 @@ impl Default for RuntimeSchema { ))] pub struct EventTopology { /// Alias event address to the canonical event-domain address. + #[serde(serialize_with = "crate::serde_sorted::map")] pub aliases: HashMap, /// Canonical event domains in evaluation order. pub ordered_events: Vec, /// Canonical clocks whose value may be changed by another event domain. pub cascaded_events: BTreeSet, /// Canonical asynchronous/synchronous reset to its canonical clock. + #[serde(serialize_with = "crate::serde_sorted::map")] pub reset_clocks: HashMap, } @@ -481,6 +769,7 @@ impl EventTopology { deserialize = "A: Deserialize<'de> + Eq + std::hash::Hash + Ord" ))] pub struct ElaboratedDesign { + #[serde(serialize_with = "crate::serde_sorted::map")] pub state_objects: HashMap, pub events: EventTopology, pub initial_state: Vec>, @@ -935,6 +1224,7 @@ mod tests { template: Some("failed".to_string()), sizing: DisplaySizing::Veryl, scope: None, + location: None, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 5f10bab6c9f..c12ee0902bc 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -6,18 +6,19 @@ //! suspension stores the next resume point, a [`ProcessStatus`] and its wait //! amount into the process's control slots and returns to the runtime. //! -//! A delay resumes after a time. An event or level wait resumes at a check -//! the kernel runs itself: the runtime resumes the process whenever the -//! state may have changed, and the kernel continues past the wait or -//! reports that it is still pending. +//! A delay resumes after a time, a clock wait after a number of edges of a +//! process clock, and a host request once the host has served it. An event +//! or level wait resumes at a check the kernel runs itself: the runtime +//! resumes the process whenever the state may have changed, and the kernel +//! continues past the wait or reports that it is still pending. //! //! The builder is source-independent: a frontend lowers statements and //! expressions into [`ProcessKernelBuilder::builder`] and calls the //! suspension methods where the source suspends. use celox_design::{ - PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, - RegionedVarAddrBase, STABLE_REGION, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, + ProcessSlots, ProcessStatus, RegionedVarAddrBase, STABLE_REGION, }; use celox_sir::{ BinaryOp, BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, @@ -45,45 +46,101 @@ pub enum ProcessKernelError { TooManySuspensions, #[error("a process waits on clock {0}, which its slots do not list")] UnknownClock(u32), + #[error("a process ends a wait with release {0}, which its slots do not list")] + UnknownRelease(u32), + #[error("a process makes host request {0}, which its slots do not list")] + UnknownHostRequest(u32), } -/// Builder of one process kernel. -pub struct ProcessKernelBuilder { - builder: SIRBuilder, - slots: ProcessSlots, +/// The stable-region address of a control slot. +pub fn stable_slot(var_id: SourceVarId) -> RegionedSourceAddr { + RegionedVarAddrBase { + region: STABLE_REGION, + var_id, + } +} + +/// Builder of one process kernel, addressed like its slots: `A` is the +/// stable-region address type of the kernel. +pub struct ProcessKernelBuilder { + builder: SIRBuilder, + resume: A, + status: A, + delay: A, + clock: A, + release: A, + clock_count: usize, + release_count: usize, + host_request_count: usize, /// The block each resume point continues in; point 0 is the start. resume_blocks: Vec, } -impl ProcessKernelBuilder { - /// Start a kernel. The builder is positioned at the start of the - /// process body. +impl ProcessKernelBuilder { + /// Start a kernel whose slots are module variables. The builder is + /// positioned at the start of the process body. pub fn new(slots: ProcessSlots) -> Self { + Self::with_addresses(slots.map(stable_slot)) + } +} + +impl ProcessKernelBuilder { + /// Start a kernel whose slots are the given stable addresses. The + /// builder is positioned at the start of the process body. + pub fn with_addresses(slots: ProcessSlots) -> Self { let builder = SIRBuilder::new(); let start = builder.current_block(); Self { builder, - slots, + resume: slots.resume, + status: slots.status, + delay: slots.delay, + clock: slots.clock, + release: slots.release, + clock_count: slots.clocks.len(), + release_count: slots.releases.len(), + host_request_count: slots.host_requests.len(), resume_blocks: vec![start], } } /// The SIR builder positioned where the process continues. After - /// [`Self::finish`] no block is open until the caller switches to one. - pub fn builder(&mut self) -> &mut SIRBuilder { + /// [`Self::build`] no block is open until the caller switches to one. + pub fn builder(&mut self) -> &mut SIRBuilder { &mut self.builder } - fn store_constant(&mut self, slot: SourceVarId, width: usize, value: u64) { + /// Register a further clock the process waits on, for a frontend that + /// finds the clocks while it lowers the body; returns its index. The + /// slots the frontend emits must list it at that index. + pub fn add_clock(&mut self) -> u32 { + self.clock_count += 1; + self.clock_count as u32 - 1 + } + + /// Register a further release a wait may end with; see + /// [`Self::add_clock`]. + pub fn add_release(&mut self) -> u32 { + self.release_count += 1; + self.release_count as u32 - 1 + } + + /// Register a further host request; see [`Self::add_clock`]. + pub fn add_host_request(&mut self) -> u32 { + self.host_request_count += 1; + self.host_request_count as u32 - 1 + } + + fn store_constant(&mut self, slot: A, width: usize, value: u64) { let register = self.builder.alloc_bit(width, false); self.builder .emit(SIRInstruction::Imm(register, SIRValue::new(value))); self.store(slot, width, register); } - fn store(&mut self, slot: SourceVarId, width: usize, value: RegisterId) { + fn store(&mut self, slot: A, width: usize, value: RegisterId) { self.builder.emit(SIRInstruction::Store( - stable(slot), + slot, SIROffset::Static(0), width, value, @@ -95,46 +152,20 @@ impl ProcessKernelBuilder { /// Return to the runtime with `status`, leaving no block open. fn end(&mut self, status: ProcessStatus) { self.store_constant( - self.slots.status, + self.status.clone(), PROCESS_STATUS_WIDTH, u64::from(status.code()), ); self.builder.seal_block(SIRTerminator::Return); } - /// Suspend for the number of time units in `amount`, an unsigned - /// two-state register of [`PROCESS_DELAY_WIDTH`] bits, and continue at - /// a new resume point. - pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { - self.delay_with_status(amount, ProcessStatus::Delay) - } - - /// A delay whose zero value resumes in the inactive region before NBA - /// publication, as SystemVerilog requires (IEEE 1800-2023 4.5). - pub fn inactive_delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { - self.delay_with_status(amount, ProcessStatus::InactiveDelay) - } - - /// Return for a budget check and immediately resume this same process. - /// This does not schedule an inactive-region delay or run another process. - pub fn yield_events(&mut self) -> Result<(), ProcessKernelError> { - let zero = self.builder.alloc_bit(PROCESS_DELAY_WIDTH, false); - self.builder - .emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); - self.delay_with_status(zero, ProcessStatus::Yield) - } - - fn delay_with_status( - &mut self, - amount: RegisterId, - status: ProcessStatus, - ) -> Result<(), ProcessKernelError> { + /// Store the next resume point and open its block after `end` runs. + fn suspend(&mut self, status: ProcessStatus) -> Result<(), ProcessKernelError> { let point = self.resume_blocks.len(); if point > MAX_PROCESS_SUSPENSIONS { return Err(ProcessKernelError::TooManySuspensions); } - self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount); - self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); + self.store_constant(self.resume.clone(), PROCESS_RESUME_WIDTH, point as u64); self.end(status); let resume = self.builder.new_block(); self.resume_blocks.push(resume); @@ -142,27 +173,68 @@ impl ProcessKernelBuilder { Ok(()) } + /// Suspend for the number of time units in `amount`, an unsigned + /// two-state register of [`PROCESS_DELAY_WIDTH`] bits, and continue at + /// a new resume point. + pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + self.store(self.delay.clone(), PROCESS_DELAY_WIDTH, amount); + self.suspend(ProcessStatus::Delay) + } + + /// Suspend in the inactive region for a SystemVerilog zero delay. + pub fn inactive_delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> { + self.store(self.delay.clone(), PROCESS_DELAY_WIDTH, amount); + self.suspend(ProcessStatus::InactiveDelay) + } + /// Suspend until `count` rising edges of the process clock `clock` (an /// index into the slots' clock list) have passed, and continue at a new /// resume point one period after the last of them. `count` is an /// unsigned two-state register of [`PROCESS_DELAY_WIDTH`] bits; a count - /// of zero continues at once. - pub fn wait_clock(&mut self, clock: u32, count: RegisterId) -> Result<(), ProcessKernelError> { - if clock as usize >= self.slots.clocks.len() { + /// of zero continues at once. With `release`, the runtime makes that + /// write of the slots' release list when the wait is over. + pub fn wait_clock( + &mut self, + clock: u32, + count: RegisterId, + release: Option, + ) -> Result<(), ProcessKernelError> { + if clock as usize >= self.clock_count { return Err(ProcessKernelError::UnknownClock(clock)); } - let point = self.resume_blocks.len(); - if point > MAX_PROCESS_SUSPENSIONS { - return Err(ProcessKernelError::TooManySuspensions); + let release = match release { + Some(release) if release as usize >= self.release_count => { + return Err(ProcessKernelError::UnknownRelease(release)); + } + Some(release) => u64::from(release) + 1, + None => 0, + }; + self.store(self.delay.clone(), PROCESS_DELAY_WIDTH, count); + self.store_constant(self.clock.clone(), PROCESS_CLOCK_WIDTH, u64::from(clock)); + self.store_constant(self.release.clone(), PROCESS_RELEASE_WIDTH, release); + self.suspend(ProcessStatus::WaitClock) + } + + /// Ask the host to serve `request` (an index into the slots' request + /// list) and continue at a new resume point once it has. + pub fn host(&mut self, request: u32) -> Result<(), ProcessKernelError> { + if request as usize >= self.host_request_count { + return Err(ProcessKernelError::UnknownHostRequest(request)); } - self.store(self.slots.delay, PROCESS_DELAY_WIDTH, count); - self.store_constant(self.slots.clock, PROCESS_CLOCK_WIDTH, u64::from(clock)); - self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); - self.end(ProcessStatus::WaitClock); - let resume = self.builder.new_block(); - self.resume_blocks.push(resume); - self.builder.switch_to_block(resume); - Ok(()) + self.store_constant(self.delay.clone(), PROCESS_DELAY_WIDTH, u64::from(request)); + self.suspend(ProcessStatus::Host) + } + + /// Have the runtime settle the combinational logic, then continue at + /// once. A process stores to design state directly, so a read of a + /// combinational result after such a store needs this first. + /// Drain host events and resume without reevaluating clean logic. + pub fn yield_events(&mut self) -> Result<(), ProcessKernelError> { + self.suspend(ProcessStatus::Yield) + } + + pub fn settle(&mut self) -> Result<(), ProcessKernelError> { + self.suspend(ProcessStatus::Settle) } /// Suspend until a condition the kernel evaluates holds, and continue at @@ -189,16 +261,7 @@ impl ProcessKernelBuilder { /// Arm an event wait whose samples may be polled between queued drives. pub fn begin_event_wait(&mut self) -> Result<(), ProcessKernelError> { - let point = self.resume_blocks.len(); - if point > MAX_PROCESS_SUSPENSIONS { - return Err(ProcessKernelError::TooManySuspensions); - } - self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64); - self.end(ProcessStatus::Wait); - let resume = self.builder.new_block(); - self.resume_blocks.push(resume); - self.builder.switch_to_block(resume); - Ok(()) + self.suspend(ProcessStatus::Wait) } /// At the resume point of a [`Self::begin_wait`]: continue when @@ -239,7 +302,7 @@ impl ProcessKernelBuilder { let request = self.builder.alloc_bit(PROCESS_DELAY_WIDTH, false); self.builder.emit(SIRInstruction::Load( request, - stable(self.slots.delay), + self.delay.clone(), SIROffset::Static(0), PROCESS_DELAY_WIDTH, )); @@ -268,7 +331,7 @@ impl ProcessKernelBuilder { let status = self.builder.alloc_bit(PROCESS_STATUS_WIDTH, false); self.builder.emit(SIRInstruction::Load( status, - stable(self.slots.status), + self.status.clone(), SIROffset::Static(0), PROCESS_STATUS_WIDTH, )); @@ -299,8 +362,13 @@ impl ProcessKernelBuilder { self.end(ProcessStatus::Finish); } + /// End a sequential testbench after publishing this round's prior writes. + pub fn finish_after_publication(&mut self) { + self.end(ProcessStatus::FinishAfterPublication); + } + /// Complete the kernel. If a block is still open, the process ends there. - pub fn build(mut self) -> ExecutionUnit { + pub fn build(mut self) -> ExecutionUnit { if self.builder.has_open_block() { self.end(ProcessStatus::Done); } @@ -315,7 +383,7 @@ impl ProcessKernelBuilder { let resume = self.builder.alloc_bit(PROCESS_RESUME_WIDTH, false); self.builder.emit(SIRInstruction::Load( resume, - stable(self.slots.resume), + self.resume.clone(), SIROffset::Static(0), PROCESS_RESUME_WIDTH, )); @@ -324,7 +392,7 @@ impl ProcessKernelBuilder { .chunks(1 << SWITCH_BITS) .map(<[BlockId]>::to_vec) .collect::>(); - let byte = |builder: &mut SIRBuilder, lsb: usize| { + let byte = |builder: &mut SIRBuilder, lsb: usize| { let byte = builder.alloc_bit(SWITCH_BITS, false); builder.emit(SIRInstruction::Slice(byte, resume, lsb, SWITCH_BITS)); byte @@ -376,13 +444,6 @@ impl ProcessKernelBuilder { } } -fn stable(var_id: SourceVarId) -> RegionedSourceAddr { - RegionedSourceAddr { - region: STABLE_REGION, - var_id, - } -} - fn switch_cases(targets: &[BlockId]) -> Vec { targets .iter() diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 187743ff56a..b4b6369bca6 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -2,9 +2,9 @@ use celox_design::{ BinaryOp, BitAccess, DomainKind, InitialStateData, InitialStateValue, ModuleId, - PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessClock, - ProcessSlots, RegionedVarAddrBase, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, - VariableMetadata, WORKING_REGION, + PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, + PortTypeKind, ProcessClock, ProcessSlots, RegionedVarAddrBase, STABLE_REGION, TriggerSet, + UnaryOp, VarAtomBase, VariableMetadata, WORKING_REGION, }; use celox_frontend_sdk::{ ActiveLevel, Direction, Edge, ExprId, ExprNode, FrontendArtifact, SignalId, SignalSlice, @@ -1143,7 +1143,7 @@ fn lower_statements( kernel.builder(), &mut cache, )?; - kernel.wait_clock(index as u32, count)?; + kernel.wait_clock(index as u32, count, None)?; } Statement::Finish => { kernel.finish(); @@ -1195,10 +1195,14 @@ fn lower_processes( let mut clocks = Vec::new(); celox_frontend_sdk::collect_process_clocks(process.body(), &mut clocks); let slots = ProcessSlots { + comb_clean: None, resume: declare(name("resume"), PROCESS_RESUME_WIDTH), status: declare(name("status"), PROCESS_STATUS_WIDTH), delay: declare(name("delay"), PROCESS_DELAY_WIDTH), clock: declare(name("clock"), PROCESS_CLOCK_WIDTH), + release: declare(name("release"), PROCESS_RELEASE_WIDTH), + releases: Vec::new(), + host_requests: Vec::new(), clocks: clocks .iter() .map(|clock| { diff --git a/crates/celox-frontend-core/src/shared/lookup.rs b/crates/celox-frontend-core/src/shared/lookup.rs index d8faf9d8542..954f8173a7a 100644 --- a/crates/celox-frontend-core/src/shared/lookup.rs +++ b/crates/celox-frontend-core/src/shared/lookup.rs @@ -89,7 +89,7 @@ impl fmt::Debug for VariableInfo { } } -#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct InstancePath(pub Vec<(String, usize)>); /// Source-language-independent lookup retained for diagnostics and public paths. diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 56ca734f8bd..e757277327a 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1444,6 +1444,7 @@ pub fn schedule_symbolic_rtl( dead_store_policy: Default::default(), live_signals: Default::default(), processes: process_slots, + testbench_kernels: None, process_event_counters, active_ff_events: HashSet::default(), }, diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index bb5d5179bd4..1f98d127b8c 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -12,9 +12,9 @@ use std::path::Path; use celox_design::{ BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType, InitialStateData, InitialStateValue, ModuleId, PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, - PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, - RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, - WORKING_REGION, + PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, + RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, + VarAtomBase, WORKING_REGION, }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ @@ -3658,11 +3658,15 @@ fn lower_initial_processes( id }; ProcessSlots { + comb_clean: None, resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), clock: declare("clock", PROCESS_CLOCK_WIDTH), + release: declare("release", PROCESS_RELEASE_WIDTH), clocks: Vec::new(), + releases: Vec::new(), + host_requests: Vec::new(), } }) .collect(); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 9131a0b2546..a0486f867ff 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3227,6 +3227,7 @@ impl<'p, 'a> Comb<'p, 'a> { arg_widths, arg_signed, arg_is_string, + location: None, }); let mut preceding_writes = Vec::new(); for (id, range) in store.iter() { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index d73a10e725b..3b966683019 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2316,6 +2316,7 @@ impl<'p, 'a> Ff<'p, 'a> { arg_widths, arg_signed, arg_is_string, + location: None, }); self.b.emit(SIRInstruction::RuntimeEvent { site_id, diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 98d7979b320..8918f9e78e8 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -27,6 +27,10 @@ pub struct VerylSymbolicRtl<'a> { pub symbolic: crate::symbolic::artifact::SymbolicRtl, pub module_ir: HashMap, pub source_id_maps: HashMap>, + /// Hidden state of each module's `initial` blocks when they are + /// compiled into process kernels. + pub process_storage: + HashMap, } /// Export source-neutral port signatures before either language's hierarchy is @@ -74,7 +78,7 @@ pub fn external_signatures( let mut port_ids = module.ports.values().copied().collect::>(); port_ids.sort(); let port_order = port_ids.iter().map(|id| ids[id]).collect(); - let (sim_module, _) = + let (sim_module, _, _) = project_module_with_ids(&empty, module, config, ids, &HashMap::default())?; let id = celox_design::ModuleId(external.modules.len()); external.roots.insert(sim_module.name.clone(), id); @@ -366,6 +370,7 @@ pub(crate) fn project_module_with_ids( ( crate::symbolic::artifact::SimModule, HashMap, + crate::lowering::process::ModuleProcessStorage, ), ParserError, > { @@ -373,7 +378,7 @@ pub(crate) fn project_module_with_ids( source_variables.sort_unstable_by_key(|(id, _)| **id); let mut source_texts = HashMap::default(); - let variables = source_variables + let mut variables = source_variables .into_iter() .map(|(id, variable)| { let (dimensions, _, _) = bitaccess::get_dimensions_and_strides(ir, *id)?; @@ -422,6 +427,11 @@ pub(crate) fn project_module_with_ids( )) }) .collect::, ParserError>>()?; + let process_storage = if config.testbench_kernels { + crate::lowering::process::declare_storage(ir, &ids, &mut variables)? + } else { + Default::default() + }; let mut arena = SLTNodeArena::new(); let mut cache = HashMap::default(); @@ -566,6 +576,7 @@ pub(crate) fn project_module_with_ids( process_event_counters: Vec::new(), }, ids, + process_storage, )) } diff --git a/crates/celox-frontend-veryl/src/config.rs b/crates/celox-frontend-veryl/src/config.rs index cf32adb1e70..0a42506f8a2 100644 --- a/crates/celox-frontend-veryl/src/config.rs +++ b/crates/celox-frontend-veryl/src/config.rs @@ -7,6 +7,9 @@ pub struct BuildConfig { /// Simulation lanes requested for partitioned execution. More than one /// lane also lowers every FF trigger group as independent parts. pub parallel_lanes: u32, + /// Compile the `initial` blocks of a `#[test]` module into process + /// kernels run by the timed scheduler instead of testbench bytecode. + pub testbench_kernels: bool, } impl Default for BuildConfig { @@ -15,6 +18,7 @@ impl Default for BuildConfig { clock_type: ClockType::PosEdge, reset_type: ResetType::AsyncLow, parallel_lanes: 1, + testbench_kernels: false, } } } @@ -25,6 +29,7 @@ impl From<&veryl_metadata::Build> for BuildConfig { clock_type: build.clock_type, reset_type: build.reset_type, parallel_lanes: 1, + testbench_kernels: false, } } } diff --git a/crates/celox-frontend-veryl/src/dynamic_for_check.rs b/crates/celox-frontend-veryl/src/dynamic_for_check.rs index f186e9b4a9d..bea657363d1 100644 --- a/crates/celox-frontend-veryl/src/dynamic_for_check.rs +++ b/crates/celox-frontend-veryl/src/dynamic_for_check.rs @@ -306,6 +306,9 @@ fn check_elaborated_for( hints: &FusedSirOptimizationHints, diagnostics: &mut Vec, ) { + if initial_bound_finishes(statement, module) { + return; + } let continuation_bound = match &statement.range { ForRange::Forward { end, .. } | ForRange::Stepped { end, .. } => end, ForRange::Reverse { start, .. } => start, @@ -1269,12 +1272,78 @@ fn check_statements( } } +fn initial_bound_finishes(statement: &ForStatement, module: &Module) -> bool { + let first = match &statement.range { + ForRange::Forward { start, .. } | ForRange::Stepped { start, .. } => start, + ForRange::Reverse { end, .. } => end, + }; + let ForBound::Expression(expression) = first else { + return false; + }; + let Expression::Term(factor) = expression.as_ref() else { + return false; + }; + let Factor::FunctionCall(call) = factor.as_ref() else { + return false; + }; + fn expression_finishes( + expression: &Expression, + module: &Module, + active: &mut HashSet, + ) -> bool { + matches!(expression, Expression::Term(factor) if matches!(factor.as_ref(), Factor::FunctionCall(call) if call_finishes(call, module, active))) + } + fn call_finishes(call: &FunctionCall, module: &Module, active: &mut HashSet) -> bool { + if !active.insert(call.id) { + return false; + } + let body = module.functions.get(&call.id).and_then(|function| { + call.index + .as_deref() + .and_then(|index| function.get_function(index)) + .or_else(|| function.get_function(&[])) + }); + let finishes = body.is_some_and(|body| { + for statement in &body.statements { + match statement { + Statement::SystemFunctionCall(call) + if matches!(call.kind, SystemFunctionKind::Finish) => + { + return true; + } + Statement::Assign(assign) => { + if expression_finishes(&assign.expr, module, active) { + return true; + } + } + Statement::FunctionCall(call) => { + if call_finishes(call, module, active) { + return true; + } + } + Statement::Null + | Statement::SystemFunctionCall(_) + | Statement::TbMethodCall(_) => {} + _ => return false, + } + } + false + }); + active.remove(&call.id); + finishes + } + call_finishes(call, module, &mut HashSet::default()) +} + fn check_for( statement: &ForStatement, module: &Module, diagnostics: &mut Vec, from_ff: bool, ) { + if initial_bound_finishes(statement, module) { + return; + } let continuation_bound = match &statement.range { ForRange::Forward { end, .. } | ForRange::Stepped { end, .. } => end, ForRange::Reverse { start, .. } => start, diff --git a/crates/celox-frontend-veryl/src/hierarchy.rs b/crates/celox-frontend-veryl/src/hierarchy.rs index b8da652c4e1..3eae1a7eb1a 100644 --- a/crates/celox-frontend-veryl/src/hierarchy.rs +++ b/crates/celox-frontend-veryl/src/hierarchy.rs @@ -366,6 +366,7 @@ fn parse_external_hierarchy<'a>( .collect() }); } + let mut process_storage = HashMap::default(); for (module_id, mut sim_module) in parsed_modules { let ir_module = module_ir[&module_id]; if let Some(symbols) = &symbols @@ -390,10 +391,11 @@ fn parse_external_hierarchy<'a>( .collect(); } let id_map = source_id_maps[&module_id].clone(); - let (sim_module, id_map) = + let (sim_module, id_map, storage) = project_module_with_ids(&sim_module, ir_module, config, id_map, &source_id_maps)?; modules.insert(module_id, sim_module); source_id_maps.insert(module_id, id_map); + process_storage.insert(module_id, storage); } fn check_cycles( @@ -439,6 +441,7 @@ fn parse_external_hierarchy<'a>( }, module_ir, source_id_maps, + process_storage, }) } diff --git a/crates/celox-frontend-veryl/src/lib.rs b/crates/celox-frontend-veryl/src/lib.rs index c40be7d1f60..0973360841e 100644 --- a/crates/celox-frontend-veryl/src/lib.rs +++ b/crates/celox-frontend-veryl/src/lib.rs @@ -16,6 +16,7 @@ pub(crate) mod lowering; pub mod module; mod portability_check; mod readmem; +mod runtime_functions; mod schedule; mod source; mod testbench; @@ -41,6 +42,7 @@ pub use interface_captures::lower_interface_captures; pub use lowering::types::{resolve_dims, resolve_total_width}; pub use module::external_port_formal_names; pub use portability_check::{check_array_literal_side_effects, check_function_output_aliases}; +pub use runtime_functions::{RuntimeFunctions, preserve_terminating_function_calls}; pub use schedule::schedule_symbolic_rtl; pub use source::{ AbsoluteAddr, GlueAddr, GlueBlock, ModuleInitialMemoryValue, RegionedAbsoluteAddr, diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 871f3817388..6ac8364916b 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -21,7 +21,7 @@ use num_traits::{ToPrimitive, Zero}; use veryl_analyzer::ir::{ AssertKind, CaseStatement, Expression, FfDeclaration, FfReset, ForBound, ForRange, ForStatement, IfResetStatement, IfStatement, Module, Op, Statement, SystemFunctionCall, - SystemFunctionInput, SystemFunctionKind, TypeKind, VarId, + SystemFunctionInput, SystemFunctionKind, TypeKind, VarId, VarPath, }; use veryl_analyzer::symbol::Affiliation; use veryl_analyzer::value::Value; @@ -337,14 +337,20 @@ mod expression; pub(crate) use expression::expression_has_side_effect; mod function_call; mod inline_call; +pub(crate) use inline_call::collect_statement_variables; pub enum Domain { Ff, // TODO: add clock + /// A process kernel: blocking statements over stable state only, so + /// every variable, including locals and loop variables, lives in the + /// stable region and survives the kernel's suspensions. + Process, } impl Domain { pub fn region(&self) -> u32 { match self { Domain::Ff => WORKING_REGION, + Domain::Process => STABLE_REGION, } } } @@ -422,15 +428,38 @@ pub struct FfParser<'a> { runtime_error_code_map: Option>, runtime_event_site_base: u32, config: BuildConfig, + /// Hierarchical references a process may make, as synthetic variables + /// of the module (see `lowering::process`). + hierarchical_vars: HashMap<(Vec, VarPath), VarId>, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ControlFlow { +pub(crate) enum ControlFlow { Continue, Break, } impl<'a> FfParser<'a> { + pub(super) fn process_expression_value(&self, token: TokenRange) -> Option { + self.function_expression_value_stack + .iter() + .rev() + .find_map(|values| values.get(&token).copied()) + } + + pub(super) fn push_process_expression_values( + &mut self, + values: HashMap, + ) { + self.function_expression_value_stack.push(values); + } + + pub(super) fn pop_process_expression_values(&mut self) { + self.function_expression_value_stack + .pop() + .expect("process expression scope"); + } + pub fn new(module: &'a Module, config: BuildConfig) -> Self { let local_working_vars = module .variables @@ -467,9 +496,61 @@ impl<'a> FfParser<'a> { runtime_error_code_map: None, runtime_event_site_base: 0, config, + hierarchical_vars: HashMap::default(), } } + /// Resolve hierarchical references through synthetic variables of the + /// module, keyed by instance path and variable path. + pub(crate) fn with_hierarchical_vars( + mut self, + vars: HashMap<(Vec, VarPath), VarId>, + ) -> Self { + self.hierarchical_vars = vars; + self + } + + /// The synthetic variable of a hierarchical reference. + pub(crate) fn hierarchical_var( + &self, + key: &(Vec, VarPath), + ) -> Option<&VarId> { + self.hierarchical_vars.get(key) + } + + /// Where the runtime event sites this parser registers start. + pub(crate) fn with_runtime_event_site_base(mut self, base: u32) -> Self { + self.runtime_event_site_base = base; + self + } + + /// The runtime event sites registered so far, for annotation. + pub(crate) fn runtime_event_sites_mut(&mut self) -> &mut Vec { + &mut self.runtime_event_sites + } + + /// The value the last expression lowering produced. + pub(crate) fn pop_value(&mut self) -> RegisterId { + self.stack.pop_back().expect("an expression value") + } + + /// Make `value` the value a following store consumes. + pub(crate) fn push_value(&mut self, value: RegisterId) { + self.stack.push_back(value); + } + + /// Forget values cached in registers: after a kernel suspension, no + /// register survives. + pub(crate) fn clear_register_cache(&mut self) { + self.local_let_values.clear(); + self.stack.clear(); + } + + /// The blocks a `break` in the process lowering leaves to. + pub(crate) fn loop_exit_blocks_mut(&mut self) -> &mut Vec { + &mut self.loop_exit_blocks + } + pub fn with_relocated_runtime_ids( mut self, runtime_error_code_map: HashMap, @@ -503,7 +584,7 @@ impl<'a> FfParser<'a> { &self.runtime_event_sites } - fn runtime_error(&mut self, message: impl Into, signals: Vec) -> i64 { + pub(crate) fn runtime_error(&mut self, message: impl Into, signals: Vec) -> i64 { let local_code = self.next_runtime_error_code; self.next_runtime_error_code += 1; let code = self @@ -521,7 +602,7 @@ impl<'a> FfParser<'a> { code } - fn static_string_expr(expr: &Expression) -> Option { + pub(crate) fn static_string_expr(expr: &Expression) -> Option { if !expr.comptime().r#type.is_string() { return None; } @@ -529,7 +610,7 @@ impl<'a> FfParser<'a> { byte_value_to_string(value) } - fn register_runtime_event_site( + pub(crate) fn register_runtime_event_site( &mut self, kind: RuntimeEventKind, args: &[SystemFunctionInput], @@ -564,6 +645,7 @@ impl<'a> FfParser<'a> { .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + location: None, }; let id = self .runtime_event_site_base @@ -573,7 +655,7 @@ impl<'a> FfParser<'a> { id } - fn parse_runtime_event_expression( + pub(crate) fn parse_runtime_event_expression( &mut self, expr: &Expression, targets: &mut Vec>, @@ -601,7 +683,7 @@ impl<'a> FfParser<'a> { result } - fn emit_runtime_event( + pub(crate) fn emit_runtime_event( &mut self, site_id: u32, args: &[SystemFunctionInput], @@ -634,7 +716,7 @@ impl<'a> FfParser<'a> { Ok(()) } - fn prepare_effectful_runtime_event_args( + pub(crate) fn prepare_effectful_runtime_event_args( &mut self, args: &[SystemFunctionInput], targets: &mut Vec>, @@ -679,7 +761,7 @@ impl<'a> FfParser<'a> { .collect() } - fn emit_runtime_event_with_prepared_args( + pub(crate) fn emit_runtime_event_with_prepared_args( &mut self, site_id: u32, args: &[SystemFunctionInput], @@ -718,7 +800,7 @@ impl<'a> FfParser<'a> { Ok(()) } - fn parse_system_task_statement( + pub(crate) fn parse_system_task_statement( &mut self, call: &SystemFunctionCall, targets: &mut Vec>, @@ -926,7 +1008,7 @@ impl<'a> FfParser<'a> { eval_constexpr(expr)?.to_u64() } - fn get_constant_procedural_truth(expr: &Expression) -> Option { + pub(crate) fn get_constant_procedural_truth(expr: &Expression) -> Option { let comptime = expr.comptime(); let is_value = matches!(expr, Expression::Term(factor) if matches!(factor.as_ref(), veryl_analyzer::ir::Factor::Value(_))); if !(comptime.is_const || is_value && comptime.evaluated) { @@ -947,7 +1029,7 @@ impl<'a> FfParser<'a> { .flatten() } - fn lower_procedural_condition( + pub(crate) fn lower_procedural_condition( &self, condition: RegisterId, ir_builder: &mut SIRBuilder, @@ -996,7 +1078,7 @@ impl<'a> FfParser<'a> { } } - fn cast_reg_width_ext( + pub(crate) fn cast_reg_width_ext( &self, ir_builder: &mut SIRBuilder, reg: RegisterId, @@ -1040,7 +1122,7 @@ impl<'a> FfParser<'a> { } } - fn get_expression_width(&self, expr: &Expression) -> usize { + pub(crate) fn get_expression_width(&self, expr: &Expression) -> usize { crate::context_width::get_expr_width(expr) .or_else(|| expr.comptime().r#type.total_width()) .unwrap_or(64) @@ -1049,7 +1131,7 @@ impl<'a> FfParser<'a> { // expression / function-call lowering is split into submodules: // - parser/ff/expression.rs // - parser/ff/function_call.rs - fn parse_statement_list( + pub(crate) fn parse_statement_list( &mut self, stmts: &[Statement], targets: &mut Vec>, @@ -1619,7 +1701,7 @@ impl<'a> FfParser<'a> { } } - fn parse_for_bound( + pub(crate) fn parse_for_bound( &mut self, bound: &ForBound, canonical_width: usize, diff --git a/crates/celox-frontend-veryl/src/lowering/ff/expression.rs b/crates/celox-frontend-veryl/src/lowering/ff/expression.rs index a8f2d731c83..98eb626fcb8 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/expression.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/expression.rs @@ -3198,7 +3198,7 @@ impl<'a> FfParser<'a> { }) } - pub(super) fn op_load( + pub(crate) fn op_load( &mut self, var_id: VarId, index: &VarIndex, @@ -3210,7 +3210,9 @@ impl<'a> FfParser<'a> { ) -> Result<(), ParserError> { let is_local_let = { let variable = &self.module.variables[&var_id]; - variable.affiliation == Affiliation::AlwaysFf && variable.kind == VarKind::Let + variable.affiliation == Affiliation::AlwaysFf + && variable.kind == VarKind::Let + && !matches!(domain, Domain::Process) }; if is_local_let && let Some(&value) = self.local_let_values.get(&var_id) { let selected = self.emit_register_select( @@ -3265,7 +3267,7 @@ impl<'a> FfParser<'a> { } let is_internal = self.local_working_vars.contains(&var_id) || self.inline_function_locals.contains(&var_id); - let load_region = if is_internal { + let load_region = if is_internal && !matches!(domain, Domain::Process) { WORKING_REGION } else { STABLE_REGION @@ -3298,7 +3300,7 @@ impl<'a> FfParser<'a> { Ok(()) } - pub(super) fn op_store( + pub(crate) fn op_store( &mut self, dst: &AssignDestination, targets: &mut Vec>, @@ -3314,6 +3316,7 @@ impl<'a> FfParser<'a> { let variable = &self.module.variables[&dst.id]; variable.affiliation == Affiliation::AlwaysFf && variable.kind == VarKind::Let + && !matches!(domain, Domain::Process) && dst.index.0.is_empty() && dst.select.0.is_empty() && dst.select.1.is_none() @@ -3378,10 +3381,11 @@ impl<'a> FfParser<'a> { if self.inline_function_locals.contains(&dst.id) { // Inline function storage is blocking and call-private, so it // bypasses the FF target, seed, and commit bookkeeping. + let region = domain.region(); emit_guarded_store( ir_builder, &guard, - || convert(dst.id, WORKING_REGION), + || convert(dst.id, region), offset, target_width, src_reg, @@ -3737,7 +3741,7 @@ impl<'a> FfParser<'a> { Ok(()) } - pub(super) fn parse_assign_statement( + pub(crate) fn parse_assign_statement( &mut self, assign_statement: &AssignStatement, targets: &mut Vec>, @@ -4308,14 +4312,26 @@ impl<'a> FfParser<'a> { } } Factor::HierVariable(reference) => { - return Err(ParserError::illegal_context( - "hierarchical variable reference", - format!( - "`{}` is only valid in a native testbench block", - reference.var_path - ), - Some(&reference.comptime.token), - )); + let key = (reference.inst_path.clone(), reference.var_path.clone()); + let Some(&var_id) = self.hierarchical_vars.get(&key) else { + return Err(ParserError::illegal_context( + "hierarchical variable reference", + format!( + "`{}` is only valid in a native testbench block", + reference.var_path + ), + Some(&reference.comptime.token), + )); + }; + self.op_load( + var_id, + &reference.index, + &reference.select, + domain, + convert, + sources, + ir_builder, + )?; } Factor::Value(comptime) => { let (celox_value, mask_xz, width, _) = @@ -5154,7 +5170,7 @@ impl<'a> FfParser<'a> { Ok(()) } - pub(super) fn parse_expression( + pub(crate) fn parse_expression( &mut self, expr: &Expression, targets: &mut Vec>, diff --git a/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs b/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs index a7c82db7d33..ad8d7a230e5 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/function_call.rs @@ -723,7 +723,7 @@ impl<'a> FfParser<'a> { ) } - pub(super) fn coerce_function_input_expression( + pub(crate) fn coerce_function_input_expression( &self, expr: Expression, formal_id: VarId, @@ -1760,7 +1760,7 @@ impl<'a> FfParser<'a> { } } - pub(super) fn coerce_register_to_variable_type( + pub(crate) fn coerce_register_to_variable_type( &self, reg: RegisterId, var_id: VarId, diff --git a/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs b/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs index a08dbca3271..c2785543241 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff/inline_call.rs @@ -543,7 +543,7 @@ impl<'a> FfParser<'a> { } } -fn collect_statement_variables(statements: &[Statement], out: &mut HashSet) { +pub(crate) fn collect_statement_variables(statements: &[Statement], out: &mut HashSet) { for statement in statements { match statement { Statement::Assign(assign) => { @@ -593,10 +593,15 @@ fn collect_statement_variables(statements: &[Statement], out: &mut HashSet collect_system_call_variables(call, out), Statement::FunctionCall(call) => collect_call_variables(call, out), - Statement::TbMethodCall(_) - | Statement::Break - | Statement::Unsupported(_) - | Statement::Null => {} + Statement::TbMethodCall(tb) => { + for expr in crate::lowering::process::expressions::statement_inputs(statement) { + collect_expression_variables(expr, out); + } + if let Some(destination) = tb.ret.as_deref() { + collect_destination_variables(destination, out); + } + } + Statement::Break | Statement::Unsupported(_) | Statement::Null => {} } } } diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index 24eaf85c9b0..ddabc804c91 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -112,6 +112,7 @@ fn register_comb_runtime_event_site<'a>( .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + location: None, }; let id = collector.sites.len() as u32; collector.sites.push(site); @@ -208,7 +209,10 @@ fn collect_system_function_effect( observed_inputs.extend(collector.active_guard_sources.iter().copied()); let guard = match (kind, collector.active_guard, explicit_guard) { ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::AssertPass, active, None, ) => active, @@ -227,7 +231,10 @@ fn collect_system_function_effect( Some(active) } ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::AssertPass, _, Some(_), ) => { diff --git a/crates/celox-frontend-veryl/src/lowering/mod.rs b/crates/celox-frontend-veryl/src/lowering/mod.rs index 9b2b064ebfc..76b194f294c 100644 --- a/crates/celox-frontend-veryl/src/lowering/mod.rs +++ b/crates/celox-frontend-veryl/src/lowering/mod.rs @@ -8,5 +8,6 @@ pub(crate) mod ff; mod function_return; pub(crate) mod global_ff; pub(crate) mod logic_tree; +pub(crate) mod process; pub(crate) mod registry; pub(crate) mod types; diff --git a/crates/celox-frontend-veryl/src/lowering/process.rs b/crates/celox-frontend-veryl/src/lowering/process.rs new file mode 100644 index 00000000000..2cad569b63e --- /dev/null +++ b/crates/celox-frontend-veryl/src/lowering/process.rs @@ -0,0 +1,3775 @@ +//! The `initial` blocks of a `#[test]` module as resumable process kernels. +//! +//! Each block becomes one kernel over the elaborated instance's stable +//! state. Expressions and assignments go through [`FfParser`] in its +//! process domain; control flow, clock and reset waits, assertions and the +//! `$tb` methods are lowered here. A loop keeps its counter and bounds in +//! state, so a wait inside its body can suspend the kernel. Random numbers +//! and component methods are host requests served through scratch state. +//! A hierarchical reference becomes a synthetic variable of the module that +//! addresses the child instance's state. + +use celox_design::{ + AbsoluteAddrBase, EventLocation, HostRequest, HostValue, PROCESS_CLOCK_WIDTH, + PROCESS_DELAY_WIDTH, PROCESS_RELEASE_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessClock, + ProcessRelease, ProcessSlots, RegionedAbsoluteAddrBase, RuntimeErrorInfo, RuntimeEventKind, + STABLE_REGION, VarAtomBase, VariableMetadata, +}; +use celox_frontend_core::process::{PROCESS_RESUME_WIDTH, ProcessKernelBuilder}; +use celox_sir::{ + BasicBlock, BinaryOp, BlockId, ExecutionUnit, RegisterId, RegisterType, SIRInstruction, + SIROffset, SIRTerminator, SIRValue, UnaryOp, +}; +use num_bigint::BigUint; +use veryl_analyzer::ir::{ + AssertKind, AssignDestination, AssignStatement, Expression, ForBound, ForRange, Function, + FunctionBody, HierVarRef, Module, Op, Statement, SystemFunctionCall, SystemFunctionInput, + SystemFunctionKind, SystemFunctionOutput, TbMethod, TbMethodCall, VarId, VarIndex, VarSelect, +}; +use veryl_analyzer::symbol::Affiliation; +use veryl_parser::resource_table::{self, StrId}; + +use crate::{ + BuildConfig, FrontendLookup, HashMap, HashSet, ParserError, SourceVarId, VariableKind, + VerylTestbenchSource, + lowering::{ + case::case_arm_condition_expr, + context_width::expression_signed, + ff::{Domain, FfParser}, + types::resolve_total_width, + }, + symbolic::artifact::SymbolicVariable, +}; +use celox_frontend_core::ScheduledRtl; + +pub(crate) mod expressions; +use veryl_parser::token_range::TokenRange; + +type SourceAddr = AbsoluteAddrBase; +type RegionedSourceAddr = RegionedAbsoluteAddrBase; + +/// A hidden state object one block needs, in the order the lowering +/// consumes them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScratchNeed { + pub purpose: &'static str, + pub width: usize, +} + +/// The hidden state of one `initial` block. +#[derive(Clone, Debug)] +pub struct BlockStorage { + pub resume: SourceVarId, + pub status: SourceVarId, + pub delay: SourceVarId, + pub clock: SourceVarId, + pub release: SourceVarId, + pub event_counters: Vec<(VarId, SourceVarId, SourceVarId)>, + pub hierarchical_event_counters: Vec<(SourceVarId, SourceVarId)>, + pub scratch: Vec<(ScratchNeed, SourceVarId)>, + /// The block's own copy of each function-local variable, so a call + /// that waits keeps its arguments and locals while another block calls + /// the function. + pub private: HashMap, + /// Values preserved while nested expression calls suspend. + pub expression_values: HashMap, +} + +/// The hidden state of a module's `initial` blocks, in declaration order. +#[derive(Clone, Debug, Default)] +pub struct ModuleProcessStorage { + pub blocks: Vec, +} + +/// Declare the hidden state the module's `initial` blocks need as +/// variables after `variables`, and describe it. +pub(crate) fn declare_storage( + ir: &Module, + ids: &HashMap, + variables: &mut HashMap, +) -> Result { + let mut function_locals: Vec = ir + .variables + .iter() + .filter(|(_, variable)| variable.affiliation == Affiliation::Function) + .map(|(id, _)| *id) + .collect(); + function_locals.sort_unstable(); + let templates = function_locals + .iter() + .map(|&local| (local, variables[&ids[&local]].clone())) + .collect::>(); + let mut event_variables = ir + .variables + .keys() + .filter(|id| { + ir.variables[id].affiliation != Affiliation::Function + && matches!( + variables[&ids[id]].metadata.kind, + celox_design::DomainKind::ClockPosedge + | celox_design::DomainKind::ClockNegedge + | celox_design::DomainKind::ResetAsyncHigh + | celox_design::DomainKind::ResetAsyncLow + ) + }) + .copied() + .collect::>(); + event_variables.sort_unstable(); + let mut next = variables.len() as u32; + let mut declare = + |path: Vec, template: Option<&SymbolicVariable>, width: usize, is_4state: bool| { + let id = SourceVarId(next); + next += 1; + let variable = match template { + Some(template) => SymbolicVariable { + path, + source: None, + module_affiliated: false, + ..template.clone() + }, + None => SymbolicVariable { + path, + kind: VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state, + kind: celox_design::DomainKind::Other, + type_kind: if is_4state { + PortTypeKind::Logic + } else { + PortTypeKind::Bit + }, + array_dims: Vec::new(), + }, + packed_dims: vec![width], + source: None, + // Hidden state is not a signal of the design. + module_affiliated: false, + }, + }; + variables.insert(id, variable); + id + }; + let mut blocks = Vec::new(); + for (index, statements) in initial_blocks(ir).enumerate() { + let name = |slot: &str| vec![format!("$initial[{index}]"), slot.to_string()]; + let needs = scratch_needs(ir, statements)?; + let scratch = needs + .into_iter() + .enumerate() + .map(|(slot, need)| { + let id = declare( + name(&format!("{}@{slot}", need.purpose)), + None, + need.width, + matches!(need.purpose, "file_arg" | "function_output"), + ); + (need, id) + }) + .collect(); + let mut expression_needs = HashMap::default(); + collect_expression_storage( + ir, + statements, + &mut HashSet::default(), + None, + &mut expression_needs, + ); + let mut expression_needs = expression_needs.into_iter().collect::>(); + expression_needs.sort_by_key(|((frame, token), _)| { + ( + frame.clone(), + token + .beg + .source + .get_path() + .and_then(resource_table::get_path_value) + .map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_default(), + token.beg.pos, + token.end.pos, + ) + }); + let expression_values = expression_needs + .into_iter() + .enumerate() + .map(|(slot, (token, width))| { + let id = declare(name(&format!("expression@{slot}")), None, width, true); + (token, (width, id)) + }) + .collect(); + let private = templates + .iter() + .map(|(local, template)| { + let path = name(&format!("{}@private", template.path.join("."))); + (*local, declare(path, Some(template), 0, false)) + }) + .collect(); + blocks.push(BlockStorage { + resume: declare(name("resume"), None, PROCESS_RESUME_WIDTH, false), + status: declare(name("status"), None, PROCESS_STATUS_WIDTH, false), + delay: declare(name("delay"), None, PROCESS_DELAY_WIDTH, false), + clock: declare(name("clock"), None, PROCESS_CLOCK_WIDTH, false), + release: declare(name("release"), None, PROCESS_RELEASE_WIDTH, false), + event_counters: event_variables + .iter() + .map(|&var| { + ( + var, + declare( + name(&format!("event_rises@{}", ids[&var].0)), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, + ), + declare( + name(&format!("event_falls@{}", ids[&var].0)), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, + ), + ) + }) + .collect(), + hierarchical_event_counters: hierarchical_references(ir, statements) + .iter() + .enumerate() + .map(|(index, _)| { + ( + declare( + name(&format!("hier_event_rises@{index}")), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, + ), + declare( + name(&format!("hier_event_falls@{index}")), + None, + celox_design::PROCESS_EVENT_COUNTER_WIDTH, + false, + ), + ) + }) + .collect(), + scratch, + private, + expression_values, + }); + } + for block in &blocks { + for (_, id) in block.expression_values.values() { + let variable = variables.get_mut(id).unwrap(); + variable.metadata.is_4state = true; + variable.metadata.type_kind = PortTypeKind::Logic; + } + } + Ok(ModuleProcessStorage { blocks }) +} + +fn initial_blocks(ir: &Module) -> impl Iterator { + ir.declarations + .iter() + .filter_map(|declaration| match declaration { + veryl_analyzer::ir::Declaration::Initial(initial) => { + Some(initial.statements.as_slice()) + } + _ => None, + }) +} + +fn constant_truth(expr: &Expression) -> Option { + if expressions::has_call(expr) { + None + } else { + FfParser::get_constant_procedural_truth(expr) + } +} + +type FunctionKey = (VarId, Option>); +type ExpressionStorageKey = (Option, TokenRange); +fn function_key(call: &veryl_analyzer::ir::FunctionCall) -> FunctionKey { + (call.id, call.index.clone()) +} +fn selected_case_body(stmt: &veryl_analyzer::ir::CaseStatement) -> Option<&[Statement]> { + // Arithmetic targets need each label's comparison width. Prune only + // self-determined known nonnegative terms whose value fits in u64. + let value = |expr: &Expression| { + if !matches!(expr, Expression::Term(_)) + || expressions::has_call(expr) + || !expr.comptime().is_const + { + return None; + } + let value = expr.comptime().get_value().ok()?; + let width = value.width(); + if value.is_xz() || width == 0 || width > 64 { + return None; + } + let bits = value.payload_u64(); + if value.signed() && bits & (1u64 << (width - 1)) != 0 { + return None; + } + Some(bits) + }; + let target = value(&stmt.case_target)?; + for arm in &stmt.arms { + let mut selected = false; + for pattern in &arm.patterns { + selected |= match pattern { + veryl_analyzer::ir::CasePattern::Eq(pattern) => target == value(pattern)?, + veryl_analyzer::ir::CasePattern::Range { lo, hi, inclusive } => { + let lo = value(lo)?; + let hi = value(hi)?; + lo <= target + && if *inclusive { + target <= hi + } else { + target < hi + } + } + }; + } + if selected { + return Some(&arm.body); + } + } + Some(&stmt.default) +} + +/// Whether a range with constant bounds has no value. +fn constant_empty_range(range: &ForRange) -> bool { + let constant = |bound: &ForBound| match bound { + ForBound::Const(value, _) => Some(*value), + ForBound::Expression(_) => None, + }; + match range { + ForRange::Forward { + start, + end, + inclusive, + .. + } + | ForRange::Stepped { + start, + end, + inclusive, + .. + } => match (constant(start), constant(end)) { + (Some(start), Some(end)) => { + if *inclusive { + start > end + } else { + start >= end + } + } + _ => false, + }, + ForRange::Reverse { + start, + end, + inclusive, + .. + } => match (constant(start), constant(end)) { + (Some(start), Some(end)) => { + if *inclusive { + end < start + } else { + end <= start + } + } + _ => false, + }, + } +} + +fn constant_nonempty_range(range: &ForRange) -> bool { + let (start, end) = match range { + ForRange::Forward { start, end, .. } + | ForRange::Reverse { start, end, .. } + | ForRange::Stepped { start, end, .. } => (start, end), + }; + matches!((start, end), (ForBound::Const(..), ForBound::Const(..))) + && !constant_empty_range(range) +} + +/// How a `for` loop compares and steps, following the testbench +/// interpreter: the counter is kept at its own width, bounds compare in +/// the counter's signedness only when the bound is signed too, and a +/// step that does not move the counter is an error. +struct LoopShape<'s> { + start: &'s ForBound, + end: &'s ForBound, + inclusive: bool, + reverse: bool, + step: usize, + op: Option, + var_width: usize, + var_signed: bool, + /// The width the bounds and the counter compare in. + width: usize, + /// Whether the comparison with the bound the loop runs towards is signed. + cmp_signed: bool, + start_signed: bool, + end_signed: bool, + /// Whether an unsigned bound may hold a value above 64 bits, which the + /// interpreter only runs as a single iteration. + start_wide: bool, + end_wide: bool, +} + +impl LoopShape<'_> { + fn wide_capable(&self) -> bool { + self.start_wide || self.end_wide + } +} + +fn loop_shape<'s>( + ir: &Module, + stmt: &'s veryl_analyzer::ir::ForStatement, +) -> Result, ParserError> { + let var_width = resolve_total_width(ir, &ir.variables[&stmt.var_id])?.max(1); + let var_signed = stmt.var_type.signed; + let bound_width = |bound: &ForBound| match bound { + ForBound::Const(..) => 64, + ForBound::Expression(expr) => expr.comptime().r#type.total_width().unwrap_or(64), + }; + let bound_signed = |bound: &ForBound| match bound { + ForBound::Const(_, signed) => *signed, + ForBound::Expression(expr) => expression_signed(expr), + }; + let (start, end, inclusive, step, reverse, op) = match &stmt.range { + ForRange::Forward { + start, + end, + inclusive, + step, + } => (start, end, *inclusive, *step, false, None), + ForRange::Reverse { + start, + end, + inclusive, + step, + } => (start, end, *inclusive, *step, true, None), + ForRange::Stepped { + start, + end, + inclusive, + step, + op, + } => (start, end, *inclusive, *step, false, Some(*op)), + }; + let start_signed = bound_signed(start); + let end_signed = bound_signed(end); + let continuation_signed = if reverse { start_signed } else { end_signed }; + Ok(LoopShape { + start, + end, + inclusive, + reverse, + step, + op, + var_width, + var_signed, + width: var_width + .max(bound_width(start)) + .max(bound_width(end)) + .max(64) + + 1, + cmp_signed: var_signed && continuation_signed, + start_signed, + end_signed, + start_wide: bound_width(start) > if start_signed { 128 } else { 64 }, + end_wide: bound_width(end) > if end_signed { 128 } else { 64 }, + }) +} + +/// The width of a value passed to a component method: the width its +/// context gives it, else the width the expression evaluates in. +fn argument_width(input: &SystemFunctionInput) -> usize { + let expr = &input.0; + let context = expr.comptime().expr_context.width; + if context > 0 { + return context; + } + crate::context_width::get_expr_width(expr) + .or_else(|| expr.comptime().r#type.total_width()) + .or_else(|| expr.comptime().get_value().ok().map(|value| value.width())) + .unwrap_or(64) + .max(1) +} + +fn function_body( + functions: &HashMap, + call: &veryl_analyzer::ir::FunctionCall, +) -> Option { + let function = functions.get(&call.id)?; + match &call.index { + Some(index) => function.get_function(index), + None => function.get_function(&[]), + } +} + +// Output selectors can reenter the completed callee. Preserve its outgoing +// values (and expression result) before evaluating any selector calls. +fn output_snapshot_formals( + call: &veryl_analyzer::ir::FunctionCall, + body: &FunctionBody, +) -> Vec { + if !call.outputs.values().flatten().any(|destination| { + expressions::selection(&destination.index, &destination.select) + .into_iter() + .any(expressions::has_call) + }) { + return Vec::new(); + } + let mut formals = call + .outputs + .iter() + .filter_map(|(path, _)| body.arg_map.get(path).copied()) + .chain(body.ret) + .collect::>(); + formals.sort(); + formals.dedup(); + formals +} + +fn collect_output_scratch( + ir: &Module, + call: &veryl_analyzer::ir::FunctionCall, + body: &FunctionBody, + needs: &mut Vec, +) -> Result<(), ParserError> { + for formal in output_snapshot_formals(call, body) { + needs.push(ScratchNeed { + purpose: "function_output", + width: resolve_total_width(ir, &ir.variables[&formal])?.max(1), + }); + } + Ok(()) +} + +fn collect_expression_storage( + ir: &Module, + statements: &[Statement], + active: &mut HashSet, + frame: Option, + values: &mut HashMap, +) { + fn expr( + ir: &Module, + value: &Expression, + active: &mut HashSet, + frame: Option, + values: &mut HashMap, + ) { + if expressions::has_call(value) { + values.insert( + (frame.clone(), value.token_range()), + expressions::storage_width(value), + ); + for child in expressions::children(value) { + values.insert( + (frame.clone(), child.token_range()), + expressions::storage_width(child), + ); + } + } + for child in expressions::children(value) { + expr(ir, child, active, frame.clone(), values); + } + if let Expression::Term(factor) = value + && let veryl_analyzer::ir::Factor::FunctionCall(call) = factor.as_ref() + && active.insert(function_key(call)) + { + if let Some(body) = function_body(&ir.functions, call) { + collect_expression_storage( + ir, + &body.statements, + active, + Some(function_key(call)), + values, + ); + } + active.remove(&function_key(call)); + } + } + for statement in statements { + let inputs = expressions::statement_inputs(statement); + if inputs.iter().any(|expr| expressions::has_call(expr)) { + for input in &inputs { + values.insert( + (frame.clone(), input.token_range()), + expressions::storage_width(input), + ); + } + } + for value in inputs { + expr(ir, value, active, frame.clone(), values); + } + if let Statement::Case(stmt) = statement { + values.insert( + (frame.clone(), stmt.case_target.token_range()), + expressions::storage_width(&stmt.case_target), + ); + } + if let Statement::FunctionCall(call) = statement + && call.inputs.values().any(expressions::has_call) + { + for input in call.inputs.values() { + values.insert( + (frame.clone(), input.token_range()), + expressions::storage_width(input), + ); + } + } + if let Statement::FunctionCall(call) = statement + && active.insert(function_key(call)) + { + if let Some(body) = function_body(&ir.functions, call) { + collect_expression_storage( + ir, + &body.statements, + active, + Some(function_key(call)), + values, + ); + } + active.remove(&function_key(call)); + } + for body in expressions::statement_bodies(statement) { + collect_expression_storage(ir, body, active, frame.clone(), values); + } + } +} + +/// The scratch state the statements need, in lowering order. +fn scratch_needs(ir: &Module, statements: &[Statement]) -> Result, ParserError> { + let mut needs = Vec::new(); + let mut active = HashSet::default(); + collect_scratch_needs(ir, statements, &mut active, &mut needs)?; + // Taken first, before any statement (see `lower_block`). + needs.insert( + 0, + ScratchNeed { + purpose: "event_yield_clean", + width: 1, + }, + ); + if contains_runtime_event(ir, statements, &mut HashSet::default()) { + needs.insert( + 1, + ScratchNeed { + purpose: "event_yield", + width: EVENT_YIELD_WIDTH, + }, + ); + } + Ok(needs) +} + +/// Whether `statements`, or a function they call, emit a runtime event +/// (`$display`, `$write`, `$assert`). +fn contains_runtime_event( + ir: &Module, + statements: &[Statement], + active: &mut HashSet, +) -> bool { + for statement in statements { + if matches!(statement, Statement::SystemFunctionCall(call) if matches!(call.kind, SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) | SystemFunctionKind::Assert {..})) + { + return true; + } + let mut calls = Vec::new(); + for expr in expressions::statement_inputs(statement) { + expressions::expression_calls(expr, &mut calls); + } + if let Statement::FunctionCall(call) = statement { + calls.push(call); + } + for call in calls { + if active.insert(function_key(call)) { + let emits = function_body(&ir.functions, call) + .is_some_and(|body| contains_runtime_event(ir, &body.statements, active)); + active.remove(&function_key(call)); + if emits { + return true; + } + } + } + for body in expressions::statement_bodies(statement) { + if contains_runtime_event(ir, body, active) { + return true; + } + } + } + false +} + +fn collect_scratch_needs( + ir: &Module, + statements: &[Statement], + active: &mut HashSet, + needs: &mut Vec, +) -> Result<(), ParserError> { + let need = |needs: &mut Vec, purpose: &'static str, width: usize| { + needs.push(ScratchNeed { purpose, width }); + }; + // The planning follows the lowering: a side a constant condition keeps + // out of the kernel, and a loop over a constant-empty range, take no + // scratch, as their slots would otherwise be handed to a later statement. + for statement in statements { + let mut calls = Vec::new(); + for expr in expressions::statement_inputs(statement) { + expressions::expression_calls(expr, &mut calls); + } + for call in calls { + if active.insert(function_key(call)) { + if let Some(body) = function_body(&ir.functions, call) { + collect_scratch_needs(ir, &body.statements, active, needs)?; + collect_output_scratch(ir, call, &body, needs)?; + } + active.remove(&function_key(call)); + } + } + match statement { + Statement::If(stmt) => match constant_truth(&stmt.cond) { + Some(true) => collect_scratch_needs(ir, &stmt.true_side, active, needs)?, + Some(false) => collect_scratch_needs(ir, &stmt.false_side, active, needs)?, + None => { + collect_scratch_needs(ir, &stmt.true_side, active, needs)?; + collect_scratch_needs(ir, &stmt.false_side, active, needs)?; + } + }, + Statement::IfReset(stmt) => { + collect_scratch_needs(ir, &stmt.true_side, active, needs)?; + collect_scratch_needs(ir, &stmt.false_side, active, needs)?; + } + Statement::Case(_) => { + for body in expressions::statement_bodies(statement) { + collect_scratch_needs(ir, body, active, needs)?; + } + } + Statement::For(stmt) => { + if constant_empty_range(&stmt.range) { + continue; + } + let shape = loop_shape(ir, stmt)?; + need(needs, "for_start", shape.width); + need(needs, "for_end", shape.width); + if shape.wide_capable() { + need(needs, "for_single", 1); + } + collect_scratch_needs(ir, &stmt.body, active, needs)?; + } + Statement::FunctionCall(call) => { + if active.insert(function_key(call)) + && let Some(body) = function_body(&ir.functions, call) + { + collect_scratch_needs(ir, &body.statements, active, needs)?; + collect_output_scratch(ir, call, &body, needs)?; + active.remove(&function_key(call)); + } + } + Statement::TbMethodCall(tb) => match &tb.method { + TbMethod::FileOpen { name, .. } => need(needs, "file_arg", argument_width(name)), + TbMethod::FileWrite { args } => { + let skip = usize::from( + args.first() + .is_some_and(|arg| FfParser::static_string_expr(&arg.0).is_some()), + ); + for arg in &args[skip..] { + need(needs, "file_arg", argument_width(arg)); + } + } + TbMethod::RandomSeed { .. } => need(needs, "random_seed", 64), + TbMethod::RandomGet { width, .. } => { + need(needs, "random_value", (*width as usize).max(1)); + } + TbMethod::RandomGetRange { width, .. } => { + need(needs, "random_min", 64); + need(needs, "random_max", 64); + need(needs, "random_value", (*width as usize).max(1)); + } + TbMethod::RandomGetSeed => need(needs, "random_seed", 64), + TbMethod::Component { args, .. } => { + for arg in args { + need(needs, "component_arg", argument_width(arg)); + } + if tb.ret.is_some() { + need( + needs, + "component_result", + tb.ret_width.map_or(64, |w| w as usize).max(1), + ); + } + } + TbMethod::ClockNext { + count: Some(count), .. + } if expressions::has_call(count) => { + need(needs, "clock_count", PROCESS_DELAY_WIDTH) + } + TbMethod::ClockNext { .. } + | TbMethod::ResetAssert { .. } + | TbMethod::FileClose + | TbMethod::FileFlush => {} + }, + Statement::Assign(_) + | Statement::SystemFunctionCall(_) + | Statement::Break + | Statement::Unsupported(_) + | Statement::Null => {} + } + } + Ok(()) +} + +/// Compile the `initial` blocks of every instance in `testbench` into +/// kernels appended to `scheduled`. +pub(crate) fn lower_testbench_kernels( + scheduled: &mut ScheduledRtl, + testbench: &VerylTestbenchSource, + module_ir: &HashMap, + storage: &HashMap, + config: &BuildConfig, +) -> Result<(), ParserError> { + for source in testbench.sources() { + if source.initial_statements.is_none() { + continue; + } + let instance = source.base_instance(&scheduled.frontend_lookup); + let module_id = scheduled.frontend_lookup.instance_module[&instance]; + let ir = module_ir[&module_id]; + let storage = storage.get(&module_id).ok_or_else(|| { + ParserError::illegal_context( + "testbench process lowering", + "the module's process storage was not declared", + None, + ) + })?; + for (index, statements) in source.initial_blocks().into_iter().enumerate() { + let block = storage.blocks.get(index).ok_or_else(|| { + ParserError::illegal_context( + "testbench process lowering", + format!("initial block {index} has no process storage"), + None, + ) + })?; + lower_block( + scheduled, testbench, source, module_ir, instance, module_id, ir, block, + statements, config, + )?; + } + } + Ok(()) +} + +enum Flow { + /// The block is open; the next statement follows. + Continue, + /// Control left the block. + Ended, +} + +struct BlockLowering<'a> { + parser: FfParser<'a>, + kernel: ProcessKernelBuilder, + ir: &'a Module, + ids: &'a HashMap, + lookup: &'a FrontendLookup, + instance: celox_design::InstanceId, + module_id: celox_design::ModuleId, + hierarchical: HashMap, + private: HashMap, + loop_counters: HashSet, + expression_values: HashMap, + scratch: Vec<(ScratchNeed, SourceVarId)>, + clocks: Vec<(StrId, ProcessClock)>, + releases: Vec>, + host_requests: Vec>, + clock_periods: &'a HashMap, + resource_prefix: String, + active_functions: HashSet, + expression_frame: Option, + site_base: u32, + targets: Vec>, + sources: Vec>, + /// The process stored to design state since the combinational logic + /// was last settled, so a statement that reads design state settles + /// it first. + dirty: bool, + /// Scratch counting the runtime events emitted since the kernel last + /// gave the host a chance to drain them (see + /// [`BlockLowering::yield_for_runtime_event`]). + event_yield: Option, + /// Runtime branch state: the most recent event yield already settled a write. + event_yield_clean: Option, + event_counters: HashMap, +} + +/// Bits of the runtime-event yield counter. +const EVENT_YIELD_WIDTH: usize = 16; +/// Runtime events a kernel emits between two yields to the host: well +/// within the runtime event ring, so none is lost before the host drains. +const EVENT_YIELD_EVERY: u64 = 256; + +#[allow(clippy::too_many_arguments)] +fn lower_block( + scheduled: &mut ScheduledRtl, + testbench: &VerylTestbenchSource, + source: &VerylTestbenchSource, + module_ir: &HashMap, + instance: celox_design::InstanceId, + module_id: celox_design::ModuleId, + ir: &Module, + storage: &BlockStorage, + statements: &[Statement], + config: &BuildConfig, +) -> Result<(), ParserError> { + let lookup = &scheduled.frontend_lookup; + let ids = &testbench.id_map.module_variables[&module_id]; + // Hierarchical references become synthetic variables of a copy of the + // module, so the expression lowering treats them like local ones. + let mut module = ir.clone(); + let mut hierarchical_vars = HashMap::default(); + let mut hierarchical = HashMap::default(); + let mut next_synthetic = 0x4000_0000u32; + let references = hierarchical_references(ir, statements); + let mut event_counters: HashMap<_, _> = storage + .event_counters + .iter() + .map(|(var, rises, falls)| (*var, (*rises, *falls))) + .collect(); + let mut counter_targets: Vec<_> = storage + .event_counters + .iter() + .map(|(var, rises, falls)| { + ( + SourceAddr { + instance_id: instance, + var_id: ids[var], + }, + *rises, + *falls, + ) + }) + .collect(); + for (reference, &(rises, falls)) in references + .into_iter() + .zip(&storage.hierarchical_event_counters) + { + let key = (reference.inst_path.clone(), reference.var_path.clone()); + if hierarchical_vars.contains_key(&key) { + continue; + } + let resolved = resolve_hierarchical(lookup, module_ir, testbench, instance, &reference)?; + let id = VarId::from_raw(next_synthetic); + next_synthetic += 1; + let mut variable = resolved.variable; + variable.id = id; + module.variables.insert(id, variable); + hierarchical_vars.insert(key, id); + if let Some(signal) = lookup.state_address(&resolved.target) { + let signal = scheduled.design.events.canonical(signal); + if scheduled.design.events.ordered_events.contains(&signal) { + event_counters.insert(id, (rises, falls)); + counter_targets.push((resolved.target, rises, falls)); + } + } + hierarchical.insert(id, resolved.target); + } + let site_base = scheduled.runtime_schema.runtime_event_sites.len() as u32; + let parser = FfParser::new(&module, *config) + .with_hierarchical_vars(hierarchical_vars) + .with_runtime_event_site_base(site_base); + let stable = |var_id: SourceVarId| RegionedSourceAddr { + region: STABLE_REGION, + instance_id: instance, + var_id, + }; + let kernel = ProcessKernelBuilder::with_addresses(ProcessSlots::new( + stable(storage.resume), + stable(storage.status), + stable(storage.delay), + stable(storage.clock), + stable(storage.release), + )); + let resource_prefix = lookup + .instance_ids + .iter() + .find_map(|(path, &id)| { + (id == instance).then(|| lookup.instance_path_segments(path).join(".")) + }) + .unwrap_or_default(); + let mut lowering = BlockLowering { + parser, + kernel, + ir: &module, + ids, + lookup, + instance, + module_id, + hierarchical, + private: storage.private.clone(), + loop_counters: HashSet::default(), + expression_values: storage.expression_values.clone(), + scratch: storage.scratch.clone(), + clocks: Vec::new(), + releases: Vec::new(), + host_requests: Vec::new(), + clock_periods: &source.clock_periods, + resource_prefix, + active_functions: HashSet::default(), + expression_frame: None, + site_base, + targets: Vec::new(), + sources: Vec::new(), + dirty: false, + event_yield: None, + event_yield_clean: None, + event_counters, + }; + lowering.event_yield_clean = Some(lowering.take_scratch("event_yield_clean", 1)?.1); + let clean = lowering.constant(1, 1); + lowering.store_scratch(lowering.event_yield_clean.unwrap(), 1, clean); + if contains_runtime_event(ir, statements, &mut HashSet::default()) { + lowering.event_yield = Some(lowering.take_scratch("event_yield", EVENT_YIELD_WIDTH)?.1); + // Resume-zero entry starts a new run of this compiled kernel. + let zero = lowering.constant(0, EVENT_YIELD_WIDTH); + lowering.store_scratch(lowering.event_yield.unwrap(), EVENT_YIELD_WIDTH, zero); + } + lowering.declare_clocks(statements); + // A block that ends right after a store settles, so a process that runs + // next reads the logic derived from it. + if let Flow::Continue = lowering.lower_statements(statements)? { + lowering.settle_if_dirty()?; + } + let BlockLowering { + parser, + kernel, + clocks, + releases, + host_requests, + event_yield_clean, + .. + } = lowering; + let mut unit = kernel.build(); + prune_unreachable_blocks(&mut unit); + + // Runtime errors: the parser numbers them locally from 2000. + let next_code = scheduled + .runtime_schema + .runtime_errors + .keys() + .copied() + .max() + .map_or(1, |code| code + 1); + let mut codes = HashMap::default(); + let mut errors = parser.runtime_errors().iter().collect::>(); + errors.sort_by_key(|(code, _)| **code); + for (offset, (&local, info)) in errors.into_iter().enumerate() { + let global = next_code + offset as i64; + codes.insert(local, global); + scheduled.runtime_schema.runtime_errors.insert( + global, + RuntimeErrorInfo { + message: info.message.clone(), + signals: info + .signals + .iter() + .filter_map(|var| { + let var_id = *ids.get(var)?; + lookup.state_address(&SourceAddr { + instance_id: instance, + var_id, + }) + }) + .collect(), + }, + ); + } + for site in parser.runtime_event_sites() { + scheduled + .runtime_schema + .runtime_event_sites + .push(site.clone()); + } + let to_state = |address: &SourceAddr| { + lookup.state_address(address).ok_or_else(|| { + ParserError::illegal_context( + "testbench process lowering", + format!("{address:?} has no state object"), + None, + ) + }) + }; + let unit = map_unit(&unit, &codes, |address| { + Ok(RegionedAbsoluteAddrBase { + region: address.region, + instance_id: to_state(&SourceAddr { + instance_id: address.instance_id, + var_id: address.var_id, + })? + .instance_id, + var_id: to_state(&SourceAddr { + instance_id: address.instance_id, + var_id: address.var_id, + })? + .var_id, + }) + })?; + let slots = ProcessSlots { + comb_clean: event_yield_clean.map(|id| stable(id).into_absolute()), + resume: stable(storage.resume).into_absolute(), + status: stable(storage.status).into_absolute(), + delay: stable(storage.delay).into_absolute(), + clock: stable(storage.clock).into_absolute(), + release: stable(storage.release).into_absolute(), + clocks: clocks.into_iter().map(|(_, clock)| clock).collect(), + releases, + host_requests, + }; + let mut failure = None; + let slots = slots.map(|address| match to_state(&address) { + Ok(state) => state, + Err(error) => { + failure.get_or_insert(error); + celox_design::StateAddr { + instance_id: address.instance_id, + var_id: celox_design::StateObjectId::from_raw(0), + } + } + }); + if let Some(error) = failure { + return Err(error); + } + // The first testbench kernel marks where the design's own processes end. + scheduled + .runtime_schema + .testbench_kernels + .get_or_insert(scheduled.runtime_schema.processes.len()); + for (target, rises, falls) in &counter_targets { + let signal = to_state(target)?; + let signal = scheduled.design.events.canonical(signal); + if scheduled.design.events.ordered_events.contains(&signal) { + let counters = celox_design::ProcessEventCounters { + signal, + rises: to_state(&stable(*rises).into_absolute())?, + falls: to_state(&stable(*falls).into_absolute())?, + }; + scheduled + .runtime_schema + .testbench_read_roots + .extend([counters.rises, counters.falls]); + scheduled + .runtime_schema + .process_event_counters + .push(counters); + } + } + if let Some(flag) = slots.comb_clean { + scheduled.runtime_schema.testbench_read_roots.insert(flag); + } + scheduled.sir.processes.push(unit); + scheduled.runtime_schema.processes.push(slots); + Ok(()) +} + +trait IntoAbsolute { + fn into_absolute(self) -> SourceAddr; +} + +impl IntoAbsolute for RegionedSourceAddr { + fn into_absolute(self) -> SourceAddr { + SourceAddr { + instance_id: self.instance_id, + var_id: self.var_id, + } + } +} + +struct ResolvedHierarchical { + variable: veryl_analyzer::ir::Variable, + target: SourceAddr, +} + +/// The child instance's variable a hierarchical reference names. +fn resolve_hierarchical( + lookup: &FrontendLookup, + module_ir: &HashMap, + testbench: &VerylTestbenchSource, + base_instance: celox_design::InstanceId, + reference: &HierVarRef, +) -> Result { + let (state, _) = + crate::testbench::resolve_hierarchical_reference_from(lookup, base_instance, reference)?; + let source = lookup.state_to_source.get(&state).ok_or_else(|| { + ParserError::illegal_context( + "hierarchical variable reference", + format!("`{}` has no source variable", reference.var_path), + Some(&reference.comptime.token), + ) + })?; + let module_id = lookup.instance_module[&source.instance_id]; + let ids = &testbench.id_map.module_variables[&module_id]; + let ir = module_ir[&module_id]; + let variable = ir + .variables + .iter() + .find(|(id, _)| ids.get(id) == Some(&source.var_id)) + .map(|(_, variable)| variable.clone()) + .ok_or_else(|| { + ParserError::illegal_context( + "hierarchical variable reference", + format!("`{}` is not a variable of the instance", reference.var_path), + Some(&reference.comptime.token), + ) + })?; + Ok(ResolvedHierarchical { + variable, + target: *source, + }) +} + +/// Stable unique reference order shared by storage declaration and lowering. +fn hierarchical_references(ir: &Module, statements: &[Statement]) -> Vec { + let mut references = Vec::new(); + collect_hierarchical_references( + statements, + &ir.functions, + &mut HashSet::default(), + &mut references, + ); + let mut seen = HashSet::default(); + references + .retain(|reference| seen.insert((reference.inst_path.clone(), reference.var_path.clone()))); + references +} + +/// Every hierarchical reference the statements make, reads and writes. +fn collect_hierarchical_references( + statements: &[Statement], + functions: &HashMap, + active: &mut HashSet, + out: &mut Vec, +) { + let mut reads = Vec::new(); + crate::testbench::collect_statement_reads( + statements, + functions, + &mut HashSet::default(), + &mut reads, + ); + for read in reads { + if let crate::testbench::TestbenchRead::Hierarchical(reference) = read { + out.push(*reference); + } + } + for statement in statements { + match statement { + Statement::Assign(assign) => { + if let Some(destination) = &assign.hier_dst { + out.push(crate::testbench::hierarchical_destination_reference( + destination, + )); + } + } + Statement::SystemFunctionCall(call) => { + if let SystemFunctionKind::Readmemh(_, SystemFunctionOutput::Hier(reference)) = + &call.kind + { + out.push((**reference).clone()); + } + } + Statement::If(stmt) => { + collect_hierarchical_references(&stmt.true_side, functions, active, out); + collect_hierarchical_references(&stmt.false_side, functions, active, out); + } + Statement::IfReset(stmt) => { + collect_hierarchical_references(&stmt.true_side, functions, active, out); + collect_hierarchical_references(&stmt.false_side, functions, active, out); + } + Statement::Case(stmt) => { + for arm in &stmt.arms { + collect_hierarchical_references(&arm.body, functions, active, out); + } + collect_hierarchical_references(&stmt.default, functions, active, out); + } + Statement::For(stmt) => { + collect_hierarchical_references(&stmt.body, functions, active, out); + } + Statement::FunctionCall(call) => { + if active.insert(function_key(call)) + && let Some(body) = function_body(functions, call) + { + collect_hierarchical_references(&body.statements, functions, active, out); + active.remove(&function_key(call)); + } + } + Statement::TbMethodCall(_) + | Statement::Break + | Statement::Unsupported(_) + | Statement::Null => {} + } + } +} + +/// The address of a module variable, or of the child state a synthetic +/// variable stands for. A process reads and writes stable state only. +fn convert_fn<'b>( + instance: celox_design::InstanceId, + ids: &'b HashMap, + hierarchical: &'b HashMap, + private: &'b HashMap, +) -> impl Fn(VarId, u32) -> RegionedSourceAddr + 'b { + move |var_id, _region| { + let target = hierarchical + .get(&var_id) + .copied() + .unwrap_or_else(|| SourceAddr { + instance_id: instance, + var_id: private + .get(&var_id) + .copied() + .unwrap_or_else(|| ids[&var_id]), + }); + RegionedSourceAddr { + region: STABLE_REGION, + instance_id: target.instance_id, + var_id: target.var_id, + } + } +} + +/// The parser, kernel and the operand stacks with the address mapping. +macro_rules! parts { + ($self:ident) => {{ + let BlockLowering { + parser, + kernel, + targets, + sources, + ids, + hierarchical, + private, + instance, + .. + } = $self; + let convert = convert_fn(*instance, ids, hierarchical, private); + (parser, kernel, targets, sources, convert) + }}; +} + +impl<'a> BlockLowering<'a> { + fn scratch_addr(&self, id: SourceVarId) -> RegionedSourceAddr { + RegionedSourceAddr { + region: STABLE_REGION, + instance_id: self.instance, + var_id: id, + } + } + + fn take_scratch( + &mut self, + purpose: &'static str, + width: usize, + ) -> Result<(usize, SourceVarId), ParserError> { + // Nested expression calls can consume their storage between the host + // operation's own values. Slots are distinct; select by purpose/type + // rather than requiring planning and evaluation to interleave alike. + let position = self + .scratch + .iter() + .position(|(need, _)| need.purpose == purpose && need.width == width) + .ok_or_else(|| { + ParserError::internal( + "testbench process lowering", + format!("missing scratch for {purpose} at width {width}"), + None, + ) + })?; + let (need, id) = self.scratch.remove(position); + Ok((need.width, id)) + } + + fn error( + &self, + what: &'static str, + detail: impl Into, + token: Option<&veryl_parser::token_range::TokenRange>, + ) -> ParserError { + ParserError::illegal_context(what, detail.into(), token) + } + + /// The module variable named by a `$tb` instance. + fn instance_var(&self, inst: StrId) -> Result { + self.ir + .variables + .iter() + .find(|(_, variable)| variable.path.0.as_slice() == [inst]) + .map(|(id, _)| *id) + .ok_or_else(|| { + self.error( + "testbench method call", + format!("`{}` is not a variable of the module", source_name(inst)), + None, + ) + }) + } + + fn resource_name(&self, name: StrId) -> String { + let local = source_name(name); + if self.resource_prefix.is_empty() { + local + } else { + format!("{}.{local}", self.resource_prefix) + } + } + + /// The clocks the block waits on, in first-use order, with their + /// periods. + fn declare_clocks(&mut self, statements: &[Statement]) { + let mut active = HashSet::default(); + self.scan_clocks(statements, &mut active, true); + } + + fn contains_loop_break( + &mut self, + statements: &[Statement], + active: &mut HashSet, + ) -> bool { + for statement in statements { + if matches!(statement, Statement::Break) { + return true; + } + // The call scanner follows input/body/copy-back order. A break + // inside a callee or nested loop does not exit this loop. + if let Statement::FunctionCall(call) = statement { + if !self.scan_call_clocks(call, active, false) { + return false; + } + continue; + } + if let Statement::Case(stmt) = statement { + if !self.scan_expression_clocks(&stmt.case_target, active, false) { + return false; + } + let found = if let Some(body) = selected_case_body(stmt) { + self.contains_loop_break(body, active) + } else { + self.contains_case_break(stmt, 0, active) + }; + if found { + return true; + } + } else { + for expr in expressions::statement_inputs(statement) { + if !self.scan_expression_clocks(expr, active, false) { + return false; + } + } + let found = match statement { + Statement::For(_) => false, + Statement::If(stmt) => match constant_truth(&stmt.cond) { + Some(true) => self.contains_loop_break(&stmt.true_side, active), + Some(false) => self.contains_loop_break(&stmt.false_side, active), + None => { + self.contains_loop_break(&stmt.true_side, active) + || self.contains_loop_break(&stmt.false_side, active) + } + }, + _ => expressions::statement_bodies(statement) + .iter() + .any(|body| self.contains_loop_break(body, active)), + }; + if found { + return true; + } + } + if !self.scan_clocks(std::slice::from_ref(statement), active, false) { + return false; + } + } + false + } + + fn contains_case_break( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + arm: usize, + active: &mut HashSet, + ) -> bool { + let Some(case_arm) = stmt.arms.get(arm) else { + return self.contains_loop_break(&stmt.default, active); + }; + let condition = case_arm_condition_expr(&stmt.case_target, &case_arm.patterns); + if !self.scan_expression_clocks(&condition, active, false) { + return false; + } + match constant_truth(&condition) { + Some(true) => self.contains_loop_break(&case_arm.body, active), + Some(false) => self.contains_case_break(stmt, arm + 1, active), + None => { + self.contains_loop_break(&case_arm.body, active) + || self.contains_case_break(stmt, arm + 1, active) + } + } + } + + fn scan_clocks( + &mut self, + statements: &[Statement], + active: &mut HashSet, + declare: bool, + ) -> bool { + for statement in statements { + // Calls and case patterns have their own conditional evaluation + // order; a flat input list cannot describe their continuation. + match statement { + Statement::FunctionCall(call) => { + if !self.scan_call_clocks(call, active, declare) { + return false; + } + continue; + } + Statement::Case(stmt) => { + if !self.scan_expression_clocks(&stmt.case_target, active, declare) { + return false; + } + let continues = if let Some(body) = selected_case_body(stmt) { + self.scan_clocks(body, active, declare) + } else { + self.scan_case_clock_arms(stmt, 0, active, declare) + }; + if !continues { + return false; + } + continue; + } + _ => {} + } + for expr in expressions::statement_inputs(statement) { + if !self.scan_expression_clocks(expr, active, declare) { + return false; + } + } + match statement { + Statement::TbMethodCall(tb) => match &tb.method { + TbMethod::ClockNext { period, .. } => { + let period = self + .clock_periods + .get(&tb.inst) + .copied() + .or_else(|| period.as_deref().and_then(try_eval_const)) + .unwrap_or(2) + .max(2); + if declare { + self.declare_clock(tb.inst, period); + } + } + TbMethod::ResetAssert { clock, .. } => { + let period = self.clock_periods.get(clock).copied().unwrap_or(2).max(2); + if declare { + self.declare_clock(*clock, period); + } + } + _ => {} + }, + Statement::If(stmt) => { + let continues = match constant_truth(&stmt.cond) { + Some(true) => self.scan_clocks(&stmt.true_side, active, declare), + Some(false) => self.scan_clocks(&stmt.false_side, active, declare), + None => { + let a = self.scan_clocks(&stmt.true_side, active, declare); + let b = self.scan_clocks(&stmt.false_side, active, declare); + a || b + } + }; + if !continues { + return false; + } + } + Statement::IfReset(stmt) => { + self.scan_clocks(&stmt.true_side, active, declare); + self.scan_clocks(&stmt.false_side, active, declare); + } + Statement::For(stmt) if !constant_empty_range(&stmt.range) => { + let continues = self.scan_clocks(&stmt.body, active, declare); + if !continues + && constant_nonempty_range(&stmt.range) + && !self.contains_loop_break(&stmt.body, active) + { + return false; + } + } + Statement::SystemFunctionCall(call) + if matches!(call.kind, SystemFunctionKind::Finish) => + { + return false; + } + Statement::Break => return false, + _ => {} + } + } + true + } + + fn scan_expression_clocks( + &mut self, + expr: &Expression, + active: &mut HashSet, + declare: bool, + ) -> bool { + if let Expression::Term(factor) = expr + && let veryl_analyzer::ir::Factor::FunctionCall(call) = factor.as_ref() + { + return self.scan_call_clocks(call, active, declare); + } + match expr { + Expression::Binary(lhs, op, rhs, _) if matches!(op, Op::LogicAnd | Op::LogicOr) => { + if !self.scan_expression_clocks(lhs, active, declare) { + return false; + } + match constant_truth(lhs) { + Some(truth) + if (*op == Op::LogicAnd && !truth) || (*op == Op::LogicOr && truth) => + { + true + } + Some(_) => self.scan_expression_clocks(rhs, active, declare), + None => { + // RHS runs only on the non-short-circuit path. + self.scan_expression_clocks(rhs, active, declare); + true + } + } + } + Expression::Ternary(cond, yes, no, _) => { + if !self.scan_expression_clocks(cond, active, declare) { + return false; + } + match constant_truth(cond) { + Some(true) => self.scan_expression_clocks(yes, active, declare), + Some(false) => self.scan_expression_clocks(no, active, declare), + None => { + let yes = self.scan_expression_clocks(yes, active, declare); + let no = self.scan_expression_clocks(no, active, declare); + yes || no + } + } + } + _ => expressions::children(expr) + .into_iter() + .all(|child| self.scan_expression_clocks(child, active, declare)), + } + } + + fn scan_call_clocks( + &mut self, + call: &veryl_analyzer::ir::FunctionCall, + active: &mut HashSet, + declare: bool, + ) -> bool { + // Match lower_function_call's formal argument and copy-back order. + let paths = self.ir.functions[&call.id] + .args + .iter() + .flat_map(|arg| arg.members.iter().map(|(path, _, _)| path.clone())) + .collect::>(); + for path in &paths { + if let Some(expr) = call + .inputs + .iter() + .find_map(|(input, expr)| (input == path).then_some(expr)) + && !self.scan_expression_clocks(expr, active, declare) + { + return false; + } + } + if active.insert(function_key(call)) { + let continues = function_body(&self.ir.functions, call) + .is_none_or(|body| self.scan_clocks(&body.statements, active, declare)); + active.remove(&function_key(call)); + if !continues { + return false; + } + } + for path in &paths { + if let Some(destinations) = call + .outputs + .iter() + .find_map(|(output, destinations)| (output == path).then_some(destinations)) + { + for destination in destinations { + for expr in expressions::selection(&destination.index, &destination.select) { + if !self.scan_expression_clocks(expr, active, declare) { + return false; + } + } + } + } + } + true + } + + fn scan_case_clock_arms( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + arm: usize, + active: &mut HashSet, + declare: bool, + ) -> bool { + let Some(case_arm) = stmt.arms.get(arm) else { + return self.scan_clocks(&stmt.default, active, declare); + }; + let condition = case_arm_condition_expr(&stmt.case_target, &case_arm.patterns); + if !self.scan_expression_clocks(&condition, active, declare) { + return false; + } + match constant_truth(&condition) { + Some(true) => self.scan_clocks(&case_arm.body, active, declare), + Some(false) => self.scan_case_clock_arms(stmt, arm + 1, active, declare), + None => { + let matched = self.scan_clocks(&case_arm.body, active, declare); + let unmatched = self.scan_case_clock_arms(stmt, arm + 1, active, declare); + matched || unmatched + } + } + } + + fn declare_clock(&mut self, inst: StrId, period: u64) { + if self.clocks.iter().any(|(name, _)| *name == inst) { + return; + } + let Ok(var) = self.instance_var(inst) else { + return; + }; + let signal = SourceAddr { + instance_id: self.instance, + var_id: self.ids[&var], + }; + self.clocks.push((inst, ProcessClock { signal, period })); + let index = self.kernel.add_clock(); + debug_assert_eq!(index as usize + 1, self.clocks.len()); + } + + fn clock_index(&self, inst: StrId) -> Result { + self.clocks + .iter() + .position(|(name, _)| *name == inst) + .map(|index| index as u32) + .ok_or_else(|| { + self.error( + "testbench method call", + format!("`{}` is not a clock of the module", source_name(inst)), + None, + ) + }) + } + + // ------------------------------------------------------------ helpers + + fn raw_expression(&mut self, expr: &Expression) -> Result { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.parse_expression( + expr, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + None, + )?; + Ok(parser.pop_value()) + } + + fn condition(&mut self, expr: &Expression) -> Result { + let value = self.expression(expr)?; + Ok(self + .parser + .lower_procedural_condition(value, self.kernel.builder())) + } + + /// `value` as an unsigned two-state register of `width` bits. + fn unsigned_bits(&mut self, value: RegisterId, width: usize) -> RegisterId { + let builder = self.kernel.builder(); + let value = match *builder.register(&value) { + RegisterType::Logic { width } => { + let two_state = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Unary(two_state, UnaryOp::ToTwoState, value)); + two_state + } + RegisterType::Bit { .. } => value, + }; + let signed = matches!( + builder.register(&value), + RegisterType::Bit { signed: true, .. } + ); + let cast = self + .parser + .cast_reg_width_ext(self.kernel.builder(), value, width, signed); + let builder = self.kernel.builder(); + match *builder.register(&cast) { + RegisterType::Bit { + width: w, + signed: false, + } if w == width => cast, + _ => { + let unsigned = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Unary(unsigned, UnaryOp::Ident, cast)); + unsigned + } + } + } + + fn constant(&mut self, value: u64, width: usize) -> RegisterId { + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm(reg, SIRValue::new(value))); + reg + } + + fn store_scratch(&mut self, id: SourceVarId, width: usize, value: RegisterId) { + let address = self.scratch_addr(id); + self.kernel.builder().emit(SIRInstruction::Store( + address, + SIROffset::Static(0), + width, + value, + Vec::new(), + Vec::new(), + )); + } + + fn load_scratch(&mut self, id: SourceVarId, width: usize, signed: bool) -> RegisterId { + let address = self.scratch_addr(id); + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, signed); + builder.emit(SIRInstruction::Load( + reg, + address, + SIROffset::Static(0), + width, + )); + reg + } + + fn load_output_scratch( + &mut self, + id: SourceVarId, + width: usize, + signed: bool, + two_state: bool, + ) -> RegisterId { + if two_state { + return self.load_scratch(id, width, signed); + } + let address = self.scratch_addr(id); + let builder = self.kernel.builder(); + let reg = builder.alloc_logic(width); + builder.emit(SIRInstruction::Load( + reg, + address, + SIROffset::Static(0), + width, + )); + reg + } + + fn destination( + &self, + var_id: VarId, + token: veryl_parser::token_range::TokenRange, + ) -> AssignDestination { + AssignDestination { + id: var_id, + path: self.ir.variables[&var_id].path.clone(), + index: VarIndex::default(), + select: VarSelect::default(), + comptime: Default::default(), + token, + } + } + + fn copy_back( + &mut self, + destination: &AssignDestination, + load: impl FnOnce(&mut Self) -> Result, + ) -> Result { + let inputs = expressions::selection(&destination.index, &destination.select); + if !inputs.is_empty() { + self.settle_if_dirty()?; + } + let mut bindings = HashMap::default(); + if inputs.iter().any(|expr| expressions::has_call(expr)) { + for expr in &inputs { + let value = self.expression(expr)?; + if !self.scan_expression_clocks(expr, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } + self.save_expression(expr, value)?; + } + bindings = inputs + .into_iter() + .map(|expr| (expr.token_range(), self.saved_expression(expr))) + .collect(); + } + self.parser.push_process_expression_values(bindings); + let result = load(self).and_then(|value| self.store(destination, value)); + self.parser.pop_process_expression_values(); + result?; + Ok(Flow::Continue) + } + + fn store( + &mut self, + destination: &AssignDestination, + value: RegisterId, + ) -> Result<(), ParserError> { + if let Some(&id) = self.ids.get(&destination.id) + && let Some(info) = self.lookup.module_variables[&self.module_id].get(&id) + { + crate::testbench::ExprCompiler::validate_target_bounds_parts( + info, + &destination.index, + &destination.select, + ) + .map_err(|error| match error { + ParserError::IllegalContext { + feature, detail, .. + } => ParserError::illegal_context(feature, detail, Some(&destination.token)), + other => other, + })?; + } + if self.is_design_variable(destination.id) { + self.mark_dirty(); + } + let counters = self.event_counters.get(&destination.id).copied(); + let before = if counters.is_some() { + self.parser.clear_register_cache(); + Some(self.load_var(destination.id)?) + } else { + None + }; + { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.push_value(value); + parser.op_store( + destination, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + )?; + } + if let (Some((rises, falls)), Some(before)) = (counters, before) { + self.parser.clear_register_cache(); + let after = self.load_var(destination.id)?; + self.record_event_edges(before, after, rises, falls); + } + Ok(()) + } + + fn record_event_edges( + &mut self, + before: RegisterId, + after: RegisterId, + rises: SourceVarId, + falls: SourceVarId, + ) { + let builder = self.kernel.builder(); + let logic = matches!(builder.register(&before), RegisterType::Logic { .. }); + let mut known = Vec::new(); + for value in [0u8, 1] { + let reg = if logic { + builder.alloc_logic(1) + } else { + builder.alloc_bit(1, false) + }; + builder.emit(SIRInstruction::Imm(reg, SIRValue::new(value))); + known.push(reg); + } + let mut eq = Vec::new(); + for value in [before, after] { + for constant in &known { + let reg = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + reg, + value, + BinaryOp::EqCase, + *constant, + )); + eq.push(reg); + } + } + for (counter, a, b, c, d) in [ + (rises, eq[0], eq[2], eq[1], eq[3]), + (falls, eq[1], eq[3], eq[0], eq[2]), + ] { + let not_b = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary(not_b, UnaryOp::BitNot, b)); + let first = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(first, a, BinaryOp::And, not_b)); + let not_c = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary(not_c, UnaryOp::BitNot, c)); + let second = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(second, not_c, BinaryOp::And, d)); + let edge = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(edge, first, BinaryOp::Or, second)); + let width = celox_design::PROCESS_EVENT_COUNTER_WIDTH; + let delta = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Unary(delta, UnaryOp::Ident, edge)); + let address = RegionedSourceAddr { + region: STABLE_REGION, + instance_id: self.instance, + var_id: counter, + }; + let old = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Load( + old, + address, + SIROffset::Static(0), + width, + )); + let next = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Binary(next, old, BinaryOp::Add, delta)); + builder.emit(SIRInstruction::Store( + address, + SIROffset::Static(0), + width, + next, + Vec::new(), + Vec::new(), + )); + } + } + + fn is_design_variable(&self, id: VarId) -> bool { + self.hierarchical.contains_key(&id) + || (!self.private.contains_key(&id) + && !self.loop_counters.contains(&id) + && self + .ir + .variables + .get(&id) + .is_some_and(|variable| variable.affiliation == Affiliation::Module)) + } + + fn mark_dirty(&mut self) { + self.dirty = true; + if let Some(slot) = self.event_yield_clean { + let zero = self.constant(0, 1); + self.store_scratch(slot, 1, zero); + } + } + + /// Settle the combinational logic before a read of design state that + /// follows a store, as the statements of a testbench are sequential. + fn settle_if_dirty(&mut self) -> Result<(), ParserError> { + if !self.dirty { + return Ok(()); + } + let after = if let Some(slot) = self.event_yield_clean { + let clean = self.load_scratch(slot, 1, false); + let builder = self.kernel.builder(); + let settle = builder.new_block(); + let after = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: clean, + true_block: (after, Vec::new()), + false_block: (settle, Vec::new()), + }); + builder.switch_to_block(settle); + Some(after) + } else { + None + }; + self.kernel + .settle() + .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + if let Some(after) = after { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(after, Vec::new())); + self.kernel.builder().switch_to_block(after); + let clean = self.constant(1, 1); + self.store_scratch(self.event_yield_clean.unwrap(), 1, clean); + } + self.suspended(); + Ok(()) + } + + fn load_var(&mut self, var_id: VarId) -> Result { + let (parser, kernel, _targets, sources, convert) = parts!(self); + parser.op_load( + var_id, + &VarIndex::default(), + &VarSelect::default(), + &Domain::Process, + &convert, + sources, + kernel.builder(), + )?; + Ok(parser.pop_value()) + } + + /// The process gave control to the runtime: registers and the settled + /// state are fresh when it resumes. + fn suspended(&mut self) { + self.parser.clear_register_cache(); + self.dirty = false; + if let Some(slot) = self.event_yield_clean { + let clean = self.constant(1, 1); + self.store_scratch(slot, 1, clean); + } + } + + fn host_scratch( + &mut self, + purpose: &'static str, + width: usize, + signed: bool, + is_string: bool, + ) -> Result<(HostValue, SourceVarId), ParserError> { + let (width, id) = self.take_scratch(purpose, width)?; + Ok(( + HostValue { + signal: SourceAddr { + instance_id: self.instance, + var_id: id, + }, + width, + signed, + is_string, + }, + id, + )) + } + + fn host_request(&mut self, request: HostRequest) -> Result<(), ParserError> { + // Random requests do not settle the design themselves. + self.settle_if_dirty()?; + self.host_requests.push(request); + let index = self.kernel.add_host_request(); + debug_assert_eq!(index as usize + 1, self.host_requests.len()); + self.kernel + .host(index) + .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + self.suspended(); + Ok(()) + } + + // --------------------------------------------------------- statements + + fn lower_statements(&mut self, statements: &[Statement]) -> Result { + for statement in statements { + if let Flow::Ended = self.lower_statement(statement)? { + return Ok(Flow::Ended); + } + } + Ok(Flow::Continue) + } + + fn lower_statement(&mut self, statement: &Statement) -> Result { + let flow = self.lower_statement_body(statement)?; + if matches!(flow, Flow::Continue) + && !self.scan_clocks( + std::slice::from_ref(statement), + &mut HashSet::default(), + false, + ) + { + self.kernel.finish(); + return Ok(Flow::Ended); + } + Ok(flow) + } + + fn lower_statement_body(&mut self, statement: &Statement) -> Result { + let reads = match statement { + Statement::Null | Statement::Break => false, + Statement::SystemFunctionCall(call) => !matches!(call.kind, SystemFunctionKind::Finish), + _ => true, + }; + if reads { + self.settle_if_dirty()?; + } + match statement { + Statement::Assign(assign) => { + if let Flow::Ended = self.lower_assign(assign)? { + return Ok(Flow::Ended); + } + if assign.hier_dst.is_some() + || assign + .dst + .iter() + .any(|destination| self.is_design_variable(destination.id)) + { + self.mark_dirty(); + } + Ok(Flow::Continue) + } + Statement::If(stmt) => { + // A constant condition keeps the other side out of the + // kernel, as the interpreter never ran it. + match constant_truth(&stmt.cond) { + Some(true) => self.lower_statements(&stmt.true_side), + Some(false) => self.lower_statements(&stmt.false_side), + None => { + let condition = self.condition(&stmt.cond)?; + if !self.scan_expression_clocks(&stmt.cond, &mut HashSet::default(), false) + { + self.kernel.finish(); + return Ok(Flow::Ended); + } + self.branch(condition, &stmt.true_side, &stmt.false_side) + } + } + } + Statement::IfReset(stmt) => Err(self.error( + "statement in an initial block", + "if_reset", + Some(&stmt.token), + )), + Statement::Case(stmt) => self.lower_case(stmt), + Statement::For(stmt) => { + if constant_empty_range(&stmt.range) { + // The body never runs; its `$readmemh` files need not exist. + return Ok(Flow::Continue); + } + self.lower_for(stmt) + } + Statement::Break => { + let Some(exit) = self.parser.loop_exit_blocks_mut().last().copied() else { + return Err(self.error( + "statement in an initial block", + "break outside loop", + None, + )); + }; + self.settle_if_dirty()?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(exit, Vec::new())); + Ok(Flow::Ended) + } + Statement::SystemFunctionCall(call) => self.lower_system_function(call), + Statement::FunctionCall(call) => self.lower_function_call(call), + Statement::TbMethodCall(tb) => self.lower_tb_method(tb), + Statement::Null => Ok(Flow::Continue), + Statement::Unsupported(token) => Err(self.error( + "statement in an initial block", + "unsupported statement", + Some(token), + )), + } + } + + /// Branch on `condition` into two bodies that rejoin. + fn branch( + &mut self, + condition: RegisterId, + true_side: &[Statement], + false_side: &[Statement], + ) -> Result { + let builder = self.kernel.builder(); + let then_block = builder.new_block(); + let else_block = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (then_block, Vec::new()), + false_block: (else_block, Vec::new()), + }); + // Each side starts from the state before the branch; the join is + // dirty when any side reaching it stored. + let dirty_before = self.dirty; + let mut joined = None; + for (block, body) in [(then_block, true_side), (else_block, false_side)] { + self.kernel.builder().switch_to_block(block); + self.dirty = dirty_before; + if let Flow::Continue = self.lower_statements(body)? { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + joined = Some(joined.unwrap_or(false) || self.dirty); + } + } + self.join(join, joined) + } + + /// Continue in `join`, which `joined` sides reach with that dirty state, + /// or end the block when no side reaches it. + fn join(&mut self, join: BlockId, joined: Option) -> Result { + self.kernel.builder().switch_to_block(join); + match joined { + Some(dirty) => { + self.dirty = dirty; + Ok(Flow::Continue) + } + None => { + self.kernel.builder().seal_block(SIRTerminator::Return); + Ok(Flow::Ended) + } + } + } + + fn lower_case( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + ) -> Result { + let value = self.expression(&stmt.case_target)?; + if !self.scan_expression_clocks(&stmt.case_target, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } + self.save_expression(&stmt.case_target, value)?; + if let Some(body) = selected_case_body(stmt) { + return self.lower_statements(body); + } + self.lower_case_arm(stmt, 0) + } + + fn lower_case_arm( + &mut self, + stmt: &veryl_analyzer::ir::CaseStatement, + arm: usize, + ) -> Result { + let Some(case_arm) = stmt.arms.get(arm) else { + return self.lower_statements(&stmt.default); + }; + let condition_expr = case_arm_condition_expr(&stmt.case_target, &case_arm.patterns); + self.settle_if_dirty()?; + let target = self.saved_expression(&stmt.case_target); + self.parser.push_process_expression_values( + [(stmt.case_target.token_range(), target)] + .into_iter() + .collect(), + ); + let condition = self.condition(&condition_expr); + self.parser.pop_process_expression_values(); + let condition = condition?; + if !self.scan_expression_clocks(&condition_expr, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } + let builder = self.kernel.builder(); + let then_block = builder.new_block(); + let else_block = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (then_block, Vec::new()), + false_block: (else_block, Vec::new()), + }); + let dirty_before = self.dirty; + let mut joined = None; + self.kernel.builder().switch_to_block(then_block); + if let Flow::Continue = self.lower_statements(&case_arm.body)? { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + joined = Some(self.dirty); + } + self.kernel.builder().switch_to_block(else_block); + self.dirty = dirty_before; + if let Flow::Continue = self.lower_case_arm(stmt, arm + 1)? { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + joined = Some(joined.unwrap_or(false) || self.dirty); + } + self.join(join, joined) + } + + fn lower_assign(&mut self, assign: &AssignStatement) -> Result { + // A constant index or part select outside the destination is an + // error of the testbench, as it was for the interpreter. + for destination in &assign.dst { + if let Some(&var_id) = self.ids.get(&destination.id) + && let Some(info) = self.lookup.module_variables[&self.module_id].get(&var_id) + { + crate::testbench::ExprCompiler::validate_target_bounds_parts( + info, + &destination.index, + &destination.select, + ) + .map_err(|error| match error { + ParserError::IllegalContext { + feature, detail, .. + } => ParserError::illegal_context(feature, detail, Some(&destination.token)), + other => other, + })?; + } + } + let rewritten; + let assign = if let Some(destination) = &assign.hier_dst { + let reference = crate::testbench::hierarchical_destination_reference(destination); + let key = (reference.inst_path.clone(), reference.var_path.clone()); + let id = *self.parser.hierarchical_var(&key).ok_or_else(|| { + self.error( + "hierarchical assignment", + format!("`{}` was not resolved", destination.var_path), + Some(&destination.token), + ) + })?; + // The child's variable is checked like a local destination. + if let Some(target) = self.hierarchical.get(&id) + && let Some(module) = self.lookup.instance_module.get(&target.instance_id) + && let Some(info) = self + .lookup + .module_variables + .get(module) + .and_then(|variables| variables.get(&target.var_id)) + { + crate::testbench::ExprCompiler::validate_target_bounds_parts( + info, + &destination.index, + &destination.select, + ) + .map_err(|error| match error { + ParserError::IllegalContext { + feature, detail, .. + } => ParserError::illegal_context(feature, detail, Some(&destination.token)), + other => other, + })?; + } + rewritten = AssignStatement { + dst: vec![AssignDestination { + id, + path: destination.var_path.clone(), + index: destination.index.clone(), + select: destination.select.clone(), + comptime: destination.comptime.clone(), + token: destination.token, + }], + hier_dst: None, + width: assign.width, + expr: assign.expr.clone(), + token: assign.token, + }; + &rewritten + } else { + assign + }; + let statement = Statement::Assign(assign.clone()); + let Some(bindings) = + self.expression_bindings(&expressions::statement_inputs(&statement))? + else { + return Ok(Flow::Ended); + }; + self.parser.push_process_expression_values(bindings); + let mut counter_values = Vec::new(); + for destination in &assign.dst { + if let Some(&(rises, falls)) = self.event_counters.get(&destination.id) { + self.parser.clear_register_cache(); + let before = self.load_var(destination.id)?; + counter_values.push((destination.id, rises, falls, before)); + } + } + let result = { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.parse_assign_statement( + assign, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + ) + }; + self.parser.pop_process_expression_values(); + result?; + for (var, rises, falls, before) in counter_values { + self.parser.clear_register_cache(); + let after = self.load_var(var)?; + self.record_event_edges(before, after, rises, falls); + } + Ok(Flow::Continue) + } + + /// A `for` loop whose counter and bounds live in state, so its body + /// may suspend. See [`LoopShape`] for the semantics. + fn lower_for(&mut self, stmt: &veryl_analyzer::ir::ForStatement) -> Result { + self.loop_counters.insert(stmt.var_id); + let shape = loop_shape(self.ir, stmt)?; + let LoopShape { + inclusive, + reverse, + step, + op, + var_width, + var_signed, + width, + cmp_signed, + .. + } = shape; + let (_, start_slot) = self.take_scratch("for_start", width)?; + let (_, end_slot) = self.take_scratch("for_end", width)?; + let single_slot = if shape.wide_capable() { + Some(self.take_scratch("for_single", 1)?.1) + } else { + None + }; + let start_reg = self.for_bound(shape.start, width, cmp_signed)?; + if let ForBound::Expression(expression) = shape.start + && self.argument_ended(expression) + { + return Ok(Flow::Ended); + } + self.store_scratch(start_slot, width, start_reg); + let end_reg = self.for_bound(shape.end, width, cmp_signed)?; + if let ForBound::Expression(expression) = shape.end + && self.argument_ended(expression) + { + return Ok(Flow::Ended); + } + self.store_scratch(end_slot, width, end_reg); + // Bounds can write design state even when the range is empty. + self.settle_if_dirty()?; + let start_reg = self.load_scratch(start_slot, width, cmp_signed); + let end_reg = self.load_scratch(end_slot, width, cmp_signed); + let var = self.destination(stmt.var_id, stmt.token); + let stall_message = format!( + "non-progressing stepped for loop (loop variable `{}`)", + source_name(stmt.var_name) + ); + + let builder = self.kernel.builder(); + let header = builder.new_block(); + let body = builder.new_block(); + let latch = builder.new_block(); + let exit = builder.new_block(); + let normal = builder.new_block(); + + // A bound above 64 bits runs the body once when the range is that + // one value, nothing when it is empty, and fails otherwise. + if let Some(single_slot) = single_slot { + let mut wide = None; + for (reg, is_wide, signed_bound) in [ + (start_reg, shape.start_wide, shape.start_signed), + (end_reg, shape.end_wide, shape.end_signed), + ] { + if !is_wide { + continue; + } + let signed_high = if signed_bound { + let low = self + .parser + .cast_reg_width_ext(self.kernel.builder(), reg, 128, true); + Some(self.extend_for_compare(low, width, true)) + } else { + None + }; + let builder = self.kernel.builder(); + let shift = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm(shift, SIRValue::new(64u64))); + let high = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Binary(high, reg, BinaryOp::Shr, shift)); + let zero = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); + let nonzero = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + nonzero, + if signed_bound { reg } else { high }, + BinaryOp::Ne, + signed_high.unwrap_or(zero), + )); + wide = Some(match wide { + None => nonzero, + Some(previous) => { + let either = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + either, + previous, + BinaryOp::Or, + nonzero, + )); + either + } + }); + } + let wide = wide.expect("a wide bound"); + let builder = self.kernel.builder(); + let wide_block = builder.new_block(); + let single_block = builder.new_block(); + let fail_block = builder.new_block(); + let decide_block = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: wide, + true_block: (wide_block, Vec::new()), + false_block: (normal, Vec::new()), + }); + builder.switch_to_block(wide_block); + let empty = builder.alloc_bit(1, false); + let (lhs, op_empty, rhs) = match (reverse, inclusive, cmp_signed) { + (false, true, true) => (start_reg, BinaryOp::GtS, end_reg), + (false, true, false) => (start_reg, BinaryOp::GtU, end_reg), + (false, false, true) => (start_reg, BinaryOp::GeS, end_reg), + (false, false, false) => (start_reg, BinaryOp::GeU, end_reg), + (true, true, true) => (end_reg, BinaryOp::LtS, start_reg), + (true, true, false) => (end_reg, BinaryOp::LtU, start_reg), + (true, false, true) => (end_reg, BinaryOp::LeS, start_reg), + (true, false, false) => (end_reg, BinaryOp::LeU, start_reg), + }; + builder.emit(SIRInstruction::Binary(empty, lhs, op_empty, rhs)); + builder.seal_block(SIRTerminator::Branch { + cond: empty, + true_block: (exit, Vec::new()), + false_block: (decide_block, Vec::new()), + }); + builder.switch_to_block(decide_block); + let single = if inclusive { + let same = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + same, + start_reg, + BinaryOp::Eq, + end_reg, + )); + same + } else { + let never = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u64))); + never + }; + builder.seal_block(SIRTerminator::Branch { + cond: single, + true_block: (single_block, Vec::new()), + false_block: (fail_block, Vec::new()), + }); + builder.switch_to_block(fail_block); + let code = self.parser.runtime_error( + format!( + "dynamic for-loop bound exceeds host {}", + if var_signed { "i128" } else { "usize" } + ), + vec![stmt.var_id], + ); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + self.kernel.builder().switch_to_block(single_block); + let one = self.constant(1, 1); + self.store_scratch(single_slot, 1, one); + let counter = self.parser.cast_reg_width_ext( + self.kernel.builder(), + start_reg, + var_width, + cmp_signed, + ); + self.store(&var, counter)?; + self.parser.clear_register_cache(); + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(body, Vec::new())); + self.kernel.builder().switch_to_block(normal); + let zero = self.constant(0, 1); + self.store_scratch(single_slot, 1, zero); + } else { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(normal, Vec::new())); + self.kernel.builder().switch_to_block(normal); + } + + // A signed counter cannot reach an unsigned bound above its maximum. + if var_signed && var_width <= 64 { + let max = (1u64 << (var_width - 1)) - 1; + for (reg, bound_signed, is_end) in [ + (start_reg, shape.start_signed, false), + (end_reg, shape.end_signed, true), + ] { + if bound_signed { + continue; + } + let builder = self.kernel.builder(); + let limit = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(limit, SIRValue::new(max))); + let above = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(above, reg, BinaryOp::GtU, limit)); + let out_of_range = if is_end && !inclusive { + // An exclusive end one above the maximum is reachable. + let next = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(next, SIRValue::new(max + 1))); + let allowed = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(allowed, reg, BinaryOp::Eq, next)); + let not_allowed = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary( + not_allowed, + UnaryOp::LogicNot, + allowed, + )); + let out = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary( + out, + above, + BinaryOp::And, + not_allowed, + )); + out + } else { + above + }; + let fail_block = builder.new_block(); + let continue_block = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: out_of_range, + true_block: (fail_block, Vec::new()), + false_block: (continue_block, Vec::new()), + }); + builder.switch_to_block(fail_block); + let code = self + .parser + .runtime_error(stall_message.clone(), vec![stmt.var_id]); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + self.kernel.builder().switch_to_block(continue_block); + } + } + + // The counter starts at the first value of the range. + let initial = if reverse { + if inclusive { + end_reg + } else { + let builder = self.kernel.builder(); + let one = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + let first = builder.alloc_bit(width, cmp_signed); + builder.emit(SIRInstruction::Binary(first, end_reg, BinaryOp::Sub, one)); + first + } + } else { + start_reg + }; + let initial = + self.parser + .cast_reg_width_ext(self.kernel.builder(), initial, var_width, cmp_signed); + self.store(&var, initial)?; + self.parser.clear_register_cache(); + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(header, Vec::new())); + + // Header: compare the counter with the bound it runs towards. + self.kernel.builder().switch_to_block(header); + let current = self.load_var(stmt.var_id)?; + let current = self.extend_for_compare(current, width, cmp_signed); + let bound = if reverse { + self.load_scratch(start_slot, width, cmp_signed) + } else { + self.load_scratch(end_slot, width, cmp_signed) + }; + let builder = self.kernel.builder(); + let in_range = builder.alloc_bit(1, false); + let op_in_range = match (reverse, inclusive, cmp_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, + }; + builder.emit(SIRInstruction::Binary( + in_range, + current, + op_in_range, + bound, + )); + builder.seal_block(SIRTerminator::Branch { + cond: in_range, + true_block: (body, Vec::new()), + false_block: (exit, Vec::new()), + }); + + // Body. + self.kernel.builder().switch_to_block(body); + self.parser.clear_register_cache(); + self.parser.loop_exit_blocks_mut().push(exit); + let flow = self.lower_statements(&stmt.body); + self.parser.loop_exit_blocks_mut().pop(); + let body_flow = flow?; + if let Flow::Continue = body_flow { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(latch, Vec::new())); + } + + // Latch: the step at the counter's width; a counter that does not + // move towards the bound is an error. + self.kernel.builder().switch_to_block(latch); + self.parser.clear_register_cache(); + let current = self.load_var(stmt.var_id)?; + let builder = self.kernel.builder(); + let step_bits = if var_width < 64 { + (step as u64) & ((1u64 << var_width) - 1) + } else { + step as u64 + }; + let step_reg = builder.alloc_bit(var_width, var_signed); + builder.emit(SIRInstruction::Imm(step_reg, SIRValue::new(step_bits))); + let next = builder.alloc_bit(var_width, var_signed); + let binary = match op { + None if reverse => Some(BinaryOp::Sub), + None => Some(BinaryOp::Add), + Some(Op::Add) => Some(BinaryOp::Add), + Some(Op::Sub) => Some(BinaryOp::Sub), + Some(Op::Mul) => Some(BinaryOp::Mul), + Some(Op::LogicShiftL | Op::ArithShiftL) => { + if step >= var_width { + None + } else { + Some(BinaryOp::Shl) + } + } + Some(Op::BitOr) => Some(BinaryOp::Or), + Some(Op::BitXor) => Some(BinaryOp::Xor), + Some(Op::BitAnd) => Some(BinaryOp::And), + Some(other) => { + return Err(self.error( + "for loop step operator in an initial block", + format!("{other:?}"), + Some(&stmt.token), + )); + } + }; + match binary { + Some(binary) => builder.emit(SIRInstruction::Binary(next, current, binary, step_reg)), + None => builder.emit(SIRInstruction::Imm(next, SIRValue::new(0u64))), + } + let stalled = builder.alloc_bit(1, false); + let op_stalled = match (reverse, var_signed) { + (false, true) => BinaryOp::LeS, + (false, false) => BinaryOp::LeU, + (true, true) => BinaryOp::GeS, + (true, false) => BinaryOp::GeU, + }; + builder.emit(SIRInstruction::Binary(stalled, next, op_stalled, current)); + let progress = builder.new_block(); + let stall = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: stalled, + true_block: (stall, Vec::new()), + false_block: (progress, Vec::new()), + }); + builder.switch_to_block(stall); + let code = self.parser.runtime_error(stall_message, vec![stmt.var_id]); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + self.kernel.builder().switch_to_block(progress); + self.store(&var, next)?; + self.settle_if_dirty()?; + self.parser.clear_register_cache(); + match single_slot { + Some(single_slot) => { + let single = self.load_scratch(single_slot, 1, false); + self.kernel.builder().seal_block(SIRTerminator::Branch { + cond: single, + true_block: (exit, Vec::new()), + false_block: (header, Vec::new()), + }); + } + None => { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(header, Vec::new())); + } + } + self.kernel.builder().switch_to_block(exit); + self.parser.clear_register_cache(); + if matches!(body_flow, Flow::Ended) + && constant_nonempty_range(&stmt.range) + && !self.contains_loop_break(&stmt.body, &mut HashSet::default()) + { + // The exit is unreachable for this known nonempty terminating body. + self.kernel.finish(); + Ok(Flow::Ended) + } else { + Ok(Flow::Continue) + } + } + + /// `value` at `width` bits, sign-extended when `signed`. + fn extend_for_compare(&mut self, value: RegisterId, width: usize, signed: bool) -> RegisterId { + let value = self + .parser + .cast_reg_width_ext(self.kernel.builder(), value, width, signed); + let builder = self.kernel.builder(); + match *builder.register(&value) { + RegisterType::Bit { + width: w, + signed: s, + } if w == width && s == signed => value, + _ => { + let typed = builder.alloc_bit(width, signed); + builder.emit(SIRInstruction::Unary(typed, UnaryOp::Ident, value)); + typed + } + } + } + + fn for_bound( + &mut self, + bound: &ForBound, + width: usize, + signed: bool, + ) -> Result { + let prepared = match bound { + ForBound::Expression(expr) if expressions::has_call(expr) => { + Some((expr.token_range(), self.expression(expr)?)) + } + _ => None, + }; + if let Some((token, value)) = prepared { + self.parser + .push_process_expression_values([(token, value)].into_iter().collect()); + } + let (parser, kernel, targets, sources, convert) = parts!(self); + let result = parser.parse_for_bound( + bound, + width, + width, + signed, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + ); + if prepared.is_some() { + self.parser.pop_process_expression_values(); + } + result + } + + fn lower_system_function(&mut self, call: &SystemFunctionCall) -> Result { + match &call.kind { + SystemFunctionKind::Finish => { + self.kernel.finish_after_publication(); + Ok(Flow::Ended) + } + SystemFunctionKind::Assert { kind, cond, args } => { + self.lower_assert(call, *kind, cond, args) + } + SystemFunctionKind::Readmemh(_, SystemFunctionOutput::Local(_)) => { + self.mark_dirty(); + self.system_task(call) + } + SystemFunctionKind::Readmemh(filename, SystemFunctionOutput::Hier(reference)) => { + let key = (reference.inst_path.clone(), reference.var_path.clone()); + let id = *self.parser.hierarchical_var(&key).ok_or_else(|| { + self.error( + "$readmemh destination", + format!("`{}` was not resolved", reference.var_path), + Some(&reference.comptime.token), + ) + })?; + let local = SystemFunctionCall { + kind: SystemFunctionKind::Readmemh( + filename.clone(), + SystemFunctionOutput::Local(vec![AssignDestination { + id, + path: reference.var_path.clone(), + index: reference.index.clone(), + select: reference.select.clone(), + comptime: reference.comptime.clone(), + token: reference.comptime.token, + }]), + ), + comptime: call.comptime.clone(), + }; + self.mark_dirty(); + self.system_task(&local) + } + SystemFunctionKind::Display(_) | SystemFunctionKind::Write(_) => { + let flow = self.system_task(call)?; + if matches!(flow, Flow::Ended) { + return Ok(flow); + } + self.yield_for_runtime_event()?; + Ok(flow) + } + SystemFunctionKind::Bits(_) + | SystemFunctionKind::Size(..) + | SystemFunctionKind::Clog2(_) + | SystemFunctionKind::Onehot(_) + | SystemFunctionKind::Signed(_) + | SystemFunctionKind::Unsigned(_) => Ok(Flow::Continue), + } + } + + fn system_task(&mut self, call: &SystemFunctionCall) -> Result { + let Some(bindings) = self.expression_bindings(&expressions::system_inputs(&call.kind))? + else { + return Ok(Flow::Ended); + }; + self.parser.push_process_expression_values(bindings); + let first_site = self.parser.runtime_event_sites().len(); + let (parser, kernel, targets, sources, convert) = parts!(self); + let result = parser.parse_system_task_statement( + call, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + ); + self.parser.pop_process_expression_values(); + result?; + // Kernel events execute at suspension boundaries, unlike RTL events + // emitted on every fused edge. Preserve their source ownership marker. + let location = event_location(&call.comptime.token); + for site in &mut self.parser.runtime_event_sites_mut()[first_site..] { + site.location = location.clone(); + } + Ok(Flow::Continue) + } + + fn lower_assert( + &mut self, + call: &SystemFunctionCall, + kind: AssertKind, + cond: &SystemFunctionInput, + args: &[SystemFunctionInput], + ) -> Result { + let mut condition = self.condition(&cond.0)?; + if self.argument_ended(&cond.0) { + return Ok(Flow::Ended); + } + let argument_calls = args.iter().any(|arg| expressions::has_call(&arg.0)); + let freeze_condition = argument_calls || expressions::has_call(&cond.0); + if freeze_condition { + self.save_expression(&cond.0, condition)?; + } + self.settle_if_dirty()?; + let inputs = args.iter().map(|arg| &arg.0).collect::>(); + let Some(bindings) = self.expression_bindings(&inputs)? else { + return Ok(Flow::Ended); + }; + if freeze_condition { + let value = self.saved_expression(&cond.0); + condition = self + .parser + .lower_procedural_condition(value, self.kernel.builder()); + } + self.parser.push_process_expression_values(bindings); + let location = event_location(&call.comptime.token); + let pass_site = self + .parser + .register_runtime_event_site(RuntimeEventKind::AssertPass, args); + let fail_kind = match kind { + AssertKind::Fatal => RuntimeEventKind::AssertFatal, + AssertKind::Continue => RuntimeEventKind::AssertContinue, + }; + let fail_site = self.parser.register_runtime_event_site(fail_kind, args); + for site in [pass_site, fail_site] { + let index = (site - self.site_base) as usize; + self.parser.runtime_event_sites_mut()[index].location = location.clone(); + } + let prepared = { + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.prepare_effectful_runtime_event_args( + args, + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + )? + }; + let builder = self.kernel.builder(); + let pass_block = builder.new_block(); + let fail_block = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (pass_block, Vec::new()), + false_block: (fail_block, Vec::new()), + }); + for (block, site) in [(pass_block, pass_site), (fail_block, fail_site)] { + self.kernel.builder().switch_to_block(block); + let (parser, kernel, targets, sources, convert) = parts!(self); + parser.emit_runtime_event_with_prepared_args( + site, + args, + prepared.clone(), + targets, + &Domain::Process, + &convert, + sources, + kernel.builder(), + )?; + if site == fail_site && matches!(kind, AssertKind::Fatal) { + let message = args + .first() + .and_then(|arg| FfParser::static_string_expr(&arg.0)) + .unwrap_or_else(|| "assertion failed".to_string()); + let code = self.parser.runtime_error(message, Vec::new()); + self.kernel.builder().seal_block(SIRTerminator::Error(code)); + } else { + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } + } + self.parser.pop_process_expression_values(); + self.kernel.builder().switch_to_block(join); + self.yield_for_runtime_event()?; + Ok(Flow::Continue) + } + + /// Count a runtime event the kernel just emitted; every + /// [`EVENT_YIELD_EVERY`] events the kernel settles, which returns to the + /// host, so the runtime event ring never wraps within one kernel run. + fn yield_for_runtime_event(&mut self) -> Result<(), ParserError> { + let Some(slot) = self.event_yield else { + return Ok(()); + }; + let count = self.load_scratch(slot, EVENT_YIELD_WIDTH, false); + let one = self.constant(1, EVENT_YIELD_WIDTH); + let limit = self.constant(EVENT_YIELD_EVERY, EVENT_YIELD_WIDTH); + let zero = self.constant(0, EVENT_YIELD_WIDTH); + let builder = self.kernel.builder(); + let next = builder.alloc_bit(EVENT_YIELD_WIDTH, false); + builder.emit(SIRInstruction::Binary(next, count, BinaryOp::Add, one)); + let due = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(due, next, BinaryOp::GeU, limit)); + let yield_block = builder.new_block(); + let keep_block = builder.new_block(); + let after = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: due, + true_block: (yield_block, Vec::new()), + false_block: (keep_block, Vec::new()), + }); + builder.switch_to_block(keep_block); + self.store_scratch(slot, EVENT_YIELD_WIDTH, next); + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(after, Vec::new())); + self.kernel.builder().switch_to_block(yield_block); + self.store_scratch(slot, EVENT_YIELD_WIDTH, zero); + let dirty = self.dirty; + let yielded = if dirty { + self.kernel.settle() + } else { + self.kernel.yield_events() + }; + yielded + .map_err(|error| self.error("testbench process lowering", error.to_string(), None))?; + if dirty && let Some(slot) = self.event_yield_clean { + let one = self.constant(1, 1); + self.store_scratch(slot, 1, one); + } + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(after, Vec::new())); + self.kernel.builder().switch_to_block(after); + // Registers do not survive the yield path. The static dirty state + // includes the keep path; scratch distinguishes its runtime state. + self.parser.clear_register_cache(); + self.dirty = dirty; + Ok(()) + } + + /// Inline a function call statement: bind its inputs, run its body, and + /// copy its outputs back. + fn lower_function_call( + &mut self, + call: &veryl_analyzer::ir::FunctionCall, + ) -> Result { + let Some(body) = function_body(&self.ir.functions, call) else { + return Err(self.error( + "function call in an initial block", + format!("{call}"), + Some(&call.comptime.token), + )); + }; + let paths = self.ir.functions[&call.id] + .args + .iter() + .flat_map(|arg| arg.members.iter().map(|(path, _, _)| path.clone())) + .collect::>(); + let inputs = paths + .iter() + .filter_map(|path| { + call.inputs + .iter() + .find_map(|(input, expr)| (input == path).then_some((path, expr))) + }) + .collect::>(); + let freeze = inputs.iter().any(|(_, expr)| expressions::has_call(expr)); + let mut values = Vec::new(); + for (path, expr) in &inputs { + let actual = body.arg_map.get(*path).map(|formal| { + self.parser + .coerce_function_input_expression((*expr).clone(), *formal) + }); + let value = self.expression(actual.as_ref().unwrap_or(expr))?; + if !self.scan_expression_clocks(expr, &mut HashSet::default(), false) { + self.kernel.finish(); + return Ok(Flow::Ended); + } + if freeze { + self.save_expression(expr, value)?; + } + values.push((*path, *expr, value)); + } + if !self.active_functions.insert(function_key(call)) { + return Err(self.error( + "function call in an initial block", + "recursive call", + Some(&call.comptime.token), + )); + } + let mut storage = HashSet::default(); + super::ff::collect_statement_variables(&body.statements, &mut storage); + storage.extend(body.arg_map.values().copied()); + storage.extend(body.ret); + let mut storage = storage + .into_iter() + .filter(|id| self.ir.variables[id].affiliation == Affiliation::Function) + .collect::>(); + storage.sort(); + for id in storage { + let variable = &self.ir.variables[&id]; + let width = resolve_total_width(self.ir, variable)?.max(1); + let two_state = variable.r#type.is_2state(); + let builder = self.kernel.builder(); + let reg = if two_state { + builder.alloc_bit(width, variable.r#type.signed) + } else { + builder.alloc_logic(width) + }; + let value = if two_state { + SIRValue::new(0u8) + } else { + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + SIRValue::new_four_state(mask.clone(), mask) + }; + builder.emit(SIRInstruction::Imm(reg, value)); + self.store(&self.destination(id, call.comptime.token), reg)?; + } + for (path, expr, value) in values { + if let Some(&formal) = body.arg_map.get(path) { + let value = if freeze { + self.saved_expression(expr) + } else { + value + }; + let value = self.parser.coerce_register_to_variable_type( + value, + formal, + expression_signed(expr), + self.kernel.builder(), + )?; + let destination = self.destination(formal, call.comptime.token); + self.store(&destination, value)?; + } + } + let previous_frame = self.expression_frame.replace(function_key(call)); + let flow = self.lower_statements(&body.statements); + self.expression_frame = previous_frame; + let flow = flow?; + self.active_functions.remove(&function_key(call)); + if let Flow::Ended = flow { + return Ok(Flow::Ended); + } + let mut outgoing = HashMap::default(); + for formal in output_snapshot_formals(call, &body) { + let variable = &self.ir.variables[&formal]; + let width = resolve_total_width(self.ir, variable)?.max(1); + let signed = variable.r#type.signed; + let two_state = variable.r#type.is_2state(); + let (_, slot) = self.take_scratch("function_output", width)?; + let value = self.load_var(formal)?; + self.store_scratch(slot, width, value); + outgoing.insert(formal, (slot, width, signed, two_state)); + } + for path in &paths { + let Some(destinations) = call + .outputs + .iter() + .find_map(|(output, destinations)| (output == path).then_some(destinations)) + else { + continue; + }; + if let Some(&formal) = body.arg_map.get(path) { + for destination in destinations { + let snapshot = outgoing.get(&formal).copied(); + if let Flow::Ended = self.copy_back(destination, |this| match snapshot { + Some((slot, width, signed, two_state)) => { + Ok(this.load_output_scratch(slot, width, signed, two_state)) + } + None => this.load_var(formal), + })? { + return Ok(Flow::Ended); + } + } + } + } + if let Some(formal) = body.ret + && let Some(&(slot, width, signed, two_state)) = outgoing.get(&formal) + { + let value = self.load_output_scratch(slot, width, signed, two_state); + self.store(&self.destination(formal, call.comptime.token), value)?; + } + Ok(Flow::Continue) + } + + fn argument_ended(&mut self, expression: &Expression) -> bool { + if self.scan_expression_clocks(expression, &mut HashSet::default(), false) { + false + } else { + self.kernel.finish(); + true + } + } + + fn file_argument( + &mut self, + arg: &SystemFunctionInput, + ) -> Result>, ParserError> { + let width = argument_width(arg); + let signed = expression_signed(&arg.0); + let (mut value, slot) = self.host_scratch( + "file_arg", + width, + signed, + arg.0.comptime().r#type.is_string(), + )?; + let reg = if let Some(text) = FfParser::static_string_expr(&arg.0) { + if text.is_empty() { + value.width = 0; + } + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm( + reg, + SIRValue::new(BigUint::from_bytes_be(text.as_bytes())), + )); + reg + } else { + let reg = self.expression(&arg.0)?; + if self.argument_ended(&arg.0) { + return Ok(None); + } + self.parser + .cast_reg_width_ext(self.kernel.builder(), reg, width, signed) + }; + self.store_scratch(slot, width, reg); + Ok(Some(value)) + } + + fn lower_tb_method(&mut self, tb: &TbMethodCall) -> Result { + if matches!( + tb.method, + TbMethod::ClockNext { .. } | TbMethod::ResetAssert { .. } + ) { + let statement = Statement::TbMethodCall(tb.clone()); + if !self.scan_clocks( + std::slice::from_ref(&statement), + &mut HashSet::default(), + false, + ) { + // Evaluate the terminating argument, then seal only its dead + // continuation. The outer wait has no reachable clock metadata. + for expr in expressions::statement_inputs(&statement) { + self.expression(expr)?; + } + self.kernel.finish(); + return Ok(Flow::Ended); + } + } + match &tb.method { + TbMethod::ClockNext { count, .. } => { + let clock = self.clock_index(tb.inst)?; + let count = match count { + Some(expr) => { + let value = self.expression(expr)?; + self.unsigned_bits(value, PROCESS_DELAY_WIDTH) + } + None => self.constant(1, PROCESS_DELAY_WIDTH), + }; + let count = if self.dirty { + let (_, slot) = self.take_scratch("clock_count", PROCESS_DELAY_WIDTH)?; + self.store_scratch(slot, PROCESS_DELAY_WIDTH, count); + self.settle_if_dirty()?; + self.load_scratch(slot, PROCESS_DELAY_WIDTH, false) + } else { + count + }; + self.kernel + .wait_clock(clock, count, None) + .map_err(|error| { + self.error("testbench process lowering", error.to_string(), None) + })?; + self.suspended(); + Ok(Flow::Continue) + } + TbMethod::ResetAssert { clock, duration } => { + let clock_index = self.clock_index(*clock)?; + let reset = self.instance_var(tb.inst)?; + let reset_source = SourceAddr { + instance_id: self.instance, + var_id: self.ids[&reset], + }; + let type_kind = self.lookup.module_variables[&self.module_id][&reset_source.var_id] + .metadata + .type_kind; + let (assert_value, deassert_value) = match type_kind { + PortTypeKind::ResetAsyncHigh | PortTypeKind::ResetSyncHigh => (1, 0), + _ => (0, 1), + }; + let duration = match duration { + Some(expr) => { + let value = self.expression(expr)?; + let value = self.unsigned_bits(value, PROCESS_DELAY_WIDTH); + // A reset holds for at least one cycle. + let builder = self.kernel.builder(); + let zero = builder.alloc_bit(PROCESS_DELAY_WIDTH, false); + builder.emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); + let one = builder.alloc_bit(PROCESS_DELAY_WIDTH, false); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + let is_zero = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(is_zero, value, BinaryOp::Eq, zero)); + let held = builder.alloc_bit(PROCESS_DELAY_WIDTH, false); + builder.emit(SIRInstruction::Mux(held, is_zero, one, value)); + held + } + None => self.constant(3, PROCESS_DELAY_WIDTH), + }; + let value = self.constant(assert_value, 1); + let destination = self.destination( + reset, + tb.ret.as_ref().map_or(self.ir.token, |ret| ret.token), + ); + self.store(&destination, value)?; + let clock_var = self.instance_var(*clock)?; + let clock_source = SourceAddr { + instance_id: self.instance, + var_id: self.ids[&clock_var], + }; + let release = match self.releases.iter().position(|release| { + release.signal == reset_source && release.clock == Some(clock_source) + }) { + Some(index) => index as u32, + None => { + let clock_var = self.instance_var(*clock)?; + self.releases.push(ProcessRelease { + signal: reset_source, + value: deassert_value, + clock: Some(SourceAddr { + instance_id: self.instance, + var_id: self.ids[&clock_var], + }), + }); + let index = self.kernel.add_release(); + debug_assert_eq!(index as usize + 1, self.releases.len()); + index + } + }; + self.kernel + .wait_clock(clock_index, duration, Some(release)) + .map_err(|error| { + self.error("testbench process lowering", error.to_string(), None) + })?; + self.suspended(); + Ok(Flow::Continue) + } + TbMethod::RandomSeed { value } => { + let seed = self.expression(value)?; + if self.argument_ended(value) { + return Ok(Flow::Ended); + } + let seed = self.unsigned_bits(seed, 64); + let (host_value, slot) = self.host_scratch("random_seed", 64, false, false)?; + self.store_scratch(slot, 64, seed); + self.host_request(HostRequest::RandomSeed { + handle: self.resource_name(tb.inst), + value: host_value, + })?; + Ok(Flow::Continue) + } + TbMethod::RandomGet { width, signed } => { + let (result, slot) = + self.host_scratch("random_value", (*width as usize).max(1), *signed, false)?; + let result_width = result.width; + self.host_request(HostRequest::RandomGet { + handle: self.resource_name(tb.inst), + result, + })?; + if let Some(ret) = tb.ret.as_deref() { + return self.copy_back(ret, |this| { + Ok(this.load_scratch(slot, result_width, *signed)) + }); + } + Ok(Flow::Continue) + } + TbMethod::RandomGetRange { + min, + max, + width, + signed, + } => { + let freeze = expressions::has_call(min) || expressions::has_call(max); + let min_reg = self.expression(min)?; + if self.argument_ended(min) { + return Ok(Flow::Ended); + } + if freeze { + self.save_expression(min, min_reg)?; + } + let max_reg = self.expression(max)?; + if self.argument_ended(max) { + return Ok(Flow::Ended); + } + let min_reg = if freeze { + self.saved_expression(min) + } else { + min_reg + }; + let min_reg = self.unsigned_bits(min_reg, 64); + let max_reg = self.unsigned_bits(max_reg, 64); + let (min_value, min_slot) = self.host_scratch("random_min", 64, *signed, false)?; + let (max_value, max_slot) = self.host_scratch("random_max", 64, *signed, false)?; + let (result, slot) = + self.host_scratch("random_value", (*width as usize).max(1), *signed, false)?; + let result_width = result.width; + self.store_scratch(min_slot, 64, min_reg); + self.store_scratch(max_slot, 64, max_reg); + self.host_request(HostRequest::RandomGetRange { + handle: self.resource_name(tb.inst), + min: min_value, + max: max_value, + result, + })?; + if let Some(ret) = tb.ret.as_deref() { + return self.copy_back(ret, |this| { + Ok(this.load_scratch(slot, result_width, *signed)) + }); + } + Ok(Flow::Continue) + } + TbMethod::RandomGetSeed => { + let (result, slot) = self.host_scratch("random_seed", 64, false, false)?; + self.host_request(HostRequest::RandomGetSeed { + handle: self.resource_name(tb.inst), + result, + })?; + if let Some(ret) = tb.ret.as_deref() { + return self.copy_back(ret, |this| Ok(this.load_scratch(slot, 64, false))); + } + Ok(Flow::Continue) + } + TbMethod::Component { method, args } => { + let mut host_args = Vec::new(); + for arg in args { + let is_string = arg.0.comptime().r#type.is_string(); + let signed = expression_signed(&arg.0); + let (mut value, slot) = + self.host_scratch("component_arg", argument_width(arg), signed, is_string)?; + let width = value.width; + if is_string + && FfParser::static_string_expr(&arg.0).is_some_and(|text| text.is_empty()) + { + value.width = 0; // logical byte length; physical scratch still has one bit + } + let reg = if let Some(text) = FfParser::static_string_expr(&arg.0) { + let builder = self.kernel.builder(); + let reg = builder.alloc_bit(width, false); + builder.emit(SIRInstruction::Imm( + reg, + SIRValue::new(BigUint::from_bytes_be(text.as_bytes())), + )); + reg + } else { + let reg = self.expression(&arg.0)?; + if self.argument_ended(&arg.0) { + return Ok(Flow::Ended); + } + self.unsigned_bits(reg, width) + }; + self.store_scratch(slot, width, reg); + host_args.push(value); + } + let result = match tb.ret.as_deref() { + Some(_) => { + let (value, slot) = self.host_scratch( + "component_result", + tb.ret_width.map_or(64, |width| width as usize).max(1), + tb.ret_signed, + false, + )?; + Some((value, slot)) + } + None => None, + }; + self.host_request(HostRequest::Component { + instance: self.resource_name(tb.inst), + method: source_name(*method), + args: host_args, + result: result.as_ref().map(|(value, _)| value.clone()), + declared_width: tb.ret_width.map(|w| w as usize), + strict: tb.ret_strict, + })?; + if let (Some(ret), Some((value, slot))) = (tb.ret.as_deref(), result) { + return self.copy_back(ret, |this| { + Ok(this.load_scratch(slot, value.width, tb.ret_signed)) + }); + } + Ok(Flow::Continue) + } + TbMethod::FileOpen { name, append } => { + let Some(path) = self.file_argument(name)? else { + return Ok(Flow::Ended); + }; + self.host_request(HostRequest::FileOpen { + handle: self.resource_name(tb.inst), + path, + append: *append, + })?; + Ok(Flow::Continue) + } + TbMethod::FileWrite { args } => { + let template = args + .first() + .and_then(|arg| FfParser::static_string_expr(&arg.0)); + let skip = usize::from(template.is_some()); + let mut values = Vec::new(); + for arg in &args[skip..] { + let Some(value) = self.file_argument(arg)? else { + return Ok(Flow::Ended); + }; + values.push(value); + } + self.host_request(HostRequest::FileWrite { + handle: self.resource_name(tb.inst), + template, + args: values, + })?; + Ok(Flow::Continue) + } + TbMethod::FileClose => { + self.host_request(HostRequest::FileClose { + handle: self.resource_name(tb.inst), + })?; + Ok(Flow::Continue) + } + TbMethod::FileFlush => { + self.host_request(HostRequest::FileFlush { + handle: self.resource_name(tb.inst), + })?; + Ok(Flow::Continue) + } + } + } +} + +fn source_name(id: StrId) -> String { + resource_table::get_str_value(id).unwrap_or_else(|| format!("{id}")) +} + +fn try_eval_const(expr: &Expression) -> Option { + if !expr.comptime().is_const { + return None; + } + expr.comptime() + .get_value() + .ok() + .map(|value| value.payload_u64()) +} + +fn event_location(token: &veryl_parser::token_range::TokenRange) -> Option { + let begin = &token.beg; + let file = begin + .source + .get_path() + .and_then(resource_table::get_path_value)?; + Some(EventLocation { + file: file.to_string_lossy().into_owned(), + line: begin.line, + column: begin.column, + }) +} + +/// Drop the blocks control never enters. +fn prune_unreachable_blocks(unit: &mut ExecutionUnit) { + let mut reachable = HashSet::default(); + let mut work = vec![unit.entry_block_id]; + while let Some(block) = work.pop() { + if !reachable.insert(block) { + continue; + } + match &unit.blocks[&block].terminator { + SIRTerminator::Jump(target, _) => work.push(*target), + SIRTerminator::Branch { + true_block, + false_block, + .. + } => { + work.push(true_block.0); + work.push(false_block.0); + } + SIRTerminator::Switch { cases, default, .. } => { + work.extend(cases.iter().map(|case| case.target)); + work.push(*default); + } + SIRTerminator::Return | SIRTerminator::Error(_) => {} + } + } + unit.blocks.retain(|id, _| reachable.contains(id)); +} + +/// Map the addresses and runtime error codes of a unit. +fn map_unit( + unit: &ExecutionUnit, + codes: &HashMap, + mut map: impl FnMut(&A) -> Result, +) -> Result, ParserError> { + let mut blocks = HashMap::default(); + let mut ids: Vec<&BlockId> = unit.blocks.keys().collect(); + ids.sort(); + for id in ids { + let block = &unit.blocks[id]; + let mut instructions = Vec::with_capacity(block.instructions.len()); + for instruction in &block.instructions { + // Resolve every address first, then rebuild with the results. + let mut resolved = Vec::new(); + let mut failure = None; + instruction.map_addr(|address| match map(address) { + Ok(address) => resolved.push(address), + Err(error) => { + failure.get_or_insert(error); + } + }); + if let Some(error) = failure { + return Err(error); + } + let mut resolved = resolved.into_iter(); + instructions.push( + instruction + .map_addr(|_| resolved.next().expect("one resolved address per address")), + ); + } + let terminator = match &block.terminator { + SIRTerminator::Error(code) => { + SIRTerminator::Error(codes.get(code).copied().unwrap_or(*code)) + } + other => other.clone(), + }; + blocks.insert( + *id, + BasicBlock { + id: block.id, + params: block.params.clone(), + instructions, + terminator, + }, + ); + } + Ok(ExecutionUnit { + entry_block_id: unit.entry_block_id, + blocks, + register_map: unit.register_map.clone(), + }) +} diff --git a/crates/celox-frontend-veryl/src/lowering/process/expressions.rs b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs new file mode 100644 index 00000000000..273ac153377 --- /dev/null +++ b/crates/celox-frontend-veryl/src/lowering/process/expressions.rs @@ -0,0 +1,557 @@ +//! Expressions a process evaluates, in their source order. +use super::*; +use veryl_analyzer::ir::{ArrayLiteralItem, CasePattern, Factor}; + +pub(super) fn system_inputs(kind: &SystemFunctionKind) -> Vec<&Expression> { + match kind { + SystemFunctionKind::Bits(input) + | SystemFunctionKind::Size(input, _) + | SystemFunctionKind::Clog2(input) + | SystemFunctionKind::Onehot(input) + | SystemFunctionKind::Signed(input) + | SystemFunctionKind::Unsigned(input) + | SystemFunctionKind::Readmemh(input, _) => vec![&input.0], + SystemFunctionKind::Display(inputs) | SystemFunctionKind::Write(inputs) => { + inputs.iter().map(|input| &input.0).collect() + } + SystemFunctionKind::Assert { cond, args, .. } => std::iter::once(&cond.0) + .chain(args.iter().map(|input| &input.0)) + .collect(), + SystemFunctionKind::Finish => Vec::new(), + } +} +pub(super) fn selection<'s>(index: &'s VarIndex, select: &'s VarSelect) -> Vec<&'s Expression> { + index + .0 + .iter() + .chain(select.0.iter()) + .chain(select.1.iter().map(|(_, expr)| expr)) + .collect() +} +pub(super) fn children(expr: &Expression) -> Vec<&Expression> { + match expr { + Expression::Term(factor) => match factor.as_ref() { + Factor::Variable(_, index, select, _) => selection(index, select), + Factor::HierVariable(reference) => selection(&reference.index, &reference.select), + Factor::FunctionCall(call) => call + .inputs + .values() + .chain(call.outputs.values().flat_map(|destinations| { + destinations + .iter() + .flat_map(|dst| selection(&dst.index, &dst.select)) + })) + .collect(), + Factor::SystemFunctionCall(call) + if !matches!( + call.kind, + SystemFunctionKind::Bits(_) | SystemFunctionKind::Size(..) + ) => + { + system_inputs(&call.kind) + } + _ => Vec::new(), + }, + Expression::Unary(_, inner, _) => vec![inner], + Expression::Binary(lhs, _, rhs, _) => vec![lhs, rhs], + Expression::Ternary(cond, yes, no, _) => vec![cond, yes, no], + Expression::Concatenation(parts, _) => parts + .iter() + .flat_map(|(value, repeat)| std::iter::once(value).chain(repeat.iter())) + .collect(), + Expression::ArrayLiteral(items, _) => items + .iter() + .flat_map(|item| match item { + ArrayLiteralItem::Value(value, repeat) => std::iter::once(value.as_ref()) + .chain(repeat.iter().map(|expr| expr.as_ref())) + .collect::>(), + ArrayLiteralItem::Defaul(value) => vec![value.as_ref()], + }) + .collect(), + Expression::StructConstructor(_, fields, _) => { + fields.iter().map(|(_, expr)| expr).collect() + } + } +} +pub(super) fn has_call(expr: &Expression) -> bool { + matches!(expr, Expression::Term(factor) if matches!(factor.as_ref(),Factor::FunctionCall(_))) + || children(expr).into_iter().any(has_call) +} +pub(crate) fn statement_inputs(statement: &Statement) -> Vec<&Expression> { + match statement { + Statement::Assign(assign) => std::iter::once(&assign.expr) + .chain( + assign + .dst + .iter() + .flat_map(|dst| selection(&dst.index, &dst.select)), + ) + .collect(), + Statement::If(stmt) => vec![&stmt.cond], + // A statically selected arm never evaluates later pattern helpers. + Statement::Case(stmt) if selected_case_body(stmt).is_some() => { + vec![stmt.case_target.as_ref()] + } + Statement::Case(stmt) => std::iter::once(stmt.case_target.as_ref()) + .chain(stmt.arms.iter().flat_map(|arm| { + arm.patterns.iter().flat_map(|pattern| match pattern { + CasePattern::Eq(expr) => vec![expr.as_ref()], + CasePattern::Range { lo, hi, .. } => vec![lo.as_ref(), hi.as_ref()], + }) + })) + .collect(), + Statement::For(stmt) => { + let (start, end) = match &stmt.range { + ForRange::Forward { start, end, .. } + | ForRange::Reverse { start, end, .. } + | ForRange::Stepped { start, end, .. } => (start, end), + }; + [start, end] + .into_iter() + .filter_map(|bound| { + if let ForBound::Expression(expr) = bound { + Some(expr.as_ref()) + } else { + None + } + }) + .collect() + } + Statement::FunctionCall(call) => call + .inputs + .values() + .chain(call.outputs.values().flat_map(|destinations| { + destinations + .iter() + .flat_map(|dst| selection(&dst.index, &dst.select)) + })) + .collect(), + Statement::SystemFunctionCall(call) => match call.kind { + SystemFunctionKind::Bits(_) + | SystemFunctionKind::Size(..) + | SystemFunctionKind::Clog2(_) + | SystemFunctionKind::Onehot(_) + | SystemFunctionKind::Signed(_) + | SystemFunctionKind::Unsigned(_) => Vec::new(), + _ => system_inputs(&call.kind), + }, + Statement::TbMethodCall(tb) => { + let mut inputs: Vec<&Expression> = match &tb.method { + TbMethod::ClockNext { count, .. } => count.iter().collect(), + TbMethod::ResetAssert { duration, .. } => duration.iter().collect(), + TbMethod::RandomSeed { value, .. } => vec![value], + TbMethod::RandomGetRange { min, max, .. } => vec![min, max], + TbMethod::FileOpen { name, .. } => vec![&name.0], + TbMethod::FileWrite { args } => args.iter().map(|arg| &arg.0).collect(), + TbMethod::Component { args, .. } => args.iter().map(|arg| &arg.0).collect(), + _ => Vec::new(), + }; + if let Some(ret) = tb.ret.as_deref() { + inputs.extend(selection(&ret.index, &ret.select)); + } + inputs + } + _ => Vec::new(), + } +} +pub(super) fn statement_bodies(statement: &Statement) -> Vec<&[Statement]> { + match statement { + Statement::If(stmt) => match constant_truth(&stmt.cond) { + Some(true) => vec![&stmt.true_side], + Some(false) => vec![&stmt.false_side], + None => vec![&stmt.true_side, &stmt.false_side], + }, + Statement::IfReset(stmt) => vec![&stmt.true_side, &stmt.false_side], + Statement::Case(stmt) if selected_case_body(stmt).is_some() => { + vec![selected_case_body(stmt).unwrap()] + } + Statement::Case(stmt) => stmt + .arms + .iter() + .map(|arm| arm.body.as_slice()) + .chain(std::iter::once(stmt.default.as_slice())) + .collect(), + Statement::For(stmt) if !constant_empty_range(&stmt.range) => vec![&stmt.body], + _ => Vec::new(), + } +} +/// Calls in potentially evaluated branches of this expression. +pub(super) fn expression_calls<'s>( + expr: &'s Expression, + calls: &mut Vec<&'s veryl_analyzer::ir::FunctionCall>, +) { + let inputs = match expr { + Expression::Binary(lhs, Op::LogicAnd, _, _) if constant_truth(lhs) == Some(false) => { + vec![lhs.as_ref()] + } + Expression::Binary(lhs, Op::LogicOr, _, _) if constant_truth(lhs) == Some(true) => { + vec![lhs.as_ref()] + } + Expression::Ternary(cond, yes, no, _) => match constant_truth(cond) { + Some(true) => vec![cond.as_ref(), yes.as_ref()], + Some(false) => vec![cond.as_ref(), no.as_ref()], + None => children(expr), + }, + _ => children(expr), + }; + for child in inputs { + expression_calls(child, calls); + } + if let Expression::Term(factor) = expr + && let Factor::FunctionCall(call) = factor.as_ref() + { + calls.push(call); + } +} +pub(super) fn storage_width(expr: &Expression) -> usize { + expr.comptime() + .expr_context + .width + .max(crate::context_width::get_expr_width(expr).unwrap_or(0)) + .max(expr.comptime().r#type.total_width().unwrap_or(64)) + .max( + expr.comptime() + .get_value() + .ok() + .map_or(0, |value| value.width()), + ) + .max(1) +} + +impl BlockLowering<'_> { + pub(super) fn save_expression( + &mut self, + expr: &Expression, + value: RegisterId, + ) -> Result<(), ParserError> { + let (width, id) = self + .expression_values + .get(&(self.expression_frame.clone(), expr.token_range())) + .copied() + .ok_or_else(|| { + self.error( + "process expression storage", + format!("missing value for {expr}"), + Some(&expr.token_range()), + ) + })?; + let value = self.parser.cast_reg_width_ext( + self.kernel.builder(), + value, + width, + expression_signed(expr), + ); + self.store_scratch(id, width, value); + Ok(()) + } + pub(super) fn saved_expression(&mut self, expr: &Expression) -> RegisterId { + let (width, id) = + self.expression_values[&(self.expression_frame.clone(), expr.token_range())]; + let builder = self.kernel.builder(); + let value = if expr.comptime().r#type.is_2state() { + builder.alloc_bit(width, expression_signed(expr)) + } else { + builder.alloc_logic(width) + }; + builder.emit(SIRInstruction::Load( + value, + RegionedSourceAddr { + region: STABLE_REGION, + instance_id: self.instance, + var_id: id, + }, + SIROffset::Static(0), + width, + )); + value + } + fn parse_with_values( + &mut self, + expr: &Expression, + values: HashMap, + ) -> Result { + // The bound children are runtime results. Analyzer constant values + // of a compound call expression cannot replace those results. + let mut evaluated = expr.clone(); + evaluated.comptime_mut().is_const = false; + self.parser.push_process_expression_values(values); + let result = self.raw_expression(&evaluated); + self.parser.pop_process_expression_values(); + result + } + fn has_unbound_calls(&self, expr: &Expression) -> bool { + self.parser + .process_expression_value(expr.token_range()) + .is_none() + && (matches!(expr,Expression::Term(factor) if matches!(factor.as_ref(),Factor::FunctionCall(_))) + || children(expr) + .into_iter() + .any(|child| self.has_unbound_calls(child))) + } + + pub(super) fn expression_bindings( + &mut self, + inputs: &[&Expression], + ) -> Result>, ParserError> { + if !inputs.iter().any(|expr| has_call(expr)) { + return Ok(Some(HashMap::default())); + } + let inputs = inputs + .iter() + .copied() + .filter(|expr| has_call(expr) || FfParser::static_string_expr(expr).is_none()) + .collect::>(); + for expr in &inputs { + let value = self.expression(expr)?; + if self.argument_ended(expr) { + return Ok(None); + } + self.save_expression(expr, value)?; + } + Ok(Some( + inputs + .into_iter() + .map(|expr| (expr.token_range(), self.saved_expression(expr))) + .collect(), + )) + } + + pub(super) fn expression(&mut self, expr: &Expression) -> Result { + self.settle_if_dirty()?; + if let Some(value) = self.parser.process_expression_value(expr.token_range()) { + return Ok(value); + } + if !self.has_unbound_calls(expr) { + return self.raw_expression(expr); + } + if let Expression::Term(factor) = expr + && let Factor::FunctionCall(call) = factor.as_ref() + { + let body = function_body(&self.ir.functions, call).ok_or_else(|| { + self.error( + "process function expression", + format!("{call}"), + Some(&call.comptime.token), + ) + })?; + if let Flow::Ended = self.lower_function_call(call)? { + // Keep the syntactic continuation unreachable. The Finish return + // already stops this kernel and the other ready processes. + let unreachable = self.kernel.builder().new_block(); + self.kernel.builder().switch_to_block(unreachable); + return Ok(self.constant(0, storage_width(expr))); + } + self.parser.clear_register_cache(); + return self.load_var(body.ret.ok_or_else(|| { + self.error( + "process function expression", + "function has no result", + Some(&call.comptime.token), + ) + })?); + } + if let Expression::Binary(lhs, op, rhs, _) = expr + && matches!(op, Op::LogicAnd | Op::LogicOr) + { + if let Some(truth) = constant_truth(lhs) + && ((*op == Op::LogicAnd && !truth) || (*op == Op::LogicOr && truth)) + { + return Ok(self.constant(u64::from(truth), 1)); + } + return self.logical_expression(expr, lhs, rhs, *op == Op::LogicAnd); + } + if let Expression::Ternary(cond, yes, no, _) = expr { + return self.conditional_expression(expr, cond, yes, no); + } + let inputs = match expr { + Expression::Binary(lhs, Op::As, _, _) => vec![lhs.as_ref()], + _ => children(expr), + }; + for child in &inputs { + let value = self.expression(child)?; + if !self.scan_expression_clocks(child, &mut HashSet::default(), false) { + return Ok(self.constant(0, storage_width(expr))); + } + self.save_expression(child, value)?; + } + let values = inputs + .into_iter() + .map(|child| (child.token_range(), self.saved_expression(child))) + .collect(); + self.parse_with_values(expr, values) + } + fn logical_expression( + &mut self, + expr: &Expression, + lhs: &Expression, + rhs: &Expression, + is_and: bool, + ) -> Result { + let left = self.expression(lhs)?; + if !self.scan_expression_clocks(lhs, &mut HashSet::default(), false) { + return Ok(self.constant(0, storage_width(expr))); + } + self.save_expression(lhs, left)?; + let builder = self.kernel.builder(); + let not = builder.alloc_logic(1); + builder.emit(SIRInstruction::Unary(not, UnaryOp::LogicNot, left)); + let dominant = if is_and { + not + } else { + let truth = builder.alloc_logic(1); + builder.emit(SIRInstruction::Unary(truth, UnaryOp::LogicNot, not)); + truth + }; + let shortcut = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary( + shortcut, + UnaryOp::ToTwoState, + dominant, + )); + let short = builder.new_block(); + let full = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: shortcut, + true_block: (short, Vec::new()), + false_block: (full, Vec::new()), + }); + let dirty_before = self.dirty; + self.kernel.builder().switch_to_block(short); + let value = self.constant(u64::from(!is_and), 1); + self.save_expression(expr, value)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.kernel.builder().switch_to_block(full); + let full_reaches_join = self.scan_expression_clocks(rhs, &mut HashSet::default(), false); + let right = self.expression(rhs)?; + if full_reaches_join { + let left = self.saved_expression(lhs); + let builder = self.kernel.builder(); + let value = builder.alloc_logic(1); + builder.emit(SIRInstruction::Binary( + value, + left, + if is_and { + BinaryOp::LogicAnd + } else { + BinaryOp::LogicOr + }, + right, + )); + self.save_expression(expr, value)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + // expression() leaves an unreachable block after a finishing call. + self.kernel.builder().seal_block(SIRTerminator::Return); + } + self.dirty = dirty_before || (full_reaches_join && self.dirty); + self.kernel.builder().switch_to_block(join); + self.parser.clear_register_cache(); + Ok(self.saved_expression(expr)) + } + fn conditional_expression( + &mut self, + expr: &Expression, + cond: &Expression, + yes: &Expression, + no: &Expression, + ) -> Result { + if let Some(truth) = constant_truth(cond) { + let value = self.expression(if truth { yes } else { no })?; + self.save_expression(expr, value)?; + return Ok(self.saved_expression(expr)); + } + let value = self.expression(cond)?; + if !self.scan_expression_clocks(cond, &mut HashSet::default(), false) { + return Ok(self.constant(0, storage_width(expr))); + } + self.save_expression(cond, value)?; + let truth = self + .parser + .lower_procedural_condition(value, self.kernel.builder()); + let builder = self.kernel.builder(); + let yes_block = builder.new_block(); + let decide = builder.new_block(); + let no_block = builder.new_block(); + let unknown = builder.new_block(); + let join = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: truth, + true_block: (yes_block, Vec::new()), + false_block: (decide, Vec::new()), + }); + let dirty_before = self.dirty; + self.kernel.builder().switch_to_block(yes_block); + let yes_reaches_join = self.scan_expression_clocks(yes, &mut HashSet::default(), false); + let result = self.expression(yes)?; + let yes_dirty = yes_reaches_join && self.dirty; + if yes_reaches_join { + self.save_expression(expr, result)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + } + self.kernel.builder().switch_to_block(decide); + self.dirty = dirty_before; + let condition = self.saved_expression(cond); + let builder = self.kernel.builder(); + let not = builder.alloc_logic(1); + builder.emit(SIRInstruction::Unary(not, UnaryOp::LogicNot, condition)); + let false_known = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Unary(false_known, UnaryOp::ToTwoState, not)); + builder.seal_block(SIRTerminator::Branch { + cond: false_known, + true_block: (no_block, Vec::new()), + false_block: (unknown, Vec::new()), + }); + self.kernel.builder().switch_to_block(no_block); + let no_reaches_join = self.scan_expression_clocks(no, &mut HashSet::default(), false); + let result = self.expression(no)?; + let no_dirty = no_reaches_join && self.dirty; + if no_reaches_join { + self.save_expression(expr, result)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + } + self.kernel.builder().switch_to_block(unknown); + self.dirty = dirty_before; + let mut unknown_reaches_join = true; + for (child, reaches) in [(yes, yes_reaches_join), (no, no_reaches_join)] { + let value = self.expression(child)?; + if !reaches { + unknown_reaches_join = false; + break; + } + self.save_expression(child, value)?; + } + let unknown_dirty = unknown_reaches_join && self.dirty; + if unknown_reaches_join { + let values = [cond, yes, no] + .into_iter() + .map(|child| (child.token_range(), self.saved_expression(child))) + .collect(); + let result = self.parse_with_values(expr, values)?; + self.save_expression(expr, result)?; + self.kernel + .builder() + .seal_block(SIRTerminator::Jump(join, Vec::new())); + } else { + self.kernel.builder().seal_block(SIRTerminator::Return); + } + self.kernel.builder().switch_to_block(join); + // The unknown path evaluates both arms in order; a terminating arm + // never contributes a continuation to this join. + self.dirty = dirty_before || yes_dirty || no_dirty || unknown_dirty; + self.parser.clear_register_cache(); + Ok(self.saved_expression(expr)) + } +} diff --git a/crates/celox-frontend-veryl/src/module.rs b/crates/celox-frontend-veryl/src/module.rs index 3ba79cb895b..aab386e88af 100644 --- a/crates/celox-frontend-veryl/src/module.rs +++ b/crates/celox-frontend-veryl/src/module.rs @@ -2429,7 +2429,7 @@ pub(crate) fn readmem_image( }; index }; - if depth <= 1 { + if depth == 0 || var.r#type.array.iter().count() == 0 { return Err(ParserError::illegal_context( "$readmemh destination", "destination must be an unpacked array", diff --git a/crates/celox-frontend-veryl/src/runtime_functions.rs b/crates/celox-frontend-veryl/src/runtime_functions.rs new file mode 100644 index 00000000000..944b82e7cbc --- /dev/null +++ b/crates/celox-frontend-veryl/src/runtime_functions.rs @@ -0,0 +1,88 @@ +//! Preserve runtime termination before the analyzer folds loop bounds. + +use veryl_analyzer::{ + AnalyzerError, analyzer_error::UnevaluableValueKind, symbol::SymbolKind, symbol_table, +}; +use veryl_parser::{ + veryl_grammar_trait::{DollarIdentifier, FunctionDeclaration, InitialDeclaration, Veryl}, + veryl_walker::VerylWalker, +}; + +/// Source contexts where the kernel supports runtime case conditions. +#[derive(Default)] +pub struct RuntimeFunctions { + initials: Vec, +} +impl RuntimeFunctions { + /// Kernel initial blocks evaluate case patterns at runtime. Keep the + /// analyzer's constant-case requirement for RTL and other contexts. + pub fn is_runtime_case_condition(&self, error: &AnalyzerError) -> bool { + let AnalyzerError::UnevaluableValue { + kind: UnevaluableValueKind::CaseCondition, + error_location, + token_source, + .. + } = error + else { + return false; + }; + self.initials.iter().any(|range| { + let span: miette::SourceSpan = range.into(); + &range.beg.source == token_source + && span.offset() <= error_location.offset() + && error_location.offset() + error_location.len() <= span.offset() + span.len() + }) + } +} + +/// Call after pass 1 and before its global post-pass. A function containing +/// `$finish` cannot be constant evaluated even if its return value is constant. +/// Seeding that fact before the analyzer resolves functions also propagates it +/// to callers through its normal constant-function dependency analysis. +pub fn preserve_terminating_function_calls<'a>( + asts: impl IntoIterator, +) -> RuntimeFunctions { + #[derive(Default)] + struct Finish { + found: bool, + } + impl VerylWalker for Finish { + fn dollar_identifier(&mut self, identifier: &DollarIdentifier) { + self.found |= identifier.dollar_identifier_token.token.text.to_string() == "$finish"; + } + } + #[derive(Default)] + struct Functions { + tokens: crate::HashSet, + initials: Vec, + } + impl VerylWalker for Functions { + fn initial_declaration(&mut self, initial: &InitialDeclaration) { + self.initials.push(initial.into()); + self.statement_block(&initial.statement_block); + } + fn function_declaration(&mut self, function: &FunctionDeclaration) { + let mut finish = Finish::default(); + finish.statement_block(&function.statement_block); + if finish.found { + self.tokens + .insert(function.identifier.identifier_token.token.id); + } + } + } + let mut functions = Functions::default(); + for ast in asts { + functions.veryl(ast); + } + for mut symbol in symbol_table::get_all() { + if functions.tokens.contains(&symbol.token.id) + && let SymbolKind::Function(property) = &mut symbol.kind + { + property.constantable = Some(false); + symbol_table::update(symbol); + } + } + RuntimeFunctions { + initials: functions.initials, + } +} diff --git a/crates/celox-frontend-veryl/src/schedule.rs b/crates/celox-frontend-veryl/src/schedule.rs index f9a056536a5..f37d928f808 100644 --- a/crates/celox-frontend-veryl/src/schedule.rs +++ b/crates/celox-frontend-veryl/src/schedule.rs @@ -30,6 +30,7 @@ pub fn schedule_symbolic_rtl( symbolic, module_ir, source_id_maps, + process_storage, } = source; let root_id = symbolic.root_id; let root = module_ir.get(&root_id).copied(); @@ -62,7 +63,7 @@ pub fn schedule_symbolic_rtl( .unwrap_or_default(); let fused_ff_factory = super::lowering::global_ff::VerylFusedFfFactory::new(&module_ir, &source_id_maps, *config); - let output = assembly::schedule_symbolic_rtl( + let mut output = assembly::schedule_symbolic_rtl( symbolic, Some(&fused_ff_factory), ignored_loops, @@ -131,7 +132,7 @@ pub fn schedule_symbolic_rtl( components.append(&mut instance_components); component_bindings.append(&mut instance_bindings); } - let testbench_source = VerylTestbenchSource { + let mut testbench_source = VerylTestbenchSource { id_map: VerylIdMap { module_variables: source_id_maps, }, @@ -159,11 +160,23 @@ pub fn schedule_symbolic_rtl( component_bindings, component_libraries: Vec::new(), component_file_base: None, + kernels: false, }; + if config.testbench_kernels && !testbench_source.is_empty() { + super::lowering::process::lower_testbench_kernels( + &mut output.scheduled, + &testbench_source, + &module_ir, + &process_storage, + config, + )?; + testbench_source.kernels = true; + } // Use the exact elaborated module, including parameter specialization, for // each process owner. Resolving by root/module name loses child scopes. let mut dynamic_for_diagnostics = Vec::new(); for source in testbench_source.sources() { + let lookup = &output.scheduled.frontend_lookup; let instance = source.base_instance(lookup); let Some(&module) = module_ir.get(&lookup.instance_module[&instance]) else { continue; diff --git a/crates/celox-frontend-veryl/src/source.rs b/crates/celox-frontend-veryl/src/source.rs index 3e441520ff5..8732afbdf46 100644 --- a/crates/celox-frontend-veryl/src/source.rs +++ b/crates/celox-frontend-veryl/src/source.rs @@ -73,6 +73,9 @@ pub struct VerylTestbenchSource { pub component_bindings: Vec, pub component_libraries: Vec, pub component_file_base: Option, + /// The `initial` blocks were compiled into process kernels: the + /// testbench program carries only the components. + pub kernels: bool, } impl VerylTestbenchSource { diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 07d25bbf427..6eba6c334e8 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -116,6 +116,7 @@ fn runtime_event_site_for_assert( .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + location: None, } } @@ -593,7 +594,7 @@ fn variable_access_width( } } -enum TestbenchRead { +pub(crate) enum TestbenchRead { Root(VarId), Hierarchical(Box), } @@ -702,7 +703,7 @@ fn collect_instance_testbench_observability( Ok((sites, reads)) } -fn collect_statement_reads( +pub(crate) fn collect_statement_reads( stmts: &[Statement], funcs: &fxhash::FxHashMap, active_functions: &mut FxHashSet, @@ -1057,7 +1058,7 @@ fn lower_testbench_operator(op: VerylOp) -> Op { } } -struct ExprCompiler<'a> { +pub(crate) struct ExprCompiler<'a> { lookup: &'a FrontendLookup, id_map: &'a VerylIdMap, functions: &'a HashMap, @@ -1967,7 +1968,7 @@ impl ExprCompiler<'_> { Self::validate_target_bounds_parts(info, &destination.index, &destination.select) } - fn validate_target_bounds_parts( + pub(crate) fn validate_target_bounds_parts( info: &VariableInfo, index: &VarIndex, select: &VarSelect, @@ -3559,6 +3560,7 @@ pub fn compile_semantic_testbench( runtime_event_site_count: usize, random_seed: Option, ) -> Result>, ParserError> { + let kernels = source.kernels; let sources: Vec<_> = source .sources() .filter(|source| source.initial_statements.is_some()) @@ -3593,6 +3595,9 @@ pub fn compile_semantic_testbench( let mut site_end = runtime_event_site_count.saturating_sub(total_sites); let mut processes = Vec::new(); for source in sources { + if kernels { + break; + } let initial_stmts = source.initial_statements.as_ref().unwrap(); validate_testbench_statements(initial_stmts, lookup, source, &mut FxHashSet::default())?; site_end += count_assert_statements(initial_stmts, &source.functions); diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index d34c3ab9d33..5e822374e73 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -18,8 +18,8 @@ pub use reflection::{ SignalDirection, }; pub use simulation::{ - EventInfo, ProcessClockRef, ProcessClockState, ProcessRefs, ScheduleParts, SimulationExecutor, - SimulationSnapshot, SimulationState, + EventInfo, ProcessClockRef, ProcessClockState, ProcessRefs, ProcessReleaseRef, ScheduleParts, + SimulationExecutor, SimulationSnapshot, SimulationState, }; pub use state_file::{ ScheduleRecord, ScheduledEvent, StateDifference, StateFile, StateFileError, StateObject, diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs index 089b675d6d6..78fb55ffe0a 100644 --- a/crates/celox-runtime/src/simulation.rs +++ b/crates/celox-runtime/src/simulation.rs @@ -33,10 +33,6 @@ fn count_delta_pass(rounds: &mut usize) -> Result<(), SimulatorErrorCode> { /// decoration and waveform capture outside the backend-independent scheduler. pub trait SimulationExecutor { type Backend: SimBackend; - fn finish_requested(&mut self, _time: u64) -> bool { - false - } - /// Whether individual scheduled writes have observable combinational /// effects even without an event waiter. fn scheduled_updates_need_settle(&self) -> bool { @@ -58,10 +54,22 @@ pub trait SimulationExecutor { &mut self, event: ::Event, ) -> Result<(), SimulatorErrorCode>; - fn run_process(&mut self, index: usize) -> Result<(), SimulatorErrorCode> { + /// Run process kernel `index` at simulation time `time` until it + /// suspends or ends. + fn run_process(&mut self, index: usize, _time: u64) -> Result<(), SimulatorErrorCode> { self.backend_mut().run_process(index) } + /// Whether this process has made no design store since its last settle. + fn process_is_clean(&self, _index: usize) -> bool { + false + } + + /// Whether an internal settle or process execution emitted a finish event. + fn finish_requested(&mut self, _time: u64) -> bool { + false + } + /// Run up to `count` rising edges of `event` as fused ticks: each one /// evaluates the combinational logic and then the sequential domain, /// without toggling the clock signal. Returns how many completed before @@ -89,6 +97,32 @@ pub trait SimulationExecutor { false } + /// Whether a served request leaves design writes needing a settle. + /// Unknown hosts remain conservative; scratch-only services or hosts + /// that already settled their writes can preserve a completed settle. + fn host_request_changes_design(&self, _process: usize, _request: usize) -> bool { + true + } + + /// Serve host request `request` of process `process` at `time`, reading + /// and writing the scratch state the request names. Returns whether the + /// process resumes; `false` ends the simulation, as when a host + /// component requested the end of the run. + fn host_request( + &mut self, + process: usize, + request: usize, + time: u64, + ) -> Result { + let _ = time; + Err(SimulatorErrorCode::Runtime { + message: format!( + "process {process} made host request {request}, which this host does not serve" + ), + signals: Vec::new(), + }) + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( @@ -137,7 +171,29 @@ pub struct ProcessRefs { pub status: SignalRef, pub delay: SignalRef, pub clock: SignalRef, + pub release: SignalRef, pub clocks: Vec>, + /// The writes a clock wait may end with. + pub releases: Vec>, +} + +/// A write a clock wait ends with: the signal, the event of its domain +/// when it is the clock or reset of one, and the value. +#[derive(Debug)] +pub struct ProcessReleaseRef { + pub signal: SignalRef, + pub event: Option, + pub value: u64, +} + +impl Clone for ProcessReleaseRef { + fn clone(&self) -> Self { + Self { + signal: self.signal, + event: self.event, + value: self.value, + } + } } impl Clone for ProcessRefs { @@ -146,7 +202,9 @@ impl Clone for ProcessRefs { status: self.status, delay: self.delay, clock: self.clock, + release: self.release, clocks: self.clocks.clone(), + releases: self.releases.clone(), } } } @@ -181,11 +239,12 @@ impl Clone for TickClock { } /// A process waiting for `remaining` more rising edges of the process clock -/// with event id `clock`. +/// with event id `clock`, ending with the process's release `release`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct ClockWait { clock: usize, remaining: u64, + release: Option, } /// The state of one process clock, for schedules expressed by name. @@ -268,6 +327,9 @@ pub struct SimulationState { periodic_events: FxHashMap, last_clock_values: BitSet, pending_host_edges: BTreeMap, + settled_process_edges: BTreeMap, + /// Events whose signal was x or z when edge detection last sampled it: + /// a change to a known value is an edge (IEEE 1800-2023 9.4.2). unknown_clock_values: BitSet, topo_signals: Vec<(SignalRef, usize, usize)>, domain_kinds: Vec>, @@ -278,6 +340,7 @@ pub struct SimulationState { process_event_counters: Vec<(usize, SignalRef, SignalRef)>, active_ff_domains: BitSet, process_wakeups: BinaryHeap, + budget_blocked_processes: BTreeSet, /// Processes suspended at an event or level wait, which their kernels /// re-check whenever the state may have changed. waiting: BTreeSet, @@ -287,15 +350,29 @@ pub struct SimulationState { clock_waits: BTreeMap, /// Processes that ran to their end. done: BTreeSet, - /// Rising edges of process clocks so far. + /// Writes to make when a process resumes from a clock wait. + pending_releases: BTreeMap, + /// Times with a rising edge of a process clock so far. ticks: u64, + /// How many more times with a rising edge of a process clock may run. + /// At zero, pending falling edges and releases still complete, but no + /// edge fires and no process resumes from a clock wait. + tick_budget: Option, sampled_ready: BTreeSet, inactive: BTreeSet, /// A process requested the end of the simulation. finished: bool, finish_round: bool, + /// A wait ended with a release this round: the combinational logic is + /// settled before the processes run, so the released process reads + /// what its release implies. + settle_before_processes: bool, } +/// The edges of a transition between sampled values `(nonzero, unknown)`, +/// as `(posedge, negedge)` (IEEE 1800-2023 Table 9-2): a change from 0, or +/// from x or z to 1, is a posedge, and a change from 1, or from x or z to 0, +/// is a negedge; between x and z there is no edge. fn transition_edges(was: (bool, bool), is: (bool, bool)) -> (bool, bool) { let (was_nonzero, was_unknown) = was; let (is_nonzero, is_unknown) = is; @@ -330,6 +407,7 @@ impl SimulationState { /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { self.pending_host_edges.clear(); + self.settled_process_edges.clear(); self.sample_event_values(backend); for clock in self.tick_clocks.values_mut() { clock.driven_value = None; @@ -463,11 +541,11 @@ impl SimulationState { } signal_to_id.insert(signal, id); signal_index_by_id[id] = index; - let (value, unknown) = sample_event_signal(backend, signal); - if value { + let (is_nonzero, is_unknown) = sample_event_signal(backend, signal); + if is_nonzero { last_clock_values.insert(id); } - if unknown { + if is_unknown { unknown_clock_values.insert(id); } } @@ -477,6 +555,7 @@ impl SimulationState { periodic_events: FxHashMap::default(), last_clock_values, pending_host_edges: BTreeMap::new(), + settled_process_edges: BTreeMap::new(), unknown_clock_values, topo_signals, domain_kinds, @@ -486,6 +565,7 @@ impl SimulationState { process_wakeups: (0..processes.len()) .map(|process| Reverse((0, process))) .collect(), + budget_blocked_processes: BTreeSet::new(), processes, process_event_counters: Vec::new(), active_ff_domains: BitSet::new(), @@ -493,10 +573,13 @@ impl SimulationState { tick_clocks: BTreeMap::new(), clock_waits: BTreeMap::new(), done: BTreeSet::new(), + pending_releases: BTreeMap::new(), ticks: 0, + tick_budget: None, sampled_ready: BTreeSet::new(), inactive: BTreeSet::new(), finished: false, + settle_before_processes: false, round_published_domains: BitSet::new(), round_triggered_domains: BitSet::new(), scheduled_clock_drives: BitSet::new(), @@ -507,11 +590,39 @@ impl SimulationState { } } - /// Rising edges of process clocks the simulation has run so far. + /// Times with a rising edge of a process clock the simulation has run + /// so far. pub fn ticks(&self) -> u64 { self.ticks } + /// Limit the times with a rising edge of a process clock that may still + /// run; `None` lifts the limit. + pub fn set_tick_budget(&mut self, budget: Option) { + self.tick_budget = budget; + if !self.tick_budget_spent() { + for process in std::mem::take(&mut self.budget_blocked_processes) { + self.process_wakeups + .push(Reverse((self.scheduler.time, process))); + } + } + } + + /// Whether the tick budget is spent. + pub fn tick_budget_spent(&self) -> bool { + self.tick_budget == Some(0) + } + + /// Whether a process still waits for edges of a clock. + pub fn has_clock_waits(&self) -> bool { + !self.clock_waits.is_empty() + } + + /// Whether every process ran to its end. + pub fn all_processes_done(&self) -> bool { + self.done.len() == self.processes.len() + } + fn clock_has_waiters(&self, clock: usize) -> bool { self.clock_waits.values().any(|wait| wait.clock == clock) } @@ -579,11 +690,15 @@ impl SimulationState { } /// Capture suspended event waits without executing their continuations. - pub fn sample_waiting_events(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + pub fn sample_waiting_events( + &mut self, + executor: &mut E, + time: u64, + ) -> Result<(), SimulatorErrorCode> where E: SimulationExecutor, { - self.sample_waiting(executor, false) + self.sample_waiting(executor, time, false) } /// Probe event and level waits without running their continuations. @@ -592,10 +707,15 @@ impl SimulationState { where E: SimulationExecutor, { - self.sample_waiting(executor, true) + self.sample_waiting(executor, self.time(), true) } - fn sample_waiting(&mut self, executor: &mut E, probe: bool) -> Result<(), SimulatorErrorCode> + fn sample_waiting( + &mut self, + executor: &mut E, + time: u64, + probe: bool, + ) -> Result<(), SimulatorErrorCode> where E: SimulationExecutor, { @@ -614,7 +734,7 @@ impl SimulationState { executor .backend_mut() .set(refs.delay, if probe { 2u64 } else { 1u64 }); - let result = executor.run_process(process); + let result = executor.run_process(process, time); executor.backend_mut().set(refs.delay, delay); result?; if ProcessStatus::from_code(executor.backend().get_as(refs.status)) @@ -733,6 +853,7 @@ impl SimulationState { }); } } + let ready = self.take_ready_processes(executor, current_time, &mut events_to_process); let rising: Vec = self .tick_clocks .iter() @@ -742,6 +863,7 @@ impl SimulationState { && (!self.last_clock_values.contains(**id) || self.unknown_clock_values.contains(**id)); (!events_to_process.is_empty() || pending_rise) + && !self.tick_budget_spent() && !falling.contains(*id) && clock.next_edge == current_time && self.clock_has_waiters(**id) @@ -759,7 +881,6 @@ impl SimulationState { next_val: 1, }); } - let ready = self.take_ready_processes(current_time); let mut delta_rounds = 0; let result = self.step_round( executor, @@ -796,26 +917,41 @@ impl SimulationState { E: SimulationExecutor, { while !self.finished { - let due: Vec = self + let due: Vec = if self.tick_budget_spent() { + Vec::new() + } else { + self.tick_clocks + .iter() + .filter(|(id, clock)| { + clock.next_edge == current_time && self.clock_has_waiters(**id) + }) + .map(|(id, _)| *id) + .collect() + }; + let falling: Vec = self .tick_clocks .iter() - .filter(|(id, clock)| { - clock.next_edge == current_time && self.clock_has_waiters(**id) - }) + .filter(|(_, clock)| clock.falling_edge == Some(current_time)) .map(|(id, _)| *id) .collect(); - if let [clock] = due[..] + if falling.is_empty() + && let [clock] = due[..] && self.fused_ticks(executor, clock, current_time, limit)? { // Time moved on; the processes that resume run in the next step. return Ok(()); } - let fired = !due.is_empty(); + let fired = !due.is_empty() || !falling.is_empty(); if fired { - self.fire_edges(executor, current_time, &due, delta_rounds)?; + self.fire_edges(executor, current_time, &due, &falling, delta_rounds)?; } - let ready = self.take_ready_processes(current_time); - if ready.is_empty() && self.waiting.is_empty() { + let mut events = Vec::new(); + let ready = self.take_ready_processes(executor, current_time, &mut events); + if ready.is_empty() + && self.waiting.is_empty() + && events.is_empty() + && !self.settle_before_processes + { if fired { // The edges may have released waits that resume now. continue; @@ -825,7 +961,7 @@ impl SimulationState { let result = self.step_round( executor, current_time, - Vec::new(), + events, Vec::new(), ready, false, @@ -840,14 +976,16 @@ impl SimulationState { Ok(()) } - /// Apply the rising edges of the process clocks `due` at `time`, count - /// them against the processes waiting on them, and schedule the - /// resumptions and falling edges. + /// Apply the rising edges of the process clocks `due` and the falling + /// edges of the clocks `falling` at `time` as one set of simultaneous + /// events, count the rising edges against the processes waiting on + /// them, and schedule the resumptions and falling edges. fn fire_edges( &mut self, executor: &mut E, time: u64, due: &[usize], + falling: &[usize], delta_rounds: &mut usize, ) -> Result<(), SimulatorErrorCode> where @@ -859,10 +997,20 @@ impl SimulationState { } // A clock that is high when its edge is due (the host or a previous // run left it so) falls first, in a round of its own: the rising - // edge that counts is then a real one. - let mut events = Vec::with_capacity(due.len()); + // edge that counts is then a real one. The falling edges due now + // are applied in the same round. + let mut events = Vec::with_capacity(falling.len() + due.len()); + for id in falling { + let clock = &self.tick_clocks[id]; + events.push(SimEvent { + time, + event_ref: clock.event, + signal: clock.signal, + next_val: 0, + }); + } let mut rising = Vec::with_capacity(due.len()); - let mut falling = Vec::new(); + let mut falling = falling.to_vec(); for id in due { let clock = &self.tick_clocks[id]; let high = sample_event_signal(executor.backend(), clock.signal) == (true, false); @@ -939,12 +1087,22 @@ impl SimulationState { time: u64, rising: Vec, ) -> Result<(), SimulatorErrorCode> { + if rising.is_empty() { + return Ok(()); + } + for id in &rising { + time.checked_add(self.tick_clocks[id].period) + .ok_or_else(|| clock_overflow(*id))?; + } + self.ticks += 1; + if let Some(budget) = &mut self.tick_budget { + *budget -= 1; + } for id in rising { let clock = self.tick_clocks.get_mut(&id).expect("a due process clock"); let next_edge = time .checked_add(clock.period) .ok_or_else(|| clock_overflow(id))?; - self.ticks += 1; clock.next_edge = next_edge; clock.falling_edge = Some(next_edge - clock.period / 2); let resume_at = clock.next_edge; @@ -967,7 +1125,10 @@ impl SimulationState { }) .collect(); for process in released { - self.clock_waits.remove(&process); + let wait = self.clock_waits.remove(&process).expect("a released wait"); + if let Some(release) = wait.release { + self.pending_releases.insert(process, release); + } self.process_wakeups.push(Reverse((resume_at, process))); } } @@ -1016,8 +1177,11 @@ impl SimulationState { (clock.event, clock.signal, clock.period) }; // Edges at `time`, `time + period`, ...: the last one stays at or - // before `limit`. - let count = needed.min(limit.saturating_sub(time) / period + 1); + // before `limit` and within the tick budget. + let mut count = needed.min(limit.saturating_sub(time) / period + 1); + if let Some(budget) = self.tick_budget { + count = count.min(budget); + } if count == 0 { return Ok(false); } @@ -1049,6 +1213,9 @@ impl SimulationState { // the schedule agrees with the state it left. if completed != 0 { self.ticks += completed; + if let Some(budget) = &mut self.tick_budget { + *budget -= completed; + } self.scheduler.time = time + (completed - 1) * period; let next_edge = completed .checked_mul(period) @@ -1155,7 +1322,9 @@ impl SimulationState { E: SimulationExecutor, { if self.finished - || (self.waiting.is_empty() && self.pending_host_edges.is_empty()) + || (self.waiting.is_empty() + && self.pending_host_edges.is_empty() + && self.settled_process_edges.is_empty()) || self.scheduler.time > limit { return Ok(false); @@ -1168,13 +1337,14 @@ impl SimulationState { { return Ok(false); } - self.sample_waiting_events(executor)?; - let ready = self.take_ready_processes(time); + self.sample_waiting_events(executor, time)?; + let mut events = Vec::new(); + let ready = self.take_ready_processes(executor, time, &mut events); let mut delta_rounds = 0; let result = self.step_round( executor, time, - Vec::new(), + events, Vec::new(), ready, false, @@ -1190,8 +1360,23 @@ impl SimulationState { Ok(true) } - /// Remove the processes waiting for `time`, in declaration order. - fn take_ready_processes(&mut self, time: u64) -> Vec { + /// Remove the processes waiting for `time`, in declaration order. With + /// the tick budget spent, a process resuming from a clock wait only gets + /// its release and stays suspended. + /// The processes that resume at `time`, after making the releases their + /// waits ended with: a release of a signal with an event domain is an + /// event of `time`, added to `events`, so the domain and the host hooks + /// see its edge; any other is written directly. Once the tick budget + /// is spent, releases are still made but no process resumes. + fn take_ready_processes( + &mut self, + executor: &mut E, + time: u64, + events: &mut Vec>, + ) -> Vec + where + E: SimulationExecutor, + { let mut ready = std::mem::take(&mut self.inactive) .into_iter() .collect::>(); @@ -1200,11 +1385,114 @@ impl SimulationState { break; } self.process_wakeups.pop(); + if let Some(release) = self.pending_releases.remove(&process) { + self.settle_before_processes = true; + let release = self.processes[process].releases[release].clone(); + match release.event { + Some(event) => events.push(SimEvent { + time, + event_ref: event, + signal: release.signal, + next_val: release.value as u8, + }), + None => executor + .backend_mut() + .set_wide(release.signal, release.value.into()), + } + } + if self.tick_budget_spent() { + self.budget_blocked_processes.insert(process); + continue; + } ready.push(process); } ready } + fn process_counter_values(&self, backend: &B) -> Vec<(u32, u32)> { + self.process_event_counters + .iter() + .map(|(_, rises, falls)| (backend.get_as(*rises), backend.get_as(*falls))) + .collect() + } + + fn add_process_edge_replays( + &self, + backend: &B, + before: &[(u32, u32)], + replays: &mut std::collections::BTreeMap, + preceding_edges: &BitSet, + ) { + let mut counters = std::collections::BTreeMap::new(); + for ((id, rises, falls), (old_rises, old_falls)) in + self.process_event_counters.iter().zip(before) + { + let rise = backend.get_as::(*rises).wrapping_sub(*old_rises) as u64; + let fall = backend.get_as::(*falls).wrapping_sub(*old_falls) as u64; + let count = match self.domain_kinds[*id] { + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => fall, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => rise, + _ => rise + fall, + }; + let canonical = self.event_info[*id].canonical_id; + let Some(info) = self.event_info.get(canonical) else { + continue; + }; + if info.eval_ff_event.is_none() + && info.eval_only_event.is_none() + && info.apply_event.is_none() + { + continue; + } + counters + .entry((canonical, *rises, *falls)) + .and_modify(|n: &mut u64| *n = (*n).max(count)) + .or_insert(count); + } + let mut totals = std::collections::BTreeMap::::new(); + for ((id, _, _), count) in counters { + *totals.entry(id).or_default() += count; + } + for (&id, &count) in &self.settled_process_edges { + *totals.entry(id).or_default() += count; + } + for (id, count) in totals { + // Keep the first process occurrence separate from an already + // captured scheduled/host edge of the same canonical domain. + let occupied = preceding_edges + .iter() + .any(|edge| self.event_info[edge].canonical_id == id); + *replays.entry(id).or_default() += count.saturating_sub(u64::from(!occupied)); + } + } + + fn process_counter_edges(&mut self, backend: &B, before: &[(u32, u32)]) -> BitSet { + let mut edges = BitSet::with_capacity(backend.num_events()); + for (id, _) in std::mem::take(&mut self.settled_process_edges) { + edges.insert(id); + } + for ((id, rises, falls), (old_rises, old_falls)) in + self.process_event_counters.iter().zip(before) + { + let changed = match self.domain_kinds[*id] { + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + backend.get_as::(*falls) != *old_falls + } + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + backend.get_as::(*rises) != *old_rises + } + _ => { + backend.get_as::(*rises) != *old_rises + || backend.get_as::(*falls) != *old_falls + } + }; + if changed { + edges.insert(*id); + } + } + edges + } + /// Run `ready` processes, and the processes waiting for an event or a /// condition, in declaration order until each suspends or ends. A /// process another one wakes runs in a further pass of the same round, @@ -1217,11 +1505,16 @@ impl SimulationState { executor: &mut E, current_time: u64, ready: Vec, + comb_current: &mut bool, delta_rounds: &mut usize, ) -> Result where E: SimulationExecutor, { + if self.finished || executor.finish_requested(current_time) { + self.finished = true; + return Ok(false); + } let mut progressed = false; let mut pass = ready; loop { @@ -1251,11 +1544,20 @@ impl SimulationState { ) }) .collect::>(); + let before_signals = self + .topo_signals + .iter() + .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) + .collect::>(); + let mut counter_recorded = BitSet::new(); executor .backend_mut() .set(self.processes[process].delay, 0u64); - executor.run_process(process)?; + executor.run_process(process, current_time)?; self.sampled_ready.remove(&process); + if !executor.process_is_clean(process) { + *comb_current = false; + } if executor.finish_requested(current_time) { self.finish_round = true; @@ -1269,12 +1571,23 @@ impl SimulationState { Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { executor.backend().get_as::(*falls) != old_falls } - _ => executor.backend().get_as::(*rises) != old_rises, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + executor.backend().get_as::(*rises) != old_rises + } + _ => { + executor.backend().get_as::(*rises) != old_rises + || executor.backend().get_as::(*falls) != old_falls + } }; if changed { executor.backend_mut().mark_triggered_bit(*id); + let canonical = self.event_info[*id].canonical_id; + if canonical != usize::MAX { + counter_recorded.insert(canonical); + } } } + let refs = &self.processes[process]; let status: u8 = executor.backend().get_as(refs.status); match ProcessStatus::from_code(status) { @@ -1290,6 +1603,22 @@ impl SimulationState { any_ran = true; continue; } + Some(ProcessStatus::Settle) => { + executor.eval_comb()?; + self.record_process_settle_edges( + executor.backend(), + &before_signals, + &counter_recorded, + ); + self.sample_waiting_events(executor, current_time)?; + *comb_current = true; + if executor.finish_requested(current_time) { + self.finished = true; + return Ok(true); + } + any_ran = true; + continue; + } Some(ProcessStatus::Delay | ProcessStatus::InactiveDelay) => { let delay: u64 = executor.backend().get_as(refs.delay); let time = current_time.checked_add(delay).ok_or_else(|| { @@ -1316,8 +1645,11 @@ impl SimulationState { self.done.insert(process); any_ran = true; } - Some(ProcessStatus::Finish) => { - self.finish_round = true; + Some( + status + @ (ProcessStatus::Finish | ProcessStatus::FinishAfterPublication), + ) => { + self.finish_round = status == ProcessStatus::Finish; self.waiting.remove(&process); self.done.insert(process); self.finished = true; @@ -1330,13 +1662,48 @@ impl SimulationState { Some(ProcessStatus::WaitClock) => { let count: u64 = executor.backend().get_as(refs.delay); let index: u32 = executor.backend().get_as(refs.clock); + let release: u32 = executor.backend().get_as(refs.release); let Some(clock) = refs.clocks.get(index as usize) else { return Err(SimulatorErrorCode::InternalError); }; + let release = match release { + 0 => None, + index if (index as usize) <= refs.releases.len() => { + Some(index as usize - 1) + } + _ => return Err(SimulatorErrorCode::InternalError), + }; self.waiting.remove(&process); if count == 0 { - // A zero-count wait does not yield to another process, - // but repeated immediate continuations must be bounded. + // Nothing to wait for: the release is made and + // the process continues at once, as a zero + // count documents. + if let Some(release) = release { + let release = refs.releases[release].clone(); + let before_release = self + .topo_signals + .iter() + .map(|(signal, _, _)| { + sample_event_signal(executor.backend(), *signal) + }) + .collect::>(); + executor + .backend_mut() + .set_wide(release.signal, release.value.into()); + executor.eval_comb()?; + self.record_process_settle_edges( + executor.backend(), + &before_release, + &BitSet::new(), + ); + self.sample_waiting_events(executor, current_time)?; + *comb_current = true; + if executor.finish_requested(current_time) { + self.finished = true; + return Ok(true); + } + } + any_ran = true; if let Err(error) = count_delta_pass(delta_rounds) { self.process_wakeups.push(Reverse((current_time, process))); for process in remaining { @@ -1362,6 +1729,7 @@ impl SimulationState { ClockWait { clock: id, remaining: count, + release, }, ); // Retain the activation before validation so @@ -1370,6 +1738,45 @@ impl SimulationState { } any_ran = true; } + // A served host request resumes the same process at + // once: the request is a zero-time call of the + // statement, and no other process runs in between. + Some(ProcessStatus::Host) => { + let request: u64 = executor.backend().get_as(refs.delay); + self.waiting.remove(&process); + let before_host = self + .topo_signals + .iter() + .map(|(signal, _, _)| { + sample_event_signal(executor.backend(), *signal) + }) + .collect::>(); + if !executor.host_request(process, request as usize, current_time)? { + self.finish_round = true; + self.done.insert(process); + self.finished = true; + return Ok(true); + } + // A host may leave design writes outside this + // kernel's store instrumentation that need settling. + if executor.host_request_changes_design(process, request as usize) { + executor.eval_comb()?; + *comb_current = true; + } + self.record_process_settle_edges( + executor.backend(), + &before_host, + &BitSet::new(), + ); + self.sample_waiting_events(executor, current_time)?; + if executor.finish_requested(current_time) { + self.finish_round = true; + self.finished = true; + return Ok(true); + } + any_ran = true; + continue; + } // The kernel found its wait condition unmet and ran // nothing; it stays waiting. Some(ProcessStatus::Pending) => {} @@ -1387,6 +1794,48 @@ impl SimulationState { } } + fn record_process_settle_edges( + &mut self, + backend: &B, + before: &[(bool, bool)], + counter_recorded: &BitSet, + ) { + let mut seen = BitSet::new(); + for ((signal, id, canonical), before) in + self.topo_signals.iter().zip(before.iter().copied()) + { + if *id == usize::MAX || *canonical == usize::MAX { + continue; + } + let info = &self.event_info[*canonical]; + if info.eval_ff_event.is_none() + && info.eval_only_event.is_none() + && info.apply_event.is_none() + { + continue; + } + let after = sample_event_signal(backend, *signal); + let active = match self.domain_kinds[*id] { + Some( + DomainKind::ClockPosedge + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncHigh + | DomainKind::ResetAsyncLow, + ) => self.edge_triggers(*id, before, after), + _ => before != after, + }; + if active && !counter_recorded.contains(*canonical) && seen.insert(*canonical) { + *self.settled_process_edges.entry(*canonical).or_default() += 1; + } + } + } + + /// Whether all processes at or beyond the testbench boundary are done. + pub fn processes_done_from(&self, first: usize) -> bool { + first <= self.processes.len() + && self.done.range(first..).count() == self.processes.len() - first + } + /// Record a finish emitted by the host while settling current-time writes. pub fn finish(&mut self) { self.finish_round = true; @@ -1420,12 +1869,13 @@ impl SimulationState { if settled_target { return Ok(Some(time)); } - let ready = self.take_ready_processes(time); + let mut events = Vec::new(); + let ready = self.take_ready_processes(executor, time, &mut events); let mut delta_rounds = 0; let result = self.step_round( executor, time, - Vec::new(), + events, Vec::new(), ready, true, @@ -1457,6 +1907,7 @@ impl SimulationState { where E: SimulationExecutor, { + let mut comb_current = false; self.scheduler.time = current_time; self.round_published_domains.make_empty(); self.round_triggered_domains.make_empty(); @@ -1573,7 +2024,13 @@ impl SimulationState { } } } - self.sample_waiting_events(executor)?; + self.sample_waiting_events(executor, current_time)?; + } + if std::mem::take(&mut self.settle_before_processes) + && (!ready_processes.is_empty() || !self.waiting.is_empty()) + { + executor.eval_comb()?; + comb_current = true; } for (id, count) in batch_edge_counts { // The first occurrence is already in scheduled_edges, unless a @@ -1585,18 +2042,25 @@ impl SimulationState { // Processes run after this time's scheduled values are applied and // see the state settled at the previous time. The event signals they // change are edges of this time, like scheduled events. + // (event, the sampled value now): the edge is judged against the + // sampled value before, so transitions from and into x or z count + // as IEEE 1800-2023 Table 9-2 says. executor.backend_mut().clear_triggered_bits(); - let counter_values = self.event_counter_values(executor.backend()); + let counter_values = self.process_counter_values(executor.backend()); let mut process_driven = Vec::new(); - let mut process_settled = false; if !ready_processes.is_empty() || !self.waiting.is_empty() { let before: Vec<(bool, bool)> = self .topo_signals .iter() .map(|(signal, _, _)| sample_event_signal(executor.backend(), *signal)) .collect(); - let progressed = - self.run_processes(executor, current_time, ready_processes, delta_rounds)?; + let progressed = self.run_processes( + executor, + current_time, + ready_processes, + &mut comb_current, + delta_rounds, + )?; if self.finished && self.finish_round { return Ok(true); } @@ -1604,26 +2068,29 @@ impl SimulationState { && !settle_idle && events_to_process.is_empty() && scheduled_edges.is_empty() + && self.settled_process_edges.is_empty() { return Ok(false); } // Discover combinationally derived edges before choosing the // generated clocks that must share this publication round. - if progressed { + if progressed && !comb_current { executor.eval_comb()?; - process_settled = true; + comb_current = true; if executor.finish_requested(current_time) { self.finished = true; return Ok(true); } } - for ((signal, id, _), before) in self.topo_signals.iter().zip(before) { + for ((signal, id, _), (was_nonzero, was_unknown)) in + self.topo_signals.iter().zip(before) + { if *id == usize::MAX { continue; } - let value = sample_event_signal(executor.backend(), *signal); - if value != before { - process_driven.push((*id, value)); + let is = sample_event_signal(executor.backend(), *signal); + if is != (was_nonzero, was_unknown) { + process_driven.push((*id, is)); } } } @@ -1641,13 +2108,21 @@ impl SimulationState { &mut edge_replays, &scheduled_edges, ); - let process_recorded_edges = self.counter_edges(executor.backend(), &counter_values); + let process_recorded_edges = + self.process_counter_edges(executor.backend(), &counter_values); + + // Ready processes can activate a clock at this timestamp. Join + // its first rise with existing events and reset assertions before + // any coincident domain publishes its FF updates. An isolated + // ordinary clock wait retains the fused-tick path. + let reset_edge_due = self.clock_waits.values().any(|wait| { + wait.release.is_some() && self.tick_clocks[&wait.clock].next_edge == current_time + }); - // Ready processes may activate a clock at this timestamp. Join it - // to existing source events before any coincident FF domain commits. - // With no other event, retain the later fused-tick path. if !self.finished - && (!scheduled_edges.is_empty() + && !self.tick_budget_spent() + && (reset_edge_due + || !scheduled_edges.is_empty() || !events_to_process.is_empty() || !process_driven.is_empty() || !generated_events.is_empty() @@ -1689,8 +2164,10 @@ impl SimulationState { .checked_add(self.tick_clocks[&id].period) .ok_or_else(|| clock_overflow(id))?; } + if !generated_events.is_empty() { + comb_current = false; + } for event in &generated_events { - process_settled = false; executor.backend_mut().set(event.signal, event.next_val); self.record_generated_clock_drive(event); } @@ -1715,19 +2192,19 @@ impl SimulationState { .map(|&id| (id, (event.next_val & 1 != 0, false))) }) .chain(process_driven); - for (id, is_nonzero) in scheduled { + for (id, is) in scheduled { track_stable_edges = true; - let was_nonzero = ( + let was = ( self.last_clock_values.contains(id), self.unknown_clock_values.contains(id), ); - if self.edge_triggers(id, was_nonzero, is_nonzero) { + if self.edge_triggers(id, was, is) { scheduled_trigger_ids.insert(id); executor.backend_mut().mark_triggered_bit(id); } } - if !process_settled { + if !comb_current { executor.eval_comb()?; } if executor.finish_requested(current_time) { @@ -1736,7 +2213,7 @@ impl SimulationState { } // Capture every waiter before any continuation can remove a // propagated edge produced by the active process writes. - self.sample_waiting_events(executor)?; + self.sample_waiting_events(executor, current_time)?; // Settle process writes before deciding whether they restored an // early edge. Persistent edges follow the ordinary cascade after // source FF publication; only vanished edges need explicit replay. @@ -1848,7 +2325,7 @@ impl SimulationState { newly_triggered.push(info.canonical_id); self.round_triggered_domains.insert(info.canonical_id); - let before = self.event_counter_values(executor.backend()); + let before = self.process_counter_values(executor.backend()); if let Some(event) = info.eval_only_event { executor.stage_external_event( info.eval_ff_event.unwrap_or(event), @@ -1877,7 +2354,8 @@ impl SimulationState { &mut edge_replays, &occupied, ); - ff_body_edges.union_with(&self.counter_edges(executor.backend(), &before)); + ff_body_edges + .union_with(&self.process_counter_edges(executor.backend(), &before)); } recorded_edges.union_with(&ff_body_edges); @@ -1892,10 +2370,15 @@ impl SimulationState { // FF evaluations and before the pending NBA publications. // Drain active evaluations before promoting another inactive // batch, including evaluations a combinational settle woke. - let inactive_counter_values = self.event_counter_values(executor.backend()); + let inactive_counter_values = self.process_counter_values(executor.backend()); let mut inactive_samples = None; - let mut active_ran = - self.run_processes(executor, current_time, Vec::new(), delta_rounds)?; + let mut active_ran = self.run_processes( + executor, + current_time, + Vec::new(), + &mut comb_current, + delta_rounds, + )?; if !active_ran { // Drain active combinational effects of blocking FF stores // before either inactive continuations or NBA publication. @@ -1909,7 +2392,7 @@ impl SimulationState { } // Latch every waiter before another active FF or // continuation can erase a propagated blocking edge. - self.sample_waiting_events(executor)?; + self.sample_waiting_events(executor, current_time)?; self.replace_triggers_with_stable_edges(executor.backend_mut()); for id in ff_body_edges.iter() { executor.backend_mut().mark_triggered_bit(id); @@ -1924,8 +2407,13 @@ impl SimulationState { } executor.backend_mut().clear_triggered_bits(); } - active_ran = - self.run_processes(executor, current_time, Vec::new(), delta_rounds)?; + active_ran = self.run_processes( + executor, + current_time, + Vec::new(), + &mut comb_current, + delta_rounds, + )?; } if self.finished && self.finish_round { return Ok(true); @@ -1970,7 +2458,13 @@ impl SimulationState { } } inactive_samples = Some(before); - self.run_processes(executor, current_time, ready, delta_rounds)? + self.run_processes( + executor, + current_time, + ready, + &mut comb_current, + delta_rounds, + )? }; if progressed { self.add_process_edge_replays( @@ -1980,7 +2474,7 @@ impl SimulationState { &BitSet::new(), ); let mut driven = - self.counter_edges(executor.backend(), &inactive_counter_values); + self.process_counter_edges(executor.backend(), &inactive_counter_values); recorded_edges.union_with(&driven); driven.union_with(&ff_body_edges); executor.eval_comb()?; @@ -2093,10 +2587,15 @@ impl SimulationState { } if polled { - self.sample_waiting_events(executor)?; - let counter_values = self.event_counter_values(executor.backend()); - any_process_ran |= - self.run_processes(executor, current_time, Vec::new(), delta_rounds)?; + self.sample_waiting_events(executor, current_time)?; + let counter_values = self.process_counter_values(executor.backend()); + any_process_ran |= self.run_processes( + executor, + current_time, + Vec::new(), + &mut comb_current, + delta_rounds, + )?; if self.finished && self.finish_round { return Ok(true); } @@ -2107,14 +2606,15 @@ impl SimulationState { &mut edge_replays, &BitSet::new(), ); - let mut driven = self.counter_edges(executor.backend(), &counter_values); + let mut driven = + self.process_counter_edges(executor.backend(), &counter_values); recorded_edges.union_with(&driven); for ((signal, id, _), before) in self.topo_signals.iter().zip(before) { if *id == usize::MAX { continue; } - let value = sample_event_signal(executor.backend(), *signal); - if value != before && self.edge_triggers(*id, before, value) { + let is = sample_event_signal(executor.backend(), *signal); + if is != before && self.edge_triggers(*id, before, is) { driven.insert(*id); executor.backend_mut().mark_triggered_bit(*id); } @@ -2149,17 +2649,17 @@ impl SimulationState { if *id == usize::MAX { continue; } - let (value, unknown) = sample_event_signal(executor.backend(), *signal); - if unknown { - self.unknown_clock_values.insert(*id); - } else { - self.unknown_clock_values.remove(*id); - } - if value { + let (is_nonzero, is_unknown) = sample_event_signal(executor.backend(), *signal); + if is_nonzero { self.last_clock_values.insert(*id); } else { self.last_clock_values.remove(*id); } + if is_unknown { + self.unknown_clock_values.insert(*id); + } else { + self.unknown_clock_values.remove(*id); + } } for event in periodic_events_to_process { @@ -2193,13 +2693,13 @@ impl SimulationState { self.round_published_domains.insert(canonical); for (signal, id, _) in &self.topo_signals { if *id != usize::MAX && self.event_info[*id].canonical_id == canonical { - let (value, unknown) = sample_event_signal(backend, *signal); + let (nonzero, unknown) = sample_event_signal(backend, *signal); if unknown { self.unknown_clock_values.insert(*id); } else { self.unknown_clock_values.remove(*id); } - if value { + if nonzero { self.last_clock_values.insert(*id); } else { self.last_clock_values.remove(*id); @@ -2208,80 +2708,8 @@ impl SimulationState { } } - fn event_counter_values(&self, backend: &B) -> Vec<(u32, u32)> { - self.process_event_counters - .iter() - .map(|(_, rises, falls)| (backend.get_as(*rises), backend.get_as(*falls))) - .collect() - } - - fn add_process_edge_replays( - &self, - backend: &B, - before: &[(u32, u32)], - replays: &mut BTreeMap, - preceding_edges: &BitSet, - ) { - let mut counters = BTreeMap::new(); - for ((id, rises, falls), (old_rises, old_falls)) in - self.process_event_counters.iter().zip(before) - { - let rise = backend.get_as::(*rises).wrapping_sub(*old_rises) as u64; - let fall = backend.get_as::(*falls).wrapping_sub(*old_falls) as u64; - let count = match self.domain_kinds[*id] { - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => fall, - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => rise, - _ => rise + fall, - }; - let canonical = self.event_info[*id].canonical_id; - let Some(info) = self.event_info.get(canonical) else { - continue; - }; - if info.eval_ff_event.is_none() - && info.eval_only_event.is_none() - && info.apply_event.is_none() - { - continue; - } - counters - .entry((canonical, *rises, *falls)) - .and_modify(|n: &mut u64| *n = (*n).max(count)) - .or_insert(count); - } - let mut totals = BTreeMap::::new(); - for ((id, _, _), count) in counters { - *totals.entry(id).or_default() += count; - } - for (id, count) in totals { - // One occurrence fits in the normal trigger set. If an earlier - // queued/host edge occupies it, replay the full process delta. - let occupied = preceding_edges - .iter() - .any(|edge| self.event_info[edge].canonical_id == id); - *replays.entry(id).or_default() += count.saturating_sub(u64::from(!occupied)); - } - } - - fn counter_edges(&self, backend: &B, before: &[(u32, u32)]) -> BitSet { - let mut edges = BitSet::with_capacity(backend.num_events()); - for ((id, rises, falls), (old_rises, old_falls)) in - self.process_event_counters.iter().zip(before) - { - let changed = match self.domain_kinds[*id] { - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { - backend.get_as::(*falls) != *old_falls - } - _ => backend.get_as::(*rises) != *old_rises, - }; - if changed { - edges.insert(*id); - } - } - edges - } - - /// Whether a change of event signal `id` from `was_nonzero` to - /// `is_nonzero` is the edge its domain triggers on. + /// Whether a change of event signal `id` from `was` to `is` (nonzero, + /// unknown) is the edge its domain triggers on. fn edge_triggers(&self, id: usize, was: (bool, bool), is: (bool, bool)) -> bool { let (posedge, negedge) = transition_edges(was, is); match self.domain_kinds[id] { @@ -2305,7 +2733,10 @@ impl SimulationState { if self.finished { return None; } - if !self.pending_host_edges.is_empty() || !self.sampled_ready.is_empty() { + if !self.pending_host_edges.is_empty() + || !self.settled_process_edges.is_empty() + || !self.sampled_ready.is_empty() + { return Some(self.scheduler.time); } let process = if self.inactive.is_empty() { @@ -2313,12 +2744,13 @@ impl SimulationState { } else { Some(self.scheduler.time) }; + let budget_spent = self.tick_budget_spent(); let clocks = self .tick_clocks .iter() .flat_map(|(id, clock)| { [ - self.clock_has_waiters(*id).then_some(clock.next_edge), + (!budget_spent && self.clock_has_waiters(*id)).then_some(clock.next_edge), clock.falling_edge, ] }) @@ -2350,13 +2782,17 @@ impl SimulationState { periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), pending_host_edges: self.pending_host_edges.clone(), + settled_process_edges: self.settled_process_edges.clone(), unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), + budget_blocked_processes: self.budget_blocked_processes.clone(), waiting: self.waiting.clone(), tick_clocks: self.tick_clocks.clone(), clock_waits: self.clock_waits.clone(), done: self.done.clone(), + pending_releases: self.pending_releases.clone(), ticks: self.ticks, + tick_budget: self.tick_budget, sampled_ready: self.sampled_ready.clone(), inactive: self.inactive.clone(), scheduled_clock_drives: self.scheduled_clock_drives.clone(), @@ -2409,14 +2845,20 @@ impl SimulationState { .clone_from(&snapshot.last_clock_values); self.pending_host_edges .clone_from(&snapshot.pending_host_edges); + self.settled_process_edges + .clone_from(&snapshot.settled_process_edges); self.unknown_clock_values .clone_from(&snapshot.unknown_clock_values); self.process_wakeups.clone_from(&snapshot.process_wakeups); + self.budget_blocked_processes + .clone_from(&snapshot.budget_blocked_processes); self.waiting.clone_from(&snapshot.waiting); self.tick_clocks = tick_clocks; self.clock_waits.clone_from(&snapshot.clock_waits); self.done.clone_from(&snapshot.done); + self.pending_releases.clone_from(&snapshot.pending_releases); self.ticks = snapshot.ticks; + self.tick_budget = snapshot.tick_budget; self.sampled_ready.clone_from(&snapshot.sampled_ready); self.inactive.clone_from(&snapshot.inactive); self.scheduled_clock_drives @@ -2442,20 +2884,26 @@ pub struct ScheduleParts { pub high_events: Vec, /// Captured host edges; repeated handles retain repeated occurrences. pub captured_edges: Vec, + /// Unpublished FF occurrences sampled during process-internal settling. + pub settled_process_edges: Vec<(B::Event, u64)>, pub unknown_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, + pub budget_blocked_processes: Vec, /// Processes waiting for an event or a condition, in ascending order. pub waiting_processes: Vec, /// Process clocks that have been waited on. pub process_clocks: Vec>, /// Processes waiting for edges of a process clock: the process, the - /// clock's event, and the edges still to wait for. - pub clock_waits: Vec<(usize, B::Event, u64)>, + /// clock's event, the edges still to wait for, and the release index. + pub clock_waits: Vec<(usize, B::Event, u64, Option)>, + /// Releases to make when a process resumes: process and release index. + pub pending_releases: Vec<(usize, usize)>, /// Processes that ran to their end, in ascending order. pub done_processes: Vec, /// Rising edges of process clocks so far. pub ticks: u64, + pub tick_budget: Option, /// Timestamp and one-shot clock drives already consumed at that time. pub scheduled_clock_time: u64, pub scheduled_clock_drives: Vec, @@ -2494,6 +2942,11 @@ impl SimulationState { }) .collect(), high_events: self.last_clock_values.iter().map(|id| events[id]).collect(), + settled_process_edges: self + .settled_process_edges + .iter() + .map(|(&id, &count)| (events[id], count)) + .collect(), captured_edges: self .pending_host_edges .iter() @@ -2519,6 +2972,7 @@ impl SimulationState { wakeups.dedup(); wakeups }, + budget_blocked_processes: self.budget_blocked_processes.iter().copied().collect(), waiting_processes: self.waiting.iter().copied().collect(), process_clocks: self .tick_clocks @@ -2535,10 +2989,16 @@ impl SimulationState { clock_waits: self .clock_waits .iter() - .map(|(process, wait)| (*process, events[wait.clock], wait.remaining)) + .map(|(process, wait)| (*process, events[wait.clock], wait.remaining, wait.release)) + .collect(), + pending_releases: self + .pending_releases + .iter() + .map(|(process, release)| (*process, *release)) .collect(), done_processes: self.done.iter().copied().collect(), ticks: self.ticks, + tick_budget: self.tick_budget, scheduled_clock_time: self.scheduled_clock_time, scheduled_clock_drives: self .scheduled_clock_drives @@ -2576,6 +3036,11 @@ impl SimulationState { for event in parts.unknown_events { self.unknown_clock_values.insert(event.id()); } + self.settled_process_edges = parts + .settled_process_edges + .into_iter() + .map(|(event, count)| (event.id(), count)) + .collect(); self.pending_host_edges.clear(); for event in parts.captured_edges { *self.pending_host_edges.entry(event.id()).or_default() += 1; @@ -2586,6 +3051,7 @@ impl SimulationState { .into_iter() .map(|(process, time)| Reverse((time, process))) .collect(); + self.budget_blocked_processes = parts.budget_blocked_processes.into_iter().collect(); self.waiting = parts.waiting_processes.into_iter().collect(); self.tick_clocks = parts .process_clocks @@ -2607,18 +3073,21 @@ impl SimulationState { self.clock_waits = parts .clock_waits .into_iter() - .map(|(process, event, remaining)| { + .map(|(process, event, remaining, release)| { ( process, ClockWait { clock: event.id(), remaining, + release, }, ) }) .collect(); + self.pending_releases = parts.pending_releases.into_iter().collect(); self.done = parts.done_processes.into_iter().collect(); self.ticks = parts.ticks; + self.tick_budget = parts.tick_budget; self.scheduled_clock_time = parts.scheduled_clock_time; self.scheduled_clock_drives = parts .scheduled_clock_drives @@ -2638,13 +3107,17 @@ pub struct SimulationSnapshot { periodic_events: FxHashMap, last_clock_values: BitSet, pending_host_edges: BTreeMap, + settled_process_edges: BTreeMap, unknown_clock_values: BitSet, process_wakeups: BinaryHeap, + budget_blocked_processes: BTreeSet, waiting: BTreeSet, tick_clocks: BTreeMap>, clock_waits: BTreeMap, done: BTreeSet, + pending_releases: BTreeMap, ticks: u64, + tick_budget: Option, sampled_ready: BTreeSet, inactive: BTreeSet, scheduled_clock_drives: BitSet, @@ -2661,13 +3134,17 @@ impl Clone for SimulationSnapshot { periodic_events: self.periodic_events.clone(), last_clock_values: self.last_clock_values.clone(), pending_host_edges: self.pending_host_edges.clone(), + settled_process_edges: self.settled_process_edges.clone(), unknown_clock_values: self.unknown_clock_values.clone(), process_wakeups: self.process_wakeups.clone(), + budget_blocked_processes: self.budget_blocked_processes.clone(), waiting: self.waiting.clone(), tick_clocks: self.tick_clocks.clone(), clock_waits: self.clock_waits.clone(), done: self.done.clone(), + pending_releases: self.pending_releases.clone(), ticks: self.ticks, + tick_budget: self.tick_budget, sampled_ready: self.sampled_ready.clone(), inactive: self.inactive.clone(), scheduled_clock_drives: self.scheduled_clock_drives.clone(), diff --git a/crates/celox-state-layout/src/lib.rs b/crates/celox-state-layout/src/lib.rs index 753650835d6..6f5b3c657fd 100644 --- a/crates/celox-state-layout/src/lib.rs +++ b/crates/celox-state-layout/src/lib.rs @@ -185,7 +185,7 @@ pub trait LayoutSource { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(bound( - serialize = "A: Serialize + Eq + Hash", + serialize = "A: Serialize + Eq + Hash + Ord", deserialize = "A: Deserialize<'de> + Eq + Hash" ))] pub struct MemoryLayout { @@ -194,20 +194,27 @@ pub struct MemoryLayout { pub four_state: bool, pub mode: MemoryLayoutMode, /// Stable region offsets. Includes all declared state objects. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub offsets: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub widths: HashMap, /// Whether each state object has a four-state source type. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub is_4states: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub unpacked_arrays: HashMap, /// Stable region size in bytes. pub total_size: usize, /// Working region offsets. Includes only actually-used state objects. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub working_offsets: HashMap, pub working_base_offset: usize, /// Copy-on-write next-state data for dynamically addressed FF targets. + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub sparse_offsets: HashMap, pub sparse_base_offset: usize, + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub sparse_layouts: HashMap, pub sparse_active_bits_offset: usize, pub sparse_active_capacity: usize, diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index f927ebc56b1..45e62ad1481 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -1308,6 +1308,7 @@ fn process_runtime_events() { let _ = output.write_all(&message); let _ = output.write_all(b"\n"); } + RuntimeEvent::AssertPass { .. } => {} RuntimeEvent::AssertFatal { message } => { let mut output = std::io::stderr().lock(); let _ = output.write_all(b"fatal assertion failed: "); diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index 95eb29dc429..895b8ba4884 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -187,7 +187,8 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { for event in sim.drain_runtime_events() { match event { celox::RuntimeEvent::Display { message } - | celox::RuntimeEvent::AssertContinue { message } => { + | celox::RuntimeEvent::AssertContinue { message } + | celox::RuntimeEvent::AssertPass { message } => { stdout.write_all(&message).unwrap(); stdout.write_all(b"\n").unwrap(); } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 3c0e4dd22fe..ffaac337ca1 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -383,12 +383,15 @@ struct NativeRuntimeOptions { #[derive(Clone, Debug, Serialize, Deserialize)] pub(crate) struct NativeRuntimeSchema { + #[serde(serialize_with = "celox_design::serde_sorted::map")] pub(crate) runtime_errors: HashMap>, pub(crate) runtime_event_sites: Vec, /// Extern functions the code calls, resolved when the image is attached. pub(crate) extern_functions: Vec, pub(crate) comb_observers: Vec>, + #[serde(serialize_with = "celox_design::serde_sorted::set")] pub(crate) testbench_read_roots: HashSet, + #[serde(serialize_with = "celox_design::serde_sorted::set")] pub(crate) rtl_writes: HashSet>, /// Ordered so that the encoded image does not depend on hash order. pub(crate) comb_writes: std::collections::BTreeSet, @@ -398,6 +401,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) live_signals: std::collections::BTreeSet, pub(crate) processes: Vec>, #[serde(default)] + pub(crate) testbench_kernels: Option, pub(crate) process_event_counters: Vec>, pub(crate) active_ff_events: std::collections::BTreeSet, } @@ -413,14 +417,21 @@ pub struct NativeProgramImage { comb_unit_offsets: Vec, /// Entry offset of each process kernel. process_offsets: Vec, - /// Clock-control addresses and byte offsets used to compile each process kernel. - compiled_process_clocks: Vec<(AbsoluteAddr, usize)>, + /// Control addresses and byte offsets used to compile each process kernel. + compiled_process_controls: Vec>, compiled_process_clock_lists: Vec>>, compiled_clock_phase_sensitive_comb: bool, + compiled_process_releases: Vec>>, + compiled_testbench_kernels: Option, + compiled_process_event_counters: Vec<[(AbsoluteAddr, usize); 3]>, + compiled_process_host_requests: Vec>>, compiled_native_tick_loop: bool, required_native_features: u8, + #[serde(serialize_with = "celox_design::serde_sorted::map")] event_map: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] eval_only_event_map: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] apply_event_map: HashMap, id_to_addr: Vec, id_to_event: Vec, @@ -448,6 +459,15 @@ impl NativeProgramImage { if let Some(testbench) = &mut self.testbench { testbench.try_map_paths(&mut map)?; } + for site in &mut self.runtime_schema.runtime_event_sites { + if let Some(location) = &mut site.location + && !location.file.is_empty() + { + location.file = map(std::path::Path::new(&location.file))? + .to_string_lossy() + .into_owned(); + } + } Ok(()) } @@ -504,6 +524,7 @@ impl NativeProgramImage { dead_store_policy: self.runtime_schema.dead_store_policy, live_signals: self.runtime_schema.live_signals.iter().copied().collect(), processes: self.runtime_schema.processes.clone(), + testbench_kernels: self.runtime_schema.testbench_kernels, process_event_counters: self.runtime_schema.process_event_counters.clone(), active_ff_events: self .runtime_schema @@ -529,6 +550,16 @@ impl NativeProgramImage { if self.code.is_empty() { return Err("code image is empty".into()); } + if self.runtime_schema.testbench_kernels != self.compiled_testbench_kernels { + return Err("testbench kernel boundary differs from compiled image".into()); + } + if self + .runtime_schema + .testbench_kernels + .is_some_and(|start| start > self.runtime_schema.processes.len()) + { + return Err("testbench kernel boundary exceeds process count".into()); + } let mut entry_offsets = HashSet::default(); let mut previous_end = 0usize; for entry in &self.code_entries { @@ -570,21 +601,61 @@ impl NativeProgramImage { if self.process_offsets.len() != self.runtime_schema.processes.len() { return Err("process kernels and their control slots disagree".into()); } - if self.compiled_process_clocks.len() != self.runtime_schema.processes.len() + if self.compiled_process_controls.len() != self.runtime_schema.processes.len() || self - .compiled_process_clocks + .compiled_process_controls .iter() .zip(&self.runtime_schema.processes) - .any(|((address, offset), process)| { - process.clock != *address || self.layout.offsets.get(address) != Some(offset) + .any(|(bindings, process)| { + let addresses = [ + process.resume, + process.status, + process.delay, + process.clock, + process.release, + ] + .into_iter() + .chain(process.comb_clean) + .collect::>(); + bindings.len() != addresses.len() + || bindings + .iter() + .zip(addresses) + .any(|((address, offset), expected)| { + *address != expected + || self.layout.offsets.get(address) != Some(offset) + }) }) { - return Err( - "process clock control slots disagree with compiled kernel bindings".into(), - ); + return Err("process control slots disagree with compiled kernel bindings".into()); } let mut process_clock_periods = fxhash::FxHashMap::default(); for process in &self.runtime_schema.processes { + if let Some(flag) = process.comb_clean + && !self + .design + .state_objects + .get(&flag) + .is_some_and(|metadata| { + metadata.width == 1 && !metadata.is_4state && metadata.array_dims.is_empty() + }) + { + return Err( + "a process combinational-clean flag has an invalid state object".into(), + ); + } + if !self + .design + .state_objects + .get(&process.release) + .is_some_and(|metadata| { + metadata.width == celox_design::PROCESS_RELEASE_WIDTH + && !metadata.is_4state + && metadata.array_dims.is_empty() + }) + { + return Err("a process release control slot has an invalid state object".into()); + } if !self .design .state_objects @@ -597,6 +668,49 @@ impl NativeProgramImage { { return Err("a process clock control slot has an invalid state object".into()); } + for release in &process.releases { + if !self + .design + .state_objects + .get(&release.signal) + .is_some_and(|m| m.width == 1 && m.array_dims.is_empty()) + || release.value > 1 + || release + .clock + .is_some_and(|clock| !process.clocks.iter().any(|c| c.signal == clock)) + { + return Err("a process release has an invalid signal, value or clock".into()); + } + } + let valid_host_value = |value: &celox_design::HostValue<_>| { + (value.width > 0 || value.is_string) + && self + .design + .state_objects + .get(&value.signal) + .is_some_and(|m| m.width == value.width.max(1) && m.array_dims.is_empty()) + }; + for request in &process.host_requests { + use celox_design::HostRequest; + let valid = match request { + HostRequest::RandomSeed { value, .. } => valid_host_value(value), + HostRequest::RandomGet { result, .. } + | HostRequest::RandomGetSeed { result, .. } => valid_host_value(result), + HostRequest::RandomGetRange { + min, max, result, .. + } => [min, max, result].into_iter().all(valid_host_value), + HostRequest::Component { args, result, .. } => { + args.iter().all(valid_host_value) + && result.as_ref().is_none_or(valid_host_value) + } + HostRequest::FileOpen { path, .. } => valid_host_value(path), + HostRequest::FileWrite { args, .. } => args.iter().all(valid_host_value), + HostRequest::FileFlush { .. } | HostRequest::FileClose { .. } => true, + }; + if !valid { + return Err("a process host request has an invalid state value".into()); + } + } for clock in &process.clocks { if clock.period < 2 || !self.event_map.contains_key(&clock.signal) @@ -645,11 +759,87 @@ impl NativeProgramImage { { return Err("process clock lists disagree with compiled kernel indices".into()); } + if self.compiled_process_releases.len() != self.runtime_schema.processes.len() + || self + .compiled_process_releases + .iter() + .zip(&self.runtime_schema.processes) + .any(|(compiled, process)| { + let bound = process + .releases + .iter() + .cloned() + .map(|release| { + release.map(|address| { + ( + address, + self.layout + .offsets + .get(&address) + .copied() + .unwrap_or(usize::MAX), + ) + }) + }) + .collect::>(); + compiled != &bound + }) + { + return Err("process releases disagree with compiled release indices".into()); + } + if self.compiled_process_host_requests.len() != self.runtime_schema.processes.len() + || self + .compiled_process_host_requests + .iter() + .zip(&self.runtime_schema.processes) + .any(|(compiled, process)| { + let bound = process + .host_requests + .iter() + .cloned() + .map(|request| { + request.map(|address| { + ( + address, + self.layout + .offsets + .get(&address) + .copied() + .unwrap_or(usize::MAX), + ) + }) + }) + .collect::>(); + compiled != &bound + }) + { + return Err("process host requests disagree with compiled scratch bindings".into()); + } if self.compiled_clock_phase_sensitive_comb != self.runtime_schema.clock_phase_sensitive_comb { return Err("clock phase sensitivity disagrees with compiled kernels".into()); } + let counter_bindings = self + .runtime_schema + .process_event_counters + .iter() + .map(|counter| { + [counter.signal, counter.rises, counter.falls].map(|address| { + ( + address, + self.layout + .offsets + .get(&address) + .copied() + .unwrap_or(usize::MAX), + ) + }) + }) + .collect::>(); + if self.compiled_process_event_counters != counter_bindings { + return Err("process edge counters disagree with compiled bindings".into()); + } for counters in &self.runtime_schema.process_event_counters { if !self.event_map.contains_key(&counters.signal) { return Err("a process edge counter names an unknown event domain".into()); @@ -2372,12 +2562,24 @@ fn compile_program( comb_offset, comb_unit_offsets, process_offsets, - compiled_process_clocks: sir + compiled_process_controls: sir .runtime() .runtime_schema .processes .iter() - .map(|process| (process.clock, layout.offsets[&process.clock])) + .map(|process| { + [ + process.resume, + process.status, + process.delay, + process.clock, + process.release, + ] + .into_iter() + .chain(process.comb_clean) + .map(|address| (address, layout.offsets[&address])) + .collect() + }) .collect(), compiled_process_clock_lists: sir .runtime() @@ -2386,6 +2588,49 @@ fn compile_program( .iter() .map(|process| process.clocks.clone()) .collect(), + compiled_testbench_kernels: sir.runtime().runtime_schema.testbench_kernels, + compiled_process_event_counters: sir + .runtime() + .runtime_schema + .process_event_counters + .iter() + .map(|counter| { + [counter.signal, counter.rises, counter.falls].map(|address| { + ( + address, + layout.offsets.get(&address).copied().unwrap_or(usize::MAX), + ) + }) + }) + .collect(), + compiled_process_releases: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| { + process + .releases + .iter() + .cloned() + .map(|release| release.map(|address| (address, layout.offsets[&address]))) + .collect() + }) + .collect(), + compiled_process_host_requests: sir + .runtime() + .runtime_schema + .processes + .iter() + .map(|process| { + process + .host_requests + .iter() + .cloned() + .map(|request| request.map(|address| (address, layout.offsets[&address]))) + .collect() + }) + .collect(), compiled_native_tick_loop: options.x86_options.native_tick_loop, compiled_clock_phase_sensitive_comb: sir .runtime() @@ -2424,6 +2669,7 @@ fn compile_program( .copied() .collect(), processes: sir.runtime().runtime_schema.processes.clone(), + testbench_kernels: sir.runtime().runtime_schema.testbench_kernels, process_event_counters: sir.runtime().runtime_schema.process_event_counters.clone(), active_ff_events: sir .runtime() @@ -3508,6 +3754,188 @@ mod process_metadata_tests { .into_program_image() } + #[test] + fn testbench_boundary_must_match_compiled_boundary() { + let original = image(); + original.to_container_bytes().unwrap(); + for start in [ + 0, + original.runtime_schema.processes.len(), + original.runtime_schema.processes.len() + 1, + ] { + let mut changed = original.clone(); + changed.runtime_schema.testbench_kernels = Some(start); + assert!(matches!( + changed.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + let source = + "#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{clk.next(2);$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + for boundary in [None, Some(original.runtime_schema.processes.len())] { + let mut changed = original.clone(); + changed.runtime_schema.testbench_kernels = boundary; + assert!(matches!( + changed.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + } + + #[test] + fn process_release_and_host_values_are_checked_before_attachment() { + let original = image(); + for kind in 0..5 { + let mut broken = original.clone(); + let slots = &mut broken.runtime_schema.processes[0]; + let unknown = if kind == 4 { + celox_design::StateAddr { + var_id: celox_design::StateObjectId::from_raw(u32::MAX), + ..slots.delay + } + } else { + slots.delay + }; + match kind { + 0 => slots.releases.push(celox_design::ProcessRelease { + signal: slots.delay, + value: 0, + clock: None, + }), + 1 => slots.releases.push(celox_design::ProcessRelease { + signal: slots.clocks[0].signal, + value: 0, + clock: Some(slots.delay), + }), + _ => slots + .host_requests + .push(celox_design::HostRequest::RandomGet { + handle: "test".into(), + result: celox_design::HostValue { + signal: unknown, + width: if kind == 2 { 0 } else { 1 }, + signed: false, + is_string: false, + }, + }), + } + assert!(broken.validate().is_err(), "corruption {kind} accepted"); + assert!(matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + )); + } + } + + #[test] + fn emitted_edge_counter_bindings_match_compiled_storage() { + let source = "module Counter(clk:input clock,q:output u32){always_ff(clk){q+=1;}}#[test(Top)]module Top{var go:clock;var q:u32;inst dut:Counter(clk:go,q);initial{go=1;go=0;$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + assert!(!original.runtime_schema.process_event_counters.is_empty()); + let mut broken = original.clone(); + let counter = &mut broken.runtime_schema.process_event_counters[0]; + std::mem::swap(&mut counter.rises, &mut counter.falls); + assert!(broken.to_container_bytes().is_err()); + } + + #[test] + fn ordered_release_bindings_match_compiled_indices() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen;inst a:$tb::reset_gen(clk);inst b:$tb::reset_gen(clk);initial{a.assert(1);b.assert(1);$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + let mut broken = original.clone(); + assert_eq!(broken.runtime_schema.processes[0].releases.len(), 2); + broken.runtime_schema.processes[0].releases.swap(0, 1); + assert!(broken.to_container_bytes().is_err()); + } + #[test] + fn host_request_values_bind_to_compiled_scratch() { + let source = "#[test(Top)]module Top{var random:$tb::random::;var value:u32;initial{value=random.get_range(1,2);$finish();}}"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + let mut broken = original.clone(); + let request = broken.runtime_schema.processes[0] + .host_requests + .iter_mut() + .find(|request| matches!(request, celox_design::HostRequest::RandomGetRange { .. })) + .unwrap(); + if let celox_design::HostRequest::RandomGetRange { min, max, .. } = request { + assert_ne!(min.signal, max.signal); + min.signal = max.signal; + } + assert!(broken.to_container_bytes().is_err()); + } + #[test] + fn clean_control_cannot_redirect_to_another_valid_bit() { + let source = "#[test(Top)] module Top (spare: output logic) { var source: u32; let derived: u32=source+1; initial {source=1;$assert(derived==2);source=7;} initial {spare=1;$assert(spare==1);spare=0;} }"; + let original = crate::Simulator::builder(source, "Top") + .testbench_kernels(true) + .compile_native() + .unwrap() + .into_program_image(); + original.to_container_bytes().unwrap(); + let flag = original.runtime_schema.processes[0].comb_clean.unwrap(); + let mut broken = original.clone(); + let address = original.runtime_schema.processes[1].comb_clean.unwrap(); + assert_ne!(flag, address); + broken.runtime_schema.processes[0].comb_clean = Some(address); + assert!(broken.to_container_bytes().is_err()); + } + #[test] + fn process_release_control_bindings_cannot_be_swapped() { + let original = image(); + original.to_container_bytes().unwrap(); + for control in 0..5 { + let mut broken = original.clone(); + let slots = &mut broken.runtime_schema.processes; + let get = |p: &celox_design::ProcessSlots| match control { + 0 => p.resume, + 1 => p.status, + 2 => p.delay, + 3 => p.clock, + _ => p.release, + }; + let a = get(&slots[0]); + let b = get(&slots[1]); + assert_ne!(a, b); + for (p, value) in [(0, b), (1, a)] { + match control { + 0 => slots[p].resume = value, + 1 => slots[p].status = value, + 2 => slots[p].delay = value, + 3 => slots[p].clock = value, + _ => slots[p].release = value, + } + } + assert!( + matches!( + broken.to_container_bytes(), + Err(NativeImageContainerError::InvalidImage(_)) + ), + "control {control}" + ); + } + } + #[test] fn process_clock_lists_match_the_compiled_indices() { let original = image(); @@ -3574,13 +4002,14 @@ mod process_metadata_tests { fn process_clock_metadata_is_checked_before_image_attachment() { let original = image(); original.to_container_bytes().unwrap(); - for corruption in 0..5 { + for corruption in 0..6 { let mut broken = original.clone(); let slots = &mut broken.runtime_schema.processes[0]; match corruption { 0 => slots.clocks[0].signal = slots.delay, 1 => slots.clocks[0].period = 1, 2 => slots.clock = slots.status, + 5 => slots.comb_clean = Some(slots.delay), 4 => { let signal = slots.clocks[0].signal; broken diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 5ac0b03728e..bdbe2c0f5b1 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,8 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 22; +// Version 32 records the out-of-band runtime finish latch. +const CONTAINER_VERSION: u16 = 32; 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/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 10ce330f3aa..f68af4fd75a 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -453,6 +453,7 @@ impl NativeProgramInstance { )), RuntimeEvent::Display { .. } | RuntimeEvent::Write { .. } + | RuntimeEvent::AssertPass { .. } | RuntimeEvent::AssertContinue { .. } | RuntimeEvent::Finish => None, }) { diff --git a/crates/celox/src/component.rs b/crates/celox/src/component.rs index 7958e262b6b..8419d96dc8a 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -753,6 +753,20 @@ impl ComponentRuntime { result } + /// The events bound as resets of components. + pub(crate) fn reset_event_ids(&self) -> Vec { + let mut ids: Vec = self + .components + .iter() + .flat_map(|component| &component.events) + .filter(|event| event.reset) + .map(|event| event.event_id) + .collect(); + ids.sort_unstable(); + ids.dedup(); + ids + } + pub(crate) fn begin_reset_cycles(&mut self, reset_event_id: Option) { if let Some(id) = reset_event_id { self.active_reset_events.push((None, id)); @@ -885,8 +899,18 @@ pub(crate) fn host_value_from_argument( width: usize, is_string: bool, ) -> HostValue { - let value = value.to_biguint(); + host_value_from_bits(value.to_biguint(), width, is_string) +} + +pub(crate) fn host_value_from_bits( + value: num_bigint::BigUint, + width: usize, + is_string: bool, +) -> HostValue { if is_string { + if width == 0 { + return HostValue::Str(String::new()); + } let byte_len = width.div_ceil(8); let mut bytes = value.to_bytes_be(); if bytes.len() < byte_len { diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index c7329d1d065..3ce64becf31 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -87,8 +87,11 @@ impl RuntimeInstance { #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct RuntimeDesign { semantic: celox_design::ElaboratedDesign, + #[serde(serialize_with = "celox_design::serde_sorted::map")] instances: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] instance_ids: HashMap, + #[serde(serialize_with = "celox_design::serde_sorted::map")] variables: HashMap, package_instances: crate::HashSet, } @@ -807,6 +810,15 @@ fn collect_comb_writes(program: &mut OptimizedSir) { fn rebuild_rtl_writes(program: &mut OptimizedSir) { let mut rtl_writes = crate::HashSet::default(); + // The kernels of a Veryl testbench drive signals as the testbench, not + // as RTL; the processes of an SV design are RTL. + let design_processes = program + .runtime + .runtime_schema + .testbench_kernels + .unwrap_or(program.sir.processes.len()) + .min(program.sir.processes.len()); + let processes = &program.sir.processes[..design_processes]; for unit in program .sir .eval_comb @@ -822,7 +834,7 @@ fn rebuild_rtl_writes(program: &mut OptimizedSir) { .iter() .flat_map(|parallel| parallel.units().map(|unit| &unit.unit)), ) - .chain(&program.sir.processes) + .chain(processes) { for block in unit.blocks.values() { for instruction in &block.instructions { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 2301ca89e47..2e1d957d0e2 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -69,10 +69,6 @@ impl std::fmt::Debug for Simulation { } impl SimulationExecutor for Simulator { - fn finish_requested(&mut self, _time: u64) -> bool { - self.has_pending_runtime_finish() - } - type Backend = B; fn backend(&self) -> &B { @@ -110,10 +106,47 @@ impl SimulationExecutor for Simulator { self.apply_ff_at_checked(event) } - fn run_process(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { - self.backend + fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { + let result = self + .backend .run_process(index) - .map_err(|e| self.decorate_runtime_error(e)) + .map_err(|e| self.decorate_runtime_error(e)); + // A kernel testbench's kernels yield before the runtime event ring + // could wrap; the events so far leave the ring here. + if self.testbench_random.is_some() { + let ctx = crate::simulator::RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }; + let events = self.collect_sited_runtime_events(ctx); + self.testbench_events.extend(events); + } + result + } + + fn process_is_clean(&self, index: usize) -> bool { + self.program.runtime_schema.processes[index] + .comb_clean + .is_some_and(|flag| { + self.backend + .get_as::(self.backend.resolve_signal(&flag)) + != 0 + }) + } + + fn finish_requested(&mut self, time: u64) -> bool { + if self.testbench_random.is_some() { + let ctx = crate::simulator::RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }; + let events = self.collect_sited_runtime_events(ctx); + self.testbench_events.extend(events); + } + self.testbench_events + .iter() + .any(|(_, event)| matches!(event, crate::RuntimeEvent::Finish)) + || self.has_pending_runtime_finish() } fn tick_many(&mut self, event: B::Event, count: u64) -> (u64, Result<(), RuntimeErrorCode>) { @@ -142,15 +175,48 @@ impl SimulationExecutor for Simulator { self.vcd_writer.is_none() && !self.components.has_scheduled_components() && self.program.runtime_schema.comb_observers.is_empty() + // Design events must return to the scheduler to drain the ring. + && self.program.runtime_schema.runtime_event_sites.iter().all(|site|site.location.is_some()) && !self .program .runtime_schema .runtime_event_sites .iter() .any(|site| matches!(site.kind, celox_design::RuntimeEventKind::Finish)) + && !self.program.runtime_schema.clock_phase_sensitive_comb } + fn host_request_changes_design(&self, process: usize, request: usize) -> bool { + self.program + .runtime_schema + .processes + .get(process) + .and_then(|process| process.host_requests.get(request)) + .is_none_or(|request| { + matches!(request, celox_design::HostRequest::Component { .. }) && self.dirty + }) + } + + fn host_request( + &mut self, + process: usize, + request: usize, + time: u64, + ) -> Result { + // Keep output observable before the following host-side effect, while + // retaining assertion/finish events for the runner's normal drain. + if self.testbench_random.is_some() { + crate::testbench::kernels::forward_pending_output(self); + } + crate::testbench::kernels::serve_host_request(self, process, request, time).map_err( + |message| RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + }, + ) + } + fn stage_external_event( &mut self, event: B::Event, @@ -165,13 +231,54 @@ impl SimulationExecutor for Simulator { event: B::Event, timestamp: u64, ) -> Result<(), RuntimeErrorCode> { - let writes = self - .components - .fire(event.id(), timestamp) - .map_err(|message| RuntimeErrorCode::Runtime { - message, - signals: Vec::new(), - })?; + // A testbench holds its resets through releases; while one is + // asserted, its components take reset cycles. + if !self.program.runtime_schema.processes.is_empty() { + for reset_event in self.components.reset_event_ids() { + let address = self.backend.id_to_addr_slice()[reset_event]; + let releases = self + .program + .runtime_schema + .processes + .iter() + .flat_map(|slots| &slots.releases) + .filter(|release| release.signal == address); + // Prefer the firing domain; a single-domain component can + // also inherit a held reset on its derived clock. + let release = releases + .clone() + .find(|release| { + release.clock.is_some_and(|clock| { + self.backend + .resolve_event_opt(&clock) + .is_some_and(|clock| clock.id() == event.id()) + }) + }) + .or_else(|| releases.into_iter().next()); + let Some(release) = release else { + continue; + }; + let signal = self.backend.resolve_signal(&address); + if self.backend.get(signal) == release.value.into() { + continue; + } + match release + .clock + .and_then(|clock| self.backend.resolve_event_opt(&clock)) + { + Some(clock) => self + .components + .begin_reset_clock_cycles(clock.id(), Some(reset_event)), + None => self.components.begin_reset_cycles(Some(reset_event)), + } + } + } + let fired = self.components.fire(event.id(), timestamp); + self.components.end_reset_cycles(); + let writes = fired.map_err(|message| RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + })?; for write in writes { write.apply(&mut self.backend); self.dirty = true; @@ -188,6 +295,9 @@ impl SimulationExecutor for Simulator { // ── Backend-specific constructors ─────────────────────────────────── impl Simulation { + /// Build a scheduler for design processes. Veryl `#[test]` kernels run + /// through [`crate::testbench::run_compiled_testbench`], which initializes + /// their random, file and component services. pub fn builder<'a>(code: &'a str, top: &'a str) -> crate::SimulatorBuilder<'a, Simulation> { crate::SimulatorBuilder::::new(code, top) } @@ -222,7 +332,15 @@ impl Simulation { // ── Generic methods available for any backend ─────────────────────── +/// Scheduler state used by a testbench runner, including its kernels. pub(crate) fn simulation_state(simulator: &Simulator) -> SimulationState { + simulation_state_with_process_count(simulator, simulator.program.runtime_schema.processes.len()) +} + +fn simulation_state_with_process_count( + simulator: &Simulator, + process_count: usize, +) -> SimulationState { let num_events = simulator.backend.num_events(); let topo_signals: Vec<(SignalRef, usize, usize)> = simulator .program @@ -297,10 +415,21 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul .runtime_schema .processes .iter() + .take(process_count) .map(|slots| ProcessRefs { status: simulator.backend.resolve_signal(&slots.status), delay: simulator.backend.resolve_signal(&slots.delay), clock: simulator.backend.resolve_signal(&slots.clock), + release: simulator.backend.resolve_signal(&slots.release), + releases: slots + .releases + .iter() + .map(|release| celox_runtime::ProcessReleaseRef { + signal: simulator.backend.resolve_signal(&release.signal), + event: simulator.backend.resolve_event_opt(&release.signal), + value: release.value, + }) + .collect(), clocks: slots .clocks .iter() @@ -351,7 +480,12 @@ pub(crate) fn simulation_state(simulator: &Simulator) -> Simul impl Simulation { pub(crate) fn new(simulator: Simulator) -> Self { - let state = simulation_state(&simulator); + let process_count = simulator + .program + .runtime_schema + .testbench_kernels + .unwrap_or(simulator.program.runtime_schema.processes.len()); + let state = simulation_state_with_process_count(&simulator, process_count); Self { simulator, state, @@ -497,7 +631,7 @@ impl Simulation { self.state.finish(); } else if was_dirty && !self.simulator.dirty && !self.state.is_finished() { self.state - .sample_waiting_events(&mut self.simulator) + .sample_waiting_events(&mut self.simulator, self.state.time()) .unwrap(); self.state.capture_host_edges(&self.simulator.backend); } @@ -818,7 +952,12 @@ impl Simulation { } fn has_processes(&self) -> bool { - !self.simulator.program.runtime_schema.processes.is_empty() + self.simulator + .program + .runtime_schema + .testbench_kernels + .unwrap_or(self.simulator.program.runtime_schema.processes.len()) + != 0 } /// Whether a process of the design requested the end of the simulation. @@ -833,8 +972,8 @@ impl Simulation { self.state.time() } - /// Rising edges of the clocks processes wait on that the simulation has - /// run so far. + /// Completed process-clock rounds. Coincident rising edges count as + /// one tick against the shared testbench budget. pub fn ticks(&self) -> u64 { self.state.ticks() } @@ -879,7 +1018,8 @@ impl Simulation { if self.simulator.has_pending_runtime_finish() { self.state.finish(); } - self.state.sample_waiting_events(&mut self.simulator)?; + self.state + .sample_waiting_events(&mut self.simulator, self.state.time())?; self.state.capture_host_edges(&self.simulator.backend); self.pending_host_work = false; Ok(()) @@ -2767,6 +2907,35 @@ mod rtl_finish_backend_tests { } } +#[cfg(test)] +mod tick_budget_snapshot_tests { + use super::*; + #[test] + fn restoring_a_checkpoint_restores_the_remaining_tick_budget() { + let code = + "#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{clk.next(3);$finish();}}"; + let simulator = Simulator::builder(code, "Top").build_interpreter().unwrap(); + // This budget belongs to a testbench run, whose scheduler includes + // its kernels. Ordinary Simulation constructors leave them inactive. + let state = simulation_state(&simulator); + let mut sim = Simulation { + simulator, + state, + pending_host_work: false, + }; + sim.state.set_tick_budget(Some(1)); + let saved = sim.checkpoint().unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.ticks(), 1); + assert!(sim.state.tick_budget_spent()); + sim.restore(&saved).unwrap(); + assert!(!sim.state.tick_budget_spent()); + sim.run_until(0).unwrap(); + assert_eq!(sim.ticks(), 1); + assert!(sim.state.tick_budget_spent()); + } +} + #[cfg(test)] mod finish_clock_batch_tests { use super::*; @@ -3108,8 +3277,8 @@ mod pending_generated_clock_tests { sim.step().unwrap(); assert_eq!(sim.get(sim.signal("qa")), 1u8.into()); assert_eq!(sim.get(sim.signal("qb")), 0u8.into()); - // B rose once at time zero; both A and B rise at time four. - assert_eq!(sim.ticks(), 3); + // Coincident rising edges count as one completed clock round. + assert_eq!(sim.ticks(), 2); } #[test] fn pending_rises_share_pre_edge_state_with_new_clocks() { @@ -3269,6 +3438,77 @@ mod scheduled_pulse_tests { } } +#[cfg(test)] +mod budget_resume_review_tests { + use super::*; + use crate::frontend_sdk::{Constant, Edge, ModuleBuilder, Statement, ValueType}; + fn design() -> crate::frontend_sdk::FrontendArtifact { + let mut m = ModuleBuilder::new("Top").unwrap(); + let bit = ValueType::bits(1).unwrap(); + let clk = m.internal("clk", bit).unwrap(); + let q = m.output("q", bit).unwrap(); + let done = m.output("done", bit).unwrap(); + let delayed = m.output("delayed", bit).unwrap(); + for signal in [q, done, delayed] { + m.set_initial(signal, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + } + let one = m.constant(Constant::two_state(1u8, 1).unwrap()); + let q_target = m.whole(q).unwrap(); + m.register(q_target, one, clk, Edge::Posedge, None, None) + .unwrap(); + m.clock_period(clk, 4).unwrap(); + let count = m.constant(Constant::two_state(1u8, 64).unwrap()); + let delay = m.constant(Constant::two_state(4u8, 64).unwrap()); + let done_target = m.whole(done).unwrap(); + let delayed_target = m.whole(delayed).unwrap(); + m.process(vec![ + Statement::ClockCycles { clock: clk, count }, + Statement::Assign { + target: done_target, + value: one, + }, + ]) + .unwrap(); + m.process(vec![ + Statement::Delay { amount: delay }, + Statement::Assign { + target: delayed_target, + value: one, + }, + ]) + .unwrap(); + m.finish() + } + fn check(mut sim: Simulation) { + sim.state.set_tick_budget(Some(1)); + sim.run_until(4).unwrap(); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("done")), 0u8.into()); + assert_eq!(sim.get(sim.signal("delayed")), 0u8.into()); + assert!(!sim.is_finished()); + let blocked = sim.checkpoint().unwrap(); + for budget in [Some(1), None] { + sim.restore(&blocked).unwrap(); + sim.state.set_tick_budget(budget); + sim.run_until(4).unwrap(); + assert!(sim.state.all_processes_done()); + assert_eq!(sim.get(sim.signal("delayed")), 1u8.into()); + assert_eq!(sim.ticks(), 1); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + } + } + #[test] + fn exhausted_budgets_preserve_clock_resumptions_and_unrelated_delays() { + let build = || Simulator::from_frontend(design()); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + #[cfg(test)] mod host_clock_review_tests { use super::*; @@ -4374,6 +4614,62 @@ mod host_finish_edge_review_tests { } } +#[cfg(test)] +mod ordinary_simulation_testbench_scope_tests { + use super::*; + #[cfg(feature = "systemverilog")] + #[test] + fn ordinary_simulation_keeps_design_processes_active() { + let veryl = r#"#[test(Top)]module Top{var q:logic;var r:$tb::random::;var marker:u8;inst dut:$sv::Worker(q);initial{marker=r.get_range(5,5);$finish();}}"#; + let sv = "module Worker(output bit q);initial begin #1;q=1;end endmodule"; + fn check(mut sim: Simulation) { + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.get(sim.signal("marker")), 0u8.into()); + assert!(!sim.is_finished()); + } + let build = || { + Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("top.veryl"))], + vec![(sv, std::path::Path::new("worker.sv"))], + "Top", + ) + }; + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } + + #[test] + fn ordinary_simulation_does_not_start_testbench_host_requests() { + let code = r#"#[test(Top)]module Top{var r:$tb::random::;var marker:u8;initial{r.seed(7);marker=r.get_range(5,5);$assert(marker==5);$finish();}}"#; + fn check(mut sim: Simulation) { + assert_eq!(sim.step().unwrap(), None); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(sim.signal("marker")), 0u8.into()); + assert!(!sim.is_finished()); + let tb = crate::testbench::compile_initial_testbench(&sim.simulator).unwrap(); + assert_eq!( + crate::testbench::run_compiled_testbench(&mut sim.simulator, &tb), + crate::TestResult::Pass + ); + assert_eq!( + sim.simulator.get(sim.simulator.signal("marker")), + 5u8.into() + ); + } + check(Simulation::builder(code, "Top").build().unwrap()); + let build = || Simulator::builder(code, "Top").testbench_kernels(true); + check(Simulation::new(build().build_interpreter().unwrap())); + check(Simulation::new(build().build_cranelift().unwrap())); + check(Simulation::new(build().build_wasm().unwrap())); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulation::new(build().build_native().unwrap())); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod cross_mode_clock_baseline_review_tests { use super::*; @@ -6633,6 +6929,113 @@ mod sampled_host_review { } } +#[cfg(test)] +mod zero_release_review { + use super::*; + + // Veryl reset.assert(0) deliberately holds for one cycle. Exercise the + // lower-level kernel contract by reporting a zero-count release from + // an actual compiled kernel, then delegate the rest to the real backend. + struct ZeroRelease<'a, B: SimBackend> { + sim: &'a mut Simulator, + controls: Vec<(SignalRef, SignalRef, SignalRef)>, + } + impl SimulationExecutor for ZeroRelease<'_, B> { + type Backend = B; + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_comb(self.sim) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_apply_ff_at(self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(self.sim, event) + } + fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::run_process(self.sim, index, time)?; + let (status, delay, release) = self.controls[index]; + if self.sim.backend.get_as::(status) + == celox_design::ProcessStatus::WaitClock.code() + && self.sim.backend.get_as::(release) != 0 + { + self.sim.backend.set(delay, 0u64); + } + Ok(()) + } + } + + #[test] + fn zero_count_releases_capture_edges_before_the_continuation_restores_them() { + fn check(mut sim: Simulator) { + let rst = sim.signal("rst"); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + sim.eval_comb().unwrap(); + let mut state = simulation_state(&sim); + let controls = sim + .program + .runtime_schema + .processes + .iter() + .map(|slots| { + ( + sim.backend.resolve_signal(&slots.status), + sim.backend.resolve_signal(&slots.delay), + sim.backend.resolve_signal(&slots.release), + ) + }) + .collect(); + let mut executor = ZeroRelease { + sim: &mut sim, + controls, + }; + while state.next_event_time().is_some_and(|time| time <= 10) { + state.step(&mut executor).unwrap(); + } + let count = sim.signal("count"); + assert_eq!(sim.get(count), 1u8.into()); + assert_eq!(sim.get(rst), 0u8.into()); + } + let code = r#" + module Counter(clk: input clock, count: output logic<8>) { + always_ff(clk) { count += 1; } + } + #[test(Top)] module Top { + inst clk: $tb::clock_gen #(period: 10); + inst rst: $tb::reset_gen(clk); + var gate: logic; + let released: '_ clock = ~rst & gate; + var count: logic<8>; + inst dut: Counter(clk: released, count); + initial { gate = 1; rst.assert(1); gate = 0; clk.next(1); } + }"#; + macro_rules! build { + ($method:ident) => { + check( + Simulator::builder(code, "Top") + .testbench_kernels(true) + .reset_type(crate::ResetType::AsyncHigh) + .$method() + .unwrap(), + ); + }; + } + build!(build_interpreter); + build!(build_cranelift); + build!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + build!(build_native); + } +} + #[cfg(all(test, feature = "systemverilog"))] mod host_finish_step_review { use super::*; @@ -7014,7 +7417,7 @@ mod clean_waiter_settle_review { kernel .builder() .emit(SIRInstruction::Imm(count, SIRValue::new(4u8))); - kernel.wait_clock(0, count).unwrap(); + kernel.wait_clock(0, count, None).unwrap(); let one = kernel.builder().alloc_bit(1, false); kernel .builder() @@ -7064,7 +7467,7 @@ mod clean_waiter_settle_review { fn apply_ff_at(&mut self, e: B::Event) -> Result<(), RuntimeErrorCode> { SimulationExecutor::apply_ff_at(&mut self.sim, e) } - fn run_process(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { + fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { let slots = &self.sim.program.runtime_schema.processes[index]; let mode = self .sim @@ -7082,7 +7485,7 @@ mod clean_waiter_settle_review { }); } } - SimulationExecutor::run_process(&mut self.sim, index) + SimulationExecutor::run_process(&mut self.sim, index, time) } } #[test] diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index a0fc53e39e0..9ff67a72f24 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -106,6 +106,13 @@ mod host { pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, pub(crate) component_simulation: Option>, + /// The random number generators of a running kernel testbench. + pub(crate) testbench_random: Option, + pub(crate) testbench_files: Option, + /// Runtime events of a running kernel testbench the executor took + /// out of the ring when a kernel yielded, until the runner drains + /// them. + pub(crate) testbench_events: Vec<(Option, RuntimeEvent)>, runtime_event_read_seq: Arc, runtime_finish_state: Arc>, runtime_event_drain_active: Arc, @@ -148,6 +155,10 @@ mod host { }, /// The design executed `$finish`. The host decides whether to stop. Finish, + /// An assertion of a testbench process held. + AssertPass { + message: Vec, + }, Missed { count: u64, }, @@ -351,6 +362,45 @@ mod host { } } + pub(crate) fn render_host_message( + sim: &Simulator, + template: Option, + args: &[celox_design::HostValue], + time: u64, + ) -> Vec { + let values = args + .iter() + .map(|arg| { + let signal = sim.backend.resolve_signal(&arg.signal); + let (value, mask) = sim.backend.get_four_state(signal); + RuntimeEventArgValue { + values: value.to_u64_digits(), + masks: mask.to_u64_digits(), + width: arg.width, + signed: arg.signed, + is_string: arg.is_string, + } + }) + .collect::>(); + render_runtime_event_message( + &RuntimeEventSite { + kind: RuntimeEventKind::Write, + template, + sizing: DisplaySizing::Veryl, + scope: None, + arg_widths: Vec::new(), + arg_signed: Vec::new(), + arg_is_string: Vec::new(), + location: None, + }, + &values, + RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }, + ) + } + fn render_runtime_event_message( site: &RuntimeEventSite, args: &[RuntimeEventArgValue], @@ -373,6 +423,12 @@ mod host { } 'x' } + RuntimeEventKind::AssertPass => { + if args.is_empty() { + return b"assertion passed".to_vec(); + } + 'x' + } }; return args .iter() @@ -465,6 +521,7 @@ mod host { RuntimeEventKind::AssertContinue => RuntimeEvent::AssertContinue { message }, RuntimeEventKind::AssertFatal => RuntimeEvent::AssertFatal { message }, RuntimeEventKind::Finish => RuntimeEvent::Finish, + RuntimeEventKind::AssertPass => RuntimeEvent::AssertPass { message }, }) } } @@ -697,6 +754,9 @@ mod host { warnings, components: Default::default(), component_simulation: None, + testbench_random: None, + testbench_files: None, + testbench_events: Vec::new(), runtime_event_read_seq: Arc::new(AtomicU64::new(0)), runtime_finish_state: Arc::new(Mutex::new(RuntimeFinishState::default())), runtime_event_drain_active: Arc::new(AtomicBool::new(false)), @@ -884,6 +944,38 @@ mod host { self.collect_formatted_runtime_events(ctx) } + /// Collect already-published events with their sites. Scheduler callers + /// settle explicitly; collecting after an execution error must not retry + /// the failed combinational evaluation. + pub(crate) fn collect_sited_runtime_events( + &mut self, + ctx: RuntimeFormatContext<'_>, + ) -> Vec<(Option, RuntimeEvent)> { + assert!( + !self.runtime_event_drain_active.load(Ordering::Acquire), + "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active", + ); + if self.runtime_event_read_seq.load(Ordering::Acquire) == self.runtime_event_write_seq() + { + return Vec::new(); + } + self.collect_backend_runtime_events() + .into_iter() + .filter_map(|raw| { + let site = match &raw { + RawRuntimeEvent::Event { site_id, .. } => Some(*site_id), + RawRuntimeEvent::Missed { .. } => None, + }; + let event = render_raw_runtime_event( + raw, + &self.program.runtime_schema.runtime_event_sites, + ctx, + )?; + Some((site, event)) + }) + .collect() + } + fn eval_comb_for_runtime_event_drain(&mut self) -> Result<(), RuntimeErrorCode> { let (result, _) = self.eval_comb_capturing_events(); self.check_comb_backend_result(result)?; @@ -1004,7 +1096,7 @@ mod host { finish.requested } - pub(super) fn reset_runtime_finish(&self, finished: bool) { + pub(crate) fn reset_runtime_finish(&self, finished: bool) { let mut finish = self.runtime_finish_state.lock().unwrap(); let offset = celox_state_layout::RUNTIME_EVENT_FINISH_OFFSET; if let Some(buffer) = self.backend.runtime_event_buffer() { diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 4220cd538cd..100e0cff9d4 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -281,6 +281,7 @@ fn analyze( preserve_element_storage_layout: bool, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> ( Result, Vec, @@ -397,11 +398,20 @@ fn analyze( let loop_sources = parser::loop_provenance::LoopSourceTable::collect(parsers.iter().map(|x| &x.veryl)); - // Global post-pass1 + let has_testbench = symbol_table::get_all() + .iter() + .any(|symbol| matches!(&symbol.kind, SymbolKind::Module(module) if module.test.is_some())); + let runtime_functions = if testbench_kernels && has_testbench { + celox_frontend_veryl::preserve_terminating_function_calls(parsers.iter().map(|x| &x.veryl)) + } else { + Default::default() + }; + // Resolve constant-function dependencies only after runtime termination + // has been classified, so transitive callers retain those effects too. errors.append(&mut Analyzer::analyze_post_pass1()); - // Shared context for pass2 let mut context = Context::default(); + context.disalbe_const_opt = testbench_kernels && has_testbench; let mut ir = Ir::default(); @@ -418,6 +428,7 @@ fn analyze( } errors.append(&mut context.drain_errors()); errors.append(&mut Analyzer::analyze_post_pass2(&ir)); + errors.retain(|error| !runtime_functions.is_runtime_case_condition(error)); // Veryl reports combinational loops before Celox can apply its path-level // false-loop and true-loop authorizations. When the caller supplied such @@ -472,6 +483,7 @@ fn analyze( build_config.reset_type = rt; } build_config.parallel_lanes = optimize_options.parallel_lanes(); + build_config.testbench_kernels = testbench_kernels; let sir = if let Some(external) = external_frontend { parser::parse_with_external_hierarchy( &top, @@ -644,6 +656,7 @@ pub fn compile_to_sir( crate::backend::memory_layout::MemoryLayoutMode::Packed, true, false, + false, ) } @@ -758,6 +771,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { // The testbench drives time itself and never resumes process kernels. if !artifact.processes().is_empty() { @@ -789,6 +803,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ); let (real_errors, analyzer_warnings): (Vec<_>, Vec<_>) = errors.into_iter().partition(AnalyzerError::is_error); @@ -846,6 +861,7 @@ fn compile_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { let (sir, errors, frontend_diagnostics) = analyze( sources, @@ -867,6 +883,7 @@ fn compile_to_sir_with_layout_mode( layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ); let (real_errors, analyzer_warnings): (Vec<_>, Vec<_>) = errors.into_iter().partition(AnalyzerError::is_error); @@ -1040,6 +1057,7 @@ pub fn compile_mixed_to_sir( crate::backend::memory_layout::MemoryLayoutMode::Packed, true, false, + false, ) } @@ -1071,6 +1089,7 @@ fn compile_mixed_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { let (sir, errors, frontend_diagnostics) = analyze( sources, @@ -1092,6 +1111,7 @@ fn compile_mixed_to_sir_with_layout_mode( layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ); let (real_errors, analyzer_warnings): (Vec<_>, Vec<_>) = errors.into_iter().partition(AnalyzerError::is_error); @@ -1152,6 +1172,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, allow_always_ff_function_effects: bool, + testbench_kernels: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { #[cfg(not(feature = "systemverilog"))] { @@ -1174,6 +1195,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ) } #[cfg(feature = "systemverilog")] @@ -1196,6 +1218,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ), (true, false) => compile_sv_to_sir_with_layout_mode( sv_sources, @@ -1232,6 +1255,7 @@ fn compile_hdl_to_sir_with_layout_mode( layout_mode, recover_comb_loops, allow_always_ff_function_effects, + testbench_kernels, ), } } @@ -1294,6 +1318,10 @@ mod host { pub allow_always_ff_function_effects: bool, /// Where the C functions of DPI-C imports are found. pub dpi: crate::DpiSymbols, + /// Compile the `initial` blocks of a `#[test]` module into process + /// kernels run by the timed scheduler instead of the testbench + /// bytecode interpreter. + pub testbench_kernels: bool, } /// A code-generated native program that has not been loaded into @@ -1478,6 +1506,7 @@ mod host { tier_promotion: TierPromotion::Always, allow_always_ff_function_effects: false, dpi: crate::DpiSymbols::default(), + testbench_kernels: true, } } } @@ -1617,6 +1646,13 @@ mod host { self } + /// Run the `initial` blocks of a `#[test]` module as process kernels + /// of the timed scheduler instead of the bytecode interpreter. + pub fn testbench_kernels(mut self, enable: bool) -> Self { + self.options.testbench_kernels = enable; + self + } + /// Enable native-image support for foreign force/release operations. /// /// This emits extra combinational entry points, so ordinary simulator @@ -2201,6 +2237,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, )? } } else { @@ -2223,6 +2260,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, )? }; if let Some(start) = compile_start { @@ -2256,6 +2294,11 @@ mod host { self.options .dpi .resolve_ahead(&laid_out.runtime().runtime_schema.extern_functions)?; + // Process kernels run under the timed scheduler, which discovers + // the edges they cause through the trigger bits. + if !laid_out.runtime().runtime_schema.processes.is_empty() { + self.options.emit_triggers = true; + } Ok(( laid_out, @@ -2764,6 +2807,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, ) } } else { @@ -2786,12 +2830,16 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, ) }; let sim_res = program_res.and_then(|(program, warnings)| { let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); + if !laid_out.runtime().runtime_schema.processes.is_empty() { + self.options.emit_triggers = true; + } if self.vcd_path.is_some() { laid_out.enable_vcd_tracking(); } @@ -3046,6 +3094,7 @@ mod host { layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, + self.options.testbench_kernels, )? }; let mut laid_out = diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 1e183fc73e1..8838822b22d 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -493,6 +493,7 @@ impl Simulator { .filter(|name| !saved_unknown.contains(name.as_str()) || supports_unknown(name)) .map(|name| events[name]) .collect(), + settled_process_edges: Vec::new(), captured_edges: record .captured_edges .iter() @@ -507,11 +508,14 @@ impl Simulator { .collect(), // State files are rejected for designs with processes. process_wakeups: Vec::new(), + budget_blocked_processes: Vec::new(), waiting_processes: Vec::new(), process_clocks: Vec::new(), clock_waits: Vec::new(), + pending_releases: Vec::new(), done_processes: Vec::new(), ticks: 0, + tick_budget: None, scheduled_clock_time: record.time, scheduled_clock_drives: Vec::new(), inactive_processes: Vec::new(), diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index d742551fdbb..ce6c4d134f4 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -256,13 +256,13 @@ fn execution_random_seed(seed: Option) -> u64 { // Keep the generator, seed derivation, and range sampling byte-for-byte // compatible with Veryl's `$tb::random` runtime. -struct RandomTable { +pub(crate) struct RandomTable { base_seed: u64, rngs: HashMap, } impl RandomTable { - fn new(base_seed: u64) -> Self { + pub(crate) fn new(base_seed: u64) -> Self { Self { base_seed, rngs: HashMap::default(), @@ -1037,6 +1037,8 @@ async fn exec_for_loop_async>( ExecResult::Continue } +pub(crate) mod kernels; + pub(crate) fn run_testbench( sim: &mut Simulator, testbench: &CompiledTestbench, @@ -1050,6 +1052,9 @@ fn run_testbench_limited( tick_limit: Option, require_finish: bool, ) -> LimitedTestbenchResult { + if kernels::enabled(sim) { + return kernels::run_limited(sim, testbench, tick_limit, require_finish); + } let test_name = root_testbench_name(sim); let use_4state = sim.backend.layout().four_state; let initial_writes = match sim.components.initialize( @@ -1198,6 +1203,9 @@ pub(crate) fn run_testbench_detailed( sim: &mut Simulator, testbench: &CompiledTestbench, ) -> TestResultDetailed { + if kernels::enabled(sim) { + return kernels::run_detailed(sim, testbench); + } let test_name = root_testbench_name(sim); let use_4state = sim.backend.layout().four_state; let initial_writes = match sim.components.initialize( @@ -1457,6 +1465,13 @@ fn drain_runtime_assertions( location: None, }); } + RuntimeEvent::AssertPass { message } => { + ctx.assertions.push(AssertionResult { + passed: true, + message: Some(message), + location: location.cloned(), + }); + } RuntimeEvent::Display { message } => forward_display(&message, true), RuntimeEvent::Write { message } => forward_display(&message, false), RuntimeEvent::Finish => finished = true, @@ -2542,20 +2557,19 @@ mod tests { } "#; let sim = Simulator::builder(code, "t").build_with_trace().unwrap(); - let tb = compile_initial_testbench(&sim).unwrap(); - - assert!(matches!( - tb.statements().first(), - Some(GenericTestbenchStatement::Display { newline: true, .. }) - )); - assert!(matches!( - tb.statements().get(1), - Some(GenericTestbenchStatement::Display { newline: false, .. }) - )); - assert!(matches!( - tb.statements().get(2), - Some(GenericTestbenchStatement::Finish) - )); + compile_initial_testbench(&sim).unwrap(); + + // The initial block is one process kernel whose output goes through + // runtime event sites. + assert_eq!(sim.program().runtime_schema.processes.len(), 1); + let kinds: Vec<_> = sim + .program() + .runtime_schema + .runtime_event_sites + .iter() + .map(|site| format!("{:?}", site.kind)) + .collect(); + assert_eq!(kinds, vec!["Display", "Write"]); } #[test] diff --git a/crates/celox/src/testbench/kernels.rs b/crates/celox/src/testbench/kernels.rs new file mode 100644 index 00000000000..9aec0764149 --- /dev/null +++ b/crates/celox/src/testbench/kernels.rs @@ -0,0 +1,1446 @@ +//! Running the process kernels of a `#[test]` module. +//! +//! The `initial` blocks are compiled into process kernels (see the Veryl +//! frontend's process lowering), and the timed scheduler of +//! [`celox_runtime::SimulationState`] runs them: clock waits become fused +//! ticks, a reset wait releases the reset when it ends, and the host serves +//! the random number and component requests a kernel makes through scratch +//! state. + +use super::{ + AssertionResult, CompiledTestbench, LimitedTestbenchResult, RandomTable, SourceLocation, + TestResult, TestResultDetailed, apply_component_writes, execution_random_seed, forward_display, + resize_component_return, root_testbench_name, +}; +use crate::backend::SimBackend; +use crate::simulator::{RuntimeEvent, RuntimeFormatContext, Simulator}; +use celox_design::{HostRequest, HostValue}; +use num_bigint::BigUint; +use num_traits::ToPrimitive as _; + +pub(crate) struct FileTable { + files: crate::HashMap, + base: Option, +} + +impl FileTable { + fn flush(&mut self) -> Result<(), String> { + use std::io::Write; + for file in self.files.values_mut() { + file.flush().map_err(|error| error.to_string())?; + } + Ok(()) + } +} + +/// Whether the simulator's testbench runs as process kernels: the schema +/// marks them (a design's own processes alone do not make a kernel +/// testbench). +pub(crate) fn enabled(sim: &Simulator) -> bool { + sim.program.runtime_schema.testbench_kernels.is_some() +} + +/// What a run of the kernels observed. +struct KernelRun { + assertions: Vec, + error: Option, + finished: bool, + ticks: u64, + tick_limit_reached: bool, +} + +pub(crate) fn run_limited( + sim: &mut Simulator, + testbench: &CompiledTestbench, + tick_limit: Option, + require_finish: bool, +) -> LimitedTestbenchResult { + let run = run(sim, testbench, tick_limit); + let failed_messages = run + .assertions + .iter() + .filter(|assertion| !assertion.passed) + .map(|assertion| { + assertion + .message + .as_deref() + .map(super::message_diagnostic) + .unwrap_or_else(|| "assertion failed".to_string()) + }) + .collect::>(); + let result = match run.error { + Some(message) => { + if failed_messages.is_empty() { + TestResult::Fail(message) + } else if failed_messages.last().is_some_and(|m| m == &message) { + TestResult::Fail(failed_messages.join("\n")) + } else { + let mut combined = failed_messages; + combined.push(message); + TestResult::Fail(combined.join("\n")) + } + } + None => { + if !failed_messages.is_empty() { + TestResult::Fail(failed_messages.join("\n")) + } else if require_finish && !run.finished { + TestResult::Fail("testbench returned without reaching $finish".to_string()) + } else { + TestResult::Pass + } + } + }; + LimitedTestbenchResult { + result, + ticks: run.ticks, + tick_limit_reached: run.tick_limit_reached, + } +} + +pub(crate) fn run_detailed( + sim: &mut Simulator, + testbench: &CompiledTestbench, +) -> TestResultDetailed { + let run = run(sim, testbench, None); + let passed = run.error.is_none() && run.assertions.iter().all(|a| a.passed); + TestResultDetailed { + passed, + assertions: run.assertions, + error: run.error, + } +} + +fn run( + sim: &mut Simulator, + testbench: &CompiledTestbench, + tick_limit: Option, +) -> KernelRun { + let failed = |message: String| KernelRun { + assertions: Vec::new(), + error: Some(message), + finished: false, + ticks: 0, + tick_limit_reached: false, + }; + let test_name = root_testbench_name(sim); + let use_4state = sim.backend.layout().four_state; + let seed = execution_random_seed(testbench.configured_random_seed()); + // A run starts every process at its beginning, whatever an earlier run + // of the same simulator left in the control slots, and every process + // clock low, as the bytecode testbench does: the first `clk.next()` + // then counts a real rising edge. + let restarting = sim.program.runtime_schema.processes.iter().any(|slots| { + sim.backend + .get_as::(sim.backend.resolve_signal(&slots.status)) + != 0 + }); + let mut reset_signals = crate::HashSet::default(); + for slots in &sim.program.runtime_schema.processes.clone() { + for slot in slots.iter() { + let signal = sim.backend.resolve_signal(slot); + sim.backend.set_wide(signal, BigUint::ZERO); + } + // A previous run may have finished while another process held a + // reset. The old scheduler's pending release does not survive a run. + for release in slots.releases.iter().filter(|_| restarting) { + let signal = sim.backend.resolve_signal(&release.signal); + sim.backend.set_wide(signal, release.value.into()); + reset_signals.insert(signal); + sim.dirty = true; + } + for clock in &slots.clocks { + let signal = sim.backend.resolve_signal(&clock.signal); + sim.backend.set_wide(signal, BigUint::ZERO); + reset_signals.insert(signal); + sim.dirty = true; + } + } + // Component on_init stages connected inputs immediately, including logic + // derived from the clocks reset above. Settle that logic before staging. + sim.reset_runtime_finish(false); + let stage_derived_inputs = testbench.component_bindings().iter().any(|component| { + component.connections.iter().any(|connection| { + connection.input.as_ref().is_some_and(|input| { + input.constant_u64().is_none() + && !connection.input_target.as_ref().is_some_and(|target| { + target.selection.is_none() && reset_signals.contains(&target.signal) + }) + }) + }) + }); + // Constants and directly restored control signals already have startup values. + // Avoid running unrelated comb observers when on_init needs no settle: + // an init hook may finish the test before those observers should run. + if sim.dirty && stage_derived_inputs { + if let Err(error) = sim.eval_comb_checked() { + return failed(error.to_string()); + } + sim.dirty = false; + } + let initial_writes = match sim.components.initialize( + testbench.components(), + testbench.component_bindings(), + testbench.component_libraries(), + testbench.component_file_base(), + seed, + &test_name, + use_4state, + &mut sim.backend, + ) { + Ok(writes) => writes, + Err(message) => return failed(message), + }; + if let Some(writer) = sim.vcd_writer.as_mut() + && let Err(error) = writer.add_external_signals(&sim.components.trace_descriptors()) + { + let _ = sim.components.finish(0); + return failed(format!("component VCD registration failed: {error}")); + } + apply_component_writes(sim, initial_writes); + sim.testbench_random = Some(RandomTable::new(seed)); + sim.testbench_files = Some(FileTable { + files: crate::HashMap::default(), + base: testbench.component_file_base().map(|base| base.to_owned()), + }); + sim.testbench_events.clear(); + + // The scheduler samples the clocks it detects edges on from settled + // state. + if sim.dirty && !sim.components.finish_requested() { + if let Err(error) = sim.eval_comb_checked() { + // The components were installed above; take them down again. + let _ = sim.components.finish(0); + sim.testbench_random = None; + sim.testbench_files = None; + return failed(error.to_string()); + } + sim.dirty = false; + } + let mut state = crate::simulation::simulation_state(sim); + state.set_tick_budget(tick_limit); + let mut assertions = Vec::new(); + let mut error = None; + // A `$finish` of the design's own logic arrives as a runtime event; it + // ends the run like a kernel's. + let mut finish_observed = false; + let mut finished = sim.components.finish_requested(); + let progress_every = sim + .diagnostics + .testbench_progress_every + .filter(|every| *every != 0); + let mut reported_ticks = 0; + while !finished { + let stepped = state.step(sim); + if let Some(every) = progress_every { + // A step may run many fused ticks; report each multiple it passed. + let mut tick = (reported_ticks / every + 1) * every; + while tick <= state.ticks() { + tracing::debug!("[testbench-progress] tick={tick}"); + tick += every; + } + reported_ticks = state.ticks(); + } + let drained = drain(sim, &mut assertions, state.time()); + if let Some(fatal) = drained.fatal { + error = Some(fatal); + finished = true; + } + match stepped { + Ok(Some(_)) => { + if sim + .program + .runtime_schema + .testbench_kernels + .is_some_and(|first| state.processes_done_from(first)) + { + finished = true; + } + } + Ok(None) => finished = true, + Err(code) => { + if error.is_none() { + error = Some(code.to_string()); + } + finished = true; + } + } + finish_observed |= drained.finished; + if finish_observed || state.is_finished() || sim.components.finish_requested() { + finished = true; + } + } + sim.testbench_random = None; + if let Some(mut files) = sim.testbench_files.take() + && let Err(message) = files.flush() + && error.is_none() + { + error = Some(message); + } + + // A completion a component requested is read before the teardown + // clears the components. + let component_finished = sim.components.finish_requested(); + if let Err(message) = sim.components.finish(state.time()) + && error.is_none() + { + error = Some(message); + } + let finished = finish_observed || state.is_finished() || component_finished; + KernelRun { + assertions, + error, + finished, + ticks: state.ticks(), + tick_limit_reached: tick_limit.is_some_and(|limit| state.ticks() >= limit) + && !sim + .program + .runtime_schema + .testbench_kernels + .is_some_and(|first| state.processes_done_from(first)) + && !finished, + } +} + +struct Drained { + fatal: Option, + finished: bool, +} + +/// Record the assertions the kernels evaluated and forward their output. +fn drain( + sim: &mut Simulator, + assertions: &mut Vec, + time: u64, +) -> Drained { + let ctx = RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }; + let mut drained = Drained { + fatal: None, + finished: false, + }; + // The events the kernels' yields let the executor spill, then the ring. + let mut events = std::mem::take(&mut sim.testbench_events); + events.extend(sim.collect_sited_runtime_events(ctx)); + for (site, event) in events { + let location = site.and_then(|site| { + sim.program + .runtime_schema + .runtime_event_sites + .get(site)? + .location + .as_ref() + .map(|location| SourceLocation { + file: location.file.clone(), + line: location.line, + column: location.column, + }) + }); + match event { + RuntimeEvent::AssertPass { message } => assertions.push(AssertionResult { + passed: true, + message: site + .and_then(|id| sim.program.runtime_schema.runtime_event_sites.get(id)) + .filter(|site| site.template.is_some() || !site.arg_widths.is_empty()) + .map(|_| message), + location, + }), + RuntimeEvent::AssertContinue { message } => assertions.push(AssertionResult { + passed: false, + message: Some(message), + location, + }), + RuntimeEvent::AssertFatal { message } => { + if drained.fatal.is_none() { + drained.fatal = Some(super::message_diagnostic(&message)); + } + assertions.push(AssertionResult { + passed: false, + message: Some(message), + location, + }); + } + RuntimeEvent::Missed { count } => assertions.push(AssertionResult { + passed: false, + message: Some(format!("missed {count} runtime events").into_bytes()), + location: None, + }), + RuntimeEvent::Display { message } => forward_display(&message, true), + RuntimeEvent::Write { message } => forward_display(&message, false), + RuntimeEvent::Finish => drained.finished = true, + } + } + drained +} + +pub(crate) fn forward_pending_output(sim: &mut Simulator) { + sim.testbench_events.retain(|(_, event)| match event { + RuntimeEvent::Display { message } => { + forward_display(message, true); + false + } + RuntimeEvent::Write { message } => { + forward_display(message, false); + false + } + _ => true, + }); +} + +/// Serve host request `request` of process `process` at `time`. +pub(crate) fn serve_host_request( + sim: &mut Simulator, + process: usize, + request: usize, + time: u64, +) -> Result { + let request = sim + .program + .runtime_schema + .processes + .get(process) + .and_then(|slots| slots.host_requests.get(request)) + .cloned() + .ok_or_else(|| format!("process {process} made unknown host request {request}"))?; + let close_file = matches!(request, HostRequest::FileClose { .. }); + match request { + HostRequest::FileOpen { + handle, + path, + append, + } => { + // BigUint omits leading zero bytes; the declared string width + // is part of the path and must survive conversion (including NUL). + let value = read(sim, &path).to_bytes_be(); + let mut bytes = vec![0; path.width.div_ceil(8)]; + let count = bytes.len().min(value.len()); + let start = bytes.len() - count; + bytes[start..].copy_from_slice(&value[value.len() - count..]); + let path = String::from_utf8(bytes) + .map_err(|error| format!("testbench file path: {error}"))?; + let files = sim + .testbench_files + .as_mut() + .ok_or("files are only available while a testbench runs")?; + let path = match &files.base { + Some(base) => base.join(path), + None => path.into(), + }; + let file = std::fs::OpenOptions::new() + .create(true) + .write(true) + .append(append) + .truncate(!append) + .open(&path) + .map_err(|error| format!("testbench file {}: {error}", path.display()))?; + if let Some(mut previous) = files.files.insert(handle, file) { + use std::io::Write; + previous.flush().map_err(|error| error.to_string())?; + } + } + HostRequest::FileWrite { + handle, + template, + args, + } => { + use std::io::Write; + let bytes = crate::simulator::render_host_message(sim, template, &args, time); + let files = sim + .testbench_files + .as_mut() + .ok_or("files are only available while a testbench runs")?; + files + .files + .get_mut(&handle) + .ok_or_else(|| format!("testbench file {handle} is not open"))? + .write_all(&bytes) + .map_err(|error| error.to_string())?; + } + HostRequest::FileFlush { handle } | HostRequest::FileClose { handle } => { + use std::io::Write; + + let files = sim + .testbench_files + .as_mut() + .ok_or("files are only available while a testbench runs")?; + let file = files + .files + .get_mut(&handle) + .ok_or_else(|| format!("testbench file {handle} is not open"))?; + file.flush().map_err(|error| error.to_string())?; + if close_file { + files.files.remove(&handle); + } + } + + HostRequest::RandomSeed { handle, value } => { + let seed = read(sim, &value).to_u64().unwrap_or(u64::MAX); + random(sim)?.seed(&handle, seed); + } + HostRequest::RandomGet { handle, result } => { + let value = random(sim)?.get(&handle, result.width as u32); + write(sim, &result, BigUint::from(value)); + } + HostRequest::RandomGetRange { + handle, + min, + max, + result, + } => { + let min = read(sim, &min).to_u64().unwrap_or(u64::MAX); + let max = read(sim, &max).to_u64().unwrap_or(u64::MAX); + let value = + random(sim)?.get_range(&handle, min, max, result.width as u32, result.signed); + write(sim, &result, BigUint::from(value)); + } + HostRequest::RandomGetSeed { handle, result } => { + let seed = random(sim)?.get_seed(&handle); + write(sim, &result, BigUint::from(seed)); + } + HostRequest::Component { + instance, + method, + args, + result, + declared_width, + strict, + } => { + // Effectful arguments have a lowering barrier. A clean call + // must not replay combinational displays/assertions. + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } + let host_args = args + .iter() + .map(|arg| { + crate::component::host_value_from_bits(read(sim, arg), arg.width, arg.is_string) + }) + .collect::>(); + let (returned, writes) = sim.components.call_method( + &instance, + &method, + &host_args, + time, + &mut sim.backend, + )?; + apply_component_writes(sim, writes); + if sim.components.finish_requested() { + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } + return Ok(false); + } + let Some(result) = result else { + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } + return Ok(true); + }; + let Some((value, width)) = crate::component::host_bits(&returned) else { + return Err(format!( + "component method `{instance}.{method}` returned no bit value" + )); + }; + if let Some(expected) = declared_width + && width as usize != expected + { + return Err(format!( + "component method `{method}` declares a {expected}-bit return value but returned {width} bits" + )); + } + if declared_width.is_none() && strict && width > 64 { + return Err(format!( + "component method `{method}` returned {width} bits; the expression form carries at most 64 bits" + )); + } + let value = resize_component_return(value, width as usize, result.signed, result.width); + write(sim, &result, value); + // Invalid return contracts must not expose derived output effects. + if sim.dirty { + sim.eval_comb_checked().map_err(|error| error.to_string())?; + sim.dirty = false; + } + } + } + Ok(true) +} + +fn random(sim: &mut Simulator) -> Result<&mut RandomTable, String> { + sim.testbench_random + .as_mut() + .ok_or_else(|| "random numbers are only available while a testbench runs".to_string()) +} + +fn read(sim: &Simulator, value: &HostValue) -> BigUint { + let signal = sim.backend.resolve_signal(&value.signal); + sim.backend.get(signal) +} + +fn write( + sim: &mut Simulator, + target: &HostValue, + value: BigUint, +) { + let signal = sim.backend.resolve_signal(&target.signal); + let mask = (BigUint::from(1u8) << target.width) - BigUint::from(1u8); + sim.backend.set_wide(signal, value & mask); +} + +#[cfg(test)] +mod event_yield_settle_tests { + use super::*; + use crate::RuntimeErrorCode; + use celox_runtime::SimulationExecutor; + + struct CountingExecutor { + sim: Simulator, + settles: usize, + combs: usize, + fused: u64, + combs_before_edge: Option, + combs_at_finish: Option, + } + impl SimulationExecutor for CountingExecutor { + type Backend = B; + fn host_request_changes_design(&self, process: usize, request: usize) -> bool { + SimulationExecutor::host_request_changes_design(&self.sim, process, request) + } + fn host_request( + &mut self, + process: usize, + request: usize, + time: u64, + ) -> Result { + SimulationExecutor::host_request(&mut self.sim, process, request, time) + } + fn backend(&self) -> &B { + &self.sim.backend + } + fn backend_mut(&mut self) -> &mut B { + &mut self.sim.backend + } + fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { + self.combs += 1; + SimulationExecutor::eval_comb(&mut self.sim) + } + fn process_is_clean(&self, index: usize) -> bool { + SimulationExecutor::process_is_clean(&self.sim, index) + } + fn fused_ticks_allowed(&self) -> bool { + SimulationExecutor::fused_ticks_allowed(&self.sim) + } + fn tick_many( + &mut self, + event: B::Event, + count: u64, + ) -> (u64, Result<(), RuntimeErrorCode>) { + self.combs_before_edge.get_or_insert(self.combs); + let result = SimulationExecutor::tick_many(&mut self.sim, event, count); + self.fused = self.fused.max(count); + result + } + fn run_process(&mut self, index: usize, time: u64) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::run_process(&mut self.sim, index, time)?; + let slot = self.sim.program.runtime_schema.processes[index].status; + let signal = self.sim.backend.resolve_signal(&slot); + if matches!( + celox_design::ProcessStatus::from_code(self.sim.backend.get_as(signal)), + Some( + celox_design::ProcessStatus::Finish + | celox_design::ProcessStatus::FinishAfterPublication + ) + ) { + self.combs_at_finish = Some(self.combs); + } + if celox_design::ProcessStatus::from_code(self.sim.backend.get_as(signal)) + == Some(celox_design::ProcessStatus::Settle) + { + self.settles += 1; + } + Ok(()) + } + fn eval_apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + self.combs_before_edge.get_or_insert(self.combs); + SimulationExecutor::eval_apply_ff_at(&mut self.sim, event) + } + fn eval_only_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::eval_only_ff_at(&mut self.sim, event) + } + fn apply_ff_at(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + SimulationExecutor::apply_ff_at(&mut self.sim, event) + } + fn finish_requested(&mut self, time: u64) -> bool { + SimulationExecutor::finish_requested(&mut self.sim, time) + } + } + fn count(mut sim: Simulator, iterations: usize) -> usize { + let limit = sim.signal("limit"); + sim.modify(|io| { + io.set(limit, iterations as u32); + }) + .unwrap(); + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + for _ in 0..10000 { + if state.step(&mut executor).unwrap().is_none() || state.is_finished() { + return executor.settles; + } + } + panic!("process did not finish"); + } + #[test] + fn round60_terminating_expression_branches_do_not_dirty_the_join() { + fn count(sim: Simulator) -> usize { + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + for _ in 0..20 { + if state.step(&mut executor).unwrap().is_none() || state.is_finished() { + break; + } + } + assert!(state.is_finished()); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("derived")), + 1 + ); + executor.combs + } + let source = |expression: &str| { + format!( + "#[test(Top)]module Top(cond:input logic){{var value:u8;var derived:u8;always_comb{{derived=value;}}function stop()->u8{{value=2;$finish();return 0;}}initial{{value=1;$assert(({expression})==0);$assert(derived==1);$finish();}}}}" + ) + }; + // Compare reachable generated control flow with an otherwise identical + // terminating helper that makes no design write. Runtime clean flags + // can suppress the redundant settle, masking the bad compile-time join. + let branches = |source: &str| { + let compilation = Simulator::builder(source, "Top") + .testbench_kernels(true) + .trace_post_optimized_sir() + .build_with_trace(); + compilation.res.unwrap(); + let program = compilation.trace.post_optimized_sir.unwrap(); + assert!( + !program.sir.processes.is_empty(), + "inspect actual testbench kernels" + ); + program + .sir + .processes + .iter() + .flat_map(|p| p.blocks.values()) + .filter(|block| matches!(block.terminator, celox_sir::SIRTerminator::Branch { .. })) + .count() + }; + for expr in [ + "if cond ? stop() : 8'd0", + "cond && (stop()!=0)", + "!( !cond || (stop()!=0))", + ] { + let writing = source(expr); + let clean = writing.replace("value=2;", ""); + assert_eq!( + branches(&writing), + branches(&clean), + "unreachable writes add a settle guard at {expr}" + ); + } + macro_rules! check { + ($build:ident) => {{ + let active = source("if !cond ? stop() : 8'd0") + .replace("value=2;$finish();return 0;", "value=2;return 0;") + .replace("$assert(derived==1)", "$assert(derived==2)"); + let mut sim = Simulator::builder(&active, "Top").$build().unwrap(); + let tb = crate::testbench::compile_initial_testbench(&sim).unwrap(); + assert_eq!( + crate::testbench::run_compiled_testbench(&mut sim, &tb), + TestResult::Pass + ); + + let baseline = count(Simulator::builder(&source("8'd0"), "Top").$build().unwrap()); + for expr in [ + "if cond ? stop() : 8'd0", + "cond && (stop()!=0)", + "!( !cond || (stop()!=0))", + ] { + assert_eq!( + count(Simulator::builder(&source(expr), "Top").$build().unwrap()), + baseline, + "{expr}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[test] + fn round60_release_reuses_completed_settle() { + fn check(sim: Simulator, writing: bool) { + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + for _ in 0..20 { + if state.step(&mut executor).unwrap().is_none() || state.is_finished() { + break; + } + } + assert!(state.is_finished()); + let before_finish = executor.combs_at_finish.expect("finish continuation ran"); + if writing { + assert!( + executor.combs > before_finish, + "a design write still needs settling" + ); + } else { + assert_eq!( + executor.combs, before_finish, + "clean finish must reuse the release settle" + ); + } + } + for writing in [false, true] { + let source = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;inst rst:$tb::reset_gen(clk);var value:u8;var derived:u8;always_comb{{derived=value;}}initial{{rst.assert(1);{}$finish();}}}}", + if writing { "value=1;" } else { "" } + ); + check( + Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(), + writing, + ); + check( + Simulator::builder(&source, "Top") + .build_cranelift() + .unwrap(), + writing, + ); + check( + Simulator::builder(&source, "Top").build_wasm().unwrap(), + writing, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&source, "Top").build_native().unwrap(), + writing, + ); + } + } + // A child process captures real flushed stderr bytes, including file host + // effects; inspecting the event queue alone cannot establish visibility. + #[cfg(unix)] + #[test] + fn round60_output_visibility_and_release_settle() { + const CHILD: &str = "CELOX_ROUND60_OUTPUT_CHILD"; + #[expect( + clippy::disallowed_methods, + reason = "test subprocess marker only; no simulator diagnostics are read" + )] + let child = std::env::var_os(CHILD).is_some(); + if !child { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "testbench::kernels::event_yield_settle_tests::round60_output_visibility_and_release_settle", "--nocapture"]) + .env(CHILD, "1").output().unwrap(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!( + output.status.success(), + "{}\n{stderr}", + String::from_utf8_lossy(&output.stdout) + ); + assert_eq!(stderr.matches("before|host|after\n").count(), 4, "{stderr}"); + assert_eq!(stderr.matches("release-clean\n").count(), 4, "{stderr}"); + assert_eq!(stderr.matches("release-write=0\n").count(), 4, "{stderr}"); + assert_eq!(stderr.matches("release-write=1\n").count(), 4, "{stderr}"); + return; + } + fn execute(mut sim: Simulator) { + let tb = crate::testbench::compile_initial_testbench(&sim).unwrap(); + assert_eq!( + crate::testbench::run_compiled_testbench(&mut sim, &tb), + TestResult::Pass + ); + } + let ordered = r#"#[test(Top)] module Top {var f:$tb::file;initial {f.open("/dev/stderr");$write("before|");f.write("host|");f.flush();$display("after");f.close();$assert(1==1);$finish();}}"#; + let release = |writing: bool| { + format!( + r#"#[test(Top)] module Top {{inst clk:$tb::clock_gen;inst rst:$tb::reset_gen(clk);var value:u8;var armed:logic;always_comb {{if armed && (rst as u8)!=0 {{ {} }} }}initial {{armed=1;rst.assert(1);{}$finish();}}}}"#, + if writing { + r#"$display("release-write=%d",value);"# + } else { + r#"$display("release-clean");"# + }, + if writing { "value=1;" } else { "" } + ) + }; + macro_rules! check { + ($build:ident) => {{ + for source in [ordered.to_owned(), release(false), release(true)] { + execute(Simulator::builder(&source, "Top").$build().unwrap()); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[test] + fn clean_random_host_requests_preserve_settled_design_state() { + fn count_host(mut sim: Simulator) -> usize { + sim.testbench_random = Some(RandomTable::new(7)); + sim.testbench_files = Some(FileTable { + files: crate::HashMap::default(), + base: None, + }); + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + state.step(&mut executor).unwrap(); + assert!(state.is_finished()); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("derived")), + 1 + ); + executor.combs + } + let source = |body: &str| { + format!( + "#[test(Top)]module Top{{var random:$tb::random::;var f:$tb::file;var source:u8;var derived:u8;always_comb{{derived=source;}}initial{{source=1;{body}$finish();}}}}" + ) + }; + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("clean.txt"); + let file_body = format!( + "f.open(\"{}\");f.write(\"x\");f.flush();f.close();", + file.display() + ); + macro_rules! check { + ($build:ident) => {{ + let baseline = source(""); + let expected = count_host(Simulator::builder(&baseline, "Top").$build().unwrap()); + for body in ["random.seed(7);", file_body.as_str()] { + let seeded = source(body); + assert_eq!( + count_host(Simulator::builder(&seeded, "Top").$build().unwrap()), + expected + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[cfg(feature = "host-runtime")] + #[test] + fn writing_component_host_request_preserves_completed_settle() { + use std::ffi::c_void; + use veryl_component_sys as sys; + struct Host { + api: *const sys::VrlHostApi, + output: u32, + } + unsafe extern "C" fn create( + ctx: *mut sys::VrlCtx, + api: *const sys::VrlHostApi, + ) -> *mut c_void { + let clock = unsafe { + ((*api).port_index)(ctx, sys::VrlStr::from_str("clk"), sys::VRL_DIR_CLOCK) + }; + let output = unsafe { + ((*api).port_index)(ctx, sys::VrlStr::from_str("q"), sys::VRL_DIR_OUTPUT) + }; + if clock < 0 || output < 0 { + return std::ptr::null_mut(); + } + Box::into_raw(Box::new(Host { + api, + output: output as u32, + })) + .cast() + } + unsafe extern "C" fn destroy(state: *mut c_void) { + drop(unsafe { Box::from_raw(state.cast::()) }); + } + unsafe extern "C" fn hook(_: *mut c_void, _: *mut sys::VrlCtx) -> i32 { + 0 + } + unsafe extern "C" fn call( + state: *mut c_void, + ctx: *mut sys::VrlCtx, + name: sys::VrlStr, + args: *const sys::VrlValue, + nargs: usize, + _: *mut sys::VrlValue, + ) -> i32 { + let method = unsafe { name.as_str() }; + if !matches!(method, "drive" | "drive_finish") || nargs != 1 { + return 1; + } + let state = unsafe { &*state.cast::() }; + let value = unsafe { (*args).words.as_ref() }.copied().unwrap(); + unsafe { ((*state.api).write_output)(ctx, state.output, &value, std::ptr::null()) }; + if method == "drive_finish" { + unsafe { ((*state.api).finish)(ctx) }; + } + 0 + } + static COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { + abi_version: sys::VRL_COMPONENT_ABI_VERSION, + kind: sys::VRL_KIND_CLOCKED, + create, + destroy, + on_init: hook, + on_reset: hook, + on_clock: hook, + call_method: call, + on_finish: hook, + }; + crate::register_static_component("settled_writer", &COMPONENT); + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("component")).unwrap(); + std::fs::write(dir.path().join("Veryl.toml"), "[project]\nname=\"settled_writer_test\"\nversion=\"0.1.0\"\n[[components]]\npath=\"component\"\n").unwrap(); + std::fs::write(dir.path().join("component/veryl.manifest.json"), r#"{"types":{"settled_writer":{"kind":"clocked","ports":[{"name":"clk","dir":"input","role":"clock"},{"name":"q","dir":"output"}],"methods":[{"name":"drive","args":[{"name":"value","type":"value"}]},{"name":"drive_finish","args":[{"name":"value","type":"value"}]}]}}}"#).unwrap(); + let code = r#"#[test(Top)]module Top{ + inst clk:$tb::clock_gen;var q:u8;var source:u8;var derived:u8; + inst c:$comp::settled_writer(clk,q); + always_comb{derived=q+source;} + initial{source=1;c.drive(7);$finish();}} + "#; + fn check(mut sim: Simulator) { + let tb = super::super::compile_initial_testbench(&sim).unwrap(); + let initial = sim + .components + .initialize( + tb.components(), + tb.component_bindings(), + tb.component_libraries(), + tb.component_file_base(), + 7, + "Top", + false, + &mut sim.backend, + ) + .unwrap(); + apply_component_writes(&mut sim, initial); + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + state.step(&mut executor).unwrap(); + assert!(state.is_finished()); + assert_eq!( + executor.sim.backend.get_as::(executor.sim.signal("q")), + 7 + ); + assert_eq!( + executor + .sim + .backend + .get_as::(executor.sim.signal("derived")), + 8 + ); + assert_eq!(executor.combs, 1, "{}", std::any::type_name::()); + } + macro_rules! check_backend { + ($build:ident, $source:expr) => { + let metadata = + veryl_metadata::Metadata::load(dir.path().join("Veryl.toml")).unwrap(); + check( + Simulator::builder($source, "Top") + .with_metadata(metadata) + .$build() + .unwrap(), + ); + }; + } + for method in ["drive", "drive_finish"] { + let code = code.replace("c.drive(7)", &format!("c.{method}(7)")); + let code = code.as_str(); + check_backend!(build_interpreter, code); + check_backend!(build_cranelift, code); + check_backend!(build_wasm, code); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_backend!(build_native, code); + } + let pulse = "module Counter(clk:input clock,count:output u8){always_ff(clk){count+=1;}}#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:u8;var enable:logic;let gated:'_ clock=q[0] & enable;var count:u8;inst c:$comp::settled_writer(clk,q);inst dut:Counter(clk:gated,count);initial{enable=1;c.drive(1);enable=0;clk.next(1);$assert(count==1,\"component edge lost\");$finish();}}"; + macro_rules! check_pulse { + ($build:ident) => {{ + let metadata = + veryl_metadata::Metadata::load(dir.path().join("Veryl.toml")).unwrap(); + let mut sim = Simulator::builder(pulse, "Top") + .with_metadata(metadata) + .testbench_kernels(true) + .$build() + .unwrap(); + let tb = super::super::compile_initial_testbench(&sim).unwrap(); + assert_eq!( + super::super::run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + }}; + } + check_pulse!(build_interpreter); + check_pulse!(build_cranelift); + check_pulse!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check_pulse!(build_native); + } + + #[test] + fn private_loop_counters_do_not_request_settles() { + let code = r#"#[test(Top)]module Top(limit:input u32){initial{for i in 0..limit{$assert(1);}$finish();}}"#; + macro_rules! check { + ($method:ident) => {{ + assert_eq!( + count( + Simulator::builder(code, "Top") + .testbench_kernels(true) + .$method() + .unwrap(), + 3 + ), + 0 + ); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + #[test] + fn clean_conditional_paths_do_not_request_a_settle() { + for statement in [ + "if limit != 0 {source=1;}", + "case limit {0:{} default:{source=1;}}", + ] { + let code = format!( + "#[test(Top)]module Top(limit:input u32){{var source:u32;var derived:u32;always_comb{{derived=source;}}initial{{{statement}$assert(derived==source);$finish();}}}}" + ); + macro_rules! check { + ($method:ident) => {{ + for (input, expected) in [(0, 0), (1, 1)] { + assert_eq!( + count( + Simulator::builder(&code, "Top") + .testbench_kernels(true) + .$method() + .unwrap(), + input + ), + expected, + "{statement}, input={input}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + } + + #[test] + fn event_yield_does_not_settle_a_write_twice() { + let code = r#"#[test(Top)]module Top(limit:input u32){var source:u32;var derived:u32; + always_comb{derived=source;} + function mark(x:input u32,o:output u32)->u32{o=x;return 1;} + initial{for i in 0..limit{$assert(1,"tb %d",mark(i,source));$assert(derived==i,"read");$assert(1);}$assert(derived==limit-1,"end");$finish();}}"#; + macro_rules! check { + ($method:ident) => {{ + let run = |n| { + count( + Simulator::builder(code, "Top") + .testbench_kernels(true) + .$method() + .unwrap(), + n, + ) + }; + let small_delta = run(2) - run(1); + let before_yield = run(85); + let at_yield = run(86); + let after_yield = run(87); + assert_eq!( + at_yield - before_yield, + small_delta, + "256th event settled twice" + ); + assert_eq!( + after_yield - at_yield, + small_delta, + "post-yield write must settle" + ); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + fn execution_counts(sim: Simulator, steps: usize) -> (usize, u64, u64) { + let mut state = crate::simulation::simulation_state(&sim); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + for _ in 0..steps { + if state.step(&mut executor).unwrap().is_none() { + break; + } + if state.is_finished() { + break; + } + } + if let Ok(q) = executor.sim.try_signal("q") { + assert_eq!(executor.sim.backend.get_as::(q), state.ticks() as u32); + } + if let (Ok(source), Ok(derived)) = ( + executor.sim.try_signal("source"), + executor.sim.try_signal("derived"), + ) { + assert_eq!( + executor.sim.backend.get_as::(derived), + executor.sim.backend.get_as::(source) + ); + } + ( + executor.combs_before_edge.unwrap_or(executor.combs), + executor.fused, + state.ticks(), + ) + } + #[test] + fn kernel_output_after_wait_preserves_fusion_but_design_output_does_not() { + for task in ["$display(\"done\");", "$write(\"done\");"] { + let code = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;var q:u32;always_ff(clk){{q+=1;}}initial{{clk.next(1000);{task}$assert(q==1000);$finish();}}}}" + ); + macro_rules! check { + ($method:ident) => {{ + let (_, fused, ticks) = + execution_counts(Simulator::builder(&code, "Top").$method().unwrap(), 3000); + assert_eq!(fused, 1000); + assert_eq!(ticks, 1000); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + let code = "#[test(Top)]module Top{inst clk:$tb::clock_gen;always_ff(clk){$display(\"edge\");}initial{clk.next(1000);$finish();}}"; + let (_, fused, _) = execution_counts( + Simulator::builder(code, "Top").build_interpreter().unwrap(), + 2, + ); + assert_eq!(fused, 0); + } + #[test] + fn clean_clock_wait_continuations_do_not_repeat_comb_settles() { + for (body, expected) in [ + ("source=1;", 1), + ("source=1;clk.next(1);", 2), + ("source=1;$assert(derived==1);source=2;", 2), + ("source=1;$assert(derived==1);clk.next(write());", 3), + ] { + let code = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;var source:u32;var derived:u32;always_comb{{derived=source;$assert(1,\"comb\");}}function write()->u32{{source=2;return 1;}}initial{{{body}}}}}" + ); + macro_rules! check { + ($method:ident) => {{ + let (combs, _, _) = + execution_counts(Simulator::builder(&code, "Top").$method().unwrap(), 1); + assert_eq!(combs, expected, "{body}"); + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); + } + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + fn native_image_preserves_clean_continuation_after_optimization() { + let code = "#[test(Top)]module Top{var source:u32;var derived:u32;always_comb{derived=source;}initial{source=1;}}"; + let original = Simulator::builder(code, "Top") + .opt_level(crate::OptLevel::O2) + .build_native() + .unwrap(); + let bytes = original + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = crate::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + assert!(image.runtime_schema().processes[0].comb_clean.is_some()); + let restored = Simulator::builder("unused", "unused") + .build_native_from_image(image) + .unwrap(); + assert_eq!(execution_counts(restored, 1).0, 1); + } + #[test] + fn repeated_kernel_entries_restart_the_event_yield_count() { + let code = r#"#[test(Top)]module Top{var source:u32;var derived:u32; + always_comb{derived=source;} + function mark(o:output u32)->u32{o=1;return 1;} + initial{$assert(1,"value %d",mark(source));$finish();}} + "#; + fn check(sim: Simulator) { + let source = sim.signal("source"); + let derived = sim.signal("derived"); + let mut executor = CountingExecutor { + sim, + settles: 0, + combs: 0, + fused: 0, + combs_before_edge: None, + combs_at_finish: None, + }; + for run in 1..=256 { + // Restart control slots as the public runner does, retaining + // the same compiled kernel and its other scratch storage. + for slots in &executor.sim.program.runtime_schema.processes { + for address in slots.iter() { + let signal = executor.sim.backend.resolve_signal(address); + executor.sim.backend.set(signal, 0u64); + } + } + executor.sim.backend.set(source, 0u32); + executor.eval_comb().unwrap(); + let mut state = crate::simulation::simulation_state(&executor.sim); + let before = executor.settles; + while !state.is_finished() { + assert!(state.step(&mut executor).unwrap().is_some()); + } + assert_eq!( + executor.settles - before, + 0, + "run {run} inherited an event-yield budget" + ); + assert_eq!(executor.sim.backend.get_as::(source), 1); + assert_eq!(executor.sim.backend.get_as::(derived), 1); + } + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); + } +} + +#[cfg(test)] +mod file_path_width_tests { + use super::*; + #[test] + fn leading_nul_host_path_does_not_open_the_stripped_filename() { + fn check(mut sim: Simulator, filename: &std::path::Path, zeros: usize) { + std::fs::write(filename, b"keep").unwrap(); + let (process, request, path) = + sim.program + .runtime_schema + .processes + .iter() + .enumerate() + .find_map(|(p, slots)| { + slots.host_requests.iter().enumerate().find_map( + |(r, request)| match request { + HostRequest::FileOpen { path, .. } => Some((p, r, path.clone())), + _ => None, + }, + ) + }) + .unwrap(); + let text = filename.to_str().unwrap(); + assert!(path.is_string); + assert_eq!(path.width, (text.len() + zeros) * 8); + // The compiled scratch has room for the declared leading bytes. + // Set its payload directly: Veryl source literals cannot spell NUL. + let signal = sim.backend.resolve_signal(&path.signal); + sim.backend + .set_wide(signal, BigUint::from_bytes_be(text.as_bytes())); + sim.testbench_files = Some(FileTable { + files: crate::HashMap::default(), + base: None, + }); + let result = serve_host_request(&mut sim, process, request, 0); + assert!(result.is_err(), "leading NUL path was accepted: {result:?}"); + assert_eq!(std::fs::read(filename).unwrap(), b"keep"); + } + let dir = tempfile::tempdir().unwrap(); + let filename = dir.path().join("output"); + for zeros in [1, 2] { + let text = format!("{}{}", " ".repeat(zeros), filename.display()); + let source = format!( + r#"#[test(Top)]module Top{{var f:$tb::file;initial{{f.open("{text}");$finish();}}}}"# + ); + let build = || crate::Simulator::builder(&source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap(), &filename, zeros); + check(build().build_cranelift().unwrap(), &filename, zeros); + check(build().build_wasm().unwrap(), &filename, zeros); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), &filename, zeros); + } + } +} diff --git a/crates/celox/src/testbench_compile.rs b/crates/celox/src/testbench_compile.rs index 5faa159f784..1839eb70ec9 100644 --- a/crates/celox/src/testbench_compile.rs +++ b/crates/celox/src/testbench_compile.rs @@ -9,7 +9,11 @@ pub(crate) fn project_observability( ) -> Result<(), celox_frontend_veryl::ParserError> { let (sites, read_variables) = celox_frontend_veryl::collect_testbench_observability(lookup, source)?; - runtime_schema.runtime_event_sites.extend(sites); + // Kernels register their own sites; the roots still keep the state the + // testbench reads alive. + if !source.kernels { + runtime_schema.runtime_event_sites.extend(sites); + } runtime_schema.testbench_read_roots.extend(read_variables); Ok(()) } @@ -30,7 +34,7 @@ pub(crate) fn compile_semantic_testbench( #[cfg(all(test, feature = "systemverilog"))] mod process_root_tests { - use crate::{Simulation, Simulator}; + use crate::{OptLevel, Simulation, Simulator}; #[test] fn semantic_testbench_projection_preserves_process_counter_roots() { let veryl = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:logic;inst dut:$sv::Pulse(q);initial{clk.next(2);$assert(q==1);$finish();}}"#; @@ -40,7 +44,8 @@ mod process_root_tests { vec![(sv, std::path::Path::new("pulse.sv"))], "Top", ) - .optimize(true) + .testbench_kernels(false) + .opt_level(OptLevel::O2) .build_interpreter() .unwrap(); let schema = &sim.program.runtime_schema; diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index 840858afa2e..e6472d5a116 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -84,6 +84,9 @@ unsafe extern "C" fn call_method( if unsafe { args[0].str_.as_str() } == "hello" { state.value = 7; 0 + } else if unsafe { args[0].str_.as_str() }.is_empty() { + state.value = 9; + 0 } else { 1 } @@ -304,7 +307,7 @@ unsafe extern "C" fn clock_call_method( name: sys::VrlStr, args: *const sys::VrlValue, nargs: usize, - _ret: *mut sys::VrlValue, + ret: *mut sys::VrlValue, ) -> i32 { let state = unsafe { &mut *state.cast::() }; let api = unsafe { &*state.api }; @@ -358,6 +361,12 @@ unsafe extern "C" fn clock_call_method( unsafe { (api.write_output)(ctx, state.output, &value, std::ptr::null()) }; 0 } + "drive_lying" if args.is_empty() => { + let value = 1; + unsafe { (api.write_output)(ctx, state.output, &value, std::ptr::null()) }; + unsafe { write_return(ret, 1, 16) }; + 0 + } "check_clocks" if args.len() == 1 && argument(0) == Some(state.clocks) => 0, "stop" if args.is_empty() => { unsafe { (api.finish)(ctx) }; @@ -397,6 +406,32 @@ static CLOCK_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { on_finish: hook, }; +unsafe extern "C" fn clock_init_from_clock(state: *mut c_void, ctx: *mut sys::VrlCtx) -> i32 { + let state = unsafe { &mut *state.cast::() }; + let api = unsafe { &*state.api }; + let clock = unsafe { (api.port_index)(ctx, sys::VrlStr::from_str("clk"), sys::VRL_DIR_CLOCK) }; + if clock < 0 { + return 1; + } + let mut value = 0; + let mut mask = 0; + unsafe { (api.read_input)(ctx, clock as u32, &mut value, &mut mask) }; + unsafe { (api.write_output)(ctx, state.output, &value, &mask) }; + 0 +} + +static INIT_CLOCK_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { + abi_version: sys::VRL_COMPONENT_ABI_VERSION, + kind: sys::VRL_KIND_CLOCKED, + create: create_clock, + destroy: destroy_clock, + on_init: clock_init_from_clock, + on_reset: hook, + on_clock: hook, + call_method: clock_call_method, + on_finish: hook, +}; + static INIT_INPUT_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { abi_version: sys::VRL_COMPONENT_ABI_VERSION, kind: sys::VRL_KIND_CLOCKED, @@ -750,6 +785,7 @@ fn register_component() { celox::register_static_component("celox_param", &COMPONENT); celox::register_static_component("celox_clocked", &CLOCK_COMPONENT); celox::register_static_component("celox_init_input", &INIT_INPUT_COMPONENT); + celox::register_static_component("celox_init_clock", &INIT_CLOCK_COMPONENT); celox::register_static_component("celox_wide_clocked", &WIDE_CLOCK_COMPONENT); celox::register_static_component("celox_modport", &MODPORT_COMPONENT); celox::register_static_component("celox_bad_clock", &BAD_CLOCK_COMPONENT); @@ -821,6 +857,14 @@ fn component_metadata() -> (tempfile::TempDir, veryl_metadata::Metadata) { ], "params": [{"name":"STEP","type":"value"}] }, + "celox_init_clock": { + "kind": "clocked", + "ports": [ + {"name":"clk","dir":"input","role":"clock"}, + {"name":"d","dir":"input"}, + {"name":"q","dir":"output"} + ] + }, "celox_init_input": { "kind": "clocked", "ports": [ @@ -1039,6 +1083,137 @@ fn connected_clocked_component_stages_inputs_and_applies_outputs() { ); } +#[test] +fn repeated_kernel_runs_stage_low_clocks_before_component_init() { + register_component(); + let code = r#" + #[test(t)] module t { + inst clk: $tb::clock_gen; + var q: logic<8>; + inst probe: $comp::celox_init_clock(clk, d: 8'h0, q); + inst finisher: $comp::celox_finisher(clk); + initial { + $assert(q == 0, "on_init must observe a low generated clock: %h", q); + clk.next(10); + $assert(0, "component must finish on the first rising edge"); + } + } + "#; + macro_rules! check { + ($method:ident) => {{ + let (_dir, metadata) = component_metadata(); + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(true) + .$method() + .unwrap(); + let compiled = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for run in 0..3 { + assert_eq!( + celox::testbench::run_compiled_testbench(&mut sim, &compiled), + TestResult::Pass, + "run {run}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); +} + +#[test] +fn repeated_kernel_runs_settle_derived_clock_before_component_init() { + register_component(); + let code = r#" + #[test(t)] module t { + inst clk: $tb::clock_gen; + var q: logic<8>; + let derived: logic<8> = (clk as u8) + 8'h1; + inst probe: $comp::celox_init_input(clk, d: derived, q); + inst finisher: $comp::celox_finisher(clk); + initial { + $assert(q == 1, "on_init must observe a settled derived clock: %h", q); + clk.next(10); + $assert(0, "component must finish on the first rising edge"); + } + } + "#; + macro_rules! check { + ($method:ident) => {{ + let (_dir, metadata) = component_metadata(); + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(true) + .$method() + .unwrap(); + let compiled = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for run in 0..3 { + assert_eq!( + celox::testbench::run_compiled_testbench(&mut sim, &compiled), + TestResult::Pass, + "run {run}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); +} + +#[test] +fn repeated_kernel_runs_deassert_interrupted_reset_before_component_init() { + register_component(); + let code = r#" + #[test(t)] module t { + inst clk: $tb::clock_gen; + inst rst: $tb::reset_gen(clk); + var q: logic<8>; + let derived: logic<8> = (rst as u8) + 8'h1; + inst probe: $comp::celox_init_input(clk, d: derived, q); + inst finisher: $comp::celox_finisher(clk); + initial { rst.assert(5); $assert(0, "reset must be interrupted"); } + initial { + clk.next(10); + $assert(0, "component must finish on the first rising edge"); + } + } + "#; + macro_rules! check { + ($method:ident) => {{ + let (_dir, metadata) = component_metadata(); + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(true) + .$method() + .unwrap(); + let compiled = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for run in 0..3 { + assert_eq!( + celox::testbench::run_compiled_testbench(&mut sim, &compiled), + TestResult::Pass, + "run {run}" + ); + assert_eq!( + sim.get(sim.signal("q")), + (if run == 0 { 1u8 } else { 2u8 }).into(), + "on_init on run {run}" + ); + } + }}; + } + check!(build_interpreter); + check!(build_cranelift); + check!(build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check!(build_native); +} + #[test] fn component_on_init_observes_connected_inputs() { register_component(); @@ -1686,6 +1861,7 @@ fn component_method_refreshes_inputs_and_applies_outputs_immediately() { inst clk: $tb::clock_gen; var d: logic<16>; var q: logic<16>; + let derived: logic<16> = ~q; inst component: $comp::celox_clocked #(STEP: 0) ( clk, d: d[7:0], @@ -1697,6 +1873,9 @@ fn component_method_refreshes_inputs_and_applies_outputs_immediately() { component.check_input(8'h34); component.drive(8'h5a); $assert(q == 16'hab5a, "method output must update only the selected destination: %h", q); + // The logic derived from the output is settled before the + // next statement reads it. + $assert(derived == 16'h54a5, "derived logic must see the method output: %h", derived); $finish(); } } @@ -1827,47 +2006,6 @@ fn synchronous_reset_without_runtime_reset_event_still_binds() { .build() .unwrap(); let testbench = celox::testbench::compile_initial_testbench(&simulator).unwrap(); - let semantic_reset = simulator - .program() - .testbench - .as_ref() - .unwrap() - .statements() - .iter() - .find_map(|statement| match statement { - celox_testbench::TestbenchStatement::ResetAssert { - reset_signal, - clock_event, - duration, - assert_value, - deassert_value, - .. - } => Some(celox_testbench::TestbenchStatement::ResetAssert { - reset_signal: *reset_signal, - reset_event: None, - clock_event: *clock_event, - duration: duration.clone(), - period: 2, - assert_value: *assert_value, - deassert_value: *deassert_value, - }), - _ => None, - }) - .unwrap(); - let isolated = celox_testbench::TestbenchProgram::new(vec![semantic_reset]); - let bound = celox_runtime::bind_testbench_program( - simulator.backend_ref(), - isolated, - &fxhash::FxHashSet::default(), - ) - .unwrap(); - assert!(matches!( - bound.statements().first(), - Some(celox_testbench::TestbenchStatement::ResetAssert { - reset_event: None, - .. - }) - )); assert_eq!( celox::testbench::run_compiled_testbench(&mut simulator, &testbench), TestResult::Pass @@ -2098,7 +2236,9 @@ fn component_finish_request_during_init_skips_testbench_execution() { module t { inst clk: $tb::clock_gen; inst component: $comp::celox_init_finisher (clk); + always_comb { $assert(0, "on_init finish must skip initial settling"); } initial { + clk.next(); $assert(0, "on_init finish must skip this statement"); } } @@ -2908,7 +3048,9 @@ fn component_finish_hook_observes_final_testbench_time() { .unwrap(), TestResult::Pass ); - assert_eq!(FINISH_TIME.load(Ordering::Relaxed), 10); + // The finish hook sees the scheduler time: ten edges of the default + // clock (period 2) end at time 18, and the process resumes at 20. + assert_eq!(FINISH_TIME.load(Ordering::Relaxed), 20); for period in [2, 10] { let code = code .replace( @@ -3088,3 +3230,137 @@ fn concurrent_reset_only_replaces_its_own_component_clock_domain() { TestResult::Pass ); } + +static VCD_FINISH_CALLS: AtomicUsize = AtomicUsize::new(0); +unsafe extern "C" fn finish_vcd_registration(_: *mut c_void, _: *mut sys::VrlCtx) -> i32 { + VCD_FINISH_CALLS.fetch_add(1, Ordering::Relaxed); + 0 +} +static VCD_CLEANUP_COMPONENT: sys::VrlComponentVTable = sys::VrlComponentVTable { + on_finish: finish_vcd_registration, + ..CLOCK_COMPONENT +}; + +#[test] +fn failed_component_vcd_registration_calls_finish_on_each_run() { + celox::register_static_component("celox_vcd_cleanup", &VCD_CLEANUP_COMPONENT); + VCD_FINISH_CALLS.store(0, Ordering::Relaxed); + let (directory, metadata) = component_metadata(); + let manifest = directory.path().join("component/veryl.manifest.json"); + let mut json: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&manifest).unwrap()).unwrap(); + json["types"]["celox_vcd_cleanup"] = json["types"]["celox_clocked"].clone(); + std::fs::write(&manifest, serde_json::to_vec(&json).unwrap()).unwrap(); + let code = r#"#[test(t)] module t { + inst clk: $tb::clock_gen; + var d: logic<8>; var q: logic<8>; + inst component: $comp::celox_vcd_cleanup #(STEP: 0)(clk,d,q); + initial {clk.next();$finish();} + }"#; + let mut sim = Simulator::builder(code, "t") + .with_metadata(metadata) + .vcd(directory.path().join("cleanup.vcd")) + .build() + .unwrap(); + // A written header cannot accept newly initialized component signals. + sim.dump(0); + let tb = celox::testbench::compile_initial_testbench(&sim).unwrap(); + for expected in 1..=2 { + let result = celox::testbench::run_compiled_testbench(&mut sim, &tb); + assert!( + matches!(result,TestResult::Fail(ref message) if message.contains("component VCD registration failed")), + "{result:?}" + ); + assert_eq!(VCD_FINISH_CALLS.load(Ordering::Relaxed), expected); + } +} + +#[test] +fn empty_component_string_arguments_preserve_bytecode_behavior() { + register_component(); + for kernels in [false, true] { + let (_dir, metadata) = component_metadata(); + let code = r#"#[test(t)] module t { var c:$comp::celox_counter; + initial { c.set_str(""); var value:u8; value=c.get(); $assert(value==9); $finish(); } + }"#; + assert_eq!( + Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(kernels) + .run_test() + .unwrap(), + TestResult::Pass + ); + } +} + +#[test] +fn clean_component_calls_do_not_replay_comb_assertions() { + register_component(); + let count = |calls: &str| { + let (_dir, metadata) = component_metadata(); + let code = format!( + r#"#[test(t)] module t {{ var c:$comp::celox_counter; + always_comb {{ $assert(1,"comb"); }} + initial {{ {calls} $finish(); }} + }}"# + ); + let result = Simulator::builder(&code, "t") + .with_metadata(metadata) + .run_test_detailed() + .unwrap(); + assert!(result.passed, "{result:?}"); + result + .assertions + .iter() + .filter(|a| a.message.as_deref() == Some(b"comb".as_slice())) + .count() + }; + assert_eq!(count("c.get(); c.get();"), count("")); +} + +#[test] +fn invalid_component_returns_precede_output_assertions() { + register_component(); + for kernels in [false, true] { + let (dir, _) = component_metadata(); + let path = dir.path().join("component/veryl.manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + manifest["types"]["celox_clocked"]["methods"] = + serde_json::json!([{"name":"drive_lying","args":[],"ret":"value","ret_width":8}]); + std::fs::write(path, serde_json::to_vec(&manifest).unwrap()).unwrap(); + let metadata = veryl_metadata::Metadata::load(dir.path().join("Veryl.toml")).unwrap(); + let code = r#"#[test(t)] module t { + inst clk:$tb::clock_gen;var d:u8;var q:u8;var value:u8; + inst c:$comp::celox_clocked #(STEP:0)(clk:clk,d,q); + always_comb { $assert(q!=1,"output assertion"); } + initial { value=c.drive_lying();$finish(); } + }"#; + let result = Simulator::builder(code, "t") + .with_metadata(metadata) + .testbench_kernels(kernels) + .run_test() + .unwrap(); + assert!( + matches!(result,TestResult::Fail(ref message) if message.contains("declares a 8-bit return value but returned 16 bits")), + "{result:?}" + ); + } +} + +#[test] +fn component_return_selection_helpers_resume() { + register_component(); + let (_dir, metadata) = component_metadata(); + let code = r#"#[test(t)]module t{inst clk:$tb::clock_gen;var c:$comp::celox_counter;var words:u8[2]; + function index()->u32{clk.next();$assert(1,"index");return 1;} + initial{c.set(7);words[index()]=c.get();$assert(words[1]==7);$finish();}}"#; + assert_eq!( + Simulator::builder(code, "t") + .with_metadata(metadata) + .run_test() + .unwrap(), + TestResult::Pass + ); +} diff --git a/crates/celox/tests/concurrent_initial_runtime.rs b/crates/celox/tests/concurrent_initial_runtime.rs index a295e84b849..ddce7866102 100644 --- a/crates/celox/tests/concurrent_initial_runtime.rs +++ b/crates/celox/tests/concurrent_initial_runtime.rs @@ -2,7 +2,7 @@ use celox::testbench::{ compile_initial_testbench, run_compiled_testbench, run_compiled_testbench_to_finish, run_compiled_testbench_with_tick_limit, }; -use celox::{Simulator, TestResult}; +use celox::{SimBackend, Simulator, TestResult}; // These runtime-specific tests use package-local snapshots of the shared suite's // testbench fixtures. Keep them in celox's archive: sibling crate directories @@ -148,7 +148,7 @@ fn native_image_roundtrip_preserves_concurrent_processes_and_periods() { .build_native_from_image(image) .unwrap(); let tb = compile_initial_testbench(&restored).unwrap(); - assert!(tb.processes().count() >= 2); + assert!(restored.program().runtime_schema.processes.len() >= 2); assert_eq!( run_compiled_testbench_to_finish(&mut restored, &tb), TestResult::Pass @@ -453,6 +453,7 @@ fn tick_limit_drains_falling_edges_and_reset_release_without_resuming_processes( check(Simulator::builder(code, "Top").build_interpreter().unwrap()); check(Simulator::builder(code, "Top").build_cranelift().unwrap()); check(Simulator::builder(code, "Top").build_wasm().unwrap()); + check(Simulator::builder(code, "Top").build_tiered().unwrap()); #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] check(Simulator::builder(code, "Top").build_native().unwrap()); } @@ -540,3 +541,1761 @@ fn concurrent_runtime_assertions_use_event_time() { ] ); } + +fn check_passes_on_every_backend(code: &str) { + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass, + "backend={}", + std::any::type_name::() + ); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +/// A read after a branch whose one side stored and whose other side waited +/// sees the settled logic. +#[test] +fn read_after_branch_settles_the_store_of_the_other_side() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var source: logic<8>; + var cond: logic; + let derived: logic<8> = source + 8'd1; + initial { + cond = 1; + source = 8'd1; + if cond { source = 8'd41; } else { clk.next(); } + $assert(derived == 8'd42, "derived=%d", derived); + case cond { + 1'b0: clk.next(); + default: source = 8'd7; + } + $assert(derived == 8'd8, "derived=%d", derived); + $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +/// Constructs a constant keeps out of the kernel take no scratch state, so +/// a later statement gets the scratch planned for it. +#[test] +fn unreachable_loops_take_no_scratch_state() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var r: $tb::random::; + var x: u8; + initial { + if 1'b0 { + for i in 0..3 { clk.next(); } + } + for j in 3..3 { clk.next(); } + r.seed(7); + x = r.get_range(5, 5); + $assert(x == 8'd5, "x=%d", x); + $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +/// A host request (a random number here) is a zero-time call: no other +/// process runs between the statements around it. +#[test] +fn host_requests_do_not_interleave_other_processes() { + let code = r#"#[test(Top)] module Top { + var r: $tb::random::; + var x: u8; + var v: u8; + var seen: u8; + initial { x = 8'd1; v = r.get(); x = 8'd2; } + initial { seen = x; $assert(seen == 8'd2, "seen=%d", seen); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +/// A `$finish` of the design's own clocked logic completes the run. +#[test] +fn finish_from_design_logic_completes_the_run() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var count: logic<8>; + always_ff (clk) { + if count == 8'd3 { $finish(); } + count += 1; + } + initial { clk.next(10); } + }"#; + check_passes_on_every_backend(code); + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &tb, 100); + assert_eq!(result.result, TestResult::Pass); + assert!(!result.tick_limit_reached); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); +} + +/// A run starts its process clocks low, as the bytecode testbench did: a +/// clock the host drove high still counts a real first edge. +#[test] +fn a_run_starts_its_process_clocks_low() { + let code = r#" + module Counter(clk: input clock, count: output logic<8>) { + always_ff(clk) { count += 1; } + } + #[test(Top)] module Top { + inst clk: $tb::clock_gen; + var count: logic<8>; + inst dut: Counter(clk, count); + initial { clk.next(1); $finish(); } + }"#; + let mut sim = Simulator::builder(code, "Top").build_cranelift().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + let clk = sim.signal("clk"); + sim.set_wide(clk, 1u8.into()); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("count")), 1u32.into()); +} + +/// More runtime events than the ring holds, in one uninterrupted block: +/// the kernel yields to the host before the ring wraps. +#[test] +fn many_events_in_one_run_are_not_missed() { + let code = r#"#[test(Top)] module Top { + var x: logic<8>; + initial { + x = 1; + for i in 0..3000 { $assert(x == 1, "x=%d", x); } + for i in 0..1500 { $display("line %d", i); } + $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +/// A fatal assertion with a formatted message fails with that message +/// alone. +#[test] +fn a_fatal_assertion_reports_its_rendered_message_once() { + let code = r#"#[test(Top)] module Top { + var x: logic<8>; + initial { x = 5; $assert(x == 6, "x=%d", x); $finish(); } + }"#; + let mut sim = Simulator::builder(code, "Top").build_cranelift().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench(&mut sim, &tb), + TestResult::Fail("x=5".to_string()) + ); +} + +/// `clk.next(0)` continues at once: no other block runs in between. +#[test] +fn zero_count_clock_waits_do_not_interleave_other_processes() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var x: u8; + var seen: u8; + initial { x = 8'd1; clk.next(0); x = 8'd2; } + initial { seen = x; $assert(seen == 8'd2, "seen=%d", seen); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +/// A block that ends right after a store settles, so the next block reads +/// the logic derived from it. +#[test] +fn a_block_ending_after_a_store_settles_for_the_next_block() { + let code = r#"#[test(Top)] module Top { + var source: logic<8>; + let derived: logic<8> = source + 8'd1; + initial { source = 8'd41; } + initial { $assert(derived == 8'd42, "derived=%d", derived); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn expression_helper_finish_stops_continuations_and_other_processes() { + let code = r#"#[test(Top)] module Top { + var value: u32; + function stop() -> u32 { $finish(); return 7; } + initial { value = stop(); for i in 0..10000 { $assert(1'd0, "continued after finish"); } } + initial { $assert(1'd0, "other process ran after finish"); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn expression_helper_output_stores_settle_derived_reads() { + let code = r#"#[test(Top)] module Top { + var source: logic<8>; + let derived: logic<8> = source + 8'd1; + function update(value: output logic<8>) -> logic { value = 8'd41; return 1'd1; } + initial { if update(source) { $assert(derived == 8'd42); } $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn effectful_case_target_is_evaluated_once() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + function next() -> u32 { calls += 1; return calls; } + initial { case next() { 0: $assert(1'd0); 1: $assert(calls == 1); default: $assert(1'd0); } $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn loop_backedges_settle_the_previous_iteration_store() { + let code = r#"#[test(Top)] module Top { + var source: u32; + let derived: u32 = source + 1; + initial { for i in 0..3 { $assert(derived == i + 1); source += 1; } $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn expression_values_survive_nested_helper_clock_waits() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var value: u32; + function later(value: input u32) -> u32 { clk.next(); return value; } + initial { value = later(2) + later(5); $assert(value == 7); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn effectful_expression_helpers_preserve_short_circuit_and_branch_selection() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + var value: logic; + function next() -> logic { calls += 1; return 1'd1; } + initial { + value = 1'd0 && next(); $assert(value == 1'd0); + value = 1'd1 || next(); $assert(value == 1'd1); + value = if 1'd1 ? next() : next(); + $assert(calls == 1); $finish(); + } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn expression_helpers_publish_passing_assertions_and_yield_before_ring_wrap() { + let code = r#"#[test(Top)] module Top { + var value: u32; + function emit_event() -> u32 { $write(""); $assert(1'd1); return 1; } + initial { for i in 0..1500 { value = emit_event(); } $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(detailed.passed, "{detailed:?}"); + assert_eq!(detailed.assertions.len(), 1500); + assert!( + detailed + .assertions + .iter() + .all(|assertion| assertion.passed && assertion.message.is_none()) + ); + check_passes_on_every_backend(code); +} + +#[test] +fn fatal_combinational_step_returns_failure_without_event_drain_panic() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var count: u32; + always_ff(clk) { count += 1; } + always_comb { $assert(count <: 2, "comb failed"); } + initial { clk.next(10); $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(!detailed.passed); + assert!( + detailed + .error + .as_deref() + .is_some_and(|error| error.contains("comb failed")), + "{detailed:?}" + ); +} + +#[test] +fn dynamic_signed_wide_singleton_uses_the_wide_loop_path() { + let code = r#"#[test(Top)] module Top { + var bound: signed logic<192>; + var count: u32; + initial { bound = -(192'd1 << 150); for i in bound..=bound { count += 1; } $assert(count == 1); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn unreachable_clock_waits_leave_a_host_driven_clock_unchanged() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + initial { if 1'd0 { clk.next(); } for i in 3..3 { clk.next(); } $assert(clk == 1'd1); $finish(); } + }"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); +} + +#[test] +fn reset_duration_reads_the_value_before_assertion() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen #(period: 2); + inst rst: $tb::reset_gen(clk); + initial { rst.assert(1); rst.assert((rst as u32) + 1); $assert(1'd1, "time=%t"); $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(detailed.passed, "{detailed:?}"); + assert_eq!( + detailed.assertions[0].message.as_deref(), + Some(b"time=6".as_slice()) + ); + check_passes_on_every_backend(code); +} + +#[test] +fn statement_call_arguments_preserve_order_and_each_nested_result() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + function probe(value: input u32) -> u32 { calls = calls * 10 + value; return value; } + function accept(first: input u32, second: input u32) { $assert(first == 1 && second == 2); } + initial { accept(probe(1), probe(2)); $assert(calls == 12); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn selected_method_and_function_outputs_validate_destination_bounds() { + for operation in ["words[2] = random.get();", "fill(words[2]);"] { + let code = format!( + r#"#[test(Top)] module Top {{ + var random: $tb::random::; + var words: u8[2]; + function fill(value: output u8) {{ value=7; }} + initial {{ {operation} $finish(); }} + }}"# + ); + let error = Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap_err() + .to_string(); + assert!( + error.contains("testbench selected destination") || error.contains("invalid select"), + "{error}" + ); + } +} + +#[test] +fn display_and_assertion_arguments_use_process_helper_effects() { + let code = r#"#[test(Top)] module Top { + var calls: u32; + function probe(value: input u32) -> u32 { calls += 1; $assert(1'd1); return value; } + initial { $write("%d",probe(1)); $assert(1'd1,"value=%d",probe(2)); $assert(calls == 2); $finish(); } + }"#; + let detailed = Simulator::builder(code, "Top").run_test_detailed().unwrap(); + assert!(detailed.passed, "{detailed:?}"); + assert_eq!(detailed.assertions.len(), 4); + assert_eq!( + detailed.assertions[2].message.as_deref(), + Some(b"value=2".as_slice()) + ); + check_passes_on_every_backend(code); +} + +#[test] +fn loop_and_random_bounds_survive_a_suspending_expression_call() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var random: $tb::random::; + var count: u32; + var value: u8; + function bound(value: input u32) -> u32 { var sample:u8; sample=random.get(); clk.next(); return value + (sample & 0); } + initial { for i in bound(0)..3 { count += 1; } value=random.get_range(7,bound(7)); $assert(count == 3 && value == 7); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn unknown_conditional_helpers_preserve_value_masks_and_both_effects() { + let code = r#"#[test(Top)] module Top(value: output logic<8>, calls: output u32) { + var selector: logic; + function one() -> logic<8> {calls += 1;return 8'haa;} + function two() -> logic<8> {calls += 1;return 8'haf;} + initial {selector=1'bx;value=if selector ? one() : two();$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!( + sim.get_four_state(sim.signal("value")), + (0xafu8.into(), 5u8.into()) + ); + } + macro_rules! backend { + ($build:ident) => { + check( + Simulator::builder(code, "Top") + .four_state(true) + .$build() + .unwrap(), + ) + }; + } + backend!(build_interpreter); + backend!(build_cranelift); + backend!(build_wasm); + backend!(build_tiered); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + backend!(build_native); +} + +#[test] +fn statically_skipped_expression_helpers_do_not_install_clocks() { + let code = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen; + var value: logic; + function wait_on_clk() -> logic { clk.next(); return 1'd1; } + initial { + value = 1'd0 && wait_on_clk(); + value = 1'd1 || wait_on_clk(); + value = if 1'd0 ? wait_on_clk() : 1'd1; + value = if 1'd1 ? 1'd1 : wait_on_clk(); + $assert(clk == 1'd1); $finish(); + } + }"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); +} + +#[test] +fn dirty_break_edges_settle_before_loop_successors() { + let code = r#"#[test(Top)] module Top { + var source: u32; var derived: u32; + assign derived = source + 1; + initial { for i in 0..4 { source = 41; break; } $assert(derived == 42); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn overlapping_function_outputs_copy_in_declaration_order() { + let code = r#"#[test(Top)] module Top { + var value: u32; + function update(a: output u32, b: output u32) { a = 1; b = 2; } + initial { update(value, value); $assert(value == 2); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn finished_paths_do_not_initialize_unreachable_clocks() { + for tail in [ + "$finish(); clk.next();", + "if 1'd1 { $finish(); } clk.next();", + ] { + let code = + format!("#[test(Top)] module Top {{ inst clk: $tb::clock_gen; initial {{ {tail} }} }}"); + let mut sim = Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); + } +} + +#[test] +fn design_finish_during_settle_stops_kernel_continuations() { + let code = r#"#[test(Top)] module Top { + var go: logic; + var after: logic; + always_comb { if go { $finish(); } } + initial { go=1; after=1; $assert(1'd0, "continued after finish"); } + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("after")), 0u8.into()); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +#[test] +fn overlapping_clock_outputs_retain_the_intermediate_rising_edge() { + let code = r#"#[test(Top)] module Top { + var clk: clock; + var q: logic; + function update(a: output clock, b: output clock) { a=1; b=0; } + always_ff (clk) { q=1; } + initial { clk=0; update(clk, clk); $assert(clk == 0); $finish(); } + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + } + for four_state in [false, true] { + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_interpreter() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_cranelift() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top") + .four_state(four_state) + .build_native() + .unwrap(), + ); + } +} + +#[test] +fn conditional_finish_calls_preserve_reachable_clocks() { + for expression in ["if flag ? stop() : 0", "flag && stop()", "!flag || stop()"] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk: $tb::clock_gen; + var flag: logic; + var value: logic; + function stop() -> logic {{ $finish(); return 1; }} + initial {{ flag=0; value={expression}; clk.next(); $finish(); }} + }}"# + ); + check_passes_on_every_backend(&code); + } +} + +#[test] +fn consecutive_reset_helpers_share_the_first_clock_edge() { + for body in [ + "for i in 1..=3 { rst.assert(i); }", + "reset_for(2); reset_for(4);", + ] { + let code = format!( + r#"module Counter(clk: input clock, rst: input reset, q: output u32) {{ + always_ff {{ if_reset {{ q+=1; }} else {{ q+=1; }} }} + }} + #[test(Top)] module Top {{ + inst clk: $tb::clock_gen; inst rst: $tb::reset_gen(clk); var q:u32; + inst dut: Counter(clk,rst,q); + function reset_for(n: input u32) {{ rst.assert(n); }} + initial {{ {body} $assert(q==6,"ticks=%d",q); $finish(); }} + }}"# + ); + check_passes_on_every_backend(&code); + let mut fallback = Simulator::builder(&code, "Top") + .testbench_kernels(false) + .build_interpreter() + .unwrap(); + let tb = compile_initial_testbench(&fallback).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut fallback, &tb), + TestResult::Pass + ); + } +} + +#[test] +fn empty_dynamic_loop_bounds_settle_their_effects() { + let code = r#"#[test(Top)] module Top { + var source:u32; let derived:u32=source+1; var limit:u32; + function bound(value:output u32)->u32 { value=7; return 1; } + initial { limit=0; for i in bound(source)..limit { source=9; } $assert(derived==8); $finish(); } + }"#; + check_passes_on_every_backend(code); +} +#[test] +fn random_arguments_settle_their_effects() { + for op in [ + "random.seed(bound(source));", + "value=random.get_range(bound(source),bound(source));", + ] { + let code = format!( + r#"#[test(Top)] module Top {{ + var random:$tb::random::; var source:u32; let derived:u32=source+1; var value:u32; + function bound(value:output u32)->u32 {{ value=7; return 3; }} + initial {{ {op} $assert(derived==8); $finish(); }} + }}"# + ); + check_passes_on_every_backend(&code); + } +} +#[test] +fn tick_limit_settles_reset_releases_without_domains() { + let code = r#"#[test(Top)] module Top { + inst clk:$tb::clock_gen; inst rst:$tb::reset_gen(clk); let released:logic=rst; + initial { rst.assert(1); $finish(); } + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &tb, 1); + assert_eq!(result.result, TestResult::Pass); + assert_eq!(result.ticks, 1); + assert_eq!(sim.get(sim.signal("rst")), sim.get(sim.signal("released"))); + assert_eq!(sim.get(sim.signal("released")), 1u8.into()); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +#[test] +fn assignment_selection_helpers_use_process_semantics() { + let code = r#"#[test(Top)] module Top { inst clk:$tb::clock_gen; var words:u8[2]; + function index()->u32 { clk.next(); $assert(1,"selected"); return 1; } + initial { words[index()]=7; $assert(words[1]==7); $finish(); } + }"#; + check_passes_on_every_backend(code); +} +#[cfg(feature = "systemverilog")] +#[test] +fn testbench_fallthrough_ignores_background_design_processes() { + let veryl = + "#[test(Top)] module Top { var x:logic; inst dut:$sv::Worker(x); initial { $assert(1); } }"; + let sv = "module Worker(output logic x);initial forever #1 x=~x;endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("top.veryl"))], + vec![(sv, std::path::Path::new("worker.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); +} +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn traced_builds_preserve_kernel_clock_pulses() { + let code = r#"#[test(Top)] module Top {var clk:clock;var q:logic; + function pulse(a:output clock,b:output clock) {a=1;b=0;} always_ff(clk){q=1;} + initial{clk=0;pulse(clk,clk);$finish();} }"#; + let mut sim = Simulator::builder(code, "Top") + .build_with_trace() + .res + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); +} + +#[test] +fn private_assignments_and_event_yields_do_not_replay_clean_comb_logic() { + let count = |body: &str| { + let code = format!( + r#"#[test(Top)] module Top {{ + always_comb {{ $assert(1,"comb"); }} + function helper()->u32 {{var tmp:u32;tmp=1;return tmp;}} + initial {{ {body} $finish(); }} + }}"# + ); + let result = Simulator::builder(&code, "Top") + .run_test_detailed() + .unwrap(); + assert!(result.passed, "{result:?}"); + result + .assertions + .iter() + .filter(|a| a.message.as_deref() == Some(b"comb".as_slice())) + .count() + }; + assert_eq!(count("helper();"), count("")); + assert_eq!(count(&"$assert(1);".repeat(600)), count("")); +} + +#[test] +fn copyback_selection_helpers_resume_for_random_and_function_outputs() { + for action in [ + "words[index()]=random.get_range(7,7);", + "give(words[index()]);", + ] { + let code = format!( + r#"#[test(Top)]module Top{{inst clk:$tb::clock_gen;var random:$tb::random::;var words:u8[2]; + function index()->u32{{clk.next();$assert(1,"index");return 1;}} + function give(value:output u8){{value=7;}} + initial{{{action}$assert(words[1]==7);$finish();}} + }}"# + ); + check_passes_on_every_backend(&code); + } +} +#[test] +fn guaranteed_finish_loops_do_not_register_unreachable_clocks() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{for i in 0..1{$finish();}clk.next();}}"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); +} +#[test] +fn long_clock_waits_drain_design_runtime_events() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:u32;always_ff(clk){$display("edge");q+=1;}initial{clk.next(1500);$assert(q==1500);$finish();}}"#; + check_passes_on_every_backend(code); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn optimized_mixed_testbenches_preserve_sv_process_pulses() { + let veryl = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var q:logic;inst dut:$sv::Pulse(q);initial{clk.next(2);$assert(q==1);$finish();}}"#; + let sv = "module Pulse(output bit q);bit clk;always @(posedge clk)q<=1;initial begin #1;clk=1;clk=0;end endmodule"; + let builder = || { + Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("top.veryl"))], + vec![(sv, std::path::Path::new("pulse.sv"))], + "Top", + ) + .opt_level(celox::OptLevel::O2) + }; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + } + check(builder().build_interpreter().unwrap()); + check(builder().build_cranelift().unwrap()); + check(builder().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(builder().build_native().unwrap()); +} + +#[test] +fn unselected_constant_case_arms_leave_host_clocks_unchanged() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{case 1 {1:{$assert(1);}2:{clk.next();}default:{$assert(0);}}$finish();}}"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); +} + +#[test] +fn fatal_settle_stops_the_continuation_and_other_processes() { + let code = r#"#[test(Top)] module Top { + var go: logic; + var marker: u32; + var later: u32; + var observed: u32; + always_comb { observed = marker + later; $assert(go == 0, "fatal settle"); } + initial { go = 1; if go { marker = 1; } $finish(); } + initial { later = 2; } + }"#; + fn check(mut sim: Simulator) { + let testbench = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench(&mut sim, &testbench); + assert!( + matches!(&result, TestResult::Fail(message) if message.contains("fatal settle")), + "{result:?}" + ); + let marker = sim.signal("marker"); + assert_eq!(sim.backend_ref().get(marker), 0u8.into()); + let later = sim.signal("later"); + assert_eq!(sim.backend_ref().get(later), 0u8.into()); + } + let build = || Simulator::builder(code, "Top"); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn automatic_function_storage_is_reset_on_every_call() { + let code = r#"#[test(Top)] module Top(value:output logic<8>,out:output logic<8>) { + function only_zero(x:input u32, o:output logic<8>) -> logic<8> { + var tmp:logic<8>; + if x==0 { tmp=7; o=tmp; return tmp; } + o=tmp; + } + initial {value=only_zero(0,out);value=only_zero(5,out);$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + for name in ["value", "out"] { + assert_eq!( + sim.get_four_state(sim.signal(name)), + (255u8.into(), 255u8.into()), + "{name}" + ); + } + } + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_interpreter() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_cranelift() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top") + .four_state(true) + .build_native() + .unwrap(), + ); +} + +#[test] +fn specialized_helpers_preserve_expression_storage() { + let code = r#"#[test(Top)] module Top(a:output u32,b:output u32) { + function leaf(x:input u32) -> u32 {return x+20;} + function helper::(x:input logic) -> u32 {return x*10+leaf(x);} + initial {a=helper::<2>(2);b=helper::<1>(1);$assert(helper::<2>(2)==42,"two");$assert(helper::<1>(1)==31,"one");$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("a")), 42u8.into(), "a"); + assert_eq!(sim.get(sim.signal("b")), 31u8.into(), "b"); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +#[test] +fn file_methods_execute_and_evaluate_arguments() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("kernel.txt"); + let code = format!( + r#"#[test(Top)] module Top {{ + var f:$tb::file; var calls:u32; + function value()->u32 {{calls+=1;return 42;}} + function emit() {{f.write("value=%d",value());}} + initial {{calls=0;f.open("{}");emit();f.flush();f.close(); + f.append("{}");f.write("!");f.close();$assert(calls==1);$finish();}} + }}"#, + path.display(), + path.display() + ); + fn check(mut sim: Simulator, path: &std::path::Path) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(std::fs::read(path).unwrap(), b"value=42!"); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top").build_cranelift().unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top").build_wasm().unwrap(), + &path, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&code, "Top").build_native().unwrap(), + &path, + ); +} + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn native_images_preserve_file_host_requests() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("image.txt"); + let code = format!( + r#"#[test(Top)] module Top {{var f:$tb::file;initial{{f.open("{}");f.write("image");f.flush();f.close();$finish();}}}}"#, + path.display() + ); + let original = Simulator::builder(&code, "Top").build_native().unwrap(); + let bytes = original + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = celox::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + let mut sim = Simulator::builder("invalid", "unused") + .build_native_from_image(image) + .unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(std::fs::read(path).unwrap(), b"image"); +} + +#[test] +fn file_io_failures_stop_later_kernel_effects() { + let code = r#"#[test(Top)] module Top(after:output u32) {var f:$tb::file;initial {f.write("closed");after=1;$finish();}}"#; + let mut sim = Simulator::builder(code, "Top").build_interpreter().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_to_finish(&mut sim, &tb); + assert!( + matches!(result,TestResult::Fail(ref message) if message.contains("not open")), + "{result:?}" + ); + assert_eq!(sim.get(sim.signal("after")), 0u8.into()); +} + +#[test] +fn file_arguments_preserve_unknown_automatic_values() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("mask.txt"); + let code = format!( + r#"#[test(Top)] module Top {{var f:$tb::file; + function emit() {{var value:logic<8>;f.write("%h",value);}} + initial{{f.open("{}");emit();f.flush();f.close();$finish();}} + }}"#, + path.display() + ); + fn check(mut sim: Simulator, path: &std::path::Path) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(std::fs::read(path).unwrap(), b"xx"); + } + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_interpreter() + .unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_cranelift() + .unwrap(), + &path, + ); + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_wasm() + .unwrap(), + &path, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&code, "Top") + .four_state(true) + .build_native() + .unwrap(), + &path, + ); +} + +#[test] +fn passing_dynamic_assertions_keep_their_messages() { + let code = r#"#[test(Top)]module Top{var value:logic<8>;initial{value=42;$assert(1,value);$finish();}}"#; + for kernels in [false, true] { + let result = Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .run_test_detailed() + .unwrap(); + assert!(result.passed); + assert_eq!( + result.assertions[0].message.as_deref(), + Some(b"2a".as_slice()) + ); + } +} + +#[test] +fn event_yields_preserve_comb_assertions() { + fn check(mut sim: Simulator, count: usize) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_to_finish(&mut sim, &tb); + let TestResult::Fail(message) = result else { + panic!("expected nonfatal comb assertions"); + }; + assert_eq!( + message.lines().filter(|message| *message == "comb").count(), + count - 1, + "{count}: {}", + std::any::type_name::() + ); + } + for count in [256, 257] { + let code = format!( + r#"#[test(Top)]module Top {{var source:u32;var derived:u32; + always_comb {{derived=source;if(source){{$assert_continue(0,"comb");}}}} + function mark(x:input u32,o:output u32)->u32{{o=x;return 1;}} + initial{{for i in 0..{count}{{$assert(1,"tb %d",mark(i,source));}}$assert(derived=={count}-1,"end");$finish();}} + }}"# + ); + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + count, + ); + check( + Simulator::builder(&code, "Top").build_cranelift().unwrap(), + count, + ); + check( + Simulator::builder(&code, "Top").build_wasm().unwrap(), + count, + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(&code, "Top").build_native().unwrap(), + count, + ); + } +} + +#[test] +fn nested_loop_breaks_do_not_register_clocks_after_outer_finish() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{for i in 0..1{for j in 0..1{break;}$finish();}clk.next();}}"#; + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); + } + let build = || Simulator::builder(code, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn hierarchical_clock_pulses_survive_a_settling_read() { + let code = r#"module Child(clk:input clock,q:output logic){always_ff(clk){q=1;}} + #[test(Top)]module Top{var q:logic;inst dut:Child(q);initial{dut.q=0;dut.clk=1;$assert(dut.q==0);dut.clk=0;}} + "#; + fn check(mut sim: Simulator) { + sim.set(sim.signal("q"), 0u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + for four_state in [false, true] { + let build = || { + Simulator::builder(code, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + check(build().build_native().unwrap()); + let image = build().compile_native().unwrap().into_program_image(); + let image = celox::NativeProgramImage::from_container_bytes( + &image.to_container_bytes().unwrap(), + ) + .unwrap(); + check( + Simulator::from_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + ); + } + } +} + +#[test] +fn terminating_clock_arguments_leave_unreachable_clock_and_reset_untouched() { + for wait in ["clk.next(stop());", "rst.assert(stop());"] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk: $tb::clock_gen; + inst rst: $tb::reset_gen(clk); + function stop()->u32 {{$finish();return 1;}} + initial {{{wait} $assert(0,"continued after finish");}} + }}"# + ); + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + let rst = sim.signal("rst"); + sim.set(clk, 1u8); + sim.set(rst, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(clk), 1u8.into()); + assert_eq!(sim.get(rst), 1u8.into()); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + ); + check(Simulator::builder(&code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(&code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(&code, "Top").build_native().unwrap()); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn bounded_testbench_with_background_delay_returns_after_clock_and_reset_boundary() { + let veryl = r#"#[test(Top)] module Top { + inst clk: $tb::clock_gen #(period: 10); + inst rst: $tb::reset_gen(clk); + var background: u32; + inst worker: $sv::Worker(background); + initial { rst.assert(1); $assert(0,"resumed after budget"); } + initial { clk.next(100); $assert(0,"resumed after budget"); } + }"#; + let sv = + "module Worker(output bit[31:0] background);always #1 background=background+1;endmodule"; + fn check(mut sim: Simulator, limit: u64) { + let tb = compile_initial_testbench(&sim).unwrap(); + let result = run_compiled_testbench_with_tick_limit(&mut sim, &tb, limit); + assert_eq!(result.result, TestResult::Pass); + assert_eq!(result.ticks, limit); + assert!(result.tick_limit_reached); + assert_eq!(sim.get(sim.signal("clk")), 0u8.into()); + assert_eq!(sim.get(sim.signal("rst")), u8::from(limit > 0).into()); + // At time zero the first tick consumes the budget. Background delay + // resumptions are blocked too; only clock falls/releases still drain. + assert_eq!(sim.get(sim.signal("background")), 0u32.into()); + } + for limit in [0, 1] { + let build = || { + Simulator::from_mixed_sources( + vec![(veryl, std::path::Path::new("bounded.veryl"))], + vec![(sv, std::path::Path::new("background.sv"))], + "Top", + ) + }; + check(build().build_interpreter().unwrap(), limit); + check(build().build_cranelift().unwrap(), limit); + check(build().build_wasm().unwrap(), limit); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), limit); + } +} + +#[test] +fn skipped_case_pattern_finish_does_not_hide_a_reachable_clock_wait() { + for (target, helper) in [(1, "$finish();"), (2, "")] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk:$tb::clock_gen; + var q:u32; always_ff(clk) {{q+=1;}} + function later()->u32 {{{helper}return 2;}} + initial {{case {target} {{1:{{$assert({target}==1);}} later():{{$assert({target}==2);}}}} + clk.next(1);$finish();}} + }}"# + ); + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u32.into()); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + ); + check(Simulator::builder(&code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(&code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(&code, "Top").build_native().unwrap()); + } +} + +#[test] +fn repeated_clockless_runs_settle_residual_writes_before_entry_reads() { + let code = r#"#[test(Top)] module Top {var source:u32;var derived:u32; + always_comb {derived=source;} + initial {$assert(derived==source,"entry read");source=1;$finish();} + }"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + for _ in 0..2 { + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + // Raw reads prove the final TB settle happened without a lazy get. + assert_eq!(sim.backend_ref().get_as::(sim.signal("source")), 1); + assert_eq!(sim.backend_ref().get_as::(sim.signal("derived")), 1); + } + } + for kernels in [false, true] { + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_interpreter() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_cranelift() + .unwrap(), + ); + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_wasm() + .unwrap(), + ); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top") + .testbench_kernels(kernels) + .build_native() + .unwrap(), + ); + } +} + +#[test] +fn output_selectors_are_scanned_after_the_timed_callee() { + for (selector, tail) in [ + ( + "$finish(); return 0;", + "unused.next();$assert(0,\"continued after selector finish\");", + ), + ("return 0;", "$assert(words[0]==7); $finish();"), + ] { + let code = format!( + r#"#[test(Top)]module Top {{ + inst clk:$tb::clock_gen;inst unused:$tb::clock_gen;var q:u32;var words:u32[2]; + always_ff(clk){{q+=1;}} + function index()->u32 {{{selector}}} + function give(o:output u32){{clk.next(1);o=7;}} + initial {{give(words[index()]);{tail}}} + }}"# + ); + fn check(mut sim: Simulator) { + sim.set(sim.signal("unused"), 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), 1u32.into()); + assert_eq!(sim.get(sim.signal("unused")), 1u8.into()); + } + check( + Simulator::builder(&code, "Top") + .build_interpreter() + .unwrap(), + ); + check(Simulator::builder(&code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(&code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(&code, "Top").build_native().unwrap()); + } +} + +#[test] +fn runtime_case_scans_only_the_unmatched_path_to_later_patterns() { + let code = r#"#[test(Top)]module Top(choose:input u32){ + inst clk:$tb::clock_gen;inst unused:$tb::clock_gen;var selector:u32;var q:u32; + always_ff(clk){q+=1;} + function stop()->u32{$finish();return 1;} + initial{selector=choose;case selector{0:{}stop():{}default:{unused.next();}} + clk.next(1);$assert(q==1);$finish();} + }"#; + fn check(mut sim: Simulator, input: u32) { + sim.set(sim.signal("unused"), 1u8); + sim.set(sim.signal("choose"), input); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(sim.signal("q")), u32::from(input == 0).into()); + assert_eq!(sim.get(sim.signal("unused")), 1u8.into()); + } + for input in [0, 1] { + check( + Simulator::builder(code, "Top").build_interpreter().unwrap(), + input, + ); + check( + Simulator::builder(code, "Top").build_cranelift().unwrap(), + input, + ); + check(Simulator::builder(code, "Top").build_wasm().unwrap(), input); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check( + Simulator::builder(code, "Top").build_native().unwrap(), + input, + ); + } +} + +#[test] +fn output_selector_scratch_follows_a_looping_callee() { + let code = r#"#[test(Top)] module Top { + var random:$tb::random::; var words:u8[2]; + function index()->u32 { var sample:u8; sample=random.get(); return (sample & 0) as u32; } + function give(value:output u8) { value=0; for i in 0..3 { value+=1; } } + initial { give(words[index()]); $assert(words[0]==3); $finish(); } + }"#; + check_passes_on_every_backend(code); +} + +#[test] +fn value_system_statement_operands_leave_reachable_clocks_registered() { + let code = r#"#[test(Top)] module Top {inst clk:$tb::clock_gen;var q:u32; + always_ff(clk){q+=1;} function stop()->u32{$finish();return 0;} + initial{$bits(stop());clk.next(1);$assert(q==1);$finish();}} + "#; + check_passes_on_every_backend(code); +} +#[test] +fn terminating_assignment_expressions_do_not_lower_their_clock_tail() { + for statement in ["value=stop();", "value=1+stop();", "value=stop()+other();"] { + let code = format!( + r#"#[test(Top)] module Top {{inst clk:$tb::clock_gen;var value:u32; + function stop()->u32{{$finish();return 0;}} function other()->u32{{clk.next();return 1;}} + initial{{{statement}clk.next();}}}}"# + ); + + check_passes_on_every_backend(&code); + } +} + +#[test] +fn clean_random_seed_does_not_replay_combinational_observers() { + let count = |body: &str| { + let code = format!( + r#"#[test(Top)]module Top{{var random:$tb::random::;var source:u8;var derived:u8;always_comb{{derived=source;$assert(1,"comb");}}initial{{source=1;{body}$finish();}}}}"# + ); + let result = Simulator::builder(&code, "Top") + .run_test_detailed() + .unwrap(); + assert!(result.passed, "{result:?}"); + result + .assertions + .iter() + .filter(|a| a.message.as_deref() == Some(b"comb".as_slice())) + .count() + }; + assert_eq!(count("random.seed(7);"), count("")); +} + +#[test] +fn no_op_value_operands_do_not_initialize_an_unused_clock() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;inst unused:$tb::clock_gen; + function hidden()->u32{unused.next();return 0;} + initial{$bits(hidden());clk.next();$finish();}}"#; + fn check(mut sim: Simulator) { + let unused = sim.signal("unused"); + sim.set(unused, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + assert_eq!(sim.get(unused), 1u8.into()); + } + check(Simulator::builder(code, "Top").build_interpreter().unwrap()); + check(Simulator::builder(code, "Top").build_cranelift().unwrap()); + check(Simulator::builder(code, "Top").build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(Simulator::builder(code, "Top").build_native().unwrap()); +} + +#[test] +fn terminating_host_argument_skips_later_clock_argument() { + for call in [ + "value=random.get_range(stop(),later());", + "f.write(\"%d %d\",stop(),later());", + ] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk:$tb::clock_gen; var random:$tb::random::; var f:$tb::file; var value:u32; + function stop()->u32 {{$finish();return 0;}} + function later()->u32 {{clk.next();return 10;}} + initial {{{call}}} + }}"# + ); + check_passes_on_every_backend(&code); + } +} + +#[test] +fn terminating_event_argument_skips_later_clock_argument() { + for call in [ + "$display(\"%d %d\",stop(),later());", + "$write(\"%d %d\",stop(),later());", + "$assert(1,\"%d %d\",stop(),later());", + ] { + let code = format!( + r#"#[test(Top)] module Top {{ + inst clk:$tb::clock_gen; + function stop()->u32 {{$finish();return 0;}} + function later()->u32 {{clk.next();return 10;}} + initial {{{call}}} + }}"# + ); + check_passes_on_every_backend(&code); + } +} + +#[test] +fn terminating_for_start_skips_a_later_clock_bound() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var seed:u32;function stop()->u32{$finish();return seed;}function later()->u32{clk.next();return 2;}initial{for i in stop()..later(){$assert(0);}}}"#; + for source in [ + code.to_owned(), + code.replace("return seed", "return 0"), + code.replace( + "function stop()->u32{$finish();return seed;}", + "function inner()->u32{$finish();return 0;}function stop()->u32{return inner();}", + ), + ] { + check_passes_on_every_backend(&source); + } +} +#[test] +fn zero_clock_count_keeps_helper_design_writes_dirty() { + let code = r#"#[test(Top)]module Top{inst clk:$tb::clock_gen;var source:u32;let derived:u32=source+1;function change(dst:output u32)->u32{dst=7;return 0;}initial{source=1;clk.next(change(source));$assert(derived==source+1);$finish();}}"#; + check_passes_on_every_backend(code); +} +#[test] +fn repeated_hierarchical_clock_edges_keep_their_count() { + let code = r#"module Child(clk:input clock,q:output u32){always_ff(clk){q=q+1;}}#[test(Top)]module Top{var q:u32;inst dut:Child(q);initial{dut.q=0;dut.clk=1;$assert(dut.q==0);dut.clk=0;$assert(dut.q==0);dut.clk=1;$assert(dut.q==0);dut.clk=0;}}"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), 2u8.into()); + } + for four_state in [false, true] { + let build = || { + Simulator::builder(code, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } +} + +#[test] +fn distinct_kernels_add_clock_edge_counts() { + let code = r#"module Child(clk:input clock,q:output u32){always_ff(clk){q=q+1;}}#[test(Top)]module Top{var q:u32;inst dut:Child(q);initial{dut.q=0;dut.clk=1;$assert(dut.q==0);dut.clk=0;}initial{dut.clk=1;$assert(dut.q==0);dut.clk=0;}}"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), 2u8.into()); + } + for four_state in [false, true] { + let build = || { + Simulator::builder(code, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } +} + +#[test] +fn repeated_runs_reset_the_rtl_finish_tracker() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen;var count:u32;var starts:u32;always_ff(clk){count+=1;$finish();}initial{starts+=1;clk.next(2);}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + for run in 1u8..=2 { + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("starts")), run.into()); + } + } + let build = || Simulator::builder(source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn unreachable_breaks_after_finish_do_not_declare_clocks() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen;initial{for i in 0..1{$finish();break;}clk.next();}}"; + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); + } + let build = || Simulator::builder(source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} +#[test] +fn derived_clock_pulses_survive_process_settles() { + for expression in ["go", "go & enable"] { + for four_state in [false, true] { + for pulses in [1, 2] { + let body = "go=1;$assert(q==0);go=0;$assert(q==0);".repeat(pulses); + let source = format!( + "module Child(clk:input clock,q:output u32){{always_ff(clk){{q+=1;}}}}#[test(Top)]module Top{{var go:logic;var enable:logic;let gated:clock={expression};var q:u32;inst dut:Child(clk:gated,q);initial{{enable=1;dut.q=0;{body}}}}}" + ); + fn check(mut sim: Simulator, pulses: usize) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(sim.signal("q")), pulses.into()); + } + let build = || { + Simulator::builder(&source, "Top") + .testbench_kernels(true) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap(), pulses); + check(build().build_cranelift().unwrap(), pulses); + check(build().build_wasm().unwrap(), pulses); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), pulses); + } + } + } +} + +#[test] +fn plain_output_selectors_see_the_callee_final_design_write() { + let source = r#"#[test(Top)]module Top{var source:u32;let index:u32=source;var words:u32[2];function give(value:output u32){value=7;source=1;}initial{source=0;give(words[index]);$assert(words[0]==0,"old index");$assert(words[1]==7,"new index");$finish();}}"#; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + let build = || Simulator::builder(source, "Top"); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn reentrant_output_selectors_preserve_outer_formals() { + let source = "#[test(Top)]module Top{var words:u32[2];function give(v:input u32,o:output u32){o=v;}function index()->u32{var tmp:u32;give(9,tmp);return 0;}initial{give(7,words[index()]);$assert(words[0]==7);$finish();}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + let build = || Simulator::builder(source, "Top"); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn helper_termination_hides_unreachable_loop_breaks() { + for (helper, body) in [ + ("function stop(){$finish();}", "stop();break;"), + ( + "var seed:u32;function stop()->u32{$finish();return seed;}", + "if stop()==seed {break;}", + ), + ] { + let source = format!( + "#[test(Top)]module Top{{inst clk:$tb::clock_gen;{helper}initial{{for i in 0..1{{{body}}}clk.next();}}}}" + ); + fn check(mut sim: Simulator) { + let clk = sim.signal("clk"); + sim.set(clk, 1u8); + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!(run_compiled_testbench(&mut sim, &tb), TestResult::Pass); + assert_eq!(sim.get(clk), 1u8.into()); + } + let build = || Simulator::builder(&source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } +} + +#[test] +fn recorded_pulses_join_the_first_generated_clock_batch() { + let source = "#[test(Top)]module Top{inst clk:$tb::clock_gen #(period:4);var go:clock;var source:u32;var sampled:u32;always_ff(go){source=1;}always_ff(clk){sampled=source;}initial{go=1;go=0;clk.next(1);$assert(source==1);$assert(sampled==0);$finish();}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + } + let derived = source + .replace( + "var source:u32;", + "var source:u32;var enable:logic;let gated:'_ clock=go & enable;", + ) + .replace("always_ff(go)", "always_ff(gated)") + .replace("initial{go=1;", "initial{enable=1;go=1;"); + for source in [source, derived.as_str()] { + let build = || Simulator::builder(source, "Top").testbench_kernels(true); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); + } +} + +#[test] +fn reentrant_output_snapshots_keep_all_masks_and_return_across_waits() { + let source = "#[test(Top)]module Top(words:output logic<16>,other:output logic<8>,result:output logic<8>){inst clk:$tb::clock_gen;function give(v:input logic<8>,a:output logic<8>,b:output logic<8>)->logic<8>{a=v;b=~v;return v;}function index()->u32{var a:logic<8>;var b:logic<8>;var r:logic<8>;r=give(8'h09,a,b);clk.next(1);return 0;}initial{words=0;result=give(8'b10xz0101,words[index()+:8],other);$finish();}}"; + fn check(mut sim: Simulator) { + let tb = compile_initial_testbench(&sim).unwrap(); + assert_eq!( + run_compiled_testbench_to_finish(&mut sim, &tb), + TestResult::Pass + ); + for (name, value, mask) in [ + ("words", 0xa5u32, 0x30u32), + ("other", 0x7a, 0x30), + ("result", 0xa5, 0x30), + ] { + assert_eq!( + sim.get_four_state(sim.signal(name)), + (value.into(), mask.into()), + "{name}" + ); + } + } + let build = || { + Simulator::builder(source, "Top") + .four_state(true) + .testbench_kernels(true) + }; + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} + +#[test] +fn runtime_case_exceptions_do_not_relax_rtl_case_conditions() { + let source = "#[test(Top)]module Top{var label:u32;var q:u32;always_comb{q=0;case 0{label:{q=1;}}}initial{$finish();}}"; + let error = Simulator::builder(source, "Top") + .build_interpreter() + .unwrap_err(); + assert!(format!("{error:?}").contains("CaseCondition"), "{error}"); +} diff --git a/crates/celox/tests/error_detection.rs b/crates/celox/tests/error_detection.rs index 30c2ff92f99..867271c13fc 100644 --- a/crates/celox/tests/error_detection.rs +++ b/crates/celox/tests/error_detection.rs @@ -679,7 +679,41 @@ fn test_selected_testbench_destination_out_of_range_is_rejected() { } #[test] -fn test_expression_testbench_function_selected_destination_is_rejected() { +fn test_selected_hierarchical_destination_out_of_range_is_rejected() { + let code = r#" + module Child (clk: input clock, out: output logic<8>) { + #[allow(unassign_variable)] + var word: logic<8>; + always_ff (clk) { out = word; } + } + #[test(t)] + module t { + inst clk: $tb::clock_gen; + var out: logic<8>; + inst dut: Child (clk, out); + + initial { + dut.word[6 +: 4] = 4'hf; + $finish(); + } + } + "#; + + let err = Simulator::builder(code, "t") + .build() + .expect_err("out-of-range hierarchical selected destination must be rejected"); + match err.kind() { + SimulatorErrorKind::SIRParser(ParserError::IllegalContext { feature, .. }) => { + assert_eq!(*feature, "testbench selected destination"); + } + other => panic!("expected selected destination geometry error, got {other:?}"), + } +} + +#[test] +fn test_expression_testbench_function_selected_destination_runs() { + // A part-select store in an expression-form helper runs in the process + // kernel; the bytecode interpreter rejected it. let code = r#" module Driver (source: output logic<8>) { assign source = 8'h05; @@ -704,18 +738,10 @@ fn test_expression_testbench_function_selected_destination_is_rejected() { } "#; - let err = Simulator::builder(code, "t") - .build() - .expect_err("selected destination in an expression helper must be rejected"); - match err.kind() { - SimulatorErrorKind::SIRParser(ParserError::IllegalContext { feature, .. }) => { - assert_eq!( - *feature, - "selected destination in expression testbench function" - ); - } - other => panic!("expected expression helper selected destination error, got {other:?}"), - } + assert_eq!( + Simulator::builder(code, "t").run_test().unwrap(), + celox::TestResult::Pass + ); } #[test] diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index 7e09ff73e3d..1e5c7ba9127 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -2698,10 +2698,12 @@ fn test_ff_runtime_events_drain_with_per_tick_time() { .iter() .map(|a| a.message.as_deref()) .collect::>(), + // `%t` is the scheduler time: the default clock has period 2, and + // its first edge is at time 0. vec![ - Some(b"ff time=1".as_slice()), + Some(b"ff time=0".as_slice()), Some(b"ff time=2".as_slice()), - Some(b"ff time=3".as_slice()) + Some(b"ff time=4".as_slice()) ], ); } @@ -2722,9 +2724,11 @@ fn test_assert_format_args_render_current_time_for_percent_t() { let detailed = Simulator::builder(code, "t").run_test_detailed().unwrap(); assert!(!detailed.passed); assert_eq!(detailed.assertions.len(), 1); + // Three edges of the default clock (period 2) end at time 4; the + // process resumes one period later. assert_eq!( detailed.assertions[0].message.as_deref(), - Some(b"time=3".as_slice()) + Some(b"time=6".as_slice()) ); } @@ -2901,7 +2905,10 @@ fn test_run_test_stops_on_ff_fatal_runtime_event() { } } "#; - let result = Simulator::builder(code, "t").run_test().unwrap(); + let result = Simulator::builder(code, "t") + .testbench_kernels(false) + .run_test() + .unwrap(); assert_eq!(result, TestResult::Fail("ff fatal".to_string())); } diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 36e6d5400c4..b89f0e1774c 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -821,6 +821,77 @@ fn clock_waits_interleave_with_delays_and_checkpoints() { assert_eq!(sim.get(count), 20u32.into()); } +/// IEEE 1800-2023 Table 9-2: a change from 0, or from x to 1, is a posedge; +/// a change from 1, or from x to 0, is a negedge. +#[test] +fn four_state_edges_count_transitions_into_and_out_of_unknown() { + let bit = ValueType::new(1, false, true).unwrap(); + let byte = ValueType::new(8, false, true).unwrap(); + let mut module = ModuleBuilder::new("UnknownEdges").unwrap(); + // One signal per edge kind, driven alike. + let clk_rising = module.internal("clk_rising", bit).unwrap(); + let clk_falling = module.internal("clk_falling", bit).unwrap(); + let rising = module.output("rising", byte).unwrap(); + let falling = module.output("falling", byte).unwrap(); + for clk in [clk_rising, clk_falling] { + module + .set_initial(clk, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + } + for signal in [rising, falling] { + module + .set_initial(signal, Constant::two_state(0u8, 8).unwrap()) + .unwrap(); + } + let one = constant(&mut module, 1, 8); + for (signal, clk, edge) in [ + (rising, clk_rising, Edge::Posedge), + (falling, clk_falling, Edge::Negedge), + ] { + let value = module.read(signal).unwrap(); + let next = module.binary(BinaryOp::Add, value, one, byte).unwrap(); + let target = module.whole(signal).unwrap(); + module + .register(target, next, clk, edge, None, None) + .unwrap(); + } + let five = constant(&mut module, 5, 8); + let targets = [ + module.whole(clk_rising).unwrap(), + module.whole(clk_falling).unwrap(), + ]; + // 0 -> x -> 1 -> x -> 0 -> x: three posedges and two negedges. + let mut body = Vec::new(); + for (payload, mask) in [(0u8, 1u8), (1, 0), (0, 1), (0, 0), (0, 1)] { + body.push(Statement::Delay { amount: five }); + let value = module.constant(Constant::four_state(payload, mask, 1).unwrap()); + for target in targets { + body.push(Statement::Assign { target, value }); + } + } + // Publish the final sampled edge before terminating. Finish itself must + // not execute FF work after the kernel has requested termination. + body.push(Statement::Delay { amount: five }); + body.push(Statement::Finish); + module.process(body).unwrap(); + let artifact = module.finish(); + + fn check(mut sim: Simulation) { + let rising = sim.signal("rising"); + let falling = sim.signal("falling"); + sim.run_until(100).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(rising), 3u8.into()); + assert_eq!(sim.get(falling), 2u8.into()); + } + let builder = || Simulation::from_frontend(artifact.clone()).four_state(true); + check(builder().build_interpreter().unwrap()); + check(builder().build_cranelift().unwrap()); + check(builder().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(builder().build_native().unwrap()); +} + /// A step whose clock waits ran as fused ticks reports the time it reached. #[test] fn a_fused_step_returns_the_time_it_reached() { diff --git a/crates/celox/tests/state_file.rs b/crates/celox/tests/state_file.rs index 744dc86d4d8..6316844285d 100644 --- a/crates/celox/tests/state_file.rs +++ b/crates/celox/tests/state_file.rs @@ -519,3 +519,49 @@ fn a_failed_load_changes_nothing() { assert_eq!(target.time(), 10); assert_eq!(target.get(b), 3u8.into()); } + +#[test] +fn timed_state_files_preserve_unknown_edge_detection_baselines() { + let code = r#"module Top(clk: input clock, q: output logic<8>) { + always_ff(clk) { q += 1; } + }"#; + for (clock_type, payload, next) in [ + (celox::ClockType::PosEdge, 1u8, 1u8), + (celox::ClockType::NegEdge, 0u8, 0u8), + ] { + let builder = || { + celox::Simulation::builder(code, "Top") + .four_state(true) + .clock_type(clock_type) + .build() + .unwrap() + }; + let mut source = builder(); + let clk = source.signal("clk"); + let q = source.signal("q"); + source + .modify(|io| { + io.set(q, 0u8); + io.set(clk, 0u8); + }) + .unwrap(); + source.settle().unwrap(); + source + .modify(|io| io.set_four_state(clk, payload.into(), 1u8.into())) + .unwrap(); + source.settle().unwrap(); + let expected = source.get(q) + 1u8; + let file = through_bytes(&source.save_state().unwrap()); + assert_eq!( + file.schedule.as_ref().unwrap().unknown_events, + Some(vec!["clk".to_owned()]) + ); + let mut restored = builder(); + restored.load_state(&file).unwrap(); + let clk = restored.signal("clk"); + let q = restored.signal("q"); + restored.modify(|io| io.set(clk, next)).unwrap(); + restored.settle().unwrap(); + assert_eq!(restored.get(q), expected, "{clock_type:?}"); + } +} diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index a45d4f22c4a..2855d50ed87 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -213,7 +213,8 @@ while a process ran, so that a process another one wakes runs before the registers of that time evaluate; this matches the active-region order in which a process woken by a clock edge reads the registers' previous values. It detects the clock edges the processes cause by comparing event signals -before and after, and then settles as for scheduled events. Processes that +before and after (in four-state by IEEE 1800-2023 Table 9-2, so a change +into or out of x or z is an edge), and then settles as for scheduled events. Processes that waited for zero time, or that the settled state wakes, resume in a further round at the same time, which repeats the edge detection and settling; a round in which every waiting process reports a pending wait ends the time. @@ -239,9 +240,32 @@ optimizer does not yet optimize kernels, but it treats their accesses like those of FF domains, so identity aliasing and dead-store elimination keep the state they use. +The `initial` blocks of a Veryl `#[test]` module are compiled into process +kernels in the same way (the `testbench_kernels` option, on by default). The +Veryl frontend lowers each block with its procedural expression lowering +over the elaborated instance's stable state; a hierarchical reference becomes +a synthetic variable of the module that addresses the child's state. A loop +keeps its counter and bounds in hidden state, so a wait inside its body can +suspend the kernel, and each block has its own copy of the module's +function-local variables, so a call that waits keeps its arguments. Because +a kernel writes design state directly, a statement that reads design state +after a store first reports a `settle` status, which has the runtime settle +the combinational logic and resume the kernel at once. `clk.next(n)` is a +clock wait; `rst.assert(n)` is a clock wait with a release, a write the +scheduler makes when the wait ends, so the reset is deasserted even when the +tick budget is spent. Random numbers and the methods of host components are +host requests: the kernel stores the arguments in scratch state, reports the +request's index, and the host serves it through the scratch state, settles +the logic a component's output writes feed, and resumes the kernel at once, +so no other process runs inside the statement. `$assert` emits a runtime event on both outcomes, so the +detailed test result lists every evaluation with its source location. +Formatted `%t` is the scheduler time, in which the default process clock has +period 2. + 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. +bound testbench components, and compiled backend. The backend owns the +finalized layout. Frontend and optimizer state are discarded after +compilation. ## Public API boundary diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index 2afc09c893b..dbb618ce26f 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -186,7 +186,7 @@ for. | `celox-backend-x86` | x86 MIR, instruction selection, target allocation policy, and machine-code emission | Frontend or runtime policy | | `celox-backend-cranelift` | Cranelift translation and JIT construction | Frontend or x86-specific MIR | | `celox-backend-wasm` | WebAssembly module generation | Host runtime behavior | -| `celox-testbench` | Source-independent testbench bytecode and values | Veryl AST traversal or simulator memory ownership | +| `celox-testbench` | Source-independent testbench components, bytecode and values | 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 | @@ -227,7 +227,7 @@ state addresses can now be resolved without consulting Veryl source objects. ### `RuntimeProgram` The source-independent metadata retained after code generation: elaborated design -metadata, public path lookup, runtime schema, and bound testbench bytecode. A +metadata, public path lookup, runtime schema, and bound testbench components. A running `Simulator` stores this artifact beside the executable backend; compiler IR and layout requirements do not remain live during simulation. @@ -249,8 +249,9 @@ The following rules define the intended architecture: their backend; target-independent allocation mechanisms belong in `celox-backend-common`. 6. Runtime code depends on backend contracts, not concrete compiler pipelines. -7. Testbench execution uses source-independent bytecode; only the frontend parses - Veryl testbench syntax. +7. Testbench execution uses process kernels of the runtime schema (or, as a + fallback, source-independent bytecode); only the frontend parses Veryl + testbench syntax. 8. The facade coordinates phases but does not become a second owner of their algorithms or data structures. diff --git a/packages/celox/src/e2e.test.ts b/packages/celox/src/e2e.test.ts index 4017e26217d..e2e0706c903 100644 --- a/packages/celox/src/e2e.test.ts +++ b/packages/celox/src/e2e.test.ts @@ -4018,6 +4018,66 @@ test.each(["step", "run", "bounded"])( }, ); +test("retained NAPI memory cannot inject a generated clock edge", () => { + const artifact = JSON.parse(FRONTEND_FINISH_ARTIFACT); + artifact.format_version = 3; + artifact.signals[0].initial = { + payload: [0], + mask: [], + value_type: artifact.signals[0].value_type, + }; + artifact.signals.push({ + id: 1, + name: "clk", + direction: "Internal", + value_type: { width: 1, signed: false, four_state: false }, + initial: null, + }); + artifact.expressions[0].node.Constant.payload = [1]; + artifact.expressions.push({ + id: 2, + node: { Signal: { signal: 0, lsb: 0, width: 8 } }, + value_type: artifact.signals[0].value_type, + }); + artifact.expressions.push({ + id: 3, + node: { Binary: { op: "Add", lhs: 2, rhs: 0 } }, + value_type: artifact.signals[0].value_type, + }); + artifact.registers = [ + { + target: { signal: 0, lsb: 0, width: 8 }, + next: 3, + clock: 1, + edge: "Posedge", + async_reset: null, + enable: null, + }, + ]; + artifact.clock_periods = [[1, 2]]; + artifact.processes[0].body = [{ ClockCycles: { clock: 1, count: 1 } }]; + const Handle = loadNativeAddon().NativeSimulationHandle; + if (!Handle) throw new Error("native simulation unavailable"); + for (const explicit of [false, true]) { + const raw = Handle.fromFrontendArtifact(JSON.stringify(artifact)); + try { + const memory = raw.sharedMemory(); + const layout = parseNapiLayout(raw.layoutJson).forDut; + raw.runUntil(1); + expect(memory[layout.y.offset]).toBe(1); + memory[layout.clk.offset] = 1; + if (!raw.checkpoint) throw new Error("checkpoint unavailable"); + expect(() => raw.checkpoint?.()).toThrow(/direct host write/); + expect(() => (explicit ? raw.evalComb() : raw.runUntil(2))).toThrow( + /direct host write/, + ); + expect(memory[layout.y.offset]).toBe(1); + } finally { + raw.dispose(); + } + } +}); + test("finished native state files preserve cached outputs after shared writes", () => { const Handle = loadNativeAddon().NativeSimulationHandle; if (!Handle) throw new Error("native simulation unavailable");