Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/celox-frontend-veryl/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ pub fn schedule_symbolic_rtl(
})
}

/// The period of every `$tb::clock_gen` instance of `module`.
///
/// Veryl 0.22 keeps clock configuration on instance symbols, but only copies it
/// into ClockNext IR. Recover it while the analyzer symbols are still available,
/// using the specialization's overrides rather than a parameter's default.
Expand All @@ -262,11 +264,14 @@ fn configured_clock_periods(
let SymbolKind::Instance(instance) = &symbol.found.kind else {
continue;
};
// A clock variable declared by an instance is a `$tb::clock_gen`;
// without a `period` it has the default period.
let Some((_, target)) = instance
.parameter_connects
.iter()
.find(|(name, _)| name.text.to_string() == "period")
else {
periods.insert(symbol.found.token.text, 2);
continue;
};
let context = context.get_or_insert_with(|| {
Expand Down
18 changes: 17 additions & 1 deletion crates/celox-frontend-veryl/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use celox_testbench::{
AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, ExprBytecode,
ExprOpcode as TbOpcode, LoopBound as GenericLoopBound, SemanticArgument,
SemanticComponentBinding, SemanticSignal, SemanticStatement, SourceLocation, StateLocation,
TestbenchOperator as Op, TestbenchProgram, TestbenchSelection,
TestbenchClock, TestbenchOperator as Op, TestbenchProgram, TestbenchSelection,
TestbenchStatement as GenericTestbenchStatement, TestbenchTarget,
};
use fxhash::{FxHashMap as HashMap, FxHashSet};
Expand Down Expand Up @@ -2568,6 +2568,17 @@ impl<'a> SemanticTestbenchBuilder<'a> {
}
}

/// The `$tb::clock_gen` instances of this source's module.
fn clock_generators(&self) -> impl Iterator<Item = TestbenchClock<StateAddr>> + '_ {
self.testbench_source
.clock_periods
.iter()
.filter_map(|(&name, &period)| {
let (event, _) = self.named_variable(name)?;
Some(TestbenchClock { event, period })
})
}

fn named_variable(&self, name: StrId) -> Option<(StateAddr, &VariableInfo)> {
let instance = self.testbench_source.base_instance(self.lookup);
let module = self.lookup.instance_module.get(&instance)?;
Expand Down Expand Up @@ -3852,19 +3863,24 @@ pub fn compile_semantic_testbench(
.sum();
let mut site_end = runtime_event_site_count.saturating_sub(total_sites);
let mut processes = Vec::new();
let mut clocks = Vec::new();
for source in sources {
let initial_stmts = source.initial_statements.as_ref().unwrap();
validate_testbench_statements(initial_stmts, lookup, source, &mut FxHashSet::default())?;
site_end += count_assert_statements(initial_stmts, &source.functions);
let mut builder = SemanticTestbenchBuilder::new(lookup, source, site_end);
builder.prepared_readmem = super::readmem::prepare_testbench_memories(lookup, source)?;
builder.build_event_map(initial_stmts);
clocks.extend(builder.clock_generators());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Collect clocks from modules without initial blocks

When a clock generator belongs to a module with no initial block, it is excluded here because sources was filtered by initial_statements.is_some() above (and child sources without initial blocks may not be retained at all). If another process advances simulation time, that generator never enters ExecutableTestbench::clocks, so its signal and clocked domains remain idle despite the new guarantee that every $tb::clock_gen runs from time 0. Collect generators independently from the sources used to compile initial processes.

Useful? React with 👍 / 👎.

processes.extend(builder.convert(initial_stmts));
}
clocks.sort_unstable_by_key(|clock: &TestbenchClock<StateAddr>| clock.event);
clocks.dedup_by_key(|clock| clock.event);
let builder = SemanticTestbenchBuilder::new(lookup, source, runtime_event_site_count);
let component_bindings = builder.convert_component_bindings()?;
Ok(Some(
TestbenchProgram::from_processes(processes)
.with_clocks(clocks)
.with_private_variables(private_variables)
.with_random_seed_option(random_seed)
.with_components(source.components.clone())
Expand Down
38 changes: 27 additions & 11 deletions crates/celox-napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,36 +918,46 @@ enum HandleDerivedTicks {

#[cfg(not(target_arch = "wasm32"))]
impl HandleBackend {
/// Tick an event as `Simulator::tick` does: settle, run its domain,
/// settle, and run the derived clock domains the tick reaches.
/// Tick an event as `Simulator::tick` does: a pulse of its signal to
/// the active level, running every domain sensitive to its edges.
fn tick(
&mut self,
event_id: usize,
derived: &HandleDerivedTicks,
event_edges: &celox::EventEdges,
scratch: &mut celox::DerivedTickScratch,
) -> std::result::Result<(), celox::RuntimeErrorCode> {
fn tick_with<B: celox::SimBackend>(
backend: &mut B,
event_id: usize,
plans: &celox::DerivedTickPlans<B::Event>,
event_edges: &celox::EventEdges,
scratch: &mut celox::DerivedTickScratch,
) -> std::result::Result<(), celox::RuntimeErrorCode> {
let event = backend.id_to_event_slice()[event_id];
match plans.get(event_id) {
Some(Some(plan)) => plan.tick(&mut celox::BackendExecutor(backend), scratch, true),
_ => {
backend.eval_comb()?;
backend.eval_apply_ff_at(event)?;
backend.eval_comb()
}
let plan = plans.get(event_id).and_then(Option::as_ref);
match celox::run_tick(
&mut celox::BackendExecutor(backend),
plan,
event_edges[event_id],
scratch,
event,
true,
celox::set_level,
) {
Ok(()) => Ok(()),
// A bare backend reports no `$finish` or `$stop`; what ran
// settles here.
Err(celox::Halt::Finish | celox::Halt::Stop) => backend.eval_comb(),
Err(celox::Halt::Error(error)) => Err(error),
}
}
match (self, derived) {
(Self::Default(backend), HandleDerivedTicks::Default(plans)) => {
tick_with(backend, event_id, plans, scratch)
tick_with(backend, event_id, plans, event_edges, scratch)
}
(Self::Tiered(backend), HandleDerivedTicks::Tiered(plans)) => {
tick_with(backend.as_mut(), event_id, plans, scratch)
tick_with(backend.as_mut(), event_id, plans, event_edges, scratch)
}
_ => unreachable!("derived tick plans belong to the handle's backend"),
}
Expand Down Expand Up @@ -1544,6 +1554,7 @@ impl NativeSimulatorHandle {
b.tick(
event_id as usize,
&self.derived_ticks,
&self.event_edges,
&mut self.derived_scratch,
)
.map_err(|e| napi_runtime_error(&runtime_errors, e))
Expand Down Expand Up @@ -1620,6 +1631,7 @@ impl NativeSimulatorHandle {
b.tick(
event_id as usize,
&self.derived_ticks,
&self.event_edges,
&mut self.derived_scratch,
)
.map_err(|e| napi_runtime_error(&runtime_errors, e))?;
Expand Down Expand Up @@ -3958,9 +3970,13 @@ mod tests {

#[test]
fn native_handle_dumps_consume_activity_until_memory_is_exposed() {
// A tick writes `clk` as well as `q`. The wide inputs keep those two
// trace groups below half of the design, where a dump scans every
// signal.
let source = "module Top (
clk: input clock, q: output logic<64>,
a: input logic<512>, b: input logic<512>, c: input logic<512>,
d: input logic<512>, e: input logic<512>,
) { always_ff (clk) { q += 1; } }";
let dir = tempfile::tempdir().unwrap();
// Warm the uninstrumented cache first. A traced build must not reuse it.
Expand Down
12 changes: 6 additions & 6 deletions crates/celox-runtime/src/derived_tick.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Derived clock domains of an event-based tick.
//! Derived clock domains of an event-based edge.
//!
//! A tick is one active edge of an event. Clocks derived from the event run
//! with the rules of the timed scheduler:
//! A plan runs the domains one edge of an event reaches. Clocks derived from
//! the event run with the rules of the timed scheduler:
//!
//! - A clock computed combinationally from the event's signal, such as
//! `clk & enable`, changes at the same instant as the event. Its edge is
Expand All @@ -17,9 +17,9 @@
//! commit raises while the clock is high is a further edge. Each domain
//! fires at most once per phase.
//!
//! A tick is the event's active edge only and does not change the event's
//! signal. Domains that react to the signal's opposite edge, such as one
//! clocked by `~clk` or by a falling `clk & en`, do not run on a tick.
//! A plan's [`DerivedTickPlan::tick`] is the event's active edge with its
//! signal left as it is; the edge APIs move the signal around it, and a
//! `Simulator::tick` takes the active edge and then the inactive one.
//!
//! What an event can reach is computed when the simulator is built
//! ([`celox_design::EventTopology::derived_events`] and
Expand Down
52 changes: 52 additions & 0 deletions crates/celox-runtime/src/edge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ impl Edge {
Edge::Falling => 0,
}
}

/// The other transition.
pub fn opposite(self) -> Edge {
match self {
Edge::Rising => Edge::Falling,
Edge::Falling => Edge::Rising,
}
}
}

/// What an edge needs to know about one event.
Expand Down Expand Up @@ -346,3 +354,47 @@ where
moved_only(comb_read)
})
}

/// One tick of `event`: a clock period of its signal, defined as the
/// SystemVerilog statements
///
/// ```systemverilog
/// s <= A; #H;
/// s <= I; #L;
/// ```
///
/// where `A` and `I` are the event's active and inactive levels: the active
/// edge, then the inactive edge, each running every domain sensitive to it.
/// Combinational logic is settled afterwards. `dirty` says whether it has
/// pending changes; `write` moves the signal.
#[allow(clippy::too_many_arguments)]
pub fn run_tick<X, E>(
executor: &mut X,
plan: Option<&DerivedTickPlan<E>>,
info: EventEdge,
scratch: &mut DerivedTickScratch,
event: E,
dirty: bool,
mut write: impl FnMut(&mut X::Backend, SignalRef, u8),
) -> Result<(), Halt>
where
X: TickExecutor,
X::Backend: SimBackend<Event = E>,
E: EventHandle,
{
let active = info.active_edge();
let mut dirty = dirty;
for edge in [active, active.opposite()] {
dirty = match run_edge(
executor, plan, info, scratch, event, edge, dirty, &mut write,
)? {
EdgeOutcome::Unchanged | EdgeOutcome::Stored => dirty,
EdgeOutcome::Moved => true,
EdgeOutcome::Settled => false,
};
}
if dirty {
executor.eval_comb()?;
}
Ok(())
}
2 changes: 1 addition & 1 deletion crates/celox-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub use derived_tick::{
};
pub use edge::{
Edge, EdgeOutcome, EventEdge, EventEdges, SignalWrite, build_event_edges, move_signal,
run_edge, run_edges, set_level,
run_edge, run_edges, run_tick, set_level,
};
pub use error::{SimulatorErrorCode, comb_fatal_code, comb_fatal_site};
pub use event_buffer::RuntimeEventBuffer;
Expand Down
17 changes: 15 additions & 2 deletions crates/celox-runtime/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ use celox_testbench::{
AssertMessage as GenericAssertMessage, ClockCount as GenericClockCount, CompiledExpr,
ExecutableArgument, ExecutableAssertMessage, ExecutableClockCount, ExecutableLoopBound,
ExecutableStatement, ExecutableTestbench, ExprBytecode, LoopBound as GenericLoopBound,
SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchProgram,
TestbenchSelection, TestbenchStatement as GenericTestbenchStatement, TestbenchTarget,
SemanticArgument, SemanticComponentBinding, SemanticStatement, StateLocation, TestbenchClock,
TestbenchProgram, TestbenchSelection, TestbenchStatement as GenericTestbenchStatement,
TestbenchTarget,
};

use crate::{SignalRef, backend::SimBackend};
Expand Down Expand Up @@ -389,6 +390,17 @@ pub fn bind_testbench_program<B: SimBackend>(
}
}
let random_seed = program.configured_random_seed();
// A clock generator without an event drives no domain.
let clocks = program
.clocks()
.iter()
.filter_map(|clock| {
Some(TestbenchClock {
event: backend.resolve_event_opt(&clock.event)?,
period: clock.period,
Comment on lines +397 to +400

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep clock generators that have no event domain

Dropping a generator when resolve_event_opt returns None also prevents its signal from toggling, even though the signal can still be observed by testbench expressions. For example, while a domain-bearing period: 2 clock advances time, a second otherwise-unused period: 6 clock should be high at time 2; this filter leaves it permanently low, so assertions or conditions that sample it disagree with the documented SystemVerilog generator. Clocks without domains still need their signal transitions scheduled.

Useful? React with 👍 / 👎.

})
})
.collect();
let components = program.components().to_vec();
let component_libraries = program.component_libraries().to_vec();
let component_file_base = program.component_file_base().map(ToOwned::to_owned);
Expand All @@ -410,6 +422,7 @@ pub fn bind_testbench_program<B: SimBackend>(
.collect();
Some(
ExecutableTestbench::from_processes(processes, random_seed)
.with_clocks(clocks)
.with_private_signals(private_signals)
.with_component_runtime(
components,
Expand Down
35 changes: 35 additions & 0 deletions crates/celox-testbench/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,10 +271,21 @@ pub type SemanticStatement<A> = TestbenchStatement<
pub type SemanticComponentBinding<A> =
ComponentBinding<A, SemanticSignal<A>, ExprBytecode<StateLocation<A>>>;

/// A `$tb::clock_gen` instance: a clock that runs from time 0, rising at
/// multiples of `period` and falling `ceil(period / 2)` after each rise,
/// whether or not a process waits on it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestbenchClock<Event> {
pub event: Event,
/// At least two.
pub period: u64,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestbenchProgram<A> {
statements: Vec<SemanticStatement<A>>,
process_lengths: Vec<usize>,
clocks: Vec<TestbenchClock<A>>,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bump the native image container version

Adding clocks changes the postcard layout of TestbenchProgram, which is embedded directly in serialized NativeProgramImage, but CONTAINER_VERSION remains 28. A current runtime loading a version-28 image containing a testbench from before this commit therefore passes the version check and then misdecodes or rejects the shifted payload, and older runtimes likewise treat new images as the same format. Increment the native image container version with this schema change.

Useful? React with 👍 / 👎.

private_variables: Vec<A>,
random_seed: Option<u64>,
components: Vec<TestbenchComponent>,
Expand All @@ -288,6 +299,7 @@ impl<A> Default for TestbenchProgram<A> {
Self {
statements: Vec::new(),
process_lengths: Vec::new(),
clocks: Vec::new(),
private_variables: Vec::new(),
random_seed: None,
components: Vec::new(),
Expand All @@ -302,6 +314,7 @@ impl<A> TestbenchProgram<A> {
pub fn new(statements: Vec<SemanticStatement<A>>) -> Self {
Self {
process_lengths: vec![statements.len()],
clocks: Vec::new(),
private_variables: Vec::new(),
statements,
random_seed: None,
Expand All @@ -320,6 +333,16 @@ impl<A> TestbenchProgram<A> {
program
}

/// The clock generators of the testbench.
pub fn with_clocks(mut self, clocks: Vec<TestbenchClock<A>>) -> Self {
self.clocks = clocks;
self
}

pub fn clocks(&self) -> &[TestbenchClock<A>] {
&self.clocks
}

/// Temporaries whose values belong to each independently suspended process.
pub fn with_private_variables(mut self, variables: Vec<A>) -> Self {
self.private_variables = variables;
Expand Down Expand Up @@ -578,6 +601,7 @@ pub type ExecutableComponentBinding<Event, Signal> = ComponentBinding<Event, Sig
pub struct ExecutableTestbench<Event, Signal> {
statements: Vec<ExecutableStatement<Event, Signal>>,
process_lengths: Vec<usize>,
clocks: Vec<TestbenchClock<Event>>,
private_signals: Vec<Signal>,
random_seed: Option<u64>,
components: Vec<TestbenchComponent>,
Expand All @@ -597,6 +621,7 @@ impl<Event, Signal> ExecutableTestbench<Event, Signal> {
) -> Self {
Self {
process_lengths: vec![statements.len()],
clocks: Vec::new(),
private_signals: Vec::new(),
statements,
random_seed,
Expand Down Expand Up @@ -633,6 +658,16 @@ impl<Event, Signal> ExecutableTestbench<Event, Signal> {
program
}

/// The clock generators of the testbench.
pub fn with_clocks(mut self, clocks: Vec<TestbenchClock<Event>>) -> Self {
self.clocks = clocks;
self
}

pub fn clocks(&self) -> &[TestbenchClock<Event>] {
&self.clocks
}

pub fn with_private_signals(mut self, signals: Vec<Signal>) -> Self {
self.private_signals = signals;
self
Expand Down
Loading
Loading