From afa4716ea308d097e7a0dd9a318b23f4e7107eeb Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 15:41:23 +0900 Subject: [PATCH] feat(sv)!: support wait fork and disable fork process control Forked processes could run concurrently but their caller could not wait for all outstanding children or cancel them. Implement wait fork across all live immediate children, including earlier forks and task calls. Implement disable fork across every descendant, including descendants of completed parents, while preserving the caller and its siblings. Remove cancelled activations from pending starts, waits, ready/inactive/reactive queues and scheduled wakeups before reusing their IDs. Preserve checkpoint replay of joins and cancellation. Function calls retain their caller's process identity for disable fork; wait fork remains forbidden in functions. Handle frameless processes and zero-time final procedures safely. Update obsolete rejection tests and document the supported behavior. Accept exactly four measured official fail-to-pass verdicts for wait_fork and disable_fork in two/four-state modes. These upstream cases exercise elaboration; portable cases exercise execution. Partially addresses #2111. State-file serialization, compound automatic-local event expressions, deferred assertions and join_none exceptions remain separate work. Validation: - P2 review follow-up: retain the kernel during wait-condition evaluation, restore the full predicate resume point after a false reevaluation, and propagate wait fork/fork through task classification. Four new cases fail in all 24 configurations before the fix and pass afterward. - Follow-up validation: 1,057 timing tests, affected frontend unit tests, runtime consumers, Clippy, debug NAPI and 28 JS tests pass. The final explicit-argument reevaluation case also passes all six backend configurations. - External follow-up: Verilator passes three of four new cases, but waits on a cached function result instead of reevaluating the effectful predicate in the fourth (expected q=1, observed q=0). Icarus passes both event-driven task cases; a no-argument wait function hits its Empty NexusSet internal error and the explicit-argument cancellation case leaves the child alive (q=99). - Twelve portable cases pass in 72 configurations across Native/parallel/image, Cranelift/parallel and WASM, including four-state behavior. - Four API tests cover Interpreter/native differential checkpoint replay, cancellation and ID reuse, final no-op behavior and frameless process wakeups. The frameless regression panics before the fix and passes afterward. - Existing fork API seven, library 946 and consumer 343 tests pass. Timing has 1,032 passing tests; the sole stale unsupported-feature expectation was updated and its focused rerun passes. - Formatting, affected-crate Clippy, debug NAPI build and 28 JS boundary tests pass. - Official pinned runner verifies both affected cases in both modes using the debug driver; full release conformance remains in CI. - Verilator 5.052 passes all eleven two-state cases; four-state is unsupported. Icarus 13.0 passes ten cases but fails to cancel descendants of completed parents and children from a function call. Expectations follow IEEE 1800-2023 9.6.1, 9.6.3 and 13.4 and are corroborated by Verilator. BREAKING CHANGE: ProcessStatus and procedural IR gain process-control variants; native image format advances to version 41. Change-Id: I9f0dd3b8a7a23a655d9b8a76f9a8a545ec1a4a22 --- conformance/sv-tests/expected.tsv | 8 +- crates/celox-design/src/lib.rs | 8 + crates/celox-frontend-core/src/process.rs | 24 +- crates/celox-frontend-sv/src/lowering/comb.rs | 5 +- crates/celox-frontend-sv/src/lowering/ff.rs | 65 ++++-- .../src/simulation/activation.rs | 58 +++++ .../celox-runtime/src/simulation/process.rs | 5 + .../celox-runtime/src/simulation/terminal.rs | 7 +- .../src/ast/const_functions.rs | 6 +- crates/celox-sv-analyzer/src/ast/lifetimes.rs | 8 +- .../celox-sv-analyzer/src/ast/procedural.rs | 13 +- .../src/ast/procedural/timed_tasks.rs | 9 +- crates/celox-sv-analyzer/src/procedural.rs | 5 + crates/celox-sv-analyzer/src/tests.rs | 2 - .../src/sv/cases/fork_control.vtest | 219 ++++++++++++++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- .../tests/frontends/systemverilog/timing.rs | 30 ++- crates/celox/tests/sv_fork_control.rs | 94 ++++++++ docs/guide/systemverilog-reference.md | 11 +- 20 files changed, 533 insertions(+), 50 deletions(-) create mode 100644 crates/celox-test-suite/src/sv/cases/fork_control.vtest create mode 100644 crates/celox/tests/sv_fork_control.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 3b247a58676..3a8ec649374 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1645,14 +1645,14 @@ chapter-9/9.4.5--event_nonblocking_assignment_repeat_int_neg.sv 2state fail chapter-9/9.4.5--event_nonblocking_assignment_repeat_int_neg.sv 4state fail chapter-9/9.4.5--event_nonblocking_assignment_repeat_neg.sv 2state fail chapter-9/9.4.5--event_nonblocking_assignment_repeat_neg.sv 4state fail -chapter-9/9.6.1--wait_fork.sv 2state fail -chapter-9/9.6.1--wait_fork.sv 4state fail +chapter-9/9.6.1--wait_fork.sv 2state pass +chapter-9/9.6.1--wait_fork.sv 4state pass chapter-9/9.6.2--disable.sv 2state fail chapter-9/9.6.2--disable.sv 4state fail chapter-9/9.6.2--disable_other.sv 2state fail chapter-9/9.6.2--disable_other.sv 4state fail -chapter-9/9.6.3--disable_fork.sv 2state fail -chapter-9/9.6.3--disable_fork.sv 4state fail +chapter-9/9.6.3--disable_fork.sv 2state pass +chapter-9/9.6.3--disable_fork.sv 4state pass chapter-9/9.7--process_cls_await.sv 2state fail chapter-9/9.7--process_cls_await.sv 4state fail chapter-9/9.7--process_cls_kill.sv 2state fail diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index c8f08f14e9d..faeb44eabf3 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -464,6 +464,10 @@ pub enum ProcessStatus { Fork, /// Allocate a fresh automatic local cell before its declaration initializer. Local, + /// Wait for all live immediate child activations. + WaitFork, + /// Terminate all descendants of the calling activation. + DisableFork, } impl ProcessStatus { @@ -484,6 +488,8 @@ impl ProcessStatus { Self::Exit => 11, Self::Fork => 12, Self::Local => 13, + Self::WaitFork => 14, + Self::DisableFork => 15, } } @@ -502,6 +508,8 @@ impl ProcessStatus { 11 => Some(Self::Exit), 12 => Some(Self::Fork), 13 => Some(Self::Local), + 14 => Some(Self::WaitFork), + 15 => Some(Self::DisableFork), _ => None, } } diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 2d382987de9..4a8eabf3658 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -60,8 +60,8 @@ pub struct ProcessKernelBuilder { slots: ProcessSlots, /// The block each resume point continues in; point 0 is the start. resume_blocks: Vec, - /// The wait site whose resume point is being lowered. - wait_site: Option, + /// The wait site and predicate entry resume point being lowered. + wait_site: Option<(u32, usize)>, /// The runtime event site the process reports at its flush points /// (see [`Self::flush_deferred_at`]). flush_site: Option, @@ -217,6 +217,19 @@ impl ProcessKernelBuilder { Ok((children, self.builder.current_block())) } + /// Wait for the calling process's immediate children (IEEE 1800-2023 9.6.1). + pub fn wait_fork(&mut self) -> Result<(), ProcessKernelError> { + self.slots.const_delays = false; + self.slots.requires_timed_simulation = true; + self.suspend(ProcessStatus::WaitFork) + } + + /// Cancel descendants without suspending HDL execution (9.6.3). + pub fn disable_fork(&mut self) -> Result<(), ProcessKernelError> { + self.slots.const_delays = false; + self.suspend(ProcessStatus::DisableFork) + } + pub fn local(&mut self, slot: usize) -> Result<(), ProcessKernelError> { self.store_delay_constant(slot as u64); self.suspend(ProcessStatus::Local) @@ -245,7 +258,7 @@ impl ProcessKernelBuilder { pub fn suspend_wait(&mut self, site: u32) -> Result<(), ProcessKernelError> { self.store_delay_constant(u64::from(site)); self.suspend(ProcessStatus::Wait)?; - self.wait_site = Some(site); + self.wait_site = Some((site, self.resume_blocks.len() - 1)); Ok(()) } @@ -254,7 +267,7 @@ impl ProcessKernelBuilder { /// that the wait is still pending and return to the same resume point. /// The continuation block is open afterwards. pub fn wake_if(&mut self, condition: RegisterId) { - let site = self.wait_site.take().expect("wake_if follows suspend_wait"); + let (site, resume) = self.wait_site.take().expect("wake_if follows suspend_wait"); let woken = self.builder.new_block(); let pending = self.builder.new_block(); self.builder.seal_block(SIRTerminator::Branch { @@ -263,6 +276,9 @@ impl ProcessKernelBuilder { false_block: (pending, Vec::new()), }); self.builder.switch_to_block(pending); + // Predicate evaluation may itself yield to the runtime (for example, + // disable fork). A later wakeup must evaluate the whole predicate. + self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, resume as u64); self.store_delay_constant(u64::from(site)); self.end(ProcessStatus::Pending); self.builder.switch_to_block(woken); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 3f3e7324f06..06233d06023 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2026,7 +2026,10 @@ impl<'p, 'a> Comb<'p, 'a> { stmt: &sv::ir::Stmt, ) -> Result { match stmt { - sv::ir::Stmt::Fork { .. } => Err(unsupported("fork outside a timed process")), + sv::ir::Stmt::DisableFork => Ok(store), + sv::ir::Stmt::Fork { .. } | sv::ir::Stmt::WaitFork => { + Err(unsupported("fork control outside a timed process")) + } sv::ir::Stmt::Assign { lhs, rhs, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index e063153f265..26ef54d8fb1 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -3014,6 +3014,23 @@ impl<'p, 'a> Ff<'p, 'a> { self.wait_level(condition)?; Ok(true) } + sv::ir::Stmt::WaitFork | sv::ir::Stmt::DisableFork => { + if self.kernel.is_none() { + return if matches!(stmt, sv::ir::Stmt::DisableFork) { + Ok(true) + } else { + Err(unsupported("fork control outside a timed process")) + }; + } + if matches!(stmt, sv::ir::Stmt::WaitFork) { + self.with_kernel(ProcessKernelBuilder::wait_fork) + .map_err(kernel_error)?; + } else { + self.with_kernel(ProcessKernelBuilder::disable_fork) + .map_err(kernel_error)?; + } + Ok(true) + } sv::ir::Stmt::Fork { join, branches } => { if self.kernel.is_none() { return Err(unsupported("fork outside a timed process")); @@ -5231,7 +5248,7 @@ impl Ff<'_, '_> { let mut calls = Vec::new(); for stmt in body { stmt.walk(&mut |stmt| match stmt { - sv::ir::Stmt::Fork { .. } => found = true, + sv::ir::Stmt::Fork { .. } | sv::ir::Stmt::WaitFork => found = true, sv::ir::Stmt::Call { name, .. } => calls.push(name.clone()), _ => {} }); @@ -6130,30 +6147,29 @@ impl Ff<'_, '_> { .map(|id| (id, CounterKind::Changes)) .collect(), ); - // The condition is lowered once per check: before the process - // suspends and at every resume. - let mut error = None; - let mut kernel = self.kernel.take().expect("lowering a process kernel"); - std::mem::swap(&mut self.b, kernel.builder()); - // The kernel is out of `self` while it builds the checks; reads go - // to stable state all the same. + // Keep the kernel available while evaluating the predicate: functions + // may perform synchronous process control such as disable fork. let direct = std::mem::replace(&mut self.direct, true); - let result = kernel.wait_level(site, |builder| { - std::mem::swap(&mut self.b, builder); - let truth = self.eval_truth(condition).map(|(truth, _)| truth); - std::mem::swap(&mut self.b, builder); - truth.unwrap_or_else(|e| { - error = Some(e); - let never = builder.alloc_bit(1, false); - builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u8))); - never - }) - }); + let result = (|| { + let (holds, _) = self.eval_truth(condition)?; + let join = self.b.new_block(); + let wait = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: holds, + true_block: (join, Vec::new()), + false_block: (wait, Vec::new()), + }); + self.b.switch_to_block(wait); + self.with_kernel(|kernel| kernel.suspend_wait(site)) + .map_err(kernel_error)?; + let (holds, _) = self.eval_truth(condition)?; + self.with_kernel(|kernel| kernel.wake_if(holds)); + self.b.seal_block(SIRTerminator::Jump(join, Vec::new())); + self.b.switch_to_block(join); + Ok(()) + })(); self.direct = direct; - std::mem::swap(&mut self.b, kernel.builder()); - self.kernel = Some(kernel); - result.map_err(kernel_error)?; - error.map_or(Ok(()), Err) + result } /// Declare a wait site of the process with the given terms and return @@ -6394,7 +6410,8 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { args: args.clone(), arg_order: arg_order.clone(), }), - sv::ir::Stmt::SystemTask { .. } + sv::ir::Stmt::DisableFork + | sv::ir::Stmt::SystemTask { .. } | sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::WaitImplicit(_) diff --git a/crates/celox-runtime/src/simulation/activation.rs b/crates/celox-runtime/src/simulation/activation.rs index 401dbbd316e..dcdcaeea1b7 100644 --- a/crates/celox-runtime/src/simulation/activation.rs +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -196,6 +196,64 @@ impl SimulationState { } } + /// Only immediate, still-live children participate, even when an already + /// completed child left running descendants (IEEE 1800-2023 9.6.1). + pub(super) fn wait_for_children(&mut self, process: usize) -> bool { + let children: Vec<_> = self + .process_state + .activations + .iter() + .enumerate() + .filter_map(|(id, activation)| { + (activation.live && activation.parent == Some(process)).then_some(id) + }) + .collect(); + if children.is_empty() { + return true; + } + self.process_state.activations[process].join = Some((ForkJoin::All, children)); + false + } + + /// Follow ancestry through completed parents too (IEEE 1800-2023 9.6.3). + /// Remove scheduler entries before releasing IDs for reuse. + pub(super) fn disable_children(&mut self, process: usize) { + if self.process_state.activations.is_empty() { + return; + } + let mut cancelled = vec![false; self.process_state.activations.len()]; + let mut pending = vec![process]; + while let Some(parent) = pending.pop() { + for (id, activation) in self.process_state.activations.iter().enumerate() { + if activation.parent == Some(parent) && !cancelled[id] { + cancelled[id] = true; + pending.push(id); + } + } + } + let state = &mut self.process_state; + for (id, activation) in state.activations.iter_mut().enumerate() { + activation.pending.retain(|&child| !cancelled[child]); + if cancelled[id] { + activation.live = false; + activation.join = None; + state.waiters.remove(id); + state.ready.remove(&id); + state.reactive.remove(&id); + state.inactive.remove(&id); + state.re_inactive.remove(&id); + } + } + self.process_wakeups + .retain(|std::cmp::Reverse((_, id))| !cancelled[*id]); + // Already captured NBA values are independent scheduler work. + for (id, &cancelled) in cancelled.iter().enumerate() { + if cancelled { + self.retire_activation(id); + } + } + } + pub(super) fn end_activation(&mut self, process: usize) { if self.process_state.activations.is_empty() || self.model.processes[process].frame.is_none() diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index eb6b0b2684e..3716a3a3721 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -196,6 +196,11 @@ impl SimulationState { self.charge(*returns, Some(process))?; return self.fork_activation(executor.backend_mut(), process, encoded); } + Some(ProcessStatus::WaitFork) => return Ok(self.wait_for_children(process)), + Some(ProcessStatus::DisableFork) => { + self.disable_children(process); + return Ok(true); + } Some(ProcessStatus::Local) => { let index = delay() as usize; self.allocate_local(process, index)?; diff --git a/crates/celox-runtime/src/simulation/terminal.rs b/crates/celox-runtime/src/simulation/terminal.rs index 0681a7d80f1..1fb18cc4d8c 100644 --- a/crates/celox-runtime/src/simulation/terminal.rs +++ b/crates/celox-runtime/src/simulation/terminal.rs @@ -84,7 +84,12 @@ impl SimulationState { } // 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 | ProcessStatus::Local) => {} + Some( + ProcessStatus::Yield + | ProcessStatus::Nba + | ProcessStatus::Local + | ProcessStatus::DisableFork, + ) => {} _ => { return Err(SimulatorErrorCode::Runtime { message: "final procedure cannot suspend for HDL timing".into(), diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 7235a522ed1..4d687e8baed 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -1402,7 +1402,11 @@ impl Frame<'_> { Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { return None; } - Stmt::Fork { .. } | Stmt::AssignConcat { .. } | Stmt::Call { .. } => return None, + Stmt::Fork { .. } + | Stmt::WaitFork + | Stmt::DisableFork + | Stmt::AssignConcat { .. } + | Stmt::Call { .. } => return None, } Some(Flow::Next) } diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 1bf88b7c1f5..da8e1a27b8b 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -673,6 +673,7 @@ impl Flow<'_> { self.read(expr, written)?; Ok(Exits::next(written)) } + Stmt::WaitFork | Stmt::DisableFork => Ok(Exits::next(written)), Stmt::WaitEvent(items) => { for item in items { self.read(&item.expr, written)?; @@ -829,7 +830,12 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { Stmt::Delay { amount: expr, .. } | Stmt::Wait(expr) => vec![expr], Stmt::WaitEvent(items) => items.iter().map(|item| &item.expr).collect(), // The statements of an `@*` describe its reads and do not run. - Stmt::Fork { .. } | Stmt::WaitImplicit(_) | Stmt::Break | Stmt::Continue => Vec::new(), + Stmt::Fork { .. } + | Stmt::WaitFork + | Stmt::DisableFork + | Stmt::WaitImplicit(_) + | Stmt::Break + | Stmt::Continue => Vec::new(), } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 4d97adbc841..56bbd57c002 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -968,7 +968,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { _ => self.subroutine_call_statement(*id), }, StatementKind::Assertion { .. } => Err(unsupported("concurrent assertion")), - StatementKind::WaitFork => Err(unsupported("wait fork statement")), + StatementKind::WaitFork => { + self.allow_timing("wait fork statement")?; + Ok(vec![Stmt::WaitFork]) + } StatementKind::WaitOrder { .. } => Err(unsupported("wait order statement")), StatementKind::EventTrigger(_) => Err(unsupported("event trigger")), StatementKind::ProceduralAssign(_) | StatementKind::ProceduralRelease(_) => { @@ -985,11 +988,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .filter(|token| !token.is_trivia()) .find(|token| token.text != "disable") .is_some_and(|token| token.text == "fork"); - Err(unsupported(if disables_fork { - "disable fork statement" + if disables_fork { + Ok(vec![Stmt::DisableFork]) } else { - "disable statement" - })) + Err(unsupported("disable statement")) + } } StatementKind::Parallel { .. } => Err(unsupported("fork-join block")), _ => Err(unsupported("procedural statement")), 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 06f9181f7e6..ac49518f3ac 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -192,9 +192,12 @@ fn suspends(body: &[Stmt], timed: &HashSet) -> bool { for statement in body { statement.walk(&mut |statement| { result |= match statement { - Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { - true - } + Stmt::Delay { .. } + | Stmt::WaitEvent(_) + | Stmt::WaitImplicit(_) + | Stmt::Wait(_) + | Stmt::WaitFork + | Stmt::Fork { .. } => true, Stmt::Call { name, .. } => timed.contains(name), _ => false, }; diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index b706c7cf6d8..0aeab0c945e 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -133,6 +133,8 @@ pub enum StmtBase { /// the reads: they do not execute here, and [`StmtBase::walk`] does not /// visit them. WaitImplicit(Vec>), + WaitFork, + DisableFork, /// `wait (condition)`: suspend the process until the condition is true /// (9.4.3). Wait(E), @@ -371,6 +373,8 @@ impl StmtBase { }) .collect(), ), + StmtBase::WaitFork => StmtBase::WaitFork, + StmtBase::DisableFork => StmtBase::DisableFork, StmtBase::Wait(condition) => StmtBase::Wait(fe(condition)), StmtBase::WaitImplicit(reads) => StmtBase::WaitImplicit(body(reads, fe, fl)), } @@ -489,6 +493,7 @@ impl StmtBase { fe(&mut item.expr); } } + StmtBase::WaitFork | StmtBase::DisableFork => {} StmtBase::Wait(condition) => fe(condition), StmtBase::WaitImplicit(reads) => body(reads, fe, fl, fname), } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 7d280a56b89..7e00ceaa10a 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3494,7 +3494,6 @@ fn rejects_unlowered_constructs() { #[test] fn rejects_unimplemented_timing_constructs() { for (body, construct) in [ - ("initial wait fork;", "wait fork statement"), // The `event` data type is rejected by name before its uses. ("event e; initial @e;", "named event"), ("event e; initial ->e;", "named event"), @@ -3511,7 +3510,6 @@ fn rejects_unimplemented_timing_constructs() { "intra-assignment timing control", ), ("initial begin : b disable b; end", "disable statement"), - ("initial disable fork;", "disable fork statement"), ( "logic a, y; always_latch y <= a;", "nonblocking assignment inside always_latch", diff --git a/crates/celox-test-suite/src/sv/cases/fork_control.vtest b/crates/celox-test-suite/src/sv/cases/fork_control.vtest new file mode 100644 index 00000000000..1b2c152615f --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/fork_control.vtest @@ -0,0 +1,219 @@ +(group fork_control (category sequential)) + +; IEEE 1800-2023 9.6.1 and 9.6.3: immediate-child waits vs descendant cancellation. +(case no_children_does_not_suspend + (source "empty.sv" #"module Top(output int q); + initial begin q=0; wait fork; disable fork; q=1; end +endmodule"#) + (top Top) (run_until 0) (assert_eq q 1)) + +(case wait_in_task_includes_earlier_forks + (source "wait_task.sv" #"module Top(output bit [3:0] q); + task await_children; + fork begin #2; q[1]=1; end join_none + wait fork; + q[3]=1; + endtask + initial begin + fork begin #3; q[0]=1; end join_none + fork begin #1; q[2]=1; end join_any + await_children(); + end +endmodule"#) + (top Top) (run_until 2) (assert_eq q 4) + (run_until 3) (assert_eq q 15)) + +(case wait_excludes_descendants_of_completed_children + (source "wait_immediate.sv" #"module Top(output bit [2:0] q); + initial begin + fork + begin fork begin #4; q[0]=1; end join_none end + begin #1; q[1]=1; end + join_none + wait fork; q[2]=1; + end +endmodule"#) + (top Top) (run_until 1) (assert_eq q 6) + (run_until 4) (assert_eq q 7)) + +(case disable_before_children_start + (source "disable_pending.sv" #"module Top(output int q); + initial begin + q=0; + fork begin q=99; #1; q=100; end join_none + disable fork; + wait fork; + q=1; + end +endmodule"#) + (top Top) (run_until 3) (assert_eq q 1)) + +(case disable_after_join_any_cancels_waiters_and_delays + (source "disable_waiters.sv" #"module Top(output bit [4:0] q); + bit trigger; + initial begin + fork + begin #1; q[0]=1; end + begin #4; q[1]=1; end + begin @(posedge trigger); q[2]=1; end + begin wait(trigger); q[3]=1; end + join_any + disable fork; + wait fork; + q[4]=1; + #1; trigger=1; + end +endmodule"#) + (top Top) (run_until 5) (assert_eq q 17)) + +(case disable_reaches_through_completed_parents + (source "disable_descendants.sv" #"module Top(output bit [1:0] q); + initial begin + fork begin + fork begin #4; q[0]=1; end join_none + end join_none + wait fork; + #1; + disable fork; + q[1]=1; + end +endmodule"#) + (top Top) (run_until 5) (assert_eq q 2)) + +(case disable_does_not_kill_siblings_or_caller + (source "disable_scope.sv" #"module Top(output bit [2:0] q); + initial begin + fork + begin + fork begin #3; q[0]=1; end join_none + #1; disable fork; wait fork; q[1]=1; + end + begin #2; q[2]=1; end + join + end +endmodule"#) + (top Top) (run_until 4) (assert_eq q 6)) + +(case disable_removes_nested_join_waits + (source "disable_nested_join.sv" #"module Top(output bit [3:0] q); + initial begin + fork begin + fork begin #3; q[0]=1; end begin #4; q[1]=1; end join + q[2]=1; + end join_none + #1; disable fork; + wait fork; q[3]=1; + end +endmodule"#) + (top Top) (run_until 5) (assert_eq q 8)) + +(case cancelled_ids_can_be_reused_without_stale_wakeups + (source "disable_reuse.sv" #"module Top(output int q); + int n=20; + initial begin + q=0; + for (int i=0; i(mut sim: Simulation) { + sim.run_until(1).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + for _ in 0..3 { + sim.restore(&checkpoint).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + sim.run_until(7).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 3u8.into()); + } +} + +#[test] +fn checkpoint_replays_cancellation_join_and_id_reuse() { + let source = r#"`timescale 1ns/1ns +module Top(output bit [1:0] q); + initial begin + fork begin #4; q=2; end join_none + #2; disable fork; + fork begin #5; q[0]=1; end join_none + wait fork; + q[1]=1; + end +endmodule"#; + replay( + Simulation::from_sv_sources(vec![(source, Path::new("control.sv"))], "Top") + .build_interpreter() + .unwrap(), + ); + replay( + Simulation::from_sv_sources(vec![(source, Path::new("control.sv"))], "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native() + .unwrap(), + ); +} + +#[test] +fn checkpoint_preserves_wait_fork_membership() { + let source = r#"`timescale 1ns/1ns +module Top(output bit [2:0] q); + initial begin + fork begin #2; q[0]=1; end begin #4; q[1]=1; end join_none + wait fork; q[2]=1; + end +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("wait.sv"))], "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native() + .unwrap(); + sim.run_until(1).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + for _ in 0..3 { + sim.restore(&checkpoint).unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 7u8.into()); + } +} + +#[test] +fn disable_without_children_in_final_is_a_zero_time_noop() { + let source = r#"module Top(output int q); + initial q=1; + final begin disable fork; q=2; end +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("final.sv"))], "Top") + .build_native() + .unwrap(); + sim.run_until(0).unwrap(); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("q")), 2u8.into()); + assert_eq!(sim.time(), 0); +} + +#[test] +fn disable_without_activation_frames_preserves_other_process_wakeups() { + let source = r#"`timescale 1ns/1ns +module Top(output bit [1:0] q); + initial begin #1; disable fork; q[0]=1; end + initial begin #2; q[1]=1; end +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("empty.sv"))], "Top") + .scheduler_mode(SchedulerMode::Differential) + .build_native() + .unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 3u8.into()); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 048546111d6..b74b6f5a4b7 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -134,10 +134,19 @@ new storage. Static variables retain shared storage. Child random streams are seeded from the parent's stream. Execution uses the simulation scheduler, not one OS thread per child. +`wait fork` waits for all live immediate children of the calling process, +including earlier forks and children spawned by called tasks. It does not wait +for grandchildren whose parents have already ended (9.6.1). With no live children +it continues immediately. `disable fork` terminates all descendants, including +those of completed children, without stopping its caller or siblings (9.6.3). +It removes pending starts, event waits and scheduled resumptions; a subsequent +fork can reuse their activation storage. Calls through tasks and functions keep +the calling process's identity; `wait fork` remains forbidden in functions. + Checkpoints preserve children, their locals and pending joins. Layout-independent state files do not yet record dynamic activations and report an error; use `checkpoint()` / `restore()` instead. Forks in functions or final procedures, -`wait fork`, `disable fork`, deferred assertions in a process containing forks, +deferred assertions in a process containing forks, and compound event expressions reading fork-shared automatic locals remain unsupported. Direct event controls on those locals and `wait` conditions are supported.