From 6b7252fa636f15904de13d6ed490b62f58d736fd Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 15:10:30 +0900 Subject: [PATCH] feat(sv)!: execute fork branches as dynamic process activations SystemVerilog fork blocks were rejected. Lower fork/join, join_any and join_none into child entry points of stackless process kernels and schedule dynamic activations, starting children when their parent blocks or terminates. Give each activation private control, temporary and random state while sharing automatic lexical cells with its children. Preserve local lifetimes, nested and repeated forks, event waits, queued NBA captures, heap roots, checkpoint restoration and native image roundtrips. Terminate pending children on program $exit and preserve $stop/$finish behavior. Document current restrictions. Layout-independent state files reject dynamic activations explicitly; checkpoint/restore is supported. Follow-up work is tracked in #2111. Validation: - CI run 40278499596 executes 3,300 official mode runs: 12 fail-to-pass improvements, no regressions. Accept only these measured fork/block expectation rows (six cases in both state modes). - 16 shared cases pass in 96 backend configurations, including native/parallel/image roundtrip, Cranelift/parallel and WASM with a four-state regression. - Seven API tests pass, covering Interpreter, differential scheduling, checkpoints, stop/finish and program exit. The exit regression fails before the fix. - 946 library, 379 consumer, 961 timing and 18 final-procedure tests pass; existing ignores retained. Focused program revalidation passes 49 tests, and the parameter-override diagnostic regression passes. - Debug NAPI build and 28 JS boundary tests pass. Formatting, diff checks and affected-crate Clippy pass. - Icarus 13.0: 8 pass, 5 unsupported automatic-lifetime compilation errors, 3 internal aborts on detached automatic tasks. - Verilator 5.052: 14 pass, one unsupported four-state case, one NBA mismatch caused by a shared pending index/flag across coroutine activations. Expectations remain unchanged; full release-driver conformance is left to CI. BREAKING CHANGE: Process frame metadata and dynamic activation state extend the runtime/schema interfaces; native image format advances to version 40. Change-Id: I30dae837f9b9116374981790de83472a4e3a2313 --- conformance/sv-tests/expected.tsv | 24 +- crates/celox-design/src/lib.rs | 41 +++ crates/celox-design/src/schedule.rs | 5 +- crates/celox-frontend-core/src/process.rs | 35 ++ crates/celox-frontend-core/src/sdk.rs | 1 + .../src/symbolic/artifact.rs | 1 + .../src/symbolic/assembly.rs | 31 ++ crates/celox-frontend-sv/src/lowering.rs | 1 + crates/celox-frontend-sv/src/lowering/comb.rs | 1 + crates/celox-frontend-sv/src/lowering/ff.rs | 107 +++++- crates/celox-runtime/src/schedule.rs | 11 +- .../src/simulation/activation.rs | 321 ++++++++++++++++++ .../celox-runtime/src/simulation/compiled.rs | 1 + crates/celox-runtime/src/simulation/host.rs | 3 + crates/celox-runtime/src/simulation/mod.rs | 12 +- .../celox-runtime/src/simulation/persist.rs | 6 + .../celox-runtime/src/simulation/process.rs | 57 +++- .../celox-runtime/src/simulation/terminal.rs | 2 +- crates/celox-runtime/src/simulation/time.rs | 1 + crates/celox-runtime/src/simulation/wait.rs | 22 ++ crates/celox-runtime/src/timing.rs | 4 + .../src/ast/const_functions.rs | 2 +- crates/celox-sv-analyzer/src/ast/lifetimes.rs | 98 +++++- .../src/ast/procedural/control.rs | 83 +++++ .../celox-sv-analyzer/src/ast/validation.rs | 1 + crates/celox-sv-analyzer/src/procedural.rs | 24 ++ crates/celox-sv-analyzer/src/tests.rs | 12 +- .../celox-test-suite/src/sv/cases/fork.vtest | 220 ++++++++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + crates/celox/src/backend/native/backend.rs | 26 ++ crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 23 ++ crates/celox/src/simulator.rs | 2 + crates/celox/src/simulator/heap.rs | 9 +- crates/celox/src/simulator/state_file.rs | 5 +- .../tests/frontends/systemverilog/timing.rs | 23 +- crates/celox/tests/sv_fork_join.rs | 164 +++++++++ docs/guide/systemverilog-reference.md | 27 +- 38 files changed, 1354 insertions(+), 58 deletions(-) create mode 100644 crates/celox-runtime/src/simulation/activation.rs create mode 100644 crates/celox-test-suite/src/sv/cases/fork.vtest create mode 100644 crates/celox/tests/sv_fork_join.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 404b148ae0e..3b247a58676 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1583,24 +1583,24 @@ 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 -chapter-9/9.3.2--parallel_block_join.sv 4state fail -chapter-9/9.3.2--parallel_block_join_any.sv 2state fail -chapter-9/9.3.2--parallel_block_join_any.sv 4state fail -chapter-9/9.3.2--parallel_block_join_none.sv 2state fail -chapter-9/9.3.2--parallel_block_join_none.sv 4state fail -chapter-9/9.3.3--block_start_finish.sv 2state fail -chapter-9/9.3.3--block_start_finish.sv 4state fail +chapter-9/9.3.2--parallel_block_join.sv 2state pass +chapter-9/9.3.2--parallel_block_join.sv 4state pass +chapter-9/9.3.2--parallel_block_join_any.sv 2state pass +chapter-9/9.3.2--parallel_block_join_any.sv 4state pass +chapter-9/9.3.2--parallel_block_join_none.sv 2state pass +chapter-9/9.3.2--parallel_block_join_none.sv 4state pass +chapter-9/9.3.3--block_start_finish.sv 2state pass +chapter-9/9.3.3--block_start_finish.sv 4state pass chapter-9/9.3.3--event.sv 2state fail chapter-9/9.3.3--event.sv 4state fail chapter-9/9.3.3--fork_return.sv 2state pass chapter-9/9.3.3--fork_return.sv 4state pass -chapter-9/9.3.4--block_names_par.sv 2state fail -chapter-9/9.3.4--block_names_par.sv 4state fail +chapter-9/9.3.4--block_names_par.sv 2state pass +chapter-9/9.3.4--block_names_par.sv 4state pass chapter-9/9.3.4--block_names_seq.sv 2state pass chapter-9/9.3.4--block_names_seq.sv 4state pass -chapter-9/9.3.5--statement_labels_par.sv 2state fail -chapter-9/9.3.5--statement_labels_par.sv 4state fail +chapter-9/9.3.5--statement_labels_par.sv 2state pass +chapter-9/9.3.5--statement_labels_par.sv 4state pass chapter-9/9.3.5--statement_labels_seq.sv 2state pass chapter-9/9.3.5--statement_labels_seq.sv 4state pass chapter-9/9.4.1--delay_control-sim.sv 2state pass diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7cb6fdda1da..c8f08f14e9d 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -412,6 +412,14 @@ pub struct RuntimeErrorInfo { pub signals: Vec, } +/// When a parent resumes after creating concurrent children (IEEE 1800-2023 9.3.2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ForkJoin { + All, + Any, + None, +} + /// How a process kernel returned control to the runtime, as stored in its /// [`ProcessSlots::status`] slot. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -452,6 +460,10 @@ pub enum ProcessStatus { /// A program kernel called `$exit` (IEEE 1800-2023 24.7): it and every /// other kernel of its program instance ([`ProcessSlots::program`]) end. Exit, + /// Create child activations. The delay slot encodes their entry points and join mode. + Fork, + /// Allocate a fresh automatic local cell before its declaration initializer. + Local, } impl ProcessStatus { @@ -470,6 +482,8 @@ impl ProcessStatus { Self::Stop => 9, Self::HostRequest => 10, Self::Exit => 11, + Self::Fork => 12, + Self::Local => 13, } } @@ -486,6 +500,8 @@ impl ProcessStatus { 9 => Some(Self::Stop), 10 => Some(Self::HostRequest), 11 => Some(Self::Exit), + 12 => Some(Self::Fork), + 13 => Some(Self::Local), _ => None, } } @@ -627,6 +643,29 @@ pub enum ProcessKind { Final, } +/// Storage switched when several activations execute the same kernel. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProcessFrame { + /// Compiler temporaries and control slots private to each activation. + pub private: Vec, + /// Automatic locals shared with children until the declaration is re-entered. + pub locals: Vec, + pub random: A, + pub seed: u32, + pub starts_with_event_wait: bool, +} +impl ProcessFrame { + pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessFrame { + ProcessFrame { + private: self.private.into_iter().map(&mut map).collect(), + locals: self.locals.into_iter().map(&mut map).collect(), + random: map(self.random), + seed: self.seed, + starts_with_event_wait: self.starts_with_event_wait, + } + } +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to @@ -1034,6 +1073,7 @@ pub struct RuntimeSchema { pub processes: Vec>, /// Source procedures of the process kernels, in kernel order. pub process_origins: Vec, + pub process_frames: Vec>>, /// Counted signals and their occurrence counters. pub watches: Vec>, /// Bit ranges whose changes bump an occurrence counter: the sensitivity @@ -1302,6 +1342,7 @@ impl Default for RuntimeSchema { live_signals: HashSet::default(), processes: Vec::new(), process_origins: Vec::new(), + process_frames: Vec::new(), watches: Vec::new(), occurrence_probes: Vec::new(), wait_sites: Vec::new(), diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index fa96b6ed9e5..bbe9a4a74fe 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -63,6 +63,7 @@ pub struct CountedModel { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ProcessModel { pub slots: ProcessSlots, + pub frame: Option>, pub waits: Vec>>, pub nbas: Vec>, pub host_requests: Vec>, @@ -101,7 +102,9 @@ impl ScheduleModel { let mut processes: Vec> = schema .processes .iter() - .map(|slots| ProcessModel { + .enumerate() + .map(|(index, slots)| ProcessModel { + frame: schema.process_frames.get(index).cloned().flatten(), slots: *slots, waits: Vec::new(), nbas: Vec::new(), diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index a67dbcf8eb8..2d382987de9 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -192,6 +192,36 @@ impl ProcessKernelBuilder { self.suspend(ProcessStatus::Yield) } + /// Reserve one entry point for each child, then return to the runtime to spawn them. + /// The caller lowers each child into its entry block and ends it with `complete`. + pub fn fork( + &mut self, + count: usize, + join: celox_design::ForkJoin, + ) -> Result<(Vec, BlockId), ProcessKernelError> { + let first = self.resume_blocks.len(); + if first + count > MAX_PROCESS_SUSPENSIONS { + return Err(ProcessKernelError::TooManySuspensions); + } + let children: Vec<_> = (0..count).map(|_| self.builder.new_block()).collect(); + self.resume_blocks.extend(children.iter().copied()); + let mode = match join { + celox_design::ForkJoin::All => 0u64, + celox_design::ForkJoin::Any => 1, + celox_design::ForkJoin::None => 2, + }; + self.store_delay_constant(first as u64 | ((count as u64) << 16) | (mode << 32)); + self.slots.const_delays = false; + self.slots.requires_timed_simulation = true; + self.suspend(ProcessStatus::Fork)?; + Ok((children, self.builder.current_block())) + } + + pub fn local(&mut self, slot: usize) -> Result<(), ProcessKernelError> { + self.store_delay_constant(slot as u64); + self.suspend(ProcessStatus::Local) + } + /// Suspend the simulation (`$stop`), and continue at a new resume point /// when it continues. pub fn stop(&mut self) -> Result<(), ProcessKernelError> { @@ -379,6 +409,11 @@ impl ProcessKernelBuilder { Ok(()) } + /// End only this activation, notifying a waiting fork parent. + pub fn complete(&mut self) { + self.end(ProcessStatus::Done); + } + /// End the simulation. No block is open afterwards. pub fn finish(&mut self) { self.wait_site = None; diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index c5c89c1135f..978966f9d2f 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1754,6 +1754,7 @@ fn lower_processes( stable_signal(address, artifact.signals().len()) })); processes.push(SymbolicProcess { + frame: None, kernel, slots, origin: celox_design::ProcessOrigin { diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 80dffff18d2..13d9d614ced 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -54,6 +54,7 @@ impl FfPart { pub struct SymbolicProcess { pub kernel: ExecutionUnit, pub slots: ProcessSlots, + pub frame: Option>, pub origin: celox_design::ProcessOrigin, } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index aa5104fcb87..e87368905cc 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2122,10 +2122,12 @@ pub fn schedule_symbolic_rtl_reporting_loops( } let mut process_kernels = Vec::with_capacity(processes.len()); let mut process_slots = Vec::with_capacity(processes.len()); + let mut process_frames = Vec::with_capacity(processes.len()); let mut process_origins = Vec::with_capacity(processes.len()); for process in processes { process_kernels.push(process.kernel); process_slots.push(process.slots); + process_frames.push(process.frame); process_origins.push(process.origin); } let TimingMetadata { @@ -2333,6 +2335,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } + let process_frames: Vec<_> = process_frames + .into_iter() + .map(|frame| frame.map(|frame| frame.map(project))) + .collect(); let process_slots = process_slots .into_iter() .map(|slots| slots.map(project)) @@ -2464,6 +2470,13 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) .collect(); // The runtime counts the occurrences its own writes cause. + timing_read_roots.extend( + process_frames + .iter() + .flatten() + .flat_map(|frame| frame.private.iter().chain(&frame.locals)) + .copied(), + ); timing_read_roots.extend( occurrence_probes .iter() @@ -2538,6 +2551,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( declaration_startup, dead_store_policy: Default::default(), live_signals: Default::default(), + process_frames, processes: process_slots, process_origins, watches, @@ -3948,6 +3962,10 @@ fn relocate_units( &extern_function_map, ), slots: process.slots.map(|var_id| bindings.locate(*id, var_id)), + frame: process + .frame + .clone() + .map(|frame| frame.map(|var_id| bindings.locate(*id, var_id))), origin: celox_design::ProcessOrigin { scope: Some(scope.clone()), ..process.origin.clone() @@ -4079,6 +4097,7 @@ fn relocate_units( struct RelocatedProcess { kernel: ExecutionUnit, slots: ProcessSlots, + frame: Option>, origin: celox_design::ProcessOrigin, /// The instance and the module-local index of the process. key: (InstanceId, usize), @@ -4284,6 +4303,18 @@ fn select_nba_paths( staged: &HashSet, processes: &mut [RelocatedProcess], ) { + let mut staged = staged.clone(); + // Fork activations can reach one NBA site concurrently. Always queue its + // captured value, rather than leaving one shared pending slot per kernel. + for site in &timing.nba_sites { + if processes[site.process].frame.is_some() { + for switch in &timing.nba_switches { + if switch.value == site.value { + staged.remove(&switch.switch); + } + } + } + } let switches: HashMap> = timing .nba_switches .iter() diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 11a49c86e24..f03fd8c924f 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5230,6 +5230,7 @@ fn lower_initial_processes( })); Ok(SymbolicProcess { kernel: kernel.unit, + frame: kernel.frame, slots: kernel.slots, origin: process_origin(process), }) diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index a7a1d8c72ba..3f3e7324f06 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2026,6 +2026,7 @@ 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::Assign { lhs, rhs, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 091ffbfa863..e063153f265 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -84,6 +84,8 @@ pub(super) struct Ff<'p, 'a> { /// body is lowered, and the process reads and writes stable state /// directly. kernel: Option, + forked: bool, + frame_locals: Vec, /// The index of the process being lowered among the module's kernels. process: usize, /// The wait sites of the process, by local index. @@ -149,6 +151,8 @@ impl<'p, 'a> Ff<'p, 'a> { random_seed, dist_seed: None, kernel: None, + forked: false, + frame_locals: Vec::new(), direct: false, input_occurrences: true, process: 0, @@ -3010,11 +3014,46 @@ impl<'p, 'a> Ff<'p, 'a> { self.wait_level(condition)?; Ok(true) } + sv::ir::Stmt::Fork { join, branches } => { + if self.kernel.is_none() { + return Err(unsupported("fork outside a timed process")); + } + self.forked = true; + let (entries, continuation) = self + .with_kernel(|kernel| kernel.fork(branches.len(), *join)) + .map_err(kernel_error)?; + self.b.seal_block(SIRTerminator::Return); + let loops = std::mem::take(&mut self.loops); + let functions = std::mem::take(&mut self.functions); + let overlay = std::mem::take(&mut self.overlay); + for (entry, branch) in entries.into_iter().zip(branches) { + self.b.switch_to_block(entry); + if self.exec_block(branch)? { + self.with_kernel(ProcessKernelBuilder::complete); + } + } + self.loops = loops; + self.functions = functions; + self.overlay = overlay; + self.b.switch_to_block(continuation); + Ok(true) + } sv::ir::Stmt::Local { name, init } => { let id = self .m .id(name) .ok_or_else(|| unsupported(format!("local `{name}`")))?; + if self.forked && self.kernel.is_some() { + let slot = match self.frame_locals.iter().position(|&local| local == id) { + Some(slot) => slot, + None => { + self.frame_locals.push(id); + self.frame_locals.len() - 1 + } + }; + self.with_kernel(|kernel| kernel.local(slot)) + .map_err(kernel_error)?; + } match init { Some(init) => self.assign(&sv::ir::LValue::Ident(name.clone()), init)?, None => self.init_default(id), @@ -3836,6 +3875,12 @@ impl<'p, 'a> Ff<'p, 'a> { self.element_widths.insert(working(copy), width); } self.m.name_to_id.insert(name.clone(), copy); + if self.forked { + let slot = self.frame_locals.len(); + self.frame_locals.push(copy); + self.with_kernel(|kernel| kernel.local(slot)) + .map_err(kernel_error)?; + } activation.push((name.clone(), original)); } } @@ -5175,7 +5220,40 @@ impl Ff<'_, '_> { process: usize, ) -> Result { self.process = process; + let starts_with_event_wait = slots.requires_timed_simulation; + let first_created = self.m.created.len(); + fn has_fork( + m: &ProcModule<'_>, + body: &[sv::ir::Stmt], + visited: &mut HashSet, + ) -> bool { + let mut found = false; + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Fork { .. } => found = true, + sv::ir::Stmt::Call { name, .. } => calls.push(name.clone()), + _ => {} + }); + } + found + || calls.into_iter().any(|name| { + visited.insert(name.clone()) + && m.subroutine(&name) + .is_some_and(|sub| has_fork(m, &sub.body, visited)) + }) + } + self.forked = has_fork(self.m, body, &mut HashSet::default()); + // Forks reached through inlined tasks also need per-activation random state. + if self.forked { + self.urandom_state(); + } let mut kernel = ProcessKernelBuilder::new(slots); + if self.forked && self.has_deferred_assertions(body, &mut HashSet::default()) { + return Err(unsupported( + "deferred assertions in a process with fork-join", + )); + } if let Some(site) = self.deferred_flush_site(body) { kernel.flush_deferred_at(site); } @@ -5187,7 +5265,21 @@ impl Ff<'_, '_> { let slots = kernel.slots(); let mut unit = kernel.build(); prune_unreachable_blocks(&mut unit); + let frame = self.forked.then(|| { + let mut private = self.m.created[first_created..].to_vec(); + private.extend([slots.resume, slots.status, slots.delay]); + private + .retain(|id| !self.frame_locals.contains(id) && Some(*id) != self.m.id(TIME_SLOT)); + celox_design::ProcessFrame { + private, + locals: self.frame_locals, + random: self.random.as_ref().unwrap().0, + seed: self.random_seed, + starts_with_event_wait, + } + }); Ok(KernelUnit { + frame, unit, slots, wait_sites: self.wait_sites, @@ -5844,7 +5936,12 @@ impl Ff<'_, '_> { } let id = match &expr { sv::ir::Expr::Ident(name) => match self.m.id(name) { - Some(id) if !self.m.is_hidden(id) => id, + Some(id) + if !self.m.is_hidden(id) + || (self.forked && self.frame_locals.contains(&id)) => + { + id + } Some(_) => self.event_expression(&expr, samples)?, // A constant never changes. None if self.m.constants.contains_key(name) => continue, @@ -5927,6 +6024,11 @@ impl Ff<'_, '_> { }) .collect(); locals.sort_unstable(); + if self.forked && locals.iter().any(|(_, id)| self.frame_locals.contains(id)) { + return Err(unsupported( + "compound event expression reading a fork-shared automatic variable", + )); + } // Another call can copy a new argument into a static formal while // the process waits, which a copy taken now would not see. if locals.iter().any(|&(_, id)| self.is_static_task_formal(id)) { @@ -6019,7 +6121,7 @@ impl Ff<'_, '_> { let mut ids: Vec<_> = names .iter() .filter_map(|name| self.m.id(name)) - .filter(|&id| !self.m.is_hidden(id)) + .filter(|&id| !self.m.is_hidden(id) || (self.forked && self.frame_locals.contains(&id))) .collect(); ids.sort_unstable(); ids.dedup(); @@ -6108,6 +6210,7 @@ impl Ff<'_, '_> { pub(super) struct KernelUnit { pub unit: ExecutionUnit, pub slots: ProcessSlots, + pub frame: Option>, pub wait_sites: Vec>, pub nba_sites: Vec>, pub host_request_sites: Vec>, diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 99e07af4d2a..436f3c1fc08 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -198,10 +198,19 @@ impl ResolvedSchedule { .processes .iter() .map(|process| ProcessRefs { + frame: process + .frame + .clone() + .map(|frame| frame.map(|id| resolve(&id))), 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, + starts_with_event_wait: process + .frame + .as_ref() + .map_or(process.slots.requires_timed_simulation, |frame| { + frame.starts_with_event_wait + }), status: resolve(&process.slots.status), delay: resolve(&process.slots.delay), wait_sites: process diff --git a/crates/celox-runtime/src/simulation/activation.rs b/crates/celox-runtime/src/simulation/activation.rs new file mode 100644 index 00000000000..401dbbd316e --- /dev/null +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -0,0 +1,321 @@ +//! Dynamic executions of a stackless kernel. Forks share lexical cells, but +//! each child owns its control slots and compiler temporaries. +use super::{SimulationState, wait::wake_in_region}; +use crate::{ + SignalRef, SimulatorErrorCode, + backend::SimBackend, + timing::{Halt, Value, read}, +}; +use celox_design::ForkJoin; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Activation { + pub kernel: usize, + pub parent: Option, + pub private: Vec, + pub locals: Vec>, + pub live: bool, + pub pending: Vec, + pub join: Option<(ForkJoin, Vec)>, +} +impl Activation { + fn root(kernel: usize) -> Self { + Self { + kernel, + parent: None, + private: Vec::new(), + locals: Vec::new(), + live: true, + pending: Vec::new(), + join: None, + } + } +} +fn write(backend: &mut B, signal: SignalRef, value: &Value) { + backend.set_four_state(signal, value.0.clone(), value.1.clone()); +} +impl SimulationState { + pub(super) fn restore_activation(&mut self, backend: &mut B, process: usize) -> usize { + if self.process_state.activations.is_empty() { + if !self.model.processes.iter().any(|p| p.frame.is_some()) { + return process; + } + self.process_state.activations = (0..self.kernel_count).map(Activation::root).collect(); + } + let activation = &mut self.process_state.activations[process]; + if let Some(frame) = &self.model.processes[process].frame { + if activation.private.is_empty() { + activation.private = frame + .private + .iter() + .map(|&slot| read(backend, slot)) + .collect(); + activation.locals.resize(frame.locals.len(), None); + } else { + for (&slot, value) in frame.private.iter().zip(&activation.private) { + write(backend, slot, value); + } + } + for (&slot, cell) in frame.locals.iter().zip(&activation.locals) { + if let Some(cell) = cell { + write(backend, slot, &self.process_state.cells[*cell]); + } + } + } + activation.kernel + } + + pub(super) fn save_activation(&mut self, backend: &B, process: usize) { + let Some(frame) = &self.model.processes[process].frame else { + return; + }; + let activation = &mut self.process_state.activations[process]; + for (&slot, value) in frame.private.iter().zip(&mut activation.private) { + *value = read(backend, slot); + } + for (&slot, cell) in frame.locals.iter().zip(&activation.locals) { + if let Some(cell) = cell { + self.process_state.cells[*cell] = read(backend, slot); + } + } + } + + pub(super) fn allocate_local(&mut self, process: usize, index: usize) -> Result<(), Halt> { + if self.model.processes[process].frame.is_none() { + return Ok(()); + } + if self.process_state.cells.len() >= 1024 + && self.process_state.cells.len().is_multiple_of(1024) + { + self.collect_activation_cells(); + } + let locals = &mut self.process_state.activations[process].locals; + let target = locals + .get_mut(index) + .ok_or(SimulatorErrorCode::InternalError)?; + *target = Some(self.process_state.cells.len()); + self.process_state.cells.push(Value::default()); + Ok(()) + } + + pub(super) fn fork_activation( + &mut self, + backend: &mut B, + process: usize, + encoded: u64, + ) -> Result { + let first = (encoded & 0xffff) as usize; + let count = ((encoded >> 16) & 0xffff) as usize; + let join = match encoded >> 32 { + 0 => ForkJoin::All, + 1 => ForkJoin::Any, + 2 => ForkJoin::None, + _ => return Err(SimulatorErrorCode::InternalError.into()), + }; + self.save_activation(backend, process); + let frame = self.model.processes[process] + .frame + .as_ref() + .ok_or(SimulatorErrorCode::InternalError)?; + let resume = frame + .private + .iter() + .position(|slot| *slot == self.model.processes[process].resume) + .ok_or(SimulatorErrorCode::InternalError)?; + let status = frame + .private + .iter() + .position(|slot| *slot == self.model.processes[process].status) + .ok_or(SimulatorErrorCode::InternalError)?; + let random_slot = frame.random; + let random = frame + .private + .iter() + .position(|slot| *slot == random_slot) + .ok_or(SimulatorErrorCode::InternalError)?; + let raw = backend.get_as::(random_slot); + let mut seed = if raw == 0 { frame.seed } else { raw as u32 }; + let mut children = Vec::with_capacity(count); + for entry in first..first + count { + let mut child = self.process_state.activations[process].clone(); + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + child.private[random] = ((u64::from(seed) | (1 << 32)).into(), 0u8.into()); + child.parent = Some(process); + child.pending.clear(); + child.join = None; + child.private[resume] = ((entry as u64).into(), 0u8.into()); + child.private[status] = (0u8.into(), 0u8.into()); + let reusable = (self.kernel_count..self.process_state.activations.len()).find(|&id| { + !self.process_state.activations[id].live + && !self + .process_state + .activations + .iter() + .any(|a| a.parent == Some(id)) + }); + let id = reusable.unwrap_or(self.process_state.activations.len()); + if id == self.process_state.activations.len() { + self.process_state.activations.push(child); + self.model + .processes + .push(self.model.processes[process].clone()); + } else { + self.process_state.activations[id] = child; + self.model.processes[id] = self.model.processes[process].clone(); + } + children.push(id); + } + if count != 0 { + backend.set(random_slot, u64::from(seed) | (1 << 32)); + } + self.process_state.activations[process] + .pending + .extend(&children); + if join == ForkJoin::None || children.is_empty() { + return Ok(true); + } + self.process_state.activations[process].join = Some((join, children)); + Ok(false) + } + + /// A real HDL suspension or termination starts the children created since + /// the last such boundary. Host requests, NBA staging and budget yields do not. + pub(super) fn release_children(&mut self, process: usize) { + if self.process_state.activations.is_empty() { + return; + } + let pending = std::mem::take(&mut self.process_state.activations[process].pending); + for child in pending { + let state = &mut self.process_state; + wake_in_region( + &self.model.processes, + &mut state.ready, + &mut state.reactive, + child, + ); + } + } + + pub(super) fn end_activation(&mut self, process: usize) { + if self.process_state.activations.is_empty() + || self.model.processes[process].frame.is_none() + { + return; + } + self.process_state.activations[process].live = false; + if let Some(parent) = self.process_state.activations[process].parent { + let parent = &mut self.process_state.activations[parent]; + if let Some((join, children)) = &mut parent.join { + let member = children.contains(&process); + children.retain(|&child| child != process); + if member && (*join == ForkJoin::Any || children.is_empty()) { + parent.join = None; + let id = self.process_state.activations[process].parent.unwrap(); + let state = &mut self.process_state; + wake_in_region( + &self.model.processes, + &mut state.ready, + &mut state.reactive, + id, + ); + } + } + } + } + + pub(super) fn retire_activation(&mut self, process: usize) { + let mut next = Some(process); + while let Some(id) = next { + let has_children = self + .process_state + .activations + .iter() + .any(|child| child.parent == Some(id)); + let Some(activation) = self.process_state.activations.get_mut(id) else { + break; + }; + if activation.live { + break; + } + activation.private.clear(); + activation.locals.clear(); + if has_children { + break; + } + next = activation.parent.take(); + } + } + + fn collect_activation_cells(&mut self) { + let state = &mut self.process_state; + let mut mapping = vec![None; state.cells.len()]; + let mut cells = Vec::new(); + for activation in &mut state.activations { + for cell in activation.locals.iter_mut().flatten() { + let new = *mapping[*cell].get_or_insert_with(|| { + cells.push(state.cells[*cell].clone()); + cells.len() - 1 + }); + *cell = new; + } + } + state.cells = cells; + } + + /// Keep heap handles stored outside the backend memory alive at host safepoints. + pub fn retain_activation_roots>( + &self, + executor: &mut E, + ) { + let mut values = Vec::new(); + for (id, activation) in self.process_state.activations.iter().enumerate() { + if !activation.live { + continue; + } + if let Some(frame) = &self.model.processes[id].frame { + values.extend( + frame + .private + .iter() + .copied() + .zip(activation.private.iter().cloned()), + ); + values.extend(frame.locals.iter().zip(&activation.locals).filter_map( + |(&slot, cell)| cell.map(|cell| (slot, self.process_state.cells[cell].clone())), + )); + } + } + executor.retain_process_values(&values); + } + + pub(super) fn rebuild_activation_models(&mut self) { + self.model.processes.truncate(self.kernel_count); + for index in 0..self.process_state.activations.len() { + let kernel = self.process_state.activations[index].kernel; + if index == self.model.processes.len() { + self.model + .processes + .push(self.model.processes[kernel].clone()); + } + } + } +} + +pub(super) fn activation_value<'a>( + activations: &'a [Activation], + cells: &'a [Value], + refs: &crate::timing::ProcessRefs, + process: usize, + signal: SignalRef, +) -> Option<&'a Value> { + let frame = refs.frame.as_ref()?; + let activation = activations.get(process)?; + if let Some(index) = frame.locals.iter().position(|&slot| slot == signal) { + return activation.locals.get(index)?.map(|cell| &cells[cell]); + } + frame + .private + .iter() + .position(|&slot| slot == signal) + .and_then(|index| activation.private.get(index)) +} diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 852dd20dd2e..df6c6b04732 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -412,6 +412,7 @@ impl SimulationState { return Err(SimulatorErrorCode::InternalError.into()); } } + self.retain_activation_roots(executor); executor.try_finish_timed_step(now)?; // What the host writes after the slot is an update of its time. if executor.take_slot_writes() { diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index 5e31cbfa1c6..e2c753c4181 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -125,6 +125,9 @@ pub trait HostBoundary: UnitExecutor { CompiledSlots::None } + /// Live values kept in dynamic process frames, outside backend state memory. + fn retain_process_values(&mut self, _values: &[(crate::SignalRef, crate::timing::Value)]) {} + /// Called after the state for a simulation timestamp has stabilized. fn finish_timed_step(&mut self, _timestamp: u64) {} diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index a0e68d89208..0a57c8a08b0 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -1,6 +1,8 @@ //! The timed scheduler: time slots, rounds, the process phase and the //! batch step of designs without processes. +mod activation; +pub use activation::Activation; mod batch; mod compiled; mod edges; @@ -136,8 +138,9 @@ pub struct SimulationState { /// The design keeps unknown bits, so edges follow the four-state rows /// of IEEE 1800-2023 Table 9-2. four_state: bool, - /// The design's scheduling facts, which never change. + /// Scheduling facts, including descriptors for dynamically spawned processes. model: ResolvedSchedule, + kernel_count: usize, process_wakeups: BinaryHeap, process_state: ProcessState, declaration_processes: Vec, @@ -210,6 +213,7 @@ impl SimulationState { .filter(|&index| model.processes[index].kind != celox_design::ProcessKind::Final) .map(|process| Reverse((0, process))) .collect(), + kernel_count: model.processes.len(), model, process_state, declaration_processes, @@ -407,6 +411,11 @@ impl SimulationState { self.host_pending } + /// Whether runtime-owned activation storage needs a same-design checkpoint. + pub fn has_fork_activations(&self) -> bool { + !self.process_state.activations.is_empty() + } + /// Set whether the next step settles host changes at the current time /// first, as when copying another simulation's state. #[doc(hidden)] @@ -424,6 +433,7 @@ impl SimulationState { where E: SimulationExecutor, { + self.retain_activation_roots(executor); match executor.try_finish_timed_step(time) { Ok(()) => Ok(()), Err(Halt::Error(error)) => { diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index d652d9f9e82..5da0c2a960b 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -61,6 +61,7 @@ impl SimulationState { .clone_from(&snapshot.last_clock_unknown); self.process_wakeups.clone_from(&snapshot.process_wakeups); self.process_state.clone_from(&snapshot.process_state); + self.rebuild_activation_models(); self.declarations_pending = snapshot.declarations_pending; self.host_pending = snapshot.host_pending; self.finished = snapshot.finished; @@ -192,6 +193,7 @@ impl SimulationState { .map(|(process, time)| Reverse((time, process))) .collect(); self.process_state = parts.process_state; + self.rebuild_activation_models(); 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| { @@ -298,6 +300,8 @@ impl SimulationState { re_inactive: state.re_inactive.iter().copied().collect(), re_nba_queue: state.re_nba_queue.clone(), domain_counters: state.domain_counters.clone(), + activations: state.activations.clone(), + cells: state.cells.clone(), declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, @@ -328,6 +332,8 @@ pub struct ScheduleKey { pub re_inactive: Vec, pub re_nba_queue: Vec, pub domain_counters: Vec<[u32; 3]>, + pub activations: Vec, + pub cells: Vec, pub declarations_pending: bool, pub host_pending: bool, pub finished: bool, diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index e8a7324dabd..eb6b0b2684e 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -124,11 +124,32 @@ impl SimulationState { process: usize, returns: &mut u64, ) -> Result + where + E: SimulationExecutor, + { + let kernel = self.restore_activation(executor.backend_mut(), process); + let result = self.run_activation(executor, current_time, process, kernel, returns); + self.save_activation(executor.backend(), process); + if matches!(result, Ok(false)) { + self.release_children(process); + } + self.retire_activation(process); + result + } + + fn run_activation( + &mut self, + executor: &mut E, + current_time: u64, + process: usize, + kernel: usize, + returns: &mut u64, + ) -> Result where E: SimulationExecutor, { { - executor.run_process(process)?; + executor.run_process(kernel)?; let status: u8 = executor .backend() .get_as(self.model.processes[process].status); @@ -155,6 +176,7 @@ impl SimulationState { } } Some(ProcessStatus::Done) => { + self.end_activation(process); if self.model.processes[process].program.is_some() { self.program_kernel_ended(executor.backend())?; } @@ -168,6 +190,17 @@ impl SimulationState { let site = delay() as usize; self.register_waiter(executor.backend(), process, site)?; } + Some(ProcessStatus::Fork) => { + let encoded = delay(); + *returns += 1; + self.charge(*returns, Some(process))?; + return self.fork_activation(executor.backend_mut(), process, encoded); + } + Some(ProcessStatus::Local) => { + let index = delay() as usize; + self.allocate_local(process, index)?; + return Ok(true); + } Some(ProcessStatus::Nba) => { let site = delay() as usize; self.queue_nba(executor.backend_mut(), process, site)?; @@ -278,12 +311,17 @@ impl SimulationState { let program = self.model.processes[process] .program .ok_or(SimulatorErrorCode::InternalError)?; - for &index in &self.model.program_processes { + for index in 0..self.model.processes.len() { let refs = &self.model.processes[index]; if refs.program != Some(program) { continue; } backend.set(refs.status, ProcessStatus::Done.code()); + if let Some(activation) = self.process_state.activations.get_mut(index) { + activation.live = false; + activation.pending.clear(); + activation.join = None; + } let state = &mut self.process_state; state.waiters.remove(index); state.ready.remove(&index); @@ -302,11 +340,16 @@ impl SimulationState { /// ends with an implicit `$finish` (IEEE 1800-2023 24.3). fn program_kernel_ended(&self, backend: &B) -> Result<(), Halt> { let done = ProcessStatus::Done.code(); - let all_done = self - .model - .program_processes - .iter() - .all(|&process| backend.get_as::(self.model.processes[process].status) == done); + let all_done = self.model.program_processes.iter().all(|&process| { + self.process_state + .activations + .get(process) + .filter(|_| self.model.processes[process].frame.is_some()) + .map_or_else( + || backend.get_as::(self.model.processes[process].status) == done, + |activation| !activation.live, + ) + }); if all_done { Err(Halt::Finish) } else { Ok(()) } } diff --git a/crates/celox-runtime/src/simulation/terminal.rs b/crates/celox-runtime/src/simulation/terminal.rs index 8d2553e935d..0681a7d80f1 100644 --- a/crates/celox-runtime/src/simulation/terminal.rs +++ b/crates/celox-runtime/src/simulation/terminal.rs @@ -84,7 +84,7 @@ 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) => {} + Some(ProcessStatus::Yield | ProcessStatus::Nba | ProcessStatus::Local) => {} _ => { return Err(SimulatorErrorCode::Runtime { message: "final procedure cannot suspend for HDL timing".into(), diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 89f621c1e8d..a48ba7bd963 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -205,6 +205,7 @@ impl SimulationState { self.charge_pass()?; self.step_round(executor, current_time, Vec::new(), ready, false, false)?; } + self.retain_activation_roots(executor); executor.try_finish_timed_step(current_time)?; // What the host writes after the slot is an update of its time. if executor.take_slot_writes() { diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index d9f4c083796..7c23f974f2e 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -35,6 +35,7 @@ impl SimulationState { .get(site) .ok_or_else(|| Self::site_error(process, site))?; let driven = terms.iter().any(|term| term.driven); + let frame = &self.model.processes[process].frame; self.process_state .waiters .register(process, driven, |waiter| { @@ -48,6 +49,12 @@ impl SimulationState { .extend(terms.iter().map(|_| Baseline::Value(Value::default()))); } for (term, baseline) in terms.iter().zip(&mut waiter.baselines) { + if frame.as_ref().is_some_and(|frame| { + frame.locals.contains(&term.signal) || frame.private.contains(&term.signal) + }) { + *baseline = Baseline::Value(read(backend, term.signal)); + continue; + } match term.counter { Some(counter) => { let seen = backend.get_as(counter); @@ -154,6 +161,8 @@ impl SimulationState { waiters, ready, reactive, + activations, + cells, .. } = &mut self.process_state; waiters.retain(driven_only, |process, waiter| { @@ -165,6 +174,19 @@ impl SimulationState { continue; } let baseline = &mut waiter.baselines[index]; + if let Some(value) = super::activation::activation_value( + activations, + cells, + &processes[process], + process, + term.signal, + ) { + if let Baseline::Value(last) = baseline { + wake |= occurs(term.kind, last, value); + *last = value.clone(); + continue; + } + } // The common term: a plain signal no counter counts. if let Baseline::Raw(last) = baseline { let now = state.planes(term.signal).expect("a plain signal"); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 20cdc112493..63478460d29 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -153,6 +153,7 @@ pub struct NbaSiteRefs { /// Control slots and sites of one process kernel. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { + pub frame: Option>, 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 @@ -175,6 +176,7 @@ impl ProcessRefs { /// A process without wait or nonblocking sites. pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { + frame: None, kind: celox_design::ProcessKind::Regular, program: None, resume: status, @@ -330,6 +332,8 @@ pub fn planes_occur(kind: CounterKind, old: &[u8], new: &[u8], width: usize) -> /// assignments. All of it is empty in a design without process kernels. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ProcessState { + pub activations: Vec, + pub cells: Vec, /// Processes suspended at a wait. pub waiters: Waiters, /// Processes ready to run in the active region of the current time. diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index a30bc59d28b..7235a522ed1 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -1402,7 +1402,7 @@ impl Frame<'_> { Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { return None; } - Stmt::AssignConcat { .. } | Stmt::Call { .. } => return None, + Stmt::Fork { .. } | 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 884c9ebcffe..1bf88b7c1f5 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -43,6 +43,10 @@ pub(super) fn keep_static_locals<'b, T>( return Ok((kept, initializers)); } for body in bodies { + let mut concurrent = false; + for stmt in body.iter() { + stmt.walk(&mut |stmt| concurrent |= matches!(stmt, Stmt::Fork { .. })); + } keep_in( state, body, @@ -50,6 +54,7 @@ pub(super) fn keep_static_locals<'b, T>( directions, &mut kept, &mut initializers, + concurrent, )?; } Ok((kept, initializers)) @@ -62,19 +67,21 @@ fn keep_in( directions: &Directions, kept: &mut Vec, initializers: &mut Vec, + concurrent: bool, ) -> Result<(), AnalyzerError> { let mut index = 0; while index < stmts.len() { if let Stmt::Local { name, init } = &stmts[index] && statics.contains_key(name) - && entry( - state, - name, - init.as_ref(), - &stmts[index + 1..], - directions, - &HashMap::default(), - )? == Entry::Observed + && (concurrent + || entry( + state, + name, + init.as_ref(), + &stmts[index + 1..], + directions, + &HashMap::default(), + )? == Entry::Observed) { let Stmt::Local { name, init } = stmts.remove(index) else { unreachable!("the statement is a local declaration"); @@ -95,8 +102,24 @@ fn keep_in( else_body, .. } => { - keep_in(state, then_body, statics, directions, kept, initializers)?; - keep_in(state, else_body, statics, directions, kept, initializers)?; + keep_in( + state, + then_body, + statics, + directions, + kept, + initializers, + concurrent, + )?; + keep_in( + state, + else_body, + statics, + directions, + kept, + initializers, + concurrent, + )?; } Stmt::Case { items, default, .. } => { for item in items { @@ -107,18 +130,56 @@ fn keep_in( directions, kept, initializers, + concurrent, )?; } if let Some(default) = default { - keep_in(state, default, statics, directions, kept, initializers)?; + keep_in( + state, + default, + statics, + directions, + kept, + initializers, + concurrent, + )?; } } Stmt::Loop { init, step, body, .. } => { - keep_in(state, init, statics, directions, kept, initializers)?; - keep_in(state, step, statics, directions, kept, initializers)?; - keep_in(state, body, statics, directions, kept, initializers)?; + keep_in( + state, + init, + statics, + directions, + kept, + initializers, + concurrent, + )?; + keep_in( + state, + step, + statics, + directions, + kept, + initializers, + concurrent, + )?; + keep_in( + state, + body, + statics, + directions, + kept, + initializers, + concurrent, + )?; + } + Stmt::Fork { branches, .. } => { + for branch in branches { + keep_in(state, branch, statics, directions, kept, initializers, true)?; + } } _ => {} } @@ -550,6 +611,13 @@ impl Flow<'_> { Ok(Exits::next(written)) } } + Stmt::Fork { branches, .. } => { + for branch in branches { + self.block(branch, written)?; + } + // A sibling's write need not precede another sibling's read. + Ok(Exits::next(written)) + } Stmt::Break => Ok(Exits { breaks: Some(written), ..Exits::default() @@ -761,7 +829,7 @@ 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::WaitImplicit(_) | Stmt::Break | Stmt::Continue => Vec::new(), + Stmt::Fork { .. } | Stmt::WaitImplicit(_) | Stmt::Break | Stmt::Continue => Vec::new(), } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index a5d8c5c49c5..4b9619346cd 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -21,6 +21,19 @@ struct CaseState { enum Job { Enter(StatementId), EndScope, + ForkNext { + items: Vec, + index: usize, + join: celox_design::ForkJoin, + branches: Vec>, + }, + ForkBranch { + items: Vec, + index: usize, + join: celox_design::ForkJoin, + branches: Vec>, + start: usize, + }, IfNext(IfState), IfBranch { state: IfState, @@ -118,11 +131,81 @@ impl BodyBuilder<'_, '_, '_> { let mut output = Vec::new(); while let Some(job) = jobs.pop() { match job { + Job::ForkNext { + items, + index, + join, + branches, + } => { + if let Some(&id) = items.get(index) { + if let StatementKind::Declaration(declaration) = &native.statement(id).kind + { + output.extend(self.block_item_declaration(declaration)?); + jobs.push(Job::ForkNext { + items, + index: index + 1, + join, + branches, + }); + } else { + jobs.push(Job::ForkBranch { + items, + index, + join, + branches, + start: output.len(), + }); + jobs.push(Job::Enter(id)); + } + } else { + self.pop_scope(); + output.push(Stmt::Fork { join, branches }); + } + } + Job::ForkBranch { + items, + index, + join, + mut branches, + start, + } => { + let branch = output.split_off(start); + let mut returns = false; + for stmt in &branch { + stmt.walk(&mut |s| returns |= matches!(s, Stmt::Return(_))); + } + if returns { + return Err(unsupported("return from a fork-join block")); + } + branches.push(branch); + jobs.push(Job::ForkNext { + items, + index: index + 1, + join, + branches, + }); + } Job::Enter(id) => match &native.statement(id).kind { StatementKind::Empty => {} StatementKind::Declaration(declaration) => { output.extend(self.block_item_declaration(declaration)?) } + StatementKind::Parallel { items, join, .. } => { + self.allow_timing("fork-join block")?; + self.push_scope(); + let join = match join.as_str() { + "join" => celox_design::ForkJoin::All, + "join_any" => celox_design::ForkJoin::Any, + "join_none" => celox_design::ForkJoin::None, + _ => return Err(disagreement()), + }; + jobs.push(Job::ForkNext { + items: items.clone(), + index: 0, + join, + branches: Vec::new(), + }); + } StatementKind::Block { items, .. } => { self.push_scope(); jobs.push(Job::EndScope); diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 3d981ce9419..208edd2cca9 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -74,6 +74,7 @@ fn has_timing_control( if matches!( statement.kind, StatementKind::Timing { .. } + | StatementKind::Parallel { .. } | StatementKind::Wait { .. } | StatementKind::WaitFork | StatementKind::WaitOrder { .. } diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index 2da16383d4f..b706c7cf6d8 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -79,6 +79,11 @@ pub enum StmtBase { step: Vec>, body: Vec>, }, + /// Concurrent child processes (IEEE 1800-2023 9.3.2). + Fork { + join: celox_design::ForkJoin, + branches: Vec>>, + }, Break, Continue, Return(Option), @@ -309,6 +314,10 @@ impl StmtBase { step: body(step, fe, fl), body: body(loop_body, fe, fl), }, + StmtBase::Fork { join, branches } => StmtBase::Fork { + join, + branches: branches.into_iter().map(|b| body(b, fe, fl)).collect(), + }, StmtBase::Break => StmtBase::Break, StmtBase::Continue => StmtBase::Continue, StmtBase::Return(value) => StmtBase::Return(value.map(fe)), @@ -443,6 +452,11 @@ impl StmtBase { body(step, fe, fl, fname); body(loop_body, fe, fl, fname); } + StmtBase::Fork { branches, .. } => { + for branch in branches { + body(branch, fe, fl, fname); + } + } StmtBase::Break | StmtBase::Continue => {} StmtBase::Return(value) => { if let Some(value) = value { @@ -512,6 +526,11 @@ impl StmtBase { visit(step); visit(body); } + StmtBase::Fork { branches, .. } => { + for branch in branches { + visit(branch); + } + } _ => {} } } @@ -548,6 +567,11 @@ impl StmtBase { visit(step); visit(body); } + StmtBase::Fork { branches, .. } => { + for branch in branches { + visit(branch); + } + } _ => {} } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 10ebdfcfbd0..7d280a56b89 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3483,7 +3483,10 @@ fn rejects_unlowered_constructs() { Path::new("fork.sv"), ) .expect_err("unlowered constructs must not be silently ignored"); - assert!(matches!(error, AnalyzerError::Unsupported(_)), "{error:?}"); + assert!( + matches!(error, AnalyzerError::TimingControlOutsideProcess { .. }), + "{error:?}" + ); } /// Timing constructs that remain unimplemented are rejected with their @@ -3491,7 +3494,6 @@ fn rejects_unlowered_constructs() { #[test] fn rejects_unimplemented_timing_constructs() { for (body, construct) in [ - ("initial begin fork #1; join end", "fork-join block"), ("initial wait fork;", "wait fork statement"), // The `event` data type is rejected by name before its uses. ("event e; initial @e;", "named event"), @@ -7203,10 +7205,8 @@ fn final_join_none_is_unsupported_rather_than_a_function_statement_violation() { Path::new("final_join_none.sv"), ) .unwrap_err(); - assert_eq!( - error.to_string(), - "Unsupported SystemVerilog construct: fork-join block" - ); + assert!(error.to_string().contains("fork-join block"), "{error}"); + assert!(error.to_string().contains("final procedure"), "{error}"); } #[test] diff --git a/crates/celox-test-suite/src/sv/cases/fork.vtest b/crates/celox-test-suite/src/sv/cases/fork.vtest new file mode 100644 index 00000000000..a106fc0befb --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/fork.vtest @@ -0,0 +1,220 @@ +(group fork (category sequential)) + +; IEEE 1800-2023 9.3.2: concurrent stackless processes and their join boundaries. + +(case join_any_keeps_other_children_running + (source "join_any_keeps_other_children_running.sv" #"module Top(output int q); + initial begin + q=0; + fork begin #1; q=1; end begin #3; q=q+4; end join_any + q=q+2; + end +endmodule"#) + (top Top) + (run_until 10) + (assert_eq q 7)) + +(case join_none_starts_after_parent_blocks + (source "join_none_starts_after_parent_blocks.sv" #"module Top(output int q); + initial begin + q=0; + fork begin q=q+2; #1; q=q+4; end join_none + q=1; + #2; q=q+8; + end +endmodule"#) + (top Top) + (run_until 10) + (assert_eq q 15)) + +(case repeated_forks_capture_each_automatic_local + (source "repeated_forks_capture_each_automatic_local.sv" #"module Top(output int q); + int n=3; + initial begin + q=0; + for(int i=0; i>, pub(crate) processes: Vec>, pub(crate) process_origins: Vec, + pub(crate) process_frames: Vec>>, pub(crate) watches: Vec>, pub(crate) occurrence_probes: Vec<(celox_design::VarAtomBase, AbsoluteAddr)>, pub(crate) wait_sites: Vec>, @@ -582,6 +583,7 @@ impl NativeProgramImage { live_signals: self.runtime_schema.live_signals.iter().copied().collect(), processes: self.runtime_schema.processes.clone(), process_origins: self.runtime_schema.process_origins.clone(), + process_frames: self.runtime_schema.process_frames.clone(), watches: self.runtime_schema.watches.clone(), occurrence_probes: self.runtime_schema.occurrence_probes.clone(), wait_sites: self.runtime_schema.wait_sites.clone(), @@ -703,6 +705,29 @@ impl NativeProgramImage { { return Err("process kernels and their control slots disagree".into()); } + if self.runtime_schema.process_frames.len() != self.runtime_schema.processes.len() { + return Err("process kernels and their activation frames disagree".into()); + } + for (slots, frame) in self + .runtime_schema + .processes + .iter() + .zip(&self.runtime_schema.process_frames) + { + let Some(frame) = frame else { + continue; + }; + let mut addresses = HashSet::default(); + if ![slots.resume, slots.status, slots.delay, frame.random] + .iter() + .all(|slot| frame.private.contains(slot)) + || frame.private.iter().chain(&frame.locals).any(|slot| { + !self.design.state_objects.contains_key(slot) || !addresses.insert(*slot) + }) + { + return Err("invalid process activation frame storage".into()); + } + } if self.required_native_features & !KNOWN_NATIVE_FEATURES != 0 { return Err("native image contains unknown feature requirements".into()); } @@ -2606,6 +2631,7 @@ fn compile_program( .collect(), processes: sir.runtime().runtime_schema.processes.clone(), process_origins: sir.runtime().runtime_schema.process_origins.clone(), + process_frames: sir.runtime().runtime_schema.process_frames.clone(), watches: sir.runtime().runtime_schema.watches.clone(), occurrence_probes: sir.runtime().runtime_schema.occurrence_probes.clone(), wait_sites: sir.runtime().runtime_schema.wait_sites.clone(), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index ae25f64d4a2..6d40eda2a40 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 = 39; +const CONTAINER_VERSION: u16 = 40; 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/simulation.rs b/crates/celox/src/simulation.rs index 05548af21f6..dfc7e05abd1 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -295,6 +295,25 @@ impl HostBoundary for Simulator { CompiledSlots::Any } + fn retain_process_values(&mut self, values: &[(SignalRef, celox_runtime::timing::Value)]) { + let slots = self.handle_slots(); + self.process_heap_roots.clear(); + for (signal, (value, _)) in values { + for &(offset, kind) in slots.iter().filter(|&&(offset, _)| { + offset >= signal.offset && offset < signal.offset + signal.width.div_ceil(8) + }) { + let bytes = (value >> ((offset - signal.offset) * 8)).to_bytes_le(); + let mut raw = [0; celox_heap::HANDLE_BYTES]; + let count = bytes.len().min(raw.len()); + raw[..count].copy_from_slice(&bytes[..count]); + self.process_heap_roots.push(celox_heap::Root { + kind, + handle: celox_heap::Handle::from_le_bytes(raw), + }); + } + } + } + fn finish_timed_step(&mut self, timestamp: u64) { self.dirty = false; self.dump_unless_rewound(timestamp); @@ -489,6 +508,9 @@ impl Simulation { if self.state.is_suspended() { return Err(CheckpointError::Stopped.into()); } + if self.state.has_fork_activations() { + return Err(StateError::Processes); + } let mut file = self .simulator .state_schema() @@ -542,6 +564,7 @@ impl Simulation { }) .map_err(|_| CheckpointError::DesignMismatch)?; self.simulator.restore(&checkpoint.simulator)?; + self.state.retain_activation_roots(&mut self.simulator); self.simulator.declaration_phase = false; self.simulator .host_watch diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 0eed2799e5d..d0e1e8c7398 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -129,6 +129,7 @@ mod host { /// Set while handles live outside state memory, where no collection /// may run: between the polls of concurrent testbench processes. pub(crate) heap_safepoints_blocked: bool, + pub(crate) process_heap_roots: Vec, file_io: celox_runtime::file_io::FileIo, pending_host_events: Arc>, pub(crate) program: RuntimeProgram, @@ -1053,6 +1054,7 @@ mod host { warnings, handle_slots: Default::default(), heap_safepoints_blocked: false, + process_heap_roots: Vec::new(), file_io: Default::default(), pending_host_events: Arc::new(std::sync::Mutex::new(PendingRuntimeEvents { deferred: DeferredQueues { diff --git a/crates/celox/src/simulator/heap.rs b/crates/celox/src/simulator/heap.rs index 162e1d25644..9eedb0b5b90 100644 --- a/crates/celox/src/simulator/heap.rs +++ b/crates/celox/src/simulator/heap.rs @@ -98,8 +98,11 @@ impl Simulator { return; } let roots = self.handle_roots(); - self.backend - .heap_mut() - .collect(roots.into_iter().chain(extra_roots)); + self.backend.heap_mut().collect( + roots + .into_iter() + .chain(self.process_heap_roots.iter().copied()) + .chain(extra_roots), + ); } } diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 55120c284c9..3ef0f4727cf 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -36,9 +36,8 @@ pub enum StateError { MissingSchedule, #[error("evaluating combinational logic failed: {0}")] Runtime(RuntimeErrorCode), - /// Not returned: state files record suspended processes. Kept so that - /// matching code keeps compiling. - #[error("the state of the simulation's processes could not be recorded")] + /// Dynamic fork activations have storage outside the named state objects. + #[error("state files do not record dynamic fork activations; use a checkpoint instead")] Processes, /// Not returned: state files record strings by their contents. Kept so /// that matching code keeps compiling. diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 9df87b6b032..3dbab1e4880 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -461,8 +461,6 @@ fn event_expressions_with_effects_are_rejected() { fn unimplemented_timing_features_are_rejected() { for (body, construct, issue) in [ ("bit a; initial @(a iff a);", "iff-qualified event", 1444), - ("initial fork #1; join", "fork-join block", 88), - ("initial fork #1; join_none", "fork-join block", 88), ("event e; initial -> e;", "named event", 88), ( "bit a, b; initial a = #1 b;", @@ -1165,3 +1163,24 @@ fn design_processes_a_program_wakes_run_before_the_nonblocking_updates() { assert_eq!(values, [0u8.into(), 1u8.into()], "four_state={four_state}"); } } + +// Forked child activations and join boundaries. +timed_cases! { + fn fork_join_any_keeps_other_children_running = "fork::join_any_keeps_other_children_running"; + fn fork_join_none_starts_after_parent_blocks = "fork::join_none_starts_after_parent_blocks"; + fn fork_repeated_forks_capture_each_automatic_local = "fork::repeated_forks_capture_each_automatic_local"; + fn fork_nested_forks_wait_for_their_own_children = "fork::nested_forks_wait_for_their_own_children"; + fn fork_automatic_task_inputs_outlive_the_call = "fork::automatic_task_inputs_outlive_the_call"; + fn fork_fork_children_wait_for_signal_changes = "fork::fork_children_wait_for_signal_changes"; + fn fork_repeated_forks_reuse_finished_instances = "fork::repeated_forks_reuse_finished_instances"; + fn fork_static_locals_are_shared_between_overlapping_children = "fork::static_locals_are_shared_between_overlapping_children"; + fn fork_fork_nonblocking_updates_keep_each_child_value = "fork::fork_nonblocking_updates_keep_each_child_value"; + fn fork_children_share_a_live_automatic_local = "fork::children_share_a_live_automatic_local"; + fn fork_wait_on_shared_automatic_local_wakes_after_child_write = "fork::wait_on_shared_automatic_local_wakes_after_child_write"; + fn fork_event_on_shared_automatic_local_wakes_after_child_write = "fork::event_on_shared_automatic_local_wakes_after_child_write"; + fn fork_suspended_child_keeps_automatic_string_alive = "fork::suspended_child_keeps_automatic_string_alive"; + fn fork_child_delay_uses_current_simulation_time = "fork::child_delay_uses_current_simulation_time"; + fn fork_join_any_waits_only_for_immediate_children = "fork::join_any_waits_only_for_immediate_children"; +} + +timed_cases! { fn fork_four_state_automatic_values_survive_fork_suspension = "fork::four_state_automatic_values_survive_fork_suspension"; } diff --git a/crates/celox/tests/sv_fork_join.rs b/crates/celox/tests/sv_fork_join.rs new file mode 100644 index 00000000000..8ff88ee460f --- /dev/null +++ b/crates/celox/tests/sv_fork_join.rs @@ -0,0 +1,164 @@ +#![cfg(feature = "systemverilog")] +use celox::{SimBackend, Simulation}; +use std::path::Path; + +fn check(mut sim: Simulation) { + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 7u8.into()); +} +#[test] +fn fork_join_smoke() { + let source = r#"`timescale 1ns/1ns +module Top(output bit [2:0] q); + initial begin + fork + begin #1; q[0] = 1; end + begin #2; q[1] = 1; end + join + q[2] = 1; + end +endmodule"#; + check( + Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .build_interpreter() + .unwrap(), + ); + check( + Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .build_native() + .unwrap(), + ); + let image = Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + check( + Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + ); +} + +#[test] +fn checkpoint_replays_pending_children() { + let source = r#"`timescale 1ns/1ns +module Top(output int q); + initial begin q=0; fork begin #2; q=q+1; end begin #4; q=q+2; end join q=q+4; end +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .build_native() + .unwrap(); + sim.run_until(1).unwrap(); + let saved = sim.checkpoint().unwrap(); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 7u8.into()); + sim.restore(&saved).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 checkpoint_before_spawn_can_be_restored_repeatedly() { + let source = r#"`timescale 1ns/1ns +module Top(output int q); + initial begin q=0; #1; fork begin #1; q=q+1; end begin #2; q=q+2; end join end +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .build_native() + .unwrap(); + sim.run_until(0).unwrap(); + let saved = sim.checkpoint().unwrap(); + for _ in 0..3 { + sim.restore(&saved).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 3u8.into()); + } + assert!(matches!( + sim.save_state(), + Err(celox::StateError::Processes) + )); +} + +#[test] +fn stop_resumes_the_same_child_before_other_ready_processes() { + let source = r#"`timescale 1ns/1ns +module Top(output bit [2:0] q); + initial begin + fork begin q[0]=1; $stop; q[1]=1; end begin #2; q[2]=1; end join + end +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .scheduler_mode(celox::SchedulerMode::Differential) + .build_native() + .unwrap(); + sim.run_until(5).unwrap(); + assert!(sim.is_stopped()); + 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 child_finish_runs_final_once_without_resuming_siblings() { + let source = r#"`timescale 1ns/1ns +module Top(output bit [2:0] q); + initial fork begin #1; q[0]=1; $finish; end begin #2; q[1]=1; end join + final q[2]=1; +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .build_native() + .unwrap(); + sim.run_until(5).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("q")), 5u8.into()); + assert_eq!(sim.time(), 1); +} + +#[test] +fn fork_and_compiled_processes_share_scheduler_state() { + let source = r#"`timescale 1ns/1ns +module Top(output bit [2:0] q); + initial begin + fork begin #1; q[0]=1; end begin #3; q[1]=1; end join + end + initial begin #2; q[2]=1; end +endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .scheduler_mode(celox::SchedulerMode::Differential) + .build_native() + .unwrap(); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 7u8.into()); +} + +#[test] +fn program_exit_discards_children_waiting_for_parent_suspension() { + let source = r#"`timescale 1ns/1ns +module Top(output int q); + Tb t(q); + Other other(); +endmodule +program Tb(output int q); + initial begin + q=0; + fork begin #1; q=7; end join_none + $exit; + end +endprogram +program Other; + initial #10; +endprogram"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("fork.sv"))], "Top") + .scheduler_mode(celox::SchedulerMode::Differential) + .build_native() + .unwrap(); + sim.run_until(5).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert!(!sim.is_finished()); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ec4f308a543..048546111d6 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -119,6 +119,29 @@ to enums as well. Mixed enum and integer argument lists are supported. Constraints (`with`), enums with unsupported or unresolved domains, unpacked arrays, nets, constants, selects and concatenation arguments are unsupported and rejected. +### Parallel processes + +`fork ... join`, `join_any` and `join_none` create concurrent child processes +in `initial` / `always` procedures and tasks. `join` waits for every child; +`join_any` waits for one child and leaves the others running; `join_none` +continues without waiting. Children start when their parent blocks or ends, +not at compiler or host-service yields (IEEE 1800-2023 9.3.2). + +Forks can be nested or executed repeatedly while earlier children remain +alive. Automatic variables are shared with children of that activation and +remain alive after the parent returns; re-entering their declaration allocates +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. + +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, +and compound event expressions reading fork-shared automatic locals remain +unsupported. Direct event controls on those locals and `wait` conditions are +supported. + ### Class randomization `object.randomize()` randomizes enabled `rand` properties and returns signed @@ -195,7 +218,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - 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: 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`. + named events and `->`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. - Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), impure function calls in event expressions, and `wait` or event expressions reading a static task argument. @@ -619,7 +642,7 @@ 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. +procedures (13.4.4). `fork` / `join_none` inside final procedures remains unsupported. ### Programs {#programs}