diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 5e45cf13916..9a6ccd0d0c6 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1058,6 +1058,9 @@ pub struct SchedulerSchema { /// The event signals a host periodic clock may drive inside the /// scheduler's slots, in the order of its clock slots. pub clocks: Vec, + /// Per process kernel, the event signals it writes, as indices into + /// [`Self::events`]; empty for a kernel the scheduler does not run. + pub kernel_events: Vec>, } impl SchedulerSchema { @@ -1069,6 +1072,7 @@ impl SchedulerSchema { fallback: self.fallback, events: self.events.into_iter().map(&mut map).collect(), clocks: self.clocks.into_iter().map(map).collect(), + kernel_events: self.kernel_events, } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 7682ec5627d..aab80fca1fd 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2072,6 +2072,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( fallback: Vec::new(), events: Vec::new(), clocks: Vec::new(), + kernel_events: Vec::new(), }); // The runtime reads counters, the signals waits watch and staged // nonblocking values directly; no unit loads a wait's signal. diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index b9a0e39311b..4d8e7f255e0 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -77,6 +77,10 @@ pub(crate) struct SchedulerRefs { /// The event id and signal of each host clock the scheduler may run, /// in the order of its clock slots. pub(crate) clocks: Vec<(usize, SignalRef)>, + /// Per process kernel, the bits of `levels` of the events it writes. + pub(crate) kernel_events: Vec, + /// Per clock slot, the bit of `levels` of its event. + pub(crate) clock_events: Vec, pub(crate) clock_next: SignalRef, pub(crate) clock_period: SignalRef, pub(crate) clock_value: SignalRef, @@ -365,6 +369,24 @@ impl ResolvedSchedule { .iter() .map(|event| backend.resolve_event_opt(event).map(|event| event.id())) .collect::>()?, + kernel_events: (0..scheduler.fallback.len()) + .map(|index| { + scheduler + .kernel_events + .get(index) + .into_iter() + .flatten() + .fold(0, |mask, &bit| mask | 1 << bit) + }) + .collect(), + clock_events: scheduler + .clocks + .iter() + .map(|clock| { + let bit = scheduler.events.iter().position(|event| event == clock)?; + Some(1 << bit) + }) + .collect::>()?, clocks: scheduler .clocks .iter() diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index aa78df40bca..5fff1ceb3e2 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -75,17 +75,19 @@ impl SimulationState { || !pending.ready.is_empty() || !pending.inactive.is_empty() || !pending.nba_queue.is_empty() - || pending - .waiters - .iter() - .any(|(process, _)| scheduler.waits.get(process).is_none_or(Option::is_none)) + || pending.waiters.iter().any(|(process, _)| { + scheduler.waits.get(process).is_none_or(Option::is_none) + || self.writes_observed(scheduler, process) + }) { return None; } let mut first = u64::MAX; let mut other = u64::MAX; for &Reverse((time, process)) in self.process_wakeups.iter() { - if scheduler.wake.get(process).is_some_and(Option::is_some) { + if scheduler.wake.get(process).is_some_and(Option::is_some) + && !self.writes_observed(scheduler, process) + { first = first.min(time); } else { other = other.min(time); @@ -100,8 +102,10 @@ impl SimulationState { let clocks = &self.scheduler.clocks; let compiled = compiled_clocks(scheduler, queue, clocks); for event in queue { - if clock_slot(scheduler, event, clocks).is_some_and(|bit| compiled >> bit & 1 != 0) - { + if clock_slot(scheduler, event, clocks).is_some_and(|bit| { + compiled >> bit & 1 != 0 + && scheduler.clock_events[bit] & self.observed_events == 0 + }) { first = first.min(event.time); } else { other = other.min(event.time); @@ -126,6 +130,15 @@ impl SimulationState { }) } + /// Whether `process` may change an event the host observes, so that + /// its slots run in the reference loop. + fn writes_observed(&self, scheduler: &SchedulerRefs, process: usize) -> bool { + scheduler + .kernel_events + .get(process) + .is_some_and(|&events| events & self.observed_events != 0) + } + /// Run the compiled scheduler for the slots up to `limit`. Returns, like /// [`Self::step_until`], the time of the last slot run. pub(super) fn run_compiled( @@ -393,6 +406,10 @@ impl SimulationState { } } executor.try_finish_timed_step(now)?; + // What the host writes after the slot is an update of its time. + if executor.take_slot_writes() { + self.host_pending = true; + } Ok(now) } } diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index e2dca455e4c..206b2f1cdd0 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -81,6 +81,23 @@ pub trait HostBoundary: UnitExecutor { output } + /// Called in every round when its processes and scheduled values have + /// run and its flip-flop domains are about to evaluate: the round's + /// edges are in state, and no domain has committed. Returns whether the + /// host wrote state; the round then settles it before the domains read + /// it. Writes to signals a wait watches are logged as in + /// [`Self::take_host_writes`]. + fn before_domains(&mut self, _timestamp: u64) -> Result { + Ok(false) + } + + /// Whether the host wrote state in [`Self::try_finish_timed_step`] + /// since the last call. The writes are updates of that slot's time: the + /// next step settles them there. + fn take_slot_writes(&mut self) -> bool { + false + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 7523e231da0..05d3f8e0ecb 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -27,7 +27,7 @@ pub use wait::{Baseline, Waiter, Waiters}; use self::round::Round; use crate::{ - SimulatorErrorCode, + SignalRef, SimulatorErrorCode, backend::SimBackend, schedule::ResolvedSchedule, scheduler::{Scheduler, SimEvent}, @@ -161,6 +161,10 @@ pub struct SimulationState { slot_passes: u64, /// The loop that runs time slots, and the slots each loop ran. stats: SchedulerStats, + /// The bits of the compiled scheduler's events whose changes the host + /// observes inside a slot: the kernels and host clocks that write them + /// run in the reference loop. + observed_events: u64, } impl SimulationState { @@ -213,6 +217,7 @@ impl SimulationState { return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, stats: SchedulerStats::default(), + observed_events: 0, }; state.stats.kernels = (0..state.model.processes.len()) .map(|index| match state.model.kernel_fallback.get(index) { @@ -341,6 +346,22 @@ impl SimulationState { &self.stats } + /// The signals whose changes the host observes inside a time slot (see + /// [`HostBoundary::before_domains`]). The slots in which a kernel or + /// host clock of the compiled scheduler may change an observed event + /// signal run in the reference loop, where the host sees the change + /// before any domain commits; the other kernels' slots stay compiled. + pub fn set_observed_signals(&mut self, signals: impl IntoIterator) { + let Some(scheduler) = &self.model.scheduler else { + return; + }; + self.observed_events = signals + .into_iter() + .filter_map(|signal| self.model.signal_to_id.get(&signal)) + .filter_map(|event| scheduler.events.iter().position(|id| id == event)) + .fold(0, |mask, bit| mask | 1 << bit); + } + /// [`Self::step_until`], showing the step to `observer`. An error of /// the observer replaces the step's result. pub fn step_until_observed( diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 813b446c1a2..630f3fdd904 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -536,6 +536,15 @@ impl SimulationState { loop { let mut any_new_outer_loop_trigger = false; let mut newly_triggered = Vec::new(); + // The host sees the wave's edges before its domains commit, and + // its writes are in state before they evaluate. + if executor.before_domains(current_time)? { + for (signal, value) in executor.take_host_writes() { + self.observe_host_write(signal, &value); + } + executor.eval_comb()?; + self.observe_driven(executor.backend()); + } loop { let mut any_new_sequential_trigger = false; diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index f5e2bde7145..a6fee8795ab 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -191,6 +191,10 @@ impl SimulationState { self.step_round(executor, current_time, Vec::new(), ready, false)?; } executor.try_finish_timed_step(current_time)?; + // What the host writes after the slot is an update of its time. + if executor.take_slot_writes() { + self.host_pending = true; + } Ok(()) } diff --git a/crates/celox/examples/sched_bench.rs b/crates/celox/examples/sched_bench.rs index 2ca280dd104..332dccb682a 100644 --- a/crates/celox/examples/sched_bench.rs +++ b/crates/celox/examples/sched_bench.rs @@ -1,6 +1,6 @@ //! Timed-scheduler overhead benchmark for instruction-count comparisons. //! -//! Usage: `sched_bench [default|reference|compiled] [native|interp]` +//! Usage: `sched_bench [default|reference|compiled] [native|interp] [observe=]` //! //! Every variant clocks the same 64 registers `rK <= rK + (seed ^ K)`: //! @@ -17,7 +17,9 @@ //! //! The optional third argument selects the timed scheduler (hidden builder //! option), by default the library's; the fourth the backend, by default the -//! host's native one. +//! host's native one. With a fifth, `observe=`, a timed variant runs +//! with a slot observer that counts the changes of `` at the end of +//! every slot, as a VPI value-change callback does. //! //! The scheduler's cost per cycle is the difference of the whole-program //! instruction counts of two runs, which cancels compilation: @@ -138,10 +140,18 @@ fn main() { Some(other) => panic!("unknown scheduler {other}: expected reference or compiled"), }; let builder = celox::Simulation::from_sv_sources(sources, "Top").scheduler_mode(mode); + let observed = args + .get(5) + .map(|arg| arg.strip_prefix("observe=").expect("observe=")); if interpreter { - run(builder.build_interpreter().unwrap(), variant, cycles) + run( + builder.build_interpreter().unwrap(), + variant, + cycles, + observed, + ) } else { - run(builder.build().unwrap(), variant, cycles) + run(builder.build().unwrap(), variant, cycles, observed) } }; println!("{variant} {cycles} out={out:?}"); @@ -159,12 +169,42 @@ fn tick(mut sim: celox::Simulator, cycles: u64) -> celo sim.get(out) } +/// Counts the changes of one signal at the end of every slot. +struct Changes { + signal: celox::SignalRef, + last: Option, + count: std::rc::Rc>, +} + +impl celox::SlotObserver for Changes { + fn before_domains(&mut self, _: &mut celox::SlotIo<'_, B>, _: u64) {} + + fn end_of_slot(&mut self, io: &mut celox::SlotIo<'_, B>, _: u64) { + let value = io.get(self.signal); + if self.last.as_ref() != Some(&value) { + self.count.set(self.count.get() + 1); + self.last = Some(value); + } + } +} + /// The timed variants: run `cycles` clock periods. fn run( mut sim: celox::Simulation, variant: &str, cycles: u64, + observed: Option<&str>, ) -> celox::BigUint { + let changes = std::rc::Rc::new(std::cell::Cell::new(0)); + if let Some(path) = observed { + let signal = sim.signal(path); + let observer = Changes { + signal, + last: None, + count: std::rc::Rc::clone(&changes), + }; + sim.observe_slots(Box::new(observer), &[signal]); + } if variant == "ac" { let seed = sim.signal("seed"); sim.modify(|io| io.set(seed, 7u32)).unwrap(); @@ -179,8 +219,10 @@ fn run( sim.run_until(cycles * 10).unwrap(); let stats = sim.scheduler_stats(); println!( - "compiled slots {}, kernels {:?}", - stats.compiled_slots, stats.kernels + "compiled slots {}, kernels {:?}, observed changes {}", + stats.compiled_slots, + stats.kernels, + changes.get() ); let out = sim.signal("out"); sim.get(out) diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0c95b249cc8..7278978181c 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 34; +const CONTAINER_VERSION: u16 = 35; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 28c216b193e..2ccf09b621e 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -108,7 +108,7 @@ mod host_api { }; pub use crate::debug::CompilationTraceResult; pub use crate::diagnostics::DiagnosticsOptions; - pub use crate::simulation::{Simulation, SimulationCheckpoint}; + pub use crate::simulation::{Simulation, SimulationCheckpoint, SlotObserver}; #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -169,6 +169,54 @@ mod host_api { } } + /// State access of a [`SlotObserver`] inside a time slot: reads see + /// the slot's state so far, writes are blocking writes of the host at + /// the slot's time. + pub struct SlotIo<'a, B: SimBackend = DefaultBackend> { + io: IOContext<'a, B>, + wrote: bool, + } + + impl<'a, B: SimBackend> SlotIo<'a, B> { + pub(crate) fn new(io: IOContext<'a, B>) -> Self { + Self { io, wrote: false } + } + + pub(crate) fn wrote(&self) -> bool { + self.wrote + } + + /// The stored value, with X/Z bits as their payload. + pub fn get(&self, signal: crate::SignalRef) -> crate::BigUint { + self.io.backend.get(signal) + } + + /// The stored payload and X/Z mask. + pub fn get_four_state(&self, signal: crate::SignalRef) -> (crate::BigUint, crate::BigUint) { + self.io.get_four_state(signal) + } + + pub fn set(&mut self, signal: crate::SignalRef, val: T) { + self.wrote = true; + self.io.set(signal, val); + } + + pub fn set_wide(&mut self, signal: crate::SignalRef, val: crate::BigUint) { + self.wrote = true; + self.io.set_wide(signal, val); + } + + pub fn set_four_state( + &mut self, + signal: crate::SignalRef, + val: crate::BigUint, + mask: crate::BigUint, + ) { + self.wrote = true; + self.io.set_four_state(signal, val, mask); + } + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 6287e96a9ee..ad39a81df2e 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -71,15 +71,36 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { return; }; let kernels = program.runtime.runtime_schema.processes.len(); - let (fallback, unit, events, clocks) = match Plan::new(program, &schema.slots) { - Err(reason) => (vec![Some(reason); kernels], None, Vec::new(), Vec::new()), + let (fallback, unit, events, clocks, kernel_events) = match Plan::new(program, &schema.slots) { + Err(reason) => ( + vec![Some(reason); kernels], + None, + Vec::new(), + Vec::new(), + vec![Vec::new(); kernels], + ), Ok(plan) => { let fallback = plan.fallback.clone(); // Without kernels, slots of host clocks alone. let unit = (plan.kernels.iter().any(Option::is_some) || !plan.clocks.is_empty()) .then(|| plan.generate(program, &schema.slots)); - let events = plan - .edged() + let edged = plan.edged(); + let kernel_events = plan + .kernels + .iter() + .map(|kernel| { + kernel + .iter() + .flat_map(|kernel| &kernel.writes) + .map(|event| { + edged + .binary_search(event) + .expect("the scheduler's kernels write edged events") + }) + .collect() + }) + .collect(); + let events = edged .into_iter() .map(|event| plan.events[event].signal) .collect(); @@ -88,7 +109,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { .iter() .map(|&event| plan.events[event].signal) .collect(); - (fallback, unit, events, clocks) + (fallback, unit, events, clocks, kernel_events) } }; let scheduler = program @@ -100,6 +121,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { scheduler.fallback = fallback; scheduler.events = events; scheduler.clocks = clocks; + scheduler.kernel_events = kernel_events; if let Some(unit) = unit { scheduler.unit = Some(program.sir.processes.len()); program.sir.processes.push(unit); diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index fa8d71e731d..4023e326033 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -57,6 +57,33 @@ impl std::fmt::Debug for SimulationCheckpoint { /// A timed simulation wrapper around the core logic engine. /// +/// What a host observes inside the time slots of a [`Simulation`], in +/// addition to the state between steps: changes of its signals before the +/// flip-flop domains commit, and the settled slot. +/// +/// A slot observer is how a host such as a VPI driver keeps the regions of +/// IEEE 1800-2023 4.4 inside one time slot. Its writes are blocking writes +/// of the host at the slot's time, like [`Simulation::modify`]. +pub trait SlotObserver { + /// A round of the slot has run its processes and scheduled values and + /// is about to evaluate its flip-flop domains: the round's edges are in + /// state and no nonblocking update has been made. Writes are in state + /// before the domains evaluate. + fn before_domains(&mut self, io: &mut crate::SlotIo<'_, B>, time: u64); + + /// The slot has settled: every region is empty. Writes are updates of + /// `time`, which the simulation settles there before it advances. + /// + /// This is where an observer finds the changes of signals that are not + /// among the event signals it watches: after the nonblocking updates of + /// the slot and the combinational settle that follows them. That is an + /// implementation choice, not an order the standard fixes: the observer's + /// callback and the updates the settle makes are active events of the + /// same region, which a simulator may process in any order (IEEE + /// 1800-2023 4.7). + fn end_of_slot(&mut self, io: &mut crate::SlotIo<'_, B>, time: u64); +} + /// Manages simulation time, periodic clocks, and an event queue. /// /// The default type parameter uses the host's [`crate::DefaultBackend`]. @@ -218,14 +245,27 @@ impl HostBoundary for Simulator { Ok(()) } + fn before_domains(&mut self, timestamp: u64) -> Result { + Ok(!self.frozen + && self.show_slot(timestamp, |observer, io, time| { + observer.before_domains(io, time) + })) + } + + fn take_slot_writes(&mut self) -> bool { + std::mem::take(&mut self.slot_writes) + } + fn compiled_slots(&self) -> celox_runtime::CompiledSlots { use celox_runtime::CompiledSlots; if self.frozen || !self.components.is_empty() || !self.backend.runs_compiled_scheduler() { return CompiledSlots::None; } - // Waveforms record, and the heap collects, at every slot boundary. + // Waveforms record, the heap collects and a slot observer looks at + // every slot boundary. let vcd = &self.sv_vcd; - if self.vcd_writer.is_some() + if self.slot_observer.is_some() + || self.vcd_writer.is_some() || vcd.path.is_some() || vcd.started.is_some() || vcd.pending @@ -254,7 +294,35 @@ impl HostBoundary for Simulator { })?; self.dirty = false; self.try_dump_unless_rewound(timestamp) - .map_err(|error| Halt::Error(vcd_dump_runtime_error(error))) + .map_err(|error| Halt::Error(vcd_dump_runtime_error(error)))?; + if !self.frozen { + self.slot_writes |= self.show_slot(timestamp, |observer, io, time| { + observer.end_of_slot(io, time) + }); + } + Ok(()) + } +} + +impl Simulator { + /// Show the slot observer, if any, the state at `time`. Returns whether + /// it wrote. + fn show_slot( + &mut self, + time: u64, + show: impl FnOnce(&mut dyn SlotObserver, &mut crate::SlotIo<'_, B>, u64), + ) -> bool { + let Some(observer) = self.slot_observer.as_deref_mut() else { + return false; + }; + let mut io = crate::SlotIo::new(crate::IOContext { + backend: &mut self.backend, + watch: &mut self.host_watch, + }); + show(observer, &mut io, time); + let wrote = io.wrote(); + self.dirty |= wrote; + wrote } } @@ -528,6 +596,31 @@ impl Simulation { Ok(()) } + /// Show every time slot to `observer`, which watches `signals`. + /// + /// The slots in which a compiled process kernel or host clock may change + /// an event signal among `signals` run in the reference loop, where + /// [`SlotObserver::before_domains`] sees the change before any domain + /// commits; the other kernels' slots stay compiled, one slot per run so + /// that [`SlotObserver::end_of_slot`] sees each of them. Changes of other + /// signals are the observer's to find, at either point. A differential + /// simulation stops checking: the shadow does not see the observer's + /// writes. + pub fn observe_slots(&mut self, observer: Box>, signals: &[SignalRef]) { + self.simulator.slot_observer = Some(observer); + self.state.set_observed_signals(signals.iter().copied()); + if self.shadow.take().is_some() { + self.unchecked = Some("a slot observer writes state the shadow does not see"); + } + } + + /// Stop showing the time slots to the observer of + /// [`Self::observe_slots`], and return it. + pub fn stop_observing_slots(&mut self) -> Option>> { + self.state.set_observed_signals([]); + self.simulator.slot_observer.take() + } + /// Register a clock signal and its period, enqueuing the first edge. /// Odd periods alternate floor/ceil half periods. Periods below two /// time units use a two-unit period so both phases advance time. diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index ffccc1394d2..3d73eee6348 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -174,6 +174,10 @@ mod host { pub(crate) frozen: bool, /// Host writes a timed simulation observes one at a time. pub(crate) host_watch: celox_runtime::HostWatch, + /// What a timed simulation's host observes inside its time slots. + pub(crate) slot_observer: Option>>, + /// The slot observer wrote at the end of the last time slot. + pub(crate) slot_writes: bool, /// Runtime-event sequence up to which a timed simulation looked for /// `$finish` records. pub(crate) finish_scan_seq: u64, @@ -896,6 +900,8 @@ mod host { derived_settle, frozen: false, host_watch: Default::default(), + slot_observer: None, + slot_writes: false, finish_scan_seq: 0, finish_sites: false, event_edges, diff --git a/crates/celox/tests/slot_observer.rs b/crates/celox/tests/slot_observer.rs new file mode 100644 index 00000000000..0731e515e57 --- /dev/null +++ b/crates/celox/tests/slot_observer.rs @@ -0,0 +1,217 @@ +//! A host that observes the regions inside a time slot, as a VPI driver +//! does (#1730): edges before the flip-flop domains commit, and settled +//! slots. +#![cfg(feature = "systemverilog")] + +use std::cell::RefCell; +use std::path::Path; +use std::rc::Rc; + +use celox::{SignalRef, SimBackend, Simulation, SlotIo, SlotObserver}; + +fn simulation(source: &str) -> Simulation { + Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .build() + .unwrap() +} + +const COUNTER: &str = r#"`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] q = 0; + logic [7:0] d = 0; + logic [7:0] ticks = 0; + always #5 clk = ~clk; + always #7 ticks = ticks + 1; + always_ff @(posedge clk) q <= q + 1; +endmodule +"#; + +/// Records `watched` at every rise of `clk` before the domains commit, and +/// writes `write` there if set. +struct Edges { + clk: SignalRef, + watched: SignalRef, + write: Option, + level: u8, + seen: Rc>>, +} + +impl SlotObserver for Edges { + fn before_domains(&mut self, io: &mut SlotIo<'_, B>, time: u64) { + let level = u8::try_from(io.get(self.clk)).unwrap(); + if level == 1 && self.level == 0 { + let value = u64::try_from(io.get(self.watched)).unwrap(); + self.seen.borrow_mut().push((time, value)); + if let Some(write) = self.write { + io.set(write, time as u8); + } + } + self.level = level; + } + + fn end_of_slot(&mut self, _: &mut SlotIo<'_, B>, _: u64) {} +} + +#[test] +fn an_observed_edge_is_seen_before_the_domains_commit() { + let mut sim = simulation(COUNTER); + let seen = Rc::new(RefCell::new(Vec::new())); + let clk = sim.signal("clk"); + let observer = Edges { + clk, + watched: sim.signal("q"), + write: None, + level: 0, + seen: Rc::clone(&seen), + }; + sim.observe_slots(Box::new(observer), &[clk]); + sim.run_until(40).unwrap(); + // The rises at 5, 15, 25 and 35 see the count before their update. + assert_eq!(*seen.borrow(), vec![(5, 0), (15, 1), (25, 2), (35, 3)]); + assert_eq!(sim.get(sim.signal("q")), 4u8.into()); +} + +#[test] +fn only_the_kernels_that_write_an_observed_event_leave_compiled_slots() { + let mut plain = simulation(COUNTER); + plain.run_until(200).unwrap(); + let unobserved = plain.scheduler_stats().compiled_slots; + assert!(unobserved > 0); + + let mut sim = simulation(COUNTER); + let clk = sim.signal("clk"); + let observer = Edges { + clk, + watched: sim.signal("q"), + write: None, + level: 0, + seen: Rc::default(), + }; + sim.observe_slots(Box::new(observer), &[clk]); + sim.run_until(200).unwrap(); + let observed = sim.scheduler_stats().compiled_slots; + // The slots of `ticks` alone (7, 14, 21, ... off the clock's) stay + // compiled; those of the clock run in the reference loop. + assert!( + observed > 0 && observed < unobserved, + "{observed} of {unobserved}" + ); + assert_eq!(sim.get(sim.signal("q")), plain.get(plain.signal("q"))); + assert_eq!( + sim.get(sim.signal("ticks")), + plain.get(plain.signal("ticks")) + ); +} + +#[test] +fn a_write_before_the_domains_is_what_they_sample() { + let source = r#"`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] d = 0; + logic [7:0] q = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) q <= d; +endmodule +"#; + let mut sim = simulation(source); + let clk = sim.signal("clk"); + let d = sim.signal("d"); + let observer = Edges { + clk, + watched: d, + write: Some(d), + level: 0, + seen: Rc::default(), + }; + sim.observe_slots(Box::new(observer), &[clk]); + sim.run_until(16).unwrap(); + // The rise at 15 samples the 15 the host wrote at that edge. + assert_eq!(sim.get(sim.signal("q")), 15u8.into()); +} + +/// At the end of every slot, records changes of `watched` and sets `flag` +/// once `watched` reaches `at`. +struct Settled { + watched: SignalRef, + flag: SignalRef, + at: u64, + last: u64, + seen: Rc>>, +} + +impl SlotObserver for Settled { + fn before_domains(&mut self, _: &mut SlotIo<'_, B>, _: u64) {} + + fn end_of_slot(&mut self, io: &mut SlotIo<'_, B>, time: u64) { + let value = u64::try_from(io.get(self.watched)).unwrap(); + if value != self.last { + self.seen.borrow_mut().push((time, value)); + if value == self.at { + io.set(self.flag, 1u8); + } + } + self.last = value; + } +} + +#[test] +fn a_settled_slot_shows_every_change_and_its_writes_stay_in_the_slot() { + let source = r#"`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] q = 0; + logic flag = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) q <= q + 1; + initial begin + wait (flag); + $display("flag at %0t q=%0d", $time, q); + end +endmodule +"#; + let mut sim = simulation(source); + let seen = Rc::new(RefCell::new(Vec::new())); + let watched = sim.signal("q"); + let observer = Settled { + watched, + flag: sim.signal("flag"), + at: 2, + last: 0, + seen: Rc::clone(&seen), + }; + sim.observe_slots(Box::new(observer), &[watched]); + sim.run_until(40).unwrap(); + // Every slot of the compiled clock is seen, one per run. + assert_eq!(*seen.borrow(), vec![(5, 1), (15, 2), (25, 3), (35, 4)]); + assert!(sim.scheduler_stats().compiled_slots > 0); + // The flag written at the end of slot 15 wakes the process at 15. + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"flag at 15 q=2".to_vec() + }] + ); +} + +#[test] +fn a_differential_simulation_stops_checking_an_observed_simulation() { + let mut sim = Simulation::from_sv_sources(vec![(COUNTER, Path::new("top.sv"))], "Top") + .scheduler_mode(celox::SchedulerMode::Differential) + .build() + .unwrap(); + let watched = sim.signal("q"); + let observer = Settled { + watched, + flag: sim.signal("d"), + at: u64::MAX, + last: 0, + seen: Rc::default(), + }; + sim.observe_slots(Box::new(observer), &[watched]); + sim.run_until(40).unwrap(); + let stats = sim.scheduler_stats(); + assert_eq!(stats.checked_steps, 0); + assert!(stats.unchecked.is_some()); +}