From e6a9338fbd25dcc765e9474e4cb01ff411f34cb9 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 08:42:45 +0900 Subject: [PATCH 1/8] refactor(frontend)!: declare the slots of a compiled scheduler Timed designs get hidden `$scheduler.*` variables on the top module: the limit, current time, exit code and argument, current kernel, start-of-slot levels, finish flag, settle continuation and slot count of a run, and a wake time and waiting flag per process kernel. RuntimeSchema::scheduler (and ScheduleModel::scheduler) carries them with the index of a generated scheduler unit and why each kernel falls back. State files leave the slots out; the native image carries the schema, accepts the extra process unit, and moves to format 29. BREAKING CHANGE: RuntimeSchema and ScheduleModel have a new field, `scheduler`. Native images use container format 29; images written by earlier versions must be rebuilt. Change-Id: Ia8fd6db4be840280b8e1b964521f291af2419c8e --- crates/celox-design/src/lib.rs | 136 ++++++++++++++++++ crates/celox-design/src/schedule.rs | 4 + .../src/symbolic/assembly.rs | 78 +++++++++- crates/celox/src/backend/native/backend.rs | 24 +++- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulator/state_file.rs | 15 +- 6 files changed, 255 insertions(+), 4 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 50e687c8a08..7cb1572d8e2 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -842,6 +842,141 @@ pub struct RuntimeSchema { /// most one per module instance. Before each round a timed scheduler /// stores the current time into each, as [`TIME_SLOT_WIDTH`] bits. pub time_slots: Vec, + /// The state a compiled scheduler exchanges with the runtime, and the + /// scheduler itself once one is generated. Present when the design has + /// process kernels. + pub scheduler: Option>, +} + +/// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`], +/// [`SchedulerSlots::exit_arg`], [`SchedulerSlots::count`], +/// [`SchedulerSlots::current`], [`SchedulerSlots::levels`] and every [`SchedulerSlots::wake`] object. +pub const SCHEDULER_TIME_WIDTH: usize = 64; +/// Width of [`SchedulerSlots::exit`], [`SchedulerSlots::finish`], +/// [`SchedulerSlots::cont`] and every [`SchedulerSlots::waiting`] object. +pub const SCHEDULER_FLAG_WIDTH: usize = 8; + +/// Hidden state objects through which a compiled scheduler and the runtime +/// exchange a run of time slots. Between runs they hold no state: the +/// runtime's scheduling state is the source of truth, so state files leave +/// them out. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct SchedulerSlots { + /// The last time the run may reach. + pub limit: A, + /// The time of the last slot the run reached. + pub now: A, + /// Why the run returned, a [`SchedulerExit`] code. + pub exit: A, + /// The process an exit concerns. + pub exit_arg: A, + /// Set when a `$finish` record was emitted in the unit just run. + pub finish: A, + /// Where a shared combinational settle continues. + pub cont: A, + /// The number of time slots the run ran. + pub count: A, + /// The kernel running when the run returned, `u64::MAX` for none. + pub current: A, + /// The levels of the event signals at the start of the last slot, one + /// bit per event in event order. + pub levels: A, + /// The time each process kernel resumes at, in kernel order, valid + /// where [`Self::waiting`] is set. + pub wake: Vec, + /// Whether each process kernel waits for its wake time. + pub waiting: Vec, +} + +impl SchedulerSlots { + pub fn map(self, mut map: impl FnMut(A) -> B) -> SchedulerSlots { + SchedulerSlots { + limit: map(self.limit), + now: map(self.now), + exit: map(self.exit), + exit_arg: map(self.exit_arg), + finish: map(self.finish), + cont: map(self.cont), + count: map(self.count), + current: map(self.current), + levels: map(self.levels), + wake: self.wake.into_iter().map(&mut map).collect(), + waiting: self.waiting.into_iter().map(map).collect(), + } + } + + /// Every slot. + pub fn iter(&self) -> impl Iterator { + [ + &self.limit, + &self.now, + &self.exit, + &self.exit_arg, + &self.finish, + &self.cont, + &self.count, + &self.current, + &self.levels, + ] + .into_iter() + .chain(&self.wake) + .chain(&self.waiting) + } +} + +/// Why a run of the compiled scheduler returned. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[repr(u8)] +pub enum SchedulerExit { + /// The next time slot is after the limit. + Limit = 0, + /// A process or a `$finish` record finished the simulation. + Finish = 1, + /// The delay of process [`SchedulerSlots::exit_arg`] overflows the + /// simulation time. + DelayOverflow = 2, + /// A process suspended in a way the scheduler does not compile. + Internal = 3, +} + +impl SchedulerExit { + pub const fn from_code(code: u8) -> Option { + match code { + 0 => Some(Self::Limit), + 1 => Some(Self::Finish), + 2 => Some(Self::DelayOverflow), + 3 => Some(Self::Internal), + _ => None, + } + } +} + +/// A design's compiled scheduler: the process unit that runs time slots of +/// the kernels it compiles, and its slots. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct SchedulerSchema { + pub slots: SchedulerSlots, + /// The index of the scheduler unit among the process units, after the + /// kernels; `None` when no scheduler was generated. + pub unit: Option, + /// Per process kernel, why the scheduler does not run it, or `None` when + /// it does. + pub fallback: Vec>, + /// The event signals the scheduler's kernels write, in the order of + /// the bits of [`SchedulerSlots::levels`]. + pub events: Vec, +} + +impl SchedulerSchema { + pub fn map(self, map: impl FnMut(A) -> B) -> SchedulerSchema { + let mut map = map; + SchedulerSchema { + slots: self.slots.map(&mut map), + unit: self.unit, + fallback: self.fallback, + events: self.events.into_iter().map(map).collect(), + } + } } /// Width of every [`RuntimeSchema::time_slots`] object. @@ -869,6 +1004,7 @@ impl Default for RuntimeSchema { host_request_sites: Vec::new(), active_commits: Vec::new(), time_slots: Vec::new(), + scheduler: None, } } } diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index e7af72a6efd..e492266cc18 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -43,6 +43,9 @@ pub struct ScheduleModel { /// Objects the scheduler stores the current time into /// ([`RuntimeSchema::time_slots`]). pub time_slots: Vec, + /// The compiled scheduler, if one was generated + /// ([`RuntimeSchema::scheduler`]). + pub scheduler: Option>, } /// A counted signal and the canonical domains its counters trigger. @@ -142,6 +145,7 @@ impl ScheduleModel { .any(|site| matches!(site.kind, RuntimeEventKind::Finish)), active_commits: schema.active_commits.clone(), time_slots: schema.time_slots.clone(), + scheduler: schema.scheduler.clone(), } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 2c6fcd74880..6a8f45347bb 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -613,7 +613,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .expect("source program identity exhausted").to_string()) .entered(); let SymbolicRtl { - modules, + mut modules, module_names, root_id, packages, @@ -645,6 +645,11 @@ pub fn schedule_symbolic_rtl_reporting_loops( let (mut expanded, mut instance_modules, indexed_instances) = timed_sub!("expand_hierarchy", expand_hierarchy(&root_id, &modules)); + let process_count = instance_modules + .values() + .map(|module| modules[module].processes.len()) + .sum(); + let scheduler_slots = declare_scheduler_slots(&mut modules, root_id, process_count); // Each package with variables is one instance outside the hierarchy, // named by a path segment no instance name can take. let mut package_instances = HashMap::default(); @@ -1971,6 +1976,18 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(); let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); + let root_instance = expanded[&InstancePath(Vec::new())]; + let scheduler = scheduler_slots.map(|slots| celox_design::SchedulerSchema { + slots: slots.map(|var_id| { + project(AbsoluteAddr { + instance_id: root_instance, + var_id, + }) + }), + unit: None, + fallback: Vec::new(), + events: Vec::new(), + }); // The runtime reads counters, the signals waits watch and staged // nonblocking values directly; no unit loads a wait's signal. let mut timing_read_roots: HashSet = watches @@ -2072,6 +2089,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( host_request_sites, active_commits, time_slots, + scheduler, }, }; @@ -2089,6 +2107,64 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) } +/// Declare the hidden objects a compiled scheduler exchanges with the +/// runtime (`RuntimeSchema::scheduler`) as variables of the top module, +/// when the design has `process_count` process kernels. +fn declare_scheduler_slots( + modules: &mut HashMap, + root: ModuleId, + process_count: usize, +) -> Option> { + if process_count == 0 { + return None; + } + let variables = &mut modules.get_mut(&root)?.variables; + let mut next = variables.keys().map(|id| id.0 + 1).max().unwrap_or(0); + let mut declare = |name: String, width: usize| { + let id = SourceVarId(next); + next += 1; + variables.insert( + id, + crate::symbolic::artifact::SymbolicVariable { + path: vec!["$scheduler".to_string(), name], + kind: crate::VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state: false, + kind: DomainKind::Other, + type_kind: celox_design::PortTypeKind::Bit, + array_dims: Vec::new(), + value_kind: Default::default(), + }, + packed_dims: vec![width], + unpacked_ranges: Vec::new(), + source: None, + module_affiliated: false, + }, + ); + id + }; + use celox_design::{SCHEDULER_FLAG_WIDTH as FLAG, SCHEDULER_TIME_WIDTH as TIME}; + Some(celox_design::SchedulerSlots { + limit: declare("limit".into(), TIME), + now: declare("now".into(), TIME), + exit: declare("exit".into(), FLAG), + exit_arg: declare("exit_arg".into(), TIME), + finish: declare("finish".into(), FLAG), + cont: declare("cont".into(), FLAG), + count: declare("count".into(), TIME), + current: declare("current".into(), TIME), + levels: declare("levels".into(), TIME), + wake: (0..process_count) + .map(|index| declare(format!("wake[{index}]"), TIME)) + .collect(), + waiting: (0..process_count) + .map(|index| declare(format!("waiting[{index}]"), FLAG)) + .collect(), + }) +} + fn module_variables( modules: &HashMap, ) -> ( diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 1d1990bb5a4..76d361f2870 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -408,6 +408,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) host_request_sites: Vec>, pub(crate) active_commits: Vec, pub(crate) time_slots: Vec, + pub(crate) scheduler: Option>, } /// Pointer-free native compiler artifact which can be attached to the @@ -522,6 +523,7 @@ impl NativeProgramImage { host_request_sites: self.runtime_schema.host_request_sites.clone(), active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), + scheduler: self.runtime_schema.scheduler.clone(), }, testbench: self.testbench.clone(), } @@ -604,7 +606,26 @@ impl NativeProgramImage { { return Err("a process kernel offset does not name an image entry".into()); } - if self.process_offsets.len() != self.runtime_schema.processes.len() { + // A generated scheduler unit follows the kernels. + let scheduler_units = self + .runtime_schema + .scheduler + .as_ref() + .and_then(|scheduler| scheduler.unit) + .map_or(0, |unit| { + if unit == self.runtime_schema.processes.len() { + 1 + } else { + usize::MAX + } + }); + if self.process_offsets.len() + != self + .runtime_schema + .processes + .len() + .saturating_add(scheduler_units) + { return Err("process kernels and their control slots disagree".into()); } if self.required_native_features & !KNOWN_NATIVE_FEATURES != 0 { @@ -2418,6 +2439,7 @@ fn compile_program( declaration_startup: sir.runtime().runtime_schema.declaration_startup.clone(), active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), + scheduler: sir.runtime().runtime_schema.scheduler.clone(), }, layout: layout.clone(), native_memory_size, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 3a7780001a7..a36af8f6961 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 = 28; +const CONTAINER_VERSION: u16 = 29; 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/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 50b7218fed1..9359e2afc0f 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -376,7 +376,20 @@ impl Simulator { let comb_writes = &self.program.runtime_schema.comb_writes; // A timed simulation stores its time into the time slots, and a state // file keeps the time in its schedule; an untimed one reads zero. - let time_slots: crate::HashSet<_> = self.program.runtime_schema.time_slots.iter().collect(); + // A compiled scheduler's slots hold nothing between runs. + let time_slots: crate::HashSet<_> = self + .program + .runtime_schema + .time_slots + .iter() + .chain( + self.program + .runtime_schema + .scheduler + .iter() + .flat_map(|scheduler| scheduler.slots.iter()), + ) + .collect(); let mut objects: Vec<_> = self .backend .layout() From 92fb2b7752189fcaf7c504a364f42eb5c5df3f7a Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 08:42:45 +0900 Subject: [PATCH 2/8] feat(runtime)!: compiled time-slot loop for delay-only kernels A timed simulation now generates one SIR process unit that runs the time slots of kernels that only delay by constants: it takes the earliest wake time, publishes the time, runs the due kernels in kernel order, settles, runs the domain whose edge they gave (eval_apply) or several domains (eval_only each, then apply each) and settles again, exactly as the reference loop does for such a slot. It inlines the units the reference loop calls; nothing in the backends changes. SimulationState::run_until hands a stretch of slots to the unit when nothing else is pending (no waiting or ready process, no queued NBA, no host change, no scheduled event or other kernel's wakeup before it) and takes the wake times back. Any other slot, and every design or kernel that does not qualify, runs in the reference loop as before; the reasons are in scheduler_stats. A run that ends in the middle of a slot (a finish, a delay overflow, an error) leaves the reference's state: the kernel that ended it is filed nowhere, kernels due then that did not run are ready, and the slot's edge baseline is restored. Backends that run the unit slower than the loop (the interpreter, the tiered backend before it adopts generated code) keep the reference loop. SchedulerMode::Compiled is the default; SchedulerMode::DifferentialRuns checks multi-slot runs against the shadow. BREAKING CHANGE: SchedulerMode defaults to Compiled and has a new variant, DifferentialRuns; KernelSchedule::Reference holds a String. Change-Id: I33705e908c95b460326c670c2ab9c74a90c68449 --- crates/celox-runtime/src/backend.rs | 7 + crates/celox-runtime/src/lib.rs | 6 +- crates/celox-runtime/src/schedule.rs | 57 ++ .../celox-runtime/src/simulation/compiled.rs | 194 +++++ crates/celox-runtime/src/simulation/host.rs | 20 + crates/celox-runtime/src/simulation/mod.rs | 36 +- crates/celox-runtime/src/simulation/stats.rs | 7 +- crates/celox/src/backend/interp.rs | 6 + crates/celox/src/backend/tiered.rs | 6 + crates/celox/src/lib.rs | 3 + crates/celox/src/scheduler.rs | 812 ++++++++++++++++++ crates/celox/src/simulation.rs | 22 +- crates/celox/src/simulation/differential.rs | 235 ++++- crates/celox/src/simulator/builder.rs | 14 +- 14 files changed, 1403 insertions(+), 22 deletions(-) create mode 100644 crates/celox-runtime/src/simulation/compiled.rs create mode 100644 crates/celox/src/scheduler.rs diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index be3477e7562..511a3310d32 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -144,6 +144,13 @@ pub trait SimBackend { /// The heap, for changes made while no compiled code runs. fn heap_mut(&mut self) -> &mut celox_heap::Heap; + /// Whether a compiled scheduler's unit runs time slots for less than + /// the runtime's loop does. An interpreter executes the unit slower + /// than the loop's native bookkeeping. + fn runs_compiled_scheduler(&self) -> bool { + true + } + // ── event enumeration ─────────────────────────────────────── fn id_to_addr_slice(&self) -> &[AbsoluteAddr]; fn id_to_event_slice(&self) -> &[Self::Event]; diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index ecffa23e4b5..6dd1b5f2158 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -35,9 +35,9 @@ pub use reflection::{ }; pub use schedule::{ResolvedSchedule, host_watch}; pub use simulation::{ - EventInfo, HostBoundary, KernelSchedule, ScheduleKey, ScheduleParts, SchedulerMode, - SchedulerStats, SimulationExecutor, SimulationSnapshot, SimulationState, StepObserver, - UnitExecutor, + CompiledSlots, EventInfo, HostBoundary, KernelSchedule, ScheduleKey, ScheduleParts, + SchedulerMode, SchedulerStats, SimulationExecutor, SimulationSnapshot, SimulationState, + StepObserver, UnitExecutor, }; pub use state_file::{ BaselineRecord, NbaRecord, ProcessRecord, ScheduleRecord, ScheduledEvent, StateDifference, diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 560a9cd775b..e555082d04d 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -36,6 +36,29 @@ pub struct ResolvedSchedule { pub(crate) active_commits: bit_set::BitSet, /// Signals the current time is stored into before each round. pub(crate) time_slots: Vec, + /// The compiled scheduler, when one was generated. + pub(crate) scheduler: Option, + /// Per process kernel, why the compiled scheduler does not run it, or + /// `None` when it does. Empty when no scheduler was considered. + pub(crate) kernel_fallback: Vec>, +} + +/// A design's compiled scheduler resolved against a backend: its process +/// unit and the slots it exchanges a run with. +pub(crate) struct SchedulerRefs { + pub(crate) unit: usize, + pub(crate) limit: SignalRef, + pub(crate) now: SignalRef, + pub(crate) exit: SignalRef, + pub(crate) finish: SignalRef, + pub(crate) count: SignalRef, + pub(crate) current: SignalRef, + pub(crate) levels: SignalRef, + /// The wake and waiting slots of each kernel the scheduler runs, by + /// process index. + pub(crate) wake: Vec>, + /// The event ids of the bits of `levels`. + pub(crate) events: Vec, } impl ResolvedSchedule { @@ -212,6 +235,40 @@ impl ResolvedSchedule { timed: model.timed, active_commits, time_slots: model.time_slots.iter().map(resolve).collect(), + scheduler: model.scheduler.as_ref().and_then(|scheduler| { + let slots = &scheduler.slots; + Some(SchedulerRefs { + unit: scheduler.unit?, + limit: resolve(&slots.limit), + now: resolve(&slots.now), + exit: resolve(&slots.exit), + finish: resolve(&slots.finish), + count: resolve(&slots.count), + current: resolve(&slots.current), + levels: resolve(&slots.levels), + wake: slots + .wake + .iter() + .zip(&slots.waiting) + .zip(&scheduler.fallback) + .map(|((wake, waiting), fallback)| { + fallback + .is_none() + .then(|| (resolve(wake), resolve(waiting))) + }) + .collect(), + events: scheduler + .events + .iter() + .map(|event| backend.resolve_event_opt(event).map(|event| event.id())) + .collect::>()?, + }) + }), + kernel_fallback: model + .scheduler + .as_ref() + .map(|scheduler| scheduler.fallback.clone()) + .unwrap_or_default(), } } } diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs new file mode 100644 index 00000000000..fb98dba1379 --- /dev/null +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -0,0 +1,194 @@ +//! Runs of a design's compiled scheduler: the time slots it can take over +//! from the reference loop, and the hand-over of the scheduling state. + +use std::cmp::Reverse; + +use celox_design::SchedulerExit; + +use super::{CompiledSlots, SchedulerMode, SimulationExecutor, SimulationState}; +use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; + +impl SimulationState { + /// Whether a compiled scheduler may run slots of this simulation. + pub(super) fn compiles_slots(&self) -> bool { + self.model.scheduler.is_some() && self.stats.mode != SchedulerMode::Reference + } + + /// The limit of a run of the compiled scheduler that may start now and + /// end by `end`, running one slot only if `one_slot`, or `None` when the + /// next slot needs the reference loop. + /// + /// A run takes the slots due to the kernels the scheduler runs while + /// nothing else is pending: no process waits for an event or is ready, + /// no nonblocking assignment is queued, no host change awaits a settle, + /// and the slot comes before every scheduled event and every wakeup of + /// another kernel. + pub(super) fn compiled_limit(&self, executor: &E, end: u64, one_slot: bool) -> Option + where + E: SimulationExecutor, + { + let scheduler = self.model.scheduler.as_ref()?; + let pending = &self.process_state; + if self.finished + || self.stopped + || self.suspended.is_some() + || self.declarations_pending + || self.host_pending + || !pending.ready.is_empty() + || !pending.inactive.is_empty() + || !pending.nba_queue.is_empty() + || !pending.waiters.is_empty() + { + 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) { + first = first.min(time); + } else { + other = other.min(time); + } + } + let reference = other.min(self.scheduler.next_event_time().unwrap_or(u64::MAX)); + // Time zero starts processes in their own order; the reference loop + // runs it. + if first == u64::MAX || first == 0 || first > end || first >= reference { + return None; + } + let one_slot = match executor.compiled_slots() { + CompiledSlots::None => return None, + CompiledSlots::One => true, + CompiledSlots::Any => one_slot, + }; + Some(if one_slot { + first + } else { + end.min(reference - 1) + }) + } + + /// 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( + &mut self, + executor: &mut E, + limit: u64, + ) -> Result, SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.stopped = false; + match self.run_compiled_slots(executor, limit) { + Ok(time) => Ok(Some(time)), + Err(Halt::Finish) => { + self.finalize_terminal(executor)?; + Ok(Some(self.scheduler.time)) + } + Err(Halt::Stop) => Ok(Some(self.scheduler.time)), + Err(Halt::Error(error)) => { + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } + } + } + + fn run_compiled_slots(&mut self, executor: &mut E, limit: u64) -> Result + where + E: SimulationExecutor, + { + let scheduler = self + .model + .scheduler + .as_ref() + .ok_or(SimulatorErrorCode::InternalError)?; + let backend = executor.backend_mut(); + backend.set(scheduler.limit, limit); + backend.set(scheduler.exit, 0u8); + backend.set(scheduler.finish, 0u8); + backend.set(scheduler.count, 0u64); + for &(_, waiting) in scheduler.wake.iter().flatten() { + backend.set(waiting, 0u8); + } + // The scheduler's kernels wait in its wake slots during the run. + let mut kept = Vec::with_capacity(self.process_wakeups.len()); + for wakeup @ Reverse((time, process)) in self.process_wakeups.drain() { + match scheduler.wake.get(process).copied().flatten() { + Some((wake, waiting)) => { + backend.set(wake, time); + backend.set(waiting, 1u8); + } + None => kept.push(wakeup), + } + } + self.process_wakeups.extend(kept); + let unit = scheduler.unit; + let result = executor.run_process(unit); + + let scheduler = self + .model + .scheduler + .as_ref() + .ok_or(SimulatorErrorCode::InternalError)?; + let backend = executor.backend(); + let count: u64 = backend.get_as(scheduler.count); + let now: u64 = backend.get_as(scheduler.now); + let exit = SchedulerExit::from_code(backend.get_as(scheduler.exit)); + let current: u64 = backend.get_as(scheduler.current); + let complete = result.is_ok() && exit == Some(SchedulerExit::Limit); + for (process, wake) in scheduler.wake.iter().enumerate() { + let Some((wake, waiting)) = *wake else { + continue; + }; + if backend.get_as::(waiting) == 0 { + continue; + } + let time: u64 = backend.get_as(wake); + if !complete && time == now { + // The run returned in the middle of slot `now`: the kernel + // that ended it is filed nowhere, as the reference loop + // leaves it, and kernels due then that did not run yet are + // still ready. + if process as u64 != current { + self.process_state.ready.insert(process); + } + continue; + } + self.process_wakeups.push(Reverse((time, process))); + } + self.stats.compiled_slots += count; + if count > 0 { + self.scheduler.time = now; + } + if complete { + // The slots ended with their levels as the baseline of the next. + self.resample_clock_values(executor.backend()); + } else if count > 0 { + // The baseline is the levels slot `now` started from; events the + // kernels do not write kept theirs. + let levels: u64 = executor.backend().get_as(scheduler.levels); + for (bit, &id) in scheduler.events.clone().iter().enumerate() { + self.record_level(id, u8::from(levels >> bit & 1 != 0)); + } + } + // Domains mark trigger bits as they run; between slots none is set. + executor.backend_mut().clear_triggered_bits(); + result?; + match exit { + Some(SchedulerExit::Limit) => {} + Some(SchedulerExit::Finish) => return Err(Halt::Finish), + Some(SchedulerExit::DelayOverflow) => { + return Err(Halt::Error(SimulatorErrorCode::Runtime { + message: format!("process {current} delay overflows simulation time"), + signals: Vec::new(), + })); + } + Some(SchedulerExit::Internal) | None => { + return Err(SimulatorErrorCode::InternalError.into()); + } + } + executor.try_finish_timed_step(now)?; + Ok(now) + } +} diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index f153709e0e7..e2dca455e4c 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -101,6 +101,13 @@ pub trait HostBoundary: UnitExecutor { Ok(()) } + /// How many time slots a compiled scheduler may run between calls of + /// [`Self::try_finish_timed_step`]. The default keeps every slot in the + /// runtime's loop. + fn compiled_slots(&self) -> CompiledSlots { + CompiledSlots::None + } + /// Called after the state for a simulation timestamp has stabilized. fn finish_timed_step(&mut self, _timestamp: u64) {} @@ -112,6 +119,19 @@ pub trait HostBoundary: UnitExecutor { } } +/// How many time slots a compiled scheduler may run at once (see +/// [`HostBoundary::compiled_slots`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompiledSlots { + /// None: the runtime's loop runs every slot. + None, + /// One per run: the host acts at every slot boundary. + One, + /// Any number: the host's boundary call after the last slot of a run + /// stands for the calls after the others. + Any, +} + /// Backend execution hooks needed by the timed simulation engine: its /// units and its host boundary. /// diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 81e6885be18..f5f950ad24b 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -2,6 +2,7 @@ //! batch step of designs without processes. mod batch; +mod compiled; mod edges; mod host; mod nba; @@ -18,7 +19,7 @@ use bit_set::BitSet; use celox_design::CounterKind; pub(crate) use batch::{edge_level, event_level}; -pub use host::{HostBoundary, HostWatch, SimulationExecutor, UnitExecutor}; +pub use host::{CompiledSlots, HostBoundary, HostWatch, SimulationExecutor, UnitExecutor}; pub use nba::NbaUpdate; pub use persist::{ScheduleKey, ScheduleParts, SimulationSnapshot}; pub use stats::{KernelSchedule, SchedulerMode, SchedulerStats}; @@ -87,6 +88,12 @@ struct Suspended { /// Sees the steps of [`SimulationState::run_until_observed`] and /// [`SimulationState::step_until_observed`]. pub trait StepObserver { + /// Whether a run of the compiled scheduler takes one slot at a time, so + /// that every slot is a step the observer sees. + fn one_slot(&self) -> bool { + false + } + /// Called before a step, with the state it starts from. fn before_step(&mut self, state: &SimulationState, executor: &mut E); @@ -207,10 +214,13 @@ impl SimulationState { slot_passes: 0, stats: SchedulerStats::default(), }; - state.stats.kernels = vec![ - KernelSchedule::Reference("the design has no compiled scheduler"); - state.model.processes.len() - ]; + state.stats.kernels = (0..state.model.processes.len()) + .map(|index| match state.model.kernel_fallback.get(index) { + Some(None) if state.model.scheduler.is_some() => KernelSchedule::Compiled, + Some(Some(reason)) => KernelSchedule::Reference(reason.clone()), + _ => KernelSchedule::Reference("the design has no compiled scheduler".into()), + }) + .collect(); state.synchronize_event_values(backend); state } @@ -284,11 +294,25 @@ impl SimulationState { // describing different moments, so an earlier target is a no-op. return Ok(false); } + let compiles = self.compiles_slots(); while let Some(next_time) = self.next_event_time() { if next_time > end { break; } - self.step_until_observed(executor, end, observer)?; + // A waiting process keeps the slot in the reference loop; test + // that first, as fallback designs fail it at every step. + let compiled = if compiles && self.process_state.waiters.is_empty() { + self.compiled_limit(executor, end, observer.one_slot()) + } else { + None + }; + observer.before_step(self, executor); + let result = match compiled { + Some(limit) => self.run_compiled(executor, limit), + None => self.step_until(executor, end), + }; + observer.after_step(self, executor, end, &result)?; + result?; if self.stopped { return Ok(false); } diff --git a/crates/celox-runtime/src/simulation/stats.rs b/crates/celox-runtime/src/simulation/stats.rs index bb8d9316138..cb33abe3c02 100644 --- a/crates/celox-runtime/src/simulation/stats.rs +++ b/crates/celox-runtime/src/simulation/stats.rs @@ -5,15 +5,18 @@ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum SchedulerMode { /// The runtime's loop runs every time slot. - #[default] Reference, /// The design's compiled scheduler runs the time slots it can, and the /// runtime's loop the others. A design without a compiled scheduler /// runs as in [`Self::Reference`]. + #[default] Compiled, /// [`Self::Compiled`], checked after every time slot against a shadow /// simulation of the same design in [`Self::Reference`]. Differential, + /// [`Self::Compiled`] with runs of any length, checked after each run + /// against a shadow that runs the same slots in [`Self::Reference`]. + DifferentialRuns, } /// How one process kernel is scheduled. @@ -23,7 +26,7 @@ pub enum KernelSchedule { /// The compiled scheduler runs it. Compiled, /// The runtime's loop runs it, for the reason given. - Reference(&'static str), + Reference(String), } /// The loop that runs time slots and how each process kernel is scheduled. diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 3f7165c53e9..1101a082e15 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1519,6 +1519,12 @@ impl InterpBackend { } impl SimBackend for InterpBackend { + /// Interpreting the scheduler unit costs more than the runtime's loop + /// (sched_bench (d): about 9% more per cycle). + fn runs_compiled_scheduler(&self) -> bool { + false + } + type Event = InterpEventRef; fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode> { diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index 006d0ee904b..38c5e94aefc 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -1219,6 +1219,12 @@ impl Drop for TieredBackend { } impl SimBackend for TieredBackend { + /// Only generated code runs the scheduler unit faster than the + /// runtime's loop. + fn runs_compiled_scheduler(&self) -> bool { + matches!(self.phase, Phase::Compiled(_)) + } + type Event = TieredEventRef; fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode> { diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 5f4e4a92a38..9d7d34825df 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -30,6 +30,9 @@ mod ir; mod optimizer; mod parser; pub(crate) mod portable; +// Builds without the host runtime run every slot in the reference loop. +#[cfg(feature = "host-runtime")] +mod scheduler; #[cfg(feature = "host-runtime")] mod simulation; mod simulator; diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs new file mode 100644 index 00000000000..2186b9e3589 --- /dev/null +++ b/crates/celox/src/scheduler.rs @@ -0,0 +1,812 @@ +//! The compiled scheduler: one SIR unit that runs time slots of the process +//! kernels that only delay, as the runtime's reference loop runs them. +//! +//! In a design whose event signals only such kernels write, a time slot of +//! the reference loop is short. The kernels due at the slot run in kernel +//! order; combinational logic settles; if the kernels gave an active edge +//! of one event, that domain's `eval_apply` unit runs, or with several, the +//! `eval_only` unit of each then the `apply` unit of each, in event order; +//! combinational logic settles again. The unit does exactly this in a loop +//! over the slots up to a limit the runtime sets, with the wake time of +//! each kernel in [`SchedulerSlots::wake`]. It inlines the units the +//! reference loop calls, so their code is unchanged. +//! +//! The runtime runs the unit only for slots that touch nothing else (see +//! `celox_runtime::SimulationState::run_until_observed`): every other slot, +//! and every design or kernel this module does not qualify, runs in the +//! reference loop. + +use celox_design::{ + DomainKind, ProcessStatus, RuntimeEventKind, SCHEDULER_FLAG_WIDTH, SCHEDULER_TIME_WIDTH, + STABLE_REGION, SchedulerExit, SchedulerSlots, TIME_SLOT_WIDTH, schedule::ScheduleModel, +}; +use celox_sir::{BinaryOp, SIRBuilder, SIRSwitchCase, SIRValue}; + +use crate::{ + HashMap, HashSet, + ir::{ + AbsoluteAddr, ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, + SIRInstruction, SIROffset, SIRTerminator, + }, +}; + +type Unit = ExecutionUnit; +type Builder = SIRBuilder; + +/// The most events whose edges one slot can record. +const MAX_EVENTS: usize = 64; + +/// Generate the compiled scheduler of `program`, if it qualifies, and record +/// for every process kernel whether the scheduler runs it. +pub(crate) fn attach(program: &mut LaidOutProgram) { + let Some(schema) = program.runtime.runtime_schema.scheduler.clone() else { + return; + }; + let kernels = program.runtime.runtime_schema.processes.len(); + let (fallback, unit, events) = match Plan::new(program, &schema.slots) { + Err(reason) => (vec![Some(reason); kernels], None, Vec::new()), + Ok(plan) => { + let fallback = plan.fallback.clone(); + let unit = plan + .kernels + .iter() + .any(Option::is_some) + .then(|| plan.generate(program, &schema.slots)); + let events = plan + .written() + .into_iter() + .map(|event| plan.events[event].signal) + .collect(); + (fallback, unit, events) + } + }; + let scheduler = program + .runtime + .runtime_schema + .scheduler + .as_mut() + .expect("checked above"); + scheduler.fallback = fallback; + scheduler.events = events; + if let Some(unit) = unit { + scheduler.unit = Some(program.sir.processes.len()); + program.sir.processes.push(unit); + } +} + +/// An event the scheduler records edges of. +struct Event { + /// The canonical event address, which is also its signal. + signal: AbsoluteAddr, + width: usize, + /// The level of the signal after an active edge. + active: u8, + eval_apply: Vec, + eval_only: Vec, + apply: Vec, +} + +/// A kernel the scheduler runs. +struct Kernel { + /// The events whose signal the kernel writes, as indices into + /// [`Plan::events`]. + writes: Vec, +} + +struct Plan { + /// In event-id order, which the reference loop visits several triggered + /// domains in. + events: Vec, + /// Per process kernel, `Some` when the scheduler runs it. + kernels: Vec>, + fallback: Vec>, + /// Runtime event sites that record a `$finish`. + finish_sites: HashSet, +} + +impl Plan { + fn new(program: &LaidOutProgram, slots: &SchedulerSlots) -> Result { + let schema = &program.runtime.runtime_schema; + let model = ScheduleModel::derive(&program.design, schema); + if program.layout().four_state { + return Err("the design is four-state".into()); + } + if !model.counted.is_empty() { + return Err("the design counts event occurrences".into()); + } + let topology = &model.events; + if !topology.cascaded_events.is_empty() + || !topology.derived_events.is_empty() + || !topology.combinational_derived.is_empty() + { + return Err("the design has derived clocks".into()); + } + if !schema.comb_observers.is_empty() { + return Err("the design observes combinational processes".into()); + } + if slots.wake.len() != schema.processes.len() { + return Err("the scheduler slots do not match the kernels".into()); + } + let sir = &program.sir; + let comb_fatal = sir.eval_comb.iter().any(|unit| { + instructions(unit).any(|inst| { + matches!( + inst, + SIRInstruction::CombCaptureEvent { + fatal_error_code: Some(_), + .. + } + ) + }) + }); + if comb_fatal { + return Err("combinational logic has fatal assertions".into()); + } + + let shared = program.shared_storage(); + let storage = |address: AbsoluteAddr| shared.get(&address).copied().unwrap_or(address); + let addresses = crate::edge_plans::event_addresses(program); + if addresses.len() > MAX_EVENTS { + return Err(format!("the design has more than {MAX_EVENTS} events")); + } + let mut events = Vec::with_capacity(addresses.len()); + let mut event_storage = HashMap::default(); + for &signal in &addresses { + let active = match model.kinds.get(&signal) { + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => 1, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => 0, + _ => return Err("an event is not a clock or reset edge".into()), + }; + let units = |map: &HashMap>| -> Result, String> { + let aliased = map + .keys() + .any(|key| *key != signal && topology.canonical(*key) == signal); + match map.get(&signal) { + Some(units) if !aliased => Ok(units.clone()), + _ => Err("an event domain has no separate units".into()), + } + }; + let event = Event { + signal, + width: *program + .layout() + .widths + .get(&signal) + .ok_or("an event signal has no storage")?, + active, + eval_apply: units(&sir.eval_apply_ffs)?, + eval_only: units(&sir.eval_only_ffs)?, + apply: units(&sir.apply_ffs)?, + }; + if event_storage + .insert(storage(signal), events.len()) + .is_some() + { + return Err("two events share a signal".into()); + } + events.push(event); + } + // Event signals change only where the scheduler sees them change. + let written = |unit: &Unit| -> Vec { + let mut written: Vec = instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Store(target, ..) | SIRInstruction::Commit(_, target, ..) => { + event_storage.get(&storage(target.absolute_addr())).copied() + } + _ => None, + }) + .collect(); + written.sort_unstable(); + written.dedup(); + written + }; + let rtl_units = sir + .eval_comb + .iter() + .chain(sir.eval_apply_ffs.values().flatten()) + .chain(sir.eval_only_ffs.values().flatten()) + .chain(sir.apply_ffs.values().flatten()); + for unit in rtl_units { + if !written(unit).is_empty() { + return Err("RTL logic drives an event signal".into()); + } + } + // A domain that commits its blocking results in the active region + // evaluates before the NBA region when it triggers; a kernel that + // may trigger it keeps the reference loop. + let active_commits: HashSet = events + .iter() + .enumerate() + .filter(|(_, event)| model.active_commits.contains(&event.signal)) + .map(|(index, _)| index) + .collect(); + + let mut kernels = Vec::with_capacity(schema.processes.len()); + let mut fallback = Vec::with_capacity(schema.processes.len()); + for (index, slots) in schema.processes.iter().enumerate() { + let process = &model.processes[index]; + let unit = &sir.processes[index]; + let reason = if slots.is_initializer { + Some("a declaration initializer") + } else if slots.requires_timed_simulation { + Some("an edge procedure") + } else if !slots.const_delays { + Some("a delay is not a constant of at least one time unit") + } else if !process.waits.is_empty() { + Some("the process waits for events") + } else if !process.nbas.is_empty() { + Some("the process has nonblocking assignments") + } else if !process.host_requests.is_empty() { + Some("the process makes host requests") + } else if !delay_statuses_only(unit, slots.status) { + Some("the process suspends other than for a delay") + } else if written(unit) + .iter() + .any(|event| active_commits.contains(event)) + { + Some( + "the process drives a clock whose domain commits blocking results in the active region", + ) + } else { + None + }; + match reason { + Some(reason) => { + kernels.push(None); + fallback.push(Some(reason.to_string())); + } + None => { + kernels.push(Some(Kernel { + writes: written(unit), + })); + fallback.push(None); + } + } + } + let finish_sites = schema + .runtime_event_sites + .iter() + .enumerate() + .filter(|(_, site)| matches!(site.kind, RuntimeEventKind::Finish)) + .map(|(index, _)| index as u32) + .collect(); + Ok(Self { + events, + kernels, + fallback, + finish_sites, + }) + } + + /// The events the scheduler's kernels write, in event order: the only + /// ones that can have edges in its slots. + fn written(&self) -> Vec { + let mut written: Vec = self + .kernels + .iter() + .flatten() + .flat_map(|kernel| kernel.writes.iter().copied()) + .collect(); + written.sort_unstable(); + written.dedup(); + written + } + + fn generate(&self, program: &LaidOutProgram, slots: &SchedulerSlots) -> Unit { + let schema = &program.runtime.runtime_schema; + let written = self.written(); + let mut g = Generator { + b: Builder::new(), + slots, + finish_sites: &self.finish_sites, + exits: Vec::new(), + }; + let header = g.b.new_block(); + g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); + + // The next slot: the earliest wake time of a waiting kernel. + g.b.switch_to_block(header); + let mut time = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); + let mut any = g.constant(0, 1); + for (index, kernel) in self.kernels.iter().enumerate() { + if kernel.is_some() { + let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); + let waiting = g.waiting(index); + let earlier = g.binary(1, wake, BinaryOp::LtU, time); + let earlier = g.binary(1, earlier, BinaryOp::And, waiting); + let next = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); + g.b.emit(SIRInstruction::Mux(next, earlier, wake, time)); + time = next; + any = g.binary(1, any, BinaryOp::Or, waiting); + } + } + let limit = g.load(slots.limit, SCHEDULER_TIME_WIDTH); + let after = g.binary(1, time, BinaryOp::GtU, limit); + let one = g.constant(1, 1); + let none = g.binary(1, any, BinaryOp::Xor, one); + let stop = g.binary(1, after, BinaryOp::Or, none); + let run = g.b.new_block(); + let limit_exit = g.exit_block(SchedulerExit::Limit, None); + g.b.seal_block(SIRTerminator::Branch { + cond: stop, + true_block: (limit_exit, Vec::new()), + false_block: (run, Vec::new()), + }); + + g.b.switch_to_block(run); + g.store(slots.now, SCHEDULER_TIME_WIDTH, time); + let count = g.load(slots.count, SCHEDULER_TIME_WIDTH); + let one = g.constant(1, SCHEDULER_TIME_WIDTH); + let count = g.binary(SCHEDULER_TIME_WIDTH, count, BinaryOp::Add, one); + g.store(slots.count, SCHEDULER_TIME_WIDTH, count); + for &slot in &schema.time_slots { + g.store(slot, TIME_SLOT_WIDTH, time); + } + // The levels the slot starts from, the baseline of its edges, for an + // exit in the middle of the slot. + let mut levels = g.constant(0, MAX_EVENTS); + for (bit, &event) in written.iter().enumerate() { + let level = g.level(&self.events[event]); + let set = g.constant(1 << bit, MAX_EVENTS); + let unset = g.constant(0, MAX_EVENTS); + let value = g.b.alloc_bit(MAX_EVENTS, false); + g.b.emit(SIRInstruction::Mux(value, level, set, unset)); + levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, value); + } + g.store(slots.levels, SCHEDULER_TIME_WIDTH, levels); + let finish_exit = g.exit_block(SchedulerExit::Finish, None); + let internal_exit = g.exit_block(SchedulerExit::Internal, None); + + // The kernels due now, in kernel order, and the active edges they + // give, as a mask over the events. + let mut mask = g.constant(0, MAX_EVENTS); + for (index, kernel) in self.kernels.iter().enumerate() { + let Some(kernel) = kernel else { + continue; + }; + let process = &schema.processes[index]; + let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); + let waiting = g.waiting(index); + let due = g.binary(1, wake, BinaryOp::Eq, time); + let due = g.binary(1, due, BinaryOp::And, waiting); + let run = g.b.new_block(); + let joined = g.b.alloc_bit(MAX_EVENTS, false); + let join = g.b.new_block_with(vec![joined]); + g.b.seal_block(SIRTerminator::Branch { + cond: due, + true_block: (run, Vec::new()), + false_block: (join, vec![mask]), + }); + + g.b.switch_to_block(run); + let current = g.constant(index as u64, SCHEDULER_TIME_WIDTH); + g.store(slots.current, SCHEDULER_TIME_WIDTH, current); + let before: Vec<_> = kernel + .writes + .iter() + .map(|&event| g.level(&self.events[event])) + .collect(); + g.inline(&program.sir.processes[index], finish_exit); + let status = g.load(process.status, celox_design::PROCESS_STATUS_WIDTH); + let code = |status: ProcessStatus| u64::from(status.code()); + let finished = g.equals(status, code(ProcessStatus::Finish)); + let not_finished = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: finished, + true_block: (finish_exit, Vec::new()), + false_block: (not_finished, Vec::new()), + }); + g.b.switch_to_block(not_finished); + let done = g.equals(status, code(ProcessStatus::Done)); + let ended = g.b.new_block(); + let suspended = g.b.new_block(); + let resumed = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: done, + true_block: (ended, Vec::new()), + false_block: (suspended, Vec::new()), + }); + g.b.switch_to_block(ended); + let idle = g.constant(0, SCHEDULER_FLAG_WIDTH); + g.store(slots.waiting[index], SCHEDULER_FLAG_WIDTH, idle); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + + g.b.switch_to_block(suspended); + let delay = g.equals(status, code(ProcessStatus::Delay)); + let inactive = g.equals(status, code(ProcessStatus::InactiveDelay)); + let delayed = g.binary(1, delay, BinaryOp::Or, inactive); + let wait = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: delayed, + true_block: (wait, Vec::new()), + false_block: (internal_exit, Vec::new()), + }); + g.b.switch_to_block(wait); + let amount = g.load(process.delay, celox_design::PROCESS_DELAY_WIDTH); + let wake = g.binary(SCHEDULER_TIME_WIDTH, time, BinaryOp::Add, amount); + let overflow = g.binary(1, wake, BinaryOp::LtU, time); + let overflow_exit = g.exit_block(SchedulerExit::DelayOverflow, None); + let in_range = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: overflow, + true_block: (overflow_exit, Vec::new()), + false_block: (in_range, Vec::new()), + }); + g.b.switch_to_block(in_range); + g.store(slots.wake[index], SCHEDULER_TIME_WIDTH, wake); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + + g.b.switch_to_block(resumed); + let mut edges = mask; + for (&event, &was) in kernel.writes.iter().zip(&before) { + let is = g.level(&self.events[event]); + let changed = g.binary(1, was, BinaryOp::Ne, is); + let active = g.equals(is, u64::from(self.events[event].active)); + let edge = g.binary(1, changed, BinaryOp::And, active); + let set = g.constant(1 << event, MAX_EVENTS); + let unset = g.constant(0, MAX_EVENTS); + let bit = g.b.alloc_bit(MAX_EVENTS, false); + g.b.emit(SIRInstruction::Mux(bit, edge, set, unset)); + edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + } + g.b.seal_block(SIRTerminator::Jump(join, vec![edges])); + g.b.switch_to_block(join); + mask = joined; + } + + // The settle after the kernels, shared with the one after the + // domains: the mask waits in `exit_arg` meanwhile. + let none = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); + g.store(slots.current, SCHEDULER_TIME_WIDTH, none); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, mask); + let comb = g.b.new_block(); + g.call_comb(comb, 1); + + g.b.switch_to_block(comb); + for unit in &program.sir.eval_comb { + g.inline(unit, finish_exit); + } + let continuation = g.load(slots.cont, SCHEDULER_FLAG_WIDTH); + let settled = g.b.new_block(); + let slot_end = g.b.new_block(); + g.b.seal_block(SIRTerminator::Switch { + selector: continuation, + cases: vec![ + SIRSwitchCase { + value: 1u8.into(), + target: settled, + }, + SIRSwitchCase { + value: 2u8.into(), + target: slot_end, + }, + ], + default: internal_exit, + }); + + // The domains the edges trigger. + g.b.switch_to_block(settled); + if written.is_empty() { + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + g.b.switch_to_block(slot_end); + g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); + return g.finish(); + } + let mask = g.load(slots.exit_arg, MAX_EVENTS); + let zero = g.constant(0, MAX_EVENTS); + let quiet = g.binary(1, mask, BinaryOp::Eq, zero); + let triggered = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: quiet, + true_block: (slot_end, Vec::new()), + false_block: (triggered, Vec::new()), + }); + g.b.switch_to_block(triggered); + let one = g.constant(1, MAX_EVENTS); + let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); + let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let single = g.binary(1, others, BinaryOp::Eq, zero); + let one_domain = g.b.new_block(); + let domains = g.b.new_block(); + let evaluated = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: single, + true_block: (one_domain, Vec::new()), + false_block: (domains, Vec::new()), + }); + + // One triggered domain evaluates and applies at once. + g.b.switch_to_block(one_domain); + for &index in &written { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let this = g.binary(1, mask, BinaryOp::Eq, bit); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + for unit in &event.eval_apply { + g.inline(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + g.b.switch_to_block(next); + } + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + + // Several evaluate, then apply, each in event order. + g.b.switch_to_block(domains); + if written.len() < 2 { + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + g.b.switch_to_block(evaluated); + g.call_comb(comb, 2); + g.b.switch_to_block(slot_end); + g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); + return g.finish(); + } + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in &written { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); + let this = g.binary(1, selected, BinaryOp::Ne, zero); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + let units = match phase { + Phase::Evaluate => &event.eval_only, + Phase::Apply => &event.apply, + }; + for unit in units { + g.inline(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + g.b.switch_to_block(next); + } + } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + + g.b.switch_to_block(evaluated); + g.call_comb(comb, 2); + + g.b.switch_to_block(slot_end); + g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); + g.finish() + } +} + +enum Phase { + Evaluate, + Apply, +} + +struct Generator<'a> { + b: Builder, + slots: &'a SchedulerSlots, + finish_sites: &'a HashSet, + /// Exit blocks not yet emitted. + exits: Vec<(celox_sir::BlockId, SchedulerExit, Option)>, +} + +impl Generator<'_> { + fn constant(&mut self, value: u64, width: usize) -> RegisterId { + let register = self.b.alloc_bit(width, false); + self.b + .emit(SIRInstruction::Imm(register, SIRValue::new(value))); + register + } + + fn binary( + &mut self, + width: usize, + lhs: RegisterId, + op: BinaryOp, + rhs: RegisterId, + ) -> RegisterId { + let register = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Binary(register, lhs, op, rhs)); + register + } + + fn equals(&mut self, value: RegisterId, constant: u64) -> RegisterId { + let width = self.b.register(&value).width(); + let constant = self.constant(constant, width); + self.binary(1, value, BinaryOp::Eq, constant) + } + + /// Whether kernel `index` waits for its wake time. + fn waiting(&mut self, index: usize) -> RegisterId { + let flag = self.load(self.slots.waiting[index], SCHEDULER_FLAG_WIDTH); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + self.binary(1, flag, BinaryOp::Ne, zero) + } + + fn load(&mut self, address: AbsoluteAddr, width: usize) -> RegisterId { + let register = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Load( + register, + stable(address), + SIROffset::Static(0), + width, + )); + register + } + + fn store(&mut self, address: AbsoluteAddr, width: usize, value: RegisterId) { + self.b.emit(SIRInstruction::Store( + stable(address), + SIROffset::Static(0), + width, + value, + Vec::new(), + Vec::new(), + )); + } + + /// The edge level of `event`'s signal, as the runtime reads it: whether + /// its low byte, within its width, is not zero. + fn level(&mut self, event: &Event) -> RegisterId { + let width = event.width.min(8); + let value = self.load(event.signal, width); + let zero = self.constant(0, width); + self.binary(1, value, BinaryOp::Ne, zero) + } + + /// A block that ends the run with `exit` and its argument, emitted by + /// [`Self::emit_exits`]. + fn exit_block(&mut self, exit: SchedulerExit, argument: Option) -> celox_sir::BlockId { + let block = self.b.new_block(); + self.exits.push((block, exit, argument)); + block + } + + /// The unit, once every block is sealed. + fn finish(mut self) -> Unit { + self.emit_exits(); + let (blocks, register_map, _) = self.b.drain(); + Unit { + entry_block_id: celox_sir::BlockId(0), + blocks, + register_map, + } + } + + fn emit_exits(&mut self) { + for (block, exit, argument) in std::mem::take(&mut self.exits) { + self.b.switch_to_block(block); + let code = self.constant(exit as u64, SCHEDULER_FLAG_WIDTH); + self.store(self.slots.exit, SCHEDULER_FLAG_WIDTH, code); + if let Some(argument) = argument { + let argument = self.constant(argument, SCHEDULER_TIME_WIDTH); + self.store(self.slots.exit_arg, SCHEDULER_TIME_WIDTH, argument); + } + self.b.seal_block(SIRTerminator::Return); + } + } + + /// Run the shared settle, continuing at case `continuation` of its end. + fn call_comb(&mut self, comb: celox_sir::BlockId, continuation: u8) { + let value = self.constant(u64::from(continuation), SCHEDULER_FLAG_WIDTH); + self.store(self.slots.cont, SCHEDULER_FLAG_WIDTH, value); + self.b.seal_block(SIRTerminator::Jump(comb, Vec::new())); + } + + /// Inline `unit`. A `$finish` record it emits ends the run after it, as + /// the reference loop ends the slot after the unit that emitted one. + fn inline(&mut self, unit: &Unit, finish_exit: celox_sir::BlockId) { + if self.finish_sites.is_empty() || !self.emits_finish(unit) { + self.b.inline_execution_unit(unit); + return; + } + let instrumented = self.instrument(unit); + self.b.inline_execution_unit(&instrumented); + let finished = self.load(self.slots.finish, SCHEDULER_FLAG_WIDTH); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + let set = self.binary(1, finished, BinaryOp::Ne, zero); + let next = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: set, + true_block: (finish_exit, Vec::new()), + false_block: (next, Vec::new()), + }); + self.b.switch_to_block(next); + } + + fn emits_finish(&self, unit: &Unit) -> bool { + instructions(unit).any(|inst| { + matches!(inst, SIRInstruction::RuntimeEvent { site_id, .. } + if self.finish_sites.contains(site_id)) + }) + } + + /// A copy of `unit` that sets the finish slot after every `$finish` + /// record. + fn instrument(&self, unit: &Unit) -> Unit { + let mut unit = unit.clone(); + let mut next = unit + .register_map + .keys() + .map(|register| register.0 + 1) + .max() + .unwrap_or(0); + let mut registers = Vec::new(); + for block in unit.blocks.values_mut() { + let mut instructions = Vec::with_capacity(block.instructions.len()); + for inst in block.instructions.drain(..) { + let finish = matches!(&inst, SIRInstruction::RuntimeEvent { site_id, .. } + if self.finish_sites.contains(site_id)); + instructions.push(inst); + if finish { + // Each site defines its own register. + let one = RegisterId(next); + next += 1; + registers.push(one); + instructions.push(SIRInstruction::Imm(one, SIRValue::new(1u8))); + instructions.push(SIRInstruction::Store( + stable(self.slots.finish), + SIROffset::Static(0), + SCHEDULER_FLAG_WIDTH, + one, + Vec::new(), + Vec::new(), + )); + } + } + block.instructions = instructions; + } + for register in registers { + unit.register_map.insert( + register, + crate::ir::RegisterType::Bit { + width: SCHEDULER_FLAG_WIDTH, + signed: false, + }, + ); + } + unit + } +} + +fn stable(address: AbsoluteAddr) -> RegionedAbsoluteAddr { + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address) +} + +fn instructions(unit: &Unit) -> impl Iterator> { + unit.blocks.values().flat_map(|block| &block.instructions) +} + +/// Whether every status `unit` stores into `status` is a constant that +/// suspends for a delay, ends the process or finishes the simulation. +fn delay_statuses_only(unit: &Unit, status: AbsoluteAddr) -> bool { + let constants: HashMap = instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Imm(register, value) => u64::try_from(&value.payload) + .ok() + .map(|value| (*register, value)), + _ => None, + }) + .collect(); + let allowed = [ + ProcessStatus::Delay, + ProcessStatus::InactiveDelay, + ProcessStatus::Done, + ProcessStatus::Finish, + ] + .map(|status| u64::from(status.code())); + let status = stable(status); + instructions(unit).all(|inst| match inst { + SIRInstruction::Store(target, _, _, value, ..) if *target == status => constants + .get(value) + .is_some_and(|code| allowed.contains(code)), + SIRInstruction::Commit(_, target, ..) => *target != status, + _ => true, + }) +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 30acc066cc3..fa8d71e731d 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -218,6 +218,24 @@ impl HostBoundary for Simulator { Ok(()) } + 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. + let vcd = &self.sv_vcd; + if self.vcd_writer.is_some() + || vcd.path.is_some() + || vcd.started.is_some() + || vcd.pending + || !self.handle_slots().is_empty() + { + return CompiledSlots::One; + } + CompiledSlots::Any + } + fn finish_timed_step(&mut self, timestamp: u64) { self.dirty = false; self.dump_unless_rewound(timestamp); @@ -551,7 +569,7 @@ impl Simulation { let Some(mut shadow) = self.shadow.take() else { return self.state.step_until(&mut self.simulator, end_time); }; - let mut check = differential::ShadowCheck::new(&mut shadow); + let mut check = differential::ShadowCheck::new(&mut shadow, self.mode()); let result = self .state .step_until_observed(&mut self.simulator, end_time, &mut check); @@ -569,7 +587,7 @@ impl Simulation { let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, Some(mut shadow) => { - let mut check = differential::ShadowCheck::new(&mut shadow); + let mut check = differential::ShadowCheck::new(&mut shadow, self.mode()); let result = self.state .run_until_observed(&mut self.simulator, end_time, &mut check); diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index acdaefda40b..5cbcd773323 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -30,6 +30,10 @@ impl Simulation { } } + pub(super) fn mode(&self) -> crate::SchedulerMode { + self.state.scheduler_stats().mode + } + /// The scheduler mode, the steps checked against a shadow and how each /// process kernel is scheduled. #[doc(hidden)] @@ -45,6 +49,9 @@ impl Simulation { /// Checks each step of a primary simulation against a shadow. pub(super) struct ShadowCheck<'a, B: SimBackend> { shadow: &'a mut Simulation, + /// Compiled runs take one slot each; otherwise the shadow catches up + /// with a longer run slot by slot. + one_slot: bool, /// The time the step in progress started from. start: u64, /// Steps checked. @@ -52,9 +59,10 @@ pub(super) struct ShadowCheck<'a, B: SimBackend> { } impl<'a, B: SimBackend> ShadowCheck<'a, B> { - pub(super) fn new(shadow: &'a mut Simulation) -> Self { + pub(super) fn new(shadow: &'a mut Simulation, mode: crate::SchedulerMode) -> Self { Self { shadow, + one_slot: mode != crate::SchedulerMode::DifferentialRuns, start: 0, checked: 0, } @@ -62,6 +70,10 @@ impl<'a, B: SimBackend> ShadowCheck<'a, B> { } impl StepObserver> for ShadowCheck<'_, B> { + fn one_slot(&self) -> bool { + self.one_slot + } + fn before_step(&mut self, state: &SimulationState, primary: &mut Simulator) { self.start = state.time(); let shadow = &mut *self.shadow; @@ -87,7 +99,23 @@ impl StepObserver> for ShadowCheck<'_, B> { result: &Result, RuntimeErrorCode>, ) -> Result<(), RuntimeErrorCode> { let shadow = &mut *self.shadow; - let reference = shadow.state.step_until(&mut shadow.simulator, limit); + let mut reference = shadow.state.step_until(&mut shadow.simulator, limit); + // A compiled run of several slots: the shadow runs them one by one. + if let Ok(Some(time)) = result { + while let Ok(Some(reached)) = reference { + if reached >= *time + || shadow.state.is_finished() + || shadow.state.is_stopped() + || shadow + .state + .next_event_time() + .is_none_or(|next| next > *time) + { + break; + } + reference = shadow.state.step_until(&mut shadow.simulator, limit); + } + } self.checked += 1; match difference(state, primary, shadow, result, &reference) { None => Ok(()), @@ -128,7 +156,20 @@ fn difference( "scheduling state {key:?}, the reference {reference:?}" )); } - if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend) { + // The compiled scheduler's slots hold nothing between runs. + let scheduler: Vec<_> = primary + .program + .runtime_schema + .scheduler + .iter() + .flat_map(|scheduler| scheduler.slots.iter()) + .map(|address| { + let signal = primary.backend.resolve_signal(address); + signal.offset..signal.offset + celox_state_layout::get_byte_size(signal.width) + }) + .collect(); + if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend, &scheduler) + { let signal = primary .named_signals() .into_iter() @@ -158,9 +199,13 @@ fn difference( None } -/// The first byte of design state that differs between two backends of the -/// same design. -fn first_difference(primary: &B, shadow: &B) -> Option { +/// The first byte of design state outside `excluded` that differs between +/// two backends of the same design. +fn first_difference( + primary: &B, + shadow: &B, + excluded: &[std::ops::Range], +) -> Option { let range = celox_state_layout::STATE_HEADER_SIZE..primary.layout().total_size; let bytes = |backend: &B| { let (ptr, len) = backend.memory_as_ptr(); @@ -173,8 +218,10 @@ fn first_difference(primary: &B, shadow: &B) -> Option { primary .iter() .zip(&shadow) - .position(|(a, b)| a != b) - .map(|index| range.start + index) + .enumerate() + .map(|(index, pair)| (range.start + index, pair)) + .find(|(offset, (a, b))| a != b && !excluded.iter().any(|r| r.contains(offset))) + .map(|(offset, _)| offset) } #[cfg(all(test, feature = "systemverilog"))] @@ -284,6 +331,178 @@ mod tests { } } + #[test] + fn the_compiled_scheduler_runs_delay_only_kernels() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] count); + logic clk = 1'b0; + always #5 clk = ~clk; + initial count = 8'd0; + always_ff @(posedge clk) count <= count + 8'd1; + endmodule + "#; + for mode in [ + SchedulerMode::Compiled, + SchedulerMode::Differential, + SchedulerMode::DifferentialRuns, + SchedulerMode::Reference, + ] { + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .scheduler_mode(mode) + .build() + .unwrap(); + sim.run_until(1000).unwrap(); + let count = sim.signal("count"); + assert_eq!(sim.get(count), 100u8.into(), "{mode:?}"); + let stats = sim.scheduler_stats(); + if mode == SchedulerMode::Reference { + assert_eq!(stats.compiled_slots, 0); + } else { + assert!(stats.compiled_slots > 0, "{mode:?}: {stats:?}"); + } + match mode { + SchedulerMode::Differential => { + assert!(stats.checked_steps >= stats.compiled_slots) + } + // One run takes all the slots up to the target. + SchedulerMode::DifferentialRuns => { + assert!(stats.checked_steps < stats.compiled_slots, "{stats:?}") + } + _ => {} + } + } + } + + /// A kernel whose writes no event domain listens to: the scheduler + /// runs its slots without any domain to dispatch. + #[test] + fn the_compiled_scheduler_runs_kernels_without_event_writes() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] seen); + logic tick = 1'b0; + logic [7:0] count = 8'd0; + always #5 begin + tick = ~tick; + count = count + 8'd1; + end + assign seen = count + {7'd0, tick}; + endmodule + "#; + for mode in [SchedulerMode::Differential, SchedulerMode::DifferentialRuns] { + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .scheduler_mode(mode) + .build() + .unwrap(); + sim.run_until(52).unwrap(); + let seen = sim.signal("seen"); + assert_eq!(sim.get(seen), 10u8.into(), "{mode:?}"); + assert!(sim.scheduler_stats().compiled_slots > 0, "{mode:?}"); + } + } + + const MODES: [SchedulerMode; 3] = [ + SchedulerMode::Compiled, + SchedulerMode::Differential, + SchedulerMode::DifferentialRuns, + ]; + + fn build_in(source: &str, mode: SchedulerMode) -> Simulation { + Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .scheduler_mode(mode) + .build() + .unwrap() + } + + /// A `$finish` in a domain the scheduler inlines, with two sites. + #[test] + fn compiled_slots_end_at_a_finish_in_a_domain() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic err, output logic [7:0] n); + logic clk = 1'b0; + always #5 clk = ~clk; + initial n = 8'd0; + always_ff @(posedge clk) begin + n <= n + 8'd1; + if (n == 8'd3) $finish; + if (err) $finish; + end + endmodule + "#; + let mut reference = build_in(source, SchedulerMode::Reference); + reference.run_until(100).unwrap(); + assert!(reference.is_finished()); + for mode in MODES { + let mut sim = build_in(source, mode); + sim.run_until(100).unwrap(); + assert!(sim.is_finished(), "{mode:?}"); + assert_eq!(sim.time(), reference.time(), "{mode:?}"); + let n = sim.signal("n"); + assert_eq!(sim.get(n), reference.get(n), "{mode:?}"); + assert!(sim.scheduler_stats().compiled_slots > 0, "{mode:?}"); + } + } + + /// A compiled kernel's `$finish` leaves the state the reference leaves: + /// a kernel due in the same slot that did not run yet is still ready, + /// and a state file taken afterwards is the same. + #[test] + fn compiled_slots_end_at_a_kernel_finish_as_the_reference_does() { + let clock = "always #5 clk = ~clk;"; + for finish in ["initial #27 $finish;", "initial #30 $finish;"] { + for order in [[finish, clock], [clock, finish]] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] count); + logic clk = 1'b0; + {} + {} + initial count = 8'd0; + always_ff @(posedge clk) count <= count + 8'd1; + endmodule", + order[0], order[1] + ); + let mut reference = build_in(&source, SchedulerMode::Reference); + reference.run_until(100).unwrap(); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(&source, mode); + sim.run_until(100).unwrap(); + assert!(sim.is_finished(), "{mode:?} {order:?}"); + assert!(sim.scheduler_stats().compiled_slots > 0, "{mode:?}"); + assert_eq!(sim.save_state().unwrap(), expected, "{mode:?} {order:?}"); + assert!(sim.checkpoint().is_ok()); + } + } + } + } + + /// A kernel may wake at the last representable time. + #[test] + fn compiled_kernels_may_wake_at_the_last_time() { + let source = r#" + `timescale 1fs/1fs + module Top(output logic [7:0] x); + initial begin + x = 8'd0; + #10 x = 8'd1; + #(64'd18446744073709551605) x = 8'd2; + end + endmodule + "#; + for mode in MODES { + let mut sim = build_in(source, mode); + sim.run_until(100).unwrap(); + let x = sim.signal("x"); + assert_eq!(sim.get(x), 1u8.into(), "{mode:?}"); + assert_eq!(sim.next_event_time(), Some(u64::MAX), "{mode:?}"); + sim.run_until(u64::MAX).unwrap(); + assert_eq!(sim.get(x), 2u8.into(), "{mode:?}"); + } + } + #[test] fn differential_mode_reports_a_diverging_step() { let mut sim = build(SchedulerMode::Differential); diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 9c44bf4a7d1..0df87c12b46 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2824,6 +2824,15 @@ mod host { } } + // A timed simulation runs the slots of kernels that only delay + // in a compiled scheduler, generated from the final units. + #[cfg(feature = "host-runtime")] + if self.options.emit_triggers + && self.options.scheduler != crate::SchedulerMode::Reference + { + crate::scheduler::attach(&mut laid_out); + } + // Link DPI-C imports before code generation, so a missing C // function fails the build early; the backends reuse the result. self.options @@ -3721,7 +3730,10 @@ mod host { self.into_laid_out_program(layout_mode)?; let backend = compile(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; - let shadow = if options.scheduler != crate::SchedulerMode::Differential { + let shadow = if !matches!( + options.scheduler, + crate::SchedulerMode::Differential | crate::SchedulerMode::DifferentialRuns + ) { None } else if !injected_components.definitions.is_empty() { Some(Err("the design has external components")) From 516f63c7e7e94fe6523461afcc2216f051823d2b Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 08:42:45 +0900 Subject: [PATCH 3/8] test(sv): report and check compiled scheduler coverage In differential modes the suite harness reports, per case, whether it ran compiled slots and why none was checked. A test prints how the compiled scheduler runs the kernels of every timed case, requires the cases of generated clocks it targets to compile entirely and a floor on the compiled share. run_to_finish runs run_until stretches, so compiled slots also reach a finish. Change-Id: I6a7cd1e638c23aca36a5489606133b792aa66543 --- .../tests/frontends/systemverilog/suite.rs | 117 +++++++++++++++++- 1 file changed, 111 insertions(+), 6 deletions(-) diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 79c4a1193ab..d3f41052704 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -11,6 +11,10 @@ struct CeloxBackend(Simulator); /// the default 1 ps. const UNIT: u64 = 1000; +/// How far past the next event each run of `run_to_finish` goes, in +/// simulation time units. +const FINISH_STRETCH: u64 = 1 << 20; + /// A timed case: the design's own processes and clocks run in a /// [`Simulation`]. A host write is settled at the current time by the next /// run operation, read, eval or output collection. @@ -96,7 +100,12 @@ impl TimedBackend { impl Drop for TimedBackend { #[allow(clippy::disallowed_macros)] // The skip report goes to the test log. fn drop(&mut self) { - if std::thread::panicking() || scheduler_mode() != SchedulerMode::Differential { + if std::thread::panicking() + || !matches!( + scheduler_mode(), + SchedulerMode::Differential | SchedulerMode::DifferentialRuns + ) + { return; } let stats = self.sim.scheduler_stats(); @@ -109,6 +118,10 @@ impl Drop for TimedBackend { } None => {} } + eprintln!( + "differential: compiled slots: {}", + u8::from(stats.compiled_slots > 0) + ); } } @@ -185,12 +198,14 @@ impl Backend for TimedBackend { if self.finished { return Err("run_to_finish: the design had already finished".into()); } + // Runs to the next events and a stretch beyond, as a host loop + // would, so that a compiled scheduler may run up to the finish. while !self.finished { - let step = self.sim.step()?; - self.capture_events()?; - if step.is_none() { + let Some(next) = self.sim.next_event_time() else { break; - } + }; + self.sim.run_until(next.saturating_add(FINISH_STRETCH))?; + self.capture_events()?; } if !self.finished { return Err( @@ -255,13 +270,15 @@ impl Backend for CeloxBackend { } /// The scheduler mode of timed cases: `CELOX_SCHEDULER` set to -/// `reference`, `compiled` or `differential`, by default the library's. +/// `reference`, `compiled`, `differential` or `differential-runs`, by +/// default the library's. #[allow(clippy::disallowed_methods)] // Opt-in test configuration is environment-driven. fn scheduler_mode() -> SchedulerMode { match std::env::var("CELOX_SCHEDULER").as_deref() { Ok("reference") => SchedulerMode::Reference, Ok("compiled") => SchedulerMode::Compiled, Ok("differential") => SchedulerMode::Differential, + Ok("differential-runs") => SchedulerMode::DifferentialRuns, Ok(other) => panic!("unknown CELOX_SCHEDULER mode `{other}`"), Err(_) => SchedulerMode::default(), } @@ -360,3 +377,91 @@ pub fn run_case(name: &'static str, backend: &'static str) { .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); }); } + +/// Timed cases whose every kernel the compiled scheduler must run: clocks +/// generated by delay processes, with the domains, resets and finishes +/// around them. +const COMPILED_CASES: [&str; 6] = [ + "timing::always_with_a_delay_generates_a_clock", + "timing::asynchronous_reset_driven_by_a_delay_process", + "timing::generated_clocks_with_a_common_edge_sample_each_other", + "timing::script_writes_between_runs_reach_generated_clock_domains", + "timing::finish_from_a_delay_process_between_clock_edges", + "timing::finish_in_an_always_process_ends_the_simulation", +]; + +/// The share of the kernels of the timed cases the compiled scheduler must +/// run at least. +const COMPILED_FLOOR: f64 = 0.3; + +/// How the compiled scheduler runs the kernels of every timed suite case: +/// how many it compiles and why it leaves the others to the reference loop. +/// The report goes to the test output; the cases of [`COMPILED_CASES`] must +/// compile entirely, and the share of compiled kernels must stay above +/// [`COMPILED_FLOOR`]. +#[test] +#[allow(clippy::disallowed_macros)] // The report goes to the test log. +fn compiled_scheduler_coverage() { + use std::fmt::Write; + let (report, compiled, total, incomplete) = std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(64 * 1024 * 1024) + .spawn_scoped(scope, || { + let mut report = String::new(); + let (mut compiled_total, mut total) = (0, 0); + let mut incomplete = Vec::new(); + for case in celox_test_suite::sv::cases() { + let design = case.design(); + if !design.timed { + continue; + } + let sources = design + .sources + .iter() + .map(|source| (source.text.as_str(), source.path.as_path())) + .collect::>(); + let builder = design.parameters.iter().fold( + Simulation::from_sv_sources(sources, &design.top) + .scheduler_mode(SchedulerMode::Compiled) + .four_state(design.four_state) + .allow_inferred_latches(design.allow_inferred_latches), + |builder, (name, value)| builder.param(name, *value), + ); + let Ok(sim) = builder.build_interpreter() else { + continue; + }; + let kernels = sim.scheduler_stats().kernels; + let compiled = kernels + .iter() + .filter(|kernel| matches!(kernel, celox::KernelSchedule::Compiled)) + .count(); + compiled_total += compiled; + total += kernels.len(); + if COMPILED_CASES.contains(&case.name) && compiled != kernels.len() { + incomplete.push(case.name); + } + let mut reasons = std::collections::BTreeMap::<&str, usize>::new(); + for kernel in &kernels { + if let celox::KernelSchedule::Reference(reason) = kernel { + *reasons.entry(reason).or_default() += 1; + } + } + write!(report, "{}: {compiled}/{}", case.name, kernels.len()).unwrap(); + for (reason, count) in reasons { + write!(report, "; {reason} ({count})").unwrap(); + } + report.push('\n'); + } + (report, compiled_total, total, incomplete) + }) + .unwrap() + .join() + .unwrap() + }); + eprintln!("compiled scheduler coverage: {compiled}/{total} kernels\n{report}"); + assert!(incomplete.is_empty(), "kernels fall back in {incomplete:?}"); + assert!( + compiled as f64 >= COMPILED_FLOOR * total as f64, + "only {compiled} of {total} kernels compile" + ); +} From 388541584614eda270eddf292fd498c05a50eedf Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 08:42:45 +0900 Subject: [PATCH 4/8] chore: add a delay-only variant to the scheduler bench Variant d clocks the registers from always #5 clk = ~clk alone. A third argument selects the scheduler, a fourth the backend, and the run prints its stats. Change-Id: I62dc870c9cfec474addfd69220d5e04b27e49e99 --- crates/celox/examples/sched_bench.rs | 85 +++++++++++++++++++++++----- 1 file changed, 72 insertions(+), 13 deletions(-) diff --git a/crates/celox/examples/sched_bench.rs b/crates/celox/examples/sched_bench.rs index ed4e41d97cd..112da616da7 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 ` +//! Usage: `sched_bench [default|reference|compiled] [native|interp]` //! //! Every variant clocks the same 64 registers `rK <= rK + (seed ^ K)`: //! @@ -9,6 +9,12 @@ //! - `b1`: the clock comes from `always #5 clk = ~clk` and the registers read //! `stim`, which `initial forever @(posedge clk) stim = stim + 3` drives. //! - `b5`: like `b1` with `stim <= stim + 3`. +//! - `d`: the clock comes from `always #5 clk = ~clk` and the registers read +//! a constant seed, so only delay-only kernels run. +//! +//! 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. //! //! The scheduler's cost per cycle is the difference of the whole-program //! instruction counts of two runs, which cancels compilation: @@ -43,7 +49,15 @@ fn source(variant: &str) -> String { "stim", ) } - _ => panic!("unknown variant {variant}: expected a, ac, b1 or b5"), + "d" => ( + "module Top(output logic [31:0] out);\n\ + logic clk = 0;\n\ + logic [31:0] seed = 7;\n\ + always #5 clk = ~clk;\n" + .to_string(), + "seed", + ), + _ => panic!("unknown variant {variant}: expected a, ac, b1, b5 or d"), }; // One time unit per tick, so that `#5` and `add_clock(10, 5)` agree. let mut body = String::from("`timescale 1fs/1fs\n"); @@ -68,7 +82,18 @@ fn main() { .unwrap_or(20_000); let source = source(variant); let sources = vec![(source.as_str(), std::path::Path::new("sched_bench.sv"))]; - let out = if variant == "a" { + let interpreter = match args.get(4).map(String::as_str) { + None | Some("native") => false, + Some("interp") => true, + Some(other) => panic!("unknown backend {other}: expected native or interp"), + }; + let out = if variant == "a" && interpreter { + let sim = celox::Simulator::from_sv_sources(sources, "Top") + .build_interpreter() + .unwrap(); + tick(sim, cycles) + } else if variant == "a" { + // The loop of the native case stays in `main`, as the baseline has it. let mut sim = celox::Simulator::from_sv_sources(sources, "Top") .build() .unwrap(); @@ -81,17 +106,51 @@ fn main() { let out = sim.signal("out"); sim.get(out) } else { - let mut sim = celox::Simulation::from_sv_sources(sources, "Top") - .build() - .unwrap(); - if variant == "ac" { - let seed = sim.signal("seed"); - sim.modify(|io| io.set(seed, 7u32)).unwrap(); - sim.add_clock("clk", 10, 5); + let mode = match args.get(3).map(String::as_str) { + None | Some("default") => celox::SchedulerMode::default(), + Some("reference") => celox::SchedulerMode::Reference, + Some("compiled") => celox::SchedulerMode::Compiled, + Some(other) => panic!("unknown scheduler {other}: expected reference or compiled"), + }; + let builder = celox::Simulation::from_sv_sources(sources, "Top").scheduler_mode(mode); + if interpreter { + run(builder.build_interpreter().unwrap(), variant, cycles) + } else { + run(builder.build().unwrap(), variant, cycles) } - sim.run_until(cycles * 10).unwrap(); - let out = sim.signal("out"); - sim.get(out) }; println!("{variant} {cycles} out={out:?}"); } + +/// Variant `a` on another backend: one tick per cycle. +fn tick(mut sim: celox::Simulator, cycles: u64) -> celox::BigUint { + let seed = sim.signal("seed"); + sim.modify(|io| io.set(seed, 7u32)).unwrap(); + let clk = sim.event("clk"); + for _ in 0..cycles { + sim.tick(clk).unwrap(); + } + let out = sim.signal("out"); + sim.get(out) +} + +/// The timed variants: run `cycles` clock periods. +fn run( + mut sim: celox::Simulation, + variant: &str, + cycles: u64, +) -> celox::BigUint { + if variant == "ac" { + let seed = sim.signal("seed"); + sim.modify(|io| io.set(seed, 7u32)).unwrap(); + sim.add_clock("clk", 10, 5); + } + sim.run_until(cycles * 10).unwrap(); + let stats = sim.scheduler_stats(); + println!( + "compiled slots {}, kernels {:?}", + stats.compiled_slots, stats.kernels + ); + let out = sim.signal("out"); + sim.get(out) +} From 5b5ab7b53e98642c8afa3cf1c039c7a929e293ed Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 5/8] fix(sv): reject edge event controls on reals A real has no least significant bit to judge an edge on, and IEEE 1800-2023 6.12 prohibits posedge, negedge and edge of a real. A process waiting on one was accepted and never woke; it is now an error. Change-Id: If5c69702c6a335e0ca9a8f0621451d23335be3fa --- crates/celox-frontend-sv/src/lowering/ff.rs | 11 +++++++ crates/celox-sv-analyzer/src/lib.rs | 4 +++ .../tests/frontends/systemverilog/timing.rs | 33 +++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ba395190ed5..21b4c83ce8b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4626,6 +4626,17 @@ impl Ff<'_, '_> { let mut samples = Vec::new(); for item in items { let expr = self.propagate(&item.expr); + let edge = match item.edge { + sv::ir::EventEdge::Any => None, + sv::ir::EventEdge::Pos => Some("posedge"), + sv::ir::EventEdge::Neg => Some("negedge"), + sv::ir::EventEdge::Both => Some("edge"), + }; + if let Some(edge) = edge + && self.m.expr_float_precision(&expr).is_some() + { + return Err(sv::AnalyzerError::RealEdgeEvent { edge }); + } let id = match &expr { sv::ir::Expr::Ident(name) => match self.m.id(name) { Some(id) if !self.m.is_hidden(id) => id, diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 6cb234e623f..76c037db994 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -158,6 +158,10 @@ pub enum AnalyzerError { actual: String, target: String, }, + /// `posedge`, `negedge` or `edge` of a real expression, which has no + /// least significant bit to judge the edge on (IEEE 1800-2023 6.12). + #[error("`{edge}` of a real expression: edge event controls do not apply to reals")] + RealEdgeEvent { edge: &'static str }, } impl miette::Diagnostic for AnalyzerError {} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 204f36c4992..eed894ee5aa 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -536,6 +536,39 @@ fn unimplemented_timing_features_are_rejected() { } } +/// A real has no least significant bit, so no edge event control applies to +/// one (IEEE 1800-2023 6.12); a change of its value is an event. +#[test] +fn edge_events_of_reals_are_errors() { + for (body, edge) in [ + ("real r; initial @(posedge r);", "posedge"), + ("real r; int n; always @(negedge r) n++;", "negedge"), + ("real r; initial @(edge (r * 2.0));", "edge"), + ( + "shortreal r; bit c; int n; always @(posedge c or posedge r) n++;", + "posedge", + ), + ] { + let source = format!("module Top; {body} endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("real_edge.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("`{body}` must be rejected")) + .to_string(); + assert!( + error.contains(&format!("`{edge}` of a real expression")), + "{body}: {error}" + ); + } + let source = "module Top; real r; initial @(r); endmodule"; + celox::Simulation::from_sv_sources(vec![(source, std::path::Path::new("real.sv"))], "Top") + .build() + .expect("a change of a real is an event"); +} + /// Only `initial` and `always` processes may suspend (IEEE 1800-2023 /// 9.2.2.2, 9.2.2.4 and 13.4); a timing control elsewhere is an error. #[test] From e512f6dbe68557ef8218802726c69965b1a8f175 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 6/8] feat(sv): run plain always blocks without the flip-flop shape as processes IEEE 1800-2023 9.2.2.4 restricts only always_ff to the shape of a flip-flop. A plain always whose event control is not a clock and asynchronous resets of one-bit variables now runs as a process waiting on the same event control, instead of being rejected: an edge of a select or an expression, `edge`, an item without an edge next to edges, a multi-bit edge signal (judged on its least significant bit), and several edges of which the body tests none as a reset. Blocks of the flip-flop shape stay on the flip-flop path, lowered as before. always_ff of the other shapes stays rejected. Fixes #1708. Change-Id: Ic4652f6e110243b39566bbf2ed1d2ab3f81a2f7e --- crates/celox-frontend-sv/src/lowering.rs | 74 ++++++++++++++---- .../celox-sv-analyzer/src/ast/ff_process.rs | 34 ++++++-- .../celox-sv-analyzer/src/ast/procedural.rs | 3 +- .../celox-sv-analyzer/src/ast/validation.rs | 5 +- crates/celox-sv-analyzer/src/ir.rs | 18 ++++- .../src/sv/cases/timing.vtest | 77 +++++++++++++++++++ .../verification/sv/icarus/timing.json | 33 ++++++++ .../verification/sv/verilator/timing.json | 33 ++++++++ .../tests/frontends/systemverilog/timing.rs | 11 ++- 9 files changed, 258 insertions(+), 30 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index ce9eeda9600..e88c58796ab 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -2712,6 +2712,31 @@ fn lower_module_with_overrides( force_signals: &[String], level_lists: LevelLists<'_>, ) -> Result { + let parameter_types = module + .imported_parameters() + .iter() + .chain(module.parameters()) + .filter_map(|parameter| { + Some(( + parameter.name().to_string(), + ( + parameter.resolved_width()?, + parameter.resolved_signed().unwrap_or(false), + ), + )) + }) + .collect(); + let constants = module_constants_with_overrides(module, parameter_overrides); + let fallbacks = module + .ff_processes() + .iter() + .any(|process| runs_as_process(module, process, &constants, ¶meter_types)) + .then(|| { + module.clone().run_edge_processes_as_processes(|process| { + runs_as_process(module, process, &constants, ¶meter_types) + }) + }); + let module = fallbacks.as_ref().unwrap_or(module); let mut ff_event_roles = Vec::new(); for process in module.ff_processes() { let clock = clock_event_from_ff_process(process) @@ -2734,21 +2759,6 @@ fn lower_module_with_overrides( }); } } - let parameter_types = module - .imported_parameters() - .iter() - .chain(module.parameters()) - .filter_map(|parameter| { - Some(( - parameter.name().to_string(), - ( - parameter.resolved_width()?, - parameter.resolved_signed().unwrap_or(false), - ), - )) - }) - .collect(); - let constants = module_constants_with_overrides(module, parameter_overrides); let shared_memories = shared_edge_memories(module, &constants, ¶meter_types, warnings); validate_variable_driver_ranges(module, &constants, ¶meter_types, &shared_memories)?; let scheduled = module @@ -8392,6 +8402,40 @@ fn insert_or_merge_ff_unit( } } +/// A plain `always` sensitive to edges is a flip-flop only in the shape of +/// one: a clock and asynchronous resets, each a one-bit variable. Any other +/// edge-sensitive `always` runs as a process waiting on the same events. +fn runs_as_process( + module: &sv::ir::Module, + process: &sv::ir::FfProcess, + constants: &HashMap, + parameter_types: &HashMap, +) -> bool { + let multi_bit = |name: &str| { + let r#type = module + .ports() + .iter() + .find(|port| port.name() == name) + .map(sv::ir::Port::r#type) + .or_else(|| { + module + .signals() + .iter() + .find(|signal| signal.name() == name) + .map(sv::ir::Signal::r#type) + }); + r#type + .and_then(|r#type| signal_type_from_sv(r#type, constants, parameter_types).ok()) + .is_some_and(|type_info| type_info.width != 1) + }; + !process.is_always_ff() + && (clock_event_from_ff_process(process).is_none() + || process + .events() + .iter() + .any(|event| multi_bit(event.signal()))) +} + fn clock_event_from_ff_process(process: &sv::ir::FfProcess) -> Option<&sv::ir::FfEvent> { let clock = process.events().first()?; if process.events().len() == 1 { diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index 944550c2926..c4b8cb131dd 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -66,8 +66,12 @@ fn ff_process_from_procedure( if always_kind(procedure, syntax_tree.declarations())? != AlwaysKind::Ff { return Ok(None); } - let root = procedure.body; - let (events, body) = ff_event_control_and_body(root, syntax_tree)?; + let Some((events, body)) = ff_event_control_and_body(procedure.body, syntax_tree)? else { + if procedure.kind == celox_sv_syntax::ProcedureKind::AlwaysFf { + return Err(unsupported("always_ff event expression")); + } + return Ok(None); + }; let mut local_dimensions = packed_dimensions.clone(); local_dimensions.const_env = const_env.clone().into(); let mut builder = procedural::BodyBuilder::new( @@ -93,12 +97,26 @@ fn ff_process_from_procedure( })) } +/// A plain `always` sensitive to edges runs as a process when its events are +/// not all `posedge` or `negedge` of a variable, such as `@(posedge v[0])`, +/// `@(edge a)` or `@(posedge clk or a)`. Only `always_ff` must have this shape +/// (IEEE 1800-2023 9.2.2.4). +pub(super) fn always_falls_back_to_process( + procedure: &celox_sv_syntax::Procedure, + tree: &AnalysisContext<'_>, +) -> Result { + Ok(procedure.kind == celox_sv_syntax::ProcedureKind::Always + && always_kind(procedure, tree.declarations())? == AlwaysKind::Ff + && ff_event_control_and_body(procedure.body, tree)?.is_none()) +} + +/// The events of a flip-flop shaped event control and the body it controls, +/// or `None` when an event is not an edge of a variable. fn ff_event_control_and_body( root: celox_sv_syntax::StatementId, tree: &AnalysisContext<'_>, -) -> Result<(Vec, celox_sv_syntax::StatementId), AnalyzerError> { +) -> Result, celox_sv_syntax::StatementId)>, AnalyzerError> { use celox_sv_syntax::{EventControl, StatementKind, TimingControlKind, TimingEdge}; - let unsupported_event = || unsupported("always_ff event expression"); let native = tree.declarations(); let StatementKind::Timing { control, body } = native.statement(root).kind else { return Err(timing::disagreement()); @@ -115,12 +133,14 @@ fn ff_event_control_and_body( let edge = match item.edge { TimingEdge::Pos => FfEdge::Pos, TimingEdge::Neg => FfEdge::Neg, - _ => return Err(unsupported_event()), + _ => return Ok(None), }; let expression = expression_binding::value(item.expression, native, tree, &PackedDimensions::default())?; - let signal = expr_ident_name(&expression).ok_or_else(unsupported_event)?; + let Some(signal) = expr_ident_name(&expression) else { + return Ok(None); + }; events.push(FfEvent::new(edge, signal)); } - Ok((events, body)) + Ok(Some((events, body))) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 7fb788f706d..f749276459d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -2701,7 +2701,8 @@ pub(super) fn initial_processes_from_scope( celox_sv_syntax::ProcedureKind::Initial => false, celox_sv_syntax::ProcedureKind::Always if validation::always_kind(procedure, tree.declarations())? - == validation::AlwaysKind::Process => + == validation::AlwaysKind::Process + || ff_process::always_falls_back_to_process(procedure, tree)? => { true } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index fd6a43b40ab..1ccf521aeb4 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -14,7 +14,10 @@ pub(super) enum AlwaysKind { /// `always_comb` and `always @*` are combinational; `always_ff` and an /// `always` sensitive to clock edges are sequential, as long as their body -/// has no timing control of its own. Every other `always` is a process. +/// has no timing control of its own. Every other `always` is a process, and +/// so is an edge-sensitive `always` whose events are not edges of variables +/// (`ff_process::always_falls_back_to_process`). The frontend runs one whose +/// events are not a one-bit clock and resets as a process too. /// `always_latch` has the execution and sensitivity rules of `always_comb`. pub(super) fn always_kind( procedure: &celox_sv_syntax::Procedure, diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 9a02e684932..3fabbdb7eb8 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -77,7 +77,21 @@ pub struct Module { impl Module { /// Represent selected edge procedures as scheduled processes. A host /// request must finish synchronously before the following statement runs. - pub fn schedule_edge_processes(mut self, mut select: impl FnMut(&FfProcess) -> bool) -> Self { + pub fn schedule_edge_processes(self, select: impl FnMut(&FfProcess) -> bool) -> Self { + self.edge_processes_as_processes(select, true) + } + + /// Run selected plain `always` edge procedures as ordinary processes that + /// wait on the same events, for those that do not fit the flip-flop shape. + pub fn run_edge_processes_as_processes(self, select: impl FnMut(&FfProcess) -> bool) -> Self { + self.edge_processes_as_processes(select, false) + } + + fn edge_processes_as_processes( + mut self, + mut select: impl FnMut(&FfProcess) -> bool, + scheduled_edge: bool, + ) -> Self { let mut retained = Vec::new(); for process in std::mem::take(&mut self.ff_processes) { if !select(&process) { @@ -101,7 +115,7 @@ impl Module { self.initial_processes.push(InitialProcess { creation_order: process.creation_order, site: process.site, - scheduled_edge: true, + scheduled_edge, condition: None, body: vec![Stmt::Loop { kind: LoopKind::Forever, diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index d696896ac9a..1b446580399 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -2082,3 +2082,80 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (top Top) (run_to_finish) (expect_output "q=2 r=1 s=1\n")) + +(case plain_always_expression_edges_run_as_processes + ; IEEE 1800-2023 9.2.2.4 restricts only always_ff to the flip-flop shape. + ; A plain always waits on its event control like any other process: an + ; edge of a select or an expression, or `edge` (9.4.2). + (source "always_expression_edges.sv" #" + module Top(output bit [7:0] selected, both, any); + bit [3:0] v; + bit a, b; + always @(posedge v[1]) selected = selected + 8'd1; + always @(posedge (a & b)) both = both + 8'd1; + always @(edge a) any = any + 8'd1; + initial begin + #1; v = 4'b0010; a = 1; + #1; b = 1; + #1; v = 4'b0000; a = 0; + #1; v = 4'b0010; a = 1; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq selected 1) + (assert_eq both 0) + (assert_eq any 1) + (run_until 2) + (assert_eq both 1 "a & b rose") + (run_until 4) + (assert_eq selected 2) + (assert_eq both 2) + (assert_eq any 3 "a rose, fell and rose")) + +(case plain_always_multi_bit_edges_follow_the_lsb + ; Table 9-2 judges the edge of a multi-bit expression on its least + ; significant bit. + (source "always_multi_bit_edge.sv" #" + module Top(output bit [7:0] count); + bit [3:0] bus; + always @(posedge bus) count = count + 8'd1; + initial begin + #1; bus = 4'b0010; + #1; bus = 4'b0011; + #1; bus = 4'b0000; + #1; bus = 4'b0001; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 0 "the least significant bit stayed 0") + (run_until 2) + (assert_eq count 1) + (run_until 4) + (assert_eq count 2)) + +(case plain_always_edges_without_a_reset_run_as_processes + ; Neither edge is tested in the body, so neither is an asynchronous + ; reset: the process wakes on each of them. + (source "always_two_edges.sv" #" + module Top(output bit [7:0] count); + bit c, d; + always @(posedge c or posedge d) count <= count + 8'd1; + initial begin + #1; c = 1; + #1; d = 1; + #1; c = 0; d = 0; + #1; c = 1; + end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 1) + (run_until 2) + (assert_eq count 2) + (run_until 4) + (assert_eq count 3)) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index 8c54f5c6013..b6998ae9588 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -673,6 +673,39 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_edges_without_a_reset_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_expression_edges_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_multi_bit_edges_follow_the_lsb", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 07c3f4d070c..7a14137d3b9 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -781,6 +781,39 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_edges_without_a_reset_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_expression_edges_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::plain_always_multi_bit_edges_follow_the_lsb", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index eed894ee5aa..809fe25b00b 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -160,6 +160,9 @@ timed_cases! { fn blocking_write_waiters_run_before_nonblocking_updates = "timing::blocking_write_waiters_run_before_nonblocking_updates"; fn blocking_write_waiters_rearm_before_nonblocking_updates = "timing::blocking_write_waiters_rearm_before_nonblocking_updates"; fn blocking_write_edges_read_values_before_nonblocking_updates = "timing::blocking_write_edges_read_values_before_nonblocking_updates"; + fn plain_always_expression_edges_run_as_processes = "timing::plain_always_expression_edges_run_as_processes"; + fn plain_always_multi_bit_edges_follow_the_lsb = "timing::plain_always_multi_bit_edges_follow_the_lsb"; + fn plain_always_edges_without_a_reset_run_as_processes = "timing::plain_always_edges_without_a_reset_run_as_processes"; } #[test] @@ -474,19 +477,19 @@ fn unimplemented_timing_features_are_rejected() { "delayed continuous assignment", 444, ), - // #1708: a plain `always` that is not a flip-flop runs as a process. + // A plain `always` of these forms runs as a process. ( - "bit [3:0] v; int n; always @(posedge v[0]) n++;", + "bit [3:0] v; int n; always_ff @(posedge v[0]) n <= n + 1;", "always_ff event expression", 464, ), ( - "bit [3:0] v; int n; always @(posedge v) n++;", + "bit [3:0] v; int n; always_ff @(posedge v) n <= n + 1;", "multi-bit always_ff event signal", 88, ), ( - "bit a, b; int n; always @(posedge a or posedge b) n <= n + 1;", + "bit a, b; int n; always_ff @(posedge a or posedge b) n <= n + 1;", "always_ff event control", 88, ), From 554f20493b4ed4d734940e22114e119d9722e35e Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 7/8] docs(sv): describe plain always blocks that run as processes Change-Id: I8638596a6f136bca76c8d2cfa844f258f36c3d38 --- docs/guide/systemverilog-reference.md | 19 ++++++++++++------- docs/ja/guide/systemverilog-reference.md | 13 ++++++++----- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index cd74c47a430..68085540f6b 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -62,9 +62,15 @@ both `Simulator` and `Simulation`: `always @(a or b) y = a + b;` or or a nonblocking assignment. Any other sensitivity list without edges runs as a process: `always @(a) y = a + b;` leaves `y` unchanged when only `b` changes. So does a list that, as `always @*`, would close a combinational -loop with other logic. A `Simulator` runs no processes, so building one for -such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation`; use -`Simulation`, or write `always @*` or `always_comb`. +loop with other logic. So does an edge-sensitive `always` +that does not have the shape of a flip-flop: one with an edge of a select or +an expression (`@(posedge v[0])`, `@(posedge (a & b))`), an `edge`, an item +without an edge next to edges, a multi-bit edge signal (its least significant +bit decides the edge), or several edges of which the body tests none as an +asynchronous reset. Only `always_ff` must have that shape. A `Simulator` runs +no processes, so building one for such a design fails with +`SimulatorErrorKind::ProcessRequiresSimulation`; use `Simulation`, or write +`always @*` or `always_comb`. ### Timed task calls @@ -147,10 +153,9 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - Declarations: variable declaration initializers of members of an interface array, ANSI port default values, tagged unions, soft packed unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs and `real`. -- Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) and edge operands other than a - plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists. A plain `always` with - such an edge, a multi-bit edge signal, or several edges without a reset is - rejected too, until it runs as a process ([#1708](https://github.com/celox-sim/celox/issues/1708)). +- Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) in event lists, and in + `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit + edge signals, and several edges without an asynchronous reset. - Combinational processes: nonblocking assignments inside `always_comb` ([#453](https://github.com/celox-sim/celox/issues/453)). - Loops: a procedural loop unrolls at most 10,000 iterations; a combinational diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f4a3e96b0a5..ee9a7dc32b9 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -60,7 +60,11 @@ outline: [2, 3] 文にはタイミング制御とノンブロッキング代入を含められません。エッジを持たないそれ以外の センシティビティリストを持つ `always` はプロセスとして実行します。`always @(a) y = a + b;` は `b` だけが変化しても `y` を更新しません。`always @*` として扱うと他の論理と組み合わせループを作るリストも -プロセスとして実行します。`Simulator` はプロセスを実行しないため、このようなデザインでは +プロセスとして実行します。フリップフロップの形をしていないエッジ駆動の `always` も同様です。 +選択や式のエッジ(`@(posedge v[0])`、`@(posedge (a & b))`)、`edge`、エッジと並んだエッジなしの項目、 +複数ビットのエッジ信号(最下位ビットでエッジを判定)、本体がどれも非同期リセットとして判定しない +複数のエッジを持つものがこれに当たります。この形でなければならないのは `always_ff` だけです。 +`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗します。`Simulation` を使うか、 `always @*` / `always_comb` で記述してください。 @@ -135,10 +139,9 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 - 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 -- 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))と単純な信号以外のエッジ - オペランド([#464](https://github.com/celox-sim/celox/issues/464))。このようなエッジ、複数ビットのエッジ信号、リセットを持たない - 複数のエッジを持つ通常の `always` も、プロセスとして実行できるようになるまで拒否します - ([#1708](https://github.com/celox-sim/celox/issues/1708))。 +- 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での + 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 + 非同期リセットを持たない複数のエッジ。 - 組み合わせ回路のプロセス:`always_comb` 内のノンブロッキング代入([#453](https://github.com/celox-sim/celox/issues/453))。 - ループ:手続き的なループの展開は 10,000 回までです。反復回数が実行時に決まる組み合わせ 回路のループは、カウンタ形式の `for` である必要があります。loop-generate は 10,000 回を From d8d628e65550d60570f34500f4dc7c64a9966a1d Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 14:22:37 +0900 Subject: [PATCH 8/8] test(sv): expect sv-tests event_control_edge to pass Change-Id: Ic07f6d1941094224ee0e090dc8381f0a424f3198 --- conformance/sv-tests/expected.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 6e2efb757e4..535226b7930 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1607,8 +1607,8 @@ chapter-9/9.4.1--delay_control-two-blocks-sim.sv 2state pass chapter-9/9.4.1--delay_control-two-blocks-sim.sv 4state pass chapter-9/9.4.1--delay_control.sv 2state pass chapter-9/9.4.1--delay_control.sv 4state pass -chapter-9/9.4.2--event_control_edge.sv 2state fail -chapter-9/9.4.2--event_control_edge.sv 4state fail +chapter-9/9.4.2--event_control_edge.sv 2state pass +chapter-9/9.4.2--event_control_edge.sv 4state pass chapter-9/9.4.2--event_control_negedge.sv 2state pass chapter-9/9.4.2--event_control_negedge.sv 4state pass chapter-9/9.4.2--event_control_posedge.sv 2state pass