From 388c2141216f902aa6afb8ebe8a2e459a86ffdfb Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 12:07:59 +0900 Subject: [PATCH 1/3] fix(sv): fill unbased parameter overrides to their declared width Overriding a 58-bit parameter with '1 through -G or the Rust builder retained only 32 one bits, corrupting Taxi LFSR initialization. Apply the declaration width and signedness after selecting the override, including the final override pass, before binding dependent parameters. Extend API and CLI coverage above 32 bits and check signed fills, dependent parameters, and wide X/Z overrides. Validation: - SV analyzer: 770 passed, 3 existing ignores. - Literal-parameter API regression passes on all four backend variants; project CLI suite: 17 passed. - Taxi cc70b270b910d369ab1ad7b3855e76399fd461f1: original 58-bit scramble and descramble configurations pass at O1 with the original '1 argument and cocotb 2.0.1. - Formatting and all-target Clippy for the affected crates pass. Change-Id: If5f1b4a1bc351fcdacd025ea7d9d0829360d4b2c --- .../celox-sv-analyzer/src/ast/parameters.rs | 8 +++-- .../src/ast/parameters/tests.rs | 31 +++++++++++++++++++ crates/celox-vpi/tests/project_cli.rs | 4 +-- .../frontends/systemverilog/hierarchy.rs | 13 +++++--- 4 files changed, 48 insertions(+), 8 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 8bd0afb46cf..77f6b969d1d 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -119,7 +119,11 @@ pub(super) fn apply_parameter_overrides( } for parameter in parameters { if let Some(value) = overrides.get(parameter.name()) { - parameter.value = Some(value.clone()); + parameter.value = normalize_unbased_unsized_parameter_value( + Some(value.clone()), + parameter.declared_width(), + parameter.declared_signed(), + ); } } Ok(()) @@ -431,7 +435,6 @@ pub(super) fn parameters_from_native_with_environment( } else { None }; - value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed); // Apply overrides as each declaration is collected so later // parameter initializers (including casts) are evaluated from the // specialized values rather than defaults that will be replaced @@ -439,6 +442,7 @@ pub(super) fn parameters_from_native_with_environment( if !is_local && let Some(override_value) = parameter_overrides.get(&name) { value = Some(override_value.clone()); } + value = normalize_unbased_unsized_parameter_value(value, parameter_width, parameter_signed); if value .as_ref() .is_some_and(|expression| is_unbounded(expression, const_env)) diff --git a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs index a1ea6d0ef37..3ea1ba6bf94 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs @@ -1385,3 +1385,34 @@ fn logical_type_inference_requires_operand_types_outside_bounded_proofs() { }), ); } + +#[test] +fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() { + let tree = crate::source_tree::parse_scope_fixture( + "module Top #(parameter logic [57:0] FILL=0, \ + parameter logic signed [57:0] SIGNED_FILL=0, \ + parameter logic [57:0] COPY=FILL, parameter NEGATIVE=SIGNED_FILL < 0); endmodule", + Path::new("unbased_parameter_overrides.sv"), + ) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + for (literal, unsigned, signed) in [("'1", (1i128 << 58) - 1, -1), ("'0", 0, 0)] { + let overrides = ["FILL", "SIGNED_FILL"] + .into_iter() + .map(|name| (name.into(), ConstExpr::Literal(literal.into()))) + .collect(); + let mut parameters = + parameters_from_scope(&tree, &HashMap::default(), &HashMap::default(), &overrides) + .unwrap(); + for reapplied in [false, true] { + if reapplied { + apply_parameter_overrides(&mut parameters, &overrides).unwrap(); + } + let values = const_env_from_parameters(&tree.state, ¶meters); + assert_eq!(values["FILL"], unsigned, "{literal}, reapplied={reapplied}"); + assert_eq!(values["SIGNED_FILL"], signed); + assert_eq!(values["COPY"], unsigned); + assert_eq!(values["NEGATIVE"], i128::from(signed < 0)); + } + } +} diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index d1b03347042..43426385fbc 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -596,11 +596,11 @@ fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { let root = tempfile::tempdir().unwrap(); let source = r#" module Top #(parameter VENDOR="GENERIC", parameter NEG=3, - parameter logic [64:0] WIDE=0, parameter logic [11:0] FILL=0, + parameter logic [64:0] WIDE=0, parameter logic [57:0] FILL=0, parameter logic [3:0] UNKNOWN=0)(output logic matched); assign matched=(VENDOR == "XILINX") && (NEG == -8) && (NEG < 0) && ($bits(NEG) == 32) && ($bits(VENDOR) == 48) - && (WIDE == 65'h10000000000000001) && (FILL == 12'hfff) + && (WIDE == 65'h10000000000000001) && (FILL == 58'h3ffffffffffffff) && (UNKNOWN === 4'b10xz); initial begin #1; assert(matched) else $fatal(1,"literal parameter types"); $display("ok"); $finish; end diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index f1baf76a403..c1dc0f96413 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -368,12 +368,16 @@ sv_backends! { @setup { let source = r#" module Top #(parameter TEXT="default", parameter NEG=0, - parameter logic [11:0] FILL=0, parameter logic [3:0] UNKNOWN=0, - parameter logic [64:0] WIDE=0, parameter FINAL=0)(output logic matched); + parameter logic [57:0] FILL=0, parameter logic [3:0] UNKNOWN=0, + parameter logic [64:0] WIDE=0, parameter FINAL=0, + parameter logic [57:0] X=0, parameter logic [57:0] Z=0, + parameter logic [57:0] COPY=FILL)(output logic matched); assign matched=(TEXT=="XILINX") && ($bits(TEXT)==48) && (NEG==-8) && (NEG<0) && ($bits(NEG)==32) - && (FILL==12'hfff) && (UNKNOWN===4'b10xz) - && (WIDE==65'h10000000000000001) && (FINAL==7); + && (FILL==58'h3ffffffffffffff) && (UNKNOWN===4'b10xz) + && (WIDE==65'h10000000000000001) && (FINAL==7) + && (COPY==58'h3ffffffffffffff) + && (X===58'bx) && (Z===58'bz); endmodule "#; } @@ -383,6 +387,7 @@ sv_backends! { .param_literal("FILL", "'1").param_literal("UNKNOWN", "4'b10xz") .param_literal("WIDE", "65'h10000000000000001") .param_literal("FINAL", "-1").param("FINAL", 7) + .param_literal("X", "'x").param_literal("Z", "'z") .four_state(true).opt_level(celox::OptLevel::O2); assert_eq!(sim.get(sim.signal("matched")), BigUint::from(1u8)); } From 40433f0d9b563f23e13d2b7edbb00eb5c4c2078d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 12:08:13 +0900 Subject: [PATCH 2/3] fix(sv): defer indexed part-select base binding until types are available Runtime casts in an indexed part-select base were bound during preliminary validation as constant expressions, rejecting valid Taxi DMA selects with a constant-cast-operand error. Validate the positive constant width there and let normal expression lowering bind the variable base with complete type information, as required by IEEE 1800-2023 11.5.1. Add a shared regression for numeric and typedef casts in runtime read and write bases, including truncating indices. Validation: - Shared SV suite: 3287 passed, 90 existing ignores across the backend variants; indexed-select group: 298 passed. - New shared case passes Verilator and Icarus execution. - SV analyzer: 770 passed, 3 existing ignores; project CLI: 17 passed. - Original Taxi AXI CDMA [8-0] and AXI DMA [0-8] builds pass the former cast error and stop at separate combinational expression lowering failures for read_addr_next and addr_next. Neither is counted as an upstream runtime pass. - Formatting and affected-crate all-target Clippy pass. Change-Id: I57adbbd3abcd3c0e4761b3deb63d5232558a7f27 --- .../celox-sv-analyzer/src/ast/validation.rs | 9 +++---- .../src/sv/cases/indexed_select.vtest | 27 +++++++++++++++++++ .../frontends/systemverilog/indexed_select.rs | 4 +++ 3 files changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index c68a5d34ca4..efbe9323bcc 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -466,12 +466,11 @@ fn validate_scope( return Err(unsupported("mintypmax expression")); } ExprKind::Select { dimension, .. } => { - if let DimensionKind::Indexed { base, width, .. } = dimension.kind { + if let DimensionKind::Indexed { width, .. } = dimension.kind { if parameter_ranges.iter().any(|range| contains(*range, dimension.tokens)) { continue; } - let mut dimensions = indexed_dimensions.clone(); - dimensions.constant_indexed_base = true; - let value = expression_binding::value(base, native, syntax_tree, &dimensions)?; - selects::indexed_expression_value(&syntax_tree.state, value, &dimensions).ok_or_else(|| unsupported("index expression"))?; + // IEEE 1800-2023 11.5.1 permits a variable base. Its + // expression is bound after variable types are available; + // only the width requires constant validation here. check_indexed_width(width, syntax_tree, indexed_dimensions)?; } } diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 34f641f537e..da1e5612b22 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1736,3 +1736,30 @@ (top Top) (assert_eq enumeration 10) (assert_eq width 10)) + +(case runtime_indexed_bases_preserve_numeric_and_type_casts + (source "runtime_indexed_cast.sv" #" + module Top(input logic [63:0] data, input logic [1:0] offset, + input logic [3:0] index, + output logic [31:0] y, output logic [3:0] narrowed, + output logic [3:0] typed, output logic [63:0] written); + typedef logic [2:0] index_t; + assign y = data[3'(4-offset)*8 +: 32]; + assign narrowed = data[2'(index) +: 4]; + assign typed = data[index_t'(index) +: 4]; + always_comb begin + written = data; + written[3'(4-offset)*8 +: 8] = 8'hff; + end + endmodule + "#) + (top Top) + (modify (set data 0x0123456789abcdef)) + (for offset_value (range 0 4) + (modify (set offset offset_value)) + (assert_eq y (& (>> 0x0123456789abcdef (* (- 4 offset_value) 8)) 0xffffffff)) + (assert_eq written (| 0x0123456789abcdef (<< 0xff (* (- 4 offset_value) 8))))) + (for index_value (range 0 16) + (modify (set index index_value)) + (assert_eq narrowed (& (>> 0x0123456789abcdef (& index_value 3)) 15)) + (assert_eq typed (& (>> 0x0123456789abcdef (& index_value 7)) 15)))) diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 9acf8d49142..94701d08590 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -128,6 +128,10 @@ sv_backends! { assert_eq!(sim.get(sim.signal("narrow")), 0x1bu8.into()); } + fn runtime_indexed_bases_preserve_numeric_and_type_casts(sim) { + @case "indexed_select::runtime_indexed_bases_preserve_numeric_and_type_casts"; + } + fn indexed_select_preserves_selected_and_cast_bases(sim) { @case "indexed_select::indexed_select_preserves_selected_and_cast_bases"; } From f7bca3757b6bcfd56b3c14b877c23dc8b8d956d1 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 12:29:12 +0900 Subject: [PATCH 3/3] feat(sv): lower expression events and @* in processes Part of #1123, step 4 PR 4. An event item other than a whole module variable (selects, variable-index selects, any expression, pure function calls) becomes a hidden continuous assignment `$event[k] = expr`, and the wait term watches `$event[k]` (Rises, Falls or Changes). Each update of its value is an occurrence; an edge is one of the expression's LSB (IEEE 1800-2023 9.4.2, Table 9-2). Process-local and automatic operands are copied into `$event[k].arg[n]` before the process suspends, and the process stores the expression's value into `$event[k]`, so the event control samples it when it begins. The process only stores; detection stays the assignment plus the value baseline, and the store does not make `$event[k]` a counted signal. These variables are hidden from the signal listing and the waveform like the process slots, and persist in state files. `@*` in a process waits on the variables its statement reads (9.4.2.2). `iff`, impure calls and static task arguments stay rejected. Change-Id: Ifaff84d2abec60db0541d6ba8455b8815726c52a --- crates/celox-frontend-sv/src/lowering.rs | 35 +- crates/celox-frontend-sv/src/lowering/ff.rs | 361 +++++++++++++++++- .../src/lowering/procedural.rs | 47 ++- .../src/ast/procedural/control.rs | 25 +- .../src/ast/procedural/timing.rs | 186 ++++++++- .../src/source_tree/tests/timing_controls.rs | 1 - crates/celox-sv-analyzer/src/tests.rs | 34 +- crates/celox-test-suite/LIMITATIONS.md | 2 + .../src/sv/cases/timing.vtest | 140 +++++++ .../sv_expression_event_sample_icarus.json | 34 ++ ...v_implicit_event_in_process_verilator.json | 34 ++ .../verification/sv/icarus/timing.json | 254 ++++++++++++ .../verification/sv/limitations.json | 34 ++ .../verification/sv/verilator/timing.json | 254 ++++++++++++ .../tests/frontends/systemverilog/timing.rs | 134 ++++++- 15 files changed, 1532 insertions(+), 43 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json create mode 100644 crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 1c576a4a14d..55a2e7b7115 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -59,6 +59,9 @@ pub enum FrontendError { // from the source-facing hierarchy. The runtime image records their addresses. const FORCE_ENABLE: &str = "@force-enable:"; const FORCE_VALUE: &str = "@force-value:"; +/// The prefix of the variables `$event[k]` that hold the value of an event +/// expression, and of their copies of process-local operands. +const EVENT_PREFIX: &str = "$event["; #[derive(Clone)] struct SvVariable { @@ -104,9 +107,14 @@ impl SvVariable { } /// A hidden variable other than the time slot, whose value the lowered - /// code computes. The time slot is state the scheduler writes. + /// code computes. The time slot is state the scheduler writes, and an + /// event expression's variables are state its process and its + /// continuous assignment share. fn is_scratch(&self) -> bool { - self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() + self.hidden + && self.path != [TIME_SLOT] + && self.force_control.is_none() + && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -125,6 +133,9 @@ pub(crate) struct LoweredSvModule { package_variables: Vec<(SourceVarId, String, String)>, /// The hidden `(copy, signal)` event copies of [`FfEventVars`]. event_copies: Vec<(SourceVarId, SourceVarId)>, + /// The continuous assignments of the event expressions the processes + /// wait on, by their hidden target `$event[k]`. + event_assignments: Vec<(SourceVarId, Vec)>, } #[derive(Clone)] @@ -1472,6 +1483,7 @@ fn prepare_external_hierarchy_collecting( package_variables: Vec::new(), // The foreign module's own combinational blocks carry its copies. event_copies: Vec::new(), + event_assignments: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -2682,7 +2694,7 @@ fn lower_module_with_overrides( }; mark_ff_event_domains(&event_vars, &mut variables); - let (initial_values, processes, wait_sites, nba_sites, host_request_sites) = + let (initial_values, processes, wait_sites, nba_sites, host_request_sites, event_assignments) = lower_initial_processes( module, &mut variables, @@ -2806,6 +2818,7 @@ fn lower_module_with_overrides( instances, package_variables, event_copies: event_vars.copies, + event_assignments, }) } @@ -3187,6 +3200,9 @@ pub(crate) fn attach_instance_glue( .insert(*id, pm.variables[id].to_symbolic_variable()); } } + // An event expression is one more continuous assignment to a hidden + // buffer the processes watch. + port_assignments.extend(lowered.event_assignments.iter().cloned()); let (comb_blocks, arena, created, comb_observers, comb_sites) = lower_comb_processes( &lowered.source, &port_assignments, @@ -3529,11 +3545,12 @@ fn lower_initial_processes( Vec>, Vec>, Vec>, + Vec<(SourceVarId, Vec)>, ), sv::AnalyzerError, > { if module.initial_processes().is_empty() { - return Ok((Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new())); + return Ok(Default::default()); } let mut values = Vec::new(); let mut runtime = Vec::new(); @@ -3588,7 +3605,14 @@ fn lower_initial_processes( } } if runtime.is_empty() { - return Ok((values, Vec::new(), Vec::new(), Vec::new(), Vec::new())); + return Ok(( + values, + Vec::new(), + Vec::new(), + Vec::new(), + Vec::new(), + Vec::new(), + )); } let mut next_id = SourceVarId( @@ -3686,6 +3710,7 @@ fn lower_initial_processes( wait_sites, nba_sites, host_request_sites, + std::mem::take(&mut pm.event_assignments), )) } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 0a7a5fd1a6b..1f6528c1d3e 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4175,14 +4175,29 @@ impl Ff<'_, '_> { /// `@(items)` (IEEE 1800-2023 9.4.2): the process waits for an /// occurrence of any item, which the runtime detects on the watched /// signals themselves, so nothing is left to check when it resumes. + /// + /// An item other than a variable of the module is watched through the + /// variable `$event[k]` of a continuous assignment of the expression: + /// each update of its value is an occurrence, and an edge is one of the + /// least significant bit of the expression (Table 9-2). Before it + /// suspends, the process copies the process-local operands the + /// assignment reads and stores the expression's value, which the event + /// control samples as it begins. fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { let mut terms = Vec::new(); + let mut samples = Vec::new(); for item in items { - let id = match &item.expr { - sv::ir::Expr::Ident(name) => self.m.id(name).filter(|&id| !self.m.is_hidden(id)), - _ => None, - } - .ok_or_else(|| unsupported("event expression other than a variable"))?; + let expr = self.propagate(&item.expr); + let id = match &expr { + sv::ir::Expr::Ident(name) => match self.m.id(name) { + Some(id) if !self.m.is_hidden(id) => id, + Some(_) => self.event_expression(&expr, &mut samples)?, + // A constant never changes. + None if self.m.constants.contains_key(name) => continue, + None => return Err(unsupported(format!("event expression `{name}`"))), + }, + _ => self.event_expression(&expr, &mut samples)?, + }; match item.edge { sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), sv::ir::EventEdge::Pos => terms.push((id, CounterKind::Rises)), @@ -4193,6 +4208,9 @@ impl Ff<'_, '_> { } } } + for (target, value) in samples { + self.assign(&sv::ir::LValue::Ident(target), &value)?; + } let site = self.wait_site(terms); self.with_kernel(|kernel| -> Result<(), ProcessKernelError> { kernel.suspend_wait(site)?; @@ -4206,6 +4224,105 @@ impl Ff<'_, '_> { .map_err(kernel_error) } + /// The variable `$event[k]` of a new event expression `expr`, with its + /// continuous assignment added to the module. `samples` gets the + /// assignments the process makes before it suspends: the copies of the + /// process-local operands, then `$event[k]` itself. + fn event_expression( + &mut self, + expr: &sv::ir::Expr, + samples: &mut Vec<(String, sv::ir::Expr)>, + ) -> Result { + if let Some(name) = impure_call(self.m, expr) { + return Err(unsupported(format!( + "impure call `{name}` in an event expression" + ))); + } + let typed = self.m.typed_calls(expr); + let width = sv_expr_natural_width( + &typed, + self.m.variables, + self.m.name_to_id, + self.m.constants, + self.m.parameter_types, + ) + .ok_or_else(|| unsupported("event expression of unknown width"))?; + let signed = self.expr_signed(expr); + let mut names = HashSet::default(); + expr_idents(expr, &mut names); + let mut locals: Vec<_> = names + .into_iter() + .filter_map(|name| { + let id = self.m.id(&name)?; + self.m.is_hidden(id).then_some((name, id)) + }) + .collect(); + locals.sort_unstable(); + // Another call can copy a new argument into a static formal while + // the process waits, which a copy taken now would not see. + if locals.iter().any(|&(_, id)| self.is_static_task_formal(id)) { + return Err(unsupported( + "event expression reading a static task argument", + )); + } + let index = self.m.next_event_index(); + let (event, event_name) = self.m.event_variable( + index, + None, + SvVariable { + path: Vec::new(), + width, + signed, + is_4state: true, + packed_ranges: vec![(width as i128 - 1, 0)], + array_dims: Vec::new(), + unpacked_ranges: Vec::new(), + domain_kind: DomainKind::Other, + kind: VariableKind::Variable, + type_kind: PortTypeKind::Logic, + source: None, + hidden: true, + force_control: None, + }, + ); + let mut renames = HashMap::default(); + for (position, (name, id)) in locals.into_iter().enumerate() { + let variable = self.m.var(id).clone(); + let (copy, copy_name) = + self.m + .event_variable(index, Some(format!("arg[{position}]")), variable); + if let Some(width) = self.element_widths.get(&stable(id)).copied() { + self.element_widths.insert(stable(copy), width); + self.element_widths.insert(working(copy), width); + } + samples.push((copy_name.clone(), sv::ir::Expr::Ident(name.clone()))); + renames.insert(name, copy_name); + } + let value = rename_idents(expr, &renames); + samples.push((event_name.clone(), value.clone())); + self.m.event_assignments.push(( + event, + vec![sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(event_name), + rhs: value, + nonblocking: false, + }], + )); + Ok(event) + } + + /// Whether `id` is a static formal of a task, which keeps one + /// module-wide address for every call. + fn is_static_task_formal(&self, id: SourceVarId) -> bool { + self.m.subroutines.values().any(|subroutine| { + subroutine.is_task + && subroutine.params.iter().any(|param| { + !subroutine.automatic_locals.contains(¶m.name) + && self.m.id(¶m.name) == Some(id) + }) + }) + } + /// `wait (condition)` (IEEE 1800-2023 9.4.3): the process goes on at once /// if the condition holds, and otherwise checks it again whenever a /// variable it reads changes. @@ -4217,16 +4334,10 @@ impl Ff<'_, '_> { // in, but hidden local storage has no observable change counters yet. // Do not compile a wait that would silently miss that wakeup, including // dependencies read indirectly by a function in the condition. - if self.m.subroutines.values().any(|subroutine| { - subroutine.is_task - && subroutine.params.iter().any(|param| { - !subroutine.automatic_locals.contains(¶m.name) - && names.iter().any(|name| { - self.m.id(name).is_some_and(|id| { - self.m.is_hidden(id) && Some(id) == self.m.id(¶m.name) - }) - }) - }) + if names.iter().any(|name| { + self.m + .id(name) + .is_some_and(|id| self.m.is_hidden(id) && self.is_static_task_formal(id)) }) { return Err(unsupported("wait condition reading a static task argument")); } @@ -4377,6 +4488,226 @@ fn subroutine_reads(pm: &ProcModule<'_>, expr: &sv::ir::Expr, names: &mut HashSe } } +/// The name of a call in `expr` that has an effect or reads the state of the +/// simulation, directly or through the functions it calls: an event +/// expression must be a value of the variables it reads. +fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { + let mut pending = vec![expr.clone()]; + let mut visited = HashSet::default(); + while let Some(expr) = pending.pop() { + let callees = std::cell::RefCell::new(Vec::new()); + expr_calls(&expr, &|callee| { + callees.borrow_mut().push(callee.clone()); + false + }); + for callee in callees.into_inner() { + let name = match callee { + sv::ir::Callee::System(function) => { + if function.reads_simulation_state() { + return Some(function.name().to_string()); + } + continue; + } + sv::ir::Callee::Subroutine(name) => name, + }; + if !visited.insert(name.clone()) { + continue; + } + if let Some(import) = pm.dpi_imports.get(&name) { + if !import.is_pure() { + return Some(name); + } + continue; + } + let Some(subroutine) = pm.subroutine(&name) else { + return Some(name); + }; + if subroutine.is_task + || subroutine + .params + .iter() + .any(|param| param.direction.is_written()) + { + return Some(name); + } + pending.extend( + subroutine + .params + .iter() + .filter_map(|param| param.default.clone()), + ); + // Only the function's own variables may be written. + let local = + |lvalue: &sv::ir::LValue| pm.id(lvalue.name()).is_some_and(|id| pm.is_hidden(id)); + let mut effect = false; + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { lhs, .. } => effect |= !local(lhs), + sv::ir::Stmt::AssignConcat { parts, .. } => effect |= !parts.iter().all(local), + sv::ir::Stmt::Call { + name, + args, + arg_order, + } => pending.push(sv::ir::Expr::Call { + callee: sv::ir::Callee::Subroutine(name.clone()), + args: args.clone(), + arg_order: arg_order.clone(), + }), + sv::ir::Stmt::SystemTask { .. } + | sv::ir::Stmt::Delay { .. } + | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::Wait(_) => effect = true, + _ => {} + }); + stmt.clone().visit_mut( + &mut |expr| pending.push(expr.clone()), + &mut |_| {}, + &mut |_| {}, + ); + } + if effect { + return Some(name); + } + } + } + None +} + +/// `expr` with the identifiers in `renames` replaced. +fn rename_idents(expr: &sv::ir::Expr, renames: &HashMap) -> sv::ir::Expr { + fn constant(expr: &sv::ir::ConstExpr, renames: &HashMap) -> sv::ir::ConstExpr { + use sv::ir::ConstExpr; + let go = |expr: &ConstExpr| Box::new(constant(expr, renames)); + match expr { + ConstExpr::Ident(name) => ConstExpr::Ident(renames.get(name).unwrap_or(name).clone()), + ConstExpr::Literal(_) => expr.clone(), + ConstExpr::SelectRange { + expr, + msb, + lsb, + signed, + } => ConstExpr::SelectRange { + expr: go(expr), + msb: go(msb), + lsb: go(lsb), + signed: *signed, + }, + ConstExpr::Select { expr, bit } => ConstExpr::Select { + expr: go(expr), + bit: go(bit), + }, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), + site: *site, + args: args.iter().map(|arg| constant(arg, renames)).collect(), + }, + ConstExpr::Resize { + expr, + width, + signed, + } => ConstExpr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + ConstExpr::Unary { op, expr } => ConstExpr::Unary { + op: *op, + expr: go(expr), + }, + ConstExpr::Binary { left, op, right } => ConstExpr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => ConstExpr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, + } + } + use sv::ir::Expr; + let go = |expr: &Expr| Box::new(rename_idents(expr, renames)); + match expr { + Expr::Ident(name) => Expr::Ident(renames.get(name).unwrap_or(name).clone()), + Expr::Literal(_) => expr.clone(), + Expr::Select { + expr, + msb, + lsb, + signed, + } => Expr::Select { + expr: go(expr), + msb: constant(msb, renames), + lsb: constant(lsb, renames), + signed: *signed, + }, + Expr::Concat(parts) => Expr::Concat( + parts + .iter() + .map(|part| rename_idents(part, renames)) + .collect(), + ), + Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { + count: constant(count, renames), + parts: parts + .iter() + .map(|part| rename_idents(part, renames)) + .collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + Expr::Unary { op, expr } => Expr::Unary { + op: *op, + expr: go(expr), + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + callee: callee.clone(), + args: args + .iter() + .map(|arg| arg.as_ref().map(|arg| rename_idents(arg, renames))) + .collect(), + arg_order: arg_order.clone(), + }, + Expr::Inside { expr, items } => Expr::Inside { + expr: go(expr), + items: items + .iter() + .map(|item| item.map(&mut |operand| rename_idents(operand, renames))) + .collect(), + }, + } +} + /// The names of the user subroutines `expr` calls. fn collect_call_names(expr: &sv::ir::Expr, names: &mut Vec) { let called = std::cell::RefCell::new(Vec::new()); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 8960d107d1a..b904b4861ee 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -43,6 +43,9 @@ pub(super) struct ProcModule<'a> { pub runtime_event_sites: Vec, /// Runtime errors (fatal assertions) of the module, by local code. pub runtime_errors: HashMap>, + /// The continuous assignments `$event[k] = expr` of the event + /// expressions the module's processes wait on, by target. + pub event_assignments: Vec<(SourceVarId, Vec)>, /// The declared bounds of each unpacked dimension, by variable. unpacked_bounds: HashMap>, /// Where the warnings found while lowering go. A process lowered more @@ -144,6 +147,7 @@ impl<'a> ProcModule<'a> { capture_counter: 0, runtime_event_sites: Vec::new(), runtime_errors: HashMap::default(), + event_assignments: Vec::new(), unpacked_bounds, warnings, } @@ -645,6 +649,47 @@ impl<'a> ProcModule<'a> { id } + /// A module-scope variable of event expression `index` with the shape + /// of `variable`: `$event[index]` itself for `slot == None`, otherwise + /// its copy `$event[index].slot`. Like a process slot it is no signal of + /// the design, but state that persists while processes wait. + pub fn event_variable( + &mut self, + index: usize, + slot: Option, + variable: SvVariable, + ) -> (SourceVarId, String) { + let path: Vec<_> = std::iter::once(format!("{EVENT_PREFIX}{index}]")) + .chain(slot) + .collect(); + let name = path.join("."); + let id = next_var_id(&mut self.next_id); + self.variables.insert( + id, + SvVariable { + path, + domain_kind: DomainKind::Other, + kind: VariableKind::Variable, + source: None, + hidden: true, + force_control: None, + ..variable + }, + ); + self.name_to_id.insert(name.clone(), id); + (id, name) + } + + /// The index of the next event expression of the module. + pub fn next_event_index(&self) -> usize { + (0..) + .take_while(|index| { + self.name_to_id + .contains_key(&format!("{EVENT_PREFIX}{index}]")) + }) + .count() + } + pub fn subroutine(&self, name: &str) -> Option<&sv::ir::Subroutine> { self.subroutines.get(name) } @@ -757,7 +802,7 @@ impl<'a> ProcModule<'a> { /// `expr` with each user function call replaced by a literal of its /// return type. - fn typed_calls(&self, expr: &sv::ir::Expr) -> sv::ir::Expr { + pub fn typed_calls(&self, expr: &sv::ir::Expr) -> sv::ir::Expr { use sv::ir::Expr; let go = |expr: &Expr| self.typed_calls(expr); 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 c546db6d4e5..9f4de8c4bac 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -53,6 +53,13 @@ enum Job { loops: Vec<(String, i128, i128)>, start: usize, }, + /// The end of the statement an `@*` controls, which starts at `start` + /// of the output; `sensitivity` is where its constant-folded branches + /// start in the builder's sensitivity body. + ImplicitEvent { + start: usize, + sensitivity: usize, + }, AssertionThen { condition: Expr, keyword: String, @@ -211,8 +218,15 @@ impl BodyBuilder<'_, '_, '_> { jobs.push(Job::Enter(*body)); } StatementKind::Timing { control, body } => { - let timing = self.native_timing_control(*control)?; - output.push(timing); + if self.implicit_event_control(*control)? { + jobs.push(Job::ImplicitEvent { + start: output.len(), + sensitivity: self.sensitivity_body.len(), + }); + } else { + let timing = self.native_timing_control(*control)?; + output.push(timing); + } jobs.push(Job::Enter(*body)); } // Explicit typed assignments/calls/assertions/unsupported @@ -243,6 +257,13 @@ impl BodyBuilder<'_, '_, '_> { _ => output.extend(self.native_statement_leaf(&native.statement(id).kind)?), }, Job::EndScope => self.pop_scope(), + Job::ImplicitEvent { start, sensitivity } => { + let wait = timing::implicit_event( + &output[start..], + &self.sensitivity_body[sensitivity..], + ); + output.insert(start, wait); + } Job::AssertionThen { condition, keyword, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index 949d5cf551b..70494ce65d2 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -50,12 +50,30 @@ impl BodyBuilder<'_, '_, '_> { Ok(Stmt::WaitEvent(result)) } EventControl::Named(_) => Err(unsupported("named event")), - EventControl::Wildcard => Err(unsupported("`@*` event control in a process")), + // The statement it controls gives its event expression. + EventControl::Wildcard => Err(crate::ast::timing::disagreement()), } } } } + /// Whether `id` is `@*` (or `@(*)`), whose event expression the + /// statement it controls determines (see [`implicit_event`]). + pub(super) fn implicit_event_control( + &self, + id: TimingControlId, + ) -> Result { + let control = self.tree.declarations().timing_control(id); + if !matches!( + control.kind, + TimingControlKind::Event(EventControl::Wildcard) + ) { + return Ok(false); + } + self.allow_timing("event control")?; + Ok(true) + } + fn native_delay(&self, mut value: ExprId, parenthesized: bool) -> Result { let native = self.tree.declarations(); if parenthesized { @@ -105,3 +123,169 @@ impl BodyBuilder<'_, '_, '_> { } } } + +/// The wait of an `@*` that controls the statement lowered to `body`, with +/// the branches constant folding removed from it in `removed`: an event of +/// any change of each variable the statement reads (IEEE 1800-2023 +/// 9.4.2.2). That is every identifier in an expression, a subroutine +/// argument or a left-hand-side index, but not in a timing control (a +/// delay, wait or event control) and not an assignment target itself. Names that turn out not to +/// denote a variable, such as parameters, never change. +pub(super) fn implicit_event(body: &[Stmt], removed: &[Stmt]) -> Stmt { + fn constant(expr: &ConstExpr, names: &mut Vec) { + match expr { + ConstExpr::Ident(name) => push(name, names), + ConstExpr::Literal(_) => {} + ConstExpr::Select { expr, bit } => { + constant(expr, names); + constant(bit, names); + } + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + constant(expr, names); + constant(msb, names); + constant(lsb, names); + } + ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => constant(expr, names), + ConstExpr::Function { args, .. } => args.iter().for_each(|arg| constant(arg, names)), + ConstExpr::Binary { left, right, .. } => { + constant(left, names); + constant(right, names); + } + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => { + constant(condition, names); + constant(then_expr, names); + constant(else_expr, names); + } + } + } + fn expression(expr: &Expr, names: &mut Vec) { + match expr { + Expr::Ident(name) => push(name, names), + Expr::Literal(_) => {} + Expr::Select { expr, msb, lsb, .. } => { + expression(expr, names); + constant(msb, names); + constant(lsb, names); + } + Expr::Concat(parts) => parts.iter().for_each(|part| expression(part, names)), + Expr::RepeatConcat { count, parts } => { + constant(count, names); + parts.iter().for_each(|part| expression(part, names)); + } + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => expression(expr, names), + Expr::Binary { left, right, .. } => { + expression(left, names); + expression(right, names); + } + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + expression(condition, names); + expression(then_expr, names); + expression(else_expr, names); + } + // A function's own reads are not part of the event expression. + Expr::Call { args, .. } => args.iter().flatten().for_each(|arg| expression(arg, names)), + Expr::Inside { expr, items } => { + expression(expr, names); + for item in items { + item.exprs() + .into_iter() + .for_each(|operand| expression(operand, names)); + } + } + } + } + fn target(lvalue: &LValue, names: &mut Vec) { + if let LValue::Select { + msb, + lsb, + array_slice_width, + .. + } = lvalue + { + constant(msb, names); + constant(lsb, names); + if let Some(width) = array_slice_width { + constant(width, names); + } + } + } + fn push(name: &str, names: &mut Vec) { + if !names.iter().any(|known| known == name) { + names.push(name.to_string()); + } + } + let mut names = Vec::new(); + for stmt in body.iter().chain(removed) { + stmt.walk(&mut |stmt| match stmt { + Stmt::Assign { lhs, rhs, .. } => { + target(lhs, &mut names); + expression(rhs, &mut names); + } + Stmt::AssignConcat { parts, rhs, .. } => { + parts.iter().for_each(|part| target(part, &mut names)); + expression(rhs, &mut names); + } + Stmt::If { condition, .. } => expression(condition, &mut names), + Stmt::Case { + selector, items, .. + } => { + expression(selector, &mut names); + for label in items.iter().flat_map(|item| &item.labels) { + match label { + CaseLabel::Value(value) => expression(value, &mut names), + CaseLabel::Range { low, high } => { + expression(low, &mut names); + expression(high, &mut names); + } + } + } + } + Stmt::Loop { + kind, condition, .. + } => { + if let LoopKind::Repeat(count) = kind { + expression(count, &mut names); + } + if let Some(condition) = condition { + expression(condition, &mut names); + } + } + Stmt::Return(value) => value.iter().for_each(|value| expression(value, &mut names)), + Stmt::Call { args, .. } => args + .iter() + .flatten() + .for_each(|arg| expression(arg, &mut names)), + Stmt::Eval(expr) => expression(expr, &mut names), + Stmt::SystemTask { args, .. } => { + for arg in args { + if let SystemTaskArg::Expr(expr) = arg { + expression(expr, &mut names); + } + } + } + Stmt::Local { init, .. } => init.iter().for_each(|init| expression(init, &mut names)), + Stmt::Break + | Stmt::Continue + | Stmt::Delay { .. } + | Stmt::WaitEvent(_) + | Stmt::Wait(_) => {} + }); + } + Stmt::WaitEvent( + names + .into_iter() + .map(|name| EventItemBase { + edge: EventEdge::Any, + expr: Expr::Ident(name), + }) + .collect(), + ) +} diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs index 8e46fa7574d..4b10b9bf4e1 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs @@ -115,7 +115,6 @@ fn native_timing_event_membership_and_delay_roles_are_authoritative() { fn native_timing_preserves_existing_restrictions_including_ff_iff_validation() { for (body, diagnostic) in [ ("initial @(a iff en) q=1;", "iff-qualified event"), - ("initial @* q=1;", "`@*` event control"), ("always_comb #1 q=d;", "delay control"), ("always_ff @(edge clk) q<=d;", "always_ff event expression"), ( diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index f32421c9afb..cea7e6067b0 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3510,10 +3510,6 @@ fn rejects_unimplemented_timing_constructs() { ), ("initial begin : b disable b; end", "disable statement"), ("initial #1.5;", "delay value"), - ( - "logic a; initial @* a = 1;", - "`@*` event control in a process", - ), ("logic a, y; always_latch y = a;", "always_latch process"), ( "function void t(); #1; endfunction", @@ -3587,6 +3583,36 @@ fn analyzes_timing_controls_in_initial_blocks() { analyze_source(code, Path::new("timing.sv")).expect("timing controls in an initial block"); } +/// `@*` in a process waits on the variables its statement reads (IEEE +/// 1800-2023 9.4.2.2): right-hand sides, conditions, arguments and +/// left-hand-side indices, but not assignment targets or timing controls. +#[test] +fn implicit_event_controls_wait_on_the_reads_of_their_statement() { + let code = "module Top(input logic [7:0] a, b, c, d, i, output logic [7:0] y, z);\n\ + initial forever @* begin if (c > 0) y = a; else y = b; z[i] = 1; @(d); #(d); end\n\ + endmodule"; + let ir = analyze_source(code, Path::new("implicit.sv")).expect("`@*` in a process"); + let mut waits = Vec::new(); + for process in ir.modules()[0].initial_processes() { + for stmt in process.body() { + stmt.walk(&mut |stmt| { + if let ir::Stmt::WaitEvent(items) = stmt { + waits.push( + items + .iter() + .map(|item| match &item.expr { + ir::Expr::Ident(name) => name.clone(), + expr => panic!("unexpected event expression {expr:?}"), + }) + .collect::>(), + ); + } + }); + } + } + assert_eq!(waits, [vec!["c", "a", "b", "i"], vec!["d"]]); +} + #[test] fn analyzes_veryl_emitted_fifo_with_runtime_casts() { analyze_source( diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index baf27d6f58d..3c5142601db 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -381,6 +381,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | Group | Stage | Tool | Cases | Reason | | --- | --- | --- | ---: | --- | | `sv_icarus_automatic_task_arrays` | execute | icarus | 1 | Icarus 13.0 shares an automatic task's unpacked local array across overlapping calls. IEEE 1800-2023 13.3.1–13.3.2 require separate storage for each activation. The [pre-exclusion result](verification/repros/sv_timed_task_arrays_icarus.json) retains the first call returning 31 instead of 11. The scalar activation case remains enabled for Icarus. | +| `sv_icarus_expression_event_sample` | execute | icarus | 1 | Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (`a = 1; @(a ^ b);`). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression, and the write came before the event control. Verilator 5.052 agrees with the expected value. The [pre-exclusion result](verification/repros/sv_expression_event_sample_icarus.json) is retained. | +| `sv_verilator_implicit_event_in_process` | compile | verilator | 1 | Verilator 5.052 rejects `@*` in an `initial forever` ("Unsupported: Event control with implicit sensitivity (@*) in this context"); IEEE 1800-2023 9.4.2.2 permits it in any procedural timing control. Icarus 13.0 passes the case. The [pre-exclusion diagnostic](verification/repros/sv_implicit_event_in_process_verilator.json) is retained. | | `sv_icarus_genvar_dimensions` | execute | icarus | 1 | Icarus 13.0 returns 0 for `$dimensions` of a generated loop index's implicit integer localparam; IEEE 1800-2023 27.4 and 20.7 require one packed dimension. Celox and Verilator pass the unchanged assertions. The [standalone reproducer and pre-exclusion result](verification/repros/sv_genvar_dimensions.json) retain the observed disagreement. | | `sv_icarus_constant_array_queries` | compile | icarus | 1 | Icarus 13.0 rejects array queries of variables in constant expressions and typedef operands; IEEE 1800-2023 20.7 permits them. Verilator passes. | | `sv_icarus_runtime_array_queries` | execute | icarus | 1 | Icarus 13.0 aborts on a runtime dimension argument. A standalone reproducer also rejects an integer variable as the dimension. IEEE 1800-2023 20.7 permits querying fixed-size dimensions with runtime expressions. | diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 0d8d2319726..2327c8f2183 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1056,3 +1056,143 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (top Top) (run_to_finish) (assert_eq count 8)) + +(case expression_events_see_pulses_within_a_time_slot + ; IEEE 1800-2023 9.4.2: each change of the expression's value is an + ; event, also one the slot undoes before it ends. The waits begin after + ; time 0, where Icarus 13.0 reports an event of a new expression. + (source "expression_pulse.sv" #" + module Top(output bit [7:0] count, output bit hit); + bit a, b; + initial begin #1; forever begin @(a ^ b); count = count + 8'd1; end end + initial begin #1; @(a ^ b); hit = 1; end + initial begin #2; a = 1; #0; a = 0; #1; b = 1; a = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 0) + (run_until 2) + (assert_eq count 2 "the expression rose and fell at time 2") + (assert_eq hit 1) + (run_until 3) + (assert_eq count 2 "a and b changed together, so a ^ b did not change")) + +(case bit_select_edges_follow_the_selected_bit + ; Table 9-2 judges an edge on the least significant bit of the + ; expression: of `v[3]`, not of `v`. + (source "bit_select_edge.sv" #" + module Top(output bit [7:0] selected, whole); + bit [3:0] v; + initial forever begin @(posedge v[3]); selected = selected + 8'd1; end + initial forever begin @(posedge v); whole = whole + 8'd1; end + initial begin #1; v = 4'b1000; #1; v = 4'b0000; #1; v = 4'b1000; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq selected 1) + (assert_eq whole 0) + (run_until 3) + (assert_eq selected 2) + (assert_eq whole 0)) + +(case part_select_events_see_pulses_of_the_selected_bits + (source "part_select_pulse.sv" #" + module Top(output bit [7:0] count); + bit [3:0] v; + initial forever begin @(v[2:1]); count = count + 8'd1; end + initial begin #1; v[1] = 1; #0; v[1] = 0; #1; v[3] = 1; v[0] = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 2 "v[2:1] went to 1 and back") + (run_until 2) + (assert_eq count 2 "bits outside the select are no events")) + +(case variable_index_events_follow_the_index + ; The value of `q[i]` changes when the index does, too. + (source "variable_index_event.sv" #" + module Top(output bit [7:0] count); + bit [3:0] q; + bit [1:0] i; + initial forever begin @(q[i]); count = count + 8'd1; end + initial begin #1; q[0] = 1; #1; i = 1; #1; q[0] = 0; #1; q[1] = 1; #1; i = 2; end + endmodule + "#) + (top Top) + (run_until 1) (assert_eq count 1) + (run_until 2) (assert_eq count 2 "q[1] differs from q[0]") + (run_until 3) (assert_eq count 2 "q[0] is not selected") + (run_until 4) (assert_eq count 3) + (run_until 5) (assert_eq count 4)) + +(case pure_function_events_change_with_the_result + (source "function_event.sv" #" + module Top(output bit [7:0] count); + bit [3:0] v; + function automatic bit [1:0] middle(bit [3:0] x); + return x[2:1]; + endfunction + initial begin #1; forever begin @(middle(v)); count = count + 8'd1; end end + initial begin #2; v = 4'b0010; #1; v = 4'b1011; #1; v = 4'b1101; end + endmodule + "#) + (top Top) + (run_until 2) (assert_eq count 1) + (run_until 3) (assert_eq count 1 "the result stayed 1") + (run_until 4) (assert_eq count 2)) + +(case event_expressions_read_automatic_task_locals + ; Each call waits on `q[i]` with its own `i`, sampled when the event + ; control begins: the second call does not wake because `q[1]` differs + ; from the `q[0]` the first one waited on. + (source "task_local_event.sv" #" + module Top(output int first, second); + bit [3:0] q; + task automatic await(input int i, output int at); + @(q[i]); + at = $time; + endtask + initial begin #2; await(0, first); await(1, second); end + initial begin #3; q[0] = 1; #3; q[1] = 1; end + endmodule + "#) + (top Top) + (run_until 3) (assert_eq first 3) (assert_eq second 0) + (run_until 5) (assert_eq second 0) + (run_until 6) (assert_eq second 6)) + +(case event_controls_sample_the_expression_when_they_begin + ; IEEE 1800-2023 9.4.2: the process's own write before the event + ; control is no event of it. + (source "event_sample.sv" #" + module Top(output bit hit); + bit a, b; + initial begin #1; a = 1; @(a ^ b); hit = 1; end + initial begin #2; b = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq hit 0) + (run_until 2) + (assert_eq hit 1)) + +(case implicit_event_controls_in_processes_wait_on_their_reads + ; IEEE 1800-2023 9.4.2.2: `@*` waits on the variables the statement it + ; controls reads, not on those it writes. + (source "implicit_event.sv" #" + module Top(output bit [7:0] y, z, count); + bit [7:0] a, b; + initial forever @* begin y = a + b; count = count + 8'd1; end + always @* begin #1; z = a; end + initial begin #2; a = 3; #2; b = 4; end + endmodule + "#) + (top Top) + (run_until 1) (assert_eq count 0) (assert_eq y 0) + (run_until 2) (assert_eq count 1) (assert_eq y 3) + (run_until 3) (assert_eq z 3) + (run_until 4) (assert_eq count 2) (assert_eq y 7) (assert_eq z 3)) diff --git a/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json b/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json new file mode 100644 index 00000000000..4032154b841 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json @@ -0,0 +1,34 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "timing::event_controls_sample_the_expression_when_they_begin at 1179:3: assert_eq hit: expected 0x0, got 0x1", + "expectation": "Simulation", + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "mismatch": 1, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "note": "Focused failure before the exclusion. The design writes a = 1 and then waits on @(a ^ b); Icarus 13.0 wakes the process at that time, Verilator 5.052 does not. IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression, and the change of a happened before the event control executed. A standalone probe also wakes in Icarus, and a new event expression reports an event at time 0 there." +} diff --git a/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json b/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json new file mode 100644 index 00000000000..e9d9e676a8f --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json @@ -0,0 +1,34 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /source_0.sv:4:23: Unsupported: Event control with implicit sensitivity (@*) in this context; use an explicit sensitivity list instead\n 4 | initial forever @* begin y = a + b; count = count + 8'd1; end\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Warning-ZERODLY: /testbench.sv:73:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 73 | if (t1 > $time) #(t1 - $time);\n | ^\n ... For warning description see https://verilator.org/warn/ZERODLY?v=5.052\n ... Use \"/* verilator lint_off ZERODLY */\" and lint_on around source to disable this message.\n%Warning-ZERODLY: /testbench.sv:114:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 114 | if (t2 > $time) #(t2 - $time);\n | ^\n%Warning-ZERODLY: /testbench.sv:155:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 155 | if (t3 > $time) #(t3 - $time);\n | ^\n%Warning-ZERODLY: /testbench.sv:185:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 185 | if (t4 > $time) #(t4 - $time);\n | ^\n%Warning-INFINITELOOP: /source_0.sv:4:15: Infinite loop (condition always true)\n 4 | initial forever @* begin y = a + b; count = count + 8'd1; end\n | ^~~~~~~\n ... For warning description see https://verilator.org/warn/INFINITELOOP?v=5.052\n ... Use \"/* verilator lint_off INFINITELOOP */\" and lint_on around source to disable this message.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "compile_error": 1, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "note": "Focused failure before the exclusion. Verilator 5.052 rejects @* in an initial forever. A standalone always @* whose body has a delay compiles but does not terminate in Verilator, so the case cannot avoid the construct. Icarus 13.0 passes the case." +} diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index c6d6d4d721b..44ee9200184 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::bit_select_edges_follow_the_selected_bit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -44,6 +55,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -242,6 +264,62 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_wake_on_rising_and_falling_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_expression_event_sample_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_expression_event_sample", + "observed_version": "Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "upstream": [] + }, + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_expressions_read_automatic_task_locals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::expression_events_see_pulses_within_a_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -319,6 +397,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -352,6 +441,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::long_process_loops_finish_within_one_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::min_typ_max_delays_wait_the_typical_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -385,6 +496,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_assignments_in_processes_update_in_the_nba_region", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -407,6 +529,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::part_select_events_see_pulses_of_the_selected_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -429,6 +562,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::pure_function_events_change_with_the_result", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -539,6 +683,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_actuals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_subroutines", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_functions_report_the_time_in_the_caller_unit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_literal_delays_accept_all_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Icarus 13.0 shares an unpacked local array across overlapping calls of an automatic task, including with an explicit automatic declaration. IEEE 1800-2023 13.3.1 and 13.3.2 require separate storage for each activation. The first call returns 31 instead of 11 after the second call overwrites its array; scalar task locals remain independent.", @@ -562,6 +750,61 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_scalar_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_four_state_storage_survives_suspension", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_in_edge_always_rearms_after_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_nested_copyback_wait_and_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_static_formals_remain_shared", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -595,6 +838,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_index_events_follow_the_index", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 35bbd850afa..245fa29003a 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1492,6 +1492,40 @@ ] } }, + { + "id": "sv_icarus_expression_event_sample", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "upstream": [], + "evidence": [ + "verification/repros/sv_expression_event_sample_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::event_controls_sample_the_expression_when_they_begin" + ] + } + }, + { + "id": "sv_verilator_implicit_event_in_process", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_implicit_event_in_process_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::implicit_event_controls_in_processes_wait_on_their_reads" + ] + } + }, { "id": "sv_verilator_dist_uniform_seed_width", "category": "simulator_compile_limitation", diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index cb48ee4a4a3..0b0a47f41df 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::bit_select_edges_follow_the_selected_bit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -44,6 +55,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -242,6 +264,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_wake_on_rising_and_falling_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_expressions_read_automatic_task_locals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::expression_events_see_pulses_within_a_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -319,6 +385,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_implicit_event_in_process_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_implicit_event_in_process", + "observed_version": "Verilator 5.052", + "phase": "compile", + "reason": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "upstream": [] + }, + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -352,6 +441,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::long_process_loops_finish_within_one_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::min_typ_max_delays_wait_the_typical_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -385,6 +496,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_assignments_in_processes_update_in_the_nba_region", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -407,6 +529,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::part_select_events_see_pulses_of_the_selected_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -429,6 +562,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::pure_function_events_change_with_the_result", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -539,6 +683,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_actuals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_subroutines", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Verilator 5.052 evaluates an always_comb that reads $time again when the clocking event of the suite testbench fires, although no variable it reads has changed: at 3 ns y is 3 instead of 0. IEEE 1800-2023 9.2.2.2.1 makes always_comb sensitive to the variables it reads, and $time (20.3.1) is none. A standalone probe prints y=0 in Icarus 13.0 and Verilator without a clocking block, and y=3 in Verilator with one.", @@ -562,6 +728,83 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_literal_delays_accept_all_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_scalar_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::timed_task_four_state_storage_survives_suspension", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_in_edge_always_rearms_after_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_nested_copyback_wait_and_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_static_formals_remain_shared", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "four-state expectations", @@ -595,6 +838,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_index_events_follow_the_index", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 957479e3b3f..67948f68f2d 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -85,37 +85,23 @@ timed_cases! { fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; fn inactive_time_directives_do_not_change_scheduler_units = "timing::inactive_time_directives_do_not_change_scheduler_units"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_concatenation_publishes_one_event_update = "timing::blocking_concatenation_publishes_one_event_update"; fn finite_active_feedback_preserves_convergence = "timing::finite_active_feedback_preserves_convergence"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn pure_function_rhs_preserves_distinct_write_times = "timing::pure_function_rhs_preserves_distinct_write_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn conditional_writes_preserve_distinct_activation_times = "timing::conditional_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn case_writes_preserve_distinct_activation_times = "timing::case_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_repeat_writes_preserve_distinct_activation_times = "timing::constant_repeat_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn separate_comb_assignments_preserve_selected_dependencies = "timing::separate_comb_assignments_preserve_selected_dependencies"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_for_writes_preserve_distinct_activation_times = "timing::constant_for_writes_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_tasks_preserve_distinct_activation_times = "timing::untimed_tasks_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_task_copyback_preserves_distinct_activation_times = "timing::untimed_task_copyback_preserves_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn statically_satisfied_waits_preserve_distinct_activation_times = "timing::statically_satisfied_waits_preserve_distinct_activation_times"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn nba_woken_waiters_sample_before_continuations = "timing::nba_woken_waiters_sample_before_continuations"; fn negative_repeat_counts_do_not_run_the_body = "timing::negative_repeat_counts_do_not_run_the_body"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_ff_woken_waiters_sample_before_continuations = "timing::blocking_ff_woken_waiters_sample_before_continuations"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn direct_blocking_ff_woken_waiters_sample_before_continuations = "timing::direct_blocking_ff_woken_waiters_sample_before_continuations"; fn constant_variable_initializers_do_not_invent_clock_edges = "timing::constant_variable_initializers_do_not_invent_clock_edges"; fn repeated_active_edges_share_one_nba_batch = "timing::repeated_active_edges_share_one_nba_batch"; - #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn false_wait_preserves_separate_hierarchical_write_times = "timing::false_wait_preserves_separate_hierarchical_write_times"; fn always_timed_task_without_inline_timing_executes = "timing::always_timed_task_without_inline_timing_executes"; fn constant_comb_if_discards_unreachable_pulse_branch = "timing::constant_comb_if_discards_unreachable_pulse_branch"; @@ -133,6 +119,14 @@ timed_cases! { fn long_process_loops_finish_within_one_time_slot = "timing::long_process_loops_finish_within_one_time_slot"; fn initial_blocks_run_at_time_zero = "timing::initial_blocks_run_at_time_zero"; fn host_edges_after_time_zero_clock_flip_flops = "timing::host_edges_after_time_zero_clock_flip_flops"; + fn expression_events_see_pulses_within_a_time_slot = "timing::expression_events_see_pulses_within_a_time_slot"; + fn bit_select_edges_follow_the_selected_bit = "timing::bit_select_edges_follow_the_selected_bit"; + fn part_select_events_see_pulses_of_the_selected_bits = "timing::part_select_events_see_pulses_of_the_selected_bits"; + fn variable_index_events_follow_the_index = "timing::variable_index_events_follow_the_index"; + fn pure_function_events_change_with_the_result = "timing::pure_function_events_change_with_the_result"; + fn event_expressions_read_automatic_task_locals = "timing::event_expressions_read_automatic_task_locals"; + fn event_controls_sample_the_expression_when_they_begin = "timing::event_controls_sample_the_expression_when_they_begin"; + fn implicit_event_controls_in_processes_wait_on_their_reads = "timing::implicit_event_controls_in_processes_wait_on_their_reads"; } #[test] @@ -223,3 +217,115 @@ fn time_literal_delays_round_at_scope_precision() { sim.run_until(2800).unwrap(); assert_eq!(sim.get(coarse), 1u8.into()); } + +/// The variables of an event expression, `$event[k]` and its copies of +/// process-local operands, are state like the process slots: a state file +/// keeps them, while the signal listing and the waveform leave them out. +#[test] +fn event_expression_variables_are_hidden_state() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("events.vcd"); + let design = |dump: &str| { + format!( + r#" + module Top(output bit [7:0] count); + bit a; + task automatic await(input bit i); @(a ^ i); endtask + {dump} + initial forever begin await(1); count = count + 8'd1; end + initial begin #1; a = 1; end + endmodule + "# + ) + }; + let traced = design(&format!( + r#"initial begin $dumpfile("{}"); $dumpvars(0, Top); end"#, + path.display() + )); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(traced.as_str(), std::path::Path::new("events.sv"))], + "Top", + ) + .build() + .unwrap(); + simulation.run_until(2000).unwrap(); + assert_eq!(simulation.get(simulation.signal("count")), 1u8.into()); + simulation.flush_vcd().unwrap(); + let waveform = std::fs::read_to_string(&path).unwrap(); + assert!(waveform.contains(" count $end"), "{waveform}"); + assert!(!waveform.contains("$event"), "{waveform}"); + + let plain = design(""); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(plain.as_str(), std::path::Path::new("events.sv"))], + "Top", + ) + .build() + .unwrap(); + simulation.run_until(2000).unwrap(); + assert!( + simulation + .named_signals() + .iter() + .all(|signal| !signal.name.starts_with('$')), + "{:?}", + simulation + .named_signals() + .iter() + .map(|signal| &signal.name) + .collect::>() + ); + let state = simulation.save_state().unwrap(); + // A store of the process does not make the variable a counted signal. + assert!( + !state + .objects + .iter() + .any(|object| object.path.starts_with("$counter[$event")), + "{:?}", + state.objects + ); + for name in ["$event[0]", "$event[0].arg[0]", "$initial[0].status"] { + assert!( + state + .objects + .iter() + .any(|object| object.path == name && object.role == celox::StateRole::State), + "{name}: {:?}", + state.objects + ); + } +} + +#[test] +fn event_expressions_with_effects_are_rejected() { + for (event, construct) in [ + ( + "count_up(a)", + "impure call `count_up` in an event expression", + ), + ("$time", "impure call `$time` in an event expression"), + ("a ^ x", "event expression reading a static task argument"), + ] { + let source = format!( + r#" + module Top; + bit a; + int calls; + function automatic bit count_up(input bit v); calls++; return v; endfunction + task t(input bit x); @({event}); endtask + initial t(0); + endmodule + "# + ); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("effects.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("`@({event})` must be rejected")) + .to_string(); + assert!(error.contains(construct), "{event}: {error}"); + } +}