diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 56f9142a095..62994649eaa 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -880,10 +880,12 @@ 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`] and every [`SchedulerSlots::wake`] object. pub const SCHEDULER_TIME_WIDTH: usize = 64; /// Width of [`SchedulerSlots::exit`], [`SchedulerSlots::finish`], -/// [`SchedulerSlots::cont`] and every [`SchedulerSlots::waiting`] object. +/// [`SchedulerSlots::cont`] 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 @@ -911,11 +913,16 @@ 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, } impl SchedulerSlots { @@ -930,8 +937,10 @@ impl SchedulerSlots { 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(map).collect(), } } @@ -947,10 +956,12 @@ impl SchedulerSlots { &self.count, &self.current, &self.levels, + &self.ready, ] .into_iter() .chain(&self.wake) .chain(&self.waiting) + .chain(&self.baseline) } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 93bbcbc0acf..8022c93abd2 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2266,12 +2266,16 @@ fn declare_scheduler_slots( 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(), }) } diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index e7d4af37815..73f9bf955f7 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -59,9 +59,18 @@ pub(crate) struct SchedulerRefs { 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, } @@ -283,17 +292,45 @@ impl ResolvedSchedule { 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() diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index fb98dba1379..973e0dcdaac 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -5,8 +5,12 @@ use std::cmp::Reverse; 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::SimBackend, + timing::{Halt, copy_planes}, +}; impl SimulationState { /// Whether a compiled scheduler may run slots of this simulation. @@ -37,7 +41,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; } @@ -111,6 +118,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() { @@ -136,26 +165,69 @@ 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 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 { 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/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/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a36af8f6961..4c53415d477 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 = 30; 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..a569de75cdd 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_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) { @@ -91,6 +114,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 { @@ -200,13 +243,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 +264,44 @@ 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; + } + } - 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 +309,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 +327,135 @@ 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); + if program.layout().widths.get(&term.signal) != Some(&1) + || delay_writers.get(&signal) != Some(&1) + || rtl_stores.contains(&signal) + || other_stores.contains(&signal) + { + return Err( + "the process waits for a signal that one kernel that only delays does not drive alone", + ); + } + 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() @@ -301,24 +494,38 @@ impl Plan { finish_sites: &self.finish_sites, exits: Vec::new(), }; + 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); 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); - 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); - } + 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); } let limit = g.load(slots.limit, SCHEDULER_TIME_WIDTH); let after = g.binary(1, time, BinaryOp::GtU, limit); @@ -326,7 +533,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()), @@ -354,31 +561,68 @@ 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); + 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(); + 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,6 +630,9 @@ impl Plan { .iter() .map(|&event| g.level(&self.events[event])) .collect(); + let enter = g.b.new_block(); + g.b.seal_block(SIRTerminator::Jump(enter, Vec::new())); + g.b.switch_to_block(enter); g.inline(&program.sir.processes[index], finish_exit); let status = g.load(process.status, celox_design::PROCESS_STATUS_WIDTH); let code = |status: ProcessStatus| u64::from(status.code()); @@ -397,68 +644,112 @@ 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); @@ -484,75 +775,79 @@ 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] { + + g.b.switch_to_block(triggered); + let evaluated = g.b.new_block(); + if written.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. + 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 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,20 +856,52 @@ 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 { + for unit in &event.eval_apply { g.inline(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 written.len() < 2 { + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + } else { + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in &written { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); + let this = g.binary(1, selected, BinaryOp::Ne, zero); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + let units = match phase { + Phase::Evaluate => &event.eval_only, + Phase::Apply => &event.apply, + }; + for unit in units { + g.inline(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + g.b.switch_to_block(next); + } + } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + } } - g.b.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); g.b.switch_to_block(slot_end); @@ -593,7 +920,7 @@ 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)>, } impl Generator<'_> { @@ -660,14 +987,106 @@ 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(), + )); + self.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + self.b.switch_to_block(next); + } + } + /// The unit, once every block is sealed. fn finish(mut self) -> Unit { self.emit_exits(); @@ -680,14 +1099,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 +1190,32 @@ 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() +} + fn stable(address: AbsoluteAddr) -> RegionedAbsoluteAddr { RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address) } @@ -783,9 +1224,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 +1235,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 1135f129784..90df25ca51d 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,308 @@ 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:?}"); + } + } + + /// 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_detects_object_rng_divergence_before_randomize() { use crate::backend::SimBackend as _; 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();