diff --git a/crates/celox-bench/src/bin/layout-spike.rs b/crates/celox-bench/src/bin/layout-spike.rs index 0ba901e509a..df2b2408c55 100644 --- a/crates/celox-bench/src/bin/layout-spike.rs +++ b/crates/celox-bench/src/bin/layout-spike.rs @@ -357,6 +357,7 @@ mod tests { eval_apply_ffs: FxHashMap::default(), eval_comb_apply_ffs: FxHashMap::default(), merge_comb_apply: true, + eval_comb_stateful: None, eval_only_ffs: FxHashMap::default(), apply_ffs: FxHashMap::default(), parallel: None, diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 74cd4d8ab7f..eb09e08f828 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1361,6 +1361,11 @@ pub struct SchedulerSlots { /// last settle. The caller initializes this before every scheduler run; /// timed runs set it even after a checkpoint restore or partial-slot exit. pub dirty: A, + /// Set by a caller that observes the design itself (the compiled + /// testbench) while it runs the scheduler: a run that reaches its limit + /// then leaves a deferred settle pending instead of settling for the + /// host. + pub defer_limit_settle: A, /// The number of time slots the run ran. pub count: A, /// The kernel running when the run returned, `u64::MAX` for none. @@ -1399,6 +1404,7 @@ impl SchedulerSlots { finish: map(self.finish), cont: map(self.cont), dirty: map(self.dirty), + defer_limit_settle: map(self.defer_limit_settle), count: map(self.count), current: map(self.current), levels: map(self.levels), @@ -1423,6 +1429,7 @@ impl SchedulerSlots { &self.finish, &self.cont, &self.dirty, + &self.defer_limit_settle, &self.count, &self.current, &self.levels, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index cd7b58574b6..5a543089287 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1713,6 +1713,16 @@ pub fn schedule_symbolic_rtl_reporting_loops( tracing::debug!("[flatten] scheduler::sort: {:?}", s.elapsed()); } runtime_errors.extend(schedule.runtime_errors); + let eval_comb_stateful = schedule.stateful_targets.as_ref().map(|targets| { + targets + .iter() + .map(|target| RegionedAbsoluteAddr { + region: STABLE_REGION, + instance_id: target.id.instance_id, + var_id: target.id.var_id, + }) + .collect::>() + }); let stable_unit = |eu: ExecutionUnit| ExecutionUnit { entry_block_id: eu.entry_block_id, blocks: eu @@ -2188,6 +2198,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( eval_apply_ffs, eval_comb_apply_ffs, merge_comb_apply, + eval_comb_stateful, eval_only_ffs, apply_ffs, eval_comb, @@ -2767,6 +2778,7 @@ fn declare_scheduler_slots( finish: declare("finish".into(), FLAG), cont: declare("cont".into(), FLAG), dirty: declare("dirty".into(), FLAG), + defer_limit_settle: declare("defer_limit_settle".into(), FLAG), count: declare("count".into(), TIME), current: declare("current".into(), TIME), levels: declare("levels".into(), TIME), diff --git a/crates/celox-runtime/src/testbench.rs b/crates/celox-runtime/src/testbench.rs index 588c81fecce..78d01491897 100644 --- a/crates/celox-runtime/src/testbench.rs +++ b/crates/celox-runtime/src/testbench.rs @@ -406,8 +406,13 @@ pub fn bind_testbench_program( celox_testbench::KernelRequest::Statement(site) => { celox_testbench::KernelRequest::Statement(*site) } - celox_testbench::KernelRequest::Settle => { - celox_testbench::KernelRequest::Settle + celox_testbench::KernelRequest::Settle { reads } => { + celox_testbench::KernelRequest::Settle { + reads: reads + .iter() + .map(|address| backend.resolve_signal(address)) + .collect(), + } } celox_testbench::KernelRequest::Written { address, width } => { celox_testbench::KernelRequest::Written { diff --git a/crates/celox-sir-opt/src/optimizer/pipeline.rs b/crates/celox-sir-opt/src/optimizer/pipeline.rs index 9cacde726a8..e57fe74bc0a 100644 --- a/crates/celox-sir-opt/src/optimizer/pipeline.rs +++ b/crates/celox-sir-opt/src/optimizer/pipeline.rs @@ -73,6 +73,7 @@ mod tests { .collect(), eval_comb_apply_ffs: crate::HashMap::default(), merge_comb_apply: true, + eval_comb_stateful: None, eval_only_ffs: crate::HashMap::default(), apply_ffs: crate::HashMap::default(), parallel: None, diff --git a/crates/celox-sir-opt/src/optimizer/pipeline/process_tests.rs b/crates/celox-sir-opt/src/optimizer/pipeline/process_tests.rs index b9ca56d9de2..73b1804a545 100644 --- a/crates/celox-sir-opt/src/optimizer/pipeline/process_tests.rs +++ b/crates/celox-sir-opt/src/optimizer/pipeline/process_tests.rs @@ -154,6 +154,7 @@ fn optimize_process( eval_apply_ffs: crate::HashMap::default(), eval_comb_apply_ffs: crate::HashMap::default(), merge_comb_apply: true, + eval_comb_stateful: None, eval_only_ffs: crate::HashMap::default(), apply_ffs: crate::HashMap::default(), parallel: None, diff --git a/crates/celox-sir/src/lib.rs b/crates/celox-sir/src/lib.rs index aa22907c25e..d7867259687 100644 --- a/crates/celox-sir/src/lib.rs +++ b/crates/celox-sir/src/lib.rs @@ -45,6 +45,11 @@ pub struct SirProgram { /// FF program, so the combinational program exists once however many /// events there are. See [`SirProgram::comb_apply`]. pub merge_comb_apply: bool, + /// The storage of the `eval_comb` paths that keep state from one settle + /// to the next, as its scheduler found them: latches and other + /// previous-value reads, loops, guarded processes. Every other path is a + /// function of its inputs. `None` when unknown. + pub eval_comb_stateful: Option>, pub eval_only_ffs: HashMap>>, pub apply_ffs: HashMap>>, /// Lane-partitioned alternatives of the hot phases, present only when @@ -252,6 +257,9 @@ impl SirProgram { &mut map_state, ), merge_comb_apply: self.merge_comb_apply, + eval_comb_stateful: self + .eval_comb_stateful + .map(|stateful| stateful.into_iter().map(&mut map_state).collect()), eval_only_ffs: map_groups(self.eval_only_ffs, &mut map_event, &mut map_state), apply_ffs: map_groups(self.apply_ffs, &mut map_event, &mut map_state), processes: self @@ -1142,6 +1150,7 @@ mod program_mapping_tests { eval_apply_ffs: [(1u32, vec![unit])].into_iter().collect(), eval_comb_apply_ffs: HashMap::default(), merge_comb_apply: true, + eval_comb_stateful: None, eval_only_ffs: HashMap::default(), apply_ffs: HashMap::default(), parallel: None, diff --git a/crates/celox-sir/src/two_state.rs b/crates/celox-sir/src/two_state.rs index b3727c8ec69..939c18d73db 100644 --- a/crates/celox-sir/src/two_state.rs +++ b/crates/celox-sir/src/two_state.rs @@ -25,6 +25,7 @@ pub fn canonicalize_program(program: &mut SirProgram { /// The partitions of a partitioned settle, in schedule order; empty when /// the schedule runs as one pass. pub partitions: Vec>, + /// The targets of the paths that keep state from one settle to the next: + /// paths that read a previous value or loop, and guarded processes. + /// Every other path computes what it stores from its inputs alone (a + /// bit-level order may still load a range before the bits it needs are + /// stored, and then discards the stale bits). `None` when that is not + /// known per path: capture events, and partitioned settles, whose flags + /// keep what changed since the last one. + pub stateful_targets: Option>>, } /// Request to split a combinational schedule into partitions that run only @@ -4661,6 +4669,33 @@ fn sort_impl( ff.as_deref().map(|lowering| lowering.summaries()), ) .map_err(ClockSortError::Scheduler)?; + let component = &prepared.component_by_path; + let looping: HashSet = prepared + .adj + .iter() + .enumerate() + .flat_map(|(v, successors)| { + successors + .iter() + .filter(move |&&u| component[u] == component[v]) + .flat_map(move |&u| [u, v]) + }) + .collect(); + let stateful_targets = prepared + .input + .iter() + .enumerate() + .filter_map(|(index, path)| match &path.target { + LogicPathTarget::CombCaptureEvent { .. } => Some(None), + LogicPathTarget::Process { target, .. } => Some(Some(*target)), + LogicPathTarget::Var(target) + if !path.previous_sources.is_empty() || looping.contains(&index) => + { + Some(Some(*target)) + } + LogicPathTarget::Var(_) => None, + }) + .collect::>>(); let direct_ff_writes = prepared .direct_ff_writes_by_action .iter() @@ -4741,6 +4776,8 @@ fn sort_impl( .finish(&mut lowering.builder, &prepared.direct_ff_writes_by_action) .map_err(ClockSortError::Lowering)?; } + // Partition flags carry what changed from one settle to the next. + let stateful_targets = stateful_targets.filter(|_| plan.is_none()); Ok(ScheduleResult { execution_units: lowering.finish(), runtime_errors, @@ -4757,6 +4794,7 @@ fn sort_impl( .collect() }) .unwrap_or_default(), + stateful_targets, }) } diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 4f4aca0d10b..638c47dddde 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -292,8 +292,15 @@ pub struct TestbenchClock { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum KernelRequest { Statement(usize), - Settle, - Written { address: A, width: usize }, + /// Settle the DUT before the TB reads `reads`, the storage of DUT + /// signals its next expression loads. + Settle { + reads: Vec, + }, + Written { + address: A, + width: usize, + }, Error(String), } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index d9fb258b368..0c1979652e2 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -10,8 +10,8 @@ use std::{ use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Images retain generated TB scheduler continuations and clock state. -const CONTAINER_VERSION: u16 = 55; +// Images retain the scheduler's slots and the reads of TB settle requests. +const CONTAINER_VERSION: u16 = 56; const TRAILER_SIZE: usize = 32; // This optional prefix descriptor does not change the Postcard payload. Older // readers ignore framing flags and continue to locate the payload at EOF. diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 120cc5cc4fe..231e279f292 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -1165,6 +1165,7 @@ mod fused_hint_tests { .into_iter() .collect(), merge_comb_apply: true, + eval_comb_stateful: None, eval_only_ffs: Default::default(), apply_ffs: Default::default(), parallel: None, diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 15ba593d19e..3c393d6577f 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -30,8 +30,11 @@ //! and every design or kernel this module does not qualify, runs in the //! reference loop. +mod slice; mod testbench; +use slice::CombSlicer; + use celox_design::{ CounterKind, DomainKind, ProcessStatus, RuntimeEventKind, SCHEDULER_CLOCKS, SCHEDULER_FLAG_WIDTH, SCHEDULER_TIME_WIDTH, STABLE_REGION, SchedulerExit, SchedulerSlots, @@ -83,6 +86,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram, wiring_clocks: bool) { return; }; let kernels = program.runtime.runtime_schema.processes.len(); + let mut lazy = false; let (fallback, unit, events, clocks, kernel_events) = match Plan::new(program, &schema.slots, wiring_clocks) { Err(reason) => ( @@ -93,6 +97,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram, wiring_clocks: bool) { vec![Vec::new(); kernels], ), Ok(plan) => { + lazy = plan.lazy.is_some(); let fallback = plan.fallback.clone(); // Without kernels, slots of host clocks alone. let unit = (plan.kernels.iter().any(Option::is_some) || !plan.clocks.is_empty()) @@ -139,7 +144,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram, wiring_clocks: bool) { scheduler.unit = Some(program.sir.processes.len()); program.sir.processes.push(unit); } - testbench::attach(program); + testbench::attach(program, lazy); } /// An event the scheduler records edges of. @@ -241,6 +246,12 @@ struct Lazy { /// returns for an overflow in the middle of a later slot returns the last /// settle's state. latest: u64, + /// The part of the settle that keeps state from one settle to the next, + /// with what it reads: it runs wherever the reference settles, so its + /// state sees every activation the reference's does. Rerunning it on + /// unchanged inputs changes nothing, so the deferred settle may run it + /// again. Empty when the settle is a function of its inputs. + eager: Vec, } /// How a domain evaluates while a settle is pending. @@ -665,91 +676,112 @@ impl Plan { // its inputs that cannot fail: when it would end the run, it must do // so in its own slot; when it reads what an earlier settle left (a // latch, a guarded process's snapshots of its inputs, feedback), the - // settles in between are activations of their own. + // settles in between are activations of their own. The comb + // scheduler knows this from its bit-level dependencies; its loads + // alone can only bound it, since a load may cover bits the settle + // has not stored yet and then discard them. let comb_stores: HashSet = sir.eval_comb.iter().flat_map(stores).collect(); - let lazy = settle_reads + let eager = settle_reads .as_ref() - .filter(|_| { - !sir.eval_comb.iter().any(fails) - && !retains_state(&sir.eval_comb, &storage, &comb_stores) - }) - .map(|_| { - // The waits never watch what combinational logic writes, so - // they see the same with a settle pending. - debug_assert!( - kernels - .iter() - .flatten() - .filter_map(|kernel| kernel.wait.as_ref()) - .all(|wait| !comb_stores.contains(&storage(wait.signal))), - "a compiled wait watches a combinational output" - ); - let reads = - |unit: &Unit| loads(unit).any(|source| comb_stores.contains(&storage(source))); - let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &finish_sites); - let observes = |unit: &Unit| reads(unit) || ends(unit); - let mut longest = 0; - for (index, kernel) in kernels.iter().enumerate() { - if kernel.as_ref().is_some_and(|kernel| kernel.wait.is_none()) { - let bound = - delay_bound(&sir.processes[index], schema.processes[index].delay); - longest = longest.max(bound); + .filter(|_| !sir.eval_comb.iter().any(fails)) + .and_then(|_| { + let stateful = sir.eval_comb_stateful.as_ref(); + let eager = stateful.and_then(|stateful| { + if stateful.is_empty() { + return Some(Vec::new()); } - } - let domains = events - .iter() - .map(|event| { - if event.eval_apply.iter().any(ends) { - return DomainSettle::Settled; - } - if !event.eval_apply.iter().any(reads) { - return DomainSettle::Pending; - } - let fused = &sir.eval_comb_apply_ffs; - let aliased = fused.keys().any(|key| { - *key != event.signal && topology.canonical(*key) == event.signal - }); - match fused.get(&event.signal) { - Some(units) if !aliased => DomainSettle::Fused(units.clone()), - _ => DomainSettle::Settled, - } - }) - .collect(); - let several = events.iter().any(|event| { - event - .eval_only - .iter() - .chain(&event.apply) - .flatten() - .any(observes) + let slicer = CombSlicer::new(&sir.eval_comb, shared.clone()); + let targets = stateful.iter().map(|target| target.absolute_addr()); + // Optimization may have moved a target's storage. + if !targets.clone().all(|target| slicer.stores(target)) { + return None; + } + let eager = slicer.slice(targets); + // A part nearly the size of the settle saves nothing. + let size = |units: &[Unit]| units.iter().flat_map(instructions).count(); + (size(&eager) * 2 < size(&sir.eval_comb)).then_some(eager) }); - Lazy { - // A kernel's `$finish` is its status. - kernels: kernels - .iter() - .enumerate() - .map(|(index, kernel)| { - let unit = &sir.processes[index]; - kernel.is_some() - && (observes(unit) - || !statuses_only( - unit, - schema.processes[index].status, - &[ - ProcessStatus::Delay, - ProcessStatus::InactiveDelay, - ProcessStatus::Wait, - ProcessStatus::Nba, - ProcessStatus::Done, - ], - )) - }) - .collect(), - domains, - several, - latest: u64::MAX - longest, + eager.or_else(|| { + (!retains_state(&sir.eval_comb, &storage, &comb_stores)).then(Vec::new) + }) + }); + let lazy = eager.map(|eager| { + // The waits never watch what combinational logic writes, so + // they see the same with a settle pending. + debug_assert!( + kernels + .iter() + .flatten() + .filter_map(|kernel| kernel.wait.as_ref()) + .all(|wait| !comb_stores.contains(&storage(wait.signal))), + "a compiled wait watches a combinational output" + ); + let reads = + |unit: &Unit| loads(unit).any(|source| comb_stores.contains(&storage(source))); + let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &finish_sites); + let observes = |unit: &Unit| reads(unit) || ends(unit); + let mut longest = 0; + for (index, kernel) in kernels.iter().enumerate() { + if kernel.as_ref().is_some_and(|kernel| kernel.wait.is_none()) { + let bound = delay_bound(&sir.processes[index], schema.processes[index].delay); + longest = longest.max(bound); } + } + let domains = events + .iter() + .map(|event| { + if event.eval_apply.iter().any(ends) { + return DomainSettle::Settled; + } + if !event.eval_apply.iter().any(reads) { + return DomainSettle::Pending; + } + let fused = &sir.eval_comb_apply_ffs; + let aliased = fused.keys().any(|key| { + *key != event.signal && topology.canonical(*key) == event.signal + }); + match fused.get(&event.signal) { + Some(units) if !aliased => DomainSettle::Fused(units.clone()), + _ => DomainSettle::Settled, + } + }) + .collect(); + let several = events.iter().any(|event| { + event + .eval_only + .iter() + .chain(&event.apply) + .flatten() + .any(observes) }); + Lazy { + // A kernel's `$finish` is its status. + kernels: kernels + .iter() + .enumerate() + .map(|(index, kernel)| { + let unit = &sir.processes[index]; + kernel.is_some() + && (observes(unit) + || !statuses_only( + unit, + schema.processes[index].status, + &[ + ProcessStatus::Delay, + ProcessStatus::InactiveDelay, + ProcessStatus::Wait, + ProcessStatus::Nba, + ProcessStatus::Done, + ], + )) + }) + .collect(), + domains, + several, + latest: u64::MAX - longest, + eager, + } + }); let mut plan = Self { events, kernels, @@ -975,6 +1007,8 @@ impl Plan { shared: program.shared_storage(), comb, continuations: Vec::new(), + eager: None, + eager_continuations: Vec::new(), }; let waits: Vec<(usize, &Wait)> = self .kernels @@ -1053,7 +1087,8 @@ impl Plan { let stop = g.binary(1, after, BinaryOp::Or, none); let run = g.b.new_block(); let limit_exit = g.exit_block(SchedulerExit::Limit); - // The host reads the run's results settled. + // The host reads the run's results settled, unless the caller + // observes them itself (`defer_limit_settle`). let stopped = match &self.lazy { Some(_) => g.b.new_block(), None => limit_exit, @@ -1065,6 +1100,16 @@ impl Plan { }); if self.lazy.is_some() { g.b.switch_to_block(stopped); + let deferred = g.load(slots.defer_limit_settle, SCHEDULER_FLAG_WIDTH); + let zero = g.constant(0, SCHEDULER_FLAG_WIDTH); + let deferred = g.binary(1, deferred, BinaryOp::Ne, zero); + let settle = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: deferred, + true_block: (limit_exit, Vec::new()), + false_block: (settle, Vec::new()), + }); + g.b.switch_to_block(settle); g.settle_then(limit_exit); } @@ -1402,9 +1447,7 @@ impl Plan { .as_ref() .is_some_and(|lazy| waits.iter().any(|&(index, _)| lazy.kernels[index])); match &self.lazy { - Some(_) => { - g.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); - } + Some(lazy) => g.eager_then(&lazy.eager, settled), None => g.settle_then(settled), } @@ -1450,9 +1493,9 @@ impl Plan { // Without a domain, published nonblocking values settle once more. g.b.switch_to_block(untriggered); - if self.lazy.is_some() { + if let Some(lazy) = &self.lazy { g.publish(&staged); - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + g.eager_then(&lazy.eager, slot_end); } else if staged.is_empty() { g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); } else { @@ -1593,9 +1636,7 @@ impl Plan { g.b.switch_to_block(evaluated); g.publish(&staged); match &self.lazy { - Some(_) => { - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); - } + Some(lazy) => g.eager_then(&lazy.eager, slot_end), None => g.settle_then(slot_end), } } @@ -1686,6 +1727,9 @@ impl Plan { } g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); g.emit_settle(&program.sir.eval_comb, finish_exit, internal_exit); + if let Some(lazy) = &self.lazy { + g.emit_eager(&lazy.eager, finish_exit, internal_exit); + } g.finish() } } @@ -1880,6 +1924,11 @@ struct Generator<'a> { /// Where the shared settle continues, by case: case `i + 1` continues /// at `continuations[i]`. continuations: Vec, + /// The shared stateful part of a deferred settle, emitted by + /// [`Self::emit_eager`] once a caller uses it. + eager: Option, + /// Where it continues, as [`Self::continuations`]. + eager_continuations: Vec, } impl Generator<'_> { @@ -2174,6 +2223,76 @@ impl Generator<'_> { } } + /// Run the stateful part of a deferred settle (`Lazy::eager`) where the + /// reference settles, then continue at `target`, as + /// [`Self::settle_then`]: one copy serves every caller. + fn eager_then(&mut self, eager: &[Unit], target: celox_sir::BlockId) { + if eager.is_empty() { + self.b.seal_block(SIRTerminator::Jump(target, Vec::new())); + return; + } + let case = match self + .eager_continuations + .iter() + .position(|&block| block == target) + { + Some(index) => index, + None => { + self.eager_continuations.push(target); + self.eager_continuations.len() - 1 + } + }; + let value = self.constant(case as u64 + 1, SCHEDULER_FLAG_WIDTH); + self.store(self.slots.cont, SCHEDULER_FLAG_WIDTH, value); + let block = *self.eager.get_or_insert_with(|| self.b.new_block()); + self.b.seal_block(SIRTerminator::Jump(block, Vec::new())); + } + + /// Emit the shared stateful part of the settle, when a caller uses it: + /// skipped when the settle's inputs did not change since the last one. + fn emit_eager( + &mut self, + eager: &[Unit], + finish_exit: celox_sir::BlockId, + internal_exit: celox_sir::BlockId, + ) { + let Some(block) = self.eager else { + return; + }; + self.b.switch_to_block(block); + let dirty = self.load(self.slots.dirty, SCHEDULER_FLAG_WIDTH); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + let changed = self.binary(1, dirty, BinaryOp::Ne, zero); + let run = self.b.new_block(); + let done = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: changed, + true_block: (run, Vec::new()), + false_block: (done, Vec::new()), + }); + self.b.switch_to_block(run); + for unit in eager { + self.inline(unit, finish_exit); + } + self.b.seal_block(SIRTerminator::Jump(done, Vec::new())); + self.b.switch_to_block(done); + let continuation = self.load(self.slots.cont, SCHEDULER_FLAG_WIDTH); + let cases = self + .eager_continuations + .iter() + .enumerate() + .map(|(index, &target)| SIRSwitchCase { + value: (index as u8 + 1).into(), + target, + }) + .collect(); + self.b.seal_block(SIRTerminator::Switch { + selector: continuation, + cases, + default: internal_exit, + }); + } + /// Run the shared settle, then continue at `target`. The registers /// `target` and its successors use must be defined in it or in the slot /// loop's header, which alone dominates every entry of the settle. @@ -2650,6 +2769,30 @@ pub(crate) fn count_test_settles( fused } +/// Whether the compiled scheduler of `program` defers its settles, and +/// whether its loads alone would have allowed that. +#[cfg(test)] +pub(crate) fn defers_settles_for_test(program: &LaidOutProgram) -> (bool, bool) { + let schema = program.runtime.runtime_schema.scheduler.clone().unwrap(); + let plan = Plan::new(program, &schema.slots, true).unwrap(); + let shared = program.shared_storage(); + let storage = |address: AbsoluteAddr| shared.get(&address).copied().unwrap_or(address); + let stores: HashSet = program + .sir + .eval_comb + .iter() + .flat_map(instructions) + .filter_map(|inst| { + inst.memory_write() + .map(|write| storage(write.addr.absolute_addr())) + }) + .collect(); + ( + plan.lazy.is_some(), + !retains_state(&program.sir.eval_comb, &storage, &stores), + ) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/celox/src/scheduler/slice.rs b/crates/celox/src/scheduler/slice.rs new file mode 100644 index 00000000000..916e45afdc6 --- /dev/null +++ b/crates/celox/src/scheduler/slice.rs @@ -0,0 +1,580 @@ +//! Parts of a combinational settle that compute chosen storage. +//! +//! The settle's units are indexed once: what each register and each store +//! depends on, through data and control. A slice is then a walk from the +//! storage it must compute, linear in what it reaches. +use super::*; +use celox_sir::BlockId; + +/// What a slice needs. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Need { + Storage(AbsoluteAddr), + Register(usize, RegisterId), + /// The block runs as in the settle: what decides that it runs. + Block(usize, BlockId), +} + +/// Where a register is defined. +#[derive(Clone, Copy)] +enum Definition { + Instruction(BlockId, usize), + /// A block parameter, with its index. + Parameter(BlockId, usize), +} + +struct Indexed { + definitions: HashMap, + /// The predecessors of each block, with the arguments of their edge. + incoming: HashMap)>>, + /// The branch and switch selectors each block is control dependent on. + control: HashMap>, +} + +pub(crate) struct CombSlicer<'a> { + units: &'a [Unit], + storage: HashMap, + indexed: Vec, + /// The stores of each storage representative: unit, block, instruction. + stores: HashMap>, +} + +fn successors(terminator: &SIRTerminator) -> Vec<(BlockId, &[RegisterId])> { + match terminator { + SIRTerminator::Jump(target, arguments) => vec![(*target, arguments.as_slice())], + SIRTerminator::Branch { + true_block, + false_block, + .. + } => vec![ + (true_block.0, true_block.1.as_slice()), + (false_block.0, false_block.1.as_slice()), + ], + SIRTerminator::Switch { cases, default, .. } => cases + .iter() + .map(|case| (case.target, &[][..])) + .chain([(*default, &[][..])]) + .collect(), + SIRTerminator::Return | SIRTerminator::Error(_) => Vec::new(), + } +} + +fn selector(terminator: &SIRTerminator) -> Option { + match terminator { + SIRTerminator::Branch { cond, .. } => Some(*cond), + SIRTerminator::Switch { selector, .. } => Some(*selector), + _ => None, + } +} + +/// The immediate post-dominator of each block reachable from the entry, +/// `None` for the virtual exit (Cooper, Harvey and Kennedy). +fn post_dominators(unit: &Unit) -> HashMap> { + let mut predecessors: HashMap> = HashMap::default(); + let mut exits = Vec::new(); + for (&id, block) in &unit.blocks { + let next = successors(&block.terminator); + if next.is_empty() { + exits.push(id); + } + for (target, _) in next { + predecessors.entry(target).or_default().push(id); + } + } + exits.sort_unstable(); + // Postorder over the reverse graph, starting at the virtual exit. + let mut order: Vec = Vec::new(); + let mut visited: HashSet = HashSet::default(); + for &exit in &exits { + if !visited.insert(exit) { + continue; + } + let mut stack = vec![(exit, 0usize)]; + while let Some((block, next)) = stack.pop() { + let preds = predecessors.get(&block).map_or(&[][..], Vec::as_slice); + if next < preds.len() { + stack.push((block, next + 1)); + let pred = preds[next]; + if visited.insert(pred) { + stack.push((pred, 0)); + } + } else { + order.push(block); + } + } + } + // Number blocks by postorder; the virtual exit is above all. + let number: HashMap = order + .iter() + .enumerate() + .map(|(index, &block)| (block, index)) + .collect(); + let exit = order.len(); + let mut ipdom: HashMap = HashMap::default(); + for &block in &exits { + ipdom.insert(block, exit); + } + let intersect = |ipdom: &HashMap, mut a: usize, mut b: usize| { + while a != b { + while a < b { + a = ipdom[&order[a]]; + } + while b < a { + b = ipdom[&order[b]]; + } + } + a + }; + let mut changed = true; + while changed { + changed = false; + for &block in order.iter().rev() { + if exits.contains(&block) { + continue; + } + let mut new: Option = None; + for (target, _) in successors(&unit.blocks[&block].terminator) { + let Some(&known) = ipdom.get(&target).map(|_| &number[&target]) else { + continue; + }; + new = Some(match new { + None => known, + Some(current) => intersect(&ipdom, current, known), + }); + } + if let Some(new) = new + && ipdom.get(&block) != Some(&new) + { + ipdom.insert(block, new); + changed = true; + } + } + } + ipdom + .into_iter() + .map(|(block, dominator)| (block, (dominator != exit).then(|| order[dominator]))) + .collect() +} + +fn index(unit: &Unit) -> Indexed { + let mut definitions = HashMap::default(); + let mut incoming: HashMap)>> = HashMap::default(); + for (&id, block) in &unit.blocks { + for (position, ¶meter) in block.params.iter().enumerate() { + definitions.insert(parameter, Definition::Parameter(id, position)); + } + for (position, inst) in block.instructions.iter().enumerate() { + if let Some(register) = inst.defined_register() { + definitions.insert(register, Definition::Instruction(id, position)); + } + } + for (target, arguments) in successors(&block.terminator) { + incoming + .entry(target) + .or_default() + .push((id, arguments.to_vec())); + } + } + // A block is control dependent on a branch when it lies on a path from + // one of the branch's successors up to (not including) the branch's + // post-dominator. + let ipdom = post_dominators(unit); + let mut control: HashMap> = HashMap::default(); + for (&id, block) in &unit.blocks { + let Some(selector) = selector(&block.terminator) else { + continue; + }; + // A block that cannot reach an exit has no post-dominator: treat + // everything it reaches as depending on it. + let stop = ipdom.get(&id).copied().flatten(); + for (target, _) in successors(&block.terminator) { + let mut runner = Some(target); + let mut seen = HashSet::default(); + while let Some(current) = runner { + if Some(current) == stop || !seen.insert(current) { + break; + } + control.entry(current).or_default().push(selector); + runner = ipdom.get(¤t).copied().flatten(); + } + } + } + Indexed { + definitions, + incoming, + control, + } +} + +impl<'a> CombSlicer<'a> { + pub(crate) fn new(units: &'a [Unit], storage: HashMap) -> Self { + let mut stores: HashMap> = HashMap::default(); + let representative = + |address: AbsoluteAddr| storage.get(&address).copied().unwrap_or(address); + for (unit_index, unit) in units.iter().enumerate() { + for (&id, block) in &unit.blocks { + for (position, inst) in block.instructions.iter().enumerate() { + if let Some(write) = inst.memory_write() { + stores + .entry(representative(write.addr.absolute_addr())) + .or_default() + .push((unit_index, id, position)); + } + } + } + } + Self { + units, + indexed: units.iter().map(index).collect(), + stores, + storage, + } + } + + fn representative(&self, address: AbsoluteAddr) -> AbsoluteAddr { + self.storage.get(&address).copied().unwrap_or(address) + } + + /// Whether some unit stores `address`. + pub(crate) fn stores(&self, address: AbsoluteAddr) -> bool { + self.stores.contains_key(&self.representative(address)) + } + + /// The part of the settle that computes `reads`: every store of storage + /// they or the part load, and what decides it. Stores the part does not + /// need, and the settle's other effects, are left to the settle. + pub(crate) fn slice(&self, reads: impl IntoIterator) -> Vec { + let mut kept: Vec> = vec![HashSet::default(); self.units.len()]; + let mut seen: HashSet = HashSet::default(); + let mut work: Vec = reads + .into_iter() + .map(|address| Need::Storage(self.representative(address))) + .collect(); + let mut units: Vec; + loop { + self.walk(&mut work, &mut seen, &mut kept); + units = self.build(&kept, &seen); + // A terminator whose operands the walk did not reach survives + // only where folding could not remove it: keep what it uses. + for (unit_index, unit) in units.iter().enumerate() { + for block in unit.blocks.values() { + block.terminator.for_each_use(|register| { + let need = Need::Register(unit_index, register); + if !seen.contains(&need) { + work.push(need); + } + }); + } + } + if work.is_empty() { + return units; + } + } + } + + fn walk( + &self, + work: &mut Vec, + seen: &mut HashSet, + kept: &mut [HashSet<(BlockId, usize)>], + ) { + while let Some(need) = work.pop() { + if !seen.insert(need) { + continue; + } + match need { + Need::Storage(address) => { + for &(unit, block, position) in self.stores.get(&address).into_iter().flatten() + { + kept[unit].insert((block, position)); + let inst = &self.units[unit].blocks[&block].instructions[position]; + inst.for_each_use(|register| work.push(Need::Register(unit, register))); + if let Some(read) = inst.memory_read() { + work.push(Need::Storage( + self.representative(read.addr.absolute_addr()), + )); + } + work.push(Need::Block(unit, block)); + } + } + Need::Register(unit, register) => { + match self.indexed[unit].definitions.get(®ister) { + Some(&Definition::Instruction(block, position)) => { + kept[unit].insert((block, position)); + let inst = &self.units[unit].blocks[&block].instructions[position]; + inst.for_each_use(|register| work.push(Need::Register(unit, register))); + if let Some(read) = inst.memory_read() { + work.push(Need::Storage( + self.representative(read.addr.absolute_addr()), + )); + } + work.push(Need::Block(unit, block)); + } + Some(&Definition::Parameter(block, position)) => { + for (predecessor, arguments) in self.indexed[unit] + .incoming + .get(&block) + .into_iter() + .flatten() + { + if let Some(&argument) = arguments.get(position) { + work.push(Need::Register(unit, argument)); + } + work.push(Need::Block(unit, *predecessor)); + } + work.push(Need::Block(unit, block)); + } + None => {} + } + } + Need::Block(unit, block) => { + for &selector in self.indexed[unit].control.get(&block).into_iter().flatten() { + work.push(Need::Register(unit, selector)); + } + } + } + } + } + + fn build(&self, kept: &[HashSet<(BlockId, usize)>], seen: &HashSet) -> Vec { + self.units + .iter() + .enumerate() + .map(|(unit_index, unit)| { + let mut unit = unit.clone(); + let needed = + |register: &RegisterId| seen.contains(&Need::Register(unit_index, *register)); + // Unneeded parameters go with their arguments. + let dropped: HashMap> = unit + .blocks + .iter() + .map(|(&id, block)| (id, block.params.iter().map(|p| !needed(p)).collect())) + .collect(); + for (&id, block) in unit.blocks.iter_mut() { + let mut position = 0; + block.instructions.retain(|_| { + let keep = kept[unit_index].contains(&(id, position)); + position += 1; + keep + }); + let mut index = 0; + block.params.retain(|_| { + let keep = !dropped[&id][index]; + index += 1; + keep + }); + let prune = |target: BlockId, arguments: &mut Vec| { + let mut index = 0; + arguments.retain(|_| { + let keep = !dropped[&target][index]; + index += 1; + keep + }); + }; + match &mut block.terminator { + SIRTerminator::Jump(target, arguments) => prune(*target, arguments), + SIRTerminator::Branch { + true_block, + false_block, + .. + } => { + prune(true_block.0, &mut true_block.1); + prune(false_block.0, &mut false_block.1); + } + _ => {} + } + } + fold_empty_branches(&mut unit); + unit + }) + .collect() + } +} + +/// Replace branches whose arms run nothing on the way to one block (with +/// the same arguments) by a jump there, and drop unreachable blocks. +fn fold_empty_branches(unit: &mut Unit) { + // Where an empty, parameterless block chain ends, with its arguments. + let forward = |unit: &Unit, mut block: BlockId| -> (BlockId, Vec) { + let mut arguments = Vec::new(); + let mut seen = HashSet::default(); + while seen.insert(block) { + let current = &unit.blocks[&block]; + match ¤t.terminator { + SIRTerminator::Jump(target, next) + if current.instructions.is_empty() && current.params.is_empty() => + { + arguments = next.clone(); + block = *target; + if !arguments.is_empty() { + break; + } + } + _ => break, + } + } + (block, arguments) + }; + let mut changed = true; + while changed { + changed = false; + let mut ids: Vec<_> = unit.blocks.keys().copied().collect(); + ids.sort_unstable(); + for id in ids { + let targets: Vec<(BlockId, Vec)> = match &unit.blocks[&id].terminator { + SIRTerminator::Branch { + true_block, + false_block, + .. + } if true_block.1.is_empty() && false_block.1.is_empty() => { + vec![forward(unit, true_block.0), forward(unit, false_block.0)] + } + SIRTerminator::Switch { cases, default, .. } => cases + .iter() + .map(|case| forward(unit, case.target)) + .chain([forward(unit, *default)]) + .collect(), + _ => continue, + }; + if targets.windows(2).all(|pair| pair[0] == pair[1]) { + let (target, arguments) = targets.into_iter().next().unwrap(); + unit.blocks.get_mut(&id).unwrap().terminator = + SIRTerminator::Jump(target, arguments); + changed = true; + } + } + } + let mut reachable = HashSet::default(); + let mut work = vec![unit.entry_block_id]; + while let Some(id) = work.pop() { + if reachable.insert(id) { + work.extend( + successors(&unit.blocks[&id].terminator) + .into_iter() + .map(|(t, _)| t), + ); + } + } + unit.blocks.retain(|id, _| reachable.contains(id)); +} + +#[cfg(test)] +mod tests { + use super::*; + use celox_design::{InstanceId, StateObjectId}; + use celox_sir::SIROffset; + + fn address(id: u32) -> AbsoluteAddr { + AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId(id), + } + } + + fn stable(id: u32) -> RegionedAbsoluteAddr { + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address(id)) + } + + /// `if (a) { x = c; y = c; } z = c;` + fn settle() -> Unit { + let mut b = Builder::new(); + let [a, c, x, y, z] = [0, 1, 2, 3, 4]; + let cond = b.alloc_bit(1, false); + let value = b.alloc_bit(8, false); + b.emit(SIRInstruction::Load( + cond, + stable(a), + SIROffset::Static(0), + 1, + )); + b.emit(SIRInstruction::Load( + value, + stable(c), + SIROffset::Static(0), + 8, + )); + let then = b.new_block(); + let otherwise = b.new_block(); + let join = b.new_block(); + b.seal_block(SIRTerminator::Branch { + cond, + true_block: (then, Vec::new()), + false_block: (otherwise, Vec::new()), + }); + b.switch_to_block(then); + for target in [x, y] { + b.emit(SIRInstruction::Store( + stable(target), + SIROffset::Static(0), + 8, + value, + Vec::new(), + Vec::new(), + )); + } + b.seal_block(SIRTerminator::Jump(join, Vec::new())); + b.switch_to_block(otherwise); + b.seal_block(SIRTerminator::Jump(join, Vec::new())); + b.switch_to_block(join); + let again = b.alloc_bit(8, false); + b.emit(SIRInstruction::Load( + again, + stable(c), + SIROffset::Static(0), + 8, + )); + b.emit(SIRInstruction::Store( + stable(z), + SIROffset::Static(0), + 8, + again, + Vec::new(), + Vec::new(), + )); + b.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = b.drain(); + Unit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + } + + fn stored(units: &[Unit]) -> Vec { + let mut stored: Vec<_> = units + .iter() + .flat_map(instructions) + .filter_map(|inst| inst.memory_write().map(|write| write.addr.absolute_addr())) + .collect(); + stored.sort_unstable(); + stored + } + + #[test] + fn slice_keeps_what_decides_a_store() { + let units = [settle()]; + let slicer = CombSlicer::new(&units, HashMap::default()); + let slice = slicer.slice([address(2)]); + assert_eq!(stored(&slice), [address(2)]); + // The branch on `a` decides whether `x` is stored. + assert!(matches!( + slice[0].blocks[&BlockId(0)].terminator, + SIRTerminator::Branch { .. } + )); + } + + #[test] + fn slice_folds_branches_it_does_not_need() { + let units = [settle()]; + let slicer = CombSlicer::new(&units, HashMap::default()); + let slice = slicer.slice([address(4)]); + assert_eq!(stored(&slice), [address(4)]); + assert_eq!(slice[0].blocks.len(), 2, "the branch on `a` folds away"); + assert!( + instructions(&slice[0]).all(|inst| inst + .memory_read() + .is_none_or(|read| read.addr.absolute_addr() == address(1))), + "`a` is no longer read" + ); + } +} diff --git a/crates/celox/src/scheduler/testbench.rs b/crates/celox/src/scheduler/testbench.rs index e5af7b66f94..a922b185588 100644 --- a/crates/celox/src/scheduler/testbench.rs +++ b/crates/celox/src/scheduler/testbench.rs @@ -5,7 +5,9 @@ use celox_testbench::*; type Meta = TestbenchScheduler; -pub(super) fn attach(program: &mut LaidOutProgram) { +/// `deferred` when the shared scheduler defers settles: the TB then +/// observes what it reads itself and leaves a deferred settle pending. +pub(super) fn attach(program: &mut LaidOutProgram, deferred: bool) { let Some(tb) = program.runtime.testbench.clone() else { return; }; @@ -15,7 +17,7 @@ pub(super) fn attach(program: &mut LaidOutProgram) { let Some(schema) = program.runtime.runtime_schema.scheduler.clone() else { return; }; - let unit = generate(program, &tb, &meta, &schema.slots); + let unit = generate(program, &tb, &meta, &schema.slots, deferred); meta.entry = Some(program.sir.processes.len()); program.sir.processes.push(unit); program @@ -26,6 +28,35 @@ pub(super) fn attach(program: &mut LaidOutProgram) { .set_scheduler(meta); } +/// The parts of the settle that compute what TB reads load. +struct Cones<'a> { + slicer: CombSlicer<'a>, + size: usize, + /// What keeps state from one settle to the next: a settle the TB + /// requests is an activation of its own. + stateful: Vec, + known: HashMap, Option>>, +} + +impl Cones<'_> { + /// `None` when the reads need (nearly) the whole settle, or none are + /// named: the settle itself runs then. + fn cone(&mut self, reads: &[AbsoluteAddr]) -> Option> { + if reads.is_empty() { + return None; + } + let (slicer, size, stateful) = (&self.slicer, self.size, &self.stateful); + self.known + .entry(reads.to_vec()) + .or_insert_with(|| { + let cone = slicer.slice(reads.iter().chain(stateful).copied()); + let cone_size: usize = cone.iter().map(|unit| instructions(unit).count()).sum(); + (cone_size * 2 < size).then_some(cone) + }) + .clone() + } +} + fn put(g: &mut Generator<'_>, a: AbsoluteAddr, value: u64) { let value = g.constant(value, 64); g.store(a, 64, value); @@ -165,6 +196,7 @@ fn generate( tb: &TestbenchProgram, m: &Meta, slots: &SchedulerSlots, + deferred: bool, ) -> Unit { let mut b = Builder::new(); let comb = b.new_block(); @@ -178,6 +210,23 @@ fn generate( .filter(|(_, s)| matches!(s.kind, RuntimeEventKind::Finish | RuntimeEventKind::Stop)) .map(|(i, _)| i as u32) .collect(); + let mut cones = Cones { + slicer: CombSlicer::new(&program.sir.eval_comb, program.shared_storage()), + size: program + .sir + .eval_comb + .iter() + .map(|unit| instructions(unit).count()) + .sum(), + stateful: program + .sir + .eval_comb_stateful + .iter() + .flatten() + .map(|target| target.absolute_addr()) + .collect(), + known: HashMap::default(), + }; let mut g = Generator { b, slots, @@ -187,6 +236,8 @@ fn generate( shared: program.shared_storage(), comb, continuations: vec![], + eager: None, + eager_continuations: vec![], }; let initialize = g.b.new_block(); let start = g.b.new_block(); @@ -331,7 +382,7 @@ fn generate( for (request, block) in kernel.requests.iter().zip(requests) { g.b.switch_to_block(block); match request { - KernelRequest::Settle => { + KernelRequest::Settle { reads } => { let native = equals_slot(&mut g, m.control[TB_NATIVE_SETTLE], 1); let settle = g.b.new_block(); let host = g.b.new_block(); @@ -341,7 +392,22 @@ fn generate( put(&mut g, m.control[TB_EXIT], TB_HOST); g.b.seal_block(SIRTerminator::Return); g.b.switch_to_block(settle); - settle_then(&mut g, m, run[i]); + match deferred.then(|| cones.cone(reads)).flatten() { + // With settles deferred, computing what the TB reads + // leaves the settle pending. + Some(units) => { + let dirty = g.load(slots.dirty, 8); + let clean = g.equals(dirty, 0); + let compute = g.b.new_block(); + branch(&mut g, clean, run[i], compute); + g.b.switch_to_block(compute); + for unit in &units { + g.inline(unit, finish); + } + jump(&mut g, run[i]); + } + None => settle_then(&mut g, m, run[i]), + } } KernelRequest::Written { .. } => { let dirty = g.constant(1, 8); @@ -442,9 +508,39 @@ fn generate( }) .collect(); if let (Some(unit), Some(positions)) = (schema.unit, positions) { - let mut allowed = equals_slot(&mut g, m.control[TB_NATIVE_EDGES], 1); - let clean = equals_slot_width(&mut g, slots.dirty, 8, 0); - allowed = g.binary(1, allowed, BinaryOp::And, clean); + // A scheduler that defers settles finds a pending one itself, but + // the edges it and this unit judge need the levels of the event + // signals: compute those (the part of the settle they need, or the + // settle), or require a settled design. + let mut allowed = if deferred { + let levels: Vec = schema + .events + .iter() + .chain(m.baselines.iter().map(|(source, _)| source)) + .copied() + .collect(); + let judge = g.b.new_block(); + match cones.cone(&levels) { + Some(units) => { + let dirty = g.load(slots.dirty, 8); + let clean = g.equals(dirty, 0); + let compute = g.b.new_block(); + branch(&mut g, clean, judge, compute); + g.b.switch_to_block(compute); + for unit in &units { + g.inline(unit, finish); + } + jump(&mut g, judge); + } + None => settle_then(&mut g, m, judge), + } + g.b.switch_to_block(judge); + equals_slot(&mut g, m.control[TB_NATIVE_EDGES], 1) + } else { + let allowed = equals_slot(&mut g, m.control[TB_NATIVE_EDGES], 1); + let clean = equals_slot_width(&mut g, slots.dirty, 8, 0); + g.binary(1, allowed, BinaryOp::And, clean) + }; for &(source, saved) in &m.baselines { let before = g.load(saved, 1); let current = g.load(source, 1); @@ -497,7 +593,11 @@ fn generate( let zero = g.constant(0, 8); g.store(slots.exit, 8, zero); g.store(slots.finish, 8, zero); + let defer = g.constant(u64::from(deferred), 8); + g.store(slots.defer_limit_settle, 8, defer); g.b.inline_execution_unit(&program.sir.processes[unit]); + let zero = g.constant(0, 8); + g.store(slots.defer_limit_settle, 8, zero); let exit = g.load(slots.exit, 8); let limit = g.equals(exit, SchedulerExit::Limit as u64); let finished = g.equals(exit, SchedulerExit::Finish as u64); diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 7fa2acb2614..c50128db6f9 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -4816,6 +4816,45 @@ endmodule"#; assert!(count_clean_clock_batch(false, false, true).0 > 0); } + /// A bit-level schedule may load a range before the bits it needs are + /// stored, and discard the stale ones: the settle is still a function of + /// its inputs, so it may be deferred. + #[test] + fn discarded_stale_bits_keep_settles_deferred() { + let source = r#" + module Child ( + translate: input logic, frame: input logic<20>, pc: input logic<12>, + physical: output logic<12>, + ) { + var translated: logic<32>; + assign translated = {frame, pc}; + assign physical = if translate ? translated[11:0] : pc; + } + module Top ( + clk: input clock, rst: input reset, translate: input logic, + next_frame: input logic<20>, next_pc: input logic<12>, + physical: output logic<12>, + ) { + var frame_q: logic<20>; + var pc_q: logic<12>; + var frame: logic<20>; + always_ff { + if_reset { frame_q = 0; pc_q = 0; } else { frame_q = next_frame; pc_q = next_pc; } + } + inst child: Child (translate, frame, pc: pc_q, physical); + assign frame = frame_q; + } + "#; + let (program, _, _, _, _) = crate::Simulation::builder(source, "Top") + .four_state(false) + .into_laid_out_program(crate::MemoryLayoutMode::Packed, false) + .unwrap(); + assert_eq!(program.sir.eval_comb_stateful, Some(Vec::new())); + let (defers, by_loads) = crate::scheduler::defers_settles_for_test(&program); + assert!(defers); + assert!(!by_loads, "the fixture must load stale bits it discards"); + } + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] fn count_clean_clock_batch(clock_data: bool, alias: bool, dirty: bool) -> (u64, usize) { use crate::SimBackend; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 3f43784c2a7..2a4bd1eb4a5 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -2415,7 +2415,7 @@ mod tests { let settlements = tb.kernels()[0] .requests .iter() - .filter(|request| matches!(request, celox_testbench::KernelRequest::Settle)) + .filter(|request| matches!(request, celox_testbench::KernelRequest::Settle { .. })) .count(); assert_eq!(settlements, 2); assert_eq!( diff --git a/crates/celox/src/testbench/compiled.rs b/crates/celox/src/testbench/compiled.rs index 9b56010ff16..28cc1fc387b 100644 --- a/crates/celox/src/testbench/compiled.rs +++ b/crates/celox/src/testbench/compiled.rs @@ -131,7 +131,13 @@ pub(super) fn run( c.set((runs + 1, edges)); }); if let Err(e) = sim.backend.run_process(entry) { - return Some(ExecResult::Fail(e.to_string())); + // A fatal assertion in a domain the unit ran ends it with an + // error; its message is in the runtime events. + let drained = drain_runtime_assertions(sim, ctx, None); + if let Some(message) = drained.fatal_message { + return Some(ExecResult::Fail(message_diagnostic(&message))); + } + return Some(ExecResult::Fail(sim.decorate_runtime_error(e).to_string())); } sim.dirty = sim.backend.get_as::(dirty) != 0; if sim.dirty { @@ -285,7 +291,7 @@ pub(super) fn run( } } } - KernelRequest::Settle => { + KernelRequest::Settle { .. } => { if let Err(e) = settle_testbench(sim) { return Some(ExecResult::Fail(e.to_string())); } diff --git a/crates/celox/src/testbench/native.rs b/crates/celox/src/testbench/native.rs index d4712786d6d..5a953eabcda 100644 --- a/crates/celox/src/testbench/native.rs +++ b/crates/celox/src/testbench/native.rs @@ -80,7 +80,7 @@ impl<'a, B: SimBackend> Process<'a, B> { )); }; match request { - KernelRequest::Settle => { + KernelRequest::Settle { .. } => { if let Err(error) = settle_testbench(sim) { return Poll::Ready(ExecResult::Fail(format!("eval_comb: {error}"))); } diff --git a/crates/celox/src/testbench_compile/process.rs b/crates/celox/src/testbench_compile/process.rs index d3c9bb2bcce..9e4c10b4d95 100644 --- a/crates/celox/src/testbench_compile/process.rs +++ b/crates/celox/src/testbench_compile/process.rs @@ -1,4 +1,5 @@ //! Veryl statements lowered with the same resumable SIR builder as SV. +use crate::HashSet; use crate::ir::{AbsoluteAddr as Addr, RuntimeProgram, SirProgram}; use celox_design::{ BinaryOp, ProcessKind, ProcessSlots, RegionedVarAddrBase, STABLE_REGION, UnaryOp, @@ -24,6 +25,8 @@ struct Lower<'a> { site: usize, external_observers: bool, settled: bool, + /// The DUT storage the settles of the current segment computed. + settled_reads: HashSet, } impl Lower<'_> { fn slot(&mut self, width: usize, string: bool) -> Addr { @@ -211,7 +214,7 @@ impl Lower<'_> { reg } fn request(&mut self, request: KernelRequest) -> Result<(), String> { - self.settled = matches!(request, KernelRequest::Settle); + self.settled = matches!(request, KernelRequest::Settle { .. }); let index = self.requests.len(); self.requests.push(request); self.kernel @@ -261,24 +264,44 @@ impl Lower<'_> { fn writes_observable(&self, address: Addr) -> bool { self.external_observers || self.runtime.rtl_accesses.contains(&address) } - fn observes(&self, expr: &Expr) -> bool { - self.external_observers - || expr.ops().iter().any(|op| match op { + /// The DUT storage `expr` loads. + fn dut_reads(&self, expr: &Expr) -> HashSet { + expr.ops() + .iter() + .filter_map(|op| match op { ExprOpcode::LoadU64 { location, .. } | ExprOpcode::LoadWide { location, .. } | ExprOpcode::LoadIndexed { location, .. } | ExprOpcode::LoadBitSelect { location, .. } - | ExprOpcode::LoadString { location, .. } => { - self.runtime.rtl_accesses.contains(&location.address) - } - _ => false, + | ExprOpcode::LoadString { location, .. } => self + .runtime + .rtl_accesses + .contains(&location.address) + .then_some(location.address), + _ => None, }) + .collect() } fn settled_expression(&mut self, expr: &Expr) -> Result { // Reads within one straight-line segment see the same settled DUT. // A write, host service or control-flow boundary invalidates this fact. - if self.observes(expr) && (!self.settled || self.external_observers) { - self.request(KernelRequest::Settle)?; + // External observers see every settle, so theirs settle everything. + let reads = self.dut_reads(expr); + if self.external_observers { + self.request(KernelRequest::Settle { reads: Vec::new() })?; + } else if !reads.is_empty() { + if !self.settled { + self.settled_reads.clear(); + } + let mut missing: Vec = reads + .into_iter() + .filter(|address| !self.settled_reads.contains(address)) + .collect(); + if !missing.is_empty() { + missing.sort_unstable(); + self.settled_reads.extend(missing.iter().copied()); + self.request(KernelRequest::Settle { reads: missing })?; + } } self.expression(expr) } @@ -651,6 +674,7 @@ pub(crate) fn lower( site: 0, external_observers, settled: false, + settled_reads: HashSet::default(), }; lower.block(body, None)?; let entry = sir.processes.len();