diff --git a/crates/celox-frontend-veryl/src/schedule.rs b/crates/celox-frontend-veryl/src/schedule.rs index 0fdb7d44517..1e731abac03 100644 --- a/crates/celox-frontend-veryl/src/schedule.rs +++ b/crates/celox-frontend-veryl/src/schedule.rs @@ -238,6 +238,8 @@ pub fn schedule_symbolic_rtl( }) } +/// The period of every `$tb::clock_gen` instance of `module`. +/// /// Veryl 0.22 keeps clock configuration on instance symbols, but only copies it /// into ClockNext IR. Recover it while the analyzer symbols are still available, /// using the specialization's overrides rather than a parameter's default. @@ -262,11 +264,14 @@ fn configured_clock_periods( let SymbolKind::Instance(instance) = &symbol.found.kind else { continue; }; + // A clock variable declared by an instance is a `$tb::clock_gen`; + // without a `period` it has the default period. let Some((_, target)) = instance .parameter_connects .iter() .find(|(name, _)| name.text.to_string() == "period") else { + periods.insert(symbol.found.token.text, 2); continue; }; let context = context.get_or_insert_with(|| { diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 3f90788ba56..3ed5e6c4d11 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -6,7 +6,7 @@ use celox_testbench::{ AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, ExprBytecode, ExprOpcode as TbOpcode, LoopBound as GenericLoopBound, SemanticArgument, SemanticComponentBinding, SemanticSignal, SemanticStatement, SourceLocation, StateLocation, - TestbenchOperator as Op, TestbenchProgram, TestbenchSelection, + TestbenchClock, TestbenchOperator as Op, TestbenchProgram, TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, }; use fxhash::{FxHashMap as HashMap, FxHashSet}; @@ -2568,6 +2568,17 @@ impl<'a> SemanticTestbenchBuilder<'a> { } } + /// The `$tb::clock_gen` instances of this source's module. + fn clock_generators(&self) -> impl Iterator> + '_ { + self.testbench_source + .clock_periods + .iter() + .filter_map(|(&name, &period)| { + let (event, _) = self.named_variable(name)?; + Some(TestbenchClock { event, period }) + }) + } + fn named_variable(&self, name: StrId) -> Option<(StateAddr, &VariableInfo)> { let instance = self.testbench_source.base_instance(self.lookup); let module = self.lookup.instance_module.get(&instance)?; @@ -3852,6 +3863,7 @@ pub fn compile_semantic_testbench( .sum(); let mut site_end = runtime_event_site_count.saturating_sub(total_sites); let mut processes = Vec::new(); + let mut clocks = Vec::new(); for source in sources { let initial_stmts = source.initial_statements.as_ref().unwrap(); validate_testbench_statements(initial_stmts, lookup, source, &mut FxHashSet::default())?; @@ -3859,12 +3871,16 @@ pub fn compile_semantic_testbench( let mut builder = SemanticTestbenchBuilder::new(lookup, source, site_end); builder.prepared_readmem = super::readmem::prepare_testbench_memories(lookup, source)?; builder.build_event_map(initial_stmts); + clocks.extend(builder.clock_generators()); processes.extend(builder.convert(initial_stmts)); } + clocks.sort_unstable_by_key(|clock: &TestbenchClock| clock.event); + clocks.dedup_by_key(|clock| clock.event); let builder = SemanticTestbenchBuilder::new(lookup, source, runtime_event_site_count); let component_bindings = builder.convert_component_bindings()?; Ok(Some( TestbenchProgram::from_processes(processes) + .with_clocks(clocks) .with_private_variables(private_variables) .with_random_seed_option(random_seed) .with_components(source.components.clone()) diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index ddc686da9fd..af000d0e460 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -918,36 +918,46 @@ enum HandleDerivedTicks { #[cfg(not(target_arch = "wasm32"))] impl HandleBackend { - /// Tick an event as `Simulator::tick` does: settle, run its domain, - /// settle, and run the derived clock domains the tick reaches. + /// Tick an event as `Simulator::tick` does: a pulse of its signal to + /// the active level, running every domain sensitive to its edges. fn tick( &mut self, event_id: usize, derived: &HandleDerivedTicks, + event_edges: &celox::EventEdges, scratch: &mut celox::DerivedTickScratch, ) -> std::result::Result<(), celox::RuntimeErrorCode> { fn tick_with( backend: &mut B, event_id: usize, plans: &celox::DerivedTickPlans, + event_edges: &celox::EventEdges, scratch: &mut celox::DerivedTickScratch, ) -> std::result::Result<(), celox::RuntimeErrorCode> { let event = backend.id_to_event_slice()[event_id]; - match plans.get(event_id) { - Some(Some(plan)) => plan.tick(&mut celox::BackendExecutor(backend), scratch, true), - _ => { - backend.eval_comb()?; - backend.eval_apply_ff_at(event)?; - backend.eval_comb() - } + let plan = plans.get(event_id).and_then(Option::as_ref); + match celox::run_tick( + &mut celox::BackendExecutor(backend), + plan, + event_edges[event_id], + scratch, + event, + true, + celox::set_level, + ) { + Ok(()) => Ok(()), + // A bare backend reports no `$finish` or `$stop`; what ran + // settles here. + Err(celox::Halt::Finish | celox::Halt::Stop) => backend.eval_comb(), + Err(celox::Halt::Error(error)) => Err(error), } } match (self, derived) { (Self::Default(backend), HandleDerivedTicks::Default(plans)) => { - tick_with(backend, event_id, plans, scratch) + tick_with(backend, event_id, plans, event_edges, scratch) } (Self::Tiered(backend), HandleDerivedTicks::Tiered(plans)) => { - tick_with(backend.as_mut(), event_id, plans, scratch) + tick_with(backend.as_mut(), event_id, plans, event_edges, scratch) } _ => unreachable!("derived tick plans belong to the handle's backend"), } @@ -1544,6 +1554,7 @@ impl NativeSimulatorHandle { b.tick( event_id as usize, &self.derived_ticks, + &self.event_edges, &mut self.derived_scratch, ) .map_err(|e| napi_runtime_error(&runtime_errors, e)) @@ -1620,6 +1631,7 @@ impl NativeSimulatorHandle { b.tick( event_id as usize, &self.derived_ticks, + &self.event_edges, &mut self.derived_scratch, ) .map_err(|e| napi_runtime_error(&runtime_errors, e))?; @@ -3958,9 +3970,13 @@ mod tests { #[test] fn native_handle_dumps_consume_activity_until_memory_is_exposed() { + // A tick writes `clk` as well as `q`. The wide inputs keep those two + // trace groups below half of the design, where a dump scans every + // signal. let source = "module Top ( clk: input clock, q: output logic<64>, a: input logic<512>, b: input logic<512>, c: input logic<512>, + d: input logic<512>, e: input logic<512>, ) { always_ff (clk) { q += 1; } }"; let dir = tempfile::tempdir().unwrap(); // Warm the uninstrumented cache first. A traced build must not reuse it. diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index 19b35c1d783..c619d1f0298 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -1,7 +1,7 @@ -//! Derived clock domains of an event-based tick. +//! Derived clock domains of an event-based edge. //! -//! A tick is one active edge of an event. Clocks derived from the event run -//! with the rules of the timed scheduler: +//! A plan runs the domains one edge of an event reaches. Clocks derived from +//! the event run with the rules of the timed scheduler: //! //! - A clock computed combinationally from the event's signal, such as //! `clk & enable`, changes at the same instant as the event. Its edge is @@ -17,9 +17,9 @@ //! commit raises while the clock is high is a further edge. Each domain //! fires at most once per phase. //! -//! A tick is the event's active edge only and does not change the event's -//! signal. Domains that react to the signal's opposite edge, such as one -//! clocked by `~clk` or by a falling `clk & en`, do not run on a tick. +//! A plan's [`DerivedTickPlan::tick`] is the event's active edge with its +//! signal left as it is; the edge APIs move the signal around it, and a +//! `Simulator::tick` takes the active edge and then the inactive one. //! //! What an event can reach is computed when the simulator is built //! ([`celox_design::EventTopology::derived_events`] and diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index 3d404e53dfe..1b971593394 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -42,6 +42,14 @@ impl Edge { Edge::Falling => 0, } } + + /// The other transition. + pub fn opposite(self) -> Edge { + match self { + Edge::Rising => Edge::Falling, + Edge::Falling => Edge::Rising, + } + } } /// What an edge needs to know about one event. @@ -346,3 +354,47 @@ where moved_only(comb_read) }) } + +/// One tick of `event`: a clock period of its signal, defined as the +/// SystemVerilog statements +/// +/// ```systemverilog +/// s <= A; #H; +/// s <= I; #L; +/// ``` +/// +/// where `A` and `I` are the event's active and inactive levels: the active +/// edge, then the inactive edge, each running every domain sensitive to it. +/// Combinational logic is settled afterwards. `dirty` says whether it has +/// pending changes; `write` moves the signal. +#[allow(clippy::too_many_arguments)] +pub fn run_tick( + executor: &mut X, + plan: Option<&DerivedTickPlan>, + info: EventEdge, + scratch: &mut DerivedTickScratch, + event: E, + dirty: bool, + mut write: impl FnMut(&mut X::Backend, SignalRef, u8), +) -> Result<(), Halt> +where + X: TickExecutor, + X::Backend: SimBackend, + E: EventHandle, +{ + let active = info.active_edge(); + let mut dirty = dirty; + for edge in [active, active.opposite()] { + dirty = match run_edge( + executor, plan, info, scratch, event, edge, dirty, &mut write, + )? { + EdgeOutcome::Unchanged | EdgeOutcome::Stored => dirty, + EdgeOutcome::Moved => true, + EdgeOutcome::Settled => false, + }; + } + if dirty { + executor.eval_comb()?; + } + Ok(()) +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index f0c637d01e0..ecffa23e4b5 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -25,7 +25,7 @@ pub use derived_tick::{ }; pub use edge::{ Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, build_event_edges, move_signal, - run_edge, run_edges, set_level, + run_edge, run_edges, run_tick, set_level, }; pub use error::{SimulatorErrorCode, comb_fatal_code, comb_fatal_site}; pub use event_buffer::RuntimeEventBuffer; diff --git a/crates/celox-runtime/src/testbench.rs b/crates/celox-runtime/src/testbench.rs index 92a8753bc0e..620a9f9049b 100644 --- a/crates/celox-runtime/src/testbench.rs +++ b/crates/celox-runtime/src/testbench.rs @@ -3,8 +3,9 @@ use celox_testbench::{ AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, CompiledExpr, ExecutableArgument, ExecutableAssertMessage, ExecutableClockCount, ExecutableLoopBound, ExecutableStatement, ExecutableTestbench, ExprBytecode, LoopBound as GenericLoopBound, - SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchProgram, - TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget, + SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchClock, + TestbenchProgram, TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, + TestbenchTarget, }; use crate::{SignalRef, backend::SimBackend}; @@ -389,6 +390,17 @@ pub fn bind_testbench_program( } } let random_seed = program.configured_random_seed(); + // A clock generator without an event drives no domain. + let clocks = program + .clocks() + .iter() + .filter_map(|clock| { + Some(TestbenchClock { + event: backend.resolve_event_opt(&clock.event)?, + period: clock.period, + }) + }) + .collect(); let components = program.components().to_vec(); let component_libraries = program.component_libraries().to_vec(); let component_file_base = program.component_file_base().map(ToOwned::to_owned); @@ -410,6 +422,7 @@ pub fn bind_testbench_program( .collect(); Some( ExecutableTestbench::from_processes(processes, random_seed) + .with_clocks(clocks) .with_private_signals(private_signals) .with_component_runtime( components, diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 24217b7e149..b5f5a840fa3 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -271,10 +271,21 @@ pub type SemanticStatement = TestbenchStatement< pub type SemanticComponentBinding = ComponentBinding, ExprBytecode>>; +/// A `$tb::clock_gen` instance: a clock that runs from time 0, rising at +/// multiples of `period` and falling `ceil(period / 2)` after each rise, +/// whether or not a process waits on it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TestbenchClock { + pub event: Event, + /// At least two. + pub period: u64, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct TestbenchProgram { statements: Vec>, process_lengths: Vec, + clocks: Vec>, private_variables: Vec, random_seed: Option, components: Vec, @@ -288,6 +299,7 @@ impl Default for TestbenchProgram { Self { statements: Vec::new(), process_lengths: Vec::new(), + clocks: Vec::new(), private_variables: Vec::new(), random_seed: None, components: Vec::new(), @@ -302,6 +314,7 @@ impl TestbenchProgram { pub fn new(statements: Vec>) -> Self { Self { process_lengths: vec![statements.len()], + clocks: Vec::new(), private_variables: Vec::new(), statements, random_seed: None, @@ -320,6 +333,16 @@ impl TestbenchProgram { program } + /// The clock generators of the testbench. + pub fn with_clocks(mut self, clocks: Vec>) -> Self { + self.clocks = clocks; + self + } + + pub fn clocks(&self) -> &[TestbenchClock] { + &self.clocks + } + /// Temporaries whose values belong to each independently suspended process. pub fn with_private_variables(mut self, variables: Vec) -> Self { self.private_variables = variables; @@ -578,6 +601,7 @@ pub type ExecutableComponentBinding = ComponentBinding { statements: Vec>, process_lengths: Vec, + clocks: Vec>, private_signals: Vec, random_seed: Option, components: Vec, @@ -597,6 +621,7 @@ impl ExecutableTestbench { ) -> Self { Self { process_lengths: vec![statements.len()], + clocks: Vec::new(), private_signals: Vec::new(), statements, random_seed, @@ -633,6 +658,16 @@ impl ExecutableTestbench { program } + /// The clock generators of the testbench. + pub fn with_clocks(mut self, clocks: Vec>) -> Self { + self.clocks = clocks; + self + } + + pub fn clocks(&self) -> &[TestbenchClock] { + &self.clocks + } + pub fn with_private_signals(mut self, signals: Vec) -> Self { self.private_signals = signals; self diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 9bafc8fe723..0f6de57f77c 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -46,16 +46,6 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } }) }); - - // Explicit edges of the same clock: one cycle is a domain-running - // rising edge and a falling edge that only moves the signal. - c.bench_function("simulator_cycle_x10000", |b| { - b.iter(|| { - for _ in 0..10000 { - sim.cycle(clk).unwrap(); - } - }) - }); } // Benchmark 1b/1c: Simulator::tick with a derived clock domain: a gated @@ -93,13 +83,6 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } }) }); - c.bench_function(&format!("simulator_cycle_{name}{suffix}_x10000"), |b| { - b.iter(|| { - for _ in 0..10000 { - sim.cycle(clk).unwrap(); - } - }) - }); } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index e16d6ae2eb7..5f4e4a92a38 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -119,7 +119,7 @@ mod host_api { pub use celox_runtime::{ BackendExecutor, DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, Edge, EdgeOutcome, EventEdge, EventEdges, Halt, SignalWrite, VcdSignalDesc, VcdStatistics, VcdWriter, - move_signal, run_edge, run_edges, set_level, + move_signal, run_edge, run_edges, run_tick, set_level, }; pub struct IOContext<'a, B: SimBackend = DefaultBackend> { diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 8eea263c394..30acc066cc3 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1122,10 +1122,10 @@ mod process_tests { /// enable from before the edge (here a register of `clk`'s own domain) /// and its domain reads the state from before `clk`'s domain commits; an /// edge raising `en` raises the gate after the commit, a further edge - /// that reads the committed state. `~clk` rises when `clk` falls, which - /// the timed steps drive and a tick, the active edge only, does not. Timed steps and - /// event-based ticks agree on every backend, in both state modes; the - /// four-state ticks judge the gate by settling the design. + /// that reads the committed state. `~clk` rises when `clk` falls. Timed + /// steps and event-based ticks, one clock period each, agree on every + /// backend, in both state modes; the four-state ticks judge the gate by + /// settling the design. #[test] fn gated_clocks_share_their_source_edge_on_every_backend() { const CODE: &str = "module Top (clk: input '_ clock, rst: input '_ reset_async_low, @@ -1209,22 +1209,12 @@ mod process_tests { .iter() .map(|&enable| { sim.modify(|io| io.set(en_in, enable)).unwrap(); - let clk_before = sim.get_four_state(sim.signal("clk")); sim.tick(clk).unwrap(); - let mut observed = observe(&mut sim); - assert_eq!( - sim.get_four_state(sim.signal("clk")), - clk_before, - "a tick leaves clk as it was" - ); - // A tick is not a falling edge of `clk`: `~clk` stays put. - observed[3] = 0; - observed + observe(&mut sim) }) .collect() } let want = expected(); - let want_ticked: Vec<_> = want.iter().map(|&[a, b, c, _]| [a, b, c, 0]).collect(); for four_state in [false, true] { let build = || { crate::Simulator::builder(CODE, "Top") @@ -1240,7 +1230,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_interpreter().unwrap()), - want_ticked, + want, "{}", context("interp tick") ); @@ -1252,7 +1242,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_cranelift().unwrap()), - want_ticked, + want, "{}", context("cranelift tick") ); @@ -1264,7 +1254,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_wasm().unwrap()), - want_ticked, + want, "{}", context("wasm tick") ); @@ -1276,7 +1266,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_tiered().unwrap()), - want_ticked, + want, "{}", context("tiered tick") ); @@ -1293,7 +1283,7 @@ mod process_tests { ); assert_eq!( ticked(build().build_native().unwrap()), - want_ticked, + want, "{}", context("native tick") ); diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index da45194afbd..524a7281730 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1699,28 +1699,71 @@ mod host { .map_err(|e| self.decorate_runtime_error(e)) } - /// Manually triggers a clock or event to process sequential logic. + /// One clock period of an event's signal: its active edge, then its + /// inactive edge. /// - /// A tick is one active edge of the event. Clock domains derived from - /// it run as in the timed [`crate::Simulation`]: a clock computed - /// combinationally from the event's signal, such as `clk & enable`, - /// is judged from the state before the edge and its domain evaluates - /// together with the event's own; domains clocked from state the - /// tick changes, such as a register bit, a divider or a gate whose - /// enable the commit raises, run after the commit, transitively. + /// A tick is defined as the SystemVerilog statements /// - /// Only the active edge is ticked, and the event's signal is left - /// unchanged. Domains that react to the opposite edge of the event's - /// signal, such as one clocked by `~clk` or by a falling `clk & en`, - /// do not run; drive the signal's levels with the timed - /// [`crate::Simulation`] for them. + /// ```systemverilog + /// s <= A; #H; + /// s <= I; #L; + /// ``` + /// + /// on the event's signal `s`, where `A` is its active level (1 for a + /// positive-edge clock or an active-high reset, 0 otherwise) and `I` + /// the inactive one, with host operations taking place between + /// periods. Every domain sensitive to either edge runs, including + /// domains of the opposite edge and clocks derived from the signal, + /// and the signal ends at the inactive level. A signal already at the + /// active level takes no active edge. See the execution semantics + /// guide for the host API as a whole. pub fn tick(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - let result = self.tick_unit(event); + if self.frozen { + return Ok(()); + } + let info = self.event_edges[event.id()]; + let active = info.active_edge(); + let inactive = active.opposite(); + let plain = !matches!(self.derived_ticks.get(event.id()), Some(Some(_))); + if !(plain && self.host_watch.is_empty() && !info.can_fire(inactive)) { + self.active_edge(event)?; + return self.inactive_edge(event); + } + // Everything is read before the domain runs: right after its + // kernel, loads of host tables can wait behind the kernel's + // stores (4 KiB aliasing), which made a period cost almost two + // domain runs. The inactive edge runs nothing and only stores. + let observers = !self.program.runtime_schema.comb_observers.is_empty(); + let moved = celox_runtime::move_signal( + &mut self.backend, + &info, + active, + celox_runtime::set_level, + ); + if let Some(old) = moved { + if info.comb_read { + self.dirty = true; + } + if info.fires(old, active) { + self.fire(event)?; + } + } + self.backend.set(info.signal, inactive.level()); + if info.comb_read || observers { + self.dirty = true; + } + Ok(()) + } + + /// Run the event's domain as its active edge does, with the signal + /// left as it is: the unit of the edge APIs. + fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + let result = self.fire_unit(event); self.heap_safepoint(); result.and(self.take_heap_fault()) } - fn tick_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + fn fire_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { if let Some(Some(_)) = self.derived_ticks.get(event.id()) { return self.tick_derived(event); } @@ -1787,7 +1830,7 @@ mod host { // store the level without reading it first. A load of // the signal right after the previous edge's kernel can // wait behind the kernel's stores (4 KiB aliasing), - // which made a cycle cost almost two ticks. + // which made a period cost almost two domain runs. self.backend.set(info.signal, edge.level()); if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { self.dirty = true; @@ -1795,7 +1838,7 @@ mod host { return Ok(()); } // No derived domains: move the signal, then run the event's - // domain exactly as `tick` does. + // domain. let write = watched_write(&mut self.host_watch); let Some(old) = celox_runtime::move_signal(&mut self.backend, &info, edge, write) else { @@ -1805,7 +1848,7 @@ mod host { self.dirty = true; } if info.fires(old, edge) { - return self.tick(event); + return self.fire(event); } if !self.program.runtime_schema.comb_observers.is_empty() { self.dirty = true; @@ -1875,49 +1918,6 @@ mod host { self.edge(event, edge) } - /// One clock cycle: [`Self::active_edge`], then - /// [`Self::inactive_edge`]. - pub fn cycle(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - if self.frozen { - return Ok(()); - } - let info = self.event_edges[event.id()]; - let active = info.active_edge(); - let inactive = match active { - celox_runtime::Edge::Rising => celox_runtime::Edge::Falling, - celox_runtime::Edge::Falling => celox_runtime::Edge::Rising, - }; - let plain = !matches!(self.derived_ticks.get(event.id()), Some(Some(_))); - if !(plain && self.host_watch.is_empty() && !info.can_fire(inactive)) { - self.active_edge(event)?; - return self.inactive_edge(event); - } - // Everything is read before the domain runs: right after its - // kernel, loads of host tables can wait behind the kernel's - // stores (4 KiB aliasing), which made a cycle cost almost two - // ticks. The inactive edge runs nothing and only stores. - let observers = !self.program.runtime_schema.comb_observers.is_empty(); - let moved = celox_runtime::move_signal( - &mut self.backend, - &info, - active, - celox_runtime::set_level, - ); - if let Some(old) = moved { - if info.comb_read { - self.dirty = true; - } - if info.fires(old, active) { - self.tick(event)?; - } - } - self.backend.set(info.signal, inactive.level()); - if info.comb_read || observers { - self.dirty = true; - } - Ok(()) - } - /// Move several event signals at one instant, as coincident edges: /// every domain sensitive to one of them evaluates against the state /// before the edges, then all of them commit, then the rounds of @@ -1955,8 +1955,8 @@ mod host { std::sync::Arc::clone(&self.derived_ticks) } - /// [`Self::tick`] of an event whose ticks can trigger derived domains, - /// kept out of line so that the plain tick stays small. + /// The domain run of an event whose edges can trigger derived + /// domains, kept out of line so that the plain run stays small. #[inline(never)] fn tick_derived(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { let plans = std::sync::Arc::clone(&self.derived_ticks); @@ -2014,23 +2014,80 @@ mod host { result } - /// Advance several events as one coincident edge. + /// Tick several events at once: [`Self::tick`] with the edges of all + /// their signals made together, /// - /// Every triggered domain samples the state settled before the edge, - /// then all of them update, then combinational logic settles once. - /// This is the behaviour of clocks that share an edge in hardware, - /// such as a divided clock and its source, which sequential - /// [`Self::tick`] calls cannot express: each of them would settle - /// the design between the domains. Events of the same domain are - /// applied once. A single event behaves like [`Self::tick`]. + /// ```systemverilog + /// s1 <= A1; ... sk <= Ak; #H; + /// s1 <= I1; ... sk <= Ik; #L; + /// ``` /// - /// Derived domains of the ticked events run as in [`Self::tick`]: - /// gated clocks with the ticked domains, state-derived ones after - /// all of them commit. + /// so every domain triggered by the coincident active edges samples + /// the state settled before them, then all of them update. This is + /// the behaviour of clocks that share an edge in hardware, such as a + /// divided clock and its source, which sequential [`Self::tick`] + /// calls cannot express: each of them would settle the design + /// between the domains. Events of the same domain are applied once. + /// A single event behaves like [`Self::tick`]. pub fn tick_events(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { - let result = self.tick_events_unit(events); + if self.frozen { + return Ok(()); + } + if let [event] = events { + return self.tick(*event); + } + let only_active_edges = self.host_watch.is_empty() + && events.iter().all(|event| { + let info = self.event_edges[event.id()]; + !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + && !info.can_fire(info.active_edge().opposite()) + }); + if !only_active_edges { + let moves = |edge: fn(celox_runtime::EventEdge) -> celox_runtime::Edge| { + events + .iter() + .map(|&event| (event, edge(self.event_edges[event.id()]))) + .collect::>() + }; + let active = moves(|info| info.active_edge()); + let inactive = moves(|info| info.active_edge().opposite()); + self.edges(&active)?; + return self.edges(&inactive); + } + // The inactive edges run nothing and only store. + let mut fired = Vec::with_capacity(events.len()); + for &event in events { + let info = self.event_edges[event.id()]; + let active = info.active_edge(); + if let Some(old) = celox_runtime::move_signal( + &mut self.backend, + &info, + active, + celox_runtime::set_level, + ) { + if info.comb_read { + self.dirty = true; + } + if info.fires(old, active) { + fired.push(event); + } + } + } + let result = self.tick_events_unit(&fired); self.heap_safepoint(); - result.and(self.take_heap_fault()) + result.and(self.take_heap_fault())?; + for &event in events { + let info = self.event_edges[event.id()]; + self.backend + .set(info.signal, info.active_edge().opposite().level()); + if info.comb_read { + self.dirty = true; + } + } + if !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + Ok(()) } fn tick_events_unit(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { @@ -2073,11 +2130,11 @@ mod host { match domains.as_slice() { [] => { for event in unsplit { - self.tick(event)?; + self.fire(event)?; } return Ok(()); } - [(event, _, _)] => return self.tick(*event), + [(event, _, _)] => return self.fire(*event), _ => {} } let timing_enabled = self.diagnostics.tick_timing_every.is_some(); @@ -2122,7 +2179,7 @@ mod host { || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) { // Derived domains need the settled state to see their edges. - return self.tick(event); + return self.fire(event); } if self.dirty { self.eval_comb_apply_ff_at_checked(event)?; @@ -2133,6 +2190,16 @@ mod host { Ok(()) } + /// Whether a period of `event`'s signal, a rise and a fall, runs only + /// the event's own domain, once: no domain reacts to the other edge + /// and no clock derives from the signal. + pub(crate) fn period_runs_only_own_domain(&self, event: B::Event) -> bool { + let info = self.event_edges[event.id()]; + !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + && !info.can_fire(info.active_edge().opposite()) + && self.host_watch.is_empty() + } + /// Advance a run of identical deferred-comb ticks. Native code may keep /// the loop inside the generated function, but must return after publishing /// a runtime event so host-side observation remains tick-accurate. @@ -2786,7 +2853,7 @@ mod host { sim.frozen = true; sim.posedge(clk).unwrap(); sim.edges(&[(clk, celox_runtime::Edge::Rising)]).unwrap(); - sim.cycle(clk).unwrap(); + sim.tick(clk).unwrap(); let clk_signal = sim.signal("clk"); assert_eq!(sim.get(clk_signal), BigUint::from(0u8)); assert_eq!(sim.get(count), BigUint::from(1u8)); @@ -2844,7 +2911,7 @@ mod host { // logic stale only when it reads `clk`. sim.negedge(clk).unwrap(); assert_eq!(sim.dirty, comb_read, "{seen}"); - sim.cycle(clk).unwrap(); + sim.tick(clk).unwrap(); assert_eq!(sim.dirty, comb_read, "{seen}"); let seen_signal = sim.signal("seen"); let expected = if comb_read { 0u8 } else { 1 }; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 037d4ad61ac..f1239aa8884 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -1685,29 +1685,42 @@ struct ProcessClock { // Clock generators start low even when the design uses four-state storage. // Otherwise X's nonzero payload can make the first scheduled 1 look like a // steady high to the edge detector, losing the first clock/reset cycle. +// Returns the clock events, declared generators first. fn initialize_process_clocks( sim: &mut Simulator, - statements: &[TestbenchStatement], -) { - for statement in statements { - match statement { - GenericTestbenchStatement::ClockNext { clock_event, .. } - | GenericTestbenchStatement::ResetAssert { clock_event, .. } => { - let signal = sim.backend.resolve_signal(&clock_event.addr()); - sim_set_u64(sim, signal, 0); - } - GenericTestbenchStatement::If { - then_block, - else_block, - .. - } => { - initialize_process_clocks(sim, then_block); - initialize_process_clocks(sim, else_block); - } - GenericTestbenchStatement::For { body, .. } => initialize_process_clocks(sim, body), - _ => {} + testbench: &CompiledTestbench, +) -> Vec { + fn referenced(statements: &[TestbenchStatement], clocks: &mut Vec) { + for statement in statements { + match statement { + GenericTestbenchStatement::ClockNext { clock_event, .. } + | GenericTestbenchStatement::ResetAssert { clock_event, .. } => { + clocks.push(*clock_event); + } + GenericTestbenchStatement::If { + then_block, + else_block, + .. + } => { + referenced::(then_block, clocks); + referenced::(else_block, clocks); + } + GenericTestbenchStatement::For { body, .. } => referenced::(body, clocks), + _ => {} + } + } + } + let mut clocks: Vec<_> = testbench.clocks().iter().map(|clock| clock.event).collect(); + referenced::(testbench.statements(), &mut clocks); + let mut unique: Vec = Vec::with_capacity(clocks.len()); + for event in clocks { + if unique.iter().all(|known| known.id() != event.id()) { + let signal = sim.backend.resolve_signal(&event.addr()); + sim_set_u64(sim, signal, 0); + unique.push(event); } } + unique } fn exec_testbench( @@ -1719,7 +1732,10 @@ fn exec_testbench( .processes() .filter(|block| !block.is_empty()) .collect(); - if blocks.len() <= 1 { + let clocks = initialize_process_clocks(sim, testbench); + // One process on one clock spends time only in that clock's periods, so + // stepping them in place is the whole schedule. + if blocks.is_empty() || (blocks.len() == 1 && clocks.len() <= 1) { return exec_detailed(sim, testbench.statements(), ctx); } // Suspended processes keep their temporaries outside state memory, so @@ -1736,7 +1752,6 @@ fn exec_processes( ctx: &mut DetailedExecContext, blocks: &[&[TestbenchStatement]], ) -> ExecResult { - initialize_process_clocks(sim, testbench.statements()); // The compiler's function slots are shared by inline call sites. Keep // only these temporaries private; design variables remain shared between // initial processes and all RTL. Capture masks as well as payloads. @@ -1755,7 +1770,18 @@ fn exec_processes( .zip(&waits) .map(|(block, wait)| Some(exec_process(&sim, &ctx, wait, &reset_edges, block))) .collect(); - let mut clocks: Vec> = Vec::new(); + // Every clock generator runs from time 0, whether or not a process + // waits on it. + let mut clocks: Vec> = testbench + .clocks() + .iter() + .map(|clock| ProcessClock { + event: clock.event, + period: clock.period.max(2), + next_edge: 0, + falling_edge: None, + }) + .collect(); // Capture the baseline before runnable processes drive reset. Reset // assertions are signal writes AND events at this timestamp, even if // their clock's next edge is still in the future. Rebasing after the @@ -1868,16 +1894,9 @@ fn exec_processes( } } } - let active = |event: B::Event| { - waits.iter().any(|wait| { - wait.borrow() - .as_ref() - .is_some_and(|wait| wait.remaining != 0 && wait.clock.id() == event.id()) - }) - }; let fired: Vec<_> = clocks .iter() - .filter(|clock| !draining && !stopped && clock.next_edge == now && active(clock.event)) + .filter(|clock| !draining && !stopped && clock.next_edge == now) .map(|clock| clock.event) .collect(); { @@ -1938,7 +1957,7 @@ fn exec_processes( } let next_edge = clocks .iter() - .filter(|clock| !ctx.borrow().at_tick_limit() && active(clock.event)) + .filter(|_| !ctx.borrow().at_tick_limit()) .map(|clock| clock.next_edge) .min(); let next_falling = clocks.iter().filter_map(|clock| clock.falling_edge).min(); @@ -2078,7 +2097,7 @@ fn exec_one_detailed( let (completed, result) = if sim.components.has_scheduled_components() { (1, tick_component_clock(sim, *clock_event, ctx.current_time)) } else { - let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); + let (completed, result) = clock_periods(sim, *clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; if completed == 0 || completed > batch { @@ -2146,7 +2165,7 @@ fn exec_one_detailed( ), ) } else { - let (completed, result) = sim.tick_deferred_comb_many(*clock_event, batch); + let (completed, result) = clock_periods(sim, *clock_event, batch); (completed, result.map_err(|error| error.to_string())) }; if completed == 0 || completed > batch { @@ -2397,6 +2416,24 @@ 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. +fn clock_periods( + sim: &mut Simulator, + event: B::Event, + count: u64, +) -> (u64, Result<(), crate::RuntimeErrorCode>) { + if sim.period_runs_only_own_domain(event) { + return sim.tick_deferred_comb_many(event, count); + } + let result = sim + .edge(event, celox_runtime::Edge::Rising) + .and_then(|()| sim.edge(event, celox_runtime::Edge::Falling)); + (1, result) +} + fn tick_component_reset( sim: &mut Simulator, reset_event: Option, diff --git a/crates/celox/tests/both_clock_edges.rs b/crates/celox/tests/both_clock_edges.rs index f662b5924fd..727892aea59 100644 --- a/crates/celox/tests/both_clock_edges.rs +++ b/crates/celox/tests/both_clock_edges.rs @@ -7,9 +7,8 @@ //! 9.4.2 defines, evaluating against the state before the edge (4.4.2, //! 10.4.2), and that the copy is invisible. //! -//! Event-based `Simulator` tests with explicit edges belong here too, once the -//! `Simulator` can drive a falling edge: a `tick` is the rising edge only and -//! does not run falling-edge domains. +//! The event-based `Simulator`, whose `tick` is a clock period, is covered by +//! `tick_semantics.rs`. #![cfg(feature = "systemverilog")] diff --git a/crates/celox/tests/clock_gen_semantics.rs b/crates/celox/tests/clock_gen_semantics.rs new file mode 100644 index 00000000000..4a8b0312081 --- /dev/null +++ b/crates/celox/tests/clock_gen_semantics.rs @@ -0,0 +1,149 @@ +//! `$tb::clock_gen` and `clk.next(n)` behave as the SystemVerilog the +//! execution semantics guide defines them by: every clock generator runs from +//! time 0, rising through a nonblocking assignment at multiples of its period +//! and falling half a period later, and `clk.next(n)` resumes a period after +//! the `n`-th rising edge it waits for. +//! +//! The expected values come from running that SystemVerilog under Icarus +//! Verilog 13.0 and Verilator 5.052, which agree: +//! +//! ```systemverilog +//! bit clk = 0, clk2 = 0; +//! initial forever begin clk <= 1; #2 clk <= 0; #2; end +//! initial forever begin clk2 <= 1; #3 clk2 <= 0; #3; end +//! task automatic clk_next(int unsigned k); +//! if (k != 0) begin repeat (k) @(posedge clk); #4; end +//! endtask +//! ``` + +use celox::Simulator; +use celox::TestResult; +use celox::testbench::{compile_initial_testbench, run_compiled_testbench_to_finish}; + +const COUNTERS: &str = r#" +module Cnt ( + i_clk: input clock , + i_x : input logic<8> , + o_p : output logic<8> , + o_q : output logic<8> , +) { + var p: logic<8>; + var q: logic<8>; + always_ff (i_clk) { + p = p + 8'd1; + q = i_x + 8'd1; + } + assign o_p = p; + assign o_q = q; +} + +module NegCnt ( + i_clk: input clock_negedge, + o_n : output logic<8> , +) { + var n: logic<8>; + always_ff (i_clk) { + n = n + 8'd1; + } + assign o_n = n; +} +"#; + +fn run(top: &str) -> TestResult { + let code = format!("{COUNTERS}\n{top}"); + let mut sim = Simulator::builder(&code, "Top").build().unwrap(); + let tb = compile_initial_testbench(&sim).unwrap(); + run_compiled_testbench_to_finish(&mut sim, &tb) +} + +/// One process on one clock: the falling edge runs negative-edge domains, +/// and a write between two waits reaches the next rising edge. +#[test] +fn one_process_takes_both_edges_of_each_period() { + let result = run(r#" +#[test(Top)] +module Top { + inst clk: $tb::clock_gen #(period: 4); + var x: logic<8>; + var p: logic<8>; + var q: logic<8>; + var n: logic<8>; + inst a: Cnt (i_clk: clk, i_x: x, o_p: p, o_q: q); + inst an: NegCnt (i_clk: clk, o_n: n); + initial { + x = 8'd5; + clk.next(1); + $assert(p == 8'd1 && q == 8'd6 && n == 8'd1 && clk == 1'b0, "t=4: p=%d q=%d n=%d clk=%b", p, q, n, clk); + x = 8'd7; + clk.next(2); + $assert(p == 8'd3 && q == 8'd8 && n == 8'd3 && clk == 1'b0, "t=12: p=%d q=%d n=%d clk=%b", p, q, n, clk); + clk.next(0); + $assert(p == 8'd3 && n == 8'd3, "next(0) waits for nothing: p=%d n=%d", p, n); + $finish(); + } +} +"#); + assert_eq!(result, TestResult::Pass); +} + +/// The same with a second process: concurrency changes nothing. +#[test] +fn a_second_process_changes_nothing() { + let result = run(r#" +#[test(Top)] +module Top { + inst clk: $tb::clock_gen #(period: 4); + var x: logic<8>; + var p: logic<8>; + var q: logic<8>; + var n: logic<8>; + inst a: Cnt (i_clk: clk, i_x: x, o_p: p, o_q: q); + inst an: NegCnt (i_clk: clk, o_n: n); + initial { + x = 8'd5; + clk.next(1); + $assert(p == 8'd1 && q == 8'd6 && n == 8'd1 && clk == 1'b0, "t=4: p=%d q=%d n=%d clk=%b", p, q, n, clk); + x = 8'd7; + clk.next(2); + $assert(p == 8'd3 && q == 8'd8 && n == 8'd3 && clk == 1'b0, "t=12: p=%d q=%d n=%d clk=%b", p, q, n, clk); + $finish(); + } + initial { + clk.next(1); + } +} +"#); + assert_eq!(result, TestResult::Pass); +} + +/// A clock no process waits on still runs: `clk2` rises at 0, 6 and 12, +/// and the process resuming at 12 runs before that edge. +#[test] +fn clocks_run_whether_or_not_a_process_waits() { + let result = run(r#" +#[test(Top)] +module Top { + inst clk: $tb::clock_gen #(period: 4); + inst clk2: $tb::clock_gen #(period: 6); + var x: logic<8>; + var y: logic<8>; + var p: logic<8>; + var q: logic<8>; + var p2: logic<8>; + var q2: logic<8>; + inst a: Cnt (i_clk: clk, i_x: x, o_p: p, o_q: q); + inst b: Cnt (i_clk: clk2, i_x: y, o_p: p2, o_q: q2); + initial { + x = 8'd5; + y = 8'd9; + clk.next(1); + $assert(p == 8'd1 && q == 8'd6 && p2 == 8'd1 && q2 == 8'd10, "t=4: p=%d q=%d p2=%d q2=%d", p, q, p2, q2); + x = 8'd7; + clk.next(2); + $assert(p == 8'd3 && q == 8'd8 && p2 == 8'd2 && q2 == 8'd10, "t=12: p=%d q=%d p2=%d q2=%d", p, q, p2, q2); + $finish(); + } +} +"#); + assert_eq!(result, TestResult::Pass); +} diff --git a/crates/celox/tests/component_method.rs b/crates/celox/tests/component_method.rs index f42f5b940ec..fb120b0d587 100644 --- a/crates/celox/tests/component_method.rs +++ b/crates/celox/tests/component_method.rs @@ -3016,7 +3016,9 @@ fn child_initial_resolves_its_component_method_instance() { var d: logic<8>; var q: logic<8>; inst component: $comp::celox_clocked #(STEP: 0) (clk, d, q); - initial { component.drive(8'h5a); $assert(q == 8'h5a); } + // `clk` runs whether or not a process waits on it, and its edges + // load `d` into `q`. + initial { component.drive(8'h5a); $assert(q == 8'h5a); d = 8'h5a; } } #[test(t)] module t { inst clk: $tb::clock_gen; diff --git a/crates/celox/tests/derived_register_clock.rs b/crates/celox/tests/derived_register_clock.rs index b7cf39ab08a..ff3d100695d 100644 --- a/crates/celox/tests/derived_register_clock.rs +++ b/crates/celox/tests/derived_register_clock.rs @@ -389,8 +389,8 @@ module Top ( } /// `~clk` rises when `clk` falls: the timed simulation, which drives both -/// levels of `clk`, runs its domain once per cycle, while a tick is the -/// active edge of `clk` only and does not run it. +/// levels of `clk`, runs its domain once per cycle, and so does a tick, one +/// period of `clk`. #[test] fn an_inverted_clock_runs_on_the_falling_edge_only() { let code = r#" @@ -425,9 +425,9 @@ module Top ( let mut sim = Simulator::builder(code, "Top").build().unwrap(); let (clk, rst, cnt2) = (sim.event("clk"), sim.signal("rst"), sim.signal("cnt2")); sim.modify(|io| io.set(rst, 1u8)).unwrap(); - for _ in 0..4 { + for cycle in 0..4u64 { sim.tick(clk).unwrap(); - assert_eq!(sim.get(cnt2), 0u8.into(), "a tick is not a falling edge"); + assert_eq!(sim.get(cnt2), (cycle + 1).into(), "tick {cycle}"); } } diff --git a/crates/celox/tests/edge_api.rs b/crates/celox/tests/edge_api.rs index 20ee1eca805..995f0d22ac0 100644 --- a/crates/celox/tests/edge_api.rs +++ b/crates/celox/tests/edge_api.rs @@ -1,12 +1,11 @@ //! Explicit edges: `posedge`, `negedge`, `active_edge`, `inactive_edge`, -//! `cycle` and coincident `edges`, on every backend. +//! `tick` and coincident `edges`, on every backend. use celox::{ClockType, Edge, SimBackend, Simulation, Simulator, SimulatorBuilder}; /// A simulator under test, independent of its backend. trait Probe { fn edge(&mut self, event: &str, edge: Edge); - fn cycle(&mut self, event: &str); fn active_edge(&mut self, event: &str); fn inactive_edge(&mut self, event: &str); fn tick(&mut self, event: &str); @@ -20,10 +19,6 @@ impl Probe for Simulator { let event = self.event(event); Simulator::edge(self, event, edge).unwrap(); } - fn cycle(&mut self, event: &str) { - let event = self.event(event); - Simulator::cycle(self, event).unwrap(); - } fn active_edge(&mut self, event: &str) { let event = self.event(event); Simulator::active_edge(self, event).unwrap(); @@ -134,12 +129,12 @@ fn edges_run_the_domains_of_their_direction() { sim.edge("clk", Edge::Falling); assert_eq!(counters(sim), [1, 1, 1], "{backend}: negedge"); sim.set("en", 0); - sim.cycle("clk"); + sim.tick("clk"); assert_eq!(counters(sim), [2, 2, 1], "{backend}: closed gate"); - // A tick is the active edge only and leaves the clock low. + sim.set("en", 1); sim.tick("clk"); - assert_eq!(counters(sim), [3, 2, 1], "{backend}: tick"); - assert_eq!(sim.get("clk"), 0, "{backend}: tick leaves clk"); + assert_eq!(counters(sim), [3, 3, 2], "{backend}: tick"); + assert_eq!(sim.get("clk"), 0, "{backend}: tick leaves clk low"); } } @@ -169,20 +164,20 @@ module Top (clk: input clock, rst: input reset_async_low, q: output logic<8>) { assert_eq!(sim.get("q"), 1, "{backend}: {clock_type:?} inactive"); sim.edge("clk", active); assert_eq!(sim.get("q"), 2, "{backend}: {clock_type:?} explicit"); - sim.cycle("clk"); + // A clock at its active level takes no active edge. + sim.tick("clk"); assert_eq!(sim.get("q"), 2, "{backend}: {clock_type:?} stays active"); - sim.edge("clk", inactive); - sim.cycle("clk"); - assert_eq!(sim.get("q"), 3, "{backend}: {clock_type:?} cycle"); + sim.tick("clk"); + assert_eq!(sim.get("q"), 3, "{backend}: {clock_type:?} tick"); } } } -/// `cycle` runs a clock cycle exactly as the timed simulation's two steps +/// `tick` runs a clock period exactly as the timed simulation's two steps /// do: gated clocks with pre-edge sampling, a gate the commit raises, `~clk` /// and a register divider of a divider. #[test] -fn a_cycle_matches_the_timed_simulation() { +fn a_tick_matches_the_timed_simulation() { const CODE: &str = r#" module Top ( clk: input '_ clock, @@ -238,7 +233,7 @@ module Top ( .iter() .map(|&enable| { sim.set("en_in", enable); - sim.cycle("clk"); + sim.tick("clk"); sim.get("observed") }) .collect(); diff --git a/crates/celox/tests/four_state_explicit_edges.rs b/crates/celox/tests/four_state_explicit_edges.rs index 7bb97553b85..3e873745114 100644 --- a/crates/celox/tests/four_state_explicit_edges.rs +++ b/crates/celox/tests/four_state_explicit_edges.rs @@ -70,8 +70,8 @@ fn check(mut sim: Simulator, backend: &str) { set(&mut sim, "clkn", X); edge(&mut sim, "clkn", Edge::Rising); assert_eq!(counts(&mut sim), [1, 1, 0, 0], "{backend}: inactive from x"); - sim.cycle(sim.event("clkp")).unwrap(); - assert_eq!(counts(&mut sim), [2, 1, 0, 0], "{backend}: cycle after x"); + sim.tick(sim.event("clkp")).unwrap(); + assert_eq!(counts(&mut sim), [2, 1, 0, 0], "{backend}: tick after x"); // A gated clock: `x & 1` -> `1 & 1` rises; `x & x` -> `1 & x` stays x. set(&mut sim, "en", ONE); @@ -103,7 +103,7 @@ fn check(mut sim: Simulator, backend: &str) { edge(&mut sim, "clkd", Edge::Rising); assert_eq!(counts(&mut sim)[3], 2, "{backend}: register x -> 1"); set(&mut sim, "d", ZERO); - sim.cycle(sim.event("clkd")).unwrap(); + sim.tick(sim.event("clkd")).unwrap(); assert_eq!(counts(&mut sim)[3], 2, "{backend}: register 1 -> 0"); // Coincident edges from x judge the gated clock from x too. diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 1db1f427c34..9684113cba3 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -2048,16 +2048,21 @@ fn uses_the_first_always_ff_event_as_a_negedge_clock() { .build_cranelift() .unwrap(); let clk = sim.event("clk"); + let clk_signal = sim.signal("clk"); let rst = sim.signal("rst"); let d = sim.signal("d"); let q = sim.signal("q"); + // A tick from the active level takes no active edge, so the clock idles + // high. sim.modify(|io| { + io.set(clk_signal, 1u8); io.set(rst, 0u8); io.set(d, 1u8); }) .unwrap(); sim.tick(clk).unwrap(); assert_eq!(sim.get(q), 1u8.into()); + assert_eq!(sim.get(clk_signal), 1u8.into()); } #[test] diff --git a/crates/celox/tests/native_testbench.rs b/crates/celox/tests/native_testbench.rs index 7e09ff73e3d..a5df2eb8ac1 100644 --- a/crates/celox/tests/native_testbench.rs +++ b/crates/celox/tests/native_testbench.rs @@ -2290,15 +2290,17 @@ fn test_dual_clock() { clk_a, rst_a, clk_b, rst_b, cnt_a, cnt_b, ); + // Both clocks run throughout. `cnt_a` counts the 3 periods of + // `rst_b`'s assertion, then both count every period. initial { rst_a.assert(); rst_b.assert(); clk_a.next (10); - $assert (cnt_a == 32'd10); - $assert (cnt_b == 32'd0); + $assert (cnt_a == 32'd13); + $assert (cnt_b == 32'd10); clk_b.next (5); - $assert (cnt_a == 32'd10); - $assert (cnt_b == 32'd5); + $assert (cnt_a == 32'd18); + $assert (cnt_b == 32'd15); $finish (); } } diff --git a/crates/celox/tests/tick_semantics.rs b/crates/celox/tests/tick_semantics.rs new file mode 100644 index 00000000000..78ebf514fac --- /dev/null +++ b/crates/celox/tests/tick_semantics.rs @@ -0,0 +1,220 @@ +//! The event-based `Simulator` API behaves as the SystemVerilog the execution +//! semantics guide defines it by. Each host operation is rewritten into those +//! statements of an `initial` process, which the timed `Simulation` runs, and +//! both must observe the same values after every operation: +//! +//! - `set(x, v)` is `x = v;`, +//! - `edge(e, lvl)` is `s <= lvl;`, +//! - `tick(e)` is `s <= A; #H; s <= I; #L;`, +//! - `tick_events(e1..ek)` makes the moves of all their signals together, +//! +//! where `s` is the event's signal, `A` its active level and `I` its inactive +//! one. + +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +use celox::{Edge, Simulation, Simulator}; + +const DUT: &str = r#" +`timescale 1ns/1ns +module Dut ( + input logic clk, + input logic clk2, + input logic en, + input logic rst_n, + output logic [7:0] p, + output logic [7:0] n, + output logic [7:0] g, + output logic [7:0] ng, + output logic [7:0] r, + output logic [7:0] c2, + output logic [7:0] s, + output logic lvl +); + logic gclk; + assign gclk = clk & en; + always_ff @(posedge clk) p <= p + 8'd1; + always_ff @(negedge clk) n <= n + 8'd1; + always_ff @(posedge gclk) g <= g + 8'd1; + always_ff @(negedge gclk) ng <= ng + 8'd1; + always_ff @(posedge clk or negedge rst_n) + if (!rst_n) r <= 8'd0; + else r <= r + 8'd1; + always_ff @(posedge clk2) c2 <= c2 + 8'd1; + always_ff @(posedge clk) s <= c2; + assign lvl = clk; +endmodule +"#; + +const OUTPUTS: [&str; 8] = ["p", "n", "g", "ng", "r", "c2", "s", "lvl"]; + +/// Event signals with their active levels. +const EVENTS: [(&str, u8); 3] = [("clk", 1), ("clk2", 1), ("rst_n", 0)]; + +#[derive(Clone, Copy, Debug)] +enum Op { + Set(&'static str, u8), + Edge(&'static str, u8), + Tick(&'static [&'static str]), +} + +fn active(name: &str) -> u8 { + EVENTS.iter().find(|(event, _)| *event == name).unwrap().1 +} + +/// The statements `op` stands for, with the half periods of a tick at 1. +fn statements(op: Op) -> String { + match op { + Op::Set(name, value) => format!("{name} = {value};"), + Op::Edge(name, level) => format!("{name} <= {level};"), + Op::Tick(names) => { + let moves = |level: fn(u8) -> u8| { + names + .iter() + .map(|name| format!("{name} <= {}; ", level(active(name)))) + .collect::() + }; + format!("{}#1; {}#1;", moves(|a| a), moves(|a| 1 - a)) + } + } +} + +/// The values of `OUTPUTS` after each operation, from the timed simulation of +/// the operations' statements. Operation `k` starts at time `4k + 1`. +fn reference(ops: &[Op]) -> Vec> { + let mut body = String::new(); + for (k, &op) in ops.iter().enumerate() { + body += &format!(" #({} - $time) {}\n", 4 * k + 1, statements(op)); + } + let top = format!( + r#" +`timescale 1ns/1ns +module Top; + logic clk, clk2, en, rst_n; + wire [7:0] p, n, g, ng, r, c2, s; + wire lvl; + Dut u ( + .clk, .clk2, .en, .rst_n, .p, .n, .g, .ng, .r, .c2, .s, .lvl + ); + initial begin +{body} end +endmodule +"# + ); + let mut sim = Simulation::from_sv_sources( + vec![(DUT, Path::new("dut.sv")), (&top, Path::new("top.sv"))], + "Top", + ) + .four_state(false) + .build() + .unwrap(); + (0..ops.len()) + .map(|k| { + sim.run_until(4 * k as u64 + 4).unwrap(); + OUTPUTS + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + }) + .collect() + }) + .collect() +} + +fn hosted(ops: &[Op]) -> Vec> { + let mut sim = Simulator::from_sv_sources(vec![(DUT, Path::new("dut.sv"))], "Dut") + .four_state(false) + .build() + .unwrap(); + ops.iter() + .map(|&op| { + match op { + Op::Set(name, value) => { + let signal = sim.signal(name); + sim.set(signal, value); + } + Op::Edge(name, level) => { + let event = sim.event(name); + let edge = if level == 1 { + Edge::Rising + } else { + Edge::Falling + }; + sim.edge(event, edge).unwrap(); + } + Op::Tick([name]) => { + let event = sim.event(name); + sim.tick(event).unwrap(); + } + Op::Tick(names) => { + let events: Vec<_> = names.iter().map(|name| sim.event(name)).collect(); + sim.tick_events(&events).unwrap(); + } + } + OUTPUTS + .iter() + .map(|name| { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + }) + .collect() + }) + .collect() +} + +fn check(ops: &[Op]) { + let expected = reference(ops); + let actual = hosted(ops); + for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate() { + assert_eq!( + actual, expected, + "after {:?} (operation {k}), outputs {OUTPUTS:?}", + ops[k] + ); + } +} + +/// A tick runs the domains of both edges of its signal and of a clock gated +/// from it, and leaves the signal at its inactive level. +#[test] +fn a_tick_is_a_clock_period() { + check(&[ + Op::Edge("rst_n", 1), + Op::Set("en", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + Op::Set("en", 0), + Op::Tick(&["clk"]), + ]); +} + +/// A signal already at its active level takes no active edge: a tick of an +/// active-low reset that starts low only releases it. +#[test] +fn a_tick_from_the_active_level_takes_only_the_inactive_edge() { + check(&[ + Op::Tick(&["rst_n"]), + Op::Tick(&["clk"]), + Op::Edge("rst_n", 0), + Op::Tick(&["clk"]), + Op::Edge("rst_n", 1), + Op::Edge("clk", 1), + Op::Tick(&["clk"]), + Op::Tick(&["clk"]), + ]); +} + +/// Coincident ticks sample each other's values from before the edge. +#[test] +fn ticks_of_several_events_are_coincident() { + check(&[ + Op::Edge("rst_n", 1), + Op::Tick(&["clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk"]), + ]); +} diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 26e70805d77..b58ca97ce20 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -66,6 +66,10 @@ export default defineConfig({ text: "テストの書き方", link: "/ja/guide/writing-tests", }, + { + text: "実行の意味論", + link: "/ja/guide/execution-semantics", + }, { text: "celox CLIとcocotb", link: "/ja/guide/cocotb", @@ -185,6 +189,7 @@ export default defineConfig({ text: "Testbenches", items: [ { text: "Writing Tests", link: "/guide/writing-tests" }, + { text: "Execution Semantics", link: "/guide/execution-semantics" }, { text: "Celox CLI and cocotb", link: "/guide/cocotb" }, { text: "4-State Simulation", link: "/guide/four-state" }, { text: "Parameter Overrides", link: "/guide/parameter-overrides" }, diff --git a/docs/guide/execution-semantics.md b/docs/guide/execution-semantics.md new file mode 100644 index 00000000000..55f39d2e2c7 --- /dev/null +++ b/docs/guide/execution-semantics.md @@ -0,0 +1,194 @@ +# Execution Semantics + +The clock-driving operations of Celox are defined by IEEE 1800 scheduling. +Each host call of the event-based `Simulator` is one time slot in which a +fixed SystemVerilog statement executes, and each clock or reset component of +a Veryl native testbench is a fixed piece of SystemVerilog. An IEEE 1800 +simulator running that code observes the same values as Celox does. + +In the code below, `s` is the signal of an event (a clock or reset port), +`A` its active level and `I` its inactive one. `A` is 1 for a positive-edge +clock and an active-high reset, and 0 for a negative-edge clock and an +active-low reset. For Veryl's abstract `clock` and `reset` types it follows +the build's clock and reset types. + +Reset polarity and synchronicity belong to the design, not to these rules. +Veryl emits `always_ff (clk, rst) { if_reset ... }` as +`always_ff @(posedge clk, negedge rst_n) if (!rst_n) ...` for an +asynchronous active-low reset and as `always_ff @(posedge clk) if (!rst_n) +...` for a synchronous one, and the IEEE 1800 scheduler produces each +behavior from the signal moves alone. + +## The `Simulator` API + +A `Simulator` has no simulation time, but it schedules as an IEEE 1800 +simulation does. Each host call is one time slot (IEEE 1800-2023 4.4): the +call's statement executes in that slot, the slot runs until every region is +empty, and the next call starts a later slot. A read (`get`, `sim.dut.x`) +between two calls sees the completed slot. + +| Call | Statement of the slot | +|---|---| +| `set(x, v)`, `sim.dut.x = v` | `x = v;` | +| `edge(e, Rising)`, `posedge(e)` | `s <= 1;` | +| `edge(e, Falling)`, `negedge(e)` | `s <= 0;` | +| `active_edge(e)` / `inactive_edge(e)` | `s <= A;` / `s <= I;` | +| `edges([(e1, l1), …, (ek, lk)])` | `s1 <= l1; … sk <= lk;` | +| `tick(e)` | `s <= A;` then, in the next slot, `s <= I;` | +| `tick(e, n)` | `tick(e)` `n` times | +| `tick_events([e1, …, ek])` | `s1 <= A1; … sk <= Ak;` then, in the next slot, `s1 <= I1; … sk <= Ik;` | + +The host is not a process of the design, so no delay appears above: a slot +is the unit in which the design responds to one statement. To run the same +sequence on a SystemVerilog simulator, write the statements into one +`initial` process and follow each with a delay of one time precision unit. +A `Simulator` rejects designs with delays, so the length of that unit is not +observable. + +Some consequences: + +- A tick is one clock period. Every domain sensitive to either edge runs: + the event's own domain on the active edge, domains of the opposite edge + (`@(negedge clk)`, a register clocked by `~clk`), and clocks computed from + the signal, such as `clk & en`, on whichever edge they see. The signal ends + at its inactive level. +- A signal already at its active level takes no active edge, as + `s <= A` changes nothing. A tick of a two-state active-low reset that starts + at 0 only releases it; assert a reset with `negedge(rst)` or + `active_edge(rst)`. +- Domains triggered by one slot sample the state from before it and update + together, as nonblocking assignments do. Coincident edges of several clocks + (`edges`, `tick_events`) sample each other's values from before their shared + slot. A clock the slot itself moves, such as a register-driven divider, + rises inside the slot after that commit, and its domain runs in the same + slot. +- In a four-state design an unknown level counts as either level: `x` to 1 is + a rising edge and `x` to 0 a falling one (IEEE 1800-2023 Table 9-2). + +`set` and writes through `sim.dut` must not move an event signal or a clock +computed from one: Celox runs domains only for the edge calls above. Drive +those signals with `edge`, `tick` and their variants. + +### Resets from the host + +A reset held for `n` clock periods is the active edge of the reset, `n` ticks +of the clock, and the inactive edge of the reset: + +```typescript +sim.activeEdge(rst); +sim.tick(clk, n); +sim.inactiveEdge(rst); +``` + +An asynchronous reset domain runs in the first slot, before any clock edge; a +synchronous one resets at the first tick. The sequence is the same slots as +the testbench's `rst.assert(n)` below. + +### Several clocks + +A tick is one period of its event, so it cannot express a phase relation +between two clock inputs. For clocks with a frequency ratio, such as `clk` +and a `clk_half` of twice its period, drive each instant with `edges`: + +```typescript +sim.edges([[clk, "posedge"], [clkHalf, "posedge"]]); +sim.edges([[clk, "negedge"]]); +sim.edges([[clk, "posedge"], [clkHalf, "negedge"]]); +sim.edges([[clk, "negedge"]]); +``` + +or use the timed [`Simulation`](./writing-tests.md#time-based-simulation) +with one `addClock` per input. Alternating `tick_events([clk, clk_half])` with +`tick(clk)` gives the same results only to domains that see the rising edges: +it makes `clk_half` fall with `clk`'s falling edge instead of its next rising +one. + +## Veryl native testbenches + +The initial blocks of a Veryl testbench are SystemVerilog `initial` +processes, and `$finish()` is `$finish`. Unlike the host, these processes +have simulation time: the components below are SystemVerilog code, and their +delays are the testbench's time. + +### `$tb::clock_gen` + +`inst clk: $tb::clock_gen #(period: P);` is a clock generator that runs from +time 0, whether or not a process waits on it. `P` defaults to 2 and is at +least 2; with `H = ceil(P / 2)` and `L = floor(P / 2)`: + +```systemverilog +bit clk = 1'b0; +initial forever begin + clk <= 1'b1; #H; + clk <= 1'b0; #L; +end +``` + +### `clk.next(n)` + +```systemverilog +task automatic clk_next(int unsigned n); + if (n != 0) begin + repeat (n) @(posedge clk); + #P; + end +endtask +``` + +`clk.next()` is `clk.next(1)`. + +- The process resumes a period after the `n`-th rising edge it waits for, + just before the next one. It then observes the state after both edges of + that period: the clock is low, and negative-edge domains have run. +- The clock rises through a nonblocking assignment, after the processes that + resume at the same time have run. What a process writes between two + `next` calls is therefore sampled by the rising edge that follows, without + a race. +- Several initial processes, and several clocks of different periods, need no + further rule: they are concurrent SystemVerilog processes. A clock nobody + waits on keeps running and clocking its domains. + +### `$tb::reset_gen` + +`inst rst: $tb::reset_gen #(cycles: C) (clk);` is a reset net of the +testbench's `reset` type, deasserted from time 0: + +```systemverilog +bit rst = I; +``` + +### `rst.assert(n)` + +With `P` the period of the generator's clock: + +```systemverilog +task automatic rst_assert(int unsigned n); + if (n == 0) n = 1; + rst = A; + repeat (n) @(posedge clk); + #P; + rst = I; +endtask +``` + +`rst.assert()` is `rst.assert(C)`, and `C` defaults to 3. + +- The assertion is a blocking write at the point the process has reached, + like any other testbench write. An asynchronous reset domain runs at that + instant, with no clock edge, whether or not its clock is running. A + synchronous reset domain resets at the next rising edge. +- The level is held for `n` periods of `clk`: the `n` rising edges starting + with the next one, or with the one at the same instant, since the clock + rises after the process has written, and the period after the last of them. + Both kinds of reset see `n` reset edges and are released before edge + `n + 1`. +- The process resumes, and the reset releases, at the phase at which `next` + resumes: a period after the last awaited edge, just before the next one. + Writes that follow are sampled by that edge without a race, and + `rst.assert(n); clk.next(m);` is `n + m` periods. +- `rst.assert(0)` is `rst.assert(1)`. A reset released in the slot that + asserted it is a glitch in SystemVerilog and is not given a meaning. + +This page defines `$tb::clock_gen`, `clk.next`, `$tb::reset_gen` and +`rst.assert`. The other testbench components, `$tb::file` and `$tb::random`, +take no part in scheduling. diff --git a/docs/guide/writing-tests.md b/docs/guide/writing-tests.md index ea59203ad16..d82a68852e3 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -52,11 +52,12 @@ module Reg ( - `Simulator.create(Module)` creates a simulator instance from a Veryl module definition. - Signal values are read and written via `sim.dut.`. -- `sim.tick()` advances the simulation by one clock cycle. - Clock domains derived from that clock run in the same tick when their clock - rises: a gated `clk & en` together with `clk`'s own domain, a - register-driven divider after it. A tick is the clock's active edge only: - domains clocked by its opposite edge, such as `~clk`, do not run. +- `sim.tick()` advances the simulation by one clock period: the clock's + active edge, then its inactive edge. Every domain sensitive to either edge + runs, including clocks derived from it, such as a gated `clk & en`, a + register-driven divider or `~clk`. See + [Execution Semantics](./execution-semantics.md) for the SystemVerilog a + tick is equivalent to. - `sim.dispose()` frees the native resources. ::: tip Combinational logic @@ -65,9 +66,8 @@ For purely combinational modules (`always_comb` only), `tick()` is not required. ### Clock edges -`tick()` stands for a clock's active edge and leaves the clock signal alone. -When a design also reacts to the other edge, for example a register on `~clk` -or on a falling `clk & en`, drive the edges themselves: +`tick()` drives a whole clock period. To stop between the two edges, or to +drive a reset, move the signals edge by edge: ```typescript const clk = sim.event("clk"); @@ -76,7 +76,6 @@ sim.posedge(clk); // clk = 1: domains sensitive to its rising edge run sim.negedge(clk); // clk = 0: domains sensitive to its falling edge run sim.activeEdge(clk); // the clock's own edge: rising for a posedge clock sim.inactiveEdge(clk); // the opposite edge -sim.cycle(clk); // activeEdge(), then inactiveEdge() // Several clocks at one instant: every domain samples the state before them. sim.edges([ @@ -95,8 +94,8 @@ Veryl's abstract `clock` type, `activeEdge()` follows the build's clock type (`clockType: "negedge"` makes it the falling edge). Reset ports work the same way: `negedge(rst)` asserts an active-low asynchronous reset. -`cycle()` gives the same results as two timed steps of the clock, a rising -and a falling one. +`tick()` is `activeEdge()` followed by `inactiveEdge()`, and gives the same +results as two timed steps of the clock, a rising and a falling one. ## Time-Based Simulation diff --git a/docs/internals/cascade-limitations.md b/docs/internals/cascade-limitations.md index af32fc922d7..1c1913960f9 100644 --- a/docs/internals/cascade-limitations.md +++ b/docs/internals/cascade-limitations.md @@ -99,26 +99,22 @@ optimization and does not change the ordering model above. ## Event-based ticks -`Simulator::tick` applies the same rules to one active edge of an event. -Gated clocks of the event are judged from the state before the edge and -evaluate with the ticked domain; after the commit, the rounds above run the -domains whose clocks are computed from state and the gated clocks the commit -moves. `Simulator::tick_events` does -the same for coincident events, and the native testbench's `clock.next()` and -the N-API `tick` use the same mechanism. - -A tick is the event's active edge only, without simulation time, and does not -change the event's signal. Domains that react to the signal's opposite edge, -such as one clocked by `~clk` or by a falling edge of `clk & en`, do not run on -a tick; the timed `Simulation`, which drives both levels of a clock, runs them. - -`Simulator::posedge`, `negedge`, `active_edge`, `inactive_edge`, `cycle` and the -coincident `edges` move the signal instead and apply the same rules to the -transition they make, as a timed step does: the event's own domain runs on its -active edge, gated clocks of either polarity are judged at the transition, and -the signal stays at its new level. `cycle` is equivalent to the two timed -steps of one clock period. The N-API handles and the WASM bridge of the -TypeScript package use the same plans. +`Simulator::posedge`, `negedge`, `active_edge`, `inactive_edge` and the +coincident `edges` apply the same rules to the transition of an event signal +they make, as a timed step does: the event's own domain runs on its active +edge, gated clocks of either polarity are judged at the transition, and the +signal stays at its new level. Gated clocks are judged from the state before +the edge and evaluate with the event's own domain; after the commit, the +rounds above run the domains whose clocks are computed from state and the +gated clocks the commit moves. + +`Simulator::tick` is one clock period, the active edge followed by the +inactive edge, and is equivalent to the two timed steps of that period; +`Simulator::tick_events` does the same for coincident events, and the +native testbench's `clock.next()` takes the same two edges. The +[execution semantics](../guide/execution-semantics.md) define them by +SystemVerilog. The N-API handles and the WASM bridge of the TypeScript +package use the same plans. Which derived domains an event can reach is computed once when the design is built, together with a small program for each gate where its combinational diff --git a/docs/ja/guide/execution-semantics.md b/docs/ja/guide/execution-semantics.md new file mode 100644 index 00000000000..9959e4717c9 --- /dev/null +++ b/docs/ja/guide/execution-semantics.md @@ -0,0 +1,197 @@ +# 実行の意味論 + +Celox のクロックを駆動する操作は IEEE 1800 のスケジューリングで定義されて +います。イベントベースの `Simulator` では、ホストの各呼び出しが 1 つの +タイムスロットで、その中で決まった SystemVerilog の文が実行されます。Veryl +ネイティブテストベンチのクロック・リセットコンポーネントは、決まった +SystemVerilog のコードです。そのコードを IEEE 1800 準拠のシミュレータで +実行すると、Celox と同じ値が観測されます。 + +以下のコードで、`s` はイベント(クロックまたはリセットのポート)の信号、 +`A` はそのアクティブレベル、`I` は非アクティブレベルです。`A` は +立ち上がりエッジのクロックと active-high リセットで 1、立ち下がりエッジの +クロックと active-low リセットで 0 です。Veryl の抽象 `clock` 型と `reset` +型では、ビルドのクロック種別とリセット種別に従います。 + +リセットの極性と同期・非同期は設計側の性質で、ここの規則には現れません。 +Veryl は `always_ff (clk, rst) { if_reset ... }` を、非同期 active-low +リセットなら `always_ff @(posedge clk, negedge rst_n) if (!rst_n) ...` +に、同期リセットなら `always_ff @(posedge clk) if (!rst_n) ...` に出力し、 +IEEE 1800 のスケジューラが信号の動きだけからそれぞれの振る舞いを作ります。 + +## `Simulator` API + +`Simulator` にはシミュレーション時刻がありませんが、スケジューリングは +IEEE 1800 のシミュレーションと同じです。ホストの各呼び出しは 1 つの +タイムスロット(IEEE 1800-2023 4.4)です。呼び出しの文はそのスロットで +実行され、スロットはすべての領域が空になるまで進み、次の呼び出しは後の +スロットで始まります。呼び出しと呼び出しの間の読み出し(`get`、 +`sim.dut.x`)は、完了したスロットの状態を見ます。 + +| 呼び出し | スロットの文 | +|---|---| +| `set(x, v)`、`sim.dut.x = v` | `x = v;` | +| `edge(e, Rising)`、`posedge(e)` | `s <= 1;` | +| `edge(e, Falling)`、`negedge(e)` | `s <= 0;` | +| `active_edge(e)` / `inactive_edge(e)` | `s <= A;` / `s <= I;` | +| `edges([(e1, l1), …, (ek, lk)])` | `s1 <= l1; … sk <= lk;` | +| `tick(e)` | `s <= A;` そして次のスロットで `s <= I;` | +| `tick(e, n)` | `tick(e)` を `n` 回 | +| `tick_events([e1, …, ek])` | `s1 <= A1; … sk <= Ak;` そして次のスロットで `s1 <= I1; … sk <= Ik;` | + +ホストは設計内のプロセスではないので、上の表に遅延は現れません。スロットは +設計が 1 つの文に応答する単位です。同じ列を SystemVerilog シミュレータで +実行するには、文を 1 つの `initial` プロセスに並べ、各文の後に時間精度 1 +単位の遅延を置きます。`Simulator` は遅延を含む設計を受け付けないので、 +その単位の長さは観測できません。 + +ここから次のことが従います。 + +- tick はクロック 1 周期です。どちらかのエッジに反応するドメインはすべて + 実行されます。イベント自身のドメインはアクティブエッジで、逆エッジの + ドメイン(`@(negedge clk)`、`~clk` をクロックとするレジスタ)や + `clk & en` のように信号から計算されるクロックは、それぞれが見るエッジで + 実行されます。信号は非アクティブレベルで終わります。 +- すでにアクティブレベルにある信号では、`s <= A` は何も変えないので + アクティブエッジは起きません。2 値で 0 から始まる active-low リセットを + tick すると、解除されるだけです。リセットをアサートするには + `negedge(rst)` か `active_edge(rst)` を使います。 +- 1 つのスロットで起動されたドメインは、ノンブロッキング代入と同じく、 + スロット前の状態をサンプルしてからまとめて更新します。複数クロックの + 同時エッジ(`edges`、`tick_events`)では、共有スロットの前の値を互いに + サンプルします。レジスタによる分周クロックのように、そのスロット自身が + 動かすクロックは、コミットの後にスロット内で立ち上がり、そのドメインも + 同じスロットで実行されます。 +- 4 値の設計では、不定レベルはどちらのレベルとしても扱われます。`x` から + 1 は立ち上がりエッジ、`x` から 0 は立ち下がりエッジです + (IEEE 1800-2023 Table 9-2)。 + +`set` や `sim.dut` 経由の書き込みで、イベント信号や、それから計算される +クロックを動かしてはいけません。Celox がドメインを実行するのは上の +エッジ操作だけです。これらの信号は `edge` や `tick` とその派生で駆動して +ください。 + +### ホストからのリセット + +クロック `n` 周期のリセットは、リセットのアクティブエッジ、クロックの +`n` 回の tick、リセットの非アクティブエッジです。 + +```typescript +sim.activeEdge(rst); +sim.tick(clk, n); +sim.inactiveEdge(rst); +``` + +非同期リセットのドメインは最初のスロットで、クロックエッジの前に実行 +されます。同期リセットは最初の tick でリセットされます。この列は、後述の +テストベンチの `rst.assert(n)` と同じスロット列です。 + +### 複数のクロック + +tick はそのイベントの 1 周期なので、2 つのクロック入力の位相関係は表せ +ません。`clk` と、その 2 倍の周期をもつ `clk_half` のように周波数比のある +クロックは、`edges` で瞬間ごとに駆動します。 + +```typescript +sim.edges([[clk, "posedge"], [clkHalf, "posedge"]]); +sim.edges([[clk, "negedge"]]); +sim.edges([[clk, "posedge"], [clkHalf, "negedge"]]); +sim.edges([[clk, "negedge"]]); +``` + +または、入力ごとに `addClock` した timed +[`Simulation`](./writing-tests.md#タイムベースシミュレーション) を使います。 +`tick_events([clk, clk_half])` と `tick(clk)` を交互に呼ぶ方法は、 +立ち上がりエッジだけを見るドメインに対してのみ同じ結果になります。 +`clk_half` が次の立ち上がりではなく `clk` の立ち下がりと同時に立ち下がる +からです。 + +## Veryl ネイティブテストベンチ + +Veryl テストベンチの initial ブロックは SystemVerilog の `initial` +プロセスで、`$finish()` は `$finish` です。ホストと違い、これらの +プロセスにはシミュレーション時刻があります。以下のコンポーネントは +SystemVerilog のコードで、その遅延はテストベンチの時間です。 + +### `$tb::clock_gen` + +`inst clk: $tb::clock_gen #(period: P);` は、待つプロセスがあるかどうかに +かかわらず時刻 0 から動くクロック生成器です。`P` の既定値は 2 で、最小値も +2 です。`H = ceil(P / 2)`、`L = floor(P / 2)` として: + +```systemverilog +bit clk = 1'b0; +initial forever begin + clk <= 1'b1; #H; + clk <= 1'b0; #L; +end +``` + +### `clk.next(n)` + +```systemverilog +task automatic clk_next(int unsigned n); + if (n != 0) begin + repeat (n) @(posedge clk); + #P; + end +endtask +``` + +`clk.next()` は `clk.next(1)` です。 + +- プロセスは、待っていた `n` 回目の立ち上がりエッジから 1 周期後、次の + 立ち上がりの直前に再開します。そのため、その周期の両エッジの後の状態を + 観測します。クロックは Low で、立ち下がりエッジのドメインは実行済みです。 +- クロックはノンブロッキング代入で立ち上がり、同じ時刻に再開した + プロセスの実行後に立ち上がります。そのため、2 つの `next` の間で + プロセスが書き込んだ値は、競合なく次の立ち上がりエッジでサンプルされます。 +- 複数の initial プロセスや周期の異なる複数のクロックに、追加の規則は + ありません。これらは並行する SystemVerilog のプロセスです。誰も待って + いないクロックも動き続け、そのドメインを駆動します。 + +### `$tb::reset_gen` + +`inst rst: $tb::reset_gen #(cycles: C) (clk);` は、テストベンチの `reset` +型のリセットネットで、時刻 0 から非アサート状態です。 + +```systemverilog +bit rst = I; +``` + +### `rst.assert(n)` + +`P` を生成器に渡したクロックの周期として: + +```systemverilog +task automatic rst_assert(int unsigned n); + if (n == 0) n = 1; + rst = A; + repeat (n) @(posedge clk); + #P; + rst = I; +endtask +``` + +`rst.assert()` は `rst.assert(C)` で、`C` の既定値は 3 です。 + +- アサートは、他のテストベンチの書き込みと同じく、プロセスが到達した + 時点でのブロッキング書き込みです。非同期リセットのドメインは、クロック + エッジなしに、そのクロックが動いているかどうかにかかわらず、その瞬間に + 実行されます。同期リセットのドメインは次の立ち上がりエッジでリセット + されます。 +- レベルは `clk` の `n` 周期保持されます。次の立ち上がりエッジ、または + 同じ瞬間の立ち上がりエッジ(クロックはプロセスの書き込み後に立ち上がる + ため)から始まる `n` 回の立ち上がりエッジと、その最後のエッジの後の 1 + 周期です。どちらの種類のリセットも `n` 回のリセットエッジを見て、 + `n + 1` 回目のエッジの前に解除されます。 +- プロセスの再開とリセットの解除は、`next` が再開するのと同じ位相、つまり + 最後に待ったエッジから 1 周期後、次のエッジの直前です。その後の書き込みは + 競合なくそのエッジでサンプルされ、`rst.assert(n); clk.next(m);` は + `n + m` 周期です。 +- `rst.assert(0)` は `rst.assert(1)` です。アサートしたスロットで解除される + リセットは SystemVerilog ではグリッチなので、意味を与えません。 + +このページが定義するのは `$tb::clock_gen`、`clk.next`、`$tb::reset_gen`、 +`rst.assert` です。他のテストベンチコンポーネント `$tb::file` と +`$tb::random` はスケジューリングに関与しません。 diff --git a/docs/ja/guide/writing-tests.md b/docs/ja/guide/writing-tests.md index 23152ebf14b..19b1c132a27 100644 --- a/docs/ja/guide/writing-tests.md +++ b/docs/ja/guide/writing-tests.md @@ -52,7 +52,7 @@ module Reg ( - `Simulator.create(Module)` は Veryl モジュール定義からシミュレータインスタンスを作成します。 - シグナル値は `sim.dut.<ポート名>` で読み書きします。 -- `sim.tick()` でシミュレーションを 1 クロックサイクル進めます。 +- `sim.tick()` でシミュレーションを 1 クロック周期進めます。クロックのアクティブエッジ、続いて非アクティブエッジで、どちらかに反応するドメインはすべて実行されます。tick と等価な SystemVerilog は[実行の意味論](./execution-semantics.md)を参照してください。 - `sim.dispose()` でネイティブリソースを解放します。 ::: tip 組み合わせ回路の場合 diff --git a/packages/celox/src/simulator-edges-addon.test.ts b/packages/celox/src/simulator-edges-addon.test.ts index 070265934d8..1b313a565c6 100644 --- a/packages/celox/src/simulator-edges-addon.test.ts +++ b/packages/celox/src/simulator-edges-addon.test.ts @@ -66,10 +66,11 @@ describe("explicit clock edges", () => { sim.negedge(clk); expect(counters()).toEqual([1n, 1n, 1n]); sim.dut.en = 0n; - sim.cycle(clk); + sim.tick(clk); expect(counters()).toEqual([2n, 2n, 1n]); + sim.dut.en = 1n; sim.tick(clk); - expect(counters()).toEqual([3n, 2n, 1n]); + expect(counters()).toEqual([3n, 3n, 2n]); } finally { sim.dispose(); } @@ -159,7 +160,7 @@ module Top ( reset(sim); const observed = enables.map((enable) => { sim.dut.en_in = enable; - sim.cycle(clk); + sim.tick(clk); return [sim.dut.a_out, sim.dut.b_out, sim.dut.d_out]; }); expect(observed).toEqual(expected); diff --git a/packages/celox/src/simulator.ts b/packages/celox/src/simulator.ts index d174b5f54df..73f761011e5 100644 --- a/packages/celox/src/simulator.ts +++ b/packages/celox/src/simulator.ts @@ -449,7 +449,13 @@ export class Simulator

