diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 56f9142a095..db823a8e54f 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -880,10 +880,19 @@ pub struct RuntimeSchema { /// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`], /// [`SchedulerSlots::exit_arg`], [`SchedulerSlots::count`], -/// [`SchedulerSlots::current`], [`SchedulerSlots::levels`] and every [`SchedulerSlots::wake`] object. +/// [`SchedulerSlots::current`], [`SchedulerSlots::levels`], +/// [`SchedulerSlots::ready`], [`SchedulerSlots::clock_value`], +/// [`SchedulerSlots::clock_armed`] and every +/// [`SchedulerSlots::wake`] object, and of each element of +/// [`SchedulerSlots::clock_next`] and [`SchedulerSlots::clock_period`]. pub const SCHEDULER_TIME_WIDTH: usize = 64; +/// The most host periodic clocks a compiled scheduler runs: one element of +/// [`SchedulerSlots::clock_next`] and [`SchedulerSlots::clock_period`], and +/// one bit of the clock masks, per entry of [`SchedulerSchema::clocks`]. +pub const SCHEDULER_CLOCKS: usize = 64; /// Width of [`SchedulerSlots::exit`], [`SchedulerSlots::finish`], -/// [`SchedulerSlots::cont`] and every [`SchedulerSlots::waiting`] object. +/// [`SchedulerSlots::cont`], [`SchedulerSlots::dirty`] and every [`SchedulerSlots::waiting`] and +/// [`SchedulerSlots::baseline`] object. pub const SCHEDULER_FLAG_WIDTH: usize = 8; /// Hidden state objects through which a compiled scheduler and the runtime @@ -904,6 +913,9 @@ pub struct SchedulerSlots { pub finish: A, /// Where a shared combinational settle continues. pub cont: A, + /// Set when state combinational logic reads may have changed since its + /// last settle. + pub dirty: A, /// The number of time slots the run ran. pub count: A, /// The kernel running when the run returned, `u64::MAX` for none. @@ -911,11 +923,25 @@ pub struct SchedulerSlots { /// The levels of the event signals at the start of the last slot, one /// bit per event in event order. pub levels: A, + /// The kernels ready to run in the current slot, one bit per kernel in + /// kernel order. + pub ready: A, /// The time each process kernel resumes at, in kernel order, valid /// where [`Self::waiting`] is set. pub wake: Vec, - /// Whether each process kernel waits for its wake time. + /// Whether each process kernel waits for its wake time or event. pub waiting: Vec, + /// The level a kernel waiting for an event last saw its signal at. + pub baseline: Vec, + /// The time of each host clock's next edge, one element per entry of + /// [`SchedulerSchema::clocks`], valid where [`Self::clock_armed`] is set. + pub clock_next: A, + /// The period of each host clock, one element per clock. + pub clock_period: A, + /// The level each host clock's next edge sets, one bit per clock. + pub clock_value: A, + /// Whether each host clock has a next edge, one bit per clock. + pub clock_armed: A, } impl SchedulerSlots { @@ -927,11 +953,18 @@ impl SchedulerSlots { exit_arg: map(self.exit_arg), finish: map(self.finish), cont: map(self.cont), + dirty: map(self.dirty), count: map(self.count), current: map(self.current), levels: map(self.levels), + ready: map(self.ready), wake: self.wake.into_iter().map(&mut map).collect(), - waiting: self.waiting.into_iter().map(map).collect(), + waiting: self.waiting.into_iter().map(&mut map).collect(), + baseline: self.baseline.into_iter().map(&mut map).collect(), + clock_next: map(self.clock_next), + clock_period: map(self.clock_period), + clock_value: map(self.clock_value), + clock_armed: map(self.clock_armed), } } @@ -944,13 +977,20 @@ impl SchedulerSlots { &self.exit_arg, &self.finish, &self.cont, + &self.dirty, &self.count, &self.current, &self.levels, + &self.ready, + &self.clock_next, + &self.clock_period, + &self.clock_value, + &self.clock_armed, ] .into_iter() .chain(&self.wake) .chain(&self.waiting) + .chain(&self.baseline) } } @@ -967,6 +1007,9 @@ pub enum SchedulerExit { DelayOverflow = 2, /// A process suspended in a way the scheduler does not compile. Internal = 3, + /// The next edge of host clock [`SchedulerSlots::exit_arg`] overflows + /// the simulation time. + ClockOverflow = 4, } impl SchedulerExit { @@ -976,6 +1019,7 @@ impl SchedulerExit { 1 => Some(Self::Finish), 2 => Some(Self::DelayOverflow), 3 => Some(Self::Internal), + 4 => Some(Self::ClockOverflow), _ => None, } } @@ -992,9 +1036,12 @@ pub struct SchedulerSchema { /// Per process kernel, why the scheduler does not run it, or `None` when /// it does. pub fallback: Vec>, - /// The event signals the scheduler's kernels write, in the order of - /// the bits of [`SchedulerSlots::levels`]. + /// The event signals the scheduler's kernels write or its host clocks + /// may drive, in the order of the bits of [`SchedulerSlots::levels`]. pub events: Vec, + /// The event signals a host periodic clock may drive inside the + /// scheduler's slots, in the order of its clock slots. + pub clocks: Vec, } impl SchedulerSchema { @@ -1004,7 +1051,8 @@ impl SchedulerSchema { slots: self.slots.map(&mut map), unit: self.unit, fallback: self.fallback, - events: self.events.into_iter().map(map).collect(), + events: self.events.into_iter().map(&mut map).collect(), + clocks: self.clocks.into_iter().map(map).collect(), } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 93bbcbc0acf..1ec10efcc1b 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2071,6 +2071,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( unit: None, fallback: Vec::new(), events: Vec::new(), + clocks: Vec::new(), }); // The runtime reads counters, the signals waits watch and staged // nonblocking values directly; no unit loads a wait's signal. @@ -2255,7 +2256,9 @@ fn declare_scheduler_slots( ); id }; - use celox_design::{SCHEDULER_FLAG_WIDTH as FLAG, SCHEDULER_TIME_WIDTH as TIME}; + use celox_design::{ + SCHEDULER_CLOCKS as CLOCKS, SCHEDULER_FLAG_WIDTH as FLAG, SCHEDULER_TIME_WIDTH as TIME, + }; Some(celox_design::SchedulerSlots { limit: declare("limit".into(), TIME), now: declare("now".into(), TIME), @@ -2263,15 +2266,24 @@ fn declare_scheduler_slots( exit_arg: declare("exit_arg".into(), TIME), finish: declare("finish".into(), FLAG), cont: declare("cont".into(), FLAG), + dirty: declare("dirty".into(), FLAG), count: declare("count".into(), TIME), current: declare("current".into(), TIME), levels: declare("levels".into(), TIME), + ready: declare("ready".into(), TIME), wake: (0..process_count) .map(|index| declare(format!("wake[{index}]"), TIME)) .collect(), waiting: (0..process_count) .map(|index| declare(format!("waiting[{index}]"), FLAG)) .collect(), + baseline: (0..process_count) + .map(|index| declare(format!("baseline[{index}]"), FLAG)) + .collect(), + clock_next: declare("clock_next".into(), TIME * CLOCKS), + clock_period: declare("clock_period".into(), TIME * CLOCKS), + clock_value: declare("clock_value".into(), TIME), + clock_armed: declare("clock_armed".into(), TIME), }) } diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index e7d4af37815..b9a0e39311b 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -55,15 +55,52 @@ pub(crate) struct SchedulerRefs { pub(crate) limit: SignalRef, pub(crate) now: SignalRef, pub(crate) exit: SignalRef, + pub(crate) exit_arg: SignalRef, pub(crate) finish: SignalRef, pub(crate) count: SignalRef, pub(crate) current: SignalRef, pub(crate) levels: SignalRef, - /// The wake and waiting slots of each kernel the scheduler runs, by - /// process index. + pub(crate) ready: SignalRef, + /// The wake and waiting slots of each kernel the scheduler runs that + /// only delays, by process index. pub(crate) wake: Vec>, + /// The waiting and baseline slots of each kernel the scheduler runs that + /// waits for an edge, by process index. + pub(crate) waits: Vec>, + /// The number of such kernels. + pub(crate) wait_kernels: usize, + /// The bit of each kernel the scheduler runs in its ready mask: its + /// place among them in kernel order. + pub(crate) ordinals: Vec>, /// The event ids of the bits of `levels`. pub(crate) events: Vec, + /// 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)>, + pub(crate) clock_next: SignalRef, + pub(crate) clock_period: SignalRef, + pub(crate) clock_value: SignalRef, + pub(crate) clock_armed: SignalRef, +} + +impl SchedulerRefs { + /// Element `bit` of the per-clock slot `slots`. + pub(crate) fn clock_element(slots: SignalRef, bit: usize) -> SignalRef { + let width = celox_design::SCHEDULER_TIME_WIDTH; + SignalRef { + offset: slots.offset + bit * width / 8, + width, + is_4state: false, + array_layout: None, + } + } + + /// The clock slot that runs a scheduled `event` of `signal`, if any. + pub(crate) fn clock_of(&self, event: usize, signal: SignalRef) -> Option { + self.clocks + .iter() + .position(|&(id, clock)| id == event && clock == signal) + } } impl ResolvedSchedule { @@ -279,26 +316,67 @@ impl ResolvedSchedule { limit: resolve(&slots.limit), now: resolve(&slots.now), exit: resolve(&slots.exit), + exit_arg: resolve(&slots.exit_arg), finish: resolve(&slots.finish), count: resolve(&slots.count), current: resolve(&slots.current), levels: resolve(&slots.levels), - wake: slots - .wake - .iter() - .zip(&slots.waiting) - .zip(&scheduler.fallback) - .map(|((wake, waiting), fallback)| { - fallback - .is_none() - .then(|| (resolve(wake), resolve(waiting))) + ready: resolve(&slots.ready), + wake: (0..scheduler.fallback.len()) + .map(|index| { + (scheduler.fallback[index].is_none() + && model.processes[index].waits.is_empty()) + .then(|| (resolve(&slots.wake[index]), resolve(&slots.waiting[index]))) + }) + .collect(), + waits: (0..scheduler.fallback.len()) + .map(|index| { + (scheduler.fallback[index].is_none() + && !model.processes[index].waits.is_empty()) + .then(|| { + ( + resolve(&slots.waiting[index]), + resolve(&slots.baseline[index]), + ) + }) }) .collect(), + ordinals: { + let mut next = 0; + scheduler + .fallback + .iter() + .map(|fallback| { + fallback.is_none().then(|| { + next += 1; + next - 1 + }) + }) + .collect() + }, + wait_kernels: (0..scheduler.fallback.len()) + .filter(|&index| { + scheduler.fallback[index].is_none() + && !model.processes[index].waits.is_empty() + }) + .count(), events: scheduler .events .iter() .map(|event| backend.resolve_event_opt(event).map(|event| event.id())) .collect::>()?, + clocks: scheduler + .clocks + .iter() + .map(|clock| { + let event = backend.resolve_event_opt(clock)?; + Some((event.id(), resolve(clock))) + }) + .collect::>()?, + clock_next: resolve(&slots.clock_next), + clock_period: resolve(&slots.clock_period), + clock_value: resolve(&slots.clock_value), + clock_armed: resolve(&slots.clock_armed), }) }), kernel_fallback: model diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index fb98dba1379..aa78df40bca 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -2,11 +2,49 @@ //! from the reference loop, and the hand-over of the scheduling state. use std::cmp::Reverse; +use std::collections::BinaryHeap; use celox_design::SchedulerExit; -use super::{CompiledSlots, SchedulerMode, SimulationExecutor, SimulationState}; -use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; +use super::{Baseline, CompiledSlots, SchedulerMode, SimulationExecutor, SimulationState}; +use crate::{ + SimulatorErrorCode, + backend::{EventHandle, SimBackend}, + schedule::SchedulerRefs, + scheduler::{ClockDef, SimEvent}, + timing::{Halt, copy_planes}, +}; + +/// The clock slots of `scheduler` whose host clock it runs: the periodic +/// clocks with exactly one queued edge, one bit per clock slot. +fn compiled_clocks( + scheduler: &SchedulerRefs, + queue: &BinaryHeap>, + clocks: &[Option], +) -> u64 { + let mut seen = 0u64; + let mut twice = 0u64; + for event in queue { + if let Some(bit) = clock_slot(scheduler, event, clocks) { + twice |= seen & 1 << bit; + seen |= 1 << bit; + } + } + seen & !twice +} + +/// The clock slot of `scheduler` that may run the queued `event`. +fn clock_slot( + scheduler: &SchedulerRefs, + event: &SimEvent, + clocks: &[Option], +) -> Option { + let id = event.event_ref.id(); + if !event.periodic || clocks.get(id).is_none_or(Option::is_none) { + return None; + } + scheduler.clock_of(id, event.signal) +} impl SimulationState { /// Whether a compiled scheduler may run slots of this simulation. @@ -37,7 +75,10 @@ impl SimulationState { || !pending.ready.is_empty() || !pending.inactive.is_empty() || !pending.nba_queue.is_empty() - || !pending.waiters.is_empty() + || pending + .waiters + .iter() + .any(|(process, _)| scheduler.waits.get(process).is_none_or(Option::is_none)) { return None; } @@ -50,7 +91,24 @@ impl SimulationState { other = other.min(time); } } - let reference = other.min(self.scheduler.next_event_time().unwrap_or(u64::MAX)); + // The host clocks the scheduler runs are its work; every other + // scheduled event is the reference loop's. + let queue = &self.scheduler.event_queue; + if scheduler.clocks.is_empty() { + other = other.min(self.scheduler.next_event_time().unwrap_or(u64::MAX)); + } else { + 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) + { + first = first.min(event.time); + } else { + other = other.min(event.time); + } + } + } + let reference = other; // Time zero starts processes in their own order; the reference loop // runs it. if first == u64::MAX || first == 0 || first > end || first >= reference { @@ -111,6 +169,28 @@ impl SimulationState { for &(_, waiting) in scheduler.wake.iter().flatten() { backend.set(waiting, 0u8); } + backend.set(scheduler.ready, 0u64); + // The scheduler's waiting kernels wait in its slots during the run, + // with the level each wait last saw. + for (process, slots) in scheduler.waits.iter().enumerate() { + let Some((waiting, baseline)) = *slots else { + continue; + }; + let level = match self.process_state.waiters.get(process) { + Some(waiter) => match waiter.baselines.first() { + Some(Baseline::Raw(raw)) => raw.first().is_some_and(|byte| byte & 1 != 0), + Some(Baseline::Value((value, _))) => value.bit(0), + _ => return Err(SimulatorErrorCode::InternalError.into()), + }, + None => { + backend.set(waiting, 0u8); + continue; + } + }; + backend.set(waiting, 1u8); + backend.set(baseline, u8::from(level)); + self.process_state.waiters.remove(process); + } // The scheduler's kernels wait in its wake slots during the run. let mut kept = Vec::with_capacity(self.process_wakeups.len()); for wakeup @ Reverse((time, process)) in self.process_wakeups.drain() { @@ -123,6 +203,40 @@ impl SimulationState { } } self.process_wakeups.extend(kept); + // The host clocks it runs wait in its clock slots during the run. + let mut clocks = Vec::new(); + if !scheduler.clocks.is_empty() { + let queue = &mut self.scheduler.event_queue; + let compiled = compiled_clocks(scheduler, queue, &self.scheduler.clocks); + clocks.resize(scheduler.clocks.len(), None); + let mut values = 0u64; + for event in queue.iter() { + let Some(bit) = clock_slot(scheduler, event, &self.scheduler.clocks) + .filter(|&bit| compiled >> bit & 1 != 0) + else { + continue; + }; + let period = self.scheduler.clocks[event.event_ref.id()] + .as_ref() + .map_or(2, |clock| clock.period.max(2)); + backend.set( + SchedulerRefs::clock_element(scheduler.clock_next, bit), + event.time, + ); + backend.set( + SchedulerRefs::clock_element(scheduler.clock_period, bit), + period, + ); + values |= u64::from(event.next_val != 0) << bit; + clocks[bit] = Some(event.event_ref); + } + queue.retain(|event| { + clock_slot(scheduler, event, &self.scheduler.clocks) + .is_none_or(|bit| compiled >> bit & 1 == 0) + }); + backend.set(scheduler.clock_armed, compiled); + backend.set(scheduler.clock_value, values); + } let unit = scheduler.unit; let result = executor.run_process(unit); @@ -136,40 +250,123 @@ impl SimulationState { let now: u64 = backend.get_as(scheduler.now); let exit = SchedulerExit::from_code(backend.get_as(scheduler.exit)); let current: u64 = backend.get_as(scheduler.current); + let ready: u64 = backend.get_as(scheduler.ready); let complete = result.is_ok() && exit == Some(SchedulerExit::Limit); + // A clock that overflows ends the run after its slot completed. + let slot_complete = complete || exit == Some(SchedulerExit::ClockOverflow); + let overflowed = scheduler + .clocks + .get(backend.get_as::(scheduler.exit_arg) as usize) + .map(|&(event, _)| event); + // Armed clocks wait for their next edge in the event queue again; a + // clock whose edge applied in a slot the run left unfinished is gone, + // as the reference loop leaves it until the slot re-arms it. + let armed: u64 = backend.get_as(scheduler.clock_armed); + let values: u64 = backend.get_as(scheduler.clock_value); + let clocked = clocks.iter().any(Option::is_some); + for (bit, event_ref) in clocks.into_iter().enumerate() { + let Some(event_ref) = event_ref.filter(|_| armed >> bit & 1 != 0) else { + continue; + }; + self.scheduler.push(SimEvent { + time: backend.get_as(SchedulerRefs::clock_element(scheduler.clock_next, bit)), + event_ref, + signal: scheduler.clocks[bit].1, + next_val: u8::from(values >> bit & 1 != 0), + periodic: true, + }); + } + // A run that returned in the middle of slot `now` leaves the kernel + // that ended it filed nowhere, as the reference loop leaves it, and + // the kernels still ready in the slot ready. + let ordinals = &scheduler.ordinals; + let is_ready = |process: usize| { + ordinals + .get(process) + .copied() + .flatten() + .is_some_and(|ordinal| ready >> ordinal & 1 != 0) + }; + let pending = + |process: usize| !complete && (process as u64 == current || is_ready(process)); for (process, wake) in scheduler.wake.iter().enumerate() { let Some((wake, waiting)) = *wake else { continue; }; - if backend.get_as::(waiting) == 0 { + if pending(process) || backend.get_as::(waiting) == 0 { continue; } let time: u64 = backend.get_as(wake); - if !complete && time == now { - // The run returned in the middle of slot `now`: the kernel - // that ended it is filed nowhere, as the reference loop - // leaves it, and kernels due then that did not run yet are - // still ready. - if process as u64 != current { + self.process_wakeups.push(Reverse((time, process))); + } + for (process, slots) in scheduler.waits.iter().enumerate() { + let Some((waiting, baseline)) = *slots else { + continue; + }; + if pending(process) || backend.get_as::(waiting) == 0 { + continue; + } + let site = backend.get_as::(self.model.processes[process].delay) as usize; + let terms = self.model.processes[process] + .wait_sites + .get(site) + .ok_or_else(|| Self::site_error(process, site))?; + let level = [backend.get_as::(baseline)]; + // The slot keeps its storage, as `register_waiter` reuses it. + self.process_state.waiters.register( + process, + terms.iter().any(|term| term.driven), + |waiter| { + waiter.site = site; + waiter.baselines.truncate(1); + match waiter.baselines.first_mut() { + Some(Baseline::Raw(raw)) => copy_planes(raw, &level, 1), + _ => { + let mut raw = Vec::with_capacity(1); + copy_planes(&mut raw, &level, 1); + waiter.baselines.clear(); + waiter.baselines.push(Baseline::Raw(raw)); + } + } + }, + ); + } + if !complete { + for process in 0..ordinals.len() { + if is_ready(process) && process as u64 != current { self.process_state.ready.insert(process); } - continue; } - self.process_wakeups.push(Reverse((time, process))); } self.stats.compiled_slots += count; if count > 0 { self.scheduler.time = now; } - if complete { + if slot_complete { // The slots ended with their levels as the baseline of the next. self.resample_clock_values(executor.backend()); } else if count > 0 { // The baseline is the levels slot `now` started from; events the // kernels do not write kept theirs. let levels: u64 = executor.backend().get_as(scheduler.levels); - for (bit, &id) in scheduler.events.clone().iter().enumerate() { - self.record_level(id, u8::from(levels >> bit & 1 != 0)); + // A run without clocks records no level of their events, which + // only the clocks change. + let scheduler = self + .model + .scheduler + .as_ref() + .ok_or(SimulatorErrorCode::InternalError)?; + let recorded: Vec<(usize, bool)> = scheduler + .events + .iter() + .enumerate() + .filter(|&(_, &id)| { + clocked || scheduler.clocks.iter().all(|&(clock, _)| clock != id) + }) + .map(|(bit, &id)| (id, levels >> bit & 1 != 0)) + .collect(); + for (id, level) in recorded { + self.record_level(id, u8::from(level)); } } // Domains mark trigger bits as they run; between slots none is set. @@ -184,6 +381,13 @@ impl SimulationState { signals: Vec::new(), })); } + Some(SchedulerExit::ClockOverflow) => { + let event = overflowed.ok_or(SimulatorErrorCode::InternalError)?; + return Err(Halt::Error(SimulatorErrorCode::Runtime { + message: format!("event {event} overflows simulation time"), + signals: Vec::new(), + })); + } Some(SchedulerExit::Internal) | None => { return Err(SimulatorErrorCode::InternalError.into()); } diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index f5f950ad24b..7523e231da0 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -295,13 +295,19 @@ impl SimulationState { return Ok(false); } let compiles = self.compiles_slots(); + let waiting_kernels = self + .model + .scheduler + .as_ref() + .map_or(0, |scheduler| scheduler.wait_kernels); while let Some(next_time) = self.next_event_time() { if next_time > end { break; } - // A waiting process keeps the slot in the reference loop; test - // that first, as fallback designs fail it at every step. - let compiled = if compiles && self.process_state.waiters.is_empty() { + // A process the scheduler does not run waits: the slot stays in + // the reference loop. Test that first, as designs with such + // processes fail it at every step. + let compiled = if compiles && self.process_state.waiters.len() <= waiting_kernels { self.compiled_limit(executor, end, observer.one_slot()) } else { None diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index 696d04ec5e1..a5a5525fc53 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -100,6 +100,9 @@ impl SimulationState { /// Express the scheduling state with `backend`'s event handles. pub fn export_schedule(&self, backend: &B) -> ScheduleParts { let events = backend.id_to_event_slice(); + // In the order they fire, whatever order the queue holds them in. + let mut queue: Vec<&SimEvent> = self.scheduler.event_queue.iter().collect(); + queue.sort_by(|a, b| b.cmp(a).then(a.periodic.cmp(&b.periodic))); ScheduleParts { time: self.scheduler.time, clocks: self @@ -109,12 +112,12 @@ impl SimulationState { .enumerate() .filter_map(|(id, clock)| Some((events[id], clock.as_ref()?.period))) .collect(), - events: self.scheduler.event_queue.iter().cloned().collect(), + events: queue.iter().map(|&event| event.clone()).collect(), periodic: { // Identical periodic events once, with their number, in the // order of `events`. let mut periodic: Vec<(SimEvent, u64)> = Vec::new(); - for event in self.scheduler.event_queue.iter().filter(|e| e.periodic) { + for &event in queue.iter().filter(|e| e.periodic) { match periodic.iter_mut().find(|(known, _)| known == event) { Some((_, count)) => *count += 1, None => periodic.push((event.clone(), 1)), diff --git a/crates/celox-runtime/src/simulation/wait.rs b/crates/celox-runtime/src/simulation/wait.rs index 301f74432ac..bfbd004c30d 100644 --- a/crates/celox-runtime/src/simulation/wait.rs +++ b/crates/celox-runtime/src/simulation/wait.rs @@ -338,6 +338,15 @@ impl Waiters { self.register(process, driven, |slot| *slot = waiter); } + /// The wait of process `process`, if it waits. + pub fn get(&self, process: usize) -> Option<&Waiter> { + self.waiting + .get(process) + .copied() + .unwrap_or(false) + .then(|| &self.slots[process]) + } + /// Process `process` no longer waits. pub fn remove(&mut self, process: usize) { if self.waiting.get(process).copied().unwrap_or(false) { diff --git a/crates/celox/examples/sched_bench.rs b/crates/celox/examples/sched_bench.rs index 112da616da7..2ca280dd104 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]` //! //! Every variant clocks the same 64 registers `rK <= rK + (seed ^ K)`: //! @@ -9,8 +9,11 @@ //! - `b1`: the clock comes from `always #5 clk = ~clk` and the registers read //! `stim`, which `initial forever @(posedge clk) stim = stim + 3` drives. //! - `b5`: like `b1` with `stim <= stim + 3`. +//! - `bh`: like `b1` with the clock from `add_clock` instead of a kernel. //! - `d`: the clock comes from `always #5 clk = ~clk` and the registers read //! a constant seed, so only delay-only kernels run. +//! - `dr`: like `d` with an asynchronous reset input that the host sets +//! once and no clock drives. //! //! The optional third argument selects the timed scheduler (hidden builder //! option), by default the library's; the fourth the backend, by default the @@ -49,24 +52,46 @@ fn source(variant: &str) -> String { "stim", ) } - "d" => ( - "module Top(output logic [31:0] out);\n\ - logic clk = 0;\n\ - logic [31:0] seed = 7;\n\ - always #5 clk = ~clk;\n" + "bh" => ( + "module Top(input logic clk, output logic [31:0] out);\n\ + logic [31:0] stim = 0;\n\ + initial forever @(posedge clk) stim = stim + 3;\n" .to_string(), - "seed", + "stim", ), - _ => panic!("unknown variant {variant}: expected a, ac, b1, b5 or d"), + "d" | "dr" => { + let ports = if variant == "d" { + "output logic [31:0] out" + } else { + "input logic rst_n, output logic [31:0] out" + }; + ( + format!( + "module Top({ports});\n\ + logic clk = 0;\n\ + logic [31:0] seed = 7;\n\ + always #5 clk = ~clk;\n" + ), + "seed", + ) + } + _ => panic!("unknown variant {variant}: expected a, ac, b1, b5, bh, d or dr"), }; // One time unit per tick, so that `#5` and `add_clock(10, 5)` agree. let mut body = String::from("`timescale 1fs/1fs\n"); body.push_str(&header); for lane in 0..LANES { body.push_str(&format!("logic [31:0] r{lane} = 0;\n")); - body.push_str(&format!( - "always_ff @(posedge clk) r{lane} <= r{lane} + ({seed} ^ 32'd{lane});\n" - )); + if variant == "dr" { + body.push_str(&format!( + "always_ff @(posedge clk or negedge rst_n) \ + if (!rst_n) r{lane} <= 0; else r{lane} <= r{lane} + ({seed} ^ 32'd{lane});\n" + )); + } else { + body.push_str(&format!( + "always_ff @(posedge clk) r{lane} <= r{lane} + ({seed} ^ 32'd{lane});\n" + )); + } } let lanes: Vec = (0..LANES).map(|lane| format!("r{lane}")).collect(); body.push_str(&format!("assign out = {};\nendmodule\n", lanes.join(" + "))); @@ -143,6 +168,12 @@ fn run( if variant == "ac" { let seed = sim.signal("seed"); sim.modify(|io| io.set(seed, 7u32)).unwrap(); + } + if variant == "dr" { + let rst_n = sim.signal("rst_n"); + sim.modify(|io| io.set(rst_n, 1u8)).unwrap(); + } + if variant == "ac" || variant == "bh" { sim.add_clock("clk", 10, 5); } sim.run_until(cycles * 10).unwrap(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a36af8f6961..4cf8a4b6284 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 = 29; +const CONTAINER_VERSION: u16 = 32; 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/scheduler.rs b/crates/celox/src/scheduler.rs index 2186b9e3589..035dfd39c47 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -17,8 +17,9 @@ //! reference loop. use celox_design::{ - DomainKind, ProcessStatus, RuntimeEventKind, SCHEDULER_FLAG_WIDTH, SCHEDULER_TIME_WIDTH, - STABLE_REGION, SchedulerExit, SchedulerSlots, TIME_SLOT_WIDTH, schedule::ScheduleModel, + CounterKind, DomainKind, ProcessStatus, RuntimeEventKind, SCHEDULER_CLOCKS, + SCHEDULER_FLAG_WIDTH, SCHEDULER_TIME_WIDTH, STABLE_REGION, SchedulerExit, SchedulerSlots, + TIME_SLOT_WIDTH, schedule::ScheduleModel, }; use celox_sir::{BinaryOp, SIRBuilder, SIRSwitchCase, SIRValue}; @@ -36,6 +37,28 @@ type Builder = SIRBuilder; /// The most events whose edges one slot can record. const MAX_EVENTS: usize = 64; +/// The most kernels the ready mask of a slot holds. +const MAX_KERNELS: usize = 64; + +/// The widest selector of a nonblocking site index. +const SITE_BITS: usize = 8; + +const ACTIVE_COMMIT: &str = "the process drives or waits for a clock whose domain commits blocking results in the active region"; + +const DELAY_STATUSES: [ProcessStatus; 4] = [ + ProcessStatus::Delay, + ProcessStatus::InactiveDelay, + ProcessStatus::Done, + ProcessStatus::Finish, +]; + +const WAIT_STATUSES: [ProcessStatus; 4] = [ + ProcessStatus::Wait, + ProcessStatus::Nba, + ProcessStatus::Done, + ProcessStatus::Finish, +]; + /// Generate the compiled scheduler of `program`, if it qualifies, and record /// for every process kernel whether the scheduler runs it. pub(crate) fn attach(program: &mut LaidOutProgram) { @@ -43,8 +66,8 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { return; }; let kernels = program.runtime.runtime_schema.processes.len(); - let (fallback, unit, events) = match Plan::new(program, &schema.slots) { - Err(reason) => (vec![Some(reason); kernels], None, Vec::new()), + let (fallback, unit, events, clocks) = match Plan::new(program, &schema.slots) { + Err(reason) => (vec![Some(reason); kernels], None, Vec::new(), Vec::new()), Ok(plan) => { let fallback = plan.fallback.clone(); let unit = plan @@ -53,11 +76,16 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { .any(Option::is_some) .then(|| plan.generate(program, &schema.slots)); let events = plan - .written() + .edged() .into_iter() .map(|event| plan.events[event].signal) .collect(); - (fallback, unit, events) + let clocks = plan + .clocks + .iter() + .map(|&event| plan.events[event].signal) + .collect(); + (fallback, unit, events, clocks) } }; let scheduler = program @@ -68,6 +96,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { .expect("checked above"); scheduler.fallback = fallback; scheduler.events = events; + scheduler.clocks = clocks; if let Some(unit) = unit { scheduler.unit = Some(program.sir.processes.len()); program.sir.processes.push(unit); @@ -81,6 +110,8 @@ struct Event { width: usize, /// The level of the signal after an active edge. active: u8, + /// A clock edge rather than an asynchronous reset. + clock: bool, eval_apply: Vec, eval_only: Vec, apply: Vec, @@ -91,6 +122,26 @@ struct Kernel { /// The events whose signal the kernel writes, as indices into /// [`Plan::events`]. writes: Vec, + /// For a kernel that waits for one edge, the edge and its staged + /// nonblocking assignments; `None` for a kernel that only delays. + wait: Option, +} + +/// The single edge a kernel waits for at every wait site. +struct Wait { + signal: AbsoluteAddr, + kind: CounterKind, + /// Its nonblocking sites, by local index. + sites: Vec, +} + +/// A nonblocking site that stages its value and sets a pending flag. +struct Staged { + pending: AbsoluteAddr, + value: AbsoluteAddr, + target: AbsoluteAddr, + lsb: usize, + width: usize, } struct Plan { @@ -99,9 +150,16 @@ struct Plan { events: Vec, /// Per process kernel, `Some` when the scheduler runs it. kernels: Vec>, + /// The events a host periodic clock may drive in the scheduler's slots, + /// as indices into [`Self::events`], in event order: the bits of its + /// clock slots. + clocks: Vec, fallback: Vec>, /// Runtime event sites that record a `$finish`. finish_sites: HashSet, + /// The storage combinational logic reads, when a settle whose inputs did + /// not change may be skipped; `None` when every settle runs. + settle_reads: Option>, } impl Plan { @@ -124,6 +182,7 @@ impl Plan { if !schema.comb_observers.is_empty() { return Err("the design observes combinational processes".into()); } + const _: () = assert!(MAX_EVENTS <= SCHEDULER_CLOCKS); if slots.wake.len() != schema.processes.len() { return Err("the scheduler slots do not match the kernels".into()); } @@ -152,9 +211,11 @@ impl Plan { let mut events = Vec::with_capacity(addresses.len()); let mut event_storage = HashMap::default(); for &signal in &addresses { - let active = match model.kinds.get(&signal) { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => 1, - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => 0, + let (active, clock) = match model.kinds.get(&signal) { + Some(DomainKind::ClockPosedge) => (1, true), + Some(DomainKind::ClockNegedge) => (0, true), + Some(DomainKind::ResetAsyncHigh) => (1, false), + Some(DomainKind::ResetAsyncLow) => (0, false), _ => return Err("an event is not a clock or reset edge".into()), }; let units = |map: &HashMap>| -> Result, String> { @@ -174,6 +235,7 @@ impl Plan { .get(&signal) .ok_or("an event signal has no storage")?, active, + clock, eval_apply: units(&sir.eval_apply_ffs)?, eval_only: units(&sir.eval_only_ffs)?, apply: units(&sir.apply_ffs)?, @@ -200,13 +262,14 @@ impl Plan { written.dedup(); written }; - let rtl_units = sir - .eval_comb - .iter() - .chain(sir.eval_apply_ffs.values().flatten()) - .chain(sir.eval_only_ffs.values().flatten()) - .chain(sir.apply_ffs.values().flatten()); - for unit in rtl_units { + let rtl_units = || { + sir.eval_comb + .iter() + .chain(sir.eval_apply_ffs.values().flatten()) + .chain(sir.eval_only_ffs.values().flatten()) + .chain(sir.apply_ffs.values().flatten()) + }; + for unit in rtl_units() { if !written(unit).is_empty() { return Err("RTL logic drives an event signal".into()); } @@ -220,9 +283,65 @@ impl Plan { .filter(|(_, event)| model.active_commits.contains(&event.signal)) .map(|(index, _)| index) .collect(); + // The storage each unit writes. + let stores = |unit: &Unit| -> HashSet { + instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Store(target, ..) | SIRInstruction::Commit(_, target, ..) => { + Some(storage(target.absolute_addr())) + } + _ => None, + }) + .collect() + }; + let rtl_stores: HashSet = rtl_units().flat_map(stores).collect(); + let kernel_stores: Vec> = sir + .processes + .iter() + .take(schema.processes.len()) + .map(stores) + .collect(); + let waited: HashSet = model.waited.iter().map(|s| storage(*s)).collect(); + // Storage whose changes bump an occurrence counter: the reference + // counts the nonblocking updates it publishes into it, which the + // scheduler's publication does not. + let probed: HashSet = model + .probes + .iter() + .map(|(source, _)| storage(source.id)) + .collect(); + let mut nba_targets: HashMap = HashMap::default(); + for process in &model.processes { + for site in &process.nbas { + *nba_targets.entry(storage(site.target)).or_default() += 1; + } + } + // Storage no design code writes: only the host changes it, by + // writes between runs or by a periodic clock at the start of a slot. + // Clock slots go to the clock events among it: each costs the unit + // its domains' code even when no clock runs, and the host drives + // asynchronous resets by writes. + let undriven = |signal: AbsoluteAddr| { + !rtl_stores.contains(&signal) + && !kernel_stores.iter().any(|stores| stores.contains(&signal)) + && !nba_targets.contains_key(&signal) + }; + let clocks: Vec = events + .iter() + .enumerate() + .filter(|(index, event)| { + event.clock + && event.width == 1 + && !active_commits.contains(index) + && undriven(storage(event.signal)) + }) + .map(|(index, _)| index) + .collect(); - let mut kernels = Vec::with_capacity(schema.processes.len()); + let mut kernels: Vec> = Vec::with_capacity(schema.processes.len()); let mut fallback = Vec::with_capacity(schema.processes.len()); + // Kernels that only delay first: the signals they write are those a + // waiting kernel's edge may be on. for (index, slots) in schema.processes.iter().enumerate() { let process = &model.processes[index]; let unit = &sir.processes[index]; @@ -230,23 +349,16 @@ impl Plan { Some("a declaration initializer") } else if slots.requires_timed_simulation { Some("an edge procedure") + } else if !process.host_requests.is_empty() { + Some("the process makes host requests") + } else if !process.waits.is_empty() { + None } else if !slots.const_delays { Some("a delay is not a constant of at least one time unit") - } else if !process.waits.is_empty() { - Some("the process waits for events") } else if !process.nbas.is_empty() { Some("the process has nonblocking assignments") - } else if !process.host_requests.is_empty() { - Some("the process makes host requests") - } else if !delay_statuses_only(unit, slots.status) { + } else if !statuses_only(unit, slots.status, &DELAY_STATUSES) { Some("the process suspends other than for a delay") - } else if written(unit) - .iter() - .any(|event| active_commits.contains(event)) - { - Some( - "the process drives a clock whose domain commits blocking results in the active region", - ) } else { None }; @@ -255,14 +367,136 @@ impl Plan { kernels.push(None); fallback.push(Some(reason.to_string())); } + None if process.waits.is_empty() => { + let writes = written(unit); + if writes.iter().any(|event| active_commits.contains(event)) { + kernels.push(None); + fallback.push(Some(ACTIVE_COMMIT.to_string())); + } else { + kernels.push(Some(Kernel { writes, wait: None })); + fallback.push(None); + } + } None => { - kernels.push(Some(Kernel { - writes: written(unit), - })); + kernels.push(None); fallback.push(None); } } } + // How many kernels that only delay write each storage. A waiting + // kernel's signal has one such writer, which runs once a slot, so + // the waiting kernel wakes at most once a slot. + let mut delay_writers: HashMap = HashMap::default(); + for (_, stores) in kernels + .iter() + .zip(&kernel_stores) + .filter(|(kernel, _)| kernel.is_some()) + { + for store in stores { + *delay_writers.entry(*store).or_default() += 1; + } + } + // Storage the other kernels write, waiting ones included. + let other_stores: HashSet = kernels + .iter() + .zip(&kernel_stores) + .filter(|(kernel, _)| kernel.is_none()) + .flat_map(|(_, stores)| stores.iter().copied()) + .collect(); + for index in 0..schema.processes.len() { + let process = &model.processes[index]; + if process.waits.is_empty() || fallback[index].is_some() { + continue; + } + let slots = &schema.processes[index]; + let unit = &sir.processes[index]; + let term = &process.waits[0].first(); + let wait = (|| -> Result { + let term = term.ok_or("the process waits for a level")?; + if process + .waits + .iter() + .any(|terms| terms.len() != 1 || terms[0] != *term) + { + return Err("the process waits for more than one edge"); + } + let signal = storage(term.signal); + let delayed = delay_writers.get(&signal) == Some(&1) + && !rtl_stores.contains(&signal) + && !other_stores.contains(&signal); + if program.layout().widths.get(&term.signal) != Some(&1) + || !(delayed || undriven(signal)) + { + return Err( + "the process waits for a signal that neither one kernel that only delays nor the host alone drives", + ); + } + if event_storage + .get(&signal) + .is_some_and(|event| active_commits.contains(event)) + { + return Err(ACTIVE_COMMIT); + } + if !statuses_only(unit, slots.status, &WAIT_STATUSES) { + return Err("the process suspends other than for one edge"); + } + let writes = &kernel_stores[index]; + if !written(unit).is_empty() || writes.iter().any(|store| waited.contains(store)) { + return Err("the process drives an event or a waited signal"); + } + let sites = process + .nbas + .iter() + .map(|site| { + let target = storage(site.target); + let pending = site.pending.ok_or("a nonblocking site queues its values")?; + // A position computed at run time, or an element of + // an unpacked array, which the runtime merges through + // the array's layout, needs the runtime's publication. + if site.position.is_some() + || program.layout().unpacked_arrays.contains_key(&site.target) + || nba_targets.get(&target) != Some(&1) + || rtl_stores.contains(&target) + || kernel_stores.iter().any(|stores| stores.contains(&target)) + || waited.contains(&target) + || probed.contains(&target) + || event_storage.contains_key(&target) + { + return Err("a nonblocking target has other writers or observers"); + } + Ok(Staged { + pending, + value: site.value, + target: site.target, + lsb: site.lsb, + width: site.width, + }) + }) + .collect::, _>>()?; + if sites.len() > 1 << SITE_BITS { + return Err("the process has too many nonblocking sites"); + } + Ok(Wait { + signal: term.signal, + kind: term.kind, + sites, + }) + })(); + match wait { + Ok(wait) => { + kernels[index] = Some(Kernel { + writes: Vec::new(), + wait: Some(wait), + }) + } + Err(reason) => fallback[index] = Some(reason.to_string()), + } + } + if kernels.iter().flatten().count() > MAX_KERNELS { + return Err(format!( + "the design has more than {MAX_KERNELS} kernels to compile" + )); + } let finish_sites = schema .runtime_event_sites .iter() @@ -270,11 +504,48 @@ impl Plan { .filter(|(_, site)| matches!(site.kind, RuntimeEventKind::Finish)) .map(|(index, _)| index as u32) .collect(); + // A settle is the same function of the state it reads every time, + // unless combinational logic has effects of its own: records, + // captures, external calls or trigger marks. + let effects = sir.eval_comb.iter().any(|unit| { + instructions(unit).any(|inst| match inst { + SIRInstruction::RuntimeEvent { .. } + | SIRInstruction::CombCaptureEvent { .. } + | SIRInstruction::CombCaptureEnableIfChanged { .. } + | SIRInstruction::ExternCall { .. } => true, + SIRInstruction::Store(_, _, _, _, triggers, sites) => { + !triggers.is_empty() || !sites.is_empty() + } + SIRInstruction::Commit(_, _, _, _, triggers) => !triggers.is_empty(), + _ => false, + }) + }); + // Dirty tracking compares stable homes by their representative + // (`shared_storage`), which groups addresses only by an equal start + // offset: no two homes may overlap from different offsets. + debug_assert!( + homes_overlap_only_whole(program.layout()), + "stable homes overlap at different offsets" + ); + let settle_reads = (!effects).then(|| { + sir.eval_comb + .iter() + .flat_map(instructions) + .filter_map(|inst| match inst { + SIRInstruction::Load(_, source, ..) | SIRInstruction::Commit(source, ..) => { + Some(storage(source.absolute_addr())) + } + _ => None, + }) + .collect() + }); Ok(Self { events, kernels, + clocks, fallback, finish_sites, + settle_reads, }) } @@ -292,33 +563,95 @@ impl Plan { written } + /// The events that can have edges in the scheduler's slots, in event + /// order: those its kernels write and those its host clocks may drive. + fn edged(&self) -> Vec { + let mut edged = self.written(); + edged.extend(&self.clocks); + edged.sort_unstable(); + edged.dedup(); + edged + } + fn generate(&self, program: &LaidOutProgram, slots: &SchedulerSlots) -> Unit { let schema = &program.runtime.runtime_schema; - let written = self.written(); + let edged = self.edged(); let mut g = Generator { b: Builder::new(), slots, finish_sites: &self.finish_sites, exits: Vec::new(), + settle_reads: self.settle_reads.as_ref(), + shared: program.shared_storage(), }; + let waits: Vec<(usize, &Wait)> = self + .kernels + .iter() + .enumerate() + .filter_map(|(index, kernel)| Some((index, kernel.as_ref()?.wait.as_ref()?))) + .collect(); + let delays: Vec = self + .kernels + .iter() + .enumerate() + .filter(|(_, kernel)| kernel.as_ref().is_some_and(|kernel| kernel.wait.is_none())) + .map(|(index, _)| index) + .collect(); + // The bit of each kernel in the ready mask: its place among the + // kernels the scheduler runs, in kernel order. + let ordinals = ordinals(&self.kernels); + // Every run starts dirty, and this mark is required, not a margin: + // it is the only cover for a unit that exited to the `$finish` exit + // partway through, whose mark after the unit never ran, and for + // state a checkpoint or a state file restored between runs, which + // no mark sees. + g.mark_dirty(); let header = g.b.new_block(); g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); - // The next slot: the earliest wake time of a waiting kernel. + // The next slot: the earliest wake time of a kernel waiting for one. g.b.switch_to_block(header); let mut time = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); let mut any = g.constant(0, 1); - for (index, kernel) in self.kernels.iter().enumerate() { - if kernel.is_some() { - let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); - let waiting = g.waiting(index); - let earlier = g.binary(1, wake, BinaryOp::LtU, time); - let earlier = g.binary(1, earlier, BinaryOp::And, waiting); + for &index in &delays { + let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); + let waiting = g.waiting(index); + let earlier = g.binary(1, wake, BinaryOp::LtU, time); + let earlier = g.binary(1, earlier, BinaryOp::And, waiting); + let next = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); + g.b.emit(SIRInstruction::Mux(next, earlier, wake, time)); + time = next; + any = g.binary(1, any, BinaryOp::Or, waiting); + } + // Or the earliest next edge of a host clock, when the run has any. + if !self.clocks.is_empty() { + let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); + let zero = g.constant(0, SCHEDULER_CLOCKS); + let clocked = g.binary(1, armed, BinaryOp::Ne, zero); + let scan = g.b.new_block(); + let joined_time = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); + let joined_any = g.b.alloc_bit(1, false); + let join = g.b.new_block_with(vec![joined_time, joined_any]); + g.b.seal_block(SIRTerminator::Branch { + cond: clocked, + true_block: (scan, Vec::new()), + false_block: (join, vec![time, any]), + }); + g.b.switch_to_block(scan); + for bit in 0..self.clocks.len() { + let next_edge = g.clock_next(bit); + let on = g.mask_bit(armed, bit); + let earlier = g.binary(1, next_edge, BinaryOp::LtU, time); + let earlier = g.binary(1, earlier, BinaryOp::And, on); let next = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); - g.b.emit(SIRInstruction::Mux(next, earlier, wake, time)); + g.b.emit(SIRInstruction::Mux(next, earlier, next_edge, time)); time = next; - any = g.binary(1, any, BinaryOp::Or, waiting); + any = g.binary(1, any, BinaryOp::Or, on); } + g.b.seal_block(SIRTerminator::Jump(join, vec![time, any])); + g.b.switch_to_block(join); + time = joined_time; + any = joined_any; } let limit = g.load(slots.limit, SCHEDULER_TIME_WIDTH); let after = g.binary(1, time, BinaryOp::GtU, limit); @@ -326,7 +659,7 @@ impl Plan { let none = g.binary(1, any, BinaryOp::Xor, one); let stop = g.binary(1, after, BinaryOp::Or, none); let run = g.b.new_block(); - let limit_exit = g.exit_block(SchedulerExit::Limit, None); + let limit_exit = g.exit_block(SchedulerExit::Limit); g.b.seal_block(SIRTerminator::Branch { cond: stop, true_block: (limit_exit, Vec::new()), @@ -342,10 +675,17 @@ impl Plan { for &slot in &schema.time_slots { g.store(slot, TIME_SLOT_WIDTH, time); } + if schema.time_slots.iter().any(|&slot| g.settle_reads(slot)) { + g.mark_dirty(); + } // The levels the slot starts from, the baseline of its edges, for an - // exit in the middle of the slot. + // exit in the middle of the slot; those of the clocks' events below, + // when the run has clocks. let mut levels = g.constant(0, MAX_EVENTS); - for (bit, &event) in written.iter().enumerate() { + for (bit, &event) in edged.iter().enumerate() { + if self.clocks.contains(&event) { + continue; + } let level = g.level(&self.events[event]); let set = g.constant(1 << bit, MAX_EVENTS); let unset = g.constant(0, MAX_EVENTS); @@ -354,31 +694,139 @@ impl Plan { levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, value); } g.store(slots.levels, SCHEDULER_TIME_WIDTH, levels); - let finish_exit = g.exit_block(SchedulerExit::Finish, None); - let internal_exit = g.exit_block(SchedulerExit::Internal, None); - - // The kernels due now, in kernel order, and the active edges they - // give, as a mask over the events. - let mut mask = g.constant(0, MAX_EVENTS); - for (index, kernel) in self.kernels.iter().enumerate() { - let Some(kernel) = kernel else { - continue; - }; - let process = &schema.processes[index]; + // The kernels due now are ready; the edges of the slot collect in + // `exit_arg`. + let mut ready = g.constant(0, MAX_KERNELS); + for &index in &delays { let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); let waiting = g.waiting(index); let due = g.binary(1, wake, BinaryOp::Eq, time); let due = g.binary(1, due, BinaryOp::And, waiting); + let bit = g.bit(due, ordinals[index]); + ready = g.binary(MAX_KERNELS, ready, BinaryOp::Or, bit); + } + g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); + // The host clocks due now set their levels, in event order, before + // any kernel runs; their edges start the slot's edges, which + // collect in `exit_arg`. A clock whose edge applied waits for its + // next edge until the slot ends. A run without clocks skips them. + let zero = g.constant(0, MAX_EVENTS); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, zero); + let finish_exit = g.exit_block(SchedulerExit::Finish); + let internal_exit = g.exit_block(SchedulerExit::Internal); + let pick = g.b.new_block(); + // The clocks armed at the start of the slot, which the re-arm at its + // end compares with. + let mut started = None; + if !self.clocks.is_empty() { + let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); + let zero = g.constant(0, SCHEDULER_CLOCKS); + let clocked = g.binary(1, armed, BinaryOp::Ne, zero); + started = Some((armed, clocked)); + let apply = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: clocked, + true_block: (apply, Vec::new()), + false_block: (pick, Vec::new()), + }); + g.b.switch_to_block(apply); + let values = g.load(slots.clock_value, SCHEDULER_TIME_WIDTH); + let mut fired = g.constant(0, SCHEDULER_CLOCKS); + let mut edges = g.constant(0, MAX_EVENTS); + let mut levels = g.load(slots.levels, MAX_EVENTS); + for (bit, &index) in self.clocks.iter().enumerate() { + let event = &self.events[index]; + let next_edge = g.clock_next(bit); + let on = g.mask_bit(armed, bit); + let due = g.binary(1, next_edge, BinaryOp::Eq, time); + let due = g.binary(1, due, BinaryOp::And, on); + let value = g.mask_bit(values, bit); + let was = g.level(event); + let position = edged + .iter() + .position(|&edged| edged == index) + .expect("clocks are edged"); + let level = g.bit(was, position); + levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, level); + let is = g.b.alloc_bit(1, false); + g.b.emit(SIRInstruction::Mux(is, due, value, was)); + g.store(event.signal, 1, is); + if g.settle_reads(event.signal) { + g.mark_dirty(); + } + let changed = g.binary(1, was, BinaryOp::Ne, is); + let active = g.equals(is, u64::from(event.active)); + let edge = g.binary(1, changed, BinaryOp::And, active); + let edge = g.bit(edge, index); + edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, edge); + let bit = g.bit(due, bit); + fired = g.binary(SCHEDULER_CLOCKS, fired, BinaryOp::Or, bit); + } + g.store(slots.levels, SCHEDULER_TIME_WIDTH, levels); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, edges); + let all = g.constant(u64::MAX, SCHEDULER_CLOCKS); + let unfired = g.binary(SCHEDULER_CLOCKS, fired, BinaryOp::Xor, all); + let armed = g.binary(SCHEDULER_CLOCKS, armed, BinaryOp::And, unfired); + g.store(slots.clock_armed, SCHEDULER_TIME_WIDTH, armed); + if !waits.is_empty() { + // The waits see the clocks' levels before the process phase. + let zero = g.constant(0, SCHEDULER_CLOCKS); + let applied = g.binary(1, fired, BinaryOp::Ne, zero); + let check = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: applied, + true_block: (check, Vec::new()), + false_block: (pick, Vec::new()), + }); + g.b.switch_to_block(check); + g.check_waits(&waits_of(&waits, &ordinals)); + } + } + g.b.seal_block(SIRTerminator::Jump(pick, Vec::new())); + + // A pass of the process phase: the lowest ready kernel runs, and + // the waits see its writes before the next one while kernels remain + // ready (`run_ready`); then combinational logic settles. + g.b.switch_to_block(pick); + let ready = g.load(slots.ready, MAX_KERNELS); + let zero = g.constant(0, MAX_KERNELS); + let idle = g.binary(1, ready, BinaryOp::Eq, zero); + let pass_end = g.b.new_block(); + let chosen = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: idle, + true_block: (pass_end, Vec::new()), + false_block: (chosen, Vec::new()), + }); + g.b.switch_to_block(chosen); + let mut runs = Vec::new(); + for (index, kernel) in self.kernels.iter().enumerate() { + if kernel.is_none() { + continue; + } + let bit = g.constant(1 << ordinals[index], MAX_KERNELS); + let selected = g.binary(MAX_KERNELS, ready, BinaryOp::And, bit); + let this = g.binary(1, selected, BinaryOp::Ne, zero); let run = g.b.new_block(); - let joined = g.b.alloc_bit(MAX_EVENTS, false); - let join = g.b.new_block_with(vec![joined]); + let next = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: due, + cond: this, true_block: (run, Vec::new()), - false_block: (join, vec![mask]), + false_block: (next, Vec::new()), }); + runs.push((index, run)); + g.b.switch_to_block(next); + } + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + for (index, run) in runs { + let kernel = self.kernels[index].as_ref().expect("selected above"); + let process = &schema.processes[index]; g.b.switch_to_block(run); + let ready = g.load(slots.ready, MAX_KERNELS); + let keep = g.constant(!(1u64 << ordinals[index]), MAX_KERNELS); + let ready = g.binary(MAX_KERNELS, ready, BinaryOp::And, keep); + g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); let current = g.constant(index as u64, SCHEDULER_TIME_WIDTH); g.store(slots.current, SCHEDULER_TIME_WIDTH, current); let before: Vec<_> = kernel @@ -386,7 +834,10 @@ impl Plan { .iter() .map(|&event| g.level(&self.events[event])) .collect(); - g.inline(&program.sir.processes[index], finish_exit); + let enter = g.b.new_block(); + g.b.seal_block(SIRTerminator::Jump(enter, Vec::new())); + g.b.switch_to_block(enter); + g.inline_writer(&program.sir.processes[index], finish_exit); let status = g.load(process.status, celox_design::PROCESS_STATUS_WIDTH); let code = |status: ProcessStatus| u64::from(status.code()); let finished = g.equals(status, code(ProcessStatus::Finish)); @@ -397,74 +848,141 @@ impl Plan { false_block: (not_finished, Vec::new()), }); g.b.switch_to_block(not_finished); - let done = g.equals(status, code(ProcessStatus::Done)); - let ended = g.b.new_block(); - let suspended = g.b.new_block(); let resumed = g.b.new_block(); + match &kernel.wait { + None => { + let done = g.equals(status, code(ProcessStatus::Done)); + let ended = g.b.new_block(); + let suspended = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: done, + true_block: (ended, Vec::new()), + false_block: (suspended, Vec::new()), + }); + g.b.switch_to_block(ended); + let idle = g.constant(0, SCHEDULER_FLAG_WIDTH); + g.store(slots.waiting[index], SCHEDULER_FLAG_WIDTH, idle); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + + g.b.switch_to_block(suspended); + let delay = g.equals(status, code(ProcessStatus::Delay)); + let inactive = g.equals(status, code(ProcessStatus::InactiveDelay)); + let delayed = g.binary(1, delay, BinaryOp::Or, inactive); + let wait = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: delayed, + true_block: (wait, Vec::new()), + false_block: (internal_exit, Vec::new()), + }); + g.b.switch_to_block(wait); + let amount = g.load(process.delay, celox_design::PROCESS_DELAY_WIDTH); + let wake = g.binary(SCHEDULER_TIME_WIDTH, time, BinaryOp::Add, amount); + let overflow = g.binary(1, wake, BinaryOp::LtU, time); + let overflow_exit = g.exit_block(SchedulerExit::DelayOverflow); + let in_range = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: overflow, + true_block: (overflow_exit, Vec::new()), + false_block: (in_range, Vec::new()), + }); + g.b.switch_to_block(in_range); + g.store(slots.wake[index], SCHEDULER_TIME_WIDTH, wake); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + + // The edges of this run, against the levels before it. + g.b.switch_to_block(resumed); + let mut edges = g.load(slots.exit_arg, MAX_EVENTS); + for (&event, &was) in kernel.writes.iter().zip(&before) { + let is = g.level(&self.events[event]); + let changed = g.binary(1, was, BinaryOp::Ne, is); + let active = g.equals(is, u64::from(self.events[event].active)); + let edge = g.binary(1, changed, BinaryOp::And, active); + let bit = g.bit(edge, event); + edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + } + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, edges); + } + Some(wait) => { + // A kernel runs at most once a slot (see `Plan::new`), so + // a staged site is never staged again before the NBA + // region and the kernel never returns `Nba`. + let done = g.equals(status, code(ProcessStatus::Done)); + let suspends = g.equals(status, code(ProcessStatus::Wait)); + let other = g.b.new_block(); + let suspended = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: done, + true_block: (resumed, Vec::new()), + false_block: (other, Vec::new()), + }); + g.b.switch_to_block(other); + g.b.seal_block(SIRTerminator::Branch { + cond: suspends, + true_block: (suspended, Vec::new()), + false_block: (internal_exit, Vec::new()), + }); + + // It waits again: the edge is judged against the level + // now (`register_waiter`). + g.b.switch_to_block(suspended); + let flag = g.constant(1, SCHEDULER_FLAG_WIDTH); + g.store(slots.waiting[index], SCHEDULER_FLAG_WIDTH, flag); + let level = g.signal_level(wait.signal); + let level = g.widen(level, SCHEDULER_FLAG_WIDTH); + g.store(slots.baseline[index], SCHEDULER_FLAG_WIDTH, level); + g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); + g.b.switch_to_block(resumed); + } + } + // Before the next run, the waits see this one's writes. + let ready = g.load(slots.ready, MAX_KERNELS); + let zero = g.constant(0, MAX_KERNELS); + let more = g.binary(1, ready, BinaryOp::Ne, zero); + let check = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: done, - true_block: (ended, Vec::new()), - false_block: (suspended, Vec::new()), - }); - g.b.switch_to_block(ended); - let idle = g.constant(0, SCHEDULER_FLAG_WIDTH); - g.store(slots.waiting[index], SCHEDULER_FLAG_WIDTH, idle); - g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); - - g.b.switch_to_block(suspended); - let delay = g.equals(status, code(ProcessStatus::Delay)); - let inactive = g.equals(status, code(ProcessStatus::InactiveDelay)); - let delayed = g.binary(1, delay, BinaryOp::Or, inactive); - let wait = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: delayed, - true_block: (wait, Vec::new()), - false_block: (internal_exit, Vec::new()), - }); - g.b.switch_to_block(wait); - let amount = g.load(process.delay, celox_design::PROCESS_DELAY_WIDTH); - let wake = g.binary(SCHEDULER_TIME_WIDTH, time, BinaryOp::Add, amount); - let overflow = g.binary(1, wake, BinaryOp::LtU, time); - let overflow_exit = g.exit_block(SchedulerExit::DelayOverflow, None); - let in_range = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: overflow, - true_block: (overflow_exit, Vec::new()), - false_block: (in_range, Vec::new()), + cond: more, + true_block: (check, Vec::new()), + false_block: (pick, Vec::new()), }); - g.b.switch_to_block(in_range); - g.store(slots.wake[index], SCHEDULER_TIME_WIDTH, wake); - g.b.seal_block(SIRTerminator::Jump(resumed, Vec::new())); - - g.b.switch_to_block(resumed); - let mut edges = mask; - for (&event, &was) in kernel.writes.iter().zip(&before) { - let is = g.level(&self.events[event]); - let changed = g.binary(1, was, BinaryOp::Ne, is); - let active = g.equals(is, u64::from(self.events[event].active)); - let edge = g.binary(1, changed, BinaryOp::And, active); - let set = g.constant(1 << event, MAX_EVENTS); - let unset = g.constant(0, MAX_EVENTS); - let bit = g.b.alloc_bit(MAX_EVENTS, false); - g.b.emit(SIRInstruction::Mux(bit, edge, set, unset)); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); - } - g.b.seal_block(SIRTerminator::Jump(join, vec![edges])); - g.b.switch_to_block(join); - mask = joined; + g.b.switch_to_block(check); + g.check_waits(&waits_of(&waits, &ordinals)); + g.b.seal_block(SIRTerminator::Jump(pick, Vec::new())); } - // The settle after the kernels, shared with the one after the - // domains: the mask waits in `exit_arg` meanwhile. + // The settles after a pass and after the domains share one copy of + // combinational logic. + g.b.switch_to_block(pass_end); let none = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); g.store(slots.current, SCHEDULER_TIME_WIDTH, none); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, mask); let comb = g.b.new_block(); g.call_comb(comb, 1); + // A settle whose inputs did not change since the last one would + // write what combinational logic already holds: it is skipped. g.b.switch_to_block(comb); - for unit in &program.sir.eval_comb { - g.inline(unit, finish_exit); + if g.settle_reads.is_some() { + let dirty = g.load(slots.dirty, SCHEDULER_FLAG_WIDTH); + let zero = g.constant(0, SCHEDULER_FLAG_WIDTH); + let changed = g.binary(1, dirty, BinaryOp::Ne, zero); + let settle = g.b.new_block(); + let settled = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: changed, + true_block: (settle, Vec::new()), + false_block: (settled, Vec::new()), + }); + g.b.switch_to_block(settle); + for unit in &program.sir.eval_comb { + g.inline(unit, finish_exit); + } + let clean = g.constant(0, SCHEDULER_FLAG_WIDTH); + g.store(slots.dirty, SCHEDULER_FLAG_WIDTH, clean); + g.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); + g.b.switch_to_block(settled); + } else { + for unit in &program.sir.eval_comb { + g.inline(unit, finish_exit); + } } let continuation = g.load(slots.cont, SCHEDULER_FLAG_WIDTH); let settled = g.b.new_block(); @@ -484,75 +1002,82 @@ impl Plan { default: internal_exit, }); - // The domains the edges trigger. + // After the settle of a pass the waits see its writes; woken + // kernels run in another pass. g.b.switch_to_block(settled); - if written.is_empty() { - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); - g.b.switch_to_block(slot_end); - g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); - return g.finish(); - } + g.check_waits(&waits_of(&waits, &ordinals)); + let ready = g.load(slots.ready, MAX_KERNELS); + let zero = g.constant(0, MAX_KERNELS); + let more = g.binary(1, ready, BinaryOp::Ne, zero); + let domains = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: more, + true_block: (pick, Vec::new()), + false_block: (domains, Vec::new()), + }); + + // The domains the edges trigger, then the NBA region. + g.b.switch_to_block(domains); + let staged: Vec<&Staged> = waits.iter().flat_map(|(_, wait)| &wait.sites).collect(); let mask = g.load(slots.exit_arg, MAX_EVENTS); let zero = g.constant(0, MAX_EVENTS); let quiet = g.binary(1, mask, BinaryOp::Eq, zero); let triggered = g.b.new_block(); + let untriggered = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { cond: quiet, - true_block: (slot_end, Vec::new()), + true_block: (untriggered, Vec::new()), false_block: (triggered, Vec::new()), }); - g.b.switch_to_block(triggered); - let one = g.constant(1, MAX_EVENTS); - let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); - let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); - let single = g.binary(1, others, BinaryOp::Eq, zero); - let one_domain = g.b.new_block(); - let domains = g.b.new_block(); - let evaluated = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: single, - true_block: (one_domain, Vec::new()), - false_block: (domains, Vec::new()), - }); - // One triggered domain evaluates and applies at once. - g.b.switch_to_block(one_domain); - for &index in &written { - let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); - let this = g.binary(1, mask, BinaryOp::Eq, bit); - let unit = g.b.new_block(); - let next = g.b.new_block(); + // Without a domain, published nonblocking values settle once more. + g.b.switch_to_block(untriggered); + if staged.is_empty() { + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } else { + let mut any = g.constant(0, 1); + for site in &staged { + let pending = g.load(site.pending, 1); + any = g.binary(1, any, BinaryOp::Or, pending); + } + g.publish(&staged); + let publish_settle = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: this, - true_block: (unit, Vec::new()), - false_block: (next, Vec::new()), + cond: any, + true_block: (publish_settle, Vec::new()), + false_block: (slot_end, Vec::new()), }); - g.b.switch_to_block(unit); - for unit in &event.eval_apply { - g.inline(unit, finish_exit); - } - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); - g.b.switch_to_block(next); - } - g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); - - // Several evaluate, then apply, each in event order. - g.b.switch_to_block(domains); - if written.len() < 2 { - g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); - g.b.switch_to_block(evaluated); + g.b.switch_to_block(publish_settle); g.call_comb(comb, 2); - g.b.switch_to_block(slot_end); - g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); - return g.finish(); } - for phase in [Phase::Evaluate, Phase::Apply] { - for &index in &written { + + g.b.switch_to_block(triggered); + let evaluated = g.b.new_block(); + if edged.is_empty() { + // No event can have an edge; the mask stays empty. + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + } else { + let one = g.constant(1, MAX_EVENTS); + let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); + let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let single = g.binary(1, others, BinaryOp::Eq, zero); + let one_domain = g.b.new_block(); + let domains = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: single, + true_block: (one_domain, Vec::new()), + false_block: (domains, Vec::new()), + }); + + // One triggered domain evaluates and applies at once. The events + // kernels write are tested first: a run without clocks reaches + // their domains as soon as without clock events. + g.b.switch_to_block(one_domain); + let written = self.written(); + for &index in written.iter().chain(&self.clocks) { let event = &self.events[index]; let bit = g.constant(1 << index, MAX_EVENTS); - let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); - let this = g.binary(1, selected, BinaryOp::Ne, zero); + let this = g.binary(1, mask, BinaryOp::Eq, bit); let unit = g.b.new_block(); let next = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { @@ -561,23 +1086,132 @@ impl Plan { false_block: (next, Vec::new()), }); g.b.switch_to_block(unit); - let units = match phase { - Phase::Evaluate => &event.eval_only, - Phase::Apply => &event.apply, - }; - for unit in units { - g.inline(unit, finish_exit); + for unit in &event.eval_apply { + g.inline_writer(unit, finish_exit); } - g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); g.b.switch_to_block(next); } + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + + // Several evaluate, then apply, each in event order. + g.b.switch_to_block(domains); + if edged.len() < 2 { + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + } else { + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in &edged { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); + let this = g.binary(1, selected, BinaryOp::Ne, zero); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + let units = match phase { + Phase::Evaluate => &event.eval_only, + Phase::Apply => &event.apply, + }; + for unit in units { + g.inline_writer(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + g.b.switch_to_block(next); + } + } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + } } - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + // The domains' results and the nonblocking values publish before + // combinational logic settles. g.b.switch_to_block(evaluated); + g.publish(&staged); g.call_comb(comb, 2); + // At the end of the slot each clock whose edge applied waits for the + // opposite level, half a period later, in event order (as + // `rearm_clocks`): the extra time unit of an odd period goes to the + // high phase. The reference re-arms at the end of the slot's first + // round (`continue_round`); a compiled slot has a single round, as + // no kernel it runs resumes in the same slot. g.b.switch_to_block(slot_end); + if let Some((started, clocked)) = started { + let overflow_exit = g.exit_block(SchedulerExit::ClockOverflow); + let rearms = g.b.new_block(); + let rearmed = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: clocked, + true_block: (rearms, Vec::new()), + false_block: (rearmed, Vec::new()), + }); + g.b.switch_to_block(rearms); + // The clocks whose edge applied are those the slot disarmed. + let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); + let all = g.constant(u64::MAX, SCHEDULER_CLOCKS); + let unarmed = g.binary(SCHEDULER_CLOCKS, armed, BinaryOp::Xor, all); + let fired = g.binary(SCHEDULER_CLOCKS, started, BinaryOp::And, unarmed); + for bit in 0..self.clocks.len() { + let applied = g.mask_bit(fired, bit); + let rearm = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: applied, + true_block: (rearm, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(rearm); + let values = g.load(slots.clock_value, SCHEDULER_TIME_WIDTH); + let high = g.mask_bit(values, bit); + let period = g.load_at( + slots.clock_period, + bit * SCHEDULER_TIME_WIDTH, + SCHEDULER_TIME_WIDTH, + ); + let one = g.constant(1, SCHEDULER_TIME_WIDTH); + let half = g.binary(SCHEDULER_TIME_WIDTH, period, BinaryOp::Shr, one); + let odd = g.binary(SCHEDULER_TIME_WIDTH, period, BinaryOp::And, one); + let even = g.constant(0, SCHEDULER_TIME_WIDTH); + let extra = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); + g.b.emit(SIRInstruction::Mux(extra, high, odd, even)); + let half = g.binary(SCHEDULER_TIME_WIDTH, half, BinaryOp::Add, extra); + let next_edge = g.binary(SCHEDULER_TIME_WIDTH, time, BinaryOp::Add, half); + let overflow = g.binary(1, next_edge, BinaryOp::LtU, time); + let overflowed = g.b.new_block(); + let in_range = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: overflow, + true_block: (overflowed, Vec::new()), + false_block: (in_range, Vec::new()), + }); + g.b.switch_to_block(overflowed); + let clock = g.constant(bit as u64, SCHEDULER_TIME_WIDTH); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, clock); + g.b.seal_block(SIRTerminator::Jump(overflow_exit, Vec::new())); + g.b.switch_to_block(in_range); + g.store_at( + slots.clock_next, + bit * SCHEDULER_TIME_WIDTH, + SCHEDULER_TIME_WIDTH, + next_edge, + ); + let flip = g.constant(1 << bit, SCHEDULER_CLOCKS); + let values = g.binary(SCHEDULER_CLOCKS, values, BinaryOp::Xor, flip); + g.store(slots.clock_value, SCHEDULER_TIME_WIDTH, values); + let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); + let armed = g.binary(SCHEDULER_CLOCKS, armed, BinaryOp::Or, flip); + g.store(slots.clock_armed, SCHEDULER_TIME_WIDTH, armed); + g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + g.b.switch_to_block(next); + } + g.b.seal_block(SIRTerminator::Jump(rearmed, Vec::new())); + g.b.switch_to_block(rearmed); + } g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); g.finish() } @@ -593,7 +1227,10 @@ struct Generator<'a> { slots: &'a SchedulerSlots, finish_sites: &'a HashSet, /// Exit blocks not yet emitted. - exits: Vec<(celox_sir::BlockId, SchedulerExit, Option)>, + exits: Vec<(celox_sir::BlockId, SchedulerExit)>, + /// See [`Plan::settle_reads`]. + settle_reads: Option<&'a HashSet>, + shared: HashMap, } impl Generator<'_> { @@ -630,20 +1267,28 @@ impl Generator<'_> { } fn load(&mut self, address: AbsoluteAddr, width: usize) -> RegisterId { + self.load_at(address, 0, width) + } + + fn store(&mut self, address: AbsoluteAddr, width: usize, value: RegisterId) { + self.store_at(address, 0, width, value); + } + + fn load_at(&mut self, address: AbsoluteAddr, offset: usize, width: usize) -> RegisterId { let register = self.b.alloc_bit(width, false); self.b.emit(SIRInstruction::Load( register, stable(address), - SIROffset::Static(0), + SIROffset::Static(offset), width, )); register } - fn store(&mut self, address: AbsoluteAddr, width: usize, value: RegisterId) { + fn store_at(&mut self, address: AbsoluteAddr, offset: usize, width: usize, value: RegisterId) { self.b.emit(SIRInstruction::Store( stable(address), - SIROffset::Static(0), + SIROffset::Static(offset), width, value, Vec::new(), @@ -651,6 +1296,24 @@ impl Generator<'_> { )); } + /// The time of host clock `bit`'s next edge. + fn clock_next(&mut self, bit: usize) -> RegisterId { + self.load_at( + self.slots.clock_next, + bit * SCHEDULER_TIME_WIDTH, + SCHEDULER_TIME_WIDTH, + ) + } + + /// Whether bit `bit` of `mask` is set. + fn mask_bit(&mut self, mask: RegisterId, bit: usize) -> RegisterId { + let width = self.b.register(&mask).width(); + let selector = self.constant(1 << bit, width); + let selected = self.binary(width, mask, BinaryOp::And, selector); + let zero = self.constant(0, width); + self.binary(1, selected, BinaryOp::Ne, zero) + } + /// The edge level of `event`'s signal, as the runtime reads it: whether /// its low byte, within its width, is not zero. fn level(&mut self, event: &Event) -> RegisterId { @@ -660,14 +1323,140 @@ impl Generator<'_> { self.binary(1, value, BinaryOp::Ne, zero) } - /// A block that ends the run with `exit` and its argument, emitted by + /// A block that ends the run with `exit`, emitted by /// [`Self::emit_exits`]. - fn exit_block(&mut self, exit: SchedulerExit, argument: Option) -> celox_sir::BlockId { + fn exit_block(&mut self, exit: SchedulerExit) -> celox_sir::BlockId { let block = self.b.new_block(); - self.exits.push((block, exit, argument)); + self.exits.push((block, exit)); block } + /// Bit `index` of a 64-bit mask, set when `condition` holds. + fn bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { + let set = self.constant(1 << index, MAX_KERNELS); + let unset = self.constant(0, MAX_KERNELS); + let bit = self.b.alloc_bit(MAX_KERNELS, false); + self.b.emit(SIRInstruction::Mux(bit, condition, set, unset)); + bit + } + + /// The value of the one-bit signal `address`. + fn signal_level(&mut self, address: AbsoluteAddr) -> RegisterId { + self.load(address, 1) + } + + /// The one-bit `value` as a `width`-bit number. + fn widen(&mut self, value: RegisterId, width: usize) -> RegisterId { + let set = self.constant(1, width); + let unset = self.constant(0, width); + let wide = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Mux(wide, value, set, unset)); + wide + } + + /// Test the waits of `waits`, (kernel, ready bit, signal, edge), against their + /// signals now (`check_waits`): a wait whose edge occurred since its + /// baseline wakes its kernel; every changed signal becomes the + /// baseline. + fn check_waits(&mut self, waits: &[(usize, usize, AbsoluteAddr, CounterKind)]) { + if waits.is_empty() { + return; + } + let mut woken = self.constant(0, MAX_KERNELS); + for &(index, ordinal, signal, kind) in waits { + let waiting = self.waiting(index); + let baseline = self.load(self.slots.baseline[index], SCHEDULER_FLAG_WIDTH); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + let was = self.binary(1, baseline, BinaryOp::Ne, zero); + let is = self.signal_level(signal); + let changed = self.binary(1, was, BinaryOp::Ne, is); + let occurred = match kind { + CounterKind::Changes => changed, + CounterKind::Rises => self.binary(1, changed, BinaryOp::And, is), + CounterKind::Falls => self.binary(1, changed, BinaryOp::And, was), + }; + let wake = self.binary(1, occurred, BinaryOp::And, waiting); + let level = self.widen(is, SCHEDULER_FLAG_WIDTH); + let next = self.b.alloc_bit(SCHEDULER_FLAG_WIDTH, false); + self.b + .emit(SIRInstruction::Mux(next, waiting, level, baseline)); + self.store(self.slots.baseline[index], SCHEDULER_FLAG_WIDTH, next); + let one = self.constant(1, 1); + let stays = self.binary(1, wake, BinaryOp::Xor, one); + let still = self.binary(1, waiting, BinaryOp::And, stays); + let flag = self.widen(still, SCHEDULER_FLAG_WIDTH); + self.store(self.slots.waiting[index], SCHEDULER_FLAG_WIDTH, flag); + let bit = self.bit(wake, ordinal); + woken = self.binary(MAX_KERNELS, woken, BinaryOp::Or, bit); + } + let ready = self.load(self.slots.ready, MAX_KERNELS); + let ready = self.binary(MAX_KERNELS, ready, BinaryOp::Or, woken); + self.store(self.slots.ready, SCHEDULER_TIME_WIDTH, ready); + } + + /// Publish the staged values of `sites` whose pending flag is set into + /// their targets, clearing the flags (`publish_nba`). + fn publish(&mut self, sites: &[&Staged]) { + for site in sites { + let pending = self.load(site.pending, 1); + let publish = self.b.new_block(); + let next = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: pending, + true_block: (publish, Vec::new()), + false_block: (next, Vec::new()), + }); + self.b.switch_to_block(publish); + let clear = self.constant(0, 1); + self.store(site.pending, 1, clear); + let value = self.load(site.value, site.width); + self.b.emit(SIRInstruction::Store( + stable(site.target), + SIROffset::Static(site.lsb), + site.width, + value, + Vec::new(), + Vec::new(), + )); + if self.settle_reads(site.target) { + self.mark_dirty(); + } + self.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + self.b.switch_to_block(next); + } + } + + /// Whether combinational logic reads `address`, when settles may be + /// skipped. + fn settle_reads(&self, address: AbsoluteAddr) -> bool { + let storage = self.shared.get(&address).copied().unwrap_or(address); + self.settle_reads + .is_some_and(|reads| reads.contains(&storage)) + } + + /// Record that state combinational logic reads may have changed. + fn mark_dirty(&mut self) { + if self.settle_reads.is_some() { + let one = self.constant(1, SCHEDULER_FLAG_WIDTH); + self.store(self.slots.dirty, SCHEDULER_FLAG_WIDTH, one); + } + } + + /// Inline `unit` as [`Self::inline`] does, and record a change of what + /// combinational logic reads after it when it may write any. + fn inline_writer(&mut self, unit: &Unit, finish_exit: celox_sir::BlockId) { + self.inline(unit, finish_exit); + let writes = instructions(unit).any(|inst| match inst { + SIRInstruction::Store(target, ..) | SIRInstruction::Commit(_, target, ..) => { + self.settle_reads(target.absolute_addr()) + } + _ => false, + }); + if writes { + self.mark_dirty(); + } + } + /// The unit, once every block is sealed. fn finish(mut self) -> Unit { self.emit_exits(); @@ -680,14 +1469,10 @@ impl Generator<'_> { } fn emit_exits(&mut self) { - for (block, exit, argument) in std::mem::take(&mut self.exits) { + for (block, exit) in std::mem::take(&mut self.exits) { self.b.switch_to_block(block); let code = self.constant(exit as u64, SCHEDULER_FLAG_WIDTH); self.store(self.slots.exit, SCHEDULER_FLAG_WIDTH, code); - if let Some(argument) = argument { - let argument = self.constant(argument, SCHEDULER_TIME_WIDTH); - self.store(self.slots.exit_arg, SCHEDULER_TIME_WIDTH, argument); - } self.b.seal_block(SIRTerminator::Return); } } @@ -775,6 +1560,55 @@ impl Generator<'_> { } } +/// The waits of `waits` as (kernel, its bit in the ready mask, signal, +/// edge). +fn waits_of( + waits: &[(usize, &Wait)], + ordinals: &[usize], +) -> Vec<(usize, usize, AbsoluteAddr, CounterKind)> { + waits + .iter() + .map(|(index, wait)| (*index, ordinals[*index], wait.signal, wait.kind)) + .collect() +} + +/// The place of each kernel among those the scheduler runs, in kernel +/// order; unused for the others. +fn ordinals(kernels: &[Option]) -> Vec { + let mut next = 0; + kernels + .iter() + .map(|kernel| { + let ordinal = next; + next += usize::from(kernel.is_some()); + ordinal + }) + .collect() +} + +/// Whether every two stable homes of `layout` either start at the same +/// offset or do not overlap. +fn homes_overlap_only_whole(layout: &crate::backend::MemoryLayout) -> bool { + let mut homes: Vec<(usize, usize)> = layout + .offsets + .iter() + .map(|(address, &offset)| { + let bytes = match layout.unpacked_arrays.get(address) { + Some(array) => array.plane_size, + None => layout + .widths + .get(address) + .map_or(0, |width| width.div_ceil(8)), + }; + (offset, offset + bytes) + }) + .collect(); + // The widest of the homes that start at one offset stands for them. + homes.sort_unstable_by_key(|&(start, end)| (start, std::cmp::Reverse(end))); + homes.dedup_by_key(|home| home.0); + homes.windows(2).all(|pair| pair[0].1 <= pair[1].0) +} + fn stable(address: AbsoluteAddr) -> RegionedAbsoluteAddr { RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address) } @@ -783,9 +1617,9 @@ fn instructions(unit: &Unit) -> impl Iterator bool { +/// Whether every status `unit` stores into `status` is a constant among +/// `allowed`. +fn statuses_only(unit: &Unit, status: AbsoluteAddr, allowed: &[ProcessStatus]) -> bool { let constants: HashMap = instructions(unit) .filter_map(|inst| match inst { SIRInstruction::Imm(register, value) => u64::try_from(&value.payload) @@ -794,13 +1628,10 @@ fn delay_statuses_only(unit: &Unit, status: AbsoluteAddr) -> bool { _ => None, }) .collect(); - let allowed = [ - ProcessStatus::Delay, - ProcessStatus::InactiveDelay, - ProcessStatus::Done, - ProcessStatus::Finish, - ] - .map(|status| u64::from(status.code())); + let allowed: Vec = allowed + .iter() + .map(|status| u64::from(status.code())) + .collect(); let status = stable(status); instructions(unit).all(|inst| match inst { SIRInstruction::Store(target, _, _, value, ..) if *target == status => constants diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 5cbcd773323..9f888db0b8a 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -100,16 +100,23 @@ impl StepObserver> for ShadowCheck<'_, B> { ) -> Result<(), RuntimeErrorCode> { let shadow = &mut *self.shadow; let mut reference = shadow.state.step_until(&mut shadow.simulator, limit); - // A compiled run of several slots: the shadow runs them one by one. - if let Ok(Some(time)) = result { + // A compiled run of several slots: the shadow runs them one by one, + // up to the last slot of the run, or to the slot a failed run ended + // in, where the reference must fail the same way. + let last = match result { + Ok(Some(time)) => Some(*time), + Ok(None) => None, + Err(_) => Some(state.time()), + }; + if let Some(time) = last { while let Ok(Some(reached)) = reference { - if reached >= *time + if reached >= time || shadow.state.is_finished() || shadow.state.is_stopped() || shadow .state .next_event_time() - .is_none_or(|next| next > *time) + .is_none_or(|next| next > time) { break; } @@ -503,6 +510,659 @@ mod tests { } } + /// Run `source` to `end` in every mode and compare the state files with + /// the reference's; at least one slot must run compiled. + fn agrees_with_the_reference(source: &str, end: u64) { + let mut reference = build_in(source, SchedulerMode::Reference); + reference.run_until(end).unwrap(); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(source, mode); + sim.run_until(end).unwrap(); + assert_eq!(sim.save_state().unwrap(), expected, "{mode:?}"); + let stats = sim.scheduler_stats(); + assert!(stats.compiled_slots > 0, "{mode:?}: {stats:?}"); + } + } + + /// A kernel waiting for a clock edge writes what the domain of that edge + /// samples, blocking and nonblocking. + #[test] + fn clock_kernels_run_in_compiled_slots() { + for assign in ["=", "<="] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] sum); + logic clk = 1'b0; + logic [7:0] stim = 8'd0; + logic [7:0] r = 8'd0; + always #5 clk = ~clk; + initial forever @(posedge clk) stim {assign} stim + 8'd3; + always_ff @(posedge clk) r <= r + stim; + assign sum = r; + endmodule" + ); + agrees_with_the_reference(&source, 1000); + } + } + + /// Kernels woken in the middle of a pass, declared before and after the + /// clock kernels, and waits for falling and any edges. + #[test] + fn clock_kernels_wake_in_the_reference_order() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] seen); + logic a = 1'b0; + logic b = 1'b0; + logic [7:0] log = 8'd0; + logic [7:0] acc = 8'd0; + initial forever @(posedge a) log = log * 8'd3 + 8'd1; + always #5 a = ~a; + initial forever @(negedge a) log = log * 8'd5 + 8'd2; + always #5 b = ~b; + initial forever @(b) log = log * 8'd7 + 8'd3; + initial forever @(posedge b) acc <= acc + log; + assign seen = log + acc; + endmodule + "#; + agrees_with_the_reference(source, 200); + } + + /// A clock kernel's `$finish` ends a compiled slot as the reference's. + #[test] + fn clock_kernels_finish_compiled_slots() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] n); + logic clk = 1'b0; + always #5 clk = ~clk; + initial begin + n = 8'd0; + forever @(posedge clk) begin + n = n + 8'd1; + if (n == 8'd7) $finish; + end + end + endmodule + "#; + agrees_with_the_reference(source, 1000); + } + + /// Compiled kernels declared after more than 64 others keep their own + /// bits in the ready mask. + #[test] + fn compiled_kernels_after_many_processes() { + let mut source = String::from( + "`timescale 1ns/1ns\nmodule Top(output logic [7:0] n);\nlogic clk = 1'b0;\n", + ); + for index in 0..66 { + source.push_str(&format!( + "logic d{index} = 1'b0;\ninitial #0 d{index} = 1'b1;\n" + )); + } + source.push_str( + "always #5 clk = ~clk;\n\ + initial begin n = 8'd0; forever @(posedge clk) n = n + 8'd1; end\n\ + endmodule\n", + ); + agrees_with_the_reference(&source, 200); + } + + /// A kernel that waits and then loops without suspending yields now and + /// then, and keeps the reference loop. + #[test] + fn waiting_kernels_that_yield_fall_back() { + let reasons = |source: &str| -> Vec { + build_in(source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels + .into_iter() + .filter_map(|kernel| match kernel { + crate::KernelSchedule::Reference(reason) => Some(reason), + crate::KernelSchedule::Compiled => None, + }) + .collect() + }; + // A loop that does not suspend yields now and then. + let spinning = r#" + `timescale 1ns/1ns + module Top(output logic q); + logic clk = 1'b0; + always #5 clk = ~clk; + initial begin q = 1'b0; @(posedge clk); forever q <= ~q; end + endmodule + "#; + assert_eq!( + reasons(spinning), + ["the process suspends other than for one edge"] + ); + } + + /// A nonblocking site in a loop runs several times in one run of its + /// kernel. A loop the frontend keeps yields now and then, and the + /// copies of one it unrolls queue their values: either way the kernel + /// keeps the reference loop, and every mode leaves its state. + #[test] + fn nonblocking_sites_in_loops_keep_the_reference_loop() { + for (bound, reason) in [ + ("n", "the process suspends other than for one edge"), + ("2", "a nonblocking site queues its values"), + ] { + for tail in ["", "$finish;"] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] q); + logic clk = 1'b0; + int n = 2; + always #5 clk = ~clk; + initial begin + q = 8'd0; + forever begin + @(posedge clk); + for (int i = 0; i < {bound}; i++) q <= q + 8'(i) + 8'd1; + {tail} + end + end + endmodule" + ); + let kernels = build_in(&source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels; + assert!( + kernels.contains(&crate::KernelSchedule::Reference(reason.into())), + "{bound} {tail}: {kernels:?}" + ); + let mut reference = build_in(&source, SchedulerMode::Reference); + reference.run_until(100).unwrap(); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(&source, mode); + sim.run_until(100).unwrap(); + assert_eq!( + sim.save_state().unwrap(), + expected, + "{bound} {tail} {mode:?}" + ); + } + } + } + } + + /// A nonblocking update into what a stateful combinational process, a + /// latch, is sensitive to bumps its occurrence counter when the + /// reference publishes it: the kernel keeps the reference loop, and + /// every mode leaves the reference's state and records. + #[test] + fn nonblocking_updates_into_probed_signals_keep_the_reference_loop() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] n); + logic clk = 1'b0; + logic [7:0] q = 8'd0; + always #5 clk = ~clk; + logic [7:0] l; + initial forever @(posedge clk) q <= q + 8'd1; + always_latch if (q[0]) l = q; + assign n = l; + endmodule + "#; + let kernels = build_in(source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels; + // The frontend queues this site's values, and a staged one would + // keep the reference loop too (`Plan::new`). + assert!( + matches!(kernels[1], crate::KernelSchedule::Reference(_)), + "{kernels:?}" + ); + let displays = |sim: &mut Simulation| { + sim.drain_runtime_events() + .into_iter() + .filter(|event| matches!(event, crate::RuntimeEvent::Display { .. })) + .count() + }; + let mut reference = build_in(source, SchedulerMode::Reference); + reference.run_until(100).unwrap(); + let expected = (reference.save_state().unwrap(), displays(&mut reference)); + for mode in MODES { + let mut sim = build_in(source, mode); + sim.run_until(100).unwrap(); + let state = sim.save_state().unwrap(); + assert_eq!((state, displays(&mut sim)), expected, "{mode:?}"); + } + } + + /// What the host does before a run. + #[derive(Clone, Copy)] + enum Host { + Clock(&'static str, u64, u64), + Set(&'static str, u8), + Schedule(&'static str, u64, u64), + } + + fn drive(sim: &mut Simulation, actions: &[Host]) { + for &action in actions { + match action { + Host::Clock(port, period, delay) => sim.add_clock(port, period, delay), + Host::Set(port, value) => { + let signal = sim.signal(port); + sim.modify(|io| io.set(signal, value)).unwrap(); + } + Host::Schedule(port, time, value) => sim.schedule(port, time, value).unwrap(), + } + } + } + + /// Run `source`, whose kernels all compile, in every mode on the native + /// and Cranelift backends: before each run until `end`, the host does + /// `actions`, and afterwards the state file is the reference's. At least + /// one slot must run compiled. + fn host_driven_agrees(source: &str, runs: &[(u64, &[Host])]) { + let kernels = build_in(source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels; + assert!( + kernels + .iter() + .all(|kernel| *kernel == crate::KernelSchedule::Compiled), + "{kernels:?}" + ); + let mut reference = build_in(source, SchedulerMode::Reference); + let mut expected = Vec::new(); + for &(end, actions) in runs { + drive(&mut reference, actions); + reference.run_until(end).unwrap(); + expected.push(reference.save_state().unwrap()); + } + fn check( + mut sim: Simulation, + runs: &[(u64, &[Host])], + expected: &[crate::StateFile], + label: &str, + ) { + for (run, &(end, actions)) in runs.iter().enumerate() { + drive(&mut sim, actions); + sim.run_until(end).unwrap(); + assert_eq!( + sim.save_state().unwrap(), + expected[run], + "{label} run {run}" + ); + } + let stats = sim.scheduler_stats(); + assert!(stats.compiled_slots > 0, "{label}: {stats:?}"); + } + for mode in MODES { + check( + build_in(source, mode), + runs, + &expected, + &format!("{mode:?}"), + ); + let cranelift = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .scheduler_mode(mode) + .build_cranelift() + .unwrap(); + check(cranelift, runs, &expected, &format!("cranelift {mode:?}")); + } + } + + /// Kernels waiting for a host clock run in compiled slots with the + /// domain of their edge, blocking and nonblocking. + #[test] + fn host_clocks_run_in_compiled_slots() { + for assign in ["=", "<="] { + let source = format!( + "`timescale 1ns/1ns + module Top(input logic clk, output logic [7:0] sum); + logic [7:0] stim = 8'd0; + logic [7:0] r = 8'd0; + initial forever @(posedge clk) stim {assign} stim + 8'd3; + always_ff @(posedge clk) r <= r + stim; + assign sum = r; + endmodule" + ); + host_driven_agrees(&source, &[(1000, &[Host::Clock("clk", 10, 5)])]); + } + } + + /// Host clocks with coinciding edges, odd and short periods, a kernel + /// clock in the same slots, and waits for falling and any edges. + #[test] + fn coincident_host_clocks_run_in_compiled_slots() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic a, input logic b, input logic c, output logic [7:0] seen); + logic g = 1'b0; + logic [7:0] log = 8'd0; + logic [7:0] acc = 8'd0; + logic [7:0] ra = 8'd0; + logic [7:0] rb = 8'd0; + logic [7:0] rg = 8'd0; + logic [7:0] rc = 8'd0; + initial forever @(posedge a) log = log * 8'd3 + 8'd1; + always #3 g = ~g; + initial forever @(negedge b) log = log * 8'd5 + 8'd2; + initial forever @(c) acc <= acc + log; + always_ff @(posedge a) ra <= ra + log; + always_ff @(negedge b) rb <= rb + acc; + always_ff @(posedge g) rg <= rg + ra + rb; + always_ff @(posedge c) rc <= rc + log; + assign seen = log + acc + rg + rc; + endmodule + "#; + for (a, b, c) in [(10, 6, 15), (7, 3, 1), (2, 5, 9)] { + host_driven_agrees( + source, + &[( + 300, + &[ + Host::Clock("a", a, 1), + Host::Clock("b", b, 3), + Host::Clock("c", c, 2), + ], + )], + ); + } + } + + /// Host writes, of a clocked signal too, a clock added later, a one-shot + /// event on a clocked signal and a clock added twice to one event + /// between runs. + #[test] + fn host_clocks_agree_across_host_changes() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic clk, input logic clk2, input logic go, input logic [7:0] k, + output logic [7:0] q); + logic [7:0] n = 8'd0; + logic [7:0] m = 8'd0; + logic [7:0] r = 8'd0; + logic [7:0] r2 = 8'd0; + logic [7:0] boost = 8'd0; + initial forever @(posedge clk) n = n + k + boost; + initial @(posedge go) boost = 8'd5; + initial forever @(posedge clk2) m <= m + n; + always_ff @(posedge clk) r <= r + n + m; + always_ff @(posedge clk2) r2 <= r2 ^ m; + assign q = r + r2; + endmodule + "#; + host_driven_agrees( + source, + &[ + (100, &[Host::Set("k", 1), Host::Clock("clk", 10, 5)]), + ( + 200, + &[ + Host::Set("k", 3), + Host::Set("go", 1), + Host::Clock("clk2", 7, 2), + ], + ), + (300, &[Host::Schedule("clk", 253, 1)]), + (400, &[Host::Clock("clk2", 4, 1)]), + (500, &[Host::Set("clk", 1)]), + (600, &[Host::Set("clk", 0), Host::Set("clk2", 1)]), + ], + ); + } + + /// A kernel's `$finish` in a slot with a host clock edge, and a state + /// file and a checkpoint taken between runs and restored. + #[test] + fn host_clocks_finish_and_restore_as_the_reference() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic clk, input logic clk2, output logic [7:0] n); + logic [7:0] r = 8'd0; + initial begin + n = 8'd0; + forever @(posedge clk) begin + n = n + 8'd1; + if (n == 8'd40) $finish; + end + end + logic [7:0] q = 8'd0; + always_ff @(posedge clk2) r <= r + n; + always_ff @(posedge clk) q <= q ^ r; + endmodule + "#; + let clocks = [Host::Clock("clk", 10, 5), Host::Clock("clk2", 3, 1)]; + host_driven_agrees(source, &[(100, &clocks), (1000, &[])]); + // A state file and a checkpoint taken in the middle continue as the + // reference does. + let mut reference = build_in(source, SchedulerMode::Reference); + drive(&mut reference, &clocks); + reference.run_until(1000).unwrap(); + assert!(reference.is_finished()); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(source, mode); + drive(&mut sim, &clocks); + sim.run_until(133).unwrap(); + let state = sim.save_state().unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + sim.run_until(1000).unwrap(); + assert_eq!(sim.save_state().unwrap(), expected, "{mode:?}"); + sim.restore(&checkpoint).unwrap(); + sim.run_until(1000).unwrap(); + assert_eq!(sim.save_state().unwrap(), expected, "{mode:?} checkpoint"); + let mut loaded = build_in(source, mode); + loaded.load_state(&state).unwrap(); + loaded.run_until(1000).unwrap(); + assert_eq!( + loaded.save_state().unwrap(), + expected, + "{mode:?} state file" + ); + } + } + + /// The next edge of a host clock that overflows the simulation time + /// fails the run as the reference's, after the clocks before it in the + /// slot re-armed. + #[test] + fn host_clock_overflow_fails_as_the_reference() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic a, input logic b, output logic [7:0] n); + logic [7:0] ra = 8'd0; + logic [7:0] rb = 8'd0; + initial begin n = 8'd0; forever @(posedge b) n = n + 8'd1; end + always_ff @(posedge a) ra <= ra + n; + always_ff @(posedge b) rb <= rb + ra; + endmodule + "#; + let run = |mode: SchedulerMode| { + let mut sim = build_in(source, mode); + sim.add_clock("a", 4, u64::MAX - 3); + sim.add_clock("b", 10, u64::MAX - 3); + let error = sim.run_until(u64::MAX).unwrap_err(); + (error.to_string(), sim.save_state().unwrap(), sim) + }; + let (expected_error, expected, _) = run(SchedulerMode::Reference); + assert!( + expected_error.contains("overflows simulation time"), + "{expected_error}" + ); + for mode in MODES { + let (error, state, sim) = run(mode); + assert_eq!(error, expected_error, "{mode:?}"); + assert_eq!(state, expected, "{mode:?}"); + assert!(sim.scheduler_stats().compiled_slots > 0, "{mode:?}"); + } + } + + /// Events only the host writes and no clock drives, a reset and a clock + /// input: runs skip the clock code, host writes of them between runs + /// reach their domains in the reference loop, and a `$finish` in the + /// middle of a slot leaves their baselines as the reference's. + #[test] + fn unclocked_host_events_agree() { + for finish in ["", "initial #47 $finish;"] { + let source = format!( + "`timescale 1ns/1ns + module Top(input logic rst_n, input logic clk2, output logic [7:0] q); + logic clk = 1'b0; + logic [7:0] q2 = 8'd0; + always #5 clk = ~clk; + {finish} + always_ff @(posedge clk or negedge rst_n) + if (!rst_n) q <= 8'd0; else q <= q + 8'd1; + always_ff @(posedge clk2) q2 <= q2 + q; + endmodule" + ); + host_driven_agrees( + &source, + &[ + (100, &[Host::Set("rst_n", 1), Host::Set("clk2", 1)]), + (200, &[Host::Set("rst_n", 0), Host::Set("clk2", 0)]), + (300, &[Host::Set("rst_n", 1), Host::Set("clk2", 1)]), + ], + ); + } + } + + /// Combinational logic reads what each writer changes, on slots where + /// no domain triggers: a kernel's blocking write, a published + /// nonblocking value, a host clock's level and a host input written + /// between runs, besides a domain's registers. Each change reaches the + /// combinational outputs in the state file as in the reference. + #[test] + fn settles_follow_every_write() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic h, input logic [7:0] k, output logic [7:0] y); + logic clk = 1'b0; + logic [7:0] stim = 8'd0; + logic [7:0] staged = 8'd0; + logic [7:0] r = 8'd0; + logic [7:0] rh = 8'd0; + logic [7:0] w; + always #5 clk = ~clk; + initial forever @(negedge clk) stim = stim + 8'd1; + initial forever @(negedge clk) staged <= staged + 8'd2; + always_ff @(posedge clk) r <= r + w; + always_ff @(posedge h) rh <= rh + 8'd1; + assign w = stim * 8'd3 + staged + k + {7'd0, h}; + assign y = w ^ r ^ rh; + endmodule + "#; + host_driven_agrees( + source, + &[ + (100, &[Host::Set("k", 1)]), + (200, &[Host::Clock("h", 7, 3)]), + (300, &[Host::Set("k", 9)]), + (400, &[]), + ], + ); + } + + /// A clock on an event a kernel drives, or added twice to one event, + /// stays with the reference loop and bounds the compiled runs. + #[test] + fn other_host_clocks_bound_compiled_runs() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic h, output logic [7:0] n); + logic clk = 1'b0; + logic [7:0] r = 8'd0; + logic [7:0] r2 = 8'd0; + always #5 clk = ~clk; + initial begin n = 8'd0; forever @(posedge clk) n = n + 8'd1; end + always_ff @(posedge clk) r <= r + n; + always_ff @(posedge h) r2 <= r2 ^ n; + endmodule + "#; + host_driven_agrees(source, &[(300, &[Host::Clock("clk", 6, 2)])]); + host_driven_agrees( + source, + &[(300, &[Host::Clock("h", 20, 2), Host::Clock("h", 20, 7)])], + ); + } + + /// A compiled run of several slots that fails in a later one: the + /// shadow catches up to that slot and fails the same way, so every mode + /// reports the reference's error and leaves its state. + #[test] + fn compiled_runs_that_fail_after_several_slots_agree() { + let source = r#" + `timescale 1fs/1fs + module Top(output logic [7:0] x); + logic clk = 1'b0; + logic [7:0] r = 8'd0; + always #5 clk = ~clk; + always_ff @(posedge clk) r <= r + 8'd1; + initial begin + x = 8'd0; + #30 x = 8'd1; + #(64'd18446744073709551605) x = 8'd2; + end + endmodule + "#; + let run = |mode: SchedulerMode| { + let mut sim = build_in(source, mode); + let error = sim.run_until(100).unwrap_err().to_string(); + (error, sim.time(), sim.save_state().unwrap(), sim) + }; + let (error, time, state, _) = run(SchedulerMode::Reference); + assert!(error.contains("delay overflows simulation time"), "{error}"); + assert_eq!(time, 30); + for mode in MODES { + let (mode_error, mode_time, mode_state, sim) = run(mode); + assert_eq!(mode_error, error, "{mode:?}"); + assert_eq!(mode_time, time, "{mode:?}"); + assert_eq!(mode_state, state, "{mode:?}"); + assert!(sim.scheduler_stats().compiled_slots > 1, "{mode:?}"); + } + } + + /// A delay-only kernel pulses the signal another kernel waits on within + /// one activation, with two stores or in a loop: the frontend counts the + /// signal's occurrences, the waiting kernel wakes on every pulse, and a + /// design that counts occurrences keeps the reference loop in every + /// mode. + #[test] + fn pulses_within_one_activation_wake_as_the_reference() { + for pulse in [ + "a = 1'b1; a = 1'b0;", + "for (int i = 0; i < 2; i++) a = ~a;", + "for (int i = 0; i < k; i++) a = ~a;", + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] n); + logic a = 1'b0; + int k = 2; + always #5 begin {pulse} end + initial begin n = 8'd0; forever @(posedge a) n = n + 8'd1; end + endmodule" + ); + let counted = + crate::KernelSchedule::Reference("the design counts event occurrences".into()); + let kernels = build_in(&source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels; + assert!( + kernels.iter().all(|kernel| *kernel == counted), + "{pulse}: {kernels:?}" + ); + let mut reference = build_in(&source, SchedulerMode::Reference); + reference.run_until(100).unwrap(); + let n = reference.signal("n"); + assert_eq!(reference.get(n), 20u8.into(), "{pulse}"); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(&source, mode); + sim.run_until(100).unwrap(); + assert_eq!(sim.save_state().unwrap(), expected, "{pulse} {mode:?}"); + } + } + } + #[test] fn differential_mode_reports_a_diverging_step() { let mut sim = build(SchedulerMode::Differential); diff --git a/crates/celox/tests/sv_update_events.rs b/crates/celox/tests/sv_update_events.rs index 86eb3f3aa72..ff14803b6bd 100644 --- a/crates/celox/tests/sv_update_events.rs +++ b/crates/celox/tests/sv_update_events.rs @@ -5,6 +5,20 @@ //! performed one by one, in the order they were scheduled (10.4.2). use std::path::Path; +/// The scheduler mode: `CELOX_SCHEDULER` set to `reference`, `compiled`, +/// `differential` or `differential-runs`, by default the library's. +#[allow(clippy::disallowed_methods)] // Opt-in test configuration is environment-driven. +fn scheduler_mode() -> celox::SchedulerMode { + match std::env::var("CELOX_SCHEDULER").as_deref() { + Ok("reference") => celox::SchedulerMode::Reference, + Ok("compiled") => celox::SchedulerMode::Compiled, + Ok("differential") => celox::SchedulerMode::Differential, + Ok("differential-runs") => celox::SchedulerMode::DifferentialRuns, + Ok(other) => panic!("unknown CELOX_SCHEDULER mode `{other}`"), + Err(_) => celox::SchedulerMode::default(), + } +} + macro_rules! update_events { ($module:ident, $backend:ident) => { mod $module { @@ -18,6 +32,7 @@ macro_rules! update_events { vec![(source.as_str(), Path::new("update_events.sv"))], "Top", ) + .scheduler_mode(scheduler_mode()) .$backend() .unwrap() } @@ -146,6 +161,7 @@ macro_rules! update_events { vec![(source, Path::new("pulse.sv"))], "Top", ) + .scheduler_mode(scheduler_mode()) .$backend() .unwrap(); sim.schedule("c", 1, 1).unwrap();