From 96dd4066fa1f9761c8a78825e383e8752cc5cc41 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 06:43:19 +0900 Subject: [PATCH 1/7] feat(sim): read a native image's signal identities and force slots NativeProgramImage::signal_identity, signal_aliases, force_slots and has_processes answer from the image what NativeProgramInstance kept to itself, so that a host of a timed Simulation of the image can address and force its signals the same way. Simulation::peek_four_state reads stored state without a settle, and set_observed_signals replaces the signals a slot observer watches. Change-Id: Ice5f5f4d43c2630b20c59540f41548a631556212 --- crates/celox/src/backend/native/backend.rs | 55 ++++++++++++ .../celox/src/backend/native/runtime_image.rs | 89 +++++++------------ crates/celox/src/simulation.rs | 11 +++ 3 files changed, 98 insertions(+), 57 deletions(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 28811acbea5..d20beb9a45c 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -497,6 +497,61 @@ impl NativeProgramImage { &self.design.events } + /// The storage a reflected signal shares with its aliases: its own, or + /// for a clock or reset its canonical event domain's. + pub fn signal_identity( + &self, + id: celox_runtime::ReflectionSignalId, + ) -> Option { + let signal = self.reflection.signal(id)?; + Some(if signal.domain_kind == celox_design::DomainKind::Other { + super::NativeSignalIdentity::State(signal.signal) + } else { + super::NativeSignalIdentity::Event( + self.event_topology().canonical(signal.state_address), + ) + }) + } + + /// Whether the design has process kernels, which only a timed + /// [`crate::Simulation`] runs. + pub fn has_processes(&self) -> bool { + !self.runtime_schema.processes.is_empty() + } + + /// The compiler-inserted override slots of a reflected signal, as + /// (enable, value) pairs: setting the enable makes the design read the + /// value instead of its drivers. + pub fn force_slots( + &self, + id: celox_runtime::ReflectionSignalId, + ) -> Vec<(SignalRef, SignalRef)> { + self.runtime_schema + .force_bindings + .iter() + .filter(|binding| binding.signal == id) + .map(|binding| (binding.enabled, binding.value)) + .collect() + } + + /// Every reflected signal stored at `identity`, in storage order. + pub fn signal_aliases(&self, identity: super::NativeSignalIdentity) -> Vec { + let mut signals = self + .reflection + .signals() + .iter() + .enumerate() + .filter_map(|(index, signal)| { + (self.signal_identity(celox_runtime::ReflectionSignalId(index as u32)) + == Some(identity)) + .then_some(signal.signal) + }) + .collect::>(); + signals.sort_unstable(); + signals.dedup(); + signals + } + /// Reconstruct the source-independent runtime metadata retained by this /// image. No frontend parsing or SIR/layout work is needed on the /// execution side of a host-codegen workflow. diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index f471d653da4..c13435839e2 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use celox_design::{DomainKind, StateAddr}; +use celox_design::StateAddr; use celox_runtime::backend::EventHandle; use celox_runtime::{DesignReflection, ReflectionSignal, SignalRef}; use num_bigint::BigUint; @@ -63,9 +63,13 @@ impl NativeProgramInstance { /// An image with process kernels, which only a timed /// [`crate::Simulation`] runs, fails to attach. pub unsafe fn from_image(image: NativeProgramImage) -> Result { - let schema = image.runtime_schema(); - if !schema.processes.is_empty() { - let origin = schema.process_origins.first().cloned().unwrap_or_default(); + if image.has_processes() { + let origin = image + .runtime_schema() + .process_origins + .first() + .cloned() + .unwrap_or_default(); return Err(NativeProgramLoadError::Attach(SimulatorError::new( crate::SimulatorErrorKind::ProcessRequiresSimulation(origin), ))); @@ -154,17 +158,7 @@ impl NativeProgramInstance { &self, id: celox_runtime::ReflectionSignalId, ) -> Option { - let signal = self.reflection().signal(id)?; - Some(if signal.domain_kind == DomainKind::Other { - NativeSignalIdentity::State(signal.signal) - } else { - NativeSignalIdentity::Event( - self.shared - .program_image() - .event_topology() - .canonical(signal.state_address), - ) - }) + self.shared.program_image().signal_identity(id) } /// Execute combinational logic after one or more foreign writes. @@ -312,25 +306,20 @@ impl NativeProgramInstance { value: BigUint, mask: BigUint, ) -> bool { - let bindings = self - .runtime_schema() - .force_bindings - .iter() - .filter(|binding| binding.signal == id) - .cloned() - .collect::>(); - if !self.shared.supports_forces() && bindings.is_empty() { + let image = self.shared.program_image(); + let slots = image.force_slots(id); + if !self.shared.supports_forces() && slots.is_empty() { return false; } - for binding in bindings { - self.backend - .set_four_state(binding.value, value.clone(), mask.clone()); - self.backend.set(binding.enabled, 1u8); - } - let Some(identity) = self.signal_identity(id) else { + let Some(identity) = image.signal_identity(id) else { return false; }; - let aliases = self.signal_refs_for_identity(identity); + let aliases = image.signal_aliases(identity); + for (enabled, slot) in slots { + self.backend + .set_four_state(slot, value.clone(), mask.clone()); + self.backend.set(enabled, 1u8); + } for signal in aliases { self.backend .set_four_state(signal, value.clone(), mask.clone()); @@ -341,39 +330,23 @@ impl NativeProgramInstance { /// Restore normal design-driver control for a reflected signal. pub fn release_signal(&mut self, id: celox_runtime::ReflectionSignalId) { - let bindings = self - .runtime_schema() - .force_bindings - .iter() - .filter(|binding| binding.signal == id) - .cloned() - .collect::>(); - if !self.shared.supports_forces() && bindings.is_empty() { + let image = self.shared.program_image(); + let slots = image.force_slots(id); + if !self.shared.supports_forces() && slots.is_empty() { return; } - for binding in bindings { - self.backend.set(binding.enabled, 0u8); + let identity = image.signal_identity(id); + for (enabled, _) in slots { + self.backend.set(enabled, 0u8); } - if let Some(identity) = self.signal_identity(id) { + if let Some(identity) = identity { self.forced_values.remove(&identity); } } - fn signal_refs_for_identity(&self, identity: NativeSignalIdentity) -> Vec { - let mut signals = self - .reflection() - .signals() - .iter() - .enumerate() - .filter_map(|(index, signal)| { - (self.signal_identity(celox_runtime::ReflectionSignalId(index as u32)) - == Some(identity)) - .then_some(signal.signal) - }) - .collect::>(); - signals.sort_unstable(); - signals.dedup(); - signals + /// The image this instance runs. + pub fn program_image(&self) -> &NativeProgramImage { + self.shared.program_image() } fn runtime_schema(&self) -> &NativeRuntimeSchema { @@ -479,7 +452,9 @@ impl NativeProgramInstance { .forced_values .iter() .flat_map(|(identity, (value, mask))| { - self.signal_refs_for_identity(*identity) + self.shared + .program_image() + .signal_aliases(*identity) .into_iter() .map(|signal| (signal, value.clone(), mask.clone())) }) diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 59740d44036..a67fc71c16d 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -603,6 +603,12 @@ impl Simulation { value } + /// The stored four-state `(value, mask)` of `signal`, without settling + /// combinational logic first: what host writes and the last settle left. + pub fn peek_four_state(&self, signal: SignalRef) -> (num_bigint::BigUint, num_bigint::BigUint) { + self.simulator.backend.get_four_state(signal) + } + /// Modifies internal state via a callback and re-stabilizes combinational logic. /// /// A write that changes an event signal, and any write while a process @@ -640,6 +646,11 @@ impl Simulation { } } + /// Replace the signals the observer of [`Self::observe_slots`] watches. + pub fn set_observed_signals(&mut self, signals: &[SignalRef]) { + self.state.set_observed_signals(signals.iter().copied()); + } + /// Stop showing the time slots to the observer of /// [`Self::observe_slots`], and return it. pub fn stop_observing_slots(&mut self) -> Option>> { From a4eec8b56032676df4457458d07a0e67b460c554 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 06:43:19 +0900 Subject: [PATCH 2/7] feat(vpi): run SV processes in cocotb images celox vpi build compiles a SystemVerilog design with processes into a timed Simulation image instead of rejecting it, and the executable runs the processes in step with cocotb. Its VPI host drives the simulation through a slot observer: timers and NextTimeStep open a time step, value changes of clocks run before the domains commit, value changes of other signals, ReadWrite and ReadOnly run when the step has settled. A cocotb write is a blocking host write at the current time; the simulation schedules its edges. Designs without processes keep the untimed program instance. Closes #1730 Change-Id: If5f8d9ac914c6dd5b83a1ddd86990dadff1e5f8c --- crates/celox-vpi/src/bin/celox.rs | 67 +++-- crates/celox-vpi/src/callbacks.rs | 220 +++++++++++++++++ crates/celox-vpi/src/driver.rs | 24 +- crates/celox-vpi/src/lib.rs | 201 +++++++++------ crates/celox-vpi/src/state.rs | 230 ++++++++++++++++++ crates/celox-vpi/tests/basic_vpi.rs | 83 +++++++ crates/celox-vpi/tests/cocotb_e2e.rs | 81 ++++++ crates/celox-vpi/tests/diagnostics.rs | 18 +- .../tests/fixtures/cocotb/processes.sv | 17 ++ .../tests/fixtures/cocotb/run_icarus.py | 26 ++ .../tests/fixtures/cocotb/test_processes.py | 61 +++++ crates/celox-vpi/tests/project_cli.rs | 75 ++---- docs/guide/cocotb.md | 34 ++- docs/ja/guide/cocotb.md | 33 ++- 14 files changed, 1003 insertions(+), 167 deletions(-) create mode 100644 crates/celox-vpi/src/state.rs create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/processes.sv create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/run_icarus.py create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/test_processes.py diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 3ac3ac1a18e..d3a2ef7c2aa 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -9,8 +9,7 @@ use std::{ }; use celox::{ - NativeProgramImage, NativeProgramInstance, StateDifference, StateFile, StateObject, StateRole, - format_state_value, + NativeProgramImage, StateDifference, StateFile, StateObject, StateRole, format_state_value, }; use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand}; @@ -395,27 +394,60 @@ fn build(arguments: BuildArgs) -> Result<(), String> { Ok(()) } +/// The SystemVerilog compilation options of `design`. +#[cfg(feature = "systemverilog")] +fn configure_sv<'a, T>( + design: &'a Design, + builder: celox::SimulatorBuilder<'a, T>, +) -> celox::SimulatorBuilder<'a, T> { + let builder = builder + .four_state(design.four_state.unwrap_or(false)) + .diagnostic_policy(design.diagnostics.clone()) + .sv_timescale(design.timescale) + .signal_access(design.signal_access.clone()) + .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); + design.apply_parameters(builder) +} + fn compile_native_design(design: &Design) -> Result { if design.is_sv() { #[cfg(feature = "systemverilog")] { let sources = design.sv_sources()?; - let refs = sources + let refs: Vec<_> = sources .iter() .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); - let builder = celox::Simulator::from_sv_sources(refs, &design.top) - .four_state(design.four_state.unwrap_or(false)) - .diagnostic_policy(design.diagnostics.clone()) - .sv_timescale(design.timescale) - .signal_access(design.signal_access.clone()) - .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); - let simulator = design - .apply_parameters(builder) - .compile_native() - .map_err(|error| format!("compilation failed:\n{error}"))?; - report_warnings(simulator.warnings())?; - return Ok(simulator.into_program_image()); + let untimed = configure_sv( + design, + celox::Simulator::from_sv_sources(refs.clone(), &design.top), + ) + .compile_native(); + let image = match untimed { + Ok(simulator) => { + report_warnings(simulator.warnings())?; + simulator.into_program_image() + } + // A design with processes runs as a timed simulation, in step + // with the VPI time callbacks. + Err(error) + if matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ) => + { + let simulation = configure_sv( + design, + celox::Simulation::from_sv_sources(refs, &design.top), + ) + .compile_native() + .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulation.warnings())?; + simulation.into_program_image() + } + Err(error) => return Err(format!("compilation failed:\n{error}")), + }; + return Ok(image); } #[cfg(not(feature = "systemverilog"))] return Err( @@ -690,10 +722,7 @@ fn run_simulation(image: NativeProgramImage, arguments: SimulationArgs) -> Resul } set_environment("COCOTB_RESULTS_FILE", &results_file); - // Safety: the image is compiler-produced data attached to this executable. - let instance = unsafe { NativeProgramInstance::from_image(image) } - .map_err(|error| format!("failed to load attached design: {error}"))?; - celox_vpi::driver::run_cocotb(instance, &vpi)?; + celox_vpi::driver::run_cocotb_image(image, &vpi)?; check_results(&python, &results_file) } diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index cf97ddd89e4..af699a4ac56 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -85,6 +85,8 @@ pub(super) struct CallbackState { time: u64, pub(super) finish: bool, pub(super) running: bool, + /// The time whose ReadOnly region a timed simulation ran last. + read_only_at: Option, pub(super) detach_on_stop: bool, error: Option, } @@ -388,6 +390,224 @@ pub(super) fn run() -> bool { finished } +/// The signals of the value-change callbacks: those whose edges a timed +/// simulation shows before its domains commit. +fn watched_signals() -> Vec { + let selections = with_host(|host| { + borrow_cell(&host.callbacks, |state| { + state + .callbacks + .values() + .filter_map(|registration| callback_signal(®istration.data)) + .collect::>() + }) + }); + super::with_runtime(|runtime| { + selections + .into_iter() + .filter_map(|selection| selection.signal(runtime)) + .collect() + }) + .unwrap_or_default() +} + +fn set_time(time: u64) { + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.time = time)); +} + +fn current_time() -> u64 { + with_host(|host| borrow_cell(&host.callbacks, |state| state.time)) +} + +/// Whether a VPI write changed the timed simulation since the last call. +fn take_timed_writes() -> bool { + super::with_timed_mut(super::TimedRuntime::take_wrote).unwrap_or(false) +} + +/// What the regions after a slot's processes reached. +enum Regions { + /// A callback wrote: the simulation settles the writes at the same + /// time, and the regions start again. + Wrote, + /// Every region ran; the next is the next time. + Done, +} + +/// The regions of a settled time slot: value changes, then ReadWrite until +/// the callbacks write nothing, then ReadOnly (IEEE 1800-2023 4.4.2). +fn settled_regions() -> Regions { + take_timed_writes(); + loop { + if finish_requested() { + return Regions::Done; + } + if dispatch_value_changes() { + if take_timed_writes() { + return Regions::Wrote; + } + continue; + } + let read_write = registration_ids(CB_READ_WRITE_SYNCH); + if read_write.is_empty() { + break; + } + for id in read_write { + fire(id); + if finish_requested() { + return Regions::Done; + } + } + if take_timed_writes() { + return Regions::Wrote; + } + } + fire_all(CB_READ_ONLY_SYNCH); + with_host(|host| { + borrow_cell_mut(&host.callbacks, |state| { + state.read_only_at = Some(state.time) + }) + }); + Regions::Done +} + +/// Shows a timed simulation's slots to the VPI callbacks: value changes of +/// clocks before the domains commit, and the regions of each settled slot. +struct TimedObserver; + +impl celox::SlotObserver for TimedObserver { + fn before_domains(&mut self, io: &mut celox::SlotIo<'_, celox::NativeBackend>, time: u64) { + in_slot(io, time, || { + dispatch_value_changes(); + }); + } + + fn end_of_slot(&mut self, io: &mut celox::SlotIo<'_, celox::NativeBackend>, time: u64) { + in_slot(io, time, || { + settled_regions(); + }); + } +} + +/// Run `regions` with the VPI entry points reaching the state through `io`. +fn in_slot(io: &mut celox::SlotIo<'_, celox::NativeBackend>, time: u64, regions: impl FnOnce()) { + set_time(time); + // Safety: `io` outlives the dispatch below and nothing else uses it until + // `leave_slot`. + super::with_timed_mut(|timed| unsafe { timed.enter_slot(io) }); + regions(); + super::with_timed_mut(super::TimedRuntime::leave_slot); +} + +/// Run `step` on the timed simulation, out of the session while it runs so +/// that its observer's callbacks can reach the VPI entry points. +fn timed_step( + step: impl FnOnce( + &mut celox::Simulation, + ) -> Result<(), celox::RuntimeErrorCode>, +) { + let watched = watched_signals(); + let Some(mut simulation) = super::with_timed_mut(|timed| timed.simulation.take()).flatten() + else { + return; + }; + simulation.set_observed_signals(&watched); + let result = step(&mut simulation); + let ended = simulation.is_finished() || simulation.is_stopped(); + super::with_timed_mut(|timed| timed.simulation = Some(simulation)); + super::process_runtime_events(); + if let Err(error) = result { + fail(format!("simulation failed: {error}")); + } else if ended { + // `$stop` ends a run that has no interactive mode, as `vpiStop` does. + request_finish(); + } +} + +fn with_simulation( + operation: impl FnOnce(&mut celox::Simulation) -> R, +) -> Option { + super::with_timed_mut(|timed| timed.simulation.as_mut().map(operation)).flatten() +} + +/// The VPI regions of every time slot of a timed simulation, until +/// `vpiFinish`, the design's `$finish`, or no activity remains. +pub(super) fn run_timed() -> bool { + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.running = true)); + if let Some(Some(mut simulation)) = super::with_timed_mut(|timed| timed.simulation.take()) { + simulation.observe_slots(Box::new(TimedObserver), &[]); + super::with_timed_mut(|timed| timed.simulation = Some(simulation)); + } + fire_all(CB_START_OF_SIMULATION); + let mut iterations = 0usize; + while !finish_requested() { + iterations += 1; + if iterations > 1_000_000 { + fail( + "VPI callback scheduler exceeded 1000000 iterations without advancing time" + .to_string(), + ); + break; + } + let due = with_host(|host| { + borrow_cell(&host.callbacks, |state| { + state + .callbacks + .values() + .filter_map(|registration| registration.due) + .min() + }) + }); + let event = with_simulation(|simulation| simulation.next_event_time()).flatten(); + let Some(time) = due.into_iter().chain(event).min() else { + break; + }; + if time > current_time() { + timed_step(|simulation| simulation.advance_to(time)); + if finish_requested() { + break; + } + set_time(time); + iterations = 0; + fire_all(CB_NEXT_SIM_TIME); + } + for id in due_ids() { + fire(id); + if finish_requested() { + break; + } + } + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.read_only_at = None)); + timed_step(|simulation| simulation.run_until(time)); + // The slot ran no regions when nothing but callbacks happened at + // this time: run them here, settling what they write. + while !finish_requested() + && with_host(|host| borrow_cell(&host.callbacks, |state| state.read_only_at)) + != Some(time) + { + with_simulation(|simulation| simulation.eval_comb()); + take_timed_writes(); + if let Regions::Done = settled_regions() { + break; + } + timed_step(|simulation| simulation.run_until(time)); + iterations += 1; + if iterations > 1_000_000 { + fail( + "VPI callback scheduler exceeded 1000000 iterations without advancing time" + .to_string(), + ); + break; + } + } + } + let finished = finish_requested(); + for id in registration_ids(CB_END_OF_SIMULATION) { + fire(id); + } + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.running = false)); + finished +} + pub(super) fn is_running() -> bool { with_host(|host| borrow_cell(&host.callbacks, |state| state.running)) } diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index c7bd819169c..a0acb886ee0 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -182,7 +182,29 @@ fn compile_native_image_configured( /// Run cocotb's VPI bootstrap against a compiled native program instance. pub fn run_cocotb(instance: NativeProgramInstance, vpi_path: &Path) -> Result<(), String> { - let _session = crate::install_runtime(instance)?; + run_session(crate::install_runtime(instance)?, vpi_path) +} + +/// Run cocotb's VPI bootstrap against the design of a native image: a +/// timed simulation when the design has processes, so that they run in step +/// with the VPI time callbacks, and an untimed program instance otherwise. +pub fn run_cocotb_image(image: celox::NativeProgramImage, vpi_path: &Path) -> Result<(), String> { + let session = if image.has_processes() { + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .map_err(|error| format!("failed to load attached design: {error}"))?; + crate::install_timed_runtime(image, simulation)? + } else { + // Safety: the image is compiler-produced data attached to this + // executable. + let instance = unsafe { NativeProgramInstance::from_image(image) } + .map_err(|error| format!("failed to load attached design: {error}"))?; + crate::install_runtime(instance)? + }; + run_session(session, vpi_path) +} + +fn run_session(_session: crate::VpiSession, vpi_path: &Path) -> Result<(), String> { // Safety: cocotb's VPI library is kept loaded throughout all callbacks and // its documented bootstrap takes no arguments. let library = match unsafe { Library::new(vpi_path) } { diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 39fe402c1c4..c5d85c07617 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -21,12 +21,14 @@ use std::{ use celox::{ BigUint, DomainKind, NativeProgramInstance, NativeSignalIdentity, ReflectionScopeId, - ReflectionSignalId, RuntimeEvent, RuntimeFormatContext, Severity, SignalDirection, SimBackend, + ReflectionSignalId, RuntimeEvent, RuntimeFormatContext, Severity, SignalDirection, }; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; mod callbacks; pub mod driver; +mod state; + pub use callbacks::{ CB_AFTER_DELAY, CB_END_OF_SIMULATION, CB_NEXT_SIM_TIME, CB_READ_ONLY_SYNCH, CB_READ_WRITE_SYNCH, CB_START_OF_SIMULATION, CB_VALUE_CHANGE, VPI_SCALED_REAL_TIME, @@ -34,6 +36,7 @@ pub use callbacks::{ celox_vpi_current_time, vpi_chk_error, vpi_control, vpi_get_time, vpi_get_vlog_info, vpi_handle_by_index, vpi_register_cb, vpi_remove_cb, }; +use state::{Runtime, TimedRuntime, VpiState}; pub const VPI_BIN_STR_VAL: i32 = 1; pub const VPI_HEX_STR_VAL: i32 = 4; @@ -139,7 +142,7 @@ impl SignalSelection { } /// Resolve storage without cloning hierarchy names or dimension metadata. - fn signal(self, runtime: &NativeProgramInstance) -> Option { + fn signal(self, runtime: &dyn VpiState) -> Option { let root = runtime.reflection().signal(self.root)?; let mut signal = root.signal; if self.depth == 0 { @@ -165,7 +168,7 @@ impl SignalSelection { Some(signal) } - fn domain_kind(self, runtime: &NativeProgramInstance) -> Option { + fn domain_kind(self, runtime: &dyn VpiState) -> Option { let root = runtime.reflection().signal(self.root)?; Some(if self.depth == 0 { root.domain_kind @@ -174,7 +177,7 @@ impl SignalSelection { }) } - fn resolve(self, runtime: &NativeProgramInstance) -> Option { + fn resolve(self, runtime: &dyn VpiState) -> Option { let mut signal = runtime.reflection().signal(self.root)?.clone(); signal.signal = self.signal(runtime)?; if self.depth == 0 { @@ -205,7 +208,7 @@ impl SignalSelection { Some(signal) } - fn select(self, runtime: &NativeProgramInstance, index: i32) -> Option { + fn select(self, runtime: &dyn VpiState, index: i32) -> Option { let root = runtime.reflection().signal(self.root)?; let &(left, right) = root.unpacked_ranges.get(self.depth)?; let index = i128::from(index); @@ -232,7 +235,7 @@ impl SignalSelection { // Some arrays use contiguous bits instead of a byte stride (including // scalar arrays and arrays whose uses cannot be lowered as strided loads). - fn slice(self, runtime: &NativeProgramInstance) -> Option<(usize, usize)> { + fn slice(self, runtime: &dyn VpiState) -> Option<(usize, usize)> { let root = runtime.reflection().signal(self.root)?; if self.depth == 0 || root.signal.array_layout.is_some() { return None; @@ -246,7 +249,7 @@ impl SignalSelection { Some((self.first * element_width, remaining * element_width)) } - fn width(self, runtime: &NativeProgramInstance) -> Option { + fn width(self, runtime: &dyn VpiState) -> Option { if let Some((_, width)) = self.slice(runtime) { Some(width) } else { @@ -254,7 +257,7 @@ impl SignalSelection { } } - fn identity(self, runtime: &NativeProgramInstance) -> Option { + fn identity(self, runtime: &dyn VpiState) -> Option { let storage = if self.depth == 0 || self.slice(runtime).is_some() { runtime.signal_identity(self.root)? } else { @@ -266,38 +269,38 @@ impl SignalSelection { }) } - fn read(self, runtime: &NativeProgramInstance) -> Option<(BigUint, BigUint)> { + fn read(self, runtime: &dyn VpiState) -> Option<(BigUint, BigUint)> { let signal = self.signal(runtime)?; let Some((offset, width)) = self.slice(runtime) else { - return Some(runtime.backend().get_four_state(signal)); + return Some(runtime.get_four_state(signal)); }; let (window, shift) = bit_window(signal, offset, width); let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); - let bits = (runtime.backend().get_four_state(window).0 >> shift) & &mask; + let bits = (runtime.get_four_state(window).0 >> shift) & &mask; let unknowns = if signal.is_4state && runtime.four_state() { let mut mask_window = window; mask_window.offset += signal.width.div_ceil(8); - (runtime.backend().get_four_state(mask_window).0 >> shift) & mask + (runtime.get_four_state(mask_window).0 >> shift) & mask } else { BigUint::default() }; Some((bits, unknowns)) } - fn write(self, runtime: &mut NativeProgramInstance, bits: BigUint, mask: BigUint) { + fn write(self, runtime: &mut dyn VpiState, bits: BigUint, mask: BigUint) { let Some(signal) = self.signal(runtime) else { return; }; let Some((offset, width)) = self.slice(runtime) else { - runtime.backend_mut().set_four_state(signal, bits, mask); + runtime.set_four_state(signal, bits, mask); return; }; let (window, shift) = bit_window(signal, offset, width); let selected = ((BigUint::from(1u8) << width) - BigUint::from(1u8)) << shift; let whole = (BigUint::from(1u8) << window.width) - BigUint::from(1u8); let retained = &whole ^ &selected; - let old = runtime.backend().get_four_state(window).0; - runtime.backend_mut().set_four_state( + let old = runtime.get_four_state(window).0; + runtime.set_four_state( window, (old & &retained) | ((bits << shift) & &selected), BigUint::default(), @@ -305,8 +308,8 @@ impl SignalSelection { if signal.is_4state && runtime.four_state() { let mut mask_window = window; mask_window.offset += signal.width.div_ceil(8); - let old = runtime.backend().get_four_state(mask_window).0; - runtime.backend_mut().set_four_state( + let old = runtime.get_four_state(mask_window).0; + runtime.set_four_state( mask_window, (old & retained) | ((mask << shift) & selected), BigUint::default(), @@ -362,7 +365,7 @@ pub type VpiHandle = *mut VpiHandleObject; /// per process because standard VPI entry points carry no host context. #[derive(Default)] struct VpiHost { - runtime: RefCell>, + runtime: RefCell>, forced_values: RefCell>, pending_writes: RefCell, callbacks: RefCell, @@ -620,8 +623,22 @@ fn apply_pending_deposits( /// guard for the entire plugin lifetime. Overlapping sessions are rejected, /// including installation from a callback before its current host has stopped. pub fn install_runtime(instance: NativeProgramInstance) -> Result { + install(Runtime::Untimed(instance)) +} + +/// Install a timed simulation of `image`, which runs the design's processes +/// in step with the VPI time callbacks. Retain the returned guard as for +/// [`install_runtime`]. +pub fn install_timed_runtime( + image: celox::NativeProgramImage, + simulation: celox::Simulation, +) -> Result { + install(Runtime::Timed(TimedRuntime::new(image, simulation))) +} + +fn install(runtime: Runtime) -> Result { let mut host = VpiHost::default(); - *host.runtime.get_mut() = Some(instance); + *host.runtime.get_mut() = Some(runtime); let host = std::rc::Rc::new(host); let mut active = ACTIVE_HOST .lock() @@ -692,7 +709,12 @@ pub fn run_callbacks_result() -> Result { if let Some(error) = callbacks::take_error() { return Err(error); } - let finished = callbacks::run(); + let timed = with_timed_mut(|_| ()).is_some(); + let finished = if timed { + callbacks::run_timed() + } else { + callbacks::run() + }; let error = callbacks::take_error(); if with_host(|host| borrow_cell(&host.callbacks, |state| state.detach_on_stop)) { clear_runtime(); @@ -719,12 +741,43 @@ pub extern "C" fn celox_vpi_load_current_executable() -> i32 { } } -fn with_runtime(operation: impl FnOnce(&NativeProgramInstance) -> R) -> Option { - with_host(|host| borrow_cell(&host.runtime, |runtime| runtime.as_ref().map(operation))) +fn with_runtime(operation: impl FnOnce(&dyn VpiState) -> R) -> Option { + with_host(|host| { + borrow_cell(&host.runtime, |runtime| { + runtime.as_ref().map(|runtime| operation(runtime.state())) + }) + }) +} + +fn with_runtime_mut(operation: impl FnOnce(&mut dyn VpiState) -> R) -> Option { + with_host(|host| { + borrow_cell_mut(&host.runtime, |runtime| { + runtime + .as_mut() + .map(|runtime| operation(runtime.state_mut())) + }) + }) } -fn with_runtime_mut(operation: impl FnOnce(&mut NativeProgramInstance) -> R) -> Option { - with_host(|host| borrow_cell_mut(&host.runtime, |runtime| runtime.as_mut().map(operation))) +/// The untimed program instance of the session, whose regions the VPI host +/// schedules itself; `None` for a timed simulation. +fn with_instance_mut(operation: impl FnOnce(&mut NativeProgramInstance) -> R) -> Option { + with_host(|host| { + borrow_cell_mut(&host.runtime, |runtime| match runtime { + Some(Runtime::Untimed(instance)) => Some(operation(instance)), + _ => None, + }) + }) +} + +/// The timed runtime of the session, if it has one. +fn with_timed_mut(operation: impl FnOnce(&mut TimedRuntime) -> R) -> Option { + with_host(|host| { + borrow_cell_mut(&host.runtime, |runtime| match runtime { + Some(Runtime::Timed(timed)) => Some(operation(timed)), + _ => None, + }) + }) } fn c_string(value: &str) -> CString { @@ -1185,7 +1238,7 @@ pub unsafe extern "C" fn vpi_get_str(property: i32, reference: VpiHandle) -> *mu fn value_bits(id: SignalSelection) -> Option<(BigUint, BigUint, usize)> { with_host(|host| { borrow_cell(&host.runtime, |runtime| { - let runtime = runtime.as_ref()?; + let runtime = runtime.as_ref()?.state(); let signal = runtime.reflection().signal(id.root)?; if id.depth != signal.unpacked_dims.len() { return None; @@ -1538,27 +1591,27 @@ pub unsafe extern "C" fn vpi_put_value( } else { (released.deposited_value, released.deposited_mask) }; - runtime.release_signal(id.root); - let (old_value, old_mask) = runtime.backend().get_four_state(signal.signal); - let old_level = logic_level(&old_value, &old_mask); - let new_level = logic_level(&released_value, &released_mask); - with_host(|host| { - borrow_cell_mut(&host.pending_writes, |pending| { - record_pending_write( - pending, - id, - identity, - released_value.clone(), - released_mask.clone(), - signal.domain_kind, - old_level, - new_level, - ); - }) - }); - runtime - .backend_mut() - .set_four_state(signal.signal, released_value, released_mask); + runtime.release(id.root); + if runtime.schedules_writes() { + let (old_value, old_mask) = runtime.get_four_state(signal.signal); + let old_level = logic_level(&old_value, &old_mask); + let new_level = logic_level(&released_value, &released_mask); + with_host(|host| { + borrow_cell_mut(&host.pending_writes, |pending| { + record_pending_write( + pending, + id, + identity, + released_value.clone(), + released_mask.clone(), + signal.domain_kind, + old_level, + new_level, + ); + }) + }); + } + runtime.set_four_state(signal.signal, released_value, released_mask); true }) .unwrap_or(false) @@ -1609,8 +1662,7 @@ pub unsafe extern "C" fn vpi_put_value( }) }) .or_else(|| { - with_runtime(|runtime| Some(runtime.backend().get_four_state(id.signal(runtime)?))) - .flatten() + with_runtime(|runtime| Some(runtime.get_four_state(id.signal(runtime)?))).flatten() }); let Some((deposited_value, deposited_mask)) = deposited else { return ptr::null_mut(); @@ -1639,26 +1691,29 @@ pub unsafe extern "C" fn vpi_put_value( let old_level = logic_level(&old_value, &old_mask); let new_level = logic_level(&bits, &mask); if flags == VPI_FORCE_FLAG { - if !runtime.force_signal(id.root, bits.clone(), mask.clone()) { + if !runtime.force(id.root, bits.clone(), mask.clone()) { return false; } } else { id.write(runtime, bits.clone(), mask.clone()); } - with_host(|host| { - borrow_cell_mut(&host.pending_writes, |pending| { - record_pending_write( - pending, - id, - identity, - bits.clone(), - mask.clone(), - domain_kind, - old_level, - new_level, - ); - }) - }); + // A timed simulation schedules the edges of its host writes itself. + if runtime.schedules_writes() { + with_host(|host| { + borrow_cell_mut(&host.pending_writes, |pending| { + record_pending_write( + pending, + id, + identity, + bits.clone(), + mask.clone(), + domain_kind, + old_level, + new_level, + ); + }) + }); + } true }) .unwrap_or(false); @@ -1701,7 +1756,7 @@ fn flush_pending_writes() -> bool { let overridden = replay_overrides.keys().copied().collect::>(); let running = callbacks::is_running(); let result: Result, celox::RuntimeErrorCode> = - with_runtime_mut(|runtime| { + with_instance_mut(|runtime| { let active_edges = batch .active_signals .into_iter() @@ -1709,8 +1764,7 @@ fn flush_pending_writes() -> bool { let deposit = batch.deposits.get(&identity)?; let signal = deposit.id.resolve(runtime)?; if overridden.contains(&identity) { - let (old_value, old_mask) = - runtime.backend().get_four_state(signal.signal); + let (old_value, old_mask) = runtime.get_four_state(signal.signal); if !is_active_edge( signal.domain_kind, logic_level(&old_value, &old_mask), @@ -1757,7 +1811,7 @@ fn flush_pending_writes() -> bool { } let wrote_inputs = with_host(|host| borrow_cell(&host.pending_writes, |pending| pending.settle)); - let result = with_runtime_mut(|runtime| { + let result = with_instance_mut(|runtime| { let context = RuntimeFormatContext { tb_time: Some(celox_vpi_current_time()), scope: None, @@ -1813,7 +1867,7 @@ fn flush_pending_writes() -> bool { } } } - let result: Result<(), celox::RuntimeErrorCode> = with_runtime_mut(|runtime| { + let result: Result<(), celox::RuntimeErrorCode> = with_instance_mut(|runtime| { apply_pending_deposits(runtime, &final_deposits); runtime.settle_active_edges_with_context( &[], @@ -1834,10 +1888,11 @@ fn flush_pending_writes() -> bool { fn process_runtime_events() { let time = celox_vpi_current_time(); - let events = with_runtime_mut(|runtime| { - runtime.drain_runtime_events_with_context(RuntimeFormatContext { - tb_time: Some(time), - scope: None, + let events = with_host(|host| { + borrow_cell_mut(&host.runtime, |runtime| { + runtime + .as_mut() + .map(|runtime| runtime.drain_runtime_events(time)) }) }) .unwrap_or_default(); diff --git a/crates/celox-vpi/src/state.rs b/crates/celox-vpi/src/state.rs new file mode 100644 index 00000000000..76248f8cb2b --- /dev/null +++ b/crates/celox-vpi/src/state.rs @@ -0,0 +1,230 @@ +//! The design state behind the VPI entry points: an untimed program +//! instance, whose regions the VPI host schedules itself, or a timed +//! simulation, which runs the design's processes and schedules its regions. + +use celox::{ + BigUint, DesignReflection, NativeBackend, NativeProgramImage, NativeProgramInstance, + NativeSignalIdentity, ReflectionSignalId, RuntimeEvent, RuntimeFormatContext, SignalRef, + SimBackend, Simulation, SlotIo, +}; + +/// What the VPI entry points read and write. +pub(crate) trait VpiState { + /// The image the state belongs to: its reflection and layout. + fn image(&self) -> &NativeProgramImage; + + fn reflection(&self) -> &DesignReflection { + self.image().reflection() + } + + fn time_precision(&self) -> celox_design::TimePrecision { + self.image().time_precision() + } + + fn four_state(&self) -> bool { + self.image().four_state() + } + + fn signal_identity(&self, id: ReflectionSignalId) -> Option { + self.image().signal_identity(id) + } + + /// The stored value, without settling the design. + fn get_four_state(&self, signal: SignalRef) -> (BigUint, BigUint); + + fn set_four_state(&mut self, signal: SignalRef, value: BigUint, mask: BigUint); + + /// Override a signal until [`Self::release`]; `false` when it cannot be + /// forced. + fn force(&mut self, id: ReflectionSignalId, value: BigUint, mask: BigUint) -> bool; + + fn release(&mut self, id: ReflectionSignalId); + + /// Whether the VPI host schedules the settles and edges of its writes, + /// rather than a timed simulation doing it. + fn schedules_writes(&self) -> bool; +} + +impl VpiState for NativeProgramInstance { + fn image(&self) -> &NativeProgramImage { + self.program_image() + } + + fn get_four_state(&self, signal: SignalRef) -> (BigUint, BigUint) { + self.backend().get_four_state(signal) + } + + fn set_four_state(&mut self, signal: SignalRef, value: BigUint, mask: BigUint) { + self.backend_mut().set_four_state(signal, value, mask); + } + + fn force(&mut self, id: ReflectionSignalId, value: BigUint, mask: BigUint) -> bool { + self.force_signal(id, value, mask) + } + + fn release(&mut self, id: ReflectionSignalId) { + self.release_signal(id); + } + + fn schedules_writes(&self) -> bool { + true + } +} + +/// A timed simulation of a native image with processes. +/// +/// While a step runs, the simulation is out of `simulation`, and the VPI +/// entry points that its slot observer's callbacks call reach the state +/// through `slot`, which the observer sets for the duration of a dispatch. +pub(crate) struct TimedRuntime { + image: NativeProgramImage, + pub(crate) simulation: Option>, + slot: Option<*mut SlotIo<'static, NativeBackend>>, + /// A VPI write since the last [`Self::take_wrote`]. + wrote: bool, +} + +impl TimedRuntime { + pub(crate) fn new(image: NativeProgramImage, simulation: Simulation) -> Self { + Self { + image, + simulation: Some(simulation), + slot: None, + wrote: false, + } + } + + /// Whether a VPI write changed state since the last call. + pub(crate) fn take_wrote(&mut self) -> bool { + std::mem::take(&mut self.wrote) + } + + /// Reach the state through `slot` until [`Self::leave_slot`]. + /// + /// # Safety + /// + /// `slot` must stay live and unaliased until [`Self::leave_slot`]. + pub(crate) unsafe fn enter_slot(&mut self, slot: &mut SlotIo<'_, NativeBackend>) { + let slot: *mut SlotIo<'_, NativeBackend> = slot; + self.slot = Some(slot.cast()); + } + + pub(crate) fn leave_slot(&mut self) { + self.slot = None; + } + + /// The runtime events of the simulation since the last call; none while + /// a step runs, which drains them when it returns. + pub(crate) fn drain_runtime_events(&mut self) -> Vec { + self.simulation + .as_mut() + .map(Simulation::drain_runtime_events) + .unwrap_or_default() + } + + fn slot(&self) -> Option<&SlotIo<'static, NativeBackend>> { + // Safety: `enter_slot`'s caller keeps the slot live until `leave_slot`. + self.slot.map(|slot| unsafe { &*slot }) + } + + fn write(&mut self, signal: SignalRef, value: BigUint, mask: BigUint) { + self.wrote = true; + if let Some(slot) = self.slot { + // Safety: `enter_slot`'s caller keeps the slot live and unaliased. + unsafe { &mut *slot }.set_four_state(signal, value, mask); + } else if let Some(simulation) = &mut self.simulation { + // A write outside a step is the host's at the current time; the + // design reports its failures when the next step settles it. + let _ = simulation.modify(|io| io.set_four_state(signal, value, mask)); + } + } +} + +impl VpiState for TimedRuntime { + fn image(&self) -> &NativeProgramImage { + &self.image + } + + fn get_four_state(&self, signal: SignalRef) -> (BigUint, BigUint) { + if let Some(slot) = self.slot() { + slot.get_four_state(signal) + } else if let Some(simulation) = &self.simulation { + simulation.peek_four_state(signal) + } else { + (BigUint::default(), BigUint::default()) + } + } + + fn set_four_state(&mut self, signal: SignalRef, value: BigUint, mask: BigUint) { + self.write(signal, value, mask); + } + + /// A timed simulation forces through the compiler's override slots only: + /// it re-applies nothing between its units itself. + fn force(&mut self, id: ReflectionSignalId, value: BigUint, mask: BigUint) -> bool { + let slots = self.image.force_slots(id); + let Some(identity) = (!slots.is_empty()) + .then(|| self.image.signal_identity(id)) + .flatten() + else { + return false; + }; + for (enabled, slot) in slots { + self.write(slot, value.clone(), mask.clone()); + self.write(enabled, 1u8.into(), BigUint::default()); + } + for signal in self.image.signal_aliases(identity) { + self.write(signal, value.clone(), mask.clone()); + } + true + } + + fn release(&mut self, id: ReflectionSignalId) { + for (enabled, _) in self.image.force_slots(id) { + self.write(enabled, 0u8.into(), BigUint::default()); + } + } + + fn schedules_writes(&self) -> bool { + false + } +} + +/// The runtime of a VPI session. +#[allow( + clippy::large_enum_variant, + reason = "a session has one runtime, which its heap-allocated host owns" +)] +pub(crate) enum Runtime { + Untimed(NativeProgramInstance), + Timed(TimedRuntime), +} + +impl Runtime { + pub(crate) fn state(&self) -> &dyn VpiState { + match self { + Runtime::Untimed(instance) => instance, + Runtime::Timed(timed) => timed, + } + } + + pub(crate) fn state_mut(&mut self) -> &mut dyn VpiState { + match self { + Runtime::Untimed(instance) => instance, + Runtime::Timed(timed) => timed, + } + } + + /// The runtime events since the last call, formatted at `time`. + pub(crate) fn drain_runtime_events(&mut self, time: u64) -> Vec { + match self { + Runtime::Untimed(instance) => { + instance.drain_runtime_events_with_context(RuntimeFormatContext { + tb_time: Some(time), + scope: None, + }) + } + Runtime::Timed(timed) => timed.drain_runtime_events(), + } + } +} diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 97d8035e9b8..81c53f69574 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3274,3 +3274,86 @@ fn unpacked_array_handles_preserve_declared_indices_and_neighbor_values() { clear_runtime(); } } + +#[cfg(feature = "systemverilog")] +static TIMED_EDGES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Records the count at every rise of the DUT's clock. +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn record_timed_edge(data: *mut VpiCbData) -> i32 { + // Safety: the callback runtime passes back the registration storage, and + // its value is an integer. + if unsafe { (*(*data).value).value.integer } == 1 { + let mut count = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + // Safety: VPI calls from a callback on the session's thread. + unsafe { + let handle = vpi_handle_by_name(c"Top.count".as_ptr(), ptr::null_mut()); + vpi_get_value(handle, &mut count); + vpi_free_object(handle); + } + // Safety: `count` holds the integer just read. + let count = unsafe { count.value.integer }; + TIMED_EDGES + .lock() + .unwrap() + .push((celox_vpi_current_time(), count)); + } + 0 +} + +/// A timed runtime runs the DUT's processes between the callbacks: its own +/// clock, whose rises a value-change callback sees before the register +/// updates, and its `$finish`, which ends the run. +#[cfg(feature = "systemverilog")] +#[test] +fn a_timed_runtime_runs_the_dut_processes_between_callbacks() { + let _serial = lock_vpi(); + let source = "`timescale 1ns/1ns + module Top(output logic [7:0] count); + logic clk = 0; + always #5 clk = ~clk; + initial count = 0; + always_ff @(posedge clk) count <= count + 1; + initial #23 $finish; + endmodule"; + let sources = || vec![(source, std::path::Path::new("timed.sv"))]; + let image = celox::Simulation::from_sv_sources(sources(), "Top") + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let _session = install_timed_runtime(image, simulation).unwrap(); + TIMED_EDGES.lock().unwrap().clear(); + let mut time = VpiTime { + type_: VPI_SIM_TIME, + ..VpiTime::default() + }; + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + // Safety: VPI calls on the session's thread with live callback storage. + unsafe { + let clk = vpi_handle_by_name(c"Top.clk".as_ptr(), ptr::null_mut()); + assert!(!clk.is_null()); + let change = VpiCbData { + reason: CB_VALUE_CHANGE, + cb_rtn: Some(record_timed_edge), + obj: clk, + time: &mut time, + value: &mut value, + index: 0, + user_data: ptr::null_mut(), + }; + assert!(!vpi_register_cb(&change).is_null()); + } + assert!(run_callbacks_result().unwrap()); + assert_eq!(celox_vpi_current_time(), 23); + assert_eq!(*TIMED_EDGES.lock().unwrap(), vec![(5, 0), (15, 1)]); + clear_runtime(); +} diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index 2e41b9b75ca..a304b05dc18 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -102,6 +102,87 @@ fn cocotb_observes_edges_before_nonblocking_updates() { check_cocotb_native_design(&["edge_phase.sv"], "test_edge_phase", "edge_precedes_nba"); } +#[test] +#[ignore = "requires a cocotb installation; CI runs this test explicitly"] +fn cocotb_runs_dut_processes_in_step() { + check_cocotb_native_design(&["processes.sv"], "test_processes", "."); +} + +/// The `TRACE` lines a cocotb run of `test_processes` logged. +fn traces(output: &[u8]) -> Vec { + String::from_utf8_lossy(output) + .lines() + .filter_map(|line| { + line.split_once("TRACE ") + .map(|(_, trace)| trace.to_string()) + }) + .collect() +} + +/// The DUT processes of `processes.sv` see what they see on Icarus. +#[test] +#[ignore = "requires cocotb and Icarus Verilog; run locally"] +fn icarus_and_celox_agree_on_dut_processes() { + let python = env::var_os("CELOX_COCOTB_PYTHON") + .expect("CELOX_COCOTB_PYTHON must name the cocotb Python interpreter"); + let python = python.to_string_lossy().into_owned(); + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cocotb"); + let temporary = tempfile::tempdir().unwrap(); + let executable = temporary.path().join("processes-sim"); + let compile = Command::new(env!("CARGO_BIN_EXE_celox")) + .args(["vpi", "build"]) + .arg(fixture.join("processes.sv")) + .args(["--top", "Top", "--output"]) + .arg(&executable) + .output() + .unwrap(); + assert!( + compile.status.success(), + "{}", + String::from_utf8_lossy(&compile.stderr) + ); + let site_packages = python_output( + &python, + &["-c", "import site; print(':'.join(site.getsitepackages()))"], + ); + let celox = Command::new(&executable) + .args(["--test-module", "test_processes", "--python", &python]) + .arg("--results-file") + .arg(temporary.path().join("results.xml")) + .current_dir(&fixture) + .env( + "PYTHONPATH", + format!("{}:{site_packages}", fixture.display()), + ) + .output() + .unwrap(); + assert!( + celox.status.success(), + "{}", + String::from_utf8_lossy(&celox.stderr) + ); + let icarus = Command::new(&python) + .arg(fixture.join("run_icarus.py")) + .arg(fixture.join("processes.sv")) + .arg("test_processes") + .arg(temporary.path().join("icarus")) + .env("PYTHONPATH", &fixture) + .output() + .unwrap(); + assert!( + icarus.status.success(), + "{}", + String::from_utf8_lossy(&icarus.stderr) + ); + let expected = traces(&icarus.stdout); + assert!( + !expected.is_empty(), + "{}", + String::from_utf8_lossy(&icarus.stdout) + ); + assert_eq!(traces(&celox.stdout), expected); +} + #[test] #[ignore = "requires a cocotb installation; CI runs this test explicitly"] fn cocotb_accepts_femtosecond_clock_periods() { diff --git a/crates/celox-vpi/tests/diagnostics.rs b/crates/celox-vpi/tests/diagnostics.rs index 3299cc6b8ea..0464983bbf3 100644 --- a/crates/celox-vpi/tests/diagnostics.rs +++ b/crates/celox-vpi/tests/diagnostics.rs @@ -36,13 +36,9 @@ fn run_and_build_share_project_target_and_cli_diagnostic_precedence() { .unwrap(); fs::write(&config, "sources = ['plain.sv', 'top.sv']\ntop = 'Top'\n[diagnostics]\nmixed_timescale = 'error'\n[targets.compat.diagnostics]\nmixed_timescale = 'warn'\n").unwrap(); for build in [false, true] { - // A VPI image runs no process. - let finish = if build { "" } else { "initial #1 $finish;" }; fs::write( project.path().join("top.sv"), - format!( - "module Top(output logic y); timeunit 1ns / 1ps; Plain child(y); {finish} endmodule" - ), + "module Top(output logic y); timeunit 1ns / 1ps; Plain child(y); initial #1 $finish; endmodule", ) .unwrap(); let compile = |target: bool, overrides: &[&str], discover: bool| { @@ -161,14 +157,7 @@ fn inferred_latch_uses_common_diagnostics_for_run_and_build() { let config = project.path().join("celox.toml"); fs::write(&config, "sources = ['top.sv']\ntop = 'Top'\n[diagnostics]\ninferred_latch = 'error'\n[targets.compat.diagnostics]\ninferred_latch = 'warn'\n").unwrap(); for build in [false, true] { - // A VPI image runs no process. - let source = if build { - r#"module Top(input logic en, input logic [7:0] d, output logic [7:0] q); - timeunit 1ns / 1ps; - always_comb if (en) q = d; - endmodule"# - } else { - r#"module Top; + let source = r#"module Top; timeunit 1ns / 1ps; logic en; logic [7:0] d, q; always_comb if (en) q = d; @@ -179,8 +168,7 @@ fn inferred_latch_uses_common_diagnostics_for_run_and_build() { assert (q == 7) else $fatal(1, "closed latch"); $finish; end - endmodule"# - }; + endmodule"#; fs::write(project.path().join("top.sv"), source).unwrap(); let compile = |target: bool, overrides: &[&str]| { let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); diff --git a/crates/celox-vpi/tests/fixtures/cocotb/processes.sv b/crates/celox-vpi/tests/fixtures/cocotb/processes.sv new file mode 100644 index 00000000000..620a7205f99 --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/processes.sv @@ -0,0 +1,17 @@ +`timescale 1ns/1ps +module Top(input logic tick, input logic go, output logic [7:0] count, output logic ack, + output logic [7:0] twice, output logic [7:0] delayed); + logic clk = 0; + always #5 clk = ~clk; + initial count = 0; + always_ff @(posedge clk) count <= count + 1; + assign twice = count * 2; + initial #12 $display("at %0t count=%0d", $time, count); + initial begin + ack = 0; + @(posedge go); + #3 ack = 1; + end + initial delayed = 0; + always @(posedge tick) #1 delayed = count; +endmodule diff --git a/crates/celox-vpi/tests/fixtures/cocotb/run_icarus.py b/crates/celox-vpi/tests/fixtures/cocotb/run_icarus.py new file mode 100644 index 00000000000..f04e8df089d --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/run_icarus.py @@ -0,0 +1,26 @@ +"""Run a cocotb test module against a SystemVerilog source on Icarus. + +Usage: run_icarus.py SOURCE TEST_MODULE BUILD_DIR +""" + +import sys +from pathlib import Path + +from cocotb_tools.runner import get_runner + +source, module, build = Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]) +runner = get_runner("icarus") +runner.build( + sources=[source], + hdl_toplevel="Top", + build_dir=build, + always=True, + timescale=("1ns", "1ps"), +) +runner.test( + hdl_toplevel="Top", + test_module=module, + build_dir=build, + test_dir=build, + extra_env={"PYTHONPATH": str(source.parent)}, +) diff --git a/crates/celox-vpi/tests/fixtures/cocotb/test_processes.py b/crates/celox-vpi/tests/fixtures/cocotb/test_processes.py new file mode 100644 index 00000000000..dac3e8715e9 --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/test_processes.py @@ -0,0 +1,61 @@ +"""SV processes of the DUT run in step with cocotb (#1730).""" + +import cocotb +from cocotb.clock import Clock +from cocotb.triggers import Edge, ReadOnly, RisingEdge, Timer + + +def trace(dut, message): + dut._log.info("TRACE %s", message) + + +@cocotb.test() +async def internal_clock_edges_precede_nba(dut): + """A clock the DUT generates is seen before its registers update.""" + for _ in range(3): + await RisingEdge(dut.clk) + at_edge = int(dut.count.value) + await ReadOnly() + after = int(dut.count.value) + trace(dut, f"t={cocotb.utils.get_sim_time('ns')} edge={at_edge} after={after}") + assert after == at_edge + 1 + + +@cocotb.test() +async def dut_waits_for_a_cocotb_event(dut): + """A DUT process waits for an edge cocotb writes, then delays.""" + dut.go.value = 0 + await Timer(20, unit="ns") + dut.go.value = 1 + written = cocotb.utils.get_sim_time("ns") + await RisingEdge(dut.ack) + trace(dut, f"ack {cocotb.utils.get_sim_time('ns') - written} after go") + assert cocotb.utils.get_sim_time("ns") == written + 3 + + +@cocotb.test() +async def cocotb_clock_drives_a_dut_process(dut): + """A DUT process with a delay runs on a clock cocotb drives.""" + dut.tick.value = 0 + cocotb.start_soon(Clock(dut.tick, 10, unit="ns").start()) + for _ in range(3): + await RisingEdge(dut.tick) + edge = cocotb.utils.get_sim_time("ns") + await Edge(dut.delayed) + trace(dut, f"delayed {cocotb.utils.get_sim_time('ns') - edge} after tick") + assert cocotb.utils.get_sim_time("ns") == edge + 1 + + +@cocotb.test() +async def data_changes_are_seen_settled(dut): + """Celox reports a value change of a register after the slot has settled, + so its combinational readers already show the new value. That is an + implementation choice: IEEE 1800-2023 4.7 leaves the order open, and + Icarus reports the change before `twice` follows.""" + for _ in range(3): + await Edge(dut.count) + count = int(dut.count.value) + settled = int(dut.twice.value) == 2 * count + dut._log.info("settled at value change: %s", settled) + if cocotb.SIM_NAME == "Celox": + assert settled diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index 982b7261b75..bda55094afe 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -495,9 +495,6 @@ fn top_parameters_merge_common_target_and_cli_without_editing_sv() { fs::read_to_string(root.path().join("top.sv")).unwrap(), source ); - // A VPI image runs no process. - let untimed = "module Top #(parameter W=8, parameter V=1, parameter NEXT=V+1) (output logic [W-1:0] y); assign y=NEXT; endmodule"; - fs::write(root.path().join("top.sv"), untimed).unwrap(); success(&invoke( root.path(), &[ @@ -511,21 +508,14 @@ fn top_parameters_merge_common_target_and_cli_without_editing_sv() { "sim", ], )); - let bytes = fs::read(root.path().join("sim")).unwrap(); - let image = celox::NativeProgramImage::discover_appended(&bytes) - .unwrap() - .unwrap() - .image; - // Safety: the CLI just compiled this test's source. - let sim = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); - let signal = sim.signal_ref("Top.y").unwrap(); + let mut sim = attached_simulation(&root.path().join("sim")); + let signal = sim.signal("y"); assert_eq!(signal.width, 16); - assert_eq!(celox::SimBackend::get_as::(sim.backend(), signal), 0); + assert_eq!(sim.get(signal), 0u8.into()); assert_eq!( fs::read_to_string(root.path().join("top.sv")).unwrap(), - untimed + source ); - fs::write(root.path().join("top.sv"), source).unwrap(); let output = invoke(root.path(), &["run", "--target", "wide", "-GMISSING=1"]); assert!(!output.status.success()); assert!( @@ -653,26 +643,13 @@ fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { fs::read_to_string(root.path().join("top.sv")).unwrap(), source ); - // A VPI image runs no process. - let (design, _) = source.split_once("initial").unwrap(); - let source = format!("{design}endmodule\n"); - fs::write(root.path().join("top.sv"), &source).unwrap(); success(&invoke( root.path(), &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), )); - let bytes = fs::read(root.path().join("sim")).unwrap(); - let image = celox::NativeProgramImage::discover_appended(&bytes) - .unwrap() - .unwrap() - .image; - // Safety: the CLI compiled this test's source into the image above. - let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); - let matched = instance.signal_ref("Top.matched").unwrap(); - assert_eq!( - celox::SimBackend::get_as::(instance.backend(), matched), - 1 - ); + let mut sim = attached_simulation(&root.path().join("sim")); + let matched = sim.signal("matched"); + assert_eq!(sim.get(matched), 1u8.into()); assert_eq!( fs::read_to_string(root.path().join("top.sv")).unwrap(), source @@ -690,13 +667,6 @@ fn state_mode_merges_project_target_and_cli_for_run_and_native_build() { initial begin #1; $display("value=%b",y); $finish; end endmodule "#; - // A VPI image runs no process. - let untimed = r#" - module Top(output logic[3:0] y); - logic[3:0] uninitialized; - assign y=uninitialized; - endmodule - "#; fs::write( root.path().join("celox.toml"), "sources=['top.sv']\ntop='Top'\nfour_state=true\n[targets.two]\nfour_state=false\n", @@ -716,23 +686,13 @@ fn state_mode_merges_project_target_and_cli_for_run_and_native_build() { let run = invoke(root.path(), &[&["run"][..], &args].concat()); success(&run); assert_eq!(String::from_utf8(run.stdout).unwrap(), expected); - fs::write(root.path().join("top.sv"), untimed).unwrap(); success(&invoke( root.path(), &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), )); - let bytes = fs::read(root.path().join("sim")).unwrap(); - let image = celox::NativeProgramImage::discover_appended(&bytes) - .unwrap() - .unwrap() - .image; - // Safety: the CLI compiled this test's source into this image. - let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); - assert_eq!(instance.four_state(), is_four); - let (value, mask) = celox::SimBackend::get_four_state( - instance.backend(), - instance.signal_ref("Top.y").unwrap(), - ); + let mut sim = attached_simulation(&root.path().join("sim")); + let y = sim.signal("y"); + let (value, mask) = sim.get_four_state(y); assert_eq!( mask.to_u64_digits(), if is_four { vec![15] } else { vec![] } @@ -907,3 +867,18 @@ timescale = "1ns/1fs" .unwrap(); rejected(&invoke(root.path(), &["run"]), "invalid timescale"); } + +/// The timed simulation of the design an executable built by `vpi build` +/// carries, for a design with processes. +#[cfg(feature = "systemverilog")] +fn attached_simulation(executable: &Path) -> celox::Simulation { + let bytes = fs::read(executable).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + assert!(image.has_processes()); + celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image) + .unwrap() +} diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index 65123edabbd..b2191bc57b2 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -213,11 +213,35 @@ List package definitions before their consumers. It does not discover a must all be `.sv` files; for Veryl, pass one project entry file. The `celox-vpi-compile` binary accepts the same source list. -cocotb drives the design, so the compiled executable runs no HDL process. -Compilation fails for a design with an `initial` process, an ordinary `always` -process or another procedure Celox runs as a process, and names the first one; -constant `initial` blocks and declaration initializers still set initial -values. +### Designs with processes + +A SystemVerilog design with processes, such as an `initial` block with delays +or system tasks, an `always` block with delays or event controls, or a clock +generator like `always #5 clk = ~clk`, compiles into a timed simulation. The +executable runs its processes in step with cocotb: cocotb's timers and the +design's delays share one time axis, and the design's `$display`/`$write` +output and `$finish` work as in `celox run`. A design without processes +compiles as before. + +Within one time step, the VPI callbacks cocotb waits on run at these points: + +| cocotb trigger (VPI callback) | Runs | +|---|---| +| `Timer` (`cbAfterDelay`), `NextTimeStep` (`cbNextSimTime`) | at the start of the time step, before the design's processes | +| `RisingEdge`, `FallingEdge`, `Edge` of a clock or reset (`cbValueChange`) | after the edge, before the flip-flops it triggers make their nonblocking updates | +| `Edge` of another signal (`cbValueChange`) | when the time step has settled: after the nonblocking updates and the combinational logic that follows them | +| `ReadWrite` (`cbReadWriteSynch`) | when the time step has settled; writes there settle again at the same time | +| `ReadOnly` (`cbReadOnlySynch`) | at the end of the time step | + +A write from cocotb is a blocking assignment at the current time. Reporting a +change of a signal other than a clock or reset only once the time step has +settled is a choice of this implementation: IEEE 1800-2023 4.7 lets a simulator +process those events in any order, and Icarus Verilog, for example, reports a +register's change before its combinational readers follow it. + +`$stop` ends the run, as `vpiStop` does, because the executable has no +interactive mode. Pausing instead is tracked in +[#1886](https://github.com/celox-sim/celox/issues/1886). ## Run cocotb diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index c06aefbe3c4..fb8397fd3b7 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -188,10 +188,35 @@ package定義は利用側より先に指定してください。`Veryl.toml`や Verylではプロジェクトの入口となるファイルを1つ指定します。 `celox-vpi-compile`も同じソース一覧を受け付けます。 -設計はcocotbが駆動するため、生成した実行ファイルはHDLのプロセスを実行しません。 -`initial`プロセス、通常の`always`プロセスなど、Celoxがプロセスとして実行する -手続きを含む設計はコンパイルに失敗し、最初のプロセスを示します。定数の`initial` -ブロックと宣言初期化子は引き続き初期値を設定します。 +### プロセスを含む設計 + +遅延やシステムタスクを含む`initial`ブロック、遅延やイベント制御を含む`always` +ブロック、`always #5 clk = ~clk`のようなクロック生成など、プロセスを含む +SystemVerilog設計は時間付きシミュレーションとしてコンパイルされます。生成した +実行ファイルはそのプロセスをcocotbと歩調を合わせて実行します。cocotbのタイマーと +設計の遅延は同じ時間軸を共有し、設計の`$display`/`$write`出力と`$finish`は +`celox run`と同様に動作します。プロセスを含まない設計は従来どおりコンパイル +されます。 + +1つのタイムステップの中で、cocotbが待つVPIコールバックは次の時点で実行されます。 + +| cocotbのトリガー(VPIコールバック) | 実行される時点 | +|---|---| +| `Timer`(`cbAfterDelay`)、`NextTimeStep`(`cbNextSimTime`) | タイムステップの開始時、設計のプロセスより前 | +| クロック・リセットの`RisingEdge`、`FallingEdge`、`Edge`(`cbValueChange`) | エッジの後、それが起動するフリップフロップがノンブロッキング更新を行う前 | +| その他の信号の`Edge`(`cbValueChange`) | タイムステップが落ち着いた後。ノンブロッキング更新とそれに続く組み合わせ回路の評価の後 | +| `ReadWrite`(`cbReadWriteSynch`) | タイムステップが落ち着いた後。ここでの書き込みは同じ時刻に再び落ち着かせます | +| `ReadOnly`(`cbReadOnlySynch`) | タイムステップの終わり | + +cocotbからの書き込みは現在時刻のブロッキング代入です。クロック・リセット以外の +信号の変化をタイムステップが落ち着いてから通知するのはこの実装の選択です。 +IEEE 1800-2023 4.7はこれらのイベントを処理する順序をシミュレータに委ねており、 +たとえばIcarus Verilogはレジスタの変化を、それを読む組み合わせ回路が追従する前に +通知します。 + +実行ファイルには対話モードがないため、`$stop`は`vpiStop`と同様に実行を終了します。 +一時停止への対応は[#1886](https://github.com/celox-sim/celox/issues/1886)で +扱っています。 ## cocotbを実行する From 30a5fe9d317b437c852d8dbc697718b276621185 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 06:46:47 +0900 Subject: [PATCH 3/7] ci: cross-check cocotb time-step regions against Icarus The external-suite job (sv, icarus) runs icarus_and_celox_agree_on_dut_processes, which compares a cocotb test module's traces on Celox and on Icarus, with the locked tool versions of nix develop. Change-Id: I026ef342f35c2dd778aea6e85778642db92bdd21 --- .github/workflows/ci.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 86607a1b55e..60534e0687d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -372,6 +372,15 @@ jobs: cargo test --locked -p celox-test-suite --features "$VERIFY_TOOL" --test oracles -- --ignored + # The VPI host's time-step regions against Icarus, through the same + # cocotb test module, with the locked cocotb and Icarus versions. + - name: Cross-check cocotb time-step regions against Icarus + if: matrix.suite == 'sv' && matrix.tool == 'icarus' + run: >- + nix develop --no-update-lock-file --command + cargo test --locked -p celox-vpi --features systemverilog + --test cocotb_e2e icarus_and_celox_agree_on_dut_processes -- --ignored --exact + - name: Catalogue every shared case if: ${{ !cancelled() }} run: | From b0f16d781000566469ea7e81042fd82a76c522dc Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 19:06:53 +0900 Subject: [PATCH 4/7] fix(vpi): bound a timed time step and keep its ReadOnly region read-only A timed run counts the rounds it spends at one time, the settles of callback writes, ReadWrite passes and due timers alike, and fails with "simulation does not advance at time T" after a million. VPI writes during ReadOnly callbacks are rejected (IEEE 1800-2023 38.36.2), and a zero-delay timer registered there runs read-only without opening the time step's regions again. The cocotb guide describes the value-change timing the host has: at each boundary of a time step, after the settle of the wave that made the change and before the processes it wakes. It notes that pulses within one wave are not reported, that reads outside a step see stored values, and that only celox vpi build supports designs with processes (#1983). Change-Id: Ib964d9258f4e3844cff344d5f2c88f5c716e758b --- crates/celox-vpi/src/callbacks.rs | 94 ++++-- crates/celox-vpi/src/lib.rs | 4 + crates/celox-vpi/tests/basic_vpi.rs | 277 ++++++++++++++++++ crates/celox-vpi/tests/cocotb_e2e.rs | 32 +- .../celox-vpi/tests/fixtures/cocotb/finish.sv | 12 + .../tests/fixtures/cocotb/force_timed.sv | 8 + .../tests/fixtures/cocotb/processes.sv | 7 +- .../tests/fixtures/cocotb/test_finish.py | 11 + .../tests/fixtures/cocotb/test_force_timed.py | 26 ++ .../tests/fixtures/cocotb/test_processes.py | 13 + docs/guide/cocotb.md | 32 +- docs/ja/guide/cocotb.md | 31 +- 12 files changed, 499 insertions(+), 48 deletions(-) create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/finish.sv create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/force_timed.sv create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/test_finish.py create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/test_force_timed.py diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index af699a4ac56..5481146be2d 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -87,6 +87,12 @@ pub(super) struct CallbackState { pub(super) running: bool, /// The time whose ReadOnly region a timed simulation ran last. read_only_at: Option, + /// ReadOnly callbacks are running: VPI writes are rejected. + pub(super) read_only: bool, + /// Rounds a timed simulation spent at the current time: settles, region + /// passes and due timers. Bounded, so that callbacks that never let the + /// time step end report it instead of hanging. + rounds_at_time: usize, pub(super) detach_on_stop: bool, error: Option, } @@ -346,7 +352,7 @@ pub(super) fn run() -> bool { } break; } - progressed |= fire_all(CB_READ_ONLY_SYNCH); + progressed |= fire_read_only(); if with_host(|host| borrow_cell(&host.callbacks, |state| state.finish)) { break; @@ -412,7 +418,50 @@ fn watched_signals() -> Vec { } fn set_time(time: u64) { - with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.time = time)); + with_host(|host| { + borrow_cell_mut(&host.callbacks, |state| { + if state.time != time { + state.rounds_at_time = 0; + } + state.time = time; + }) + }); +} + +/// The rounds a timed simulation may spend at one time. +const ROUNDS_AT_TIME: usize = 1_000_000; + +/// Count a round at the current time; `false`, with the run failed, once a +/// time step has spent [`ROUNDS_AT_TIME`] of them. +fn charge_round() -> bool { + let exceeded = with_host(|host| { + borrow_cell_mut(&host.callbacks, |state| { + state.rounds_at_time += 1; + (state.rounds_at_time > ROUNDS_AT_TIME).then_some(state.time) + }) + }); + if let Some(time) = exceeded { + fail(format!( + "simulation does not advance at time {time}: callbacks and the settles of their \ + writes repeated {ROUNDS_AT_TIME} times" + )); + return false; + } + true +} + +/// Fire the ReadOnly callbacks, with VPI writes rejected (IEEE 1800-2023 +/// 38.36.2). +fn fire_read_only() -> bool { + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.read_only = true)); + let progressed = fire_all(CB_READ_ONLY_SYNCH); + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.read_only = false)); + progressed +} + +/// Whether ReadOnly callbacks are running. +pub(super) fn in_read_only() -> bool { + with_host(|host| borrow_cell(&host.callbacks, |state| state.read_only)) } fn current_time() -> u64 { @@ -438,7 +487,7 @@ enum Regions { fn settled_regions() -> Regions { take_timed_writes(); loop { - if finish_requested() { + if finish_requested() || !charge_round() { return Regions::Done; } if dispatch_value_changes() { @@ -461,7 +510,7 @@ fn settled_regions() -> Regions { return Regions::Wrote; } } - fire_all(CB_READ_ONLY_SYNCH); + fire_read_only(); with_host(|host| { borrow_cell_mut(&host.callbacks, |state| { state.read_only_at = Some(state.time) @@ -470,8 +519,9 @@ fn settled_regions() -> Regions { Regions::Done } -/// Shows a timed simulation's slots to the VPI callbacks: value changes of -/// clocks before the domains commit, and the regions of each settled slot. +/// Shows a timed simulation's slots to the VPI callbacks: value changes at +/// every wave boundary, so that an edge is seen before the domains it +/// triggers commit, and the regions of each settled slot. struct TimedObserver; impl celox::SlotObserver for TimedObserver { @@ -538,16 +588,7 @@ pub(super) fn run_timed() -> bool { super::with_timed_mut(|timed| timed.simulation = Some(simulation)); } fire_all(CB_START_OF_SIMULATION); - let mut iterations = 0usize; - while !finish_requested() { - iterations += 1; - if iterations > 1_000_000 { - fail( - "VPI callback scheduler exceeded 1000000 iterations without advancing time" - .to_string(), - ); - break; - } + while !finish_requested() && charge_round() { let due = with_host(|host| { borrow_cell(&host.callbacks, |state| { state @@ -567,8 +608,19 @@ pub(super) fn run_timed() -> bool { break; } set_time(time); - iterations = 0; fire_all(CB_NEXT_SIM_TIME); + } else if with_host(|host| borrow_cell(&host.callbacks, |state| state.read_only_at)) + == Some(time) + && event != Some(time) + { + // A zero-delay timer that a ReadOnly callback registered runs, + // still read-only: the time step's regions do not open again. + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.read_only = true)); + for id in due_ids() { + fire(id); + } + with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.read_only = false)); + continue; } for id in due_ids() { fire(id); @@ -590,14 +642,6 @@ pub(super) fn run_timed() -> bool { break; } timed_step(|simulation| simulation.run_until(time)); - iterations += 1; - if iterations > 1_000_000 { - fail( - "VPI callback scheduler exceeded 1000000 iterations without advancing time" - .to_string(), - ); - break; - } } } let finished = finish_requested(); diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index c5d85c07617..c830e6a18ce 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -1525,6 +1525,10 @@ pub unsafe extern "C" fn vpi_put_value( when: *const c_void, flags: i32, ) -> VpiHandle { + // A ReadOnly callback may not write (IEEE 1800-2023 38.36.2, Table 38-6). + if callbacks::in_read_only() { + return ptr::null_mut(); + } let inertial_is_immediate = flags == VPI_INERTIAL_DELAY && (when.is_null() || { // Safety: a non-null VPI delay pointer addresses `s_vpi_time`. diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 81c53f69574..ec01b380f17 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3357,3 +3357,280 @@ fn a_timed_runtime_runs_the_dut_processes_between_callbacks() { assert_eq!(*TIMED_EDGES.lock().unwrap(), vec![(5, 0), (15, 1)]); clear_runtime(); } + +#[cfg(feature = "systemverilog")] +static SPIN_WRITES: AtomicBool = AtomicBool::new(false); + +/// Re-registers itself in the ReadWrite region, writing `Top.x` there when +/// [`SPIN_WRITES`] is set: a time step that never ends. +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn spin_read_write(_data: *mut VpiCbData) -> i32 { + // Safety: VPI calls from a callback on the session's thread. + unsafe { + if SPIN_WRITES.load(Ordering::SeqCst) { + let x = vpi_handle_by_name(c"Top.x".as_ptr(), ptr::null_mut()); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(x, &mut value); + value.value.integer ^= 1; + vpi_put_value(x, &value, ptr::null(), VPI_NO_DELAY); + vpi_free_object(x); + } + register_spin(); + } + 0 +} + +#[cfg(feature = "systemverilog")] +unsafe fn register_spin() { + let data = VpiCbData { + reason: CB_READ_WRITE_SYNCH, + cb_rtn: Some(spin_read_write), + obj: ptr::null_mut(), + time: ptr::null_mut(), + value: ptr::null_mut(), + index: 0, + user_data: ptr::null_mut(), + }; + // Safety: the registration copies `data`. + assert!(!unsafe { vpi_register_cb(&data) }.is_null()); +} + +/// A time step whose ReadWrite callbacks never let it end fails the run, +/// whether they write or not. +#[cfg(feature = "systemverilog")] +#[test] +fn a_timed_time_step_that_never_ends_fails_the_run() { + let _serial = lock_vpi(); + let source = "`timescale 1ns/1ns + module Top(input logic x, output logic y); + assign y = x; + initial #5 $display(\"never\"); + endmodule"; + for writes in [false, true] { + let image = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("spin.sv"))], + "Top", + ) + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let _session = install_timed_runtime(image, simulation).unwrap(); + SPIN_WRITES.store(writes, Ordering::SeqCst); + // Safety: VPI registration on the session's thread. + unsafe { register_spin() }; + let error = run_callbacks_result().unwrap_err(); + assert!( + error.contains("simulation does not advance at time 0"), + "{error}" + ); + assert_eq!(celox_vpi_current_time(), 0); + clear_runtime(); + } +} + +#[cfg(feature = "systemverilog")] +static FINISH_EVENTS: AtomicI32 = AtomicI32::new(0); + +/// Finishes the run at the first rise of the DUT's clock. +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn finish_at_the_first_rise(data: *mut VpiCbData) -> i32 { + // Safety: the callback runtime passes back the registration storage, and + // its value is an integer. + if unsafe { (*(*data).value).value.integer } == 1 { + FINISH_EVENTS.fetch_or(1, Ordering::SeqCst); + assert_eq!(vpi_control(VPI_FINISH), 1); + } + 0 +} + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn record_end_of_simulation(_data: *mut VpiCbData) -> i32 { + FINISH_EVENTS.fetch_or(2, Ordering::SeqCst); + 0 +} + +/// `vpiFinish` from a value-change callback inside a time step ends the run +/// at that time: the design runs nothing later, and the end-of-simulation +/// callbacks still run. +#[cfg(feature = "systemverilog")] +#[test] +fn a_finish_inside_a_time_step_ends_a_timed_run() { + let _serial = lock_vpi(); + let source = "`timescale 1ns/1ns + module Top(output logic [7:0] count); + logic clk = 0; + always #5 clk = ~clk; + initial count = 0; + always_ff @(posedge clk) count <= count + 1; + endmodule"; + let image = + celox::Simulation::from_sv_sources(vec![(source, std::path::Path::new("stop.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let _session = install_timed_runtime(image, simulation).unwrap(); + FINISH_EVENTS.store(0, Ordering::SeqCst); + let mut time = VpiTime { + type_: VPI_SIM_TIME, + ..VpiTime::default() + }; + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + // Safety: VPI calls on the session's thread with live callback storage. + unsafe { + let clk = vpi_handle_by_name(c"Top.clk".as_ptr(), ptr::null_mut()); + let change = VpiCbData { + reason: CB_VALUE_CHANGE, + cb_rtn: Some(finish_at_the_first_rise), + obj: clk, + time: &mut time, + value: &mut value, + index: 0, + user_data: ptr::null_mut(), + }; + assert!(!vpi_register_cb(&change).is_null()); + let end = VpiCbData { + reason: CB_END_OF_SIMULATION, + cb_rtn: Some(record_end_of_simulation), + obj: ptr::null_mut(), + value: ptr::null_mut(), + ..change + }; + assert!(!vpi_register_cb(&end).is_null()); + } + assert!(run_callbacks_result().unwrap()); + assert_eq!(celox_vpi_current_time(), 5); + assert_eq!(FINISH_EVENTS.load(Ordering::SeqCst), 3); + clear_runtime(); +} + +#[cfg(feature = "systemverilog")] +static READ_ONLY_EVENTS: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + +/// Tries to write `Top.x`; returns whether the write was accepted. +#[cfg(feature = "systemverilog")] +unsafe fn try_write_x() -> bool { + // Safety: VPI calls from a callback on the session's thread. + unsafe { + let x = vpi_handle_by_name(c"Top.x".as_ptr(), ptr::null_mut()); + let value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 1 }, + }; + let accepted = !vpi_put_value(x, &value, ptr::null(), VPI_NO_DELAY).is_null(); + vpi_free_object(x); + accepted + } +} + +#[cfg(feature = "systemverilog")] +unsafe fn register_read_only_probe( + reason: i32, + callback: unsafe extern "C" fn(*mut VpiCbData) -> i32, +) { + let mut delay = VpiTime { + type_: VPI_SIM_TIME, + ..VpiTime::default() + }; + let data = VpiCbData { + reason, + cb_rtn: Some(callback), + obj: ptr::null_mut(), + time: &mut delay, + value: ptr::null_mut(), + index: 0, + user_data: ptr::null_mut(), + }; + // Safety: the registration copies `data` and `delay`. + assert!(!unsafe { vpi_register_cb(&data) }.is_null()); +} + +/// Records a ReadOnly write attempt and schedules a zero-delay timer. +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn read_only_writes(_data: *mut VpiCbData) -> i32 { + // Safety: VPI calls from a callback on the session's thread. + let accepted = unsafe { try_write_x() }; + READ_ONLY_EVENTS + .lock() + .unwrap() + .push(("read-only", celox_vpi_current_time(), accepted)); + // Safety: as above. + unsafe { register_read_only_probe(CB_AFTER_DELAY, zero_delay_after_read_only) }; + 0 +} + +/// A zero-delay timer from ReadOnly: still read-only, and the ReadWrite it +/// registers belongs to a later time step. +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn zero_delay_after_read_only(_data: *mut VpiCbData) -> i32 { + // Safety: VPI calls from a callback on the session's thread. + let accepted = unsafe { try_write_x() }; + READ_ONLY_EVENTS + .lock() + .unwrap() + .push(("timer", celox_vpi_current_time(), accepted)); + // Safety: as above. + unsafe { register_read_only_probe(CB_READ_WRITE_SYNCH, read_write_after_read_only) }; + 0 +} + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn read_write_after_read_only(_data: *mut VpiCbData) -> i32 { + // Safety: VPI calls from a callback on the session's thread. + let accepted = unsafe { try_write_x() }; + READ_ONLY_EVENTS + .lock() + .unwrap() + .push(("read-write", celox_vpi_current_time(), accepted)); + 0 +} + +/// A timed runtime rejects writes in ReadOnly (IEEE 1800-2023 38.36.2), and +/// a zero-delay timer registered there runs without opening the time +/// step's regions again. +#[cfg(feature = "systemverilog")] +#[test] +fn a_timed_read_only_region_rejects_writes_and_stays_closed() { + let _serial = lock_vpi(); + let source = "`timescale 1ns/1ns + module Top(input logic x, output logic y); + assign y = x; + initial #10 $display(\"later\"); + endmodule"; + let image = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("read_only.sv"))], + "Top", + ) + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let _session = install_timed_runtime(image, simulation).unwrap(); + READ_ONLY_EVENTS.lock().unwrap().clear(); + // Safety: VPI registration on the session's thread. + unsafe { register_read_only_probe(CB_READ_ONLY_SYNCH, read_only_writes) }; + assert!(!run_callbacks_result().unwrap()); + assert_eq!( + *READ_ONLY_EVENTS.lock().unwrap(), + vec![ + ("read-only", 0, false), + ("timer", 0, false), + ("read-write", 10, true) + ] + ); + clear_runtime(); +} diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index a304b05dc18..8d50e2c01a3 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -105,7 +105,28 @@ fn cocotb_observes_edges_before_nonblocking_updates() { #[test] #[ignore = "requires a cocotb installation; CI runs this test explicitly"] fn cocotb_runs_dut_processes_in_step() { - check_cocotb_native_design(&["processes.sv"], "test_processes", "."); + let output = check_cocotb_native_design(&["processes.sv"], "test_processes", "."); + // `%0t` formats in the time precision, 1 ps. + assert!(output.contains("at 12000 count=1\n"), "{output}"); +} + +#[test] +#[ignore = "requires a cocotb installation; CI runs this test explicitly"] +fn cocotb_forces_and_releases_a_register_of_a_timed_design() { + check_cocotb_native_design_with_options( + &["force_timed.sv"], + "test_force_timed", + ".", + &["--force-signal", "Top.x"], + ); +} + +#[test] +#[ignore = "requires a cocotb installation; CI runs this test explicitly"] +fn cocotb_ends_at_the_designs_finish() { + let output = check_cocotb_native_design(&["finish.sv"], "test_finish", "."); + assert!(output.contains("finishing at 30\n"), "{output}"); + assert!(!output.contains("late"), "{output}"); } /// The `TRACE` lines a cocotb run of `test_processes` logged. @@ -194,16 +215,18 @@ fn cocotb_accepts_femtosecond_clock_periods() { ); } -fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { - check_cocotb_native_design_with_options(source, module, filter, &[]); +fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) -> String { + check_cocotb_native_design_with_options(source, module, filter, &[]) } +/// Build `source`, run `module`'s tests matching `filter` on it, and check +/// that bad selections fail. Returns the standard output of the run. fn check_cocotb_native_design_with_options( source: &[&str], module: &str, filter: &str, options: &[&str], -) { +) -> String { let python = env::var_os("CELOX_COCOTB_PYTHON") .expect("CELOX_COCOTB_PYTHON must name the cocotb Python interpreter"); let python = python.to_string_lossy().into_owned(); @@ -299,6 +322,7 @@ fn check_cocotb_native_design_with_options( !results.exists(), "failed cocotb startup left stale results in place" ); + String::from_utf8_lossy(&runtime.stdout).into_owned() } #[test] diff --git a/crates/celox-vpi/tests/fixtures/cocotb/finish.sv b/crates/celox-vpi/tests/fixtures/cocotb/finish.sv new file mode 100644 index 00000000000..ee579356f6d --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/finish.sv @@ -0,0 +1,12 @@ +`timescale 1ns/1ns +module Top(output logic [7:0] count); + logic clk = 0; + always #5 clk = ~clk; + initial count = 0; + always_ff @(posedge clk) count <= count + 1; + initial begin + #30 $display("finishing at %0t", $time); + $finish; + end + initial #100 $display("late"); +endmodule diff --git a/crates/celox-vpi/tests/fixtures/cocotb/force_timed.sv b/crates/celox-vpi/tests/fixtures/cocotb/force_timed.sv new file mode 100644 index 00000000000..f734516545d --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/force_timed.sv @@ -0,0 +1,8 @@ +`timescale 1ns/1ps +module Top(output logic [7:0] x, output logic [7:0] y); + logic clk = 0; + always #5 clk = ~clk; + initial x = 0; + always_ff @(posedge clk) x <= x + 1; + assign y = x + 8'd100; +endmodule diff --git a/crates/celox-vpi/tests/fixtures/cocotb/processes.sv b/crates/celox-vpi/tests/fixtures/cocotb/processes.sv index 620a7205f99..faffae0ad19 100644 --- a/crates/celox-vpi/tests/fixtures/cocotb/processes.sv +++ b/crates/celox-vpi/tests/fixtures/cocotb/processes.sv @@ -1,6 +1,6 @@ `timescale 1ns/1ps module Top(input logic tick, input logic go, output logic [7:0] count, output logic ack, - output logic [7:0] twice, output logic [7:0] delayed); + output logic [7:0] twice, output logic [7:0] delayed, output logic [7:0] mirror); logic clk = 0; always #5 clk = ~clk; initial count = 0; @@ -12,6 +12,11 @@ module Top(input logic tick, input logic go, output logic [7:0] count, output lo @(posedge go); #3 ack = 1; end + initial mirror = 0; + initial forever begin + @(count); + mirror = count; + end initial delayed = 0; always @(posedge tick) #1 delayed = count; endmodule diff --git a/crates/celox-vpi/tests/fixtures/cocotb/test_finish.py b/crates/celox-vpi/tests/fixtures/cocotb/test_finish.py new file mode 100644 index 00000000000..64609910a81 --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/test_finish.py @@ -0,0 +1,11 @@ +"""The design's $finish ends a cocotb run (#1730).""" + +import cocotb +from cocotb.regression import SimFailure +from cocotb.triggers import Timer + + +@cocotb.test(expect_error=SimFailure) +async def design_finish_ends_the_run(dut): + await Timer(100, unit="ns") + dut._log.info("TRACE the run went on") diff --git a/crates/celox-vpi/tests/fixtures/cocotb/test_force_timed.py b/crates/celox-vpi/tests/fixtures/cocotb/test_force_timed.py new file mode 100644 index 00000000000..bbda224681d --- /dev/null +++ b/crates/celox-vpi/tests/fixtures/cocotb/test_force_timed.py @@ -0,0 +1,26 @@ +"""Force and release a register of a design with processes (#1730).""" + +import cocotb +from cocotb.handle import Force, Release +from cocotb.triggers import ReadOnly, RisingEdge, Timer + + +@cocotb.test() +async def force_holds_a_register_until_release(dut): + await RisingEdge(dut.clk) + dut.x.value = Force(50) + await ReadOnly() + assert (int(dut.x.value), int(dut.y.value)) == (50, 150) + for _ in range(2): + await RisingEdge(dut.clk) + await ReadOnly() + assert (int(dut.x.value), int(dut.y.value)) == (50, 150) + # Between two edges, a released variable keeps its value until its next + # assignment (IEEE 1800-2023 10.6.2). + await Timer(2, unit="ns") + dut.x.value = Release() + await ReadOnly() + assert (int(dut.x.value), int(dut.y.value)) == (50, 150) + await RisingEdge(dut.clk) + await ReadOnly() + assert (int(dut.x.value), int(dut.y.value)) == (51, 151) diff --git a/crates/celox-vpi/tests/fixtures/cocotb/test_processes.py b/crates/celox-vpi/tests/fixtures/cocotb/test_processes.py index dac3e8715e9..0ef2de58a20 100644 --- a/crates/celox-vpi/tests/fixtures/cocotb/test_processes.py +++ b/crates/celox-vpi/tests/fixtures/cocotb/test_processes.py @@ -59,3 +59,16 @@ async def data_changes_are_seen_settled(dut): dut._log.info("settled at value change: %s", settled) if cocotb.SIM_NAME == "Celox": assert settled + + +@cocotb.test() +async def changes_are_seen_before_their_waiters_run(dut): + """A change is reported at the boundary of the wave that made it, before + the processes it wakes have run.""" + for _ in range(3): + await Edge(dut.count) + seen = (int(dut.count.value) - int(dut.mirror.value)) % 256 + await ReadOnly() + settled = (int(dut.count.value) - int(dut.mirror.value)) % 256 + trace(dut, f"mirror behind by {seen} at the change, {settled} at ReadOnly") + assert (seen, settled) == (1, 0) diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index b2191bc57b2..7787b1234d3 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -228,16 +228,30 @@ Within one time step, the VPI callbacks cocotb waits on run at these points: | cocotb trigger (VPI callback) | Runs | |---|---| | `Timer` (`cbAfterDelay`), `NextTimeStep` (`cbNextSimTime`) | at the start of the time step, before the design's processes | -| `RisingEdge`, `FallingEdge`, `Edge` of a clock or reset (`cbValueChange`) | after the edge, before the flip-flops it triggers make their nonblocking updates | -| `Edge` of another signal (`cbValueChange`) | when the time step has settled: after the nonblocking updates and the combinational logic that follows them | +| `RisingEdge`, `FallingEdge`, `Edge` (`cbValueChange`) | at the next boundary after the change: when a round's processes have run, before its flip-flops make their nonblocking updates; after each wave of nonblocking updates and the combinational logic that follows it; or when the time step has settled | | `ReadWrite` (`cbReadWriteSynch`) | when the time step has settled; writes there settle again at the same time | -| `ReadOnly` (`cbReadOnlySynch`) | at the end of the time step | - -A write from cocotb is a blocking assignment at the current time. Reporting a -change of a signal other than a clock or reset only once the time step has -settled is a choice of this implementation: IEEE 1800-2023 4.7 lets a simulator -process those events in any order, and Icarus Verilog, for example, reports a -register's change before its combinational readers follow it. +| `ReadOnly` (`cbReadOnlySynch`) | at the end of the time step; writes there are rejected | + +So the edge of a clock or reset is reported before the flip-flops it triggers +commit, whether cocotb or the design drives it. A change is reported at the +boundary of the wave that made it: after that wave's combinational settle, so +a register's combinational readers already show its new value, and before the +processes the change wakes have run. Where a callback runs relative to the +design's own events within the time step is a choice of this implementation: +IEEE 1800-2023 4.7 lets a simulator process those events in any order, and +Icarus Verilog, for example, reports a register's change before its +combinational readers follow it. For the same reason, a pulse within one wave, +such as `x = 1; x = 0;` in one process, is not reported: a callback sees the +value at a boundary. + +A write from cocotb is a blocking assignment at the current time. Outside the +regions of a time step, in a `Timer` callback for example, a read returns the +stored value: what combinational logic derives from a write in the same +callback reads as before until the time step settles. + +Only `celox vpi build` supports designs with processes; `celox-vpi-compile` +and its `celox-vpi-runtime` still reject them +([#1983](https://github.com/celox-sim/celox/issues/1983)). `$stop` ends the run, as `vpiStop` does, because the executable has no interactive mode. Pausing instead is tracked in diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index fb8397fd3b7..ad352d77591 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -203,16 +203,29 @@ SystemVerilog設計は時間付きシミュレーションとしてコンパイ | cocotbのトリガー(VPIコールバック) | 実行される時点 | |---|---| | `Timer`(`cbAfterDelay`)、`NextTimeStep`(`cbNextSimTime`) | タイムステップの開始時、設計のプロセスより前 | -| クロック・リセットの`RisingEdge`、`FallingEdge`、`Edge`(`cbValueChange`) | エッジの後、それが起動するフリップフロップがノンブロッキング更新を行う前 | -| その他の信号の`Edge`(`cbValueChange`) | タイムステップが落ち着いた後。ノンブロッキング更新とそれに続く組み合わせ回路の評価の後 | +| `RisingEdge`、`FallingEdge`、`Edge`(`cbValueChange`) | 変化の後の次の区切り。ラウンドのプロセスが実行された後で、そのフリップフロップがノンブロッキング更新を行う前。ノンブロッキング更新の各ウェーブとそれに続く組み合わせ回路の評価の後。またはタイムステップが落ち着いた後 | | `ReadWrite`(`cbReadWriteSynch`) | タイムステップが落ち着いた後。ここでの書き込みは同じ時刻に再び落ち着かせます | -| `ReadOnly`(`cbReadOnlySynch`) | タイムステップの終わり | - -cocotbからの書き込みは現在時刻のブロッキング代入です。クロック・リセット以外の -信号の変化をタイムステップが落ち着いてから通知するのはこの実装の選択です。 -IEEE 1800-2023 4.7はこれらのイベントを処理する順序をシミュレータに委ねており、 -たとえばIcarus Verilogはレジスタの変化を、それを読む組み合わせ回路が追従する前に -通知します。 +| `ReadOnly`(`cbReadOnlySynch`) | タイムステップの終わり。ここでの書き込みは拒否されます | + +したがって、クロックやリセットのエッジは、cocotbと設計のどちらが駆動しても、 +それが起動するフリップフロップの確定より前に通知されます。変化は、それを起こした +ウェーブの区切りで通知されます。そのウェーブの組み合わせ回路の評価の後なので、 +レジスタを読む組み合わせ回路はすでに新しい値を示し、その変化で起こされるプロセスは +まだ実行されていません。タイムステップ内で設計自身のイベントに対してコールバックを +どこで実行するかはこの実装の選択です。IEEE 1800-2023 4.7はこれらのイベントを処理 +する順序をシミュレータに委ねており、たとえばIcarus Verilogはレジスタの変化を、 +それを読む組み合わせ回路が追従する前に通知します。同じ理由で、1つのプロセスでの +`x = 1; x = 0;`のような1ウェーブ内のパルスは通知されません。コールバックが見るのは +区切りでの値です。 + +cocotbからの書き込みは現在時刻のブロッキング代入です。タイムステップの領域の外、 +たとえば`Timer`コールバックの中での読み出しは格納された値を返します。同じコール +バックでの書き込みから組み合わせ回路が導く値は、タイムステップが落ち着くまで +以前の値のままです。 + +プロセスを含む設計に対応しているのは`celox vpi build`だけです。`celox-vpi-compile` +とその`celox-vpi-runtime`は引き続きこれらを拒否します +([#1983](https://github.com/celox-sim/celox/issues/1983))。 実行ファイルには対話モードがないため、`$stop`は`vpiStop`と同様に実行を終了します。 一時停止への対応は[#1886](https://github.com/celox-sim/celox/issues/1886)で From 5303cbaa21948589d8e655f895ce60090afe53f6 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 19:41:47 +0900 Subject: [PATCH 5/7] fix(vpi): run zero-delay timers before a timed step closes and finish before its slot Timers due at the current time, including the zero-delay ones a timer or ReadWrite callback registers, now run in a loop until none is due, both before the step's slot and before its ReadOnly region; the same-time bound covers the loop. A vpiFinish from a due timer ends the run before the design's slot at that time runs, as in the untimed host. Change-Id: I8b52b5e212d440fe19398a4458d256fdb7fc6ceb --- crates/celox-vpi/src/callbacks.rs | 38 +++++- crates/celox-vpi/tests/basic_vpi.rs | 196 ++++++++++++++++++++++++++++ 2 files changed, 229 insertions(+), 5 deletions(-) diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index 5481146be2d..d1055dc5ac7 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -468,6 +468,27 @@ fn current_time() -> u64 { with_host(|host| borrow_cell(&host.callbacks, |state| state.time)) } +/// Fire the timers due now, including the zero-delay ones they register, +/// until none is due. Returns whether any fired. +fn fire_due_timers() -> bool { + let mut fired = false; + loop { + let due = due_ids(); + if due.is_empty() || finish_requested() { + return fired; + } + for id in due { + fired |= fire(id); + if finish_requested() { + return fired; + } + } + if !charge_round() { + return fired; + } + } +} + /// Whether a VPI write changed the timed simulation since the last call. fn take_timed_writes() -> bool { super::with_timed_mut(super::TimedRuntime::take_wrote).unwrap_or(false) @@ -496,6 +517,14 @@ fn settled_regions() -> Regions { } continue; } + // A zero-delay timer that a callback of this time step registered + // runs before the step closes. + if fire_due_timers() { + if take_timed_writes() { + return Regions::Wrote; + } + continue; + } let read_write = registration_ids(CB_READ_WRITE_SYNCH); if read_write.is_empty() { break; @@ -622,11 +651,10 @@ pub(super) fn run_timed() -> bool { with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.read_only = false)); continue; } - for id in due_ids() { - fire(id); - if finish_requested() { - break; - } + fire_due_timers(); + // A finish from a timer ends the run before the design's slot. + if finish_requested() { + break; } with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.read_only_at = None)); timed_step(|simulation| simulation.run_until(time)); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index ec01b380f17..e1747b3400f 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3634,3 +3634,199 @@ fn a_timed_read_only_region_rejects_writes_and_stays_closed() { ); clear_runtime(); } + +#[cfg(feature = "systemverilog")] +static ZERO_DELAY_EVENTS: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + +#[cfg(feature = "systemverilog")] +unsafe fn read_int(name: &CStr) -> i32 { + // Safety: VPI calls on the session's thread. + unsafe { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(handle, &mut value); + vpi_free_object(handle); + value.value.integer + } +} + +#[cfg(feature = "systemverilog")] +fn zero_delay_event(name: &'static str) { + // Safety: VPI calls from a callback on the session's thread. + let y = unsafe { read_int(c"Top.y") }; + ZERO_DELAY_EVENTS + .lock() + .unwrap() + .push((name, celox_vpi_current_time(), y)); +} + +/// The timer at 5 registers a zero-delay timer. +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn timer_at_five(_data: *mut VpiCbData) -> i32 { + zero_delay_event("timer"); + // Safety: VPI registration from a callback on the session's thread. + unsafe { register_read_only_probe(CB_AFTER_DELAY, first_zero_delay) }; + 0 +} + +/// Writes `x` and registers a ReadWrite callback. +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn first_zero_delay(_data: *mut VpiCbData) -> i32 { + zero_delay_event("first zero delay"); + // Safety: VPI calls from a callback on the session's thread. + unsafe { + assert!(try_write_x()); + register_read_only_probe(CB_READ_WRITE_SYNCH, read_write_registers_a_timer); + } + 0 +} + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn read_write_registers_a_timer(_data: *mut VpiCbData) -> i32 { + zero_delay_event("read-write"); + // Safety: VPI registration from a callback on the session's thread. + unsafe { register_read_only_probe(CB_AFTER_DELAY, second_zero_delay) }; + 0 +} + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn second_zero_delay(_data: *mut VpiCbData) -> i32 { + zero_delay_event("second zero delay"); + // Safety: VPI registration from a callback on the session's thread. + unsafe { register_read_only_probe(CB_READ_ONLY_SYNCH, read_only_after_timers) }; + 0 +} + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn read_only_after_timers(_data: *mut VpiCbData) -> i32 { + zero_delay_event("read-only"); + 0 +} + +/// Zero-delay timers that timer and ReadWrite callbacks register run in the +/// same time step, before its ReadOnly region closes it. +#[cfg(feature = "systemverilog")] +#[test] +fn zero_delay_timers_run_before_a_timed_step_closes() { + let _serial = lock_vpi(); + let source = "`timescale 1ns/1ns + module Top(input logic x, output logic y); + assign y = x; + initial #20 $display(\"later\"); + endmodule"; + let image = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("zero_delay.sv"))], + "Top", + ) + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let _session = install_timed_runtime(image, simulation).unwrap(); + ZERO_DELAY_EVENTS.lock().unwrap().clear(); + let mut delay = VpiTime { + type_: VPI_SIM_TIME, + low: 5, + ..VpiTime::default() + }; + let timer = VpiCbData { + reason: CB_AFTER_DELAY, + cb_rtn: Some(timer_at_five), + obj: ptr::null_mut(), + time: &mut delay, + value: ptr::null_mut(), + index: 0, + user_data: ptr::null_mut(), + }; + // Safety: VPI registration on the session's thread. + assert!(!unsafe { vpi_register_cb(&timer) }.is_null()); + assert!(!run_callbacks_result().unwrap()); + assert_eq!( + *ZERO_DELAY_EVENTS.lock().unwrap(), + vec![ + ("timer", 5, 0), + ("first zero delay", 5, 0), + ("read-write", 5, 1), + ("second zero delay", 5, 1), + ("read-only", 5, 1), + ] + ); + clear_runtime(); +} + +#[cfg(feature = "systemverilog")] +static FLAG_AT_END: AtomicI32 = AtomicI32::new(-1); + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn finish_from_a_timer(_data: *mut VpiCbData) -> i32 { + assert_eq!(vpi_control(VPI_FINISH), 1); + 0 +} + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn record_flag_at_end(_data: *mut VpiCbData) -> i32 { + // Safety: VPI calls from a callback on the session's thread. + FLAG_AT_END.store(unsafe { read_int(c"Top.flag") }, Ordering::SeqCst); + 0 +} + +/// `vpiFinish` from a due timer ends a timed run before the design's slot +/// at that time runs. +#[cfg(feature = "systemverilog")] +#[test] +fn a_finish_from_a_timer_stops_before_the_designs_slot() { + let _serial = lock_vpi(); + let source = "`timescale 1ns/1ns + module Top(output logic flag); + initial begin + flag = 0; + #5 flag = 1; + end + endmodule"; + let image = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("timer_finish.sv"))], + "Top", + ) + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let _session = install_timed_runtime(image, simulation).unwrap(); + FLAG_AT_END.store(-1, Ordering::SeqCst); + let mut delay = VpiTime { + type_: VPI_SIM_TIME, + low: 5, + ..VpiTime::default() + }; + let timer = VpiCbData { + reason: CB_AFTER_DELAY, + cb_rtn: Some(finish_from_a_timer), + obj: ptr::null_mut(), + time: &mut delay, + value: ptr::null_mut(), + index: 0, + user_data: ptr::null_mut(), + }; + let end = VpiCbData { + reason: CB_END_OF_SIMULATION, + cb_rtn: Some(record_flag_at_end), + ..timer + }; + // Safety: VPI registration on the session's thread. + unsafe { + assert!(!vpi_register_cb(&timer).is_null()); + assert!(!vpi_register_cb(&end).is_null()); + } + assert!(run_callbacks_result().unwrap()); + assert_eq!(celox_vpi_current_time(), 5); + assert_eq!(FLAG_AT_END.load(Ordering::SeqCst), 0); + clear_runtime(); +} From 562772933d0af468640413cc99d3cbad1cef3310 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 14:50:13 +0900 Subject: [PATCH 6/7] fix(vpi): honor callback finish requests before running more DUT work Propagate vpiFinish from slot observers through SlotIo::request_finish and Halt::Finish, stopping the running scheduler before its pending domains execute. IEEE 1800-2023 38.4 executes $finish on return from the application routine; 20.2 ends the simulation. Preserve writes already made by the observer. Run the fallback combinational settle through timed_step so the Simulation is out of the runtime borrow during observer dispatch, and its result and events are handled through the same path as scheduled steps. Use VERIFY_SHELL for the CI Icarus comparison, matching the external job's explicit development shell selection and its workflow regression contract. Validation: - Strengthened finish regression fails before the fix (count 1 instead of 0). - VPI suite with all ignored tests enabled: 158 passed, including cocotb and Icarus process-region comparisons. - Host library, native image and slot observer regressions: 236 passed; observer finish covered Native, Interpreter, Cranelift and Wasm. - Repository script suite: 296 passed. - Celox and celox-vpi all-target clippy, formatting and diff checks passed. Change-Id: Iac1ad02c9fa9f3f543f47663f23080e4b1204716 --- .github/workflows/ci.yml | 2 +- crates/celox-vpi/src/callbacks.rs | 10 ++++- crates/celox-vpi/tests/basic_vpi.rs | 69 +++++++++++++++++++++++++++++ crates/celox/src/lib.rs | 17 ++++++- crates/celox/src/simulation.rs | 21 +++++---- crates/celox/tests/slot_observer.rs | 60 +++++++++++++++++++++++++ 6 files changed, 168 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 60534e0687d..e95087eb916 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -377,7 +377,7 @@ jobs: - name: Cross-check cocotb time-step regions against Icarus if: matrix.suite == 'sv' && matrix.tool == 'icarus' run: >- - nix develop --no-update-lock-file --command + nix develop "$VERIFY_SHELL" --no-update-lock-file --command cargo test --locked -p celox-vpi --features systemverilog --test cocotb_e2e icarus_and_celox_agree_on_dut_processes -- --ignored --exact diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index d1055dc5ac7..1ddb11335e6 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -575,6 +575,11 @@ fn in_slot(io: &mut celox::SlotIo<'_, celox::NativeBackend>, time: u64, regions: super::with_timed_mut(|timed| unsafe { timed.enter_slot(io) }); regions(); super::with_timed_mut(super::TimedRuntime::leave_slot); + // vpiFinish takes effect when the application callback returns + // (IEEE 1800-2023 38.4), before the scheduler runs more DUT work. + if finish_requested() { + io.request_finish(); + } } /// Run `step` on the timed simulation, out of the session while it runs so @@ -664,7 +669,10 @@ pub(super) fn run_timed() -> bool { && with_host(|host| borrow_cell(&host.callbacks, |state| state.read_only_at)) != Some(time) { - with_simulation(|simulation| simulation.eval_comb()); + timed_step(|simulation| simulation.eval_comb()); + if finish_requested() { + break; + } take_timed_writes(); if let Regions::Done = settled_regions() { break; diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index e1747b3400f..151bb450beb 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3512,6 +3512,8 @@ fn a_finish_inside_a_time_step_ends_a_timed_run() { assert!(run_callbacks_result().unwrap()); assert_eq!(celox_vpi_current_time(), 5); assert_eq!(FINISH_EVENTS.load(Ordering::SeqCst), 3); + // The callback ends the run before the triggered domain can commit. + assert_eq!(unsafe { read_int(c"Top.count") }, 0); clear_runtime(); } @@ -3830,3 +3832,70 @@ fn a_finish_from_a_timer_stops_before_the_designs_slot() { assert_eq!(FLAG_AT_END.load(Ordering::SeqCst), 0); clear_runtime(); } + +#[cfg(feature = "systemverilog")] +unsafe extern "C" fn write_plain_data_input(_data: *mut VpiCbData) -> i32 { + // Safety: VPI calls on the session's thread. + assert!(unsafe { try_write_x() }); + 0 +} + +#[cfg(feature = "systemverilog")] +fn settle_plain_data_input(action: &str) -> Result { + let source = format!( + r#"`timescale 1ns/1ns + module Top(input logic x, output logic y); + assign y = x; + always_comb if (x) begin {action} end + initial #10 $finish; + endmodule"# + ); + let image = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("fallback_settle.sv"))], + "Top", + ) + .compile_native() + .unwrap() + .into_program_image(); + let simulation = celox::Simulation::from_sv_sources(Vec::new(), "") + .build_native_from_image(image.clone()) + .unwrap(); + let _session = install_timed_runtime(image, simulation).unwrap(); + let mut delay = VpiTime { + type_: VPI_SIM_TIME, + low: 5, + ..VpiTime::default() + }; + let timer = VpiCbData { + reason: CB_AFTER_DELAY, + cb_rtn: Some(write_plain_data_input), + obj: ptr::null_mut(), + time: &mut delay, + value: ptr::null_mut(), + index: 0, + user_data: ptr::null_mut(), + }; + // Safety: registration copies live callback data on the session's thread. + unsafe { + assert!(!vpi_register_cb(&timer).is_null()); + } + let result = run_callbacks_result(); + assert_eq!(celox_vpi_current_time(), 5); + clear_runtime(); + result +} + +#[cfg(feature = "systemverilog")] +#[test] +fn a_plain_input_settle_finishes_cleanly() { + let _serial = lock_vpi(); + assert!(settle_plain_data_input("$finish;").unwrap()); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn a_plain_input_settle_reports_fatal_errors() { + let _serial = lock_vpi(); + let error = settle_plain_data_input("$fatal(1, \"fallback failure\");").unwrap_err(); + assert!(error.contains("fallback failure"), "{error}"); +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 0ff34139732..864a29c7d0a 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -178,11 +178,26 @@ mod host_api { pub struct SlotIo<'a, B: SimBackend = DefaultBackend> { io: IOContext<'a, B>, wrote: bool, + finish_requested: bool, } impl<'a, B: SimBackend> SlotIo<'a, B> { pub(crate) fn new(io: IOContext<'a, B>) -> Self { - Self { io, wrote: false } + Self { + io, + wrote: false, + finish_requested: false, + } + } + + /// End the simulation when this observer callback returns, before + /// any further scheduled work runs. Earlier host writes remain in state. + pub fn request_finish(&mut self) { + self.finish_requested = true; + } + + pub(crate) fn finish_requested(&self) -> bool { + self.finish_requested } pub(crate) fn wrote(&self) -> bool { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index a67fc71c16d..a64d922aa6b 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -259,10 +259,12 @@ impl HostBoundary for Simulator { } fn before_domains(&mut self, timestamp: u64) -> Result { - Ok(!self.frozen - && self.show_slot(timestamp, |observer, io, time| { - observer.before_domains(io, time) - })) + if self.frozen { + return Ok(false); + } + self.show_slot(timestamp, |observer, io, time| { + observer.before_domains(io, time) + }) } fn take_slot_writes(&mut self) -> bool { @@ -323,7 +325,7 @@ impl HostBoundary for Simulator { if !self.frozen { self.slot_writes |= self.show_slot(timestamp, |observer, io, time| { observer.end_of_slot(io, time) - }); + })?; } Ok(()) } @@ -336,9 +338,9 @@ impl Simulator { &mut self, time: u64, show: impl FnOnce(&mut dyn SlotObserver, &mut crate::SlotIo<'_, B>, u64), - ) -> bool { + ) -> Result { let Some(observer) = self.slot_observer.as_deref_mut() else { - return false; + return Ok(false); }; let mut io = crate::SlotIo::new(crate::IOContext { backend: &mut self.backend, @@ -347,7 +349,10 @@ impl Simulator { show(observer, &mut io, time); let wrote = io.wrote(); self.dirty |= wrote; - wrote + if io.finish_requested() { + return Err(Halt::Finish); + } + Ok(wrote) } } diff --git a/crates/celox/tests/slot_observer.rs b/crates/celox/tests/slot_observer.rs index 0731e515e57..a85ba9175d3 100644 --- a/crates/celox/tests/slot_observer.rs +++ b/crates/celox/tests/slot_observer.rs @@ -215,3 +215,63 @@ fn a_differential_simulation_stops_checking_an_observed_simulation() { assert_eq!(stats.checked_steps, 0); assert!(stats.unchecked.is_some()); } + +struct FinishAtFive { + before_domains: bool, + write: SignalRef, +} + +impl SlotObserver for FinishAtFive { + fn before_domains(&mut self, io: &mut SlotIo<'_, B>, time: u64) { + if self.before_domains && time == 5 { + io.set(self.write, 55u8); + io.request_finish(); + } + } + + fn end_of_slot(&mut self, io: &mut SlotIo<'_, B>, time: u64) { + if !self.before_domains && time == 5 { + io.set(self.write, 55u8); + io.request_finish(); + } + } +} + +fn check_observer_finish(mut sim: Simulation, before_domains: bool) { + let clk = sim.signal("clk"); + let written = sim.signal("d"); + sim.observe_slots( + Box::new(FinishAtFive { + before_domains, + write: written, + }), + &[clk], + ); + sim.run_until(40).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(sim.signal("q")), u8::from(!before_domains).into()); + assert_eq!(sim.get(sim.signal("ticks")), 0u8.into()); + assert_eq!(sim.get(written), 55u8.into()); + sim.run_until(100).unwrap(); + assert_eq!(sim.time(), 5); + assert_eq!(sim.get(sim.signal("q")), u8::from(!before_domains).into()); +} + +fn check_observer_finish_backends(before_domains: bool) { + let build = || Simulation::from_sv_sources(vec![(COUNTER, Path::new("top.sv"))], "Top"); + check_observer_finish(build().build_native().unwrap(), before_domains); + check_observer_finish(build().build_interpreter().unwrap(), before_domains); + check_observer_finish(build().build_cranelift().unwrap(), before_domains); + check_observer_finish(build().build_wasm().unwrap(), before_domains); +} + +#[test] +fn an_observer_can_finish_before_domains_commit() { + check_observer_finish_backends(true); +} + +#[test] +fn an_observer_can_finish_at_the_end_of_a_slot() { + check_observer_finish_backends(false); +} From 0ac8fee3698396f82da09ce79c82910456c4574f Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 14:59:10 +0900 Subject: [PATCH 7/7] test(vpi): keep observer finish regressions independent of optional backends Retain Native and Interpreter coverage for compiled and reference execution without requiring the optional Cranelift and Wasm builder methods introduced on current master. All four backends were verified during local validation; both retained observer finish regressions pass. Change-Id: Ifefe2684679445782a2f28d1b4d38f596caaca91 --- crates/celox/tests/slot_observer.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/celox/tests/slot_observer.rs b/crates/celox/tests/slot_observer.rs index a85ba9175d3..707ecaa39d5 100644 --- a/crates/celox/tests/slot_observer.rs +++ b/crates/celox/tests/slot_observer.rs @@ -262,8 +262,6 @@ fn check_observer_finish_backends(before_domains: bool) { let build = || Simulation::from_sv_sources(vec![(COUNTER, Path::new("top.sv"))], "Top"); check_observer_finish(build().build_native().unwrap(), before_domains); check_observer_finish(build().build_interpreter().unwrap(), before_domains); - check_observer_finish(build().build_cranelift().unwrap(), before_domains); - check_observer_finish(build().build_wasm().unwrap(), before_domains); } #[test]