diff --git a/crates/celox-design/src/edges.rs b/crates/celox-design/src/edges.rs index fa3209c1f78..510b012f28d 100644 --- a/crates/celox-design/src/edges.rs +++ b/crates/celox-design/src/edges.rs @@ -14,26 +14,58 @@ pub const fn polarity(kind: DomainKind) -> Option { } } -/// Whether a level change from `was` to `is` that the scheduler applies to -/// an event signal, or that a process drives, is an active edge of a domain -/// of `kind`. A domain of unknown kind reacts to a rising edge. +/// The bit of an edge level that marks an unknown (x or z) value; the value +/// bit then tells x (1) from z (0), as in the state image. An edge level is +/// 0, 1, x (`LEVEL_UNKNOWN | 1`) or z (`LEVEL_UNKNOWN`). +pub const LEVEL_UNKNOWN: u8 = 2; + +/// Whether a change between the edge levels `was` and `is` is a rising +/// (`rising`) or a falling edge (IEEE 1800-2023 9.4.2, Table 9-2): a posedge +/// leaves 0 or reaches 1, a negedge leaves 1 or reaches 0, and a change +/// between x and z is neither. With `FOUR_STATE` false the levels are 0 or +/// 1 and this is a rise or a fall. +#[inline] +pub const fn level_edge(rising: bool, was: u8, is: u8) -> bool { + let between_unknowns = FOUR_STATE && was & is & LEVEL_UNKNOWN != 0; + let (from, to) = if rising { (0, 1) } else { (1, 0) }; + was != to && is != from && !between_unknowns +} + +/// Whether a change from edge level `was` to `is` that the scheduler +/// applies to an event signal, or that a process drives, is an active edge +/// of a domain of `kind`. A domain of unknown kind reacts to a rising edge. /// /// This differs from [`settled_edge`] for domains of unknown kind; the two /// rules stay separate. -pub const fn scheduled_edge(kind: Option, was: bool, is: bool) -> bool { +#[inline] +pub const fn scheduled_edge( + kind: Option, + was: u8, + is: u8, +) -> bool { match kind { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => !was && is, - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => was && !is, - _ => !was && is, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + level_edge::(false, was, is) + } + _ => level_edge::(true, was, is), } } -/// Whether a settled level change from `was` to `is` is an active edge of a -/// domain of `kind`. A domain of unknown kind reacts to any change. -pub const fn settled_edge(kind: Option, was: bool, is: bool) -> bool { +/// Whether a settled change from edge level `was` to `is` is an active edge +/// of a domain of `kind`. A domain of unknown kind reacts to any change. +#[inline] +pub const fn settled_edge( + kind: Option, + was: u8, + is: u8, +) -> bool { match kind { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => !was && is, - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => was && !is, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + level_edge::(true, was, is) + } + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + level_edge::(false, was, is) + } _ => was != is, } } @@ -54,10 +86,32 @@ mod tests { #[test] fn domains_of_unknown_kind_differ_between_the_rules() { for kind in [None, Some(DomainKind::Other)] { - assert!(scheduled_edge(kind, false, true)); - assert!(!scheduled_edge(kind, true, false)); - assert!(settled_edge(kind, false, true)); - assert!(settled_edge(kind, true, false)); + assert!(scheduled_edge::(kind, 0, 1)); + assert!(!scheduled_edge::(kind, 1, 0)); + assert!(settled_edge::(kind, 0, 1)); + assert!(settled_edge::(kind, 1, 0)); + } + } + + /// IEEE 1800-2023 Table 9-2, rows `from` and columns `to` in the order + /// 0, 1, x, z: `P` posedge, `N` negedge, `-` no edge. + #[test] + fn four_state_levels_follow_table_9_2() { + const LEVELS: [u8; 4] = [0, 1, LEVEL_UNKNOWN | 1, LEVEL_UNKNOWN]; + const TABLE: [&str; 4] = ["-PPP", "N-NN", "NP--", "NP--"]; + for (from, row) in LEVELS.iter().zip(TABLE) { + for (to, cell) in LEVELS.iter().zip(row.chars()) { + for (kind, mark) in [ + (DomainKind::ClockPosedge, 'P'), + (DomainKind::ResetAsyncHigh, 'P'), + (DomainKind::ClockNegedge, 'N'), + (DomainKind::ResetAsyncLow, 'N'), + ] { + let edge = cell == mark; + assert_eq!(settled_edge::(Some(kind), *from, *to), edge); + assert_eq!(scheduled_edge::(Some(kind), *from, *to), edge); + } + } } } @@ -70,10 +124,16 @@ mod tests { DomainKind::ResetAsyncLow, ] { let rising = polarity(kind) == Some(true); - for (was, is) in [(false, true), (true, false), (false, false), (true, true)] { - let edge = if rising { !was && is } else { was && !is }; - assert_eq!(scheduled_edge(Some(kind), was, is), edge); - assert_eq!(settled_edge(Some(kind), was, is), edge); + for (was, is) in [(0, 1), (1, 0), (0, 0), (1, 1)] { + let edge = if rising { + was == 0 && is == 1 + } else { + was == 1 && is == 0 + }; + assert_eq!(scheduled_edge::(Some(kind), was, is), edge); + assert_eq!(settled_edge::(Some(kind), was, is), edge); + assert_eq!(scheduled_edge::(Some(kind), was, is), edge); + assert_eq!(settled_edge::(Some(kind), was, is), edge); } assert_eq!(active_level(Some(kind)), u8::from(rising)); } diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index 902b8ccaf08..19b35c1d783 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -30,14 +30,14 @@ use celox_design::{ DomainKind, GateOp, - edges::{active_level, settled_edge}, + edges::{LEVEL_UNKNOWN, active_level, settled_edge}, schedule::ScheduleModel, }; use crate::{ AbsoluteAddr, SignalRef, SimulatorErrorCode, backend::{EventHandle, SimBackend}, - simulation::{HostBoundary, UnitExecutor, event_level}, + simulation::{HostBoundary, UnitExecutor, edge_level}, timing::Halt, }; @@ -279,6 +279,9 @@ pub struct DerivedTickPlan { /// Every gate has a program over two-state values, so gates are judged /// without settling the design. fast: bool, + /// The design keeps unknown bits: levels are read with their masks and + /// edges follow the four-state rows of IEEE 1800-2023 Table 9-2. + four_state: bool, /// The gated domains read and write no state the ticked domain writes, /// nor one another's, so they may run before it, one at a time, with the /// result of evaluating them together. @@ -296,10 +299,11 @@ pub struct DerivedTickScratch { ready: Vec, } -/// The entry's level at the start of the current phase. -const WAS: u8 = 1; +/// The entry's edge level (see [`edge_level`]) at the start of the +/// current phase. +const WAS: u8 = 1 | LEVEL_UNKNOWN; /// The entry's domain already ran in the current phase. -const FIRED: u8 = 2; +const FIRED: u8 = 4; impl DerivedTickScratch { #[inline] @@ -391,6 +395,7 @@ pub fn build_derived_tick_plans( domains, levers, fast, + four_state: !two_state, independent, })); } @@ -419,8 +424,10 @@ impl DerivedTickPlan { let mut domains: Vec> = Vec::new(); let mut levers: Vec<(SignalRef, u8)> = Vec::new(); let mut fast = true; + let mut four_state = false; for plan in plans { fast &= plan.fast; + four_state |= plan.four_state; for domain in &plan.gated { let id = domain.derived.domain.eval_apply.id(); if ticked(&domain.derived.domain) @@ -461,6 +468,7 @@ impl DerivedTickPlan { domains: domains.into(), levers: levers.into(), fast, + four_state, independent: false, } } @@ -513,6 +521,9 @@ impl DerivedTickPlan { /// `run.fire_sources`, every gated clock that sees its active edge in /// `run.transitions`, then the cascade rounds. Returns whether /// combinational logic is settled afterwards; it is not when nothing ran. + /// + /// The levels of [`EdgeRun::transitions`] are edge levels (see + /// [`celox_design::edges`]): a lever may leave x or z. pub fn run( &self, executor: &mut X, @@ -520,6 +531,25 @@ impl DerivedTickPlan { settle: bool, run: EdgeRun<'_>, ) -> Result + where + X: TickExecutor, + X::Backend: SimBackend, + { + if self.four_state { + self.run_in::(executor, scratch, settle, run) + } else { + self.run_in::(executor, scratch, settle, run) + } + } + + /// [`Self::run`] with levels read in the design's state mode. + fn run_in( + &self, + executor: &mut X, + scratch: &mut DerivedTickScratch, + settle: bool, + run: EdgeRun<'_>, + ) -> Result where X: TickExecutor, X::Backend: SimBackend, @@ -527,7 +557,7 @@ impl DerivedTickPlan { scratch.prepare(self.domains.len() + self.gated.len(), self.levers.len()); // The baseline is the state settled after the previous operation, // as the timed scheduler keeps it between steps. - self.sample_domains(executor.backend(), scratch); + self.sample_domains::(executor.backend(), scratch); let sources: &[EventDomain] = if run.fire_sources { &self.sources } else { &[] }; if self.gated.is_empty() { if sources.is_empty() { @@ -535,19 +565,25 @@ impl DerivedTickPlan { } fire(executor, settle, sources.iter())?; executor.eval_comb()?; - self.rounds(executor, scratch, run.transitions)?; + self.rounds::(executor, scratch, run.transitions)?; return Ok(true); } if self.fast { - self.run_gated_fast(executor, scratch, settle, sources, run.transitions)?; + self.run_gated_fast::( + executor, + scratch, + settle, + sources, + run.transitions, + )?; } else { - self.run_gated_settled(executor, scratch, settle, sources, &run)?; + self.run_gated_settled::(executor, scratch, settle, sources, &run)?; } Ok(true) } /// Gates judged by their programs: no settle beyond the ticked domains'. - fn run_gated_fast( + fn run_gated_fast( &self, executor: &mut X, scratch: &mut DerivedTickScratch, @@ -565,9 +601,9 @@ impl DerivedTickPlan { for (index, domain) in self.gated.iter().enumerate() { let (from, to) = transitions[domain.lever]; let backend = executor.backend(); - let before = self.gate_level(backend, domain, from); - let after = self.gate_level(backend, domain, to); - let fired = settled_edge(domain.derived.kind, before, after); + let before = self.gate_level::(backend, domain, from); + let after = self.gate_level::(backend, domain, to); + let fired = settled_edge::(domain.derived.kind, before, after); if fired { scratch.ready.push(index); } @@ -577,12 +613,12 @@ impl DerivedTickPlan { executor.eval_comb()?; // The commit may move a gate, as the nonblocking updates after the // edge do; that is a further edge of the gated clock. - self.rounds(executor, scratch, transitions) + self.rounds::(executor, scratch, transitions) } /// Gates without programs: settle the design with the levers at each /// level, as the timed scheduler does at the edge. - fn run_gated_settled( + fn run_gated_settled( &self, executor: &mut X, scratch: &mut DerivedTickScratch, @@ -604,8 +640,17 @@ impl DerivedTickPlan { scratch.flags[saved + 2 * index] = u8::try_from(&value).unwrap_or(0); scratch.flags[saved + 2 * index + 1] = u8::try_from(&mask).unwrap_or(0); } - if event_level(executor.backend(), signal) != from { - executor.backend_mut().set(signal, from); + if edge_level::(executor.backend(), signal) != from { + if FOUR_STATE && from & LEVEL_UNKNOWN != 0 { + // The lever leaves x or z. + executor.backend_mut().set_four_state( + signal, + num_bigint::BigUint::from(from & 1), + num_bigint::BigUint::from(1u8), + ); + } else { + executor.backend_mut().set(signal, from); + } moved = true; } } @@ -613,7 +658,7 @@ impl DerivedTickPlan { executor.eval_comb()?; } for (index, domain) in self.gated.iter().enumerate() { - let level = event_level(executor.backend(), domain.derived.signal) != 0; + let level = edge_level::(executor.backend(), domain.derived.signal); scratch.flags[base + index] = flags(level, false); } for (index, &(signal, _)) in self.levers.iter().enumerate() { @@ -622,9 +667,9 @@ impl DerivedTickPlan { executor.eval_comb()?; scratch.ready.clear(); for (index, domain) in self.gated.iter().enumerate() { - let before = scratch.flags[base + index] & WAS != 0; - let after = event_level(executor.backend(), domain.derived.signal) != 0; - let fired = settled_edge(domain.derived.kind, before, after); + let before = scratch.flags[base + index] & WAS; + let after = edge_level::(executor.backend(), domain.derived.signal); + let fired = settled_edge::(domain.derived.kind, before, after); if fired { scratch.ready.push(index); } @@ -632,7 +677,7 @@ impl DerivedTickPlan { } self.fire_with_gated(executor, false, sources, &scratch.ready)?; executor.eval_comb()?; - self.rounds(executor, scratch, run.transitions)?; + self.rounds::(executor, scratch, run.transitions)?; if run.persist { return Ok(()); } @@ -684,24 +729,34 @@ impl DerivedTickPlan { /// A gated clock's level with its lever at `level`, from its program in /// the fast path and from the settled design otherwise. #[inline] - fn gate_level(&self, backend: &B, domain: &GatedDomain, level: u8) -> bool { + fn gate_level( + &self, + backend: &B, + domain: &GatedDomain, + level: u8, + ) -> u8 { match &domain.gate { - Some(gate) if self.fast => gate.level(backend, level), - _ => event_level(backend, domain.derived.signal) != 0, + Some(gate) if self.fast => u8::from(gate.level(backend, level)), + _ => edge_level::(backend, domain.derived.signal), } } #[inline] - fn sample_domains(&self, backend: &B, scratch: &mut DerivedTickScratch) { + fn sample_domains( + &self, + backend: &B, + scratch: &mut DerivedTickScratch, + ) { for (index, domain) in self.domains.iter().enumerate() { - scratch.flags[index] = flags(event_level(backend, domain.signal) != 0, false); + let level = edge_level::(backend, domain.signal); + scratch.flags[index] = flags(level, false); } } /// Cascade rounds over the state-derived and gated domains: each round /// runs together every domain whose clock moved to its active edge since /// the phase began, then settles, until no further edge appears. - fn rounds( + fn rounds( &self, executor: &mut X, scratch: &mut DerivedTickScratch, @@ -719,8 +774,8 @@ impl DerivedTickPlan { if state & FIRED != 0 { continue; } - let is = event_level(executor.backend(), domain.signal) != 0; - if settled_edge(domain.kind, state & WAS != 0, is) { + let is = edge_level::(executor.backend(), domain.signal); + if settled_edge::(domain.kind, state & WAS, is) { scratch.ready.push(index); } } @@ -729,8 +784,12 @@ impl DerivedTickPlan { if state & FIRED != 0 { continue; } - let is = self.gate_level(executor.backend(), domain, transitions[domain.lever].1); - if settled_edge(domain.derived.kind, state & WAS != 0, is) { + let is = self.gate_level::( + executor.backend(), + domain, + transitions[domain.lever].1, + ); + if settled_edge::(domain.derived.kind, state & WAS, is) { scratch.ready.push(base + index); } } @@ -759,8 +818,8 @@ impl DerivedTickPlan { /// How an edge moves the signals that gate a plan's derived clocks. #[derive(Clone, Copy, Debug)] pub struct EdgeRun<'a> { - /// Per lever ([`DerivedTickPlan::lever_signals`]), its level before and - /// after the edge. + /// Per lever ([`DerivedTickPlan::lever_signals`]), its edge level (see + /// [`celox_design::edges`]) before and after the edge. pub transitions: &'a [(u8, u8)], /// The levers stay at their new level; otherwise they are left as they /// were before the edge. @@ -770,12 +829,15 @@ pub struct EdgeRun<'a> { } #[inline] -fn flags(level: bool, fired: bool) -> u8 { - (u8::from(level) * WAS) | (u8::from(fired) * FIRED) +fn flags(level: u8, fired: bool) -> u8 { + level | (u8::from(fired) * FIRED) } /// Evaluate and commit `domains` as one coincident edge: each of them /// samples the same state, then all of them commit. +// Instantiated for each state mode, it would otherwise stay out of line, +// which costs two-state ticks the call. +#[inline(always)] fn fire<'a, X, E>( executor: &mut X, settle: bool, diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index 721da594786..3d404e53dfe 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -13,7 +13,7 @@ //! so the inactive edge of a clock that only clocks flip-flops costs no //! settle on the next active edge. -use celox_design::{DomainKind, EventTopology}; +use celox_design::{DomainKind, EventTopology, edges::LEVEL_UNKNOWN}; use crate::{ AbsoluteAddr, SignalRef, @@ -21,7 +21,7 @@ use crate::{ derived_tick::{ DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, EdgeRun, EventDomain, TickExecutor, }, - simulation::event_level, + simulation::{edge_level, event_level}, timing::Halt, }; @@ -133,16 +133,19 @@ fn moved_only(comb_read: bool) -> EdgeOutcome { } } -/// The level of `signal`, or `None` while it is unknown. -fn level(backend: &B, signal: SignalRef) -> Option { +/// The edge level of `signal` (see [`celox_design::edges`]): 0, 1, or, in a +/// four-state design, x or z. +fn level(backend: &B, signal: SignalRef) -> u8 { if signal.is_4state && backend.layout().four_state { - let (value, mask) = backend.get_four_state(signal); - if mask.bit(0) { - return None; - } - return Some(value.bit(0)); + edge_level::(backend, signal) + } else { + u8::from(event_level(backend, signal) != 0) } - Some(event_level(backend, signal) != 0) +} + +/// The known value of an edge level, or `None` for x and z. +fn known(level: u8) -> Option { + (level & LEVEL_UNKNOWN == 0).then_some(level != 0) } /// Writes an event signal's new level: the host's own write of the signal, @@ -170,11 +173,22 @@ pub fn move_signal( backend: &mut B, info: &EventEdge, edge: Edge, - mut write: impl SignalWrite, + write: impl SignalWrite, ) -> Option> { + move_level(backend, info, edge, write).map(known) +} + +/// [`move_signal`], returning the edge level the signal had: x or z leave +/// for 1 or 0 like 0 or 1 do (IEEE 1800-2023 Table 9-2). +fn move_level( + backend: &mut B, + info: &EventEdge, + edge: Edge, + mut write: impl SignalWrite, +) -> Option { let old = level(backend, info.signal); let new = edge.level(); - if old == Some(new != 0) { + if old == new { return None; } write.write(backend, info.signal, new); @@ -201,14 +215,15 @@ where X::Backend: SimBackend, E: EventHandle, { - let Some(old) = move_signal(executor.backend_mut(), &info, edge, write) else { + let Some(from) = move_level(executor.backend_mut(), &info, edge, write) else { return Ok(EdgeOutcome::Unchanged); }; let new = edge.level(); - let fires = info.fires(old, edge); + let fires = info.fires(known(from), edge); let settle = dirty || info.comb_read; if let Some(plan) = plan { - let from = old.map_or(new ^ 1, u8::from); + // A gated clock is judged from the lever's real level before the + // edge, x and z included. let transition = [(from, new)]; let transitions: &[(u8, u8)] = if plan.lever_signals().next().is_some() { &transition @@ -283,14 +298,14 @@ where let info = &edges[id]; let old = level(executor.backend(), info.signal); let new = edge.level(); - if old == Some(new != 0) || transitions.iter().any(|(signal, _)| *signal == info.signal) { + if old == new || transitions.iter().any(|(signal, _)| *signal == info.signal) { continue; } any_moved = true; write.write(executor.backend_mut(), info.signal, new); - transitions.push((info.signal, (old.map_or(new ^ 1, u8::from), new))); + transitions.push((info.signal, (old, new))); comb_read |= info.comb_read; - if info.fires(old, edge) { + if info.fires(known(old), edge) { let address = executor.backend().id_to_addr_slice()[id]; sources.push(EventDomain { eval_apply: event, diff --git a/crates/celox-runtime/src/simulation/batch.rs b/crates/celox-runtime/src/simulation/batch.rs index 4fe08593259..0972bd60d3a 100644 --- a/crates/celox-runtime/src/simulation/batch.rs +++ b/crates/celox-runtime/src/simulation/batch.rs @@ -2,7 +2,7 @@ //! stable-edge helpers it calls, kept in one module. use bit_set::BitSet; -use celox_design::edges::{scheduled_edge, settled_edge}; +use celox_design::edges::{LEVEL_UNKNOWN, settled_edge}; use super::SimulationState; use super::host::SimulationExecutor; @@ -20,8 +20,53 @@ pub(crate) fn event_level(backend: &B, signal: SignalRef) -> u8 { } } +/// The edge level (see [`celox_design::edges`]) of an event signal: 0, 1, +/// or, in a four-state design, [`LEVEL_UNKNOWN`] with the value bit for x +/// and z. `FOUR_STATE` is the design's state mode; a two-state design reads +/// only the value bits, as [`event_level`] does. +#[inline] +pub(crate) fn edge_level( + backend: &B, + signal: SignalRef, +) -> u8 { + let value = u8::from(event_level(backend, signal) != 0); + if FOUR_STATE && signal.is_4state && event_unknown(backend, signal) { + value | LEVEL_UNKNOWN + } else { + value + } +} + +/// Whether a four-state event signal has unknown bits. Its mask plane +/// follows its value bytes in the state image. +#[inline] +fn event_unknown(backend: &B, signal: SignalRef) -> bool { + let mask = SignalRef { + offset: signal.offset + celox_state_layout::get_byte_size(signal.width), + width: signal.width, + is_4state: false, + array_layout: None, + }; + event_level(backend, mask) != 0 +} + impl SimulationState { + #[inline(always)] pub(super) fn stable_edge_triggered(&self, backend: &B, id: usize) -> bool { + if self.four_state { + self.stable_edge_triggered_four_state(backend, id) + } else { + self.stable_edge_triggered_in::(backend, id) + } + } + + #[inline(never)] + fn stable_edge_triggered_four_state(&self, backend: &B, id: usize) -> bool { + self.stable_edge_triggered_in::(backend, id) + } + + #[inline(always)] + fn stable_edge_triggered_in(&self, backend: &B, id: usize) -> bool { let Some((signal, _)) = self .model .topo_signals @@ -29,20 +74,28 @@ impl SimulationState { else { return true; }; - let was_nonzero = self.last_clock_values.contains(id); - let is_nonzero = event_level(backend, *signal) != 0; - settled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero) + let was = self.last_level_in::(id); + let is = edge_level::(backend, *signal); + settled_edge::(self.model.domain_kinds[id], was, is) } pub(super) fn replace_triggers_with_stable_edges(&self, backend: &mut B) { + if self.four_state { + self.replace_triggers_in::(backend); + } else { + self.replace_triggers_in::(backend); + } + } + + fn replace_triggers_in(&self, backend: &mut B) { backend.clear_triggered_bits(); for (signal, id) in &self.model.topo_signals { if *id == usize::MAX { continue; } - let was_nonzero = self.last_clock_values.contains(*id); - let is_nonzero = event_level(backend, *signal) != 0; - if settled_edge(self.model.domain_kinds[*id], was_nonzero, is_nonzero) { + let was = self.last_level_in::(*id); + let is = edge_level::(backend, *signal); + if settled_edge::(self.model.domain_kinds[*id], was, is) { backend.mark_triggered_bit(*id); } } @@ -80,14 +133,14 @@ impl SimulationState { self.model .signal_to_id .get(&event.signal) - .map(|&id| (id, event.next_val != 0)) + .map(|&id| (id, u8::from(event.next_val != 0))) }); // Scheduled signals that changed level and gate derived clocks. let mut gating_sources = Vec::new(); - for (id, is_nonzero) in scheduled { + for (id, is) in scheduled { track_stable_edges = true; - let was_nonzero = self.last_clock_values.contains(id); - if was_nonzero != is_nonzero + let was = self.last_level(id); + if was != is && self .model .combinational_derived @@ -96,8 +149,7 @@ impl SimulationState { { gating_sources.push(id); } - let triggered = scheduled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero); - if triggered { + if self.scheduled_edge(id, was, is) { scheduled_trigger_ids.insert(id); executor.backend_mut().mark_triggered_bit(id); } @@ -130,25 +182,23 @@ impl SimulationState { // NBA region do. let mut edge_approved: Option = None; for &source in &gating_sources { - for &id in self.model.combinational_derived[source].iter() { + for index in 0..self.model.combinational_derived[source].len() { + let id = self.model.combinational_derived[source][index]; if self.stable_edge_triggered(executor.backend(), id) { executor.backend_mut().mark_triggered_bit(id); edge_approved .get_or_insert_with(|| BitSet::with_capacity(num_events)) .insert(id); } - let Some((signal, _)) = self + let Some(&(signal, _)) = self .model .topo_signals .get(self.model.signal_index_by_id[id]) else { continue; }; - if event_level(executor.backend(), *signal) != 0 { - self.last_clock_values.insert(id); - } else { - self.last_clock_values.remove(id); - } + let level = self.level(executor.backend(), signal); + self.record_level(id, level); } } diff --git a/crates/celox-runtime/src/simulation/edges.rs b/crates/celox-runtime/src/simulation/edges.rs index 20ecd99b1a9..25d14024a09 100644 --- a/crates/celox-runtime/src/simulation/edges.rs +++ b/crates/celox-runtime/src/simulation/edges.rs @@ -1,38 +1,137 @@ //! Edges of event signals: marking the domains that scheduled values, //! process writes, publications and counters trigger. -use celox_design::edges::{scheduled_edge, settled_edge}; +use celox_design::edges::{LEVEL_UNKNOWN, scheduled_edge, settled_edge}; use super::round::Round; -use super::{SimulationState, event_level}; -use crate::{backend::SimBackend, timing::kind_index}; +use super::{SimulationState, edge_level}; +use crate::{SignalRef, backend::SimBackend, timing::kind_index}; impl SimulationState { /// Take the levels of the event signals as the baseline that edge /// detection compares against. + #[inline(always)] pub(super) fn resample_clock_values(&mut self, backend: &B) { - for (signal, id) in &self.model.topo_signals { - if *id == usize::MAX { - continue; - } - if event_level(backend, *signal) != 0 { - self.last_clock_values.insert(*id); - } else { - self.last_clock_values.remove(*id); - } - } + self.record_all_levels(backend); } /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { self.last_clock_values.make_empty(); - for (signal, id) in &self.model.topo_signals { - if *id == usize::MAX { - continue; + self.last_clock_unknown.make_empty(); + self.record_all_levels(backend); + } + + // The four-state paths of the level helpers stay out of line, so that a + // two-state design's callers keep the size and inlining they had before. + + /// The current edge level of an event signal (see [`edge_level`]). + #[inline] + pub(super) fn level(&self, backend: &B, signal: SignalRef) -> u8 { + if self.four_state { + self.level_four_state(backend, signal) + } else { + edge_level::(backend, signal) + } + } + + #[inline(never)] + fn level_four_state(&self, backend: &B, signal: SignalRef) -> u8 { + edge_level::(backend, signal) + } + + /// The edge level of event `id` when edge detection last sampled it. + #[inline] + pub(super) fn last_level_in(&self, id: usize) -> u8 { + let value = u8::from(self.last_clock_values.contains(id)); + if FOUR_STATE && self.last_clock_unknown.contains(id) { + value | LEVEL_UNKNOWN + } else { + value + } + } + + #[inline] + pub(super) fn last_level(&self, id: usize) -> u8 { + if self.four_state { + self.last_level_four_state(id) + } else { + self.last_level_in::(id) + } + } + + #[inline(never)] + fn last_level_four_state(&self, id: usize) -> u8 { + self.last_level_in::(id) + } + + /// Make `level` the baseline of event `id`'s next edge. + #[inline] + fn record_level_in(&mut self, id: usize, level: u8) { + if level & 1 != 0 { + self.last_clock_values.insert(id); + } else { + self.last_clock_values.remove(id); + } + if FOUR_STATE { + if level & LEVEL_UNKNOWN != 0 { + self.last_clock_unknown.insert(id); + } else { + self.last_clock_unknown.remove(id); } - if event_level(backend, *signal) != 0 { - self.last_clock_values.insert(*id); + } + } + + #[inline] + pub(super) fn record_level(&mut self, id: usize, level: u8) { + if self.four_state { + self.record_level_four_state(id, level); + } else { + self.record_level_in::(id, level); + } + } + + #[inline(never)] + fn record_level_four_state(&mut self, id: usize, level: u8) { + self.record_level_in::(id, level); + } + + /// Make every event's current level the baseline of its next edge. + #[inline(always)] + pub(super) fn record_all_levels(&mut self, backend: &B) { + if self.four_state { + self.record_levels_four_state(backend); + } else { + self.record_levels::(backend); + } + } + + #[inline(never)] + fn record_levels_four_state(&mut self, backend: &B) { + self.record_levels::(backend); + } + + #[inline(always)] + fn record_levels(&mut self, backend: &B) { + for index in 0..self.model.topo_signals.len() { + let (signal, id) = self.model.topo_signals[index]; + if id == usize::MAX { + continue; } + let level = edge_level::(backend, signal); + self.record_level_in::(id, level); + } + } + + /// Whether a scheduled or process-driven change of event `id` from level + /// `was` to `is` triggers its domain. + #[inline] + pub(super) fn scheduled_edge(&self, id: usize, was: u8, is: u8) -> bool { + let kind = self.model.domain_kinds[id]; + if self.four_state { + scheduled_edge::(kind, was, is) + } else { + scheduled_edge::(kind, was, is) } } @@ -60,14 +159,13 @@ impl SimulationState { &self, backend: &mut B, round: &mut Round, - values: &[(usize, bool)], + values: &[(usize, u8)], ) { - for &(id, is_nonzero) in values { + for &(id, is) in values { round.track_stable_edges = true; - // A signal written again compares with its preceding value. - let was_nonzero = - round.previous(id, is_nonzero, || self.last_clock_values.contains(id)); - if was_nonzero != is_nonzero + // A signal written again compares with its preceding level. + let was = round.previous(id, is, || self.last_level(id)); + if was != is && self .model .combinational_derived @@ -76,21 +174,21 @@ impl SimulationState { { round.gating_sources.push(id); } - let triggered = scheduled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero); - if triggered { + if self.scheduled_edge(id, was, is) { round.scheduled_trigger_ids.insert(id); backend.mark_triggered_bit(id); } } } + /// The edge level (see [`edge_level`]) of every event signal. pub(super) fn event_values(&self, backend: &B, values: &mut Vec) { values.clear(); values.extend( self.model .topo_signals .iter() - .map(|(signal, _)| event_level(backend, *signal)), + .map(|(signal, _)| self.level(backend, *signal)), ); } @@ -105,7 +203,7 @@ impl SimulationState { .zip(&round.after) { if *id != usize::MAX && old != new { - round.transitions.push((*id, new != 0)); + round.transitions.push((*id, new)); } } std::mem::swap(&mut round.before, &mut round.after); @@ -118,12 +216,16 @@ impl SimulationState { &self, backend: &mut B, round: &mut Round, - transitions: &[(usize, bool)], + transitions: &[(usize, u8)], ) { - for &(id, is_nonzero) in transitions { - let was_nonzero = - round.previous(id, is_nonzero, || self.last_clock_values.contains(id)); - let triggered = settled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero); + for &(id, is) in transitions { + let was = round.previous(id, is, || self.last_level(id)); + let kind = self.model.domain_kinds[id]; + let triggered = if self.four_state { + settled_edge::(kind, was, is) + } else { + settled_edge::(kind, was, is) + }; if triggered { round.occurrences.insert(id); round.scheduled_trigger_ids.insert(id); diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 1e9708c0f61..2c09657edd9 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -16,7 +16,7 @@ use std::{cmp::Reverse, collections::BinaryHeap}; use bit_set::BitSet; use celox_design::CounterKind; -pub(crate) use batch::event_level; +pub(crate) use batch::{edge_level, event_level}; pub use host::{HostBoundary, HostWatch, SimulationExecutor, UnitExecutor}; pub use nba::NbaUpdate; pub use persist::{ScheduleParts, SimulationSnapshot}; @@ -83,7 +83,15 @@ struct Suspended { /// Backend-independent state and execution rules for timed simulation. pub struct SimulationState { scheduler: Scheduler, + /// Events whose signal was high (value bit set) when edge detection last + /// sampled it. last_clock_values: BitSet, + /// Events whose signal was x or z when edge detection last sampled it. + /// Empty unless the design is four-state. + last_clock_unknown: BitSet, + /// The design keeps unknown bits, so edges follow the four-state rows + /// of IEEE 1800-2023 Table 9-2. + four_state: bool, /// The design's scheduling facts, which never change. model: ResolvedSchedule, process_wakeups: BinaryHeap, @@ -120,12 +128,6 @@ impl SimulationState { /// Every process of `model` starts at time zero, in list order. pub fn new(backend: &B, model: ResolvedSchedule) -> Self { - let mut last_clock_values = BitSet::with_capacity(backend.num_events()); - for (signal, id) in model.topo_signals.iter().copied() { - if id != usize::MAX && event_level(backend, signal) != 0 { - last_clock_values.insert(id); - } - } let process_state = ProcessState { domain_counters: model .counted @@ -136,9 +138,11 @@ impl SimulationState { .collect(), ..ProcessState::default() }; - Self { + let mut state = Self { scheduler: Scheduler::new(), - last_clock_values, + last_clock_values: BitSet::with_capacity(backend.num_events()), + last_clock_unknown: BitSet::new(), + four_state: backend.layout().four_state, process_wakeups: (0..model.processes.len()) .map(|process| Reverse((0, process))) .collect(), @@ -152,7 +156,9 @@ impl SimulationState { round_budget: SLOT_ROUND_BUDGET, return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, - } + }; + state.synchronize_event_values(backend); + state } /// Settle host writes at the current time, then advance to the next time @@ -263,9 +269,7 @@ impl SimulationState { } // Otherwise only an event signal's change needs the current time. for (signal, id) in &self.model.topo_signals { - if *id != usize::MAX - && (event_level(backend, *signal) != 0) != self.last_clock_values.contains(*id) - { + if *id != usize::MAX && self.level(backend, *signal) != self.last_level(*id) { self.host_pending = true; return; } diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index 3006c553a39..5a568466011 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -20,6 +20,7 @@ impl SimulationState { clocks: self.scheduler.clocks.clone(), event_queue: self.scheduler.event_queue.clone(), last_clock_values: self.last_clock_values.clone(), + last_clock_unknown: self.last_clock_unknown.clone(), process_wakeups: self.process_wakeups.clone(), process_state: self.process_state.clone(), host_pending: self.host_pending, @@ -54,6 +55,8 @@ impl SimulationState { self.scheduler.event_queue = event_queue; self.last_clock_values .clone_from(&snapshot.last_clock_values); + self.last_clock_unknown + .clone_from(&snapshot.last_clock_unknown); self.process_wakeups.clone_from(&snapshot.process_wakeups); self.process_state.clone_from(&snapshot.process_state); self.host_pending = snapshot.host_pending; @@ -76,7 +79,10 @@ pub struct ScheduleParts { /// the number of identical such events. pub periodic: Vec<(SimEvent, u64)>, /// Events whose signal was high when edge detection last sampled it. + /// An x counts as high. pub high_events: Vec, + /// Events whose signal was x or z when edge detection last sampled it. + pub unknown_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, /// Waiting and ready processes, queued nonblocking assignments and the @@ -115,6 +121,11 @@ impl SimulationState { periodic }, high_events: self.last_clock_values.iter().map(|id| events[id]).collect(), + unknown_events: self + .last_clock_unknown + .iter() + .map(|id| events[id]) + .collect(), process_wakeups: { let mut wakeups = self .process_wakeups @@ -162,6 +173,12 @@ impl SimulationState { for event in parts.high_events { self.last_clock_values.insert(event.id()); } + self.last_clock_unknown.make_empty(); + if self.four_state { + for event in parts.unknown_events { + self.last_clock_unknown.insert(event.id()); + } + } self.process_wakeups = parts .process_wakeups .into_iter() @@ -181,6 +198,7 @@ pub struct SimulationSnapshot { clocks: Vec>, event_queue: std::collections::BinaryHeap>, last_clock_values: BitSet, + last_clock_unknown: BitSet, process_wakeups: BinaryHeap, process_state: ProcessState, host_pending: bool, @@ -194,6 +212,7 @@ impl Clone for SimulationSnapshot { clocks: self.clocks.clone(), event_queue: self.event_queue.clone(), last_clock_values: self.last_clock_values.clone(), + last_clock_unknown: self.last_clock_unknown.clone(), process_wakeups: self.process_wakeups.clone(), process_state: self.process_state.clone(), host_pending: self.host_pending, diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index e30bb87f56e..6ffae56c3a8 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -6,7 +6,7 @@ use bit_set::BitSet; use super::host::SimulationExecutor; use super::nba::{restore_working_image, working_image}; -use super::{EventInfo, SimulationState, Suspended, event_level}; +use super::{EventInfo, SimulationState, Suspended}; use crate::{ SimulatorErrorCode, backend::SimBackend, @@ -31,10 +31,10 @@ pub(super) struct Round { /// Kernels ran in this round, so pending nonblocking flags may be set. pub(super) kernels_ran: bool, pub(super) nba_published: bool, - /// Event-signal values scheduled or written by processes, not yet - /// marked. - pub(super) transitions: Vec<(usize, bool)>, - /// Event-signal values before and after a process run. + /// Event-signal levels (see [`super::edge_level`]) scheduled or written + /// by processes, not yet marked. + pub(super) transitions: Vec<(usize, u8)>, + /// Event-signal levels before and after a process run. pub(super) before: Vec, pub(super) after: Vec, /// Event ids a pulse of several publications triggered; like counted @@ -53,7 +53,7 @@ pub(super) struct Round { /// since the baseline (`last_clock_values`) was last taken, valid where /// the stamp equals `generation`: a value written in one wave of the /// active region is the previous value of the next wave's write. - latest: Vec<(u32, bool)>, + latest: Vec<(u32, u8)>, generation: u32, } @@ -62,24 +62,19 @@ impl Round { /// baseline. fn begin_scan(&mut self, events: usize) { if self.latest.len() < events { - self.latest.resize(events, (0, false)); + self.latest.resize(events, (0, 0)); } self.generation = self.generation.wrapping_add(1); if self.generation == 0 { // Stamps of an earlier wrap must not match. - self.latest.fill((0, false)); + self.latest.fill((0, 0)); self.generation = 1; } } - /// The value event `id` had before this transition: its latest value in + /// The level event `id` had before this transition: its latest level in /// the scan, or `baseline`; records `value` as its latest. - pub(super) fn previous( - &mut self, - id: usize, - value: bool, - baseline: impl FnOnce() -> bool, - ) -> bool { + pub(super) fn previous(&mut self, id: usize, value: u8, baseline: impl FnOnce() -> u8) -> u8 { let (stamp, latest) = std::mem::replace(&mut self.latest[id], (self.generation, value)); if stamp == self.generation { latest @@ -159,23 +154,21 @@ impl SimulationState { /// edge) gives a further edge, as the update events of the NBA region do. fn judge_derived_edges(&mut self, backend: &mut B, round: &mut Round) { for source in std::mem::take(&mut round.gating_sources) { - for &id in self.model.combinational_derived[source].iter() { + for index in 0..self.model.combinational_derived[source].len() { + let id = self.model.combinational_derived[source][index]; if self.stable_edge_triggered(backend, id) { backend.mark_triggered_bit(id); round.edge_approved.insert(id); } - let Some((signal, _)) = self + let Some(&(signal, _)) = self .model .topo_signals .get(self.model.signal_index_by_id[id]) else { continue; }; - if event_level(backend, *signal) != 0 { - self.last_clock_values.insert(id); - } else { - self.last_clock_values.remove(id); - } + let level = self.level(backend, signal); + self.record_level(id, level); } } } @@ -396,7 +389,7 @@ impl SimulationState { self.model .signal_to_id .get(&event.signal) - .map(|&id| (id, event.next_val != 0)) + .map(|&id| (id, u8::from(event.next_val != 0))) })); // The check after the batch already saw every signal. diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index 0a7b177353f..a377679d3ba 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -19,6 +19,8 @@ //! event count u32, then per event: scheduled event //! periodic count u32, then per marker: scheduled event | count u64 //! high count u32, then per event: event str +//! (only with FLAG_UNKNOWN_EVENTS) unknown count u32, then per event: +//! event str //! processes (version 2): //! wakeup count u32, then per wakeup: process str | time u64 //! waiter count u32, then per waiter: @@ -47,6 +49,9 @@ const MAGIC: &[u8; 8] = b"CXSTATE\0"; const VERSION: u16 = 2; const FLAG_FOUR_STATE: u16 = 1 << 0; const FLAG_SCHEDULE: u16 = 1 << 1; +/// The schedule lists events whose signal was x or z. Set only when there are +/// any, so other files keep their earlier encoding. +const FLAG_UNKNOWN_EVENTS: u16 = 1 << 2; /// How a state object gets its value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -94,7 +99,11 @@ pub struct ScheduleRecord { /// the number of identical such events. pub periodic: Vec<(ScheduledEvent, u64)>, /// Event paths whose signal was high when edge detection last sampled it. + /// An x counts as high. pub high_events: Vec, + /// Event paths whose signal was x or z when edge detection last sampled + /// it. + pub unknown_events: Vec, /// Scheduling state of the design's processes. pub processes: ProcessRecord, } @@ -210,8 +219,11 @@ impl StateFile { if self.four_state { flags |= FLAG_FOUR_STATE; } - if self.schedule.is_some() { + if let Some(schedule) = &self.schedule { flags |= FLAG_SCHEDULE; + if !schedule.unknown_events.is_empty() { + flags |= FLAG_UNKNOWN_EVENTS; + } } put_u16(w, flags)?; put_len(w, self.objects.len())?; @@ -254,6 +266,12 @@ impl StateFile { for event in &schedule.high_events { put_str(w, event)?; } + if !schedule.unknown_events.is_empty() { + put_len(w, schedule.unknown_events.len())?; + for event in &schedule.unknown_events { + put_str(w, event)?; + } + } if let Some(processes) = processes { put_processes(w, processes)?; } @@ -322,6 +340,13 @@ impl StateFile { let high_events = (0..get_u32(r)?) .map(|_| get_str(r)) .collect::>()?; + let unknown_events = if flags & FLAG_UNKNOWN_EVENTS != 0 { + (0..get_u32(r)?) + .map(|_| get_str(r)) + .collect::>()? + } else { + Vec::new() + }; let processes = if version >= 2 { get_processes(r)? } else { @@ -333,6 +358,7 @@ impl StateFile { events, periodic, high_events, + unknown_events, processes, }) } else { @@ -682,6 +708,7 @@ mod tests { events: vec![event.clone()], periodic: vec![(event, 1)], high_events: vec!["clk".into()], + unknown_events: vec!["rst".into()], processes: ProcessRecord { wakeups: vec![("$process[0].status".into(), 20)], waiters: vec![WaiterRecord { diff --git a/crates/celox-test-suite/src/sv/cases/edges.vtest b/crates/celox-test-suite/src/sv/cases/edges.vtest new file mode 100644 index 00000000000..1d1bb80a3ac --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/edges.vtest @@ -0,0 +1,186 @@ +(group edges (category sequential)) + +; IEEE 1800-2023 9.4.2, Table 9-2 for clocks and resets the design drives +; itself. A posedge leaves 0 or reaches 1, a negedge leaves 1 or reaches 0, +; and a change between x and z is neither. Each design walks its clock or +; reset through all twelve changes between 0, 1, x and z (an Euler circuit), +; one change per tick. Rising and falling edges are sensed on two copies of +; the clock. + +(case register_clock_edges_follow_table_9_2 + (four_state) + (source "register_clock.sv" #" +module Top(input logic clk, input logic d, + output logic [7:0] pos, output logic [7:0] neg); + logic cp; + logic cn; + logic [7:0] p = 8'd0; + logic [7:0] n = 8'd0; + always_ff @(posedge clk) begin + cp <= d; + cn <= d; + end + always_ff @(posedge cp) p <= p + 8'd1; + always_ff @(negedge cn) n <= n + 8'd1; + assign pos = p; + assign neg = n; +endmodule +"#) + (top Top) + (set clk 0) + ; x -> 0 is a negedge. + (set d 0) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + (for (value pos_count neg_count) + (list (1 1 1) (0 1 2) (1'bx 2 2) (0 2 3) (1'bz 3 3) (1 4 3) + (1'bx 4 4) (1 5 4) (1'bz 5 5) (1'bx 5 5) (1'bz 5 5) (0 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; A clock computed by continuous assignments from a register. The register +; changes as a whole, so the clock changes once per tick without a glitch. +(case comb_clock_edges_follow_table_9_2 + (four_state) + (source "comb_clock.sv" #" +module Top(input logic clk, input logic [2:0] d, + output logic [7:0] pos, output logic [7:0] neg); + logic [2:0] r; + logic a; + logic cp; + logic cn; + logic [7:0] p = 8'd0; + logic [7:0] n = 8'd0; + always_ff @(posedge clk) r <= d; + assign a = r[1] & r[0]; + assign cp = r[2] ? a : 1'bz; + assign cn = r[2] ? r[1] & r[0] : 1'bz; + always_ff @(posedge cp) p <= p + 8'd1; + always_ff @(negedge cn) n <= n + 8'd1; + assign pos = p; + assign neg = n; +endmodule +"#) + (top Top) + (set clk 0) + ; x -> 0 is a negedge. + (set d 3'b101) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + ; Clock levels: 1, 0, x, 0, z, 1, x, 1, z, x, z, 0. + (for (value pos_count neg_count) + (list (3'b111 1 1) (3'b100 1 2) (3'b11z 2 2) (3'b110 2 3) (3'b011 3 3) + (3'b111 4 3) (3'b1x1 4 4) (3'b111 5 4) (3'b000 5 5) (3'bx11 5 5) + (3'b0z1 5 5) (3'b101 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; Asynchronous resets driven by registers. A reset's edge runs its register, +; which takes the reset branch only at the known active level: an edge to x +; or z increments the counter, and an edge to the active level clears it. The +; path puts an increment before every clear, and an edge that should not fire +; would increment the counter. +(case internal_async_reset_edges_follow_table_9_2 + (four_state) + (source "async_reset.sv" #" +module Top(input logic clk, input logic k, input logic dh, input logic dl, + output logic [7:0] hits_h, output logic [7:0] hits_l); + logic rh; + logic rl; + logic [7:0] h = 8'h80; + logic [7:0] l = 8'h80; + always_ff @(posedge clk) begin + rh <= dh; + rl <= dl; + end + always_ff @(posedge k or posedge rh) + if (rh) h <= 8'd0; + else h <= h + 8'd1; + always_ff @(posedge k or negedge rl) + if (!rl) l <= 8'd0; + else l <= l + 8'd1; + assign hits_h = h; + assign hits_l = l; +endmodule +"#) + (top Top) + (set clk 0) + (set k 0) + ; x -> 0 is not a posedge, and x -> 1 is not a negedge. + (set dh 0) + (set dl 1) + (tick clk) + (assert_eq hits_h 0x80) + (assert_eq hits_l 0x80) + ; Reset levels 1, 0, x, 1, x, 0, z, 1, z, x, z, 0 for `rh`; `rl` has 0 and + ; 1 swapped. + (for (high low hits) + (list (1 0 0) (0 1 0) (1'bx 1'bx 1) (1 0 0) (1'bx 1'bx 0) (0 1 0) + (1'bz 1'bz 1) (1 0 0) (1'bz 1'bz 0) (1'bx 1'bx 0) (1'bz 1'bz 0) + (0 1 0)) + (set dh high) + (set dl low) + (tick clk) + (assert_eq hits_h hits) + (assert_eq hits_l hits))) + +; A clock gated by the ticked clock, `clk & en`, rises to 1 or x with the +; tick. A tick drives `clk` from its inactive level, so an x or z `clk` goes to +; 0 first. No write between ticks raises the gated clock. +(case gated_clock_edges_from_unknown_levels + (four_state) + (source "gated_clock.sv" #" +module Top(input logic clk, input logic en, output logic [7:0] pos, + output logic [7:0] ticks); + logic g; + logic [7:0] p = 8'd0; + logic [7:0] t = 8'd0; + assign g = clk & en; + always_ff @(posedge clk) t <= t + 8'd1; + always_ff @(posedge g) p <= p + 8'd1; + assign pos = p; + assign ticks = t; +endmodule +"#) + (top Top) + (for (clock enable count) + (list (1'bx 1 1) (1'bz 1'bx 2) (1'bx 1 3) (0 1'bz 4) (1'bz 0 4) (0 1 5)) + (set clk clock) + (set en enable) + (tick clk) + (assert_eq pos count))) + +; The register clock of `register_clock_edges_follow_table_9_2` in two-state +; simulation, where only 0 and 1 occur. +(case register_clock_two_state_edges + (source "register_clock.sv" #" +module Top(input bit clk, input bit d, + output bit [7:0] pos, output bit [7:0] neg); + bit cp; + bit cn; + bit [7:0] p; + bit [7:0] n; + always_ff @(posedge clk) begin + cp <= d; + cn <= d; + end + always_ff @(posedge cp) p <= p + 8'd1; + always_ff @(negedge cn) n <= n + 8'd1; + assign pos = p; + assign neg = n; +endmodule +"#) + (top Top) + (set clk 0) + (for (value pos_count neg_count) + (list (0 0 0) (1 1 0) (1 1 0) (0 1 1) (1 2 1) (0 2 2)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 8f88d2cba33..d6dbc7e3d4a 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -11,6 +11,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/always_comb.vtest", text: include_str!("always_comb.vtest"), }, + Group { + file: "src/sv/cases/edges.vtest", + text: include_str!("edges.vtest"), + }, Group { file: "src/sv/cases/generate.vtest", text: include_str!("generate.vtest"), diff --git a/crates/celox-test-suite/src/veryl/cases/four_state.vtest b/crates/celox-test-suite/src/veryl/cases/four_state.vtest index 8c7d2c71ef0..341eb6366d5 100644 --- a/crates/celox-test-suite/src/veryl/cases/four_state.vtest +++ b/crates/celox-test-suite/src/veryl/cases/four_state.vtest @@ -2393,3 +2393,196 @@ assign narrow_256 = a_256 >> sh; (assert_eq shr_{width} (fourstate limit limit) "unknown count width={width}") (assert_eq shl_{width} (fourstate limit limit) "unknown count width={width}") (assert_eq narrow_{width} (fourstate 15 15)))))) + +; IEEE 1800-2023 9.4.2, Table 9-2: a posedge leaves 0 or reaches 1, a negedge +; leaves 1 or reaches 0, and a change between x and z is neither. The clock +; below is a register, so each of its twelve changes (an Euler circuit over +; 0, 1, x, z) is an edge of an internally driven clock. +(case test_four_state_register_clock_edges_follow_table_9_2 + (four_state) + (source "test.veryl" #" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic, + pos: output logic<8>, + neg: output logic<8>, +) { + var c: logic; + always_ff (clk) { + c = d; + } + let cp: '_ clock = c; + let cn: '_ clock_negedge = c; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#) + (top Top) + (set clk 0) + (set rst 0) + (tick rst) + (set rst 1) + (assert_eq pos 0) + (assert_eq neg 0) + ; x -> 0 is a negedge. + (set d 0) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + (for (value pos_count neg_count) + (list (1 1 1) (0 1 2) (1'bx 2 2) (0 2 3) (1'bz 3 3) (1 4 3) + (1'bx 4 4) (1 5 4) (1'bz 5 5) (1'bx 5 5) (1'bz 5 5) (0 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; The same transitions on a clock computed combinationally from a register, +; `e ? a & b : 'z`. The register changes as a whole, so the clock changes once +; per tick without a glitch. +(case test_four_state_comb_clock_edges_follow_table_9_2 + (four_state) + (source "test.veryl" #" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic<3>, + pos: output logic<8>, + neg: output logic<8>, +) { + var r: logic<3>; + always_ff (clk) { + r = d; + } + let cp: '_ clock = if r[2] ? r[1] & r[0] : 1'bz; + let cn: '_ clock_negedge = if r[2] ? r[1] & r[0] : 1'bz; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#) + (top Top) + (set clk 0) + (set rst 0) + (tick rst) + (set rst 1) + ; x -> 0 is a negedge. + (set d 3'b101) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + ; Clock levels: 1, 0, x, 0, z, 1, x, 1, z, x, z, 0. + (for (value pos_count neg_count) + (list (3'b111 1 1) (3'b100 1 2) (3'b11z 2 2) (3'b110 2 3) (3'b011 3 3) + (3'b111 4 3) (3'b1x1 4 4) (3'b111 5 4) (3'b000 5 5) (3'bx11 5 5) + (3'b0z1 5 5) (3'b101 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; Asynchronous resets driven by registers. A reset domain runs on every +; Table 9-2 edge of its reset and takes the reset branch only at the known +; active level, so an edge to x or z increments the counter and an edge to +; the active level clears it. The path through the twelve changes puts an +; increment before every clear, and any edge that should not fire would +; increment the counter. +(case test_four_state_internal_async_reset_edges_follow_table_9_2 + (four_state) + (source "test.veryl" #" +module Top ( + clk : input '_ clock, + k : input '_ clock, + clr : input logic, + dh : input logic, + dl : input logic, + hits_h: output logic<8>, + hits_l: output logic<8>, +) { + var qh: logic; + var ql: logic; + always_ff (clk) { + qh = dh; + ql = dl; + } + let rh: '_ reset_async_high = qh; + let rl: '_ reset_async_low = ql; + var h : logic<8>; + var l : logic<8>; + always_ff (k, rh) { + if_reset { + h = 0; + } else if clr { + h = 8'h80; + } else { + h = h + 8'h01; + } + } + always_ff (k, rl) { + if_reset { + l = 0; + } else if clr { + l = 8'h80; + } else { + l = l + 8'h01; + } + } + assign hits_h = h; + assign hits_l = l; +} +"#) + (top Top) + (set clk 0) + (set k 0) + ; x -> 0 is not a posedge, and x -> 1 is not a negedge. + (set dh 0) + (set dl 1) + (tick clk) + (set clr 1) + (tick k) + (set clr 0) + (assert_eq hits_h 0x80) + (assert_eq hits_l 0x80) + ; Reset levels 1, 0, x, 1, x, 0, z, 1, z, x, z, 0 for `rh`; `rl` has 0 and + ; 1 swapped. + (for (high low hits) + (list (1 0 0) (0 1 0) (1'bx 1'bx 1) (1 0 0) (1'bx 1'bx 0) (0 1 0) + (1'bz 1'bz 1) (1 0 0) (1'bz 1'bz 0) (1'bx 1'bx 0) (1'bz 1'bz 0) + (0 1 0)) + (set dh high) + (set dl low) + (tick clk) + (assert_eq hits_h hits) + (assert_eq hits_l hits))) diff --git a/crates/celox-test-suite/tests/external_adapter.rs b/crates/celox-test-suite/tests/external_adapter.rs index 6f25ed0416c..5a0b362488a 100644 --- a/crates/celox-test-suite/tests/external_adapter.rs +++ b/crates/celox-test-suite/tests/external_adapter.rs @@ -93,7 +93,7 @@ fn catalogue_has_unique_stable_names_and_categories() { assert!(names.insert(case.name), "duplicate {}", case.name); assert!(case.name.contains("::")); } - assert_eq!(names.len(), 762); + assert_eq!(names.len(), 765); assert_eq!( case("operators::test_bitwise_operations").unwrap().category, Category::Operators diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 73fd74ae014..ddada1d0180 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -190,20 +190,26 @@ fn logic_level(value: &BigUint, mask: &BigUint) -> LogicLevel { } } -fn is_active_edge(kind: DomainKind, old: LogicLevel, new: LogicLevel) -> bool { - match celox_design::edges::polarity(kind) { - Some(true) => { - matches!(old, LogicLevel::Zero) && !matches!(new, LogicLevel::Zero) - || matches!(old, LogicLevel::X | LogicLevel::Z) && matches!(new, LogicLevel::One) - } - Some(false) => { - matches!(old, LogicLevel::One) && !matches!(new, LogicLevel::One) - || matches!(old, LogicLevel::X | LogicLevel::Z) && matches!(new, LogicLevel::Zero) +impl LogicLevel { + /// The edge level of [`celox_design::edges`]. + fn edge_level(self) -> u8 { + use celox_design::edges::LEVEL_UNKNOWN; + match self { + LogicLevel::Zero => 0, + LogicLevel::One => 1, + LogicLevel::X => LEVEL_UNKNOWN | 1, + LogicLevel::Z => LEVEL_UNKNOWN, } - None => false, } } +/// Whether a write from `old` to `new` is an active edge of a domain of +/// `kind` (IEEE 1800-2023 Table 9-2). A domain without an edge has none. +fn is_active_edge(kind: DomainKind, old: LogicLevel, new: LogicLevel) -> bool { + celox_design::edges::polarity(kind).is_some() + && celox_design::edges::settled_edge::(Some(kind), old.edge_level(), new.edge_level()) +} + fn record_pending_write( pending: &mut PendingWrites, id: ReflectionSignalId, diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 23839ecada6..9bafc8fe723 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -59,71 +59,80 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } // Benchmark 1b/1c: Simulator::tick with a derived clock domain: a gated - // clock (`clk & en`) and a register-driven divider. - for (name, derived) in [ - ( - "simulator_tick_gated_x10000", - "let gated: '_ clock = clk & en; always_ff (gated) { extra += 1; }", - ), - ( - "simulator_tick_divided_x10000", - "var half: logic; always_ff (clk) { half = ~half; } - let divided: '_ clock = half; always_ff (divided) { extra += 1; }", - ), - ] { - let code = CODE.replace( - "cnt: output logic<32>[N],\n ) {", - &format!( - "cnt: output logic<32>[N],\n en: input logic,\n extra: output logic<32>,\n ) {{\n {derived}" - ), - ); - let mut sim = Simulator::builder(&code, "Top").build().unwrap(); - let clk = sim.event("clk"); - let rst = sim.signal("rst"); - let en = sim.signal("en"); - sim.modify(|io| { - io.set(rst, 0u8); - io.set(en, 1u8); - }) - .unwrap(); - sim.tick(clk).unwrap(); - sim.modify(|io| io.set(rst, 1u8)).unwrap(); - - c.bench_function(name, |b| { - b.iter(|| { - for _ in 0..10000 { - sim.tick(clk).unwrap(); - } - }) - }); - let cycle_name = name.replace("tick", "cycle"); - c.bench_function(&cycle_name, |b| { - b.iter(|| { - for _ in 0..10000 { - sim.cycle(clk).unwrap(); + // clock (`clk & en`) and a register-driven divider. The `_4state` + // variants build the same designs in four-state mode, where edges of + // derived clocks also read their unknown masks (IEEE 1800-2023 + // Table 9-2). + for four_state in [false, true] { + let suffix = if four_state { "_4state" } else { "" }; + for (name, derived) in DERIVED { + let mut sim = Simulator::builder(&derived_code(derived), "Top") + .four_state(four_state) + .build() + .unwrap(); + let clk = sim.event("clk"); + let rst = sim.signal("rst"); + let en = sim.signal("en"); + let half = (name == "divided").then(|| sim.signal("half")); + sim.modify(|io| { + io.set(rst, 0u8); + io.set(en, 1u8); + // A four-state divider starts at x and would never toggle. + if let Some(half) = half { + io.set(half, 0u8); } }) - }); + .unwrap(); + sim.tick(clk).unwrap(); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + + c.bench_function(&format!("simulator_tick_{name}{suffix}_x10000"), |b| { + b.iter(|| { + for _ in 0..10000 { + sim.tick(clk).unwrap(); + } + }) + }); + c.bench_function(&format!("simulator_cycle_{name}{suffix}_x10000"), |b| { + b.iter(|| { + for _ in 0..10000 { + sim.cycle(clk).unwrap(); + } + }) + }); + } } - // Benchmark 2: Simulation::step - { - let mut sim = Simulation::builder(CODE, "Top").build().unwrap(); - sim.add_clock("clk", 10, 10); + // Benchmark 2: Simulation::step, plain and with a register-driven + // divider, in both state modes. + for four_state in [false, true] { + let suffix = if four_state { "_4state" } else { "" }; + let divided = derived_code(DERIVED[1].1); + for (name, code) in [("", CODE), ("_divided", divided.as_str())] { + let mut sim = Simulation::builder(code, "Top") + .four_state(four_state) + .build() + .unwrap(); + if !name.is_empty() { + let half = sim.signal("half"); + sim.modify(|io| io.set(half, 0u8)).unwrap(); + } + sim.add_clock("clk", 10, 10); - // Reset - // simulation currently doesn't have a direct reset method, - // but we can schedule events or just let it run. - // For this benchmark, we just want to measure the steady state overhead. + // Reset + // simulation currently doesn't have a direct reset method, + // but we can schedule events or just let it run. + // For this benchmark, we just want to measure the steady state overhead. - c.bench_function("simulation_step_x20000", |b| { - b.iter(|| { - // 20000 steps = 10000 cycles (rising + falling) - for _ in 0..20000 { - sim.step().unwrap(); - } - }) - }); + c.bench_function(&format!("simulation_step{name}{suffix}_x20000"), |b| { + b.iter(|| { + // 20000 steps = 10000 cycles (rising + falling) + for _ in 0..20000 { + sim.step().unwrap(); + } + }) + }); + } } // Benchmark 3: Simulation::step of SystemVerilog counters at the rising @@ -171,5 +180,27 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } } +/// Derived clock domains added to [`CODE`] by [`derived_code`]. +const DERIVED: [(&str, &str); 2] = [ + ( + "gated", + "let gated: '_ clock = clk & en; always_ff (gated) { extra += 1; }", + ), + ( + "divided", + "var half: logic; always_ff (clk) { half = ~half; } + let divided: '_ clock = half; always_ff (divided) { extra += 1; }", + ), +]; + +fn derived_code(derived: &str) -> String { + CODE.replace( + "cnt: output logic<32>[N],\n ) {", + &format!( + "cnt: output logic<32>[N],\n en: input logic,\n extra: output logic<32>,\n ) {{\n {derived}" + ), + ) +} + criterion_group!(benches, benchmark_simulation_overhead); criterion_main!(benches); diff --git a/crates/celox/src/edge_plans.rs b/crates/celox/src/edge_plans.rs index 61c75ff3261..18c73387801 100644 --- a/crates/celox/src/edge_plans.rs +++ b/crates/celox/src/edge_plans.rs @@ -21,6 +21,10 @@ pub struct EdgePlanSignal { /// it in the next byte. pub offset: usize, pub width: usize, + /// The signal keeps unknown bits: its edges follow the four-state rows + /// of IEEE 1800-2023 Table 9-2. + #[serde(rename = "fourState")] + pub four_state: bool, } /// A derived event domain. @@ -96,6 +100,7 @@ pub fn edge_plans(program: &LaidOutProgram) -> EdgePlans { let signal = |address: &AbsoluteAddr| EdgePlanSignal { offset: layout.offsets.get(address).copied().unwrap_or_default(), width: layout.widths.get(address).copied().unwrap_or(1), + four_state: layout.four_state && layout.is_4states.get(address).copied().unwrap_or(false), }; let domain = |address: &AbsoluteAddr| EdgePlanDomain { event: program.get_path(address), diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 1e2b7536e32..ba25492c9fd 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1254,3 +1254,475 @@ endmodule #[cfg(all(test, feature = "host-runtime"))] mod runtime_core_tests; + +/// Edges of clocks and resets the design drives itself follow IEEE 1800-2023 +/// 9.4.2, Table 9-2 in a four-state timed simulation, on every backend: a +/// posedge leaves 0 or reaches 1, a negedge leaves 1 or reaches 0, and a +/// change between x and z is neither. +#[cfg(all(test, feature = "host-runtime"))] +mod four_state_edge_tests { + use celox_frontend_sdk::{ + BinaryOp, Constant, Edge, EventEdge, EventTerm, ExprId, FrontendArtifact, ModuleBuilder, + Statement, ValueType, + }; + use num_bigint::BigUint; + + use super::Simulation; + use crate::{SimBackend, Simulator}; + + /// The levels of a clock walking all twelve changes between 0, 1, x and + /// z (an Euler circuit from 0), as (value, mask), with the posedges and + /// negedges counted after each change. + const WALK: [((u8, u8), u8, u8); 12] = [ + ((1, 0), 1, 0), + ((0, 0), 1, 1), + ((1, 1), 2, 1), + ((0, 0), 2, 2), + ((0, 1), 3, 2), + ((1, 0), 4, 2), + ((1, 1), 4, 3), + ((1, 0), 5, 3), + ((0, 1), 5, 4), + ((1, 1), 5, 4), + ((0, 1), 5, 4), + ((0, 0), 5, 5), + ]; + + /// Build `$check` against a timed simulation of each backend. + macro_rules! on_every_backend { + ($builder:expr, $check:ident) => {{ + let builder = || $builder.four_state(true).emit_triggers(); + $check(Simulation::new(builder().build_interpreter().unwrap())); + $check(Simulation::new(builder().build_cranelift().unwrap())); + $check(Simulation::new(builder().build_wasm().unwrap())); + $check(Simulation::new(builder().build_tiered().unwrap())); + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + $check(Simulation::new(builder().build_native().unwrap())); + }}; + } + + fn set(sim: &mut Simulation, name: &str, (value, mask): (u8, u8)) { + let signal = sim.signal(name); + sim.modify(|io| io.set_four_state(signal, value.into(), mask.into())) + .unwrap(); + } + + fn get(sim: &mut Simulation, name: &str) -> BigUint { + let signal = sim.signal(name); + sim.get(signal) + } + + /// Two processes drive `cp` and `cn` through [`WALK`], one change per + /// time unit; registers count the posedges of `cp` and the negedges of + /// `cn`. + fn process_design() -> FrontendArtifact { + let bit = ValueType::new(1, false, true).unwrap(); + let word = ValueType::new(8, false, true).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let cp = module.internal("cp", bit).unwrap(); + let cn = module.internal("cn", bit).unwrap(); + let pos = module.output("pos", word).unwrap(); + let neg = module.output("neg", word).unwrap(); + for (signal, width) in [(cp, 1), (cn, 1), (pos, 8), (neg, 8)] { + module + .set_initial(signal, Constant::two_state(0u8, width).unwrap()) + .unwrap(); + } + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + for (counter, clock, edge) in [(pos, cp, Edge::Posedge), (neg, cn, Edge::Negedge)] { + let read = module.read(counter).unwrap(); + let next = module.binary(BinaryOp::Add, read, one, word).unwrap(); + let target = module.whole(counter).unwrap(); + module + .register(target, next, clock, edge, None, None) + .unwrap(); + } + let delay = module.constant(Constant::two_state(1u8, 8).unwrap()); + for clock in [cp, cn] { + let target = module.whole(clock).unwrap(); + let mut body = Vec::new(); + for ((value, mask), _, _) in WALK { + let level: ExprId = module.constant(Constant::four_state(value, mask, 1).unwrap()); + body.push(Statement::Delay { amount: delay }); + body.push(Statement::Assign { + target, + value: level, + }); + } + module.process(body).unwrap(); + } + module.finish() + } + + /// A process drives `d` through [`WALK`] and pulses `clk` after each + /// change; registers `c` and `c2` follow `d` on the rising edges of + /// `clk`. Event-control waits `@(posedge c)` and `@(negedge c)` and + /// registers on the posedges of `c` and the negedges of `c2` count the + /// edges of the register clock. + fn wait_design() -> FrontendArtifact { + let bit = ValueType::new(1, false, true).unwrap(); + let word = ValueType::new(8, false, true).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let d = module.internal("d", bit).unwrap(); + let c = module.internal("c", bit).unwrap(); + let c2 = module.internal("c2", bit).unwrap(); + let counters = ["wait_pos", "wait_neg", "ff_pos", "ff_neg"] + .map(|name| module.output(name, word).unwrap()); + for signal in [clk, d, c, c2] { + module + .set_initial(signal, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + } + for counter in counters { + module + .set_initial(counter, Constant::two_state(0u8, 8).unwrap()) + .unwrap(); + } + let d_expr = module.read(d).unwrap(); + for register in [c, c2] { + let target = module.whole(register).unwrap(); + module + .register(target, d_expr, clk, Edge::Posedge, None, None) + .unwrap(); + } + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + let increment = |module: &mut ModuleBuilder, counter| { + let read = module.read(counter).unwrap(); + let next = module.binary(BinaryOp::Add, read, one, word).unwrap(); + (module.whole(counter).unwrap(), next) + }; + let [wait_pos, wait_neg, ff_pos, ff_neg] = counters; + for (counter, clock, edge) in [(ff_pos, c, Edge::Posedge), (ff_neg, c2, Edge::Negedge)] { + let (target, next) = increment(&mut module, counter); + module + .register(target, next, clock, edge, None, None) + .unwrap(); + } + for (counter, edge) in [ + (wait_pos, EventEdge::Posedge), + (wait_neg, EventEdge::Negedge), + ] { + let (target, value) = increment(&mut module, counter); + module + .process(vec![Statement::Forever { + body: vec![ + Statement::WaitEvent { + terms: vec![EventTerm { signal: c, edge }], + }, + Statement::Assign { target, value }, + ], + }]) + .unwrap(); + } + let delay = module.constant(Constant::two_state(1u8, 8).unwrap()); + let high = module.constant(Constant::two_state(1u8, 1).unwrap()); + let low = module.constant(Constant::two_state(0u8, 1).unwrap()); + let d_target = module.whole(d).unwrap(); + let clk_target = module.whole(clk).unwrap(); + let mut body = Vec::new(); + for ((value, mask), _, _) in WALK { + let level = module.constant(Constant::four_state(value, mask, 1).unwrap()); + body.push(Statement::Assign { + target: d_target, + value: level, + }); + body.push(Statement::Delay { amount: delay }); + body.push(Statement::Assign { + target: clk_target, + value: high, + }); + body.push(Statement::Delay { amount: delay }); + body.push(Statement::Assign { + target: clk_target, + value: low, + }); + } + module.process(body).unwrap(); + module.finish() + } + + /// Event-control waits and flip-flop domains see the same Table 9-2 + /// edges of a register clock. + #[test] + fn waits_on_register_clocks_follow_table_9_2() { + fn check(mut sim: Simulation) { + for (step, (_, pos, neg)) in (0u64..).zip(WALK) { + let time = 2 * step + 1; + sim.run_until(time).unwrap(); + let counts = + ["wait_pos", "wait_neg", "ff_pos", "ff_neg"].map(|name| get(&mut sim, name)); + assert_eq!( + counts, + [pos, neg, pos, neg].map(BigUint::from), + "wait_pos, wait_neg, ff_pos, ff_neg at {time}" + ); + } + } + on_every_backend!(Simulator::from_frontend(wait_design()), check); + } + + #[test] + fn process_driven_clocks_follow_table_9_2() { + fn check(mut sim: Simulation) { + for (time, (_, pos, neg)) in (1..).zip(WALK) { + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "pos"), pos.into(), "posedges at {time}"); + assert_eq!(get(&mut sim, "neg"), neg.into(), "negedges at {time}"); + } + } + on_every_backend!(Simulator::from_frontend(process_design()), check); + } + + const REGISTER_CLOCK: &str = r#" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic, + pos: output logic<8>, + neg: output logic<8>, +) { + var c: logic; + always_ff (clk) { + c = d; + } + let cp: '_ clock = c; + let cn: '_ clock_negedge = c; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#; + + /// A clock that is a register follows `d` through [`WALK`], one change + /// per rising edge of `clk`. `clk` starts at x, so its first rise, x to + /// 1, is a posedge too. + #[test] + fn register_clocks_follow_table_9_2() { + fn check(mut sim: Simulation) { + // x -> 0 asserts the reset. + sim.schedule("rst", 0, 0).unwrap(); + sim.schedule("rst", 1, 1).unwrap(); + set(&mut sim, "d", (0, 0)); + sim.add_clock("clk", 10, 5); + // The register leaves x for 0: a negedge. + sim.run_until(5).unwrap(); + assert_eq!(get(&mut sim, "pos"), 0u8.into()); + assert_eq!(get(&mut sim, "neg"), 1u8.into()); + for (time, (level, pos, neg)) in (15..).step_by(10).zip(WALK) { + set(&mut sim, "d", level); + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "pos"), pos.into(), "posedges at {time}"); + assert_eq!(get(&mut sim, "neg"), (neg + 1).into(), "negedges at {time}"); + } + } + on_every_backend!(Simulator::builder(REGISTER_CLOCK, "Top"), check); + } + + /// A clock computed combinationally from a register, `e ? a & b : 'z`, + /// with the register written whole so the clock changes once per edge. + #[test] + fn combinational_clocks_follow_table_9_2() { + const SOURCE: &str = r#" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic<3>, + pos: output logic<8>, + neg: output logic<8>, +) { + var r: logic<3>; + always_ff (clk) { + r = d; + } + let cp: '_ clock = if r[2] ? r[1] & r[0] : 1'bz; + let cn: '_ clock_negedge = if r[2] ? r[1] & r[0] : 1'bz; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#; + /// `{e, a, b}` for each level of [`WALK`], as (value, mask). + const INPUTS: [(u8, u8); 12] = [ + (0b111, 0), + (0b100, 0), + (0b110, 0b001), // 1 & z + (0b110, 0), + (0b011, 0), // e = 0 + (0b111, 0), + (0b111, 0b010), // 1 & x + (0b111, 0), + (0b000, 0), // e = 0 + (0b111, 0b100), // e = x + (0b001, 0b010), // e = 0 + (0b101, 0), + ]; + fn check(mut sim: Simulation) { + sim.schedule("rst", 0, 0).unwrap(); + sim.schedule("rst", 1, 1).unwrap(); + set(&mut sim, "d", (0b101, 0)); + sim.add_clock("clk", 10, 5); + sim.run_until(5).unwrap(); + assert_eq!(get(&mut sim, "pos"), 0u8.into()); + assert_eq!(get(&mut sim, "neg"), 1u8.into()); + for (time, (input, (_, pos, neg))) in + (15..).step_by(10).zip(INPUTS.into_iter().zip(WALK)) + { + set(&mut sim, "d", input); + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "pos"), pos.into(), "posedges at {time}"); + assert_eq!(get(&mut sim, "neg"), (neg + 1).into(), "negedges at {time}"); + } + } + on_every_backend!(Simulator::builder(SOURCE, "Top"), check); + } + + /// Asynchronous resets that are registers. An edge to x or z runs the + /// register's clocked branch (+1), an edge to the active level clears + /// it, and every clear follows an increment. + #[test] + fn register_async_resets_follow_table_9_2() { + const SOURCE: &str = r#" +module Top ( + clk : input '_ clock, + k : input '_ clock, + clr : input logic, + dh : input logic, + dl : input logic, + hits_h: output logic<8>, + hits_l: output logic<8>, +) { + var qh: logic; + var ql: logic; + always_ff (clk) { + qh = dh; + ql = dl; + } + let rh: '_ reset_async_high = qh; + let rl: '_ reset_async_low = ql; + var h : logic<8>; + var l : logic<8>; + always_ff (k, rh) { + if_reset { + h = 0; + } else if clr { + h = 8'h80; + } else { + h = h + 8'h01; + } + } + always_ff (k, rl) { + if_reset { + l = 0; + } else if clr { + l = 8'h80; + } else { + l = l + 8'h01; + } + } + assign hits_h = h; + assign hits_l = l; +} +"#; + /// `rh` levels 1, 0, x, 1, x, 0, z, 1, z, x, z, 0 (`rl` has 0 and 1 + /// swapped), and the counter after each change. + const STEPS: [((u8, u8), u8); 12] = [ + ((1, 0), 0), + ((0, 0), 0), + ((1, 1), 1), + ((1, 0), 0), + ((1, 1), 0), + ((0, 0), 0), + ((0, 1), 1), + ((1, 0), 0), + ((0, 1), 0), + ((1, 1), 0), + ((0, 1), 0), + ((0, 0), 0), + ]; + fn check(mut sim: Simulation) { + set(&mut sim, "dh", (0, 0)); + set(&mut sim, "dl", (1, 0)); + set(&mut sim, "clr", (1, 0)); + sim.schedule("k", 0, 0).unwrap(); + sim.add_clock("clk", 10, 5); + // x -> 0 is no posedge of `rh`, x -> 1 no negedge of `rl`. + sim.schedule("k", 7, 1).unwrap(); + sim.run_until(7).unwrap(); + set(&mut sim, "clr", (0, 0)); + assert_eq!(get(&mut sim, "hits_h"), 0x80u8.into()); + assert_eq!(get(&mut sim, "hits_l"), 0x80u8.into()); + for (time, ((value, mask), hits)) in (15..).step_by(10).zip(STEPS) { + let low = if mask == 0 { value ^ 1 } else { value }; + set(&mut sim, "dh", (value, mask)); + set(&mut sim, "dl", (low, mask)); + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "hits_h"), hits.into(), "rh at {time}"); + assert_eq!(get(&mut sim, "hits_l"), hits.into(), "rl at {time}"); + } + } + on_every_backend!(Simulator::builder(SOURCE, "Top"), check); + } + + /// The edge baseline of a clock left at x survives a checkpoint: the + /// following rise, x to 1, is a posedge. + #[test] + fn unknown_edge_baselines_survive_checkpoints() { + fn check(mut sim: Simulation) { + sim.schedule("rst", 0, 0).unwrap(); + sim.schedule("rst", 1, 1).unwrap(); + set(&mut sim, "d", (1, 1)); + sim.add_clock("clk", 10, 5); + // The register leaves x for x: no edge. + sim.run_until(5).unwrap(); + assert_eq!(get(&mut sim, "pos"), 0u8.into()); + let saved = sim.checkpoint().unwrap(); + let state = sim.save_state().unwrap(); + set(&mut sim, "d", (1, 0)); + sim.run_until(15).unwrap(); + assert_eq!(get(&mut sim, "pos"), 1u8.into()); + sim.restore(&saved).unwrap(); + set(&mut sim, "d", (1, 0)); + sim.run_until(15).unwrap(); + assert_eq!(get(&mut sim, "pos"), 1u8.into(), "after a restore"); + sim.load_state(&state).unwrap(); + set(&mut sim, "d", (1, 0)); + sim.run_until(15).unwrap(); + assert_eq!(get(&mut sim, "pos"), 1u8.into(), "after a state load"); + } + on_every_backend!(Simulator::builder(REGISTER_CLOCK, "Top"), check); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index f31475354ac..6c281ce7961 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -384,6 +384,7 @@ impl Simulator { .map(|(event, count)| (named(event), *count)) .collect(), high_events: parts.high_events.into_iter().map(event_path).collect(), + unknown_events: parts.unknown_events.into_iter().map(event_path).collect(), processes, } } @@ -750,6 +751,7 @@ impl Simulator { .iter() .map(|(name, _)| name) .chain(&record.high_events) + .chain(&record.unknown_events) .chain(scheduled.clone().map(|event| &event.event)) .filter(|name| !events.contains_key(*name)) .chain( @@ -794,6 +796,11 @@ impl Simulator { .map(|(event, count)| (resolve(event), *count)) .collect(), high_events: record.high_events.iter().map(|name| events[name]).collect(), + unknown_events: record + .unknown_events + .iter() + .map(|name| events[name]) + .collect(), process_wakeups, process_state, host_pending: record.processes.host_pending, diff --git a/crates/celox/tests/both_clock_edges.rs b/crates/celox/tests/both_clock_edges.rs index 2e14eda8b01..f662b5924fd 100644 --- a/crates/celox/tests/both_clock_edges.rs +++ b/crates/celox/tests/both_clock_edges.rs @@ -166,6 +166,7 @@ fn a_reset_at_both_edges() { endmodule"; for four_state in [false, true] { let mut sim = build(source, four_state); + let initial_low = get(&mut sim, "low"); let mut observed = Vec::new(); let mut time = 0; let mut edge = |sim: &mut Simulation, port: &str, level: u64| { @@ -189,12 +190,14 @@ fn a_reset_at_both_edges() { observed.push(edge(&mut sim, "rst", 1)); observed.push(edge(&mut sim, "clk", 1)); // Before `rst` first falls, `low` is unknown, and stays unknown when - // incremented. + // incremented. In four-state, `rst` rises from its initial unknown + // level, a posedge but no negedge (IEEE 1800-2023 Table 9-2), so + // `low` keeps its initial value until the first clock edge. let low = |count: u64| if four_state { 0xff } else { count }; assert_eq!( observed, vec![ - (0, low(0)), + (0, if four_state { initial_low } else { 0 }), (0, low(1)), (0, low(2)), (0, 0), diff --git a/crates/celox/tests/four_state.rs b/crates/celox/tests/four_state.rs index e0111a4e7f3..fd59bc7a47d 100644 --- a/crates/celox/tests/four_state.rs +++ b/crates/celox/tests/four_state.rs @@ -503,4 +503,25 @@ fn test_x_literal_encoding(sim) { @case "four_state::test_x_literal_encoding"; } +// ========================================================================== +// Edges of internally driven clocks and resets (IEEE 1800-2023 Table 9-2) +// ========================================================================== + +fn test_four_state_register_clock_edges_follow_table_9_2(sim) { + // Veryl 0.22.0's simulator misses edges through x and z, such as x -> 0. + @ignore_on(veryl); + @case "four_state::test_four_state_register_clock_edges_follow_table_9_2"; +} + +fn test_four_state_comb_clock_edges_follow_table_9_2(sim) { + // Veryl 0.22.0's simulator misses edges through x and z, such as x -> 0. + @ignore_on(veryl); + @case "four_state::test_four_state_comb_clock_edges_follow_table_9_2"; +} + +fn test_four_state_internal_async_reset_edges_follow_table_9_2(sim) { + // Veryl 0.22.0's simulator misses edges through x and z, such as x -> 0. + @ignore_on(veryl); + @case "four_state::test_four_state_internal_async_reset_edges_follow_table_9_2"; +} } diff --git a/crates/celox/tests/four_state_explicit_edges.rs b/crates/celox/tests/four_state_explicit_edges.rs new file mode 100644 index 00000000000..7bb97553b85 --- /dev/null +++ b/crates/celox/tests/four_state_explicit_edges.rs @@ -0,0 +1,136 @@ +#![cfg(feature = "systemverilog")] +//! Explicit edges of four-state clocks that are x or z follow IEEE +//! 1800-2023 9.4.2, Table 9-2: a rising edge from x or z is a posedge, a +//! falling one a negedge, and a gated clock is judged from the clock's real +//! level before the edge. On plain events, gated clocks and register +//! clocks, on every backend. + +use celox::{BigUint, Edge, SimBackend, Simulator}; + +/// `clkp` and `clkn` clock plain posedge and negedge counters; `clkg` gates +/// `gc = clkg & en`; `clkd` clocks a register `r` whose posedges are +/// counted. +const SOURCE: &str = "module Top(input logic clkp, input logic clkn, input logic clkg, + input logic clkd, input logic en, input logic d, + output logic [7:0] pos, output logic [7:0] neg, output logic [7:0] gpos, + output logic [7:0] dpos); + logic [7:0] p = 8'd0; + logic [7:0] n = 8'd0; + logic [7:0] g = 8'd0; + logic [7:0] t = 8'd0; + logic [7:0] q = 8'd0; + logic r = 1'b0; + logic gc; + assign gc = clkg & en; + always_ff @(posedge clkp) p <= p + 8'd1; + always_ff @(negedge clkn) n <= n + 8'd1; + always_ff @(posedge clkg) t <= t + 8'd1; + always_ff @(posedge gc) g <= g + 8'd1; + always_ff @(posedge clkd) r <= d; + always_ff @(posedge r) q <= q + 8'd1; + assign pos = p; + assign neg = n; + assign gpos = g; + assign dpos = q; +endmodule"; + +const X: (u8, u8) = (1, 1); +const Z: (u8, u8) = (0, 1); +const ZERO: (u8, u8) = (0, 0); +const ONE: (u8, u8) = (1, 0); + +fn set(sim: &mut Simulator, name: &str, (value, mask): (u8, u8)) { + let signal = sim.signal(name); + sim.modify(|io| io.set_four_state(signal, BigUint::from(value), BigUint::from(mask))) + .unwrap(); +} + +fn get(sim: &mut Simulator, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() +} + +fn edge(sim: &mut Simulator, event: &str, edge: Edge) { + let event = sim.event(event); + sim.edge(event, edge).unwrap(); +} + +fn check(mut sim: Simulator, backend: &str) { + let counts = |sim: &mut Simulator| ["pos", "neg", "gpos", "dpos"].map(|name| get(sim, name)); + + // Plain events: x -> 1 is a posedge, z -> 0 a negedge, and the + // inactive x -> 0 runs nothing. + set(&mut sim, "clkp", X); + edge(&mut sim, "clkp", Edge::Rising); + set(&mut sim, "clkn", Z); + edge(&mut sim, "clkn", Edge::Falling); + assert_eq!(counts(&mut sim), [1, 1, 0, 0], "{backend}: plain from x/z"); + set(&mut sim, "clkp", X); + edge(&mut sim, "clkp", Edge::Falling); + set(&mut sim, "clkn", X); + edge(&mut sim, "clkn", Edge::Rising); + assert_eq!(counts(&mut sim), [1, 1, 0, 0], "{backend}: inactive from x"); + sim.cycle(sim.event("clkp")).unwrap(); + assert_eq!(counts(&mut sim), [2, 1, 0, 0], "{backend}: cycle after x"); + + // A gated clock: `x & 1` -> `1 & 1` rises; `x & x` -> `1 & x` stays x. + set(&mut sim, "en", ONE); + set(&mut sim, "clkg", X); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 1, "{backend}: gated x -> 1"); + set(&mut sim, "en", X); + set(&mut sim, "clkg", X); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 1, "{backend}: gated x -> x is no edge"); + // `z & 1` is x: z -> 1 of the clock is x -> 1 of the gated clock. + set(&mut sim, "en", ONE); + set(&mut sim, "clkg", Z); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 2, "{backend}: gated z -> 1"); + // `0 & 1` -> `1 & 1`, with the clock coming from 0. + edge(&mut sim, "clkg", Edge::Falling); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 3, "{backend}: gated 0 -> 1"); + + // A register clock: `r` goes 0 -> x -> 1, two posedges, through edges + // of a clock that starts at z. + set(&mut sim, "clkd", Z); + set(&mut sim, "d", X); + edge(&mut sim, "clkd", Edge::Rising); + assert_eq!(counts(&mut sim)[3], 1, "{backend}: register 0 -> x"); + set(&mut sim, "d", ONE); + edge(&mut sim, "clkd", Edge::Falling); + edge(&mut sim, "clkd", Edge::Rising); + assert_eq!(counts(&mut sim)[3], 2, "{backend}: register x -> 1"); + set(&mut sim, "d", ZERO); + sim.cycle(sim.event("clkd")).unwrap(); + assert_eq!(counts(&mut sim)[3], 2, "{backend}: register 1 -> 0"); + + // Coincident edges from x judge the gated clock from x too. + set(&mut sim, "en", X); + set(&mut sim, "clkg", X); + set(&mut sim, "clkp", X); + let moves = [ + (sim.event("clkg"), Edge::Rising), + (sim.event("clkp"), Edge::Rising), + ]; + sim.edges(&moves).unwrap(); + assert_eq!(counts(&mut sim)[..3], [3, 1, 3], "{backend}: coincident"); +} + +#[test] +fn explicit_edges_from_unknown_levels_follow_table_9_2() { + let build = || { + Simulator::from_sv_sources( + vec![(SOURCE, std::path::Path::new("four_state_explicit_edges.sv"))], + "Top", + ) + .four_state(true) + }; + check(build().build_interpreter().unwrap(), "interp"); + check(build().build_cranelift().unwrap(), "cranelift"); + check(build().build_wasm().unwrap(), "wasm"); + check(build().build_tiered().unwrap(), "tiered"); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), "native"); +} diff --git a/crates/celox/tests/frontends/systemverilog/edges.rs b/crates/celox/tests/frontends/systemverilog/edges.rs new file mode 100644 index 00000000000..893e189ed7c --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/edges.rs @@ -0,0 +1,24 @@ +//! Edges of clocks and resets the design drives itself, in four-state +//! simulation (IEEE 1800-2023 9.4.2, Table 9-2). + +sv_backends! { + fn register_clock_edges_follow_table_9_2(sim) { + @case "edges::register_clock_edges_follow_table_9_2"; + } + + fn comb_clock_edges_follow_table_9_2(sim) { + @case "edges::comb_clock_edges_follow_table_9_2"; + } + + fn internal_async_reset_edges_follow_table_9_2(sim) { + @case "edges::internal_async_reset_edges_follow_table_9_2"; + } + + fn gated_clock_edges_from_unknown_levels(sim) { + @case "edges::gated_clock_edges_from_unknown_levels"; + } + + fn register_clock_two_state_edges(sim) { + @case "edges::register_clock_two_state_edges"; + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index a033aa691ff..51d09dd85f4 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -100,6 +100,8 @@ macro_rules! sv_backends { #[path = "frontends/systemverilog/always_comb.rs"] mod always_comb; +#[path = "frontends/systemverilog/edges.rs"] +mod edges; #[path = "frontends/systemverilog/generate.rs"] mod generate; #[path = "frontends/systemverilog/hierarchy.rs"] diff --git a/packages/celox/src/simulation.test.ts b/packages/celox/src/simulation.test.ts index 5432fcf232e..9e0d355822b 100644 --- a/packages/celox/src/simulation.test.ts +++ b/packages/celox/src/simulation.test.ts @@ -35,12 +35,19 @@ function createMockNative(opts?: { resetTypeKind?: string; associatedClock?: string; emptyEventQueue?: boolean; + /** Four-state `clk` that starts at x; its mask plane is at offset 7. */ + unknownClock?: boolean; }): { create: NativeCreateSimulationFn; handle: NativeSimulationHandle; buffer: SharedArrayBuffer; } { const buffer = new SharedArrayBuffer(64); + if (opts?.unknownClock) { + const view = new DataView(buffer); + view.setUint8(6, 1); + view.setUint8(7, 1); + } let currentTime = 0; let nextScheduledTime: number | null = opts?.emptyEventQueue ? null : 5; const processNextEvent = (): number | null => { @@ -49,8 +56,14 @@ function createMockNative(opts?: { nextScheduledTime += 5; const view = new DataView(buffer); view.setUint8(4, view.getUint8(2)); - // Toggle clock (offset 6) on each step to simulate half-period=5 - view.setUint8(6, view.getUint8(6) === 0 ? 1 : 0); + // Toggle clock (offset 6) on each step to simulate half-period=5. An + // unknown clock rises to 1 first. + if (opts?.unknownClock && view.getUint8(7) !== 0) { + view.setUint8(7, 0); + view.setUint8(6, 1); + } else { + view.setUint8(6, view.getUint8(6) === 0 ? 1 : 0); + } return currentTime; }; @@ -99,7 +112,7 @@ function createMockNative(opts?: { offset: 6, width: 1, byteSize: 1, - is4state: false, + is4state: opts?.unknownClock ?? false, direction: "input", typeKind: "clock", }, @@ -583,6 +596,19 @@ describe("Simulation", () => { expect(t).toBe(25); }); + test("waitForCycles: x -> 1 is a rising edge (IEEE 1800-2023 Table 9-2)", () => { + const mock = createMockNative({ unknownClock: true }); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + + sim.addClock("clk", { period: 10 }); + const t = sim.waitForCycles("clk", 3); + // clk: x→1→0→1→0→1 (5 steps for 3 rising edges) + expect(mock.handle.step).toHaveBeenCalledTimes(5); + expect(t).toBe(25); + }); + test("waitForCycles: throws without addClock", () => { const mock = createMockNative(); const sim = Simulation.create(TopModule, { diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index 454a9e31565..56fd3e998f1 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -556,8 +556,10 @@ export class Simulation

