diff --git a/Cargo.lock b/Cargo.lock index 7051c188e39..53eb475bcf0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3556,9 +3556,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.13.0" +version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" dependencies = [ "aho-corasick", "memchr", diff --git a/crates/celox-backend-arm64/src/scalar.rs b/crates/celox-backend-arm64/src/scalar.rs index 68c8fc55f4c..b8815d577ba 100644 --- a/crates/celox-backend-arm64/src/scalar.rs +++ b/crates/celox-backend-arm64/src/scalar.rs @@ -237,7 +237,7 @@ pub fn emit_prepared_eu_with_arena( } }; sir_eu.verify_result().map_err(PrepareError::Sir)?; - let tick_loop = label == "eval_comb_apply_ff" && native_tick_loop; + let tick_loop = celox_backend_common::loops_ticks(label) && native_tick_loop; let check_runtime_events = tick_loop && sir_eu.blocks.values().any(|block| { block.instructions.iter().any(|instruction| { diff --git a/crates/celox-backend-common/src/lib.rs b/crates/celox-backend-common/src/lib.rs index b5434f8969b..9fa4c45393f 100644 --- a/crates/celox-backend-common/src/lib.rs +++ b/crates/celox-backend-common/src/lib.rs @@ -3,3 +3,14 @@ pub mod regalloc; pub mod cranelift_options; + +/// The compile label of a generated derived-edge unit, which runs periods +/// of its event in the tick loop. +pub const DERIVED_EDGE_LABEL: &str = "derived_edge"; + +/// Whether a function compiled under `label` runs in the tick loop when the +/// backend's native tick loop is on: the fused tick (`eval_comb_apply_ff`) +/// and the derived-edge units. +pub fn loops_ticks(label: &str) -> bool { + label == "eval_comb_apply_ff" || label == DERIVED_EDGE_LABEL +} diff --git a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs index f164ea0ab8e..4715dcf15a6 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/pipeline.rs @@ -121,7 +121,7 @@ fn emit_prepared_eu_inner( ); } dump_native_block_context(label, "after_isel", &sir_eu, &mfunc, diagnostics); - let check_runtime_events = label == "eval_comb_apply_ff" + let check_runtime_events = celox_backend_common::loops_ticks(label) && options.native_tick_loop && sir_eu.blocks.values().any(|block| { block.instructions.iter().any(|instruction| { @@ -347,7 +347,7 @@ fn emit_prepared_eu_inner( } else { &[] }; - let result = if label == "eval_comb_apply_ff" && options.native_tick_loop { + let result = if celox_backend_common::loops_ticks(label) && options.native_tick_loop { emit_with_plan_tick_loop( &mfunc, &ra.assignment, diff --git a/crates/celox-backend-x86/src/backend/native/regalloc.rs b/crates/celox-backend-x86/src/backend/native/regalloc.rs index 28c745ec1b3..02a19f2372a 100644 --- a/crates/celox-backend-x86/src/backend/native/regalloc.rs +++ b/crates/celox-backend-x86/src/backend/native/regalloc.rs @@ -461,7 +461,7 @@ fn run_regalloc_in_place( is_cancelled, )?, }; - let tick_loop = label == "eval_comb_apply_ff" && native_tick_loop; + let tick_loop = celox_backend_common::loops_ticks(label) && native_tick_loop; let vector_allocation = super::x86_slp::allocate(func, spill_frame_size, tick_loop); for (value, location) in vector_allocation.assignments { assignment.set_x86_vector(value, location); diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index ec63451c7b6..7e2b750fe62 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1390,19 +1390,28 @@ pub struct SettlePartitions { pub marks: Vec<(A, Vec)>, } -/// The process units that run the edges of one event together with its -/// derived clock domains, the signal having already moved. Each reads -/// [`SchedulerSlots::dirty`] to know whether combinational logic must -/// settle before the domains evaluate. +/// The process unit that runs edges of one event together with its derived +/// clock domains. It runs the edges [`SchedulerSlots::cont`] selects +/// ([`DERIVED_EDGE_RISING`], [`DERIVED_EDGE_FALLING`], or both, a period, in +/// that order), moving the signal itself unless [`DERIVED_EDGE_MOVED`] says +/// the host moved it for a single edge. [`SchedulerSlots::dirty`] says +/// whether combinational logic has pending changes, before and after. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct DerivedEdgeUnits { /// The canonical event. pub event: A, - /// Indices among the process units of the rising and the falling edge. - pub rising: usize, - pub falling: usize, + /// The unit's index among the process units. + pub unit: usize, } +/// A [`DerivedEdgeUnits`] mode bit: run the rising edge. +pub const DERIVED_EDGE_RISING: u8 = 1; +/// A [`DerivedEdgeUnits`] mode bit: run the falling edge. +pub const DERIVED_EDGE_FALLING: u8 = 2; +/// A [`DerivedEdgeUnits`] mode bit: the host already moved the signal +/// through the one edge selected. +pub const DERIVED_EDGE_MOVED: u8 = 4; + /// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`], /// [`SchedulerSlots::exit_arg`], [`SchedulerSlots::count`], /// [`SchedulerSlots::current`], [`SchedulerSlots::levels`], diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index eb9860f1524..0fc8bbbe896 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -892,7 +892,25 @@ pub fn schedule_symbolic_rtl_reporting_loops( .values() .map(|module| modules[module].processes.len()) .sum(); - let scheduler_slots = declare_scheduler_slots(&mut modules, root_id, process_count); + // At most one event per trigger signal of each instance's domains; + // instances connected to one clock share its event. A design with more + // events than its slots hold runs without the compiled scheduler. + let expected_events = instance_modules + .values() + .map(|module| { + let module = &modules[module]; + module + .eval_apply_ff_blocks + .keys() + .chain(module.eval_only_ff_blocks.keys()) + .chain(module.apply_ff_blocks.keys()) + .flat_map(|triggers| std::iter::once(&triggers.clock).chain(&triggers.resets)) + .collect::>() + .len() + }) + .sum::(); + let scheduler_slots = + declare_scheduler_slots(&mut modules, root_id, process_count, expected_events); // Each package with variables is one instance outside the hierarchy, // named by a path segment no instance name can take. let mut package_instances = HashMap::default(); @@ -2754,12 +2772,15 @@ fn declare_settle_flags( /// Declare the hidden objects a compiled scheduler exchanges with the /// runtime (`RuntimeSchema::scheduler`) as variables of the top module, for -/// a design with `process_count` process kernels. A design without kernels -/// has them too: host clocks may run in a compiled scheduler. +/// a design with `process_count` process kernels and about +/// `expected_events` events, whose edge and level masks hold one bit per +/// event in whole 64-bit words. A design without kernels has them too: host +/// clocks may run in a compiled scheduler. fn declare_scheduler_slots( modules: &mut HashMap, root: ModuleId, process_count: usize, + expected_events: usize, ) -> Option> { let variables = &mut modules.get_mut(&root)?.variables; let mut next = variables.keys().map(|id| id.0 + 1).max().unwrap_or(0); @@ -2791,19 +2812,20 @@ fn declare_scheduler_slots( use celox_design::{ SCHEDULER_CLOCKS as CLOCKS, SCHEDULER_FLAG_WIDTH as FLAG, SCHEDULER_TIME_WIDTH as TIME, }; + let events = expected_events.next_multiple_of(TIME).max(TIME); Some(celox_design::SchedulerSlots { limit: declare("limit".into(), TIME), now: declare("now".into(), TIME), exit: declare("exit".into(), FLAG), - exit_arg: declare("exit_arg".into(), TIME), + exit_arg: declare("exit_arg".into(), events), 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), - unknown_levels: declare("unknown_levels".into(), TIME), + levels: declare("levels".into(), events), + unknown_levels: declare("unknown_levels".into(), events), ready: declare("ready".into(), TIME), wake: (0..process_count) .map(|index| declare(format!("wake[{index}]"), TIME)) diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index ac84dd64039..e6f5815072c 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -97,6 +97,21 @@ pub trait SimBackend { }) } + /// Run process unit `index` up to `count` times in a row, as + /// [`Self::eval_comb_apply_ff_many_at`] runs ticks, and return how many + /// runs completed: generated code may loop inside the unit, returning + /// after a runtime event; backends without that loop run it once. + fn run_process_many( + &mut self, + index: usize, + count: u64, + ) -> (u64, Result<(), SimulatorErrorCode>) { + if count == 0 { + return (0, Ok(())); + } + (1, self.run_process(index)) + } + // ── signal access ─────────────────────────────────────────── fn resolve_signal(&self, addr: &AbsoluteAddr) -> SignalRef; fn resolve_event(&self, addr: &AbsoluteAddr) -> Self::Event; diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index fa45770658c..43f2a440909 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -63,6 +63,52 @@ pub struct ResolvedSchedule { /// A design's compiled scheduler resolved against a backend: its process /// unit and the slots it exchanges a run with. +/// A set of the compiled scheduler's events, by their bit in `levels`: one +/// 64-bit word per 64 events. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct EventMask(Vec); + +impl EventMask { + /// The set of the events at `bits`. + pub(crate) fn of(bits: impl IntoIterator) -> Self { + let mut mask = Self::default(); + for bit in bits { + let word = bit / 64; + if mask.0.len() <= word { + mask.0.resize(word + 1, 0); + } + mask.0[word] |= 1 << (bit % 64); + } + mask + } + + pub(crate) fn union(&self, other: &Self) -> Self { + let (long, short) = if self.0.len() >= other.0.len() { + (self, other) + } else { + (other, self) + }; + let mut union = long.clone(); + for (word, other) in union.0.iter_mut().zip(&short.0) { + *word |= other; + } + union + } + + /// The events of `self` not in `other`. + pub(crate) fn difference(&self, other: &Self) -> Self { + let mut difference = self.clone(); + for (word, other) in difference.0.iter_mut().zip(&other.0) { + *word &= !other; + } + difference + } + + pub(crate) fn intersects(&self, other: &Self) -> bool { + self.0.iter().zip(&other.0).any(|(a, b)| a & b != 0) + } +} + pub(crate) struct SchedulerRefs { pub(crate) unit: usize, pub(crate) limit: SignalRef, @@ -93,12 +139,12 @@ pub(crate) struct SchedulerRefs { /// in the order of its clock slots. pub(crate) clocks: Vec<(usize, SignalRef)>, /// Per process kernel, the bits of `levels` of the events it writes. - pub(crate) kernel_events: Vec, + pub(crate) kernel_events: Vec, /// Per clock slot, the bit of `levels` of its event. - pub(crate) clock_events: Vec, + pub(crate) clock_events: Vec, /// The bits of `levels` of clocks derived from the others, which any /// slot may change. - pub(crate) derived_events: u64, + pub(crate) derived_events: EventMask, pub(crate) clock_next: SignalRef, pub(crate) clock_period: SignalRef, pub(crate) clock_value: SignalRef, @@ -106,6 +152,16 @@ pub(crate) struct SchedulerRefs { } impl SchedulerRefs { + /// The low word of `exit_arg`, where an exit that names a clock stores + /// its index. The slot is wider when it holds the edges of more than 64 + /// events. + pub(crate) fn exit_index(&self) -> SignalRef { + SignalRef { + width: self.exit_arg.width.min(celox_design::SCHEDULER_TIME_WIDTH), + ..self.exit_arg + } + } + /// Element `bit` of the per-clock slot `slots`. pub(crate) fn clock_element(slots: SignalRef, bit: usize) -> SignalRef { let width = celox_design::SCHEDULER_TIME_WIDTH; @@ -479,12 +535,14 @@ impl ResolvedSchedule { .collect::>()?, kernel_events: (0..scheduler.fallback.len()) .map(|index| { - scheduler - .kernel_events - .get(index) - .into_iter() - .flatten() - .fold(0, |mask, &bit| mask | 1 << bit) + EventMask::of( + scheduler + .kernel_events + .get(index) + .into_iter() + .flatten() + .copied(), + ) }) .collect(), clock_events: scheduler @@ -492,7 +550,7 @@ impl ResolvedSchedule { .iter() .map(|clock| { let bit = scheduler.events.iter().position(|event| event == clock)?; - Some(1 << bit) + Some(EventMask::of([bit])) }) .collect::>()?, clocks: scheduler @@ -507,18 +565,16 @@ impl ResolvedSchedule { clock_period: resolve(&slots.clock_period), clock_value: resolve(&slots.clock_value), clock_armed: resolve(&slots.clock_armed), - derived_events: 0, + derived_events: EventMask::default(), }; // What no kernel and no clock writes itself derives from them. - let all = 1u64 - .checked_shl(refs.events.len() as u32) - .map_or(u64::MAX, |bit| bit - 1); + let all = EventMask::of(0..refs.events.len()); let driven = refs .kernel_events .iter() .chain(&refs.clock_events) - .fold(0, |mask, &bits| mask | bits); - refs.derived_events = all & !driven; + .fold(EventMask::default(), |mask, bits| mask.union(bits)); + refs.derived_events = all.difference(&driven); Some(refs) }), kernel_fallback: model diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 6f459a749d1..39d3529fddb 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -79,7 +79,7 @@ impl SimulationState { || !pending.nba_events.is_empty() // A derived clock changes with the slots of its sources, which // the scheduler does not tell apart. - || self.observed_events & scheduler.derived_events != 0 + || self.observed_events.intersects(&scheduler.derived_events) || pending.waiters.iter().any(|(process, _)| { scheduler.waits.get(process).is_none_or(Option::is_none) || self.writes_observed(scheduler, process) @@ -109,7 +109,7 @@ impl SimulationState { for event in queue { if clock_slot(scheduler, event, clocks).is_some_and(|bit| { compiled >> bit & 1 != 0 - && scheduler.clock_events[bit] & self.observed_events == 0 + && !scheduler.clock_events[bit].intersects(&self.observed_events) }) { first = first.min(event.time); } else { @@ -141,7 +141,7 @@ impl SimulationState { scheduler .kernel_events .get(process) - .is_some_and(|&events| events & self.observed_events != 0) + .is_some_and(|events| events.intersects(&self.observed_events)) } /// Run the compiled scheduler for the slots up to `limit`. Returns, like @@ -293,7 +293,7 @@ impl SimulationState { let slot_complete = complete || exit == Some(SchedulerExit::ClockOverflow); let overflowed = scheduler .clocks - .get(backend.get_as::(scheduler.exit_arg) as usize) + .get(backend.get_as::(scheduler.exit_index()) as usize) .map(|&(event, _)| event); // Armed clocks wait for their next edge in the event queue again; a // clock whose edge applied in a slot the run left unfinished is gone, @@ -393,12 +393,19 @@ impl SimulationState { } else if count > 0 { // The baseline is the levels slot `now` started from; events the // kernels do not write kept theirs. - let levels: u64 = executor.backend().get_as(scheduler.levels); - let unknown: u64 = if self.four_state { - executor.backend().get_as(scheduler.unknown_levels) - } else { - 0 + // The frontend sizes the slots from an estimate, so they can be + // wider than the events need. + let plane = |slot: crate::SignalRef| -> Box bool> { + if slot.width <= 64 { + let bits: u64 = executor.backend().get_as(slot); + Box::new(move |bit| bits >> bit & 1 != 0) + } else { + let bits = executor.backend().get(slot); + Box::new(move |bit| bits.bit(bit as u64)) + } }; + let level = plane(scheduler.levels); + let unknown = self.four_state.then(|| plane(scheduler.unknown_levels)); // A run without clocks records no level of their events, which // only the clocks change. let scheduler = self @@ -414,8 +421,11 @@ impl SimulationState { clocked || scheduler.clocks.iter().all(|&(clock, _)| clock != id) }) .map(|(bit, &id)| { - let level = (levels >> bit & 1) as u8; - (id, level | ((unknown >> bit & 1) as u8 * LEVEL_UNKNOWN)) + let unknown = unknown.as_ref().is_some_and(|unknown| unknown(bit)); + ( + id, + u8::from(level(bit)) | (u8::from(unknown) * LEVEL_UNKNOWN), + ) }) .collect(); for (id, level) in recorded { diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 17198395437..239dff9968c 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -171,7 +171,7 @@ pub struct SimulationState { /// The bits of the compiled scheduler's events whose changes the host /// observes inside a slot: the kernels and host clocks that write them /// run in the reference loop. - observed_events: u64, + observed_events: crate::schedule::EventMask, } impl SimulationState { @@ -234,7 +234,7 @@ impl SimulationState { return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, stats: SchedulerStats::default(), - observed_events: 0, + observed_events: Default::default(), }; state.stats.kernels = (0..state.model.processes.len()) .map(|index| match state.model.kernel_fallback.get(index) { @@ -427,11 +427,12 @@ impl SimulationState { let Some(scheduler) = &self.model.scheduler else { return; }; - self.observed_events = signals - .into_iter() - .filter_map(|signal| self.model.signal_to_id.get(&signal)) - .filter_map(|event| scheduler.events.iter().position(|id| id == event)) - .fold(0, |mask, bit| mask | 1 << bit); + self.observed_events = crate::schedule::EventMask::of( + signals + .into_iter() + .filter_map(|signal| self.model.signal_to_id.get(&signal)) + .filter_map(|event| scheduler.events.iter().position(|id| id == event)), + ); } /// [`Self::step_until`], showing the step to `observer`. An error of diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 913f937e2cc..ba3379ef323 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -884,11 +884,13 @@ impl NativeProgramImage { usize::MAX } }); - // Derived-edge units follow process and scheduler entries. - let derived_units = 2 * self.runtime_schema.derived_edges.len(); - let derived_in_range = self.runtime_schema.derived_edges.iter().all(|units| { - units.rising < self.process_offsets.len() && units.falling < self.process_offsets.len() - }); + // The derived-edge units follow process and scheduler entries. + let derived_units = self.runtime_schema.derived_edges.len(); + let derived_in_range = self + .runtime_schema + .derived_edges + .iter() + .all(|units| units.unit < self.process_offsets.len()); if !derived_in_range || self.process_offsets.len() != self @@ -2788,6 +2790,14 @@ fn compile_program_with_outlining_threshold( // registers, scratch values, or extern call area. process_options = process_options.with_native_callees([comb_jit.required_state_size]); } + // The derived-edge units run periods of their events in a loop. + let derived_units: crate::HashSet = sir + .runtime() + .runtime_schema + .derived_edges + .iter() + .map(|units| units.unit) + .collect(); let derived_model = (!sir.deferred_derived_edges.is_empty()).then(|| { celox_design::schedule::ScheduleModel::derive(&sir.design, &sir.runtime().runtime_schema) }); @@ -2809,13 +2819,14 @@ fn compile_program_with_outlining_threshold( }, |edge| { if outline_comb { - // The recipe estimate includes two complete comb - // copies. Both now use a single call; its fixed CFG - // allowance already covers those call instructions. + // The recipe estimate includes four complete comb + // copies, two per edge. All now use a single call; + // its fixed CFG allowance already covers those call + // instructions. ( - edge.blocks.saturating_sub(comb_blocks.saturating_mul(2)), + edge.blocks.saturating_sub(comb_blocks.saturating_mul(4)), edge.instructions - .saturating_sub(comb_instructions.saturating_mul(2)), + .saturating_sub(comb_instructions.saturating_mul(4)), ) } else { (edge.blocks, edge.instructions) @@ -2862,11 +2873,16 @@ fn compile_program_with_outlining_threshold( }) .transpose()?; let unit = generated.as_ref().unwrap_or(unit); + let label = if derived_units.contains(&index) { + celox_backend_common::DERIVED_EDGE_LABEL.to_string() + } else { + format!("process[{index}]") + }; compile_unit_refs( &[unit], layout, options.four_state, - &format!("process[{index}]"), + &label, NativeMergeKind::Complete, None, &process_options, @@ -4091,9 +4107,34 @@ impl super::super::SimBackend for NativeBackend { .process_funcs .get(index) .ok_or(SimulatorErrorCode::InternalError)?; + // A unit compiled in the tick loop runs as many times as the header + // says, which a batch that returned early leaves above one. + if self.compiled.options.native_tick_loop { + return self.call_func_many_timed(func, 1).1; + } self.call_func_timed(func) } + /// The derived-edge units are compiled with the tick loop when it is on + /// (see [`celox_backend_common::loops_ticks`]); the host runs no other + /// unit many times. + fn run_process_many( + &mut self, + index: usize, + count: u64, + ) -> (u64, Result<(), SimulatorErrorCode>) { + let Some(&func) = self.compiled.process_funcs.get(index) else { + return (0, Err(SimulatorErrorCode::InternalError)); + }; + if self.compiled.options.native_tick_loop { + self.call_func_many_timed(func, count) + } else if count == 0 { + (0, Ok(())) + } else { + (1, self.call_func_timed(func)) + } + } + fn resolve_signal(&self, addr: &AbsoluteAddr) -> SignalRef { let layout = &self.compiled.layout; let offset = layout.offsets.get(addr).copied().unwrap_or(0); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0c1979652e2..b3044cc12cc 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 the scheduler's slots and the reads of TB settle requests. -const CONTAINER_VERSION: u16 = 56; +// Derived-edge units are one per event and run periods in the tick loop. +const CONTAINER_VERSION: u16 = 57; 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/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index 2fd781ce4ca..f028fb71ab2 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -387,6 +387,23 @@ impl CompiledTier { } } + fn run_process_many( + &mut self, + index: usize, + count: u64, + ) -> (u64, Result<(), SimulatorErrorCode>) { + match self { + #[cfg(feature = "cranelift")] + Self::Jit(jit) => jit.run_process_many(index, count), + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + Self::Native(native) => native.run_process_many(index, count), + } + } + /// Resolve the phase-specific apply event for a shared trigger address /// and execute it. fn apply_ff_at_addr(&mut self, addr: &AbsoluteAddr) -> Result<(), SimulatorErrorCode> { @@ -1640,6 +1657,21 @@ impl SimBackend for TieredBackend { } } + fn run_process_many( + &mut self, + index: usize, + count: u64, + ) -> (u64, Result<(), SimulatorErrorCode>) { + self.maybe_promote(); + self.maybe_upgrade(); + self.count_evaluation_for_current_tier(); + match &mut self.phase { + Phase::Interpreting(Some(interp)) => interp.run_process_many(index, count), + Phase::Compiled(compiled) => compiled.run_process_many(index, count), + Phase::Interpreting(None) => unreachable!("promoted backend left no interpreter"), + } + } + fn resolve_signal(&self, addr: &AbsoluteAddr) -> SignalRef { match &self.phase { Phase::Interpreting(Some(interp)) => interp.resolve_signal(addr), diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 183cb8cae95..2563dfd9129 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -15,10 +15,11 @@ //! gate programs. use celox_design::{ - DomainKind, GateOp, SCHEDULER_FLAG_WIDTH, STABLE_REGION, edges::active_level, - schedule::ScheduleModel, + DERIVED_EDGE_FALLING, DERIVED_EDGE_MOVED, DERIVED_EDGE_RISING, DomainKind, GateOp, + SCHEDULER_FLAG_WIDTH, STABLE_REGION, edges::active_level, schedule::ScheduleModel, }; use celox_sir::{BinaryOp, BlockId, SIRBuilder, SIRTerminator, SIRValue, UnaryOp}; +use num_bigint::BigUint; use crate::ir::{ AbsoluteAddr, ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, SIRInstruction, @@ -34,8 +35,10 @@ const GATE_WIDTH: usize = 64; /// The deepest stack a gate program may use, as the Rust walk allows. const GATE_STACK: usize = 16; -/// The most domains one edge can fire: one bit each in a fire mask. -const MAX_ENTRIES: usize = 64; +/// The narrowest fire mask, one bit per domain an edge can fire: one 64-bit +/// word, which every edge reaching at most 64 domains uses. An edge reaching +/// more uses as many words as its domains need. +const MIN_ENTRY_BITS: usize = 64; /// The units of one event domain. #[derive(Clone, Debug)] @@ -139,9 +142,6 @@ impl EdgePlan { if comb_fatal { return Err("combinational logic has fatal assertions"); } - if domains.len() + gated.len() + 1 > MAX_ENTRIES { - return Err("an edge reaches too many derived domains"); - } // A derived clock without a domain of its own is left out, as the // Rust walk leaves out a clock without an event. let derived = |address: AbsoluteAddr| -> Result, &'static str> { @@ -204,6 +204,14 @@ impl EdgePlan { .chain(self.gated.iter().map(|gated| &gated.derived.units)) } + /// The width of a fire mask: one bit per entry, at least + /// [`MIN_ENTRY_BITS`] and a whole number of words. + fn entry_bits(&self) -> usize { + (1 + self.domains.len() + self.gated.len()) + .next_multiple_of(64) + .max(MIN_ENTRY_BITS) + } + fn gated_bit(&self, index: usize) -> usize { 1 + self.domains.len() + index } @@ -240,9 +248,11 @@ impl EdgePlan { settled: BlockId, unsettled: BlockId, ) { + let bits = self.entry_bits(); let mut e = Emitter { b, after: Vec::new(), + entry_bits: bits, }; // The state-derived clocks' levels before the edge, the baseline of // their edges for the whole phase. @@ -254,14 +264,14 @@ impl EdgePlan { // The fire section's parameters: the domains to fire, those fired so // far, whether to settle first, and whether the gated domains run // first one at a time (`fire_with_gated`). - let mask = e.b.alloc_bit(MAX_ENTRIES, false); - let fired = e.b.alloc_bit(MAX_ENTRIES, false); + let mask = e.b.alloc_bit(bits, false); + let fired = e.b.alloc_bit(bits, false); let settle_first = e.b.alloc_bit(1, false); let alone = e.b.alloc_bit(1, false); let fire = e.b.new_block_with(vec![mask, fired, settle_first, alone]); let source = e.bit(fires, 0); if self.gated.is_empty() { - let zero = e.constant(0, MAX_ENTRIES); + let zero = e.constant(0, bits); let none = e.binary(1, source, BinaryOp::Eq, zero); let no = e.constant(0, 1); let start = e.b.new_block(); @@ -276,15 +286,15 @@ impl EdgePlan { // The edge: each gated clock judged from its gate program with // the signal at its old and new level. let mut ready = source; - let mut gated_fired = e.constant(0, MAX_ENTRIES); + let mut gated_fired = e.constant(0, bits); let mut after = Vec::with_capacity(self.gated.len()); for (index, gated) in self.gated.iter().enumerate() { let before = e.gate(&gated.gate, from); let level = e.gate(&gated.gate, to); let edge = e.edge(gated.derived.kind, before, level); let bit = e.bit(edge, self.gated_bit(index)); - ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); - gated_fired = e.binary(MAX_ENTRIES, gated_fired, BinaryOp::Or, bit); + ready = e.binary(bits, ready, BinaryOp::Or, bit); + gated_fired = e.binary(bits, gated_fired, BinaryOp::Or, bit); after.push(level); } let alone = e.constant(u64::from(self.independent), 1); @@ -299,24 +309,26 @@ impl EdgePlan { e.b.switch_to_block(fire); let fire_end = e.b.new_block(); e.settle_if(settle_first, comb); - let zero = e.constant(0, MAX_ENTRIES); + let zero = e.constant(0, bits); let gated_mask = self .gated .iter() .enumerate() - .fold(0u64, |mask, (index, _)| mask | 1 << self.gated_bit(index)); - let gated_bits = e.constant(gated_mask, MAX_ENTRIES); - let gated_ready = e.binary(MAX_ENTRIES, mask, BinaryOp::And, gated_bits); + .fold(BigUint::ZERO, |mask, (index, _)| { + mask | BigUint::from(1u8) << self.gated_bit(index) + }); + let gated_bits = e.wide_constant(gated_mask, bits); + let gated_ready = e.binary(bits, mask, BinaryOp::And, gated_bits); let any_gated = e.binary(1, gated_ready, BinaryOp::Ne, zero); let in_turn = e.binary(1, alone, BinaryOp::And, any_gated); // Each domain's units appear once in the unit: the one-domain path // also serves the independent gated domains one at a time, and only // domains that can fire with another get the several-domain path. - let one_mask = e.b.alloc_bit(MAX_ENTRIES, false); - let remaining = e.b.alloc_bit(MAX_ENTRIES, false); + let one_mask = e.b.alloc_bit(bits, false); + let remaining = e.b.alloc_bit(bits, false); let turn = e.b.alloc_bit(1, false); let one_domain = e.b.new_block_with(vec![one_mask, remaining, turn]); - let rest = e.b.alloc_bit(MAX_ENTRIES, false); + let rest = e.b.alloc_bit(bits, false); let next_turn = e.b.new_block_with(vec![rest]); let together = e.b.new_block(); e.b.seal_block(SIRTerminator::Branch { @@ -333,8 +345,8 @@ impl EdgePlan { .chain(std::iter::once(0)) .collect(); for entry in order { - let bit = e.constant(1 << entry, MAX_ENTRIES); - let selected = e.binary(MAX_ENTRIES, rest, BinaryOp::And, bit); + let bit = e.single(entry, bits); + let selected = e.binary(bits, rest, BinaryOp::And, bit); let set = e.binary(1, selected, BinaryOp::Ne, zero); let take = e.b.new_block(); let skip = e.b.new_block(); @@ -344,9 +356,9 @@ impl EdgePlan { false_block: (skip, Vec::new()), }); e.b.switch_to_block(take); - let all = e.constant(u64::MAX, MAX_ENTRIES); - let others = e.binary(MAX_ENTRIES, bit, BinaryOp::Xor, all); - let left = e.binary(MAX_ENTRIES, rest, BinaryOp::And, others); + let all = e.ones(bits); + let others = e.binary(bits, bit, BinaryOp::Xor, all); + let left = e.binary(bits, rest, BinaryOp::And, others); let yes = e.constant(1, 1); e.b.seal_block(SIRTerminator::Jump(one_domain, vec![bit, left, yes])); e.b.switch_to_block(skip); @@ -356,13 +368,13 @@ impl EdgePlan { // The domains together: one evaluates and commits at once, several // evaluate, then commit, in entry order. e.b.switch_to_block(together); - let one = e.constant(1, MAX_ENTRIES); - let lower = e.binary(MAX_ENTRIES, mask, BinaryOp::Sub, one); - let others = e.binary(MAX_ENTRIES, mask, BinaryOp::And, lower); + let one = e.constant(1, bits); + let lower = e.binary(bits, mask, BinaryOp::Sub, one); + let others = e.binary(bits, mask, BinaryOp::And, lower); let single = e.binary(1, others, BinaryOp::Eq, zero); let several = e.b.new_block(); let no = e.constant(0, 1); - let none_left = e.constant(0, MAX_ENTRIES); + let none_left = e.constant(0, bits); e.b.seal_block(SIRTerminator::Branch { cond: single, true_block: (one_domain, vec![mask, none_left, no]), @@ -400,23 +412,23 @@ impl EdgePlan { // domains not fired yet whose clocks moved to their active edge. e.b.switch_to_block(fire_end); e.inline_all(comb); - let mut ready = e.constant(0, MAX_ENTRIES); + let mut ready = e.constant(0, bits); for (index, domain) in self.domains.iter().enumerate() { let is = e.level(domain.signal, domain.width); let edge = e.edge(domain.kind, was[index], is); let bit = e.bit(edge, 1 + index); - ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); + ready = e.binary(bits, ready, BinaryOp::Or, bit); } let after = std::mem::take(&mut e.after); for (index, gated) in self.gated.iter().enumerate() { let is = e.gate(&gated.gate, to); let edge = e.edge(gated.derived.kind, after[index], is); let bit = e.bit(edge, self.gated_bit(index)); - ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); + ready = e.binary(bits, ready, BinaryOp::Or, bit); } - let all = e.constant(u64::MAX, MAX_ENTRIES); - let unfired = e.binary(MAX_ENTRIES, fired, BinaryOp::Xor, all); - let ready = e.binary(MAX_ENTRIES, ready, BinaryOp::And, unfired); + let all = e.ones(bits); + let unfired = e.binary(bits, fired, BinaryOp::Xor, all); + let ready = e.binary(bits, ready, BinaryOp::And, unfired); let quiet = e.binary(1, ready, BinaryOp::Eq, zero); let round = e.b.new_block(); e.b.seal_block(SIRTerminator::Branch { @@ -425,7 +437,7 @@ impl EdgePlan { false_block: (round, Vec::new()), }); e.b.switch_to_block(round); - let now_fired = e.binary(MAX_ENTRIES, fired, BinaryOp::Or, ready); + let now_fired = e.binary(bits, fired, BinaryOp::Or, ready); let no = e.constant(0, 1); e.b.seal_block(SIRTerminator::Jump(fire, vec![ready, now_fired, no, no])); } @@ -491,16 +503,32 @@ struct Emitter<'b> { /// The gated clocks' levels just after the edge, the baseline of their /// further edges in the rounds. after: Vec, + /// See [`EdgePlan::entry_bits`]. + entry_bits: usize, } impl Emitter<'_> { fn constant(&mut self, value: u64, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(value), width) + } + + fn wide_constant(&mut self, value: BigUint, width: usize) -> RegisterId { let register = self.b.alloc_bit(width, false); self.b .emit(SIRInstruction::Imm(register, SIRValue::new(value))); register } + /// The `width`-bit value with only bit `bit` set. + fn single(&mut self, bit: usize, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(1u8) << bit, width) + } + + /// The `width`-bit value with every bit set. + fn ones(&mut self, width: usize) -> RegisterId { + self.wide_constant((BigUint::from(1u8) << width) - 1u8, width) + } + fn binary( &mut self, width: usize, @@ -561,9 +589,9 @@ impl Emitter<'_> { /// Bit `index` of a fire mask, set when `condition` holds. fn bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { - let set = self.constant(1 << index, MAX_ENTRIES); - let unset = self.constant(0, MAX_ENTRIES); - let bit = self.b.alloc_bit(MAX_ENTRIES, false); + let set = self.single(index, self.entry_bits); + let unset = self.constant(0, self.entry_bits); + let bit = self.b.alloc_bit(self.entry_bits, false); self.b.emit(SIRInstruction::Mux(bit, condition, set, unset)); bit } @@ -693,11 +721,19 @@ impl Emitter<'_> { self.b.switch_to_block(next); } + /// Whether `bit` is set in the mode `mode`. + fn mode_bit(&mut self, mode: RegisterId, bit: u8) -> RegisterId { + let selector = self.constant(u64::from(bit), SCHEDULER_FLAG_WIDTH); + let selected = self.binary(SCHEDULER_FLAG_WIDTH, mode, BinaryOp::And, selector); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + self.binary(1, selected, BinaryOp::Ne, zero) + } + /// Run `body` when bit `index` of `mask` is set. fn if_bit(&mut self, mask: RegisterId, index: usize, body: impl FnOnce(&mut Self)) { - let selector = self.constant(1 << index, MAX_ENTRIES); - let selected = self.binary(MAX_ENTRIES, mask, BinaryOp::And, selector); - let zero = self.constant(0, MAX_ENTRIES); + let selector = self.single(index, self.entry_bits); + let selected = self.binary(self.entry_bits, mask, BinaryOp::And, selector); + let zero = self.constant(0, self.entry_bits); let set = self.binary(1, selected, BinaryOp::Ne, zero); let run = self.b.new_block(); let next = self.b.new_block(); @@ -713,24 +749,12 @@ impl Emitter<'_> { } } -/// Where a generated edge unit learns whether combinational logic must -/// settle before the domains evaluate. -#[derive(Clone, Copy, Debug)] -enum Settle { - #[cfg_attr( - not(all(test, feature = "systemverilog", feature = "cranelift")), - allow(dead_code) - )] - Fixed(bool), - /// A flag object, not zero when it must. - Flag(AbsoluteAddr), -} - impl EdgePlan { /// A unit that runs one edge of the event whose signal its caller /// already moved, rising or falling; `fires` says whether the event's own - /// domain sees its active edge. - fn unit(&self, comb: &[Unit], rising: bool, fires: bool, settle: Settle) -> Unit { + /// domain sees its active edge, `settle` whether logic settles first. + #[cfg(all(test, feature = "systemverilog", feature = "cranelift"))] + fn unit(&self, comb: &[Unit], rising: bool, fires: bool, settle: bool) -> Unit { let mut b = Builder::new(); let constant = |b: &mut Builder, value: u64, width: usize| { let register = b.alloc_bit(width, false); @@ -739,28 +763,25 @@ impl EdgePlan { }; let from = constant(&mut b, u64::from(!rising), 1); let to = constant(&mut b, u64::from(rising), 1); - let source_fires = fires; - let fires = constant(&mut b, u64::from(fires), 1); - let settle = match settle { - Settle::Fixed(value) => constant(&mut b, u64::from(value), 1), - Settle::Flag(flag) => { - let value = b.alloc_bit(SCHEDULER_FLAG_WIDTH, false); - b.emit(SIRInstruction::Load( - value, - RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, flag), - SIROffset::Static(0), - SCHEDULER_FLAG_WIDTH, - )); - let zero = constant(&mut b, 0, SCHEDULER_FLAG_WIDTH); - let set = b.alloc_bit(1, false); - b.emit(SIRInstruction::Binary(set, value, BinaryOp::Ne, zero)); - set - } - }; + let fired = constant(&mut b, u64::from(fires), 1); + let settle = constant(&mut b, u64::from(settle), 1); let done = b.new_block(); - // An edge that never fires the event's own domain leaves its units - // out of the unit. - let plan = if source_fires { + self.for_edge(fires) + .emit(&mut b, comb, from, to, fired, settle, done, done); + b.switch_to_block(done); + b.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = b.drain(); + Unit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + } + + /// The plan of an edge that `fires` the event's own domain or not: one + /// that never does leaves its units out. + fn for_edge(&self, fires: bool) -> std::borrow::Cow<'_, Self> { + if fires { std::borrow::Cow::Borrowed(self) } else { std::borrow::Cow::Owned(EdgePlan { @@ -771,11 +792,150 @@ impl EdgePlan { }, ..self.clone() }) + } + } + + /// The unit of [`celox_design::DerivedEdgeUnits`]: the edges of `event` + /// (a signal of `width` bits) that the mode in `slots.0` selects, with + /// `slots.1` the flag that says whether combinational logic has pending + /// changes, before and after, as the host keeps it: an edge settles first + /// when it is set or logic reads the signal (`comb_read`) that the edge + /// moved itself; an edge that ran domains leaves logic settled; one that + /// ran nothing leaves it as it found it, pending when logic reads the + /// signal the edge moved. `fires` says whether the rising + /// (`true`) or the falling edge fires the event's own domain. + fn edges_unit( + &self, + comb: &[Unit], + event: (AbsoluteAddr, usize), + comb_read: bool, + fires: impl Fn(bool) -> bool, + slots: (AbsoluteAddr, AbsoluteAddr), + ) -> Unit { + let (signal, width) = event; + let (mode_slot, flag) = slots; + let mut b = Builder::new(); + let mut e = Emitter { + b: &mut b, + after: Vec::new(), }; - plan.emit(&mut b, comb, from, to, fires, settle, done, done); - b.switch_to_block(done); - b.seal_block(SIRTerminator::Return); - let (blocks, register_map, _) = b.drain(); + let mode = e.load(mode_slot, 0, SCHEDULER_FLAG_WIDTH); + let flag_value = e.load(flag, 0, SCHEDULER_FLAG_WIDTH); + let zero = e.constant(0, SCHEDULER_FLAG_WIDTH); + let mut dirty = e.binary(1, flag_value, BinaryOp::Ne, zero); + for rising in [true, false] { + let selected = e.mode_bit( + mode, + if rising { + DERIVED_EDGE_RISING + } else { + DERIVED_EDGE_FALLING + }, + ); + let run = e.b.new_block(); + let after = e.b.alloc_bit(1, false); + let join = e.b.new_block_with(vec![after]); + e.b.seal_block(SIRTerminator::Branch { + cond: selected, + true_block: (run, Vec::new()), + false_block: (join, vec![dirty]), + }); + // The host moved the signal for a single edge; otherwise the + // edge moves it, unless it is already at the edge's level. + e.b.switch_to_block(run); + let moved = e.mode_bit(mode, DERIVED_EDGE_MOVED); + // A host that moved the signal judged whether logic reading it + // must settle (it may have evaluated the clock's aliases) and + // put that in the flag. + let read = if comb_read { + let no = e.constant(0, 1); + e.binary(1, moved, BinaryOp::Eq, no) + } else { + e.constant(0, 1) + }; + let body = e.b.new_block(); + let check = e.b.new_block(); + e.b.seal_block(SIRTerminator::Branch { + cond: moved, + true_block: (body, Vec::new()), + false_block: (check, Vec::new()), + }); + e.b.switch_to_block(check); + let level = e.level(signal, width); + let target = e.constant(u64::from(rising), 1); + let there = e.binary(1, level, BinaryOp::Eq, target); + let store = e.b.new_block(); + e.b.seal_block(SIRTerminator::Branch { + cond: there, + true_block: (join, vec![dirty]), + false_block: (store, Vec::new()), + }); + e.b.switch_to_block(store); + let value = e.constant(u64::from(rising), width); + e.b.emit(SIRInstruction::Store( + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, signal), + SIROffset::Static(0), + width, + value, + Vec::new(), + Vec::new(), + )); + e.b.seal_block(SIRTerminator::Jump(body, Vec::new())); + + e.b.switch_to_block(body); + let settle = e.binary(1, dirty, BinaryOp::Or, read); + let from = e.constant(u64::from(!rising), 1); + let to = e.constant(u64::from(rising), 1); + let source_fires = fires(rising); + let fired = e.constant(u64::from(source_fires), 1); + let settled = e.b.new_block(); + let unsettled = e.b.new_block(); + self.for_edge(source_fires) + .emit(e.b, comb, from, to, fired, settle, settled, unsettled); + e.b.switch_to_block(settled); + let clean = e.constant(0, 1); + e.b.seal_block(SIRTerminator::Jump(join, vec![clean])); + e.b.switch_to_block(unsettled); + e.b.seal_block(SIRTerminator::Jump(join, vec![settle])); + e.b.switch_to_block(join); + dirty = after; + } + let set = e.constant(1, SCHEDULER_FLAG_WIDTH); + let clear = e.constant(0, SCHEDULER_FLAG_WIDTH); + let value = e.b.alloc_bit(SCHEDULER_FLAG_WIDTH, false); + e.b.emit(SIRInstruction::Mux(value, dirty, set, clear)); + e.b.emit(SIRInstruction::Store( + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, flag), + SIROffset::Static(0), + SCHEDULER_FLAG_WIDTH, + value, + Vec::new(), + Vec::new(), + )); + e.b.seal_block(SIRTerminator::Return); + let (mut blocks, register_map, _) = b.drain(); + // An edge whose domains always run never takes its unsettled exit. + let mut reached = crate::HashSet::default(); + let mut pending = vec![BlockId(0)]; + while let Some(block) = pending.pop() { + if !reached.insert(block) { + continue; + } + match &blocks[&block].terminator { + SIRTerminator::Jump(target, _) => pending.push(*target), + SIRTerminator::Branch { + true_block, + false_block, + .. + } => pending.extend([true_block.0, false_block.0]), + SIRTerminator::Switch { cases, default, .. } => { + pending.extend(cases.iter().map(|case| case.target)); + pending.push(*default); + } + SIRTerminator::Return | SIRTerminator::Error(_) => {} + } + } + blocks.retain(|block, _| reached.contains(block)); Unit { entry_block_id: BlockId(0), blocks, @@ -784,15 +944,17 @@ impl EdgePlan { } } -/// Generate the edge units of every event whose plan this module emits and +/// Generate the edge unit of every event whose plan this module emits and /// record them in [`celox_design::RuntimeSchema::derived_edges`]. A unit -/// reads the scheduler's dirty flag to know whether to settle first. +/// reads its mode from the scheduler's continuation slot and keeps the +/// state of combinational logic in its dirty flag, which only the +/// scheduler's own unit uses otherwise. pub(crate) fn attach(program: &mut LaidOutProgram) { attach_with_mode(program, false); } /// Reserve native entry indices without retaining a copy of the full circuit -/// for both polarities of every derived-clock event. +/// for the unit of every derived-clock event. pub(crate) fn attach_deferred(program: &mut LaidOutProgram) { attach_with_mode(program, true); } @@ -800,9 +962,12 @@ pub(crate) fn attach_deferred(program: &mut LaidOutProgram) { #[derive(Clone, Debug)] pub(crate) struct DeferredEdge { event: AbsoluteAddr, - rising: bool, - fires: bool, - flag: AbsoluteAddr, + width: usize, + comb_read: bool, + /// Whether the rising and the falling edge fire the event's own domain. + fires: [bool; 2], + /// The mode slot and the dirty flag. + slots: (AbsoluteAddr, AbsoluteAddr), pub(crate) blocks: usize, pub(crate) instructions: usize, } @@ -824,7 +989,13 @@ impl DeferredEdge { ) -> Result { let plan = EdgePlan::new(program, model, self.event)? .ok_or("deferred derived edge no longer has a plan")?; - let mut unit = plan.unit(comb, self.rising, self.fires, Settle::Flag(self.flag)); + let mut unit = plan.edges_unit( + comb, + (self.event, self.width), + self.comb_read, + |rising| self.fires[usize::from(!rising)], + self.slots, + ); crate::settle::instrument_unit(program, &mut unit); Ok(unit) } @@ -832,10 +1003,10 @@ impl DeferredEdge { fn attach_with_mode(program: &mut LaidOutProgram, deferred: bool) { let schema = &program.runtime.runtime_schema; - let Some(flag) = schema + let Some((mode, flag)) = schema .scheduler .as_ref() - .map(|scheduler| scheduler.slots.dirty) + .map(|scheduler| (scheduler.slots.cont, scheduler.slots.dirty)) else { return; }; @@ -857,27 +1028,34 @@ fn attach_with_mode(program: &mut LaidOutProgram, deferred: bool) { ) => rising == (active_level(kind) == 1), _ => true, }; - let mut indices = [0usize; 2]; - // Include both settles and every possible FF path. The control-flow - // allowance also covers gate expressions and per-unit continuations. - let (estimated_blocks, estimated_instructions) = if deferred { - let units = program - .sir - .eval_comb - .iter() - .chain(&program.sir.eval_comb) - .chain(plan.entries().flat_map(|units| { - units - .eval_apply - .iter() - .chain(units.eval_only.as_ref().unwrap_or(&units.eval_apply)) - .chain(units.apply.iter().flatten()) - })); + let Some(&width) = program.layout().widths.get(&event) else { + continue; + }; + let comb_read = model.events.combinationally_read.contains(&event); + let fires = [fires(true), fires(false)]; + let index = program.sir.processes.len(); + let unit = if deferred { + // Include both settles of both edges and every possible FF path + // of each. The control-flow allowance also covers gate + // expressions, the mode checks and per-unit continuations. + let units = std::iter::repeat_n(&program.sir.eval_comb, 4) + .flatten() + .chain( + std::iter::repeat_n((), 2) + .flat_map(|()| plan.entries()) + .flat_map(|units| { + units + .eval_apply + .iter() + .chain(units.eval_only.as_ref().unwrap_or(&units.eval_apply)) + .chain(units.apply.iter().flatten()) + }), + ); let gate_ops = plan.gated.iter().map(|gate| gate.gate.len()).sum::(); - units.fold( + let (blocks, instructions) = units.fold( ( - 1024usize, - 8192usize.saturating_add(gate_ops.saturating_mul(16)), + 2048usize, + 16384usize.saturating_add(gate_ops.saturating_mul(32)), ), |(blocks, instructions), unit| { ( @@ -890,56 +1068,45 @@ fn attach_with_mode(program: &mut LaidOutProgram, deferred: bool) { ), ) }, - ) - } else { - (0, 0) - }; - if deferred { + ); tracing::debug!( "[derived-edge-size] event={} kind={:?} blocks={} instructions={}", program.get_path(&event), kind, - estimated_blocks, - estimated_instructions, + blocks, + instructions, ); - } - for (index, rising) in [true, false].into_iter().enumerate() { - indices[index] = program.sir.processes.len(); - let unit = if deferred { - program.deferred_derived_edges.insert( - indices[index], - DeferredEdge { - event, - rising, - fires: fires(rising), - flag, - blocks: estimated_blocks, - instructions: estimated_instructions, - }, - ); - let mut builder = Builder::new(); - builder.seal_block(SIRTerminator::Return); - let (blocks, register_map, _) = builder.drain(); - Unit { - entry_block_id: BlockId(0), + program.deferred_derived_edges.insert( + index, + DeferredEdge { + event, + width, + comb_read, + fires, + slots: (mode, flag), blocks, - register_map, - } - } else { - plan.unit( - &program.sir.eval_comb, - rising, - fires(rising), - Settle::Flag(flag), - ) - }; - program.sir.processes.push(unit); - } - edges.push(celox_design::DerivedEdgeUnits { - event, - rising: indices[0], - falling: indices[1], - }); + instructions, + }, + ); + let mut builder = Builder::new(); + builder.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = builder.drain(); + Unit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + } else { + plan.edges_unit( + &program.sir.eval_comb, + (event, width), + comb_read, + |rising| fires[usize::from(!rising)], + (mode, flag), + ) + }; + edges.push(celox_design::DerivedEdgeUnits { event, unit: index }); + program.sir.processes.push(unit); } program.runtime.runtime_schema.derived_edges = edges; } @@ -954,7 +1121,7 @@ pub(crate) fn without_units(program: &LaidOutProgram) -> LaidOutProgram { .runtime_schema .derived_edges .iter() - .map(|units| units.rising.min(units.falling)) + .map(|units| units.unit) .min(); if let Some(first) = first { program.sir.processes.truncate(first); @@ -990,8 +1157,7 @@ pub(crate) fn attach_test_units(program: &mut LaidOutProgram, sink: &TestEdgeUni for rising in [false, true] { for settle in [false, true] { for fires in [false, true] { - let unit = - plan.unit(&program.sir.eval_comb, rising, fires, Settle::Fixed(settle)); + let unit = plan.unit(&program.sir.eval_comb, rising, fires, settle); let index = program.sir.processes.len(); program.sir.processes.push(unit); sink.lock().expect("unpoisoned").push(TestEdgeUnit { @@ -1060,6 +1226,19 @@ mod tests { assign q = h + w; endmodule"; + /// Edges of `clk` that run nothing leave a host write of `en` for the + /// next edge to settle: logic does not read `clk`. + const DIVIDED_ENABLE: &str = + "module Top(input logic clk, input logic en, output logic [7:0] q); + logic half = 0; + logic [7:0] h = 0; + logic [7:0] w; + assign w = en ? 8'd3 : 8'd1; + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) h <= h + w; + assign q = h; + endmodule"; + const RAISED_ENABLE: &str = "module Top(input logic clk, output logic [7:0] q); logic en = 0; logic gclk; @@ -1227,11 +1406,17 @@ mod tests { /// repeated edges, and host writes of `en` when the design has it. fn ticks_agree(source: &str) { let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); - let mut generated = build().build().unwrap(); - let mut walked = build() - .disable_pass(crate::SirPass::DerivedEdgeUnits) - .build() - .unwrap(); + ticks_agree_on( + build().build().unwrap(), + build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build() + .unwrap(), + ); + } + + /// [`ticks_agree`] for two simulators of one backend. + fn ticks_agree_on(mut generated: Simulator, mut walked: Simulator) { assert!( !generated.program.runtime_schema.derived_edges.is_empty(), "no edge unit was generated" @@ -1266,24 +1451,264 @@ mod tests { } } + /// Run batches of periods of `clk` in the generated unit and as edges + /// through the plan walk, with host writes of `en` and single rising + /// edges in between, and compare every named signal after each batch. + fn periods_agree(source: &str) { + let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + let mut generated = build().build().unwrap(); + let mut walked = build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build() + .unwrap(); + let clk = generated.event("clk"); + let en = generated.try_signal("en").ok(); + let names: Vec<_> = walked.named_signals(); + let mut longest = 0; + for step in 0..40u64 { + for sim in [&mut generated, &mut walked] { + if let Some(en) = en + && step % 5 < 2 + { + sim.modify(|io| io.set(en, u8::from(step % 3 != 0))) + .unwrap(); + } + } + // A batch may start with the signal high: its first rise moves + // nothing. + if step % 4 == 3 { + generated.edge(clk, Edge::Rising).unwrap(); + walked.edge(clk, Edge::Rising).unwrap(); + } + let count = step % 7 + 1; + let mut left = count; + while left > 0 { + let (ran, result) = generated + .derived_periods(clk, left) + .expect("clk runs its generated unit"); + result.unwrap(); + assert!(ran >= 1 && ran <= left, "step {step}: {ran} of {left}"); + longest = longest.max(ran); + left -= ran; + } + for _ in 0..count { + walked.edge(clk, Edge::Rising).unwrap(); + walked.edge(clk, Edge::Falling).unwrap(); + } + for named in &names { + assert_eq!( + generated.get(named.signal), + walked.get(named.signal), + "step {step}: {}", + named.name + ); + } + } + // The native unit loops over the periods of a batch. + assert!(longest > 1, "no batch ran more than one period"); + } + + #[test] + fn periods_run_in_generated_units_as_the_plan_walk() { + for source in [ + GATED, + INVERTED, + DIVIDERS, + DIVIDED_ENABLE, + RAISED_ENABLE, + INDEPENDENT, + ] { + periods_agree(source); + } + } + + /// A batch of periods returns after the period whose derived domain + /// records a runtime event, which the host sees in order. + #[test] + fn periods_return_after_a_runtime_event() { + let source = "module Top(input logic clk, output logic [7:0] q); + logic half = 0; + logic [7:0] h = 0; + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) begin + h <= h + 8'd1; + $display(\"h=%0d\", h); + end + assign q = h; + endmodule"; + let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + let mut generated = build().build().unwrap(); + let mut walked = build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build() + .unwrap(); + let clk = generated.event("clk"); + let mut displays = Vec::new(); + let mut left = 9u64; + while left > 0 { + let (ran, result) = generated.derived_periods(clk, left).unwrap(); + result.unwrap(); + // A display every other period: a batch ends at one. + assert!(ran <= 2, "{ran} periods ran past a display"); + displays.extend(generated.drain_runtime_events()); + left -= ran; + } + let mut expected = Vec::new(); + for _ in 0..9 { + walked.edge(clk, Edge::Rising).unwrap(); + walked.edge(clk, Edge::Falling).unwrap(); + expected.extend(walked.drain_runtime_events()); + } + assert_eq!(displays, expected); + assert_eq!(expected.len(), 5); + } + + /// How a host drives the periods of `clk`. + #[derive(Clone, Copy, Debug)] + enum Drive { + Ticks, + Edges, + Periods, + } + + /// Drive up to `limit` periods of `clk` through `sim` and return the + /// period that failed and its error, if one did. + fn first_failure( + sim: &mut Simulator, + drive: Drive, + limit: u64, + ) -> Option<(u64, String)> { + let clk = sim.event("clk"); + let period_edges = |sim: &mut Simulator| { + sim.edge(clk, Edge::Rising) + .and_then(|()| sim.edge(clk, Edge::Falling)) + }; + let mut period = 0; + while period < limit { + // The periods a call ran, the one that failed included. + let (ran, result) = match drive { + Drive::Ticks => (1, sim.tick(clk)), + Drive::Edges => (1, period_edges(sim)), + Drive::Periods => sim + .derived_periods(clk, limit - period) + // The plan walk has no batches. + .unwrap_or_else(|| (1, period_edges(sim))), + }; + if let Err(error) = result { + return Some((period + ran.saturating_sub(1), error.to_string())); + } + period += ran; + } + None + } + + /// A deferred assertion's action in a derived domain matures at the end + /// of the edge, the tick or the period that ran it, as in the plan walk. + #[test] + fn deferred_assertions_of_derived_domains_mature() { + let source = "module Top(input logic clk, output logic [7:0] q); + logic half = 0; + logic [7:0] h = 0; + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) begin + h <= h + 8'd1; + assert #0 (h != 8'd3) else $fatal(1, \"h reached 3\"); + end + assign q = h; + endmodule"; + let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + for drive in [Drive::Ticks, Drive::Edges, Drive::Periods] { + let expected = first_failure( + &mut build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build() + .unwrap(), + drive, + 20, + ); + assert!(expected.is_some(), "{drive:?}: the walk reports no failure"); + let native = first_failure(&mut build().build().unwrap(), drive, 20); + assert_eq!(native, expected, "{drive:?} native"); + let cranelift = first_failure(&mut build().build_cranelift().unwrap(), drive, 20); + assert_eq!(cranelift, expected, "{drive:?} cranelift"); + } + } + + /// A batch that returned after a runtime event leaves no periods for a + /// single edge afterwards to run. + #[test] + fn single_edges_after_a_batch_returned_early_run_once() { + let source = "module Top(input logic clk, output logic [7:0] q); + logic half = 0; + logic [7:0] h = 0; + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) begin + h <= h + 8'd1; + $display(\"h=%0d\", h); + end + assign q = h; + endmodule"; + let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + let mut generated = build().build().unwrap(); + let mut walked = build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build() + .unwrap(); + let clk = generated.event("clk"); + let (ran, result) = generated.derived_periods(clk, 9).unwrap(); + result.unwrap(); + assert!(ran < 9, "the batch did not return at its display"); + for _ in 0..ran { + walked.edge(clk, Edge::Rising).unwrap(); + walked.edge(clk, Edge::Falling).unwrap(); + } + let q = generated.signal("q"); + for step in 0..6 { + match step % 3 { + 0 => { + generated.tick(clk).unwrap(); + walked.tick(clk).unwrap(); + } + 1 => { + generated.edge(clk, Edge::Rising).unwrap(); + walked.edge(clk, Edge::Rising).unwrap(); + } + _ => { + generated.edge(clk, Edge::Falling).unwrap(); + walked.edge(clk, Edge::Falling).unwrap(); + } + } + assert_eq!(generated.get(q), walked.get(q), "step {step}"); + } + assert_eq!( + generated.drain_runtime_events(), + walked.drain_runtime_events() + ); + } + #[test] fn simulator_ticks_run_generated_edges_as_the_plan_walk() { - for source in [GATED, INVERTED, DIVIDERS, RAISED_ENABLE, INDEPENDENT] { + for source in [ + GATED, + INVERTED, + DIVIDERS, + DIVIDED_ENABLE, + RAISED_ENABLE, + INDEPENDENT, + ] { ticks_agree(source); } } - /// An edge reaching 60 gated domains. - #[test] - fn an_edge_reaching_60_gated_domains_runs_as_the_plan_walk() { - const GATED_CLOCKS: usize = 60; + /// One `clk` gating `gated_clocks` clocks, each clocking a counter. + fn gated_domains_source(gated_clocks: usize) -> String { let mut source = String::from( "module Top(input logic clk, input logic en, output logic [7:0] q);\n \ logic [6:0] count = 0;\n logic [7:0] sum;\n \ always_ff @(posedge clk) count <= count + 7'd1;\n", ); let mut terms = Vec::new(); - for index in 0..GATED_CLOCKS { + for index in 0..gated_clocks { source += &format!( " logic g{index};\n logic [7:0] n{index} = 0;\n \ assign g{index} = clk & (en ^ (count[2:0] == 3'd{bits}) ^ (count[6:3] == 4'd{high}));\n \ @@ -1294,7 +1719,34 @@ mod tests { terms.push(format!("n{index}")); } source += &format!(" assign q = {};\nendmodule\n", terms.join(" ^ ")); - ticks_agree(&source); + source + } + + /// An edge reaching 60 gated domains. + #[test] + fn an_edge_reaching_60_gated_domains_runs_as_the_plan_walk() { + ticks_agree(&gated_domains_source(60)); + } + + /// An edge reaching more domains than one word of a fire mask holds. + #[test] + fn an_edge_reaching_more_than_64_domains_runs_as_the_plan_walk() { + ticks_agree(&gated_domains_source(70)); + } + + /// The same on Cranelift, whose wide comparisons once ran every domain. + #[test] + fn an_edge_reaching_more_than_64_domains_runs_on_cranelift_as_the_plan_walk() { + let source = gated_domains_source(70); + let build = + || Simulator::from_sv_sources(vec![(source.as_str(), Path::new("top.sv"))], "Top"); + ticks_agree_on( + build().build_cranelift().unwrap(), + build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build_cranelift() + .unwrap(), + ); } #[test] diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index e81311b3f10..4449ea6b5e4 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -41,6 +41,7 @@ use celox_design::{ TIME_SLOT_WIDTH, edges::LEVEL_UNKNOWN, schedule::ScheduleModel, }; use celox_sir::{BinaryOp, SIRBuilder, SIRSwitchCase, SIRValue}; +use num_bigint::BigUint; use std::collections::BTreeSet; use crate::{ @@ -54,8 +55,10 @@ use crate::{ type Unit = ExecutionUnit; type Builder = SIRBuilder; -/// The most events whose edges one slot can record. -const MAX_EVENTS: usize = 64; +/// The narrowest event mask: one 64-bit word, which every design with at +/// most 64 events uses. A design with more uses as many words as its events +/// need. +const MIN_EVENT_BITS: usize = 64; /// The most kernels the ready mask of a slot holds. const MAX_KERNELS: usize = 64; @@ -256,6 +259,9 @@ struct Plan { /// combinationally from them, with those clocks: their edges are judged /// when the source changes. gating: Vec<(usize, Vec)>, + /// The width of an event mask: one bit per event, at least + /// [`MIN_EVENT_BITS`] and a whole number of words. + event_bits: usize, } /// Deferred settles. The reference loop settles after every pass of the @@ -316,7 +322,6 @@ impl Plan { if !schema.comb_observers.is_empty() { return Err("the design observes combinational processes".into()); } - const _: () = assert!(MAX_EVENTS <= SCHEDULER_CLOCKS); if slots.wake.len() != schema.processes.len() { return Err("the scheduler slots do not match the kernels".into()); } @@ -339,8 +344,19 @@ impl Plan { let shared = program.shared_storage(); let storage = |address: AbsoluteAddr| shared.get(&address).copied().unwrap_or(address); let addresses = crate::edge_plans::event_addresses(program); - if addresses.len() > MAX_EVENTS { - return Err(format!("the design has more than {MAX_EVENTS} events")); + let event_bits = addresses.len().next_multiple_of(64).max(MIN_EVENT_BITS); + // The masks of the edges and levels of a slot live in these slots, + // which the frontend sized for the events it expected. + for (name, slot) in [ + ("levels", slots.levels), + ("unknown_levels", slots.unknown_levels), + ("exit_arg", slots.exit_arg), + ] { + if program.layout().widths.get(&slot).copied().unwrap_or(0) < event_bits { + return Err(format!( + "the design has more events than its scheduler's {name} slot holds" + )); + } } let mut events = Vec::with_capacity(addresses.len()); let mut event_storage = HashMap::default(); @@ -515,6 +531,11 @@ impl Plan { }) .map(|(index, _)| index) .collect(); + if clocks.len() > SCHEDULER_CLOCKS { + return Err(format!( + "the design has more than {SCHEDULER_CLOCKS} host clock events" + )); + } let mut kernels: Vec> = Vec::with_capacity(schema.processes.len()); let mut fallback = Vec::with_capacity(schema.processes.len()); @@ -865,6 +886,7 @@ impl Plan { lazy, derived: Vec::new(), gating: Vec::new(), + event_bits, }; let edged = plan.edged(); // The clocks derived from the events the slots change, transitively: @@ -1086,6 +1108,7 @@ impl Plan { .layout() .four_state .then_some(&program.layout().is_4states), + event_bits: self.event_bits, }; let waits: Vec<(usize, &Wait)> = self .kernels @@ -1267,8 +1290,8 @@ impl Plan { // any kernel runs; their edges start the slot's edges, which // collect in `exit_arg`. A clock whose edge applied waits for its // next edge until the slot ends. A run without clocks skips them. - let zero = g.constant(0, MAX_EVENTS); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, zero); + let zero = g.constant(0, self.event_bits); + g.store(slots.exit_arg, self.event_bits, zero); let finish_exit = g.exit_block(SchedulerExit::Finish); let internal_exit = g.exit_block(SchedulerExit::Internal); let pick = g.b.new_block(); @@ -1282,7 +1305,7 @@ impl Plan { g.b.switch_to_block(apply); let values = g.load(slots.clock_value, SCHEDULER_TIME_WIDTH); let mut fired = g.constant(0, SCHEDULER_CLOCKS); - let mut edges = g.constant(0, MAX_EVENTS); + let mut edges = g.constant(0, self.event_bits); let mut levels = g.load_levels(); for (bit, &index) in self.clocks.iter().enumerate() { let event = &self.events[index]; @@ -1333,13 +1356,13 @@ impl Plan { g.store(slots.dirty, SCHEDULER_FLAG_WIDTH, dirty); } let edge = g.edge(event, was, is); - let edge = g.bit(edge, index); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, edge); + let edge = g.event_bit(edge, index); + edges = g.binary(self.event_bits, edges, BinaryOp::Or, edge); let bit = g.bit(due, bit); fired = g.binary(SCHEDULER_CLOCKS, fired, BinaryOp::Or, bit); } g.store_levels(levels); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, edges); + g.store(slots.exit_arg, self.event_bits, edges); let all = g.constant(u64::MAX, SCHEDULER_CLOCKS); let unfired = g.binary(SCHEDULER_CLOCKS, fired, BinaryOp::Xor, all); let armed = g.binary(SCHEDULER_CLOCKS, armed, BinaryOp::And, unfired); @@ -1467,14 +1490,14 @@ impl Plan { // 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); + let mut edges = g.load(slots.exit_arg, self.event_bits); for (&event, &was) in kernel.writes.iter().zip(&before) { let is = g.level(&self.events[event]); let edge = g.edge(&self.events[event], was, is); - let bit = g.bit(edge, event); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + let bit = g.event_bit(edge, event); + edges = g.binary(self.event_bits, edges, BinaryOp::Or, bit); } - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, edges); + g.store(slots.exit_arg, self.event_bits, edges); } Some(wait) => { // A kernel runs at most once a slot (see `Plan::new`), so @@ -1569,8 +1592,8 @@ impl Plan { self.batch(&mut g, &tracked, slot_end, finish_exit); } else { 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 mask = g.load(slots.exit_arg, self.event_bits); + let zero = g.constant(0, self.event_bits); let quiet = g.binary(1, mask, BinaryOp::Eq, zero); let triggered = g.b.new_block(); let untriggered = g.b.new_block(); @@ -1610,9 +1633,9 @@ impl Plan { // 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 one = g.constant(1, self.event_bits); + let lower = g.binary(self.event_bits, mask, BinaryOp::Sub, one); + let others = g.binary(self.event_bits, 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(); @@ -1629,7 +1652,7 @@ impl Plan { let written = self.written(); for &index in written.iter().chain(&self.clocks) { let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); + let bit = g.single(index, self.event_bits); let this = g.binary(1, mask, BinaryOp::Eq, bit); let unit = g.b.new_block(); let next = g.b.new_block(); @@ -1687,14 +1710,14 @@ impl Plan { let evaluate = g.b.new_block(); g.settle_then(evaluate); g.b.switch_to_block(evaluate); - mask = g.load(slots.exit_arg, MAX_EVENTS); - zero = g.constant(0, MAX_EVENTS); + mask = g.load(slots.exit_arg, self.event_bits); + zero = g.constant(0, self.event_bits); } for phase in [Phase::Evaluate, Phase::Apply] { for &index in &edged { let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); - let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); + let bit = g.single(index, self.event_bits); + let selected = g.binary(self.event_bits, 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(); @@ -1843,7 +1866,7 @@ impl Plan { ) { let slots = g.slots; let wave = g.b.new_block(); - let mask = g.b.alloc_bit(MAX_EVENTS, false); + let mask = g.b.alloc_bit(self.event_bits, false); let fire = g.b.new_block_with(vec![mask]); let judge = g.b.new_block(); // A pass of the process phase settles before the domains; a @@ -1856,10 +1879,10 @@ impl Plan { } g.b.switch_to_block(judge); - let active = g.load(slots.exit_arg, MAX_EVENTS); + let active = g.load(slots.exit_arg, self.event_bits); let levels = g.load_levels(); let stable = self.stable_edges(g, tracked, levels); - let mut gated_edges = g.constant(0, MAX_EVENTS); + let mut gated_edges = g.constant(0, self.event_bits); let mut judged = levels; for (source, gated) in &self.gating { let source_bit = position(tracked, *source); @@ -1872,8 +1895,8 @@ impl Plan { let is = g.level(&self.events[clock]); let edge = g.edge(&self.events[clock], was, is); let edge = g.binary(1, edge, BinaryOp::And, changed); - let bit = g.bit(edge, clock); - gated_edges = g.binary(MAX_EVENTS, gated_edges, BinaryOp::Or, bit); + let bit = g.event_bit(edge, clock); + gated_edges = g.binary(self.event_bits, gated_edges, BinaryOp::Or, bit); // The judged level is the clock's baseline from now on. let level = g.b.alloc_bit(g.level_width(), false); g.b.emit(SIRInstruction::Mux(level, changed, is, was)); @@ -1881,12 +1904,12 @@ impl Plan { } } g.store_levels(judged); - let zero = g.constant(0, MAX_EVENTS); + let zero = g.constant(0, self.event_bits); let edged = g.binary(1, active, BinaryOp::Ne, zero); - let sources = g.binary(MAX_EVENTS, active, BinaryOp::Or, gated_edges); - let triggers = g.b.alloc_bit(MAX_EVENTS, false); + let sources = g.binary(self.event_bits, active, BinaryOp::Or, gated_edges); + let triggers = g.b.alloc_bit(self.event_bits, false); g.b.emit(SIRInstruction::Mux(triggers, edged, sources, stable)); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, triggers); + g.store(slots.exit_arg, self.event_bits, triggers); let quiet = g.binary(1, triggers, BinaryOp::Eq, zero); let first = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { @@ -1899,13 +1922,13 @@ impl Plan { // A wave after a commit: the domains not run yet whose clocks moved. g.b.switch_to_block(wave); - let fired = g.load(slots.exit_arg, MAX_EVENTS); + let fired = g.load(slots.exit_arg, self.event_bits); let levels = g.load_levels(); let stable = self.stable_edges(g, tracked, levels); - let all = g.constant(u64::MAX, MAX_EVENTS); - let unfired = g.binary(MAX_EVENTS, fired, BinaryOp::Xor, all); - let ready = g.binary(MAX_EVENTS, stable, BinaryOp::And, unfired); - let zero = g.constant(0, MAX_EVENTS); + let all = g.ones(self.event_bits); + let unfired = g.binary(self.event_bits, fired, BinaryOp::Xor, all); + let ready = g.binary(self.event_bits, stable, BinaryOp::And, unfired); + let zero = g.constant(0, self.event_bits); let quiet = g.binary(1, ready, BinaryOp::Eq, zero); let next = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { @@ -1914,17 +1937,17 @@ impl Plan { false_block: (next, Vec::new()), }); g.b.switch_to_block(next); - let fired = g.binary(MAX_EVENTS, fired, BinaryOp::Or, ready); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, fired); + let fired = g.binary(self.event_bits, fired, BinaryOp::Or, ready); + g.store(slots.exit_arg, self.event_bits, fired); g.b.seal_block(SIRTerminator::Jump(fire, vec![ready])); // A wave: one domain evaluates and commits at once, several // evaluate, then commit, in event order; then logic settles. g.b.switch_to_block(fire); - let zero = g.constant(0, MAX_EVENTS); - 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 zero = g.constant(0, self.event_bits); + let one = g.constant(1, self.event_bits); + let lower = g.binary(self.event_bits, mask, BinaryOp::Sub, one); + let others = g.binary(self.event_bits, mask, BinaryOp::And, lower); let single = g.binary(1, others, BinaryOp::Eq, zero); let alone = g.b.new_block(); let together = g.b.new_block(); @@ -1969,13 +1992,13 @@ impl Plan { /// The tracked events whose levels moved to their active edge against /// `levels`, their baselines, as bits by event index. fn stable_edges(&self, g: &mut Generator<'_>, tracked: &[usize], levels: Levels) -> RegisterId { - let mut edges = g.constant(0, MAX_EVENTS); + let mut edges = g.constant(0, self.event_bits); for (position, &index) in tracked.iter().enumerate() { let was = g.saved_level(levels, position); let is = g.level(&self.events[index]); let edge = g.edge(&self.events[index], was, is); - let bit = g.bit(edge, index); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + let bit = g.event_bit(edge, index); + edges = g.binary(self.event_bits, edges, BinaryOp::Or, bit); } edges } @@ -2023,16 +2046,38 @@ struct Generator<'a> { /// loads and stores move both planes, and edge levels are four-state /// (see [`Self::level_at`]). `None` in a two-state design. four_state: Option<&'a crate::HashMap>, + /// See [`Plan::event_bits`]. + event_bits: usize, } impl Generator<'_> { fn constant(&mut self, value: u64, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(value), width) + } + + fn wide_constant(&mut self, value: BigUint, width: usize) -> RegisterId { let register = self.b.alloc_bit(width, false); self.b .emit(SIRInstruction::Imm(register, SIRValue::new(value))); register } + /// The `width`-bit value with only bit `bit` set. + fn single(&mut self, bit: usize, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(1u8) << bit, width) + } + + /// The `width`-bit value with every bit but `bit` set. + fn all_but(&mut self, bit: usize, width: usize) -> RegisterId { + let ones = (BigUint::from(1u8) << width) - 1u8; + self.wide_constant(ones ^ (BigUint::from(1u8) << bit), width) + } + + /// The `width`-bit value with every bit set. + fn ones(&mut self, width: usize) -> RegisterId { + self.wide_constant((BigUint::from(1u8) << width) - 1u8, width) + } + fn binary( &mut self, width: usize, @@ -2100,7 +2145,7 @@ impl Generator<'_> { /// Whether bit `bit` of `mask` is set. fn mask_bit(&mut self, mask: RegisterId, bit: usize) -> RegisterId { let width = self.b.register(&mask).width(); - let selector = self.constant(1 << bit, width); + let selector = self.single(bit, width); let selected = self.binary(width, mask, BinaryOp::And, selector); let zero = self.constant(0, width); self.binary(1, selected, BinaryOp::Ne, zero) @@ -2270,22 +2315,22 @@ impl Generator<'_> { /// `levels` with `level` at bit `bit`, which was clear. fn with_level(&mut self, levels: Levels, level: RegisterId, bit: usize) -> Levels { let (value, unknown) = self.level_planes(level); - let set = self.bit(value, bit); - let values = self.binary(MAX_EVENTS, levels.values, BinaryOp::Or, set); + let set = self.event_bit(value, bit); + let values = self.binary(self.event_bits, levels.values, BinaryOp::Or, set); let unknown = levels.unknown.map(|levels| { - let set = self.bit(unknown.expect("a four-state level"), bit); - self.binary(MAX_EVENTS, levels, BinaryOp::Or, set) + let set = self.event_bit(unknown.expect("a four-state level"), bit); + self.binary(self.event_bits, levels, BinaryOp::Or, set) }); Levels { values, unknown } } /// `levels` with `level` in place of the one at bit `bit`. fn replace_level(&mut self, levels: Levels, level: RegisterId, bit: usize) -> Levels { - let keep = self.constant(!(1u64 << bit), MAX_EVENTS); - let values = self.binary(MAX_EVENTS, levels.values, BinaryOp::And, keep); + let keep = self.all_but(bit, self.event_bits); + let values = self.binary(self.event_bits, levels.values, BinaryOp::And, keep); let unknown = levels .unknown - .map(|unknown| self.binary(MAX_EVENTS, unknown, BinaryOp::And, keep)); + .map(|unknown| self.binary(self.event_bits, unknown, BinaryOp::And, keep)); self.with_level(Levels { values, unknown }, level, bit) } @@ -2305,32 +2350,32 @@ impl Generator<'_> { /// No saved levels: every event at 0. fn no_levels(&mut self) -> Levels { - let values = self.constant(0, MAX_EVENTS); + let values = self.constant(0, self.event_bits); let unknown = self .four_state .is_some() - .then(|| self.constant(0, MAX_EVENTS)); + .then(|| self.constant(0, self.event_bits)); Levels { values, unknown } } /// The levels of [`SchedulerSlots::levels`]. fn load_levels(&mut self) -> Levels { - let values = self.load(self.slots.levels, MAX_EVENTS); + let values = self.load(self.slots.levels, self.event_bits); let unknown = self .four_state .is_some() - .then(|| self.load(self.slots.unknown_levels, MAX_EVENTS)); + .then(|| self.load(self.slots.unknown_levels, self.event_bits)); Levels { values, unknown } } fn store_levels(&mut self, levels: Levels) { - self.store(self.slots.levels, SCHEDULER_TIME_WIDTH, levels.values); + self.store(self.slots.levels, self.event_bits, levels.values); if let Some(unknown) = levels.unknown { - self.store(self.slots.unknown_levels, SCHEDULER_TIME_WIDTH, unknown); + self.store(self.slots.unknown_levels, self.event_bits, unknown); } } - /// Run `body` when bit `index` of the 64-bit `mask` is set. + /// Run `body` when bit `index` of `mask` is set. fn if_bit(&mut self, mask: RegisterId, index: usize, body: impl FnOnce(&mut Self)) { let set = self.mask_bit(mask, index); let run = self.b.new_block(); @@ -2354,11 +2399,20 @@ impl Generator<'_> { block } - /// Bit `index` of a 64-bit mask, set when `condition` holds. + /// Bit `index` of a kernel or clock 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.bit_of(condition, index, MAX_KERNELS) + } + + /// Bit `index` of an event mask, set when `condition` holds. + fn event_bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { + self.bit_of(condition, index, self.event_bits) + } + + fn bit_of(&mut self, condition: RegisterId, index: usize, width: usize) -> RegisterId { + let set = self.single(index, width); + let unset = self.constant(0, width); + let bit = self.b.alloc_bit(width, false); self.b.emit(SIRInstruction::Mux(bit, condition, set, unset)); bit } @@ -3195,3 +3249,141 @@ mod tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod wide_event_tests { + use num_bigint::BigUint; + + const CLOCKS: usize = 70; + const PERIODS: usize = 7; + const END: u64 = 100; + + /// 70 clocks, each clocking a counter. One process per period toggles + /// its clocks, so the events exceed a word while the kernels stay few. + fn more_than_64_events() -> String { + let mut source = String::from("`timescale 1ns/1ns\nmodule Top;\n"); + for index in 0..CLOCKS { + source += &format!( + " logic c{index} = 0;\n logic [7:0] n{index} = 0;\n \ + always_ff @(posedge c{index}) n{index} <= n{index} + 8'd1;\n" + ); + } + for period in 1..=PERIODS { + let toggles: String = (0..CLOCKS) + .filter(|index| index % PERIODS + 1 == period) + .map(|index| format!(" c{index} = ~c{index};")) + .collect(); + source += &format!(" always #{period} begin{toggles} end\n"); + } + source + "endmodule\n" + } + + fn builder(source: &str) -> crate::SimulatorBuilder<'_, crate::Simulation> { + crate::Simulation::from_sv_sources(vec![(source, std::path::Path::new("events.sv"))], "Top") + } + + /// Run to `END` and check every counter against its clock's edges; + /// returns the slots the compiled scheduler ran. + fn counts_every_edge( + backend: &str, + mut sim: crate::Simulation, + ) -> u64 { + sim.run_until(END).unwrap(); + for index in 0..CLOCKS { + // A clock with half period `p` rises at p, 3p, 5p, ... + let period = (index % PERIODS + 1) as u64; + let rises = (END / period).div_ceil(2); + let counter = sim.signal(&format!("n{index}")); + assert_eq!( + sim.get(counter), + BigUint::from(rises), + "{backend}: n{index}" + ); + } + sim.scheduler_stats().compiled_slots + } + + /// A design with more events than one word of a mask holds runs in + /// the compiled scheduler, and every domain sees each of its edges. + #[test] + fn more_than_64_events_run_in_the_compiled_scheduler() { + let source = more_than_64_events(); + let mut sim = builder(&source).build().unwrap(); + let scheduler = sim + .simulator + .program + .runtime_schema + .scheduler + .as_ref() + .unwrap(); + assert!(scheduler.unit.is_some(), "{:?}", scheduler.fallback); + assert!(scheduler.events.len() > 64); + assert!(scheduler.fallback.iter().all(Option::is_none)); + sim.run_until(1).unwrap(); + assert!(sim.scheduler_stats().compiled_slots > 0); + counts_every_edge("native", sim); + // Every step of the compiled scheduler agrees with the reference + // loop. + let mut checked = builder(&source) + .scheduler_mode(crate::SchedulerMode::Differential) + .build() + .unwrap(); + checked.run_until(END).unwrap(); + assert!(checked.scheduler_stats().checked_steps > 0); + } + + /// 70 instances on one clock: the frontend's estimate counts the clock + /// once per instance and widens the scheduler's slots, while the design + /// has few events. A `$finish` ends a compiled slot early. + #[test] + fn wide_slots_with_few_events_finish_on_every_backend() { + let mut source = String::from( + "`timescale 1ns/1ns\nmodule Counter(input logic clk, output logic [7:0] n);\n \ + initial n = 0;\n always_ff @(posedge clk) n <= n + 8'd1;\nendmodule\n\ + module Top;\n logic clk = 0;\n always #1 clk = ~clk;\n initial #20 $finish;\n", + ); + for index in 0..CLOCKS { + source += + &format!(" logic [7:0] n{index};\n Counter u{index}(.clk(clk), .n(n{index}));\n"); + } + source += "endmodule\n"; + fn finishes(backend: &str, mut sim: crate::Simulation) { + sim.run_until(100).unwrap(); + assert!(sim.is_finished(), "{backend}"); + for index in 0..CLOCKS { + let counter = sim.signal(&format!("n{index}")); + assert_eq!(sim.get(counter), BigUint::from(10u8), "{backend}: n{index}"); + } + } + let wide = builder(&source).build().unwrap(); + let scheduler = wide + .simulator + .program + .runtime_schema + .scheduler + .as_ref() + .unwrap(); + assert!(scheduler.events.len() <= 64); + assert!(wide.simulator.layout().widths[&scheduler.slots.levels] > 64); + finishes("native", wide); + finishes("interpreter", builder(&source).build_interpreter().unwrap()); + finishes("tiered", builder(&source).build_tiered().unwrap()); + #[cfg(feature = "cranelift")] + finishes("cranelift", builder(&source).build_cranelift().unwrap()); + #[cfg(feature = "wasm-runtime")] + finishes("wasm", builder(&source).build_wasm().unwrap()); + } + + /// The runtime reads the wide scheduler slots on every backend. + #[test] + fn more_than_64_events_run_on_every_backend() { + let source = more_than_64_events(); + counts_every_edge("interpreter", builder(&source).build_interpreter().unwrap()); + counts_every_edge("tiered", builder(&source).build_tiered().unwrap()); + // Cranelift's wide comparisons once ran every domain (#2102). + #[cfg(feature = "cranelift")] + assert!(counts_every_edge("cranelift", builder(&source).build_cranelift().unwrap()) > 0); + #[cfg(feature = "wasm-runtime")] + counts_every_edge("wasm", builder(&source).build_wasm().unwrap()); + } +} diff --git a/crates/celox/src/scheduler/testbench.rs b/crates/celox/src/scheduler/testbench.rs index 09373bddd6f..9e6371f73ad 100644 --- a/crates/celox/src/scheduler/testbench.rs +++ b/crates/celox/src/scheduler/testbench.rs @@ -544,6 +544,13 @@ fn generate( .layout() .four_state .then_some(&program.layout().is_4states), + // The unit judges no event masks; they keep the slot's width. + event_bits: program + .layout() + .widths + .get(&slots.levels) + .copied() + .unwrap_or(SCHEDULER_TIME_WIDTH), }; let initialize = g.b.new_block(); let start = g.b.new_block(); diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 0df960e5ae5..4932b36ba1d 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -194,12 +194,12 @@ mod host { /// Boxed, so that taking it out for a tick moves one pointer. derived_scratch: Option>, coincident_edges: celox_runtime::CoincidentEdgeCache, - /// Per event ID, the generated units that run an edge of the event + /// Per event ID, the generated unit that runs edges of the event /// with its derived domains. Empty without them. derived_units: Arc<[Option]>, - /// The flag a derived-edge unit reads to settle combinational logic - /// before the domains evaluate. - derived_settle: Option, + /// The mode a derived-edge unit reads, and the flag it keeps the + /// state of combinational logic in (`celox_design::DerivedEdgeUnits`). + derived_slots: Option<(SignalRef, SignalRef)>, /// The design finished a timed simulation (`$finish`). Evaluation, /// host writes and waveform dumps no longer change anything. pub(crate) frozen: bool, @@ -1218,7 +1218,7 @@ mod host { celox_runtime::build_derived_tick_plans(&backend, &schedule); let event_edges = celox_runtime::build_event_edges(&backend, &schedule.events, &schedule.kinds); - let (derived_units, derived_settle) = + let (derived_units, derived_slots) = derived_edge_units(&backend, &program.runtime_schema, &derived_ticks); let comb_observer_reads = crate::comb_activation::ObserverReads::new( &backend, @@ -1309,7 +1309,7 @@ mod host { derived_scratch: Some(Box::new(derived_scratch)), coincident_edges: Default::default(), derived_units, - derived_settle, + derived_slots, frozen: false, host_watch: Default::default(), slot_observer: None, @@ -2754,28 +2754,86 @@ mod host { return Ok(()); }; let fires = info.fires(old, edge); - let comb_read = self.clock_move_needs_settle(event, info.comb_read)?; - if let Some(flag) = self.derived_settle { - self.backend.set(flag, u8::from(self.dirty || comb_read)); - } - let index = match edge { - celox_runtime::Edge::Rising => unit.rising, - celox_runtime::Edge::Falling => unit.falling, - }; - if let Err(error) = self.backend.run_process(index) { + // The unit leaves logic that reads the signal pending, or settles + // it, as the flag says. + if self.clock_move_needs_settle(event, info.comb_read)? { self.dirty = true; - return Err(self.decorate_runtime_error(error)); } + let mode = celox_design::DERIVED_EDGE_MOVED + | match edge { + celox_runtime::Edge::Rising => celox_design::DERIVED_EDGE_RISING, + celox_runtime::Edge::Falling => celox_design::DERIVED_EDGE_FALLING, + }; + let result = self.run_derived_unit(unit, mode, 1).1; + result.map_err(|error| self.decorate_runtime_error(error))?; // Without a gated clock and the event's own edge nothing ran, as - // in the plan walk. - let outcome = if unit.gated || fires { - celox_runtime::EdgeOutcome::Settled - } else if comb_read { - celox_runtime::EdgeOutcome::Moved + // in the plan walk; observers still see the signal's new level at + // their next evaluation. + if !(unit.gated || fires) && !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + // The edge is a time slot, as a tick is. + self.end_host_slot() + } + + /// Run `unit` in `mode` up to `count` times, with the state of + /// combinational logic kept in its flag, and return how many runs + /// completed: the unit returns early after a runtime event. + fn run_derived_unit( + &mut self, + unit: DerivedEdgeUnit, + mode: u8, + count: u64, + ) -> (u64, Result<(), RuntimeErrorCode>) { + let Some((mode_slot, flag)) = self.derived_slots else { + return (0, Err(RuntimeErrorCode::InternalError)); + }; + self.backend.set(mode_slot, mode); + self.backend.set(flag, u8::from(self.dirty)); + let (completed, result) = if count == 1 { + (1, self.backend.run_process(unit.unit)) } else { - celox_runtime::EdgeOutcome::Stored + self.backend.run_process_many(unit.unit, count) }; - self.note_edge(Ok(outcome)) + // What ran may not have settled when it failed. + self.dirty = result.is_err() || self.backend.get_as::(flag) != 0; + (completed, result) + } + + /// Up to `count` periods of `event`'s signal, a rise then a fall, in + /// its generated derived-edge unit, as [`Self::edge`] runs each edge; + /// `None` when an edge of the event does not run that unit. + pub(crate) fn derived_periods( + &mut self, + event: B::Event, + count: u64, + ) -> Option<(u64, Result<(), RuntimeErrorCode>)> { + let unit = self.derived_units.get(event.id()).copied().flatten()?; + // A host watch sees each write of the signal, which the unit + // makes itself. Each edge of a period is a time slot, whose end + // the host keeps (deferred assertions, sampled values), and + // observers see each level of the signal. + if self.frozen + || self.finish_sites + || self.host_slot_work + || !self.host_watch.is_empty() + || !self.program.runtime_schema.comb_observers.is_empty() + { + return None; + } + self.backend.request_derived_edge_units(); + if !self.backend.runs_derived_edge_units() { + return None; + } + if count == 0 { + return Some((0, Ok(()))); + } + let mode = celox_design::DERIVED_EDGE_RISING | celox_design::DERIVED_EDGE_FALLING; + let (completed, result) = self.run_derived_unit(unit, mode, count); + Some(( + completed, + result.map_err(|error| self.decorate_runtime_error(error)), + )) } /// Settle the outcome of [`celox_runtime::run_edge`] or @@ -3767,22 +3825,25 @@ mod host { } } - /// The generated units of one event's edges with its derived domains. + /// The generated unit of one event's edges with its derived domains. #[derive(Clone, Copy, Debug)] struct DerivedEdgeUnit { - rising: usize, - falling: usize, + /// Its index among the process units. + unit: usize, /// The event gates derived clocks, so an edge always runs domains. gated: bool, } - /// Per event ID, the generated derived-edge units of `schema`, and the flag - /// they read to settle first. + /// Per event ID, the generated derived-edge unit of `schema`, and the + /// mode and flag slots they use. fn derived_edge_units( backend: &B, schema: &celox_design::RuntimeSchema, plans: &celox_runtime::DerivedTickPlans, - ) -> (Arc<[Option]>, Option) { + ) -> ( + Arc<[Option]>, + Option<(SignalRef, SignalRef)>, + ) { if schema.derived_edges.is_empty() { return (Arc::from([]), None); } @@ -3795,16 +3856,17 @@ mod host { continue; }; units[event.id()] = Some(DerivedEdgeUnit { - rising: edges.rising, - falling: edges.falling, + unit: edges.unit, gated: plan.lever_signals().next().is_some(), }); } - let flag = schema - .scheduler - .as_ref() - .map(|scheduler| backend.resolve_signal(&scheduler.slots.dirty)); - (units.into(), flag) + let slots = schema.scheduler.as_ref().map(|scheduler| { + ( + backend.resolve_signal(&scheduler.slots.cont), + backend.resolve_signal(&scheduler.slots.dirty), + ) + }); + (units.into(), slots) } /// The host's write of an event signal's level, observed by a timed diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 41c0ac09ce5..781f7f80a32 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -4326,7 +4326,7 @@ mod host { let mut deferred = base; crate::derived_edge::attach_deferred(&mut deferred); crate::settle::instrument_processes_from(&mut deferred, first, false); - assert!(deferred.deferred_derived_edges.len() >= 4); + assert!(deferred.deferred_derived_edges.len() >= 2); assert_eq!(expanded.sir.processes.len(), deferred.sir.processes.len()); assert_eq!( expanded.runtime().runtime_schema.derived_edges, @@ -4405,6 +4405,16 @@ mod host { let clk = sim.event("clk"); if step % 5 == 0 { sim.edge(clk, crate::Edge::Falling).unwrap(); + } else if step % 5 == 3 { + // Periods in the unit's tick loop, which calls + // the outlined settle. + let mut left = 3; + while left > 0 { + let (ran, result) = + sim.derived_periods(clk, left).expect("a derived-edge unit"); + result.unwrap(); + left -= ran; + } } else { sim.tick(clk).unwrap(); } diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 044f4fe3223..72106ab7a06 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1875,14 +1875,18 @@ fn exec_one_detailed( } /// Run up to `count` periods of a testbench clock generator's signal, each a -/// rise followed by a fall, and return how many ran. A run that the event's -/// own domain alone reacts to fires that domain once per period with the -/// signal left low, which is all a period does then. +/// rise followed by a fall, and return how many ran. An event with derived +/// clock domains runs its periods in its generated edge unit. A run that the +/// event's own domain alone reacts to fires that domain once per period with +/// the signal left low, which is all a period does then. fn clock_periods( sim: &mut Simulator, event: B::Event, count: u64, ) -> (u64, Result<(), crate::RuntimeErrorCode>) { + if let Some(periods) = sim.derived_periods(event, count) { + return periods; + } if sim.period_runs_only_active_edge(event) { return sim.tick_deferred_comb_many(event, count); } diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index fc8608038ba..9a742e6fa18 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -96,11 +96,13 @@ unnecessary: - a non-cascaded single domain may use a combined evaluate-and-commit kernel; - cascaded evaluation continues only while newly triggered domains exist. - an edge of an event with derived clock domains (gated clocks, dividers) runs - as generated units, which judge the gated clocks, run the domains and the - cascade rounds, instead of a walk of the derived-tick plan in Rust. These units - compile the clock's domain once more; the `derived_edge_units` selector - (`-sir:derived_edge_units`, `SirPass::DerivedEdgeUnits`) turns them off to - trade tick speed for build time. + in a generated unit, which judges the gated clocks, runs the domains and the + cascade rounds, instead of a walk of the derived-tick plan in Rust; a + testbench's `clk.next(n)` runs its periods in that unit, which the native + backends loop over like the fused tick, returning after a period that + records a runtime event. The unit compiles the clock's domain once more; the + `derived_edge_units` selector (`-sir:derived_edge_units`, + `SirPass::DerivedEdgeUnits`) turns it off to trade tick speed for build time. - the combinational settle can be cut into partitions, contiguous ranges of its schedule, that run only when their dirty flag is set (`partitioned_settle`, off unless enabled). A partition that runs sets the