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-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c7098531ea9..ce9eeda9600 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -202,6 +202,7 @@ pub(crate) struct LoweredSvPortConnection { pub formal: String, pub actual: String, pub actual_expr: Option, + pub bound_pattern: Option, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -3180,6 +3181,7 @@ fn lower_module_with_overrides( formal: connection.formal().to_string(), actual: connection.actual().to_string(), actual_expr: connection.actual_expr().cloned(), + bound_pattern: connection.bound_pattern().cloned(), }) .collect(), array_element, @@ -3454,6 +3456,7 @@ fn array_element_connections( return Ok(LoweredSvPortConnection { formal: connection.formal.clone(), actual: connection.actual.clone(), + bound_pattern: None, actual_expr: Some(sv::ir::Expr::Select { expr: Box::new(actual_expr.clone()), msb: sv::ir::ConstExpr::Literal((lsb + port_width - 1).to_string()), @@ -3489,11 +3492,50 @@ fn array_element_connections( formal: connection.formal.clone(), actual: connection.actual.clone(), actual_expr: Some(slice), + bound_pattern: None, }) }) .collect() } +fn bind_port_patterns( + connections: &mut [LoweredSvPortConnection], + child: &LoweredSvModule, +) -> Result<(), ParserError> { + for connection in connections { + let Some(pattern) = connection.bound_pattern.take() else { + continue; + }; + let port = child + .source + .ports() + .iter() + .find(|port| port.name() == connection.formal) + .ok_or_else(|| { + ParserError::illegal_context( + "systemverilog port assignment pattern", + format!("unknown port `{}`", connection.formal), + None, + ) + })?; + if port.direction() != sv::ir::PortDirection::Input { + return Err(ParserError::illegal_context( + "systemverilog port assignment pattern", + "only input port assignment patterns are supported", + None, + )); + } + connection.actual_expr = Some(port.bind_pattern(&pattern).map_err(|error| { + ParserError::illegal_context( + "systemverilog port assignment pattern", + error.to_string(), + None, + ) + })?); + } + Ok(()) +} + pub(crate) fn attach_instance_glue( module: &mut SimModule, lowered: &LoweredSvModule, @@ -3525,6 +3567,8 @@ pub(crate) fn attach_instance_glue( let Some(child) = lowered_modules.get(&child_id) else { return Err(unsupported_sv_instance(instance.module_name.clone())); }; + let mut authored_connections = instance.port_connections.clone(); + bind_port_patterns(&mut authored_connections, child)?; let connections = match instance.array_element { Some((position, count)) => { module @@ -3536,7 +3580,7 @@ pub(crate) fn attach_instance_glue( .insert(instance.instance_name.clone(), instance.array_index_base); } array_element_connections( - &instance.port_connections, + &authored_connections, child, position, count, @@ -3546,7 +3590,7 @@ pub(crate) fn attach_instance_glue( &lowered.parameter_types, )? } - None => instance.port_connections.clone(), + None => authored_connections, }; ensure_parent_output_signals( module, 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 f0c637d01e0..60e378a3a0a 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-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index f574291b4e3..6173365ce53 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -121,7 +121,13 @@ fn analyze_source_impl(source: ast::Source) -> Result { ), port.is_net(), ) - .with_default(port.default().cloned().map(Into::into)), + .with_default(port.default().cloned().map(Into::into)) + .with_pattern_target(port.r#type().pattern_target( + &ast::const_functions::Environment { + constants: &constants, + functions: &state.const_functions, + }, + )), ); } let signals = module @@ -172,6 +178,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { connection.formal().to_string(), connection.actual().to_string(), connection.actual_expr().cloned().map(Into::into), + connection.bound_pattern().cloned(), ) }) .collect(), diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 6ab988df73b..d70900dbd5c 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -185,9 +185,7 @@ use dimensions::{ use expressions::guard_zero_divisions; use ff_process::ff_processes_from_scope; use functions::{functions_from_scope, procedural_truth_condition}; -use inlining::{ - expand_expr_calls, expr_signedness, expr_signedness_with_return_types, substitute_expr_idents, -}; +use inlining::{expand_expr_calls, expr_signedness_with_return_types, substitute_expr_idents}; pub(crate) use instances::normalize_identifier; use instances::{collect_connected_nets, expr_ident_name, instances_from_scope}; use parameters::{ @@ -1054,6 +1052,7 @@ impl Module { signed: function.return_signed, is_2state: function.return_is_2state, string: function.return_string, + pattern_type: function.return_type.clone(), }, ) })); @@ -1072,6 +1071,7 @@ impl Module { signed: r#type.is_signed(), is_2state: !r#type.is_4state(), string: false, + pattern_type: None, }, )) })); @@ -1081,7 +1081,10 @@ impl Module { packed_dimensions.expression_signedness = expression_signedness.clone().into(); for instance in &mut instances { for connection in &mut instance.port_connections { - connection.actual_expr = connection.actual_expr.take().map(|expr| { + if let Some(pattern) = &mut connection.bound_pattern { + pattern.resolve_types(&packed_dimensions)?; + } + connection.map_expressions(|expr| { let expr = expand_expr_calls(expr, &functions, &expression_signedness, 0, true); substitute_expr_constants_with_parameter_literals( &syntax_tree.state, @@ -1214,6 +1217,11 @@ impl Module { if let Some(expr) = connection.actual_expr() { collect_connected_nets(expr, &mut connected_nets); } + if let Some(pattern) = connection.bound_pattern() { + pattern.visit_expressions(&mut |expr| { + collect_connected_nets(expr, &mut connected_nets) + }); + } } if let Some(signal) = signals.iter().find(|signal| { !imported.declarations_only @@ -1265,8 +1273,7 @@ impl Module { } for instance in &mut instances { for connection in &mut instance.port_connections { - connection.actual_expr = - connection.actual_expr.take().map(|expr| rename.expr(expr)); + connection.map_expressions(|expr| rename.expr(expr)); } } } @@ -1890,6 +1897,7 @@ pub struct PortConnection { formal: String, actual: String, actual_expr: Option, + bound_pattern: Option, } impl PortConnection { @@ -1898,6 +1906,20 @@ impl PortConnection { formal, actual, actual_expr, + bound_pattern: None, + } + } + + /// An untyped assignment pattern with caller-owned values. The receiving + /// port supplies its element types after parameter specialization. + pub fn bound_pattern(&self) -> Option<&BoundPattern> { + self.bound_pattern.as_ref() + } + + fn map_expressions(&mut self, mut map: impl FnMut(Expr) -> Expr) { + self.actual_expr = self.actual_expr.take().map(&mut map); + if let Some(pattern) = &mut self.bound_pattern { + pattern.map_expressions(&mut map); } } @@ -2435,6 +2457,8 @@ impl ConditionalAssignment { #[derive(Debug, Clone, PartialEq, Eq)] struct Function { + /// The aggregate return type, frozen in its declaration scope. + return_type: Option, return_real: bool, /// Whether the function returns a `string`. return_string: bool, @@ -2711,6 +2735,8 @@ struct FunctionReturnMetadata { is_2state: bool, /// The function returns a `string`. string: bool, + /// Declared aggregate type, available before function bodies are inlined. + pattern_type: Option, } #[derive(Debug, Clone, Default, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs index 63ff17e5348..78b6b1f50d8 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -3,7 +3,9 @@ //! the receiving declaration's assignment context (IEEE 1800-2023 10.9). use super::*; mod binding; +mod ports; pub(super) use binding::{Kind as NativeKind, prepare_native}; +pub(in crate::ast) use ports::{ValueType, from_port, native_value_type}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct BoundPattern { @@ -26,12 +28,17 @@ enum Items { pub(super) enum Key { Index(i128), Member(String), + Name { name: String, index: Option }, Default, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(super) enum Value { - Expression(Expr), + Expression { + expr: Expr, + signed: Option, + value_type: ports::ValueType, + }, Pattern(BoundPattern), } @@ -42,8 +49,8 @@ pub(super) fn from_param( ) -> Converted { match binding::value(root, tree, dims)? { Value::Pattern(pattern) => Ok(pattern), - Value::Expression(value) => Ok(BoundPattern { - items: Items::Value(value), + Value::Expression { expr, .. } => Ok(BoundPattern { + items: Items::Value(expr), }), } } @@ -118,6 +125,7 @@ fn frozen(state: &AnalysisState, expr: Expr, dims: &PackedDimensions) -> Convert Expr::Literal(typecheck::format_integral_literal_binary(&literal)) } value => { + let value = substitute_expr_idents(value, &dims.array_parameter_values); let values = dims .parameter_values .iter() @@ -154,39 +162,19 @@ impl Value { if let Self::Pattern(pattern) = self { return pattern.lower(state, shape, dims); } - let Self::Expression(value) = self else { - unreachable!() + let (value, signed, value_type) = match self { + Self::Expression { + expr, + signed, + value_type, + } => ( + expr, + signed.ok_or_else(|| unsupported("assignment pattern operand signedness"))?, + value_type.known(), + ), + Self::Pattern(_) => unreachable!(), }; - if default && let Some((dimension, rest)) = shape.unpacked.split_first() { - let count = eval_ast_const_expr(state, &dimension.width, &dims.const_env) - .and_then(|n| usize::try_from(n).ok()) - .ok_or_else(|| unsupported("pattern target array size"))?; - let shape = VariableDimensions { - real: false, - string: false, - class: None, - unpacked: rest.to_vec(), - ..shape.clone() - }; - return Ok(Expr::Concat(vec![ - self.lower(state, &shape, dims, true)?; - count - ])); - } - if !shape.unpacked.is_empty() { - return Err(unsupported( - "scalar assignment pattern item for unpacked array", - )); - } - let width = patterns::shape_width(state, shape, dims) - .ok_or_else(|| unsupported("assignment pattern element width"))?; - let signed = - expr_signedness(value, &dims.expression_signedness, &dims.functions).unwrap_or(false); - Ok(Expr::Resize { - expr: Box::new(value.clone()), - width, - signed, - }) + patterns::assignment_value(state, value, signed, value_type, shape, dims, default) } } @@ -243,21 +231,6 @@ impl BoundPattern { }) }) .collect::>(); - } else if !shape.members.is_empty() { - if shape.members.len() > 1 && shape.members.iter().all(|m| m.offset() == 0) { - return Err(unsupported("assignment pattern for a packed union")); - } - keys = shape - .members - .iter() - .map(|m| Key::Member(m.name().into())) - .collect(); - shapes.extend( - shape - .members - .iter() - .map(|m| procedural::dimensions_from_type(m.r#type())), - ); } else if let Some((dim, rest)) = shape.packed.split_first() && !rest.is_empty() { @@ -289,6 +262,21 @@ impl BoundPattern { }) }) .collect(); + } else if !shape.members.is_empty() { + if shape.members.len() > 1 && shape.members.iter().all(|m| m.offset() == 0) { + return Err(unsupported("assignment pattern for a packed union")); + } + keys = shape + .members + .iter() + .map(|m| Key::Member(m.name().into())) + .collect(); + shapes.extend( + shape + .members + .iter() + .map(|m| procedural::dimensions_from_type(m.r#type())), + ); } else { let width = patterns::shape_width(state, shape, dims) .ok_or_else(|| unsupported("pattern target width"))?; @@ -329,7 +317,27 @@ impl BoundPattern { values.iter().map(|v| (v, false)).collect::>() } Items::Keyed(items) => { - for (key, _) in items { + let structure = shape.unpacked.is_empty() + && shape.packed.len() <= 1 + && !shape.members.is_empty(); + let items = items + .iter() + .map(|(key, value)| { + let key = match key { + Key::Name { name, .. } if structure => Key::Member(name.clone()), + Key::Name { index, .. } => Key::Index(index.ok_or_else(|| { + unsupported("nonconstant assignment pattern index") + })?), + key => key.clone(), + }; + Ok((key, value)) + }) + .collect::>>()?; + let mut seen = HashSet::default(); + for (key, _) in &items { + if !seen.insert(key) { + return Err(unsupported("duplicate assignment pattern key")); + } if *key != Key::Default && !keys.contains(key) { return Err(unsupported("assignment pattern key outside target")); } @@ -340,13 +348,13 @@ impl BoundPattern { .iter() .rev() .find(|(k, _)| k == key) - .map(|(_, v)| (v, false)) + .map(|(_, v)| (*v, false)) .or_else(|| { items .iter() .rev() .find(|(k, _)| *k == Key::Default) - .map(|(_, v)| (v, true)) + .map(|(_, v)| (*v, true)) }) .ok_or_else(|| unsupported("assignment pattern missing element")) }) diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs index bc6ae8cb1b4..4dac52c909e 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs @@ -52,9 +52,14 @@ pub(in crate::ast) fn prepare_native( let id = item.key.ok_or_else(mismatch)?; keys.push(match &native.expression(id).kind { ExprKind::Literal(text) if text == "default" => Key::Default, + ExprKind::Name(name) if shape.is_none() => Key::Name { + name: instances::normalize_identifier(&name.spelling), + index: integer(id).ok(), + }, ExprKind::Name(name) if shape.is_some_and(|shape| { shape.unpacked.is_empty() + && shape.packed.len() <= 1 && shape.members.iter().any(|member| { member.name() == instances::normalize_identifier(&name.spelling) }) @@ -77,6 +82,15 @@ pub(super) fn value( root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions, +) -> Converted { + value_mode(root, tree, dims, true) +} + +pub(super) fn value_mode( + root: ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, + constant: bool, ) -> Converted { enum Job { Enter(ExprId), @@ -98,14 +112,42 @@ pub(super) fn value( jobs.push(Job::Finish(plan.kind, plan.bindings.len())); jobs.extend(plan.bindings.into_iter().rev().map(Job::Enter)); } - ExprKind::Pattern { .. } => { + ExprKind::Pattern { .. } if constant => { values.push(patterns::constant_native(id, tree, dims)?) } - _ => values.push(Value::Expression(frozen( - &tree.state, - expression_binding::bind(id, tree, dims)?, - dims, - )?)), + _ => { + let expr = expression_binding::bind(id, tree, dims)?; + let (expr, signed, value_type) = if constant { + // Capture the self-determined type before folding the + // value into bits, just as for runtime port values. + let types = dimensions::query_context_for_operand(id, tree, dims)?; + let value_type = super::ports::ValueType::Known( + super::ports::native_value_type(id, tree, &types)?, + ); + let signed = + dimensions::expression_signedness(&expr, &types, &types.const_env); + let expr = frozen(&tree.state, expr, dims)?; + let signed = Some(signed.unwrap_or_else(|| { + dimensions::expression_signedness(&expr, &types, &types.const_env) + .unwrap_or(false) + })); + + (expr, signed, value_type) + } else { + let signed = + dimensions::expression_signedness(&expr, dims, &dims.const_env); + ( + expr, + signed, + super::ports::native_value_type_plan(id, tree, dims)?, + ) + }; + values.push(Value::Expression { + expr, + signed, + value_type, + }); + } } } Job::Finish(kind, count) => { @@ -183,7 +225,10 @@ mod tests { depth += 1; match &items[0] { Value::Pattern(pattern) => at = pattern, - Value::Expression(Expr::Literal(value)) => { + Value::Expression { + expr: Expr::Literal(value), + .. + } => { assert_eq!(value, "1"); break; } diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs new file mode 100644 index 00000000000..c9eaace4b74 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs @@ -0,0 +1,300 @@ +//! Port patterns bind values in the caller and sizes in the specialized callee. +use super::*; + +/// Keep the operand's type independently of its lowered bit expression. A +/// conditional retains matching branch types; calls resolve after caller +/// signatures are complete, before inlining erases their declared return type. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(in crate::ast) enum ValueType { + Known(Option), + Call(Expr), + Conditional(Box, Box), +} + +impl ValueType { + pub(super) fn known(&self) -> Option<&Type> { + match self { + Self::Known(ty) => ty.as_ref(), + _ => None, + } + } + + fn resolve(&self, dims: &PackedDimensions) -> Option { + match self { + Self::Known(ty) => ty.clone(), + Self::Call(Expr::Call { + callee: Callee::Subroutine(name), + .. + }) => dims + .function_return_types + .get(name) + .and_then(|metadata| metadata.pattern_type.clone()), + Self::Call(_) => None, + Self::Conditional(left, right) => { + let left = left.resolve(dims)?; + (right.resolve(dims).as_ref() == Some(&left)).then_some(left) + } + } + } + + fn map_expressions(&mut self, map: &mut impl FnMut(Expr) -> Expr) { + match self { + Self::Known(_) => {} + Self::Call(expr) => *expr = map(expr.clone()), + Self::Conditional(left, right) => { + left.map_expressions(map); + right.map_expressions(map); + } + } + } +} + +pub(in crate::ast) fn from_port( + root: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted { + match binding::value_mode(root, tree, dims, false)? { + Value::Pattern(pattern) => Ok(pattern), + _ => Err(unsupported("untyped port assignment pattern")), + } +} + +impl BoundPattern { + pub(in crate::ast) fn resolve_types(&mut self, dims: &PackedDimensions) -> Converted<()> { + fn value(value: &mut Value, dims: &PackedDimensions) -> Converted<()> { + match value { + Value::Pattern(pattern) => pattern.resolve_types(dims)?, + Value::Expression { + expr, + signed, + value_type, + } => { + if signed.is_none() { + *signed = Some( + dimensions::expression_signedness(expr, dims, &dims.const_env) + .ok_or_else(|| { + unsupported("assignment pattern operand signedness") + })?, + ); + } + *value_type = ValueType::Known(value_type.resolve(dims)); + } + } + Ok(()) + } + match &mut self.items { + Items::List(items) | Items::Repeat(_, items) => { + for item in items { + value(item, dims)?; + } + } + Items::Keyed(items) => { + for (_, item) in items { + value(item, dims)?; + } + } + _ => {} + } + Ok(()) + } + + pub(in crate::ast) fn visit_expressions<'a>(&'a self, visit: &mut impl FnMut(&'a Expr)) { + fn value<'a>(value: &'a Value, visit: &mut impl FnMut(&'a Expr)) { + match value { + Value::Pattern(pattern) => pattern.visit_expressions(visit), + Value::Expression { expr, .. } => visit(expr), + } + } + match &self.items { + Items::Value(expr) | Items::ArrayValue { value: expr, .. } => visit(expr), + Items::List(items) | Items::Repeat(_, items) => { + for item in items { + value(item, visit); + } + } + Items::Keyed(items) => { + for (_, item) in items { + value(item, visit); + } + } + } + } + + pub(in crate::ast) fn map_expressions(&mut self, map: &mut impl FnMut(Expr) -> Expr) { + fn value(value: &mut Value, map: &mut impl FnMut(Expr) -> Expr) { + match value { + Value::Pattern(pattern) => pattern.map_expressions(map), + Value::Expression { + expr, value_type, .. + } => { + *expr = map(expr.clone()); + value_type.map_expressions(map); + } + } + } + match &mut self.items { + Items::Value(expr) | Items::ArrayValue { value: expr, .. } => { + *expr = map(expr.clone()); + } + Items::List(items) | Items::Repeat(_, items) => { + for item in items { + value(item, map); + } + } + Items::Keyed(items) => { + for (_, item) in items { + value(item, map); + } + } + } + } + + pub(crate) fn bind_port(&self, target: &Type) -> Converted { + let state = AnalysisState::default(); + let shape = procedural::dimensions_from_type(target); + self.lower(&state, &shape, &PackedDimensions::default()) + .map(Into::into) + } +} + +impl Type { + /// Freeze declaration bounds while constant functions and child parameters + /// are available. Caller identifiers in pattern values never enter this scope. + pub(crate) fn pattern_target( + &self, + constants: &dyn typecheck::ConstantEnvironment, + ) -> Option { + let literal = |expr: &ConstExpr| { + typecheck::eval_const_expr_in_env(&expr.clone().into(), constants) + .map(|value| ConstExpr::Literal(value.to_string())) + }; + let mut ty = self.clone(); + for range in &mut ty.packed_ranges { + range.left = literal(&range.left)?; + range.right = literal(&range.right)?; + } + for range in &mut ty.unpacked_ranges { + range.left = literal(&range.left)?; + range.right = literal(&range.right)?; + range.size = match range.size.as_ref() { + Some(size) => Some(literal(size)?), + None => None, + }; + } + ty.members = ty + .members + .into_iter() + .map(|member| { + let ty = member.r#type().pattern_target(constants)?; + Some(member.with_type(|_| ty)) + }) + .collect::>()?; + Some(ty) + } +} + +/// Capture aggregate identity before caller names and dimensions are lowered. +pub(in crate::ast) fn native_value_type( + root: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted> { + native_value_type_plan(root, tree, dims).map(|ty| ty.resolve(dims)) +} + +pub(super) fn native_value_type_plan( + root: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted { + use celox_sv_syntax::ExprKind; + enum Job { + Enter(celox_sv_syntax::ExprId), + Conditional, + } + let native = tree.declarations(); + let mut jobs = vec![Job::Enter(root)]; + let mut values = Vec::new(); + while let Some(job) = jobs.pop() { + match job { + Job::Enter(root) => { + let root = expression_binding::ungroup(root, native); + match native.expression(root).kind { + ExprKind::Conditional { + then_expression, + else_expression, + .. + } => { + jobs.push(Job::Conditional); + jobs.push(Job::Enter(else_expression)); + jobs.push(Job::Enter(then_expression)); + } + ExprKind::Call { .. } => { + values.push(ValueType::Call(expression_binding::bind(root, tree, dims)?)) + } + _ => { + let shape = + if matches!(native.expression(root).kind, ExprKind::Pattern { .. }) { + patterns::typed_shape(root, tree, dims)? + } else { + dimensions::operand_shape(root, tree, dims)? + }; + values.push(ValueType::Known( + shape + .filter(|shape| { + !shape.members.is_empty() + || !shape.unpacked.is_empty() + || shape.packed.len() > 1 + }) + .and_then(|shape| shape.pattern_type(&tree.state, dims)), + )); + } + } + } + Job::Conditional => { + let right = values + .pop() + .ok_or_else(|| unsupported("pattern operand type"))?; + let left = values + .pop() + .ok_or_else(|| unsupported("pattern operand type"))?; + values.push(ValueType::Conditional(Box::new(left), Box::new(right))); + } + } + } + values + .pop() + .ok_or_else(|| unsupported("pattern operand type")) +} + +impl VariableDimensions { + pub(in crate::ast) fn pattern_type( + &self, + state: &AnalysisState, + dims: &PackedDimensions, + ) -> Option { + let mut ty = Type::new(if self.is_2state { + TypeKind::Bit + } else { + TypeKind::Logic + }); + ty.is_signed = self.signed; + ty.packed_ranges = self + .packed + .iter() + .map(|dim| PackedRange::new(dim.left.clone(), dim.right.clone())) + .collect(); + ty.unpacked_ranges = self + .unpacked + .iter() + .map(|dim| UnpackedRange::new(dim.left.clone(), dim.right.clone())) + .collect(); + ty.members = self.members.clone(); + ty.signed_element_depth = self.signed_element_depth; + ty.pattern_target(&const_functions::Environment { + constants: &*dims.const_env, + functions: &state.const_functions, + }) + } +} diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index e822be405e2..f7adf4d54f9 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -367,6 +367,18 @@ fn return_metadata( signed: ty.is_some_and(Type::is_signed), is_2state: ty.is_some_and(|ty| ty.kind() == TypeKind::Bit), string: ty.is_some_and(|ty| ty.kind() == TypeKind::String), + pattern_type: ty + .filter(|ty| { + !ty.members.is_empty() + || !ty.unpacked_ranges.is_empty() + || ty.packed_ranges.len() > 1 + }) + .and_then(|ty| { + ty.pattern_target(&const_functions::Environment { + constants: &*context.const_env, + functions: &state.const_functions, + }) + }), } } fn signature( @@ -736,6 +748,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( signed: ty.is_signed(), is_2state: !ty.is_4state(), string: false, + pattern_type: None, }, ); publish(&tree.state.dimensions, &key, &context); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 6778c863882..f856c5862f0 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -865,6 +865,7 @@ mod tests { signed: false, is_2state: false, string: false, + pattern_type: None, }, ); for declaration in &tree.declarations().data_declarations { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index 67d66b43944..10c9d8a9e4f 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -125,6 +125,7 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( signed: f.return_signed, is_2state: f.return_is_2state, string: f.return_string, + pattern_type: f.return_type.clone(), }, ) })); diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 65393bef9c8..ecbd0194802 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -268,5 +268,17 @@ fn native_signature( }), return_signed: result.is_some_and(|ty| ty.signed), return_is_2state: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::Bit), + return_type: ty + .filter(|ty| { + !ty.members.is_empty() + || !ty.unpacked_ranges.is_empty() + || ty.packed_ranges.len() > 1 + }) + .and_then(|ty| { + ty.pattern_target(&const_functions::Environment { + constants: &*context.const_env, + functions: &tree.state.const_functions, + }) + }), }) } diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index efd555044b1..37f63213a44 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -2063,6 +2063,7 @@ mod tests { signed: false, is_2state: false, string: false, + pattern_type: None, }; let inner = FunctionReturnMetadata { arguments: None, @@ -2072,6 +2073,7 @@ mod tests { signed: true, is_2state: true, string: false, + pattern_type: None, }; let dimensions = PackedDimensions { function_return_types: [ diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 90db4712621..2f10cf8e479 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -43,15 +43,16 @@ pub(super) fn instances_from_scope( for instance in &mut instances[start..] { instance.name = item.instance_name(&instance.name); for connection in &mut instance.port_connections { - if let Some(expr) = &mut connection.actual_expr { - *expr = substitute_expr_constants_with_parameter_literals( + connection.map_expressions(|expr| { + let mut expr = substitute_expr_constants_with_parameter_literals( &syntax_tree.state, - expr.clone(), + expr, &item.env, &item.literals, ); - item.expr(expr); - } + item.expr(&mut expr); + expr + }); } } } @@ -121,7 +122,7 @@ fn instances_from_native_declaration( interface, )?; for connection in &mut port_connections { - connection.actual_expr = connection.actual_expr.take().map(|expr| { + connection.map_expressions(|expr| { substitute_expr_constants_with_parameter_literals( &syntax_tree.state, expr, diff --git a/crates/celox-sv-analyzer/src/ast/instances/connections.rs b/crates/celox-sv-analyzer/src/ast/instances/connections.rs index 9afd3ff7124..b2fa5a74aa7 100644 --- a/crates/celox-sv-analyzer/src/ast/instances/connections.rs +++ b/crates/celox-sv-analyzer/src/ast/instances/connections.rs @@ -50,14 +50,7 @@ pub(super) fn connections( continue; } if let Some(id) = value { - let actual_expr = - expression_binding::value(id, tree.declarations(), tree, dimensions)?; - let actual = expr_ident_name(&actual_expr).unwrap_or_else(|| formal.clone()); - lowered.push(PortConnection::new( - formal.clone(), - actual, - Some(actual_expr), - )); + lowered.push(expression_connection(formal.clone(), id, tree, dimensions)?); } } } else { @@ -72,6 +65,10 @@ pub(super) fn connections( lowered.extend(connections.iter().cloned()); continue; } + if let ConnectionValue::Expression(id) = value { + lowered.push(expression_connection(formal, *id, tree, dimensions)?); + continue; + } let actual_expr = match value { ConnectionValue::Implicit => Some(Expr::Ident(formal.clone())), ConnectionValue::Empty => None, @@ -94,3 +91,24 @@ pub(super) fn connections( } Ok(lowered) } + +fn expression_connection( + formal: String, + root: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted { + let native = tree.declarations(); + let root = expression_binding::ungroup(root, native); + if matches!( + native.expression(root).kind, + celox_sv_syntax::ExprKind::Pattern { target: None, .. } + ) { + let mut connection = PortConnection::new(formal.clone(), formal, None); + connection.bound_pattern = Some(bound_patterns::from_port(root, tree, dims)?); + return Ok(connection); + } + let expr = expression_binding::value(root, native, tree, dims)?; + let actual = expr_ident_name(&expr).unwrap_or_else(|| formal.clone()); + Ok(PortConnection::new(formal, actual, Some(expr))) +} diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index 389ac475abf..c768f78170a 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -358,6 +358,14 @@ pub(super) fn analyze_module( ¤t.type_aliases, ); dimensions.extend(parameter_packed_dimensions(¤t.parameters)); + dimensions.functions = Arc::new(current.functions.clone()); + dimensions + .function_return_types + .extend(current.function_return_types.clone()); + if let Some(item) = &generated_item { + let mut views = generate::ScopeViews::new(&dimensions); + dimensions = views.dimensions(item).clone(); + } let native = instances::declaration_from_item(id, tree)?; let interface_name = instances::normalize_identifier(&native.name.spelling); let (definition_tree, definition_path) = &definitions[&interface_name]; @@ -472,10 +480,39 @@ pub(super) fn analyze_module( else { continue; }; - let Some(actual) = connection.actual_expr.clone() else { + let actual = if let Some(pattern) = &connection.bound_pattern { + if port.direction != PortDirection::Input { + return Err(unsupported( + "output/inout/ref interface port assignment pattern", + )); + } + let mut pattern = pattern.clone(); + pattern.resolve_types(&dimensions)?; + pattern.map_expressions(&mut |expr| { + let mut expr = substitute_expr_constants_with_parameter_literals( + &tree.state, + expr, + &dimensions.const_env, + ¤t.parameter_values, + ); + if let Some(item) = &generated_item { + item.expr(&mut expr); + } + expr + }); + let shape = port_dimensions.get(&port.name).ok_or_else(|| { + unsupported("interface assignment pattern port shape") + })?; + pattern.lower(&port_state, shape, &port_dimensions)? + } else if let Some(actual) = connection.actual_expr.clone() { + actual + } else { continue; }; - let actual = if elements.shape.is_empty() { + // An untyped pattern takes the single formal's context, + // so every element of an interface array receives it. + let actual = if elements.shape.is_empty() || connection.bound_pattern.is_some() + { actual } else { let port_shape = port_dimensions.get(&port.name).unwrap(); diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs.rs b/crates/celox-sv-analyzer/src/ast/packed_structs.rs index 5b90e31879f..eb684292cb3 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs.rs @@ -12,6 +12,8 @@ pub(super) use selects::{select_member, whole_member}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(super) struct PackedMember { + /// Nominal aggregate identity (IEEE 1800-2023 6.22.1), retained through aliases. + owner: Arc, name: String, offset: usize, r#type: Type, diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index 0bc33f33312..c3908e74344 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -32,6 +32,7 @@ pub(in crate::ast) fn native_type( state: &AnalysisState, union: bool, signed: bool, + owner: Arc, fields: Vec<(String, Type)>, ranges: Vec, env: &HashMap, @@ -44,6 +45,7 @@ pub(in crate::ast) fn native_type( return None; } Some(PackedMember { + owner: owner.clone(), name, offset: 0, r#type: capture_member_type(state, ty, env)?, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 177764df0b8..3072f78cc24 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -406,7 +406,7 @@ fn pattern_items( use bound_patterns::{Key, NativeKind}; let plan = bound_patterns::prepare_native(root, tree, dims, Some(shape))?; let wrong = || unsupported("assignment pattern items do not match the target shape"); - if shape.unpacked.is_empty() && !shape.members.is_empty() { + if shape.unpacked.is_empty() && shape.packed.len() <= 1 && !shape.members.is_empty() { if shape.members.len() > 1 && shape.members.iter().all(|member| member.offset() == 0) { return Err(unsupported("assignment pattern for a packed union")); } @@ -432,7 +432,7 @@ fn pattern_items( named.insert(name, value); } Key::Default => default = Some(value), - Key::Index(_) => { + Key::Index(_) | Key::Name { .. } => { return Err(unsupported("structure assignment pattern form")); } } @@ -537,7 +537,7 @@ fn pattern_items( indices.insert(index); } Key::Default => default = true, - Key::Member(_) => { + Key::Member(_) | Key::Name { .. } => { return Err(unsupported( "member or type key in an array assignment pattern", )); diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index 51ce1e95e31..59521c62944 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -41,6 +41,7 @@ fn constant_pattern_value( .filter(|(name, _)| !dims.const_env.contains_key(*name)) .map(|(name, value)| (name.clone(), value.clone())) .collect(); + let value = substitute_expr_idents(value, &dims.array_parameter_values); let value = substitute_expr_constants_with_parameter_literals(state, value, &dims.const_env, &values); let Expr::Literal(value) = @@ -95,9 +96,11 @@ fn pattern_value( literal.value ^= &literal.value & &literal.mask; literal.mask = num_bigint::BigUint::default(); } - return Ok(bound_patterns::Value::Expression(Expr::Literal( - typecheck::format_integral_literal_binary(&literal), - ))); + return Ok(bound_patterns::Value::Expression { + expr: Expr::Literal(typecheck::format_integral_literal_binary(&literal)), + signed: Some(shape.signed), + value_type: bound_patterns::ValueType::Known(shape.pattern_type(state, dims)), + }); } Ok(bound_patterns::Value::list(parts)) } @@ -117,3 +120,119 @@ fn dimension_bounds( .ok_or_else(bounds)?; Ok((left, right, count)) } + +/// Apply the assignment context of a selected pattern element. A default +/// descends through subarrays and structures; state conversion happens at +/// the leaf so mixed bit/logic aggregates preserve their member types. +pub(super) fn assignment_value( + state: &AnalysisState, + value: &Expr, + signed: bool, + value_type: Option<&Type>, + shape: &VariableDimensions, + dims: &PackedDimensions, + default: bool, +) -> Converted { + let default = default + && !value_type.is_some_and(|ty| shape.pattern_type(state, dims).as_ref() == Some(ty)); + if default { + let array = if let Some((dim, rest)) = shape.unpacked.split_first() { + Some(( + &dim.width, + VariableDimensions { + unpacked: rest.to_vec(), + ..shape.clone() + }, + )) + } else if let Some((dim, rest)) = shape.packed.split_first() + && !rest.is_empty() + { + Some(( + &dim.width, + VariableDimensions { + packed: rest.to_vec(), + signed: shape.signed_element_depth == Some(1), + signed_element_depth: shape + .signed_element_depth + .and_then(|n| n.checked_sub(1)) + .filter(|n| *n > 0), + ..shape.clone() + }, + )) + } else { + None + }; + if let Some((width, element)) = array { + let count = eval_ast_const_expr(state, width, &dims.const_env) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| unsupported("pattern target array size"))?; + return Ok(Expr::Concat(vec![ + assignment_value( + state, value, signed, value_type, &element, dims, true + )?; + count + ])); + } + if !shape.members.is_empty() { + if shape.members.len() > 1 && shape.members.iter().all(|member| member.offset() == 0) { + return Err(unsupported("assignment pattern for a packed union")); + } + return Ok(Expr::Concat( + shape + .members + .iter() + .map(|member| { + assignment_value( + state, + value, + signed, + value_type, + &procedural::dimensions_from_type(member.r#type()), + dims, + true, + ) + }) + .collect::>()?, + )); + } + } + let actual = value_type + .map(procedural::dimensions_from_type) + .and_then(|shape| array_compatibility::unpacked_array_type(state, &shape, dims)); + let target = array_compatibility::unpacked_array_type(state, shape, dims); + match (actual, target) { + (Some(actual), Some(target)) if !actual.is_assignment_compatible_with(&target) => { + return Err(AnalyzerError::IncompatibleUnpackedArray { + context: "assignment pattern element".into(), + actual, + target, + }); + } + (Some(_), None) => { + return Err(unsupported( + "unpacked array assignment pattern item for scalar", + )); + } + (None, Some(_)) => { + return Err(unsupported( + "scalar assignment pattern item for unpacked array", + )); + } + _ => {} + } + let width = shape_width(state, shape, dims) + .ok_or_else(|| unsupported("assignment pattern element width"))?; + let resized = Expr::Resize { + expr: Box::new(value.clone()), + width, + signed, + }; + Ok(if shape.is_2state { + Expr::Unary { + op: UnaryOp::ToTwoState, + expr: Box::new(resized), + } + } else { + resized + }) +} diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index e70aab770d1..0253bcdeaec 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -76,7 +76,7 @@ fn indexed_items( *slot = Some((value, false)); } Key::Default => default = Some((value, true)), - Key::Member(_) => { + Key::Member(_) | Key::Name { .. } => { return Err(unsupported("member key in an array assignment pattern")); } } @@ -131,6 +131,45 @@ fn select<'a>( false, )); } + if let Some((dim, rest)) = shape.packed.split_first() + && !rest.is_empty() + { + let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; + let sub = Shape::Owned(Rc::new(VariableDimensions { + randomizable: true, + real: false, + string: false, + class: None, + packed: rest.to_vec(), + unpacked: Vec::new(), + signed: shape.signed_element_depth == Some(1), + is_2state: shape.is_2state, + members: shape.members.clone(), + signed_element_depth: shape + .signed_element_depth + .and_then(|depth| depth.checked_sub(1)) + .filter(|depth| *depth > 0), + })); + let items = indexed_items(kind, bindings, count, |index| { + (left.min(right)..=left.max(right)) + .contains(&index) + .then(|| usize::try_from(index.abs_diff(left)).ok()) + .flatten() + })?; + return Ok(( + items + .into_iter() + .map(|(value, default)| Selected { + value, + shape: sub.clone(), + default, + check: false, + }) + .collect(), + false, + true, + )); + } if !shape.members.is_empty() { let members = &shape.members; if members.len() > 1 && members.iter().all(|member| member.offset() == 0) { @@ -145,7 +184,7 @@ fn select<'a>( members.len() ))); } - bindings + bindings.into_iter().map(|value| (value, false)).collect() } NativeKind::Keyed(keys) => { let mut named = Vec::new(); @@ -154,7 +193,7 @@ fn select<'a>( match key { Key::Member(name) => named.push((name, value)), Key::Default => default = Some(value), - Key::Index(_) => { + Key::Index(_) | Key::Name { .. } => { return Err(unsupported("structure assignment pattern form")); } } @@ -173,8 +212,8 @@ fn select<'a>( named .iter() .find(|(name, _)| name == member.name()) - .map(|(_, value)| *value) - .or(default) + .map(|(_, value)| (*value, false)) + .or(default.map(|value| (value, true))) .ok_or_else(|| { unsupported(format!( "assignment pattern without a value for member `{}`", @@ -190,10 +229,10 @@ fn select<'a>( members .iter() .zip(values) - .map(|(member, value)| Selected { + .map(|(member, (value, default))| Selected { value, shape: Shape::Owned(Rc::new(procedural::dimensions_from_type(member.r#type()))), - default: false, + default, check: false, }) .collect(), @@ -201,45 +240,6 @@ fn select<'a>( false, )); } - if let Some((dim, rest)) = shape.packed.split_first() - && !rest.is_empty() - { - let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; - let sub = Shape::Owned(Rc::new(VariableDimensions { - randomizable: true, - real: false, - string: false, - class: None, - packed: rest.to_vec(), - unpacked: Vec::new(), - signed: shape.signed_element_depth == Some(1), - is_2state: shape.is_2state, - members: Vec::new(), - signed_element_depth: shape - .signed_element_depth - .and_then(|depth| depth.checked_sub(1)) - .filter(|depth| *depth > 0), - })); - let items = indexed_items(kind, bindings, count, |index| { - (left.min(right)..=left.max(right)) - .contains(&index) - .then(|| usize::try_from(index.abs_diff(left)).ok()) - .flatten() - })?; - return Ok(( - items - .into_iter() - .map(|(value, _)| Selected { - value, - shape: sub.clone(), - default: false, - check: false, - }) - .collect(), - false, - true, - )); - } let width = shape_width(state, &shape, dims) .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { @@ -415,16 +415,23 @@ pub(in crate::ast) fn bind_native( )); } else { let value = expression_binding::bind_value(id, native, tree, dims, None)?; - let width = shape_width(&tree.state, &shape, dims) - .ok_or_else(|| unsupported("assignment pattern element width"))?; + let type_dims = dimensions::query_context_for_operand(id, tree, dims)?; let signed = - expr_signedness(&value, &dims.expression_signedness, &dims.functions) - .unwrap_or(false); - values.push(Expr::Resize { - expr: Box::new(value), - width, + dimensions::expression_signedness(&value, &type_dims, &type_dims.const_env) + .ok_or_else(|| unsupported("assignment pattern operand signedness"))?; + let descend_default = default + && (shape.unpacked.is_empty() + || native_rank(id, native, dims) < shape.unpacked.len()); + let value_type = bound_patterns::native_value_type(id, tree, &type_dims)?; + values.push(assignment_value( + &tree.state, + &value, signed, - }); + value_type.as_ref(), + &shape, + dims, + descend_default, + )?); } } Job::Finish { diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 1b9de91aa9d..6f96b7edded 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -20,6 +20,7 @@ pub(in crate::ast) fn bind_in( Enter(TypeId), Enum(Vec), Aggregate { + owner: Arc, union: bool, signed: bool, names: Vec, @@ -112,7 +113,17 @@ pub(in crate::ast) fn bind_in( } names.push(name); } + let token = &native.tokens[data.tokens.start]; + let span = token.origin.spelling; + let owner = Arc::from(format!( + "{}:{}:{}:{}", + tree.syntax_tree.root_name().unwrap_or_default(), + native.sources.file(span.file).path.display(), + span.start, + data.tokens.start + )); jobs.push(Job::Aggregate { + owner, union: *union, signed: data.signed.unwrap_or(false), names, @@ -156,6 +167,7 @@ pub(in crate::ast) fn bind_in( values.push(ty); } Job::Aggregate { + owner, union, signed, names, @@ -170,6 +182,7 @@ pub(in crate::ast) fn bind_in( &tree.state, union, signed, + owner, fields, ranges, &context.const_env, diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index bb9656928cb..9a02e684932 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -360,6 +360,7 @@ pub struct Port { r#type: Type, is_net: bool, default: Option, + pattern_target: Option, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -417,9 +418,26 @@ impl Port { r#type, is_net, default: None, + pattern_target: None, } } + pub(crate) fn with_pattern_target(mut self, target: Option) -> Self { + self.pattern_target = target; + self + } + + /// Bind caller-owned pattern values in this specialized port's type. + pub fn bind_pattern( + &self, + pattern: &crate::ast::BoundPattern, + ) -> Result { + let target = self.pattern_target.as_ref().ok_or_else(|| { + crate::AnalyzerError::Unsupported("assignment pattern port type".into()) + })?; + pattern.bind_port(target) + } + pub fn name(&self) -> &str { &self.name } @@ -569,17 +587,30 @@ pub struct PortConnection { formal: String, actual: String, actual_expr: Option, + bound_pattern: Option, } impl PortConnection { - pub(crate) fn new(formal: String, actual: String, actual_expr: Option) -> Self { + pub(crate) fn new( + formal: String, + actual: String, + actual_expr: Option, + bound_pattern: Option, + ) -> Self { Self { formal, actual, actual_expr, + bound_pattern, } } + /// An untyped assignment pattern with caller-owned values. The receiving + /// port supplies its element types after parameter specialization. + pub fn bound_pattern(&self) -> Option<&crate::ast::BoundPattern> { + self.bound_pattern.as_ref() + } + pub fn formal(&self) -> &str { &self.formal } diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/array_parameter_patterns.rs b/crates/celox-sv-analyzer/src/source_tree/tests/array_parameter_patterns.rs index 7b311f3f37d..2161ca097ac 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/array_parameter_patterns.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/array_parameter_patterns.rs @@ -21,6 +21,10 @@ fn leaves(source: &Source) -> Vec<(usize, i128)> { let mut leaves = Vec::new(); while let Some(value) = pending.pop() { match value { + Expr::Unary { + op: crate::ast::UnaryOp::ToTwoState, + expr, + } => pending.push(expr), Expr::Concat(parts) => pending.extend(parts.iter().rev()), Expr::Resize { expr, width, .. } => { let Expr::Binary { diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs b/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs index 2cb396200ca..af7e90e2bc3 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs @@ -55,6 +55,10 @@ fn initialized(pattern: BoundPattern, declaration: &str) -> Vec { let mut values = Vec::new(); while let Some(value) = pending.pop() { match value { + crate::ir::Expr::Unary { + op: crate::ir::UnaryOp::ToTwoState, + expr, + } => pending.push(expr), crate::ir::Expr::Concat(parts) => pending.extend(parts.iter().rev()), crate::ir::Expr::Resize { expr, .. } => pending.push(expr), crate::ir::Expr::Literal(text) => { diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/typed_patterns.rs b/crates/celox-sv-analyzer/src/source_tree/tests/typed_patterns.rs index 4321c4e455f..a490a1d798d 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/typed_patterns.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/typed_patterns.rs @@ -18,6 +18,10 @@ fn widths(root: &Expr) -> Vec { let mut widths = Vec::new(); while let Some(value) = pending.pop() { match value { + Expr::Unary { + op: crate::ast::UnaryOp::ToTwoState, + expr, + } => pending.push(expr), Expr::Concat(parts) => pending.extend(parts.iter().rev()), Expr::Call { args, .. } => pending.extend(args.iter().rev().flatten()), Expr::Resize { expr, width, .. } => { diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 31e2396f386..3644c826083 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -750,3 +750,499 @@ (assert_eq y 0x12) (modify (set sel 1)) (assert_eq y 0xa5)) + +; IEEE 1800-2023 10.8 and 10.9: the input port supplies the assignment +; context, including dimensions after parameter specialization. +(case port_patterns_use_specialized_formal_shapes + (source "port_pattern_shapes.sv" #" + module Child #(parameter W=4, N=2)( + input logic [W-1:0] cfg[2:N+1], output wire [W*N-1:0] y); + for (genvar k=2; k ` +//! 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) +} 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/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/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 e16d6ae2eb7..94e0088c208 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..3fa4f94c60c --- /dev/null +++ b/crates/celox/src/scheduler.rs @@ -0,0 +1,796 @@ +//! 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()); + } + } + + 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 { + 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 8eea263c394..750499f12ed 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")) 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() diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index e400c0a1882..51913fe38fb 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,69 @@ use super::*; sv_backends! { + fn port_pattern_constant_unpacked_defaults(sim) { + @case "hierarchy::port_pattern_constant_unpacked_defaults"; + } + + fn port_pattern_constant_literal_defaults(sim) { + @case "hierarchy::port_pattern_constant_literal_defaults"; + } + + fn port_pattern_constant_mixed_state_defaults(sim) { + @case "hierarchy::port_pattern_constant_mixed_state_defaults"; + } + + fn port_pattern_constant_aggregate_defaults(sim) { + @case "hierarchy::port_pattern_constant_aggregate_defaults"; + } + fn port_pattern_default_bounds_require_matching_types(sim) { + @case "hierarchy::port_pattern_default_bounds_require_matching_types"; + } + + fn port_pattern_review_packed_value_types(sim) { + @case "hierarchy::port_pattern_review_packed_value_types"; + } + fn port_pattern_review_conditional_structs(sim) { + @case "hierarchy::port_pattern_review_conditional_structs"; + } + fn port_pattern_review_subarray_items(sim) { + @case "hierarchy::port_pattern_review_subarray_items"; + } + + fn port_pattern_review_aggregate_defaults(sim) { + @case "hierarchy::port_pattern_review_aggregate_defaults"; + } + + fn port_pattern_review_mixed_state_structs(sim) { + @case "hierarchy::port_pattern_review_mixed_state_structs"; + } + fn port_pattern_review_member_key_collisions(sim) { + @case "hierarchy::port_pattern_review_member_key_collisions"; + } + fn port_pattern_review_packed_struct_arrays(sim) { + @case "hierarchy::port_pattern_review_packed_struct_arrays"; + } + fn port_pattern_review_interface_inputs(sim) { + @case "hierarchy::port_pattern_review_interface_inputs"; + } + + fn port_patterns_preserve_four_state_elements(sim) { + @case "hierarchy::port_patterns_preserve_four_state_elements"; + } + fn port_patterns_reject_incorrect_element_counts(sim) { + @case "hierarchy::port_patterns_reject_incorrect_element_counts"; + } + + fn port_patterns_use_specialized_formal_shapes(sim) { + @case "hierarchy::port_patterns_use_specialized_formal_shapes"; + } + fn port_patterns_keep_caller_values_and_generated_names(sim) { + @case "hierarchy::port_patterns_keep_caller_values_and_generated_names"; + } + fn port_patterns_bind_nested_structure_elements(sim) { + @case "hierarchy::port_patterns_bind_nested_structure_elements"; + } + fn named_array_parameters_forward_whole_values(sim) { @case "hierarchy::named_array_parameters_forward_whole_values"; } @@ -443,3 +506,111 @@ fn rejects_incompatible_named_array_parameter_overrides() { ); } } + +#[test] +fn rejects_incompatible_port_pattern_subarray_items() { + for declaration in [ + "logic [7:0] row", + "logic [7:0] row[3]", + "logic [3:0] row[2]", + "logic signed [7:0] row[2]", + "bit [7:0] row[2]", + "logic [7:0] row[1][2]", + ] { + let source = format!( + r#" + module Child(input logic [7:0] cfg[2][2], output wire [7:0] y); + assign y=cfg[0][0]; + endmodule + module Top(output wire [7:0] y); + {declaration}; + Child c(.cfg('{{row,row}}), .y(y)); + endmodule + "# + ); + let error = + match Simulator::from_sv_sources(vec![(&source, Path::new("subarray_item.sv"))], "Top") + .build_cranelift() + { + Err(error) => error, + Ok(_) => panic!("incompatible subarray item must be rejected: {declaration}"), + }; + let error = error.to_string(); + assert!( + error.contains("is not assignment compatible") + || (error.contains("scalar") + && error.contains("assignment pattern item for unpacked array")), + "{declaration}: {error}" + ); + } +} + +#[test] +fn rejects_array_values_in_scalar_port_pattern_elements() { + for pattern in ["'{row,row}", "'{default:row}"] { + let source = format!( + r#" + module Child(input logic [7:0] cfg[2], output wire [7:0] y); + assign y=cfg[0]; + endmodule + module Top(output wire [7:0] y); + logic [7:0] row[2]; + Child c(.cfg({pattern}), .y(y)); + endmodule + "# + ); + let error = match Simulator::from_sv_sources( + vec![(&source, Path::new("array_scalar_item.sv"))], + "Top", + ) + .build_cranelift() + { + Err(error) => error, + Ok(_) => panic!("array value must not be truncated to a scalar: {pattern}"), + }; + let error = error.to_string(); + assert!( + error.contains("assignment pattern item for scalar"), + "{pattern}: {error}" + ); + } +} + +#[test] +fn rejects_recursive_port_pattern_defaults_for_packed_unions() { + for connection in [ + "Child c(.cfg('{default:'x}));", + "Child c(.cfg(P::items_t'{default:'x}));", + "Cfg c(.cfg('{default:'x}));", + "WithParam #(.CFG('{default:'x})) c();", + ] { + let source = format!( + r#" + package P; + typedef union packed {{logic a; bit b;}} item_t; + typedef item_t items_t[2]; + endpackage + module Child(input P::item_t cfg[2]); endmodule + interface Cfg(input P::item_t cfg[2]); endinterface + module WithParam #(parameter P::item_t CFG[2]='{{'0,'0}})(); endmodule + module Top; + {connection} + endmodule + "# + ); + let error = match Simulator::from_sv_sources( + vec![(&source, Path::new("union_pattern_default.sv"))], + "Top", + ) + .four_state(true) + .build_cranelift() + { + Err(error) => error, + Ok(_) => panic!("unsupported union default must be rejected: {connection}"), + }; + assert!( + error.to_string().contains("packed union"), + "{connection}: {error}" + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/snapshots/systemverilog__suite__compiled_scheduler_coverage.snap b/crates/celox/tests/frontends/systemverilog/snapshots/systemverilog__suite__compiled_scheduler_coverage.snap new file mode 100644 index 00000000000..dd93ca920b4 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/snapshots/systemverilog__suite__compiled_scheduler_coverage.snap @@ -0,0 +1,170 @@ +--- +source: crates/celox/tests/frontends/systemverilog/suite.rs +expression: report +--- +real_extensions::scanned_values_feed_math_and_realtime: 0/1; the process makes host requests (1) +realtime::realtime_returns_real_in_timed_processes: 0/0 +realtime::realtime_keeps_the_full_tick_counter: 0/0 +real_math::constant_functions: 1/1 +aggregate_regressions::independent_clock_memory_writers: 0/0 +aggregate_regressions::independent_clock_byte_writers: 0/0 +aggregate_regressions::coincident_disjoint_byte_writers: 0/0 +aggregate_regressions::shared_memory_reads_pre_edge_values: 0/0 +floating_point::real_file_display_formats: 0/1; the process makes host requests (1) +binary_file_io::zero_count_preserves_memory: 0/1; the process makes host requests (1) +scan::sscanf_integral_fields_and_failure_counts: 0/1; the process makes host requests (1) +scan::sscanf_multiple_outputs_and_packed_input: 0/1; the process makes host requests (1) +scan::sscanf_radix_unknowns_and_unknown_input: 0/1; the design is four-state (1) +scan::sscanf_real_fields_width_and_suppression: 0/1; the process makes host requests (1) +distributions::annex_n_reference_values: 0/1; the process makes host requests (1) +distributions::replay_and_normal_parameters: 0/1; the process makes host requests (1) +string::assignment_and_display: 1/1 +string::comparisons: 1/1 +string::concatenation_and_replication: 1/1 +string::character_access: 1/1 +string::methods: 1/1 +string::casts_from_integral_values: 1/1 +string::strings_across_clock_edges: 2/2 +string::strings_survive_heap_collections: 3/3 +string::string_parameters_keep_their_text: 1/1 +class::objects_properties_and_methods: 1/1 +class::implicit_constructors_and_this: 1/1 +class::objects_referring_to_objects: 0/1; the process suspends other than for a delay (1) +class::extern_methods_and_tasks: 1/1 +class::objects_survive_heap_collections: 3/3 +class::string_methods_on_properties: 1/1 +class::derived_properties_hide_base_properties: 1/1 +class::inherited_properties_and_methods: 1/1 +class::static_properties_and_methods: 1/2; a declaration initializer (1) +class::constructors_chain_to_base: 1/1 +class::virtual_methods_dispatch_on_object_class: 1/1 +class::abstract_classes_and_pure_virtual_methods: 1/1 +class::methods_of_handle_array_elements: 1/1 +class::classes_implementing_interface_classes: 1/1 +random_plusargs::plusargs_absent_preserves_destination: 0/1; the process makes host requests (1) +random_plusargs::dist_uniform_reference_sequence: 1/1 +latch::timed_initial_drives_latch: 1/1 +latch::classic_star_declaration_startup: 1/1 +latch::classic_star_initial_startup: 1/1 +latch::classic_star_continuous_startup: 1/1 +latch::classic_star_hierarchy_declaration_startup: 1/1 +latch::same_activation_change_return: 1/1 +latch::hierarchy_same_activation_change_return: 1/1 +latch::star_select_sensitivity: 1/1 +latch::star_complete_declaration_startup: 1/1 +latch::task_call_sensitivity: 1/1 +latch::star_unpacked_select_sensitivity: 1/1 +file_core::flush_preserves_stdout_order_and_integral_return_types: 0/1; the process makes host requests (1) +file_io::stdout_preserves_format_and_call_order: 0/1; the design is four-state (1) +file_io::edge_procedures_execute_requests_in_statement_order: 1/3; an edge procedure (2) +system_functions::scope_randomize_obeys_control_flow_and_statement_order: 1/1 +timing::delays_resume_initial_blocks_at_later_times: 0/1; a delay is not a constant of at least one time unit (1) +timing::always_with_a_delay_generates_a_clock: 1/1 +timing::edge_waits_resume_before_the_registers_of_that_edge_update: 1/2; the process waits for events (1) +timing::any_change_waits_wake_on_every_value_change: 1/4; the process waits for events (3) +timing::wait_statements_block_until_their_condition_holds: 1/2; the process waits for events (1) +timing::level_sensitive_always_runs_as_a_process: 1/1 +timing::explicit_list_of_every_read_waits_for_a_change: 1/1 +timing::list_missing_a_read_does_not_wake_on_it: 1/2; the process waits for events (1) +timing::list_with_an_extra_signal_wakes_on_it: 1/2; the process waits for events (1) +timing::list_of_every_read_with_a_nonblocking_body_runs: 1/2; the process waits for events (1) +timing::processes_wake_each_other_at_the_same_time: 0/2; a delay is not a constant of at least one time unit (1); the process waits for events (1) +timing::tasks_with_timing_controls_run_in_processes: 1/2; the process waits for events (1) +timing::edge_waits_see_the_signals_the_script_drives: 0/1; the process waits for events (1) +timing::time_functions_report_the_time_in_the_caller_unit: 1/1 +timing::finish_in_an_always_process_ends_the_simulation: 1/1 +timing::waiting_processes_do_not_keep_an_idle_simulation_running: 1/2; the process waits for events (1) +timing::four_state_edges_count_transitions_through_unknown: 0/4; the design is four-state (4) +timing::unknown_delays_and_conditions_count_as_zero_and_false: 0/2; the design is four-state (2) +timing::direct_reads_settle_waiting_processes: 0/1; a delay is not a constant of at least one time unit (1) +timing::output_reads_settle_waiting_processes: 0/1; the process waits for events (1) +timing::run_until_drains_target_time_before_later_writes: 1/1 +timing::repeated_settles_do_not_advance_design_time: 1/1 +timing::run_to_finish_has_no_simulated_time_deadline: 1/1 +timing::blocking_ff_stores_are_visible_before_inactive_work: 1/2; a delay is not a constant of at least one time unit (1) +timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work: 0/2; the design has derived clocks (2) +timing::nonblocking_assignments_in_processes_update_in_the_nba_region: 1/3; a delay is not a constant of at least one time unit (1); the process waits for events (1) +timing::staged_nonblocking_updates_keep_their_order: 1/3; a delay is not a constant of at least one time unit (1); the process waits for events (1) +timing::narrow_nonblocking_updates_keep_the_other_bits: 0/1; the process has nonblocking assignments (1) +timing::four_state_nonblocking_updates_keep_unknown_bits: 0/1; the design is four-state (1) +timing::nonblocking_ff_stores_remain_pending_during_inactive_work: 1/2; a delay is not a constant of at least one time unit (1) +timing::mixed_ff_stores_keep_their_active_and_nba_values: 1/2; a delay is not a constant of at least one time unit (1) +timing::printed_finish_notice_is_design_output: 1/1 +timing::combinational_finish_ends_timed_execution: 0/1; the design observes combinational processes (1) +timing::inactive_time_directives_do_not_change_scheduler_units: 1/1 +timing::blocking_concatenation_publishes_one_event_update: 3/5; the process waits for events (2) +timing::finite_active_feedback_preserves_convergence: 1/3; the process waits for events (2) +timing::list_in_a_loop_through_always_comb_converges: 1/2; the process waits for events (1) +timing::list_outside_a_loop_keeps_its_value: 1/2; the process waits for events (1) +timing::pure_function_rhs_preserves_distinct_write_times: 2/3; the process waits for events (1) +timing::conditional_writes_preserve_distinct_activation_times: 2/3; the process waits for events (1) +timing::case_writes_preserve_distinct_activation_times: 2/3; the process waits for events (1) +timing::constant_repeat_writes_preserve_distinct_activation_times: 1/3; the process suspends other than for a delay (1); the process waits for events (1) +timing::separate_comb_assignments_preserve_selected_dependencies: 1/2; the process waits for events (1) +timing::constant_for_writes_preserve_distinct_activation_times: 2/3; the process waits for events (1) +timing::untimed_tasks_preserve_distinct_activation_times: 2/3; the process waits for events (1) +timing::untimed_task_copyback_preserves_distinct_activation_times: 2/3; the process waits for events (1) +timing::statically_satisfied_waits_preserve_distinct_activation_times: 1/3; the process waits for events (2) +timing::nba_woken_waiters_sample_before_continuations: 0/3; RTL logic drives an event signal (3) +timing::negative_repeat_counts_do_not_run_the_body: 1/1 +timing::blocking_ff_woken_waiters_sample_before_continuations: 0/3; RTL logic drives an event signal (3) +timing::direct_blocking_ff_woken_waiters_sample_before_continuations: 1/3; the process waits for events (2) +timing::constant_variable_initializers_do_not_invent_clock_edges: 1/1 +timing::repeated_active_edges_share_one_nba_batch: 0/1; the design counts event occurrences (1) +timing::false_wait_preserves_separate_hierarchical_write_times: 1/3; the process waits for events (2) +timing::always_timed_task_without_inline_timing_executes: 0/1; the process suspends other than for a delay (1) +timing::constant_comb_if_discards_unreachable_pulse_branch: 0/1; the process waits for events (1) +timing::constant_child_ff_case_discards_unreachable_pulse_arm: 0/1; RTL logic drives an event signal (1) +timing::constant_child_loop_exit_keeps_one_write: 0/1; RTL logic drives an event signal (1) +timing::constant_child_case_exit_keeps_one_write: 0/1; RTL logic drives an event signal (1) +timing::four_state_child_if_keeps_one_write: 0/1; RTL logic drives an event signal (1) +timing::selected_child_dependency_ignores_unreachable_reads: 1/2; the process waits for events (1) +timing::selected_child_loop_exit_ignores_unreachable_suffix: 0/1; RTL logic drives an event signal (1) +timing::finite_process_loop_preserves_continuation_values: 0/1; the process suspends other than for a delay (1) +timing::zero_trip_child_dependencies_ignore_body_and_step: 1/2; the process waits for events (1) +timing::cross_file_package_initializers_keep_static_clock_baseline: 1/1 +timing::edge_waits_wake_on_rising_and_falling_edges: 1/2; the process waits for events (1) +timing::min_typ_max_delays_wait_the_typical_value: 1/1 +timing::long_process_loops_finish_within_one_time_slot: 0/1; the process suspends other than for a delay (1) +timing::initial_blocks_run_at_time_zero: 1/1 +timing::host_edges_after_time_zero_clock_flip_flops: 0/0 +timing::time_calls_in_child_port_actuals: 0/0 +timing::time_calls_in_child_port_subroutines: 0/0 +timing::timed_task_automatic_calls_keep_separate_storage: 0/2; a delay is not a constant of at least one time unit (2) +timing::timed_task_nested_copyback_wait_and_return: 2/3; the process waits for events (1) +timing::timed_task_static_formals_remain_shared: 0/2; a delay is not a constant of at least one time unit (2) +timing::timed_task_in_edge_always_rearms_after_return: 1/2; the process waits for events (1) +timing::timed_task_four_state_storage_survives_suspension: 0/1; the design is four-state (1) +timing::timed_task_automatic_scalar_calls_keep_separate_storage: 0/2; a delay is not a constant of at least one time unit (2) +timing::time_literal_delays_accept_all_units: 0/1; a delay is not a constant of at least one time unit (1) +timing::real_delays_round_at_the_scope_precision: 6/12; a declaration initializer (1); a delay is not a constant of at least one time unit (5) +timing::negative_real_delays_wait_their_twos_complement: 1/3; a declaration initializer (1); a delay is not a constant of at least one time unit (1) +timing::expression_events_see_pulses_within_a_time_slot: 0/3; a delay is not a constant of at least one time unit (1); the process waits for events (2) +timing::real_expression_events_see_fractional_changes: 1/2; the process waits for events (1) +timing::bit_select_edges_follow_the_selected_bit: 1/3; the process waits for events (2) +timing::part_select_events_see_pulses_of_the_selected_bits: 0/2; a delay is not a constant of at least one time unit (1); the process waits for events (1) +timing::variable_index_events_follow_the_index: 1/2; the process waits for events (1) +timing::pure_function_events_change_with_the_result: 1/2; the process waits for events (1) +timing::event_expressions_read_automatic_task_locals: 1/2; the process waits for events (1) +timing::event_controls_sample_the_expression_when_they_begin: 1/2; the process waits for events (1) +timing::implicit_event_controls_in_processes_wait_on_their_reads: 1/3; the process waits for events (2) +timing::zero_delay_process_ends_a_pulse_after_its_edge_triggers: 0/1; a delay is not a constant of at least one time unit (1) +timing::edge_waits_count_generated_clock_edges_in_any_declaration_order: 1/4; the process waits for events (3) +timing::delay_process_nonblocking_updates_reach_later_edges: 1/2; the process has nonblocking assignments (1) +timing::variable_delay_clock_changes_its_period: 1/2; a delay is not a constant of at least one time unit (1) +timing::asynchronous_reset_driven_by_a_delay_process: 2/2 +timing::generated_clocks_with_a_common_edge_sample_each_other: 2/2 +timing::script_writes_between_runs_reach_generated_clock_domains: 1/1 +timing::edge_waits_on_script_inputs_next_to_a_generated_clock: 1/2; the process waits for events (1) +timing::finish_from_a_delay_process_between_clock_edges: 2/2 +timing::static_function_storage_is_shared_between_processes: 2/2 +timing::static_function_readonly_initializer_calls_execute_once: 1/2; a declaration initializer (1) +timing::intermediate_combinational_writes_wake_waiters: 0/3; the design counts event occurrences (3) +timing::intermediate_edge_process_writes_wake_waiters: 0/6; the design counts event occurrences (6) +timing::staged_nonblocking_writes_wake_waiters: 0/3; the design counts event occurrences (3) +timing::child_port_pulses_reach_waiters_settled: 1/2; the process waits for events (1) +timing::intermediate_combinational_writes_keep_other_drivers: 0/3; the design counts event occurrences (3) +timing::parallel_flip_flop_parts_keep_pulses: 0/3; the design counts event occurrences (3) +timing::staged_nonblocking_writes_follow_later_blocking_writes: 0/2; the design counts event occurrences (2) +timing::intermediate_combinational_writes_replace_split_definitions: 0/2; the design counts event occurrences (2) +timing::intermediate_combinational_writes_reach_concatenated_ports: 0/3; the design counts event occurrences (3) diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 79c4a1193ab..1375b144d00 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,60 @@ pub fn run_case(name: &'static str, backend: &'static str) { .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); }); } + +/// 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. +/// A kernel that stops qualifying changes this snapshot. +#[test] +fn compiled_scheduler_coverage() { + use std::fmt::Write; + let report = std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(64 * 1024 * 1024) + .spawn_scoped(scope, || { + let mut report = String::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(); + 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 + }) + .unwrap() + .join() + .unwrap() + }); + insta::assert_snapshot!(report); +}