From 74104e41de817607ac0abe344a722038c5caae41 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 15:28:58 +0900 Subject: [PATCH] perf(runtime)!: run batches of derived clock periods in one generated unit Periods of an event with derived clock domains that a host runs, as a Veryl testbench's `clk.next(n)` does where the generated testbench scheduler does not (`SchedulerMode::Reference`), ran every period as two host edges, each a call of a generated edge unit (#1888), while a plain clock's periods run in one call of its fused tick loop. Each event now has one generated unit that runs the edges its mode selects, the rising, the falling or both, a period, in that order. A single edge of `Simulator::edge` passes its edge with the host having moved the signal and judged whether logic reading it must settle, as before; a batch of periods lets the unit move the signal, and the native backends compile the unit in the tick loop, which runs up to n periods and returns after one that records a runtime event (`SimBackend::run_process_many`; other backends run one period per call). The unit keeps whether combinational logic has pending changes in the scheduler's dirty flag across its edges and periods, as the host does across edges. Hosts with per-slot work (deferred assertions, sampled values), comb observers or a host watch run edges instead. A single native process run sets the tick loop's count to one, so a count left by a batch that returned early cannot make a unit run several times. One unit per event replaces the rising and falling ones; deferred expansion and the outlined combinational settle apply to it as to them. BREAKING CHANGE: celox_design::DerivedEdgeUnits has one `unit` instead of `rising` and `falling`; SimBackend has a new method, run_process_many, with a default. Native images use container format 57. Change-Id: I3f9f794d224c59eae9b5036a5ca57c342ccba653 --- crates/celox-backend-arm64/src/scalar.rs | 2 +- crates/celox-backend-common/src/lib.rs | 11 + .../src/backend/native/emit/pipeline.rs | 4 +- .../src/backend/native/regalloc.rs | 2 +- crates/celox-design/src/lib.rs | 23 +- crates/celox-runtime/src/backend.rs | 15 + crates/celox/src/backend/native/backend.rs | 74 +- crates/celox/src/backend/native/image_file.rs | 4 +- crates/celox/src/backend/tiered.rs | 32 + crates/celox/src/derived_edge.rs | 630 ++++++++++++++---- crates/celox/src/simulator.rs | 134 +++- crates/celox/src/simulator/builder.rs | 34 +- crates/celox/src/testbench.rs | 10 +- docs/internals/optimizations.md | 12 +- 14 files changed, 800 insertions(+), 187 deletions(-) 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-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/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 913f937e2cc..f177cbebd8e 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -171,6 +171,9 @@ pub struct SharedNativeCode { comb_unit_funcs: Vec, /// One function per process kernel. process_funcs: Vec, + /// Per process, whether it was compiled in the tick loop: the + /// derived-edge units when the loop is on. + process_loops: Vec, /// Lane-partitioned kernels and their task functions. lane_kernels: Option, /// Keep the combined executable image alive so every entry pointer remains @@ -332,6 +335,14 @@ impl SharedNativeCode { .copied() .map(|offset| native_function_at(&jit_image, offset)) .collect::, _>>()?; + let mut process_loops = vec![false; process_funcs.len()]; + if program_image.options.native_tick_loop { + for units in &program_image.runtime_schema.derived_edges { + if let Some(loops) = process_loops.get_mut(units.unit) { + *loops = true; + } + } + } let event_map = materialize_map(&program_image.event_map)?; let eval_only_event_map = materialize_map(&program_image.eval_only_event_map)?; let apply_event_map = materialize_map(&program_image.apply_event_map)?; @@ -375,6 +386,7 @@ impl SharedNativeCode { clock_alias_funcs, comb_unit_funcs, process_funcs, + process_loops, lane_kernels, _jit_image: jit_image, event_map, @@ -884,11 +896,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 +2802,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 +2831,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 +2885,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 +4119,33 @@ 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.process_loops[index] { + 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`]); any other unit runs once. + 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.process_loops[index] { + 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 d5e4a217b05..63538e34076 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -15,8 +15,8 @@ //! 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; @@ -721,6 +721,14 @@ 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.single(index, self.entry_bits); @@ -741,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); @@ -767,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 { @@ -799,11 +792,151 @@ 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(), + entry_bits: self.entry_bits(), }; - 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, @@ -812,15 +945,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); } @@ -828,9 +963,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, } @@ -852,7 +990,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) } @@ -860,10 +1004,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; }; @@ -885,27 +1029,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| { ( @@ -918,56 +1069,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; } @@ -982,7 +1122,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); @@ -1018,8 +1158,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 { @@ -1088,6 +1227,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; @@ -1300,9 +1452,251 @@ 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); } } 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..3fbec70bad1 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(); } @@ -4928,6 +4938,28 @@ endmodule"#; assert!(size(&first_tier) < size(&program)); } + /// Only the derived-edge units are compiled in the tick loop; a batch of + /// any other unit runs it once and says so. + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] + #[test] + fn units_without_the_tick_loop_report_one_run() { + use crate::SimBackend; + let source = "module Top (clk: input clock, d: input bit<8>, q: output bit<8>) { always_ff { q = d; } }"; + let (program, _, options, _, _) = crate::Simulation::builder(source, "Top") + .emit_triggers() + .four_state(false) + .into_laid_out_program(crate::MemoryLayoutMode::Packed, false) + .unwrap(); + assert!(options.x86_options.native_tick_loop); + let scheduler = program.runtime.runtime_schema.scheduler.clone().unwrap(); + let mut backend = crate::NativeBackend::new(&program, &options).unwrap(); + let limit = backend.resolve_signal(&scheduler.slots.limit); + backend.set(limit, 0u64); + let (runs, result) = backend.run_process_many(scheduler.unit.unwrap(), 3); + assert_eq!(runs, 1); + assert!(result.is_ok()); + } + #[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))] fn count_clean_clock_batch(clock_data: bool, alias: bool, dirty: bool) -> (u64, usize) { use crate::SimBackend; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 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