diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 3f34f2b61fc..cc67b04a278 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -211,6 +211,11 @@ pub struct RuntimeEventSite { /// deferred assertions. #[serde(default)] pub deferred: Option, + /// The last argument is the simulation time at which the site issued + /// the event, which a report carries (IEEE 1800-2023 20.10). It is not + /// formatted. + #[serde(default)] + pub timestamp_arg: bool, pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, @@ -1105,6 +1110,15 @@ 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)>, + /// Variables and copies that start with the variable's value, such as + /// the `$past` histories (IEEE 1800-2023 16.9.3): a host copies each + /// once before the first time slot. + pub initial_copies: 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 +1373,8 @@ impl Default for RuntimeSchema { host_request_sites: Vec::new(), active_commits: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), + initial_copies: Vec::new(), scheduler: None, derived_edges: Vec::new(), settle_partitions: None, @@ -2215,6 +2231,7 @@ mod tests { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), 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..a691ceaff01 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1972,6 +1972,8 @@ pub fn lower_frontend_artifact( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), + initial_copies: 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..20938dc8163 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -159,6 +159,12 @@ 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)>, + /// Variables and copies that start with their value; see + /// `RuntimeSchema::initial_copies`. + pub initial_copies: 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..88712b02971 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2135,6 +2135,8 @@ pub fn schedule_symbolic_rtl_reporting_loops( nba_sites, host_request_sites, time_slots, + sample_shadows, + initial_copies, .. } = timing; let source_sir = SirProgram { @@ -2386,6 +2388,14 @@ 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 initial_copies: Vec<(StateAddr, StateAddr)> = initial_copies + .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 +2519,13 @@ 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() + .chain(&initial_copies) + .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 +2578,8 @@ pub fn schedule_symbolic_rtl_reporting_loops( host_request_sites, active_commits, time_slots, + sample_shadows, + initial_copies, scheduler, derived_edges: Vec::new(), settle_partitions, @@ -4113,6 +4132,8 @@ struct TimingMetadata { nba_sites: Vec>, host_request_sites: Vec>, time_slots: Vec, + sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, + initial_copies: Vec<(AbsoluteAddr, AbsoluteAddr)>, nba_switches: Vec>, } @@ -4435,6 +4456,8 @@ fn relocate_timing( nba_sites: Vec::new(), host_request_sites: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), + initial_copies: Vec::new(), nba_switches: Vec::new(), }; for (&instance, module) in instances { @@ -4470,6 +4493,18 @@ 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.initial_copies.extend( + module + .initial_copies + .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..9997aab84cf 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -87,6 +87,12 @@ 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, + /// The variable whose past sampled values this hidden register holds; + /// it starts with the variable's value (`SimModule::initial_copies`). + history_of: Option, } /// Whether `expr` reads a string variable: after its calls are hoisted, a @@ -126,13 +132,16 @@ 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 + /// code computes. The time slot and the sampled copies are state the + /// scheduler writes, `$past` histories are state their process keeps, + /// 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.history_of.is_none() && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -2198,6 +2207,8 @@ fn prepare_external_hierarchy_collecting( source: variable.source.clone(), hidden: !variable.module_affiliated, force_control: None, + sampled_from: None, + history_of: None, }, ) }) @@ -3629,6 +3640,8 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, + history_of: None, }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); @@ -3713,6 +3726,8 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, + history_of: None, }; name_to_id.insert(signal.name().to_string(), id); // The package's object, or the other instance's, has its own @@ -3793,6 +3808,8 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, + history_of: None, }, ); } @@ -4005,6 +4022,8 @@ fn lower_module_with_overrides( nba_switches, host_request_sites, time_slot: name_to_id.get(TIME_SLOT).copied(), + sample_shadows: Vec::new(), + initial_copies: Vec::new(), }, variables, port_order, @@ -4793,6 +4812,18 @@ 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; + let mut initial_copies: Vec<_> = parent_variables + .iter() + .filter_map(|(©, variable)| variable.history_of.map(|variable| (variable, copy))) + .collect(); + initial_copies.sort_by_key(|&(variable, copy)| (variable.0, copy.0)); + module.initial_copies = initial_copies; for (instance, child_id, child, connections) in resolved_instances { let glue = build_instance_glue( &parent_variables, @@ -5187,6 +5218,8 @@ fn lower_initial_processes( // Control slots are not signals of the design. hidden: true, force_control: None, + sampled_from: None, + history_of: None, }, ); id @@ -5831,6 +5864,8 @@ fn ensure_parent_output_signals( source: None, hidden: false, force_control: None, + sampled_from: None, + history_of: None, }; parent .variables @@ -7713,6 +7748,12 @@ fn lower_bit_vector_function_slt( | SystemFunction::Isunbounded | SystemFunction::Signed | SystemFunction::Unsigned + | SystemFunction::Sampled + | SystemFunction::Past + | SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed | SystemFunction::Bits | SystemFunction::Size | SystemFunction::Dimensions @@ -9077,6 +9118,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 +9136,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 +9152,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)?), }, }) } @@ -9674,6 +9732,7 @@ fn lower_ff_processes( } let sites_before = pm.runtime_event_sites.len(); let extern_calls_before = pm.extern_calls; + let clock = inferred_clock(pm, process); let ff::FfProcessUnits { eval: eval_only, apply, @@ -9686,6 +9745,7 @@ fn lower_ff_processes( .with_shared_variables(shared_variables) .with_sparse_candidates(&edge_memories) .with_window_writes(&window_writes) + .with_inferred_clock(clock) .lower_process(process.body())?; repeated_writes.extend(repeated_ff_writes(&eval_only, &staged)); // A process without writes still runs for its runtime events and @@ -10403,6 +10463,37 @@ pub(crate) fn unsupported_sv_inout(path: String) -> ParserError { ) } +/// The clock that the sampled value functions of an edge-triggered process +/// infer (IEEE 1800-2023 16.14.6): its event expression of the clock, when +/// it is the only one whose signal the body reads nowhere else. With an +/// asynchronous reset the body reads the reset, so the clock remains. +fn inferred_clock( + pm: &procedural::ProcModule<'_>, + process: &sv::ir::FfProcess, +) -> Option { + let clock = clock_event_from_ff_process(process)?; + let reads: HashSet = pm + .implicit_reads(process.body(), true) + .into_iter() + .map(|atom| atom.id) + .collect(); + let unread: Vec<_> = process + .events() + .iter() + .filter(|event| pm.id(event.signal()).is_none_or(|id| !reads.contains(&id))) + .collect(); + match unread.as_slice() { + [only] if only.signal() == clock.signal() && only.edge() == clock.edge() => { + Some(ff::Clock { + signal: clock.signal().to_owned(), + rising: clock.edge() == sv::ir::FfEdge::Pos, + alone: process.events().len() == 1, + }) + } + _ => None, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 06233d06023..246447ad5c8 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3578,6 +3578,19 @@ impl<'p, 'a> Comb<'p, 'a> { arg_widths.push(self.width(node)); captured.push(self.capture(node)?); } + // A report carries the time it is issued at (IEEE 1800-2023 20.10). + // The time does not run the process. + let timestamp_arg = matches!(kind, SystemTaskKind::Message(_) | SystemTaskKind::Fatal); + if timestamp_arg { + let time = sv::ir::Expr::Ident(self.m.time_slot()); + let (node, _) = self.eval(store, frames, &time, None)?; + arg_signed.push(false); + arg_is_string.push(false); + arg_float_precision.push(None); + arg_is_handle.push(false); + arg_widths.push(self.width(node)); + captured.push(self.capture(node)?); + } let event_kind = kind.event_kind(); let condition = self.path_condition()?; let guard = if let Some(passed) = assertion { @@ -3649,6 +3662,7 @@ impl<'p, 'a> Comb<'p, 'a> { location: report_location(site), assertion: assertion_site.cloned(), deferred, + timestamp_arg, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 26ef54d8fb1..bdc54ff5324 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -102,6 +102,33 @@ 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, + /// The clock that the sampled value functions of the process infer + /// (IEEE 1800-2023 16.14.6). + inferred_clock: Option, + /// The `$past` histories of the process. + history: Vec, +} + +/// The clock of an edge-triggered process. +pub(super) struct Clock { + /// The clock signal. + pub signal: String, + /// Whether a tick is a rising edge. + pub rising: bool, + /// The clock is the only event of the process, so every run is a tick. + pub alone: bool, +} + +/// The sampled values of variable `name` at the previous ticks of the clock +/// of a process: `chain[k - 1]` holds the value `k` ticks ago, counting +/// only the ticks at which the gate held. +struct History { + name: String, + gate: Option, + /// The hidden variable that holds the gate's value at the tick, before + /// the body runs. + gate_value: Option, + chain: Vec, } fn stable(var_id: SourceVarId) -> Addr { @@ -161,9 +188,409 @@ impl<'p, 'a> Ff<'p, 'a> { host_request_sites: Vec::new(), nba_switches: Vec::new(), flush_site: None, + inferred_clock: None, + history: Vec::new(), } } + /// Lower an edge-triggered process with the clock its sampled value + /// functions infer, if any. + pub fn with_inferred_clock(mut self, clock: Option) -> Self { + self.inferred_clock = clock; + self + } + + /// 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 stays sensitive to the variables themselves, + /// whose changes run it, not to their copies: it is lowered as a gated + /// unit that keeps the value it last computed. + fn sampled( + &mut self, + args: &[Option], + ) -> Result { + let [Some(operand)] = args else { + return Err(unsupported("operand of `$sampled`")); + }; + // A sampled value function in the operand would read the sampled + // copies instead of its history. + let mut nested = Vec::new(); + collect_calls(operand, &mut nested); + if nested.iter().any(|(callee, _)| { + matches!( + callee, + sv::ir::Callee::System( + sv::ir::SystemFunction::Past + | sv::ir::SystemFunction::Rose + | sv::ir::SystemFunction::Fell + | sv::ir::SystemFunction::Stable + | sv::ir::SystemFunction::Changed + ) + ) + }) { + return Err(unsupported( + "`$sampled` of an operand that calls a sampled value function", + )); + } + 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)) + } + + /// Declare the `$past` histories that the sampled value functions of + /// `body`, and of the subroutines it calls, read, as nonblocking targets + /// of the process. A subroutine's calls infer the clock of the process + /// that calls it. + fn declare_history(&mut self, body: &[sv::ir::Stmt]) -> Result<(), sv::AnalyzerError> { + use sv::ir::SystemFunction; + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + // The calls after these are in subroutines the body calls. + let body_calls = calls.len(); + let mut visited = HashSet::default(); + let mut index = 0; + while index < calls.len() { + if let (sv::ir::Callee::Subroutine(name), args) = calls[index].clone() + && let Some(subroutine) = self.m.subroutine(&name).cloned() + { + // The defaults of omitted arguments run at the call. + default_calls(&subroutine, &args, &mut calls); + if visited.insert(name) { + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + } + } + index += 1; + } + for (position, (callee, args)) in calls.into_iter().enumerate() { + let sv::ir::Callee::System( + function @ (SystemFunction::Past + | SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed), + ) = callee + else { + continue; + }; + if self.inferred_clock.is_none() { + return Err(unsupported(format!( + "`{function}` outside an edge-triggered process whose clock it infers" + ))); + } + let (depth, gate) = past_depth_and_gate(function, &args)?; + let Some(Some(operand)) = args.first() else { + return Err(unsupported(format!("operand of `{function}`"))); + }; + // The process evaluates the gate before its body runs, outside + // the subroutine: there the gate can read only module variables, + // not the subroutine's arguments or locals. + if position >= body_calls + && let Some(gate) = &gate + { + let mut names = HashSet::default(); + expr_idents(gate, &mut names); + if names + .iter() + .any(|name| self.m.id(name).is_none_or(|id| self.m.is_hidden(id))) + { + return Err(unsupported(format!( + "`{function}` in a subroutine with a gate that reads the subroutine's arguments or locals" + ))); + } + } + // The history of a nested call would need its own chain. + let mut nested = Vec::new(); + collect_calls(operand, &mut nested); + if nested.iter().any(|(callee, _)| { + matches!( + callee, + sv::ir::Callee::System( + SystemFunction::Past + | SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed + ) + ) + }) { + return Err(unsupported(format!( + "`{function}` of an operand that calls a sampled value function other than `$sampled`" + ))); + } + // The histories hold variables: the result of a call, which can + // read the time or state the operand does not name, has none. + if nested.iter().any(|(callee, _)| { + !matches!(callee, sv::ir::Callee::System(SystemFunction::Sampled)) + }) { + return Err(unsupported(format!( + "`{function}` of an operand that calls a function" + ))); + } + let mut names = HashSet::default(); + expr_idents(operand, &mut names); + let mut names: Vec<_> = names.into_iter().collect(); + names.sort(); + 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(format!( + "`{function}` of a string or class handle" + ))); + } + // A history moves one tick back with one nonblocking copy + // of the variable, which an unpacked array has no form of. + if !self.m.var(id).array_dims.is_empty() { + return Err(unsupported(format!("`{function}` of an unpacked array"))); + } + let index = match self + .history + .iter() + .position(|history| history.name == name && history.gate == gate) + { + Some(index) => index, + None => { + self.history.push(History { + name: name.clone(), + gate: gate.clone(), + gate_value: None, + chain: Vec::new(), + }); + self.history.len() - 1 + } + }; + while self.history[index].chain.len() < depth { + let register = self.m.history_copy(id); + // A hidden variable is no target of its own: the + // history is state the process commits at each tick. + self.record_target(&sv::ir::LValue::Ident(register.clone()), false); + let copy = self.m.id(®ister).expect("a new history register"); + let width = self.m.var(copy).width; + self.targets.push((copy, BitAccess::new(0, width - 1))); + self.history[index].chain.push(register); + } + } + } + Ok(()) + } + + /// The operand of `$past` (IEEE 1800-2023 16.9.3) evaluated over the + /// sampled values of its variables `depth` ticks ago. + fn past( + &self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + let (depth, gate) = past_depth_and_gate(function, args)?; + let Some(Some(operand)) = args.first() else { + return Err(unsupported(format!("operand of `{function}`"))); + }; + let operand = self.propagate(operand); + let mut names = HashSet::default(); + expr_idents(&operand, &mut names); + let mut renames = HashMap::default(); + for name in names { + if self.m.id(&name).is_none_or(|id| self.m.is_hidden(id)) { + continue; + } + // `declare_history` declared the histories of the process body; + // a call elsewhere, as in a subroutine, has no clock. + let history = self + .history + .iter() + .find(|history| { + history.name == name && history.gate == gate && history.chain.len() >= depth + }) + .ok_or_else(|| { + unsupported(format!( + "`{function}` outside an edge-triggered process whose clock it infers" + )) + })?; + renames.insert(name, history.chain[depth - 1].clone()); + } + Ok(rename_idents(&operand, &renames)) + } + + /// `$rose`, `$fell`, `$stable` or `$changed` (IEEE 1800-2023 16.9.3): the + /// sampled value of the operand against its value at the previous tick, + /// with case equality for integral values and numeric equality for reals. + /// A change from or to X counts. `$rose` and + /// `$fell` look at the least significant bit. + fn value_change( + &mut self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + use sv::ir::{BinaryOp, Expr, SystemFunction}; + let current = self.sampled(args)?; + let past = self.past(function, args)?; + // Resolve nested $sampled calls before inspecting the operand's type. + let current = self.hoist(¤t)?; + let past = self.hoist(&past)?; + let real = floating::precision(¤t, self.m.variables, self.m.name_to_id).is_some(); + let binary = |left: Expr, op, right: Expr| Expr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + let bit = |value: Expr| binary(value, BinaryOp::BitAnd, Expr::Literal("1'b1".into())); + let literal = |text: &str| Expr::Literal(text.into()); + Ok(match function { + SystemFunction::Rose | SystemFunction::Fell => { + let level = if function == SystemFunction::Rose { + "1'b1" + } else { + "1'b0" + }; + binary( + binary(bit(past), BinaryOp::NeCase, literal(level)), + BinaryOp::LogicAnd, + binary(bit(current), BinaryOp::EqCase, literal(level)), + ) + } + SystemFunction::Stable => binary( + current, + if real { BinaryOp::Eq } else { BinaryOp::EqCase }, + past, + ), + _ => binary( + current, + if real { BinaryOp::Ne } else { BinaryOp::NeCase }, + past, + ), + }) + } + + /// The `$past` updates at the end of an evaluation, a tick of the + /// process's clock: each history moves one tick back and takes the + /// sampled value, where its gate holds at the tick. + fn update_history(&mut self) -> Result { + use sv::ir::{Expr, LValue, Stmt}; + let sampled = |expr: Expr| Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Sampled), + args: vec![Some(expr)], + arg_order: Vec::new(), + }; + let mut stmts = Vec::new(); + if self.history.is_empty() { + return Ok(true); + } + for history in &self.history { + let mut updates: Vec = history + .chain + .windows(2) + .map(|pair| Stmt::Assign { + lhs: LValue::Ident(pair[1].clone()), + rhs: Expr::Ident(pair[0].clone()), + nonblocking: true, + }) + .collect(); + updates.push(Stmt::Assign { + lhs: LValue::Ident(history.chain[0].clone()), + rhs: sampled(Expr::Ident(history.name.clone())), + nonblocking: true, + }); + match &history.gate_value { + None => stmts.extend(updates), + Some(gate) => stmts.push(Stmt::If { + condition: Expr::Ident(gate.clone()), + then_body: updates, + else_body: Vec::new(), + }), + } + } + // A run for another event, such as an asynchronous reset, is no + // tick: the clock has kept the level it had before the slot. + let clock = self + .inferred_clock + .as_ref() + .expect("histories have a clock"); + if !clock.alone { + use sv::ir::BinaryOp::{EqCase, LogicAnd, LogicOr, NeCase}; + let to = Expr::Literal(if clock.rising { "1'b1" } else { "1'b0" }.into()); + let from = Expr::Literal(if clock.rising { "1'b0" } else { "1'b1" }.into()); + // Edge events inspect only the least significant bit (9.4.2). + let signal = Expr::Resize { + expr: Box::new(Expr::Ident(clock.signal.clone())), + width: 1, + signed: false, + }; + let old = sampled(signal.clone()); + let compare = |left: Expr, op, right: Expr| Expr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + // Table 9-2: leaving the opposite known level for X/Z is an + // edge too, as is arriving at the target level from X/Z. + let tick = compare( + compare( + compare(old.clone(), EqCase, from.clone()), + LogicAnd, + compare(signal.clone(), NeCase, from), + ), + LogicOr, + compare( + compare(old, NeCase, to.clone()), + LogicAnd, + compare(signal, EqCase, to), + ), + ); + stmts = vec![Stmt::If { + condition: tick, + then_body: stmts, + else_body: Vec::new(), + }]; + } + self.exec_block(&stmts) + } + + /// Evaluate the gate of each `$past` history before the body runs. The + /// gate is the `iff` of the clocking event, which is evaluated at the + /// tick (IEEE 1800-2023 9.4.2.3), not after the body's assignments. + fn capture_history_gates(&mut self) -> Result<(), sv::AnalyzerError> { + use sv::ir::{BinaryOp, Expr}; + for index in 0..self.history.len() { + let Some(gate) = self.history[index].gate.clone() else { + continue; + }; + // Its truth, which keeps an unknown gate unknown, as `if` reads it. + let truth = Expr::Binary { + left: Box::new(gate), + op: BinaryOp::Ne, + right: Box::new(Expr::Literal("1'b0".into())), + }; + let value = self.eval(&truth, Some((1, false)))?; + let (temp, name) = self.m.temp("gate", 1, false, true); + self.store(temp, SIROffset::Static(0), 1, value); + self.history[index].gate_value = Some(name); + } + Ok(()) + } + /// Whether `stmts`, or a subroutine they call, including in timing /// controls and the defaults of omitted arguments, hold a deferred /// assertion. @@ -230,6 +657,7 @@ impl<'p, 'a> Ff<'p, 'a> { location: None, assertion: None, deferred: Some(DeferredSite::FlushPoint), + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), @@ -779,8 +1207,25 @@ 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/history functions must resolve their operands + // before nested calls hide the original inputs behind + // temporaries holding current-slot values. + let arg = if matches!( + callee, + sv::ir::Callee::System( + sv::ir::SystemFunction::Sampled + | sv::ir::SystemFunction::Past + | sv::ir::SystemFunction::Rose + | sv::ir::SystemFunction::Fell + | sv::ir::SystemFunction::Stable + | sv::ir::SystemFunction::Changed + ) + ) { + 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 +1234,18 @@ 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/history operand can retain any expression + // shape (including a resize inserted for the index). + // Evaluate it only after its references are resolved. + hoisted => { + 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 + } }; let result = ConstExpr::Ident(result); calls.push((expr.clone(), result.clone())); @@ -1074,6 +1529,36 @@ 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(function @ sv::ir::SystemFunction::Past), + args, + .. + } => { + let operand = self.past(*function, args)?; + self.hoist(&operand)? + } + Expr::Call { + callee: + sv::ir::Callee::System( + function @ (sv::ir::SystemFunction::Rose + | sv::ir::SystemFunction::Fell + | sv::ir::SystemFunction::Stable + | sv::ir::SystemFunction::Changed), + ), + args, + .. + } => { + let change = self.value_change(*function, args)?; + self.hoist(&change)? + } Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fread), args, @@ -3364,6 +3849,18 @@ impl<'p, 'a> Ff<'p, 'a> { } } } + // A report carries the time it is issued at (IEEE 1800-2023 20.10). + let timestamp_arg = matches!(kind, SystemTaskKind::Message(_) | SystemTaskKind::Fatal); + if timestamp_arg { + let time = sv::ir::Expr::Ident(self.m.time_slot()); + let reg = self.eval(&time, None)?; + arg_widths.push(self.b.register(®).width()); + arg_signed.push(false); + arg_is_string.push(false); + arg_float_precision.push(None); + arg_is_handle.push(false); + regs.push(reg); + } // Argument effects happen before branching, and the condition register // retains the value it had before those effects. let resume = match assertion { @@ -3397,6 +3894,7 @@ impl<'p, 'a> Ff<'p, 'a> { location: report_location(site), assertion: assertion_site.cloned(), deferred, + timestamp_arg, arg_widths, arg_signed, arg_is_string, @@ -4376,6 +4874,7 @@ impl<'p, 'a> Ff<'p, 'a> { mut self, body: &[sv::ir::Stmt], ) -> Result { + self.declare_history(body)?; let mut visited = HashSet::default(); self.scan(body, &mut visited); // A variable only this process's nonblocking assignments write here, @@ -4555,7 +5054,8 @@ impl<'p, 'a> Ff<'p, 'a> { args: Vec::new(), }); } - if self.exec_block(&body)? { + self.capture_history_gates()?; + if self.exec_block(&body)? && self.update_history()? { self.b.seal_block(SIRTerminator::Return); } let mut eval = seal_drained(self.b); @@ -6076,6 +6576,8 @@ impl Ff<'_, '_> { source: None, hidden: true, force_control: None, + sampled_from: None, + history_of: None, value_kind: Default::default(), }, ); @@ -6855,3 +7357,29 @@ fn force_reads(expr: &sv::ir::Expr, m: &ProcModule<'_>) -> sv::ir::Expr { }, } } + +/// The depth and the gate of a `$past` call, or of the comparison a +/// value change function makes with the previous tick. +fn past_depth_and_gate( + function: sv::ir::SystemFunction, + args: &[Option], +) -> Result<(usize, Option), sv::AnalyzerError> { + if function != sv::ir::SystemFunction::Past { + return Ok((1, None)); + } + let depth = match args.get(1) { + None | Some(None) => 1, + Some(Some(depth)) => { + let mut depth = depth; + while let sv::ir::Expr::Resize { expr, .. } = depth { + depth = expr; + } + literal_usize(depth) + .filter(|&depth| depth >= 1) + .ok_or_else(|| { + unsupported("number of ticks of `$past` other than a positive constant") + })? + } + }; + Ok((depth, args.get(2).cloned().flatten())) +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 37095d43ae5..8db1571dae6 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -974,6 +974,8 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, + history_of: None, }, ); self.name_to_id.insert(name, id); @@ -982,6 +984,35 @@ 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 + } + + /// A new hidden register of `$past` history for variable `id`, which + /// starts with the variable's value. + pub fn history_copy(&mut self, id: SourceVarId) -> String { + let (copy, name) = self.shadow(id, "past", false); + self.variables + .get_mut(©) + .expect("a new copy") + .history_of = Some(id); + name + } + pub fn shadow( &mut self, id: SourceVarId, @@ -1040,6 +1071,8 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, + history_of: None, }; let id = next_var_id(&mut self.next_id); self.variables.insert(id, variable); @@ -1070,6 +1103,8 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, + history_of: None, ..variable }, ); @@ -1597,6 +1632,8 @@ pub(super) fn register_locals( source: None, hidden: true, force_control: None, + sampled_from: None, + history_of: None, }, ); name_to_id.insert(local.name.clone(), id); @@ -2311,7 +2348,7 @@ pub(super) struct CanonicalLoop { pub decreasing: bool, } -fn literal_usize(expr: &sv::ir::Expr) -> Option { +pub(super) fn literal_usize(expr: &sv::ir::Expr) -> Option { let sv::ir::Expr::Literal(text) = expr else { return None; }; @@ -2953,7 +2990,9 @@ fn collect_const_calls( ConstExpr::Function { callee, args, .. } => { calls.push(( callee.clone(), - args.iter().map(expr_from_const_expr).collect(), + args.iter() + .map(|arg| expr_from_const_expr_with_calls(arg, true)) + .collect(), )); args.iter().for_each(|arg| collect_const_calls(arg, calls)); } diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 49fdb07fc6b..9293057ddb2 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -682,6 +682,8 @@ pub(crate) fn project_module_with_ids( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), + initial_copies: Vec::new(), }, ids, inferred_latch_diagnostics, diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 474841588f8..09a556a434a 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -556,6 +556,7 @@ impl<'a> FfParser<'a> { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args .iter() .map(|arg| self.get_expression_width(&arg.0)) diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index f3c50003647..c6164737f68 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -104,6 +104,7 @@ fn register_comb_runtime_event_site<'a>( location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args .iter() .map(|arg| arg.0.comptime().r#type.total_width().unwrap_or(1)) diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index e94a57e8747..25089bcc76e 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -112,6 +112,7 @@ fn runtime_event_site_for_assert( location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args.iter().map(assert_arg_width).collect(), arg_signed: value_args .iter() diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 850afa15f01..9a72fb0f9e5 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -143,6 +143,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/host.rs b/crates/celox-runtime/src/simulation/host.rs index e2c753c4181..146bc75484b 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -146,6 +146,14 @@ pub trait HostBoundary: UnitExecutor { fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { Ok(()) } + + /// Called before a run or a step moves from `timestamp` to a later time: + /// before the step of a later slot, and at the end of a run to a time + /// without work. An error ends the run there, as an error of a step + /// does, and so does a `$finish` the host ran there. + fn try_leave_time(&mut self, _timestamp: u64) -> Result<(), Halt> { + Ok(()) + } } /// How many time slots a compiled scheduler may run at once (see diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index af8b78fa4c3..900e810d4b5 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -278,7 +278,10 @@ impl SimulationState { Ok(Some(self.scheduler.time)) } // The time slot goes on when the simulation continues. - Err(Halt::Stop) => Ok(Some(self.scheduler.time)), + Err(Halt::Stop) => { + self.stopped = true; + Ok(Some(self.scheduler.time)) + } Err(Halt::Error(error)) => { if matches!(&error, SimulatorErrorCode::Fatal { .. }) { let _ = self.finalize_terminal(executor); @@ -342,6 +345,12 @@ impl SimulationState { } else { None }; + if compiled.is_some() + && next_time > self.scheduler.time + && !self.leave_time(executor)? + { + return Ok(false); + } observer.before_step(self, executor); let result = match compiled { Some(limit) => self.run_compiled(executor, limit), @@ -356,10 +365,42 @@ impl SimulationState { if self.finished { return Ok(false); } + if end > self.scheduler.time && !self.leave_time(executor)? { + return Ok(false); + } self.advance_time(executor.backend_mut(), end); Ok(true) } + /// The host's work before a run leaves the current time + /// ([`HostBoundary::try_leave_time`]). Returns `false` when it stopped + /// or finished the simulation. + fn leave_time(&mut self, executor: &mut E) -> Result + where + E: SimulationExecutor, + { + match executor.try_leave_time(self.scheduler.time) { + Ok(()) => Ok(true), + Err(Halt::Stop) => { + self.stopped = true; + Ok(false) + } + Err(Halt::Finish) => { + self.finalize_terminal(executor)?; + Ok(false) + } + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } + } + } + /// Select the loop that runs time slots. pub fn set_scheduler_mode(&mut self, mode: SchedulerMode) { self.stats.mode = mode; @@ -552,9 +593,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..e48d6ce660d 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -128,6 +128,9 @@ impl SimulationState { if current_time > limit { return Ok(settled); } + if current_time > self.scheduler.time { + executor.try_leave_time(self.scheduler.time)?; + } // Host writes alone: settle them, then go on to the next time. let host_only = self.host_pending && self.next_work_time() != Some(current_time); self.run_time(executor, current_time)?; @@ -214,7 +217,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 +231,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..33887ffd798 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1265,6 +1265,15 @@ pub(in crate::ast) fn bind_value( arg_order: Vec::new(), } } else { + let mut operands = operands; + // An omitted number of ticks of `$past` is + // one (IEEE 1800-2023 16.9.3); the gate stays + // the third argument. + if function == SystemFunction::Past + && args.get(1).is_some_and(Option::is_none) + { + operands.insert(1, Expr::Literal("1".into())); + } expressions::numeric_system_function( &tree.state, function, @@ -1787,6 +1796,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 | SystemFunction::Past), + 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..26524a5f22a 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -139,6 +139,51 @@ pub(super) fn numeric_system_function( signed: function == SystemFunction::Signed, }) } + // A sampled value has the type of its operand; the frontend reads + // it from copies of the operand's variables (IEEE 1800-2023 16.9.3). + SystemFunction::Sampled | SystemFunction::Past => { + let argument = arguments.first().cloned().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: arguments.into_iter().map(Some).collect(), + 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)?; + // The number of ticks is a constant expression, which the frontend + // reads as a literal. + if function == SystemFunction::Past + && let Some(ticks) = arguments.get_mut(1) + && let Some(constant) = expr_to_const(state, ticks.clone()) + && let Some(value) = eval_ast_const_expr(state, &constant, &dimensions.const_env) + { + *ticks = Expr::Literal(value.to_string()); + } + Ok(Expr::Resize { + expr: Box::new(Expr::Call { + callee: Callee::System(function), + args: arguments.into_iter().map(Some).collect(), + arg_order: Vec::new(), + }), + width, + signed, + }) + } + SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed => Ok(Expr::Call { + callee: Callee::System(function), + args: arguments.into_iter().map(Some).collect(), + arg_order: Vec::new(), + }), SystemFunction::Ln | SystemFunction::Log10 | SystemFunction::Exp diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index da8e1a27b8b..dfae6dedfab 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -71,9 +71,12 @@ fn keep_in( ) -> Result<(), AnalyzerError> { let mut index = 0; while index < stmts.len() { + // A sampled value of a static local is its value from an earlier + // time slot (IEEE 1800-2023 16.5.1), which the local keeps. if let Stmt::Local { name, init } = &stmts[index] && statics.contains_key(name) && (concurrent + || sampled_reads(&stmts[index + 1..], name) || entry( state, name, @@ -839,6 +842,25 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { } } +/// Whether a sampled value function in `stmts` reads `name`. +fn sampled_reads(stmts: &[Stmt], name: &str) -> bool { + let mut found = false; + for stmt in stmts { + stmt.walk(&mut |stmt| { + for expr in stmt_exprs(stmt) { + visit_calls(expr, &mut |callee, args| { + if let Callee::System(function) = callee + && function.reads_sampled_values() + { + found |= args.iter().flatten().any(|arg| expr_reads(arg, name)); + } + }); + } + }); + } + found +} + /// Call `f` with the callee and arguments of every call in `expr`. pub(super) fn visit_calls<'e>(expr: &'e Expr, f: &mut impl FnMut(&'e Callee, &'e [Option])) { match expr { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index 4b9619346cd..e9807660083 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -329,6 +329,20 @@ impl BodyBuilder<'_, '_, '_> { unreachable!("matched an immediate header"); }; let statement = native.statement(id); + // The action of a deferred assertion is one + // subroutine call (IEEE 1800-2023 16.4), not a block. + if deferred.is_some() + && success.iter().chain(failure).any(|&action| { + !matches!( + native.statement(action).kind, + StatementKind::Empty | StatementKind::Expression(_) + ) + }) + { + return Err(unsupported( + "deferred assertion action other than one display or severity task call", + )); + } jobs.push(Job::AssertionThen { condition, keyword: keyword.clone(), diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index f6e85cb53f9..9a1ce737663 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -60,6 +60,18 @@ 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, + /// `$past` (16.9.3): the sampled value of its operand at an earlier tick + /// of the clock. + Past, + /// `$rose`, `$fell`, `$stable` and `$changed` (16.9.3): the sampled value + /// of the operand against its sampled value at the previous tick. + Rose, + Fell, + Stable, + Changed, /// `$bits` (20.6.2). Bits, /// `$isunbounded` (20.6.3). @@ -253,6 +265,12 @@ impl SystemFunction { Self::Timeprecision => "$timeprecision", Self::Signed => "$signed", Self::Unsigned => "$unsigned", + Self::Sampled => "$sampled", + Self::Past => "$past", + Self::Rose => "$rose", + Self::Fell => "$fell", + Self::Stable => "$stable", + Self::Changed => "$changed", Self::Bits => "$bits", Self::Isunbounded => "$isunbounded", Self::Dimensions => "$dimensions", @@ -353,8 +371,29 @@ impl SystemFunction { /// Whether a call reads the state of the simulation: it has an effect, /// or it returns the simulation time. Such a call is not a constant /// expression, and a process evaluates it where it runs. + /// Whether the function reads the sampled values of its operand + /// (IEEE 1800-2023 16.9.3), which are those of earlier time slots. + pub fn reads_sampled_values(self) -> bool { + matches!( + self, + Self::Sampled | Self::Past | Self::Rose | Self::Fell | Self::Stable | Self::Changed + ) + } + 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 + | Self::Past + | Self::Rose + | Self::Fell + | Self::Stable + | Self::Changed + ) } /// Whether the call writes argument `position` back, as `$random(seed)` @@ -413,7 +452,14 @@ impl SystemFunction { | Self::Countones | Self::ScopeRandomize | Self::ScopeRandomizeEnum => Some((32, true)), - Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), + Self::Onehot + | Self::Onehot0 + | Self::Isunknown + | Self::Isunbounded + | Self::Rose + | Self::Fell + | Self::Stable + | Self::Changed => Some((1, false)), Self::Random | Self::DistUniform | Self::DistNormal @@ -440,6 +486,8 @@ impl SystemFunction { Self::Time => Some((64, false)), Self::Signed | Self::Unsigned + | Self::Sampled + | Self::Past | Self::Bits | Self::Dimensions | Self::UnpackedDimensions @@ -1141,12 +1189,12 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$assertvacuousoff", Task), unsupported("$assertcontrol", Task), // 20.12 Sampled value system functions - unsupported("$sampled", Function), - unsupported("$rose", Function), - unsupported("$fell", Function), - unsupported("$stable", Function), - unsupported("$changed", Function), - unsupported("$past", Function), + function(SystemFunction::Sampled, 1, Some(1)), + function(SystemFunction::Rose, 1, Some(1)), + function(SystemFunction::Fell, 1, Some(1)), + function(SystemFunction::Stable, 1, Some(1)), + function(SystemFunction::Changed, 1, Some(1)), + function(SystemFunction::Past, 1, Some(3)), unsupported("$past_gclk", Function), unsupported("$rose_gclk", Function), unsupported("$fell_gclk", Function), @@ -1554,11 +1602,13 @@ pub fn check_call( }); } // Functions require values, except the optional addressing operands of - // `$fread` (21.3.4.4). Tasks such as `$display(a,,b)` may omit operands. + // `$fread` (21.3.4.4) and the number of ticks of `$past` (16.9.3). Tasks + // such as `$display(a,,b)` may omit operands. if tf.kind != Task && let Some(position) = args.iter().enumerate().position(|(position, arg)| { *arg == Arg::Omitted && !(checked == SystemCall::Function(SystemFunction::Fread) && position >= 2) + && !(checked == SystemCall::Function(SystemFunction::Past) && position == 1) }) { return Err(AnalyzerError::InvalidSystemTfCall { diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index c30da3975dd..135116617ce 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -418,6 +418,10 @@ 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)>, + #[serde(default)] + pub(crate) initial_copies: Vec<(AbsoluteAddr, AbsoluteAddr)>, pub(crate) scheduler: Option>, pub(crate) derived_edges: Vec>, } @@ -596,6 +600,8 @@ 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(), + initial_copies: self.runtime_schema.initial_copies.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), settle_partitions: None, @@ -2645,6 +2651,8 @@ 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(), + initial_copies: sir.runtime().runtime_schema.initial_copies.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..71fc64b00c4 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 = 44; 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/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index ba5433e1228..bc54019bb0e 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -61,7 +61,9 @@ impl NativeProgramInstance { /// validation is structural and does not authenticate executable code. /// /// An image with process kernels, which only a timed - /// [`crate::Simulation`] runs, fails to attach. + /// [`crate::Simulation`] runs, fails to attach. So does one with sampled + /// value copies, `$past` histories or deferred assertions, whose time + /// slots a [`crate::Simulator`] or [`crate::Simulation`] ends. pub unsafe fn from_image(image: NativeProgramImage) -> Result { if image.has_processes() { let origin = image @@ -74,6 +76,24 @@ impl NativeProgramInstance { crate::SimulatorErrorKind::ProcessRequiresSimulation(origin), ))); } + let schema = image.runtime_schema(); + if !schema.sample_shadows.is_empty() + || !schema.initial_copies.is_empty() + || schema + .runtime_event_sites + .iter() + .any(|site| site.deferred.is_some()) + { + return Err(NativeProgramLoadError::Attach(SimulatorError::new( + crate::SimulatorErrorKind::Runtime(crate::RuntimeErrorCode::Runtime { + message: "a native program instance does not end time slots: sampled \ + values, `$past` and deferred assertions need a `Simulator` or \ + `Simulation`" + .to_string(), + signals: Vec::new(), + }), + ))); + } // Safety: upheld by this constructor's caller. let shared = Arc::new( unsafe { SharedNativeCode::from_image(image) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 8ea525314f2..bf3862eb9ab 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -273,19 +273,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() @@ -321,6 +316,17 @@ impl HostBoundary for Simulator { self.dump_unless_rewound(timestamp); } + /// Combinational logic still to settle belongs to `timestamp`, so its + /// reports read that time: settle it before the run moves on. + fn try_leave_time(&mut self, _timestamp: u64) -> Result<(), Halt> { + if self.timestamped_reports && self.dirty { + self.eval_comb_checked().map_err(Halt::Error)?; + self.dirty = false; + self.runtime_finish()?; + } + Ok(()) + } + /// Deferred assertions mature in the Observed and Postponed regions of /// the slot (IEEE 1800-2023 16.4). fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { @@ -460,6 +466,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), which declarations may have set. + simulator.initialize_copies(); Ok(Self { simulator, state, @@ -776,7 +785,11 @@ impl Simulation { return self.watched_step(); } // With nothing scheduled, the step ends the slot too. + let was_stopped = self.is_stopped(); self.end_idle_slot(self.state.next_event_time().unwrap_or(u64::MAX))?; + if !was_stopped && self.is_stopped() { + return Ok(Some(self.time())); + } self.step_until(u64::MAX) } @@ -787,7 +800,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 && !self.simulator.timestamped_reports) || end_time <= self.state.time() || self.state.next_event_time() == Some(self.state.time()) { @@ -802,7 +815,8 @@ impl Simulation { let result = if self.simulator.dirty { let result = self.simulator.eval_comb_checked(); self.simulator.dirty = false; - result + // A `$finish` of the settle finishes the simulation here. + result.and_then(|()| self.sync_finish_checked()) } else { Ok(()) }; @@ -824,7 +838,7 @@ impl Simulation { while let Some(next_time) = self.state.next_event_time() { if next_time > self.state.time() { self.watch_settle()?; - if self.reports.failure.is_some() { + if self.is_finished() || self.is_stopped() || self.reports.failure.is_some() { return Ok(Some(self.state.time())); } } @@ -872,7 +886,7 @@ impl Simulation { } if next_time > self.state.time() { self.watch_settle()?; - if self.reports.failure.is_some() { + if self.is_finished() || self.is_stopped() || self.reports.failure.is_some() { return Ok(false); } } @@ -886,7 +900,7 @@ impl Simulation { } } self.watch_settle()?; - Ok(self.reports.failure.is_none()) + Ok(!self.is_stopped() && self.reports.failure.is_none()) } /// Settle combinational logic that no step settled, as after host writes @@ -905,7 +919,11 @@ impl Simulation { return Ok(()); } if self.simulator.dirty { - if let Err(error) = self.simulator.eval_comb_checked() { + if let Err(error) = self + .simulator + .eval_comb_checked() + .and_then(|()| self.sync_finish_checked()) + { self.finalize_fatal(&error); self.flush_error_output(); return Err(error); @@ -987,7 +1005,11 @@ impl Simulation { return Ok(()); } } else { + let was_stopped = self.is_stopped(); self.end_idle_slot(end_time)?; + if !was_stopped && self.is_stopped() { + return Ok(()); + } } let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, @@ -1036,6 +1058,9 @@ impl Simulation { } else { self.end_idle_slot(time)?; } + if self.is_finished() || self.is_stopped() { + return Ok(()); + } self.state.advance_time(&mut self.simulator.backend, time); if let Some(shadow) = &mut self.shadow { shadow @@ -1065,7 +1090,11 @@ impl Simulation { self.run_until(end_time)?; return Ok(!self.state.is_stopped()); } + let was_stopped = self.is_stopped(); self.end_idle_slot(end_time)?; + if !was_stopped && self.is_stopped() { + return Ok(false); + } let mut steps = 0; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index b44cae3cbf5..0a0e5881c72 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -161,6 +161,14 @@ 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, + /// Some report site reads the time it issues its report at. + pub(crate) timestamped_reports: 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. @@ -298,6 +306,7 @@ mod host { } pub struct RuntimeEventDrain { + timed: bool, buffer: Arc, layout: MemoryLayout, sites: Vec, @@ -328,6 +337,7 @@ mod host { events .into_iter() .filter_map(|raw| render_raw_runtime_event(raw, &self.sites, ctx)) + .map(|event| untimed_report(event, self.timed, ctx)) .collect() } } @@ -625,6 +635,7 @@ mod host { args: &[RuntimeEventArgValue], ctx: RuntimeFormatContext<'_>, ) -> Vec { + let args = formatted_args(site, args); let Some(template) = site.template.as_deref() else { let default_spec = match site.kind { // Veryl prints arguments without a format string in hexadecimal. @@ -745,11 +756,48 @@ mod host { } } + /// Without a scheduler the simulation has no time: a report has the + /// time the host gives, not the one its site read. + fn untimed_report( + event: RuntimeEvent, + timed: bool, + ctx: RuntimeFormatContext<'_>, + ) -> RuntimeEvent { + match event { + RuntimeEvent::Report(report) if !timed => RuntimeEvent::Report(Report { + time: ctx.tb_time, + ..report + }), + event => event, + } + } + + /// The arguments of an event that its message formats: all but the + /// time of a timestamped site. + fn formatted_args<'a>( + site: &RuntimeEventSite, + args: &'a [RuntimeEventArgValue], + ) -> &'a [RuntimeEventArgValue] { + match (site.timestamp_arg, args.split_last()) { + (true, Some((_, args))) => args, + _ => args, + } + } + fn render_runtime_event( site: &RuntimeEventSite, args: &[RuntimeEventArgValue], ctx: RuntimeFormatContext<'_>, ) -> RuntimeEvent { + // The time the site issued the event, unless the host gives one. + let issued = site + .timestamp_arg + .then(|| args.last().and_then(|time| time.values.first().copied())) + .flatten(); + let ctx = RuntimeFormatContext { + tb_time: ctx.tb_time.or(issued), + ..ctx + }; let message = render_runtime_event_message(site, args, ctx); match site.kind { RuntimeEventKind::Display => RuntimeEvent::Display { message }, @@ -1019,6 +1067,7 @@ mod host { &program.runtime_schema.comb_observers, ); let sites = &program.runtime_schema.runtime_event_sites; + let timestamped_reports = sites.iter().any(|site| site.timestamp_arg); let deferred_sites = if sites.iter().any(|site| site.deferred.is_some()) { sites .iter() @@ -1030,6 +1079,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 +1126,9 @@ mod host { deferred_assertions: !deferred_sites.is_empty(), comb_deferred_groups, timed: false, + host_slot_work: !deferred_sites.is_empty() || !sample_shadows.is_empty(), + timestamped_reports, + sample_shadows, components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1093,6 +1156,7 @@ mod host { finish_sites: false, event_edges, }; + sim.initialize_copies(); sim.comb_observer_snapshots = sim.snapshot_all_comb_observers(); sim } @@ -1321,13 +1385,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( @@ -1410,6 +1473,7 @@ mod host { ctx, ) }) + .map(|event| untimed_report(event, self.timed, ctx)) .collect() } @@ -1469,6 +1533,68 @@ 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(()) + } + + /// Before the first time slot, start the `$past` histories and the + /// sampled copies with the values of their variables, the default + /// sampled values (IEEE 1800-2023 16.5.1). + pub(crate) fn initialize_copies(&mut self) { + if !self.host_slot_work && self.program.runtime_schema.initial_copies.is_empty() { + return; + } + for (variable, copy) in self.program.runtime_schema.initial_copies.clone() { + let variable = self.backend.resolve_signal(&variable); + let copy = self.backend.resolve_signal(©); + celox_runtime::copy_signal(&mut self.backend, variable, copy); + } + self.sample_values(); + } + + /// 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. @@ -1634,6 +1760,7 @@ mod host { .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .ok()?; Some(RuntimeEventDrain { + timed: self.timed, buffer, layout: self.backend.layout().clone(), sites: self.program.runtime_schema.runtime_event_sites.clone(), @@ -2054,8 +2181,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 +2228,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 +2256,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 +2326,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 +2341,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 +2420,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 +2443,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 +2483,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 +2588,7 @@ mod host { if self.frozen { return Ok(()); } + self.begin_host_slot()?; if let [event] = events { return self.tick(*event); } @@ -2492,7 +2649,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 +2751,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 +2794,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 +3541,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/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 913589e4aea..b57e8901db0 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -104,6 +104,7 @@ impl Simulator { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs index 491590fff87..38ecdd403e0 100644 --- a/crates/celox/tests/native_simulation_image.rs +++ b/crates/celox/tests/native_simulation_image.rs @@ -284,3 +284,23 @@ endmodule .unwrap(); assert_eq!(run(&mut sim), expected); } + +/// A native program instance ends no time slots, so an image with sampled +/// values or histories fails to attach. +#[test] +fn a_native_program_instance_rejects_sampled_values() { + let source = "module Top(input bit clk, input bit a, output bit r);\n \ + always_ff @(posedge clk) r <= $past(a);\nendmodule"; + let image = celox::Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + // SAFETY: the image was compiled from the trusted source above. + let Err(error) = (unsafe { NativeProgramInstance::from_image(image) }) else { + panic!("a native program instance ends no slots"); + }; + assert!( + error.to_string().contains("does not end time slots"), + "{error}" + ); +} diff --git a/crates/celox/tests/sv_deferred_assertions.rs b/crates/celox/tests/sv_deferred_assertions.rs index bffd145a554..6cc9c7493a3 100644 --- a/crates/celox/tests/sv_deferred_assertions.rs +++ b/crates/celox/tests/sv_deferred_assertions.rs @@ -390,7 +390,8 @@ macro_rules! deferred { } deferred!(interpreter, build_interpreter); -deferred!(cranelift, build); +#[cfg(feature = "cranelift")] +deferred!(cranelift, build_cranelift); #[cfg(target_arch = "x86_64")] deferred!(native, build_native); deferred!(wasm, build_wasm); @@ -526,14 +527,22 @@ fn a_first_drain_returns_actions_of_the_initial_settle() { #[test] fn deferred_actions_are_one_display_or_severity_task_call() { - let source = "module Top; bit a;\n \ - initial assert #0 (a) else begin $error(\"x\"); $error(\"y\"); end\n\ - endmodule"; - let error = celox::Simulation::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + for action in [ + "begin $error(\"x\"); $error(\"y\"); end", + "begin $error(\"x\"); end", + "a = 1;", + ] { + let source = + format!("module Top; bit a;\n initial assert #0 (a) else {action}\nendmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("deferred.sv"))], + "Top", + ) .build() .unwrap_err(); - assert!( - error.to_string().contains("deferred assertion action"), - "{error}" - ); + assert!( + error.to_string().contains("deferred assertion action"), + "{action}: {error}" + ); + } } diff --git a/crates/celox/tests/sv_past.rs b/crates/celox/tests/sv_past.rs new file mode 100644 index 00000000000..8172d6a0066 --- /dev/null +++ b/crates/celox/tests/sv_past.rs @@ -0,0 +1,446 @@ +#![cfg(feature = "systemverilog")] +//! `$past(e, k, gate)` is the sampled value of `e` at the `k`-th previous +//! tick of its clock at which `gate` held, and `$rose`, `$fell`, `$stable` +//! and `$changed` compare the sampled value with the one at the previous +//! tick. Before enough ticks, the past value is the default sampled value +//! (IEEE 1800-2023 16.9.3). The clock is inferred from an edge-triggered +//! process with one event (16.14.6). +use std::path::Path; + +/// A clock rising at 1, 3, 5, 7, ... and the declarations of the tests. +const HEADER: &str = "`timescale 1ns/1ns\nmodule Top;\n bit clk, en;\n bit [7:0] a, p1, p2, g;\n \ + bit b; logic l; int rn, fn_, sn, cn, lr, ls;\n always #1 clk = ~clk;\n"; + +macro_rules! past { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!("{HEADER}{body}\nendmodule"); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.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` is 0, 1, 2, 3 at the ticks 1, 3, 5, 7. + #[test] + fn past_values_are_sampled_at_earlier_ticks() { + let mut sim = simulation( + " always @(posedge clk) begin p1 <= $past(a); p2 <= $past(a, 2); end\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(5).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (1, 0)); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (2, 1)); + } + + #[test] + fn sampled_history_in_selects_uses_previous_ticks() { + let mut sim = simulation(r#" + bit i; + bit [1:0] data = 2'b10; + bit p, r, f, s, c; + always @(posedge clk) begin + p <= data[$past($sampled(i))]; + r <= data[$rose($sampled(i))]; + f <= data[$fell($sampled(i))]; + s <= data[$stable($sampled(i))]; + c <= data[$changed($sampled(i))]; + end + initial begin #2 i = 1; #4 i = 0; end +"#); + for (time, expected) in [ + (1, [0, 0, 0, 1, 0]), + (3, [0, 1, 0, 0, 1]), + (5, [1, 0, 0, 1, 0]), + (7, [1, 0, 1, 0, 1]), + ] { + sim.run_until(time).unwrap(); + assert_eq!(["p", "r", "f", "s", "c"].map(|n| value(&mut sim, n)), expected, "time={time}"); + } + } + + #[test] + fn real_stability_uses_numeric_equality() { + let mut sim = simulation(r#" + real d; + shortreal e; + bit ds, dc, es, ec, nested; + always @(posedge clk) begin + ds <= $stable(d); dc <= $changed(d); + es <= $stable(e); ec <= $changed(e); + nested <= $stable($sampled(d + 0.0)); + end + initial begin + #2 d = 1.5; e = 1.5; + #4 d = 0.0; e = 0.0; + #2 d = -0.0; e = -0.0; + end +"#); + for (time, expected) in [(1, [1, 0]), (3, [0, 1]), (5, [1, 0]), (7, [0, 1]), (9, [1, 0])] { + sim.run_until(time).unwrap(); + assert_eq!(["ds", "dc"].map(|n| value(&mut sim, n)), expected, "real time={time}"); + assert_eq!(["es", "ec"].map(|n| value(&mut sim, n)), expected, "shortreal time={time}"); + assert_eq!(value(&mut sim, "nested"), expected[0]); + } + } + + /// The gate's ticks: with `en` low at the tick of 5, `$past(a, 1, + /// en)` at 7 is the value at 3. + #[test] + fn a_gate_skips_ticks() { + let mut sim = simulation( + " always @(posedge clk) g <= $past(a, 1, en);\n \ + initial begin en = 1; #2 a = 1; #2 a = 2; en = 0; #2 a = 3; en = 1; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "g"), 1); + } + + /// An omitted number of ticks is one. + #[test] + fn an_omitted_number_of_ticks_is_one() { + let mut sim = simulation( + " always @(posedge clk) g <= $past(a, , en);\n \ + initial begin en = 1; #2 a = 1; #2 a = 2; en = 0; #2 a = 3; en = 1; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "g"), 1); + } + + /// The gate is evaluated at the tick, before the body clears it: + /// the tick of 3 takes `a` = 1 into the history. + #[test] + fn a_gate_is_evaluated_before_the_body() { + let mut sim = simulation( + " always @(posedge clk) begin g <= $past(a, 1, en); en = 0; end\n \ + initial begin #2 en = 1; a = 1; #2 en = 1; a = 2; end", + ); + sim.run_until(5).unwrap(); + assert_eq!(value(&mut sim, "g"), 1); + } + + /// The number of ticks is a constant expression. + #[test] + fn the_number_of_ticks_is_a_constant_expression() { + let mut sim = simulation( + " localparam int K = 1;\n \ + always @(posedge clk) begin p1 <= $past(a, K); p2 <= $past(a, K + 1); end\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (2, 1)); + } + + + /// `b` is 0, 1, 1, 0 at the ticks 1, 3, 5, 7; its value before + /// the first tick is 0. + #[test] + fn value_changes_compare_with_the_previous_tick() { + let mut sim = simulation( + " always @(posedge clk) begin\n \ + if ($rose(b)) rn <= rn + 1;\n \ + if ($fell(b)) fn_ <= fn_ + 1;\n \ + if ($stable(b)) sn <= sn + 1;\n \ + if ($changed(b)) cn <= cn + 1;\n \ + end\n \ + initial begin #2 b = 1; #4 b = 0; end", + ); + sim.run_until(7).unwrap(); + assert_eq!( + ["rn", "fn_", "sn", "cn"].map(|name| value(&mut sim, name)), + [1, 1, 2, 2] + ); + } + + /// Case equality: in four-state simulation `l` is X before the + /// first tick and at it, which is stable, and X to 1 is a rise. + #[test] + fn unknown_values_compare_with_case_equality() { + let body = " always @(posedge clk) begin\n \ + if ($stable(l)) ls <= ls + 1;\n \ + if ($rose(l)) lr <= lr + 1;\n \ + end\n \ + initial #2 l = 1;"; + let source = format!("{HEADER}{body}\nendmodule"); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.sv"))], + "Top", + ) + .four_state(true) + .$backend() + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "ls"), value(&mut sim, "lr")), (1, 0)); + sim.run_until(3).unwrap(); + assert_eq!((value(&mut sim, "ls"), value(&mut sim, "lr")), (1, 1)); + } + + /// Before the first tick the past value is the declared value. + #[test] + fn the_first_tick_sees_the_declared_value() { + let mut sim = simulation( + " bit [7:0] d = 5;\n \ + always @(posedge clk) p1 <= $past(d);\n \ + initial #0 d = 6;", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "p1"), 5); + } + + /// With an asynchronous reset the body reads the reset, so the + /// clock is inferred (IEEE 1800-2023 16.14.6); a run for the + /// reset is no tick. `a` is 0, 1, 2 at the ticks 1, 3, 5, and the + /// reset pulses low at 4: had that run shifted the history, + /// `$past(a, 2)` would be 1 at 5. + #[test] + fn an_asynchronous_reset_is_no_tick() { + let mut sim = simulation( + " bit rst = 1;\n \ + always_ff @(posedge clk or negedge rst)\n \ + if (!rst) p2 <= p2 + 1; else p1 <= $past(a, 2);\n \ + initial begin #2 a = 1; #2 a = 2; rst = 0; #0 rst = 1; end", + ); + sim.run_until(5).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (0, 1)); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "p1"), 1); + } + + /// Multi-event processes count all four-state clock edges + /// (IEEE 1800-2023 Table 9-2), including transitions into X/Z. + #[test] + fn four_state_clock_edges_advance_history() { + for (edge, old, new) in [ + ("posedge", "0", "1"), + ("posedge", "0", "x"), + ("posedge", "0", "z"), + ("posedge", "x", "1"), + ("posedge", "z", "1"), + ("negedge", "1", "0"), + ("negedge", "1", "x"), + ("negedge", "1", "z"), + ("negedge", "x", "0"), + ("negedge", "z", "0"), + ] { + let source = format!(r#"`timescale 1ns/1ns +module Top; + logic clk = 1'b{old}; + bit rst = 1; + bit [7:0] a, p; + always_ff @({edge} clk or negedge rst) + if (!rst) p <= 0; else p <= $past(a); + initial begin + a = 11; + #1 clk = 1'b{new}; + #1 a = 22; clk = 1'b{old}; + #1 clk = 1'b{new}; + end +endmodule"#); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.sv"))], "Top", + ).four_state(true).$backend().unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "p"), 11, "{edge} {old}->{new}"); + } + } + + /// A function called by a clocked process infers its clock. + #[test] + fn subroutines_infer_the_clock_of_their_caller() { + let mut sim = simulation( + " function bit [7:0] previous();\n \ + return $past(a);\n \ + endfunction\n \ + always @(posedge clk) p1 <= previous();\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "p1"), 2); + } + + /// So does the default of an omitted argument. + #[test] + fn argument_defaults_infer_the_clock_of_their_caller() { + let mut sim = simulation( + " function bit [7:0] pass(bit [7:0] v = $past(a));\n \ + return v;\n \ + endfunction\n \ + always @(posedge clk) p1 <= pass();\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "p1"), 2); + } + + /// A subroutine's history is as deep as its own calls need, also + /// beyond the caller's. + #[test] + fn subroutines_declare_their_own_history() { + let mut sim = simulation( + " function bit [7:0] deeper();\n \ + return $past(a, 2);\n \ + endfunction\n \ + always @(posedge clk) begin p1 <= $past(a); p2 <= deeper(); end\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (2, 1)); + } + + /// Without one clock to infer, the functions are rejected. + #[test] + fn a_clock_must_be_inferable() { + for item in [ + "initial #1 p1 = $past(a);", + "always_comb p1 = $past(a);", + "always @(posedge clk or posedge en) p1 <= $past(a);", + "always @(posedge clk) begin #1; p1 = $past(a); end", + ] { + let source = format!("{HEADER} {item}\nendmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.sv"))], + "Top", + ) + .$backend() + .err() + .expect("rejected"); + let text = error.to_string(); + assert!( + text.contains("whose clock it infers") + || text.contains("$sampled in combinational logic"), + "{item}: {text}" + ); + } + } + } + }; +} + +past!(interpreter, build_interpreter); +#[cfg(feature = "cranelift")] +past!(cranelift, build_cranelift); +#[cfg(target_arch = "x86_64")] +past!(native, build_native); +#[cfg(feature = "wasm-runtime")] +past!(wasm, build_wasm); + +/// A `Simulator` tick is a tick of the clock. +#[test] +fn simulator_ticks_are_clock_ticks() { + let source = "module Top(input bit clk, input bit [7:0] a, output bit [7:0] p);\n \ + always_ff @(posedge clk) p <= $past(a);\n\ + endmodule"; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap(); + let (a, p, clk) = (sim.signal("a"), sim.signal("p"), sim.event("clk")); + for value in 1..=3u8 { + sim.modify(|io| io.set(a, value)).unwrap(); + sim.tick(clk).unwrap(); + } + assert_eq!(sim.get_as::(p), 2); +} + +/// Before the first tick, a past value is the declared value. +#[test] +fn a_first_simulator_tick_sees_the_declared_value() { + let source = "module Top(input bit clk, output bit r);\n \ + bit d = 1;\n \ + always_ff @(posedge clk) begin r <= $past(d); d <= 0; end\n\ + endmodule"; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap(); + let (r, clk) = (sim.signal("r"), sim.event("clk")); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 1); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 1); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 0); +} + +/// A nested `$past` would need a history of its own. +#[test] +fn nested_past_calls_are_rejected() { + let source = "module Top(input bit clk, input bit a, output bit r);\n \ + always_ff @(posedge clk) r <= $past($past(a));\n\ + endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap_err(); + assert!( + error.to_string().contains("calls a sampled value function"), + "{error}" + ); +} + +/// Operands whose value a history of their variables cannot hold, and +/// sampled value functions inside `$sampled`, are rejected; so is a call in +/// a subroutine that needs more history than its caller declared. +#[test] +fn operands_histories_cannot_hold_are_rejected() { + for (body, message) in [ + ( + "always_ff @(posedge clk) t <= $past($time);", + "calls a function", + ), + ( + "function bit f(); return a; endfunction\n always_ff @(posedge clk) r <= $past(f());", + "calls a function", + ), + ( + "always_ff @(posedge clk) r <= $sampled($past(a));", + "`$sampled` of an operand that calls a sampled value function", + ), + ( + "function automatic bit gated(bit enable); return $past(a, 1, enable); endfunction\n \ + always_ff @(posedge clk) r <= gated(1'b1);", + "gate that reads the subroutine's arguments", + ), + ( + "function bit [7:0] previous(); return $past(a); endfunction\n \ + always_ff @(posedge clk) r <= $past(previous());", + "calls a function", + ), + ] { + let source = format!( + "module Top(input bit clk, input bit a, output bit r, output bit s, output time t);\n {body}\nendmodule" + ); + let Err(error) = + celox::Simulator::from_sv_sources(vec![(source.as_str(), Path::new("past.sv"))], "Top") + .build() + else { + panic!("{body} builds"); + }; + assert!(error.to_string().contains(message), "{body}: {error}"); + } +} + +/// A history moves with a copy of the whole variable, which an unpacked +/// array has no form of. +#[test] +fn past_values_of_unpacked_arrays_are_rejected() { + let source = "module Top(input bit clk, output bit [2:0] r);\n \ + bit [2:0] mem [0:3];\n \ + always_ff @(posedge clk) r <= $past(mem[3]);\n\ + endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap_err(); + assert!( + error.to_string().contains("of an unpacked array"), + "{error}" + ); +} diff --git a/crates/celox/tests/sv_reports.rs b/crates/celox/tests/sv_reports.rs index cceecc58a08..d7554e6b140 100644 --- a/crates/celox/tests/sv_reports.rs +++ b/crates/celox/tests/sv_reports.rs @@ -33,12 +33,24 @@ fn report( } } +/// `reports`, issued at `time`. +fn at(time: u64, reports: Vec) -> Vec { + reports + .into_iter() + .map(|report| Report { + time: Some(time), + ..report + }) + .collect() +} + macro_rules! reports { ($module:ident, $backend:ident) => { mod $module { use super::*; - /// The reports of `body` in `module Top` until time 1. + /// The reports of `body` in `module Top` until time 10, drained + /// after the run. fn reports(body: &str) -> Vec { let source = format!("`timescale 1ns/1ns\nmodule Top;\n{body}\nendmodule"); let mut sim = celox::Simulation::from_sv_sources( @@ -47,7 +59,7 @@ macro_rules! reports { ) .$backend() .unwrap(); - sim.run_until(1).unwrap(); + sim.run_until(10).unwrap(); sim.drain_runtime_events() .into_iter() .filter_map(|event| match event { @@ -68,11 +80,14 @@ macro_rules! reports { $error(\"e\");\n \ end" ), - vec![ - report(Severity::Info, "i 1", 5, None), - report(Severity::Warning, "w", 6, None), - report(Severity::Error, "e", 7, None), - ] + at( + 1, + vec![ + report(Severity::Info, "i 1", 5, None), + report(Severity::Warning, "w", 6, None), + report(Severity::Error, "e", 7, None), + ] + ) ); } @@ -91,7 +106,7 @@ macro_rules! reports { assume (!a) $info(\"assumed\");\n \ end" ), - vec![ + at(1, vec![ report( Severity::Warning, "a low", @@ -111,7 +126,7 @@ macro_rules! reports { Some((Some("c1"), Cover, Pass)) ), report(Severity::Info, "assumed", 9, Some((None, Assume, Pass))), - ] + ]) ); } @@ -131,12 +146,15 @@ macro_rules! reports { end\n \ end" ), - vec![report( - Severity::Error, - "assert failed", - 7, - Some((Some("inner"), Assert, Fail)) - )] + at( + 1, + vec![report( + Severity::Error, + "assert failed", + 7, + Some((Some("inner"), Assert, Fail)) + )] + ) ); } @@ -144,10 +162,26 @@ macro_rules! reports { fn always_comb_reports_keep_their_location() { assert_eq!( reports(" bit a;\n always_comb if (!a) $warning(\"low\");"), - vec![report(Severity::Warning, "low", 4, None)] + at(0, vec![report(Severity::Warning, "low", 4, None)]) ); } + /// A report keeps the time of its step however late the host + /// drains it (IEEE 1800-2023 20.10). + #[test] + fn reports_keep_their_time_when_drained_late() { + let times: Vec<_> = reports( + " initial begin\n \ + #1 $warning(\"w\");\n \ + #3 $error(\"e\");\n \ + end", + ) + .into_iter() + .map(|report| report.time) + .collect(); + assert_eq!(times, vec![Some(1), Some(4)]); + } + /// With `failOn`, a run stops after the time step of the first /// report of at least that severity, the next run continues, /// and every report keeps the time it was issued at. @@ -284,6 +318,145 @@ macro_rules! reports { assert!(failure.message.starts_with(b"missed "), "{failure:?}"); } + /// The initial settle of combinational logic is at time zero, + /// also when the first work is a clock edge at a later time, + /// reached by `run_until` or by `step`. + #[test] + fn initial_reports_before_a_later_first_slot_are_at_time_zero() { + let source = "`timescale 1ns/1ns\nmodule Top(input bit clk);\n \ + bit q, a;\n \ + always_ff @(posedge clk) q <= !q;\n \ + always_comb if (!a) $warning(\"low\");\nendmodule"; + for (step, watch) in [(false, false), (true, false), (false, true), (true, true)] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.add_clock("clk", 2, 5); + // Watching reports keeps the issued time too. + if watch { + sim.set_fail_on(Some(Severity::Warning)); + } + if step { + sim.step().unwrap(); + } else { + sim.run_until(10).unwrap(); + } + let times: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Report(report) => report.time, + event => panic!("unexpected event {event:?}"), + }) + .collect(); + assert_eq!(times, vec![Some(0)], "step: {step}, watch: {watch}"); + if watch { + assert_eq!(sim.failure().and_then(|report| report.time), Some(0)); + } + } + } + + /// A leave-time settle can terminate before any scheduled slot. + /// Exercise the host entry points, report watching, and final blocks. + #[test] + fn initial_report_finish_preserves_time_and_runs_final() { + for clock in [false, true] { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk); + bit a; + int ticks, final_calls; + always_ff @(posedge clk) ticks <= ticks + 1; + always_comb if (!a) begin $warning("initial"); $finish; end + final final_calls++; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if clock { sim.add_clock("clk", 2, 5); } + if watch { sim.set_fail_on(Some(Severity::Error)); } + match entry { + 0 => sim.run_until(10).unwrap(), + 1 => { sim.step().unwrap(); } + 2 => sim.advance_to(10).unwrap(), + _ => { sim.run_until_bounded(10, 10).unwrap(); } + } + assert_eq!(sim.time(), 0, "clock={clock}, watch={watch}, entry={entry}"); + assert!(sim.is_finished(), "clock={clock}, watch={watch}, entry={entry}"); + let final_calls = sim.signal("final_calls"); + let ticks = sim.signal("ticks"); + assert_eq!(sim.get(final_calls), 1u32.into()); + assert_eq!(sim.get(ticks), 0u32.into()); + let times: Vec<_> = sim.drain_runtime_events().into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Report(report) => Some(report.time), + _ => None, + }).collect(); + assert_eq!(times, vec![Some(0)]); + } + } + } + } + + #[test] + fn leave_time_final_can_stop_and_resume_at_the_same_time() { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top; + bit a; + int final_calls; + always_comb if (!a) begin $warning("initial"); $finish; end + final begin final_calls++; $stop; final_calls++; end +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if watch { sim.set_fail_on(Some(Severity::Error)); } + for resumed in [false, true] { + match entry { + 0 => sim.run_until(10).unwrap(), + 1 => { sim.step().unwrap(); } + 2 => sim.advance_to(10).unwrap(), + _ => { sim.run_until_bounded(10, 10).unwrap(); } + } + assert_eq!(sim.time(), 0); + assert_eq!(sim.is_stopped(), !resumed, "watch={watch}, entry={entry}"); + assert_eq!(sim.is_finished(), resumed); + let final_calls = sim.signal("final_calls"); + assert_eq!(sim.get(final_calls), (if resumed { 2u32 } else { 1u32 }).into()); + } + } + } + } + + #[test] + fn initial_fatal_runs_final_before_returning_the_error() { + for clock in [false, true] { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk); + bit a, q; + int final_calls; + always_ff @(posedge clk) q <= !q; + always_comb if (!a) $fatal(1, "initial"); + final final_calls++; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if clock { sim.add_clock("clk", 2, 5); } + assert!(matches!(sim.run_until(10), Err(celox::RuntimeErrorCode::Fatal { .. }))); + assert_eq!(sim.time(), 0); + assert!(sim.is_finished()); + let final_calls = sim.signal("final_calls"); + assert_eq!(sim.get(final_calls), 1u32.into()); + } + } + #[test] fn line_directives_set_the_reported_location() { let reports = reports("`line 40 \"other.sv\" 0\n initial $info(\"moved\");"); @@ -300,7 +473,8 @@ macro_rules! reports { } reports!(interpreter, build_interpreter); -reports!(cranelift, build); +#[cfg(feature = "cranelift")] +reports!(cranelift, build_cranelift); #[cfg(target_arch = "x86_64")] reports!(native, build_native); reports!(wasm, build_wasm); diff --git a/crates/celox/tests/sv_sampled.rs b/crates/celox/tests/sv_sampled.rs new file mode 100644 index 00000000000..9e7346959ea --- /dev/null +++ b/crates/celox/tests/sv_sampled.rs @@ -0,0 +1,303 @@ +#![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)); + } + + /// The copy of an array holds all of it. + #[test] + fn arrays_are_sampled_whole() { + let mut sim = simulation( + " bit [2:0] mem [0:3];\n bit [1:0] i;\n \ + int u;\n \ + always_ff @(posedge clk) mem[i] <= 3'd5;\n \ + always_ff @(posedge clk) u <= $sampled(mem[i]);\n \ + initial begin i = 3; #1 clk = 1; #1 clk = 0; #1 clk = 1; end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "u"), 0); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "u"), 5); + } + + /// 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); + } + + /// A static local keeps its value between runs, so its sampled + /// value is the one the previous run left; an automatic one is + /// read as it is (IEEE 1800-2023 16.5.1). `a` is 0, 1, 2, 3 at + /// the edges 1, 3, 5, 7. + #[test] + fn static_locals_are_sampled_and_automatic_ones_are_not() { + let mut sim = simulation( + " bit [7:0] p, q, w;\n \ + always #1 clk = ~clk;\n \ + always @(posedge clk) begin\n \ + bit [7:0] t;\n \ + automatic bit [7:0] u;\n \ + t = w; u = w;\n \ + p <= $sampled(t); q <= $sampled(u);\n \ + end\n \ + initial begin #2 w = 1; #2 w = 2; #2 w = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p"), value(&mut sim, "q")), (2, 3)); + } + + /// A combinational process runs when its inputs change, not + /// when their sampled values do, so it keeps the sampled value + /// it read (IEEE 1800-2023 4.5, 16.9.3). `a` becomes 1 at 1 and + /// 2 at 3. + #[test] + fn combinational_logic_reads_sampled_values_when_it_runs() { + for item in [ + "always_comb y = $sampled(a);", + "always @(a) y = $sampled(a);", + "assign y = $sampled(a);", + ] { + let body = format!( + " {item}\n initial begin #1 a = 1; #2 a = 0; end" + ); + let mut sim = simulation(&body); + let mut values = Vec::new(); + for time in [0, 1, 2, 3, 4] { + sim.run_until(time).unwrap(); + values.push(value(&mut sim, "y")); + } + assert_eq!(values, vec![0, 0, 0, 1, 1], "{item}"); + } + } + } + }; +} + +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..1884b55f280 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 processes, combinational logic and the subroutines they call; `$past`, `$rose`, `$fell`, `$stable` and `$changed` in edge-triggered processes whose clock they infer and the subroutines those 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 | @@ -703,12 +704,50 @@ severity, its message, the file and line of the call as `` `__FILE__ `` and action block of an immediate assertion also names that assertion: its statement label, `assert`, `assume` or `cover`, and whether the pass or the fail action issued it. Severity tasks in subroutines the action block calls -are not attributed. `time` is the time the drain's context gives, as the VPI -host does at each callback, or the time step of the report while -`Simulation::set_fail_on` is set. `Report::render` formats a report as the VPI host +are not attributed. `time` is the simulation time at which the report was +issued, however late the host drains it, unless the drain's context gives a +time, as the VPI host does at each callback; a `Simulator` has no time and +uses only the context's. +`Report::render` formats a report as the VPI host 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 static local is +sampled like a module variable. A `Simulator` call is a time slot. In +combinational logic (`always_comb`, `always_latch`, an `always` lowered as +combinational logic, a continuous assignment) the process reruns when the +operand's variables change, not when their sampled values do, and keeps the +sampled value it read until then (4.5). A design that uses `$sampled` runs the +compiled scheduler one slot at a time. + +`$past(e, k, gate)` is the sampled value of `e` at the `k`-th previous tick of +its clock at which `gate` held, the `iff` of the clock (9.4.2.3), and `$rose`, `$fell`, `$stable` +and `$changed` compare the sampled value of their operand with the one at the +previous tick, with case equality for integral values and numeric equality for +`real`/`shortreal` (`$rose` and `$fell` look at the least +significant bit). Before enough ticks, the past value is the declared or +default value (16.9.3). `k` is a positive constant. The clock is inferred +(16.14.6): in an `always_ff` or `always` process whose only timing control is +its event control, it is the clock edge when that is the only event whose +signal the body reads nowhere else, as with an asynchronous reset that the +body tests. A subroutine the process calls, also from the default of an +omitted argument, infers the same clock. The process keeps a history register +for each variable of the operand and updates it with nonblocking assignments at +the end of each run that is a tick of the clock. With an asynchronous reset, a +run is a tick when the clock has left the level it had before the time slot: a +clock that returns to that level within the slot, as `clk = 0; #0 clk = 1;` +from 1, does not move the history. An explicit clocking event argument, calls +without a clock to infer, nested calls such as `$past($past(a))` and operands +that read an unpacked array are rejected. + ### 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..439ea865291 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` はプロセス、組み合わせ回路とそれらから呼ぶサブルーチンで使用可能。`$past`、`$rose`、`$fell`、`$stable`、`$changed` はクロックを推論できるエッジで起動するプロセスと、そこから呼ぶサブルーチンで使用可能。[サンプル値](#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 値シミュレーション | @@ -403,11 +404,39 @@ static な output 引数も、代入しない経路では以前の値を保持 スコープを持ちます。即時アサーションのアクションブロックからの報告は、そのアサーションも示します。 文ラベル、`assert` / `assume` / `cover` の別、pass と fail のどちらのアクションから出たかです。 アクションブロックが呼ぶサブルーチン内の重大度タスクは、アサーションに結び付けません。`time` は -drain のコンテキストが与える時刻で、VPI ホストはコールバックごとに与えます。`Simulation::set_fail_on` -の設定中は、報告が出たタイムステップの時刻です。`Report::render` は、 +報告を出したシミュレーション時刻で、ホストがいつ drain しても変わりません。ただし drain の +コンテキストが時刻を与える場合はそれを使います。VPI ホストはコールバックごとに与えます。 +`Simulator` は時刻を持たないので、コンテキストの時刻だけを使います。`Report::render` は、 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`、継続代入)では、プロセスは +被演算子の変数が変わったときに再実行し、サンプル値が変わったときには再実行しません。それまでは +読んだサンプル値を保ちます(4.5)。`$sampled` を使う設計では、コンパイル済みスケジューラを +1 スロットずつ実行します。 + +`$past(e, k, gate)` は、クロックの `iff` である `gate`(9.4.2.3)が成り立っていたティックのうち +`k` 個前のものでの `e` のサンプル値です。`$rose`、`$fell`、`$stable`、`$changed` は、被演算子のサンプル値を +前のティックでのものと、整数型なら case 等価、`real` / `shortreal` なら数値の等価で比べます(`$rose` と `$fell` は最下位ビットを見ます)。ティックが +足りないうちは、過去の値は宣言の初期値か既定値です(16.9.3)。`k` は正の定数です。クロックは +推論します(16.14.6)。タイミング制御がイベント制御だけの `always_ff` / `always` プロセスでは、 +本体がほかで読まない信号のイベントがクロックのエッジだけのとき、それがクロックです。本体が +判定する非同期リセットがこれに当たります。プロセスが呼ぶサブルーチンも、省略した引数の既定値から +呼ぶものを含めて、同じクロックを推論します。プロセスは被演算子の変数ごとに履歴レジスタを持ち、 +クロックのティックである実行の最後にノンブロッキング代入で更新します。非同期リセットがあるときは、 +クロックがタイムスロット前のレベルから変わっている実行をティックとします。1 から `clk = 0; #0 clk = 1;` +のように同じスロット内で元のレベルに戻ったクロックでは、履歴は進みません。明示したクロッキング +イベント引数、推論できるクロックのない呼び出し、`$past($past(a))` のような入れ子の呼び出し、 +アンパック配列を読む被演算子は拒否します。 + ### 遅延付きアサーション `assert #0`、`assume #0`、`cover #0` とそれぞれの `final` 形のアクションは、プロセスの遅延