From bee666603e2db4e5a335968a121455705ebcc7f1 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 22 Oct 2026 16:19:12 +0900 Subject: [PATCH] feat(sv)!: retain static function locals and results between calls Static function locals, implicit results and output-only arguments now retain observable state between calls, including real values and integral arrays. Call sites share the storage, module instances have separate storage, and constant function evaluation uses fresh initialized values without changing runtime state. One-time initializers run through the existing initialization processes; stateful initializer calls require Simulation or a native testbench. Promote retained storage to ordinary module/package state and lower stateful calls through the imperative path, preserving the existing optimizer and checkpoint behavior. Keep the scratch-local proofs and existing restrictions on task locals, nonconstant static initializers and package writers. Class methods retain automatic lifetime; explicit and implicit constructors preserve their object handles and constructor return behavior. Add shared regressions for call ordering, early returns, real values, arrays, four-state and 981-bit storage, package and instance scopes, constant calls, and timed processes. Retain focused Verilator/Icarus disagreements and compile limitations with standalone sources and narrow tool/case exclusions. Validation after rebasing onto master (ce31782ed): - Full SystemVerilog backend suite: 4,001 passed, 20 existing ignored. - Analyzer/frontend unit tests: 795 passed, 3 existing ignored. - Lifetime/package consumers: 71 passed. - Shared suite with Verilator/Icarus features: 78 passed. - Focused Verilator: 10 passed, 2 reviewed exclusions, 1 four-state unsupported. - Focused Icarus: 9 passed, 4 reviewed exclusions. - cargo fmt and affected-crate/consumer Clippy checks passed. - Full pinned sv-tests conformance: all 2,054 case/mode verdicts match the reviewed expectations (525 passes in 2state and 527 in 4state). An independently reproduced existing Wasm bug affects unaligned multiword unpacked-array elements; the shared retained-array regression uses 64-bit elements, and the separate 981-bit packed-storage regression passes all backends. BREAKING CHANGE: SubroutineBase gains a persistent_locals field; consumers constructing this public analyzer IR structure must initialize the field. Change-Id: Ib759645220e169de2d702db4a81aa7bb4980944d --- conformance/sv-tests/README.md | 7 + conformance/sv-tests/expected.tsv | 4 +- crates/celox-frontend-sv/src/lowering.rs | 21 +- crates/celox-frontend-sv/src/lowering/comb.rs | 5 + crates/celox-frontend-sv/src/lowering/ff.rs | 11 +- .../src/lowering/procedural.rs | 3 + crates/celox-sv-analyzer/src/ast.rs | 8 +- .../src/ast/const_functions.rs | 3 + crates/celox-sv-analyzer/src/ast/functions.rs | 2 + .../src/ast/functions/symbolic.rs | 3 + crates/celox-sv-analyzer/src/ast/lifetimes.rs | 39 +++- .../src/ast/lifetimes/bit_result.rs | 43 ++-- crates/celox-sv-analyzer/src/ast/packages.rs | 5 +- .../celox-sv-analyzer/src/ast/procedural.rs | 99 +++++++-- .../src/ast/procedural/control.rs | 2 + crates/celox-sv-analyzer/src/ast/scope.rs | 6 + crates/celox-sv-analyzer/src/procedural.rs | 3 + crates/celox-test-suite/LIMITATIONS.md | 9 + .../src/sv/cases/procedural.vtest | 197 ++++++++++++++++++ .../src/sv/cases/timing.vtest | 48 +++++ .../repros/sv_static_function_lifetimes.json | 91 ++++++++ .../repros/sv_static_function_lifetimes.sv | 22 ++ .../verification/sv/icarus/procedural.json | 96 +++++++++ .../verification/sv/limitations.json | 76 +++++++ .../verification/sv/verilator/procedural.json | 48 +++++ .../frontends/systemverilog/procedural.rs | 65 ++++++ .../systemverilog/review_regressions.rs | 13 -- .../tests/frontends/systemverilog/timing.rs | 12 ++ crates/celox/tests/sv_lifetimes.rs | 37 +--- docs/guide/systemverilog-reference.md | 35 ++-- docs/ja/guide/systemverilog-reference.md | 23 +- 31 files changed, 929 insertions(+), 107 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.json create mode 100644 crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.sv diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index abc9b898890..96c8486ebd1 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -103,6 +103,13 @@ cases retain their verdicts. The pinned `real_bit_select_idx` input is rejected earlier for its undriven net, so a separate analyzer regression uses a driven input to check that real-valued indices themselves are rejected. +Static function storage support updates the two rows for +`13.4.2--function-static` from fail to pass in both state modes. The official +runner selects elaboration for this probe: its local accumulator now has +persistent storage rather than being rejected. Runtime retention is exercised +by the shared static-function simulation cases. The full pinned run matches +the reviewed expectations in both state modes. + Blocking latch support changes ten expectation rows: `12.4--if`, `12.4.1--if_else_if`, and the three `12.4.2` priority/unique conditional probes now pass elaboration in both state modes. These sources use ordinary diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 612e0df260b..0631e5f6113 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -271,8 +271,8 @@ chapter-13/13.4.2--function-automatic.sv 2state pass chapter-13/13.4.2--function-automatic.sv 4state pass chapter-13/13.4.2--function-recursive.sv 2state fail chapter-13/13.4.2--function-recursive.sv 4state fail -chapter-13/13.4.2--function-static.sv 2state fail -chapter-13/13.4.2--function-static.sv 4state fail +chapter-13/13.4.2--function-static.sv 2state pass +chapter-13/13.4.2--function-static.sv 4state pass chapter-13/13.4.3--const-function.sv 2state pass chapter-13/13.4.3--const-function.sv 4state pass chapter-13/13.4.4--fork-invalid.sv 2state pass diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b27b2f92fac..751a066eef8 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1087,12 +1087,21 @@ fn validate_variable_driver_ranges( .iter() .any(|right| left.0 != right.0 && net_driver_ranges_overlap(left.1, right.1)) }); - let overlapping_continuous = driver_ranges_overlap(&continuous_driver_ranges( - module, - signal_name, - constants, - parameter_types, - )); + let continuous = continuous_driver_ranges(module, signal_name, constants, parameter_types); + let function_storage = module.subroutines().iter().any(|subroutine| { + subroutine + .persistent_locals + .iter() + .any(|name| name == signal_name) + }); + // Multiple statements in a function are one procedural driver for + // its static storage, even when the caller is a continuous assignment. + let overlapping_continuous = continuous.iter().enumerate().any(|(index, left)| { + continuous[index + 1..].iter().any(|right| { + (!function_storage || left.0 != right.0) + && net_driver_ranges_overlap(left.1, right.1) + }) + }); if overlapping_continuous || (has_overlap && !shared_memories.contains(signal_name)) { return Err(sv::AnalyzerError::Unsupported(format!( "multiple variable drivers for `{signal_name}`" diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 071c7ce59c0..afc4d89a998 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3167,6 +3167,11 @@ impl<'p, 'a> Comb<'p, 'a> { .subroutine(name) .cloned() .ok_or_else(|| unsupported(format!("call of `{name}`")))?; + // Symbolic execution cannot represent state shared by invocations. + // Fall back to Ff, including for runtime declaration initializers. + if !subroutine.persistent_locals.is_empty() { + return Err(unsupported("stateful function call")); + } if self.active_calls.iter().any(|active| active == name) { return Err(unsupported(format!("recursive call of `{name}`"))); } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index e0bdd559d5d..3a992de49cd 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -3529,9 +3529,10 @@ impl<'p, 'a> Ff<'p, 'a> { .map_err(slt_error)?; } inputs.push((id, self.lower_slt(&arena, node)?)); - } else if self.kernel.is_none() - || !subroutine.is_task - || subroutine.automatic_locals.contains(¶m.name) + } else if !subroutine.persistent_locals.contains(¶m.name) + && (self.kernel.is_none() + || !subroutine.is_task + || subroutine.automatic_locals.contains(¶m.name)) { let value = self.default_reg(id); inputs.push((id, value)); @@ -3547,7 +3548,9 @@ impl<'p, 'a> Ff<'p, 'a> { .m .id(return_var) .ok_or_else(|| unsupported(format!("result of `{name}`")))?; - self.init_default(id); + if !subroutine.persistent_locals.contains(return_var) { + self.init_default(id); + } } let return_block = self.b.new_block(); self.functions.push(FunctionBlocks { diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 8cc6ba97f48..cc1bc52ceb4 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -257,6 +257,9 @@ impl<'a> ProcModule<'a> { sv::ir::Callee::Subroutine(name) => name, }; if let Some(subroutine) = self.subroutine(&name) { + if !subroutine.persistent_locals.is_empty() { + return true; + } default_calls(subroutine, &args, &mut calls); if visited.insert(name) { for stmt in &subroutine.body { diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index ecfc92b23b8..0f5545a9def 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1105,6 +1105,8 @@ impl Module { subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(syntax_tree), statics: Vec::new(), + static_initializers: Vec::new(), + constant_evaluation: false, }; let (mut subroutines, mut comb_processes, mut ff_processes, mut initial_processes) = if imported.declarations_only { @@ -1157,7 +1159,7 @@ impl Module { // Static locals of the processes that keep their value are variables // of the module, initialized once with the declaration initializers. let statics: HashMap = body_state.statics.drain(..).collect(); - let (kept, static_initializers) = lifetimes::keep_static_locals( + let (mut kept, mut static_initializers) = lifetimes::keep_static_locals( &syntax_tree.state, &statics, &subroutine_directions, @@ -1171,6 +1173,10 @@ impl Module { .map(|process| &mut process.body), ), )?; + for subroutine in &subroutines { + kept.extend(subroutine.persistent_locals.iter().cloned()); + } + static_initializers.append(&mut body_state.static_initializers); locals.retain(|local| !kept.contains(&local.name)); for name in kept { signals.push(Signal::new(name.clone(), statics[&name].clone())); diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 93bb8241772..18fe205b6fa 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -309,6 +309,7 @@ impl ConstantFunctions { sensitivity_body: Vec::new(), is_task: false, automatic_locals: Vec::new(), + persistent_locals: Vec::new(), return_type: function.return_var.as_ref().map(|(_, ty)| ty.clone()), return_var: function.return_var.as_ref().map(|(name, _)| name.clone()), params: function @@ -481,6 +482,8 @@ fn collect_module_constant_functions( subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(tree), statics: Vec::new(), + static_initializers: Vec::new(), + constant_evaluation: true, }; let mut rejected = HashMap::default(); let subroutines = match procedural::subroutines_with_symbolic_parameters( diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index fcabc298ad0..2112b88a286 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -85,6 +85,8 @@ pub(super) fn native_functions( subroutine_directions: &directions, automatic, statics: Vec::new(), + static_initializers: Vec::new(), + constant_evaluation: false, }; let mut dims = item.dimensions(dimensions); dims.subroutine_param_names = names.clone(); diff --git a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs index 7cf039e75bb..148f6407015 100644 --- a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs +++ b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs @@ -311,6 +311,9 @@ pub(super) fn body( subroutine: &Subroutine, locals: &[LocalVariable], ) -> Option<(Expr, Vec<(String, Expr)>)> { + if !subroutine.persistent_locals.is_empty() { + return None; + } let mut types = HashMap::default(); for local in locals { if !local.r#type.unpacked_ranges().is_empty() { diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 1ed46598ace..dae02b92839 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -8,7 +8,8 @@ //! entry is never read gives the same results that way. Any other static //! local of a procedural block keeps its value instead: its declaration no //! longer initializes it, and its initializer runs once at time zero. Static -//! locals of subroutines that keep their value are not supported. +//! locals of functions use the same storage; task locals that retain state +//! remain unsupported. use super::*; mod bit_result; @@ -210,7 +211,7 @@ pub(super) fn check_subroutine_statics( result } -/// Reject a static function whose result keeps its value between calls: in +/// Detect a static function whose result keeps its value between calls: in /// a static function the variable named after it is static too, so a call /// that does not assign it returns the result of an earlier call. pub(super) fn check_static_result( @@ -228,6 +229,7 @@ pub(super) fn check_static_result( name: result, directions, two_state_widths: &widths, + read_on_return: false, }; // `return value;` assigns the result as it leaves. match flow.block(&subroutine.body, false) { @@ -241,6 +243,22 @@ pub(super) fn check_static_result( } } +/// An output-only static formal also preserves its value before copy-out. +pub(super) fn output_retains_value( + subroutine: &Subroutine, + name: &str, + directions: &Directions, +) -> bool { + let widths = argument_widths(subroutine); + let flow = Flow { + name, + directions, + two_state_widths: &widths, + read_on_return: true, + }; + !matches!(flow.block(&subroutine.body, false), Ok(exits) if exits.next != Some(false)) +} + /// The widths of the two-state arguments of `subroutine`. fn argument_widths(subroutine: &Subroutine) -> HashMap { subroutine @@ -279,7 +297,20 @@ fn entry( name, directions, two_state_widths: widths, + read_on_return: false, }; + // Even a function that is legal in a constant expression can retain + // different state when called at runtime (13.4.3). Its initializer must + // execute once, including when the initialized local is read-only. + let mut calls_function = false; + if let Some(init) = init { + visit_calls(init, &mut |callee, _| { + calls_function |= callee.subroutine().is_some(); + }); + } + if calls_function { + return Ok(Entry::Observed); + } let observed = flow.block(after, false).is_err(); Ok(match init { // Initialized once or on every entry, a local that is never written @@ -296,6 +327,7 @@ struct Observed; /// Follows whether one local is written on every path, from its declaration /// on. struct Flow<'n> { + read_on_return: bool, name: &'n str, directions: &'n Directions, /// The widths of the two-state variables a `case` may select on, to @@ -527,6 +559,9 @@ impl Flow<'_> { ..Exits::default() }), Stmt::Return(value) => { + if self.read_on_return && !written { + return Err(Observed); + } if let Some(value) = value { self.read(value, written)?; } diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs index b0458e14acd..f30d26f43c9 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs @@ -134,7 +134,7 @@ impl Proof<'_> { } /// `true` means no entry bit can subsequently be observed. Unknown control - /// flow or calls give no proof; the ordinary lifetime check still rejects. + /// flow or calls give no proof; the ordinary lifetime check requires persistent storage. fn block(&mut self, statements: &[Stmt]) -> Option { for statement in statements { self.remaining = self.remaining.checked_sub(1)?; @@ -276,7 +276,7 @@ fn pure(expression: &Expr) -> bool { #[cfg(test)] mod tests { #[test] - fn incomplete_or_entry_dependent_scratch_arrays_stay_rejected() { + fn incomplete_or_entry_dependent_scratch_arrays_retain_storage() { for body in [ "for(integer i=0;i<1;i=i+1) words[i]=a;", "for(integer i=0;i<2;i=i+1) words[0]=a;", @@ -290,15 +290,12 @@ mod tests { logic[7:0] words[1:0]; logic[7:0] other; {body} \ f=words[0]+words[1]; endfunction assign y=f(a); endmodule" ); - let error = crate::analyze_source(&source, std::path::Path::new("partial-scratch.sv")) - .unwrap_err() - .to_string(); - assert!(error.contains("static variable `words`"), "{body}: {error}"); + assert_retained(&source, "words"); } } #[test] - fn incomplete_or_entry_dependent_results_stay_rejected() { + fn incomplete_or_entry_dependent_results_retain_storage() { for body in [ "for(integer i=0;i<3;i=i+1) f[i]=a[i];", "for(integer i=0;i<4;i=i+1) f[0]=a[i];", @@ -313,13 +310,7 @@ mod tests { function [3:0] f(input logic[3:0] a); {body} endfunction \ assign y=f(a); endmodule" ); - let error = crate::analyze_source(&source, std::path::Path::new("partial-result.sv")) - .unwrap_err() - .to_string(); - assert!( - error.contains("whose result keeps its value"), - "{body}: {error}" - ); + assert_retained(&source, "f"); } } @@ -336,9 +327,25 @@ mod tests { assign y=f(a); endmodule "#; - let error = crate::analyze_source(source, std::path::Path::new("index-call.sv")) - .unwrap_err() - .to_string(); - assert!(error.contains("whose result keeps its value"), "{error}"); + assert_retained(source, "f"); + } + + fn assert_retained(source: &str, variable: &str) { + let ir = + crate::analyze_source(source, std::path::Path::new("retained-storage.sv")).unwrap(); + let module = &ir.modules()[0]; + let function = module + .subroutines() + .iter() + .find(|function| function.name == "f") + .unwrap(); + let prefix = format!("{variable}@"); + let name = function + .persistent_locals + .iter() + .find(|name| name.starts_with(&prefix)) + .unwrap_or_else(|| panic!("missing persistent {variable}: {source}")); + assert!(module.signals().iter().any(|signal| signal.name() == name)); + assert!(!module.locals().iter().any(|local| &local.name == name)); } } diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 734d9669bc0..5f43c0845e1 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -482,7 +482,7 @@ fn analyze_package_scope( // The names the package declares, from its syntax: an escaped name may // contain `::` itself. let own = imports::scope_names(tree)?; - let variables = package_variables(name, tree)?; + let mut variables = package_variables(name, tree)?; let mut module = Module::from_scope_with_parameter_overrides( tree, "", @@ -493,6 +493,9 @@ fn analyze_package_scope( }, Arc::new(imported), )?; + for subroutine in &module.subroutines { + variables.extend(subroutine.persistent_locals.iter().cloned()); + } let mut symbols = module .symbols .take() diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index d4514fe1a50..d58ec3ad6f7 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -46,6 +46,10 @@ pub(super) struct BodyState<'a> { /// The locals declared with a static lifetime: their unique names and /// types. pub statics: Vec<(String, Type)>, + /// Function static declarations initialized once at time zero. + pub static_initializers: Vec, + /// Constant calls get a fresh frame, even for static declarations (13.4.3). + pub constant_evaluation: bool, } /// Converts the statements of one procedural body. @@ -1774,6 +1778,7 @@ pub(super) fn lower_subroutine( }) .collect::, _>>()?; let mut lowered_params = Vec::new(); + let mut formal_types = HashMap::default(); // A method receives the handle of its object first, and a constructor // returns the handle of the object it creates. let this = handle.clone().filter(|_| !constructor).map(|handle| { @@ -1791,6 +1796,7 @@ pub(super) fn lower_subroutine( .collect::>(); for ((source, direction, r#type, _), default) in this.into_iter().chain(params).zip(defaults) { let name = builder.declare(&source, r#type.clone()); + formal_types.insert(name.clone(), scoped_type(r#type.clone(), declaration_env)); lowered_params.push(SubroutineParam { name, source_name: source, @@ -1811,6 +1817,9 @@ pub(super) fn lower_subroutine( r#type.clone(), ) }); + if let (Some(name), Some(ty)) = (&return_var, &return_type) { + formal_types.insert(name.clone(), scoped_type(ty.clone(), declaration_env)); + } let parameter_locals_end = builder.state.locals.len(); let mut body = match (class, &return_var) { (Some(class), Some(this)) if constructor => builder.constructor_prologue(class, this)?, @@ -1818,13 +1827,13 @@ pub(super) fn lower_subroutine( }; body.extend(builder.native_body(&native.items, &native.authored_statements)?); builder.pop_scope(); - let statics: HashSet = builder + let static_types: HashMap = builder .state .statics .split_off(first_static) .into_iter() - .map(|(name, _)| name) .collect(); + let statics = static_types.keys().cloned().collect::>(); // A constructor's `return;` returns the object (IEEE 1800-2023 8.7). if return_var.is_some() && !constructor { let mut expressionless = false; @@ -1853,6 +1862,7 @@ pub(super) fn lower_subroutine( }) .map(|(_, local)| local.name.clone()) .collect(), + persistent_locals: Vec::new(), return_type: return_type.map(|r#type| { crate::ir::Type::from_ast( scoped_type(r#type, declaration_env), @@ -1886,22 +1896,84 @@ pub(super) fn lower_subroutine( ); } } - lifetimes::check_subroutine_statics( - &tree.state, - &subroutine, - &builder.dims.const_env, - builder.state.locals, - &statics, - builder.state.subroutine_directions, - )?; - if !builder.automatic { - lifetimes::check_static_result( + if subroutine.is_task { + lifetimes::check_subroutine_statics( &tree.state, + &subroutine, &builder.dims.const_env, builder.state.locals, - &subroutine, + &statics, builder.state.subroutine_directions, )?; + if !builder.automatic { + lifetimes::check_static_result( + &tree.state, + &builder.dims.const_env, + builder.state.locals, + &subroutine, + builder.state.subroutine_directions, + )?; + } + } else if !builder.state.constant_evaluation { + let retain_result = !builder.automatic + && lifetimes::check_static_result( + &tree.state, + &builder.dims.const_env, + builder.state.locals, + &subroutine, + builder.state.subroutine_directions, + ) + .is_err(); + // Keep scratch arrays/bitwise result proofs on the existing temporary path. + let retained_types = static_types + .iter() + .filter(|(name, _)| { + lifetimes::check_subroutine_statics( + &tree.state, + &subroutine, + &builder.dims.const_env, + builder.state.locals, + &std::iter::once((*name).clone()).collect(), + builder.state.subroutine_directions, + ) + .is_err() + }) + .map(|(name, ty)| (name.clone(), ty.clone())) + .collect::>(); + let (mut kept, mut initializers) = lifetimes::keep_static_locals( + &tree.state, + &retained_types, + builder.state.subroutine_directions, + std::iter::once(&mut subroutine.body), + )?; + if retain_result { + kept.extend(subroutine.return_var.clone()); + } + for param in &subroutine.params { + if param.direction == ParamDirection::Output + && !subroutine.automatic_locals.contains(¶m.name) + && lifetimes::output_retains_value( + &subroutine, + ¶m.name, + builder.state.subroutine_directions, + ) + { + kept.push(param.name.clone()); + } + } + for initializer in &mut initializers { + qualify_stmt(item, initializer); + substitute_stmt_constants(&tree.state, initializer, declaration_env, literals); + } + for name in &kept { + let ty = static_types + .get(name) + .or_else(|| formal_types.get(name)) + .expect("function storage has a local type"); + builder.state.statics.push((name.clone(), ty.clone())); + } + builder.state.static_initializers.extend(initializers); + subroutine.persistent_locals = kept; } Ok(subroutine) } @@ -2032,6 +2104,7 @@ fn lower_class( .iter() .map(|local| local.name.clone()) .collect(), + persistent_locals: Vec::new(), return_type: Some(crate::ir::Type::from_ast( scoped_type(handle, declaration_env), &const_functions::Environment { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index 9f4de8c4bac..8b1c7b4b101 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -469,6 +469,8 @@ mod tests { subroutine_directions: &directions, automatic: false, statics: Vec::new(), + static_initializers: Vec::new(), + constant_evaluation: false, }; let mut builder = BodyBuilder::new( &tree, diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 2356aecfd89..62b0e4857b7 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -388,6 +388,7 @@ impl ScopeSymbols { for subroutine in &self.subroutines { names.extend(subroutine.params.iter().map(|param| param.name.clone())); names.extend(subroutine.return_var.clone()); + names.extend(subroutine.persistent_locals.iter().cloned()); } names.extend(self.constant_functions.local_names().cloned()); names @@ -998,6 +999,11 @@ impl Renamer<'_> { .into_iter() .map(|name| self.name(&name)) .collect(), + persistent_locals: subroutine + .persistent_locals + .into_iter() + .map(|name| self.name(&name)) + .collect(), params: subroutine .params .into_iter() diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index 8db2fbe4b9b..b9822da6e37 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -511,6 +511,8 @@ pub struct SubroutineBase { pub is_task: bool, /// Automatic storage that needs a private activation when a task suspends. pub automatic_locals: Vec, + /// Observable static storage shared by every call of this function. + pub persistent_locals: Vec, /// `None` for a task or a `void` function. pub return_type: Option, pub params: Vec>, @@ -543,6 +545,7 @@ impl SubroutineBase { name: self.name, is_task: self.is_task, automatic_locals: self.automatic_locals, + persistent_locals: self.persistent_locals, return_type: self.return_type.map(&mut *ft), params: self .params diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 327510f98d3..ebc1d9d5ed4 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -356,6 +356,15 @@ The focused [Verilator](verification/repros/named_array_parameters_verilator.jso [Slang](verification/repros/named_array_parameters_slang.json) observations retain the failures and independent elaborated values. +Static function lifetime cases expose resets of the implicit result in Verilator +5.052 and Icarus 13.0, and of an output-only formal in Verilator. The expected +retention follows IEEE 1800-2023 6.21, 13.4.1, 13.4.2 and 13.5. The +[adapter-free source](verification/repros/sv_static_function_lifetimes.sv) and +[focused observations](verification/repros/sv_static_function_lifetimes.json) +record these differences. Icarus also rejects explicit static locals in automatic +functions and output function arguments. Only the affected tool/case pairs are +excluded; their original assertions remain available through `--include-ignored`. + The new `$dist_uniform` seed-width case is excluded for Verilator 5.052 and Icarus 13.0. Verilator generates an invalid C++ reference binding for converted seed arguments; Icarus rejects the `shortint` seed at startup. IEEE 1800-2023 diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 3b571e71fee..a0a35cf1779 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -801,3 +801,200 @@ (top Top) (assert_eq a 255) (assert_eq b 15)) + +(case static_function_locals_share_storage_between_calls + (source "static_functions.sv" #" + module Top(input logic clk, output int first, second, paired); + function int next_value(input int step); + static int saved = 7; + saved += step; + return saved; + endfunction + always_ff @(posedge clk) begin + first <= next_value(1); + second <= next_value(2); + paired <= next_value(1) + next_value(1); + end + endmodule + "#) + (top Top) + (tick clk) + (assert_eq first 8) (assert_eq second 10) (assert_eq paired 23) + (tick clk) + (assert_eq first 13) (assert_eq second 15) (assert_eq paired 33)) + +(case static_function_result_keeps_value_between_calls + (source "static_result.sv" #" + module Top(input logic clk, input bit update, input bit [15:0] value, + output bit [15:0] result); + function static bit [15:0] saved(input bit write_value, input bit [15:0] new_value); + if (write_value) saved = new_value; + endfunction + always_ff @(posedge clk) result <= saved(update, value); + endmodule + "#) + (top Top) + (modify (set update 0) (set value 23)) + (tick clk) (assert_eq result 0) + (modify (set update 1)) + (tick clk) (assert_eq result 23) + (modify (set update 0) (set value 91)) + (tick clk) (assert_eq result 23) + (tick clk) (assert_eq result 23) + (modify (set update 1)) + (tick clk) (assert_eq result 91)) + +(case static_function_real_locals_and_results_keep_value + (source "static_real.sv" #" + module Top(input logic clk, input bit update, output logic [63:0] running, cached); + function automatic real accumulate(); + static real saved = 0.5; + automatic real increment = 1.5; + saved += increment; + return saved; + endfunction + function static real remember(input bit enable, input real value); + if (enable) remember = value; + endfunction + always_ff @(posedge clk) begin + running <= $realtobits(accumulate()); + cached <= $realtobits(remember(update, 1.25)); + end + endmodule + "#) + (top Top) + (modify (set update 0)) + (tick clk) + (assert_eq running 0x4000000000000000) (assert_eq cached 0) + (modify (set update 1)) + (tick clk) + (assert_eq running 0x400c000000000000) (assert_eq cached 0x3ff4000000000000) + (modify (set update 0)) + (tick clk) + (assert_eq running 0x4014000000000000) (assert_eq cached 0x3ff4000000000000)) + +(case static_function_output_formals_keep_value + (source "static_output.sv" #" + module Top(input logic clk, input bit update, input int value, output int result); + function void remember(input bit enable, input int new_value, output int saved); + if (!enable) return; + saved = new_value; + endfunction + always_ff @(posedge clk) remember(update, value, result); + endmodule + "#) + (top Top) + (modify (set update 1) (set value 37)) + (tick clk) (assert_eq result 37) + (modify (set update 0) (set value 91)) + (tick clk) (assert_eq result 37) + (modify (set update 1)) + (tick clk) (assert_eq result 91)) + +(case static_function_constant_calls_do_not_change_runtime_storage + (source "static_constant.sv" #" + module Top #(parameter int A=next_value(), B=next_value()) (input logic clk, output int value); + function int next_value(); + static int saved = 7; + saved++; + return saved; + endfunction + always_ff @(posedge clk) value <= next_value() + A + B; + endmodule + "#) + (top Top) + (tick clk) (assert_eq value 24) + (tick clk) (assert_eq value 25)) + +(case static_function_package_storage_is_shared_between_calls + (source "static_package.sv" #" + package counters; + function int next_value(input int amount); + static int saved = 3; + saved += amount; + return saved; + endfunction + endpackage + module Child(input logic clk, output int first, second); + always_ff @(posedge clk) begin + first <= counters::next_value(2); + second <= counters::next_value(3); + end + endmodule + module Top(input logic clk, output int first, second); + Child a(clk, first, second); + endmodule + "#) + (top Top) + (tick clk) (assert_eq first 5) (assert_eq second 8) + (tick clk) (assert_eq first 10) (assert_eq second 13)) + +(case static_function_retained_arrays_and_instance_storage + (source "static_array.sv" #" + module Child(input logic clk, input bit update, input bit index, + input bit [63:0] value, output bit [63:0] result); + function bit [63:0] remember(input bit enable, input bit slot, input bit [63:0] data); + static bit [63:0] entries [0:1]; + if (enable) entries[slot] = data; + return entries[slot]; + endfunction + always_ff @(posedge clk) result <= remember(update, index, value); + endmodule + module Top(input logic first_clk, second_clk, input bit update, index, + input bit [63:0] value, output bit [63:0] first, second); + Child a(first_clk, update, index, value, first); + Child b(second_clk, update, index, value, second); + endmodule + "#) + (top Top) + (modify (set update 1) (set index 0) (set value 0x8000000000000003)) + (tick first_clk) (assert_eq first 0x8000000000000003) + (modify (set update 0)) + (tick second_clk) (assert_eq second 0) + (tick first_clk) (assert_eq first 0x8000000000000003) + (modify (set update 1) (set index 1) (set value 0x8000000000000005)) + (tick first_clk) (assert_eq first 0x8000000000000005) + (modify (set update 0) (set index 0)) + (tick first_clk) (assert_eq first 0x8000000000000003)) + +(case static_function_four_state_result_retains_unknown_and_known_values + (source "static_four_state.sv" #" + module Top(input logic selector, output logic result, unknown_value); + function logic remember(input logic value); + case (value) + 1'b0: remember = 0; + 1'b1: remember = 1; + endcase + endfunction + assign result = remember(selector); + assign unknown_value = $isunknown(result); + endmodule + "#) + (top Top) + (four_state) + (modify (set selector 1'bx)) (assert_eq unknown_value 1) + (modify (set selector 0)) (assert_eq result 0) (assert_eq unknown_value 0) + (modify (set selector 1)) (assert_eq result 1) + (modify (set selector 1'bx)) (assert_eq result 1) (assert_eq unknown_value 0) + (modify (set selector 1'bz)) (assert_eq result 1)) + +(case static_function_wide_packed_storage_keeps_all_bits + (source "static_wide.sv" #" + module Top(input logic clk, input bit update, input bit [980:0] value, + output bit [980:0] result); + function bit [980:0] remember(input bit enable, input bit [980:0] data); + static bit [980:0] saved; + if (enable) saved = data; + return saved; + endfunction + always_ff @(posedge clk) result <= remember(update, value); + endmodule + "#) + (top Top) + (let wide (| (<< 1 980) 0x0123456789abcdef)) + (modify (set update 1) (set value wide)) + (tick clk) (assert_eq result wide) + (modify (set update 0) (set value 0)) + (tick clk) (assert_eq result wide) + (modify (set update 1)) + (tick clk) (assert_eq result 0)) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index d3efcdcd376..6df07ab016a 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1704,3 +1704,51 @@ 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 3)) + +(case static_function_storage_is_shared_between_processes + (source "static_processes.sv" #" + module Top(output int first, second, third); + function int next_value(); + static int saved = 11; + saved++; + return saved; + endfunction + initial begin + #1 first = next_value(); + #2 third = next_value(); + end + initial begin + #2 second = next_value(); + #2 $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (assert_eq first 12) (assert_eq second 13) (assert_eq third 14)) + +(case static_function_readonly_initializer_calls_execute_once + (source "static_initializer.sv" #" + module Top(output int cached, next, cached_again, next_again); + function int count(); + static bit [31:0] value; + value++; + return value; + endfunction + function int remember(); + static int value = count(); + return value; + endfunction + initial begin + #1 cached = remember(); + next = count(); + #1 cached_again = remember(); + next_again = count(); + #1 $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (assert_eq cached 1) (assert_eq next 2) + (assert_eq cached_again 1) (assert_eq next_again 3)) diff --git a/crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.json b/crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.json new file mode 100644 index 00000000000..00798f7e0c6 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.json @@ -0,0 +1,91 @@ +{ + "schema_version": 3, + "suite": "sv", + "note": "Focused unexcluded observations. IEEE 1800-2023 6.21 and 13.4.2 give function items static lifetime; 13.4.1 declares the implicit result variable, and 13.5 copies output arguments only on return. The expected retained results follow from these rules. Constant calls are separately initialized under 13.4.3. Verilator is two-state, so its logic output is 0 rather than X.", + "observations": [ + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "cases": [ + { + "category": "ControlFlow", + "detail": "procedural::static_function_output_formals_keep_value at 890:14: assert_eq result: expected 0x25, got 0x0", + "expectation": "Simulation", + "name": "procedural::static_function_output_formals_keep_value", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "procedural::static_function_result_keeps_value_between_calls at 842:14: assert_eq result: expected 0x17, got 0x0", + "expectation": "Simulation", + "name": "procedural::static_function_result_keeps_value_between_calls", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] + }, + { + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "cases": [ + { + "category": "ControlFlow", + "detail": "procedural::static_function_four_state_result_retains_unknown_and_known_values at 978:32: assert_eq result: expected 0x1, got 0xX", + "expectation": "Simulation", + "name": "procedural::static_function_four_state_result_retains_unknown_and_known_values", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:3: error: Function celox_suite_tb.dut.remember port saved is not an input port.\n/source_0.sv:3: : Function arguments must be input ports.\n/source_0.sv:3: warning: user task (remember) must be automatic to be synthesized in an always_ff process.\n1 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "procedural::static_function_output_formals_keep_value", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:4: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "procedural::static_function_real_locals_and_results_keep_value", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "procedural::static_function_result_keeps_value_between_calls at 842:14: assert_eq result: expected 0x17, got 0x0", + "expectation": "Simulation", + "name": "procedural::static_function_result_keeps_value_between_calls", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] + } + ], + "standalone": { + "source": "verification/repros/sv_static_function_lifetimes.sv", + "verilator_stdout": "bit 23\nbit 0\nlogic 23\nlogic 0\noutput 37\noutput 0\n- work/static-functions/static-lifetime-probe.sv:20: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 0s; walltime 0.000 s; speed 0.000 s/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n", + "icarus_return_only_source": "module Top;\n function static bit [15:0] saved(input bit enable, input bit [15:0] value);\n if (enable) saved = value;\n endfunction\n function static logic [15:0] saved_logic(input bit enable, input bit [15:0] value);\n if (enable) saved_logic = value;\n endfunction\n initial begin\n $display(\"bit %d\", saved(1, 23));\n $display(\"bit %d\", saved(0, 91));\n $display(\"logic %d\", saved_logic(1, 23));\n $display(\"logic %d\", saved_logic(0, 91));\n end\nendmodule\n", + "icarus_return_only_stdout": "bit 23\nbit 0\nlogic 23\nlogic x\n" + } +} diff --git a/crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.sv b/crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.sv new file mode 100644 index 00000000000..ac1633d7cb2 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_static_function_lifetimes.sv @@ -0,0 +1,22 @@ +module Top; + function static bit [15:0] saved(input bit enable, input bit [15:0] value); + if (enable) saved = value; + endfunction + function static logic [15:0] saved_logic(input bit enable, input bit [15:0] value); + if (enable) saved_logic = value; + endfunction + function static void remember(input bit enable, input int value, output int saved_output); + if (!enable) return; + saved_output = value; + endfunction + int result; + initial begin + $display("bit %d", saved(1, 23)); + $display("bit %d", saved(0, 91)); + $display("logic %d", saved_logic(1, 23)); + $display("logic %d", saved_logic(0, 91)); + remember(1, 37, result); $display("output %d", result); + remember(0, 91, result); $display("output %d", result); + $finish; + end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus/procedural.json b/crates/celox-test-suite/verification/sv/icarus/procedural.json index dd1f06d9948..a504409b5f5 100644 --- a/crates/celox-test-suite/verification/sv/icarus/procedural.json +++ b/crates/celox-test-suite/verification/sv/icarus/procedural.json @@ -282,6 +282,102 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Verilator 5.052 and Icarus 13.0 reset a static function result on calls that do not assign it (0 for bit, X for logic in Icarus). IEEE 1800-2023 13.4.1 declares an implicit result variable, and 6.21/13.4.2 give it static lifetime. The standalone source reproduces the reset without the suite adapters. Celox retains the previous value.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_static_function_result_lifetime", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 and Icarus 13.0 reset a static function result on calls that do not assign it (0 for bit, X for logic in Icarus). IEEE 1800-2023 13.4.1 declares an implicit result variable, and 6.21/13.4.2 give it static lifetime. The standalone source reproduces the reset without the suite adapters. Celox retains the previous value.", + "upstream": [] + }, + "name": "procedural::static_function_four_state_result_retains_unknown_and_known_values", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Icarus 13.0 rejects the output argument of a void function: \"Function arguments must be input ports.\" IEEE 1800-2023 13.5 permits function output arguments. Celox executes the unchanged case; Verilator's separate lifetime disagreement is recorded independently.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_output_function_argument", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects the output argument of a void function: \"Function arguments must be input ports.\" IEEE 1800-2023 13.5 permits function output arguments. Celox executes the unchanged case; Verilator's separate lifetime disagreement is recorded independently.", + "upstream": [] + }, + "name": "procedural::static_function_output_formals_keep_value", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Icarus 13.0 rejects an explicit static local in an automatic function: \"Overriding the default variable lifetime is not yet supported.\" IEEE 1800-2023 6.21 permits this declaration. Celox and Verilator execute the unchanged real-valued case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_explicit_static_function_local", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects an explicit static local in an automatic function: \"Overriding the default variable lifetime is not yet supported.\" IEEE 1800-2023 6.21 permits this declaration. Celox and Verilator execute the unchanged real-valued case.", + "upstream": [] + }, + "name": "procedural::static_function_real_locals_and_results_keep_value", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Verilator 5.052 and Icarus 13.0 reset a static function result on calls that do not assign it (0 for bit, X for logic in Icarus). IEEE 1800-2023 13.4.1 declares an implicit result variable, and 6.21/13.4.2 give it static lifetime. The standalone source reproduces the reset without the suite adapters. Celox retains the previous value.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_static_function_result_lifetime", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 and Icarus 13.0 reset a static function result on calls that do not assign it (0 for bit, X for logic in Icarus). IEEE 1800-2023 13.4.1 declares an implicit result variable, and 6.21/13.4.2 give it static lifetime. The standalone source reproduces the reset without the suite adapters. Celox retains the previous value.", + "upstream": [] + }, + "name": "procedural::static_function_result_keeps_value_between_calls", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 446134fc726..42048791a99 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1,4 +1,80 @@ [ + { + "id": "sv_static_function_result_lifetime", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Verilator 5.052 and Icarus 13.0 reset a static function result on calls that do not assign it (0 for bit, X for logic in Icarus). IEEE 1800-2023 13.4.1 declares an implicit result variable, and 6.21/13.4.2 give it static lifetime. The standalone source reproduces the reset without the suite adapters. Celox retains the previous value.", + "upstream": [], + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "procedural::static_function_result_keeps_value_between_calls" + ], + "icarus": [ + "procedural::static_function_result_keeps_value_between_calls", + "procedural::static_function_four_state_result_retains_unknown_and_known_values" + ] + } + }, + { + "id": "sv_verilator_static_output_lifetime", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Verilator 5.052 resets a static output-only function argument when an early return leaves it unassigned. IEEE 1800-2023 6.21/13.4.2 give function arguments static lifetime, and 13.5 copies output values to actuals on return. The standalone source returns 0 after a previous call assigned 37; Celox retains 37.", + "upstream": [], + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "procedural::static_function_output_formals_keep_value" + ] + } + }, + { + "id": "sv_icarus_explicit_static_function_local", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects an explicit static local in an automatic function: \"Overriding the default variable lifetime is not yet supported.\" IEEE 1800-2023 6.21 permits this declaration. Celox and Verilator execute the unchanged real-valued case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "procedural::static_function_real_locals_and_results_keep_value" + ] + } + }, + { + "id": "sv_icarus_output_function_argument", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects the output argument of a void function: \"Function arguments must be input ports.\" IEEE 1800-2023 13.5 permits function output arguments. Celox executes the unchanged case; Verilator's separate lifetime disagreement is recorded independently.", + "upstream": [], + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "procedural::static_function_output_formals_keep_value" + ] + } + }, { "id": "sv_icarus_genvar_dimensions", "category": "simulator_disagreement", diff --git a/crates/celox-test-suite/verification/sv/verilator/procedural.json b/crates/celox-test-suite/verification/sv/verilator/procedural.json index 84971232d45..867c294a54d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/procedural.json +++ b/crates/celox-test-suite/verification/sv/verilator/procedural.json @@ -209,6 +209,54 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Verilator 5.052 resets a static output-only function argument when an early return leaves it unassigned. IEEE 1800-2023 6.21/13.4.2 give function arguments static lifetime, and 13.5 copies output values to actuals on return. The standalone source returns 0 after a previous call assigned 37; Celox retains 37.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_static_output_lifetime", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 resets a static output-only function argument when an early return leaves it unassigned. IEEE 1800-2023 6.21/13.4.2 give function arguments static lifetime, and 13.5 copies output values to actuals on return. The standalone source returns 0 after a previous call assigned 37; Celox retains 37.", + "upstream": [] + }, + "name": "procedural::static_function_output_formals_keep_value", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "ControlFlow", + "detail": "Verilator 5.052 and Icarus 13.0 reset a static function result on calls that do not assign it (0 for bit, X for logic in Icarus). IEEE 1800-2023 13.4.1 declares an implicit result variable, and 6.21/13.4.2 give it static lifetime. The standalone source reproduces the reset without the suite adapters. Celox retains the previous value.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_static_function_lifetimes.json", + "verification/repros/sv_static_function_lifetimes.sv", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_static_function_result_lifetime", + "observed_version": "Verilator 5.052 / Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 and Icarus 13.0 reset a static function result on calls that do not assign it (0 for bit, X for logic in Icarus). IEEE 1800-2023 13.4.1 declares an implicit result variable, and 6.21/13.4.2 give it static lifetime. The standalone source reproduces the reset without the suite adapters. Celox retains the previous value.", + "upstream": [] + }, + "name": "procedural::static_function_result_keeps_value_between_calls", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index f8b1c45eb35..709c06a182f 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -1,3 +1,5 @@ +use super::*; + sv_backends! { fn constant_functions_inside_selected_parameter_initializers(sim) { @case "procedural::constant_functions_inside_selected_parameter_initializers"; @@ -115,3 +117,66 @@ sv_backends! { @case "procedural::always_ff_reset_at_both_edges_and_as_a_clock"; } } + +sv_backends! { + fn static_function_locals_share_storage_between_calls(sim) { + @case "procedural::static_function_locals_share_storage_between_calls"; + } + fn static_function_result_keeps_value_between_calls(sim) { + @case "procedural::static_function_result_keeps_value_between_calls"; + } + fn static_function_real_locals_and_results_keep_value(sim) { + @case "procedural::static_function_real_locals_and_results_keep_value"; + } + fn static_function_output_formals_keep_value(sim) { + @case "procedural::static_function_output_formals_keep_value"; + } +} + +sv_backends! { + fn static_function_constant_calls_do_not_change_runtime_storage(sim) { + @case "procedural::static_function_constant_calls_do_not_change_runtime_storage"; + } + fn static_function_package_storage_is_shared_between_calls(sim) { + @case "procedural::static_function_package_storage_is_shared_between_calls"; + } +} + +sv_backends! { + fn static_function_retained_arrays_and_instance_storage(sim) { + @case "procedural::static_function_retained_arrays_and_instance_storage"; + } + fn static_function_four_state_result_retains_unknown_and_known_values(sim) { + @case "procedural::static_function_four_state_result_retains_unknown_and_known_values"; + } + fn static_function_real_storage_restores_checkpoint(sim) { + @setup { let source = r#" + module Top(input bit clk, output logic [63:0] value); + function real step(); + static real saved = 0.25; + saved += 0.5; + return saved; + endfunction + always_ff @(posedge clk) value <= $realtobits(step()); + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("static_checkpoint.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), num_bigint::BigUint::from(0.75f64.to_bits())); + let checkpoint = sim.checkpoint().unwrap(); + sim.tick(clk).unwrap(); + let next = sim.get(value); + assert_eq!(next, num_bigint::BigUint::from(1.25f64.to_bits())); + sim.restore(&checkpoint).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), next); + } +} + +sv_backends! { + fn static_function_wide_packed_storage_keeps_all_bits(sim) { + @case "procedural::static_function_wide_packed_storage_keeps_all_bits"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index a605a4291a7..1db1f427c34 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5796,19 +5796,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "static variable `saved` of subroutine `saved_value` that keeps its value between calls", - r#" - module Top(input logic set, value, output logic y); - function logic saved_value(input logic do_set, input logic new_value); - logic saved; - if (do_set) saved = new_value; - return saved; - endfunction - assign y = saved_value(set, value); - endmodule - "#, - ), ( "implicit net `missing` disabled", r#" diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index a4b7900eef7..b9adf8fd474 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -657,3 +657,15 @@ fn narrow_nonblocking_updates_cover_staged_and_queued_sites() { assert!(!staged(name), "{name} queues its updates"); } } + +sv_backends! { + fn static_function_storage_is_shared_between_processes(sim) { + @case "timing::static_function_storage_is_shared_between_processes"; + } +} + +sv_backends! { + fn static_function_readonly_initializer_calls_execute_once(sim) { + @case "timing::static_function_readonly_initializer_calls_execute_once"; + } +} diff --git a/crates/celox/tests/sv_lifetimes.rs b/crates/celox/tests/sv_lifetimes.rs index e93bf059655..1a04a761362 100644 --- a/crates/celox/tests/sv_lifetimes.rs +++ b/crates/celox/tests/sv_lifetimes.rs @@ -151,20 +151,13 @@ fn static_locals_written_before_they_are_read_are_temporaries() { } #[test] -fn static_subroutine_locals_that_keep_their_value_are_unsupported() { - for source in [ - "module Top(input logic clk, output logic [7:0] y); - function int f(); int c; c = c + 1; return c; endfunction - always_ff @(posedge clk) y <= f(); - endmodule", - "module Top(output logic [7:0] y); - function automatic int f(); static int c = 3; c++; return c; endfunction - assign y = f(); - endmodule", - ] { - let detail = error(source); - assert!(detail.contains("static variable `c`"), "{detail}"); - } +fn static_task_locals_that_keep_their_value_remain_unsupported() { + let detail = error( + "module Top(input logic clk, output int y); + task count(output int result); static int saved=0; saved++; result=saved; endtask + always @(posedge clk) count(y); endmodule", + ); + assert!(detail.contains("static variable `saved`"), "{detail}"); } #[test] @@ -281,13 +274,6 @@ fn interfaces_keep_their_default_lifetime() { /// selectors of concatenated targets. #[test] fn static_function_results_keep_their_value() { - let detail = error( - "module Top(input logic set, output logic [7:0] y); - function logic [7:0] f(input logic s); if (s) f = 8'd7; endfunction - assign y = f(set); - endmodule", - ); - assert!(detail.contains("whose result keeps its value"), "{detail}"); assert_eq!( output( "module Top(output logic [7:0] y); @@ -346,15 +332,6 @@ fn concatenated_targets_select_with_the_entry_value() { /// and writes through arguments of functions called in expressions. #[test] fn four_state_selectors_repeats_and_inout_arguments() { - // An X selector matches no item, so the static result would keep its - // previous value. - let detail = error( - "module Top(input logic a, output logic y); - function logic f(input logic s); case (s) 1'b0: f = 0; 1'b1: f = 1; endcase endfunction - assign y = f(a); - endmodule", - ); - assert!(detail.contains("whose result keeps its value"), "{detail}"); assert_eq!( output( "module Top(output logic [7:0] y); diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 2a545028e69..7a776ac9a3c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -377,23 +377,34 @@ unsupported, including when the inference option is enabled. ### Variable lifetimes -Variable lifetimes follow IEEE 1800-2023 6.21. A variable declared in a -procedural block, function or task is static unless it, its subroutine or -its module (`module automatic`) is declared `automatic`. A static local of a -block keeps its value from one execution of the block to the next, and its +Variable lifetimes follow IEEE 1800-2023 6.21. Outside classes, a variable +declared in a procedural block, function or task is static unless it, its +subroutine or its module (`module automatic`) is declared `automatic`. +Class methods have automatic lifetime (8.6). A static local of a block +keeps its value from one execution of the block to the next, and its initializer runs once at time zero: in `always_ff`, `int count; count++;` counts. An automatic local is initialized on every entry. A static local whose value on entry is never read, because every path writes it before reading it, behaves the same either way. Because a static local keeps its value, a local of `always_comb` that only some paths write is a latch, and -requires relaxing `inferred_latch` like other inferred latches. A static local of a function or task -that keeps its value between calls is not supported, nor is a static local -whose initializer is not constant; declare them `automatic`. The result of -a static function is static too, so one with a path that does not assign -it (other than a `case` whose items cover every value of a two-state -argument) is -rejected as well. An interface -whose default lifetime (`interface automatic`) differs from that of the +requires relaxing `inferred_latch` like other inferred latches. + +Static function locals and result variables keep their values between calls +(13.4.2), including scalar `real` values and packed/unpacked integral storage. +An explicit `static` local of an automatic function is shared too; automatic +locals are initialized on each call. Static output arguments retain their +previous values on paths that leave them unassigned. Observable static storage +is shared by call sites and timed processes, and module-local storage is separate +for each module instance. Declaration initializers run once at time zero, +including when the function has not been called. Initializers that call a +stateful function require `Simulation` or a native testbench to execute the +initialization process. Constant function calls use +fresh values and do not affect runtime storage (13.4.3). + +Task locals that keep their values and nonconstant static initializers remain +unsupported; declare those locals `automatic`. Package function state follows +the existing package-variable restrictions on multiple procedural drivers. +An interface whose default lifetime (`interface automatic`) differs from that of the module it is used in is rejected. ### Run-time loops diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f5600a1218b..7bce8fc86df 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -281,16 +281,29 @@ Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatche ### 変数の寿命 -変数の寿命は IEEE 1800-2023 6.21 に従います。プロセスのブロック、関数、タスクの中で宣言した +変数の寿命は IEEE 1800-2023 6.21 に従います。クラス外のプロセスのブロック、関数、タスクの中で宣言した 変数は、その変数自身、そのサブルーチン、またはそのモジュール(`module automatic`)が `automatic` -と宣言されていない限り static です。ブロックの static なローカル変数は、ブロックの実行をまたいで値を +と宣言されていない限り static です。クラスメソッドの寿命は automatic です(8.6)。 +ブロックの static なローカル変数は、ブロックの実行をまたいで値を 保持し、初期化子は時刻 0 に 1 回だけ実行します。`always_ff` 内の `int count; count++;` は数を数えます。 automatic なローカル変数は、ブロックに入るたびに初期化します。どの経路でも読む前に書き込むため、入った 時点の値が読まれない static なローカル変数は、どちらでも同じ動作です。static なローカル変数は値を保持する ため、一部の経路でしか書き込まない `always_comb` のローカル変数はラッチになり、ほかの暗黙のラッチと同じく -`inferred_latch` の緩和が必要です。呼び出しをまたいで値を保持する関数・タスクの static なローカル変数と、初期化子が定数でない -static なローカル変数は未対応です。`automatic` と宣言してください。static な関数の結果も static なので、 -結果を代入しない経路を持つ関数(2 値の引数のすべての値を項目が網羅する `case` を除く)も拒否します。既定の寿命(`interface automatic`)が +`inferred_latch` の緩和が必要です。 + +関数の static ローカル変数と戻り値は、呼び出しをまたいで値を保持します(13.4.2)。 +スカラーの `real` と packed/unpacked な整数の保存領域に対応しています。automatic 関数内で +明示的に `static` とした変数も共有され、automatic 変数は呼び出しごとに初期化されます。 +static な output 引数も、代入しない経路では以前の値を保持します。保持が必要な領域は呼び出し位置と +時間待ちプロセスの間で共有され、モジュール内の領域はインスタンスごとに独立します。 +宣言の初期化子は、関数が未呼び出しでも時刻 0 に一度だけ実行します。状態を保持する関数を +呼び出す初期化子は、初期化プロセスを実行する `Simulation` または native testbench が必要です。 +定数関数としての呼び出しは +毎回新しい値を使い、実行時の状態に影響しません(13.4.3)。 + +値を保持する task ローカル変数と、定数でない static 初期化子は引き続き未対応です。 +これらには `automatic` を指定してください。package 関数の状態には、複数の手続きドライバーに関する +既存の package 変数の制約が適用されます。既定の寿命(`interface automatic`)が 使用先のモジュールと異なる interface は拒否します。 ### 実行時のループ