From 883befed556beb5f4e042388950ceec6cb79756f Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 19:41:37 +0900 Subject: [PATCH 1/6] feat(runtime)!: run program kernels in the reactive region set A kernel of a program instance names the status slot of the instance's first kernel (ProcessSlots::program). Such kernels start, wake and resume in the Reactive region, a #0 resumes them in the Re-Inactive region, and their nonblocking updates take effect in the Re-NBA region (IEEE 1800-2023 4.4.2.6-4.4.2.8, 24.3.1). The reactive region set runs once the active region set is empty and returns to the active region set for the design activity it creates (4.5). ProcessStatus::Exit ends every kernel of the calling program instance (24.7), and the implicit $finish fires once every program kernel has ended (24.3). Program kernels run on the reference scheduler. Designs without programs schedule as before. BREAKING CHANGE: ProcessSlots gains `program`, ProcessStatus gains `Exit`, ProcessState and ScheduleKey gain the reactive, re-inactive and Re-NBA queues, and the native image container format is now 35. Change-Id: I6c899de1f0d5e8ca722733a53655ee80e3c988b8 --- crates/celox-design/src/lib.rs | 13 ++ crates/celox-frontend-core/src/process.rs | 7 + crates/celox-frontend-core/src/sdk.rs | 1 + crates/celox-frontend-sv/src/lowering.rs | 1 + crates/celox-runtime/src/schedule.rs | 9 ++ crates/celox-runtime/src/simulation/mod.rs | 2 +- crates/celox-runtime/src/simulation/nba.rs | 144 +++++++++++++----- .../celox-runtime/src/simulation/persist.rs | 6 + .../celox-runtime/src/simulation/process.rs | 113 ++++++++++++-- crates/celox-runtime/src/simulation/round.rs | 13 +- crates/celox-runtime/src/simulation/time.rs | 42 ++++- crates/celox-runtime/src/simulation/wait.rs | 40 ++++- crates/celox-runtime/src/timing.rs | 14 ++ crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/scheduler.rs | 2 + crates/celox/src/simulator/state_file.rs | 1 + 16 files changed, 347 insertions(+), 63 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 5e45cf13916..bdedcd2e93b 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -291,6 +291,9 @@ pub enum ProcessStatus { /// A synchronous host operation. The delay slot holds its family and /// local site index; the same process resumes after the host responds. HostRequest, + /// A program kernel called `$exit` (IEEE 1800-2023 24.7): it and every + /// other kernel of its program instance ([`ProcessSlots::program`]) end. + Exit, } impl ProcessStatus { @@ -308,6 +311,7 @@ impl ProcessStatus { Self::Yield => 8, Self::Stop => 9, Self::HostRequest => 10, + Self::Exit => 11, } } @@ -323,6 +327,7 @@ impl ProcessStatus { 8 => Some(Self::Yield), 9 => Some(Self::Stop), 10 => Some(Self::HostRequest), + 11 => Some(Self::Exit), _ => None, } } @@ -465,6 +470,12 @@ pub struct ProcessSlots { /// Every delay the kernel suspends for is a constant of at least one /// time unit. pub const_delays: bool, + /// For an `initial` procedure of a program instance (IEEE 1800-2023 + /// 24.3), the status slot of that instance's first such kernel, which + /// every kernel of the instance names: the kernel runs in the reactive + /// region set (24.3.1), and `$exit` and the end of the instance's + /// kernels act on them together (24.7). `None` for design code. + pub program: Option, pub resume: A, pub status: A, pub delay: A, @@ -476,6 +487,7 @@ impl ProcessSlots { is_initializer: self.is_initializer, requires_timed_simulation: self.requires_timed_simulation, const_delays: self.const_delays, + program: self.program.map(&mut map), resume: map(self.resume), status: map(self.status), delay: map(self.delay), @@ -1791,6 +1803,7 @@ mod tests { ProcessStatus::from_code(10), Some(ProcessStatus::HostRequest) ); + assert_eq!(ProcessStatus::from_code(11), Some(ProcessStatus::Exit)); } #[test] diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 1931a26203b..b141ad8d532 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -368,6 +368,13 @@ impl ProcessKernelBuilder { self.end(ProcessStatus::Finish); } + /// End the kernel and the other kernels of its program instance + /// (`$exit`, IEEE 1800-2023 24.7). No block is open afterwards. + pub fn exit(&mut self) { + self.wait_site = None; + self.end(ProcessStatus::Exit); + } + /// Complete the kernel. If a block is still open, the process ends there. pub fn build(mut self) -> ExecutionUnit { if self.builder.has_open_block() { diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index f74172ab2a4..18232d0b2a4 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1732,6 +1732,7 @@ fn lower_processes( is_initializer: false, requires_timed_simulation: false, const_delays: false, + program: None, resume: lowering .hidden .declare(name("resume"), PROCESS_RESUME_WIDTH, false), diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 4b662c6bf0d..1a9cccf8986 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4451,6 +4451,7 @@ fn lower_initial_processes( is_initializer: process.is_initializer(), requires_timed_simulation: process.is_scheduled_edge(), const_delays: false, + program: None, resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index b9a0e39311b..7585cab6a7e 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -21,6 +21,8 @@ pub struct ResolvedSchedule { pub(crate) signal_to_id: FxHashMap, pub(crate) signal_index_by_id: Vec, pub(crate) processes: Vec, + /// The kernels of program instances, in declaration order. + pub(crate) program_processes: Vec, /// Counted signals and the domains their counters trigger. pub(crate) counted: Vec, pub(crate) counted_by_offset: FxHashMap, @@ -190,6 +192,7 @@ impl ResolvedSchedule { .iter() .map(|process| ProcessRefs { is_initializer: process.slots.is_initializer, + program: process.slots.program.as_ref().map(resolve), resume: resolve(&process.slots.resume), starts_with_event_wait: process.slots.requires_timed_simulation, status: resolve(&process.slots.status), @@ -299,6 +302,12 @@ impl ResolvedSchedule { event_info, signal_to_id, signal_index_by_id, + program_processes: processes + .iter() + .enumerate() + .filter(|(_, process)| process.program.is_some()) + .map(|(index, _)| index) + .collect(), processes, counted, counted_by_offset, diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 7523e231da0..515b4cfb26e 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -454,7 +454,7 @@ impl SimulationState { E: SimulationExecutor, { self.slot_passes = 0; - match self.step_round(executor, time, Vec::new(), Vec::new(), true) { + match self.step_round(executor, time, Vec::new(), Vec::new(), true, false) { Ok(()) => { self.finish_timed_boundary(executor, time)?; Ok(Some(time)) diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index f2395e208c7..00b493f1180 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -32,7 +32,14 @@ impl SimulationState { let Some((lsb, width)) = refs.range(backend) else { return Ok(()); }; - self.process_state.nba_queue.push(NbaUpdate { + // A program process's update waits for the Re-NBA region (IEEE + // 1800-2023 24.3.1). + let queue = if self.model.processes[process].program.is_some() { + &mut self.process_state.re_nba_queue + } else { + &mut self.process_state.nba_queue + }; + queue.push(NbaUpdate { target: refs.target, lsb, width, @@ -57,6 +64,7 @@ impl SimulationState { self.model .processes .iter() + .filter(|process| process.program.is_none()) .flat_map(|process| &process.nba_sites) .filter_map(|site| site.pending) .filter(|&pending| backend.get_as::(pending) != 0) @@ -76,45 +84,12 @@ impl SimulationState { self.event_values(executor.backend(), &mut round.before); round.transitions.clear(); } - for update in &queued { - let new = NbaValue::Queued(&update.value); - self.publish_update(executor.backend_mut(), update, new); - if several { - self.record_transitions(executor.backend(), round); - } - } + self.publish_queued(executor, round, &queued, several); // Keep the queue's storage for the next time slot. queued.clear(); self.process_state.nba_queue = queued; if flagged > 0 { - for process in 0..self.model.processes.len() { - for site in 0..self.model.processes[process].nba_sites.len() { - let backend = executor.backend_mut(); - let Some(pending) = self.model.processes[process].nba_sites[site].pending - else { - continue; - }; - if backend.get_as::(pending) == 0 { - continue; - } - backend.set(pending, 0u8); - let site = &self.model.processes[process].nba_sites[site]; - let Some((lsb, width)) = site.range(backend) else { - continue; - }; - let (target, value) = (site.target, site.value); - let update = NbaUpdate { - target, - lsb, - width, - value: Value::default(), - }; - self.publish_update(backend, &update, NbaValue::Staged(value)); - if several { - self.record_transitions(executor.backend(), round); - } - } - } + self.publish_flagged(executor, round, false, several); } if several { let transitions = std::mem::take(&mut round.transitions); @@ -126,6 +101,103 @@ impl SimulationState { true } + /// Publish the nonblocking assignments of program processes (the Re-NBA + /// region, IEEE 1800-2023 4.4.2.8): the queued ones in issue order, then + /// the flagged ones. Like the writes of a process run, each is recorded + /// in `round.transitions` for the caller to settle. Returns whether any + /// was published. + pub(super) fn publish_re_nba(&mut self, executor: &mut E, round: &mut Round) -> bool + where + E: SimulationExecutor, + { + let any_flagged = self.model.has_pending_nba_sites && { + let backend = executor.backend(); + self.model + .program_processes + .iter() + .flat_map(|&process| &self.model.processes[process].nba_sites) + .filter_map(|site| site.pending) + .any(|pending| backend.get_as::(pending) != 0) + }; + if self.process_state.re_nba_queue.is_empty() && !any_flagged { + return false; + } + self.event_values(executor.backend(), &mut round.before); + let mut queued = std::mem::take(&mut self.process_state.re_nba_queue); + self.publish_queued(executor, round, &queued, true); + // Keep the queue's storage for the next time slot. + queued.clear(); + self.process_state.re_nba_queue = queued; + if any_flagged { + self.publish_flagged(executor, round, true, true); + } + true + } + + /// Publish `queued` in issue order, recording the transitions of each in + /// `round.transitions` if `record`. + fn publish_queued( + &mut self, + executor: &mut E, + round: &mut Round, + queued: &[NbaUpdate], + record: bool, + ) where + E: SimulationExecutor, + { + for update in queued { + let new = NbaValue::Queued(&update.value); + self.publish_update(executor.backend_mut(), update, new); + if record { + self.record_transitions(executor.backend(), round); + } + } + } + + /// Publish the flagged nonblocking sites of the program processes if + /// `program`, otherwise of the design's, in declaration order, recording + /// the transitions of each in `round.transitions` if `record`. + fn publish_flagged( + &mut self, + executor: &mut E, + round: &mut Round, + program: bool, + record: bool, + ) where + E: SimulationExecutor, + { + for process in 0..self.model.processes.len() { + if self.model.processes[process].program.is_some() != program { + continue; + } + for site in 0..self.model.processes[process].nba_sites.len() { + let backend = executor.backend_mut(); + let Some(pending) = self.model.processes[process].nba_sites[site].pending else { + continue; + }; + if backend.get_as::(pending) == 0 { + continue; + } + backend.set(pending, 0u8); + let site = &self.model.processes[process].nba_sites[site]; + let Some((lsb, width)) = site.range(backend) else { + continue; + }; + let (target, value) = (site.target, site.value); + let update = NbaUpdate { + target, + lsb, + width, + value: Value::default(), + }; + self.publish_update(backend, &update, NbaValue::Staged(value)); + if record { + self.record_transitions(executor.backend(), round); + } + } + } + } + /// Write `update`, whose value is `new`, into its target. An update /// inside a target of at most 64 bits with one state plane is merged as /// `u64`; any other as [`Value`]. diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index a5a5525fc53..aa0a94ff8e9 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -293,6 +293,9 @@ impl SimulationState { ready: state.ready.iter().copied().collect(), inactive: state.inactive.iter().copied().collect(), nba_queue: state.nba_queue.clone(), + reactive: state.reactive.iter().copied().collect(), + re_inactive: state.re_inactive.iter().copied().collect(), + re_nba_queue: state.re_nba_queue.clone(), domain_counters: state.domain_counters.clone(), declarations_pending: self.declarations_pending, host_pending: self.host_pending, @@ -319,6 +322,9 @@ pub struct ScheduleKey { pub ready: Vec, pub inactive: Vec, pub nba_queue: Vec, + pub reactive: Vec, + pub re_inactive: Vec, + pub re_nba_queue: Vec, pub domain_counters: Vec<[u32; 3]>, pub declarations_pending: bool, pub host_pending: bool, diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 3faece18b35..bc74b2729d8 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -1,12 +1,19 @@ //! The process phase of a round: running ready kernels and filing them //! where they resume. +use std::collections::BTreeSet; + use celox_design::{HostRequestKind, ProcessStatus}; use super::SimulationState; use super::host::SimulationExecutor; use super::round::Round; -use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; +use super::wait::wake_in_region; +use crate::{ + SimulatorErrorCode, + backend::SimBackend, + timing::{Halt, ProcessState}, +}; impl SimulationState { /// Execute static declaration initializers before any ordinary process, @@ -132,13 +139,25 @@ impl SimulationState { } Some(ProcessStatus::InactiveDelay) => { let delay = delay(); - if delay == 0 { - self.process_state.inactive.insert(process); - } else { + if delay != 0 { self.wake_after(current_time, delay, process)?; + } else if self.model.processes[process].program.is_some() { + // A program process resumes in the Re-Inactive + // region (IEEE 1800-2023 4.4.2.7). + self.process_state.re_inactive.insert(process); + } else { + self.process_state.inactive.insert(process); + } + } + Some(ProcessStatus::Done) => { + if self.model.processes[process].program.is_some() { + self.program_kernel_ended(executor.backend())?; } } - Some(ProcessStatus::Done) => {} + Some(ProcessStatus::Exit) => { + self.exit_program(executor.backend_mut(), process)?; + self.program_kernel_ended(executor.backend())?; + } Some(ProcessStatus::Finish) => return Err(Halt::Finish), Some(ProcessStatus::Wait | ProcessStatus::Pending) => { let site = delay() as usize; @@ -169,7 +188,10 @@ impl SimulationState { // simulation does. Some(ProcessStatus::Stop) => { self.stopped = true; - self.process_state.ready.insert(process); + let ProcessState { + ready, reactive, .. + } = &mut self.process_state; + wake_in_region(&self.model.processes, ready, reactive, process); return Err(Halt::Stop); } Some(ProcessStatus::Yield) => { @@ -195,17 +217,18 @@ impl SimulationState { where E: SimulationExecutor, { - if self.process_state.ready.is_empty() { + let reactive = round.reactive; + if self.region_ready(reactive).is_empty() { return Ok(false); } self.event_values(executor.backend(), &mut round.before); let mut resume_process = round.resume_process.take(); if let Some(process) = resume_process { - self.process_state.ready.remove(&process); + self.region_ready(reactive).remove(&process); } while let Some(process) = resume_process .take() - .or_else(|| self.process_state.ready.pop_first()) + .or_else(|| self.region_ready(reactive).pop_first()) { loop { let again = self.run_process(executor, current_time, process, returns); @@ -222,7 +245,7 @@ impl SimulationState { // Before the next run, its edges must be seen. After the last // one, the check following the settle sees them: a settle // does not write what processes write. - if again || !self.process_state.ready.is_empty() { + if again || !self.region_ready(reactive).is_empty() { self.observe_driven(executor.backend()); } if !again { @@ -233,6 +256,55 @@ impl SimulationState { Ok(true) } + /// The processes ready in the Reactive region if `reactive`, otherwise in + /// the Active region. + #[inline] + fn region_ready(&mut self, reactive: bool) -> &mut BTreeSet { + if reactive { + &mut self.process_state.reactive + } else { + &mut self.process_state.ready + } + } + + /// `$exit` of program kernel `process` (IEEE 1800-2023 24.7): every + /// kernel of its program instance ends, as if it had run to its end. + fn exit_program(&mut self, backend: &mut B, process: usize) -> Result<(), Halt> { + let program = self.model.processes[process] + .program + .ok_or(SimulatorErrorCode::InternalError)?; + for &index in &self.model.program_processes { + let refs = &self.model.processes[index]; + if refs.program != Some(program) { + continue; + } + backend.set(refs.status, ProcessStatus::Done.code()); + let state = &mut self.process_state; + state.waiters.remove(index); + state.ready.remove(&index); + state.reactive.remove(&index); + state.re_inactive.remove(&index); + } + let model = &self.model; + self.process_wakeups + .retain(|std::cmp::Reverse((_, index))| { + model.processes[*index].program != Some(program) + }); + Ok(()) + } + + /// A program kernel ended. Once every program kernel has, the simulation + /// 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); + if all_done { Err(Halt::Finish) } else { Ok(()) } + } + /// Mark the edges the processes of a pass caused and settle them. fn settle_pass(&mut self, executor: &mut E, round: &mut Round) -> Result<(), Halt> where @@ -290,6 +362,27 @@ impl SimulationState { } else { self.observe_driven(executor.backend()); } + if round.reactive { + // The Reactive region is empty: the Re-Inactive region's + // processes resume, and once both are empty the Re-NBA region + // publishes the program's nonblocking assignments. Design + // processes and domains wait for the active region set (IEEE + // 1800-2023 4.5, 24.3.1). + if !self.process_state.reactive.is_empty() { + continue; + } + if !self.process_state.re_inactive.is_empty() { + let inactive = std::mem::take(&mut self.process_state.re_inactive); + self.process_state.reactive.extend(inactive); + continue; + } + if self.publish_re_nba(executor, round) { + self.settle_pass(executor, round)?; + self.observe_driven(executor.backend()); + continue; + } + return Ok(()); + } if !self.process_state.ready.is_empty() { continue; } diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 813b446c1a2..c1738942c0f 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -18,6 +18,10 @@ use crate::{ /// Bookkeeping of one round of a time slot. #[derive(Default)] pub(super) struct Round { + /// The round's process phase is the reactive region set's: it runs + /// program processes, and the design activity they create follows it + /// (IEEE 1800-2023 4.5). + pub(super) reactive: bool, /// The stopped process resumes before any newly woken ready processes. pub(super) resume_process: Option, /// Event ids whose trigger survives the settling filter. @@ -89,7 +93,8 @@ impl Round { impl Round { /// Start a round, keeping the buffers of earlier ones. - fn reset(&mut self, track_stable_edges: bool) { + fn reset(&mut self, track_stable_edges: bool, reactive: bool) { + self.reactive = reactive; self.resume_process = None; self.scheduled_trigger_ids.make_empty(); self.track_stable_edges = track_stable_edges; @@ -422,7 +427,8 @@ impl SimulationState { /// trigger evaluate, zero-delay processes run in the inactive region, /// and only then are nonblocking assignments published. A round /// without ready processes and counted signals does exactly the batch - /// step. + /// step. In a `reactive` round the process phase is that of the reactive + /// region set, and the domains its processes trigger evaluate after it. pub(super) fn step_round( &mut self, executor: &mut E, @@ -430,6 +436,7 @@ impl SimulationState { events_to_process: Vec>, ready_processes: Vec, entry: bool, + reactive: bool, ) -> Result<(), Halt> where E: SimulationExecutor, @@ -474,7 +481,7 @@ impl SimulationState { } let mut round = self.scratch.take().unwrap_or_default(); - round.reset(events_to_process.is_empty()); + round.reset(events_to_process.is_empty(), reactive); round.begin_scan(self.model.domain_kinds.len()); self.process_state.ready.extend(ready_processes); executor.backend_mut().clear_triggered_bits(); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index f5e2bde7145..d516834414e 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -170,7 +170,14 @@ impl SimulationState { } ready.retain(|&process| !self.model.processes[process].starts_with_event_wait); } - self.step_round(executor, current_time, events_to_process, ready, true)?; + self.step_round( + executor, + current_time, + events_to_process, + ready, + true, + false, + )?; self.end_time(executor, current_time) } @@ -185,15 +192,32 @@ impl SimulationState { loop { let ready = self.take_ready_processes(current_time); if ready.is_empty() && self.process_state.ready.is_empty() { - break; + // The active region set is empty: the reactive region set + // runs, and the design activity it creates runs in the active + // region set again (IEEE 1800-2023 4.5). + if !self.reactive_pending() { + break; + } + self.charge_pass()?; + self.step_round(executor, current_time, Vec::new(), Vec::new(), false, true)?; + continue; } self.charge_pass()?; - self.step_round(executor, current_time, Vec::new(), ready, false)?; + self.step_round(executor, current_time, Vec::new(), ready, false, false)?; } executor.try_finish_timed_step(current_time)?; Ok(()) } + /// Whether a region of the reactive region set holds work. + #[inline] + fn reactive_pending(&self) -> bool { + let state = &self.process_state; + !state.reactive.is_empty() + || !state.re_inactive.is_empty() + || !state.re_nba_queue.is_empty() + } + /// Count a round or a pass of the process phase against the slot's /// budget, so that processes resuming at one time forever end the step /// with an error instead of hanging it. @@ -225,7 +249,9 @@ impl SimulationState { })) } - /// Remove the processes waiting for `time`, in declaration order. + /// Remove the processes waiting for `time`, in declaration order. Program + /// processes resume in the Reactive region (IEEE 1800-2023 24.3.1): they + /// join its queue, and only design processes are returned. fn take_ready_processes(&mut self, time: u64) -> Vec { let mut ready = Vec::new(); while let Some(&Reverse((wakeup, process))) = self.process_wakeups.peek() { @@ -233,7 +259,11 @@ impl SimulationState { break; } self.process_wakeups.pop(); - ready.push(process); + if self.model.processes[process].program.is_some() { + self.process_state.reactive.insert(process); + } else { + ready.push(process); + } } ready } @@ -259,7 +289,7 @@ impl SimulationState { if self.finished { return None; } - if !self.process_state.ready.is_empty() { + if !self.process_state.ready.is_empty() || !self.process_state.reactive.is_empty() { return Some(self.scheduler.time); } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index bfbd004c30d..d9f4c083796 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -1,5 +1,7 @@ //! Waiting processes: registering waits and testing them against writes. +use std::collections::BTreeSet; + use celox_design::CounterKind; use super::SimulationState; @@ -7,8 +9,8 @@ use crate::{ SignalRef, SimulatorErrorCode, backend::SimBackend, timing::{ - Halt, ProcessState, StateView, Value, copy_planes, encode_planes, occurs, planes, - planes_equal, planes_occur, read, + Halt, ProcessRefs, ProcessState, StateView, Value, copy_planes, encode_planes, occurs, + planes, planes_equal, planes_occur, read, }, }; @@ -148,7 +150,12 @@ impl SimulationState { fn check_waits(&mut self, backend: &B, only: Option, driven_only: bool) { let processes = &self.model.processes; let state = StateView::new(backend); - let ProcessState { waiters, ready, .. } = &mut self.process_state; + let ProcessState { + waiters, + ready, + reactive, + .. + } = &mut self.process_state; waiters.retain(driven_only, |process, waiter| { let terms = &processes[process].wait_sites[waiter.site]; let mut wake = false; @@ -210,7 +217,7 @@ impl SimulationState { }; } if wake { - ready.insert(process); + wake_in_region(processes, ready, reactive, process); } !wake }); @@ -231,7 +238,12 @@ impl SimulationState { /// Show the waits one value the host wrote to `signal`. pub(super) fn observe_host_write(&mut self, signal: SignalRef, value: &Value) { let processes = &self.model.processes; - let ProcessState { waiters, ready, .. } = &mut self.process_state; + let ProcessState { + waiters, + ready, + reactive, + .. + } = &mut self.process_state; waiters.retain(false, |process, waiter| { let terms = &processes[process].wait_sites[waiter.site]; let mut wake = false; @@ -253,13 +265,29 @@ impl SimulationState { } } if wake { - ready.insert(process); + wake_in_region(processes, ready, reactive, process); } !wake }); } } +/// Make the woken `process` ready: in the Reactive region if it is a program +/// process (IEEE 1800-2023 24.3.1), otherwise in the Active region. +#[inline] +pub(super) fn wake_in_region( + processes: &[ProcessRefs], + ready: &mut BTreeSet, + reactive: &mut BTreeSet, + process: usize, +) { + if processes[process].program.is_some() { + reactive.insert(process); + } else { + ready.insert(process); + } +} + /// What one term of a waiting process compares against. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Baseline { diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 113a88a9975..9edb4ed0927 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -154,6 +154,10 @@ pub struct NbaSiteRefs { #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { pub is_initializer: bool, + /// The status slot naming the program instance of a program kernel + /// ([`celox_design::ProcessSlots::program`]), which runs in the reactive + /// region set. + pub program: Option, pub resume: SignalRef, /// A converted edge procedure starts by registering its event control /// before scheduled time-zero inputs are applied. @@ -172,6 +176,7 @@ impl ProcessRefs { pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { is_initializer: false, + program: None, resume: status, starts_with_event_wait: false, status, @@ -333,6 +338,15 @@ pub struct ProcessState { pub inactive: std::collections::BTreeSet, /// Queued nonblocking assignments, in issue order. pub nba_queue: Vec, + /// Program processes ready to run in the Reactive region of the current + /// time (IEEE 1800-2023 4.4.2.6). + pub reactive: std::collections::BTreeSet, + /// Program processes that resume in the Re-Inactive region (`#0`, + /// 4.4.2.7). + pub re_inactive: std::collections::BTreeSet, + /// Nonblocking assignments of program processes for the Re-NBA region + /// (4.4.2.8), in issue order. + pub re_nba_queue: Vec, /// Counter values each counted domain last triggered on, by counted /// signal index and kind. pub domain_counters: Vec<[u32; 3]>, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0c95b249cc8..7278978181c 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 = 34; +const CONTAINER_VERSION: u16 = 35; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 6287e96a9ee..02e7bb18b06 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -355,6 +355,8 @@ impl Plan { let unit = &sir.processes[index]; let reason = if slots.is_initializer { Some("a declaration initializer") + } else if slots.program.is_some() { + Some("a program process runs in the reactive region set") } else if slots.requires_timed_simulation { Some("an edge procedure") } else if !process.host_requests.is_empty() { diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 2fc6b63fb8e..803b46afdaa 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -829,6 +829,7 @@ impl Simulator { inactive, nba_queue, domain_counters, + ..ProcessState::default() }, )) } From 7d1dbebe3c07bcad3cef243dd3dfb11093dfa52e Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 05:28:09 +0900 Subject: [PATCH 2/6] ci: measure compilation benchmarks with CodSpeed walltime Change-Id: I99da4b4abb1f9113e2e89fa9cbe3bb0ea9a06b0b --- .github/workflows/codspeed.yml | 10 ++++++---- CONTRIBUTING.md | 10 ++++++++-- crates/celox/benches/compilation.rs | 2 +- scripts/benchmark-workflows.test.mjs | 14 +++++++++++++- 4 files changed, 28 insertions(+), 8 deletions(-) diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index c7afb638c3f..0830b896d1b 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -18,7 +18,8 @@ permissions: {} jobs: codspeed: name: CodSpeed - runs-on: ubuntu-latest + timeout-minutes: 60 + runs-on: codspeed-macro-x64-ryzen-9950x-ubuntu-24-04 outputs: run-id: ${{ steps.benchmarks.outputs.run-id }} permissions: @@ -39,14 +40,15 @@ jobs: tool: cargo-codspeed@5.0.1 - name: Build compile-time benchmarks - run: cargo codspeed build --locked -p celox --bench compilation + run: cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation - name: Run compile-time benchmarks id: benchmarks + timeout-minutes: 15 uses: CodSpeedHQ/action@v5 with: - mode: simulation - run: cargo codspeed run -p celox + mode: walltime + run: cargo codspeed run --measurement-mode walltime -p celox --bench compilation report: name: Report CodSpeed diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b178404a8a2..ef4e1632899 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -107,6 +107,12 @@ interpreter, native and Cranelift backends in both two-state and four-state mode wide-value latch checks, and a small sorter compilation smoke test. The 257/512-bit per-bit graph cases and sorter sizes 4/8/16/32 are measured by `benches/compilation.rs` in the existing daily/manual CodSpeed workflow. +Compilation benchmarks use CodSpeed walltime measurement on its x64 Ryzen +Macro Runner: CPU simulation made +a single 512-bit case take tens of minutes. The benchmark step has a 15-minute +timeout and the complete job a 60-minute limit; a timeout is reported as failure. +The organization runner group must allow this public repository to use CodSpeed +Macro Runners. Simulation and walltime measurements have separate baselines. Nested-write benchmarks reuse the same semantic assertions as the small tests. Scaling cases use one iteration without per-case warmups or adaptive sampling; a small counter warms process-global analyzer state before measurement. @@ -117,8 +123,8 @@ CodSpeed reporting workflow. Build and run them with the same CodSpeed harness as CI: ```sh -cargo codspeed build --locked -p celox --bench compilation -cargo codspeed run -p celox +cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation +cargo codspeed run --measurement-mode walltime -p celox --bench compilation ``` ## Finish validation diff --git a/crates/celox/benches/compilation.rs b/crates/celox/benches/compilation.rs index d99104ba6c7..984d896b73d 100644 --- a/crates/celox/benches/compilation.rs +++ b/crates/celox/benches/compilation.rs @@ -58,7 +58,7 @@ fn benchmark_scaling(c: &mut Criterion) { // Warm analyzer state before any measured span, including filtered runs. compile_default(COUNTER, "Top", Some(("N", 1))); // Each large design runs once: no five-run warmup or adaptive resampling. - // CodSpeed simulation measures one iteration; walltime uses the same schedule. + // Walltime uses this fixed schedule even for the largest graphs. for n in [4, 8, 16, 32] { c.bench_function(&format!("compile/sorter_tree/n{n}"), |b| { b.iter_manual_unstable(IterManualOptions::new(), || { diff --git a/scripts/benchmark-workflows.test.mjs b/scripts/benchmark-workflows.test.mjs index 5f58b398e90..f0ccd37de28 100644 --- a/scripts/benchmark-workflows.test.mjs +++ b/scripts/benchmark-workflows.test.mjs @@ -50,7 +50,7 @@ test("CodSpeed reports the current upload even after failure or cancellation", ( const benchmark = job(codspeed, "codspeed"); const report = job(codspeed, "report"); assert.match(benchmark, /run-id: \$\{\{ steps\.benchmarks\.outputs\.run-id \}\}/); - assert.match(benchmark, /id: benchmarks\n\s+uses: CodSpeedHQ\/action@v5/); + assert.match(benchmark, /id: benchmarks\n\s+timeout-minutes: 15\n\s+uses: CodSpeedHQ\/action@v5/); assert.match(report, /needs: codspeed/); assert.match(report, /checks: read/); assert.match(report, /issues: write/); @@ -165,3 +165,15 @@ test("profiling reuse rejects pre-CLI artifacts before capture", () => { assert.match(check, /predates the celox run CLI/); assert.match(check, /exit 1/); }); + + +test("compilation scaling uses walltime consistently and has a bounded execution", () => { + const benchmark = job(codspeed, "codspeed"); + assert.match(benchmark, /runs-on: codspeed-macro-x64-ryzen-9950x-ubuntu-24-04/); + assert.match(benchmark, /timeout-minutes: 60/); + assert.match(benchmark, /cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation/); + assert.match(benchmark, /id: benchmarks\n timeout-minutes: 15\n uses: CodSpeedHQ\/action@v5/); + assert.match(benchmark, /mode: walltime/); + assert.match(benchmark, /run: cargo codspeed run --measurement-mode walltime -p celox --bench compilation/); + assert.doesNotMatch(benchmark, /simulation|continue-on-error/); +}); From 8f35ef1974aac1ead77feadf1951d0db354fc7d9 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 05:30:48 +0900 Subject: [PATCH 3/6] ci: add a build-free CodSpeed runner probe Change-Id: I34c27f4234479a98dd5a1f2e45826759af799672 --- .github/workflows/codspeed.yml | 17 ++++++++++++++++- scripts/benchmark-workflows.test.mjs | 23 +++++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index 0830b896d1b..b2e70046aa3 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -4,6 +4,11 @@ on: schedule: - cron: "17 2 * * *" workflow_dispatch: + inputs: + runner_probe: + description: Check Macro Runner availability without building or benchmarking + type: boolean + default: false concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -16,8 +21,18 @@ env: permissions: {} jobs: + runner-probe: + name: Probe CodSpeed runner + if: github.event_name == 'workflow_dispatch' && inputs.runner_probe + runs-on: codspeed-macro-x64-ryzen-9950x-ubuntu-24-04 + timeout-minutes: 2 + steps: + - name: Verify the x64 runner is available + run: test "$(uname -m)" = x86_64 + codspeed: name: CodSpeed + if: inputs.runner_probe != true timeout-minutes: 60 runs-on: codspeed-macro-x64-ryzen-9950x-ubuntu-24-04 outputs: @@ -53,7 +68,7 @@ jobs: report: name: Report CodSpeed needs: codspeed - if: always() && (github.ref_name == 'master' || github.ref_name == 'develop') + if: always() && inputs.runner_probe != true && (github.ref_name == 'master' || github.ref_name == 'develop') runs-on: ubuntu-latest timeout-minutes: 10 permissions: diff --git a/scripts/benchmark-workflows.test.mjs b/scripts/benchmark-workflows.test.mjs index f0ccd37de28..cc3e564932a 100644 --- a/scripts/benchmark-workflows.test.mjs +++ b/scripts/benchmark-workflows.test.mjs @@ -59,9 +59,9 @@ test("CodSpeed reports the current upload even after failure or cancellation", ( assert.match(report, /run: node scripts\/report-codspeed\.mjs/); assert.doesNotMatch(codspeed, /continue-on-error:/); assert.match(codspeed, /cancel-in-progress: false/); - const condition = new Function("github", "always", `return (${expression(report, "if")});`); + const condition = new Function("github", "always", "inputs", `return (${expression(report, "if")});`); for (const branch of ["master", "develop", "feature"]) { - assert.equal(condition({ ref_name: branch }, () => true), branch !== "feature"); + assert.equal(condition({ ref_name: branch }, () => true, { runner_probe: false }), branch !== "feature"); } }); @@ -177,3 +177,22 @@ test("compilation scaling uses walltime consistently and has a bounded execution assert.match(benchmark, /run: cargo codspeed run --measurement-mode walltime -p celox --bench compilation/); assert.doesNotMatch(benchmark, /simulation|continue-on-error/); }); + + +test("runner probe cannot build or benchmark and does not report a skipped benchmark as failure", () => { + const probe = job(codspeed, "runner-probe"); + const runner = block => block.match(/runs-on: (\S+)/)[1]; + assert.equal(runner(probe), runner(job(codspeed, "codspeed"))); + assert.doesNotMatch(probe, /checkout|cargo|CodSpeedHQ\/action/); + assert.match(probe, /timeout-minutes: 2/); + const probeCondition = new Function("github", "inputs", `return (${expression(probe, "if")});`); + const benchCondition = new Function("inputs", `return (${expression(job(codspeed, "codspeed"), "if")});`); + const reportCondition = new Function("github", "inputs", "always", `return (${expression(job(codspeed, "report"), "if")});`); + for (const runner_probe of [true, false]) { + const inputs = { runner_probe }; + assert.equal(Boolean(probeCondition({ event_name: "workflow_dispatch" }, inputs)), runner_probe); + assert.equal(benchCondition(inputs), !runner_probe); + assert.equal(reportCondition({ ref_name: "master" }, inputs, () => true), !runner_probe); + } + assert.equal(benchCondition({}), true); +}); From eb08d878c884902151fcc4f4173a044049fbf32f Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 05:33:32 +0900 Subject: [PATCH 4/6] ci: use the standard Graviton CodSpeed macro runner Change-Id: Ibcbf8e2b9f1a510006e52d7d3a26fed166f30bae --- .github/workflows/codspeed.yml | 8 ++++---- CONTRIBUTING.md | 2 +- scripts/benchmark-workflows.test.mjs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml index b2e70046aa3..a5509aebf40 100644 --- a/.github/workflows/codspeed.yml +++ b/.github/workflows/codspeed.yml @@ -24,17 +24,17 @@ jobs: runner-probe: name: Probe CodSpeed runner if: github.event_name == 'workflow_dispatch' && inputs.runner_probe - runs-on: codspeed-macro-x64-ryzen-9950x-ubuntu-24-04 + runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04 timeout-minutes: 2 steps: - - name: Verify the x64 runner is available - run: test "$(uname -m)" = x86_64 + - name: Verify the ARM64 runner is available + run: test "$(uname -m)" = aarch64 codspeed: name: CodSpeed if: inputs.runner_probe != true timeout-minutes: 60 - runs-on: codspeed-macro-x64-ryzen-9950x-ubuntu-24-04 + runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04 outputs: run-id: ${{ steps.benchmarks.outputs.run-id }} permissions: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef4e1632899..1eac4e7021c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -107,7 +107,7 @@ interpreter, native and Cranelift backends in both two-state and four-state mode wide-value latch checks, and a small sorter compilation smoke test. The 257/512-bit per-bit graph cases and sorter sizes 4/8/16/32 are measured by `benches/compilation.rs` in the existing daily/manual CodSpeed workflow. -Compilation benchmarks use CodSpeed walltime measurement on its x64 Ryzen +Compilation benchmarks use CodSpeed walltime measurement on its ARM64 Graviton Macro Runner: CPU simulation made a single 512-bit case take tens of minutes. The benchmark step has a 15-minute timeout and the complete job a 60-minute limit; a timeout is reported as failure. diff --git a/scripts/benchmark-workflows.test.mjs b/scripts/benchmark-workflows.test.mjs index cc3e564932a..5237aaedbb1 100644 --- a/scripts/benchmark-workflows.test.mjs +++ b/scripts/benchmark-workflows.test.mjs @@ -169,7 +169,7 @@ test("profiling reuse rejects pre-CLI artifacts before capture", () => { test("compilation scaling uses walltime consistently and has a bounded execution", () => { const benchmark = job(codspeed, "codspeed"); - assert.match(benchmark, /runs-on: codspeed-macro-x64-ryzen-9950x-ubuntu-24-04/); + assert.match(benchmark, /runs-on: codspeed-macro-arm64-graviton-ubuntu-22-04/); assert.match(benchmark, /timeout-minutes: 60/); assert.match(benchmark, /cargo codspeed build --locked --measurement-mode walltime -p celox --bench compilation/); assert.match(benchmark, /id: benchmarks\n timeout-minutes: 15\n uses: CodSpeedHQ\/action@v5/); From 8a2f25f96544a35aa027dea14a5da95d7d7b5246 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 06:06:27 +0900 Subject: [PATCH 5/6] feat(sim)!: show the regions of a time slot to a slot observer A host such as a VPI driver needs to see an edge before the flip-flop domains commit, and every settled slot. Simulation::observe_slots installs a SlotObserver: before_domains runs in every round once its processes and scheduled values have run and before its domains evaluate, end_of_slot once the slot has settled. Writes there are blocking host writes at the slot's time; the round settles them before the domains read them, and those at the end of a slot are settled at that time before the simulation advances. The compiled scheduler keeps every kernel it can. SchedulerSchema records, per kernel, the event signals it writes: the slots of the kernels and host clocks that may change an observed event signal run in the reference loop, the others stay compiled, one slot per run while an observer is installed. A differential simulation stops checking, as its shadow does not see the observer's writes. BREAKING CHANGE: native image containers are version 35; images of earlier versions no longer load. SchedulerSchema has a new public field, kernel_events. Part of #1730 Change-Id: I4ffaef0e5b3b716ec5185ff0250aeb33114fb496 --- crates/celox-design/src/lib.rs | 4 + .../src/symbolic/assembly.rs | 1 + crates/celox-runtime/src/schedule.rs | 22 ++ .../celox-runtime/src/simulation/compiled.rs | 31 ++- crates/celox-runtime/src/simulation/host.rs | 17 ++ crates/celox-runtime/src/simulation/mod.rs | 23 +- crates/celox-runtime/src/simulation/round.rs | 9 + crates/celox-runtime/src/simulation/time.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/lib.rs | 50 +++- crates/celox/src/scheduler.rs | 32 ++- crates/celox/src/simulation.rs | 99 +++++++- crates/celox/src/simulator.rs | 6 + crates/celox/tests/slot_observer.rs | 217 ++++++++++++++++++ 14 files changed, 499 insertions(+), 18 deletions(-) create mode 100644 crates/celox/tests/slot_observer.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 5e45cf13916..9a6ccd0d0c6 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1058,6 +1058,9 @@ pub struct SchedulerSchema { /// The event signals a host periodic clock may drive inside the /// scheduler's slots, in the order of its clock slots. pub clocks: Vec, + /// Per process kernel, the event signals it writes, as indices into + /// [`Self::events`]; empty for a kernel the scheduler does not run. + pub kernel_events: Vec>, } impl SchedulerSchema { @@ -1069,6 +1072,7 @@ impl SchedulerSchema { fallback: self.fallback, events: self.events.into_iter().map(&mut map).collect(), clocks: self.clocks.into_iter().map(map).collect(), + kernel_events: self.kernel_events, } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 7682ec5627d..aab80fca1fd 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2072,6 +2072,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( fallback: Vec::new(), events: Vec::new(), clocks: Vec::new(), + kernel_events: Vec::new(), }); // The runtime reads counters, the signals waits watch and staged // nonblocking values directly; no unit loads a wait's signal. diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index b9a0e39311b..4d8e7f255e0 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -77,6 +77,10 @@ pub(crate) struct SchedulerRefs { /// The event id and signal of each host clock the scheduler may run, /// in the order of its clock slots. pub(crate) clocks: Vec<(usize, SignalRef)>, + /// Per process kernel, the bits of `levels` of the events it writes. + pub(crate) kernel_events: Vec, + /// Per clock slot, the bit of `levels` of its event. + pub(crate) clock_events: Vec, pub(crate) clock_next: SignalRef, pub(crate) clock_period: SignalRef, pub(crate) clock_value: SignalRef, @@ -365,6 +369,24 @@ impl ResolvedSchedule { .iter() .map(|event| backend.resolve_event_opt(event).map(|event| event.id())) .collect::>()?, + kernel_events: (0..scheduler.fallback.len()) + .map(|index| { + scheduler + .kernel_events + .get(index) + .into_iter() + .flatten() + .fold(0, |mask, &bit| mask | 1 << bit) + }) + .collect(), + clock_events: scheduler + .clocks + .iter() + .map(|clock| { + let bit = scheduler.events.iter().position(|event| event == clock)?; + Some(1 << bit) + }) + .collect::>()?, clocks: scheduler .clocks .iter() diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index aa78df40bca..5fff1ceb3e2 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -75,17 +75,19 @@ impl SimulationState { || !pending.ready.is_empty() || !pending.inactive.is_empty() || !pending.nba_queue.is_empty() - || pending - .waiters - .iter() - .any(|(process, _)| scheduler.waits.get(process).is_none_or(Option::is_none)) + || pending.waiters.iter().any(|(process, _)| { + scheduler.waits.get(process).is_none_or(Option::is_none) + || self.writes_observed(scheduler, process) + }) { return None; } let mut first = u64::MAX; let mut other = u64::MAX; for &Reverse((time, process)) in self.process_wakeups.iter() { - if scheduler.wake.get(process).is_some_and(Option::is_some) { + if scheduler.wake.get(process).is_some_and(Option::is_some) + && !self.writes_observed(scheduler, process) + { first = first.min(time); } else { other = other.min(time); @@ -100,8 +102,10 @@ impl SimulationState { let clocks = &self.scheduler.clocks; let compiled = compiled_clocks(scheduler, queue, clocks); for event in queue { - if clock_slot(scheduler, event, clocks).is_some_and(|bit| compiled >> bit & 1 != 0) - { + if clock_slot(scheduler, event, clocks).is_some_and(|bit| { + compiled >> bit & 1 != 0 + && scheduler.clock_events[bit] & self.observed_events == 0 + }) { first = first.min(event.time); } else { other = other.min(event.time); @@ -126,6 +130,15 @@ impl SimulationState { }) } + /// Whether `process` may change an event the host observes, so that + /// its slots run in the reference loop. + fn writes_observed(&self, scheduler: &SchedulerRefs, process: usize) -> bool { + scheduler + .kernel_events + .get(process) + .is_some_and(|&events| events & self.observed_events != 0) + } + /// Run the compiled scheduler for the slots up to `limit`. Returns, like /// [`Self::step_until`], the time of the last slot run. pub(super) fn run_compiled( @@ -393,6 +406,10 @@ impl SimulationState { } } executor.try_finish_timed_step(now)?; + // What the host writes after the slot is an update of its time. + if executor.take_slot_writes() { + self.host_pending = true; + } Ok(now) } } diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index e2dca455e4c..206b2f1cdd0 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -81,6 +81,23 @@ pub trait HostBoundary: UnitExecutor { output } + /// Called in every round when its processes and scheduled values have + /// run and its flip-flop domains are about to evaluate: the round's + /// edges are in state, and no domain has committed. Returns whether the + /// host wrote state; the round then settles it before the domains read + /// it. Writes to signals a wait watches are logged as in + /// [`Self::take_host_writes`]. + fn before_domains(&mut self, _timestamp: u64) -> Result { + Ok(false) + } + + /// Whether the host wrote state in [`Self::try_finish_timed_step`] + /// since the last call. The writes are updates of that slot's time: the + /// next step settles them there. + fn take_slot_writes(&mut self) -> bool { + false + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 7523e231da0..05d3f8e0ecb 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -27,7 +27,7 @@ pub use wait::{Baseline, Waiter, Waiters}; use self::round::Round; use crate::{ - SimulatorErrorCode, + SignalRef, SimulatorErrorCode, backend::SimBackend, schedule::ResolvedSchedule, scheduler::{Scheduler, SimEvent}, @@ -161,6 +161,10 @@ pub struct SimulationState { slot_passes: u64, /// The loop that runs time slots, and the slots each loop ran. stats: SchedulerStats, + /// The bits of the compiled scheduler's events whose changes the host + /// observes inside a slot: the kernels and host clocks that write them + /// run in the reference loop. + observed_events: u64, } impl SimulationState { @@ -213,6 +217,7 @@ impl SimulationState { return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, stats: SchedulerStats::default(), + observed_events: 0, }; state.stats.kernels = (0..state.model.processes.len()) .map(|index| match state.model.kernel_fallback.get(index) { @@ -341,6 +346,22 @@ impl SimulationState { &self.stats } + /// The signals whose changes the host observes inside a time slot (see + /// [`HostBoundary::before_domains`]). The slots in which a kernel or + /// host clock of the compiled scheduler may change an observed event + /// signal run in the reference loop, where the host sees the change + /// before any domain commits; the other kernels' slots stay compiled. + pub fn set_observed_signals(&mut self, signals: impl IntoIterator) { + let Some(scheduler) = &self.model.scheduler else { + return; + }; + self.observed_events = signals + .into_iter() + .filter_map(|signal| self.model.signal_to_id.get(&signal)) + .filter_map(|event| scheduler.events.iter().position(|id| id == event)) + .fold(0, |mask, bit| mask | 1 << bit); + } + /// [`Self::step_until`], showing the step to `observer`. An error of /// the observer replaces the step's result. pub fn step_until_observed( diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 813b446c1a2..630f3fdd904 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -536,6 +536,15 @@ impl SimulationState { loop { let mut any_new_outer_loop_trigger = false; let mut newly_triggered = Vec::new(); + // The host sees the wave's edges before its domains commit, and + // its writes are in state before they evaluate. + if executor.before_domains(current_time)? { + for (signal, value) in executor.take_host_writes() { + self.observe_host_write(signal, &value); + } + executor.eval_comb()?; + self.observe_driven(executor.backend()); + } loop { let mut any_new_sequential_trigger = false; diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index f5e2bde7145..a6fee8795ab 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -191,6 +191,10 @@ impl SimulationState { self.step_round(executor, current_time, Vec::new(), ready, false)?; } 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() { + self.host_pending = true; + } Ok(()) } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0c95b249cc8..7278978181c 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 = 34; +const CONTAINER_VERSION: u16 = 35; 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/lib.rs b/crates/celox/src/lib.rs index 28c216b193e..2ccf09b621e 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -108,7 +108,7 @@ mod host_api { }; pub use crate::debug::CompilationTraceResult; pub use crate::diagnostics::DiagnosticsOptions; - pub use crate::simulation::{Simulation, SimulationCheckpoint}; + pub use crate::simulation::{Simulation, SimulationCheckpoint, SlotObserver}; #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -169,6 +169,54 @@ mod host_api { } } + /// State access of a [`SlotObserver`] inside a time slot: reads see + /// the slot's state so far, writes are blocking writes of the host at + /// the slot's time. + pub struct SlotIo<'a, B: SimBackend = DefaultBackend> { + io: IOContext<'a, B>, + wrote: bool, + } + + impl<'a, B: SimBackend> SlotIo<'a, B> { + pub(crate) fn new(io: IOContext<'a, B>) -> Self { + Self { io, wrote: false } + } + + pub(crate) fn wrote(&self) -> bool { + self.wrote + } + + /// The stored value, with X/Z bits as their payload. + pub fn get(&self, signal: crate::SignalRef) -> crate::BigUint { + self.io.backend.get(signal) + } + + /// The stored payload and X/Z mask. + pub fn get_four_state(&self, signal: crate::SignalRef) -> (crate::BigUint, crate::BigUint) { + self.io.get_four_state(signal) + } + + pub fn set(&mut self, signal: crate::SignalRef, val: T) { + self.wrote = true; + self.io.set(signal, val); + } + + pub fn set_wide(&mut self, signal: crate::SignalRef, val: crate::BigUint) { + self.wrote = true; + self.io.set_wide(signal, val); + } + + pub fn set_four_state( + &mut self, + signal: crate::SignalRef, + val: crate::BigUint, + mask: crate::BigUint, + ) { + self.wrote = true; + self.io.set_four_state(signal, val, mask); + } + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 6287e96a9ee..ad39a81df2e 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -71,15 +71,36 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { return; }; let kernels = program.runtime.runtime_schema.processes.len(); - let (fallback, unit, events, clocks) = match Plan::new(program, &schema.slots) { - Err(reason) => (vec![Some(reason); kernels], None, Vec::new(), Vec::new()), + let (fallback, unit, events, clocks, kernel_events) = match Plan::new(program, &schema.slots) { + Err(reason) => ( + vec![Some(reason); kernels], + None, + Vec::new(), + Vec::new(), + vec![Vec::new(); kernels], + ), Ok(plan) => { let fallback = plan.fallback.clone(); // Without kernels, slots of host clocks alone. let unit = (plan.kernels.iter().any(Option::is_some) || !plan.clocks.is_empty()) .then(|| plan.generate(program, &schema.slots)); - let events = plan - .edged() + let edged = plan.edged(); + let kernel_events = plan + .kernels + .iter() + .map(|kernel| { + kernel + .iter() + .flat_map(|kernel| &kernel.writes) + .map(|event| { + edged + .binary_search(event) + .expect("the scheduler's kernels write edged events") + }) + .collect() + }) + .collect(); + let events = edged .into_iter() .map(|event| plan.events[event].signal) .collect(); @@ -88,7 +109,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { .iter() .map(|&event| plan.events[event].signal) .collect(); - (fallback, unit, events, clocks) + (fallback, unit, events, clocks, kernel_events) } }; let scheduler = program @@ -100,6 +121,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { scheduler.fallback = fallback; scheduler.events = events; scheduler.clocks = clocks; + scheduler.kernel_events = kernel_events; if let Some(unit) = unit { scheduler.unit = Some(program.sir.processes.len()); program.sir.processes.push(unit); diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index fa8d71e731d..4023e326033 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -57,6 +57,33 @@ impl std::fmt::Debug for SimulationCheckpoint { /// A timed simulation wrapper around the core logic engine. /// +/// What a host observes inside the time slots of a [`Simulation`], in +/// addition to the state between steps: changes of its signals before the +/// flip-flop domains commit, and the settled slot. +/// +/// A slot observer is how a host such as a VPI driver keeps the regions of +/// IEEE 1800-2023 4.4 inside one time slot. Its writes are blocking writes +/// of the host at the slot's time, like [`Simulation::modify`]. +pub trait SlotObserver { + /// A round of the slot has run its processes and scheduled values and + /// is about to evaluate its flip-flop domains: the round's edges are in + /// state and no nonblocking update has been made. Writes are in state + /// before the domains evaluate. + fn before_domains(&mut self, io: &mut crate::SlotIo<'_, B>, time: u64); + + /// The slot has settled: every region is empty. Writes are updates of + /// `time`, which the simulation settles there before it advances. + /// + /// This is where an observer finds the changes of signals that are not + /// among the event signals it watches: after the nonblocking updates of + /// the slot and the combinational settle that follows them. That is an + /// implementation choice, not an order the standard fixes: the observer's + /// callback and the updates the settle makes are active events of the + /// same region, which a simulator may process in any order (IEEE + /// 1800-2023 4.7). + fn end_of_slot(&mut self, io: &mut crate::SlotIo<'_, B>, time: u64); +} + /// Manages simulation time, periodic clocks, and an event queue. /// /// The default type parameter uses the host's [`crate::DefaultBackend`]. @@ -218,14 +245,27 @@ impl HostBoundary for Simulator { Ok(()) } + fn before_domains(&mut self, timestamp: u64) -> Result { + Ok(!self.frozen + && self.show_slot(timestamp, |observer, io, time| { + observer.before_domains(io, time) + })) + } + + fn take_slot_writes(&mut self) -> bool { + std::mem::take(&mut self.slot_writes) + } + fn compiled_slots(&self) -> celox_runtime::CompiledSlots { use celox_runtime::CompiledSlots; if self.frozen || !self.components.is_empty() || !self.backend.runs_compiled_scheduler() { return CompiledSlots::None; } - // Waveforms record, and the heap collects, at every slot boundary. + // Waveforms record, the heap collects and a slot observer looks at + // every slot boundary. let vcd = &self.sv_vcd; - if self.vcd_writer.is_some() + if self.slot_observer.is_some() + || self.vcd_writer.is_some() || vcd.path.is_some() || vcd.started.is_some() || vcd.pending @@ -254,7 +294,35 @@ impl HostBoundary for Simulator { })?; self.dirty = false; self.try_dump_unless_rewound(timestamp) - .map_err(|error| Halt::Error(vcd_dump_runtime_error(error))) + .map_err(|error| Halt::Error(vcd_dump_runtime_error(error)))?; + if !self.frozen { + self.slot_writes |= self.show_slot(timestamp, |observer, io, time| { + observer.end_of_slot(io, time) + }); + } + Ok(()) + } +} + +impl Simulator { + /// Show the slot observer, if any, the state at `time`. Returns whether + /// it wrote. + fn show_slot( + &mut self, + time: u64, + show: impl FnOnce(&mut dyn SlotObserver, &mut crate::SlotIo<'_, B>, u64), + ) -> bool { + let Some(observer) = self.slot_observer.as_deref_mut() else { + return false; + }; + let mut io = crate::SlotIo::new(crate::IOContext { + backend: &mut self.backend, + watch: &mut self.host_watch, + }); + show(observer, &mut io, time); + let wrote = io.wrote(); + self.dirty |= wrote; + wrote } } @@ -528,6 +596,31 @@ impl Simulation { Ok(()) } + /// Show every time slot to `observer`, which watches `signals`. + /// + /// The slots in which a compiled process kernel or host clock may change + /// an event signal among `signals` run in the reference loop, where + /// [`SlotObserver::before_domains`] sees the change before any domain + /// commits; the other kernels' slots stay compiled, one slot per run so + /// that [`SlotObserver::end_of_slot`] sees each of them. Changes of other + /// signals are the observer's to find, at either point. A differential + /// simulation stops checking: the shadow does not see the observer's + /// writes. + pub fn observe_slots(&mut self, observer: Box>, signals: &[SignalRef]) { + self.simulator.slot_observer = Some(observer); + self.state.set_observed_signals(signals.iter().copied()); + if self.shadow.take().is_some() { + self.unchecked = Some("a slot observer writes state the shadow does not see"); + } + } + + /// Stop showing the time slots to the observer of + /// [`Self::observe_slots`], and return it. + pub fn stop_observing_slots(&mut self) -> Option>> { + self.state.set_observed_signals([]); + self.simulator.slot_observer.take() + } + /// Register a clock signal and its period, enqueuing the first edge. /// Odd periods alternate floor/ceil half periods. Periods below two /// time units use a two-unit period so both phases advance time. diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index ffccc1394d2..3d73eee6348 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -174,6 +174,10 @@ mod host { pub(crate) frozen: bool, /// Host writes a timed simulation observes one at a time. pub(crate) host_watch: celox_runtime::HostWatch, + /// What a timed simulation's host observes inside its time slots. + pub(crate) slot_observer: Option>>, + /// The slot observer wrote at the end of the last time slot. + pub(crate) slot_writes: bool, /// Runtime-event sequence up to which a timed simulation looked for /// `$finish` records. pub(crate) finish_scan_seq: u64, @@ -896,6 +900,8 @@ mod host { derived_settle, frozen: false, host_watch: Default::default(), + slot_observer: None, + slot_writes: false, finish_scan_seq: 0, finish_sites: false, event_edges, diff --git a/crates/celox/tests/slot_observer.rs b/crates/celox/tests/slot_observer.rs new file mode 100644 index 00000000000..0731e515e57 --- /dev/null +++ b/crates/celox/tests/slot_observer.rs @@ -0,0 +1,217 @@ +//! A host that observes the regions inside a time slot, as a VPI driver +//! does (#1730): edges before the flip-flop domains commit, and settled +//! slots. +#![cfg(feature = "systemverilog")] + +use std::cell::RefCell; +use std::path::Path; +use std::rc::Rc; + +use celox::{SignalRef, SimBackend, Simulation, SlotIo, SlotObserver}; + +fn simulation(source: &str) -> Simulation { + Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .build() + .unwrap() +} + +const COUNTER: &str = r#"`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] q = 0; + logic [7:0] d = 0; + logic [7:0] ticks = 0; + always #5 clk = ~clk; + always #7 ticks = ticks + 1; + always_ff @(posedge clk) q <= q + 1; +endmodule +"#; + +/// Records `watched` at every rise of `clk` before the domains commit, and +/// writes `write` there if set. +struct Edges { + clk: SignalRef, + watched: SignalRef, + write: Option, + level: u8, + seen: Rc>>, +} + +impl SlotObserver for Edges { + fn before_domains(&mut self, io: &mut SlotIo<'_, B>, time: u64) { + let level = u8::try_from(io.get(self.clk)).unwrap(); + if level == 1 && self.level == 0 { + let value = u64::try_from(io.get(self.watched)).unwrap(); + self.seen.borrow_mut().push((time, value)); + if let Some(write) = self.write { + io.set(write, time as u8); + } + } + self.level = level; + } + + fn end_of_slot(&mut self, _: &mut SlotIo<'_, B>, _: u64) {} +} + +#[test] +fn an_observed_edge_is_seen_before_the_domains_commit() { + let mut sim = simulation(COUNTER); + let seen = Rc::new(RefCell::new(Vec::new())); + let clk = sim.signal("clk"); + let observer = Edges { + clk, + watched: sim.signal("q"), + write: None, + level: 0, + seen: Rc::clone(&seen), + }; + sim.observe_slots(Box::new(observer), &[clk]); + sim.run_until(40).unwrap(); + // The rises at 5, 15, 25 and 35 see the count before their update. + assert_eq!(*seen.borrow(), vec![(5, 0), (15, 1), (25, 2), (35, 3)]); + assert_eq!(sim.get(sim.signal("q")), 4u8.into()); +} + +#[test] +fn only_the_kernels_that_write_an_observed_event_leave_compiled_slots() { + let mut plain = simulation(COUNTER); + plain.run_until(200).unwrap(); + let unobserved = plain.scheduler_stats().compiled_slots; + assert!(unobserved > 0); + + let mut sim = simulation(COUNTER); + let clk = sim.signal("clk"); + let observer = Edges { + clk, + watched: sim.signal("q"), + write: None, + level: 0, + seen: Rc::default(), + }; + sim.observe_slots(Box::new(observer), &[clk]); + sim.run_until(200).unwrap(); + let observed = sim.scheduler_stats().compiled_slots; + // The slots of `ticks` alone (7, 14, 21, ... off the clock's) stay + // compiled; those of the clock run in the reference loop. + assert!( + observed > 0 && observed < unobserved, + "{observed} of {unobserved}" + ); + assert_eq!(sim.get(sim.signal("q")), plain.get(plain.signal("q"))); + assert_eq!( + sim.get(sim.signal("ticks")), + plain.get(plain.signal("ticks")) + ); +} + +#[test] +fn a_write_before_the_domains_is_what_they_sample() { + let source = r#"`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] d = 0; + logic [7:0] q = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) q <= d; +endmodule +"#; + let mut sim = simulation(source); + let clk = sim.signal("clk"); + let d = sim.signal("d"); + let observer = Edges { + clk, + watched: d, + write: Some(d), + level: 0, + seen: Rc::default(), + }; + sim.observe_slots(Box::new(observer), &[clk]); + sim.run_until(16).unwrap(); + // The rise at 15 samples the 15 the host wrote at that edge. + assert_eq!(sim.get(sim.signal("q")), 15u8.into()); +} + +/// At the end of every slot, records changes of `watched` and sets `flag` +/// once `watched` reaches `at`. +struct Settled { + watched: SignalRef, + flag: SignalRef, + at: u64, + last: u64, + seen: Rc>>, +} + +impl SlotObserver for Settled { + fn before_domains(&mut self, _: &mut SlotIo<'_, B>, _: u64) {} + + fn end_of_slot(&mut self, io: &mut SlotIo<'_, B>, time: u64) { + let value = u64::try_from(io.get(self.watched)).unwrap(); + if value != self.last { + self.seen.borrow_mut().push((time, value)); + if value == self.at { + io.set(self.flag, 1u8); + } + } + self.last = value; + } +} + +#[test] +fn a_settled_slot_shows_every_change_and_its_writes_stay_in_the_slot() { + let source = r#"`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] q = 0; + logic flag = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) q <= q + 1; + initial begin + wait (flag); + $display("flag at %0t q=%0d", $time, q); + end +endmodule +"#; + let mut sim = simulation(source); + let seen = Rc::new(RefCell::new(Vec::new())); + let watched = sim.signal("q"); + let observer = Settled { + watched, + flag: sim.signal("flag"), + at: 2, + last: 0, + seen: Rc::clone(&seen), + }; + sim.observe_slots(Box::new(observer), &[watched]); + sim.run_until(40).unwrap(); + // Every slot of the compiled clock is seen, one per run. + assert_eq!(*seen.borrow(), vec![(5, 1), (15, 2), (25, 3), (35, 4)]); + assert!(sim.scheduler_stats().compiled_slots > 0); + // The flag written at the end of slot 15 wakes the process at 15. + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"flag at 15 q=2".to_vec() + }] + ); +} + +#[test] +fn a_differential_simulation_stops_checking_an_observed_simulation() { + let mut sim = Simulation::from_sv_sources(vec![(COUNTER, Path::new("top.sv"))], "Top") + .scheduler_mode(celox::SchedulerMode::Differential) + .build() + .unwrap(); + let watched = sim.signal("q"); + let observer = Settled { + watched, + flag: sim.signal("d"), + at: u64::MAX, + last: 0, + seen: Rc::default(), + }; + sim.observe_slots(Box::new(observer), &[watched]); + sim.run_until(40).unwrap(); + let stats = sim.scheduler_stats(); + assert_eq!(stats.checked_steps, 0); + assert!(stats.unchecked.is_some()); +} From 92a858edf7b5645fa56f3472039728aa6c1c13b9 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 06:06:27 +0900 Subject: [PATCH 6/6] chore: observe a signal in the scheduler bench Change-Id: I5737eb89d7389cb84585ee295af57fac35d9ccc4 --- crates/celox/examples/sched_bench.rs | 54 ++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/crates/celox/examples/sched_bench.rs b/crates/celox/examples/sched_bench.rs index 2ca280dd104..332dccb682a 100644 --- a/crates/celox/examples/sched_bench.rs +++ b/crates/celox/examples/sched_bench.rs @@ -1,6 +1,6 @@ //! Timed-scheduler overhead benchmark for instruction-count comparisons. //! -//! Usage: `sched_bench [default|reference|compiled] [native|interp]` +//! Usage: `sched_bench [default|reference|compiled] [native|interp] [observe=]` //! //! Every variant clocks the same 64 registers `rK <= rK + (seed ^ K)`: //! @@ -17,7 +17,9 @@ //! //! The optional third argument selects the timed scheduler (hidden builder //! option), by default the library's; the fourth the backend, by default the -//! host's native one. +//! host's native one. With a fifth, `observe=`, a timed variant runs +//! with a slot observer that counts the changes of `` at the end of +//! every slot, as a VPI value-change callback does. //! //! The scheduler's cost per cycle is the difference of the whole-program //! instruction counts of two runs, which cancels compilation: @@ -138,10 +140,18 @@ fn main() { Some(other) => panic!("unknown scheduler {other}: expected reference or compiled"), }; let builder = celox::Simulation::from_sv_sources(sources, "Top").scheduler_mode(mode); + let observed = args + .get(5) + .map(|arg| arg.strip_prefix("observe=").expect("observe=")); if interpreter { - run(builder.build_interpreter().unwrap(), variant, cycles) + run( + builder.build_interpreter().unwrap(), + variant, + cycles, + observed, + ) } else { - run(builder.build().unwrap(), variant, cycles) + run(builder.build().unwrap(), variant, cycles, observed) } }; println!("{variant} {cycles} out={out:?}"); @@ -159,12 +169,42 @@ fn tick(mut sim: celox::Simulator, cycles: u64) -> celo sim.get(out) } +/// Counts the changes of one signal at the end of every slot. +struct Changes { + signal: celox::SignalRef, + last: Option, + count: std::rc::Rc>, +} + +impl celox::SlotObserver for Changes { + fn before_domains(&mut self, _: &mut celox::SlotIo<'_, B>, _: u64) {} + + fn end_of_slot(&mut self, io: &mut celox::SlotIo<'_, B>, _: u64) { + let value = io.get(self.signal); + if self.last.as_ref() != Some(&value) { + self.count.set(self.count.get() + 1); + self.last = Some(value); + } + } +} + /// The timed variants: run `cycles` clock periods. fn run( mut sim: celox::Simulation, variant: &str, cycles: u64, + observed: Option<&str>, ) -> celox::BigUint { + let changes = std::rc::Rc::new(std::cell::Cell::new(0)); + if let Some(path) = observed { + let signal = sim.signal(path); + let observer = Changes { + signal, + last: None, + count: std::rc::Rc::clone(&changes), + }; + sim.observe_slots(Box::new(observer), &[signal]); + } if variant == "ac" { let seed = sim.signal("seed"); sim.modify(|io| io.set(seed, 7u32)).unwrap(); @@ -179,8 +219,10 @@ fn run( sim.run_until(cycles * 10).unwrap(); let stats = sim.scheduler_stats(); println!( - "compiled slots {}, kernels {:?}", - stats.compiled_slots, stats.kernels + "compiled slots {}, kernels {:?}, observed changes {}", + stats.compiled_slots, + stats.kernels, + changes.get() ); let out = sim.signal("out"); sim.get(out)