diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index e3fb85fb060..21bb5cc0f63 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -615,6 +615,10 @@ pub struct EventTopology { /// an earlier one writes, and none has side effects. #[serde(default)] pub independent_derived: BTreeSet, + /// Canonical events whose signal combinational logic reads. Moving such + /// a signal needs a settle before its domains evaluate. + #[serde(default)] + pub combinationally_read: BTreeSet, } /// A clock computed combinationally from an event's signal. @@ -709,6 +713,7 @@ impl Default for EventTopology { derived_events: BTreeMap::new(), combinational_derived: BTreeMap::new(), independent_derived: BTreeSet::new(), + combinationally_read: BTreeSet::new(), } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 1ccdb3bbeaa..2c7e800be86 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -740,6 +740,7 @@ pub fn schedule_symbolic_rtl( derived_events, combinational_derived, independent_derived, + combinationally_read, } = timed_sub!( "analyze_clock_dependencies", analyze_clock_dependencies( @@ -1344,6 +1345,7 @@ pub fn schedule_symbolic_rtl( .map(|(event, targets)| (project(event), targets.into_iter().map(project).collect())) .collect(), independent_derived: independent_derived.into_iter().map(project).collect(), + combinationally_read: combinationally_read.into_iter().map(project).collect(), combinational_derived: combinational_derived .into_iter() .map(|(event, clocks)| { @@ -3555,6 +3557,8 @@ struct ClockAnalysis { /// Events whose combinationally derived domains may run before them in /// turn instead of together. independent_derived: BTreeSet, + /// Events whose signal combinational logic reads. + combinationally_read: BTreeSet, } fn analyze_clock_dependencies( @@ -3950,6 +3954,12 @@ fn analyze_clock_dependencies( Some((reads, writes)) }; let mut independent_derived = BTreeSet::new(); + let combinationally_read: BTreeSet = comb_deps + .values() + .flatten() + .map(|source| clock_domains.get(source).copied().unwrap_or(*source)) + .filter(|source| unique_clocks.contains(source)) + .collect(); let combinational_derived = comb_derived_clocks .into_iter() .map(|(event, clocks)| { @@ -3989,6 +3999,7 @@ fn analyze_clock_dependencies( derived_events, combinational_derived, independent_derived, + combinationally_read, } } diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index bb7910a0fa6..e2d8ccccfc3 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -687,6 +687,7 @@ struct CachedBuild { /// Derived clock domains per event, valid for every backend sharing /// `shared_code`. derived_ticks: celox::DerivedTickPlans, + event_edges: celox::EventEdges, } #[cfg(not(target_arch = "wasm32"))] @@ -924,6 +925,62 @@ impl HandleBackend { } } + /// Run coincident edges of event signals, as `Simulator::edges` does. + fn edges( + &mut self, + moves: &[(usize, celox::Edge)], + derived: &HandleDerivedTicks, + event_edges: &celox::EventEdges, + scratch: &mut celox::DerivedTickScratch, + dirty: bool, + ) -> std::result::Result { + fn edges_with( + backend: &mut B, + moves: &[(usize, celox::Edge)], + plans: &celox::DerivedTickPlans, + event_edges: &celox::EventEdges, + scratch: &mut celox::DerivedTickScratch, + dirty: bool, + ) -> std::result::Result { + let moves: Vec<_> = moves + .iter() + .map(|&(id, edge)| (backend.id_to_event_slice()[id], edge)) + .collect(); + celox::run_edges( + &mut celox::BackendExecutor(backend), + plans, + event_edges, + scratch, + &moves, + dirty, + celox::set_level, + ) + .map_or_else( + |halt| match halt { + // A bare backend reports no `$finish`; settle next time. + celox::Halt::Finish => Ok(false), + celox::Halt::Error(error) => Err(error), + }, + |outcome| { + Ok(match outcome { + celox::EdgeOutcome::Unchanged | celox::EdgeOutcome::Stored => !dirty, + celox::EdgeOutcome::Moved => false, + celox::EdgeOutcome::Settled => true, + }) + }, + ) + } + match (self, derived) { + (Self::Default(backend), HandleDerivedTicks::Default(plans)) => { + edges_with(backend, moves, plans, event_edges, scratch, dirty) + } + (Self::Tiered(backend), HandleDerivedTicks::Tiered(plans)) => { + edges_with(backend.as_mut(), moves, plans, event_edges, scratch, dirty) + } + _ => unreachable!("derived tick plans belong to the handle's backend"), + } + } + fn event_count(&self) -> usize { match self { Self::Default(backend) => backend.id_to_event_slice().len(), @@ -1015,6 +1072,7 @@ pub struct NativeSimulatorHandle { state_schema: Arc, derived_ticks: HandleDerivedTicks, derived_scratch: celox::DerivedTickScratch, + event_edges: celox::EventEdges, } #[cfg(not(target_arch = "wasm32"))] @@ -1070,6 +1128,7 @@ impl NativeSimulatorHandle { let vcd_descs = sim.build_vcd_descs(four_state); let runtime_errors = runtime_errors_by_name(sim.program()); let derived_ticks = sim.derived_tick_plans(); + let event_edges = sim.event_edges(); let layout_map = build_signal_layout(&signals, four_state); let event_map = build_event_map(&events); @@ -1097,6 +1156,7 @@ impl NativeSimulatorHandle { state_schema: Arc::clone(&state_schema), vcd_descs: vcd_descs.clone(), derived_ticks: Arc::clone(&derived_ticks), + event_edges: Arc::clone(&event_edges), }); let mut cache = JIT_CACHE.lock().unwrap_or_else(|e| e.into_inner()); cache.insert(key, cached); @@ -1129,6 +1189,7 @@ impl NativeSimulatorHandle { state_schema, derived_ticks: HandleDerivedTicks::Default(derived_ticks), derived_scratch: Default::default(), + event_edges, }) } @@ -1167,6 +1228,7 @@ impl NativeSimulatorHandle { // Extract the backend from Simulator (drops runtime metadata which is // no longer needed). let derived_ticks = HandleDerivedTicks::Tiered(sim.derived_tick_plans()); + let event_edges = sim.event_edges(); let backend = HandleBackend::Tiered(Box::new(sim.into_backend())); Ok(Self { @@ -1183,6 +1245,7 @@ impl NativeSimulatorHandle { state_schema, derived_ticks, derived_scratch: Default::default(), + event_edges, }) } @@ -1218,6 +1281,7 @@ impl NativeSimulatorHandle { state_schema: Arc::clone(&cached.state_schema), derived_ticks: HandleDerivedTicks::Default(Arc::clone(&cached.derived_ticks)), derived_scratch: Default::default(), + event_edges: Arc::clone(&cached.event_edges), }) } @@ -1445,6 +1509,62 @@ impl NativeSimulatorHandle { .map_err(|e| napi_runtime_error(&runtime_errors, e)) } + /// Move event signals through coincident edges and run every domain + /// sensitive to them: `rising[i]` gives the direction of `event_ids[i]`. + /// See `Simulator::edges`. `dirty` says whether combinational logic has + /// pending changes (default: it has, so it settles first). Returns whether + /// combinational logic is settled afterwards: it is not when a signal that + /// combinational logic reads moved but no domain ran, or when it was + /// dirty and nothing ran. + #[napi] + pub fn edges( + &mut self, + event_ids: Vec, + rising: Vec, + dirty: Option, + ) -> Result { + if event_ids.len() != rising.len() { + return Err(Error::from_reason( + "edges needs one direction per event".to_string(), + )); + } + let runtime_errors = self.runtime_errors.clone(); + let b = self + .backend + .as_mut() + .ok_or_else(|| Error::from_reason("Simulator has been disposed"))?; + let mut moves = Vec::with_capacity(event_ids.len()); + for (&event_id, &rising) in event_ids.iter().zip(&rising) { + validate_event_id(event_id, b.event_count())?; + let edge = if rising { + celox::Edge::Rising + } else { + celox::Edge::Falling + }; + moves.push((event_id as usize, edge)); + } + b.edges( + &moves, + &self.derived_ticks, + &self.event_edges, + &mut self.derived_scratch, + dirty.unwrap_or(true), + ) + .map_err(|e| napi_runtime_error(&runtime_errors, e)) + } + + /// Whether the event's active edge is a rising one: a positive-edge + /// clock or an active-high reset. + #[napi] + pub fn active_edge_is_rising(&self, event_id: u32) -> Result { + let b = self + .backend + .as_ref() + .ok_or_else(|| Error::from_reason("Simulator has been disposed"))?; + validate_event_id(event_id, b.event_count())?; + Ok(self.event_edges[event_id as usize].active_edge() == celox::Edge::Rising) + } + /// Trigger a clock/event N times in a single NAPI call. #[napi] pub fn tick_n(&mut self, event_id: u32, count: u32) -> Result<()> { @@ -2406,23 +2526,23 @@ impl NativeSimulatorHandle { /// Returns the WASM module bytes for a specific clock/reset event. /// /// `event_name` should match a clock or reset port name (e.g. "clk", "rst"). + /// + /// An event without a domain of its own (a clock that only drives a + /// gated clock) has no module. #[napi] pub fn event_wasm_bytes(&self, event_name: String) -> Result> { - for (addr, units) in &self.program.sir.eval_apply_ffs { - let event_path = self.program.get_path(addr); - if event_path == event_name { - let wasm = celox::wasm_codegen::compile_units( - units, - self.program.layout(), - self.four_state, - false, - ); - return Ok(wasm.bytes); - } + if let Some(units) = self.event_units(&self.program.sir.eval_apply_ffs, &event_name) { + let wasm = celox::wasm_codegen::compile_units( + units, + self.program.layout(), + self.four_state, + false, + ); + return Ok(wasm.bytes); } Err(Error::from_reason(format!( - "Event '{}' not found. Available events: {}", + "Event '{}' has no kernel. Events with kernels: {}", event_name, self.program .sir @@ -2434,6 +2554,61 @@ impl NativeSimulatorHandle { ))) } + /// The units of the event named `name` (as `eventsJson` names it, or by + /// one of its aliases) in one of the program's kernel maps. + fn event_units<'a, U: 'a>( + &self, + kernels: impl IntoIterator, + name: &str, + ) -> Option<&'a U> { + let events = &self.program.design.events; + kernels + .into_iter() + .find(|(address, _)| { + self.program.get_path(address) == name + || self.program.get_path(&events.canonical(**address)) == name + }) + .map(|(_, units)| units) + } + + /// Per event name, the derived domains its ticks and edges run, as JSON + /// (`celox::EdgePlans`), for the TypeScript runtime that drives the + /// event modules itself. + #[napi] + pub fn edge_plans_json(&self) -> String { + serde_json::to_string(&celox::edge_plans(&self.program)) + .unwrap_or_else(|_| "{\"fourState\":false,\"events\":{}}".to_string()) + } + + /// The WASM module of one phase of an event's split kernels: `"evalOnly"` + /// evaluates its next state without committing, `"apply"` commits it. + /// Domains that evaluate together use them to sample the same state. + #[napi] + pub fn event_phase_wasm_bytes(&self, event_name: String, phase: String) -> Result> { + let units = match phase.as_str() { + "evalOnly" => &self.program.sir.eval_only_ffs, + "apply" => &self.program.sir.apply_ffs, + _ => { + return Err(Error::from_reason(format!( + "unknown event phase '{phase}'; expected 'evalOnly' or 'apply'" + ))); + } + }; + self.event_units(units, &event_name) + .map(|units| { + celox::wasm_codegen::compile_units( + units, + self.program.layout(), + self.four_state, + false, + ) + .bytes + }) + .ok_or_else(|| { + Error::from_reason(format!("event '{event_name}' has no {phase} kernel")) + }) + } + /// No-op on wasm32 (no native resources to release). #[napi] pub fn dispose(&mut self) {} @@ -2643,13 +2818,14 @@ impl NativeSimulatorHandle { serde_json::to_string(&layout_map).unwrap_or_else(|_| "{}".to_string()) } - /// Build events JSON from finalized SIR. + /// Build events JSON from finalized SIR, numbered as the native + /// simulator numbers them. fn build_events_json(program: &celox::LaidOutProgram) -> String { use std::collections::BTreeMap; let mut events: BTreeMap = BTreeMap::new(); - for (next_id, addr) in program.sir.eval_apply_ffs.keys().enumerate() { + for (next_id, addr) in celox::event_addresses(program).iter().enumerate() { let name = program.get_path(addr); events.insert(name, next_id); } @@ -3838,6 +4014,87 @@ mod tests { } } + /// `edges` moves the clock and runs the domains of each direction, on + /// freshly built, cached and tiered handles. + #[test] + fn native_handle_edges_run_both_directions() { + let source = "module Top ( + clk: input clock, rising: output logic<8>, falling: output logic<8>, + ) { + always_ff (clk) { rising += 1; } + let inverted: '_ clock = ~clk; + always_ff (inverted) { falling += 1; } + }"; + for mode in ["fresh", "cached", "tiered"] { + let mut handle = if mode == "tiered" { + NativeSimulatorHandle::new_tiered(napi_sources(source), "Top".into(), None) + } else { + NativeSimulatorHandle::new(napi_sources(source), "Top".into(), None) + } + .unwrap(); + let events: HashMap = serde_json::from_str(&handle.events_json()).unwrap(); + let layout: serde_json::Value = serde_json::from_str(&handle.layout_json()).unwrap(); + let offset = |name: &str| layout[name]["offset"].as_u64().unwrap() as usize; + let (clk, rising, falling) = (offset("clk"), offset("rising"), offset("falling")); + let memory = |handle: &mut NativeSimulatorHandle| { + let (ptr, len) = handle.backend.as_mut().unwrap().memory_as_mut_ptr(); + unsafe { std::slice::from_raw_parts_mut(ptr, len) } + }; + let clk_event = events["clk"]; + assert!(handle.active_edge_is_rising(clk_event).unwrap()); + let _ = handle.edges(vec![clk_event], vec![false], None).unwrap(); + let start = (memory(&mut handle)[rising], memory(&mut handle)[falling]); + assert!(handle.edges(vec![clk_event], vec![true], None).unwrap()); + assert_eq!(memory(&mut handle)[clk], 1, "{mode}: clk stays high"); + assert_eq!( + memory(&mut handle)[rising], + start.0.wrapping_add(1), + "{mode}" + ); + assert_eq!(memory(&mut handle)[falling], start.1, "{mode}"); + let _ = handle.edges(vec![clk_event], vec![false], None).unwrap(); + assert_eq!( + memory(&mut handle)[rising], + start.0.wrapping_add(1), + "{mode}" + ); + assert_eq!( + memory(&mut handle)[falling], + start.1.wrapping_add(1), + "{mode}" + ); + assert!(handle.edges(vec![clk_event], vec![], None).is_err()); + handle.dispose().unwrap(); + } + } + + #[test] + fn native_handle_edges_of_clocks_comb_logic_does_not_read_stay_settled() { + for (seen, comb_read) in [("1'b1", false), ("clk", true)] { + let source = format!( + "module Top (clk: input clock, count: output logic<8>, seen: output logic) {{ + always_ff (clk) {{ count += 1; }} + assign seen = {seen}; + }}" + ); + let mut handle = + NativeSimulatorHandle::new(napi_sources(&source), "Top".into(), None).unwrap(); + let events: HashMap = serde_json::from_str(&handle.events_json()).unwrap(); + let clk = events["clk"]; + assert!(handle.edges(vec![clk], vec![true], None).unwrap()); + // Moving `clk` without running a domain leaves combinational + // logic stale only when it reads `clk`, or already was. + assert_eq!( + handle.edges(vec![clk], vec![false], Some(false)).unwrap(), + !comb_read, + "{seen}" + ); + assert!(handle.edges(vec![clk], vec![true], Some(true)).unwrap()); + assert!(!handle.edges(vec![clk], vec![false], Some(true)).unwrap()); + handle.dispose().unwrap(); + } + } + #[test] fn simulator_handle_derives_four_state_metadata_from_layout() { let source = "module Top (a: input logic<1>) {}"; diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index 88462253f26..172ac7ff6cb 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -451,8 +451,9 @@ impl DerivedTickPlan { } /// Tick the source domains and every derived domain that sees its - /// active edge. `settle` says whether combinational logic must be settled - /// before the source domains evaluate. + /// active edge, without moving the ticked signals. `settle` says whether + /// combinational logic must be settled before the source domains + /// evaluate. pub fn tick( &self, executor: &mut X, @@ -463,20 +464,47 @@ impl DerivedTickPlan { X: TickExecutor, X::Backend: SimBackend, { - match self.tick_domains(executor, scratch, settle) { + let pulse = |&(_, active): &(SignalRef, u8)| (active ^ 1, active); + fn run(transitions: &[(u8, u8)]) -> EdgeRun<'_> { + EdgeRun { + transitions, + persist: false, + fire_sources: true, + } + } + let result = match self.levers.as_ref() { + [] => self.run(executor, scratch, settle, run(&[])), + [lever] => self.run(executor, scratch, settle, run(&[pulse(lever)])), + levers => { + let transitions: Vec<_> = levers.iter().map(pulse).collect(); + self.run(executor, scratch, settle, run(&transitions)) + } + }; + match result { // An RTL `$finish` ends only a timed simulation, which does not // tick; a tick leaves it to the host. - Ok(()) | Err(Halt::Finish) => Ok(()), + Ok(_) | Err(Halt::Finish) => Ok(()), Err(Halt::Error(error)) => Err(error), } } - fn tick_domains( + /// Ticked signals that gate derived clocks, in the order + /// [`EdgeRun::transitions`] lists their levels. + pub fn lever_signals(&self) -> impl Iterator + '_ { + self.levers.iter().map(|&(signal, _)| signal) + } + + /// Run one edge of the ticked signals: the source domains when + /// `run.fire_sources`, every gated clock that sees its active edge in + /// `run.transitions`, then the cascade rounds. Returns whether + /// combinational logic is settled afterwards; it is not when nothing ran. + pub fn run( &self, executor: &mut X, scratch: &mut DerivedTickScratch, settle: bool, - ) -> Result<(), Halt> + run: EdgeRun<'_>, + ) -> Result where X: TickExecutor, X::Backend: SimBackend, @@ -485,56 +513,67 @@ impl DerivedTickPlan { // The baseline is the state settled after the previous operation, // as the timed scheduler keeps it between steps. self.sample_domains(executor.backend(), scratch); + let sources: &[EventDomain] = if run.fire_sources { &self.sources } else { &[] }; if self.gated.is_empty() { - fire(executor, settle, self.sources.iter())?; + if sources.is_empty() { + return Ok(false); + } + fire(executor, settle, sources.iter())?; executor.eval_comb()?; - return self.rounds(executor, scratch, Phase::Active); + self.rounds(executor, scratch, run.transitions)?; + return Ok(true); } if self.fast { - self.tick_gated_fast(executor, scratch, settle) + self.run_gated_fast(executor, scratch, settle, sources, run.transitions)?; } else { - self.tick_gated_settled(executor, scratch, settle) + self.run_gated_settled(executor, scratch, settle, sources, &run)?; } + Ok(true) } /// Gates judged by their programs: no settle beyond the ticked domains'. - fn tick_gated_fast( + fn run_gated_fast( &self, executor: &mut X, scratch: &mut DerivedTickScratch, settle: bool, + sources: &[EventDomain], + transitions: &[(u8, u8)], ) -> Result<(), Halt> where X: TickExecutor, X::Backend: SimBackend, { - // The active edge: gated clocks judged from the state before it. + // The edge: gated clocks judged from the state before it. let base = self.domains.len(); scratch.ready.clear(); for (index, domain) in self.gated.iter().enumerate() { + let (from, to) = transitions[domain.lever]; let backend = executor.backend(); - let before = self.gate_level(backend, domain, Phase::Inactive); - let after = self.gate_level(backend, domain, Phase::Active); + let before = self.gate_level(backend, domain, from); + let after = self.gate_level(backend, domain, to); let fired = settled_edge(domain.derived.kind, before, after); if fired { scratch.ready.push(index); } scratch.flags[base + index] = flags(after, fired); } - self.fire_with_gated(executor, settle, &scratch.ready)?; + self.fire_with_gated(executor, settle, sources, &scratch.ready)?; executor.eval_comb()?; // The commit may move a gate, as the nonblocking updates after the // edge do; that is a further edge of the gated clock. - self.rounds(executor, scratch, Phase::Active) + self.rounds(executor, scratch, transitions) } /// Gates without programs: settle the design with the levers at each /// level, as the timed scheduler does at the edge. - fn tick_gated_settled( + fn run_gated_settled( &self, executor: &mut X, scratch: &mut DerivedTickScratch, settle: bool, + sources: &[EventDomain], + run: &EdgeRun<'_>, ) -> Result<(), Halt> where X: TickExecutor, @@ -543,12 +582,15 @@ impl DerivedTickPlan { let base = self.domains.len(); let saved = base + self.gated.len(); let mut moved = false; - for (index, &(signal, active)) in self.levers.iter().enumerate() { - let (value, mask) = executor.backend().get_four_state(signal); - scratch.flags[saved + 2 * index] = u8::try_from(&value).unwrap_or(0); - scratch.flags[saved + 2 * index + 1] = u8::try_from(&mask).unwrap_or(0); - if event_level(executor.backend(), signal) != active ^ 1 { - executor.backend_mut().set(signal, active ^ 1); + for (index, &(signal, _)) in self.levers.iter().enumerate() { + let (from, _) = run.transitions[index]; + if !run.persist { + let (value, mask) = executor.backend().get_four_state(signal); + scratch.flags[saved + 2 * index] = u8::try_from(&value).unwrap_or(0); + scratch.flags[saved + 2 * index + 1] = u8::try_from(&mask).unwrap_or(0); + } + if event_level(executor.backend(), signal) != from { + executor.backend_mut().set(signal, from); moved = true; } } @@ -559,8 +601,8 @@ impl DerivedTickPlan { let level = event_level(executor.backend(), domain.derived.signal) != 0; scratch.flags[base + index] = flags(level, false); } - for &(signal, active) in &self.levers { - executor.backend_mut().set(signal, active); + for (index, &(signal, _)) in self.levers.iter().enumerate() { + executor.backend_mut().set(signal, run.transitions[index].1); } executor.eval_comb()?; scratch.ready.clear(); @@ -573,12 +615,14 @@ impl DerivedTickPlan { } scratch.flags[base + index] = flags(after, fired); } - self.fire_with_gated(executor, false, &scratch.ready)?; + self.fire_with_gated(executor, false, sources, &scratch.ready)?; executor.eval_comb()?; - self.rounds(executor, scratch, Phase::Active)?; + self.rounds(executor, scratch, run.transitions)?; + if run.persist { + return Ok(()); + } - // Leave the levers as they were, unknown bits included. Only the - // active edge is ticked: the return of a lever fires nothing. + // Leave the levers as they were, unknown bits included. let mut restored = false; for (index, &(signal, _)) in self.levers.iter().enumerate() { let value = num_bigint::BigUint::from(scratch.flags[saved + 2 * index]); @@ -594,11 +638,12 @@ impl DerivedTickPlan { Ok(()) } - /// Run the ticked domains together with the gated domains `ready`. + /// Run `sources` together with the gated domains `ready`. fn fire_with_gated( &self, executor: &mut X, settle: bool, + sources: &[EventDomain], ready: &[usize], ) -> Result<(), Halt> where @@ -607,7 +652,7 @@ impl DerivedTickPlan { { let gated = ready.iter().map(|&index| &self.gated[index].derived.domain); if !self.independent || ready.is_empty() { - return fire(executor, settle, self.sources.iter().chain(gated)); + return fire(executor, settle, sources.iter().chain(gated)); } // Each domain finds the state the others leave alone, so running // them in turn with their fused kernels gives the same result as @@ -615,26 +660,18 @@ impl DerivedTickPlan { if settle { executor.eval_comb()?; } - for domain in gated.chain(self.sources.iter()) { + for domain in gated.chain(sources.iter()) { executor.eval_apply_ff_at(domain.eval_apply)?; } Ok(()) } - /// A gated clock's level with its lever at `phase`'s level, from its - /// program in the fast path and from the settled design otherwise. + /// A gated clock's level with its lever at `level`, from its program in + /// the fast path and from the settled design otherwise. #[inline] - fn gate_level( - &self, - backend: &B, - domain: &GatedDomain, - phase: Phase, - ) -> bool { + fn gate_level(&self, backend: &B, domain: &GatedDomain, level: u8) -> bool { match &domain.gate { - Some(gate) if self.fast => { - let level = self.levers[domain.lever].1 ^ u8::from(phase == Phase::Inactive); - gate.level(backend, level) - } + Some(gate) if self.fast => gate.level(backend, level), _ => event_level(backend, domain.derived.signal) != 0, } } @@ -653,7 +690,7 @@ impl DerivedTickPlan { &self, executor: &mut X, scratch: &mut DerivedTickScratch, - phase: Phase, + transitions: &[(u8, u8)], ) -> Result<(), Halt> where X: TickExecutor, @@ -677,7 +714,7 @@ impl DerivedTickPlan { if state & FIRED != 0 { continue; } - let is = self.gate_level(executor.backend(), domain, phase); + let is = self.gate_level(executor.backend(), domain, transitions[domain.lever].1); if settled_edge(domain.derived.kind, state & WAS != 0, is) { scratch.ready.push(base + index); } @@ -704,12 +741,17 @@ impl DerivedTickPlan { } } -/// Which level of its source a gated clock is judged at: its active level -/// at and after the edge, its inactive level before it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Phase { - Active, - Inactive, +/// How an edge moves the signals that gate a plan's derived clocks. +#[derive(Clone, Copy, Debug)] +pub struct EdgeRun<'a> { + /// Per lever ([`DerivedTickPlan::lever_signals`]), its level before and + /// after the edge. + pub transitions: &'a [(u8, u8)], + /// The levers stay at their new level; otherwise they are left as they + /// were before the edge. + pub persist: bool, + /// The ticked domains themselves see their active edge. + pub fire_sources: bool, } #[inline] diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs new file mode 100644 index 00000000000..721da594786 --- /dev/null +++ b/crates/celox-runtime/src/edge.rs @@ -0,0 +1,333 @@ +//! Explicit edges of event signals. +//! +//! An edge moves an event's signal to a new level and runs every domain +//! sensitive to that transition: the event's own domain when the transition +//! is its active edge, clocks computed combinationally from the signal that +//! see their active edge (judged from the state before the edge), and the +//! cascade rounds after the commit. The signal stays at its new level. +//! +//! An event without derived domains costs one load and one store of its +//! level on top of its domain's kernel; its signal settles first only when +//! combinational logic reads it. An edge that runs no domain leaves +//! combinational logic stale only when combinational logic reads the signal, +//! so the inactive edge of a clock that only clocks flip-flops costs no +//! settle on the next active edge. + +use celox_design::{DomainKind, EventTopology}; + +use crate::{ + AbsoluteAddr, SignalRef, + backend::{EventHandle, SimBackend}, + derived_tick::{ + DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, EdgeRun, EventDomain, TickExecutor, + }, + simulation::event_level, + timing::Halt, +}; + +/// A transition of an event signal. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Edge { + /// To 1: `posedge`. + Rising, + /// To 0: `negedge`. + Falling, +} + +impl Edge { + /// The level the signal has after the edge. + pub fn level(self) -> u8 { + match self { + Edge::Rising => 1, + Edge::Falling => 0, + } + } +} + +/// What an edge needs to know about one event. +#[derive(Clone, Copy, Debug)] +pub struct EventEdge { + /// The event's canonical signal. + pub signal: SignalRef, + pub kind: Option, + /// Combinational logic reads the signal. + pub comb_read: bool, +} + +impl EventEdge { + /// The edge that is the event's own active edge. + pub fn active_edge(&self) -> Edge { + match self.kind { + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => Edge::Falling, + _ => Edge::Rising, + } + } + + /// Whether `edge` can run the event's own domain at all, whatever the + /// level before it: always, except for the inactive edge of an event of + /// known polarity. + pub fn can_fire(&self, edge: Edge) -> bool { + self.fires(None, edge) + } + + /// Whether `edge` from `old` (`None` when unknown) runs the event's own + /// domain: its active transition, or any change for a domain of unknown + /// kind. An unknown level counts as either level, as in SystemVerilog. + pub fn fires(&self, old: Option, edge: Edge) -> bool { + match self.kind { + Some( + DomainKind::ClockPosedge + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncHigh + | DomainKind::ResetAsyncLow, + ) => edge == self.active_edge(), + _ => old != Some(edge == Edge::Rising), + } + } +} + +/// Per event ID, what an edge needs to know about it. +pub type EventEdges = std::sync::Arc<[EventEdge]>; + +/// Resolve the edge information of every event of `backend`. +pub fn build_event_edges( + backend: &B, + events: &EventTopology, + kinds: &fxhash::FxHashMap, +) -> EventEdges { + backend + .id_to_addr_slice() + .iter() + .map(|address| { + let canonical = events.canonical(*address); + EventEdge { + signal: backend.resolve_signal(&canonical), + kind: kinds.get(&canonical).copied(), + comb_read: events.combinationally_read.contains(&canonical), + } + }) + .collect() +} + +/// What an edge did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EdgeOutcome { + /// The signal already was at the edge's level: nothing changed. + Unchanged, + /// The signal moved but no domain ran, and combinational logic reads + /// it: combinational logic is stale. + Moved, + /// The signal moved but no domain ran, and combinational logic does not + /// read it: combinational logic is exactly as settled as before. + Stored, + /// Domains ran and combinational logic is settled. + Settled, +} + +/// The outcome of a move that ran no domain. +fn moved_only(comb_read: bool) -> EdgeOutcome { + if comb_read { + EdgeOutcome::Moved + } else { + EdgeOutcome::Stored + } +} + +/// The level of `signal`, or `None` while it is unknown. +fn level(backend: &B, signal: SignalRef) -> Option { + if signal.is_4state && backend.layout().four_state { + let (value, mask) = backend.get_four_state(signal); + if mask.bit(0) { + return None; + } + return Some(value.bit(0)); + } + Some(event_level(backend, signal) != 0) +} + +/// Writes an event signal's new level: the host's own write of the signal, +/// which a host observing its writes (a timed simulation's waits and +/// counters) routes through its watch. +pub trait SignalWrite { + fn write(&mut self, backend: &mut B, signal: SignalRef, level: u8); +} + +impl SignalWrite for F { + fn write(&mut self, backend: &mut B, signal: SignalRef, level: u8) { + self(backend, signal, level); + } +} + +/// A plain write of the level, for hosts that observe nothing. +pub fn set_level(backend: &mut B, signal: SignalRef, level: u8) { + backend.set(signal, level); +} + +/// Move `info`'s signal to the level of `edge` through `write`. Returns the +/// level it had (`None` while unknown), or `None` when it already was at +/// that level. +pub fn move_signal( + backend: &mut B, + info: &EventEdge, + edge: Edge, + mut write: impl SignalWrite, +) -> Option> { + let old = level(backend, info.signal); + let new = edge.level(); + if old == Some(new != 0) { + return None; + } + write.write(backend, info.signal, new); + Some(old) +} + +/// Move `event`'s signal through `edge` and run the domains sensitive to it. +/// `info` and `plan` are the event's entries of its host's tables; `dirty` +/// says whether combinational logic has pending changes; `write` moves the +/// signal. +#[allow(clippy::too_many_arguments)] +pub fn run_edge( + executor: &mut X, + plan: Option<&DerivedTickPlan>, + info: EventEdge, + scratch: &mut DerivedTickScratch, + event: E, + edge: Edge, + dirty: bool, + write: impl SignalWrite, +) -> Result +where + X: TickExecutor, + X::Backend: SimBackend, + E: EventHandle, +{ + let Some(old) = move_signal(executor.backend_mut(), &info, edge, write) else { + return Ok(EdgeOutcome::Unchanged); + }; + let new = edge.level(); + let fires = info.fires(old, edge); + let settle = dirty || info.comb_read; + if let Some(plan) = plan { + let from = old.map_or(new ^ 1, u8::from); + let transition = [(from, new)]; + let transitions: &[(u8, u8)] = if plan.lever_signals().next().is_some() { + &transition + } else { + &[] + }; + let settled = plan.run( + executor, + scratch, + settle, + EdgeRun { + transitions, + persist: true, + fire_sources: fires, + }, + )?; + return Ok(if settled { + EdgeOutcome::Settled + } else { + moved_only(info.comb_read) + }); + } + if !fires { + return Ok(moved_only(info.comb_read)); + } + if settle { + executor.eval_comb_apply_ff_at(event)?; + } else { + executor.eval_apply_ff_at(event)?; + } + executor.eval_comb()?; + Ok(EdgeOutcome::Settled) +} + +/// Move several event signals at the same instant and run the domains +/// sensitive to their edges: every domain evaluates against the state +/// before the edge, then all of them commit. `write` moves the signals. +pub fn run_edges( + executor: &mut X, + plans: &DerivedTickPlans, + edges: &[EventEdge], + scratch: &mut DerivedTickScratch, + moves: &[(E, Edge)], + dirty: bool, + mut write: impl SignalWrite, +) -> Result +where + X: TickExecutor, + X::Backend: SimBackend, + E: EventHandle, +{ + if let [(event, edge)] = moves { + let plan = plans.get(event.id()).and_then(Option::as_ref); + return run_edge( + executor, + plan, + edges[event.id()], + scratch, + *event, + *edge, + dirty, + write, + ); + } + let mut sources: Vec> = Vec::with_capacity(moves.len()); + let mut moved_plans = Vec::new(); + let mut transitions: Vec<(SignalRef, (u8, u8))> = Vec::new(); + let mut comb_read = false; + let mut any_moved = false; + for &(event, edge) in moves { + let id = event.id(); + let info = &edges[id]; + let old = level(executor.backend(), info.signal); + let new = edge.level(); + if old == Some(new != 0) || transitions.iter().any(|(signal, _)| *signal == info.signal) { + continue; + } + any_moved = true; + write.write(executor.backend_mut(), info.signal, new); + transitions.push((info.signal, (old.map_or(new ^ 1, u8::from), new))); + comb_read |= info.comb_read; + if info.fires(old, edge) { + let address = executor.backend().id_to_addr_slice()[id]; + sources.push(EventDomain { + eval_apply: event, + eval_only: executor.backend().resolve_eval_only_event(&address), + apply: executor.backend().resolve_apply_event(&address), + }); + } + if let Some(Some(plan)) = plans.get(id) { + moved_plans.push(plan); + } + } + if !any_moved { + return Ok(EdgeOutcome::Unchanged); + } + let plan = DerivedTickPlan::merge(sources, moved_plans); + let lever_transitions: Vec<(u8, u8)> = plan + .lever_signals() + .map(|signal| { + transitions + .iter() + .find(|(moved, _)| *moved == signal) + .map_or((0, 0), |(_, transition)| *transition) + }) + .collect(); + let settled = plan.run( + executor, + scratch, + dirty || comb_read, + EdgeRun { + transitions: &lever_transitions, + persist: true, + fire_sources: true, + }, + )?; + Ok(if settled { + EdgeOutcome::Settled + } else { + moved_only(comb_read) + }) +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index a55a5d27f5d..46c19a270c8 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -2,6 +2,7 @@ pub mod backend; mod derived_tick; +mod edge; mod error; mod event_buffer; pub mod parallel; @@ -15,9 +16,13 @@ pub mod timing; mod vcd; pub use derived_tick::{ - BackendExecutor, DerivedDomain, DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, + BackendExecutor, DerivedDomain, DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, EdgeRun, EventDomain, Gate, GatedDomain, TickExecutor, build_derived_tick_plans, }; +pub use edge::{ + Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, build_event_edges, move_signal, + run_edge, run_edges, set_level, +}; pub use error::{SimulatorErrorCode, comb_fatal_code, comb_fatal_site}; pub use event_buffer::RuntimeEventBuffer; pub use reflection::{ diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 9a7393c1c66..23839ecada6 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -46,6 +46,16 @@ 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 @@ -86,6 +96,14 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } }) }); + let cycle_name = name.replace("tick", "cycle"); + c.bench_function(&cycle_name, |b| { + b.iter(|| { + for _ in 0..10000 { + sim.cycle(clk).unwrap(); + } + }) + }); } // Benchmark 2: Simulation::step diff --git a/crates/celox/src/backend.rs b/crates/celox/src/backend.rs index 5ee53ea31f0..129f9a248a0 100644 --- a/crates/celox/src/backend.rs +++ b/crates/celox/src/backend.rs @@ -63,21 +63,7 @@ fn event_ids( crate::HashMap, Vec, ) { - let mut addresses = program.design.events.ordered_events.clone(); - let mut seen: crate::HashSet<_> = addresses.iter().copied().collect(); - // Preserve legacy/directly constructed programs whose event topology does - // not list every kernel, after the semantic IDs used by trigger code. - let mut extra: Vec<_> = program - .sir - .eval_apply_ffs - .keys() - .chain(program.sir.eval_only_ffs.keys()) - .chain(program.sir.apply_ffs.keys()) - .map(|address| program.design.events.canonical(*address)) - .filter(|address| seen.insert(*address)) - .collect(); - extra.sort_unstable(); - addresses.extend(extra); + let addresses = crate::edge_plans::event_addresses(program); let ids = addresses .iter() .copied() diff --git a/crates/celox/src/edge_plans.rs b/crates/celox/src/edge_plans.rs new file mode 100644 index 00000000000..61c75ff3261 --- /dev/null +++ b/crates/celox/src/edge_plans.rs @@ -0,0 +1,137 @@ +//! Derived-domain plans for hosts that run WebAssembly kernels themselves. +//! +//! The browser and WASI runtime of the TypeScript package drives one +//! WebAssembly module per event. To tick and move clocks exactly as +//! `Simulator` does, it needs the same build-time plans: for each event, its +//! signal and polarity, the clocks computed combinationally from it and the +//! domains clocked from state it writes. This module describes them by event +//! name and memory offset, as JSON. + +use std::collections::BTreeMap; + +use celox_design::DomainKind; +use serde::Serialize; + +use crate::ir::{AbsoluteAddr, LaidOutProgram}; + +/// A one-bit event signal in the packed memory layout. +#[derive(Clone, Copy, Debug, Serialize)] +pub struct EdgePlanSignal { + /// Byte offset of the value; a four-state signal's unknown mask follows + /// it in the next byte. + pub offset: usize, + pub width: usize, +} + +/// A derived event domain. +#[derive(Clone, Debug, Serialize)] +pub struct EdgePlanDomain { + /// The event name its kernel is compiled under. + pub event: String, + pub signal: EdgePlanSignal, + /// `"posedge"`, `"negedge"`, or `"any"` for a domain of unknown kind. + pub edge: &'static str, +} + +/// What an edge of one event runs besides the event's own domain. +#[derive(Clone, Debug, Serialize)] +pub struct EdgePlanEvent { + pub signal: EdgePlanSignal, + /// `"posedge"`, `"negedge"`, or `"any"`. + pub edge: &'static str, + /// Combinational logic reads the event's signal. + #[serde(rename = "combRead")] + pub comb_read: bool, + /// Domains clocked from state the event's domain writes, transitively. + pub domains: Vec, + /// Clocks computed combinationally from the event's signal. + pub gated: Vec, +} + +/// Per event name, its edge plan. +#[derive(Clone, Debug, Serialize)] +pub struct EdgePlans { + #[serde(rename = "fourState")] + pub four_state: bool, + pub events: BTreeMap, +} + +fn edge_name(kind: Option) -> &'static str { + match kind { + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => "posedge", + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => "negedge", + _ => "any", + } +} + +/// The canonical event domains of `program` in the order every execution +/// engine numbers them: the semantic event order, then any kernel the event +/// topology does not list. An event need not have a kernel of its own: a +/// clock that only drives a gated clock is one. +pub fn event_addresses(program: &LaidOutProgram) -> Vec { + let mut addresses = program.design.events.ordered_events.clone(); + let mut seen: crate::HashSet<_> = addresses.iter().copied().collect(); + // Preserve legacy/directly constructed programs whose event topology does + // not list every kernel, after the semantic IDs used by trigger code. + let mut extra: Vec<_> = program + .sir + .eval_apply_ffs + .keys() + .chain(program.sir.eval_only_ffs.keys()) + .chain(program.sir.apply_ffs.keys()) + .map(|address| program.design.events.canonical(*address)) + .filter(|address| seen.insert(*address)) + .collect(); + extra.sort_unstable(); + addresses.extend(extra); + addresses +} + +/// The edge plans of `program`'s events, named as [`event_addresses`] and +/// `program.get_path` name them. +pub fn edge_plans(program: &LaidOutProgram) -> EdgePlans { + let layout = program.layout(); + let events = &program.design.events; + let kinds = program.design.event_kinds(); + let signal = |address: &AbsoluteAddr| EdgePlanSignal { + offset: layout.offsets.get(address).copied().unwrap_or_default(), + width: layout.widths.get(address).copied().unwrap_or(1), + }; + let domain = |address: &AbsoluteAddr| EdgePlanDomain { + event: program.get_path(address), + signal: signal(address), + edge: edge_name(kinds.get(address).copied()), + }; + let plans = event_addresses(program) + .iter() + .map(|address| { + let canonical = events.canonical(*address); + let plan = EdgePlanEvent { + signal: signal(&canonical), + edge: edge_name(kinds.get(&canonical).copied()), + comb_read: events.combinationally_read.contains(&canonical), + domains: events + .derived_events + .get(&canonical) + .into_iter() + .flatten() + .filter(|target| program.sir.eval_apply_ffs.contains_key(target)) + .map(domain) + .collect(), + gated: events + .combinational_derived + .get(&canonical) + .into_iter() + .flatten() + .filter(|derived| program.sir.eval_apply_ffs.contains_key(&derived.clock)) + .map(|derived| domain(&derived.clock)) + .collect(), + }; + (program.get_path(address), plan) + }) + .collect(); + EdgePlans { + four_state: layout.four_state, + events: plans, + } +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 5ca35239a4c..9850c2b6b88 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -10,6 +10,10 @@ pub use component::{ register_static_component_manifest, }; mod debug; +mod edge_plans; +pub use edge_plans::{ + EdgePlanDomain, EdgePlanEvent, EdgePlanSignal, EdgePlans, edge_plans, event_addresses, +}; mod diagnostics; // Without a host runtime nothing builds simulators, so nothing links DPI-C. #[cfg_attr(not(feature = "host-runtime"), allow(dead_code))] @@ -98,8 +102,9 @@ mod host_api { pub use crate::testbench::{AssertionResult, SourceLocation, TestResult, TestResultDetailed}; pub use celox_macros::veryl_test; pub use celox_runtime::{ - BackendExecutor, DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, VcdSignalDesc, - VcdStatistics, VcdWriter, + BackendExecutor, DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, Edge, EdgeOutcome, + EventEdge, EventEdges, Halt, SignalWrite, VcdSignalDesc, VcdStatistics, VcdWriter, + move_signal, run_edge, run_edges, set_level, }; pub struct IOContext<'a, B: SimBackend = DefaultBackend> { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index a0de63be95b..89a6a8bf859 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -136,6 +136,8 @@ mod host { /// Whether a timed simulation runs the design and it has a `$finish` /// runtime event site. pub(crate) finish_sites: bool, + /// Per event ID, its signal and polarity for explicit edges. + event_edges: celox_runtime::EventEdges, } /// Why [`Simulator::try_dump`] failed. @@ -704,6 +706,8 @@ mod host { ); let (derived_ticks, derived_scratch) = celox_runtime::build_derived_tick_plans(&backend, &schedule); + let event_edges = + celox_runtime::build_event_edges(&backend, &schedule.events, &schedule.kinds); let mut sim = Self { backend, program, @@ -730,6 +734,7 @@ mod host { host_watch: Default::default(), finish_scan_seq: 0, finish_sites: false, + event_edges, }; sim.comb_observer_snapshots = sim.snapshot_all_comb_observers(); sim @@ -1434,6 +1439,192 @@ mod host { Ok(()) } + /// Move `event`'s signal through `edge` and run every domain + /// sensitive to that transition, as a timed step does: the event's own + /// domain when `edge` is its active edge, clocks computed + /// combinationally from the signal that see their active edge (judged + /// from the state before the edge, evaluating with the event's own + /// domain), and, after the commit, gates the commit moves and domains + /// clocked from state, transitively. The signal stays at its new + /// level. An edge to the level the signal already has does nothing. + /// + /// An unknown (X) level counts as either level, as in SystemVerilog. + pub fn edge( + &mut self, + event: B::Event, + edge: celox_runtime::Edge, + ) -> Result<(), RuntimeErrorCode> { + // A timed simulation the design finished no longer changes. + if self.frozen { + return Ok(()); + } + let info = self.event_edges[event.id()]; + if !matches!(self.derived_ticks.get(event.id()), Some(Some(_))) { + if !info.can_fire(edge) && self.host_watch.is_empty() { + // An inactive edge runs nothing, whatever the level was: + // 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. + self.backend.set(info.signal, edge.level()); + if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + return Ok(()); + } + // No derived domains: move the signal, then run the event's + // domain exactly as `tick` does. + let write = watched_write(&mut self.host_watch); + let Some(old) = celox_runtime::move_signal(&mut self.backend, &info, edge, write) + else { + return Ok(()); + }; + if info.comb_read { + self.dirty = true; + } + if info.fires(old, edge) { + return self.tick(event); + } + if !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + return Ok(()); + } + let plans = std::sync::Arc::clone(&self.derived_ticks); + let plan = plans.get(event.id()).and_then(Option::as_ref); + let mut scratch = self.derived_scratch.take().unwrap_or_default(); + let mut watch = std::mem::take(&mut self.host_watch); + let dirty = self.dirty; + let write = watched_write(&mut watch); + let result = + celox_runtime::run_edge(self, plan, info, &mut scratch, event, edge, dirty, write); + self.host_watch = watch; + self.derived_scratch = Some(scratch); + self.note_edge(result) + } + + fn note_edge( + &mut self, + outcome: Result, + ) -> Result<(), RuntimeErrorCode> { + match outcome { + Ok(celox_runtime::EdgeOutcome::Unchanged) => {} + Ok(celox_runtime::EdgeOutcome::Moved) => self.dirty = true, + // Combinational logic does not read the signal; observers + // still see its new level at their next evaluation. + Ok(celox_runtime::EdgeOutcome::Stored) => { + if !self.program.runtime_schema.comb_observers.is_empty() { + self.dirty = true; + } + } + Ok(celox_runtime::EdgeOutcome::Settled) => self.dirty = false, + // An RTL `$finish` ends only a timed simulation; an edge, as a + // tick, leaves it to the host. What ran may not have settled. + Err(celox_runtime::Halt::Finish) => self.dirty = true, + Err(celox_runtime::Halt::Error(error)) => return Err(error), + } + Ok(()) + } + + /// A rising edge of `event`'s signal; see [`Self::edge`]. + pub fn posedge(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + self.edge(event, celox_runtime::Edge::Rising) + } + + /// A falling edge of `event`'s signal; see [`Self::edge`]. + pub fn negedge(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + self.edge(event, celox_runtime::Edge::Falling) + } + + /// The event's active edge (rising for a positive-edge clock or an + /// active-high reset, falling otherwise); see [`Self::edge`]. + pub fn active_edge(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + let edge = self.event_edges[event.id()].active_edge(); + self.edge(event, edge) + } + + /// The edge opposite to the event's active edge; see [`Self::edge`]. + pub fn inactive_edge(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + let edge = match self.event_edges[event.id()].active_edge() { + celox_runtime::Edge::Rising => celox_runtime::Edge::Falling, + celox_runtime::Edge::Falling => celox_runtime::Edge::Rising, + }; + 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 + /// [`Self::edge`] follow. + pub fn edges( + &mut self, + moves: &[(B::Event, celox_runtime::Edge)], + ) -> Result<(), RuntimeErrorCode> { + if self.frozen { + return Ok(()); + } + let plans = std::sync::Arc::clone(&self.derived_ticks); + let edges = std::sync::Arc::clone(&self.event_edges); + let mut scratch = self.derived_scratch.take().unwrap_or_default(); + let mut watch = std::mem::take(&mut self.host_watch); + let dirty = self.dirty; + let write = watched_write(&mut watch); + let result = + celox_runtime::run_edges(self, &plans, &edges, &mut scratch, moves, dirty, write); + self.host_watch = watch; + self.derived_scratch = Some(scratch); + self.note_edge(result) + } + + /// Per event ID, its signal and polarity, for hosts that drive the + /// backend without this facade. + pub fn event_edges(&self) -> celox_runtime::EventEdges { + std::sync::Arc::clone(&self.event_edges) + } + /// Per event ID, the derived clock domains a tick of the event can /// trigger, for hosts that drive the backend without this facade. /// Empty when the design has no derived clocks. @@ -2223,10 +2414,110 @@ mod host { } } + /// The host's write of an event signal's level, observed by a timed + /// simulation's waits and counters as [`IOContext`] writes are. + fn watched_write( + watch: &mut celox_runtime::HostWatch, + ) -> impl FnMut(&mut B, SignalRef, u8) + '_ { + move |backend, signal, level| { + if watch.is_empty() { + backend.set(signal, level); + } else { + watch.write(backend, signal, |backend| backend.set(signal, level)); + } + } + } + #[cfg(test)] mod tests { use super::*; + const GATED_COUNTER: &str = "module Top (clk: input clock, en: input logic, count: output logic<8>, plain: output logic<8>) { + let gated: '_ clock = clk & en; + always_ff (gated) { count += 1; } + always_ff (clk) { plain += 1; } + }"; + + #[test] + fn edges_leave_a_finished_simulation_unchanged() { + let mut sim = Simulator::builder(GATED_COUNTER, "Top").build().unwrap(); + let (clk, en) = (sim.event("clk"), sim.signal("en")); + sim.modify(|io| io.set(en, 1u8)).unwrap(); + sim.posedge(clk).unwrap(); + let (count, plain) = (sim.signal("count"), sim.signal("plain")); + assert_eq!(sim.get(count), BigUint::from(1u8)); + sim.negedge(clk).unwrap(); + sim.frozen = true; + sim.posedge(clk).unwrap(); + sim.edges(&[(clk, celox_runtime::Edge::Rising)]).unwrap(); + sim.cycle(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)); + assert_eq!(sim.get(plain), BigUint::from(1u8)); + } + + #[test] + fn edges_write_the_clock_through_the_host_watch() { + for design in [ + GATED_COUNTER, + "module Top (clk: input clock, plain: output logic<8>) { + always_ff (clk) { plain += 1; } + }", + ] { + let mut sim = Simulator::builder(design, "Top").build().unwrap(); + let clk = sim.event("clk"); + let clk_signal = sim.signal("clk"); + let waited = [clk_signal.offset].into_iter().collect(); + sim.host_watch = celox_runtime::HostWatch::new([], waited); + sim.posedge(clk).unwrap(); + sim.edges(&[(clk, celox_runtime::Edge::Falling)]).unwrap(); + // Already low: no write to observe. + sim.negedge(clk).unwrap(); + let levels: Vec<_> = sim + .host_watch + .log() + .iter() + .map(|(signal, (value, _))| (signal.offset, value.clone())) + .collect(); + assert_eq!( + levels, + [ + (clk_signal.offset, BigUint::from(1u8)), + (clk_signal.offset, BigUint::from(0u8)), + ], + "{design}" + ); + } + } + + #[test] + fn edges_that_run_nothing_leave_comb_stale_only_when_comb_reads_the_clock() { + for (seen, comb_read) in [("1'b1", false), ("clk", true)] { + let source = format!( + "module Top (clk: input clock, count: output logic<8>, seen: output logic) {{ + always_ff (clk) {{ count += 1; }} + assign seen = {seen}; + }}" + ); + let mut sim = Simulator::builder(&source, "Top").build().unwrap(); + let clk = sim.event("clk"); + sim.posedge(clk).unwrap(); + assert!(!sim.dirty); + // Moving `clk` without running a domain leaves combinational + // logic stale only when it reads `clk`. + sim.negedge(clk).unwrap(); + assert_eq!(sim.dirty, comb_read, "{seen}"); + sim.cycle(clk).unwrap(); + assert_eq!(sim.dirty, comb_read, "{seen}"); + let seen_signal = sim.signal("seen"); + let expected = if comb_read { 0u8 } else { 1 }; + assert_eq!(sim.get(seen_signal), BigUint::from(expected)); + let count = sim.signal("count"); + assert_eq!(sim.get(count), BigUint::from(2u8)); + } + } + #[test] fn comb_fatal_records_do_not_mask_unrelated_backend_errors() { let mut sim = Simulator::builder( diff --git a/crates/celox/tests/edge_api.rs b/crates/celox/tests/edge_api.rs new file mode 100644 index 00000000000..20ee1eca805 --- /dev/null +++ b/crates/celox/tests/edge_api.rs @@ -0,0 +1,356 @@ +//! Explicit edges: `posedge`, `negedge`, `active_edge`, `inactive_edge`, +//! `cycle` 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); + fn edges(&mut self, moves: &[(&str, Edge)]); + fn set(&mut self, name: &str, value: u8); + fn get(&mut self, name: &str) -> u64; +} + +impl Probe for Simulator { + fn edge(&mut self, event: &str, edge: Edge) { + 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(); + } + fn inactive_edge(&mut self, event: &str) { + let event = self.event(event); + Simulator::inactive_edge(self, event).unwrap(); + } + fn tick(&mut self, event: &str) { + let event = self.event(event); + Simulator::tick(self, event).unwrap(); + } + fn edges(&mut self, moves: &[(&str, Edge)]) { + let moves: Vec<_> = moves + .iter() + .map(|&(event, edge)| (self.event(event), edge)) + .collect(); + Simulator::edges(self, &moves).unwrap(); + } + fn set(&mut self, name: &str, value: u8) { + let signal = self.signal(name); + self.modify(|io| io.set(signal, value)).unwrap(); + } + fn get(&mut self, name: &str) -> u64 { + let signal = self.signal(name); + Simulator::get(self, signal).try_into().unwrap() + } +} + +/// Build `source` on every backend, in both state modes. +fn backends( + source: &'static str, + configure: impl Fn(SimulatorBuilder<'static, Simulator>) -> SimulatorBuilder<'static, Simulator>, +) -> Vec<(String, Box)> { + let mut built: Vec<(String, Box)> = Vec::new(); + for four_state in [false, true] { + let build = || configure(Simulator::builder(source, "Top").four_state(four_state)); + let name = |backend: &str| format!("{backend}, four_state={four_state}"); + built.push(( + name("interp"), + Box::new(build().build_interpreter().unwrap()), + )); + built.push(( + name("cranelift"), + Box::new(build().build_cranelift().unwrap()), + )); + built.push((name("wasm"), Box::new(build().build_wasm().unwrap()))); + built.push((name("tiered"), Box::new(build().build_tiered().unwrap()))); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + built.push((name("native"), Box::new(build().build_native().unwrap()))); + } + built +} + +/// Assert the reset, then release it, with explicit edges. +fn reset(sim: &mut dyn Probe) { + sim.edge("rst", Edge::Rising); + sim.edge("rst", Edge::Falling); + sim.edge("rst", Edge::Rising); +} + +const COUNTERS: &str = r#" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + en: input logic, + rising: output logic<8>, + falling: output logic<8>, + gated_falling: output logic<8>, +) { + var r: logic<8>; + var f: logic<8>; + var g: logic<8>; + always_ff (clk, rst) { if_reset { r = 0; } else { r = r + 8'd1; } } + let inverted: '_ clock = ~clk; + always_ff (inverted, rst) { if_reset { f = 0; } else { f = f + 8'd1; } } + let gated: '_ clock = ~(clk & en); + always_ff (gated, rst) { if_reset { g = 0; } else { g = g + 8'd1; } } + assign rising = r; + assign falling = f; + assign gated_falling = g; +} +"#; + +fn counters(sim: &mut dyn Probe) -> [u64; 3] { + [ + sim.get("rising"), + sim.get("falling"), + sim.get("gated_falling"), + ] +} + +/// `posedge` runs the rising domain, `negedge` the domains of `~clk` and of +/// a falling `clk & en`; an edge to the level the clock already has does +/// nothing. +#[test] +fn edges_run_the_domains_of_their_direction() { + for (backend, mut sim) in backends(COUNTERS, |builder| builder) { + let sim = sim.as_mut(); + sim.set("en", 1); + sim.edge("clk", Edge::Falling); + reset(sim); + assert_eq!(counters(sim), [0, 0, 0], "{backend}: reset"); + sim.edge("clk", Edge::Rising); + assert_eq!(counters(sim), [1, 0, 0], "{backend}: posedge"); + sim.edge("clk", Edge::Rising); + assert_eq!(counters(sim), [1, 0, 0], "{backend}: no second posedge"); + sim.edge("clk", Edge::Falling); + assert_eq!(counters(sim), [1, 1, 1], "{backend}: negedge"); + sim.set("en", 0); + sim.cycle("clk"); + assert_eq!(counters(sim), [2, 2, 1], "{backend}: closed gate"); + // A tick is the active edge only and leaves the clock low. + sim.tick("clk"); + assert_eq!(counters(sim), [3, 2, 1], "{backend}: tick"); + assert_eq!(sim.get("clk"), 0, "{backend}: tick leaves clk"); + } +} + +/// With the abstract `clock` type, the active edge follows the build's clock +/// type. +#[test] +fn abstract_clocks_follow_the_clock_type() { + const CODE: &str = r#" +module Top (clk: input clock, rst: input reset_async_low, q: output logic<8>) { + var r: logic<8>; + always_ff (clk, rst) { if_reset { r = 0; } else { r = r + 8'd1; } } + assign q = r; +} +"#; + for (clock_type, active, inactive) in [ + (ClockType::PosEdge, Edge::Rising, Edge::Falling), + (ClockType::NegEdge, Edge::Falling, Edge::Rising), + ] { + for (backend, mut sim) in backends(CODE, |builder| builder.clock_type(clock_type)) { + let sim = sim.as_mut(); + sim.edge("clk", inactive); + reset(sim); + assert_eq!(sim.get("q"), 0, "{backend}: {clock_type:?} reset"); + sim.active_edge("clk"); + assert_eq!(sim.get("q"), 1, "{backend}: {clock_type:?} active"); + sim.inactive_edge("clk"); + 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"); + 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"); + } + } +} + +/// `cycle` runs a clock cycle 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() { + const CODE: &str = r#" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + en_in: input logic, + observed: output logic<64>, +) { + var a: logic<8>; + var en: logic; + var b: logic<8>; + var d: logic<8>; + var half: logic; + var quarter: logic; + var q: logic<8>; + always_ff (clk, rst) { + if_reset { a = 0; en = 1; half = 0; } else { a = a + 8'd1; en = en_in; half = ~half; } + } + let gated: '_ clock = clk & en; + always_ff (gated, rst) { if_reset { b = 0; } else { b = b + a; } } + let inverted: '_ clock = ~clk; + always_ff (inverted, rst) { if_reset { d = 0; } else { d = a ^ b; } } + let half_clk: '_ clock = half; + always_ff (half_clk, rst) { if_reset { quarter = 0; } else { quarter = ~quarter; } } + let quarter_clk: '_ clock = quarter; + always_ff (quarter_clk, rst) { if_reset { q = 0; } else { q = q + d; } } + assign observed = {a, b, d, q, 7'd0, en, 7'd0, half, 7'd0, quarter, 8'd0}; +} +"#; + const ENABLES: [u8; 12] = [1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0]; + let mut timed = Simulation::builder(CODE, "Top").build().unwrap(); + let observed = timed.signal("observed"); + let en_in = timed.signal("en_in"); + for (port, time, value) in [("clk", 0, 0), ("rst", 0, 1), ("rst", 1, 0), ("rst", 2, 1)] { + timed.schedule(port, time, value).unwrap(); + timed.step().unwrap(); + } + let mut expected = Vec::new(); + for (cycle, &enable) in ENABLES.iter().enumerate() { + let time = 10 + cycle as u64 * 20; + timed.modify(|io| io.set(en_in, enable)).unwrap(); + timed.schedule("clk", time, 1).unwrap(); + timed.step().unwrap(); + timed.schedule("clk", time + 10, 0).unwrap(); + timed.step().unwrap(); + expected.push(u64::try_from(timed.get(observed)).unwrap()); + } + + for (backend, mut sim) in backends(CODE, |builder| builder) { + let sim = sim.as_mut(); + sim.edge("clk", Edge::Falling); + reset(sim); + let observed: Vec = ENABLES + .iter() + .map(|&enable| { + sim.set("en_in", enable); + sim.cycle("clk"); + sim.get("observed") + }) + .collect(); + assert_eq!(observed, expected, "{backend}"); + } +} + +/// Coincident edges evaluate every sensitive domain against the state +/// before them. +#[test] +fn coincident_edges_sample_the_state_before_them() { + const CODE: &str = r#" +module Top (a_clk: input '_ clock, b_clk: input '_ clock, rst: input '_ reset_async_low, + a: output logic<8>, b: output logic<8>) { + var ra: logic<8>; + var rb: logic<8>; + always_ff (a_clk, rst) { if_reset { ra = 3; } else { ra = rb + 8'd1; } } + always_ff (b_clk, rst) { if_reset { rb = 5; } else { rb = ra + 8'd2; } } + assign a = ra; + assign b = rb; +} +"#; + for (backend, mut sim) in backends(CODE, |builder| builder) { + let sim = sim.as_mut(); + sim.edges(&[("a_clk", Edge::Falling), ("b_clk", Edge::Falling)]); + reset(sim); + sim.edges(&[("a_clk", Edge::Rising), ("b_clk", Edge::Rising)]); + assert_eq!(sim.get("a"), 6, "{backend}: a reads b before the edge"); + assert_eq!(sim.get("b"), 5, "{backend}: b reads a before the edge"); + } +} + +/// SystemVerilog: a register on `posedge clk` and one on `negedge` of a copy +/// of `clk` run on the matching edges, in a tick-free and a timed run. +#[cfg(feature = "systemverilog")] +#[test] +fn systemverilog_posedge_and_negedge_on_one_clock() { + let source = "module Top(input logic clk, input logic rst_n, output logic [7:0] p, n); + logic c2; + assign c2 = clk; + always_ff @(posedge clk or negedge rst_n) if (!rst_n) p <= 0; else p <= p + 1; + always_ff @(negedge c2 or negedge rst_n) if (!rst_n) n <= 0; else n <= n + 1; + endmodule"; + let path = std::path::Path::new("edges.sv"); + for four_state in [false, true] { + let mut sim = Simulator::from_sv_sources(vec![(source, path)], "Top") + .four_state(four_state) + .build() + .unwrap(); + let sim: &mut dyn Probe = &mut sim; + sim.edge("clk", Edge::Falling); + sim.edge("rst_n", Edge::Rising); + sim.edge("rst_n", Edge::Falling); + sim.edge("rst_n", Edge::Rising); + sim.edge("clk", Edge::Rising); + assert_eq!([sim.get("p"), sim.get("n")], [1, 0]); + sim.edge("clk", Edge::Falling); + assert_eq!([sim.get("p"), sim.get("n")], [1, 1]); + } + + let mut timed = Simulation::from_sv_sources(vec![(source, path)], "Top") + .build() + .unwrap(); + timed.schedule("rst_n", 0, 0).unwrap(); + timed.schedule("clk", 0, 0).unwrap(); + timed.step().unwrap(); + timed.schedule("rst_n", 1, 1).unwrap(); + timed.step().unwrap(); + timed.add_clock("clk", 10, 5); + timed.run_until(42).unwrap(); + let p = timed.signal("p"); + let n = timed.signal("n"); + assert_eq!(timed.get(p), 4u8.into(), "rising edges at 5, 15, 25, 35"); + assert_eq!(timed.get(n), 4u8.into(), "falling edges at 10, 20, 30, 40"); +} + +/// The edge plans that WASM hosts run name every derived domain of an event +/// by its kernel's event name. +#[test] +fn edge_plans_describe_derived_domains_by_event_name() { + let path = std::path::Path::new("counters.veryl"); + let (program, _) = celox::compile_to_sir( + &[(COUNTERS, path)], + "Top", + &[], + &[], + false, + &Default::default(), + None, + None, + None, + None, + &[], + &Default::default(), + ) + .unwrap(); + let plans = celox::edge_plans(&program.into_laid_out(false)); + let clk = &plans.events["clk"]; + assert_eq!(clk.edge, "posedge"); + let mut gated: Vec<_> = clk + .gated + .iter() + .map(|domain| domain.event.as_str()) + .collect(); + gated.sort_unstable(); + assert_eq!(gated, ["gated", "inverted"]); + assert!( + clk.gated + .iter() + .all(|domain| plans.events.contains_key(&domain.event)) + ); + assert!(clk.comb_read); + let json = serde_json::to_value(&plans).unwrap(); + assert_eq!(json["events"]["clk"]["combRead"], true); +} diff --git a/crates/celox/tests/flip_flop.rs b/crates/celox/tests/flip_flop.rs index bb4bff750a7..573ade5e492 100644 --- a/crates/celox/tests/flip_flop.rs +++ b/crates/celox/tests/flip_flop.rs @@ -5376,10 +5376,6 @@ fn test_ff_register_gated_clock_uses_the_pre_edge_enable(sim) { } fn test_ff_inverted_clock_samples_after_the_rising_edge(sim) { - // The suite pulses a clock for each `tick`: `~clk` rises on its return. - // Celox's harness drives `Simulator::tick`, which is the active edge of - // `clk` only, so `~clk` never rises there. - @ignore_on(native, cranelift, wasm, interp, sv); @case "flip_flop::test_ff_inverted_clock_samples_after_the_rising_edge"; } diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index 7c90eb8dde2..6314b8e056f 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -198,7 +198,20 @@ impl Backend for CeloxBackend { } fn tick(&mut self, event: &str) -> Result<()> { - self.0.tick(self.0.event(event)).map_err(Into::into) + // The suite pulses the port as the external testbenches do: to its + // inactive level, to its active level, and back unless it was active. + let handle = self.0.event(event); + let signal = self.0.signal(event); + let active = self.0.event_edges()[celox::EventHandle::id(&handle)].active_edge(); + let (value, mask) = self.0.get_four_state(signal); + let zero = celox::BigUint::default(); + let was_active = mask == zero && (value != zero) == (active == celox::Edge::Rising); + self.0.inactive_edge(handle)?; + self.0.active_edge(handle)?; + if !was_active { + self.0.inactive_edge(handle)?; + } + Ok(()) } fn take_output(&mut self) -> Result> { diff --git a/crates/celox/tests/test_utils/suite.rs b/crates/celox/tests/test_utils/suite.rs index 586e7f2c18d..daa7d61dbc7 100644 --- a/crates/celox/tests/test_utils/suite.rs +++ b/crates/celox/tests/test_utils/suite.rs @@ -46,7 +46,20 @@ impl Backend for CeloxBackend { } fn tick(&mut self, event: &str) -> Result<()> { - self.0.tick(self.0.event(event)).map_err(Into::into) + // The suite pulses the port as the external testbenches do: to its + // inactive level, to its active level, and back unless it was active. + let handle = self.0.event(event); + let signal = self.0.signal(event); + let active = self.0.event_edges()[celox::EventHandle::id(&handle)].active_edge(); + let (value, mask) = self.0.get_four_state(signal); + let was_active = mask == BigUint::default() + && (value != BigUint::default()) == (active == celox::Edge::Rising); + self.0.inactive_edge(handle)?; + self.0.active_edge(handle)?; + if !was_active { + self.0.inactive_edge(handle)?; + } + Ok(()) } } diff --git a/docs/guide/writing-tests.md b/docs/guide/writing-tests.md index 53ee498b4f3..986ac088860 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -63,6 +63,41 @@ module Reg ( For purely combinational modules (`always_comb` only), `tick()` is not required. Reading an output automatically evaluates the combinational logic with the current inputs. ::: +### 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: + +```typescript +const clk = sim.event("clk"); + +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([ + [clk, "posedge"], + [sim.event("clk_b"), "posedge"], +]); +``` + +An edge moves the clock signal and leaves it at its new level, so it can be +read through `sim.dut`. An edge to the level the signal already has does +nothing. Each edge runs the domains a timed simulation would run at that +transition: the clock's own domain on its active edge, clocks computed from +it (`clk & en`, `~clk`) that see their active edge, sampling the state from +before the edge, and the domains that the resulting updates clock in turn. For +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. + ## Time-Based Simulation `Simulation` manages clock generation for you. This is the natural choice for sequential logic with clocked flip-flops. diff --git a/docs/internals/cascade-limitations.md b/docs/internals/cascade-limitations.md index 95a74d12d0b..af32fc922d7 100644 --- a/docs/internals/cascade-limitations.md +++ b/docs/internals/cascade-limitations.md @@ -112,6 +112,14 @@ 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. + 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 cone allows: judging a gate then reads only the state it depends on instead of diff --git a/flake.nix b/flake.nix index 57d2e9dc529..1e3aa08a30b 100644 --- a/flake.nix +++ b/flake.nix @@ -45,7 +45,10 @@ "rust-analyzer" ] ); - targets = pkgs.lib.unique ((toolchain.targets or [ ]) ++ [ "wasm32-unknown-unknown" ]); + targets = pkgs.lib.unique ((toolchain.targets or [ ]) ++ [ + "wasm32-unknown-unknown" + "wasm32-wasip1-threads" + ]); }; mbx = nix-packages.packages.${system}.mbx; mergify-cli = pkgs.callPackage ./nix/mergify-cli.nix { }; diff --git a/packages/celox/package.json b/packages/celox/package.json index 103b2982a00..58cee5e097a 100644 --- a/packages/celox/package.json +++ b/packages/celox/package.json @@ -9,6 +9,10 @@ ".": { "import": "./dist/index.js", "types": "./dist/index.d.ts" + }, + "./wasm-edges": { + "import": "./dist/wasm-edges.js", + "types": "./dist/wasm-edges.d.ts" } }, "files": [ diff --git a/packages/celox/src/index.ts b/packages/celox/src/index.ts index efbc9a9d555..3130ff6815b 100644 --- a/packages/celox/src/index.ts +++ b/packages/celox/src/index.ts @@ -62,6 +62,7 @@ export { // Core types /** @internal */ export type { + ClockEdge, CreateResult, EventHandle, FourStateSignalValue, diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index 240513de9a3..05a36935464 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -814,6 +814,12 @@ export function wrapDirectSimulatorHandle( tickN(eventId: number, count: number): void { raw.tickN(eventId, count); }, + ...(raw.edges && raw.activeEdgeIsRising + ? { + edges: raw.edges.bind(raw), + activeEdgeIsRising: raw.activeEdgeIsRising.bind(raw), + } + : {}), evalComb(): void { raw.evalComb(); }, diff --git a/packages/celox/src/simulator-edges-addon.test.ts b/packages/celox/src/simulator-edges-addon.test.ts new file mode 100644 index 00000000000..553bbe1df41 --- /dev/null +++ b/packages/celox/src/simulator-edges-addon.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, test } from "vitest"; +import { Simulation } from "./simulation.js"; +import { Simulator } from "./simulator.js"; + +const COUNTERS = ` +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + en: input logic, + rising: output logic<8>, + falling: output logic<8>, + gated_falling: output logic<8>, +) { + var r: logic<8>; + var f: logic<8>; + var g: logic<8>; + always_ff (clk, rst) { if_reset { r = 0; } else { r = r + 8'd1; } } + let inverted: '_ clock = ~clk; + always_ff (inverted, rst) { if_reset { f = 0; } else { f = f + 8'd1; } } + let gated: '_ clock = ~(clk & en); + always_ff (gated, rst) { if_reset { g = 0; } else { g = g + 8'd1; } } + assign rising = r; + assign falling = f; + assign gated_falling = g; +} +`; + +type Counters = { + en: bigint; + rising: bigint; + falling: bigint; + gated_falling: bigint; +}; + +function reset(sim: Simulator): void { + const rst = sim.event("rst"); + sim.posedge(rst); + sim.negedge(rst); + sim.posedge(rst); +} + +describe("explicit clock edges", () => { + for (const tier of [undefined, "tiered"] as const) { + test(`posedge and negedge run the domains of their direction (${tier ?? "default"})`, () => { + const sim = Simulator.fromSource( + COUNTERS, + "Top", + tier ? { tier: true } : undefined, + ); + try { + const clk = sim.event("clk"); + const counters = () => [ + sim.dut.rising, + sim.dut.falling, + sim.dut.gated_falling, + ]; + sim.dut.en = 1n; + sim.negedge(clk); + reset(sim); + expect(counters()).toEqual([0n, 0n, 0n]); + sim.posedge(clk); + expect(counters()).toEqual([1n, 0n, 0n]); + sim.posedge(clk); + expect(counters()).toEqual([1n, 0n, 0n]); + sim.negedge(clk); + expect(counters()).toEqual([1n, 1n, 1n]); + sim.dut.en = 0n; + sim.cycle(clk); + expect(counters()).toEqual([2n, 2n, 1n]); + sim.tick(clk); + expect(counters()).toEqual([3n, 2n, 1n]); + } finally { + sim.dispose(); + } + }); + } + + for (const clockType of ["posedge", "negedge"] as const) { + test(`active edges follow the ${clockType} clock type`, () => { + const sim = Simulator.fromSource<{ q: bigint }>( + `module Top (clk: input clock, rst: input reset_async_low, q: output logic<8>) { + var r: logic<8>; + always_ff (clk, rst) { if_reset { r = 0; } else { r = r + 8'd1; } } + assign q = r; +}`, + "Top", + { clockType }, + ); + try { + const clk = sim.event("clk"); + sim.inactiveEdge(clk); + reset(sim); + sim.activeEdge(clk); + expect(sim.dut.q).toBe(1n); + sim.inactiveEdge(clk); + expect(sim.dut.q).toBe(1n); + if (clockType === "posedge") { + sim.posedge(clk); + } else { + sim.negedge(clk); + } + expect(sim.dut.q).toBe(2n); + } finally { + sim.dispose(); + } + }); + } + + test("a cycle matches two timed steps", () => { + const source = ` +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + en_in: input logic, + a_out: output logic<8>, + b_out: output logic<8>, + d_out: output logic<8>, +) { + var a: logic<8>; + var en: logic; + var b: logic<8>; + var d: logic<8>; + always_ff (clk, rst) { if_reset { a = 0; en = 1; } else { a = a + 8'd1; en = en_in; } } + let gated: '_ clock = clk & en; + always_ff (gated, rst) { if_reset { b = 0; } else { b = b + a; } } + let inverted: '_ clock = ~clk; + always_ff (inverted, rst) { if_reset { d = 0; } else { d = a ^ b; } } + assign a_out = a; + assign b_out = b; + assign d_out = d; +} +`; + type Ports = { en_in: bigint; a_out: bigint; b_out: bigint; d_out: bigint }; + const enables = [1n, 0n, 1n, 1n, 0n, 0n, 1n, 0n]; + const timed = Simulation.fromSource(source, "Top"); + const expected: bigint[][] = []; + try { + timed.schedule("clk", { time: 0, value: 0 }); + timed.schedule("rst", { time: 0, value: 1 }); + timed.schedule("rst", { time: 1, value: 0 }); + timed.schedule("rst", { time: 2, value: 1 }); + timed.runUntil(2); + enables.forEach((enable, cycle) => { + timed.dut.en_in = enable; + timed.schedule("clk", { time: 10 + cycle * 20, value: 1 }); + timed.schedule("clk", { time: 20 + cycle * 20, value: 0 }); + timed.runUntil(20 + cycle * 20); + expected.push([timed.dut.a_out, timed.dut.b_out, timed.dut.d_out]); + }); + } finally { + timed.dispose(); + } + + const sim = Simulator.fromSource(source, "Top"); + try { + const clk = sim.event("clk"); + sim.negedge(clk); + reset(sim); + const observed = enables.map((enable) => { + sim.dut.en_in = enable; + sim.cycle(clk); + return [sim.dut.a_out, sim.dut.b_out, sim.dut.d_out]; + }); + expect(observed).toEqual(expected); + } finally { + sim.dispose(); + } + }); + + test("coincident edges sample the state before them", () => { + const sim = Simulator.fromSource<{ a: bigint; b: bigint }>( + `module Top (a_clk: input '_ clock, b_clk: input '_ clock, rst: input '_ reset_async_low, + a: output logic<8>, b: output logic<8>) { + var ra: logic<8>; + var rb: logic<8>; + always_ff (a_clk, rst) { if_reset { ra = 3; } else { ra = rb + 8'd1; } } + always_ff (b_clk, rst) { if_reset { rb = 5; } else { rb = ra + 8'd2; } } + assign a = ra; + assign b = rb; +}`, + "Top", + ); + try { + const [aClk, bClk] = [sim.event("a_clk"), sim.event("b_clk")]; + sim.edges([ + [aClk, "negedge"], + [bClk, "negedge"], + ]); + reset(sim); + sim.edges([ + [aClk, "posedge"], + [bClk, "posedge"], + ]); + expect([sim.dut.a, sim.dut.b]).toEqual([6n, 5n]); + expect(() => sim.edges([[aClk, "sideways" as "posedge"]])).toThrow( + RangeError, + ); + } finally { + sim.dispose(); + } + }); +}); diff --git a/packages/celox/src/simulator.ts b/packages/celox/src/simulator.ts index 5d34faeb0a6..d174b5f54df 100644 --- a/packages/celox/src/simulator.ts +++ b/packages/celox/src/simulator.ts @@ -19,6 +19,7 @@ import { wrapDirectSimulatorHandle, } from "./napi-helpers.js"; import type { + ClockEdge, CreateResult, EventHandle, FourStateValue, @@ -519,6 +520,98 @@ export class Simulator

> { } } + /** + * Move a clock's signal to 1 and run every domain sensitive to that + * rising edge: its own domain when the edge is its active edge, clocks + * computed combinationally from it (sampling the state before the edge), + * and the domains the commit clocks in turn. The signal stays high; an + * edge to the level the signal already has does nothing. + * + * @param event Event handle or known raw event ID. Defaults to the first + * event. + */ + posedge(event?: EventHandle | number): void { + this.edges([[this.resolveEventId(event), "posedge"]]); + } + + /** Move a clock's signal to 0; see `posedge()`. */ + negedge(event?: EventHandle | number): void { + this.edges([[this.resolveEventId(event), "negedge"]]); + } + + /** + * The event's active edge: rising for a positive-edge clock or an + * active-high reset (including Veryl's `clock` under a `posedge` clock + * type), falling otherwise. See `posedge()`. + */ + activeEdge(event?: EventHandle | number): void { + const id = this.resolveEventId(event); + this.edges([[id, this.activeIsRising(id) ? "posedge" : "negedge"]]); + } + + /** The edge opposite to the event's active edge. See `posedge()`. */ + inactiveEdge(event?: EventHandle | number): void { + const id = this.resolveEventId(event); + 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 + * them commit, as coincident edges in hardware. + */ + edges( + moves: ReadonlyArray, + ): void { + this.ensureAlive(); + const handle = this._handle; + if (!handle.edges) { + throw new Error("This simulator backend does not support explicit edges"); + } + const ids: number[] = []; + const rising: boolean[] = []; + for (const [event, edge] of moves) { + const id = typeof event === "number" ? event : event.id; + this.assertKnownEventId(id); + if (edge !== "posedge" && edge !== "negedge") { + throw new RangeError(`Unknown clock edge '${String(edge)}'`); + } + ids.push(id); + rising.push(edge === "posedge"); + } + // The handle settles first only when needed, and leaves + // combinational logic as it was when no domain ran and nothing + // combinational reads the moved signals. + this._state.dirty = !handle.edges(ids, rising, this._state.dirty); + } + + private resolveEventId(event: EventHandle | number | undefined): number { + this.ensureAlive(); + if (event === undefined) { + if (this._eventIds.size === 0) { + throw new Error("Simulator has no events"); + } + return this._defaultEventId; + } + const id = typeof event === "number" ? event : event.id; + this.assertKnownEventId(id); + return id; + } + + private activeIsRising(eventId: number): boolean { + const handle = this._handle; + if (!handle.activeEdgeIsRising) { + throw new Error("This simulator backend does not support explicit edges"); + } + return handle.activeEdgeIsRising(eventId); + } + /** Resolve an event name to a handle for use with `tick()`. */ event(name: string): EventHandle { const id = this._events[name]; diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index 278c5291b36..c5f3c9e58ad 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -117,6 +117,16 @@ export interface NativeFrontendSimulatorHandle extends FrontendSimulatorHandleMetadata { tick(eventId: number): void; tickN(eventId: number, count: number): void; + /** + * Move event signals through coincident edges and run every domain + * sensitive to them: `rising[i]` gives the direction of `eventIds[i]`. + * `dirty` says whether combinational logic has pending changes (default + * `true`: it settles first). Returns whether combinational logic is + * settled afterwards. Absent on addons without explicit edges. + */ + edges?(eventIds: number[], rising: boolean[], dirty?: boolean): boolean; + /** Whether the event's active edge is rising. */ + activeEdgeIsRising?(eventId: number): boolean; evalComb(): void; dump(timestamp: number): void; sharedMemory(): Uint8Array; @@ -141,6 +151,16 @@ export interface WasmFrontendSimulatorHandle initialMemoryBytes(): Uint8Array | number[]; combWasmBytes(): Uint8Array | number[]; eventWasmBytes(name: string): Uint8Array | number[]; + /** + * Per event name, the derived domains its ticks and edges run, as JSON. + * Absent on addons that predate explicit edges. + */ + edgePlansJson?(): string; + /** The `"evalOnly"` or `"apply"` phase module of an event's kernels. */ + eventPhaseWasmBytes?( + name: string, + phase: "evalOnly" | "apply", + ): Uint8Array | number[]; /** * Offset where the checkpointable design state starts (it ends at * `stableSize`). Absent on addons without checkpoint support. @@ -170,6 +190,16 @@ export type FrontendSimulatorHandle = export interface NativeSimulatorHandle { tick(eventId: number): void; tickN(eventId: number, count: number): void; + /** + * Move event signals through coincident edges and run every domain + * sensitive to them: `rising[i]` gives the direction of `eventIds[i]`. + * `dirty` says whether combinational logic has pending changes (default + * `true`: it settles first). Returns whether combinational logic is + * settled afterwards. Absent on addons without explicit edges. + */ + edges?(eventIds: number[], rising: boolean[], dirty?: boolean): boolean; + /** Whether the event's active edge is rising. */ + activeEdgeIsRising?(eventId: number): boolean; evalComb(): void; dump(timestamp: number): void; dispose(): void; @@ -396,6 +426,9 @@ export interface EventHandle { readonly id: number; } +/** A transition of a clock or reset signal. */ +export type ClockEdge = "posedge" | "negedge"; + // --------------------------------------------------------------------------- // 4-state helpers // --------------------------------------------------------------------------- diff --git a/packages/celox/src/wasm-bridge.ts b/packages/celox/src/wasm-bridge.ts index e94437517ed..38dd368825b 100644 --- a/packages/celox/src/wasm-bridge.ts +++ b/packages/celox/src/wasm-bridge.ts @@ -16,6 +16,11 @@ import type { NativeSimulatorHandle, WasmFrontendSimulatorHandle, } from "./types.js"; +import { + cachedEdgeKernels, + type EdgePlans, + WasmEdgeRunner, +} from "./wasm-edges.js"; // --------------------------------------------------------------------------- // Minimal WebAssembly type declarations for environments without DOM lib. @@ -123,6 +128,64 @@ function wasmCheckpointMethods( }; } +/** + * The module of an event's own domain, or `undefined` for an event without + * one (a clock that only drives a gated clock). + */ +function eventBytes( + raw: RawWasmSimulatorHandle, + name: string, +): Uint8Array | undefined { + try { + return new Uint8Array(raw.eventWasmBytes(name)); + } catch { + return undefined; + } +} + +/** + * The edge runner of a bridge, when the raw handle provides edge plans. + * Phase modules of split kernels are compiled on first use. + */ +function wasmEdgeRunner( + raw: RawWasmSimulatorHandle, + memory: WebAssembly.Memory, + events: Record, + eventInstances: Map, + evalComb: () => void, +): WasmEdgeRunner | undefined { + if (!raw.edgePlansJson) return undefined; + const plans = JSON.parse(raw.edgePlansJson()) as EdgePlans; + const run = (instance: WebAssembly.Instance) => () => + (instance.exports.run as CallableFunction)(); + const phase = (name: string, kind: "evalOnly" | "apply") => { + if (!raw.eventPhaseWasmBytes) return undefined; + try { + const bytes = new Uint8Array(raw.eventPhaseWasmBytes(name, kind)); + const module = new WebAssembly.Module(bytes); + return run(new WebAssembly.Instance(module, { env: { memory } })); + } catch { + return undefined; + } + }; + const kernels = cachedEdgeKernels((name) => { + const id = events[name]; + const instance = id === undefined ? undefined : eventInstances.get(id); + return instance ? run(instance) : undefined; + }, phase); + return new WasmEdgeRunner(memory, plans, events, kernels, evalComb); +} + +function edgeMethods( + edges: WasmEdgeRunner | undefined, +): Pick { + if (!edges) return {}; + return { + edges: (eventIds, rising, dirty) => edges.edges(eventIds, rising, dirty), + activeEdgeIsRising: (eventId) => edges.activeEdgeIsRising(eventId), + }; +} + /** Result of creating a WASM simulator bridge. */ export interface WasmBridgeResult { /** Handle compatible with the existing Simulator code. */ @@ -168,7 +231,8 @@ export function createWasmSimulatorBridge( const eventInstances = new Map(); for (const [name, id] of Object.entries(events)) { - const bytes = new Uint8Array(raw.eventWasmBytes(name)); + const bytes = eventBytes(raw, name); + if (!bytes) continue; const mod = new WebAssembly.Module(bytes); const inst = new WebAssembly.Instance(mod, { env: { memory } }); eventInstances.set(id, inst); @@ -176,14 +240,22 @@ export function createWasmSimulatorBridge( const sharedMemory = new Uint8Array(memory.buffer, 0, stableSize); + const edges = wasmEdgeRunner(raw, memory, events, eventInstances, () => + (combInstance.exports.run as CallableFunction)(), + ); const handle: NativeSimulatorHandle = { tick(eventId: number): void { + if (edges?.hasDerived(eventId)) { + edges.tick(eventId); + return; + } // eval_comb → eval_apply_ff → eval_comb (combInstance.exports.run as CallableFunction)(); const evInst = eventInstances.get(eventId); if (evInst) (evInst.exports.run as CallableFunction)(); (combInstance.exports.run as CallableFunction)(); }, + ...edgeMethods(edges), tickN(eventId: number, count: number): void { for (let i = 0; i < count; i++) { this.tick(eventId); @@ -239,7 +311,8 @@ export async function createWasmSimulatorBridgeAsync( const eventEntries = Object.entries(events); await Promise.all( eventEntries.map(async ([name, id]) => { - const bytes = new Uint8Array(raw.eventWasmBytes(name)); + const bytes = eventBytes(raw, name); + if (!bytes) return; const mod = await WebAssembly.compile(bytes); const inst = await WebAssembly.instantiate(mod, { env: { memory } }); eventInstances.set(id, inst); @@ -248,13 +321,21 @@ export async function createWasmSimulatorBridgeAsync( const sharedMemory = new Uint8Array(memory.buffer, 0, stableSize); + const edges = wasmEdgeRunner(raw, memory, events, eventInstances, () => + (combInstance.exports.run as CallableFunction)(), + ); const handle: NativeSimulatorHandle = { tick(eventId: number): void { + if (edges?.hasDerived(eventId)) { + edges.tick(eventId); + return; + } (combInstance.exports.run as CallableFunction)(); const evInst = eventInstances.get(eventId); if (evInst) (evInst.exports.run as CallableFunction)(); (combInstance.exports.run as CallableFunction)(); }, + ...edgeMethods(edges), tickN(eventId: number, count: number): void { for (let i = 0; i < count; i++) { this.tick(eventId); diff --git a/packages/celox/src/wasm-edges.test.ts b/packages/celox/src/wasm-edges.test.ts new file mode 100644 index 00000000000..3a1d25270a2 --- /dev/null +++ b/packages/celox/src/wasm-edges.test.ts @@ -0,0 +1,189 @@ +import { expect, test, vi } from "vitest"; +import { + createWasmSimulatorBridge, + type RawWasmSimulatorHandle, +} from "./wasm-bridge.js"; +import type { EdgePlans } from "./wasm-edges.js"; + +// Memory map of a small design driven by hand-written WASM modules: +// `gated = clk & en`, `inverted = ~clk`, and one counter per domain. +const CLK = 0; +const EN = 1; +const GATED = 2; +const INVERTED = 3; +const RISING = 8; +const GATED_COUNT = 9; +const FALLING = 10; + +const I32_CONST = 0x41; +const LOAD8 = [0x2d, 0x00, 0x00]; +const STORE8 = [0x3a, 0x00, 0x00]; + +/** A module exporting `run`, which executes `body` over the shared memory. */ +function module(body: number[]): Uint8Array { + const code = [0x00, ...body, 0x0b]; + return new Uint8Array([ + ...[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00], + ...[0x01, 0x04, 0x01, 0x60, 0x00, 0x00], + ...[0x02, 0x0f, 0x01, 0x03, 0x65, 0x6e, 0x76], + ...[0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x01], + ...[0x03, 0x02, 0x01, 0x00], + ...[0x07, 0x07, 0x01, 0x03, 0x72, 0x75, 0x6e, 0x00, 0x00], + ...[0x0a, code.length + 2, 0x01, code.length, ...code], + ]); +} + +/** `mem[target] = mem[target] + 1`. */ +const increment = (target: number) => [ + I32_CONST, + target, + I32_CONST, + target, + ...LOAD8, + I32_CONST, + 1, + 0x6a, + ...STORE8, +]; + +// gated = clk & en; inverted = (clk ^ 1) & 1 +const comb = module([ + I32_CONST, + GATED, + I32_CONST, + CLK, + ...LOAD8, + I32_CONST, + EN, + ...LOAD8, + 0x71, + ...STORE8, + I32_CONST, + INVERTED, + I32_CONST, + CLK, + ...LOAD8, + I32_CONST, + 1, + 0x73, + I32_CONST, + 1, + 0x71, + ...STORE8, +]); + +const PLANS: EdgePlans = { + fourState: false, + events: { + clk: { + signal: { offset: CLK, width: 1 }, + edge: "posedge", + combRead: true, + domains: [], + gated: [ + { + event: "gated", + signal: { offset: GATED, width: 1 }, + edge: "posedge", + }, + { + event: "inverted", + signal: { offset: INVERTED, width: 1 }, + edge: "posedge", + }, + ], + }, + gated: { + signal: { offset: GATED, width: 1 }, + edge: "posedge", + combRead: false, + domains: [], + gated: [], + }, + inverted: { + signal: { offset: INVERTED, width: 1 }, + edge: "posedge", + combRead: false, + domains: [], + gated: [], + }, + }, +}; + +function raw(plans: EdgePlans | undefined): RawWasmSimulatorHandle { + const kernels: Record = { + clk: module(increment(RISING)), + gated: module(increment(GATED_COUNT)), + inverted: module(increment(FALLING)), + }; + const initial = new Uint8Array(16); + initial[INVERTED] = 1; + return { + layoutJson: "{}", + eventsJson: JSON.stringify({ clk: 0, gated: 1, inverted: 2 }), + hierarchyJson: "{}", + warningsJson: "[]", + stableSize: 16, + totalSize: 16, + dispose: vi.fn(), + initialMemoryBytes: () => initial, + combWasmBytes: () => comb, + eventWasmBytes: (name: string) => kernels[name], + ...(plans ? { edgePlansJson: () => JSON.stringify(plans) } : {}), + }; +} + +test("the WASM bridge ticks and moves clocks as the native simulator does", () => { + const { handle, sharedMemory } = createWasmSimulatorBridge(raw(PLANS)); + const counters = () => [ + sharedMemory[RISING], + sharedMemory[GATED_COUNT], + sharedMemory[FALLING], + ]; + sharedMemory[EN] = 1; + handle.evalComb(); + + // A tick is the active edge only: the gate passes it, `~clk` does not + // rise, and `clk` stays low. + handle.tick(0); + expect(counters()).toEqual([1, 1, 0]); + 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(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]); + + // 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]); +}); + +test("a bridge without edge plans keeps the plain tick", () => { + const { handle, sharedMemory } = createWasmSimulatorBridge(raw(undefined)); + sharedMemory[EN] = 1; + handle.tick(0); + expect([sharedMemory[RISING], sharedMemory[GATED_COUNT]]).toEqual([1, 0]); + expect(handle.edges).toBeUndefined(); +}); + +test("edges of a clock combinational logic does not read keep it settled", () => { + const { handle, sharedMemory } = createWasmSimulatorBridge(raw(PLANS)); + handle.evalComb(); + // `gated` only clocks its counter: its falling edge runs nothing and + // leaves combinational logic as it was. + expect(handle.edges?.([1], [true], false)).toBe(true); + expect(sharedMemory[GATED_COUNT]).toBe(1); + expect(handle.edges?.([1], [false], false)).toBe(true); + expect(handle.edges?.([1], [false], true)).toBe(false); + expect(handle.edges?.([1], [true], true)).toBe(true); + expect(sharedMemory[GATED_COUNT]).toBe(2); +}); diff --git a/packages/celox/src/wasm-edges.ts b/packages/celox/src/wasm-edges.ts new file mode 100644 index 00000000000..ee31deee116 --- /dev/null +++ b/packages/celox/src/wasm-edges.ts @@ -0,0 +1,431 @@ +/** + * Ticks and clock edges for simulators whose WASM event modules run in + * JavaScript (browser and WASI builds). + * + * These follow the rules of the native `Simulator`, from the same build-time + * plans (`edgePlansJson()` of the raw handle): + * + * - An edge runs the event's own domain when it is the domain's active edge. + * - Clocks computed combinationally from the event's signal (such as + * `clk & en` or `~clk`) are judged from the state before the edge with the + * signal at its new level, and their domains evaluate together with the + * event's own, against the same state, before any of them commits. + * - 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. + * + * Gates are judged by settling the design with the signal at each level. + * + * @module + */ + +/** The memory the kernels share. */ +export interface EdgeMemory { + readonly buffer: ArrayBuffer; +} + +/** A one-bit event signal in the packed memory layout. */ +export interface EdgePlanSignal { + readonly offset: number; + readonly width: number; +} + +/** The active edge of a domain, or `"any"` for a domain of unknown kind. */ +export type EdgePlanEdge = "posedge" | "negedge" | "any"; + +/** A derived event domain. */ +export interface EdgePlanDomain { + readonly event: string; + readonly signal: EdgePlanSignal; + readonly edge: EdgePlanEdge; +} + +/** What an edge of one event runs besides the event's own domain. */ +export interface EdgePlanEvent { + readonly signal: EdgePlanSignal; + readonly edge: EdgePlanEdge; + readonly combRead: boolean; + readonly domains: readonly EdgePlanDomain[]; + readonly gated: readonly EdgePlanDomain[]; +} + +/** Per event name, its edge plan (`celox::EdgePlans`). */ +export interface EdgePlans { + readonly fourState: boolean; + readonly events: Readonly>; +} + +/** One compiled kernel: runs a module's `run` export. */ +export type KernelRun = () => void; + +/** The kernels of one event domain. */ +export interface EdgeKernels { + /** Evaluate and commit the domain. */ + evalApply(): void; + /** Evaluate the domain's next state without committing it. */ + evalOnly?(): void; + /** Commit what `evalOnly()` evaluated. */ + apply?(): void; +} + +/** + * Kernels looked up by event name on first use and cached: `evalApply(name)` + * runs the event's domain, `phase(name, kind)` one phase of its split + * kernels. An event without a domain of its own (a clock that only drives a + * gated clock) has no kernels. + */ +export function cachedEdgeKernels( + evalApply: (name: string) => KernelRun | undefined, + phase: (name: string, kind: "evalOnly" | "apply") => KernelRun | undefined, +): (name: string) => EdgeKernels | undefined { + const cache = new Map(); + return (name) => { + if (cache.has(name)) return cache.get(name); + const run = evalApply(name); + let kernels: EdgeKernels | undefined; + if (run) { + const evalOnly = phase(name, "evalOnly"); + const apply = phase(name, "apply"); + kernels = + evalOnly && apply + ? { evalApply: run, evalOnly, apply } + : { evalApply: run }; + } + cache.set(name, kernels); + return kernels; + }; +} + +/** One entry of a cascade round: a domain and the level it last had. */ +interface RoundEntry { + readonly domain: EdgePlanDomain; + was: boolean; + fired: boolean; +} + +/** A signal moved by an edge, with its level before and after. */ +interface Lever { + readonly signal: EdgePlanSignal; + readonly from: number; + readonly to: number; +} + +function stableEdge(edge: EdgePlanEdge, was: boolean, is: boolean): boolean { + switch (edge) { + case "posedge": + return !was && is; + case "negedge": + return was && !is; + default: + return was !== is; + } +} + +/** + * Edge execution over a shared memory and per-event kernels. + */ +export class WasmEdgeRunner { + private readonly memory: EdgeMemory; + private readonly plans: EdgePlans; + private readonly eventNames: Map; + private readonly kernels: (name: string) => EdgeKernels | undefined; + private readonly evalComb: () => void; + + constructor( + memory: EdgeMemory, + plans: EdgePlans, + events: Readonly>, + kernels: (name: string) => EdgeKernels | undefined, + evalComb: () => void, + ) { + this.memory = memory; + this.plans = plans; + this.eventNames = new Map( + Object.entries(events).map(([name, id]) => [id, name]), + ); + this.kernels = kernels; + this.evalComb = evalComb; + } + + /** Whether ticks of the event can run derived domains. */ + hasDerived(eventId: number): boolean { + const plan = this.plan(eventId); + return !!plan && (plan.domains.length > 0 || plan.gated.length > 0); + } + + /** Whether the event's active edge is a rising one. */ + activeEdgeIsRising(eventId: number): boolean { + return this.plan(eventId)?.edge !== "negedge"; + } + + /** The event's active edge without moving its signal, as `tick`. */ + tick(eventId: number): void { + const name = this.name(eventId); + const plan = this.plan(eventId); + if (!plan || !this.hasDerived(eventId)) { + 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, + }, + ); + } + + /** + * Move event signals at one instant; `rising[i]` gives the direction of + * `eventIds[i]`. `dirty` says whether combinational logic has pending + * changes. Returns whether combinational logic is settled afterwards: + * moving a signal that combinational logic does not read, without running + * a domain, leaves it as it was. + */ + edges( + eventIds: readonly number[], + rising: readonly boolean[], + dirty = true, + ): boolean { + const sources: string[] = []; + const levers: Lever[] = []; + const domains: EdgePlanDomain[] = []; + const gated: [EdgePlanDomain, number][] = []; + let moved = false; + let combRead = false; + eventIds.forEach((eventId, index) => { + const name = this.name(eventId); + const plan = this.plan(eventId); + if (!plan) { + return; + } + const to = rising[index] ? 1 : 0; + const old = this.knownLevel(plan.signal); + if ( + old === to || + levers.some((l) => l.signal.offset === plan.signal.offset) + ) { + return; + } + moved = true; + combRead ||= plan.combRead; + this.setLevel(plan.signal, to); + const lever = { signal: plan.signal, from: old ?? to ^ 1, to }; + if (plan.edge === "any" || (plan.edge === "posedge") === (to === 1)) { + sources.push(name); + } + if (plan.gated.length > 0) { + levers.push(lever); + for (const domain of plan.gated) { + if (!gated.some(([known]) => known.event === domain.event)) { + gated.push([domain, levers.length - 1]); + } + } + } + for (const domain of plan.domains) { + if (!domains.some((known) => known.event === domain.event)) { + domains.push(domain); + } + } + }); + if (!moved) { + return !dirty; + } + const notSource = (domain: EdgePlanDomain) => + !sources.includes(domain.event); + const ran = this.run( + sources, + domains.filter(notSource), + gated.filter(([domain]) => notSource(domain)), + levers, + { settle: dirty || combRead, persist: true }, + ); + return ran || (!dirty && !combRead); + } + + private run( + sources: readonly string[], + domains: readonly EdgePlanDomain[], + gated: readonly (readonly [EdgePlanDomain, number])[], + levers: readonly Lever[], + options: { settle: boolean; persist: boolean }, + ): boolean { + const rounds: RoundEntry[] = domains.map((domain) => ({ + domain, + was: this.level(domain.signal), + fired: false, + })); + if (gated.length === 0) { + if (sources.length === 0) { + return false; + } + this.fire(sources, options.settle); + this.evalComb(); + this.rounds(rounds); + return true; + } + const saved = options.persist + ? [] + : levers.map((lever) => this.saveLevel(lever.signal)); + let moved = false; + for (const lever of levers) { + if (this.level(lever.signal) !== (lever.from === 1)) { + this.setLevel(lever.signal, lever.from); + moved = true; + } + } + if (moved || options.settle) { + this.evalComb(); + } + const before = gated.map(([domain]) => this.level(domain.signal)); + for (const lever of levers) { + this.setLevel(lever.signal, lever.to); + } + this.evalComb(); + const gatedEntries: RoundEntry[] = gated.map(([domain], index) => { + const now = this.level(domain.signal); + return { + domain, + was: now, + fired: stableEdge(domain.edge, before[index] ?? now, now), + }; + }); + this.fire( + [ + ...sources, + ...gatedEntries + .filter((entry) => entry.fired) + .map((entry) => entry.domain.event), + ], + false, + ); + this.evalComb(); + this.rounds([...rounds, ...gatedEntries]); + if (!options.persist) { + levers.forEach((lever, index) => { + this.restoreLevel(lever.signal, saved[index] ?? [0, 0]); + }); + this.evalComb(); + } + return true; + } + + /** Cascade rounds: run every domain whose clock moved to its active edge. */ + private rounds(entries: RoundEntry[]): void { + for (;;) { + const ready = entries.filter( + (entry) => + !entry.fired && + stableEdge( + entry.domain.edge, + entry.was, + this.level(entry.domain.signal), + ), + ); + if (ready.length === 0) { + return; + } + this.fire( + ready.map((entry) => entry.domain.event), + false, + ); + for (const entry of ready) { + entry.fired = true; + } + this.evalComb(); + } + } + + /** Evaluate `events` against one state, then commit all of them. */ + private fire(events: readonly string[], settle: boolean): void { + if (settle) { + this.evalComb(); + } + // An event without a domain of its own runs nothing. + const kernels = events + .map((name) => this.kernels(name)) + .filter((kernel): kernel is EdgeKernels => kernel !== undefined); + const [only] = kernels; + if (kernels.length === 1 && only !== undefined) { + only.evalApply(); + return; + } + for (const kernel of kernels) { + if (kernel.evalOnly) { + kernel.evalOnly(); + } else { + kernel.evalApply(); + } + } + for (const kernel of kernels) { + kernel.apply?.(); + } + } + + private bytes(): Uint8Array { + return new Uint8Array(this.memory.buffer); + } + + private byte(offset: number): number { + return this.bytes()[offset] ?? 0; + } + + private level(signal: EdgePlanSignal): boolean { + return (this.byte(signal.offset) & 1) !== 0; + } + + /** The signal's level, or `null` while it is unknown. */ + private knownLevel(signal: EdgePlanSignal): number | null { + if (this.plans.fourState && (this.byte(signal.offset + 1) & 1) !== 0) { + return null; + } + return this.byte(signal.offset) & 1; + } + + private setLevel(signal: EdgePlanSignal, level: number): void { + const bytes = this.bytes(); + bytes[signal.offset] = (this.byte(signal.offset) & ~1) | level; + if (this.plans.fourState) { + bytes[signal.offset + 1] = this.byte(signal.offset + 1) & ~1; + } + } + + private saveLevel(signal: EdgePlanSignal): [number, number] { + return [ + this.byte(signal.offset), + this.plans.fourState ? this.byte(signal.offset + 1) : 0, + ]; + } + + private restoreLevel(signal: EdgePlanSignal, saved: [number, number]): void { + const bytes = this.bytes(); + bytes[signal.offset] = saved[0]; + if (this.plans.fourState) { + bytes[signal.offset + 1] = saved[1]; + } + } + + private name(eventId: number): string { + const name = this.eventNames.get(eventId); + if (name === undefined) { + throw new RangeError(`Unknown event ID ${eventId}`); + } + return name; + } + + private plan(eventId: number): EdgePlanEvent | undefined { + return this.plans.events[this.name(eventId)]; + } +} diff --git a/packages/playground/src/celox-compiler-protocol.ts b/packages/playground/src/celox-compiler-protocol.ts index 91dc832be7e..419508fdc4d 100644 --- a/packages/playground/src/celox-compiler-protocol.ts +++ b/packages/playground/src/celox-compiler-protocol.ts @@ -1,3 +1,5 @@ +import type { EdgePlans } from "@celox-sim/celox/wasm-edges"; + export type CeloxSourceFile = { content: string; path: string; @@ -10,7 +12,15 @@ export type CompiledSimulator = { events: Record; totalSize: number; combModule: WebAssembly.Module; + /** Per event, its own domain; absent for an event without one. */ eventModules: Record; + /** Per event, the phases of its split kernels, where it has them. */ + phaseModules: Record< + string, + { evalOnly: WebAssembly.Module; apply: WebAssembly.Module } + >; + /** Derived and gated domains of each event's ticks and edges. */ + edgePlans: EdgePlans; }; export type CeloxCompilerRequest = diff --git a/packages/playground/src/celox-compiler-worker.ts b/packages/playground/src/celox-compiler-worker.ts index 5a440f03230..061b0fe5782 100644 --- a/packages/playground/src/celox-compiler-worker.ts +++ b/packages/playground/src/celox-compiler-worker.ts @@ -1,8 +1,8 @@ import type { CeloxCompilerRequest, CeloxCompilerResponse, - CompiledSimulator, } from "./celox-compiler-protocol.js"; +import { compiledFromHandle } from "./compile-simulator.js"; const workerScope = globalThis as unknown as { addEventListener( @@ -30,33 +30,7 @@ try { { fourState: request.fourState }, ); try { - const layout = JSON.parse(handle.layoutJson); - const events = JSON.parse(handle.eventsJson) as Record; - const fourStateInitRegions = JSON.parse( - handle.fourStateInitRegionsJson, - ) as Array<[number, number]>; - const combModule = new WebAssembly.Module( - new Uint8Array(handle.combWasmBytes()), - ); - const eventModules: Record = {}; - for (const name of Object.keys(events)) { - try { - eventModules[name] = new WebAssembly.Module( - new Uint8Array(handle.eventWasmBytes(name)), - ); - } catch { - // An event without generated code is valid and has nothing to run. - } - } - const value: CompiledSimulator = { - fourState: request.fourState, - fourStateInitRegions, - layout, - events, - totalSize: handle.totalSize, - combModule, - eventModules, - }; + const value = compiledFromHandle(handle, request.fourState); workerScope.postMessage({ type: "result", id: request.id, value }); } finally { handle.dispose(); diff --git a/packages/playground/src/celox-wasm-loader.d.ts b/packages/playground/src/celox-wasm-loader.d.ts index 12b272a745a..29d2726e5d8 100644 --- a/packages/playground/src/celox-wasm-loader.d.ts +++ b/packages/playground/src/celox-wasm-loader.d.ts @@ -15,5 +15,7 @@ export class NativeSimulatorHandle { initialMemoryBytes(): Uint8Array; combWasmBytes(): Uint8Array; eventWasmBytes(name: string): Uint8Array; + edgePlansJson(): string; + eventPhaseWasmBytes(name: string, phase: "evalOnly" | "apply"): Uint8Array; dispose(): void; } diff --git a/packages/playground/src/compile-simulator.ts b/packages/playground/src/compile-simulator.ts new file mode 100644 index 00000000000..ff43d1282bb --- /dev/null +++ b/packages/playground/src/compile-simulator.ts @@ -0,0 +1,61 @@ +import type { EdgePlans } from "@celox-sim/celox/wasm-edges"; +import type { CompiledSimulator } from "./celox-compiler-protocol.js"; + +/** The parts of the wasm32 Celox handle a compiled simulator is made from. */ +export interface CompilerHandle { + readonly layoutJson: string; + readonly eventsJson: string; + readonly fourStateInitRegionsJson: string; + readonly totalSize: number; + combWasmBytes(): Uint8Array; + eventWasmBytes(name: string): Uint8Array; + edgePlansJson(): string; + eventPhaseWasmBytes(name: string, phase: "evalOnly" | "apply"): Uint8Array; +} + +function compileModule( + bytes: () => Uint8Array, +): WebAssembly.Module | undefined { + try { + return new WebAssembly.Module(new Uint8Array(bytes())); + } catch { + // An event without a domain of its own (a clock that only drives a + // gated clock) has no module. + return undefined; + } +} + +/** Compile every module of `handle` for the playground runtime. */ +export function compiledFromHandle( + handle: CompilerHandle, + fourState: boolean, +): CompiledSimulator { + const events = JSON.parse(handle.eventsJson) as Record; + const eventModules: CompiledSimulator["eventModules"] = {}; + const phaseModules: CompiledSimulator["phaseModules"] = {}; + for (const name of Object.keys(events)) { + const own = compileModule(() => handle.eventWasmBytes(name)); + if (!own) continue; + eventModules[name] = own; + const evalOnly = compileModule(() => + handle.eventPhaseWasmBytes(name, "evalOnly"), + ); + const apply = compileModule(() => + handle.eventPhaseWasmBytes(name, "apply"), + ); + if (evalOnly && apply) phaseModules[name] = { evalOnly, apply }; + } + return { + fourState, + fourStateInitRegions: JSON.parse(handle.fourStateInitRegionsJson) as Array< + [number, number] + >, + layout: JSON.parse(handle.layoutJson), + events, + totalSize: handle.totalSize, + combModule: new WebAssembly.Module(new Uint8Array(handle.combWasmBytes())), + eventModules, + phaseModules, + edgePlans: JSON.parse(handle.edgePlansJson()) as EdgePlans, + }; +} diff --git a/packages/playground/src/main.ts b/packages/playground/src/main.ts index befa5ce205b..af064eee6c0 100644 --- a/packages/playground/src/main.ts +++ b/packages/playground/src/main.ts @@ -1,25 +1,14 @@ import { chai, JestAsymmetricMatchers, JestChaiExpect } from "@vitest/expect"; import * as monaco from "monaco-editor"; -import celoxDutDts from "../../celox/dist/dut.d.ts?raw"; -import celoxIndexDts from "../../celox/dist/index.d.ts?raw"; -import celoxNapiBridgeDts from "../../celox/dist/napi-bridge.d.ts?raw"; -import celoxNapiHelpersDts from "../../celox/dist/napi-helpers.d.ts?raw"; -import celoxSimulationDts from "../../celox/dist/simulation.d.ts?raw"; -import celoxSimulatorDts from "../../celox/dist/simulator.d.ts?raw"; -// Import real .d.ts files from @celox-sim/celox for Monaco type injection -import celoxTypesDts from "../../celox/dist/types.d.ts?raw"; -import celoxWasmBridgeDts from "../../celox/dist/wasm-bridge.d.ts?raw"; import { CeloxCompilerClient } from "./celox-compiler-client.js"; import { buildMonacoTestbenchCompilerOptions } from "./monaco-testbench-options.js"; +import { celoxDtsLibs } from "./playground-dts.js"; +import { FourState, X, Z } from "./playground-runtime-helpers.js"; import { - FourState, - initializeFourStateMemory, - type PlaygroundSignalValue, - runPlaygroundTicks, - writeSignalValue, - X, - Z, -} from "./playground-runtime-helpers.js"; + createPlaygroundSimulation, + createPlaygroundSimulator, + type PlaygroundDumpSink, +} from "./playground-simulator.js"; import { transpileTestbench } from "./testbench-transpile.js"; import { buildVirtualModuleDts, @@ -1099,41 +1088,14 @@ declare module "vitest" { // ── @celox-sim/celox type registration (from real .d.ts) ── -// Rewrite relative imports in .d.ts to match Monaco's virtual FS paths -function fixDtsImports(content: string): string { - return content.replace( - /from\s+["']\.\/(\w+)\.js["']/g, - 'from "@celox-sim/celox/$1"', - ); -} - -// Register all @celox-sim/celox .d.ts files so Monaco resolves imports -const celoxDtsFiles: Record = { - types: celoxTypesDts, - simulator: celoxSimulatorDts, - simulation: celoxSimulationDts, - index: celoxIndexDts, - dut: celoxDutDts, - "napi-helpers": celoxNapiHelpersDts, - "wasm-bridge": celoxWasmBridgeDts, - "napi-bridge": celoxNapiBridgeDts, -}; -monacoTypeScript.typescriptDefaults.addExtraLib( - fixDtsImports(celoxIndexDts), - "file:///node_modules/@celox-sim/celox/index.d.ts", -); -for (const [name, content] of Object.entries(celoxDtsFiles)) { - const fixed = fixDtsImports(content); - // Register as both the sub-module path and the node_modules-style path - monacoTypeScript.typescriptDefaults.addExtraLib( - fixed, - `file:///node_modules/@celox-sim/celox/dist/${name}.d.ts`, - ); - // Also register as a bare module specifier for "from '@celox-sim/celox/xxx'" resolution - monacoTypeScript.typescriptDefaults.addExtraLib( - fixed, - `file:///node_modules/@celox-sim/celox/${name}.d.ts`, - ); +// Every declaration file of the package, so the whole public API resolves. +const celoxDtsSources = import.meta.glob("../../celox/dist/*.d.ts", { + query: "?raw", + import: "default", + eager: true, +}); +for (const lib of celoxDtsLibs(celoxDtsSources)) { + monacoTypeScript.typescriptDefaults.addExtraLib(lib.content, lib.filePath); } // ── DUT type injection (.veryl module declarations) ───── @@ -1437,156 +1399,13 @@ async function run() { type PlaygroundSimulatorOptions = { fourState?: boolean }; - // Build simulation factory (creates fresh instance per call) - function createSim(options?: PlaygroundSimulatorOptions) { - const fourStateEnabled = options?.fourState === true; - const { - layout, - events, - totalSize, - combModule, - eventModules, - fourStateInitRegions, - } = fourStateEnabled ? fourStateCompiled : twoStateCompiled; - const pages = Math.max(1, Math.ceil(totalSize / 65536)); - const memory = new WebAssembly.Memory({ initial: pages }); - initializeFourStateMemory(memory, fourStateInitRegions); - const combInst = new WebAssembly.Instance(combModule, { - env: { memory }, - }); - - // Build event instances and id→name mapping (mirrors real Simulator) - const eventNames = Object.keys(events); - const eventInsts: Record = {}; - for (const name of eventNames) { - const id: number = events[name]; - const eventModule = eventModules[name]; - if (eventModule) { - eventInsts[id] = new WebAssembly.Instance(eventModule, { - env: { memory }, - }); - } - } - const defaultEventId = eventNames.length > 0 ? events[eventNames[0]] : -1; - const knownEventIds = new Set(Object.values(events)); - - const view = new DataView(memory.buffer); - let dirty = false; - - const dut = new Proxy({} as Record, { - get(_, prop: string) { - const sig = layout[prop]; - if (!sig) return undefined; - // Lazy evalComb on output reads (matches real Simulator DUT behavior) - if (dirty && sig.direction !== "input") { - (combInst.exports.run as Function)(); - dirty = false; - } - let v = 0n; - for (let i = sig.byte_size - 1; i >= 0; i--) - v = (v << 8n) | BigInt(view.getUint8(sig.offset + i)); - if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n; - return v; - }, - set(_, prop: string, value: PlaygroundSignalValue) { - const sig = layout[prop]; - if (!sig) throw new Error(`Signal '${prop}' not found`); - writeSignalValue(view, sig, value, fourStateEnabled); - dirty = true; - return true; - }, - }); - - function evalComb() { - (combInst.exports.run as Function)(); - dirty = false; - } - - function flushDirty() { - if (dirty) evalComb(); - } - - function tickOne(eventId: number) { - const inst = eventInsts[eventId]; - if (inst) (inst.exports.run as Function)(); - (combInst.exports.run as Function)(); - dirty = false; - } - - const tickRuntime = { - defaultEventId, - knownEventIds, - flushDirty, - tickOne, - }; - - return { - dut, - warnings: [] as readonly string[], - tick( - eventOrCount?: { name: string; id: number } | number, - count?: number, - ) { - runPlaygroundTicks(tickRuntime, eventOrCount, count); - }, - event(name: string): { name: string; id: number } { - const id = events[name]; - if (id === undefined) { - throw new Error( - `Unknown event '${name}'. Available: ${eventNames.join(", ")}`, - ); - } - return { name, id }; - }, - fourState(portName: string): { - __fourState: true; - value: bigint; - mask: bigint; - } { - const sig = layout[portName]; - if (!sig) { - throw new Error( - `Unknown port '${portName}'. Available: ${Object.keys(layout).join(", ")}`, - ); - } - if (dirty && sig.direction !== "input") evalComb(); - let value = 0n; - for (let i = sig.byte_size - 1; i >= 0; i--) - value = (value << 8n) | BigInt(view.getUint8(sig.offset + i)); - if (sig.width < 64) value &= (1n << BigInt(sig.width)) - 1n; - // 4-state mask lives immediately after value bytes - let mask = 0n; - if (sig.is_4state) { - for (let i = sig.byte_size - 1; i >= 0; i--) - mask = - (mask << 8n) | - BigInt(view.getUint8(sig.offset + sig.byte_size + i)); - if (sig.width < 64) mask &= (1n << BigInt(sig.width)) - 1n; - } - return { __fourState: true, value, mask }; - }, - dump(timestamp: number) { - if (vcdSignals.length === 0) { - for (const [name, sig] of Object.entries(layout)) { - vcdSignals.push({ name, width: sig.width }); - } - } - if (dirty) { - evalComb(); - } - const values: bigint[] = []; - for (const sig of Object.values(layout)) { - let v = 0n; - for (let i = sig.byte_size - 1; i >= 0; i--) - v = (v << 8n) | BigInt(view.getUint8(sig.offset + i)); - if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n; - values.push(v); - } - vcdSnapshots.push({ timestamp, values }); - }, - dispose() {}, - }; - } + // Every dump() lands in the waveform viewer's current trace. + const recordDump: PlaygroundDumpSink = (timestamp, signals, values) => { + if (vcdSignals.length === 0) vcdSignals.push(...signals); + vcdSnapshots.push({ timestamp, values }); + }; + const compiledFor = (options?: PlaygroundSimulatorOptions) => + options?.fourState === true ? fourStateCompiled : twoStateCompiled; // Build module definitions from genTsFromSource result for .veryl imports const moduleNames = (genTsResult?.modules || []) @@ -1595,383 +1414,13 @@ async function run() { const Simulator = { create(_module: any, options?: PlaygroundSimulatorOptions) { - return createSim(options); + return createPlaygroundSimulator(compiledFor(options), recordDump); }, }; - // Time-based Simulation: event queue with signal toggling on top of WASM bridge - // Mirrors the native Simulation's step() logic: - // 1. Pop all events at current time - // 2. Write signal values to memory - // 3. Detect edges (posedge/negedge) and fire triggered FF handlers - // 4. Evaluate combinational logic - // 5. Reschedule recurring clocks with toggled value - function createSimulation(options?: PlaygroundSimulatorOptions) { - const fourStateEnabled = options?.fourState === true; - const { - layout, - events, - totalSize, - combModule, - eventModules, - fourStateInitRegions, - } = fourStateEnabled ? fourStateCompiled : twoStateCompiled; - const pages = Math.max(1, Math.ceil(totalSize / 65536)); - const memory = new WebAssembly.Memory({ initial: pages }); - initializeFourStateMemory(memory, fourStateInitRegions); - const combInst = new WebAssembly.Instance(combModule, { - env: { memory }, - }); - - const eventNames = Object.keys(events); - const eventInsts: Record = {}; - for (const name of eventNames) { - const id: number = events[name]; - const eventModule = eventModules[name]; - if (eventModule) { - eventInsts[id] = new WebAssembly.Instance(eventModule, { - env: { memory }, - }); - } - } - - const view = new DataView(memory.buffer); - - // Determine edge type for each event from layout type_kind - const edgeType: Record = {}; - for (const name of eventNames) { - const id: number = events[name]; - const sig = layout[name]; - if (!sig) continue; - const tk: string = sig.type_kind ?? "logic"; - if (tk === "reset_async_low" || tk === "reset_sync_low") { - edgeType[id] = "negedge"; - } else { - edgeType[id] = "posedge"; // clock, reset_async_high, etc. - } - } - - // Event queue entry: carries the signal name, next value, and optional clock reschedule info - type QueueEntry = { - time: number; - eventId: number; - signalName: string; - nextVal: number; - clockHalfPeriod?: number; // if set, reschedule with toggled value - }; - const queue: QueueEntry[] = []; - const clocks = new Map(); - let currentTime = 0; - // Track last signal values for edge detection - const lastValues: Record = {}; - - function enqueue(entry: QueueEntry) { - let lo = 0, - hi = queue.length; - while (lo < hi) { - const mid = (lo + hi) >>> 1; - if (queue[mid].time <= entry.time) lo = mid + 1; - else hi = mid; - } - queue.splice(lo, 0, entry); - } - - function writeSignal(name: string, val: number) { - const sig = layout[name]; - if (sig) writeSignalValue(view, sig, val, fourStateEnabled); - } - - function resolveEvent(name: string): number { - const id = events[name]; - if (id === undefined) { - throw new Error( - `Unknown event '${name}'. Available: ${eventNames.join(", ")}`, - ); - } - return id; - } - - // Process one time step: pop all events at next time, write values, detect edges, fire FFs - function processStep(): number | null { - if (queue.length === 0) return null; - const t = queue[0].time; - // Collect all events at this time - const batch: QueueEntry[] = []; - while (queue.length > 0 && queue[0].time === t) { - batch.push(queue.shift()!); - } - currentTime = t; - - // Phase 1: Write signal values to memory - for (const ev of batch) { - writeSignal(ev.signalName, ev.nextVal); - } - - // Phase 2: Edge detection + fire triggered FFs - for (const ev of batch) { - const prevVal = lastValues[ev.eventId] ?? 0; - const curVal = ev.nextVal; - const edge = edgeType[ev.eventId] ?? "posedge"; - const triggered = - edge === "posedge" - ? prevVal === 0 && curVal !== 0 - : prevVal !== 0 && curVal === 0; - if (triggered) { - const inst = eventInsts[ev.eventId]; - if (inst) (inst.exports.run as Function)(); - } - lastValues[ev.eventId] = curVal; - } - - // Phase 3: Evaluate combinational logic - (combInst.exports.run as Function)(); - - // Phase 4: Reschedule clocks with toggled value - for (const ev of batch) { - if (ev.clockHalfPeriod != null) { - enqueue({ - time: currentTime + ev.clockHalfPeriod, - eventId: ev.eventId, - signalName: ev.signalName, - nextVal: 1 - ev.nextVal, - clockHalfPeriod: ev.clockHalfPeriod, - }); - } - } - - return currentTime; - } - - // DUT proxy with lazy evalComb on output reads - let simDirty = false; - const dut = new Proxy({} as Record, { - get(_, prop: string) { - const sig = layout[prop]; - if (!sig) return undefined; - if (simDirty && sig.direction !== "input") { - (combInst.exports.run as Function)(); - simDirty = false; - } - let v = 0n; - for (let i = sig.byte_size - 1; i >= 0; i--) - v = (v << 8n) | BigInt(view.getUint8(sig.offset + i)); - if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n; - return v; - }, - set(_, prop: string, value: PlaygroundSignalValue) { - const sig = layout[prop]; - if (!sig) throw new Error(`Signal '${prop}' not found`); - writeSignalValue(view, sig, value, fourStateEnabled); - simDirty = true; - return true; - }, - }); - - const sim = { - dut, - warnings: [] as readonly string[], - - addClock( - name: string, - opts: { period: number; initialDelay?: number }, - ) { - const eventId = resolveEvent(name); - clocks.set(name, { period: opts.period, eventId }); - const delay = opts.initialDelay ?? 0; - const halfPeriod = opts.period / 2; - // Schedule first edge (0→1) at delay, then toggles every half-period - enqueue({ - time: currentTime + delay, - eventId, - signalName: name, - nextVal: 1, - clockHalfPeriod: halfPeriod, - }); - }, - - schedule(name: string, opts: { time: number; value: number }) { - const eventId = resolveEvent(name); - enqueue({ - time: opts.time, - eventId, - signalName: name, - nextVal: opts.value, - }); - }, - - step: processStep, - - time(): number { - return currentTime; - }, - - nextEventTime(): number | null { - return queue.length > 0 ? queue[0].time : null; - }, - - runUntil(endTime: number, opts?: { maxSteps?: number }) { - const max = opts?.maxSteps; - let steps = 0; - while (queue.length > 0 && queue[0].time <= endTime) { - processStep(); - steps++; - if (max != null && steps >= max) { - throw new Error( - `runUntil: exceeded ${max} steps at time ${currentTime} (target ${endTime})`, - ); - } - } - currentTime = endTime; - }, - - waitUntil( - condition: () => boolean, - opts?: { maxSteps?: number }, - ): number { - const max = opts?.maxSteps ?? 100_000; - let steps = 0; - while (!condition()) { - if (queue.length === 0) break; - processStep(); - steps++; - if (steps >= max) { - throw new Error( - `waitUntil: condition not met after ${max} steps at time ${currentTime}`, - ); - } - } - return currentTime; - }, - - waitForCycles( - clock: string, - count: number, - opts?: { maxSteps?: number }, - ): number { - const clkInfo = clocks.get(clock); - if (!clkInfo) - throw new Error( - `No clock registered for '${clock}'. Call addClock() first.`, - ); - const sig = layout[clock]; - if (!sig) throw new Error(`No layout entry for clock '${clock}'.`); - const readClk = () => view.getUint8(sig.offset); - let prev = readClk(); - let remaining = count; - return sim.waitUntil(() => { - const curr = readClk(); - if (prev === 0 && curr !== 0) remaining--; - prev = curr; - return remaining <= 0; - }, opts); - }, - - reset( - signal: string, - opts?: { activeCycles?: number; duration?: number }, - ) { - const sig = layout[signal]; - if (!sig) - throw new Error( - `Unknown port '${signal}'. Available: ${Object.keys(layout).join(", ")}`, - ); - const typeKind: string = sig.type_kind ?? ""; - if (!typeKind.startsWith("reset")) { - throw new Error( - `Port '${signal}' is not a reset signal (type_kind: '${typeKind}').`, - ); - } - const isActiveLow = - typeKind === "reset_async_low" || typeKind === "reset_sync_low"; - const activeValue = isActiveLow ? 0n : 1n; - const inactiveValue = isActiveLow ? 1n : 0n; - - dut[signal] = activeValue; - - if (opts?.duration != null) { - sim.runUntil(currentTime + opts.duration); - } else { - const cycles = opts?.activeCycles ?? 2; - const firstClock = clocks.keys().next().value; - if (firstClock) { - sim.waitForCycles(firstClock, cycles); - } else { - // No clock registered — fire the reset event directly - const eventId = events[signal]; - if (eventId !== undefined) { - writeSignal(signal, Number(activeValue)); - const inst = eventInsts[eventId]; - if (inst) (inst.exports.run as Function)(); - (combInst.exports.run as Function)(); - } - } - } - - dut[signal] = inactiveValue; - }, - - event(name: string): { name: string; id: number } { - return { name, id: resolveEvent(name) }; - }, - - fourState(portName: string): { - __fourState: true; - value: bigint; - mask: bigint; - } { - const sig = layout[portName]; - if (!sig) - throw new Error( - `Unknown port '${portName}'. Available: ${Object.keys(layout).join(", ")}`, - ); - if (simDirty && sig.direction !== "input") { - (combInst.exports.run as Function)(); - simDirty = false; - } - let value = 0n; - for (let i = sig.byte_size - 1; i >= 0; i--) - value = (value << 8n) | BigInt(view.getUint8(sig.offset + i)); - if (sig.width < 64) value &= (1n << BigInt(sig.width)) - 1n; - let mask = 0n; - if (sig.is_4state) { - for (let i = sig.byte_size - 1; i >= 0; i--) - mask = - (mask << 8n) | - BigInt(view.getUint8(sig.offset + sig.byte_size + i)); - if (sig.width < 64) mask &= (1n << BigInt(sig.width)) - 1n; - } - return { __fourState: true, value, mask }; - }, - - dump(timestamp: number) { - if (vcdSignals.length === 0) { - for (const [name, sig] of Object.entries(layout)) { - vcdSignals.push({ name, width: sig.width }); - } - } - if (simDirty) { - (combInst.exports.run as Function)(); - simDirty = false; - } - const values: bigint[] = []; - for (const sig of Object.values(layout)) { - let v = 0n; - for (let i = sig.byte_size - 1; i >= 0; i--) - v = (v << 8n) | BigInt(view.getUint8(sig.offset + i)); - if (sig.width < 64) v &= (1n << BigInt(sig.width)) - 1n; - values.push(v); - } - vcdSnapshots.push({ timestamp, values }); - }, - - dispose() {}, - }; - return sim; - } - const Simulation = { create(_module: any, options?: PlaygroundSimulatorOptions) { - return createSimulation(options); + return createPlaygroundSimulation(compiledFor(options), recordDump); }, }; diff --git a/packages/playground/src/playground-dts.ts b/packages/playground/src/playground-dts.ts index ca3981ae6e6..d64a2880b91 100644 --- a/packages/playground/src/playground-dts.ts +++ b/packages/playground/src/playground-dts.ts @@ -1,3 +1,37 @@ +/** A declaration file for Monaco's TypeScript service. */ +export interface ExtraLib { + readonly content: string; + readonly filePath: string; +} + +const CELOX_ROOT = "file:///node_modules/@celox-sim/celox"; + +/** Rewrite the relative imports of a `@celox-sim/celox` declaration file. */ +function fixCeloxDtsImports(content: string): string { + return content.replace( + /from\s+["']\.\/([\w-]+)\.js["']/g, + 'from "@celox-sim/celox/$1"', + ); +} + +/** + * Monaco libraries for every declaration file of `@celox-sim/celox`'s + * `dist`, keyed by path (as `import.meta.glob` returns them): each one under + * `dist/` and under its bare subpath, and `index.d.ts` as the package root, + * so that testbenches see the whole public API, explicit edges included. + */ +export function celoxDtsLibs(files: Record): ExtraLib[] { + const libs: ExtraLib[] = []; + for (const [path, content] of Object.entries(files)) { + const name = /([\w-]+)\.d\.ts$/.exec(path)?.[1]; + if (!name) continue; + const fixed = fixCeloxDtsImports(content); + libs.push({ content: fixed, filePath: `${CELOX_ROOT}/dist/${name}.d.ts` }); + libs.push({ content: fixed, filePath: `${CELOX_ROOT}/${name}.d.ts` }); + } + return libs; +} + export type VirtualPortDirection = "input" | "output" | "inout"; export type VirtualPortKind = "logic" | "bit" | "clock" | "reset"; diff --git a/packages/playground/src/playground-simulator.ts b/packages/playground/src/playground-simulator.ts new file mode 100644 index 00000000000..949185bd18f --- /dev/null +++ b/packages/playground/src/playground-simulator.ts @@ -0,0 +1,487 @@ +/** + * The playground's simulators: the compiled WebAssembly modules of a design, + * driven as `@celox-sim/celox` drives them in the browser. + * + * Ticks, explicit edges and timed steps run through the edge runner of + * `@celox-sim/celox`, from the build-time edge plans, so derived and gated + * clocks fire exactly as in the native simulator. + * + * @module + */ + +import { + cachedEdgeKernels, + type KernelRun, + WasmEdgeRunner, +} from "@celox-sim/celox/wasm-edges"; +import type { CompiledSimulator } from "./celox-compiler-protocol.js"; +import { + initializeFourStateMemory, + type PlaygroundEventHandle, + type PlaygroundSignalValue, + runPlaygroundTicks, + writeSignalValue, +} from "./playground-runtime-helpers.js"; + +/** A clock edge, as `Simulator.edges()` of `@celox-sim/celox` names it. */ +export type PlaygroundClockEdge = "posedge" | "negedge"; + +/** An event, by handle or ID. */ +export type PlaygroundEvent = PlaygroundEventHandle | number; + +/** Receives `dump()` snapshots for the waveform viewer. */ +export type PlaygroundDumpSink = ( + timestamp: number, + signals: { name: string; width: number }[], + values: bigint[], +) => void; + +export type PlaygroundFourStateValue = { + __fourState: true; + value: bigint; + mask: bigint; +}; + +function runExport(instance: WebAssembly.Instance): KernelRun { + return () => (instance.exports.run as CallableFunction)(); +} + +/** One instantiated design: its memory, kernels and edge runner. */ +class PlaygroundInstance { + readonly layout: Record; + readonly events: Record; + readonly eventNames: string[]; + readonly knownEventIds: ReadonlySet; + readonly view: DataView; + readonly runner: WasmEdgeRunner; + readonly fourState: boolean; + /** Combinational logic has pending input changes. */ + dirty = false; + private readonly comb: KernelRun; + + constructor(compiled: CompiledSimulator) { + this.layout = compiled.layout; + this.events = compiled.events; + this.eventNames = Object.keys(compiled.events); + this.knownEventIds = new Set(Object.values(compiled.events)); + this.fourState = compiled.fourState; + const pages = Math.max(1, Math.ceil(compiled.totalSize / 65536)); + const memory = new WebAssembly.Memory({ initial: pages }); + initializeFourStateMemory(memory, compiled.fourStateInitRegions); + this.view = new DataView(memory.buffer); + const instantiate = (module: WebAssembly.Module) => + runExport(new WebAssembly.Instance(module, { env: { memory } })); + this.comb = instantiate(compiled.combModule); + const evalApply = new Map(); + for (const [name, module] of Object.entries(compiled.eventModules)) { + evalApply.set(name, instantiate(module)); + } + const kernels = cachedEdgeKernels( + (name) => evalApply.get(name), + (name, kind) => { + const phases = compiled.phaseModules[name]; + return phases ? instantiate(phases[kind]) : undefined; + }, + ); + this.runner = new WasmEdgeRunner( + memory, + compiled.edgePlans, + compiled.events, + kernels, + this.comb, + ); + } + + evalComb(): void { + this.comb(); + this.dirty = false; + } + + flushDirty(): void { + if (this.dirty) this.evalComb(); + } + + /** The event's active edge without moving its signal, as `tick`. */ + tickOne(eventId: number): void { + this.runner.tick(eventId); + this.dirty = false; + } + + /** Coincident edges; see `Simulator.edges()` of `@celox-sim/celox`. */ + edges(eventIds: number[], rising: boolean[]): void { + this.dirty = !this.runner.edges(eventIds, rising, this.dirty); + } + + activeIsRising(eventId: number): boolean { + return this.runner.activeEdgeIsRising(eventId); + } + + resolveEvent(name: string): number { + const id = this.events[name]; + if (id === undefined) { + throw new Error( + `Unknown event '${name}'. Available: ${this.eventNames.join(", ")}`, + ); + } + return id; + } + + signal(name: string): any { + const sig = this.layout[name]; + if (!sig) { + throw new Error( + `Unknown port '${name}'. Available: ${Object.keys(this.layout).join(", ")}`, + ); + } + return sig; + } + + read(sig: any, plane = 0): bigint { + let value = 0n; + const base = sig.offset + plane * sig.byte_size; + for (let i = sig.byte_size - 1; i >= 0; i--) + value = (value << 8n) | BigInt(this.view.getUint8(base + i)); + if (sig.width < 64) value &= (1n << BigInt(sig.width)) - 1n; + return value; + } + + write(name: string, value: PlaygroundSignalValue): void { + const sig = this.layout[name]; + if (!sig) throw new Error(`Signal '${name}' not found`); + writeSignalValue(this.view, sig, value, this.fourState); + this.dirty = true; + } + + /** A DUT whose output reads settle combinational logic first. */ + dut(): Record { + return new Proxy({} as Record, { + get: (_, prop: string) => { + const sig = this.layout[prop]; + if (!sig) return undefined; + if (sig.direction !== "input") this.flushDirty(); + return this.read(sig); + }, + set: (_, prop: string, value: PlaygroundSignalValue) => { + this.write(prop, value); + return true; + }, + }); + } + + fourStateOf(portName: string): PlaygroundFourStateValue { + const sig = this.signal(portName); + if (sig.direction !== "input") this.flushDirty(); + const value = this.read(sig); + const mask = sig.is_4state ? this.read(sig, 1) : 0n; + return { __fourState: true, value, mask }; + } + + dump(timestamp: number, sink: PlaygroundDumpSink | undefined): void { + this.flushDirty(); + const entries = Object.entries(this.layout); + sink?.( + timestamp, + entries.map(([name, sig]) => ({ name, width: sig.width })), + entries.map(([, sig]) => this.read(sig)), + ); + } +} + +/** + * A simulator with untimed ticks and explicit edges, as `Simulator` of + * `@celox-sim/celox`. + */ +export function createPlaygroundSimulator( + compiled: CompiledSimulator, + sink?: PlaygroundDumpSink, +) { + const design = new PlaygroundInstance(compiled); + const defaultEventId = + design.eventNames.length > 0 + ? (design.events[design.eventNames[0] as string] as number) + : -1; + const tickRuntime = { + defaultEventId, + knownEventIds: design.knownEventIds, + flushDirty: () => design.flushDirty(), + tickOne: (eventId: number) => design.tickOne(eventId), + }; + + const resolveEventId = (event: PlaygroundEvent | undefined): number => { + if (event === undefined) { + if (design.knownEventIds.size === 0) { + throw new Error("Simulator has no events"); + } + return defaultEventId; + } + const id = typeof event === "number" ? event : event.id; + if (!design.knownEventIds.has(id)) { + throw new RangeError(`Unknown event ID ${id}`); + } + return id; + }; + + const sim = { + dut: design.dut(), + warnings: [] as readonly string[], + tick(eventOrCount?: PlaygroundEvent, count?: number) { + runPlaygroundTicks(tickRuntime, eventOrCount, count); + }, + /** + * Move 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. + */ + edges( + moves: ReadonlyArray, + ) { + const ids: number[] = []; + const rising: boolean[] = []; + for (const [event, edge] of moves) { + if (edge !== "posedge" && edge !== "negedge") { + throw new RangeError(`Unknown clock edge '${String(edge)}'`); + } + ids.push(resolveEventId(event)); + rising.push(edge === "posedge"); + } + design.edges(ids, rising); + }, + /** Move a clock's signal to 1 and run every domain sensitive to it. */ + posedge(event?: PlaygroundEvent) { + sim.edges([[resolveEventId(event), "posedge"]]); + }, + /** Move a clock's signal to 0; see `posedge()`. */ + negedge(event?: PlaygroundEvent) { + sim.edges([[resolveEventId(event), "negedge"]]); + }, + /** The event's active edge. */ + activeEdge(event?: PlaygroundEvent) { + const id = resolveEventId(event); + sim.edges([[id, design.activeIsRising(id) ? "posedge" : "negedge"]]); + }, + /** The edge opposite to the event's active edge. */ + inactiveEdge(event?: PlaygroundEvent) { + 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) }; + }, + fourState(portName: string): PlaygroundFourStateValue { + return design.fourStateOf(portName); + }, + dump(timestamp: number) { + design.dump(timestamp, sink); + }, + dispose() {}, + }; + return sim; +} + +/** + * A timed simulation, as `Simulation` of `@celox-sim/celox`: scheduled + * signal changes at one time are coincident edges. + */ +export function createPlaygroundSimulation( + compiled: CompiledSimulator, + sink?: PlaygroundDumpSink, +) { + const design = new PlaygroundInstance(compiled); + const { layout } = design; + + type QueueEntry = { + time: number; + eventId: number; + nextVal: number; + clockHalfPeriod?: number; + }; + const queue: QueueEntry[] = []; + const clocks = new Map(); + let currentTime = 0; + + function enqueue(entry: QueueEntry) { + let lo = 0; + let hi = queue.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((queue[mid] as QueueEntry).time <= entry.time) lo = mid + 1; + else hi = mid; + } + queue.splice(lo, 0, entry); + } + + /** Pop every change at the next time and run them as coincident edges. */ + function processStep(): number | null { + const first = queue[0]; + if (!first) return null; + const t = first.time; + const batch: QueueEntry[] = []; + while (queue.length > 0 && (queue[0] as QueueEntry).time === t) { + batch.push(queue.shift() as QueueEntry); + } + currentTime = t; + design.edges( + batch.map((entry) => entry.eventId), + batch.map((entry) => entry.nextVal !== 0), + ); + design.flushDirty(); + for (const entry of batch) { + if (entry.clockHalfPeriod != null) { + enqueue({ + time: currentTime + entry.clockHalfPeriod, + eventId: entry.eventId, + nextVal: 1 - entry.nextVal, + clockHalfPeriod: entry.clockHalfPeriod, + }); + } + } + return currentTime; + } + + const dut = design.dut(); + const sim = { + dut, + warnings: [] as readonly string[], + + addClock(name: string, opts: { period: number; initialDelay?: number }) { + const eventId = design.resolveEvent(name); + clocks.set(name, { period: opts.period, eventId }); + // The first edge (0→1) at the delay, then toggles every half period. + enqueue({ + time: currentTime + (opts.initialDelay ?? 0), + eventId, + nextVal: 1, + clockHalfPeriod: opts.period / 2, + }); + }, + + schedule(name: string, opts: { time: number; value: number }) { + enqueue({ + time: opts.time, + eventId: design.resolveEvent(name), + nextVal: opts.value, + }); + }, + + step: processStep, + + time(): number { + return currentTime; + }, + + nextEventTime(): number | null { + return queue[0]?.time ?? null; + }, + + runUntil(endTime: number, opts?: { maxSteps?: number }) { + const max = opts?.maxSteps; + let steps = 0; + while (queue.length > 0 && (queue[0] as QueueEntry).time <= endTime) { + processStep(); + steps++; + if (max != null && steps >= max) { + throw new Error( + `runUntil: exceeded ${max} steps at time ${currentTime} (target ${endTime})`, + ); + } + } + currentTime = endTime; + }, + + waitUntil(condition: () => boolean, opts?: { maxSteps?: number }): number { + const max = opts?.maxSteps ?? 100_000; + let steps = 0; + while (!condition()) { + if (queue.length === 0) break; + processStep(); + steps++; + if (steps >= max) { + throw new Error( + `waitUntil: condition not met after ${max} steps at time ${currentTime}`, + ); + } + } + return currentTime; + }, + + waitForCycles( + clock: string, + count: number, + opts?: { maxSteps?: number }, + ): number { + if (!clocks.has(clock)) { + throw new Error( + `No clock registered for '${clock}'. Call addClock() first.`, + ); + } + const sig = layout[clock]; + if (!sig) throw new Error(`No layout entry for clock '${clock}'.`); + const readClk = () => design.view.getUint8(sig.offset) & 1; + let prev = readClk(); + let remaining = count; + return sim.waitUntil(() => { + const curr = readClk(); + if (prev === 0 && curr !== 0) remaining--; + prev = curr; + return remaining <= 0; + }, opts); + }, + + reset(signal: string, opts?: { activeCycles?: number; duration?: number }) { + const sig = design.signal(signal); + const typeKind: string = sig.type_kind ?? ""; + if (!typeKind.startsWith("reset")) { + throw new Error( + `Port '${signal}' is not a reset signal (type_kind: '${typeKind}').`, + ); + } + const isActiveLow = + typeKind === "reset_async_low" || typeKind === "reset_sync_low"; + const activeValue = isActiveLow ? 0n : 1n; + const inactiveValue = isActiveLow ? 1n : 0n; + + if (opts?.duration != null) { + dut[signal] = activeValue; + sim.runUntil(currentTime + opts.duration); + } else { + const firstClock = clocks.keys().next().value; + if (firstClock) { + dut[signal] = activeValue; + sim.waitForCycles(firstClock, opts?.activeCycles ?? 2); + } else { + // No clock registered: assert the reset as an edge of its own. + const eventId = design.events[signal]; + if (eventId !== undefined) { + dut[signal] = inactiveValue; + design.edges([eventId], [activeValue === 1n]); + design.flushDirty(); + } else { + dut[signal] = activeValue; + } + } + } + + dut[signal] = inactiveValue; + }, + + event(name: string): PlaygroundEventHandle { + return { name, id: design.resolveEvent(name) }; + }, + + fourState(portName: string): PlaygroundFourStateValue { + return design.fourStateOf(portName); + }, + + dump(timestamp: number) { + design.dump(timestamp, sink); + }, + + dispose() {}, + }; + return sim; +} diff --git a/packages/playground/test/playground-dts.test.ts b/packages/playground/test/playground-dts.test.ts index 215a5b41ad3..87ea9c8ce94 100644 --- a/packages/playground/test/playground-dts.test.ts +++ b/packages/playground/test/playground-dts.test.ts @@ -1,10 +1,59 @@ +import { readdirSync, readFileSync } from "node:fs"; import { describe, expect, test } from "vitest"; import { buildVirtualModuleDts, + celoxDtsLibs, extractPortsFromSource, } from "../src/playground-dts"; +const CELOX_DIST = new URL("../../celox/dist/", import.meta.url); + +function celoxDistDts(): Record { + const files: Record = {}; + for (const name of readdirSync(CELOX_DIST)) { + if (name.endsWith(".d.ts")) { + files[`../../celox/dist/${name}`] = readFileSync( + new URL(name, CELOX_DIST), + "utf8", + ); + } + } + return files; +} + +describe("celox declarations for Monaco", () => { + test("every import between them resolves and explicit edges are typed", () => { + const libs = celoxDtsLibs(celoxDistDts()); + const paths = new Set(libs.map((lib) => lib.filePath)); + for (const lib of libs) { + for (const [, name] of lib.content.matchAll( + /from\s+["']@celox-sim\/celox\/([\w-]+)["']/g, + )) { + expect(paths).toContain( + `file:///node_modules/@celox-sim/celox/${name}.d.ts`, + ); + } + // Imports of sibling modules all point into the package. + expect(lib.content).not.toMatch(/from\s+["']\.\/[\w-]+\.js["']/); + } + const simulator = libs.find((lib) => + lib.filePath.endsWith("/celox/simulator.d.ts"), + ); + for (const method of [ + "posedge(", + "negedge(", + "activeEdge(", + "inactiveEdge(", + "cycle(", + "edges(", + ]) { + expect(simulator?.content).toContain(method); + } + expect(paths).toContain("file:///node_modules/@celox-sim/celox/index.d.ts"); + }); +}); + describe("playground-dts", () => { test("4-state inputs accept FourStateSignalValue in virtual module DTS", () => { const ports = extractPortsFromSource(`module FourStateDemo ( diff --git a/packages/playground/test/playground-simulator-wasm.test.ts b/packages/playground/test/playground-simulator-wasm.test.ts new file mode 100644 index 00000000000..3e41fb8b612 --- /dev/null +++ b/packages/playground/test/playground-simulator-wasm.test.ts @@ -0,0 +1,151 @@ +/** + * The playground's own runtime over modules from the WASM addon: ticks, + * explicit edges and timed steps fire derived and gated clocks as the + * native simulator does. The expected counts are the native simulator's. + */ +import { loadNativeAddon, Simulator } from "@celox-sim/celox"; +import { describe, expect, test } from "vitest"; +import { + type CompilerHandle, + compiledFromHandle, +} from "../src/compile-simulator"; +import { + createPlaygroundSimulation, + createPlaygroundSimulator, +} from "../src/playground-simulator"; + +const isWasm = + !!process.env.NAPI_RS_WASI_FLAVOR || + process.env.NAPI_RS_FORCE_WASI === "true" || + process.env.NAPI_RS_FORCE_WASI === "error"; + +const CLOCKS = `module Top ( + clk: input clock, + en: input logic, + rising: output logic<8>, + falling: output logic<8>, + gated_count: output logic<8>, + divided_count: output logic<8>, +) { + always_ff (clk) { rising += 1; } + let inverted: '_ clock = ~clk; + always_ff (inverted) { falling += 1; } + let gated: '_ clock = clk & en; + always_ff (gated) { gated_count += 1; } + var half: logic; + always_ff (clk) { half = ~half; } + let divided: '_ clock = half; + always_ff (divided) { divided_count += 1; } +}`; + +// `clk` has no domain of its own: it only drives the gated clock. +const LEVER = `module Lever (clk: input clock, en: input logic, count: output logic<8>) { + let gated: '_ clock = clk & en; + always_ff (gated) { count += 1; } +}`; + +type WasmAddon = { + NativeSimulatorHandle: new ( + sources: { content: string; path: string }[], + top: string, + options?: { fourState?: boolean }, + ) => CompilerHandle & { dispose(): void }; +}; + +function compile(source: string, top: string) { + const addon = loadNativeAddon() as unknown as WasmAddon; + const handle = new addon.NativeSimulatorHandle( + [{ content: source, path: "top.veryl" }], + top, + { fourState: false }, + ); + try { + return compiledFromHandle(handle, false); + } finally { + handle.dispose(); + } +} + +describe.skipIf(!isWasm)("playground runtime (WASM)", () => { + test("explicit edges and ticks run derived and gated domains", () => { + const sim = createPlaygroundSimulator(compile(CLOCKS, "Top")); + const counts = () => + [ + sim.dut.rising, + sim.dut.falling, + sim.dut.gated_count, + sim.dut.divided_count, + ].map(Number); + const clk = sim.event("clk"); + sim.dut.en = 1n; + + sim.posedge(clk); + expect(counts()).toEqual([1, 0, 1, 1]); + sim.negedge(clk); + expect(counts()).toEqual([1, 1, 1, 1]); + sim.cycle(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]); + sim.dut.en = 0n; + sim.cycle(clk); + expect(counts()).toEqual([4, 3, 3, 2]); + // The clock is already at its inactive level: no edge. + sim.inactiveEdge(clk); + expect(counts()).toEqual([4, 3, 3, 2]); + sim.activeEdge(); + sim.edges([[clk, "negedge"]]); + expect(counts()).toEqual([5, 4, 3, 3]); + expect(() => sim.edges([[clk, "sideways" as "posedge"]])).toThrow( + RangeError, + ); + }); + + test("a clock that only drives a gated clock is an event", () => { + const sim = createPlaygroundSimulator(compile(LEVER, "Lever")); + const clk = sim.event("clk"); + sim.dut.en = 1n; + sim.cycle(clk); + sim.cycle(clk); + expect(sim.dut.count).toBe(2n); + sim.tick(clk); + expect(sim.dut.count).toBe(3n); + }); + + test("the package's WASM bridge also drives such a clock", () => { + const sim = Simulator.fromSource(LEVER, "Lever"); + const clk = sim.event("clk"); + sim.dut.en = 1n; + sim.cycle(clk); + sim.tick(clk); + expect(sim.dut.count).toBe(2n); + sim.dispose(); + }); + + test("timed steps fire derived and gated clocks", () => { + const sim = createPlaygroundSimulation(compile(CLOCKS, "Top")); + sim.dut.en = 1n; + sim.addClock("clk", { period: 10 }); + sim.runUntil(100); + expect( + [ + sim.dut.rising, + sim.dut.falling, + sim.dut.gated_count, + sim.dut.divided_count, + ].map(Number), + ).toEqual([11, 10, 11, 6]); + }); + + test("dump reports every signal to the sink", () => { + const dumps: { timestamp: number; names: string[] }[] = []; + const sim = createPlaygroundSimulator(compile(LEVER, "Lever"), (timestamp, signals) => + dumps.push({ timestamp, names: signals.map((s) => s.name) }), + ); + sim.dump(7); + expect(dumps).toHaveLength(1); + expect(dumps[0]?.timestamp).toBe(7); + expect(dumps[0]?.names).toEqual(expect.arrayContaining(["en", "count"])); + }); +});