From 96dd4066fa1f9761c8a78825e383e8752cc5cc41 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 06:43:19 +0900 Subject: [PATCH 1/9] 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/9] 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/9] 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/9] 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/9] 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 7c6f1e57a9b57a856f6cef8a9bfddf262c334833 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 07:10:42 +0900 Subject: [PATCH 6/9] feat(sv)!: execute final procedures at simulation termination SystemVerilog final procedures were rejected, so testbenches could not inspect their last state or report results at termination. Preserve them as terminal process kernels and run them once on $finish, $fatal, or explicit Simulation::finish(). The batch CLI and sv-tests driver finish on quiescence; bounded host runs remain resumable. Program finals also run after implicit termination. Keep final execution sequential and at zero simulation time. Resume $stop inside final at its cursor, stop immediately at $finish inside final, preserve the initiating fatal error, and prevent queued HDL events or deferred assertions from executing after termination. Validate function-statement restrictions, including omitted argument defaults. Route fatal errors from explicit waveform dumps and end-of-run waveform evaluation through the same terminal phase. Finalize immediate fatal errors raised by lazy runtime-event draining before collecting reports. Settle and execute final procedures before capturing saved state, and reject saving if final execution stops. Keep differential scheduling synchronized on these host-triggered termination paths. Document the lifecycle and restrictions. Validation: - 18 final API tests cover two/four-state Interpreter, Cranelift, WASM, Native and Tiered execution, differential scheduling, checkpoints and native-image roundtrip. - CI follow-up: default-feature library 150, enabled-feature library 229, VCD 36, reference-adapter 7, the unsupported-construct regression and JS boundary 9 tests pass. Formatting and Clippy pass. Fatal errors terminate execution while preserving the original diagnostic and waveform; tests no longer require recovery from $fatal. - P2 regression coverage: all four added tests fail before the fix and pass after it. Related library, checkpoint, observer, runtime API, state-file, deferred-assertion and VCD tests pass (1,281 tests; 34 existing ignores). Rebuilt the debug NAPI addon; 28 JS checkpoint/runtime-event/timing tests, formatting and Clippy pass. - Direct portable fixtures: Icarus 13.0 passes all three; Verilator 5.052 passes state/hierarchy but continues after $finish inside final, contrary to 9.2.3. Keep immediate-termination expectations. These fixtures use owning-crate API tests because the shared timed emitter has its own final checker with unspecified relative ordering. - Focused sv-tests rerun: 70 additional passing cases per mode out of 108 previously blocked by final; update exactly 140 measured expectations. Full release-driver conformance remains in CI as requested. BREAKING CHANGE: ProcessSlots and ProcessRefs use ProcessKind instead of is_initializer; fatal errors have a distinct Fatal variant; SimulationState::finish is fallible; native image format advances to version 39. Change-Id: I75200be6ce640d73a84562a25ff48cdae2237106 --- conformance/sv-tests/expected.tsv | 280 +++++----- crates/celox-design/src/lib.rs | 19 +- crates/celox-frontend-core/src/sdk.rs | 2 +- .../src/symbolic/assembly.rs | 2 +- crates/celox-frontend-sv/src/lowering.rs | 24 +- crates/celox-runtime/src/error.rs | 23 +- crates/celox-runtime/src/schedule.rs | 6 +- .../celox-runtime/src/simulation/compiled.rs | 4 + crates/celox-runtime/src/simulation/mod.rs | 71 +-- .../celox-runtime/src/simulation/persist.rs | 21 +- .../celox-runtime/src/simulation/process.rs | 7 +- .../celox-runtime/src/simulation/terminal.rs | 99 ++++ crates/celox-runtime/src/simulation/time.rs | 5 +- crates/celox-runtime/src/timing.rs | 4 +- crates/celox-sv-analyzer/src/ast.rs | 24 +- .../src/ast/array_parameters.rs | 3 +- .../celox-sv-analyzer/src/ast/comb_process.rs | 5 +- .../src/ast/const_functions.rs | 88 +-- .../celox-sv-analyzer/src/ast/ff_process.rs | 5 +- .../celox-sv-analyzer/src/ast/procedural.rs | 36 +- .../src/ast/procedural/final_procedures.rs | 182 ++++++ .../src/ast/procedural/timed_tasks.rs | 9 +- crates/celox-sv-analyzer/src/ast/scope.rs | 18 +- .../celox-sv-analyzer/src/ast/validation.rs | 42 +- crates/celox-sv-analyzer/src/ir.rs | 30 +- crates/celox-sv-analyzer/src/parsed.rs | 2 +- .../src/source_tree/tests/process_roots.rs | 31 +- .../celox-sv-analyzer/src/system_functions.rs | 2 + crates/celox-sv-analyzer/src/tests.rs | 210 +++++++ crates/celox-vpi/src/bin/celox.rs | 29 +- crates/celox/examples/sv_tests.rs | 25 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/scheduler.rs | 4 +- crates/celox/src/simulation.rs | 103 +++- crates/celox/src/simulation/differential.rs | 22 + .../src/simulation/runtime_core_tests.rs | 2 +- crates/celox/src/simulator.rs | 67 ++- crates/celox/src/simulator/builder.rs | 2 +- crates/celox/src/simulator/state_file.rs | 9 +- crates/celox/tests/comb_observer.rs | 14 +- crates/celox/tests/fixtures/final/finish.sv | 19 + .../celox/tests/fixtures/final/hierarchy.sv | 15 + crates/celox/tests/fixtures/final/state.sv | 16 + .../tests/frontends/systemverilog/final.rs | 521 ++++++++++++++++++ .../systemverilog/review_regressions.rs | 8 - crates/celox/tests/runtime_api.rs | 4 +- crates/celox/tests/shared_jit_cache.rs | 19 + crates/celox/tests/sv_vcd.rs | 26 +- crates/celox/tests/systemverilog.rs | 2 + crates/celox/tests/test_utils/veryl_sim.rs | 2 +- crates/celox/tests/veryl_reference_adapter.rs | 2 +- docs/guide/systemverilog-reference.md | 28 +- docs/guide/systemverilog.md | 5 +- 53 files changed, 1835 insertions(+), 365 deletions(-) create mode 100644 crates/celox-runtime/src/simulation/terminal.rs create mode 100644 crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs create mode 100644 crates/celox/tests/fixtures/final/finish.sv create mode 100644 crates/celox/tests/fixtures/final/hierarchy.sv create mode 100644 crates/celox/tests/fixtures/final/state.sv create mode 100644 crates/celox/tests/frontends/systemverilog/final.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index a6186810a34..404b148ae0e 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -777,18 +777,18 @@ chapter-21/21.2--write-boh.sv 2state pass chapter-21/21.2--write-boh.sv 4state pass chapter-21/21.2--write.sv 2state pass chapter-21/21.2--write.sv 4state pass -chapter-21/21.3--fdisplay-boh.sv 2state fail -chapter-21/21.3--fdisplay-boh.sv 4state fail -chapter-21/21.3--fdisplay.sv 2state fail -chapter-21/21.3--fdisplay.sv 4state fail +chapter-21/21.3--fdisplay-boh.sv 2state pass +chapter-21/21.3--fdisplay-boh.sv 4state pass +chapter-21/21.3--fdisplay.sv 2state pass +chapter-21/21.3--fdisplay.sv 4state pass chapter-21/21.3--feof.sv 2state pass chapter-21/21.3--feof.sv 4state pass chapter-21/21.3--ferror.sv 2state fail chapter-21/21.3--ferror.sv 4state fail chapter-21/21.3--fflush.sv 2state pass chapter-21/21.3--fflush.sv 4state pass -chapter-21/21.3--fgetc.sv 2state fail -chapter-21/21.3--fgetc.sv 4state fail +chapter-21/21.3--fgetc.sv 2state pass +chapter-21/21.3--fgetc.sv 4state pass chapter-21/21.3--fgets.sv 2state fail chapter-21/21.3--fgets.sv 4state fail chapter-21/21.3--file.sv 2state pass @@ -797,16 +797,16 @@ chapter-21/21.3--fmonitor.sv 2state fail chapter-21/21.3--fmonitor.sv 4state fail chapter-21/21.3--fpos.sv 2state pass chapter-21/21.3--fpos.sv 4state pass -chapter-21/21.3--fread.sv 2state fail -chapter-21/21.3--fread.sv 4state fail -chapter-21/21.3--fscanf.sv 2state fail -chapter-21/21.3--fscanf.sv 4state fail +chapter-21/21.3--fread.sv 2state pass +chapter-21/21.3--fread.sv 4state pass +chapter-21/21.3--fscanf.sv 2state pass +chapter-21/21.3--fscanf.sv 4state pass chapter-21/21.3--fstrobe.sv 2state fail chapter-21/21.3--fstrobe.sv 4state fail -chapter-21/21.3--fwrite-boh.sv 2state fail -chapter-21/21.3--fwrite-boh.sv 4state fail -chapter-21/21.3--fwrite.sv 2state fail -chapter-21/21.3--fwrite.sv 4state fail +chapter-21/21.3--fwrite-boh.sv 2state pass +chapter-21/21.3--fwrite-boh.sv 4state pass +chapter-21/21.3--fwrite.sv 2state pass +chapter-21/21.3--fwrite.sv 4state pass chapter-21/21.3--sscanf.sv 2state pass chapter-21/21.3--sscanf.sv 4state pass chapter-21/21.3--ungetc.sv 2state fail @@ -1579,8 +1579,8 @@ chapter-9/9.2.2.3--always_latch.sv 2state fail chapter-9/9.2.2.3--always_latch.sv 4state fail chapter-9/9.2.2.4--always_ff.sv 2state pass chapter-9/9.2.2.4--always_ff.sv 4state pass -chapter-9/9.2.3--final.sv 2state fail -chapter-9/9.2.3--final.sv 4state fail +chapter-9/9.2.3--final.sv 2state pass +chapter-9/9.2.3--final.sv 4state pass chapter-9/9.3.1--sequential_block.sv 2state pass chapter-9/9.3.1--sequential_block.sv 4state pass chapter-9/9.3.2--parallel_block_join.sv 2state fail @@ -1735,46 +1735,46 @@ generated/assignment_op/11.4.1--plus_assignment.sv 2state pass generated/assignment_op/11.4.1--plus_assignment.sv 4state pass generated/assignment_op/11.4.1--xor_assignment.sv 2state pass generated/assignment_op/11.4.1--xor_assignment.sv 4state pass -generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state fail +generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state pass generated/binary_op/11.4.10--binary_op_arith_shl.sv 2state pass generated/binary_op/11.4.10--binary_op_arith_shl.sv 4state pass generated/binary_op/11.4.10--binary_op_arith_shr.sv 2state pass @@ -2467,22 +2467,22 @@ generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 2s generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 4state fail generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 2state fail generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state fail +generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state pass generated/nets/6.6.1--net_tri.sv 2state pass generated/nets/6.6.1--net_tri.sv 4state pass generated/nets/6.6.1--net_wire.sv 2state pass @@ -2507,42 +2507,42 @@ generated/nets/6.6.6--net_supply0.sv 2state fail generated/nets/6.6.6--net_supply0.sv 4state fail generated/nets/6.6.6--net_supply1.sv 2state fail generated/nets/6.6.6--net_supply1.sv 4state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state pass generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 2state pass generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 4state pass generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 2state pass generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 4state pass -generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state pass generated/operators_sim/11.4.3--simple_div_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_div_operator_sim.sv 4state pass generated/operators_sim/11.4.3--simple_exp_operator_sim.sv 2state pass @@ -2555,22 +2555,22 @@ generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 4state pass generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 4state pass -generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state pass generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 4state pass generated/operators_sim/11.4.4--simple_gt_operator_sim.sv 2state pass @@ -2579,14 +2579,14 @@ generated/operators_sim/11.4.4--simple_le_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_le_operator_sim.sv 4state pass generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 4state pass -generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state pass generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 4state pass generated/operators_sim/11.4.5--simple_eq_xz_operator_sim.sv 2state pass @@ -2595,18 +2595,18 @@ generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 4state pass generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 4state pass -generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state pass generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 2state pass generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 4state pass generated/operators_sim/11.4.8--simple_bit_or_operator_sim.sv 2state pass diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7294c286a4e..42bf3b118f7 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -616,6 +616,17 @@ impl std::fmt::Display for ProcessOrigin { } } +/// When a procedural kernel is invoked by the runtime. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ProcessKind { + /// Static declarations run before ordinary HDL procedures. + Initializer, + #[default] + Regular, + /// A final procedure runs only when simulation ends (IEEE 1800-2023 9.2.3). + Final, +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to @@ -625,9 +636,9 @@ impl std::fmt::Display for ProcessOrigin { /// checkpoints capture a suspended process. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { - /// A static declaration initializer, executed before all HDL procedures. - pub is_initializer: bool, - /// This kernel originated from an edge procedure and must execute in Simulation. + /// The phase in which the runtime invokes this kernel. + pub kind: ProcessKind, + /// This kernel requires Simulation's process scheduler rather than Simulator. pub requires_timed_simulation: bool, /// Every delay the kernel suspends for is a constant of at least one /// time unit. @@ -646,7 +657,7 @@ pub struct ProcessSlots { impl ProcessSlots { pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots { ProcessSlots { - is_initializer: self.is_initializer, + kind: self.kind, requires_timed_simulation: self.requires_timed_simulation, const_delays: self.const_delays, program: self.program.map(&mut map), diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index f955fda9e87..c5c89c1135f 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1729,7 +1729,7 @@ fn lower_processes( for (index, process) in artifact.processes().iter().enumerate() { let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; let slots = ProcessSlots { - is_initializer: false, + kind: celox_design::ProcessKind::Regular, requires_timed_simulation: false, const_delays: false, program: None, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 1b720f15176..e01059c7e68 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1940,7 +1940,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(); let declaration_startup = processes .iter() - .any(|process| process.slots.is_initializer) + .any(|process| process.slots.kind == celox_design::ProcessKind::Initializer) .then(|| { let targets: BTreeSet<_> = folded_initials.iter().map(|init| init.address).collect(); let mut reset = targets diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b5b0d177f4c..11a49c86e24 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1348,7 +1348,7 @@ fn kernel_window_writes( for process in module .initial_processes() .iter() - .filter(|process| !process.is_initializer()) + .filter(|process| !process.is_initializer() && !process.is_final()) { let body = process.body(); let first = if process.repeats() { @@ -4978,6 +4978,7 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig let construct = match process.site() { Some(site) => site.construct, None if process.is_initializer() => "declaration initializer", + None if process.is_final() => "final", None if process.repeats() => "always", None => "initial", }; @@ -4988,9 +4989,9 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig } } -/// The `initial` blocks and declaration initializers (IEEE 1800-2023 9.2.1, -/// 10.5): the initial state they define, and the processes that run the -/// others from time zero. +/// Lower declaration initializers and procedural kernels. Final procedures +/// retain kernels but execute only at simulation termination (9.2.3); they +/// must never contribute folded initial state. /// /// A block whose writes have constant values defines initial state, with /// the hidden variables used while executing it discarded. Declaration @@ -5062,7 +5063,10 @@ fn lower_initial_processes( // initial state. A program's `initial` procedure runs in the reactive // region set (IEEE 1800-2023 24.3.1), after the design's processes of // time zero, so it is not folded either. - if process.repeats() || (module.is_program() && !process.is_initializer()) { + if process.is_final() + || process.repeats() + || (module.is_program() && !process.is_initializer()) + { runtime.push((process, random_seed)); continue; } @@ -5138,8 +5142,8 @@ fn lower_initial_processes( id }; ProcessSlots { - is_initializer: process.is_initializer(), - requires_timed_simulation: process.is_scheduled_edge(), + kind: process.kind(), + requires_timed_simulation: process.is_scheduled_edge() || process.is_final(), const_delays: false, program: None, resume: declare("resume", PROCESS_RESUME_WIDTH), @@ -5155,10 +5159,10 @@ fn lower_initial_processes( let program = slots .iter() .zip(&runtime) - .find(|(_, (process, _))| !process.is_initializer()) + .find(|(_, (process, _))| !process.is_initializer() && !process.is_final()) .map(|(slots, _)| slots.status); for (slots, (process, _)) in slots.iter_mut().zip(&runtime) { - if !process.is_initializer() { + if !process.is_initializer() && !process.is_final() { slots.program = program; } } @@ -10725,7 +10729,7 @@ endmodule .runtime_schema .processes .iter() - .filter(|process| !process.is_initializer) + .filter(|process| process.kind != celox_design::ProcessKind::Initializer) .count() } diff --git a/crates/celox-runtime/src/error.rs b/crates/celox-runtime/src/error.rs index 33603a87ee6..5cb9f3f2f03 100644 --- a/crates/celox-runtime/src/error.rs +++ b/crates/celox-runtime/src/error.rs @@ -5,6 +5,11 @@ pub enum SimulatorErrorCode { DetectedTrueLoopAt { signals: Vec, }, + /// `$fatal` also implicitly requests simulation termination. + Fatal { + message: String, + signals: Vec, + }, Runtime { message: String, signals: Vec, @@ -36,6 +41,16 @@ impl PartialEq for SimulatorErrorCode { signals: sb, }, ) => a == b && sa == sb, + ( + Self::Fatal { + message: a, + signals: sa, + }, + Self::Fatal { + message: b, + signals: sb, + }, + ) => a == b && sa == sb, (Self::NotAnEvent(a), Self::NotAnEvent(b)) => a == b, _ => false, } @@ -54,8 +69,12 @@ impl std::fmt::Display for SimulatorErrorCode { Self::DetectedTrueLoopAt { signals } => { write!(f, "Detected True Loop: {}", signals.join(", ")) } - Self::Runtime { message, signals } if signals.is_empty() => write!(f, "{message}"), - Self::Runtime { message, signals } => { + Self::Fatal { message, signals } | Self::Runtime { message, signals } + if signals.is_empty() => + { + write!(f, "{message}") + } + Self::Fatal { message, signals } | Self::Runtime { message, signals } => { write!(f, "{}: {}", message, signals.join(", ")) } Self::InternalError => write!(f, "Internal Error"), diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 064c9049bad..99e07af4d2a 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -198,7 +198,7 @@ impl ResolvedSchedule { .processes .iter() .map(|process| ProcessRefs { - is_initializer: process.slots.is_initializer, + kind: process.slots.kind, program: process.slots.program.as_ref().map(resolve), resume: resolve(&process.slots.resume), starts_with_event_wait: process.slots.requires_timed_simulation, @@ -312,7 +312,9 @@ impl ResolvedSchedule { program_processes: processes .iter() .enumerate() - .filter(|(_, process)| process.program.is_some()) + .filter(|(_, process)| { + process.kind == celox_design::ProcessKind::Regular && process.program.is_some() + }) .map(|(index, _)| index) .collect(), processes, diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 7173050bca6..852dd20dd2e 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -161,6 +161,10 @@ impl SimulationState { } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } let _ = self.finish_timed_boundary(executor, self.scheduler.time); let _ = executor.flush_output(); Err(error) diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index dded48af181..a0e68d89208 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -10,6 +10,7 @@ mod persist; mod process; mod round; mod stats; +mod terminal; mod time; mod wait; @@ -146,6 +147,8 @@ pub struct SimulationState { host_pending: bool, /// A process requested the end of the simulation. finished: bool, + /// Next final procedure while terminal execution is suspended by `$stop`. + finalizing: Option, /// A process suspended the simulation (`$stop`) in the last step. stopped: bool, /// The round a `$stop` suspended, which the next step continues. @@ -193,7 +196,9 @@ impl SimulationState { .processes .iter() .enumerate() - .filter_map(|(index, process)| process.is_initializer.then_some(index)) + .filter_map(|(index, process)| { + (process.kind == celox_design::ProcessKind::Initializer).then_some(index) + }) .collect(); let declarations_pending = !declaration_processes.is_empty(); let mut state = Self { @@ -202,6 +207,7 @@ impl SimulationState { last_clock_unknown: BitSet::new(), four_state: backend.layout().four_state, process_wakeups: (0..model.processes.len()) + .filter(|&index| model.processes[index].kind != celox_design::ProcessKind::Final) .map(|process| Reverse((0, process))) .collect(), model, @@ -210,6 +216,7 @@ impl SimulationState { declarations_pending, host_pending: false, finished: false, + finalizing: None, stopped: false, suspended: None, scratch: None, @@ -253,6 +260,13 @@ impl SimulationState { E: SimulationExecutor, { self.stopped = false; + if self.finalizing.is_some() { + if self.scheduler.time > limit { + return Ok(None); + } + self.finalize_terminal(executor)?; + return Ok(Some(self.scheduler.time)); + } match self.step_time(executor, limit) { Ok(time) => Ok(time), Err(Halt::Finish) => { @@ -262,6 +276,10 @@ impl SimulationState { // The time slot goes on when the simulation continues. Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } // Preserve the primary runtime failure even if diagnostic // waveform output also fails. This does not resume processes. let _ = self.finish_timed_boundary(executor, self.scheduler.time); @@ -312,7 +330,10 @@ impl SimulationState { // A process the scheduler does not run waits: the slot stays in // the reference loop. Test that first, as designs with such // processes fail it at every step. - let compiled = if compiles && self.process_state.waiters.len() <= waiting_kernels { + let compiled = if self.finalizing.is_none() + && compiles + && self.process_state.waiters.len() <= waiting_kernels + { self.compiled_limit(executor, end, observer.one_slot()) } else { None @@ -405,9 +426,14 @@ impl SimulationState { { match executor.try_finish_timed_step(time) { Ok(()) => Ok(()), - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + } + Err(error) + } Err(Halt::Finish) => { - self.finish_checked(executor)?; + self.finalize_terminal(executor)?; Ok(()) } Err(Halt::Stop) => { @@ -417,34 +443,6 @@ impl SimulationState { } } - fn finish_checked(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> - where - E: SimulationExecutor, - { - self.finished = true; - executor.try_freeze() - } - - /// Once $finish is consumed, output errors must not make execution resumable. - pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> - where - E: SimulationExecutor, - { - self.finished = true; - let output = self.finish_timed_boundary(executor, self.scheduler.time); - let frozen = executor.try_freeze(); - output.and(frozen) - } - - /// End the simulation where it is. - pub fn finish(&mut self, executor: &mut E) - where - E: SimulationExecutor, - { - self.finished = true; - executor.freeze(); - } - /// Whether a process requested the end of the simulation. pub fn is_finished(&self) -> bool { self.finished @@ -461,7 +459,8 @@ impl SimulationState { /// Whether the simulation is suspended in the middle of a time slot, so /// that its scheduling state cannot be captured. pub fn is_suspended(&self) -> bool { - self.suspended.is_some() || (self.stopped && self.declarations_pending) + self.suspended.is_some() + || (self.stopped && (self.declarations_pending || self.finalizing.is_some())) } /// Settle externally driven state against the previous edge baseline even @@ -486,6 +485,10 @@ impl SimulationState { } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } // Preserve the primary runtime failure even if diagnostic // waveform output also fails. This does not resume processes. let _ = self.finish_timed_boundary(executor, self.scheduler.time); @@ -556,7 +559,7 @@ impl SimulationState { return None; } // Host writes are work of the current time. - if self.host_pending { + if self.host_pending || self.finalizing.is_some() { return Some(self.scheduler.time); } self.next_work_time() diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index aa0a94ff8e9..d652d9f9e82 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -26,6 +26,7 @@ impl SimulationState { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, } } @@ -63,6 +64,7 @@ impl SimulationState { self.declarations_pending = snapshot.declarations_pending; self.host_pending = snapshot.host_pending; self.finished = snapshot.finished; + self.finalizing = snapshot.finalizing; self.stopped = false; self.suspended = None; Ok(()) @@ -190,17 +192,14 @@ impl SimulationState { .map(|(process, time)| Reverse((time, process))) .collect(); self.process_state = parts.process_state; - self.declarations_pending = self - .process_wakeups - .iter() - .any(|Reverse((_, index))| self.model.processes[*index].is_initializer) - || self - .process_state - .ready - .iter() - .any(|&index| self.model.processes[index].is_initializer); + self.declarations_pending = self.process_wakeups.iter().any(|Reverse((_, index))| { + self.model.processes[*index].kind == celox_design::ProcessKind::Initializer + }) || self.process_state.ready.iter().any(|&index| { + self.model.processes[index].kind == celox_design::ProcessKind::Initializer + }); self.host_pending = parts.host_pending; self.finished = parts.finished; + self.finalizing = None; self.stopped = false; self.suspended = None; } @@ -218,6 +217,7 @@ pub struct SimulationSnapshot { declarations_pending: bool, host_pending: bool, finished: bool, + finalizing: Option, } impl Clone for SimulationSnapshot { @@ -233,6 +233,7 @@ impl Clone for SimulationSnapshot { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, } } } @@ -300,6 +301,7 @@ impl SimulationState { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, stopped: self.stopped, suspended: self.suspended.is_some(), } @@ -329,6 +331,7 @@ pub struct ScheduleKey { pub declarations_pending: bool, pub host_pending: bool, pub finished: bool, + pub finalizing: Option, pub stopped: bool, pub suspended: bool, } diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index bc74b2729d8..e8a7324dabd 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -29,7 +29,12 @@ impl SimulationState { self.stopped = true; Ok(()) } - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + } + Err(error) + } } } diff --git a/crates/celox-runtime/src/simulation/terminal.rs b/crates/celox-runtime/src/simulation/terminal.rs new file mode 100644 index 00000000000..8d2553e935d --- /dev/null +++ b/crates/celox-runtime/src/simulation/terminal.rs @@ -0,0 +1,99 @@ +//! Terminal procedures run sequentially, without scheduling another HDL event. + +use celox_design::{HostRequestKind, ProcessKind, ProcessStatus}; + +use super::{SimulationExecutor, SimulationState}; +use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; + +impl SimulationState { + /// Finish once, running final procedures before flushing output and freezing. + /// A `$stop` in a final procedure suspends this phase; the next step resumes it. + pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + if self.finished { + return Ok(()); + } + self.stopped = false; + if self.finalizing.is_none() { + // An explicit host finish may replace a stopped ordinary round. + self.suspended = None; + self.host_pending = false; + self.finalizing = Some(0); + } + let result = self.run_final_procedures(executor); + if matches!(result, Err(Halt::Stop)) { + self.stopped = true; + return Ok(()); + } + // A failed final procedure or output flush cannot make termination resumable. + self.finished = true; + self.finalizing = None; + let output = self.finish_timed_boundary(executor, self.scheduler.time); + let frozen = executor.try_freeze(); + match result { + Ok(()) | Err(Halt::Finish) => output.and(frozen), + Err(Halt::Error(error)) => Err(error), + Err(Halt::Stop) => unreachable!(), + } + } + + /// Explicitly end simulation at its current time. Merely exhausting currently + /// scheduled work does not end an externally driven simulation. + pub fn finish(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.finalize_terminal(executor) + } + + fn run_final_procedures(&mut self, executor: &mut E) -> Result<(), Halt> + where + E: SimulationExecutor, + { + let mut returns = 0; + while let Some(index) = self + .finalizing + .filter(|&index| index < self.model.processes.len()) + { + let process = &self.model.processes[index]; + if process.kind != ProcessKind::Final { + self.finalizing = Some(index + 1); + continue; + } + executor.run_process(index)?; + returns += 1; + self.charge(returns, Some(index))?; + let status: u8 = executor.backend().get_as(process.status); + match ProcessStatus::from_code(status) { + Some(ProcessStatus::Done) => self.finalizing = Some(index + 1), + Some(ProcessStatus::Finish) => return Err(Halt::Finish), + Some(ProcessStatus::Stop) => return Err(Halt::Stop), + Some(ProcessStatus::HostRequest) => { + let encoded: u64 = executor.backend().get_as(process.delay); + let (kind, site) = HostRequestKind::decode(encoded) + .ok_or(SimulatorErrorCode::InternalError)?; + let request = process + .host_requests + .iter() + .filter(|request| request.kind == kind) + .nth(site as usize) + .ok_or(SimulatorErrorCode::InternalError)?; + executor.host_request(request, self.scheduler.time)?; + } + // Yield is an implementation boundary, not an HDL timing control. + // NBA events created by a final never run after termination (9.2.3). + Some(ProcessStatus::Yield | ProcessStatus::Nba) => {} + _ => { + return Err(SimulatorErrorCode::Runtime { + message: "final procedure cannot suspend for HDL timing".into(), + signals: Vec::new(), + } + .into()); + } + } + } + Ok(()) + } +} diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index e25822ae243..89f621c1e8d 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -299,7 +299,10 @@ impl SimulationState { if self.finished { return None; } - if !self.process_state.ready.is_empty() || !self.process_state.reactive.is_empty() { + if self.finalizing.is_some() + || !self.process_state.ready.is_empty() + || !self.process_state.reactive.is_empty() + { return Some(self.scheduler.time); } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 9edb4ed0927..20cdc112493 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -153,7 +153,7 @@ pub struct NbaSiteRefs { /// Control slots and sites of one process kernel. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { - pub is_initializer: bool, + pub kind: celox_design::ProcessKind, /// The status slot naming the program instance of a program kernel /// ([`celox_design::ProcessSlots::program`]), which runs in the reactive /// region set. @@ -175,7 +175,7 @@ impl ProcessRefs { /// A process without wait or nonblocking sites. pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { - is_initializer: false, + kind: celox_design::ProcessKind::Regular, program: None, resume: status, starts_with_event_wait: false, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index cb6cbe72434..9472313a755 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1331,7 +1331,7 @@ impl Module { // Declaration initializers run before the other initial blocks. let first_block = initial_processes .iter() - .position(|process| !process.initializer) + .position(|process| !process.is_initializer()) .unwrap_or(initial_processes.len()); initial_processes.insert( first_block, @@ -1340,7 +1340,8 @@ impl Module { site: None, condition: None, body: static_initializers, - initializer: true, + kind: celox_design::ProcessKind::Initializer, + validation_body: Vec::new(), synthetic: false, repeats: false, }, @@ -1379,6 +1380,7 @@ impl Module { } for process in &mut initial_processes { process.body = body(std::mem::take(&mut process.body)); + process.validation_body = body(std::mem::take(&mut process.validation_body)); } for subroutine in &mut subroutines { *subroutine = rename.subroutine(subroutine.clone()); @@ -2535,14 +2537,16 @@ impl FfProcess { } } -/// An `initial` process. +/// A scheduled procedure, including initial/always processes and final procedures. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, site: Option, condition: Option, body: Vec, - initializer: bool, + kind: celox_design::ProcessKind, + /// Folded-away statements retained only for final-procedure legality checks. + validation_body: Vec, synthetic: bool, /// An `always` process: its body runs forever. repeats: bool, @@ -2562,6 +2566,16 @@ impl InitialProcess { self.condition.as_ref() } + /// The procedure's simulation phase. + pub fn kind(&self) -> celox_design::ProcessKind { + self.kind + } + + /// A final procedure runs once when the simulation finishes (9.2.3). + pub fn is_final(&self) -> bool { + self.kind == celox_design::ProcessKind::Final + } + /// Compiler-generated storage initialization, without a user static process. pub fn is_synthetic(&self) -> bool { self.synthetic @@ -2569,7 +2583,7 @@ impl InitialProcess { /// Whether this process holds variable declaration initializers. pub fn is_initializer(&self) -> bool { - self.initializer + self.kind == celox_design::ProcessKind::Initializer } /// Whether this is an `always` process, which runs its body forever and diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index 6dfd67cbc94..8429bf932e9 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -220,7 +220,8 @@ impl ArrayParameter { rhs: value, nonblocking: false, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: true, repeats: false, }) diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index d958288a35a..4bc6aaf825e 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -295,7 +295,10 @@ fn comb_process_from_procedure( parameter_literals: &HashMap, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { - if procedure.kind == celox_sv_syntax::ProcedureKind::Initial { + if matches!( + procedure.kind, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final + ) { return Ok(None); } let Some(body) = always_comb_body(procedure, syntax_tree.declarations())? else { diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 49f89a48c9e..f8b18fc9f97 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -613,10 +613,10 @@ fn simulation_state_readers(functions: &[Subroutine]) -> HashMap HashMap { + Expressions(&'a [Option]), + Constants(&'a [ConstExpr]), +} + +impl CallArguments<'_> { + pub(in crate::ast) fn is_present(self, index: usize) -> bool { + match self { + Self::Expressions(args) => args.get(index).is_some_and(Option::is_some), + Self::Constants(args) => index < args.len(), + } + } +} + /// Calls in an expression, including the index expressions represented by /// ConstExpr. Those indices can contain runtime calls in procedural code. -fn visit_expr_callees<'a>(expr: &'a Expr, f: &mut impl FnMut(&'a Callee)) { +pub(in crate::ast) fn visit_expr_calls<'a>( + expr: &'a Expr, + f: &mut impl FnMut(&'a Callee, CallArguments<'a>), +) { match expr { Expr::Ident(_) | Expr::Literal(_) => {} Expr::Call { callee, args, .. } => { - f(callee); + f(callee, CallArguments::Expressions(args)); for arg in args.iter().flatten() { - visit_expr_callees(arg, f); + visit_expr_calls(arg, f); } } Expr::Select { expr, msb, lsb, .. } => { - visit_expr_callees(expr, f); - visit_const_callees(msb, f); - visit_const_callees(lsb, f); + visit_expr_calls(expr, f); + visit_const_calls(msb, f); + visit_const_calls(lsb, f); } - Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => visit_expr_callees(expr, f), + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => visit_expr_calls(expr, f), Expr::Concat(parts) => { for part in parts { - visit_expr_callees(part, f); + visit_expr_calls(part, f); } } Expr::RepeatConcat { count, parts } => { - visit_const_callees(count, f); + visit_const_calls(count, f); for part in parts { - visit_expr_callees(part, f); + visit_expr_calls(part, f); } } Expr::Binary { left, right, .. } => { - visit_expr_callees(left, f); - visit_expr_callees(right, f); + visit_expr_calls(left, f); + visit_expr_calls(right, f); } Expr::Mux { condition, then_expr, else_expr, } => { - visit_expr_callees(condition, f); - visit_expr_callees(then_expr, f); - visit_expr_callees(else_expr, f); + visit_expr_calls(condition, f); + visit_expr_calls(then_expr, f); + visit_expr_calls(else_expr, f); } Expr::Inside { expr, items } => { - visit_expr_callees(expr, f); + visit_expr_calls(expr, f); for item in items { for expr in item.exprs() { - visit_expr_callees(expr, f); + visit_expr_calls(expr, f); } } } } } -fn visit_const_callees<'a>(expr: &'a ConstExpr, f: &mut impl FnMut(&'a Callee)) { +pub(in crate::ast) fn visit_const_calls<'a>( + expr: &'a ConstExpr, + f: &mut impl FnMut(&'a Callee, CallArguments<'a>), +) { match expr { ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} ConstExpr::Function { callee, args, .. } => { - f(callee); + f(callee, CallArguments::Constants(args)); for arg in args { - visit_const_callees(arg, f); + visit_const_calls(arg, f); } } ConstExpr::Select { expr, bit } => { - visit_const_callees(expr, f); - visit_const_callees(bit, f); + visit_const_calls(expr, f); + visit_const_calls(bit, f); } ConstExpr::SelectRange { expr, msb, lsb, .. } => { - visit_const_callees(expr, f); - visit_const_callees(msb, f); - visit_const_callees(lsb, f); + visit_const_calls(expr, f); + visit_const_calls(msb, f); + visit_const_calls(lsb, f); } ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => { - visit_const_callees(expr, f) + visit_const_calls(expr, f) } ConstExpr::Binary { left, right, .. } => { - visit_const_callees(left, f); - visit_const_callees(right, f); + visit_const_calls(left, f); + visit_const_calls(right, f); } ConstExpr::Mux { condition, then_expr, else_expr, } => { - visit_const_callees(condition, f); - visit_const_callees(then_expr, f); - visit_const_callees(else_expr, f); + visit_const_calls(condition, f); + visit_const_calls(then_expr, f); + visit_const_calls(else_expr, f); } } } diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index c4b8cb131dd..610a7de1bbf 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -60,7 +60,10 @@ fn ff_process_from_procedure( packed_dimensions: &PackedDimensions, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { - if procedure.kind == celox_sv_syntax::ProcedureKind::Initial { + if matches!( + procedure.kind, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final + ) { return Ok(None); } if always_kind(procedure, syntax_tree.declarations())? != AlwaysKind::Ff { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 8adc8f68e14..4d97adbc841 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -9,6 +9,7 @@ use super::*; mod assertions; mod control; +mod final_procedures; mod foreach; mod randomization; pub(super) mod timed_tasks; @@ -1001,6 +1002,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { fn allow_timing(&self, construct: &'static str) -> Result<(), AnalyzerError> { match self.body { system_functions::Body::Initial => Ok(()), + system_functions::Body::Final => Err(AnalyzerError::TimingControlOutsideProcess { + construct, + context: "a final procedure", + }), system_functions::Body::Always => Err(AnalyzerError::TimingControlOutsideProcess { construct, context: "an always_comb or always_ff body", @@ -3021,7 +3026,8 @@ pub(super) fn initial_processes_from_scope( ), condition: None, body, - initializer: true, + kind: celox_design::ProcessKind::Initializer, + validation_body: Vec::new(), synthetic: false, repeats: false, }); @@ -3033,10 +3039,13 @@ pub(super) fn initial_processes_from_scope( }; let construct = match procedure.kind { celox_sv_syntax::ProcedureKind::Initial => "initial", + celox_sv_syntax::ProcedureKind::Final => "final", _ => "always", }; let repeats = match procedure.kind { - celox_sv_syntax::ProcedureKind::Initial => false, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final => { + false + } celox_sv_syntax::ProcedureKind::Always if validation::always_kind(procedure, tree.declarations())? == validation::AlwaysKind::Process @@ -3047,15 +3056,23 @@ pub(super) fn initial_processes_from_scope( _ => continue, }; let (item_dimensions, literals) = views.get(item); - // A process statement runs in the body kind of an `initial` block: - // it may suspend and call any task. + let is_final = procedure.kind == celox_sv_syntax::ProcedureKind::Final; let mut builder = BodyBuilder::new( tree, item_dimensions, state, - system_functions::Body::Initial, + if is_final { + system_functions::Body::Final + } else { + system_functions::Body::Initial + }, ); let body = builder.native_body(&[procedure.body], &procedure.authored_statements)?; + let mut validation_body = if is_final { + std::mem::take(&mut builder.sensitivity_body) + } else { + Vec::new() + }; let mut body = if repeats { vec![Stmt::Loop { kind: LoopKind::Forever, @@ -3067,7 +3084,7 @@ pub(super) fn initial_processes_from_scope( } else { body }; - for stmt in &mut body { + for stmt in body.iter_mut().chain(&mut validation_body) { substitute_stmt_constants(&tree.state, stmt, &item.env, literals); qualify_stmt(item, stmt); substitute_stmt_constants(&tree.state, stmt, const_env, parameter_literals); @@ -3081,7 +3098,12 @@ pub(super) fn initial_processes_from_scope( ), condition: None, body, - initializer: false, + kind: if is_final { + celox_design::ProcessKind::Final + } else { + celox_design::ProcessKind::Regular + }, + validation_body, synthetic: false, repeats, }); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs b/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs new file mode 100644 index 00000000000..64466d163fe --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs @@ -0,0 +1,182 @@ +//! Function-statement restrictions across calls from final procedures (9.2.3). +use super::*; +use const_functions::CallArguments; + +pub(super) fn validate(subroutines: &[&Subroutine], processes: &[InitialProcess]) -> Converted<()> { + if !processes.iter().any(InitialProcess::is_final) { + return Ok(()); + } + let definitions = subroutines + .iter() + .map(|subroutine| (subroutine.name.as_str(), *subroutine)) + .collect(); + let mut forbidden = HashSet::default(); + let mut calls = Vec::new(); + let mut schedules = HashSet::default(); + let mut runtime_calls = Vec::new(); + for subroutine in subroutines { + let (invalid, _, callees) = effects( + subroutine.body.iter().chain(&subroutine.sensitivity_body), + &definitions, + ); + // Functions cannot enable even an untimed task (13.4 b). + if subroutine.is_task || invalid { + forbidden.insert(subroutine.name.clone()); + } + calls.push((&subroutine.name, callees)); + // Unlike the function-statement restrictions, 13.4.4 concerns an + // executed event scheduling operation. A folded-away NBA is harmless. + let (_, nba, callees) = effects(subroutine.body.iter(), &definitions); + if nba { + schedules.insert(subroutine.name.clone()); + } + runtime_calls.push((&subroutine.name, callees)); + } + loop { + let previous = (forbidden.len(), schedules.len()); + for (name, callees) in &calls { + if callees.iter().any(|callee| forbidden.contains(callee)) { + forbidden.insert((*name).clone()); + } + } + for (name, callees) in &runtime_calls { + if callees.iter().any(|callee| schedules.contains(callee)) { + schedules.insert((*name).clone()); + } + } + if previous == (forbidden.len(), schedules.len()) { + break; + } + } + for process in processes.iter().filter(|process| process.is_final()) { + let (invalid, _, callees) = effects( + process.body.iter().chain(&process.validation_body), + &definitions, + ); + if invalid { + return Err(unsupported("timing control in a final procedure")); + } + if let Some(callee) = callees + .iter() + .filter(|callee| forbidden.contains(*callee)) + .min() + { + return Err(unsupported(format!( + "call to `{callee}` in a final procedure does not obey function-statement restrictions" + ))); + } + let (_, _, callees) = effects(process.body.iter(), &definitions); + if let Some(callee) = callees + .iter() + .filter(|callee| schedules.contains(*callee)) + .min() + { + return Err(unsupported(format!( + "call to `{callee}` from a final procedure schedules an event after the function returns; IEEE 1800-2023 13.4.4 requires an initial/always process" + ))); + } + } + Ok(()) +} + +/// Include discarded branches, expression calls and lvalue selectors: legality +/// is a property of the authored procedure, not just the path executed now. +fn effects<'a>( + body: impl Iterator, + definitions: &HashMap<&str, &Subroutine>, +) -> (bool, bool, HashSet) { + let mut invalid = false; + let mut nba = false; + let mut calls = Calls { + definitions, + names: HashSet::default(), + defaults: Vec::new(), + expanded: HashSet::default(), + }; + for statement in body { + statement.walk(&mut |statement| { + invalid |= matches!( + statement, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) + ); + nba |= matches!( + statement, + Stmt::Assign { + nonblocking: true, + .. + } | Stmt::AssignConcat { + nonblocking: true, + .. + } + ); + if let Stmt::Call { name, args, .. } = statement { + calls.record(name, CallArguments::Expressions(args)); + } + let mut call = |callee: &Callee, args| { + if let Callee::Subroutine(name) = callee { + calls.record(name, args); + } + }; + for expr in lifetimes::stmt_exprs(statement) { + const_functions::visit_expr_calls(expr, &mut call); + } + let targets = match statement { + Stmt::Assign { lhs, .. } => std::slice::from_ref(lhs), + Stmt::AssignConcat { parts, .. } => parts.as_slice(), + _ => &[], + }; + for target in targets { + if let LValue::Select { + msb, + lsb, + array_slice_width, + .. + } = target + { + for index in [Some(msb), Some(lsb), array_slice_width.as_ref()] + .into_iter() + .flatten() + { + const_functions::visit_const_calls(index, &mut call); + } + } + } + }); + } + calls.expand_defaults(); + (invalid, nba, calls.names) +} + +struct Calls<'map, 'definition> { + definitions: &'map HashMap<&'definition str, &'definition Subroutine>, + names: HashSet, + defaults: Vec<&'definition Expr>, + expanded: HashSet<(String, usize)>, +} + +impl Calls<'_, '_> { + fn record(&mut self, name: &str, args: CallArguments<'_>) { + self.names.insert(name.to_owned()); + let Some(&subroutine) = self.definitions.get(name) else { + return; + }; + for (index, parameter) in subroutine.params.iter().enumerate() { + if !args.is_present(index) + && let Some(default) = ¶meter.default + && self.expanded.insert((name.to_owned(), index)) + { + self.defaults.push(default); + } + } + } + + fn expand_defaults(&mut self) { + while let Some(default) = self.defaults.pop() { + const_functions::visit_expr_calls(default, &mut |callee, args| { + if let Callee::Subroutine(name) = callee { + self.record(name, args); + } + }); + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs index 76e37f3c563..06f9181f7e6 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -8,6 +8,7 @@ pub(in crate::ast) fn classify<'a>( processes: &mut Vec, ) -> Result<(), AnalyzerError> { let subroutines: Vec<_> = subroutines.collect(); + super::final_procedures::validate(&subroutines, processes)?; let mut timed = HashSet::default(); loop { let previous = timed.len(); @@ -132,7 +133,8 @@ pub(in crate::ast) fn classify<'a>( step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: false, repeats: true, }); @@ -172,14 +174,15 @@ pub(in crate::ast) fn classify<'a>( step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: false, repeats: true, }); } *ff = retained; if processes.len() != initial_count { - processes.sort_by_key(|process| (!process.initializer, process.creation_order)); + processes.sort_by_key(|process| (!process.is_initializer(), process.creation_order)); } Ok(()) } diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 2c1bd94a779..3e324055c7d 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -355,7 +355,13 @@ impl ScopeSymbols { .cloned() .map(|stmt| rename.stmt(stmt)) .collect(), - initializer: process.initializer, + kind: process.kind, + validation_body: process + .validation_body + .iter() + .cloned() + .map(|stmt| rename.stmt(stmt)) + .collect(), synthetic: process.synthetic, repeats: process.repeats, }) @@ -596,7 +602,13 @@ impl ScopeSymbols { .cloned() .map(|stmt| rename.stmt(stmt)) .collect(), - initializer: process.initializer, + kind: process.kind, + validation_body: process + .validation_body + .iter() + .cloned() + .map(|stmt| rename.stmt(stmt)) + .collect(), synthetic: process.synthetic, repeats: process.repeats, }) @@ -609,7 +621,7 @@ impl ScopeSymbols { /// Whether `process` assigns the signal `name`. pub(super) fn initializes(process: &InitialProcess, name: &str) -> bool { - process.body.iter().any(|stmt| stmt_initializes(stmt, name)) + !process.is_final() && process.body.iter().any(|stmt| stmt_initializes(stmt, name)) } fn stmt_initializes(stmt: &Stmt, name: &str) -> bool { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 669af79e830..3d981ce9419 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -126,7 +126,7 @@ fn validate_procedure( use celox_sv_syntax::{EventControl, ProcedureKind, StatementKind, TimingControlKind}; let kind = match procedure.kind { ProcedureKind::Initial => return Ok(()), - ProcedureKind::Final => return Err(unsupported("final construct")), + ProcedureKind::Final => return validate_final(procedure.body, native), _ => always_kind(procedure, native)?, }; let mut pending = vec![procedure.body]; @@ -166,6 +166,46 @@ fn validate_procedure( Ok(()) } +/// Final restrictions are syntactic, so even branches later folded away +/// must obey the function-statement rules (IEEE 1800-2023 9.2.3, 13.4). +fn validate_final( + root: celox_sv_syntax::StatementId, + native: &celox_sv_syntax::Declarations, +) -> Converted<()> { + use celox_sv_syntax::StatementKind; + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + let statement = native.statement(id); + let forbidden = match &statement.kind { + StatementKind::Assignment { + timing: Some(_), .. + } + | StatementKind::Assignment { + event_control: Some(_), + .. + } + | StatementKind::Timing { .. } => Some("timing control"), + StatementKind::Wait { .. } + | StatementKind::WaitFork + | StatementKind::WaitOrder { .. } => Some("wait statement"), + StatementKind::Parallel { join, .. } if join != "join_none" => Some("fork-join block"), + // 13.4.4 permits join_none in functions. Its child statements + // obey task rules, so leave the whole construct to the existing + // unsupported parallel-process binder rather than rejecting it. + StatementKind::Parallel { .. } => continue, + StatementKind::Assertion { keyword, .. } if keyword == "expect" => { + Some("expect statement") + } + _ => None, + }; + if let Some(construct) = forbidden { + return Err(unsupported(format!("{construct} in a final procedure"))); + } + pending.extend(statement.kind.children()); + } + Ok(()) +} + /// Root module inspection skips control branches. The subsequent active-item /// inspection visits an opaque checker's complete captured syntax, matching the /// existing validation contract without implementing checker elaboration. diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 32df6c7df93..f094e067c62 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -125,14 +125,14 @@ impl Module { step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, synthetic: false, repeats: true, }); } self.ff_processes = retained; self.initial_processes - .sort_by_key(|process| (!process.initializer, process.creation_order)); + .sort_by_key(|process| (!process.is_initializer(), process.creation_order)); self } @@ -1146,7 +1146,7 @@ impl FfProcess { } } -/// An `initial` process. +/// A scheduled procedure, including initial/always processes and final procedures. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, @@ -1154,7 +1154,7 @@ pub struct InitialProcess { scheduled_edge: bool, condition: Option, body: Vec, - initializer: bool, + kind: celox_design::ProcessKind, synthetic: bool, /// An `always` process: its body runs forever. repeats: bool, @@ -1176,19 +1176,33 @@ impl InitialProcess { self.site.as_ref() } - pub(crate) fn new(condition: Option, body: Vec, initializer: bool) -> Self { + pub(crate) fn new( + condition: Option, + body: Vec, + kind: celox_design::ProcessKind, + ) -> Self { Self { creation_order: 0, site: None, scheduled_edge: false, condition, body, - initializer, + kind, synthetic: false, repeats: false, } } + /// The procedure's simulation phase. + pub fn kind(&self) -> celox_design::ProcessKind { + self.kind + } + + /// A final procedure runs once when the simulation finishes (9.2.3). + pub fn is_final(&self) -> bool { + self.kind == celox_design::ProcessKind::Final + } + /// Compiler-generated storage initialization, without a user static process. pub fn is_synthetic(&self) -> bool { self.synthetic @@ -1197,7 +1211,7 @@ impl InitialProcess { /// Whether this process holds variable declaration initializers, which /// run before every `initial` and `always` procedure. pub fn is_initializer(&self) -> bool { - self.initializer + self.kind == celox_design::ProcessKind::Initializer } /// Whether this is an `always` process, which runs its body forever and @@ -1602,7 +1616,7 @@ impl From for InitialProcess { .cloned() .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), - process.is_initializer(), + process.kind(), ); result.creation_order = process.creation_order(); result.site = process.site().cloned(); diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 143a76ffce4..6fff884e774 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -1339,7 +1339,7 @@ mod declaration_tests { &ModuleInterfaces::default(), &packages ) - .is_err() + .is_ok() ); let ir = source .analyze_module_declarations("Top", &overrides, &packages) diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs b/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs index 401b8012f3c..be3717fa014 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs @@ -204,7 +204,7 @@ fn native_process_restrictions_apply_only_to_active_generate_items() { #[test] fn native_direct_nested_unit_restrictions_are_preserved_for_selected_parent() { for (process, expected) in [ - ("final begin end", "final construct"), + ("final #1;", "timing control in a final procedure"), ( "always_latch begin int y;y<=1;end", "nonblocking assignment inside always_latch", @@ -229,7 +229,7 @@ fn native_direct_nested_unit_restrictions_are_preserved_for_selected_parent() { #[test] fn unconverted_checker_processes_retain_existing_restriction_diagnostics() { for (process, expected) in [ - ("final begin end", "final construct"), + ("final #1;", "timing control in a final procedure"), ( "always_latch begin int y;y<=1;end", "nonblocking assignment inside always_latch", @@ -248,26 +248,17 @@ fn unconverted_checker_processes_retain_existing_restriction_diagnostics() { #[test] fn checker_and_nested_unit_validation_keep_the_legacy_root_and_active_leaf_contract() { for (body, rejected) in [ - ("checker C;final begin end endchecker", true), - ("checker C;if(0)final begin end endchecker", true), + ("checker C;final #1; endchecker", true), + ("checker C;if(0)final #1; endchecker", true), + ("if(0)begin:g checker C;final #1; endchecker end", false), + ("if(1)begin:g checker C;final #1; endchecker end", true), + ("module N;checker C;final #1; endchecker endmodule", true), ( - "if(0)begin:g checker C;final begin end endchecker end", + "module N;checker C;if(0)final #1; endchecker endmodule", false, ), ( - "if(1)begin:g checker C;final begin end endchecker end", - true, - ), - ( - "module N;checker C;final begin end endchecker endmodule", - true, - ), - ( - "module N;checker C;if(0)final begin end endchecker endmodule", - false, - ), - ( - "module N;checker C;if(1)final begin end endchecker endmodule", + "module N;checker C;if(1)final #1; endchecker endmodule", false, ), ] { @@ -281,7 +272,9 @@ fn checker_and_nested_unit_validation_keep_the_legacy_root_and_active_leaf_contr if rejected { let error = result.unwrap_err(); assert!( - error.to_string().contains("final construct"), + error + .to_string() + .contains("timing control in a final procedure"), "{body}: {error}" ); } else { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 6b3b0ef51fb..f6e85cb53f9 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -1465,6 +1465,8 @@ pub enum Body { /// `always`, `always_comb`, or `always_ff`. Always, Initial, + /// A final procedure, restricted to function statements (9.2.3). + Final, /// A function or task. Subroutine, } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index c9385650f3d..10ebdfcfbd0 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -7031,3 +7031,213 @@ fn preserves_legal_enum_declaration_initializers() { .unwrap_or_else(|error| panic!("{source}: {error}")); } } + +#[test] +fn final_procedures_preserve_phase_and_active_generate_order() { + let ir = analyze_source( + r#"module Top; + int value = 3; + function int read_value(); return value; endfunction + initial value = 5; + final begin value = read_value(); $display("final %d", value); end + if (0) begin: inactive final #1; end + for (genvar i = 0; i < 2; i++) begin: active + final $display("generated %d", i); + end + endmodule"#, + Path::new("final_procedures.sv"), + ) + .unwrap(); + assert!(ir.modules()[0].comb_processes().is_empty()); + assert!(ir.modules()[0].ff_processes().is_empty()); + let processes = ir.modules()[0].initial_processes(); + assert_eq!( + processes + .iter() + .filter(|process| process.is_initializer()) + .count(), + 1 + ); + assert_eq!( + processes + .iter() + .filter(|process| process.is_final()) + .count(), + 3 + ); + let finals: Vec<_> = processes + .iter() + .filter(|process| process.is_final()) + .collect(); + assert!( + finals + .windows(2) + .all(|pair| pair[0].creation_order() < pair[1].creation_order()) + ); + assert!( + finals.iter().all(|process| !process.repeats() + && !process.is_initializer() + && !process.is_synthetic()) + ); + assert!( + finals + .iter() + .all(|process| process.kind() == celox_design::ProcessKind::Final) + ); +} + +#[test] +fn final_procedures_reject_timing_before_folding() { + for statement in [ + "#1 value = 1;", + "@(value) value = 1;", + "wait(value) value = 1;", + "wait fork;", + "fork value = 1; join", + "value = #1 2;", + ] { + for body in [ + statement.to_string(), + format!("if (0) begin {statement} end"), + ] { + let source = format!("module Top; int value; final begin {body} end endmodule"); + let error = analyze_source(&source, Path::new("illegal_final.sv")).unwrap_err(); + assert!( + error.to_string().contains("final procedure"), + "{source}: {error}" + ); + } + } +} + +#[test] +fn final_procedures_reject_task_and_nba_through_function_calls() { + for declarations in [ + "task work(); endtask", + "task work(); #1; endtask", + "task t(); endtask function void work(); t(); endfunction", + "function void work(); value <= 1; endfunction", + "function void bad(); value <= 1; endfunction function void work(); bad(); endfunction", + ] { + for body in ["work();", "if (0) work();"] { + if declarations.contains("<=") && body.starts_with("if (0)") { + continue; + } + let source = + format!("module Top; int value; {declarations} final begin {body} end endmodule"); + let error = analyze_source(&source, Path::new("illegal_final_call.sv")).unwrap_err(); + if declarations.contains("<=") { + assert!(error.to_string().contains("13.4.4"), "{source}: {error}"); + } + assert!( + error.to_string().contains("final procedure"), + "{source}: {error}" + ); + } + } + let source = "module Top; int value; function int bad(); value <= 1; return value; endfunction final value = bad(); endmodule"; + let error = analyze_source(source, Path::new("illegal_final_expression.sv")).unwrap_err(); + assert!(error.to_string().contains("final procedure"), "{error}"); + let source = "package p; task work(); endtask endpackage module Top; import p::*; final work(); endmodule"; + let error = analyze_source(source, Path::new("illegal_imported_final_call.sv")).unwrap_err(); + assert!(error.to_string().contains("final procedure"), "{error}"); +} + +#[test] +fn final_procedures_preserve_legal_functions_and_finish() { + for body in [ + "value = compute();", + "report();", + "$finish;", + "$stop;", + "$fatal;", + "$fclose(value);", + "$sscanf(\"1\", \"%d\", value);", + "begin int local_value; local_value = value; $display(local_value); end", + ] { + let source = format!( + "module Top; int value; function int compute(); return value + 1; endfunction function void report(); $display(value); endfunction final {body} endmodule" + ); + let ir = analyze_source(&source, Path::new("legal_final.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + assert_eq!( + ir.modules()[0] + .initial_processes() + .iter() + .filter(|process| process.is_final()) + .count(), + 1 + ); + } +} + +#[test] +fn final_procedures_allow_direct_nba_and_unexecuted_scheduling_calls() { + for body in ["value <= 1;", "if (0) schedule();", "no_schedule();"] { + let source = format!( + "module Top; int value; function void schedule(); value <= 1; endfunction function void no_schedule(); if (0) value <= 1; endfunction final {body} endmodule" + ); + let ir = analyze_source(&source, Path::new("final_nba.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + let process = ir.modules()[0] + .initial_processes() + .iter() + .find(|process| process.is_final()) + .unwrap(); + if body == "value <= 1;" { + assert!(matches!( + process.body(), + [ir::Stmt::Assign { + nonblocking: true, + .. + }] + )); + } + } +} + +#[test] +fn final_join_none_is_unsupported_rather_than_a_function_statement_violation() { + let error = analyze_source( + "module Top; final fork #1; join_none endmodule", + Path::new("final_join_none.sv"), + ) + .unwrap_err(); + assert_eq!( + error.to_string(), + "Unsupported SystemVerilog construct: fork-join block" + ); +} + +#[test] +fn final_procedures_only_follow_defaults_for_omitted_arguments() { + let declarations = r#" + int value; + function int schedule(); value <= 1; return 0; endfunction + function int take(input int a = schedule(), input int b = 0); return a + b; endfunction + function int nested(input int a = take()); return a; endfunction + function void explicit_wrapper(); value = take(0); endfunction + function void omitted_wrapper(); value = take(); endfunction + "#; + for (body, rejected) in [ + ("value = take();", true), + ("value = take(, 1);", true), + ("value = take(.b(1));", true), + ("value = nested();", true), + ("omitted_wrapper();", true), + ("value = take(0);", false), + ("value = take(.a(0));", false), + ("value = nested(0);", false), + ("explicit_wrapper();", false), + ("if (0) value = take();", false), + ] { + let source = format!("module Top; {declarations} final {body} endmodule"); + let result = analyze_source(&source, Path::new("final_default_arguments.sv")); + if rejected { + let error = result.unwrap_err(); + assert!(error.to_string().contains("13.4.4"), "{body}: {error}"); + } else { + result.unwrap_or_else(|error| panic!("{body}: {error}")); + } + } +} diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index a996e6eb580..c68196a6dda 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -288,6 +288,9 @@ fn simulate_sv( saves.after_step(&mut simulation)?; steps += 1; } + let finished = simulation.finish(); + drain_sv_output(&mut simulation, output, &mut failed)?; + finished.map_err(|error| error.to_string())?; saves.finish(&mut simulation)?; if failed { return Err("SystemVerilog testbench reported an assertion failure or $error".to_string()); @@ -1164,8 +1167,7 @@ mod tests { #[cfg(feature = "systemverilog")] #[test] fn sv_scheduler_limit_fails_and_preserves_scheduled_output() { - let source = - "module Top(input bit clk); always @(posedge clk) $display(\"tick\"); endmodule"; + let source = "module Top(input bit clk); always @(posedge clk) $display(\"tick\"); final $display(\"finalized\"); endmodule"; let mut simulation = celox::Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") .build() @@ -1174,7 +1176,28 @@ mod tests { let mut output = Vec::new(); let error = simulate_sv(simulation, 3, StateSaves::default(), &mut output).unwrap_err(); assert!(error.contains("exceeded --max-steps 3")); - assert!(String::from_utf8(output).unwrap().contains("tick")); + let output = String::from_utf8(output).unwrap(); + assert!(output.contains("tick")); + assert!(!output.contains("finalized")); + } + + #[cfg(feature = "systemverilog")] + #[test] + fn sv_batch_runs_final_output_on_quiescence_and_finish() { + for ending in ["", "$finish;"] { + let source = format!( + "module Top; int value; initial begin value=42; {ending} end final $display(\"final=%0d\", value); endmodule" + ); + let simulation = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("top.sv"))], + "Top", + ) + .build() + .unwrap(); + let mut output = Vec::new(); + simulate_sv(simulation, 10, StateSaves::default(), &mut output).unwrap(); + assert_eq!(String::from_utf8(output).unwrap(), "final=42\n"); + } } /// Only `$error` and `$fatal` fail a run; every report is printed with diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index b87450b0b2f..f0726b032cd 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -237,6 +237,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { use std::io::Write as _; let mut stdout = std::io::stdout().lock(); let mut output = |sim: &mut celox::Simulation| -> Result<(), String> { + let mut fatal = None; for event in sim.drain_runtime_events() { match event { celox::RuntimeEvent::Report(celox::Report { @@ -246,7 +247,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { }) => { stdout.write_all(&message).unwrap(); stdout.write_all(b"\n").unwrap(); - return Err(format!( + fatal = Some(format!( "$fatal: {}", std::str::from_utf8(&message) .map(str::to_owned) @@ -265,7 +266,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { } } } - Ok(()) + fatal.map_or(Ok(()), Err) }; let initial = sim.eval_comb().map_err(|error| error.to_string()); output(&mut sim)?; @@ -279,6 +280,13 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { break; } } + if !sim.is_stopped() { + // Quiescence ends this batch run, but is not itself terminal for the + // reusable Simulation API (a host can still supply new inputs). + let finished = sim.finish().map_err(|error| error.to_string()); + output(&mut sim)?; + finished?; + } Ok(()) } @@ -421,6 +429,19 @@ mod tests { ); } + #[test] + fn simulation_runs_final_on_quiescence_but_elaboration_does_not() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture( + dir.path(), + "final.sv", + "module Top; initial #2; final $fatal(1, \"from final\"); endmodule", + ); + run(&fixture_options(vec![path.clone()], Mode::Elaboration)).unwrap(); + let error = run(&fixture_options(vec![path], Mode::Simulation)).unwrap_err(); + assert!(error.contains("from final"), "{error}"); + } + #[test] fn simulation_variants_use_separate_arguments_and_fresh_state() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 984c26ba14a..ae25f64d4a2 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 38; +const CONTAINER_VERSION: u16 = 39; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 05002091ffb..f3dcfc3baa6 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -425,8 +425,10 @@ impl Plan { for (index, slots) in schema.processes.iter().enumerate() { let process = &model.processes[index]; let unit = &sir.processes[index]; - let reason = if slots.is_initializer { + let reason = if slots.kind == celox_design::ProcessKind::Initializer { Some("a declaration initializer") + } else if slots.kind == celox_design::ProcessKind::Final { + Some("a final procedure") } else if slots.program.is_some() { Some("a program process runs in the reactive region set") } else if slots.requires_timed_simulation { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 967e6da71b4..56bd3dfcdaa 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -158,9 +158,7 @@ impl UnitExecutor for Simulator { } fn run_process(&mut self, index: usize) -> Result<(), Halt> { - self.backend - .run_process(index) - .map_err(|e| self.decorate_runtime_error(e))?; + self.run_process_checked(index)?; self.runtime_finish() } @@ -474,9 +472,22 @@ impl Simulation { if self.state.is_suspended() { return Err(CheckpointError::Stopped.into()); } - let mut file = self.simulator.save_state()?; + if let Err(error) = self.simulator.prepare_save_state() { + if let StateError::Runtime(error) = &error { + self.finalize_fatal(error); + } + return Err(error); + } // Settling for the file may have executed a `$finish`. self.sync_finish_checked().map_err(StateError::Runtime)?; + // A final procedure can write state or suspend with `$stop`. + if self.state.is_suspended() { + return Err(CheckpointError::Stopped.into()); + } + let mut file = self + .simulator + .state_schema() + .capture(&self.simulator.backend)?; let parts = self.state.export_schedule(&self.simulator.backend); let mut record = self.simulator.name_schedule(parts); record.processes.host_writes = self.simulator.name_host_writes(); @@ -537,11 +548,19 @@ impl Simulation { /// step, during a direct settle, read or dump, ends the simulation too. fn sync_finish_checked(&mut self) -> Result<(), RuntimeErrorCode> { if !self.state.is_finished() && self.simulator.take_runtime_finish() { - self.state.finalize_terminal(&mut self.simulator)?; + self.finish()?; } Ok(()) } + /// A fatal report implicitly calls `$finish`; retain the original diagnostic + /// even if a final procedure or output flush fails during termination. + fn finalize_fatal(&mut self, error: &RuntimeErrorCode) { + if matches!(error, RuntimeErrorCode::Fatal { .. }) { + let _ = self.finish(); + } + } + /// Publish diagnostic state without replacing a primary evaluation error /// or freezing a simulation whose caller may recover. fn flush_error_output(&mut self) { @@ -556,13 +575,17 @@ impl Simulation { /// Captures the current state of all signals and writes them to the VCD file. pub fn dump(&mut self, timestamp: u64) { - self.simulator.dump(timestamp); - self.sync_finish(); + if let Err(error) = self.try_dump(timestamp) { + panic!("VCD dump at {timestamp} failed: {error}"); + } } /// See [`Simulator::try_dump`]. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), crate::simulator::DumpError> { let result = self.simulator.try_dump(timestamp); + if let Err(crate::simulator::DumpError::Runtime(error)) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); if matches!(&result, Err(crate::simulator::DumpError::Runtime(_))) { self.flush_error_output(); @@ -615,6 +638,9 @@ impl Simulation { F: FnOnce(&mut crate::IOContext), { let result = self.simulator.modify(f); + if let Err(error) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); result?; finished?; @@ -716,6 +742,7 @@ impl Simulation { Ok(()) }; if let Err(error) = result.and_then(|()| self.simulator.mature_deferred_assertions()) { + self.finalize_fatal(&error); self.flush_error_output(); return Err(error); } @@ -801,6 +828,9 @@ impl Simulation { /// that wake no process, at the current time, and watch its reports. A /// watched run does this before it moves to a later time. fn watch_settle(&mut self) -> Result<(), RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(()); + } // The run leaves the time or ends at it: the slot is over, and the // deferred actions waiting from any settle at that time mature // before the reports are watched. @@ -811,6 +841,7 @@ impl Simulation { } if self.simulator.dirty { if let Err(error) = self.simulator.eval_comb_checked() { + self.finalize_fatal(&error); self.flush_error_output(); return Err(error); } @@ -821,6 +852,9 @@ impl Simulation { } else { Ok(()) }; + if let Err(error) = &matured { + self.finalize_fatal(error); + } self.watch_reports(); if let Err(error) = matured { self.flush_error_output(); @@ -906,7 +940,8 @@ impl Simulation { return Ok(()); } if let Err(error) = self.simulator.try_dump_unless_rewound(end_time) { - if matches!(&error, crate::simulator::DumpError::Runtime(_)) { + if let crate::simulator::DumpError::Runtime(runtime_error) = &error { + self.finalize_fatal(runtime_error); self.flush_error_output(); } return Err(vcd_dump_runtime_error(error)); @@ -984,9 +1019,28 @@ impl Simulation { Ok(!self.state.is_stopped()) } - /// Whether a process of the design requested the end of the simulation. - /// Once it has, [`Self::step`] returns `None` and [`Self::run_until`] - /// stops at the time of the request. + /// End simulation at its current time, running final procedures once. + /// Idle steps and bounded runs remain resumable until this is requested. + /// If a final procedure executes `$stop`, a later step resumes finalization. + pub fn finish(&mut self) -> Result<(), RuntimeErrorCode> { + use celox_runtime::StepObserver; + let Some(mut shadow) = self.shadow.take() else { + return self.state.finish(&mut self.simulator); + }; + let mut check = differential::ShadowCheck::new(&mut shadow, self.mode()); + check.before_step(&self.state, &mut self.simulator); + let result = self.state.finish(&mut self.simulator); + let comparison = check.after_finish(&self.state, &mut self.simulator, &result); + self.checked_steps += check.checked; + self.shadow = Some(shadow); + comparison?; + result + } + + /// Whether simulation has terminated and its final procedures have completed. + /// Termination can be requested by the design or by [`Self::finish`]. + /// Once complete, [`Self::step`] returns `None` and [`Self::run_until`] + /// stops at the termination time. pub fn is_finished(&self) -> bool { self.state.is_finished() } @@ -1014,18 +1068,32 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + // Keep termination visible to the timed owner before collecting reports. + // The untimed drain intentionally turns immediate fatals into reports. + if self.simulator.dirty { + let settled = self.simulator.eval_comb_checked(); + self.simulator.dirty = false; + match settled.and_then(|()| self.sync_finish_checked()) { + Err(error @ RuntimeErrorCode::Fatal { .. }) => self.finalize_fatal(&error), + result => result.unwrap(), + } + } // A slot with nothing more due is over, also before the first step: // the initial settle of combinational logic belongs to time zero. // A fatal action is drained as a fatal report. - if self.simulator.deferred_assertions + if !self.state.is_finished() + && self.simulator.deferred_assertions && self.state.next_event_time() != Some(self.state.time()) { - // Lazily settled logic runs in the slot too. - self.simulator.settle_for_runtime_event_drain(); - let _ = self.simulator.mature_deferred_assertions(); + if let Err(error) = self.simulator.mature_deferred_assertions() { + self.finalize_fatal(&error); + } } let mut events = std::mem::take(&mut self.reports.events); - events.extend(self.simulator.drain_runtime_events()); + events.extend( + self.simulator + .drain_settled_runtime_events_with_context(crate::RuntimeFormatContext::default()), + ); events } @@ -1037,6 +1105,9 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { let result = self.simulator.eval_comb(); + if let Err(error) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); if result.is_err() { self.flush_error_output(); diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ceb3ba86f99..76f162baa87 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -69,6 +69,28 @@ impl<'a, B: SimBackend> ShadowCheck<'a, B> { } } +impl ShadowCheck<'_, B> { + pub(super) fn after_finish( + &mut self, + state: &SimulationState, + primary: &mut Simulator, + result: &Result<(), RuntimeErrorCode>, + ) -> Result<(), RuntimeErrorCode> { + let shadow = &mut *self.shadow; + let reference = shadow.state.finish(&mut shadow.simulator); + self.checked += 1; + let result = result.clone().map(|()| Some(state.time())); + let reference = reference.map(|()| Some(shadow.state.time())); + match difference(state, primary, shadow, &result, &reference) { + None => Ok(()), + Some(message) => Err(RuntimeErrorCode::Runtime { + message: format!("finalization diverged from the reference: {message}"), + signals: Vec::new(), + }), + } + } +} + impl StepObserver> for ShadowCheck<'_, B> { fn one_slot(&self) -> bool { self.one_slot diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 2b497812fd2..53d13ef05df 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -796,7 +796,7 @@ endmodule .runtime_schema .processes .iter() - .filter(|slots| !slots.is_initializer) + .filter(|slots| slots.kind != celox_design::ProcessKind::Initializer) .map(|slots| slots.const_delays) .collect(); // `initial clk = 1'b0` folds into an initial value. A real delay diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 6e1d6ae5327..b34212fdae3 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -952,7 +952,7 @@ mod host { match err { RuntimeErrorCode::DetectedTrueLoopCode(code) => { if self.comb_fatal_site(code).is_some() { - return RuntimeErrorCode::Runtime { + return RuntimeErrorCode::Fatal { message: "Fatal assertion (runtime event record overwritten)" .to_string(), signals: Vec::new(), @@ -1470,7 +1470,9 @@ mod host { /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 /// 16.4). A fatal one ends the simulation with an error. pub(crate) fn mature_deferred_assertions(&mut self) -> Result<(), RuntimeErrorCode> { - if !self.deferred_assertions { + // Terminal output draining must not execute actions left in the + // Observed/Postponed queues after final procedures (9.2.3). + if self.frozen || !self.deferred_assertions { return Ok(()); } self.stash_runtime_events(); @@ -1493,7 +1495,7 @@ mod host { }) else { return Ok(()); }; - Err(RuntimeErrorCode::Runtime { + Err(RuntimeErrorCode::Fatal { message: message_diagnostic(&report.message), signals: Vec::new(), }) @@ -1584,6 +1586,9 @@ mod host { } fn runtime_event_write_seq(&self) -> u64 { + if self.program.runtime_schema.runtime_event_sites.is_empty() { + return 0; + } if let Some(buffer) = self.backend.runtime_event_buffer() { buffer.load_atomic_u64(0, std::sync::atomic::Ordering::Acquire) } else { @@ -1822,7 +1827,7 @@ mod host { return Err(error); } if fatal_status { - return Err(RuntimeErrorCode::Runtime { + return Err(RuntimeErrorCode::Fatal { message: "Fatal assertion (runtime event record overwritten)".to_string(), signals: Vec::new(), }); @@ -1835,7 +1840,9 @@ mod host { ) -> (Result<(), RuntimeErrorCode>, Vec) { // Event-drain writes use this entry directly instead of the // checked facade. Leave observers and runtime events untouched. - if self.declaration_phase { + // A boundary observer may have marked the state dirty immediately + // before freezing; draining output must not activate HDL afterwards. + if self.frozen || self.declaration_phase { return (Ok(()), Vec::new()); } if self.program.runtime_schema.runtime_event_sites.is_empty() { @@ -1931,7 +1938,7 @@ mod host { if !site.kind.is_fatal() || site.deferred.is_some() { return None; } - Some(RuntimeErrorCode::Runtime { + Some(RuntimeErrorCode::Fatal { message: message_diagnostic(&render_runtime_event_message( site, args, @@ -1942,40 +1949,62 @@ mod host { }) } + /// Keep a fatal report distinct from ordinary runtime faults before its + /// backend status is decorated into a diagnostic. + fn checked_kernel_result( + &self, + result: Result<(), RuntimeErrorCode>, + start: u64, + ) -> Result<(), RuntimeErrorCode> { + result.map_err(|error| { + if self.program.runtime_schema.runtime_event_sites.is_empty() { + return self.decorate_runtime_error(error); + } + self.fatal_comb_capture_error(&self.peek_backend_runtime_events_from(start)) + .unwrap_or_else(|| self.decorate_runtime_error(error)) + }) + } + + pub(crate) fn run_process_checked(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { + let start = self.runtime_event_write_seq(); + let result = self.backend.run_process(index); + self.checked_kernel_result(result, start) + } + pub(crate) fn eval_apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_apply_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn eval_comb_apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_comb_apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_comb_apply_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn eval_only_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_only_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_only_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.apply_ff_at(event); + self.checked_kernel_result(result, start) } /// One clock period of an event's signal: its active edge, then its @@ -3535,7 +3564,7 @@ mod host { assert!(sim.fatal_comb_capture_error(&events).is_none()); assert!(sim.check_comb_backend_result(result.clone()).is_ok()); assert!(matches!(sim.decorate_runtime_error(result.unwrap_err()), - RuntimeErrorCode::Runtime { message, .. } if message.contains("overwritten"))); + RuntimeErrorCode::Fatal { message, .. } if message.contains("overwritten"))); let drained = sim.drain_runtime_events(); assert!(matches!( drained.first(), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 75e1a4f61a5..d052dadf20c 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -4061,7 +4061,7 @@ mod host { .runtime_schema .processes .iter() - .any(|slots| slots.is_initializer) + .any(|slots| slots.kind == celox_design::ProcessKind::Initializer) { sim.modify(|_| {}).map_err(|error| { SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 803b46afdaa..1cdab79f2a7 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -303,6 +303,13 @@ impl Simulator { /// Combinational values are settled first, so the file shows the values /// a read would return. pub fn save_state(&mut self) -> Result { + self.prepare_save_state()?; + self.state_schema().capture(&self.backend) + } + + /// Validate support and settle before a timed owner synchronizes termination. + /// Capture must follow that synchronization, since final procedures can write state. + pub(crate) fn prepare_save_state(&mut self) -> Result<(), StateError> { self.check_host_checkpoint_support()?; if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); @@ -311,7 +318,7 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - self.state_schema().capture(&self.backend) + Ok(()) } /// Load the state saved in `file`, matching objects by path. diff --git a/crates/celox/tests/comb_observer.rs b/crates/celox/tests/comb_observer.rs index ae525ef7dbf..47f1ca24605 100644 --- a/crates/celox/tests/comb_observer.rs +++ b/crates/celox/tests/comb_observer.rs @@ -783,7 +783,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "constant fail".to_string(), signals: Vec::new(), }, @@ -806,7 +806,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "initial fatal".to_string(), signals: Vec::new(), }, @@ -831,7 +831,7 @@ module Top ( let err = sim.modify(|io| io.set(trigger, 1u8)).unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "constant fatal after modify".to_string(), signals: Vec::new(), }, @@ -853,7 +853,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "user says for-loop step does not advance the loop variable".to_string(), signals: Vec::new(), }, @@ -899,7 +899,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "a must be set".to_string(), signals: Vec::new(), }, @@ -1205,7 +1205,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "fatal y".to_string(), signals: Vec::new(), }, @@ -1718,7 +1718,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "x1 became 1".to_string(), signals: Vec::new(), }, diff --git a/crates/celox/tests/fixtures/final/finish.sv b/crates/celox/tests/fixtures/final/finish.sv new file mode 100644 index 00000000000..cfb9816211f --- /dev/null +++ b/crates/celox/tests/fixtures/final/finish.sv @@ -0,0 +1,19 @@ +`timescale 1ns/1ns +// Whichever final runs first must terminate the current and remaining finals. +module Top(output int calls, after_finish); + initial begin calls = 0; after_finish = 0; #1; $finish; end + final begin + calls = calls + 1; + $display("final calls=%0d", calls); + $finish; + after_finish = 1; + $display("unreachable first"); + end + final begin + calls = calls + 1; + $display("final calls=%0d", calls); + $finish; + after_finish = 2; + $display("unreachable second"); + end +endmodule diff --git a/crates/celox/tests/fixtures/final/hierarchy.sv b/crates/celox/tests/fixtures/final/hierarchy.sv new file mode 100644 index 00000000000..32b84b938ff --- /dev/null +++ b/crates/celox/tests/fixtures/final/hierarchy.sv @@ -0,0 +1,15 @@ +`timescale 1ns/1ns +// The order of final procedures is unspecified. Each emits a distinct +// label so an external check can compare the labels without ordering them. +module Child(output bit done); + final begin done = 1; $display("child"); end +endmodule +module Top(output bit first, second, child_done, output bit [1:0] generated); + Child child(child_done); + initial begin #1; $finish; end + final begin first = 1; $display("top first"); end + final begin second = 1; $display("top second"); end + for (genvar i = 0; i < 2; i++) begin : g + final begin generated[i] = 1; $display("generate %0d", i); end + end +endmodule diff --git a/crates/celox/tests/fixtures/final/state.sv b/crates/celox/tests/fixtures/final/state.sv new file mode 100644 index 00000000000..ae4e6549072 --- /dev/null +++ b/crates/celox/tests/fixtures/final/state.sv @@ -0,0 +1,16 @@ +`timescale 1ns/1ns +// IEEE 1800-2023 9.2.3: final observes the last state and runs once. +module Top(output int value, calls); + initial begin + value = 3; calls = 0; + $display("initial calls=%0d", calls); + #2 value = 7; + $finish; + end + final begin + calls = calls + 1; + value = value + 10; + if (value != 17 || calls != 1) $fatal(1, "bad final state"); + $display("final value=%0d calls=%0d", value, calls); + end +endmodule diff --git a/crates/celox/tests/frontends/systemverilog/final.rs b/crates/celox/tests/frontends/systemverilog/final.rs new file mode 100644 index 00000000000..f904597200c --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/final.rs @@ -0,0 +1,521 @@ +use celox::{RuntimeEvent, SimBackend, Simulation}; +use std::path::Path; + +// The shared timed-suite emitter uses its own final checker and therefore +// rejects final procedures whose order relative to that checker is unspecified. +// These portable fixtures are also suitable for direct external execution; +// API checks here inspect state only after finalization has completed. +// Every source uses 1ns/1ns so API ticks and HDL delay units coincide. +const STATE: &str = include_str!("../../fixtures/final/state.sv"); +const HIERARCHY: &str = include_str!("../../fixtures/final/hierarchy.sv"); +const FINISH: &str = include_str!("../../fixtures/final/finish.sv"); + +#[test] +fn final_procedures_require_the_simulation_api() { + let source = "module Top(input logic done); final assert (done); endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("final.sv"))], "Top") + .build_interpreter() + .unwrap_err(); + assert!( + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" + ); +} + +fn displays(events: Vec) -> Vec> { + events + .into_iter() + .filter_map(|event| match event { + RuntimeEvent::Display { message } => Some(message), + _ => None, + }) + .collect() +} + +fn check_final_state(mut sim: Simulation) { + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 17u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![ + b"initial calls=0".to_vec(), + b"final value=17 calls=1".to_vec(), + ] + ); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert!(displays(sim.drain_runtime_events()).is_empty()); +} + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn final_procedures_survive_native_image_roundtrip() { + let image = Simulation::from_sv_sources(vec![(STATE, Path::new("final_state.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + check_final_state( + Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + ); +} + +macro_rules! check_backends { + ($source:expr, $check:ident) => { + for four_state in [false, true] { + let build = || { + Simulation::from_sv_sources(vec![($source, Path::new("final.sv"))], "Top") + .four_state(four_state) + }; + $check(build().build_interpreter().unwrap()); + $check(build().build_cranelift().unwrap()); + $check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + $check(build().build_native().unwrap()); + $check(build().build_tiered().unwrap()); + $check( + build() + .scheduler_mode(celox::SchedulerMode::Differential) + .build_native() + .unwrap(), + ); + } + } + }; +} + +#[test] +fn final_nonblocking_updates_do_not_run_after_termination() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, observed); + initial begin value=3; #1; $finish; end + final begin value <= 99; observed = value; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 3u8.into()); + assert_eq!(sim.get(sim.signal("observed")), 3u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn explicit_finish_runs_final_with_last_state() { + check_backends!(STATE, check_final_state); +} + +#[test] +fn final_procedures_run_in_modules_and_generate_blocks() { + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + for name in ["first", "second"] { + assert_eq!(sim.get(sim.signal(name)), 1u8.into(), "{name}"); + } + // Output variable ports connect through implicit continuous + // assignments (4.9.6, 23.2.2.3). Finalization does not run another + // scheduled settle (9.2.3), so inspect the child's own final write. + let child_done = sim.child_signal(&[("child", 0)], "done"); + assert_eq!(sim.get(child_done), 1u8.into()); + assert_eq!(sim.get(sim.signal("generated")), 3u8.into()); + let mut labels = displays(sim.drain_runtime_events()); + labels.sort(); + assert_eq!( + labels, + [ + "child", + "generate 0", + "generate 1", + "top first", + "top second" + ] + .map(|text| text.as_bytes().to_vec()) + ); + } + check_backends!(HIERARCHY, check); +} + +#[test] +fn finish_in_final_stops_remaining_execution() { + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("after_finish")), 0u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final calls=1".to_vec()] + ); + } + check_backends!(FINISH, check); +} + +#[test] +fn host_finish_is_explicit_and_runs_final_only_once() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, calls); + initial begin value = 3; calls = 0; #2 value = 7; end + final begin calls = calls + 1; value = value + 10; $display("final"); end + endmodule"#; + fn check(mut sim: Simulation) { + let value = sim.signal("value"); + let calls = sim.signal("calls"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(calls), 0u8.into()); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(value), 3u8.into()); + assert_eq!(sim.get(calls), 0u8.into()); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(value), 7u8.into()); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(calls), 0u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + sim.finish().unwrap(); + assert_eq!(sim.get(value), 17u8.into()); + assert_eq!(sim.get(calls), 1u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final".to_vec()] + ); + sim.finish().unwrap(); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(calls), 1u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn stop_in_final_resumes_at_the_cursor_without_running_scheduled_events() { + let source = r#"`timescale 1ns/1ns + module Top(output int calls, other_calls, late_event); + initial begin calls = 0; other_calls = 0; late_event = 0; #10 late_event = 1; end + final begin calls = calls + 1; $stop; calls = calls + 1; end + final other_calls = other_calls + 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.finish().unwrap(); + assert!(sim.is_stopped()); + assert!(sim.checkpoint().is_err()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("late_event")), 0u8.into()); + // The other final may precede or follow the suspended one. After + // resumption both must be complete, with no restart of either body. + sim.step().unwrap(); + assert!(!sim.is_stopped()); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!(sim.get(sim.signal("other_calls")), 1u8.into()); + let finished = sim.checkpoint().unwrap(); + sim.restore(&finished).unwrap(); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + sim.run_until(100).unwrap(); + sim.finish().unwrap(); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(sim.signal("late_event")), 0u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!(sim.get(sim.signal("other_calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn stop_suspends_without_running_final() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, calls); + initial begin value = 3; calls = 0; #1 $stop; value = 7; $finish; end + final begin calls = calls + 1; value = value + 10; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(10).unwrap(); + assert!(sim.is_stopped()); + assert_eq!(sim.get(sim.signal("calls")), 0u8.into()); + assert_eq!(sim.get(sim.signal("value")), 3u8.into()); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("value")), 17u8.into()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn fatal_runs_final_and_preserves_the_original_error() { + // IEEE 1800-2023 20.10: $fatal implicitly calls $finish. + let source = r#"`timescale 1ns/1ns + module Top(output int calls); + initial begin calls = 0; #1 $fatal(1, "initial fatal"); end + final begin calls = calls + 1; $display("final after fatal"); end + endmodule"#; + fn check(mut sim: Simulation) { + let error = sim.run_until(2).unwrap_err(); + assert!(error.to_string().contains("initial fatal"), "{error}"); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + let events = sim.drain_runtime_events(); + assert!(events.iter().any(|event| matches!(event, + RuntimeEvent::Report(report) + if report.severity == celox::Severity::Fatal && report.message == b"initial fatal" + )), "{events:?}"); + assert!( + events.iter().any(|event| matches!(event, + RuntimeEvent::Display { message } if message == b"final after fatal" + )), + "{events:?}" + ); + } + check_backends!(source, check); +} + +#[test] +fn final_order_is_sequential_and_repeatable() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin #1; $finish; end + final begin $write("A"); $display("a"); end + final begin $write("B"); $display("b"); end + final begin $write("C"); $display("c"); end + endmodule"#; + fn transcript(mut sim: Simulation) -> Vec { + sim.run_until(2).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter(|event| { + matches!( + event, + RuntimeEvent::Write { .. } | RuntimeEvent::Display { .. } + ) + }) + .collect() + } + // Order is implementation-defined; require complete procedure pairs and + // stability between fresh instances, not a particular source order. + for four_state in [false, true] { + let build = || { + Simulation::from_sv_sources(vec![(source, Path::new("final_order.sv"))], "Top") + .four_state(four_state) + }; + let first = transcript(build().build_interpreter().unwrap()); + assert_eq!(first, transcript(build().build_interpreter().unwrap())); + assert_eq!(first.len(), 6); + let mut labels = Vec::new(); + for pair in first.as_chunks::<2>().0 { + let [ + RuntimeEvent::Write { message: upper }, + RuntimeEvent::Display { message: lower }, + ] = pair + else { + panic!("interleaved final procedures: {first:?}"); + }; + assert_eq!(upper.len(), 1); + assert_eq!(lower, &upper.to_ascii_lowercase()); + labels.push(upper[0]); + } + labels.sort_unstable(); + assert_eq!(labels, b"ABC"); + } +} + +#[test] +fn watched_idle_deferred_fatal_runs_final_and_preserves_the_error() { + let source = r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb assert final (!fail) else $fatal(1, "deferred fatal"); + final calls = calls + 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.set_fail_on(Some(celox::Severity::Error)); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + // No timed process is scheduled: run_until must finalize a fatal + // deferred report matured while settling watched host writes. + let error = sim.run_until(1).unwrap_err(); + assert!(error.to_string().contains("deferred fatal"), "{error}"); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn pending_deferred_output_does_not_run_after_final() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin assert final (0) else $display("late"); $finish; end + final $display("final"); + endmodule"#; + fn check(mut sim: Simulation) { + sim.step().unwrap(); + assert!(sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + assert_eq!(sim.step().unwrap(), None); + assert!(displays(sim.drain_runtime_events()).is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn pending_deferred_output_does_not_run_while_final_is_stopped() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin assert final (0) else $display("late"); $finish; end + final begin $display("before"); $stop; $display("after"); end + endmodule"#; + fn check(mut sim: Simulation) { + sim.step().unwrap(); + assert!(sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"before".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + sim.step().unwrap(); + assert!(!sim.is_stopped()); + assert!(sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"after".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn event_drain_finalizes_immediate_fatal_before_deferred_actions() { + for deferred in [ + "", + "always_comb assert final (!fail) else $display(\"deferred\");", + ] { + let source = format!( + r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb if (fail) $fatal(1, "drain fatal"); + {deferred} + final begin calls += 1; $display("final"); end + endmodule"# + ); + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.drain_runtime_events(); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + let events = sim.drain_runtime_events(); + assert!(sim.is_finished(), "{events:?}"); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!( + events + .iter() + .filter(|event| matches!(event, + RuntimeEvent::Report(report) if report.severity == celox::Severity::Fatal + && report.message == b"drain fatal" + )) + .count(), + 1, + "{events:?}" + ); + assert_eq!(displays(events), vec![b"final".to_vec()]); + assert!(sim.drain_runtime_events().is_empty()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source.as_str(), check); + } +} + +#[test] +fn saved_state_contains_final_updates_after_lazy_finish() { + let source = r#"`timescale 1ns/1ns + module Top(input bit go, output int result, calls); + initial begin result = 7; calls = 0; end + always_comb if (go) $finish; + final begin result = 42; calls += 1; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let before = sim.save_state().unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let finished = sim.save_state().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + sim.load_state(&before).unwrap(); + assert!(!sim.is_finished()); + sim.load_state(&finished).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn saving_state_rejects_a_stop_reached_inside_final() { + let source = r#"`timescale 1ns/1ns + module Top(input bit go, output int result); + initial result = 0; + always_comb if (go) $finish; + final begin result = 7; $stop; result = 42; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + assert!(matches!( + sim.save_state(), + Err(celox::StateError::Checkpoint( + celox::CheckpointError::Stopped + )) + )); + assert!(sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 7u8.into()); + sim.step().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + let finished = sim.save_state().unwrap(); + sim.load_state(&finished).unwrap(); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn saving_state_preserves_fatal_and_runs_final() { + let source = r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb if (fail) $fatal(1, "save fatal"); + final calls += 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + assert!(matches!(sim.save_state(), + Err(celox::StateError::Runtime(celox::RuntimeErrorCode::Fatal { message, .. })) + if message == "save fatal" + )); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index e34c6124f7a..9000b8ab688 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5486,14 +5486,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "final construct", - r#" - module Top(input logic done); - final assert (done); - endmodule - "#, - ), ( "non-ANSI port expressions", r#" diff --git a/crates/celox/tests/runtime_api.rs b/crates/celox/tests/runtime_api.rs index d88637e469c..4e34e8420a9 100644 --- a/crates/celox/tests/runtime_api.rs +++ b/crates/celox/tests/runtime_api.rs @@ -13,7 +13,7 @@ all_backends! { @build Simulator::builder(r#" module Top { always_comb { $assert(1'd0, "site zero"); } } "#, "Top"); - assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Runtime { message, .. }) if message == "site zero")); + assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Fatal { message, .. }) if message == "site zero")); assert_eq!(bare(sim.drain_runtime_events()), vec![RuntimeEvent::Report(Report::new(Severity::Fatal, b"site zero".to_vec()))]); assert!(bare(sim.drain_runtime_events()).is_empty()); } @@ -30,7 +30,7 @@ module Top { } } "#, "Top"); - assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Runtime { message, .. }) if message == "site two")); + assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Fatal { message, .. }) if message == "site two")); assert_eq!(bare(sim.drain_runtime_events()), vec![ RuntimeEvent::Display { message: b"first".to_vec() }, RuntimeEvent::Display { message: b"second".to_vec() }, diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 43766a4dabe..1bf274b058a 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -678,6 +678,25 @@ fn native_program_image_rejects_v19_before_loading_float_helper_abi() { )); } +/// Version 39 replaces the initializer flag with a process phase. +#[test] +fn native_program_image_rejects_v38_before_decoding_process_kinds() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&38u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(38)) + )); +} + /// Version 38 adds host operand value kinds to the runtime metadata. #[test] fn native_program_image_rejects_v37_before_decoding_host_operand_value_kinds() { diff --git a/crates/celox/tests/sv_vcd.rs b/crates/celox/tests/sv_vcd.rs index c642322ee11..bef605a10ed 100644 --- a/crates/celox/tests/sv_vcd.rs +++ b/crates/celox/tests/sv_vcd.rs @@ -681,8 +681,8 @@ fn scoped_parameter_dump_does_not_select_imported_state() { } #[test] -fn direct_fatal_errors_publish_waveform_without_freezing_recovery() { - for action in ["eval_comb", "try_dump"] { +fn direct_fatal_errors_publish_waveform_and_terminate() { + for action in ["eval_comb", "try_dump", "dump"] { check_direct_fatal_waveform(action); } } @@ -701,9 +701,10 @@ fn check_direct_fatal_waveform(action: &str) { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("direct-fatal.vcd"); let source = format!( - r#"module Top(input logic fail_now, output logic value); - initial begin $dumpfile("{}"); $dumpvars(0,Top.value); end + r#"module Top(input logic fail_now, output logic value, output int final_calls); + initial begin final_calls=0; $dumpfile("{}"); $dumpvars(0,Top.value); end always_comb begin value=fail_now; if(fail_now) $fatal(1,"direct primary"); end + final final_calls += 1; endmodule"#, path.display() ); @@ -716,6 +717,13 @@ fn check_direct_fatal_waveform(action: &str) { let error = match action { "eval_comb" => format!("{:?}", simulation.eval_comb().unwrap_err()), "try_dump" => format!("{:?}", simulation.try_dump(0).unwrap_err()), + "dump" => { + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + simulation.dump(0); + })) + .unwrap_err(); + *panic.downcast::().unwrap() + } "run_until" => format!("{:?}", simulation.run_until(1).unwrap_err()), "run_until_bounded" => format!("{:?}", simulation.run_until_bounded(1, 10).unwrap_err()), _ => unreachable!(), @@ -723,11 +731,17 @@ fn check_direct_fatal_waveform(action: &str) { assert!(error.contains("direct primary"), "{action}: {error}"); let text = std::fs::read_to_string(path).unwrap(); assert!(text.contains("1!"), "{action}: {text}"); + // $fatal implicitly calls $finish (20.10), including when lazy + // combinational evaluation was triggered by a waveform API. + assert!(simulation.is_finished(), "{action}"); + let final_calls = simulation.signal("final_calls"); + assert_eq!(simulation.get(final_calls), 1u8.into(), "{action}"); simulation.modify(|io| io.set(fail, 0u8)).unwrap(); simulation.eval_comb().unwrap(); let value = simulation.signal("value"); - assert_eq!(simulation.get(value), 0u8.into()); - assert!(!simulation.is_finished()); + assert_eq!(simulation.get(value), 1u8.into(), "{action}"); + simulation.finish().unwrap(); + assert_eq!(simulation.get(final_calls), 1u8.into(), "{action}"); } #[test] diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index e33f385b835..541cfe4ae39 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -113,6 +113,8 @@ mod edges; mod file_core; #[path = "frontends/systemverilog/file_io.rs"] mod file_io; +#[path = "frontends/systemverilog/final.rs"] +mod final_procedures; #[path = "frontends/systemverilog/generate.rs"] mod generate; #[path = "frontends/systemverilog/hierarchical_references.rs"] diff --git a/crates/celox/tests/test_utils/veryl_sim.rs b/crates/celox/tests/test_utils/veryl_sim.rs index e19773cfad0..ed3eb9010ea 100644 --- a/crates/celox/tests/test_utils/veryl_sim.rs +++ b/crates/celox/tests/test_utils/veryl_sim.rs @@ -148,7 +148,7 @@ fn take_runtime_error() -> Result<(), RuntimeErrorCode> { if is_non_progressing_loop_diagnostic(&message) { Err(RuntimeErrorCode::DetectedTrueLoop) } else { - Err(RuntimeErrorCode::Runtime { + Err(RuntimeErrorCode::Fatal { message, signals: Vec::new(), }) diff --git a/crates/celox/tests/veryl_reference_adapter.rs b/crates/celox/tests/veryl_reference_adapter.rs index 2955afbbce7..af26db3177d 100644 --- a/crates/celox/tests/veryl_reference_adapter.rs +++ b/crates/celox/tests/veryl_reference_adapter.rs @@ -87,7 +87,7 @@ fn empty_modify_still_reports_initial_fatal_diagnostics() { let mut sim = build_veryl_adapter(&[(code, Path::new("test.veryl"))], "Top", false); assert_eq!( sim.modify(|_| {}).unwrap_err(), - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "initial fatal from empty modify".to_string(), signals: Vec::new(), }, diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ced3e927699..a3972e2dd6c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -188,7 +188,7 @@ it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). - Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, specializations of a parameterized class outside the package or compilation unit that declares it, and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. -- Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), +- Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. - Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), @@ -594,6 +594,28 @@ simulation is suspended (`CheckpointError::Stopped`). In an `always` process, `$ Its diagnostic level argument prints nothing. Batch hosts without an interactive mode, such as the VPI host, end the run at `$stop`. +### Final procedures {#final-procedures} + +`final` procedures require `Simulation`. They run once, sequentially at the +termination time, on `$finish`, `$fatal` or an explicit `Simulation::finish()` +call (IEEE 1800-2023 9.2.3, 20.10). Their relative order is deterministic but +unspecified. The CLI and sv-tests batch driver finish when scheduled work runs +out. An idle `step()` or the end of `run_until()` does not terminate the reusable +Rust simulation; a host can supply more inputs or call `finish()`. + +Ordinary `$stop` does not run final procedures. A `$stop` inside a final +procedure suspends finalization, and a later step or `finish()` resumes it. +`$finish` inside a final procedure immediately ends that procedure and skips +all remaining finals. The original `$fatal` error is preserved when it starts +termination. + +No scheduled HDL events run after final procedures. In particular, a +nonblocking assignment made directly in a final procedure never applies its +queued update. Timing controls and calls to user tasks are rejected, including +through functions. Calls to functions that schedule events after returning +require an initial/always process context and are rejected from final +procedures (13.4.4). `fork` / `join_none` remains unsupported. + ### Programs {#programs} A `program` (IEEE 1800-2023 Clause 24) is declared and instantiated like a @@ -621,8 +643,8 @@ so a program that resumes after `#0` reads their new values, whereas 4.5 evaluates them only once the reactive region set is empty; programs nested in modules and anonymous programs are rejected; a program that no module instantiates is not an implicit top level next to the design's top -module; `final` procedures and clocking blocks are unsupported in programs as -everywhere. +module; clocking blocks are unsupported. Program `final` procedures run during +termination, including the implicit `$finish` after the last initial procedure. ### `$exit` diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 952eb064d73..f148c3826f0 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -55,12 +55,12 @@ compilation unit; choose the top by its SystemVerilog module name. | What your test needs | API | | --- | --- | | Set inputs, evaluate logic and advance clock events from Rust | `Simulator::from_sv_sources` | -| Advance simulation time and run `initial` and `always` processes with timing controls | `Simulation::from_sv_sources` | +| Advance simulation time, run timed processes and execute `final` procedures | `Simulation::from_sv_sources` | | Include both Veryl and SystemVerilog sources | `Simulator::from_mixed_sources` | `Simulator::tick` drives the rising edge of the selected event. `Simulation` tracks time and runs scheduled edges. Constant initialization applies to both. -`initial` blocks that read design state or call system tasks, processes with +`final` procedures, `initial` blocks that read design state or call system tasks, processes with timing controls and `always` blocks whose sensitivity list is neither `@*` nor [the variables they read](./systemverilog-reference#timing-controls) run as processes and need `Simulation`. A `Simulator` runs no process, so building @@ -85,6 +85,7 @@ The main supported areas are: | Timed processes | `initial` and `always` with `#delay` (also time literals such as `#5ns`), `@(...)` on variables, edges, selects, expressions and `@*`, `wait (...)`, nonblocking assignments and task calls with timing controls | | Computation | Arithmetic, selects, assignment patterns, branches, loops and functions | | Simulation helpers | Immediate and deferred immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | +| Termination | `final` procedures on `$finish`, `$fatal` or explicit `Simulation::finish()`; see [termination semantics](./systemverilog-reference#final-procedures) | Each area has restrictions. Use the [detailed support list](./systemverilog-reference#what-is-supported) to check From 7e7b80ed3e64a71c43c920b1af7f23705cf5bd64 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 09:55:52 +0900 Subject: [PATCH 7/9] feat(runtime)!: opt-in partitioned combinational settle Cut the combinational settle into contiguous ranges of its schedule, each guarded by a dirty flag in a hidden `$settle.flags` object. A partition that runs clears its flag and sets the flags of the partitions reading what it wrote; every other writer of state the settle reads or writes sets them too: generated stores and commits, host and VCD writes, initial values, state loads, and a retained raw view (the untracked flag, after which every partition runs). Off unless `SirPass::PartitionedSettle` is enabled or `SimulatorBuilder::settle_partition` is called (#2013). The flags stay out of state files and of the differential and derived-edge checks. `SimulatorBuilder::settle_check` runs every settle a second time with every partition flagged and panics where the two differ. BREAKING CHANGE: RuntimeSchema has a new field, `settle_partitions`, and MemoryLayout a new field, `settle`; SirPass has a new variant, PartitionedSettle. Native images use container format 39; images written by earlier versions must be rebuilt. Change-Id: I6d2c7e90376cf6fd96173e2cd4959f79171834fc --- CLAUDE.md | 1 + crates/celox-backend-arm64/src/isel/tests.rs | 1 + crates/celox-backend-wasm/src/lib.rs | 1 + .../src/backend/native/isel/tests.rs | 1 + .../backend/native/isel/tests/bit_count.rs | 1 + .../src/backend/native/isel/tests/memory.rs | 4 + .../backend/native/isel/tests/selection.rs | 1 + .../src/backend/native/isel/tests/wide.rs | 2 + .../src/backend/native/sparse_write_state.rs | 1 + .../tests/support/packed_index_fixture.rs | 1 + crates/celox-design/src/lib.rs | 22 + crates/celox-frontend-core/src/lib.rs | 2 +- .../src/symbolic/assembly.rs | 157 ++++- .../src/symbolic/parallel.rs | 17 + crates/celox-runtime/src/backend.rs | 30 +- crates/celox-sir-opt/src/lib.rs | 3 +- .../memory/pass_identity_store_bypass.rs | 246 ++++++- crates/celox-sir-opt/src/policy.rs | 36 +- crates/celox-slt/src/scheduler.rs | 604 +++++++++++++++++- crates/celox-state-layout/src/lib.rs | 15 + crates/celox-state-layout/src/settle.rs | 74 +++ crates/celox/src/backend/interp.rs | 10 +- crates/celox/src/backend/memory_image.rs | 6 + crates/celox/src/backend/native/backend.rs | 44 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/backend/runtime.rs | 21 +- crates/celox/src/backend/wasm_runtime.rs | 5 + crates/celox/src/derived_edge.rs | 20 +- crates/celox/src/ir.rs | 30 +- crates/celox/src/lib.rs | 2 + crates/celox/src/optimizer.rs | 11 +- crates/celox/src/parser.rs | 8 +- crates/celox/src/settle.rs | 238 +++++++ crates/celox/src/simulation/differential.rs | 16 +- crates/celox/src/simulator.rs | 1 + crates/celox/src/simulator/builder.rs | 52 +- crates/celox/src/simulator/state_file.rs | 11 +- crates/celox/src/testbench.rs | 5 +- crates/celox/tests/settle_partitions.rs | 297 +++++++++ docs/internals/optimizations.md | 9 + packages/celox/src/types.ts | 4 +- 41 files changed, 1956 insertions(+), 56 deletions(-) create mode 100644 crates/celox-state-layout/src/settle.rs create mode 100644 crates/celox/src/settle.rs create mode 100644 crates/celox/tests/settle_partitions.rs diff --git a/CLAUDE.md b/CLAUDE.md index 4b006d7bd54..40fa5b29d36 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -101,6 +101,7 @@ GCC-style optimization level presets with per-pass overrides. | `IdentityStoreBypass` | Detects identity copies and registers address aliases | | `TailCallSplit` | Splits large functions into tail-call chains (enabled even at O0) | | `DerivedEdgeUnits` | Runs edges of gated/divided clocks in generated units instead of the Rust plan walk (not a SIR transform; costs build time, `-sir:derived_edge_units` to opt out) | +| `PartitionedSettle` | Splits the combinational settle into partitions that run only when state they read changed (not a SIR transform; off unless enabled, `+sir:partitioned_settle`; `SimulatorBuilder::settle_check` cross-checks it) | ### Cranelift Backend Optimization diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index 3456a2c8be1..92e7fc934be 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -16,6 +16,7 @@ fn layout_for(address: AbsoluteAddr, width: usize, four_state: bool) -> MemoryLa let total_size = plane_size * if four_state { 2 } else { 1 }; MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-wasm/src/lib.rs b/crates/celox-backend-wasm/src/lib.rs index 5b146b76b5a..cc010904637 100644 --- a/crates/celox-backend-wasm/src/lib.rs +++ b/crates/celox-backend-wasm/src/lib.rs @@ -6488,6 +6488,7 @@ mod bit_count_tests { MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests.rs b/crates/celox-backend-x86/src/backend/native/isel/tests.rs index 19b3c5d844b..8d513fecf0b 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests.rs @@ -16,6 +16,7 @@ use num_bigint::BigUint; fn empty_layout() -> MemoryLayout { MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs index 7ed5e929daa..db8fe2abd3f 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs @@ -196,6 +196,7 @@ fn compile_bit_count(op: UnaryOp, source_width: usize, four_state: bool) -> Comp let layout = MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs index aed958745c1..97a0c5cf9e5 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs @@ -800,6 +800,7 @@ fn narrowed_wide_binary_store_does_not_write_source_width() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1130,6 +1131,7 @@ fn execute_unaligned_64_bit_load(dynamic: bool) -> u64 { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1295,6 +1297,7 @@ fn verify_scalar_alignment_matrix(dynamic: bool, four_state: bool) { eu.verify(); let layout = MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1511,6 +1514,7 @@ fn verify_wide_alignment_matrix(dynamic: bool) { eu.verify(); let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs index ddce616c2bb..37503198e34 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs @@ -511,6 +511,7 @@ fn lowers_shared_selector_roots_to_cached_indexed_table_loads() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs index 51d1ae82584..3f94d1bda99 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs @@ -660,6 +660,7 @@ fn narrow_wide_shift_uses_only_chunks_covered_by_the_result() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -836,6 +837,7 @@ fn wide_shift_result_is_canonical_before_mux_condition() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs index fd1e45ec7e1..e0b20af1d78 100644 --- a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs +++ b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs @@ -1426,6 +1426,7 @@ mod tests { .collect(); MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs index 437eff6db62..0c82cb95455 100644 --- a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs +++ b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs @@ -145,6 +145,7 @@ pub fn compile(recover: bool) -> CompiledUpdate { )]; let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: celox_state_layout::MemoryLayoutMode::Packed, offsets: [ diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7294c286a4e..c2a6d1ce08c 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1053,6 +1053,27 @@ pub struct RuntimeSchema { /// Generated units that run an edge of an event with every derived /// clock domain it reaches, for the events that have them. pub derived_edges: Vec>, + /// The partitions of a partitioned combinational settle, when it is + /// partitioned. + pub settle_partitions: Option>, +} + +/// A combinational settle split into partitions that run only when state +/// they read changed since they last ran. +/// +/// Byte `p` of `flags` is partition `p`'s dirty flag; the byte after the +/// last partition's is the untracked byte, set once state may change +/// without anyone setting flags (a retained raw view), after which every +/// partition always runs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SettlePartitions { + pub flags: A, + pub partitions: u32, + /// State the settle reads or writes, with the partitions to mark when + /// something other than the settle writes it. A written object lists + /// its writers as well, so that, as in a single pass, the settle + /// recomputes it. + pub marks: Vec<(A, Vec)>, } /// The process units that run the edges of one event together with its @@ -1279,6 +1300,7 @@ impl Default for RuntimeSchema { time_slots: Vec::new(), scheduler: None, derived_edges: Vec::new(), + settle_partitions: None, } } } diff --git a/crates/celox-frontend-core/src/lib.rs b/crates/celox-frontend-core/src/lib.rs index 05e833c6575..5a208e3e8c1 100644 --- a/crates/celox-frontend-core/src/lib.rs +++ b/crates/celox-frontend-core/src/lib.rs @@ -18,7 +18,7 @@ pub use shared::{ pub use trace::{FrontendTrace, FrontendTraceOptions, TraceSimModule}; pub use symbolic::flattening; -pub use symbolic::parallel::ParallelScheduleOptions; +pub use symbolic::parallel::{ParallelScheduleOptions, SettlePartitionMode}; pub(crate) type HashMap = fxhash::FxHashMap; pub(crate) type HashSet = fxhash::FxHashSet; diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 1b720f15176..11f7925b198 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -8,7 +8,7 @@ use crate::symbolic::artifact::{ use crate::{ FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap, HashSet, InstancePath, ParallelScheduleOptions, ParserError, ScheduledRtl, ScheduledRtlOutput, - SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening, + SettlePartitionMode, SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening, }; use celox_design::{ BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign, @@ -1507,6 +1507,29 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } let parallel_comb_blocks = parallel.enabled().then(|| comb_blocks.clone()); + // The flag object of a partitioned settle is declared once the + // partitions are known; reserve its address now. + let root_instance = expanded[&InstancePath(Vec::new())]; + let settle_flags = + settle_partitioning(parallel, &comb_blocks, &global_arena, eval_apply_ffs.len()).map( + |target_cost| { + let var_id = SourceVarId( + modules[&root_id] + .variables + .keys() + .map(|id| id.0 + 1) + .max() + .unwrap_or(0), + ); + scheduler::SettlePartitioning { + flags: AbsoluteAddr { + instance_id: root_instance, + var_id, + }, + target_cost, + } + }, + ); let sched_start = flatten_timing.then(std::time::Instant::now); let schedule = match scheduler::sort_with_unpacked_element_widths( comb_blocks, @@ -1517,6 +1540,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( &var_widths, &unpacked_element_widths, next_runtime_error_code, + settle_flags, ) { Ok(schedule) => schedule, Err(error) => { @@ -1557,6 +1581,19 @@ pub fn schedule_symbolic_rtl_reporting_loops( }); } }; + let settle_partitions = schedule.partitions.clone(); + + let settle_flags = settle_flags.filter(|_| !settle_partitions.is_empty()); + if let Some(settle) = &settle_flags { + // The flags carry what changed from one settle to the next. + persistent_comb_state.insert(settle.flags); + declare_settle_flags( + &mut modules, + root_id, + settle.flags.var_id, + settle_partitions.len(), + ); + } let object_sizes = super::parallel::ObjectSizes { widths: &var_widths, element_widths: &unpacked_element_widths, @@ -1677,7 +1714,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( // events; that copy lets the FF part use comb values in registers. // Beyond that the copies would multiply the design by its event count, // so the ticks share the one `eval_comb` program instead. - let merge_comb_apply = eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS; + // A merged program drops comb stores the next full settle would redo; + // a partitioned settle keeps what its skipped partitions stored. + let merge_comb_apply = + eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS && settle_flags.is_none(); let mut eval_comb_apply_ffs = HashMap::default(); let mut fused_direct_ff_writes = HashMap::default(); if let ( @@ -1920,6 +1960,21 @@ pub fn schedule_symbolic_rtl_reporting_loops( .chain(bound_initials) .map(|(_, init)| init) .collect(); + if let Some(settle) = &settle_flags { + // Every partition runs at the first settle. + let partitions = settle_partitions.len(); + let value = (0..partitions).fold(BigUint::default(), |value, partition| { + value | (BigUint::from(1u8) << (partition * 8)) + }); + initial_memory_values.push(InitialStateValue { + address: settle.flags, + data: InitialStateData::Packed { + value, + mask: BigUint::default(), + written_mask: (BigUint::from(1u8) << ((partitions + 1) * 8)) - 1u8, + }, + }); + } let state_objects: HashMap = instance_modules .iter() .flat_map(|(&instance_id, module_id)| { @@ -2326,6 +2381,32 @@ pub fn schedule_symbolic_rtl_reporting_loops( let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); let root_instance = expanded[&InstancePath(Vec::new())]; + let settle_partitions = settle_flags.map(|settle| { + let mut marks: HashMap> = HashMap::default(); + for (index, partition) in settle_partitions.iter().enumerate() { + let index = index as u32; + for addr in &partition.reads { + if let Some(&state) = source_to_state.get(addr) { + marks.entry(state).or_default().insert(index); + } + } + for addr in &partition.writes { + if let Some(&state) = source_to_state.get(addr) { + marks.entry(state).or_default().insert(index); + } + } + } + let mut marks = marks + .into_iter() + .map(|(state, partitions)| (state, partitions.into_iter().collect())) + .collect::>(); + marks.sort_unstable(); + celox_design::SettlePartitions { + flags: project(settle.flags), + partitions: settle_partitions.len() as u32, + marks, + } + }); let scheduler = scheduler_slots.map(|slots| celox_design::SchedulerSchema { slots: slots.map(|var_id| { project(AbsoluteAddr { @@ -2468,6 +2549,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( time_slots, scheduler, derived_edges: Vec::new(), + settle_partitions, }, }; @@ -2485,6 +2567,77 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) } +/// Smallest combinational program, in expression nodes, whose settle +/// [`SettlePartitionMode::Estimated`] partitions. +const MIN_PARTITIONED_SETTLE_COST: usize = 20_000; +/// Expression nodes per partition of an estimated partitioned settle. +const SETTLE_PARTITION_COST: usize = 2_000; + +/// The cost per partition of a partitioned settle of `comb_blocks`, or +/// `None` to keep one pass. +/// +/// A partition costs a flag test per settle and flag stores in every writer +/// of what it reads, and pays off when most of the program is idle in most +/// settles. A design with few event domains drives most of its logic from +/// one clock, so it keeps the single pass, as does a small program. +fn settle_partitioning( + parallel: &ParallelScheduleOptions, + comb_blocks: &[LogicPath], + arena: &SLTNodeArena, + events: usize, +) -> Option { + // Lane-partitioned kernels run the comb program as lane tasks. + if parallel.enabled() { + return None; + } + match parallel.settle { + SettlePartitionMode::Off => None, + SettlePartitionMode::Always => Some(1), + SettlePartitionMode::Estimated => { + if events <= MERGED_COMB_APPLY_EVENTS { + return None; + } + let cost: usize = comb_blocks + .iter() + .map(|path| scheduler::path_cost(arena, path)) + .sum(); + (cost >= MIN_PARTITIONED_SETTLE_COST).then_some(SETTLE_PARTITION_COST) + } + } +} + +/// Declare the flags of a settle of `partitions` partitions, one byte each +/// plus the untracked byte, as a hidden variable of the top module. +fn declare_settle_flags( + modules: &mut HashMap, + root: ModuleId, + var_id: SourceVarId, + partitions: usize, +) { + let width = (partitions + 1) * 8; + let variables = &mut modules.get_mut(&root).expect("top module").variables; + variables.insert( + var_id, + crate::symbolic::artifact::SymbolicVariable { + path: vec!["$settle".to_string(), "flags".to_string()], + kind: crate::VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state: false, + kind: DomainKind::Other, + type_kind: celox_design::PortTypeKind::Bit, + array_dims: Vec::new(), + value_kind: Default::default(), + }, + packed_dims: vec![width], + unpacked_ranges: Vec::new(), + source: None, + module_affiliated: false, + }, + ); +} + /// Declare the hidden objects a compiled scheduler exchanges with the /// runtime (`RuntimeSchema::scheduler`) as variables of the top module, for /// a design with `process_count` process kernels. A design without kernels diff --git a/crates/celox-frontend-core/src/symbolic/parallel.rs b/crates/celox-frontend-core/src/symbolic/parallel.rs index dccfada3730..f0824ef3d88 100644 --- a/crates/celox-frontend-core/src/symbolic/parallel.rs +++ b/crates/celox-frontend-core/src/symbolic/parallel.rs @@ -27,6 +27,22 @@ pub struct ParallelScheduleOptions { /// Smallest accepted estimated speedup of a partitioned phase, in /// percent of its single-lane cost. pub minimum_speedup_percent: u64, + /// Whether the combinational settle may be split into partitions that + /// run only when what they read changed. Only a host that reports its + /// writes and instruments the units it generates may request it. + pub settle: SettlePartitionMode, +} + +/// Whether a settle is partitioned ([`ParallelScheduleOptions::settle`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SettlePartitionMode { + /// One pass over the whole combinational program. + #[default] + Off, + /// Partition designs with many event domains and a large program. + Estimated, + /// Partition every program into the smallest partitions. For tests. + Always, } impl ParallelScheduleOptions { @@ -35,6 +51,7 @@ impl ParallelScheduleOptions { lanes: 1, synchronization_cost: 400, minimum_speedup_percent: 125, + settle: SettlePartitionMode::Off, }; /// Request `lanes` simulation lanes with the default cost model. diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 94ba20cf12e..05bb918ca1e 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -119,6 +119,27 @@ pub trait SimBackend { assert!(offset + bytes.len() <= len, "write past the memory image"); // Safety: the backend exposes `len` writable bytes at `ptr`. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.add(offset), bytes.len()) }; + self.mark_settle_range(offset, bytes.len()); + } + + /// Set the flags of the settle partitions reading `offset..offset + len`, + /// which the host wrote. + fn mark_settle_range(&mut self, offset: usize, len: usize) { + if let Some(settle) = self.layout().settle.as_ref() { + let (ptr, _) = self.memory_as_ptr(); + // SAFETY: the settle layout describes this backend's state image. + unsafe { settle.mark_range(ptr.cast_mut(), offset, len) }; + } + } + + /// From now on run every settle partition on every settle: a raw view + /// of the state can change it without reporting. + fn mark_settle_untracked(&mut self) { + if let Some(settle) = self.layout().settle.as_ref() { + let (ptr, _) = self.memory_as_ptr(); + // SAFETY: the settle layout describes this backend's state image. + unsafe { settle.mark_untracked(ptr.cast_mut()) }; + } } /// Return an opaque owner that keeps the memory allocation alive. @@ -200,17 +221,18 @@ pub trait SimBackend { /// Called by host setters, which share the generated-store notification ABI. fn mark_vcd_signal(&mut self, signal: SignalRef) { + let len = signal.array_layout.map_or_else( + || celox_state_layout::get_byte_size(signal.width), + |array| array.element_count * array.element_stride, + ); if let Some(trace) = self.layout().trace.as_ref() { - let len = signal.array_layout.map_or_else( - || celox_state_layout::get_byte_size(signal.width), - |array| array.element_count * array.element_stride, - ); let (ptr, _) = self.memory_as_ptr(); // SAFETY: layout homes and metadata fit in the writable state image. unsafe { trace.mark_range(ptr.cast_mut(), signal.offset, len); } } + self.mark_settle_range(signal.offset, len); } } diff --git a/crates/celox-sir-opt/src/lib.rs b/crates/celox-sir-opt/src/lib.rs index 352f3cbc005..57d173ca032 100644 --- a/crates/celox-sir-opt/src/lib.rs +++ b/crates/celox-sir-opt/src/lib.rs @@ -102,5 +102,6 @@ pub fn optimize( mod policy; pub use policy::{ - OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SirDiagnostics, SirPass, + OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SettlePartition, SirDiagnostics, + SirPass, }; diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs index 7ec294253c5..8d6b6973002 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs @@ -44,6 +44,14 @@ struct StoreCandidate { struct GlobalIdentityFacts { accesses: HashMap, stores: Vec, + /// In a partitioned settle, where each address is loaded and the + /// immediate dominators of every unit (see [`reads_follow_store`]). + settle_loads: Option, +} + +struct SettleLoads { + sites: HashMap>, + immediate_dominators: Vec>, } /// Analyze all combinational units before selecting any whole-program address @@ -69,15 +77,27 @@ pub(in crate::optimizer) fn optimize_program_identity_stores( ); blocked_aliases.extend(program.design.initial_state.iter().map(|init| init.address)); + let settle_flags = settle_flags(program); optimize_eval_comb_identity_stores( &mut program.sir.eval_comb, &metadata, &blocked_aliases, program.layout_requirements.state_aliases(), four_state, + settle_flags, ) } +/// The flags of a partitioned settle, whose guards skip a partition only +/// when it would store what memory already holds. +fn settle_flags(program: &OptimizationContext) -> Option { + program + .runtime_schema + .settle_partitions + .as_ref() + .map(|settle| settle.flags) +} + fn address_metadata(program: &OptimizationContext) -> HashMap { program .design @@ -101,8 +121,9 @@ fn optimize_eval_comb_identity_stores( blocked_aliases: &HashSet, existing_aliases: &HashMap, four_state: bool, + settle_flags: Option, ) -> HashMap { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); let aliases = select_aliases( &facts, metadata, @@ -129,20 +150,36 @@ pub(crate) fn retain_final_identity_aliases(program: &mut OptimizationContext, f let aliases = program.layout_requirements.state_aliases().clone(); let mut valid = aliases.keys().copied().collect::>(); + let settle_flags = settle_flags(program); retain_aliases_valid_for_units( &program.sir.eval_comb, &aliases, &metadata, four_state, + settle_flags, &mut valid, ); for units in program.sir.eval_comb_apply_ffs.values() { - retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid); + retain_aliases_valid_for_units( + units, + &aliases, + &metadata, + four_state, + settle_flags, + &mut valid, + ); } // The lane-partitioned combinational kernel is one more projection of the // same comb logic, lowered and optimized independently. with_parallel_comb_units(program, |units| { - retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid); + retain_aliases_valid_for_units( + units, + &aliases, + &metadata, + four_state, + settle_flags, + &mut valid, + ); }); program .layout_requirements @@ -190,17 +227,31 @@ pub(crate) fn remove_final_identity_alias_stores( return; } let metadata = address_metadata(program); + let settle_flags = settle_flags(program); remove_proven_alias_stores( &mut program.sir.eval_comb, validated_aliases, &metadata, four_state, + settle_flags, ); for units in program.sir.eval_comb_apply_ffs.values_mut() { - remove_proven_alias_stores(units, validated_aliases, &metadata, four_state); + remove_proven_alias_stores( + units, + validated_aliases, + &metadata, + four_state, + settle_flags, + ); } with_parallel_comb_units(program, |units| { - remove_proven_alias_stores(units, validated_aliases, &metadata, four_state); + remove_proven_alias_stores( + units, + validated_aliases, + &metadata, + four_state, + settle_flags, + ); }); } @@ -263,9 +314,10 @@ fn retain_aliases_valid_for_units( aliases: &HashMap, metadata: &HashMap, four_state: bool, + settle_flags: Option, valid: &mut HashSet, ) { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); valid.retain(|alias| { aliases .get(alias) @@ -316,8 +368,9 @@ fn remove_proven_alias_stores( aliases: &HashMap, metadata: &HashMap, four_state: bool, + settle_flags: Option, ) { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); let mut sites = aliases .iter() .filter_map(|(&alias, &canonical)| proven_alias_store(&facts, alias, canonical).flatten()) @@ -373,7 +426,7 @@ fn analyze_eval_comb_aliases( ) -> HashMap { // Phase 1: collect every read/write and every syntactic store candidate. // No alias decision is made while the scan is incomplete. - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, None); // Phase 2: require the completed global facts for both identity and // duplicate-store proofs. @@ -390,9 +443,14 @@ fn collect_global_facts( units: &[ExecutionUnit], metadata: &HashMap, four_state: bool, + settle_flags: Option, ) -> GlobalIdentityFacts { let mut accesses = HashMap::::default(); let mut stores = Vec::new(); + let mut settle_loads = settle_flags.map(|_| SettleLoads { + sites: HashMap::default(), + immediate_dominators: units.iter().map(immediate_dominators).collect(), + }); for (eu_index, eu) in units.iter().enumerate() { let mut defs = HashMap::default(); @@ -408,7 +466,7 @@ fn collect_global_facts( // each candidate applies a sparse decrement map rather than cloning // this whole table. let use_counts = register_use_counts(eu); - let must_execute = must_execute_blocks(eu); + let must_execute = must_execute_blocks(eu, settle_flags); for block in eu.blocks.values() { for (instruction_index, inst) in block.instructions.iter().enumerate() { @@ -417,6 +475,13 @@ fn collect_global_facts( increment_saturating( &mut accesses.entry(address.absolute_addr()).or_default().reads, ); + if let Some(loads) = &mut settle_loads { + loads + .sites + .entry(address.absolute_addr()) + .or_default() + .push((eu_index, block.id, instruction_index)); + } } SIRInstruction::Store( address, @@ -477,6 +542,14 @@ fn collect_global_facts( increment_saturating( &mut accesses.entry(source.absolute_addr()).or_default().reads, ); + if let Some(loads) = &mut settle_loads { + // A commit reads its source outside any proof here. + loads + .sites + .entry(source.absolute_addr()) + .or_default() + .push((usize::MAX, block.id, instruction_index)); + } increment_saturating( &mut accesses .entry(destination.absolute_addr()) @@ -498,7 +571,108 @@ fn collect_global_facts( store.address, ) }); - GlobalIdentityFacts { accesses, stores } + GlobalIdentityFacts { + accesses, + stores, + settle_loads, + } +} + +/// Whether every read of `store`'s address comes after the store: later in +/// its block, in a block it dominates, or in a later unit, which the +/// topological order runs after it. Then an alias reads what the store +/// would have written. +/// +/// Only a partitioned settle relaxes the unread rule this way: there a +/// reader in a later partition loads a copy's target from memory, where the +/// single pass forwards the stored register. +fn reads_follow_store(facts: &GlobalIdentityFacts, store: &StoreCandidate) -> bool { + let Some(loads) = &facts.settle_loads else { + return false; + }; + let address = store.address.absolute_addr(); + let Some(sites) = loads.sites.get(&address) else { + return true; + }; + sites.iter().all(|&(eu_index, block, instruction_index)| { + if eu_index == usize::MAX { + return false; + } + if eu_index != store.eu_index { + return eu_index > store.eu_index; + } + if block == store.block { + return instruction_index > store.instruction_index; + } + let dominators = &loads.immediate_dominators[eu_index]; + let mut current = block; + while let Some(&parent) = dominators.get(¤t) { + if parent == store.block { + return true; + } + if parent == current { + return false; + } + current = parent; + } + false + }) +} + +/// The immediate dominator of every block of `eu` reachable from its entry; +/// the entry is its own. +fn immediate_dominators(eu: &ExecutionUnit) -> HashMap { + let blocks = reverse_postorder_with(eu, &terminator_successors); + let indices = blocks + .iter() + .copied() + .enumerate() + .map(|(index, block)| (block, index)) + .collect::>(); + let mut predecessors = vec![Vec::new(); blocks.len()]; + for (index, block_id) in blocks.iter().enumerate() { + if let Some(block) = eu.blocks.get(block_id) { + for successor in terminator_successors(&block.terminator) { + if let Some(&successor_index) = indices.get(&successor) { + predecessors[successor_index].push(index); + } + } + } + } + let mut immediate_dominator = vec![None; blocks.len()]; + if blocks.is_empty() { + return HashMap::default(); + } + immediate_dominator[0] = Some(0); + let mut changed = true; + while changed { + changed = false; + for block in 1..blocks.len() { + let mut defined = predecessors[block] + .iter() + .copied() + .filter(|&predecessor| immediate_dominator[predecessor].is_some()); + let Some(mut new_dominator) = defined.next() else { + continue; + }; + for predecessor in defined { + if let Some(intersection) = + intersect_dominators(predecessor, new_dominator, &immediate_dominator) + { + new_dominator = intersection; + } + } + if immediate_dominator[block] != Some(new_dominator) { + immediate_dominator[block] = Some(new_dominator); + changed = true; + } + } + } + immediate_dominator + .into_iter() + .enumerate() + .filter_map(|(index, dominator)| Some((blocks[index], blocks[dominator?]))) + .collect() } fn identity_commit_is_profitable( @@ -645,7 +819,12 @@ fn select_aliases( || !store.effects_are_removable || blocked_aliases.contains(&alias) || existing_aliases.contains_key(&alias) - || !is_unique_unread_alias(alias, &facts.accesses) + || !(is_unique_unread_alias(alias, &facts.accesses) + || (facts + .accesses + .get(&alias) + .is_some_and(|access| access.writes == 1) + && reads_follow_store(facts, store))) || facts .accesses .get(&canonical) @@ -910,8 +1089,35 @@ fn ff_referenced_addresses(program: &OptimizationContext) -> HashSet) -> HashSet { - let blocks = reverse_postorder(eu); +/// +/// A partitioned settle skips a partition only when its stores would write +/// what memory already holds, so for an identity copy the partition counts +/// as executed: its guard (a branch into a block that stores to +/// `settle_flags`) is treated as always taken. +fn must_execute_blocks( + eu: &ExecutionUnit, + settle_flags: Option, +) -> HashSet { + let successors = |terminator: &SIRTerminator| { + if let ( + Some(flags), + SIRTerminator::Branch { + true_block: (body, _), + .. + }, + ) = (settle_flags, terminator) + && eu.blocks.get(body).is_some_and(|block| { + block.instructions.iter().any(|instruction| { + matches!(instruction, SIRInstruction::Store(address, ..) + if address.region == STABLE_REGION && address.absolute_addr() == flags) + }) + }) + { + return vec![*body]; + } + terminator_successors(terminator) + }; + let blocks = reverse_postorder_with(eu, &successors); if blocks.is_empty() { return HashSet::default(); } @@ -927,7 +1133,7 @@ fn must_execute_blocks(eu: &ExecutionUnit) -> HashSet) -> Vec { +fn reverse_postorder_with( + eu: &ExecutionUnit, + successors_of: &dyn Fn(&SIRTerminator) -> Vec, +) -> Vec { if !eu.blocks.contains_key(&eu.entry_block_id) { return Vec::new(); } @@ -1029,7 +1238,7 @@ fn reverse_postorder(eu: &ExecutionUnit) -> Vec { return Vec::new(); }; stack.push((block_id, true)); - let mut successors = terminator_successors(&block.terminator); + let mut successors = successors_of(&block.terminator); successors.reverse(); stack.extend(successors.into_iter().map(|successor| (successor, false))); } @@ -1429,6 +1638,7 @@ mod tests { &HashSet::default(), existing_aliases, four_state, + None, ) } @@ -2349,7 +2559,7 @@ mod tests { .collect(); let metadata = metadata(&[(source, 8), (destination, 8)]); - remove_proven_alias_stores(&mut units, &aliases, &metadata, false); + remove_proven_alias_stores(&mut units, &aliases, &metadata, false, None); assert_eq!( units[0].blocks[&BlockId(0)].instructions, @@ -2374,7 +2584,7 @@ mod tests { &[(0, 8)], )]; let metadata = metadata(&[(source, 8), (destination, 8)]); - let facts = collect_global_facts(&units, &metadata, false); + let facts = collect_global_facts(&units, &metadata, false, None); assert!( proven_alias_store(&facts, destination.absolute_addr(), source.absolute_addr()) diff --git a/crates/celox-sir-opt/src/policy.rs b/crates/celox-sir-opt/src/policy.rs index 90c1664ed84..caa5fca0305 100644 --- a/crates/celox-sir-opt/src/policy.rs +++ b/crates/celox-sir-opt/src/policy.rs @@ -30,7 +30,8 @@ impl OptLevel { pub fn default_enabled(self, pass: SirPass) -> bool { match self { OptLevel::O0 => matches!(pass, SirPass::TailCallSplit), - OptLevel::O1 | OptLevel::O2 => true, + // Opt-in until it pays off on its own (#2013). + OptLevel::O1 | OptLevel::O2 => !matches!(pass, SirPass::PartitionedSettle), } } @@ -122,6 +123,10 @@ define_sir_passes! { /// clock's domain once more, so disabling it trades tick speed for build /// time. DerivedEdgeUnits => "derived_edge_units", + /// Split the combinational settle of designs with many event domains + /// into partitions that run only when state they read changed. Not a + /// SIR transform: the frontend consumes it. Off unless enabled. + PartitionedSettle => "partitioned_settle", } /// Diagnostics and additional verification for the SIR optimizer. /// @@ -167,9 +172,21 @@ pub struct OptimizeOptions { max_native_memory_width: usize, parallel_lanes: u32, parallel_partition: ParallelPartition, + settle_partition: SettlePartition, pub diagnostics: SirDiagnostics, } +/// How the compiler decides whether to partition the combinational settle +/// ([`SirPass::PartitionedSettle`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SettlePartition { + /// Partition designs with many event domains and a large program. + #[default] + Estimated, + /// Partition every program as finely as possible. For tests. + Always, +} + /// How the compiler decides whether a phase gets a lane-partitioned kernel. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum ParallelPartition { @@ -202,6 +219,7 @@ impl OptimizeOptions { }, parallel_lanes: 1, parallel_partition: ParallelPartition::Estimated, + settle_partition: SettlePartition::Estimated, diagnostics: SirDiagnostics::default(), } } @@ -273,6 +291,15 @@ impl OptimizeOptions { self.parallel_partition } + pub fn with_settle_partition(mut self, partition: SettlePartition) -> Self { + self.settle_partition = partition; + self + } + + pub fn settle_partition(&self) -> SettlePartition { + self.settle_partition + } + /// Query whether a specific pass is active. pub fn is_enabled(&self, pass: SirPass) -> bool { if self.enabled.contains(&pass) { @@ -285,10 +312,13 @@ impl OptimizeOptions { } /// Returns true if any SIR transform is enabled: any pass other than - /// the TailCallSplit and DerivedEdgeUnits selectors. + /// the TailCallSplit, DerivedEdgeUnits and PartitionedSettle selectors. pub fn any_enabled(&self) -> bool { SirPass::ALL.iter().any(|&p| { - !matches!(p, SirPass::TailCallSplit | SirPass::DerivedEdgeUnits) && self.is_enabled(p) + !matches!( + p, + SirPass::TailCallSplit | SirPass::DerivedEdgeUnits | SirPass::PartitionedSettle + ) && self.is_enabled(p) }) } diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs index c0aa948bae2..4f2f1390dd8 100644 --- a/crates/celox-slt/src/scheduler.rs +++ b/crates/celox-slt/src/scheduler.rs @@ -2420,6 +2420,37 @@ pub struct ScheduleResult { /// comb/FF schedule. These Stores are semantic state updates rather than /// disposable comb publications. pub direct_ff_writes: Vec>, + /// The partitions of a partitioned settle, in schedule order; empty when + /// the schedule runs as one pass. + pub partitions: Vec>, +} + +/// Request to split a combinational schedule into partitions that run only +/// when state they read changed since they last ran. +/// +/// Byte `p` of `flags`, a two-state object, is partition `p`'s dirty flag: +/// the settle runs the partition only when it is not zero, and clears it. +/// A partition that runs sets the flags of the partitions reading what it +/// writes; every other writer of state a partition reads must set its flag +/// too ([`SettlePartition::reads`]). +#[derive(Clone, Copy, Debug)] +pub struct SettlePartitioning { + pub flags: Addr, + /// Approximate expression nodes per partition. + pub target_cost: usize, +} + +/// One partition of a partitioned settle. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SettlePartition { + /// The state objects the partition reads. A change to any of them must + /// set the partition's flag before the next settle. + pub reads: Vec, + /// The state objects the partition writes. + pub writes: Vec, + /// Whether the partition runs on every settle, because it has effects + /// beyond its stores. + pub pinned: bool, } pub trait ClockFfLowering { @@ -3464,6 +3495,333 @@ const UNROLL_THRESHOLD: usize = 32; /// compatibility matrix for a long run of independent roots. const MAX_JOINT_FOLD_ROOTS: usize = 16; +/// One partition of a settle plan. +struct PlannedPartition { + reads: Vec, + writes: Vec, + /// The partitions whose flags it sets when it runs: those reading what + /// it writes, itself included when it reads the previous value of its + /// own writes. + marks: Vec, + pinned: bool, +} + +/// The partitions of a settle, each a contiguous run of scheduled work. +struct PartitionPlan { + /// The first scheduled work of each partition. + first_work: Vec, + partitions: Vec>, +} + +/// The paths of one piece of scheduled combinational work. +fn work_paths(work: &ScheduledWork) -> &[usize] { + match work { + ScheduledWork::CombPath(path) => std::slice::from_ref(path), + ScheduledWork::CombScc(paths) | ScheduledWork::GuardedComb { paths, .. } => paths, + ScheduledWork::Ff(_) => &[], + } +} + +/// The approximate lowering cost of a path: its distinct expression nodes, +/// or a process unit's instructions. +pub fn path_cost( + arena: &SLTNodeArena, + path: &LogicPath, +) -> usize { + if let LogicPathTarget::Process { unit, .. } = &path.target { + return unit + .blocks + .values() + .map(|block| block.instructions.len() + 1) + .sum(); + } + let mut seen = HashSet::default(); + let mut stack = vec![path.expr]; + let mut cost = 0; + while let Some(node) = stack.pop() { + if !seen.insert(node) { + continue; + } + cost += 1; + match arena.get(node) { + SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]), + SLTNode::Unary(_, operand) + | SLTNode::Slice { expr: operand, .. } + | SLTNode::Capture { expr: operand, .. } => stack.push(*operand), + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => stack.extend([*cond, *then_expr, *else_expr]), + SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)), + // A loop's cost scales with its trip count; count it as large. + SLTNode::ForFold { .. } | SLTNode::ForFoldGroup { .. } => cost += 64, + SLTNode::Input { .. } | SLTNode::Constant(..) => {} + } + } + cost +} + +/// Whether a path's expression captures a value at an evaluation position. +fn path_has_capture( + arena: &SLTNodeArena, + path: &LogicPath, +) -> bool { + if matches!(path.target, LogicPathTarget::CombCaptureEvent { .. }) { + return true; + } + let mut seen = HashSet::default(); + let mut stack = vec![path.expr]; + while let Some(node) = stack.pop() { + if !seen.insert(node) { + continue; + } + match arena.get(node) { + SLTNode::Capture { .. } => return true, + SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]), + SLTNode::Unary(_, operand) | SLTNode::Slice { expr: operand, .. } => { + stack.push(*operand) + } + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => stack.extend([*cond, *then_expr, *else_expr]), + SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)), + _ => {} + } + } + false +} + +/// Whether a path does more than store its value: comb capture events, +/// activation of capture sites, and process units with runtime events or +/// extern calls. A partition holding one runs on every settle. +fn path_has_effects(path: &LogicPath) -> bool { + if !path.comb_capture_enable_sites.is_empty() || path.comb_capture_enable_always { + return true; + } + match &path.target { + LogicPathTarget::CombCaptureEvent { .. } => true, + LogicPathTarget::Process { unit, .. } => unit.blocks.values().any(|block| { + block + .instructions + .iter() + .any(|instruction| match instruction { + SIRInstruction::RuntimeEvent { .. } + | SIRInstruction::CombCaptureEvent { .. } + | SIRInstruction::CombCaptureEnableIfChanged { .. } + | SIRInstruction::ExternCall { .. } => true, + SIRInstruction::Store(.., capture_sites) => !capture_sites.is_empty(), + _ => false, + }) + }), + LogicPathTarget::Var(_) => false, + } +} + +/// Cut a combinational schedule into partitions of about +/// `partitioning.target_cost`, or `None` when it would be one. +fn plan_settle_partitions( + prepared: &PreparedSchedule, + arena: &SLTNodeArena, + var_widths: &HashMap, + partitioning: SettlePartitioning, +) -> Option<(PartitionPlan, Addr)> { + let input = &prepared.input; + // A captured value or a pre-lowered node is materialized at one place + // and reused at a later one through the lowering cache, which a + // partition boundary between them would clear. + if input + .iter() + .any(|path| !path.pre_lower_nodes.is_empty() || path_has_capture(arena, path)) + { + return None; + } + // Whole-variable copies, by target. + let mut copy_source: HashMap = HashMap::default(); + for work in &prepared.scheduled_work { + if let ScheduledWork::CombPath(path) = work + && let Some((target, source)) = whole_variable_copy(arena, &input[*path], var_widths) + { + copy_source.insert(target, source); + } + } + let mut first_work = Vec::new(); + let mut cost = 0; + for (index, work) in prepared.scheduled_work.iter().enumerate() { + if first_work.is_empty() || cost >= partitioning.target_cost { + first_work.push(index); + cost = 0; + } + cost += work_paths(work) + .iter() + .map(|&path| path_cost(arena, &input[path])) + .sum::(); + } + if first_work.len() < 2 { + return None; + } + let mut partition_of_work = vec![0; prepared.scheduled_work.len()]; + for (partition, &first) in first_work.iter().enumerate() { + let end = first_work + .get(partition + 1) + .copied() + .unwrap_or(prepared.scheduled_work.len()); + partition_of_work[first..end].fill(partition); + } + let count = first_work.len(); + let mut reads = vec![BTreeSet::new(); count]; + let mut writes = vec![BTreeSet::new(); count]; + let mut previous = vec![BTreeSet::new(); count]; + let mut pinned = vec![false; count]; + for (index, work) in prepared.scheduled_work.iter().enumerate() { + let partition = partition_of_work[index]; + for &path_index in work_paths(work) { + let path = &input[path_index]; + pinned[partition] |= path_has_effects(path); + let atoms = path + .sources + .iter() + .chain(&path.address_sources) + .chain(&path.previous_sources); + reads[partition].extend(atoms.map(|atom| atom.id)); + // A process's activation guard reads its occurrence counters and + // startup slots as well. + if let LogicPathTarget::Process { + sensitivity_counters, + startup, + unit, + .. + } = &path.target + { + // The unit may read more than its listed sources, such as + // force controls. It runs at its process's first projection + // and writes every output there. + for block in unit.blocks.values() { + for instruction in &block.instructions { + match instruction { + SIRInstruction::Load(_, address, ..) => { + reads[partition].insert(*address); + } + SIRInstruction::Store(address, ..) => { + writes[partition].insert(*address); + } + SIRInstruction::Commit(source, target, ..) => { + reads[partition].insert(*source); + writes[partition].insert(*target); + } + _ => {} + } + } + } + for (atom, counter) in sensitivity_counters { + reads[partition].extend([atom.id, *counter]); + } + if let Some(startup) = startup { + reads[partition].insert(startup.initialized); + for (atom, slot) in &startup.inputs { + reads[partition].extend([atom.id, *slot]); + } + for (counter, slot) in &startup.counters { + reads[partition].extend([*counter, *slot]); + } + } + } + previous[partition].extend(path.previous_sources.iter().map(|atom| atom.id)); + if let Some(target) = path.target.var() { + writes[partition].insert(target.id); + } + } + } + // Reading a copy's target reads its source: the copy may become an + // alias of its source, whose changes then reach the target without the + // copy running. + for read in &mut reads { + let mut sources = Vec::new(); + for &addr in read.iter() { + let mut current = addr; + let mut steps = 0; + while let Some(&source) = copy_source.get(¤t) { + sources.push(source); + current = source; + steps += 1; + if steps > copy_source.len() { + break; + } + } + } + read.extend(sources); + } + let mut readers: HashMap> = HashMap::default(); + for (partition, read) in reads.iter().enumerate() { + for &addr in read { + readers.entry(addr).or_default().push(partition); + } + } + let partitions = (0..count) + .map(|partition| { + let mut marks = BTreeSet::new(); + for addr in &writes[partition] { + for &reader in readers.get(addr).into_iter().flatten() { + if reader != partition || previous[partition].contains(addr) { + marks.insert(reader); + } + } + } + PlannedPartition { + reads: reads[partition].iter().copied().collect(), + writes: writes[partition].iter().copied().collect(), + marks: marks.into_iter().collect(), + pinned: pinned[partition], + } + }) + .collect(); + Some(( + PartitionPlan { + first_work, + partitions, + }, + partitioning.flags, + )) +} + +/// The `(target, source)` of a path that copies one whole variable into +/// another of the same width. +fn whole_variable_copy( + arena: &SLTNodeArena, + path: &LogicPath, + var_widths: &HashMap, +) -> Option<(Addr, Addr)> { + if !path.transparent_copy || !path.previous_sources.is_empty() { + return None; + } + let target = match &path.target { + LogicPathTarget::Var(target) => target, + _ => return None, + }; + let width = *var_widths.get(&target.id)?; + if target.access.lsb != 0 || target.access.msb + 1 != width { + return None; + } + match arena.get(path.expr) { + SLTNode::Input { + variable, + index, + access, + .. + } if index.is_empty() + && access.lsb == 0 + && access.msb + 1 == width + && var_widths.get(variable) == Some(&width) + && *variable != target.id => + { + Some((target.id, *variable)) + } + _ => None, + } +} + /// Lowering state for one sequence of scheduled work emitted through one SIR /// builder. Register numbers and the expression cache are local to it. struct WorkLowering<'a, Addr: Clone + Eq + Hash> { @@ -3478,6 +3836,11 @@ struct WorkLowering<'a, Addr: Clone + Eq + Hash> { /// The processes whose unit an acyclic projection has run (see /// [`Self::lower`]). run_processes: HashSet, + /// Inside a partition of a partitioned settle, which units must not + /// split. + in_partition: bool, + /// Where a guarded partition continues when it is skipped. + partition_merge: Option, } impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a, Addr> { @@ -3492,9 +3855,102 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a pending_fold_indices: Vec::new(), pending_fold_roots: HashSet::default(), run_processes: HashSet::default(), + in_partition: false, + partition_merge: None, } } + /// Open partition `index`: run it only when its flag or the untracked + /// byte (`untracked`) is set, and clear its flag. Values computed before + /// it may be reused inside, but not the other way round, so the + /// expression cache starts over. + fn begin_partition( + &mut self, + flags: Addr, + index: usize, + untracked: usize, + partition: &PlannedPartition, + ) { + self.flush_pending_folds(); + if self.context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT { + if let Some(eu) = self.builder.flush_eu() { + self.execution_units.push(eu); + } + } + self.lower_cache.clear(); + self.in_partition = true; + let offset = SIROffset::Static(index * 8); + if !partition.pinned { + let own = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Load(own, flags, offset.clone(), 8)); + let all = self.builder.alloc_bit(8, false); + self.builder.emit(SIRInstruction::Load( + all, + flags, + SIROffset::Static(untracked * 8), + 8, + )); + let flag = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Binary(flag, own, BinaryOp::Or, all)); + let zero = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); + let dirty = self.builder.alloc_bit(1, false); + self.builder + .emit(SIRInstruction::Binary(dirty, flag, BinaryOp::Ne, zero)); + let body = self.builder.new_block(); + let merge = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: dirty, + true_block: (body, Vec::new()), + false_block: (merge, Vec::new()), + }); + self.builder.switch_to_block(body); + self.partition_merge = Some(merge); + } + let clean = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(clean, SIRValue::new(0u64))); + self.builder.emit(SIRInstruction::Store( + flags, + offset, + 8, + clean, + Vec::new(), + Vec::new(), + )); + } + + /// Close a partition: set the flags of the partitions reading what it + /// wrote, then join the path that skipped it. + fn end_partition(&mut self, flags: Addr, partition: &PlannedPartition) { + self.flush_pending_folds(); + if !partition.marks.is_empty() { + let one = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + for &reader in &partition.marks { + self.builder.emit(SIRInstruction::Store( + flags, + SIROffset::Static(reader * 8), + 8, + one, + Vec::new(), + Vec::new(), + )); + } + } + if let Some(merge) = self.partition_merge.take() { + self.builder + .seal_block(SIRTerminator::Jump(merge, Vec::new())); + self.builder.switch_to_block(merge); + } + self.lower_cache.clear(); + self.in_partition = false; + } + /// Lower the buffered run of exact grouped-fold paths. fn flush_pending_folds(&mut self) { let context = self.context; @@ -3854,7 +4310,10 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a } } else { // DAG Part — flush before emitting if the EU has grown too large - if context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT { + if context.split_large_units + && !self.in_partition + && self.builder.block_count() >= EU_BLOCK_LIMIT + { self.flush_pending_folds(); if let Some(eu) = self.builder.flush_eu() { self.execution_units.push(eu); @@ -3932,6 +4391,7 @@ fn sort_impl( unpacked_element_widths: &HashMap, first_runtime_error_code: i64, mut ff: Option<&mut dyn ClockFfLowering>, + partitioning: Option>, ) -> Result, ClockSortError> { let prepared = prepare_schedule( input, @@ -3972,7 +4432,25 @@ fn sort_impl( } let mut runtime_errors: HashMap> = HashMap::default(); let mut next_runtime_error_code = first_runtime_error_code; - for work in &prepared.scheduled_work { + let plan = partitioning + .filter(|_| ff.is_none()) + .and_then(|partitioning| { + plan_settle_partitions(&prepared, arena, var_widths, partitioning) + }); + for (index, work) in prepared.scheduled_work.iter().enumerate() { + if let Some((plan, flags)) = &plan { + if let Some(partition) = plan.first_work.iter().position(|&first| first == index) { + if partition > 0 { + lowering.end_partition(*flags, &plan.partitions[partition - 1]); + } + lowering.begin_partition( + *flags, + partition, + plan.partitions.len(), + &plan.partitions[partition], + ); + } + } lowering.lower( work, ff.as_deref_mut(), @@ -3980,6 +4458,11 @@ fn sort_impl( &mut next_runtime_error_code, )?; } + if let Some((plan, flags)) = &plan + && let Some(last) = plan.partitions.last() + { + lowering.end_partition(*flags, last); + } // Flush the final exact grouped-fold run after the SCC loop. lowering.flush_pending_folds(); if let Some(ff_lowering) = ff { @@ -3991,6 +4474,18 @@ fn sort_impl( execution_units: lowering.finish(), runtime_errors, direct_ff_writes, + partitions: plan + .map(|(plan, _)| { + plan.partitions + .into_iter() + .map(|partition| SettlePartition { + reads: partition.reads, + writes: partition.writes, + pinned: partition.pinned, + }) + .collect() + }) + .unwrap_or_default(), }) } @@ -4013,6 +4508,7 @@ pub fn sort( var_widths, &HashMap::default(), first_runtime_error_code, + None, ) } @@ -4025,6 +4521,7 @@ pub fn sort_with_unpacked_element_widths, unpacked_element_widths: &HashMap, first_runtime_error_code: i64, + partitioning: Option>, ) -> Result, SchedulerError> { match sort_impl::( input, @@ -4036,6 +4533,7 @@ pub fn sort_with_unpacked_element_widths Ok(result), Err(ClockSortError::Scheduler(error)) => Err(error), @@ -4066,6 +4564,7 @@ pub fn sort_clock( unpacked_element_widths, first_runtime_error_code, Some(ff), + None, ) } @@ -4085,7 +4584,7 @@ mod tests { LogicPath, LogicPathTarget, SLTForFoldGroupState, SLTNode, SLTNodeArena, SLTToSIRLowerer, }; use celox_design::{BinaryOp, BitAccess, VarAtomBase}; - use celox_sir::{SIRBuilder, SIRInstruction, SIRTerminator}; + use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator}; #[test] fn deep_input_dependencies_use_heap_and_preserve_inverse_index() { @@ -4629,6 +5128,105 @@ mod tests { assert_eq!(adj, vec![vec![1], vec![2], Vec::new()]); } + fn partitioned_sort( + paths: Vec>, + arena: &SLTNodeArena, + ) -> super::ScheduleResult { + let widths = (10..14).map(|id| (id, 8)).collect(); + super::sort_with_unpacked_element_widths( + paths, + arena, + &crate::HashSet::default(), + &crate::HashMap::default(), + false, + &widths, + &crate::HashMap::default(), + 1, + Some(super::SettlePartitioning { + flags: 99, + target_cost: 1, + }), + ) + .unwrap() + } + + #[test] + fn settle_partitions_follow_schedule_and_guard_on_their_flags() { + let mut arena = SLTNodeArena::new(); + let paths = vec![ + simple_path(&mut arena, 13, Some(12)), + simple_path(&mut arena, 12, Some(11)), + simple_path(&mut arena, 11, Some(10)), + ]; + let result = partitioned_sort(paths, &arena); + let plan = result + .partitions + .iter() + .map(|partition| (partition.reads.clone(), partition.writes.clone())) + .collect::>(); + assert_eq!( + plan, + vec![ + (vec![10], vec![11]), + (vec![11], vec![12]), + (vec![12], vec![13]), + ] + ); + assert!(result.partitions.iter().all(|partition| !partition.pinned)); + // Each partition loads its own flag and the untracked-writes flag + // after them; a partition sets its reader's. + let mut loaded = Vec::new(); + let mut stored = Vec::new(); + for unit in &result.execution_units { + for block in unit.blocks.values() { + for instruction in &block.instructions { + match instruction { + SIRInstruction::Load(_, 99, SIROffset::Static(byte), 8) => { + loaded.push(*byte) + } + SIRInstruction::Store(99, SIROffset::Static(byte), 8, ..) => { + stored.push(*byte) + } + _ => {} + } + } + } + } + loaded.sort_unstable(); + stored.sort_unstable(); + assert_eq!(loaded, vec![0, 8, 16, 24, 24, 24]); + // The clears of all three flags, and the marks of partitions 1 and 2. + assert_eq!(stored, vec![0, 8, 8, 16, 16]); + } + + #[test] + fn settle_copy_readers_read_the_copied_source() { + let mut arena = SLTNodeArena::new(); + let mut copy = simple_path(&mut arena, 12, Some(11)); + copy.transparent_copy = true; + let paths = vec![ + simple_path(&mut arena, 13, Some(12)), + copy, + simple_path(&mut arena, 11, Some(10)), + ]; + let result = partitioned_sort(paths, &arena); + let plan = result + .partitions + .iter() + .map(|partition| (partition.reads.clone(), partition.writes.clone())) + .collect::>(); + // The copy is guarded like other work, and its reader reads the + // copied source too. + assert_eq!( + plan, + vec![ + (vec![10], vec![11]), + (vec![11], vec![12]), + (vec![11, 12], vec![13]), + ] + ); + } + #[test] fn memory_ssa_scheduler_lowers_independent_single_use_chains_contiguously() { let mut arena = SLTNodeArena::new(); diff --git a/crates/celox-state-layout/src/lib.rs b/crates/celox-state-layout/src/lib.rs index ff2fbef6463..f296da09d27 100644 --- a/crates/celox-state-layout/src/lib.rs +++ b/crates/celox-state-layout/src/lib.rs @@ -11,7 +11,9 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use serde::{Deserialize, Serialize}; use std::hash::Hash; +mod settle; mod trace; +pub use settle::{SettleLayout, SettleObject}; pub use trace::{TRACE_GROUP_BYTES, TraceLayout}; pub const RUNTIME_EVENT_CAPACITY: usize = 1024; @@ -191,6 +193,9 @@ pub trait LayoutSource { pub struct MemoryLayout { /// Present only in builds that record waveforms. pub trace: Option, + /// Present when the combinational settle is partitioned. + #[serde(default)] + pub settle: Option, pub four_state: bool, pub mode: MemoryLayoutMode, /// Stable region offsets. Includes all declared state objects. @@ -338,6 +343,15 @@ fn place_region( align_up(current + LANE_SEGMENT_GUARD, LANE_SEGMENT_ALIGN) } +impl MemoryLayout { + /// Whether each settle runs a second time to cross-check its partitions + /// ([`SettleLayout::check`]). + #[inline] + pub fn settle_check(&self) -> bool { + self.settle.as_ref().is_some_and(|settle| settle.check) + } +} + impl MemoryLayout where A: Copy + Eq + Hash + Ord, @@ -553,6 +567,7 @@ where Self { trace: None, + settle: None, four_state, mode, offsets, diff --git a/crates/celox-state-layout/src/settle.rs b/crates/celox-state-layout/src/settle.rs new file mode 100644 index 00000000000..652d5009930 --- /dev/null +++ b/crates/celox-state-layout/src/settle.rs @@ -0,0 +1,74 @@ +//! Dirty flags of a partitioned combinational settle. +//! +//! Generated code sets the flags of the partitions reading the state it +//! writes; host writes go through [`SettleLayout::mark_range`]. Writes no +//! one reports, through a retained raw view of the state, set the untracked +//! byte, after which every partition runs on every settle. +use serde::{Deserialize, Serialize}; + +/// State written outside generated code and the partitions reading it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SettleObject { + /// Byte range of the object, both planes. + pub start: usize, + pub end: usize, + pub partitions: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SettleLayout { + /// One byte per partition, then the untracked byte. + pub flags_offset: usize, + pub partitions: usize, + /// Sorted by `start`, disjoint. + pub objects: Vec, + /// Debug cross-check: the backends run each settle again with every + /// partition flagged and panic where the results differ. + #[serde(default)] + pub check: bool, +} + +impl SettleLayout { + pub fn new(flags_offset: usize, partitions: usize, mut objects: Vec) -> Self { + objects.sort_unstable_by_key(|object| object.start); + Self { + flags_offset, + partitions, + objects, + check: false, + } + } + + /// Set the flags of the partitions reading state in `offset..offset + len`. + /// + /// # Safety + /// `memory` must point to the writable state image this layout describes. + pub unsafe fn mark_range(&self, memory: *mut u8, offset: usize, len: usize) { + let end = offset + len.max(1); + let first = self.objects.partition_point(|object| object.end <= offset); + for object in self.objects[first..] + .iter() + .take_while(|object| object.start < end) + { + for &partition in &object.partitions { + // SAFETY: flags lie inside the image (caller contract). + unsafe { *memory.add(self.flags_offset + partition as usize) = 1 }; + } + } + } + + /// The bytes of the flags, the untracked byte included. + pub fn flags(&self) -> std::ops::Range { + self.flags_offset..self.flags_offset + self.partitions + 1 + } + + /// Run every partition on every settle from now on: a raw view of the + /// state can change it without reporting. + /// + /// # Safety + /// `memory` must point to the writable state image this layout describes. + pub unsafe fn mark_untracked(&self, memory: *mut u8) { + // SAFETY: the untracked byte follows the flags (caller contract). + unsafe { *memory.add(self.flags_offset + self.partitions) = 1 }; + } +} diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 6a7c6a613bd..2a17b1cf19a 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1983,10 +1983,12 @@ impl SimBackend for InterpBackend { } fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { - ( + let view = ( self.memory.expose_mut_ptr() as *mut u8, self.layout.merged_total_size, - ) + ); + self.mark_settle_untracked(); + view } fn memory_owner(&self) -> Option> { @@ -1995,6 +1997,10 @@ impl SimBackend for InterpBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/memory_image.rs b/crates/celox/src/backend/memory_image.rs index d24445e881b..aa1abc8e54a 100644 --- a/crates/celox/src/backend/memory_image.rs +++ b/crates/celox/src/backend/memory_image.rs @@ -134,6 +134,12 @@ impl MemoryImage { unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.logical_words) } } + pub(crate) fn as_mut_bytes(&mut self) -> &mut [u8] { + let words = self.as_mut_slice(); + // SAFETY: the words are initialized, and bytes have no alignment. + unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast(), words.len() * 8) } + } + pub(crate) fn len_words(&self) -> usize { self.logical_words } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 020fc779b31..f1bca202fb7 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -536,6 +536,7 @@ impl NativeProgramImage { time_slots: self.runtime_schema.time_slots.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), + settle_partitions: None, }, testbench: self.testbench.clone(), } @@ -2589,6 +2590,9 @@ pub struct NativeBackend { /// Boxed so the address in the state header survives moves. heap: Box, execution_timing: Option, + /// Whether generated calls go through [`Self::call_func_slow`]: timing + /// is on, or settles are cross-checked. + slow_calls: bool, /// Worker threads for lane-partitioned kernels, started on first use. lane_pool: Option, /// Per-kernel choice between partitioned and sequential code. @@ -2807,6 +2811,7 @@ impl NativeBackend { } } + let slow_calls = shared.layout.settle_check(); let mut backend = Self { compiled: shared, memory, @@ -2814,6 +2819,7 @@ impl NativeBackend { comb_capture_enabled, heap: Default::default(), execution_timing: None, + slow_calls, lane_pool: None, lane_selectors: Default::default(), }; @@ -2836,6 +2842,7 @@ impl NativeBackend { comb_capture_enabled: Vec, heap: Box, ) -> Self { + let slow_calls = shared.layout.settle_check(); let mut backend = Self { compiled: shared, memory, @@ -2843,6 +2850,7 @@ impl NativeBackend { comb_capture_enabled, heap, execution_timing: None, + slow_calls, lane_pool: None, lane_selectors: Default::default(), }; @@ -2948,6 +2956,7 @@ impl NativeBackend { /// Start a fresh opt-in measurement of generated native function calls. pub fn start_execution_timing(&mut self) { self.execution_timing = Some(NativeExecutionTiming::default()); + self.slow_calls = true; } /// Total capacity of the live image in `u64` words. @@ -2967,10 +2976,12 @@ impl NativeBackend { self.memory.resize_zeroed_within_capacity(mem_size_words); } self.compiled = shared; + self.slow_calls = self.execution_timing.is_some() || self.compiled.layout.settle_check(); } /// Stop timing and return the accumulated generated-code interval. pub fn finish_execution_timing(&mut self) -> Option { + self.slow_calls = self.compiled.layout.settle_check(); self.execution_timing.take() } @@ -3145,6 +3156,29 @@ impl NativeBackend { } fn call_func_timed(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { + if !self.slow_calls { + return Self::call_func(self.memory.as_mut_slice(), func); + } + self.call_func_slow(func) + } + + #[cold] + fn call_func_slow(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { + if func as usize == self.compiled.comb_func as usize && self.compiled.layout.settle_check() + { + let compiled = Arc::clone(&self.compiled); + return crate::settle::run_checked( + self, + compiled.layout.settle.as_ref().expect("checked settle"), + compiled.layout.total_size, + |backend| backend.memory.as_mut_bytes(), + |backend| backend.call_func_measured(func), + ); + } + self.call_func_measured(func) + } + + fn call_func_measured(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { let Some(_) = self.execution_timing else { return Self::call_func(self.memory.as_mut_slice(), func); }; @@ -3514,10 +3548,12 @@ impl super::super::SimBackend for NativeBackend { } fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { - ( + let view = ( self.memory.expose_mut_ptr().cast(), self.memory.len_words() * 8, - ) + ); + self.mark_settle_untracked(); + view } fn memory_owner(&self) -> Option> { @@ -3526,6 +3562,10 @@ impl super::super::SimBackend for NativeBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 984c26ba14a..ae25f64d4a2 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 38; +const CONTAINER_VERSION: u16 = 39; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/runtime.rs b/crates/celox/src/backend/runtime.rs index 49e879915c7..ebc6e902a1c 100644 --- a/crates/celox/src/backend/runtime.rs +++ b/crates/celox/src/backend/runtime.rs @@ -912,7 +912,18 @@ impl JitBackend { |backend| backend.run_sim_func(comb_func), ); } - self.run_sim_func(self.comb_func) + let comb_func = self.comb_func; + if self.shared.layout.settle_check() { + let shared = Arc::clone(&self.shared); + return crate::settle::run_checked( + self, + shared.layout.settle.as_ref().expect("checked settle"), + shared.layout.total_size, + |backend| backend.memory.as_mut_bytes(), + |backend| backend.run_sim_func(comb_func), + ); + } + self.run_sim_func(comb_func) } /// Resolves an `AbsoluteAddr` into a performance-optimized [`SignalRef`]. @@ -1230,7 +1241,9 @@ impl JitBackend { /// Returns a mutable raw pointer to the JIT memory and its total size in bytes. pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { let size = self.shared.layout.merged_total_size; - (self.memory.expose_mut_ptr() as *mut u8, size) + let view = (self.memory.expose_mut_ptr() as *mut u8, size); + celox_runtime::backend::SimBackend::mark_settle_untracked(self); + view } pub fn runtime_event_buffer_as_ptr(&self) -> (*const u8, usize) { @@ -1415,6 +1428,10 @@ impl super::SimBackend for JitBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 45cbdac4913..506bbabcaa3 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -111,6 +111,10 @@ impl super::traits::SimBackend for WasmBackend { } fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.data_mut(&mut self.store)[offset..offset + bytes.len()].copy_from_slice(bytes); + self.mark_settle_range(offset, bytes.len()); + if self.raw_view_exposed { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { !self.raw_view_exposed @@ -683,6 +687,7 @@ impl WasmBackend { pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { self.raw_view_exposed = true; + celox_runtime::backend::SimBackend::mark_settle_untracked(self); let data = self.memory.data_mut(&mut self.store); (data.as_mut_ptr(), self.layout.merged_total_size) } diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 5b45f5b093e..3ebc630ef97 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -1077,8 +1077,24 @@ mod tests { generated_dirty = stale(generated_dirty, outcome); assert_eq!(generated_dirty, walked_dirty, "step {step}"); let (left, right) = (state(&generated.backend), state(&walked.backend)); - if let Some(offset) = left.iter().zip(&right).position(|(a, b)| a != b) { - let offset = offset + celox_state_layout::STATE_HEADER_SIZE; + // The settle's partition flags hold only what is left to + // recompute. + let flags = walked + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags()); + if let Some(offset) = left + .iter() + .zip(&right) + .enumerate() + .map(|(offset, pair)| (offset + celox_state_layout::STATE_HEADER_SIZE, pair)) + .find(|(offset, (a, b))| { + a != b && !flags.as_ref().is_some_and(|flags| flags.contains(offset)) + }) + .map(|(offset, _)| offset) + { let name = walked .named_signals() .into_iter() diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 718e9675d66..f226fc20aa6 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -566,6 +566,18 @@ pub struct LaidOutProgram { } impl LaidOutProgram { + /// The units, with the layout and runtime metadata they are checked + /// against, borrowed apart. + pub(crate) fn split_mut( + &mut self, + ) -> ( + &mut SirProgram, + &crate::backend::MemoryLayout, + &RuntimeProgram, + ) { + (&mut self.sir, &self.layout, &self.runtime) + } + #[cfg(feature = "host-runtime")] pub(crate) fn enable_vcd_tracking(&mut self) { self.layout.enable_trace(); @@ -575,6 +587,15 @@ impl LaidOutProgram { &self.layout } + /// Cross-check every partitioned settle (see + /// [`celox_state_layout::SettleLayout::check`]). + #[cfg(feature = "host-runtime")] + pub(crate) fn set_settle_check(&mut self, check: bool) { + if let Some(settle) = self.layout.settle.as_mut() { + settle.check = check; + } + } + pub fn runtime(&self) -> &RuntimeProgram { &self.runtime } @@ -701,7 +722,8 @@ impl OptimizedSir { }); } crate::optimizer::sir::retain_final_identity_aliases(&mut program, four_state); - let layout = crate::backend::MemoryLayout::build(&program, four_state, mode); + let mut layout = crate::backend::MemoryLayout::build(&program, four_state, mode); + layout.settle = crate::settle::layout(&program, &layout); // Classify before alias stores disappear: an identity alias is a // combinational copy even once it only shares its source's storage. collect_comb_writes(&mut program); @@ -747,11 +769,13 @@ impl OptimizedSir { layout_requirements, } = program; debug_assert!(layout_requirements.is_empty()); - LaidOutProgram { + let mut laid_out = LaidOutProgram { sir, runtime, layout, - } + }; + crate::settle::instrument(&mut laid_out); + laid_out } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 474221fabfc..79ebb562df4 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -37,6 +37,7 @@ pub(crate) mod portable; // Builds without the host runtime run every slot in the reference loop. #[cfg(feature = "host-runtime")] mod scheduler; +mod settle; #[cfg(feature = "host-runtime")] mod simulation; mod simulator; @@ -90,6 +91,7 @@ pub use num_bigint::BigUint; pub use optimizer::OptLevel; pub use optimizer::OptimizeOptions; pub use optimizer::ParallelPartition; +pub use optimizer::SettlePartition; pub use optimizer::SirDiagnostics; pub use optimizer::SirPass; pub use simulator::render_diagnostic; diff --git a/crates/celox/src/optimizer.rs b/crates/celox/src/optimizer.rs index ed23d101223..97b35bfc831 100644 --- a/crates/celox/src/optimizer.rs +++ b/crates/celox/src/optimizer.rs @@ -1,4 +1,6 @@ -pub use celox_sir_opt::{OptLevel, OptimizeOptions, ParallelPartition, SirDiagnostics, SirPass}; +pub use celox_sir_opt::{ + OptLevel, OptimizeOptions, ParallelPartition, SettlePartition, SirDiagnostics, SirPass, +}; pub mod sir; @@ -98,5 +100,12 @@ pub(crate) fn parallel_schedule_options( parallel.synchronization_cost = 0; parallel.minimum_speedup_percent = 0; } + parallel.settle = if !options.is_enabled(SirPass::PartitionedSettle) { + celox_frontend_core::SettlePartitionMode::Off + } else if options.settle_partition() == SettlePartition::Always { + celox_frontend_core::SettlePartitionMode::Always + } else { + celox_frontend_core::SettlePartitionMode::Estimated + }; parallel } diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 94da9e00dc9..cad4dd76b4c 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -600,6 +600,12 @@ pub fn parse_sv( ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); + let mut schedule_options = crate::optimizer::parallel_schedule_options(optimize_options); + if !force_signals.is_empty() { + // Native code applies explicit forces to reads the SLT has already + // folded, outside any partition's dependencies. + schedule_options.settle = celox_frontend_core::SettlePartitionMode::Off; + } let scheduled = celox_frontend_sv::schedule_sources_with_parameter_expressions_and_latch_policy( sources, @@ -608,7 +614,7 @@ pub fn parse_sv( ignored_loops, true_loops, four_state, - &crate::optimizer::parallel_schedule_options(optimize_options), + &schedule_options, &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), config.allow_inferred_latches, diff --git a/crates/celox/src/settle.rs b/crates/celox/src/settle.rs new file mode 100644 index 00000000000..24a5bf6bde5 --- /dev/null +++ b/crates/celox/src/settle.rs @@ -0,0 +1,238 @@ +//! Partitioned combinational settle (`RuntimeSchema::settle_partitions`): +//! the flag layout, and the flag stores of the units outside the settle. +//! +//! A partition of the settle runs only when its flag is set. The settle's +//! own partitions set the flags of their readers; every other writer of +//! state the settle reads or writes sets them here, at each store or commit +//! to the state, and host writes set them through +//! [`celox_state_layout::SettleLayout`]. +use crate::ir::{ + ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, RegisterType, SIRInstruction, + SIROffset, STABLE_REGION, +}; +use celox_sir::SIRValue; +use celox_state_layout::{SettleLayout, SettleObject}; + +/// The flag layout of `program`'s partitioned settle, if it has one. +pub(crate) fn layout( + program: &crate::ir::OptimizedSir, + layout: &crate::backend::MemoryLayout, +) -> Option { + let settle = program.runtime.runtime_schema.settle_partitions.as_ref()?; + let planes = |address| { + if layout.four_state && layout.is_4states.get(address).copied().unwrap_or(false) { + 2 + } else { + 1 + } + }; + let mut objects: Vec = Vec::new(); + for (address, partitions) in &settle.marks { + let Some(&start) = layout.offsets.get(address) else { + continue; + }; + let end = start + layout.plane_size(address) * planes(address); + objects.push(SettleObject { + start, + end, + partitions: partitions.clone(), + }); + } + // Aliases share storage: one entry per home, with every reader. + objects.sort_unstable_by_key(|object| (object.start, object.end)); + let mut merged: Vec = Vec::new(); + for object in objects { + match merged.last_mut() { + Some(last) if last.start == object.start => { + last.end = last.end.max(object.end); + last.partitions.extend(object.partitions); + last.partitions.sort_unstable(); + last.partitions.dedup(); + } + _ => merged.push(object), + } + } + Some(SettleLayout::new( + layout.offsets[&settle.flags], + settle.partitions as usize, + merged, + )) +} + +/// Run a settle through `run` and cross-check it ([`SettleLayout::check`]): +/// run it again from the same state with every partition flagged, and panic +/// at the first byte of design state (below `state_end`) the two runs leave +/// differently. The state continues from the first run. +// The backends that cross-check: native and Cranelift. +#[cfg(any( + feature = "cranelift", + all( + feature = "host-runtime", + any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ) + ) +))] +#[cold] +pub(crate) fn run_checked( + backend: &mut B, + settle: &SettleLayout, + state_end: usize, + memory: impl Fn(&mut B) -> &mut [u8], + mut run: impl FnMut(&mut B) -> Result<(), E>, +) -> Result<(), E> { + let flags = settle.flags(); + let before = memory(backend).to_vec(); + run(backend)?; + let partial = memory(backend).to_vec(); + let state = memory(backend); + state.copy_from_slice(&before); + state[flags.start..flags.end - 1].fill(1); + run(backend)?; + let full = memory(backend); + if let Some(offset) = (celox_state_layout::STATE_HEADER_SIZE..state_end) + .find(|offset| full[*offset] != partial[*offset] && !flags.contains(offset)) + { + let object = settle + .objects + .iter() + .find(|object| (object.start..object.end).contains(&offset)); + let dirty: Vec = (0..settle.partitions) + .filter(|&partition| before[flags.start + partition] != 0) + .collect(); + panic!( + "partitioned settle: state byte {offset} is {} after the partitions that ran, {} \ + after all ({}; flagged at entry: {dirty:?} of {})", + partial[offset], + full[offset], + object.map_or_else( + || "not read or written by the settle".to_string(), + |object| format!( + "object {}..{} of partitions {:?}", + object.start, object.end, object.partitions + ) + ), + settle.partitions + ); + } + full.copy_from_slice(&partial); + Ok(()) +} + +/// Add the flag stores to every unit outside the settle. +pub(crate) fn instrument(program: &mut LaidOutProgram) { + instrument_processes_from(program, 0, true); +} + +/// Add the flag stores to the processes from index `first` on, and to the +/// other units outside the settle when `all`. +pub(crate) fn instrument_processes_from(program: &mut LaidOutProgram, first: usize, all: bool) { + let (sir, layout, runtime) = program.split_mut(); + let Some(marker) = Marker::new(layout, runtime) else { + return; + }; + if all { + for unit in sir + .eval_apply_ffs + .values_mut() + .chain(sir.eval_comb_apply_ffs.values_mut()) + .chain(sir.eval_only_ffs.values_mut()) + .chain(sir.apply_ffs.values_mut()) + .flatten() + { + marker.instrument(unit); + } + } + for unit in sir.processes.iter_mut().skip(first) { + marker.instrument(unit); + } +} + +struct Marker<'a> { + settle: &'a SettleLayout, + layout: &'a crate::backend::MemoryLayout, + flags: RegionedAbsoluteAddr, +} + +impl<'a> Marker<'a> { + fn new( + layout: &'a crate::backend::MemoryLayout, + runtime: &'a crate::ir::RuntimeProgram, + ) -> Option { + let settle = layout.settle.as_ref()?; + let schema = runtime.runtime_schema.settle_partitions.as_ref()?; + Some(Self { + settle, + layout, + flags: RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, schema.flags), + }) + } + + /// The partitions reading the stable state `address` names. + fn readers(&self, address: &RegionedAbsoluteAddr) -> Vec { + if address.region != STABLE_REGION { + return Vec::new(); + } + let Some(&start) = self.layout.offsets.get(&address.absolute_addr()) else { + return Vec::new(); + }; + let index = self + .settle + .objects + .partition_point(|object| object.start < start); + match self.settle.objects.get(index) { + Some(object) if object.start == start => object.partitions.clone(), + _ => Vec::new(), + } + } + + fn instrument(&self, unit: &mut ExecutionUnit) { + let mut next_register = unit + .register_map + .keys() + .map(|register| register.0 + 1) + .max() + .unwrap_or(0); + for block in unit.blocks.values_mut() { + let mut one = None; + let mut instructions = Vec::with_capacity(block.instructions.len()); + for instruction in std::mem::take(&mut block.instructions) { + let readers = match &instruction { + SIRInstruction::Store(address, ..) => self.readers(address), + SIRInstruction::Commit(_, address, ..) => self.readers(address), + _ => Vec::new(), + }; + instructions.push(instruction); + if readers.is_empty() { + continue; + } + let one = *one.get_or_insert_with(|| { + let register = RegisterId(next_register); + next_register += 1; + unit.register_map.insert( + register, + RegisterType::Bit { + width: 8, + signed: false, + }, + ); + instructions.push(SIRInstruction::Imm(register, SIRValue::new(1u64))); + register + }); + for partition in readers { + instructions.push(SIRInstruction::Store( + self.flags, + SIROffset::Static(partition as usize * 8), + 8, + one, + Vec::new(), + Vec::new(), + )); + } + } + block.instructions = instructions; + } + } +} diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ceb3ba86f99..d736149742d 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -163,8 +163,9 @@ fn difference( "scheduling state {key:?}, the reference {reference:?}" )); } - // The compiled scheduler's slots hold nothing between runs. - let scheduler: Vec<_> = primary + // The compiled scheduler's slots hold nothing between runs, and the + // settle's partition flags only what is left to recompute. + let excluded: Vec<_> = primary .program .runtime_schema .scheduler @@ -174,9 +175,16 @@ fn difference( let signal = primary.backend.resolve_signal(address); signal.offset..signal.offset + celox_state_layout::get_byte_size(signal.width) }) + .chain( + primary + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags()), + ) .collect(); - if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend, &scheduler) - { + if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend, &excluded) { let signal = primary .named_signals() .into_iter() diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 6e1d6ae5327..e07b3fd7954 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1288,6 +1288,7 @@ mod host { ); } } + self.backend.mark_settle_range(signal.offset, 1); } /// Drain runtime events, lazily evaluating dirty combinational logic. diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 75e1a4f61a5..caf6d58953f 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1686,6 +1686,9 @@ mod host { /// Emit the additional combinational entries needed to reapply foreign /// force overrides between procedural store boundaries. pub native_force_support: bool, + /// Cross-check every partitioned settle against one that runs every + /// partition (see [`SimulatorBuilder::settle_check`]). + pub settle_check: bool, /// Explicit hierarchical observation and native force targets. pub signal_access: crate::SignalAccessOptions, /// Dead store elimination policy. @@ -1991,6 +1994,7 @@ mod host { emit_triggers: false, #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] derived_edge_units: None, + settle_check: false, native_force_support: false, signal_access: crate::SignalAccessOptions::default(), dead_store_policy: DeadStorePolicy::Off, @@ -2221,9 +2225,11 @@ mod host { pub fn opt_level(mut self, level: crate::optimizer::OptLevel) -> Self { let lanes = self.options.optimize_options.parallel_lanes(); let partition = self.options.optimize_options.parallel_partition(); + let settle = self.options.optimize_options.settle_partition(); self.options.optimize_options = crate::optimizer::OptimizeOptions::new(level) .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self.options.cranelift_options = crate::backend::CraneliftOptions::for_speed_optimization( level != crate::optimizer::OptLevel::O0, @@ -2258,13 +2264,15 @@ mod host { pub fn optimize(mut self, enable: bool) -> Self { let lanes = self.options.optimize_options.parallel_lanes(); let partition = self.options.optimize_options.parallel_partition(); + let settle = self.options.optimize_options.settle_partition(); self.options.optimize_options = if enable { crate::optimizer::OptimizeOptions::all() } else { crate::optimizer::OptimizeOptions::none() } .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self } @@ -2284,9 +2292,15 @@ mod host { } else { self.options.optimize_options.parallel_partition() }; + let settle = if options.settle_partition() == crate::SettlePartition::Always { + crate::SettlePartition::Always + } else { + self.options.optimize_options.settle_partition() + }; self.options.optimize_options = options .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self } @@ -2328,6 +2342,34 @@ mod host { self } + /// Debug cross-check of a partitioned settle: the native and + /// Cranelift backends run each settle a second time from the same + /// state with every partition flagged, and panic at the first state + /// byte the two runs leave differently. Slow; for testing the + /// partitioning. Effects of the partitions that run in both passes, + /// such as runtime events, happen twice. + pub fn settle_check(mut self, enable: bool) -> Self { + self.options.settle_check = enable; + self + } + + /// Cut the combinational settle into partitions that run only when + /// state they read changed ([`crate::SirPass::PartitionedSettle`]). + /// + /// [`crate::SettlePartition::Estimated`] partitions a large settle of + /// a design with several clock events; + /// [`crate::SettlePartition::Always`] partitions every settle it can, + /// for testing. + pub fn settle_partition(mut self, partition: crate::SettlePartition) -> Self { + self.options.optimize_options = self + .options + .optimize_options + .clone() + .enable(crate::optimizer::SirPass::PartitionedSettle) + .with_settle_partition(partition); + self + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -2902,6 +2944,8 @@ mod host { } } + // Units generated from here on write state the settle may read. + let first_generated_process = laid_out.sir.processes.len(); // A timed simulation runs the slots of kernels that only delay // in a compiled scheduler, generated from the final units. #[cfg(feature = "host-runtime")] @@ -2922,6 +2966,8 @@ mod host { if let Some(sink) = &self.options.derived_edge_units { crate::derived_edge::attach_test_units(&mut laid_out, sink); } + crate::settle::instrument_processes_from(&mut laid_out, first_generated_process, false); + laid_out.set_settle_check(self.options.settle_check); // Link DPI-C imports before code generation, so a missing C // function fails the build early; the backends reuse the result. diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 803b46afdaa..66576f565f2 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -376,7 +376,9 @@ impl Simulator { let comb_writes = &self.program.runtime_schema.comb_writes; // A timed simulation stores its time into the time slots, and a state // file keeps the time in its schedule; an untimed one reads zero. - // A compiled scheduler's slots hold nothing between runs. + // A compiled scheduler's slots hold nothing between runs, and the + // flags of a partitioned settle describe how this build settles, + // not the design: loading state sets them. let time_slots: crate::HashSet<_> = self .program .runtime_schema @@ -390,12 +392,19 @@ impl Simulator { .flat_map(|scheduler| scheduler.slots.iter()), ) .collect(); + let settle_flags = self + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags_offset); let mut objects: Vec<_> = self .backend .layout() .offsets .keys() .filter(|address| !time_slots.contains(address)) + .filter(|address| Some(self.backend.layout().offsets[*address]) != settle_flags) .map(|&address| (self.program.get_path(&address), address)) .collect(); objects.sort_unstable(); diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index b01452f8fc2..0d5c205b104 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -116,7 +116,7 @@ pub(crate) fn eval_backend_expr( |offset, len| writes.push((offset, len)), ); if let Some(trace) = backend.layout().trace.as_ref() { - for (offset, len) in writes { + for &(offset, len) in &writes { // SAFETY: bound bytecode writes valid locations in this image, and // the simulator cannot execute concurrently with this evaluation. unsafe { @@ -124,6 +124,9 @@ pub(crate) fn eval_backend_expr( } } } + for (offset, len) in writes { + backend.mark_settle_range(offset, len); + } value } diff --git a/crates/celox/tests/settle_partitions.rs b/crates/celox/tests/settle_partitions.rs new file mode 100644 index 00000000000..3e9fa3dba0f --- /dev/null +++ b/crates/celox/tests/settle_partitions.rs @@ -0,0 +1,297 @@ +//! A partitioned settle runs a partition only when state it reads changed +//! (#2013). Forced on every settle it can cut, it must match the single-pass +//! settle on every backend, whatever wrote the state: a register update, a +//! host write, a loaded state file. +use celox::{BigUint, SettlePartition, Simulator, SirPass}; + +/// Two clock domains feeding a combinational network deep enough to cut into +/// many partitions, with a memory read through a run-time index and a +/// combinational output depending on a host input only. +const DESIGN: &str = r#" +module Top ( + clk_a: input 'a clock, + clk_b: input 'b clock, + rst: input 'a reset, + din: input 'a logic<8>, + sel: input 'a logic<2>, + bypass: input 'a logic<8>, + sum: output 'a logic<8>, + mixed: output 'a logic<8>, + picked: output 'a logic<8>, + direct: output 'a logic<8>, + slow: output 'b logic<8>, +) { + var ra: 'a logic<8>; + var mem: 'a logic<8> [4]; + var rb: 'b logic<8>; + var s1: 'a logic<8>; + var s2: 'a logic<8>; + var s3: 'a logic<8>; + var s4: 'a logic<8>; + always_ff (clk_a, rst) { + if_reset { + ra = 0; + } else { + ra = ra + din; + mem[ra[1:0]] = ra ^ din; + } + } + unsafe (cdc) { + always_ff (clk_b) { + rb = rb + s4; + } + assign s2 = s1 ^ rb; + assign slow = rb; + } + assign s1 = ra + 8'd1; + assign s3 = {s2[3:0], s1[7:4]}; + assign s4 = s3 + bypass; + assign sum = s4 + s1; + assign mixed = s3 ^ s2; + assign picked = mem[sel]; + assign direct = bypass + 8'd3; +} +"#; + +const OUTPUTS: [&str; 5] = ["sum", "mixed", "picked", "direct", "slow"]; + +fn partitioned() -> celox::SimulatorBuilder<'static, Simulator> { + Simulator::builder(DESIGN, "Top") + .settle_partition(SettlePartition::Always) + .settle_check(true) +} + +fn single_pass() -> celox::SimulatorBuilder<'static, Simulator> { + Simulator::builder(DESIGN, "Top").disable_pass(SirPass::PartitionedSettle) +} + +/// Drive both clocks and the inputs with a fixed pseudo-random sequence, +/// reading every output after each host write and each tick. +macro_rules! trace { + ($sim:expr) => {{ + let sim = &mut $sim; + let clk_a = sim.event("clk_a"); + let clk_b = sim.event("clk_b"); + let rst = sim.signal("rst"); + let din = sim.signal("din"); + let sel = sim.signal("sel"); + let bypass = sim.signal("bypass"); + let outputs = OUTPUTS.map(|name| sim.signal(name)); + let mut trace = Vec::new(); + macro_rules! read { + () => { + outputs + .iter() + .map(|&signal| sim.get(signal)) + .collect::>() + }; + } + sim.modify(|io| io.set(rst, 0u8)).unwrap(); + sim.tick(clk_a).unwrap(); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + let mut seed = 0x2013u32; + for _ in 0..64 { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + let bits = seed >> 8; + // A host write alone must reach the combinational outputs. + sim.modify(|io| { + io.set(din, bits as u8); + io.set(sel, (bits >> 8) as u8 & 3); + io.set(bypass, (bits >> 10) as u8); + }) + .unwrap(); + trace.push(read!()); + match bits >> 18 & 3 { + 0 => sim.tick(clk_a).unwrap(), + 1 => sim.tick(clk_b).unwrap(), + 2 => sim.tick_events(&[clk_a, clk_b]).unwrap(), + _ => {} + } + trace.push(read!()); + } + trace + }}; +} + +fn reference() -> Vec> { + trace!(single_pass().build().unwrap()) +} + +#[test] +fn partitioned_interpreter_matches_single_pass() { + assert_eq!( + trace!(partitioned().build_interpreter().unwrap()), + reference() + ); +} + +#[test] +fn partitioned_cranelift_matches_single_pass() { + assert_eq!( + trace!(partitioned().build_cranelift().unwrap()), + reference() + ); +} + +#[test] +fn partitioned_wasm_matches_single_pass() { + assert_eq!(trace!(partitioned().build_wasm().unwrap()), reference()); +} + +#[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) +))] +#[test] +fn partitioned_native_matches_single_pass() { + assert_eq!(trace!(partitioned().build_native().unwrap()), reference()); +} + +/// Loading a state file writes every object, so every partition reading one +/// must run again; the settle's flags themselves are not state. +#[test] +fn loaded_state_reaches_partitions() { + let mut source = partitioned().build().unwrap(); + trace!(source); + let file = source.save_state().unwrap(); + assert!( + file.objects + .iter() + .all(|object| !object.path.contains("$settle")), + "the settle flags are saved as state" + ); + let mut target = partitioned().build().unwrap(); + // Settle once before the load, so no partition is pending. + trace!(target); + target.load_state(&file).unwrap(); + let mut plain = single_pass().build().unwrap(); + plain.load_state(&file).unwrap(); + assert_eq!(trace!(target), trace!(plain)); +} + +#[cfg(feature = "systemverilog")] +mod systemverilog { + use std::path::Path; + + use celox::{BigUint, SettlePartition, Simulation, SirPass}; + + /// A clock gated through a latch (Xilinx BUFGCE): the latch is a process + /// of the settle, and the gated clock's edge runs another domain. + const GATED: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [7:0] fast, + output logic [7:0] gated, + output logic [7:0] view +); + logic clk = 0; + logic en = 0; + logic en_l; + logic [7:0] din = 0; + always #5 clk = ~clk; + always #7 en = ~en; + always #3 din = din + 8'd29; + always_latch begin + if (!clk) en_l = en; + end + wire gclk = clk & en_l; + initial begin fast = 0; gated = 0; end + always_ff @(posedge clk) fast <= fast + din; + always_ff @(posedge gclk) gated <= gated ^ fast; + assign view = gated + fast; +endmodule +"#; + + /// A process writing two outputs runs at its first output's place in + /// the schedule, so the second output changes there too. + const SPLIT: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [3:0] y, + output logic [3:0] b, + output logic [1:0] w, + output int n +); + logic [3:0] a = 4'b0101; + logic c = 0; + always_comb begin y = 4'b0; if (c) y = a; b = a; end + assign w = y[1:0]; + initial begin n = 0; #1 forever begin @(y); n++; end end + initial begin + #2 c = 1; + #1 a = 4'b0110; + #1 a = 4'b0111; + #2 c = 0; + #1 a = 4'b1001; + end +endmodule +"#; + + /// A whole-variable copy of a process output, read by another process. + const COPY: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [7:0] r, + output logic [7:0] q +); + logic [7:0] a = 8'd3; + logic s = 0; + logic [7:0] p; + logic [7:0] pc; + always_comb begin p = 8'd0; q = 8'd0; if (s) begin p = a; q = ~a; end end + assign pc = p; + always_comb r = pc + 8'd1; + always #2 a = a + 8'd5; + always #3 s = ~s; +endmodule +"#; + + fn trace( + source: &str, + outputs: &[&str], + end: u64, + settle: Option, + ) -> Vec> { + let builder = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + let builder = match settle { + Some(settle) => builder.settle_partition(settle).settle_check(true), + None => builder.disable_pass(SirPass::PartitionedSettle), + }; + let mut sim = builder.build().unwrap(); + let outputs: Vec<_> = outputs.iter().map(|name| sim.signal(name)).collect(); + let mut trace = Vec::new(); + for time in 0..end { + sim.run_until(time).unwrap(); + trace.push(outputs.iter().map(|&signal| sim.get(signal)).collect()); + } + trace + } + + fn matches_single_pass(source: &str, outputs: &[&str], end: u64) -> Vec> { + let single = trace(source, outputs, end, None); + assert_eq!( + trace(source, outputs, end, Some(SettlePartition::Always)), + single + ); + single + } + + #[test] + fn latch_gated_clock_matches_single_pass() { + let single = matches_single_pass(GATED, &["fast", "gated", "view"], 200); + // The gated domain must have run. + assert_ne!(single.last().unwrap()[1], BigUint::from(0u8)); + } + + #[test] + fn multi_output_process_matches_single_pass() { + let single = matches_single_pass(SPLIT, &["y", "b", "w", "n"], 10); + // At 5, y and w follow a through the intermediate 0. + assert_eq!(single[5][2], BigUint::from(3u8)); + } + + #[test] + fn copy_of_a_process_output_matches_single_pass() { + matches_single_pass(COPY, &["r", "q"], 40); + } +} diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index a10c48ca3b5..fc8608038ba 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -101,6 +101,15 @@ unnecessary: compile the clock's domain once more; the `derived_edge_units` selector (`-sir:derived_edge_units`, `SirPass::DerivedEdgeUnits`) turns them off to trade tick speed for build time. +- the combinational settle can be cut into partitions, contiguous ranges of + its schedule, that run only when their dirty flag is set + (`partitioned_settle`, off unless enabled). A partition that runs sets the + flags of the partitions reading what it writes; every other writer sets them + too: generated stores and commits of state a partition reads or writes, host + writes, state loads, and a retained raw view of the state, after which every + partition runs. `SimulatorBuilder::settle_check` runs each settle a second + time with every partition flagged and panics where the two differ; effects + of partitions that run twice, such as runtime events, then happen twice. - in the time slots a compiled scheduler runs, a combinational settle waits until its results are read: it runs, where the reference loop last settled, before a process kernel or domain that reads combinational outputs diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index b358062dc33..466b8f0b6ae 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -394,7 +394,9 @@ export interface SimulatorOptions { * split_coalesced_stores, partial_forward, identity_store_bypass, tail_call_split, * derived_edge_units (generated units for the edges of gated and divided * clocks; "-sir:derived_edge_units" walks their plans instead, which - * builds faster and ticks slower) + * builds faster and ticks slower), partitioned_settle (settle only the + * partitions of the combinational logic whose inputs changed; off unless + * enabled with "+sir:partitioned_settle") * * @example ["-sir:reschedule", "+sir:gvn"] */ From 562772933d0af468640413cc99d3cbad1cef3310 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 14:50:13 +0900 Subject: [PATCH 8/9] 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 9/9] 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]