diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index f1b9fbe01c7..f02463dbca3 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -216,6 +216,11 @@ pub struct RuntimeCombObserver { pub site_id: u32, pub activation_group: u32, pub sensitivity: Vec>, + /// Occurrence counters of the sensitivity: a counter that moved since + /// the last check activates the observer even when the settled value + /// equals the last one. + #[serde(default = "Vec::new")] + pub occurrence_counters: Vec, pub written_inputs: Vec, } @@ -822,6 +827,11 @@ pub struct RuntimeSchema { pub process_origins: Vec, /// Counted signals and their occurrence counters. pub watches: Vec>, + /// Bit ranges whose changes bump an occurrence counter: the sensitivity + /// of change-gated combinational processes and comb observers. Design + /// code counts its own writes; the runtime counts the writes it makes, + /// such as the nonblocking updates it publishes. + pub occurrence_probes: Vec<(VarAtomBase, A)>, /// Wait sites of the process kernels. A process's sites appear in the /// order of its local site indices. pub wait_sites: Vec>, @@ -860,6 +870,7 @@ impl Default for RuntimeSchema { processes: Vec::new(), process_origins: Vec::new(), watches: Vec::new(), + occurrence_probes: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), host_request_sites: Vec::new(), @@ -1657,6 +1668,7 @@ mod tests { id: initial.address, access: BitAccess { lsb: 3, msb: 7 }, }], + occurrence_counters: Vec::new(), written_inputs: vec![initial.address], }); runtime.testbench_read_roots.insert(initial.address); diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index e7af72a6efd..c3a047e2555 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -26,12 +26,15 @@ pub struct ScheduleModel { /// Counted signals with all their counters, and the canonical domains /// each counter triggers, in [`RuntimeSchema::watches`] order. pub counted: Vec>, + /// Bit ranges whose changes bump an occurrence counter + /// ([`RuntimeSchema::occurrence_probes`]). + pub probes: Vec<(crate::VarAtomBase, A)>, /// Process kernels in kernel order. pub processes: Vec>, /// Signals a wait watches, which the host's writes must be logged for. pub waited: Vec, - /// The design has process kernels or counted signals. Without either, - /// a round of the scheduler is the batch step. + /// The design has process kernels. Without them, a round of the + /// scheduler is the batch step, which also checks counted signals. pub timed: bool, /// Some nonblocking site has a pending flag. pub has_pending_nba_sites: bool, @@ -131,8 +134,9 @@ impl ScheduleModel { Self { events: design.events.clone(), kinds: design.event_kinds(), - timed: !processes.is_empty() || !counted.is_empty(), + timed: !processes.is_empty(), counted, + probes: schema.occurrence_probes.clone(), processes, waited, has_pending_nba_sites, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 9e7edb1dc0c..d5d48be525f 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -16,7 +16,7 @@ use celox_design::{ InitialStateValue, InstanceId, ModuleId, NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedStateAddr, RuntimeCombObserver, RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, RuntimeSchema, STABLE_REGION, StateAddr, StateObjectId, TriggerSet, VarAtomBase, - VariableMetadata, WaitSite, + VariableMetadata, WORKING_REGION, WaitSite, }; use celox_sir::{ BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIROffset, @@ -733,6 +733,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) .collect(); let declaration_probes; + let occurrence_probes: Vec<(VarAtomBase, AbsoluteAddr)>; let counted = { // Flip-flop event domains and the aliases that resolve to them. let event_addresses: HashSet = eval_apply_ffs @@ -761,6 +762,13 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } } + for observer in &comb_observers { + for &(source, counter) in &observer.sensitivity_counters { + if !probes.contains(&(source, counter)) { + probes.push((source, counter)); + } + } + } // A direct wire/port connection carries occurrences as well as its // settled value. Preserve them when a kernel writes the upstream // object twice before the copy path is evaluated. Only equal-width, @@ -808,6 +816,13 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } declaration_probes = probes.clone(); + occurrence_probes = probes.clone(); + // Signals a flip-flop evaluation may store twice in its working + // state. Each store is an update event (IEEE 1800-2023 4.3, 10.4.2) + // that the commit of the final value alone would not show; the + // working state is seeded with the stable value first, so a store + // compares with the value its update replaces. + let ff_multi_stored = ff_multi_stored(&eval_apply_ffs, &eval_only_ffs, ¶llel_ff_units); for (source, counter) in probes { let width = source.access.msb - source.access.lsb + 1; let four_state = four_state && variables[&source.id].1; @@ -854,6 +869,27 @@ pub fn schedule_symbolic_rtl_reporting_loops( crate::watch::instrument_unit(&mut part.apply, code); } } + if ff_multi_stored.contains(&source.id) { + let working = + |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); + let code = |address: &RegionedAbsoluteAddr| { + (address.region == WORKING_REGION && address.absolute_addr() == source.id).then( + || crate::watch::WatchCode { + signal: working(source.id), + width, + offset: offset.clone(), + four_state, + counters: vec![(CounterKind::Changes, stable(counter))], + }, + ) + }; + for_each_ff_evaluation( + &mut eval_apply_ffs, + &mut eval_only_ffs, + &mut parallel_ff_units, + |unit| crate::watch::instrument_stores(unit, code), + ); + } for path in &mut comb_blocks { if let LogicPathTarget::Process { unit, .. } = &mut path.target { crate::watch::instrument_unit(unit, |address| { @@ -868,14 +904,42 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } } - instrument_counted_signals( + let counted = instrument_counted_signals( &timing, &event_addresses, &variables, four_state, &mut processes, &mut comb_blocks, - ) + ); + for (signal, slots) in &counted { + if !ff_multi_stored.contains(signal) { + continue; + } + let (width, is_4state) = variables[signal]; + let regioned = RegionedAbsoluteAddr::from_absolute_addr; + let code = |address: &RegionedAbsoluteAddr| { + (address.region == WORKING_REGION && address.absolute_addr() == *signal).then( + || crate::watch::WatchCode { + signal: regioned(WORKING_REGION, *signal), + offset: celox_sir::SIROffset::Static(0), + width, + four_state: four_state && is_4state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) + .collect(), + }, + ) + }; + for_each_ff_evaluation( + &mut eval_apply_ffs, + &mut eval_only_ffs, + &mut parallel_ff_units, + |unit| crate::watch::instrument_stores(unit, code), + ); + } + counted }; // Combinational values and the variables they are computed from. let comb_sources = comb_sources(&comb_blocks, &global_arena); @@ -1621,6 +1685,11 @@ pub fn schedule_symbolic_rtl_reporting_loops( site_id: observer.site_id, activation_group: observer.activation_group, sensitivity: observer.sensitivity.clone(), + occurrence_counters: observer + .sensitivity_counters + .iter() + .map(|&(_, counter)| counter) + .collect(), written_inputs: observer.written_inputs.clone(), }) .collect(); @@ -1835,6 +1904,11 @@ pub fn schedule_symbolic_rtl_reporting_loops( access: atom.access, }) .collect(), + occurrence_counters: observer + .occurrence_counters + .into_iter() + .map(project) + .collect(), written_inputs: observer.written_inputs.into_iter().map(project).collect(), }) .collect(); @@ -1968,6 +2042,24 @@ pub fn schedule_symbolic_rtl_reporting_loops( .chain(host_request_sites.iter().flat_map(|site| site.slots())) .collect(); let declaration_startup = declaration_startup.map(|startup| startup.map(project)); + let occurrence_probes: Vec<(VarAtomBase, StateAddr)> = occurrence_probes + .into_iter() + .map(|(source, counter)| { + ( + VarAtomBase { + id: project(source.id), + access: source.access, + }, + project(counter), + ) + }) + .collect(); + // The runtime counts the occurrences its own writes cause. + timing_read_roots.extend( + occurrence_probes + .iter() + .flat_map(|(source, counter)| [source.id, *counter]), + ); if let Some(startup) = &declaration_startup { timing_read_roots.extend( startup @@ -2040,6 +2132,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( processes: process_slots, process_origins, watches, + occurrence_probes, wait_sites, nba_sites, host_request_sites, @@ -3586,6 +3679,52 @@ fn relocate_timing( metadata } +type FfUnits = HashMap>>; +type FfParts = HashMap)>>; + +/// The signals some flip-flop evaluation may store twice in its working +/// state in one execution. +fn ff_multi_stored( + eval_apply_ffs: &FfUnits, + eval_only_ffs: &FfUnits, + parallel_ff_units: &FfParts, +) -> HashSet { + let working = |address: &RegionedAbsoluteAddr| { + (address.region == WORKING_REGION).then(|| address.absolute_addr()) + }; + eval_apply_ffs + .values() + .chain(eval_only_ffs.values()) + .flatten() + .chain( + parallel_ff_units + .values() + .flatten() + .map(|(_, part)| &part.evaluate), + ) + .flat_map(|unit| crate::watch::multi_store_only_candidates(unit, working)) + .collect() +} + +/// Run `f` on every flip-flop evaluation. +fn for_each_ff_evaluation( + eval_apply_ffs: &mut FfUnits, + eval_only_ffs: &mut FfUnits, + parallel_ff_units: &mut FfParts, + mut f: impl FnMut(&mut ExecutionUnit), +) { + for unit in eval_apply_ffs + .values_mut() + .chain(eval_only_ffs.values_mut()) + .flatten() + { + f(unit); + } + for (_, part) in parallel_ff_units.values_mut().flatten() { + f(&mut part.evaluate); + } +} + /// Counted signals: those a unit may store twice between two runtime checks /// (a frontend declared counters for them) and that a flip-flop domain or a /// wait watches. Returns their counters by signal and instruments the diff --git a/crates/celox-frontend-core/src/symbolic/flattening.rs b/crates/celox-frontend-core/src/symbolic/flattening.rs index 878f6df13bf..d12fe533003 100644 --- a/crates/celox-frontend-core/src/symbolic/flattening.rs +++ b/crates/celox-frontend-core/src/symbolic/flattening.rs @@ -1050,6 +1050,16 @@ fn convert_comb_observer< .iter() .map(|v| VarAtomBase::new(f(&v.id), v.access.lsb, v.access.msb)) .collect(), + sensitivity_counters: observer + .sensitivity_counters + .iter() + .map(|(v, counter)| { + ( + VarAtomBase::new(f(&v.id), v.access.lsb, v.access.msb), + f(counter), + ) + }) + .collect(), local_inputs: observer .local_inputs .iter() diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 008f9d44bc0..7dbf1c1aeb7 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -367,13 +367,31 @@ pub fn write_destination(instruction: &SIRInstruction) -> Option<&A> { pub fn multi_store_candidates( unit: &ExecutionUnit, key: impl Fn(&A) -> Option, +) -> Vec { + multi_write_candidates(unit, |instruction| { + write_destination(instruction).and_then(&key) + }) +} + +/// Like [`multi_store_candidates`], over the stores alone. A flip-flop +/// evaluation seeds its working state with commits; only its stores are +/// writes of the process. +pub fn multi_store_only_candidates( + unit: &ExecutionUnit, + key: impl Fn(&A) -> Option, +) -> Vec { + multi_write_candidates(unit, |instruction| match instruction { + SIRInstruction::Store(address, ..) => key(address), + _ => None, + }) +} + +fn multi_write_candidates( + unit: &ExecutionUnit, + destination: impl Fn(&SIRInstruction) -> Option, ) -> Vec { let writes = |block: &celox_sir::BasicBlock| -> Vec> { - block - .instructions - .iter() - .map(|instruction| write_destination(instruction).and_then(&key)) - .collect() + block.instructions.iter().map(&destination).collect() }; let block_writes: crate::HashMap>> = unit .blocks @@ -419,6 +437,30 @@ pub fn multi_store_candidates( pub fn instrument_unit( unit: &mut ExecutionUnit, watch_for: impl Fn(&A) -> Option>, +) { + instrument_writes(unit, write_destination, watch_for); +} + +/// Like [`instrument_unit`], for the stores alone: the commits that seed a +/// flip-flop evaluation's working state are not writes of the process. +pub fn instrument_stores( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&A) -> Option>, +) { + instrument_writes( + unit, + |instruction| match instruction { + SIRInstruction::Store(address, ..) => Some(address), + _ => None, + }, + watch_for, + ); +} + +fn instrument_writes( + unit: &mut ExecutionUnit, + destination: impl Fn(&SIRInstruction) -> Option<&A>, + watch_for: impl Fn(&A) -> Option>, ) { let mut next_register = unit .register_map @@ -427,16 +469,16 @@ pub fn instrument_unit( .max() .unwrap_or(0); for block in unit.blocks.values_mut() { - if !block.instructions.iter().any(|instruction| { - write_destination(instruction) - .and_then(&watch_for) - .is_some() - }) { + if !block + .instructions + .iter() + .any(|instruction| destination(instruction).and_then(&watch_for).is_some()) + { continue; } let mut instructions = Vec::with_capacity(block.instructions.len()); for instruction in std::mem::take(&mut block.instructions) { - let Some(watch) = write_destination(&instruction).and_then(&watch_for) else { + let Some(watch) = destination(&instruction).and_then(&watch_for) else { instructions.push(instruction); continue; }; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b27b2f92fac..1711d5ce30a 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -3649,6 +3649,14 @@ pub(crate) fn attach_instance_glue( )); } } + // A flip-flop evaluation stores each update in the working state; two + // of one execution are two update events (IEEE 1800-2023 4.3, 10.4.2). + for unit in module.eval_only_ff_blocks.values() { + candidates.extend(celox_frontend_core::watch::multi_store_only_candidates( + unit, + |address| (address.region == WORKING_REGION).then_some(address.var_id), + )); + } module.arena = arena; // Combinational event sites follow the flip-flop ones, including the // events run-time loops emit. @@ -4297,10 +4305,35 @@ fn lower_comb_processes( .collect(); } } - // The sites of one process activate together. + // The sites of one process activate together. Every change of a + // source schedules the process (IEEE 1800-2023 4.3), also one that a + // later write of the same time slot undoes, so each sensitivity atom + // counts its occurrences. let base = sites.len() as u32; + let mut counters: Vec<(VarAtomBase, SourceVarId)> = Vec::new(); for mut observer in std::mem::take(&mut comb.observers) { observer.activation_group = base; + for atom in &observer.sensitivity { + if !counters.iter().any(|(counted, _)| counted == atom) { + let (counter, _) = comb.m.temp( + "comb_occurrences", + celox_design::EVENT_COUNTER_WIDTH, + false, + false, + ); + counters.push((*atom, counter)); + } + } + observer.sensitivity_counters = observer + .sensitivity + .iter() + .map(|atom| { + *counters + .iter() + .find(|(counted, _)| counted == atom) + .expect("a counter for every sensitivity atom") + }) + .collect(); observers.push(observer); } sites.append(&mut comb.sites); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 071c7ce59c0..98c1c1bd75b 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3595,6 +3595,7 @@ impl<'p, 'a> Comb<'p, 'a> { args: captured, loop_runner: None, sensitivity: Vec::new(), + sensitivity_counters: Vec::new(), local_inputs, observed_inputs: observed .into_iter() diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index f4fce2b13c3..385bcbc0bb6 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -373,6 +373,16 @@ fn map_observer( .collect::>()?, loop_runner: observer.loop_runner.map(&mut map_node).transpose()?, sensitivity: map_atoms(&observer.sensitivity), + sensitivity_counters: observer + .sensitivity_counters + .iter() + .map(|(atom, counter)| { + ( + VarAtomBase::new(ids[&atom.id], atom.access.lsb, atom.access.msb), + ids[counter], + ) + }) + .collect(), local_inputs: observer .local_inputs .iter() diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index 94cfa90963d..c4623e4f940 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -342,6 +342,7 @@ fn collect_system_function_effect( args: observer_args, loop_runner: None, sensitivity: Vec::new(), + sensitivity_counters: Vec::new(), local_inputs, observed_inputs: observed_inputs.into_iter().collect(), position_inputs: position_inputs.into_iter().collect(), diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 560a9cd775b..2b3148f0343 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -6,7 +6,7 @@ use fxhash::{FxHashMap, FxHashSet}; use crate::{ AbsoluteAddr, EventDomain, EventInfo, HostWatch, SignalRef, backend::{EventHandle, SimBackend}, - timing::{CountedDomainRefs, CountedRefs, NbaSiteRefs, ProcessRefs, TermRefs}, + timing::{CountedDomainRefs, CountedRefs, NbaSiteRefs, ProbeRefs, ProcessRefs, TermRefs}, }; /// The facts a timed simulation keeps but never changes: event signals, @@ -24,13 +24,18 @@ pub struct ResolvedSchedule { /// Counted signals and the domains their counters trigger. pub(crate) counted: Vec, pub(crate) counted_by_offset: FxHashMap, + /// Each counter that triggers a domain: the counter, the event id, and + /// where its last seen value is kept ([`ProcessState::domain_counters`]). + pub(crate) counted_triggers: Vec, + /// Occurrence probes by the offset of their signal. + pub(crate) probes_by_offset: FxHashMap>, /// Whether any process has a nonblocking site with a pending flag. pub(crate) has_pending_nba_sites: bool, /// Per event ID, the event IDs of clocks computed combinationally from /// the event's signal. Empty when the design has none. pub(crate) combinational_derived: Vec>, - /// The design has process kernels or counted signals. Without either, a - /// round is exactly the batch step and skips every process check. + /// The design has process kernels. Without them, a round is the batch + /// step and skips every process check. pub(crate) timed: bool, /// Canonical event IDs whose evaluation commits their blocking results. pub(crate) active_commits: bit_set::BitSet, @@ -198,6 +203,34 @@ impl ResolvedSchedule { .enumerate() .map(|(index, counted)| (counted.refs.signal.offset, index)) .collect(); + let counted_triggers = counted + .iter() + .enumerate() + .flat_map(|(index, counted)| { + counted + .domains + .iter() + .map(move |&(id, kind)| CountedTrigger { + counter: counted.refs.counter(kind), + id, + seen: (index, crate::timing::kind_index(kind)), + }) + }) + .collect(); + let mut probes_by_offset: FxHashMap> = FxHashMap::default(); + for (source, counter) in &model.probes { + let probe = ProbeRefs { + lsb: source.access.lsb, + msb: source.access.msb, + counter: resolve(counter), + }; + let probes = probes_by_offset + .entry(resolve(&source.id).offset) + .or_default(); + if !probes.contains(&probe) { + probes.push(probe); + } + } Self { topo_signals, domain_kinds, @@ -207,6 +240,8 @@ impl ResolvedSchedule { processes, counted, counted_by_offset, + counted_triggers, + probes_by_offset, has_pending_nba_sites: model.has_pending_nba_sites, combinational_derived, timed: model.timed, @@ -216,6 +251,15 @@ impl ResolvedSchedule { } } +/// A counter that triggers a domain. +#[derive(Clone, Copy, Debug)] +pub(crate) struct CountedTrigger { + pub counter: SignalRef, + pub id: usize, + /// The index of the counted signal and of the counter kind. + pub seen: (usize, usize), +} + fn counted_refs( backend: &B, counted: &celox_design::schedule::CountedModel, diff --git a/crates/celox-runtime/src/simulation/batch.rs b/crates/celox-runtime/src/simulation/batch.rs index 0972bd60d3a..449175c28cc 100644 --- a/crates/celox-runtime/src/simulation/batch.rs +++ b/crates/celox-runtime/src/simulation/batch.rs @@ -1,12 +1,17 @@ -//! The round of a design without processes and counted signals, and the -//! stable-edge helpers it calls, kept in one module. +//! The round of a design without processes, and the stable-edge helpers it +//! calls, kept in one module. use bit_set::BitSet; use celox_design::edges::{LEVEL_UNKNOWN, settled_edge}; use super::SimulationState; use super::host::SimulationExecutor; -use crate::{SignalRef, backend::SimBackend, scheduler::SimEvent, timing::Halt}; +use crate::{ + SignalRef, + backend::SimBackend, + scheduler::SimEvent, + timing::{Halt, read}, +}; /// The level of an event signal: its value bits, without the unused bits /// above its width that share its storage byte. Backends need not keep those @@ -101,9 +106,10 @@ impl SimulationState { } } - /// The round of a design without processes and counted signals: the - /// batch step as it was before process rounds, kept apart from - /// [`Self::step_round`] so that such designs run its code unchanged. + /// The round of a design without processes: the batch step as it was + /// before process rounds, kept apart from [`Self::step_round`] so that + /// such designs run its code unchanged. Counted signals add only a + /// check of their counters after each evaluation. pub(super) fn batch_round( &mut self, executor: &mut E, @@ -116,8 +122,21 @@ impl SimulationState { self.scheduler.time = current_time; let num_events = executor.backend().num_events(); + let counted = !self.model.counted.is_empty(); for event in &events_to_process { - executor.backend_mut().set(event.signal, event.next_val); + let backend = executor.backend_mut(); + match counted + .then(|| self.model.counted_by_offset.get(&event.signal.offset)) + .flatten() + { + Some(&counted) => { + let old = read(backend, event.signal); + backend.set(event.signal, event.next_val); + let new = read(backend, event.signal); + self.model.counted[counted].refs.bump(backend, &old, &new); + } + None => backend.set(event.signal, event.next_val), + } } let mut triggered_domains = BitSet::with_capacity(num_events); @@ -181,6 +200,9 @@ impl SimulationState { // with the edge) gives a further edge, as the update events of the // NBA region do. let mut edge_approved: Option = None; + if counted { + self.mark_counted_domains_in_batch(executor.backend_mut(), &mut edge_approved); + } for &source in &gating_sources { for index in 0..self.model.combinational_derived[source].len() { let id = self.model.combinational_derived[source][index]; @@ -230,6 +252,12 @@ impl SimulationState { if track_stable_edges { self.replace_triggers_with_stable_edges(executor.backend_mut()); } + if counted { + self.mark_counted_domains_in_batch( + executor.backend_mut(), + &mut edge_approved, + ); + } comb_already_done = true; break; } @@ -301,6 +329,9 @@ impl SimulationState { if track_stable_edges { self.replace_triggers_with_stable_edges(executor.backend_mut()); } + if counted { + self.mark_counted_domains_in_batch(executor.backend_mut(), &mut edge_approved); + } } } diff --git a/crates/celox-runtime/src/simulation/edges.rs b/crates/celox-runtime/src/simulation/edges.rs index 25d14024a09..d39c37cb958 100644 --- a/crates/celox-runtime/src/simulation/edges.rs +++ b/crates/celox-runtime/src/simulation/edges.rs @@ -152,6 +152,28 @@ impl SimulationState { } } + /// Like [`Self::mark_counted_domains`], for the batch round: a counted + /// occurrence is an edge even where the settled levels show none, so + /// the marked domains are added to `approved`. + pub(super) fn mark_counted_domains_in_batch( + &mut self, + backend: &mut B, + approved: &mut Option, + ) { + for trigger in &self.model.counted_triggers { + let value: u32 = backend.get_as(trigger.counter); + let (index, kind) = trigger.seen; + let seen = &mut self.process_state.domain_counters[index][kind]; + if value != *seen { + *seen = value; + backend.mark_triggered_bit(trigger.id); + approved + .get_or_insert_with(Default::default) + .insert(trigger.id); + } + } + } + /// Mark the domains a scheduled or process-driven value of an event /// signal triggers, against the values of the last settled round. #[inline] diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index f5dcb5ffac9..73f47c66135 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -1,4 +1,4 @@ -//! Rounds of a time slot with processes or counted signals: settling, +//! Rounds of a time slot with processes: settling, //! derived-clock edges, domains evaluated before an inactive region and //! their publication. diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index f8497a81a6d..da21433b58d 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -80,18 +80,33 @@ impl SimulationState { signal: SignalRef, write: impl FnOnce(&mut B), ) { - if self.model.counted.is_empty() && self.process_state.waiters.is_empty() { + if self.model.counted.is_empty() + && self.model.probes_by_offset.is_empty() + && self.process_state.waiters.is_empty() + { write(backend); return; } - match self.model.counted_by_offset.get(&signal.offset).copied() { - Some(counted) => { - let old = read(backend, signal); - write(backend); - let new = read(backend, signal); + let counted = self.model.counted_by_offset.get(&signal.offset).copied(); + let probes = self.model.probes_by_offset.get(&signal.offset); + if counted.is_none() && probes.is_none() { + write(backend); + } else { + let old = read(backend, signal); + write(backend); + let new = read(backend, signal); + if let Some(counted) = counted { self.model.counted[counted].refs.bump(backend, &old, &new); } - None => write(backend), + // One counter can observe several ranges of the signal; a write + // is one occurrence. + let mut bumped: Vec = Vec::new(); + for probe in probes.into_iter().flatten() { + if !bumped.contains(&probe.counter) && probe.changed(&old, &new) { + probe.bump(backend); + bumped.push(probe.counter); + } + } } if !self.process_state.waiters.is_empty() { self.observe(backend, Some(signal)); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 87b98bb827f..7c1144c404a 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -104,6 +104,29 @@ impl CountedRefs { } } +/// A bit range whose changes bump an occurrence counter. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProbeRefs { + pub lsb: usize, + pub msb: usize, + pub counter: SignalRef, +} + +impl ProbeRefs { + /// Whether the probed range differs between `old` and `new`. + pub fn changed(&self, old: &Value, new: &Value) -> bool { + let width = self.msb - self.lsb + 1; + let mask = (BigUint::from(1u8) << width) - 1u8; + let bits = |plane: &BigUint| (plane >> self.lsb) & &mask; + bits(&old.0) != bits(&new.0) || bits(&old.1) != bits(&new.1) + } + + pub fn bump(&self, backend: &mut B) { + let value: u32 = backend.get_as(self.counter); + backend.set(self.counter, value.wrapping_add(1)); + } +} + /// One term of a wait site. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TermRefs { diff --git a/crates/celox-slt/src/lib.rs b/crates/celox-slt/src/lib.rs index fe5e99b2481..ac8a9ec8a9a 100644 --- a/crates/celox-slt/src/lib.rs +++ b/crates/celox-slt/src/lib.rs @@ -56,6 +56,10 @@ pub struct CombObserver { pub args: Vec, pub loop_runner: Option, pub sensitivity: Vec>, + /// Occurrence counters of sensitivity atoms, each paired with its atom. + /// Writers count every change, so a value that changes and changes back + /// between two activation checks still activates the observer. + pub sensitivity_counters: Vec<(VarAtomBase, A)>, pub local_inputs: Vec<(A, NodeId)>, pub observed_inputs: Vec>, pub position_inputs: Vec>, diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index 0f17d06b6b6..f1819cdce52 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -87,8 +87,17 @@ pub(super) fn runtime_cast_target_expr( let width = expr_static_width(state, &expr, packed_dimensions).ok_or_else(|| { unsupported("signedness cast of an operand without a static width") })?; + let operand_signed = + dimensions::expression_signedness(&expr, packed_dimensions, const_env) + .ok_or_else(|| unsupported("cast of an operand whose signedness is unknown"))?; return Ok(Expr::Resize { - expr: Box::new(expr), + // Signing changes the result type after evaluating the operand + // in its own type; it must not change a division's operator. + expr: Box::new(Expr::Resize { + expr: Box::new(expr), + width, + signed: operand_signed, + }), width, signed, }); diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index 41cb101e880..6241980bc29 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -84,6 +84,14 @@ pub(super) fn expr_static_width( } } Expr::Inside { .. } => Some(1), + // The synthetic unknown arm has the guarded operation's width. + Expr::Mux { + then_expr, + else_expr, + .. + } if matches!(&**then_expr, Expr::Literal(text) if text == crate::DIV_ZERO_UNKNOWN_LITERAL) => { + expr_static_width(state, else_expr, packed_dimensions) + } Expr::Mux { then_expr, else_expr, diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 19ded55a670..5dd450c54b0 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -3,6 +3,14 @@ use super::*; pub(super) fn guard_zero_divisions(state: &AnalysisState, expr: Expr) -> Expr { + // Binding an enclosing expression can visit an already guarded operand. + // Its children were guarded when it was constructed. Wrapping it again + // loses the operation's type when the internal unknown arm is lowered. + if matches!(&expr, Expr::Mux { then_expr, .. } + if matches!(&**then_expr, Expr::Literal(text) if text == crate::DIV_ZERO_UNKNOWN_LITERAL)) + { + return expr; + } match expr { Expr::Ident(_) | Expr::Literal(_) => expr, Expr::Select { diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index 87149c159ab..424f95348e4 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -83,6 +83,20 @@ pub(super) fn expr_signedness_with_return_types( ) } } + // The internal zero-divisor arm represents an unknown value of the + // guarded operation's type, not a separate source-language operand. + Expr::Mux { + then_expr, + else_expr, + .. + } if matches!(&**then_expr, Expr::Literal(text) if text == crate::DIV_ZERO_UNKNOWN_LITERAL) => { + expr_signedness_with_return_types( + else_expr, + identifiers, + functions, + function_return_types, + ) + } Expr::Mux { then_expr, else_expr, diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index 611fb4327de..28f734e4535 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -1690,3 +1690,72 @@ endmodule (assert_eq mul 0xfffffffc) (assert_eq div 0) (assert_eq dynamic_mul 0xfffffff0)) + +; IEEE 1800-2023 6.24.1: a size cast preserves operand signedness. +(case casts_preserve_guarded_division_signedness + (source "guarded_division_casts.sv" #" + module Top #(parameter DIVISOR = 2)( + input logic signed [12:0] a, + input logic signed [3:0] b, + input logic [3:0] u, + output logic [31:0] quotient, remainder, mixed, narrowed, nested, + output logic [31:0] parameter_quotient, typed, unsigned_quotient, signed_mixed); + assign quotient = 32'(a / b); + assign remainder = 32'(a % b); + assign mixed = 32'(a / u); + assign narrowed = 4'(a / b); + assign nested = 32'((a / b) / b); + assign parameter_quotient = 32'(a / DIVISOR); + assign typed = int'(a / b); + assign unsigned_quotient = unsigned'(a / b); + assign signed_mixed = signed'(a / u); + endmodule + "#) + (top Top) + (modify (set a 0x1ff3) (set b 2) (set u 2)) + (assert_eq quotient 0xfffffffa) + (assert_eq remainder 0xffffffff) + (assert_eq mixed 4089) + (assert_eq narrowed 0xfffffffa) + (assert_eq nested 0xfffffffd) + (assert_eq parameter_quotient 0xfffffffa) + (assert_eq typed 0xfffffffa) + (assert_eq unsigned_quotient 8186) + (assert_eq signed_mixed 4089) + (modify (set u 1)) + (assert_eq signed_mixed 0xfffffff3) + (modify (set u 2)) + (modify (set a 13) (set b 0xe)) + (assert_eq quotient 0xfffffffa) + (assert_eq remainder 1) + (assert_eq mixed 6) + (assert_eq narrowed 0xfffffffa) + (assert_eq nested 3) + (assert_eq parameter_quotient 6) + (assert_eq typed 0xfffffffa) + (assert_eq unsigned_quotient 8186) + (assert_eq signed_mixed 6)) + +(case casts_preserve_guarded_division_unknowns + (four_state) + (source "guarded_division_unknowns.sv" #" + module Top(input logic signed [12:0] a, input logic signed [3:0] b, + output logic [31:0] quotient, remainder, nested, + output int two_state); + assign quotient = 32'(a / b); + assign remainder = 32'(a % b); + assign nested = 32'((a / b) / b); + assign two_state = int'(a / b); + endmodule + "#) + (top Top) + (modify (set a 0x1ff3) (set b 2)) + (assert_eq quotient 0xfffffffa) + (assert_eq remainder 0xffffffff) + (assert_eq nested 0xfffffffd) + (assert_eq two_state 0xfffffffa) + (modify (set b 0)) + (assert_eq quotient (fourstate 0xffffffff 0xffffffff)) + (assert_eq remainder (fourstate 0xffffffff 0xffffffff)) + (assert_eq nested (fourstate 0xffffffff 0xffffffff)) + (assert_eq two_state 0)) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 1d1990bb5a4..5be2afa0491 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -403,6 +403,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) processes: Vec>, pub(crate) process_origins: Vec, pub(crate) watches: Vec>, + pub(crate) occurrence_probes: Vec<(celox_design::VarAtomBase, AbsoluteAddr)>, pub(crate) wait_sites: Vec>, pub(crate) nba_sites: Vec>, pub(crate) host_request_sites: Vec>, @@ -517,6 +518,7 @@ impl NativeProgramImage { processes: self.runtime_schema.processes.clone(), process_origins: self.runtime_schema.process_origins.clone(), watches: self.runtime_schema.watches.clone(), + occurrence_probes: self.runtime_schema.occurrence_probes.clone(), wait_sites: self.runtime_schema.wait_sites.clone(), nba_sites: self.runtime_schema.nba_sites.clone(), host_request_sites: self.runtime_schema.host_request_sites.clone(), @@ -2412,6 +2414,7 @@ fn compile_program( processes: sir.runtime().runtime_schema.processes.clone(), process_origins: sir.runtime().runtime_schema.process_origins.clone(), watches: sir.runtime().runtime_schema.watches.clone(), + occurrence_probes: sir.runtime().runtime_schema.occurrence_probes.clone(), wait_sites: sir.runtime().runtime_schema.wait_sites.clone(), nba_sites: sir.runtime().runtime_schema.nba_sites.clone(), host_request_sites: sir.runtime().runtime_schema.host_request_sites.clone(), diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 3e1bc73d563..ff7cbbfbb6e 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -44,7 +44,10 @@ pub struct NativeProgramInstance { shared: Arc, backend: NativeBackend, runtime_event_read_seq: u64, - comb_observer_snapshots: Vec>, + comb_observer_snapshots: Vec, + /// Storage reused for the next snapshot. + comb_observer_scratch: Vec, + comb_observer_reads: crate::comb_activation::ObserverReads, comb_observer_initial_eval: bool, forced_values: crate::HashMap, } @@ -63,11 +66,17 @@ impl NativeProgramInstance { .map_err(NativeProgramLoadError::Attach)?, ); let backend = NativeBackend::from_shared(Arc::clone(&shared)); + let comb_observer_reads = crate::comb_activation::ObserverReads::new( + &backend, + &shared.program_image().runtime_schema().comb_observers, + ); let mut instance = Self { shared, backend, runtime_event_read_seq: 0, comb_observer_snapshots: Vec::new(), + comb_observer_scratch: Vec::new(), + comb_observer_reads, comb_observer_initial_eval: true, forced_values: crate::HashMap::default(), }; @@ -421,37 +430,29 @@ impl NativeProgramInstance { return result; } - let before = self.snapshot_all_comb_observers(); - let active_before = before - .iter() - .zip(&self.comb_observer_snapshots) - .map(|(current, previous)| current != previous) - .collect::>(); - let mut active_sites = vec![false; self.runtime_schema().runtime_event_sites.len()]; - for (observer, active) in self - .runtime_schema() - .comb_observers - .iter() - .zip(active_before) - { - if active || self.comb_observer_initial_eval { - for group_observer in &self.runtime_schema().comb_observers { - if group_observer.activation_group == observer.activation_group { - active_sites[group_observer.site_id as usize] = true; - } - } - } - } + let mut snapshots = std::mem::take(&mut self.comb_observer_scratch); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); + let active_sites = crate::comb_activation::active_sites( + &self.runtime_schema().comb_observers, + self.runtime_schema().runtime_event_sites.len(), + &self.comb_observer_reads, + &snapshots, + &self.comb_observer_snapshots, + self.comb_observer_initial_eval, + ); self.backend.set_comb_capture_event_enabled(&active_sites); let result = self.eval_comb_backend(); - let after = self.snapshot_all_comb_observers(); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); self.backend.set_comb_capture_event_enabled(&vec![ false; self.runtime_schema() .runtime_event_sites .len() ]); - self.comb_observer_snapshots = after; + self.comb_observer_scratch = + std::mem::replace(&mut self.comb_observer_snapshots, snapshots); self.comb_observer_initial_eval = false; self.check_fatal_events_since(start_seq, context)?; result @@ -529,36 +530,7 @@ impl NativeProgramInstance { Ok(()) } - fn snapshot_all_comb_observers(&self) -> Vec> { - self.runtime_schema() - .comb_observers - .iter() - .map(|observer| { - observer - .sensitivity - .iter() - .map(|atom| { - let signal = self.backend.resolve_signal(&atom.id); - let (value, mask) = if signal.is_4state { - self.backend.get_four_state(signal) - } else { - (self.backend.get(signal), BigUint::default()) - }; - ( - slice_biguint(&value, atom.access.lsb, atom.access.msb), - slice_biguint(&mask, atom.access.lsb, atom.access.msb), - ) - }) - .collect() - }) - .collect() - } -} - -fn slice_biguint(value: &BigUint, least: usize, most: usize) -> BigUint { - if most < least { - return BigUint::default(); + fn snapshot_all_comb_observers(&self) -> Vec { + self.comb_observer_reads.take(&self.backend) } - let width = most - least + 1; - (value >> least) & ((BigUint::from(1u8) << width) - BigUint::from(1u8)) } diff --git a/crates/celox/src/comb_activation.rs b/crates/celox/src/comb_activation.rs new file mode 100644 index 00000000000..293f2e5eecf --- /dev/null +++ b/crates/celox/src/comb_activation.rs @@ -0,0 +1,185 @@ +//! Activation of combinational observers: a process is observed again when +//! the values of its sensitivity, or the occurrence counters of those +//! values, differ from their last snapshot. +//! +//! The reads are resolved once. A range of a signal of at most 64 bits is +//! read as a word; only wider signals go through `BigUint`. + +use num_bigint::BigUint; + +use crate::backend::{SimBackend, get_byte_size}; +use celox_design::RuntimeCombObserver; +use celox_runtime::{AbsoluteAddr, SignalRef}; + +#[derive(Clone, Debug)] +enum Read { + /// Bits `lsb..lsb + width` of a signal of at most 64 bits, with its + /// mask plane when the signal is held in four-state form. + Word { + value: SignalRef, + mask: Option, + lsb: usize, + bits: u64, + }, + Wide { + signal: SignalRef, + lsb: usize, + msb: usize, + }, + Counter(SignalRef), +} + +/// The resolved reads of every observer, in schema order. +#[derive(Clone, Debug, Default)] +pub(crate) struct ObserverReads { + observers: Vec>, + /// Each observer's activation group, numbered densely from 0. + groups: Vec, + group_count: usize, +} + +/// The values one observer's reads returned. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct ObserverSnapshot { + words: Vec, + wide: Vec<(BigUint, BigUint)>, +} + +impl ObserverReads { + pub(crate) fn new( + backend: &B, + observers: &[RuntimeCombObserver], + ) -> Self { + let four_state = backend.layout().four_state; + let reads = observers + .iter() + .map(|observer| { + observer + .sensitivity + .iter() + .map(|atom| { + let signal = backend.resolve_signal(&atom.id); + let (lsb, msb) = (atom.access.lsb, atom.access.msb); + if signal.width > 64 || signal.array_layout.is_some() || msb < lsb { + return Read::Wide { signal, lsb, msb }; + } + let mask = (four_state && signal.is_4state).then(|| SignalRef { + offset: signal.offset + get_byte_size(signal.width), + width: signal.width, + is_4state: false, + array_layout: None, + }); + Read::Word { + value: signal, + mask, + lsb, + bits: u64::MAX >> (63 - (msb - lsb)), + } + }) + .chain( + observer + .occurrence_counters + .iter() + .map(|counter| Read::Counter(backend.resolve_signal(counter))), + ) + .collect() + }) + .collect(); + let mut numbers = crate::HashMap::default(); + let groups = observers + .iter() + .map(|observer| { + let next = numbers.len(); + *numbers.entry(observer.activation_group).or_insert(next) + }) + .collect(); + Self { + observers: reads, + groups, + group_count: numbers.len(), + } + } + + /// Read every observer into `snapshots`, reusing its storage. + pub(crate) fn snapshot( + &self, + backend: &B, + snapshots: &mut Vec, + ) { + snapshots.resize_with(self.observers.len(), Default::default); + for (reads, snapshot) in self.observers.iter().zip(snapshots.iter_mut()) { + snapshot.words.clear(); + snapshot.wide.clear(); + for read in reads { + match *read { + Read::Word { + value, + mask, + lsb, + bits, + } => { + let word = |signal| (backend.get_as::(signal) >> lsb) & bits; + snapshot.words.push(word(value)); + if let Some(mask) = mask { + snapshot.words.push(word(mask)); + } + } + Read::Wide { signal, lsb, msb } => { + let (value, mask) = if signal.is_4state { + backend.get_four_state(signal) + } else { + (backend.get(signal), BigUint::default()) + }; + snapshot + .wide + .push((slice(&value, lsb, msb), slice(&mask, lsb, msb))); + } + Read::Counter(counter) => snapshot + .words + .push(u64::from(backend.get_as::(counter))), + } + } + } + } + + /// A snapshot of every observer. + pub(crate) fn take(&self, backend: &B) -> Vec { + let mut snapshots = Vec::new(); + self.snapshot(backend, &mut snapshots); + snapshots + } +} + +fn slice(value: &BigUint, lsb: usize, msb: usize) -> BigUint { + if msb < lsb { + return BigUint::default(); + } + let width = msb - lsb + 1; + (value >> lsb) & ((BigUint::from(1u8) << width) - 1u8) +} + +/// The event sites whose observers are active: an observer whose snapshot +/// differs from the last one, or every observer at the first evaluation, +/// activates the sites of its activation group. +pub(crate) fn active_sites( + observers: &[RuntimeCombObserver], + site_count: usize, + reads: &ObserverReads, + now: &[ObserverSnapshot], + last: &[ObserverSnapshot], + initial: bool, +) -> Vec { + let mut active_groups = vec![false; reads.group_count]; + for (index, &group) in reads.groups.iter().enumerate() { + if initial || now.get(index) != last.get(index) { + active_groups[group] = true; + } + } + let mut active_sites = vec![false; site_count]; + for (observer, &group) in observers.iter().zip(&reads.groups) { + if active_groups[group] { + active_sites[observer.site_id as usize] = true; + } + } + active_sites +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 0eea3828822..ece0f5cb4e0 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -9,6 +9,8 @@ mod backend; #[cfg(all(feature = "arm64-codegen", feature = "x86_64-codegen"))] compile_error!("arm64-codegen and x86_64-codegen cannot be enabled together"); #[cfg(feature = "host-runtime")] +mod comb_activation; +#[cfg(feature = "host-runtime")] mod component; #[cfg(feature = "host-runtime")] pub use component::{ diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 9651f481f31..2323e2c23b0 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -144,7 +144,10 @@ mod host { pub(crate) component_simulation: Option>, runtime_event_read_seq: Arc, runtime_event_drain_active: Arc, - pub(super) comb_observer_snapshots: Vec>, + pub(super) comb_observer_snapshots: Vec, + /// Storage reused for the next snapshot. + comb_observer_scratch: Vec, + comb_observer_reads: crate::comb_activation::ObserverReads, pub(super) comb_observer_initial_eval: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, @@ -374,21 +377,6 @@ mod host { } } - fn mask_width(value: BigUint, width: usize) -> BigUint { - if width == 0 { - BigUint::from(0u8) - } else { - value & ((BigUint::from(1u8) << width) - BigUint::from(1u8)) - } - } - - fn slice_biguint(value: &BigUint, lsb: usize, msb: usize) -> BigUint { - if msb < lsb { - return BigUint::from(0u8); - } - mask_width(value >> lsb, msb - lsb + 1) - } - fn write_bits_to_memory(mem: &mut [u8], dst_bit_offset: usize, bit_width: usize, src: &[u8]) { write_bits_to_memory_from(mem, dst_bit_offset, bit_width, src, 0); } @@ -862,6 +850,10 @@ mod host { celox_runtime::build_derived_tick_plans(&backend, &schedule); let event_edges = celox_runtime::build_event_edges(&backend, &schedule.events, &schedule.kinds); + let comb_observer_reads = crate::comb_activation::ObserverReads::new( + &backend, + &program.runtime_schema.comb_observers, + ); let mut sim = Self { backend, program, @@ -880,6 +872,8 @@ mod host { runtime_event_read_seq: Arc::new(AtomicU64::new(0)), runtime_event_drain_active: Arc::new(AtomicBool::new(false)), comb_observer_snapshots: Vec::new(), + comb_observer_scratch: Vec::new(), + comb_observer_reads, comb_observer_initial_eval: true, checkpoint_fingerprint: std::sync::OnceLock::new(), state_schema: std::sync::OnceLock::new(), @@ -1535,33 +1529,21 @@ mod host { return (result, events); } - let before = self.snapshot_all_comb_observers(); - let active_before: Vec = before - .iter() - .zip(&self.comb_observer_snapshots) - .map(|(now, prev)| now != prev) - .collect(); - let mut active_sites = - vec![false; self.program.runtime_schema.runtime_event_sites.len()]; - for (observer, is_active) in self - .program - .runtime_schema - .comb_observers - .iter() - .zip(active_before.iter().copied()) - { - if is_active || self.comb_observer_initial_eval { - let group = observer.activation_group; - for group_observer in &self.program.runtime_schema.comb_observers { - if group_observer.activation_group == group { - active_sites[group_observer.site_id as usize] = true; - } - } - } - } + let mut snapshots = std::mem::take(&mut self.comb_observer_scratch); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); + let active_sites = crate::comb_activation::active_sites( + &self.program.runtime_schema.comb_observers, + self.program.runtime_schema.runtime_event_sites.len(), + &self.comb_observer_reads, + &snapshots, + &self.comb_observer_snapshots, + self.comb_observer_initial_eval, + ); self.backend.set_comb_capture_event_enabled(&active_sites); let eval_result = self.backend.eval_comb(); - let after = self.snapshot_all_comb_observers(); + self.comb_observer_reads + .snapshot(&self.backend, &mut snapshots); let runtime_events = self.peek_backend_runtime_events_from(runtime_event_start_seq); self.backend.set_comb_capture_event_enabled(&vec![ false; @@ -1570,35 +1552,16 @@ mod host { .runtime_event_sites .len() ]); - self.comb_observer_snapshots = after; + self.comb_observer_scratch = + std::mem::replace(&mut self.comb_observer_snapshots, snapshots); self.comb_observer_initial_eval = false; (eval_result, runtime_events) } - pub(super) fn snapshot_all_comb_observers(&self) -> Vec> { - self.program - .runtime_schema - .comb_observers - .iter() - .map(|observer| { - observer - .sensitivity - .iter() - .map(|atom| { - let signal = self.backend.resolve_signal(&atom.id); - let (value, mask) = if signal.is_4state { - self.backend.get_four_state(signal) - } else { - (self.backend.get(signal), BigUint::default()) - }; - ( - slice_biguint(&value, atom.access.lsb, atom.access.msb), - slice_biguint(&mask, atom.access.lsb, atom.access.msb), - ) - }) - .collect() - }) - .collect() + pub(super) fn snapshot_all_comb_observers( + &self, + ) -> Vec { + self.comb_observer_reads.take(&self.backend) } fn fatal_comb_capture_error(&self, events: &[RawRuntimeEvent]) -> Option { diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 569d454a274..29d48e87623 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -9,7 +9,6 @@ //! state header in front of it holds host pointers and is never copied. use celox_state_layout::STATE_HEADER_SIZE; -use num_bigint::BigUint; use super::host::Simulator; use crate::backend::SimBackend; @@ -98,7 +97,7 @@ fn state_range(backend: &B) -> std::ops::Range { #[derive(Clone)] pub struct Checkpoint { image: StateImage, - comb_observer_snapshots: Vec>, + comb_observer_snapshots: Vec, comb_observer_initial_eval: bool, /// Whether the design had finished a timed simulation. frozen: bool, diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index 425858e0afb..04f2499e68f 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -1,4 +1,12 @@ sv_backends! { + fn casts_preserve_guarded_division_signedness(sim) { + @case "operators::casts_preserve_guarded_division_signedness"; + } + + fn casts_preserve_guarded_division_unknowns(sim) { + @case "operators::casts_preserve_guarded_division_unknowns"; + } + fn preserves_power_signedness_in_arithmetic(sim) { @case "operators::preserves_power_signedness_in_arithmetic"; } diff --git a/crates/celox/tests/sv_update_events.rs b/crates/celox/tests/sv_update_events.rs new file mode 100644 index 00000000000..86eb3f3aa72 --- /dev/null +++ b/crates/celox/tests/sv_update_events.rs @@ -0,0 +1,166 @@ +#![cfg(feature = "systemverilog")] +//! Every change of a variable is an update event that schedules the +//! processes sensitive to it (IEEE 1800-2023 4.3, 4.5), also a change that +//! a later write of the same time slot undoes. Nonblocking updates are +//! performed one by one, in the order they were scheduled (10.4.2). +use std::path::Path; + +macro_rules! update_events { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!( + "`timescale 1ns/1ns\nmodule Top;\n bit a, c;\n int count;\n{body}\nendmodule" + ); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("update_events.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + /// The `$display`s of `sim` until `time`. + fn displays(sim: &mut celox::Simulation, time: u64) -> usize { + sim.run_until(time).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter(|event| matches!(event, celox::RuntimeEvent::Display { .. })) + .count() + } + + /// The assertion failures of `sim` until `time`. + fn failures(sim: &mut celox::Simulation, time: u64) -> usize { + sim.run_until(time).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter(|event| matches!(event, celox::RuntimeEvent::AssertContinue { .. })) + .count() + } + + fn value(sim: &mut celox::Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + } + + #[test] + fn blocking_writes_that_restore_a_source_reexecute_always_comb() { + let mut sim = simulation( + " always_comb if (!a) $display(\"low\");\n \ + initial begin #1; a = 1; a = 0; end", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn kernel_nonblocking_updates_that_restore_a_source_reexecute_always_comb() { + let mut sim = simulation( + " always_comb if (!a) $display(\"low\");\n \ + initial begin #1; a <= 1; a <= 0; end", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn flip_flop_nonblocking_updates_that_restore_a_source_reexecute_always_comb() { + let mut sim = simulation( + " always_ff @(posedge c) begin a <= 1; a <= 0; end\n \ + always_comb if (!a) $display(\"low\");\n \ + initial #1 c = 1;", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn immediate_assertions_in_always_comb_report_each_reexecution() { + let mut sim = simulation( + " always_comb assert (a) else $error(\"a low\");\n \ + initial begin #1; a = 1; a = 0; end", + ); + assert_eq!(failures(&mut sim, 0), 1); + assert_eq!(failures(&mut sim, 1), 1); + } + + #[test] + fn flip_flop_nonblocking_updates_that_restore_a_signal_are_events() { + let mut sim = simulation( + " always @(posedge c) begin a <= 1; a <= 0; end\n \ + initial begin @(a) count = count + 1; end\n \ + always @(posedge a) count = count + 10;\n \ + initial #1 c = 1;", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "count"), 11); + assert_eq!(value(&mut sim, "a"), 0); + } + + #[test] + fn flip_flop_blocking_writes_that_restore_a_signal_are_events() { + let mut sim = simulation( + " always @(posedge c) begin a = 1; a = 0; end\n \ + initial begin @(a) count = count + 1; end\n \ + initial #1 c = 1;", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "count"), 1); + } + + #[test] + fn updates_that_keep_the_value_are_no_events() { + let mut sim = simulation( + " always_ff @(posedge c) begin a <= 0; a <= 0; end\n \ + always_comb if (!a) $display(\"low\");\n \ + initial begin @(a) count = count + 1; end\n \ + initial begin #1; c = 1; #1; a = 0; a = 0; end", + ); + assert_eq!(displays(&mut sim, 0), 1); + assert_eq!(displays(&mut sim, 2), 0); + assert_eq!(value(&mut sim, "count"), 0); + } + + #[test] + fn updates_in_exclusive_branches_are_one_event() { + let mut sim = simulation( + " always_ff @(posedge c) if (count == 0) a <= 1; else a <= 0;\n \ + always_comb if (a) $display(\"high\");\n \ + initial #1 c = 1;", + ); + assert_eq!(displays(&mut sim, 0), 0); + assert_eq!(displays(&mut sim, 1), 1); + } + + #[test] + fn flip_flop_pulses_trigger_domains_without_processes() { + // No process: the batch round checks the counted signal. + let source = "module Top(input bit c);\n \ + bit d;\n int count;\n \ + always_ff @(posedge c) begin d <= 1; d <= 0; end\n \ + always_ff @(posedge d) count <= count + 1;\n\ + endmodule"; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("pulse.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.schedule("c", 1, 1).unwrap(); + sim.schedule("c", 2, 0).unwrap(); + sim.schedule("c", 3, 1).unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "count"), 2); + assert_eq!(value(&mut sim, "d"), 0); + } + } + }; +} + +update_events!(interpreter, build_interpreter); +update_events!(cranelift, build); +#[cfg(target_arch = "x86_64")] +update_events!(native, build_native); +update_events!(wasm, build_wasm);