From 903b7899fc733746b0e9bcf59a26d4212d845586 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 18:41:46 +0900 Subject: [PATCH] feat(sv): support $sampled in processes Implement sampled values for static variables using copies captured before advancing to a later timestamp (IEEE 1800-2023 16.5.1 and 16.9.3). Initialize from declarations, preserve automatic variables, and copy strided arrays through their layouts. Same-timestamp host resumptions and writes retain the Preponed baseline; untimed Simulator calls each form a slot. Resolve sampled select operands before hoisting nested calls, including calls with side effects. Cover timed host-only writes, repeated run_until calls, bounded runs, step, advance_to, and report watching. Verify that the compiled scheduler actually executes in the regression. The runtime schema gains sample_shadows; native image version is 42. Combinational $sampled and handle operands remain unsupported in this stack member. Validation: - sv_sampled: 35 passed across interpreter, native, actual Cranelift and WASM. - Celox/runtime unit tests: 309 passed. - Time, stop, state-file, runtime API, clock and image consumers: 110 passed, 2 ignored. - Formatting and affected-crate Clippy with -D warnings. Change-Id: I764da6c419a54df2ca88f784d797f22e5c8520eb --- crates/celox-design/src/lib.rs | 6 + crates/celox-design/src/schedule.rs | 4 + crates/celox-frontend-core/src/sdk.rs | 1 + .../src/symbolic/artifact.rs | 3 + .../src/symbolic/assembly.rs | 20 ++ crates/celox-frontend-sv/src/lowering.rs | 59 +++- crates/celox-frontend-sv/src/lowering/ff.rs | 76 ++++- .../src/lowering/procedural.rs | 22 ++ crates/celox-frontend-veryl/src/artifact.rs | 1 + crates/celox-runtime/src/lib.rs | 23 ++ crates/celox-runtime/src/schedule.rs | 7 + crates/celox-runtime/src/simulation/batch.rs | 2 - .../celox-runtime/src/simulation/compiled.rs | 20 +- crates/celox-runtime/src/simulation/mod.rs | 14 + crates/celox-runtime/src/simulation/round.rs | 4 +- crates/celox-runtime/src/simulation/time.rs | 15 +- .../src/ast/expression_binding/direct.rs | 6 + .../celox-sv-analyzer/src/ast/expressions.rs | 28 ++ .../celox-sv-analyzer/src/system_functions.rs | 13 +- crates/celox/src/backend/native/backend.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 20 +- crates/celox/src/simulator.rs | 169 ++++++++++- crates/celox/tests/sv_sampled.rs | 264 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 16 ++ docs/ja/guide/systemverilog-reference.md | 13 + 26 files changed, 760 insertions(+), 52 deletions(-) create mode 100644 crates/celox/tests/sv_sampled.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 3f34f2b61fc..a85be9c3be6 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1105,6 +1105,11 @@ pub struct RuntimeSchema { /// most one per module instance. Before each round a timed scheduler /// stores the current time into each, as [`TIME_SLOT_WIDTH`] bits. pub time_slots: Vec, + /// Variables of `$sampled` operands and their copies, which hold the + /// value of the variable in the Preponed region (IEEE 1800-2023 + /// 16.5.1): a host copies each variable into its copy when a time slot + /// is over, and once before the first. + pub sample_shadows: Vec<(A, A)>, /// The state a compiled scheduler exchanges with the runtime, and the /// scheduler itself once one is generated. Present when the design has /// process kernels. @@ -1359,6 +1364,7 @@ impl Default for RuntimeSchema { host_request_sites: Vec::new(), active_commits: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), scheduler: None, derived_edges: Vec::new(), settle_partitions: None, diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index bbe9a4a74fe..a8b28da4739 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -46,6 +46,9 @@ pub struct ScheduleModel { /// Objects the scheduler stores the current time into /// ([`RuntimeSchema::time_slots`]). pub time_slots: Vec, + /// Sampled variables and their copies + /// ([`RuntimeSchema::sample_shadows`]). + pub sample_shadows: Vec<(A, A)>, /// The compiled scheduler, if one was generated /// ([`RuntimeSchema::scheduler`]). pub scheduler: Option>, @@ -152,6 +155,7 @@ impl ScheduleModel { .any(|site| matches!(site.kind, RuntimeEventKind::Finish)), active_commits: schema.active_commits.clone(), time_slots: schema.time_slots.clone(), + sample_shadows: schema.sample_shadows.clone(), scheduler: schema.scheduler.clone(), } } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 978966f9d2f..b17909e54cd 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1972,6 +1972,7 @@ pub fn lower_frontend_artifact( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), }; let symbolic = SymbolicRtl { modules: [(module_id, sim_module.clone())].into_iter().collect(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 13d9d614ced..6f6acef4356 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -159,6 +159,9 @@ pub struct SimModule { /// The variable through which the module's code reads the simulation /// time; see `RuntimeSchema::time_slots`. pub time_slot: Option, + /// Variables and their sampled copies; see + /// `RuntimeSchema::sample_shadows`. + pub sample_shadows: Vec<(SourceVarId, SourceVarId)>, } /// A nonblocking site whose kernel has two paths, as diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 288fda6029b..766715c6749 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2135,6 +2135,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( nba_sites, host_request_sites, time_slots, + sample_shadows, .. } = timing; let source_sir = SirProgram { @@ -2386,6 +2387,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(); let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); + let sample_shadows: Vec<(StateAddr, StateAddr)> = sample_shadows + .into_iter() + .map(|(variable, copy)| (project(variable), project(copy))) + .collect(); let root_instance = expanded[&InstancePath(Vec::new())]; let settle_partitions = settle_flags.map(|settle| { let mut marks: HashMap> = HashMap::default(); @@ -2509,6 +2514,12 @@ pub fn schedule_symbolic_rtl_reporting_loops( .flat_map(|(source, counter)| [source.id, *counter]), ); } + // The host copies each sampled variable into its copy. + timing_read_roots.extend( + sample_shadows + .iter() + .flat_map(|&(variable, copy)| [variable, copy]), + ); // A package variable's state object maps back to the package's own // variable, not to one of its aliases. let state_to_source = source_to_state @@ -2561,6 +2572,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( host_request_sites, active_commits, time_slots, + sample_shadows, scheduler, derived_edges: Vec::new(), settle_partitions, @@ -4113,6 +4125,7 @@ struct TimingMetadata { nba_sites: Vec>, host_request_sites: Vec>, time_slots: Vec, + sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, nba_switches: Vec>, } @@ -4435,6 +4448,7 @@ fn relocate_timing( nba_sites: Vec::new(), host_request_sites: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), nba_switches: Vec::new(), }; for (&instance, module) in instances { @@ -4470,6 +4484,12 @@ fn relocate_timing( }), ); metadata.time_slots.extend(module.time_slot.map(locate)); + metadata.sample_shadows.extend( + module + .sample_shadows + .iter() + .map(|&(variable, copy)| (locate(variable), locate(copy))), + ); metadata.nba_switches.extend( module .nba_switches diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 763987247b7..98a11f435f2 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -87,6 +87,9 @@ struct SvVariable { hidden: bool, /// Compiler-generated external override slot: (target, is_enable). force_control: Option<(SourceVarId, bool)>, + /// The variable whose sampled value this hidden copy holds + /// (`SimModule::sample_shadows`). + sampled_from: Option, } /// Whether `expr` reads a string variable: after its calls are hoisted, a @@ -126,13 +129,14 @@ impl SvVariable { } /// A hidden variable other than the time slot, whose value the lowered - /// code computes. The time slot is state the scheduler writes, and an - /// event expression's variables are state its process and its - /// continuous assignment share. + /// code computes. The time slot and the sampled copies are state the + /// scheduler writes, and an event expression's variables are state its + /// process and its continuous assignment share. fn is_scratch(&self) -> bool { self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() + && self.sampled_from.is_none() && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -2198,6 +2202,7 @@ fn prepare_external_hierarchy_collecting( source: variable.source.clone(), hidden: !variable.module_affiliated, force_control: None, + sampled_from: None, }, ) }) @@ -3629,6 +3634,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); @@ -3713,6 +3719,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }; name_to_id.insert(signal.name().to_string(), id); // The package's object, or the other instance's, has its own @@ -3793,6 +3800,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }, ); } @@ -4005,6 +4013,7 @@ fn lower_module_with_overrides( nba_switches, host_request_sites, time_slot: name_to_id.get(TIME_SLOT).copied(), + sample_shadows: Vec::new(), }, variables, port_order, @@ -4793,6 +4802,12 @@ pub(crate) fn attach_instance_glue( } // Combinational processes may read the time too. module.time_slot = signal_names.get(TIME_SLOT).copied(); + let mut sample_shadows: Vec<_> = parent_variables + .iter() + .filter_map(|(©, variable)| variable.sampled_from.map(|variable| (variable, copy))) + .collect(); + sample_shadows.sort_by_key(|&(variable, copy)| (variable.0, copy.0)); + module.sample_shadows = sample_shadows; for (instance, child_id, child, connections) in resolved_instances { let glue = build_instance_glue( &parent_variables, @@ -5187,6 +5202,7 @@ fn lower_initial_processes( // Control slots are not signals of the design. hidden: true, force_control: None, + sampled_from: None, }, ); id @@ -5831,6 +5847,7 @@ fn ensure_parent_output_signals( source: None, hidden: false, force_control: None, + sampled_from: None, }; parent .variables @@ -7713,6 +7730,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::Isunbounded | SystemFunction::Signed | SystemFunction::Unsigned + | SystemFunction::Sampled | SystemFunction::Bits | SystemFunction::Size | SystemFunction::Dimensions @@ -9077,6 +9095,15 @@ fn runtime_select_as_shift( } fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { + expr_from_const_expr_with_calls(expr, false) +} + +/// Reconstruct a select operand, optionally retaining nested runtime calls. +fn expr_from_const_expr_with_calls( + expr: &sv::ir::ConstExpr, + allow_calls: bool, +) -> Option { + let convert = |expr| expr_from_const_expr_with_calls(expr, allow_calls); Some(match expr { sv::ir::ConstExpr::Literal(value) => sv::ir::Expr::Literal(value.clone()), sv::ir::ConstExpr::Ident(name) => sv::ir::Expr::Ident(name.clone()), @@ -9086,13 +9113,13 @@ fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { lsb, signed, } => sv::ir::Expr::Select { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), msb: (**msb).clone(), lsb: (**lsb).clone(), signed: *signed, }, sv::ir::ConstExpr::Select { expr, bit } => sv::ir::Expr::Select { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), msb: (**bit).clone(), lsb: (**bit).clone(), signed: false, @@ -9102,28 +9129,36 @@ fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { width, signed, } => sv::ir::Expr::Resize { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), width: *width, signed: *signed, }, + sv::ir::ConstExpr::Function { callee, args, .. } if allow_calls => sv::ir::Expr::Call { + callee: callee.clone(), + arg_order: Vec::new(), + args: args + .iter() + .map(|arg| convert(arg).map(Some)) + .collect::>()?, + }, sv::ir::ConstExpr::Function { .. } => return None, sv::ir::ConstExpr::Unary { op, expr } => sv::ir::Expr::Unary { op: *op, - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), }, sv::ir::ConstExpr::Binary { left, op, right } => sv::ir::Expr::Binary { - left: Box::new(expr_from_const_expr(left)?), + left: Box::new(convert(left)?), op: *op, - right: Box::new(expr_from_const_expr(right)?), + right: Box::new(convert(right)?), }, sv::ir::ConstExpr::Mux { condition, then_expr, else_expr, } => sv::ir::Expr::Mux { - condition: Box::new(expr_from_const_expr(condition)?), - then_expr: Box::new(expr_from_const_expr(then_expr)?), - else_expr: Box::new(expr_from_const_expr(else_expr)?), + condition: Box::new(convert(condition)?), + then_expr: Box::new(convert(then_expr)?), + else_expr: Box::new(convert(else_expr)?), }, }) } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 26ef54d8fb1..7a1bbbff731 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -102,6 +102,8 @@ pub(super) struct Ff<'p, 'a> { /// The flush-point site of a process with deferred assertions, whose /// queue their actions wait in. flush_site: Option, + /// A combinational process is being lowered. + combinational: bool, } fn stable(var_id: SourceVarId) -> Addr { @@ -161,9 +163,44 @@ impl<'p, 'a> Ff<'p, 'a> { host_request_sites: Vec::new(), nba_switches: Vec::new(), flush_site: None, + combinational: false, } } + /// The operand of `$sampled` (IEEE 1800-2023 16.9.3) with each static + /// variable read through its sampled copy. Automatic variables and the + /// lowering's own temporaries keep their current value (16.5.1). A + /// combinational process reruns when its inputs change, not when their + /// sampled values do, so it cannot read them. + fn sampled( + &mut self, + args: &[Option], + ) -> Result { + if self.combinational { + return Err(unsupported("$sampled in combinational logic")); + } + let [Some(operand)] = args else { + return Err(unsupported("operand of `$sampled`")); + }; + let operand = self.propagate(operand); + let mut names = HashSet::default(); + expr_idents(&operand, &mut names); + let mut renames = HashMap::default(); + for name in names { + let Some(id) = self.m.id(&name) else { + continue; + }; + if self.m.is_hidden(id) { + continue; + } + if self.m.var(id).value_kind.is_handle() { + return Err(unsupported("$sampled of a string or class handle")); + } + renames.insert(name, self.m.sampled_copy(id)); + } + Ok(rename_idents(&operand, &renames)) + } + /// Whether `stmts`, or a subroutine they call, including in timing /// controls and the defaults of omitted arguments, hold a deferred /// assertion. @@ -779,8 +816,18 @@ impl<'p, 'a> Ff<'p, 'a> { } let mut lowered = Vec::with_capacity(args.len()); for arg in args { - let arg = self.hoist_const(arg, calls)?; - lowered.push(expr_from_const_expr(&arg).ok_or_else(|| { + // $sampled must rewrite its operand before any nested + // call reads it. Hoisting first hides the original inputs + // behind a temporary holding their current-slot value. + let arg = if matches!( + callee, + sv::ir::Callee::System(sv::ir::SystemFunction::Sampled) + ) { + arg.clone() + } else { + self.hoist_const(arg, calls)? + }; + lowered.push(expr_from_const_expr_with_calls(&arg, true).ok_or_else(|| { unsupported(format!("argument of `{callee}` in a select")) })?); } @@ -789,8 +836,19 @@ impl<'p, 'a> Ff<'p, 'a> { callee: callee.clone(), args: lowered.into_iter().map(Some).collect(), }; - let sv::ir::Expr::Ident(result) = self.hoist(&call)? else { - return Err(unsupported(format!("call of `{callee}` in a select"))); + let result = match self.hoist(&call)? { + sv::ir::Expr::Ident(result) => result, + // A sampled operand, as `$sampled(i + 1)`: its value at + // this point is the select's. + hoisted @ sv::ir::Expr::Binary { .. } + | hoisted @ sv::ir::Expr::Unary { .. } => { + let value = self.eval(&hoisted, None)?; + let width = self.b.register(&value).width(); + let (temp, name) = self.m.temp("select", width, false, true); + self.store(temp, SIROffset::Static(0), width, value); + name + } + _ => return Err(unsupported(format!("call of `{callee}` in a select"))), }; let result = ConstExpr::Ident(result); calls.push((expr.clone(), result.clone())); @@ -1074,6 +1132,14 @@ impl<'p, 'a> Ff<'p, 'a> { self.assign(&sv::ir::LValue::Ident(name.clone()), value)?; Expr::Ident(name) } + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Sampled), + args, + .. + } => { + let operand = self.sampled(args)?; + self.hoist(&operand)? + } Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fread), args, @@ -4064,6 +4130,7 @@ impl<'p, 'a> Ff<'p, 'a> { // `initial` blocks, like `always_comb`, as Verilator settles them. let runs_at_time_zero = always_comb || !self.m.four_state; self.direct = true; + self.combinational = true; let mut reads = self.m.implicit_reads(body, always_comb); reads.extend(self.m.implicit_reads(sensitivity_body, always_comb)); for stmt in body { @@ -6076,6 +6143,7 @@ impl Ff<'_, '_> { source: None, hidden: true, force_control: None, + sampled_from: None, value_kind: Default::default(), }, ); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 37095d43ae5..404fb18d038 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -974,6 +974,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, }, ); self.name_to_id.insert(name, id); @@ -982,6 +983,24 @@ impl<'a> ProcModule<'a> { } /// A hidden variable with the shape of `id`, two-state when `two_state`. + /// The hidden copy that holds the sampled value of variable `id` + /// (IEEE 1800-2023 16.5.1), created on first use. + pub fn sampled_copy(&mut self, id: SourceVarId) -> String { + if let Some((name, _)) = self + .name_to_id + .iter() + .find(|(_, copy)| self.variables[copy].sampled_from == Some(id)) + { + return name.clone(); + } + let (copy, name) = self.shadow(id, "sampled", false); + self.variables + .get_mut(©) + .expect("a new copy") + .sampled_from = Some(id); + name + } + pub fn shadow( &mut self, id: SourceVarId, @@ -1040,6 +1059,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, }; let id = next_var_id(&mut self.next_id); self.variables.insert(id, variable); @@ -1070,6 +1090,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, ..variable }, ); @@ -1597,6 +1618,7 @@ pub(super) fn register_locals( source: None, hidden: true, force_control: None, + sampled_from: None, }, ); name_to_id.insert(local.name.clone(), id); diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 49fdb07fc6b..526b5b7dbf0 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -682,6 +682,7 @@ pub(crate) fn project_module_with_ids( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), }, ids, inferred_latch_diagnostics, diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 2a07d54399b..71aaa07ba01 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -142,6 +142,29 @@ pub struct SignalRef { pub array_layout: Option, } +/// Copy the value of `from`, with its unknown bits, into `to`, a signal of +/// the same width and state form. +pub fn copy_signal(backend: &mut B, from: SignalRef, to: SignalRef) { + if from.array_layout.is_some() || to.array_layout.is_some() { + // Each array has its own layout, packed or with strided elements: + // the backend gathers and scatters the elements. + let (value, mask) = backend.get_four_state(from); + backend.set_four_state(to, value, mask); + return; + } + let planes = if backend.layout().four_state && from.is_4state { + 2 + } else { + 1 + }; + let bytes = celox_state_layout::get_byte_size(from.width) * planes; + let (memory, size) = backend.memory_as_mut_ptr(); + assert!(from.offset + bytes <= size && to.offset + bytes <= size); + // SAFETY: both ranges are in the backend's memory. Signal views can + // alias, so use the copy operation that permits overlapping ranges. + unsafe { std::ptr::copy(memory.add(from.offset), memory.add(to.offset), bytes) }; +} + #[cfg(test)] mod array_layout_tests { use super::SignalArrayLayout; diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 436f3c1fc08..7ec03666d06 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -43,6 +43,8 @@ pub struct ResolvedSchedule { pub(crate) active_commits: bit_set::BitSet, /// Signals the current time is stored into before each round. pub(crate) time_slots: Vec, + /// Sampled variables and their copies, captured before entering a later timestamp. + pub(crate) sample_shadows: Vec<(SignalRef, SignalRef)>, /// The compiled scheduler, when one was generated. pub(crate) scheduler: Option, /// Per process kernel, why the compiled scheduler does not run it, or @@ -336,6 +338,11 @@ impl ResolvedSchedule { timed: model.timed, active_commits, time_slots: model.time_slots.iter().map(resolve).collect(), + sample_shadows: model + .sample_shadows + .iter() + .map(|(variable, copy)| (resolve(variable), resolve(copy))) + .collect(), scheduler: model.scheduler.as_ref().and_then(|scheduler| { let slots = &scheduler.slots; let mut refs = SchedulerRefs { diff --git a/crates/celox-runtime/src/simulation/batch.rs b/crates/celox-runtime/src/simulation/batch.rs index 449175c28cc..6b6eeea398b 100644 --- a/crates/celox-runtime/src/simulation/batch.rs +++ b/crates/celox-runtime/src/simulation/batch.rs @@ -119,8 +119,6 @@ impl SimulationState { where E: SimulationExecutor, { - self.scheduler.time = current_time; - let num_events = executor.backend().num_events(); let counted = !self.model.counted.is_empty(); for event in &events_to_process { diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index df6c6b04732..0b3133476a8 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -124,7 +124,7 @@ impl SimulationState { let one_slot = match executor.compiled_slots() { CompiledSlots::None => return None, CompiledSlots::One => true, - CompiledSlots::Any => one_slot, + CompiledSlots::Any => one_slot || self.one_slot_runs(), }; Some(if one_slot { first @@ -176,6 +176,11 @@ impl SimulationState { where E: SimulationExecutor, { + // Designs with sampled values are limited to one slot, so `limit` + // is that slot's timestamp. Keep its baseline on same-time reentry. + if self.one_slot_runs() && limit > self.scheduler.time { + self.sample_values(executor.backend_mut()); + } let scheduler = self .model .scheduler @@ -418,6 +423,19 @@ impl SimulationState { if executor.take_slot_writes() { self.host_pending = true; } + // A run of one slot ends it unless work is left at its time. + if (self.one_slot_runs() || executor.compiled_slots() == CompiledSlots::One) + && !self.host_pending + && self.next_work_time() != Some(now) + { + self.end_time_slot(executor, now)?; + } Ok(now) } + + /// Whether every run of the compiled scheduler takes one slot: the + /// sampled copies are made before entering each later timestamp. + fn one_slot_runs(&self) -> bool { + !self.model.sample_shadows.is_empty() + } } diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 0a57c8a08b0..bc1af0b2da8 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -552,9 +552,23 @@ impl SimulationState { /// Move to `time` without running anything there, as the end of a run /// to a time without work does. Design code reads the new time. pub fn advance_time(&mut self, backend: &mut B, time: u64) { + if time > self.scheduler.time { + self.sample_values(backend); + } self.set_time(backend, time); } + /// Copy each sampled variable into its copy, which then holds the value + /// the variable has in the Preponed region of the next time slot (IEEE + /// 1800-2023 4.4.2.1, 16.5.1). A timed simulation does it before + /// advancing to a later timestamp and once before the first slot. + /// Returning to the host at the same timestamp must retain the copy. + pub fn sample_values(&self, backend: &mut B) { + for &(variable, copy) in &self.model.sample_shadows { + crate::copy_signal(backend, variable, copy); + } + } + /// Store `time` where design code reads the simulation time (`$time`). fn publish_time(&self, backend: &mut B, time: u64) { for &slot in &self.model.time_slots { diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 881f1d146e6..5ab9a9d3a57 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -441,12 +441,10 @@ impl SimulationState { where E: SimulationExecutor, { - self.publish_time(executor.backend_mut(), current_time); + self.advance_time(executor.backend_mut(), current_time); if !self.model.timed { return self.batch_round(executor, current_time, events_to_process); } - self.scheduler.time = current_time; - // Host writes the waits must see one at a time. for (signal, value) in executor.take_host_writes() { self.observe_host_write(signal, &value); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index a48ba7bd963..cad499b6469 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -214,7 +214,7 @@ impl SimulationState { // The slot is over when nothing more is due at its time, host // writes included. if !self.host_pending && self.next_work_time() != Some(current_time) { - executor.try_end_time_slot(current_time)?; + self.end_time_slot(executor, current_time)?; } Ok(()) } @@ -228,6 +228,19 @@ impl SimulationState { || !state.re_nba_queue.is_empty() } + /// Run the host's Observed and Postponed work after quiescence. + /// The host may resume this timestamp, so sampling waits for time advance. + pub(super) fn end_time_slot( + &mut self, + executor: &mut E, + current_time: u64, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + executor.try_end_time_slot(current_time) + } + /// Count a round or a pass of the process phase against the slot's /// budget, so that processes resuming at one time forever end the step /// with an error instead of hanging it. diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 41d24194d86..d769b5e4a65 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1787,6 +1787,12 @@ pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> .functions .get(name) .is_some_and(|function| function.return_real), + // A sampled value has the type of its operand. + Expr::Call { + callee: Callee::System(SystemFunction::Sampled), + args, + .. + } => matches!(args.first(), Some(Some(operand)) if real_value(operand, dimensions)), Expr::Unary { op: UnaryOp::Plus | UnaryOp::Minus | UnaryOp::ToTwoState, expr, diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index c19568558e4..8b451cf93d7 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -139,6 +139,34 @@ pub(super) fn numeric_system_function( signed: function == SystemFunction::Signed, }) } + // The sampled value has the type of its operand; the frontend reads + // it from the operand's sampled copy (IEEE 1800-2023 16.9.3). + SystemFunction::Sampled => { + let argument = arguments.pop().ok_or_else(operand_error)?; + // A real operand keeps its type: an integral resize would + // round it. + if expression_binding::real_value(&argument, dimensions) { + return Ok(Expr::Call { + callee: Callee::System(function), + args: vec![Some(argument)], + arg_order: Vec::new(), + }); + } + let width = + expr_static_width(state, &argument, dimensions).ok_or_else(operand_error)?; + let signed = + dimensions::expression_signedness(&argument, dimensions, &dimensions.const_env) + .ok_or_else(operand_error)?; + Ok(Expr::Resize { + expr: Box::new(Expr::Call { + callee: Callee::System(function), + args: vec![Some(argument)], + arg_order: Vec::new(), + }), + width, + signed, + }) + } SystemFunction::Ln | SystemFunction::Log10 | SystemFunction::Exp diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index f6e85cb53f9..3b541bf184e 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -60,6 +60,9 @@ pub enum SystemFunction { Signed, /// `$unsigned` (11.7). Unsigned, + /// `$sampled` (IEEE 1800-2023 16.9.3): the value of its operand in the + /// Preponed region of the time slot. + Sampled, /// `$bits` (20.6.2). Bits, /// `$isunbounded` (20.6.3). @@ -253,6 +256,7 @@ impl SystemFunction { Self::Timeprecision => "$timeprecision", Self::Signed => "$signed", Self::Unsigned => "$unsigned", + Self::Sampled => "$sampled", Self::Bits => "$bits", Self::Isunbounded => "$isunbounded", Self::Dimensions => "$dimensions", @@ -354,7 +358,11 @@ impl SystemFunction { /// or it returns the simulation time. Such a call is not a constant /// expression, and a process evaluates it where it runs. pub fn reads_simulation_state(self) -> bool { - self.is_effectful() || matches!(self, Self::Time | Self::Stime | Self::Realtime) + self.is_effectful() + || matches!( + self, + Self::Time | Self::Stime | Self::Realtime | Self::Sampled + ) } /// Whether the call writes argument `position` back, as `$random(seed)` @@ -440,6 +448,7 @@ impl SystemFunction { Self::Time => Some((64, false)), Self::Signed | Self::Unsigned + | Self::Sampled | Self::Bits | Self::Dimensions | Self::UnpackedDimensions @@ -1141,7 +1150,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$assertvacuousoff", Task), unsupported("$assertcontrol", Task), // 20.12 Sampled value system functions - unsupported("$sampled", Function), + function(SystemFunction::Sampled, 1, Some(1)), unsupported("$rose", Function), unsupported("$fell", Function), unsupported("$stable", Function), diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index b605d44113b..e050bed0c41 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -418,6 +418,8 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) host_request_sites: Vec>, pub(crate) active_commits: Vec, pub(crate) time_slots: Vec, + #[serde(default)] + pub(crate) sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, pub(crate) scheduler: Option>, pub(crate) derived_edges: Vec>, } @@ -591,6 +593,7 @@ impl NativeProgramImage { host_request_sites: self.runtime_schema.host_request_sites.clone(), active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), + sample_shadows: self.runtime_schema.sample_shadows.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), settle_partitions: None, @@ -2640,6 +2643,7 @@ fn compile_program( declaration_startup: sir.runtime().runtime_schema.declaration_startup.clone(), active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), + sample_shadows: sir.runtime().runtime_schema.sample_shadows.clone(), scheduler: sir.runtime().runtime_schema.scheduler.clone(), derived_edges: sir.runtime().runtime_schema.derived_edges.clone(), }, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a697a472d00..1b329072c48 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 41; +const CONTAINER_VERSION: u16 = 42; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index dfc7e05abd1..8e8137bd495 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -271,19 +271,14 @@ impl HostBoundary for Simulator { fn compiled_slots(&self) -> celox_runtime::CompiledSlots { use celox_runtime::CompiledSlots; - // Deferred assertions mature when a slot is over, which the - // runtime's loop tells apart from the end of a step. - if self.frozen - || !self.components.is_empty() - || self.deferred_assertions - || !self.backend.runs_compiled_scheduler() - { + if self.frozen || !self.components.is_empty() || !self.backend.runs_compiled_scheduler() { return CompiledSlots::None; } - // Waveforms record, the heap collects and a slot observer looks at - // every slot boundary. + // Waveforms record, the heap collects, deferred assertions mature + // and a slot observer looks at every slot boundary. let vcd = &self.sv_vcd; - if self.slot_observer.is_some() + if self.deferred_assertions + || self.slot_observer.is_some() || self.vcd_writer.is_some() || vcd.path.is_some() || vcd.started.is_some() @@ -458,6 +453,9 @@ impl Simulation { simulator.timed = true; simulator.skip_runtime_finish(); state.initialize_declarations(&mut simulator)?; + // Before the first slot, a sampled value is the declared or default + // value (IEEE 1800-2023 16.5.1). + state.sample_values(&mut simulator.backend); Ok(Self { simulator, state, @@ -761,7 +759,7 @@ impl Simulation { /// run at that time. #[inline] fn end_idle_slot(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { - if !self.simulator.deferred_assertions + if !self.simulator.host_slot_work || end_time <= self.state.time() || self.state.next_event_time() == Some(self.state.time()) { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d0e1e8c7398..0db616ec3fe 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -161,6 +161,12 @@ mod host { /// A timed simulation owns this simulator: a time slot ends when its /// scheduler says so, not when combinational logic settles. pub(crate) timed: bool, + /// Sampled variables and their copies + /// (`RuntimeSchema::sample_shadows`). + sample_shadows: Vec<(SignalRef, SignalRef)>, + /// Deferred assertions or sampled copies have work when a host + /// call's time slot is over. + pub(crate) host_slot_work: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -1030,6 +1036,17 @@ mod host { } else { Vec::new() }; + let sample_shadows: Vec<(SignalRef, SignalRef)> = program + .runtime_schema + .sample_shadows + .iter() + .map(|(variable, copy)| { + ( + backend.resolve_signal(variable), + backend.resolve_signal(copy), + ) + }) + .collect(); let mut comb_deferred_groups: Vec<(u32, usize)> = Vec::new(); for observer in &program.runtime_schema.comb_observers { if matches!( @@ -1066,6 +1083,8 @@ mod host { deferred_assertions: !deferred_sites.is_empty(), comb_deferred_groups, timed: false, + host_slot_work: !deferred_sites.is_empty() || !sample_shadows.is_empty(), + sample_shadows, components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1321,13 +1340,12 @@ mod host { } } - /// Without a scheduler, a host call is a time slot: mature the - /// deferred assertions it ran. + /// Without a scheduler, a host call is a time slot: end it. fn end_untimed_slot(&mut self) -> Result<(), RuntimeErrorCode> { if self.timed { return Ok(()); } - self.mature_deferred_assertions() + self.end_host_slot() } pub(crate) fn drain_runtime_events_deferred_with_context( @@ -1469,6 +1487,53 @@ mod host { self.host_watch.set_log(other.host_watch.log().to_vec()); } + /// A host call without a scheduler is a time slot, which is over: + /// deferred assertions mature, then the sampled copies are made. + #[inline] + fn end_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.host_slot_work { + return Ok(()); + } + self.finish_host_slot() + } + + /// A host call without a scheduler begins a time slot. Logic that + /// host writes since the previous call left dirty settles first, in + /// the previous slot, which then ends: the call's domains sample the + /// values it settled to, and settles within the call do not change + /// them. + #[inline] + fn begin_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.host_slot_work || !self.dirty || self.timed { + return Ok(()); + } + self.settle_host_slot() + } + + #[cold] + #[inline(never)] + fn settle_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + self.eval_comb_checked()?; + self.dirty = false; + self.finish_host_slot() + } + + #[cold] + #[inline(never)] + fn finish_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + self.mature_deferred_assertions()?; + self.sample_values(); + Ok(()) + } + + /// Copy each sampled variable into its copy (IEEE 1800-2023 + /// 16.5.1). + pub(crate) fn sample_values(&mut self) { + for &(variable, copy) in &self.sample_shadows { + celox_runtime::copy_signal(&mut self.backend, variable, copy); + } + } + /// The time slot ends: the actions of deferred assertions that their /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 /// 16.4). A fatal one ends the simulation with an error. @@ -2054,8 +2119,10 @@ mod host { // Nothing the domain runs reads the level, which is the // inactive one before and after the period: both stores are // unobservable, and the period is one run of the domain. - return self.fire(event); + // The call begins its slot in the domain's run. + return self.fire_from::(event); } + self.begin_host_slot()?; let moved = celox_runtime::move_signal( &mut self.backend, &info, @@ -2099,13 +2166,27 @@ mod host { /// Run the event's domain as its active edge does, with the signal /// left as it is: the unit of the edge APIs. fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { - let result = self.fire_unit(event); + self.fire_from::(event) + } + + /// [`Self::fire`]; with `BEGIN`, also the start of the host call, + /// whose slot [`Self::begin_host_slot`] begins in the domain's run, + /// where the clock that nothing reads has already moved. + #[inline] + fn fire_from( + &mut self, + event: B::Event, + ) -> Result<(), RuntimeErrorCode> { + let result = self.fire_unit::(event); self.heap_safepoint(); result.and(self.take_heap_fault())?; - self.mature_deferred_assertions() + self.end_host_slot() } - fn fire_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + fn fire_unit( + &mut self, + event: B::Event, + ) -> Result<(), RuntimeErrorCode> { if let Some(Some(_)) = self.derived_ticks.get(event.id()) { return self.tick_derived(event); } @@ -2113,7 +2194,10 @@ mod host { let mut eval_comb_ns = 0u64; let mut eval_apply_ns = 0u64; if self.dirty { - if timing_enabled { + if BEGIN && self.host_slot_work && !self.timed { + self.settle_host_slot()?; + self.eval_apply_ff_at_checked(event)?; + } else if timing_enabled { let start = crate::timing::now(); self.eval_comb_checked()?; eval_comb_ns = eval_comb_ns.saturating_add(start.elapsed().as_nanos() as u64); @@ -2180,7 +2264,12 @@ mod host { return Ok(()); } // No derived domains: move the signal, then run the event's - // domain. + // domain. Logic that reads the signal settles before it + // moves; otherwise the call begins its slot in the domain's + // run. + if info.comb_read { + self.begin_host_slot()?; + } let write = watched_write(&mut self.host_watch); let Some(old) = celox_runtime::move_signal(&mut self.backend, &info, edge, write) else { @@ -2190,13 +2279,18 @@ mod host { self.dirty = true; } if info.fires(old, edge) { - return self.fire(event); + return if info.comb_read { + self.fire(event) + } else { + self.fire_from::(event) + }; } if !self.program.runtime_schema.comb_observers.is_empty() { self.dirty = true; } return Ok(()); } + self.begin_host_slot()?; if let Some(Some(unit)) = self.derived_units.get(event.id()).copied() && !self.finish_sites && self.backend.runs_derived_edge_units() @@ -2264,8 +2358,7 @@ mod host { } /// Settle the outcome of [`celox_runtime::run_edge`] or - /// [`celox_runtime::run_edges`], and mature the deferred assertions - /// they ran. + /// [`celox_runtime::run_edges`], and end the time slot they ran. fn note_edge( &mut self, outcome: Result, @@ -2288,7 +2381,7 @@ mod host { Err(celox_runtime::Halt::Error(error)) => return Err(error), } // The edges are a time slot, as a tick is. - self.mature_deferred_assertions() + self.end_host_slot() } /// A rising edge of `event`'s signal; see [`Self::edge`]. @@ -2328,6 +2421,7 @@ mod host { if self.frozen { return Ok(()); } + self.begin_host_slot()?; 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(); @@ -2432,6 +2526,7 @@ mod host { if self.frozen { return Ok(()); } + self.begin_host_slot()?; if let [event] = events { return self.tick(*event); } @@ -2492,7 +2587,7 @@ mod host { let result = self.tick_events_unit(&fired); self.heap_safepoint(); result.and(self.take_heap_fault())?; - self.mature_deferred_assertions()?; + self.end_host_slot()?; for &event in events { let info = self.event_edges[event.id()]; self.backend @@ -2594,8 +2689,11 @@ mod host { ) -> Result<(), RuntimeErrorCode> { if !self.program.runtime_schema.comb_observers.is_empty() || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + || self.host_slot_work { - // Derived domains need the settled state to see their edges. + // Derived domains need the settled state to see their edges, + // and each tick of a design with slot work is a host call. + self.begin_host_slot()?; return self.fire(event); } if self.dirty { @@ -2634,6 +2732,7 @@ mod host { if !self.program.runtime_schema.comb_observers.is_empty() || !self.dirty || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + || self.host_slot_work { return (1, self.tick_deferred_comb(event)); } @@ -3380,6 +3479,46 @@ mod host { } } + #[test] + fn signal_copy_accepts_an_aliased_four_state_view() { + let mut sim = Simulator::builder("module Top (data: input logic<32>) {}", "Top") + .four_state(true) + .build_interpreter() + .unwrap(); + let signal = sim.try_child_signal(&[], "data").unwrap(); + let value = BigUint::from(0x1234u32); + let mask = BigUint::from(0x00ffu32); + sim.backend + .set_four_state(signal, value.clone(), mask.clone()); + celox_runtime::copy_signal(&mut sim.backend, signal, signal); + assert_eq!(sim.backend.get_four_state(signal), (value, mask)); + } + + /// Batched testbench ticks end each tick's slot in a design with + /// sampled values: a register capturing `$sampled(count)` follows + /// the preceding tick. + #[cfg(feature = "systemverilog")] + #[test] + fn batched_testbench_ticks_end_each_slot() { + let source = "module Top(input bit clk, output bit [7:0] count, output bit [7:0] seen);\n \ + always_ff @(posedge clk) begin count <= count + 1; seen <= $sampled(count); end\n\ + endmodule"; + let mut sim = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("t.sv"))], "Top") + .build() + .unwrap(); + let clk = sim.event("clk"); + sim.dirty = true; + let mut done = 0; + while done < 3 { + let (ran, result) = sim.tick_deferred_comb_many(clk, 3 - done); + result.unwrap(); + done += ran; + } + let seen = sim.signal("seen"); + assert_eq!(sim.get(seen), BigUint::from(2u8)); + } + #[test] fn edges_leave_a_finished_simulation_unchanged() { let mut sim = Simulator::builder(GATED_COUNTER, "Top").build().unwrap(); diff --git a/crates/celox/tests/sv_sampled.rs b/crates/celox/tests/sv_sampled.rs new file mode 100644 index 00000000000..756fb132c5f --- /dev/null +++ b/crates/celox/tests/sv_sampled.rs @@ -0,0 +1,264 @@ +#![cfg(feature = "systemverilog")] +//! `$sampled(e)` is the value of `e` in the Preponed region of the time +//! slot, the value at the end of the previous slot, and before the first +//! slot the declared or default value (IEEE 1800-2023 4.4.2.1, 16.5.1, +//! 16.9.3). +use std::path::Path; + +macro_rules! sampled { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!( + "`timescale 1ns/1ns\nmodule Top;\n bit clk, a, b, r, s, x, y, z;\n int v;\n{body}\nendmodule" + ); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("sampled.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + fn value(sim: &mut celox::Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + } + + /// A clock edge and a blocking write in one slot: the register + /// sees the new value, `$sampled` the value from before the slot. + #[test] + fn a_flip_flop_samples_the_value_before_the_slot() { + let mut sim = simulation( + " always @(posedge clk) begin r <= $sampled(a); s <= a; end\n \ + initial begin #1 a = 1; clk = 1; #1 clk = 0; #1 clk = 1; end", + ); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "r"), value(&mut sim, "s")), (0, 1)); + sim.run_until(3).unwrap(); + assert_eq!((value(&mut sim, "r"), value(&mut sim, "s")), (1, 1)); + } + + /// Returning to the host does not advance the Preponed baseline: + /// the host may schedule more work at the same timestamp. + #[test] + fn host_resumptions_keep_the_current_timestamp_sample() { + for mode in [celox::SchedulerMode::Reference, celox::SchedulerMode::Compiled] { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk, input bit [7:0] host); + bit [7:0] a, r; + always @(posedge clk) r <= $sampled(a + host); + initial #1 a = 1; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("sampled.sv"))], "Top", + ).scheduler_mode(mode).$backend().unwrap(); + if watch { sim.set_fail_on(Some(celox::Severity::Error)); } + sim.run_until(0).unwrap(); + match entry { + 0 => sim.run_until(1).unwrap(), + 1 => { sim.run_until_bounded(1, 10).unwrap(); } + 2 => { assert_eq!(sim.step().unwrap(), Some(1)); } + _ => { sim.advance_to(1).unwrap(); sim.run_until(1).unwrap(); } + } + assert_eq!(value(&mut sim, "a"), 1); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "r"), 0, "{mode:?}, watch={watch}, entry={entry}"); + + // Host writes also belong to time 1, not a new slot. + let host = sim.signal("host"); + sim.modify(|io| io.set(host, 2u8)).unwrap(); + sim.schedule("clk", 1, 0).unwrap(); + sim.run_until(1).unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "r"), 0); + + // Once time advances, the updated values are sampled. + sim.schedule("clk", 2, 0).unwrap(); + sim.schedule("clk", 3, 1).unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "r"), 3); + if matches!(mode, celox::SchedulerMode::Compiled) + && !watch && entry == 0 + && matches!(stringify!($backend), "build" | "build_cranelift") { + assert!(sim.scheduler_stats().compiled_slots > 0); + } + } + } + } + } + + /// In the first slot the sampled value is the declared value, + /// in a later slot the value at the end of the previous one. + #[test] + fn time_zero_samples_the_declared_value() { + let mut sim = simulation( + " bit d = 1;\n \ + initial begin\n \ + x = $sampled(b) ^ $sampled(d); b = 1; d = 0; #0 y = $sampled(b) ^ $sampled(d);\n \ + #1 z = $sampled(b) ^ $sampled(d);\n \ + end", + ); + sim.run_until(1).unwrap(); + assert_eq!( + (value(&mut sim, "x"), value(&mut sim, "y"), value(&mut sim, "z")), + (1, 1, 1) + ); + } + + /// A real operand keeps its type. + #[test] + fn real_operands_keep_their_type() { + let mut sim = simulation( + " real d = 1.25;\n real rr;\n initial begin rr = $sampled(d); $display(\"%0.2f\", rr); end", + ); + sim.run_until(0).unwrap(); + assert!(matches!( + sim.drain_runtime_events().as_slice(), + [celox::RuntimeEvent::Display { message }] if message == b"1.25" + )); + } + + /// A sampled expression selects, as `$sampled(i + 1)`. + #[test] + fn sampled_expressions_select() { + let mut sim = simulation( + " bit [7:0] data [0:3] = '{10, 11, 12, 13};\n bit [1:0] i = 1;\n bit [7:0] q;\n \ + always @(posedge clk) q <= data[$sampled(i + 1)];\n \ + initial begin #1 clk = 1; i = 0; end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "q"), 12); + } + + /// A call in a sampled select index reads the sampled values too. + #[test] + fn sampled_calls_select() { + let mut sim = simulation( + " int calls; function automatic bit [1:0] f(bit [1:0] k); calls++; return k; endfunction\n \ + bit [7:0] data [0:3] = '{10, 11, 12, 13};\n bit [1:0] i = 2;\n bit [7:0] q;\n bit [3:0] w;\n \ + always @(posedge clk) begin q <= data[$sampled(f(i))]; w[$sampled(f(i))] <= 1; end\n \ + initial begin #1 clk = 1; i = 0; end", + ); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "q"), value(&mut sim, "w")), (12, 4)); + } + + /// Automatic variables keep their current value; the operand may + /// be any expression. + #[test] + fn automatic_variables_and_expressions() { + let mut sim = simulation( + " initial begin\n \ + automatic int k = 5;\n \ + #1 a = 1; b = 1;\n \ + v = $sampled(k + a + {31'b0, b});\n \ + end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "v"), 5); + } + + #[test] + fn combinational_logic_cannot_read_sampled_values() { + for item in [ + "always_comb y = $sampled(a);", + "always @(a) y = $sampled(a);", + "assign y = $sampled(a);", + ] { + let source = format!("module Top; bit a, y; {item} endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("sampled.sv"))], + "Top", + ) + .$backend() + .err() + .expect("rejected"); + assert!( + error.to_string().contains("$sampled in combinational logic"), + "{item}: {error}" + ); + } + } + } + }; +} + +sampled!(interpreter, build_interpreter); +#[cfg(feature = "cranelift")] +sampled!(cranelift, build_cranelift); +#[cfg(target_arch = "x86_64")] +sampled!(native, build_native); +#[cfg(feature = "wasm-runtime")] +sampled!(wasm, build_wasm); + +/// A `Simulator` call is a time slot: a domain reads the values its +/// inputs had when the previous call ended. +#[test] +fn a_tick_samples_the_value_of_the_previous_call() { + let source = "module Top(input bit clk, input bit a, output bit r, output bit s);\n \ + always_ff @(posedge clk) begin r <= $sampled(a); s <= a; end\n\ + endmodule"; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top") + .build() + .unwrap(); + let (a, r, s, clk) = ( + sim.signal("a"), + sim.signal("r"), + sim.signal("s"), + sim.event("clk"), + ); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!((sim.get_as::(r), sim.get_as::(s)), (1, 1)); +} + +/// A domain of a derived clock samples the values from before the call, not +/// those the source domain committed in it. +#[test] +fn derived_domains_sample_the_values_from_before_the_call() { + let source = "module Top(input bit clk, output bit [7:0] r);\n \ + bit div;\n bit [7:0] a;\n \ + always_ff @(posedge clk) begin div <= !div; a <= a + 1; end\n \ + always_ff @(posedge div) r <= $sampled(a);\n\ + endmodule"; + // With the edges in generated units and through the plan walk. + for units in [true, false] { + let mut builder = + celox::Simulator::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top"); + if !units { + builder = builder.disable_pass(celox::SirPass::DerivedEdgeUnits); + } + let mut sim = builder.build().unwrap(); + let (r, clk) = (sim.signal("r"), sim.event("clk")); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 0, "units: {units}"); + sim.tick(clk).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 2, "units: {units}"); + } +} + +/// A host write in a slot with nothing to run is what the next slot +/// samples. +#[test] +fn host_writes_of_idle_slots_are_sampled() { + let source = "`timescale 1ns/1ns\nmodule Top(input bit clk, input bit a, output bit r);\n \ + always_ff @(posedge clk) r <= $sampled(a);\nendmodule"; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top") + .build() + .unwrap(); + sim.add_clock("clk", 2, 1); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.run_until(1).unwrap(); + let r = sim.signal("r"); + assert_eq!(sim.get(r), 1u8.into()); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index b74b6f5a4b7..ae258e91cbb 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -210,6 +210,7 @@ waits zero. | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | Random numbers | `$urandom`, `$urandom_range`, `$random` and `$dist_uniform` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | Simulation time | `$time`, `$stime` and `$realtime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | +| Sampled values | `$sampled` in edge-triggered processes, processes with timing controls, `initial` blocks and the subroutines they call; see [Sampled values](#sampled-values) | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | @@ -709,6 +710,21 @@ host does at each callback, or the time step of the report while and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. +### Sampled values {#sampled-values} + +`$sampled(e)` is the value `e` has in the Preponed region of the time slot: +the value at the end of the previous slot, and in the first slot the declared +or default value (IEEE 1800-2023 4.4.2.1, 16.5.1). Each static variable the +operand reads, the indices of its selects and the arguments of its calls +included, is read from a copy that the timed simulation updates before advancing +to a later timestamp. Returning to the host and resuming at the same timestamp +retains that copy, including across host writes. Automatic variables keep their current value. A `Simulator` call is a +time slot. `$sampled` in combinational logic (`always_comb`, `always_latch`, +an `always` lowered as combinational logic, a continuous assignment) is +rejected: such a process reruns when its inputs change, not when their sampled +values do. A design that uses `$sampled` runs the compiled scheduler one slot +at a time. + ### Deferred assertions The action of `assert #0`, `assume #0`, `cover #0` and their `final` forms diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index ff7e7377ff9..2839b045e40 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -154,6 +154,7 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | 乱数 | `$urandom`、`$urandom_range`、`$random`、`$dist_uniform` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | シミュレーション時刻 | `$time`、`$stime`、`$realtime` はクロックで起動するプロセス、組合せプロセス、継続代入、`initial` とそれらから呼ぶサブルーチンで使用可能 | +| サンプル値 | `$sampled` はエッジで起動するプロセス、タイミング制御を含むプロセス、`initial` とそれらから呼ぶサブルーチンで使用可能。[サンプル値](#sampled-values) を参照 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`、[VCD 制御](./vcd#systemverilog-source-controls)。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | @@ -408,6 +409,18 @@ drain のコンテキストが与える時刻で、VPI ホストはコールバ VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 +### サンプル値 {#sampled-values} + +`$sampled(e)` は、タイムスロットの Preponed region での `e` の値です。前のスロットの終わりの値で、 +最初のスロットでは宣言の初期値か既定値です(IEEE 1800-2023 4.4.2.1、16.5.1)。被演算子が読む +静的変数は、選択のインデックスや呼び出しの引数の中のものも含めて、時刻を先へ進める直前に +更新するコピーから読みます。同じ時刻にホストへ戻って再開しても、ホストからの書き込みを含め、 +コピーは更新しません。automatic 変数は現在の値のままです。`Simulator` では呼び出し 1 回が +タイムスロットです。組み合わせ回路(`always_comb`、`always_latch`、組み合わせ回路として扱う +`always`、継続代入)の中の `$sampled` は拒否します。こうしたプロセスは入力が変わったときに +再実行するもので、入力のサンプル値が変わったときではないためです。`$sampled` を使う設計では、 +コンパイル済みスケジューラを 1 スロットずつ実行します。 + ### 遅延付きアサーション `assert #0`、`assume #0`、`cover #0` とそれぞれの `final` 形のアクションは、プロセスの遅延