> { /** * Wait for `count` rising edges of the given clock. * - * Detects actual 0→1 transitions by reading the clock signal directly - * from the shared buffer (clock ports are excluded from the DUT proxy). + * Detects actual posedges by reading the clock signal directly from the + * shared buffer (clock ports are excluded from the DUT proxy). In a + * four-state simulation, a change from x or z to 1 and from 0 to x or z + * is a posedge too (IEEE 1800-2023 Table 9-2). * The clock must have been registered via `addClock`. * * @returns The simulation time after the edges are observed. @@ -579,12 +581,20 @@ export class Simulation

> { throw new Error(`No layout entry for clock '${clock}'.`); } const view = new DataView(this._buffer); - const readClk = () => view.getUint8(sig.offset); + // The level of the clock's LSB: 0, 1, or 2 plus the value bit for x + // and z, whose mask plane follows the value plane. + const maskOffset = sig.is4state ? sig.offset + sig.byteSize : -1; + const readClk = () => { + const value = view.getUint8(sig.offset) & 1; + return maskOffset < 0 + ? value + : value | ((view.getUint8(maskOffset) & 1) << 1); + }; let prev = readClk(); let remaining = count; return this.waitUntil(() => { const curr = readClk(); - if (prev === 0 && curr !== 0) remaining--; + if (prev !== 1 && curr !== 0 && (prev & curr & 2) === 0) remaining--; prev = curr; return remaining <= 0; }, opts); diff --git a/packages/celox/src/simulator-edges-addon.test.ts b/packages/celox/src/simulator-edges-addon.test.ts index 553bbe1df41..070265934d8 100644 --- a/packages/celox/src/simulator-edges-addon.test.ts +++ b/packages/celox/src/simulator-edges-addon.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "vitest"; import { Simulation } from "./simulation.js"; import { Simulator } from "./simulator.js"; +import { type FourStateSignalValue, X } from "./types.js"; const COUNTERS = ` module Top ( @@ -199,4 +200,50 @@ module Top ( sim.dispose(); } }); + + test("edges of a four-state clock follow IEEE 1800-2023 Table 9-2 from x", () => { + const source = ` +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + en: input logic, + rising: output logic<8>, + gated_rising: output logic<8>, +) { + var r: logic<8>; + var g: logic<8>; + always_ff (clk, rst) { if_reset { r = 0; } else { r = r + 8'd1; } } + let gated: '_ clock = clk & en; + always_ff (gated, rst) { if_reset { g = 0; } else { g = g + 8'd1; } } + assign rising = r; + assign gated_rising = g; +} +`; + type Ports = { + get en(): bigint; + set en(value: FourStateSignalValue); + readonly rising: bigint; + readonly gated_rising: bigint; + }; + const sim = Simulator.fromSource(source, "Top", { + fourState: true, + }); + try { + const clk = sim.event("clk"); + const counters = () => [sim.dut.rising, sim.dut.gated_rising]; + reset(sim); + expect(counters()).toEqual([0n, 0n]); + // The clock rises from x: a posedge of its own domain, while + // `x & x` stays x and the gated clock has no edge. + sim.dut.en = X; + sim.posedge(clk); + expect(counters()).toEqual([1n, 0n]); + sim.negedge(clk); + sim.dut.en = 1n; + sim.posedge(clk); + expect(counters()).toEqual([2n, 1n]); + } finally { + sim.dispose(); + } + }); }); diff --git a/packages/celox/src/wasm-edges.test.ts b/packages/celox/src/wasm-edges.test.ts index 3a1d25270a2..e82a48d3c38 100644 --- a/packages/celox/src/wasm-edges.test.ts +++ b/packages/celox/src/wasm-edges.test.ts @@ -3,7 +3,7 @@ import { createWasmSimulatorBridge, type RawWasmSimulatorHandle, } from "./wasm-bridge.js"; -import type { EdgePlans } from "./wasm-edges.js"; +import { type EdgePlans, WasmEdgeRunner } from "./wasm-edges.js"; // Memory map of a small design driven by hand-written WASM modules: // `gated = clk & en`, `inverted = ~clk`, and one counter per domain. @@ -187,3 +187,93 @@ test("edges of a clock combinational logic does not read keep it settled", () => expect(handle.edges?.([1], [true], true)).toBe(true); expect(sharedMemory[GATED_COUNT]).toBe(2); }); + +test("four-state edges judge a gated clock from x and z (IEEE 1800-2023 Table 9-2)", () => { + // Value bytes with their unknown masks in the following byte. + const clk = { offset: 0, width: 1 }; + const en = { offset: 2, width: 1 }; + const gated = { offset: 4, width: 1 }; + const COUNT = 8; + const plans: EdgePlans = { + fourState: true, + events: { + clk: { + signal: clk, + edge: "posedge", + combRead: true, + domains: [], + gated: [{ event: "gated", signal: gated, edge: "posedge" }], + }, + gated: { + signal: gated, + edge: "posedge", + combRead: false, + domains: [], + gated: [], + }, + }, + }; + const memory = { buffer: new ArrayBuffer(16) }; + const bytes = new Uint8Array(memory.buffer); + const set = (offset: number, level: "0" | "1" | "x" | "z") => { + bytes[offset] = level === "1" || level === "x" ? 1 : 0; + bytes[offset + 1] = level === "x" || level === "z" ? 1 : 0; + }; + // gated = clk & en, with four-state AND: a known 0 wins, then x. + const evalComb = () => { + const known0 = (offset: number) => + (bytes[offset + 1] ?? 0) === 0 && (bytes[offset] ?? 0) === 0; + const known1 = (offset: number) => + (bytes[offset + 1] ?? 0) === 0 && (bytes[offset] ?? 0) === 1; + if (known0(clk.offset) || known0(en.offset)) { + set(gated.offset, "0"); + } else if (known1(clk.offset) && known1(en.offset)) { + set(gated.offset, "1"); + } else { + set(gated.offset, "x"); + } + }; + const kernels = (name: string) => + name === "gated" + ? { + evalApply: () => { + bytes[COUNT] = (bytes[COUNT] ?? 0) + 1; + }, + } + : undefined; + const runner = new WasmEdgeRunner( + memory, + plans, + { clk: 0, gated: 1 }, + kernels, + evalComb, + ); + const rise = () => runner.edges([0], [true]); + const fall = () => runner.edges([0], [false]); + + // x & x stays x when the clock rises from x: no edge. + set(clk.offset, "x"); + set(en.offset, "x"); + evalComb(); + rise(); + expect(bytes[COUNT]).toBe(0); + // x & 1 -> 1 & 1: a posedge. + set(clk.offset, "x"); + set(en.offset, "1"); + evalComb(); + rise(); + expect(bytes[COUNT]).toBe(1); + // z & 1 is x: z -> 1 of the clock is x -> 1 of the gated clock. + set(clk.offset, "z"); + evalComb(); + rise(); + expect(bytes[COUNT]).toBe(2); + // A falling edge from x is no posedge, and the clock ends at a known 0. + set(clk.offset, "x"); + evalComb(); + fall(); + expect(bytes[COUNT]).toBe(2); + expect([bytes[clk.offset], bytes[clk.offset + 1]]).toEqual([0, 0]); + rise(); + expect(bytes[COUNT]).toBe(3); +}); diff --git a/packages/celox/src/wasm-edges.ts b/packages/celox/src/wasm-edges.ts index ee31deee116..9e4c1cc966a 100644 --- a/packages/celox/src/wasm-edges.ts +++ b/packages/celox/src/wasm-edges.ts @@ -18,6 +18,10 @@ * * Gates are judged by settling the design with the signal at each level. * + * In a four-state design, levels are 0, 1, x and z, and edges follow + * IEEE 1800-2023 Table 9-2: a posedge leaves 0 or reaches 1, a negedge + * leaves 1 or reaches 0, and a change between x and z is neither. + * * @module */ @@ -30,6 +34,11 @@ export interface EdgeMemory { export interface EdgePlanSignal { readonly offset: number; readonly width: number; + /** + * The signal keeps unknown bits; its mask follows the value byte. + * Defaults to the plans' `fourState`. + */ + readonly fourState?: boolean; } /** The active edge of a domain, or `"any"` for a domain of unknown kind. */ @@ -98,26 +107,37 @@ export function cachedEdgeKernels( }; } -/** One entry of a cascade round: a domain and the level it last had. */ +/** + * The bit of an edge level that marks an unknown value; the value bit then + * tells x (1) from z (0). An edge level is 0, 1, x (3) or z (2). + */ +const UNKNOWN = 2; + +/** One entry of a cascade round: a domain and the edge level it last had. */ interface RoundEntry { readonly domain: EdgePlanDomain; - was: boolean; + was: number; fired: boolean; } -/** A signal moved by an edge, with its level before and after. */ +/** A signal moved by an edge, with its edge level before and after. */ interface Lever { readonly signal: EdgePlanSignal; readonly from: number; readonly to: number; } -function stableEdge(edge: EdgePlanEdge, was: boolean, is: boolean): boolean { +/** + * Whether a change between the edge levels `was` and `is` is an active edge + * of a domain sensing `edge` (IEEE 1800-2023 Table 9-2). + */ +function stableEdge(edge: EdgePlanEdge, was: number, is: number): boolean { + const betweenUnknowns = (was & is & UNKNOWN) !== 0; switch (edge) { case "posedge": - return !was && is; + return was !== 1 && is !== 0 && !betweenUnknowns; case "negedge": - return was && !is; + return was !== 0 && is !== 1 && !betweenUnknowns; default: return was !== is; } @@ -212,7 +232,7 @@ export class WasmEdgeRunner { return; } const to = rising[index] ? 1 : 0; - const old = this.knownLevel(plan.signal); + const old = this.level(plan.signal); if ( old === to || levers.some((l) => l.signal.offset === plan.signal.offset) @@ -222,7 +242,9 @@ export class WasmEdgeRunner { moved = true; combRead ||= plan.combRead; this.setLevel(plan.signal, to); - const lever = { signal: plan.signal, from: old ?? to ^ 1, to }; + // A gated clock is judged from the lever's real level, x and z + // included. + const lever = { signal: plan.signal, from: old, to }; if (plan.edge === "any" || (plan.edge === "posedge") === (to === 1)) { sources.push(name); } @@ -281,7 +303,7 @@ export class WasmEdgeRunner { : levers.map((lever) => this.saveLevel(lever.signal)); let moved = false; for (const lever of levers) { - if (this.level(lever.signal) !== (lever.from === 1)) { + if (this.level(lever.signal) !== lever.from) { this.setLevel(lever.signal, lever.from); moved = true; } @@ -382,37 +404,40 @@ export class WasmEdgeRunner { return this.bytes()[offset] ?? 0; } - private level(signal: EdgePlanSignal): boolean { - return (this.byte(signal.offset) & 1) !== 0; + private fourState(signal: EdgePlanSignal): boolean { + return signal.fourState ?? this.plans.fourState; } - /** The signal's level, or `null` while it is unknown. */ - private knownLevel(signal: EdgePlanSignal): number | null { - if (this.plans.fourState && (this.byte(signal.offset + 1) & 1) !== 0) { - return null; + /** The signal's edge level: 0, 1, or x (3) and z (2) while unknown. */ + private level(signal: EdgePlanSignal): number { + const value = this.byte(signal.offset) & 1; + if (this.fourState(signal) && (this.byte(signal.offset + 1) & 1) !== 0) { + return UNKNOWN | value; } - return this.byte(signal.offset) & 1; + return value; } + /** Move the signal to the edge level `level`. */ private setLevel(signal: EdgePlanSignal, level: number): void { const bytes = this.bytes(); - bytes[signal.offset] = (this.byte(signal.offset) & ~1) | level; - if (this.plans.fourState) { - bytes[signal.offset + 1] = this.byte(signal.offset + 1) & ~1; + bytes[signal.offset] = (this.byte(signal.offset) & ~1) | (level & 1); + if (this.fourState(signal)) { + const unknown = (level & UNKNOWN) !== 0 ? 1 : 0; + bytes[signal.offset + 1] = (this.byte(signal.offset + 1) & ~1) | unknown; } } private saveLevel(signal: EdgePlanSignal): [number, number] { return [ this.byte(signal.offset), - this.plans.fourState ? this.byte(signal.offset + 1) : 0, + this.fourState(signal) ? this.byte(signal.offset + 1) : 0, ]; } private restoreLevel(signal: EdgePlanSignal, saved: [number, number]): void { const bytes = this.bytes(); bytes[signal.offset] = saved[0]; - if (this.plans.fourState) { + if (this.fourState(signal)) { bytes[signal.offset + 1] = saved[1]; } } diff --git a/packages/playground/test/playground-simulator-wasm.test.ts b/packages/playground/test/playground-simulator-wasm.test.ts index 3e41fb8b612..985912eb06a 100644 --- a/packages/playground/test/playground-simulator-wasm.test.ts +++ b/packages/playground/test/playground-simulator-wasm.test.ts @@ -3,7 +3,7 @@ * explicit edges and timed steps fire derived and gated clocks as the * native simulator does. The expected counts are the native simulator's. */ -import { loadNativeAddon, Simulator } from "@celox-sim/celox"; +import { loadNativeAddon, Simulator, X } from "@celox-sim/celox"; import { describe, expect, test } from "vitest"; import { type CompilerHandle, @@ -52,15 +52,27 @@ type WasmAddon = { ) => CompilerHandle & { dispose(): void }; }; -function compile(source: string, top: string) { +// A gated clock with a reset, so that its counter is known in four-state +// simulation. +const GATED_RESET = `module GatedReset ( + clk: input clock, + rst: input reset_async_low, + en: input logic, + count: output logic<8>, +) { + let gated: '_ clock = clk & en; + always_ff (gated, rst) { if_reset { count = 0; } else { count += 1; } } +}`; + +function compile(source: string, top: string, fourState = false) { const addon = loadNativeAddon() as unknown as WasmAddon; const handle = new addon.NativeSimulatorHandle( [{ content: source, path: "top.veryl" }], top, - { fourState: false }, + { fourState }, ); try { - return compiledFromHandle(handle, false); + return compiledFromHandle(handle, fourState); } finally { handle.dispose(); } @@ -148,4 +160,25 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { expect(dumps[0]?.timestamp).toBe(7); expect(dumps[0]?.names).toEqual(expect.arrayContaining(["en", "count"])); }); + + test("four-state edges judge a gated clock from x (IEEE 1800-2023 Table 9-2)", () => { + const sim = createPlaygroundSimulator( + compile(GATED_RESET, "GatedReset", true), + ); + const clk = sim.event("clk"); + const rst = sim.event("rst"); + sim.negedge(rst); + sim.posedge(rst); + expect(sim.dut.count).toBe(0n); + // The clock rises from x with `en` at x: `x & x` stays x, no edge. + // The DUT is typed for two-state values; its setter takes X too. + (sim.dut as Record).en = X; + sim.posedge(clk); + expect(sim.dut.count).toBe(0n); + // From a known 0, `0 & 1` -> `1 & 1` rises. + sim.negedge(clk); + sim.dut.en = 1n; + sim.posedge(clk); + expect(sim.dut.count).toBe(1n); + }); });