> { } /** - * Trigger a clock edge. + * Run clock periods of an event's signal. + * + * One tick is the event's active edge, then its inactive edge: every + * domain sensitive to either runs, including domains of the opposite edge + * and clocks derived from the signal, and the signal ends at its inactive + * level. See the execution semantics guide for the SystemVerilog this is + * equivalent to. * * A single numeric argument is the tick count for the default event. When a * second argument is not `undefined`, a numeric first argument is treated as @@ -555,12 +561,6 @@ export class Simulator

> { this.edges([[id, this.activeIsRising(id) ? "negedge" : "posedge"]]); } - /** One clock cycle: `activeEdge()`, then `inactiveEdge()`. */ - cycle(event?: EventHandle | number): void { - this.activeEdge(event); - this.inactiveEdge(event); - } - /** * Move several event signals at one instant. Every domain sensitive to * one of the edges evaluates against the state before them, then all of diff --git a/packages/celox/src/wasm-bridge.ts b/packages/celox/src/wasm-bridge.ts index b5810fcaca4..f3d5aeb6182 100644 --- a/packages/celox/src/wasm-bridge.ts +++ b/packages/celox/src/wasm-bridge.ts @@ -263,7 +263,7 @@ export function createWasmSimulatorBridge( ); const handle: NativeSimulatorHandle = { tick(eventId: number): void { - if (edges?.hasDerived(eventId)) { + if (edges) { edges.tick(eventId); return; } @@ -345,7 +345,7 @@ export async function createWasmSimulatorBridgeAsync( ); const handle: NativeSimulatorHandle = { tick(eventId: number): void { - if (edges?.hasDerived(eventId)) { + if (edges) { edges.tick(eventId); return; } diff --git a/packages/celox/src/wasm-edges.test.ts b/packages/celox/src/wasm-edges.test.ts index e82a48d3c38..8968c0daf7c 100644 --- a/packages/celox/src/wasm-edges.test.ts +++ b/packages/celox/src/wasm-edges.test.ts @@ -143,28 +143,28 @@ test("the WASM bridge ticks and moves clocks as the native simulator does", () = sharedMemory[EN] = 1; handle.evalComb(); - // A tick is the active edge only: the gate passes it, `~clk` does not - // rise, and `clk` stays low. + // A tick is a clock period: the gate passes its rising edge, `~clk` + // rises on its falling edge, and `clk` ends low. handle.tick(0); - expect(counters()).toEqual([1, 1, 0]); + expect(counters()).toEqual([1, 1, 1]); expect(sharedMemory[CLK]).toBe(0); expect(handle.activeEdgeIsRising?.(0)).toBe(true); expect(handle.edges?.([0], [true])).toBe(true); - expect(counters()).toEqual([2, 2, 0]); + expect(counters()).toEqual([2, 2, 1]); expect(sharedMemory[CLK]).toBe(1); // Already high: no edge. handle.edges?.([0], [true]); - expect(counters()).toEqual([2, 2, 0]); - handle.edges?.([0], [false]); expect(counters()).toEqual([2, 2, 1]); + handle.edges?.([0], [false]); + expect(counters()).toEqual([2, 2, 2]); // A closed gate passes no edge. sharedMemory[EN] = 0; handle.evalComb(); handle.edges?.([0], [true]); handle.edges?.([0], [false]); - expect(counters()).toEqual([3, 2, 2]); + expect(counters()).toEqual([3, 2, 3]); }); test("a bridge without edge plans keeps the plain tick", () => { diff --git a/packages/celox/src/wasm-edges.ts b/packages/celox/src/wasm-edges.ts index 9e4c1cc966a..6a088098cda 100644 --- a/packages/celox/src/wasm-edges.ts +++ b/packages/celox/src/wasm-edges.ts @@ -13,8 +13,8 @@ * - After the commit, every domain whose clock then moved to its active edge * runs, in rounds, until no further edge appears: domains clocked from * state, and gates the commit moved. - * - `tick` is the event's active edge without moving its signal. An edge - * moves the signal and leaves it at its new level. + * - An edge moves the signal and leaves it at its new level. `tick` is a + * clock period: the active edge, then the inactive edge. * * Gates are judged by settling the design with the signal at each level. * @@ -180,31 +180,22 @@ export class WasmEdgeRunner { return this.plan(eventId)?.edge !== "negedge"; } - /** The event's active edge without moving its signal, as `tick`. */ + /** A clock period of the event's signal, as `tick`. */ tick(eventId: number): void { const name = this.name(eventId); const plan = this.plan(eventId); - if (!plan || !this.hasDerived(eventId)) { + if (!plan) { this.evalComb(); this.kernels(name)?.evalApply(); this.evalComb(); return; } - const active = plan.edge === "negedge" ? 0 : 1; - const levers: Lever[] = - plan.gated.length > 0 - ? [{ signal: plan.signal, from: active ^ 1, to: active }] - : []; - this.run( - [name], - plan.domains, - plan.gated.map((g) => [g, 0]), - levers, - { - settle: true, - persist: false, - }, - ); + const rising = plan.edge !== "negedge"; + let settled = this.edges([eventId], [rising]); + settled = this.edges([eventId], [!rising], !settled); + if (!settled) { + this.evalComb(); + } } /** diff --git a/packages/playground/src/playground-simulator.ts b/packages/playground/src/playground-simulator.ts index 1fd89e7e534..30f42e11848 100644 --- a/packages/playground/src/playground-simulator.ts +++ b/packages/playground/src/playground-simulator.ts @@ -106,7 +106,7 @@ class PlaygroundInstance { if (this.dirty) this.evalComb(); } - /** The event's active edge without moving its signal, as `tick`. */ + /** A clock period of the event's signal, as `tick`. */ tickOne(eventId: number): void { this.runner.tick(eventId); this.dirty = false; @@ -269,11 +269,6 @@ export function createPlaygroundSimulator( const id = resolveEventId(event); sim.edges([[id, design.activeIsRising(id) ? "negedge" : "posedge"]]); }, - /** One clock cycle: `activeEdge()`, then `inactiveEdge()`. */ - cycle(event?: PlaygroundEvent) { - sim.activeEdge(event); - sim.inactiveEdge(event); - }, event(name: string): PlaygroundEventHandle { return { name, id: design.resolveEvent(name) }; }, diff --git a/packages/playground/test/playground-dts.test.ts b/packages/playground/test/playground-dts.test.ts index 87ea9c8ce94..a70e9f7b1f4 100644 --- a/packages/playground/test/playground-dts.test.ts +++ b/packages/playground/test/playground-dts.test.ts @@ -45,7 +45,7 @@ describe("celox declarations for Monaco", () => { "negedge(", "activeEdge(", "inactiveEdge(", - "cycle(", + "tick(", "edges(", ]) { expect(simulator?.content).toContain(method); diff --git a/packages/playground/test/playground-simulator-wasm.test.ts b/packages/playground/test/playground-simulator-wasm.test.ts index 985912eb06a..a0817dce6a8 100644 --- a/packages/playground/test/playground-simulator-wasm.test.ts +++ b/packages/playground/test/playground-simulator-wasm.test.ts @@ -95,20 +95,20 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { expect(counts()).toEqual([1, 0, 1, 1]); sim.negedge(clk); expect(counts()).toEqual([1, 1, 1, 1]); - sim.cycle(clk); + // A tick is a clock period: both edges of the clock. + sim.tick(clk); expect(counts()).toEqual([2, 2, 2, 1]); - // A tick is the active edge without moving the clock. sim.tick(clk); - expect(counts()).toEqual([3, 2, 3, 2]); + expect(counts()).toEqual([3, 3, 3, 2]); sim.dut.en = 0n; - sim.cycle(clk); - expect(counts()).toEqual([4, 3, 3, 2]); + sim.tick(clk); + expect(counts()).toEqual([4, 4, 3, 2]); // The clock is already at its inactive level: no edge. sim.inactiveEdge(clk); - expect(counts()).toEqual([4, 3, 3, 2]); + expect(counts()).toEqual([4, 4, 3, 2]); sim.activeEdge(); sim.edges([[clk, "negedge"]]); - expect(counts()).toEqual([5, 4, 3, 3]); + expect(counts()).toEqual([5, 5, 3, 3]); expect(() => sim.edges([[clk, "sideways" as "posedge"]])).toThrow( RangeError, ); @@ -118,8 +118,8 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { const sim = createPlaygroundSimulator(compile(LEVER, "Lever")); const clk = sim.event("clk"); sim.dut.en = 1n; - sim.cycle(clk); - sim.cycle(clk); + sim.tick(clk); + sim.tick(clk); expect(sim.dut.count).toBe(2n); sim.tick(clk); expect(sim.dut.count).toBe(3n); @@ -129,7 +129,7 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { const sim = Simulator.fromSource(LEVER, "Lever"); const clk = sim.event("clk"); sim.dut.en = 1n; - sim.cycle(clk); + sim.tick(clk); sim.tick(clk); expect(sim.dut.count).toBe(2n); sim.dispose();