From 304f4ac3d531b073a168a2025ceb55a7f353c5bc Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 10:41:43 +0900 Subject: [PATCH 1/2] feat(sv)!: support $stop and $exit $stop in a process kernel suspends the simulation (IEEE 1800-2023 20.2): the process returns with the new Stop status, the scheduler settles combinational logic, saves the round in progress and returns with is_stopped() set. The next step continues that round after the $stop, so edges made before it still trigger their domains. Checkpoints and state files are refused while suspended. Outside a kernel, $stop is reported as RuntimeEvent::Stop, as $finish is reported as Finish. Batch hosts end the run at it. $exit is ignored: Celox has no program blocks, and 24.7 ignores a call from outside one. BREAKING CHANGE: RuntimeEvent, RuntimeEventKind, ProcessStatus, Halt and CheckpointError gain a Stop/Stopped variant. Change-Id: Ia7467b814439b7542423436ce48b87e1a2d0597f --- crates/celox-design/src/lib.rs | 8 + crates/celox-frontend-core/src/process.rs | 6 + .../src/symbolic/assembly.rs | 10 +- crates/celox-frontend-sv/src/lowering/comb.rs | 17 +- crates/celox-frontend-sv/src/lowering/ff.rs | 23 ++- .../src/lowering/procedural.rs | 15 +- .../src/lowering/logic_tree/effect.rs | 17 +- crates/celox-napi/src/lib.rs | 16 +- crates/celox-runtime/src/derived_tick.rs | 6 +- crates/celox-runtime/src/simulation/mod.rs | 33 +++- .../celox-runtime/src/simulation/persist.rs | 4 + .../celox-runtime/src/simulation/process.rs | 45 ++++- crates/celox-runtime/src/simulation/round.rs | 32 ++- crates/celox-runtime/src/simulation/time.rs | 23 ++- crates/celox-runtime/src/timing.rs | 3 + .../celox-sv-analyzer/src/system_functions.rs | 12 +- crates/celox-vpi/src/lib.rs | 4 +- crates/celox/examples/sv_tests.rs | 6 +- .../celox/src/backend/native/runtime_image.rs | 3 +- crates/celox/src/simulation.rs | 29 ++- crates/celox/src/simulator.rs | 23 ++- crates/celox/src/simulator/checkpoint.rs | 7 + crates/celox/src/testbench.rs | 3 +- .../systemverilog/system_functions.rs | 185 ++++++++++++++++-- docs/guide/systemverilog.md | 17 +- docs/ja/guide/systemverilog.md | 13 +- packages/celox/src/napi-helpers.ts | 3 + packages/celox/src/simulation.ts | 10 + packages/celox/src/types.ts | 2 + 29 files changed, 502 insertions(+), 73 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 21bb5cc0f63..2982ce71c1d 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -67,6 +67,8 @@ pub enum RuntimeEventKind { AssertFatal, /// `$finish` executed by the design (IEEE 1800-2023 20.2). Finish, + /// `$stop` executed by the design (IEEE 1800-2023 20.2). + Stop, } /// How a runtime event site sizes its formatted arguments. @@ -244,6 +246,10 @@ pub enum ProcessStatus { /// The process returned so the runtime can charge its time-slot budget. /// It resumes at once. Yield, + /// The process suspended the simulation (`$stop`, IEEE 1800-2023 20.2). + /// It resumes at the point stored in [`ProcessSlots::resume`] when the + /// simulation continues. + Stop, } impl ProcessStatus { @@ -259,6 +265,7 @@ impl ProcessStatus { Self::Pending => 6, Self::Nba => 7, Self::Yield => 8, + Self::Stop => 9, } } @@ -272,6 +279,7 @@ impl ProcessStatus { 6 => Some(Self::Pending), 7 => Some(Self::Nba), 8 => Some(Self::Yield), + 9 => Some(Self::Stop), _ => None, } } diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 8b7b42e9480..dde70afe4f0 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -156,6 +156,12 @@ impl ProcessKernelBuilder { self.suspend(ProcessStatus::Yield) } + /// Suspend the simulation (`$stop`), and continue at a new resume point + /// when it continues. + pub fn stop(&mut self) -> Result<(), ProcessKernelError> { + self.suspend(ProcessStatus::Stop) + } + /// Suspend at wait site `site` of this process. The open block /// afterwards is the site's resume point: the caller lowers the wait's /// condition there and ends it with [`Self::wake_if`]. diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 2c7e800be86..a4742149e02 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2976,7 +2976,10 @@ fn build_comb_observer_capture_paths( }; let emit_on_true = matches!( sites[observer.site_id as usize].kind, - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop ); let fatal_error_code = matches!( sites[observer.site_id as usize].kind, @@ -3029,7 +3032,10 @@ fn build_comb_observer_capture_paths( let member = &observers[member_idx]; let member_emit_on_true = matches!( sites[member.site_id as usize].kind, - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop ); let member_fatal_error_code = matches!( sites[member.site_id as usize].kind, diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index bb8fdea1ce8..a6a2b8cfbe7 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -1916,6 +1916,12 @@ impl<'p, 'a> Comb<'p, 'a> { self.readmem(&mut store, frames, *format, args)?; Ok(store) } + // IEEE 1800-2023 24.7: `$exit` outside a program block is + // ignored. + sv::ir::Stmt::SystemTask { + task: sv::ir::SystemTask::Exit, + .. + } => Ok(store), sv::ir::Stmt::SystemTask { task, .. } if self.initial => Err(unsupported(format!( "system task `{task}` inside an initial block" ))), @@ -3152,7 +3158,7 @@ impl<'p, 'a> Comb<'p, 'a> { } let event_kind = match &kind { SystemTaskKind::Print(kind, _) => *kind, - SystemTaskKind::Finish => RuntimeEventKind::Finish, + SystemTaskKind::Control(kind) => *kind, SystemTaskKind::Message => RuntimeEventKind::AssertContinue, SystemTaskKind::Fatal => RuntimeEventKind::AssertFatal, SystemTaskKind::Assertion(kind) => *kind, @@ -3169,8 +3175,8 @@ impl<'p, 'a> Comb<'p, 'a> { }) } else { match (&kind, condition) { - (SystemTaskKind::Print(..) | SystemTaskKind::Finish, None) => None, - (SystemTaskKind::Print(..) | SystemTaskKind::Finish, Some((node, sources))) => { + (SystemTaskKind::Print(..) | SystemTaskKind::Control(_), None) => None, + (SystemTaskKind::Print(..) | SystemTaskKind::Control(_), Some((node, sources))) => { observed.extend(sources); Some(node) } @@ -3199,7 +3205,10 @@ impl<'p, 'a> Comb<'p, 'a> { effects.push(SLTForEffect::Event { site_id, guard, - emit_on_true: matches!(kind, SystemTaskKind::Print(..) | SystemTaskKind::Finish), + emit_on_true: matches!( + kind, + SystemTaskKind::Print(..) | SystemTaskKind::Control(_) + ), args: captured.clone(), fatal_error_code: kind.is_fatal().then_some(i64::from(site_id)), }); diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 90d3adfda0d..1e727f1ea7d 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1974,13 +1974,26 @@ impl<'p, 'a> Ff<'p, 'a> { } return Ok(true); } + // IEEE 1800-2023 24.7: `$exit` outside a program block is ignored. + if task == sv::ir::SystemTask::Exit { + return Ok(true); + } let kind = system_task_kind(task).ok_or_else(|| unsupported(format!("system task `{task}`")))?; // A process ends the simulation itself; the rest of its body does not - // run. - if matches!(kind, SystemTaskKind::Finish) && self.kernel.is_some() { - self.with_kernel(ProcessKernelBuilder::finish); - return Ok(false); + // run. A stop suspends the process with the simulation, which then + // continues after the call. + match kind { + SystemTaskKind::Control(RuntimeEventKind::Finish) if self.kernel.is_some() => { + self.with_kernel(ProcessKernelBuilder::finish); + return Ok(false); + } + SystemTaskKind::Control(RuntimeEventKind::Stop) if self.kernel.is_some() => { + self.with_kernel(ProcessKernelBuilder::stop) + .map_err(|error| unsupported(error.to_string()))?; + return Ok(true); + } + _ => {} } let assertion = if matches!(kind, SystemTaskKind::Assertion(_)) { let Some(sv::ir::SystemTaskArg::Expr(condition)) = args.first() else { @@ -2042,7 +2055,7 @@ impl<'p, 'a> Ff<'p, 'a> { }; let event_kind = match &kind { SystemTaskKind::Print(kind, _) => *kind, - SystemTaskKind::Finish => RuntimeEventKind::Finish, + SystemTaskKind::Control(kind) => *kind, SystemTaskKind::Message => RuntimeEventKind::AssertContinue, SystemTaskKind::Fatal => RuntimeEventKind::AssertFatal, SystemTaskKind::Assertion(kind) => *kind, diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 9f5131bc10a..b87fd7840c6 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -790,8 +790,8 @@ pub(super) enum SystemTaskKind { /// `$display` and `$write`, with the radix of their `b`, `o` and `h` /// variants (`d` otherwise). Print(RuntimeEventKind, char), - /// `$finish`. - Finish, + /// `$finish` and `$stop`, with their event kind. + Control(RuntimeEventKind), /// `$error`, `$warning`, `$info`: a message, then execution continues. Message, /// `$fatal`: a message, then the simulation ends with an error. @@ -811,8 +811,8 @@ impl SystemTaskKind { } /// How a task reports, for the tasks that report: `$readmemh`/`$readmemb` -/// load memory instead, and the analyzer rewrites `$printtimescale` into a -/// `$display`. +/// load memory instead, the analyzer rewrites `$printtimescale` into a +/// `$display`, and `$exit` outside a program block does nothing. pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option { use sv::ir::SystemTask; Some(match task { @@ -820,12 +820,13 @@ pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter()), - SystemTask::Finish => SystemTaskKind::Finish, + SystemTask::Finish => SystemTaskKind::Control(RuntimeEventKind::Finish), + SystemTask::Stop => SystemTaskKind::Control(RuntimeEventKind::Stop), SystemTask::Severity(_) => SystemTaskKind::Message, SystemTask::Fatal => SystemTaskKind::Fatal, SystemTask::Assert => SystemTaskKind::Assertion(RuntimeEventKind::AssertFatal), SystemTask::AssertContinue => SystemTaskKind::Assertion(RuntimeEventKind::AssertContinue), - SystemTask::Readmem(_) | SystemTask::Printtimescale => return None, + SystemTask::Readmem(_) | SystemTask::Printtimescale | SystemTask::Exit => return None, }) } @@ -863,7 +864,7 @@ pub(super) fn system_task_template( &args[1..] } SystemTaskKind::Assertion(_) => &args[1..], - SystemTaskKind::Finish => &[][..], + SystemTaskKind::Control(_) => &[][..], _ => args, }; let (mut template, values) = match args.first() { diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index 24eaf85c9b0..07c99954f25 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -208,7 +208,10 @@ fn collect_system_function_effect( observed_inputs.extend(collector.active_guard_sources.iter().copied()); let guard = match (kind, collector.active_guard, explicit_guard) { ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop, active, None, ) => active, @@ -227,11 +230,14 @@ fn collect_system_function_effect( Some(active) } ( - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish, + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop, _, Some(_), ) => { - unreachable!("display/write/finish has no explicit guard") + unreachable!("display/write/finish/stop has no explicit guard") } } .map(|node| -> Result { @@ -249,7 +255,10 @@ fn collect_system_function_effect( guard, emit_on_true: matches!( kind, - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop ), args: observer_args.clone(), fatal_error_code: matches!(kind, RuntimeEventKind::AssertFatal) diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index e2d8ccccfc3..a07a0fcd5b0 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -957,8 +957,9 @@ impl HandleBackend { ) .map_or_else( |halt| match halt { - // A bare backend reports no `$finish`; settle next time. - celox::Halt::Finish => Ok(false), + // A bare backend reports no `$finish` or `$stop`; settle + // next time. + celox::Halt::Finish | celox::Halt::Stop => Ok(false), celox::Halt::Error(error) => Err(error), }, |outcome| { @@ -2097,6 +2098,17 @@ impl NativeSimulationHandle { Ok(sim.is_finished()) } + /// Returns whether the last step or run returned early because a process + /// of the design executed `$stop`. The next step continues it. + #[napi] + pub fn is_stopped(&self) -> Result { + let sim = self + .sim + .as_ref() + .ok_or_else(|| Error::from_reason("Simulation has been disposed"))?; + Ok(sim.is_stopped()) + } + /// Evaluate combinational logic. #[napi] pub fn eval_comb(&mut self) -> Result<()> { diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index 0de446ccf89..902b8ccaf08 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -496,9 +496,9 @@ impl DerivedTickPlan { } }; match result { - // An RTL `$finish` ends only a timed simulation, which does not - // tick; a tick leaves it to the host. - Ok(_) | Err(Halt::Finish) => Ok(()), + // An RTL `$finish` or `$stop` ends or suspends only a timed + // simulation, which does not tick; a tick leaves it to the host. + Ok(_) | Err(Halt::Finish | Halt::Stop) => Ok(()), Err(Halt::Error(error)) => Err(error), } } diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 9638d412749..1e9708c0f61 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -27,7 +27,7 @@ use crate::{ SimulatorErrorCode, backend::SimBackend, schedule::ResolvedSchedule, - scheduler::Scheduler, + scheduler::{Scheduler, SimEvent}, timing::{Halt, ProcessState}, }; @@ -73,6 +73,13 @@ impl std::fmt::Debug for EventInfo { } } +/// A round suspended by `$stop` in its process phase: the round and the +/// scheduled events it processes, whose periodic clocks re-arm at its end. +struct Suspended { + round: Box, + events: Vec>, +} + /// Backend-independent state and execution rules for timed simulation. pub struct SimulationState { scheduler: Scheduler, @@ -86,6 +93,10 @@ pub struct SimulationState { host_pending: bool, /// A process requested the end of the simulation. finished: bool, + /// A process suspended the simulation (`$stop`) in the last step. + stopped: bool, + /// The round a `$stop` suspended, which the next step continues. + suspended: Option>, /// Buffers of the round in progress, kept between rounds. scratch: Option>, /// Rounds and process-phase passes one time slot may run, and kernel @@ -135,6 +146,8 @@ impl SimulationState { process_state, host_pending: false, finished: false, + stopped: false, + suspended: None, scratch: None, round_budget: SLOT_ROUND_BUDGET, return_budget: SLOT_RETURN_BUDGET, @@ -164,6 +177,7 @@ impl SimulationState { where E: SimulationExecutor, { + self.stopped = false; match self.step_time(executor, limit) { Ok(time) => Ok(time), Err(Halt::Finish) => { @@ -172,6 +186,8 @@ impl SimulationState { self.finish(executor); Ok(Some(self.scheduler.time)) } + // The time slot goes on when the simulation continues. + Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => Err(error), } } @@ -190,6 +206,20 @@ impl SimulationState { self.finished } + /// Whether the last step returned because a process suspended the + /// simulation with `$stop` (IEEE 1800-2023 20.2). The simulation is + /// suspended in the middle of a time slot, and the next step continues it + /// after the `$stop`. + pub fn is_stopped(&self) -> bool { + self.stopped + } + + /// 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() + } + /// Settle externally driven state against the previous edge baseline even /// when no clock/reset signal is explicitly scheduled at this timestamp. pub fn settle_at( @@ -211,6 +241,7 @@ impl SimulationState { self.finish(executor); Ok(Some(self.scheduler.time)) } + Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => Err(error), } } diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index 667c327ee9e..3006c553a39 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -58,6 +58,8 @@ impl SimulationState { self.process_state.clone_from(&snapshot.process_state); self.host_pending = snapshot.host_pending; self.finished = snapshot.finished; + self.stopped = false; + self.suspended = None; Ok(()) } } @@ -168,6 +170,8 @@ impl SimulationState { self.process_state = parts.process_state; self.host_pending = parts.host_pending; self.finished = parts.finished; + self.stopped = false; + self.suspended = None; } } diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index dab60b77349..2fcc709482f 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -59,6 +59,13 @@ impl SimulationState { self.charge(*returns, Some(process))?; return Ok(true); } + // The process continues after the `$stop`, first, when the + // simulation does. + Some(ProcessStatus::Stop) => { + self.stopped = true; + self.process_state.ready.insert(process); + return Err(Halt::Stop); + } Some(ProcessStatus::Yield) => { *returns += 1; self.charge(*returns, Some(process))?; @@ -88,10 +95,14 @@ impl SimulationState { self.event_values(executor.backend(), &mut round.before); while let Some(process) = self.process_state.ready.pop_first() { loop { - let again = self.run_process(executor, current_time, process, returns)?; + let again = self.run_process(executor, current_time, process, returns); // Each run is a separate update of the event signals, so a - // pulse across two runs is an edge. - self.record_transitions(executor.backend(), round); + // pulse across two runs is an edge. A stop keeps those of its + // run for the rest of the round. + if matches!(again, Ok(_) | Err(Halt::Stop)) { + self.record_transitions(executor.backend(), round); + } + let again = again?; // Before the next run, its edges must be seen. After the last // one, the check following the settle sees them: a settle // does not write what processes write. @@ -106,6 +117,18 @@ impl SimulationState { Ok(true) } + /// Mark the edges the processes of a pass caused and settle them. + fn settle_pass(&mut self, executor: &mut E, round: &mut Round) -> Result<(), Halt> + where + E: SimulationExecutor, + { + let transitions = std::mem::take(&mut round.transitions); + self.mark_scheduled_edges(executor.backend_mut(), round, &transitions); + round.transitions = transitions; + round.transitions.clear(); + self.settle_marked(executor, round) + } + /// The process phase of a round: the active and inactive regions before /// any domain publishes (IEEE 1800-2023 4.5). Without ready processes, /// waits or counted signals this is one settle, the batch step's. @@ -127,14 +150,18 @@ impl SimulationState { // and see the state settled at the previous time. The event // signals they change are edges of this time, like scheduled // events. - let ran = self.run_ready(executor, current_time, round, &mut returns)?; + let ran = match self.run_ready(executor, current_time, round, &mut returns) { + // The host sees the state settled at the stop. + Err(Halt::Stop) => { + round.kernels_ran = true; + self.settle_pass(executor, round)?; + return Err(Halt::Stop); + } + ran => ran?, + }; round.kernels_ran |= ran; if first || ran { - let transitions = std::mem::take(&mut round.transitions); - self.mark_scheduled_edges(executor.backend_mut(), round, &transitions); - round.transitions = transitions; - round.transitions.clear(); - self.settle_marked(executor, round)?; + self.settle_pass(executor, round)?; first = false; } if entry { diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 87dc735b9d6..e30bb87f56e 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -6,7 +6,7 @@ use bit_set::BitSet; use super::host::SimulationExecutor; use super::nba::{restore_working_image, working_image}; -use super::{EventInfo, SimulationState, event_level}; +use super::{EventInfo, SimulationState, Suspended, event_level}; use crate::{ SimulatorErrorCode, backend::SimBackend, @@ -354,7 +354,6 @@ impl SimulationState { self.observe_host_write(signal, &value); } - let num_events = executor.backend().num_events(); for (index, event) in events_to_process.iter().enumerate() { let signal = event.signal; let value = event.next_val; @@ -402,8 +401,35 @@ impl SimulationState { // The check after the batch already saw every signal. let entry = entry && events_to_process.is_empty(); - self.process_phase(executor, current_time, &mut round, entry)?; + self.continue_round(executor, current_time, round, events_to_process, entry) + } + /// The rest of a round from its process phase. A `$stop` there suspends + /// the round, and the next step continues it here. + pub(super) fn continue_round( + &mut self, + executor: &mut E, + current_time: u64, + mut round: Box, + events_to_process: Vec>, + entry: bool, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + match self.process_phase(executor, current_time, &mut round, entry) { + Ok(()) => {} + Err(Halt::Stop) => { + self.suspended = Some(Suspended { + round, + events: events_to_process, + }); + return Err(Halt::Stop); + } + Err(halt) => return Err(halt), + } + + let num_events = executor.backend().num_events(); let mut triggered_domains = BitSet::with_capacity(num_events); let mut discovered_in_this_step = BitSet::with_capacity(num_events); let mut comb_already_done = false; diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 960660b5b0e..4245098f1cf 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -89,6 +89,19 @@ impl SimulationState { where E: SimulationExecutor, { + // A suspended time slot continues where the `$stop` left it. + if let Some(suspended) = self.suspended.take() { + let current_time = self.scheduler.time; + self.continue_round( + executor, + current_time, + suspended.round, + suspended.events, + false, + )?; + self.end_time(executor, current_time)?; + return Ok(Some(current_time)); + } let mut settled = None; loop { let Some(current_time) = self.next_event_time() else { @@ -100,7 +113,7 @@ impl SimulationState { // Host writes alone: settle them, then go on to the next time. let host_only = self.host_pending && self.next_work_time() != Some(current_time); self.run_time(executor, current_time)?; - if !host_only { + if !host_only || self.stopped { return Ok(Some(current_time)); } settled = Some(current_time); @@ -125,6 +138,14 @@ impl SimulationState { }; let ready = self.take_ready_processes(current_time); self.step_round(executor, current_time, events_to_process, ready, true)?; + self.end_time(executor, current_time) + } + + /// The rounds of time slot `current_time` after its first. + fn end_time(&mut self, executor: &mut E, current_time: u64) -> Result<(), Halt> + where + E: SimulationExecutor, + { // A process that waited for zero time, or that the round woke, // resumes in a later round of this time, after the previous round's // edges have been handled. diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 4318bd6211f..c0da3a86a8c 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -21,6 +21,9 @@ use crate::{SignalRef, SimulatorErrorCode, backend::SimBackend}; pub enum Halt { /// `$finish`: the simulation ends where it is (IEEE 1800-2023 20.2). Finish, + /// `$stop`: the simulation is suspended where it is (IEEE 1800-2023 + /// 20.2), and continues there with the next step. + Stop, Error(SimulatorErrorCode), } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 1eade455720..59269ec1ba2 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -167,6 +167,12 @@ impl fmt::Display for SystemFunction { pub enum SystemTask { /// `$finish` (20.2). Finish, + /// `$stop` (20.2). + Stop, + /// `$exit` (20.2, 24.7), which ends the initial procedures of the + /// program block that calls it. Celox has no program blocks, and a call + /// from outside one is ignored. + Exit, /// `$printtimescale` (20.4.1); the analyzer rewrites it into a /// [`SystemTask::Display`] of the message. Printtimescale, @@ -239,6 +245,8 @@ impl SystemTask { use Radix::{Binary, Decimal, Hexadecimal, Octal}; match self { Self::Finish => "$finish", + Self::Stop => "$stop", + Self::Exit => "$exit", Self::Printtimescale => "$printtimescale", Self::Fatal => "$fatal", Self::Severity(Severity::Error) => "$error", @@ -435,8 +443,8 @@ const fn function(function: SystemFunction, min_args: usize, max_args: Option callbacks::request_finish(), + // Like `vpiStop` in `vpi_control`, `$stop` ends a run that has + // no interactive mode. + RuntimeEvent::Finish | RuntimeEvent::Stop => callbacks::request_finish(), RuntimeEvent::Missed { count } => { let _ = writeln!( std::io::stderr().lock(), diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index 95eb29dc429..9681e8ce05e 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -202,7 +202,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { .unwrap_or_else(|_| message.escape_ascii().to_string()) )); } - celox::RuntimeEvent::Finish => {} + celox::RuntimeEvent::Finish | celox::RuntimeEvent::Stop => {} celox::RuntimeEvent::Missed { count } => { return Err(format!("{count} runtime events were lost")); } @@ -215,7 +215,9 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { while !sim.is_finished() { let step = sim.step().map_err(|error| error.to_string()); output(&mut sim)?; - if step?.is_none() { + // A batch run has no interactive mode to suspend into, so it ends at + // `$stop`, as `vvp -n` does. + if step?.is_none() || sim.is_stopped() { break; } } diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 7dfdf72d48e..c22fc1f196b 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -452,7 +452,8 @@ impl NativeProgramInstance { RuntimeEvent::Display { .. } | RuntimeEvent::Write { .. } | RuntimeEvent::AssertContinue { .. } - | RuntimeEvent::Finish => None, + | RuntimeEvent::Finish + | RuntimeEvent::Stop => None, }) { return Err(celox_runtime::SimulatorErrorCode::Runtime { message, diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4a877e70f4d..88b008f47b3 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -242,6 +242,9 @@ impl Simulation { /// Save the design state, simulation time, clocks and pending events. pub fn checkpoint(&self) -> Result, CheckpointError> { + if self.state.is_suspended() { + return Err(CheckpointError::Stopped); + } Ok(SimulationCheckpoint { simulator: self.simulator.checkpoint()?, schedule: self.state.snapshot(), @@ -252,6 +255,9 @@ impl Simulation { /// Save the value of every state object by path, together with the /// simulation time, clocks and pending events by name. pub fn save_state(&mut self) -> Result { + if self.state.is_suspended() { + return Err(CheckpointError::Stopped.into()); + } let mut file = self.simulator.save_state()?; // Settling for the file may have executed a `$finish`. self.sync_finish(); @@ -407,6 +413,9 @@ impl Simulation { /// Advance time and run until `end_time` (inclusive). /// Targets earlier than the current time leave time and state unchanged. + /// A process that executes `$stop` returns control early, after the time + /// slot of the stop, with [`Self::is_stopped`] set; calling this again + /// continues. pub fn run_until(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { if end_time < self.state.time() { // Time only moves forward. Moving the timestamp back while the @@ -419,6 +428,9 @@ impl Simulation { break; } self.step_until(end_time)?; + if self.state.is_stopped() { + return Ok(()); + } } if self.state.is_finished() { return Ok(()); @@ -430,7 +442,8 @@ impl Simulation { /// Like [`Self::run_until`], but takes at most `max_steps` steps. /// Returns `false`, with the simulation at the time of its last step, - /// when another step would be needed to reach `end_time`. + /// when another step would be needed to reach `end_time`, including when + /// a step stopped at `$stop`. pub fn run_until_bounded( &mut self, end_time: u64, @@ -449,9 +462,12 @@ impl Simulation { } self.step_until(end_time)?; steps += 1; + if self.state.is_stopped() { + return Ok(false); + } } self.run_until(end_time)?; - Ok(true) + Ok(!self.state.is_stopped()) } /// Whether a process of the design requested the end of the simulation. @@ -461,6 +477,15 @@ impl Simulation { self.state.is_finished() } + /// Whether the last [`Self::step`] or [`Self::run_until`] returned early + /// because a process of the design executed `$stop` (IEEE 1800-2023 + /// 20.2). The simulation is suspended in the middle of that time; the + /// next step continues it after the `$stop`. Checkpoints and state files + /// cannot be taken while it is suspended. + pub fn is_stopped(&self) -> bool { + self.state.is_stopped() + } + /// Returns the current simulation time. pub fn time(&self) -> u64 { self.state.time() diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 67f4b713b58..bc6a9a32ec4 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -167,6 +167,9 @@ mod host { }, /// The design executed `$finish`. The host decides whether to stop. Finish, + /// The design executed `$stop` outside a process kernel. The host + /// decides whether to suspend. + Stop, Missed { count: u64, }, @@ -361,14 +364,18 @@ mod host { let Some(template) = site.template.as_deref() else { let default_spec = match site.kind { // Veryl prints arguments without a format string in hexadecimal. - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop if site.sizing == DisplaySizing::Veryl => { 'x' } - RuntimeEventKind::Display | RuntimeEventKind::Write | RuntimeEventKind::Finish => { - 'd' - } + RuntimeEventKind::Display + | RuntimeEventKind::Write + | RuntimeEventKind::Finish + | RuntimeEventKind::Stop => 'd', RuntimeEventKind::AssertContinue | RuntimeEventKind::AssertFatal => { if args.is_empty() { return b"assertion failed".to_vec(); @@ -467,6 +474,7 @@ mod host { RuntimeEventKind::AssertContinue => RuntimeEvent::AssertContinue { message }, RuntimeEventKind::AssertFatal => RuntimeEvent::AssertFatal { message }, RuntimeEventKind::Finish => RuntimeEvent::Finish, + RuntimeEventKind::Stop => RuntimeEvent::Stop, }) } } @@ -1518,9 +1526,10 @@ mod host { } } Ok(celox_runtime::EdgeOutcome::Settled) => self.dirty = false, - // An RTL `$finish` ends only a timed simulation; an edge, as a - // tick, leaves it to the host. What ran may not have settled. - Err(celox_runtime::Halt::Finish) => self.dirty = true, + // An RTL `$finish` or `$stop` ends or suspends only a timed + // simulation; an edge, as a tick, leaves it to the host. What + // ran may not have settled. + Err(celox_runtime::Halt::Finish | celox_runtime::Halt::Stop) => self.dirty = true, Err(celox_runtime::Halt::Error(error)) => return Err(error), } Ok(()) diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index e766ce119df..b9c681a0a46 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -132,6 +132,13 @@ pub enum CheckpointError { switch to a new VCD file first" )] VcdRewind { time: u64, last_dumped: u64 }, + /// A `$stop` suspended the simulation in the middle of a time slot, + /// whose progress a checkpoint does not capture. + #[error( + "the simulation is suspended at `$stop` in the middle of a time step; \ + continue it before taking a checkpoint" + )] + Stopped, } impl Simulator { diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 6ba13234cba..91e1a4c4daf 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1482,7 +1482,8 @@ fn drain_runtime_assertions( } RuntimeEvent::Display { message } => forward_display(&message, true), RuntimeEvent::Write { message } => forward_display(&message, false), - RuntimeEvent::Finish => finished = true, + // The testbench has no interactive mode to suspend into. + RuntimeEvent::Finish | RuntimeEvent::Stop => finished = true, } } DrainedAssertionEvents { diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 24e485fbba5..9db62d543e1 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1250,16 +1250,7 @@ fn readmem_diagnostics_identify_task_and_requested_range() { } #[test] -fn rejects_stop_and_deferred_cover_instead_of_discarding_their_semantics() { - for body in [ - "initial $stop;", - "always_comb begin $stop(0); y = 0; end", - "always_ff @(posedge clk) begin $stop; y <= 0; end", - "function automatic int f(); $stop; return 1; endfunction initial y = f();", - ] { - let source = format!("module Top(input logic clk, output logic y); {body} endmodule"); - assert!(build_error(&source).contains("system task `$stop`")); - } +fn rejects_deferred_cover_instead_of_discarding_its_semantics() { for timing in ["#0", "final"] { let source = format!("module Top(output logic y); initial cover {timing} (1) y = 1; endmodule"); @@ -1267,6 +1258,176 @@ fn rejects_stop_and_deferred_cover_instead_of_discarding_their_semantics() { } } +/// IEEE 1800-2023 20.2: `$stop` suspends the simulation, and continuing it +/// resumes after the call, including inside loops and functions. The other +/// processes of the round wait for the simulation to continue. +#[test] +fn stop_suspends_the_simulation_until_it_continues() { + let source = r#" + module Top(input int rounds, output int count, other, sum); + int acc; + function automatic int bump(input int x); + $stop; + return x + 1; + endfunction + initial begin + count = 1; + $stop; + count = 2; + acc = 10; + for (int i = 0; i < rounds; i++) begin + if (i != 1) $stop(0); + count = count + 1; + acc = acc + i; + end + count = bump(count); + $display("done %0d %0d", count, acc); + end + // Reading an input keeps this block a process instead of initial + // state. + initial other = rounds + 2; + assign sum = count + other; + endmodule + "#; + let mut sim = initial_simulation(source); + let rounds = sim.signal("rounds"); + sim.modify(|io| io.set(rounds, 3u8)).unwrap(); + let (count, other, sum) = (sim.signal("count"), sim.signal("other"), sim.signal("sum")); + for expected in [1u8, 2, 4, 5] { + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(sim.is_stopped()); + assert_eq!(sim.get(count), expected.into()); + assert_eq!(sim.get(other), 0u8.into()); + assert_eq!(sim.get(sum), expected.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + // A suspended time step cannot be captured. + assert!(matches!( + sim.checkpoint(), + Err(celox::CheckpointError::Stopped) + )); + } + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(!sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!(sim.get(count), 6u8.into()); + assert_eq!(sim.get(other), 5u8.into()); + assert_eq!(sim.get(sum), 11u8.into()); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"done 6 13".to_vec(), + }], + ); + assert_eq!(sim.step().unwrap(), None); + assert!(sim.checkpoint().is_ok()); + + // `run_until` returns at the stop, before reaching its target time, and + // continues when called again. + let mut sim = initial_simulation(source); + let rounds = sim.signal("rounds"); + sim.modify(|io| io.set(rounds, 3u8)).unwrap(); + for expected in [1u8, 2, 4, 5] { + sim.run_until(10).unwrap(); + assert!(sim.is_stopped()); + assert_eq!(sim.time(), 0); + assert_eq!(sim.get(count), expected.into()); + } + sim.run_until(10).unwrap(); + assert!(!sim.is_stopped()); + assert_eq!(sim.time(), 10); + assert_eq!(sim.get(count), 6u8.into()); + assert_eq!(sim.get(other), 5u8.into()); +} + +/// The time step a `$stop` suspends continues where it stopped: an edge a +/// process made before the stop triggers its domain after the rest of the +/// process has run. +#[test] +fn stop_keeps_the_edges_of_its_time_step() { + let source = r#" + module Top(input int start, output logic clk, output int q); + always_ff @(posedge clk) q <= q + 1; + initial begin + clk = start[0]; + clk = 1; + $stop; + $display("q=%0d", q); + end + endmodule + "#; + let mut sim = initial_simulation(source); + let q = sim.signal("q"); + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(sim.is_stopped()); + assert_eq!(sim.get(q), 0u8.into()); + assert_eq!(sim.step().unwrap(), Some(0)); + assert!(!sim.is_stopped()); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"q=0".to_vec(), + }], + ); + assert_eq!(sim.get(q), 1u8.into()); +} + +/// Outside a process kernel, `$stop` is reported to the host like `$finish`. +#[test] +fn stop_in_a_clocked_or_combinational_process_is_an_event() { + let source = r#" + module Top(input logic clk, enabled, output logic y); + always_ff @(posedge clk) if (enabled) $stop; + always_comb begin + if (enabled) $stop(2); + y = enabled; + end + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("stop.sv"))], "Top") + .build_cranelift() + .unwrap(); + sim.drain_runtime_events(); + sim.tick(sim.event("clk")).unwrap(); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + let enabled = sim.signal("enabled"); + sim.modify(|io| io.set(enabled, 1u8)).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![celox::RuntimeEvent::Stop]); + sim.tick(sim.event("clk")).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![celox::RuntimeEvent::Stop]); +} + +/// IEEE 1800-2023 24.7: `$exit` outside a program block is ignored. +#[test] +fn exit_outside_a_program_block_is_ignored() { + let source = r#" + module Top(input logic clk, output int a, b); + initial begin + a = 1; + $exit; + a = 2; + $exit(); + a = 3; + end + always_ff @(posedge clk) begin + $exit; + b <= b + 1; + end + endmodule + "#; + let mut sim = initial_simulation(source); + sim.run_until(0).unwrap(); + assert!(!sim.is_finished()); + assert!(!sim.is_stopped()); + assert_eq!(sim.get(sim.signal("a")), 3u8.into()); + assert_eq!(sim.drain_runtime_events(), Vec::new()); + let error = + build_error("module Top(output logic y); initial $exit(1); assign y = 0; endmodule"); + assert!( + error.contains("$exit") && error.contains("expected 0 arguments"), + "{error}" + ); +} + #[test] fn rejects_unknown_system_functions_in_every_context() { let cases = [ @@ -1360,8 +1521,8 @@ fn reports_where_a_known_system_function_is_not_supported() { endmodule", ), ( - "system task `$stop`", - "module Top(output logic y); initial $stop; assign y = 0; endmodule", + "system task `$dumpvars`", + "module Top(output logic y); initial $dumpvars; assign y = 0; endmodule", ), ( "system task `$stacktrace`", diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 963940f0c26..a274a65d2a6 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -86,7 +86,7 @@ synthesis and is tested at the design level. | Parameters | integral parameters, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | Random numbers | `$urandom`, `$urandom_range` and `$random` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | -| System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | +| System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -304,8 +304,19 @@ imports, task imports, exports, packed vector arguments (`svBitVecVal` / - **System functions called as statements**, such as `$countones(f(a));`, are checked and evaluated like the same call in an expression, and their value is discarded. `$bits` and `$size` do not evaluate their operand. -- **Simulation suspension** (`$stop`) is rejected explicitly. The host API does - not provide suspended-process continuation; `$finish` remains supported. +- **Simulation suspension.** `$stop` in an `initial` block suspends the + simulation (IEEE 1800-2023 20.2): `Simulation::step` and `run_until` return + at the time of the stop with `is_stopped()` set, the other processes of that + time wait, and the next call continues after the `$stop`, also inside loops + and functions. The suspended time step keeps the edges the process made + before the stop. A checkpoint or state file cannot be taken while the + simulation is suspended (`CheckpointError::Stopped`). In an `always` process, `$stop` is reported as + `RuntimeEvent::Stop`, as `$finish` is reported as `RuntimeEvent::Finish`. + Its diagnostic level argument prints nothing. Batch hosts without an + interactive mode, such as the VPI host, end the run at `$stop`. +- **`$exit`** ends the initial procedures of the program block that calls it + (24.7). Celox has no program blocks, and a call from anywhere else is + ignored, as 24.7 specifies. - **Immediate cover** executes its pass statement when the condition is true. Coverage counters and reports are not exposed. Deferred cover (`#0` / `final`) is rejected because its scheduling is not modeled. diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 52d84f87476..0fd535c3463 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -72,7 +72,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 | パラメータ | 整数のパラメータと、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | 乱数 | `$urandom`、`$urandom_range`、`$random` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | -| システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | +| システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 状態 | 2 値・4 値シミュレーション | 上記の各構文は、ソフトウェアモデルと結果を比較するテストで確認しています。Veryl が出力する @@ -241,3 +241,14 @@ Icarus Verilog などそれを実装するシミュレータと同じ値を返 `$random(seed)` はシード変数を更新します。引数がなければプロセスごとのシードを 使い、その初期値は0です。そのため `$random` を呼ぶプロセスが1つだけの設計では、 設計全体で1つのシードを持つシミュレータと一致します。 + +`initial` ブロックの `$stop` はシミュレーションを一時停止します(IEEE 1800-2023 20.2)。 +`Simulation::step` と `run_until` は停止した時刻で戻り、`is_stopped()` が真になります。 +その時刻の他のプロセスは待機し、次の呼び出しでループや関数の中も含めて `$stop` の +直後から再開します。停止した時刻の処理は、停止前にプロセスが起こしたエッジも保ったまま +再開します。停止中はチェックポイントと状態ファイルを作れません(`CheckpointError::Stopped`)。 +`always` 系のプロセスでは、`$finish` が `RuntimeEvent::Finish` に +なるのと同様に `RuntimeEvent::Stop` として報告します。診断レベルの引数では何も +表示しません。VPI ホストのように対話モードを持たないバッチ実行では `$stop` で終了します。 +`$exit` は呼び出した program ブロックの initial 手続きを終了します(24.7)。 +Celox は program ブロックを持たず、それ以外からの呼び出しは 24.7 の規定どおり無視します。 diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index 05a36935464..0dea70c46d1 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -52,6 +52,8 @@ export interface RawNapiSimulationHandle { nextEventTime(): number | null; /** Whether a process requested the end of the simulation. */ isFinished?(): boolean; + /** Whether the last step or run returned early at `$stop`. */ + isStopped?(): boolean; evalComb(): void; dump(timestamp: number): void; sharedMemory(): Uint8Array; @@ -912,6 +914,7 @@ export function wrapDirectSimulationHandle( : {}), ...(raw.clockPeriods ? { clockPeriods: () => raw.clockPeriods!() } : {}), ...(raw.isFinished ? { isFinished: () => raw.isFinished!() } : {}), + ...(raw.isStopped ? { isStopped: () => raw.isStopped!() } : {}), }; } diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index f575986cd10..454a9e31565 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -514,6 +514,16 @@ export class Simulation

> { return this._handle.isFinished?.() ?? false; } + /** + * Whether the last `step()` or `runUntil()` returned early because a + * process of the design executed `$stop`. The next call continues the + * simulation after the `$stop`. + */ + isStopped(): boolean { + this.ensureAlive(); + return this._handle.isStopped?.() ?? false; + } + /** * Step until `condition()` returns true. * diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index c5f3c9e58ad..0440dc99017 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -245,6 +245,8 @@ export interface NativeSimulationHandle { nextEventTime(): number | null; /** Whether a process requested the end of the simulation. */ isFinished?(): boolean; + /** Whether the last step or run returned early at `$stop`. */ + isStopped?(): boolean; evalComb(): void; dump(timestamp: number): void; dispose(): void; From aa048d54891241a3adac53d2ceecdadfb3828e7e Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 10:44:17 +0900 Subject: [PATCH 2/2] test(sv-tests): accept the $stop and $exit results --- conformance/sv-tests/expected.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index df1c18dab94..c24b1699178 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -345,9 +345,9 @@ chapter-20/20.15--dist_poisson.sv fail chapter-20/20.15--dist_t.sv fail chapter-20/20.15--dist_uniform.sv fail chapter-20/20.15--random.sv pass -chapter-20/20.2--exit.sv fail +chapter-20/20.2--exit.sv pass chapter-20/20.2--finish.sv pass -chapter-20/20.2--stop.sv fail +chapter-20/20.2--stop.sv pass chapter-20/20.3--realtime.sv fail chapter-20/20.3--stime.sv fail chapter-20/20.3--time.sv fail