diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c1d56b95e5b..aad26f6f9c8 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1187,8 +1187,8 @@ chapter-6/6.19.5.4--enum_prev.sv 2state pass chapter-6/6.19.5.4--enum_prev.sv 4state pass chapter-6/6.19.5.5--enum_num.sv 2state pass chapter-6/6.19.5.5--enum_num.sv 4state pass -chapter-6/6.19.5.6--enum_name.sv 2state fail -chapter-6/6.19.5.6--enum_name.sv 4state fail +chapter-6/6.19.5.6--enum_name.sv 2state pass +chapter-6/6.19.5.6--enum_name.sv 4state pass chapter-6/6.20.2--parameter.sv 2state pass chapter-6/6.20.2--parameter.sv 4state pass chapter-6/6.20.2--parameter_aggregate.sv 2state pass @@ -1557,10 +1557,10 @@ chapter-8/8.5--properties_enum.sv 2state fail chapter-8/8.5--properties_enum.sv 4state fail chapter-8/8.6--methods.sv 2state pass chapter-8/8.6--methods.sv 4state pass -chapter-8/8.7--constructor.sv 2state fail -chapter-8/8.7--constructor.sv 4state fail -chapter-8/8.7--constructor_param.sv 2state fail -chapter-8/8.7--constructor_param.sv 4state fail +chapter-8/8.7--constructor.sv 2state pass +chapter-8/8.7--constructor.sv 4state pass +chapter-8/8.7--constructor_param.sv 2state pass +chapter-8/8.7--constructor_param.sv 4state pass chapter-8/8.7--constructor_super.sv 2state pass chapter-8/8.7--constructor_super.sv 4state pass chapter-8/8.8--typed_constructor.sv 2state pass diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 1cc4cc9b101..bce87c08b8a 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1263,6 +1263,7 @@ impl Module { subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(syntax_tree), statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; @@ -1330,18 +1331,25 @@ impl Module { &subroutine_directions, comb_processes .iter_mut() - .map(|process| &mut process.body) - .chain(ff_processes.iter_mut().map(|process| &mut process.body)) + .map(|process| (&mut process.body, false)) + .chain( + ff_processes + .iter_mut() + .map(|process| (&mut process.body, false)), + ) .chain( initial_processes .iter_mut() - .map(|process| &mut process.body), + .map(|process| (&mut process.body, !process.repeats)), ), + Some(&body_state.explicit_statics), )?; for subroutine in &subroutines { kept.extend(subroutine.persistent_locals.iter().cloned()); } - static_initializers.append(&mut body_state.static_initializers); + // Statics of subroutines are initialized first: a run-time + // initializer of a process local may call the subroutine. + static_initializers.splice(0..0, body_state.static_initializers.drain(..)); locals.retain(|local| !kept.contains(&local.name)); for name in kept { signals.push(Signal::new(name.clone(), statics[&name].clone())); @@ -1352,10 +1360,18 @@ impl Module { .iter() .position(|process| !process.is_initializer()) .unwrap_or(initial_processes.len()); + // They may read module variables, so they also stay after those + // initializers when processes are reordered by creation. + let creation_order = initial_processes + .iter() + .filter(|process| process.is_initializer()) + .map(|process| process.creation_order) + .max() + .unwrap_or(0); initial_processes.insert( first_block, InitialProcess { - creation_order: 0, + creation_order, site: None, condition: None, body: static_initializers, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index c2450c8a986..22a41a5f0ba 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -503,6 +503,7 @@ fn collect_module_constant_functions( subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(tree), statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: true, }; diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index c40ffb644be..0c0813c79aa 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -75,6 +75,7 @@ pub(super) fn native_functions( subroutine_directions: &directions, automatic, statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 9d191a2934c..fed3e3d3183 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -31,18 +31,27 @@ enum Entry { /// time-zero initializations. /// `directions` gives the argument directions of the subroutines a body /// may call. +/// For the bodies of processes, `explicit` gives the statics declared with +/// the `static` keyword, and each body tells whether its process runs once; +/// see [`initialized_at_time_zero`]. pub(super) fn keep_static_locals<'b, T>( state: &AnalysisState, statics: &HashMap, directions: &Directions, - bodies: impl IntoIterator>, + bodies: impl IntoIterator, bool)>, + explicit: Option<&HashSet>, ) -> Result<(Vec, Vec), AnalyzerError> { let mut kept = Vec::new(); let mut initializers = Vec::new(); if statics.is_empty() { return Ok((kept, initializers)); } - for body in bodies { + let mut bodies = bodies.into_iter().collect::>(); + let initialized = match explicit { + Some(explicit) => initialized_at_time_zero(state, statics, explicit, &bodies), + None => HashSet::default(), + }; + for (body, _) in &mut bodies { let mut concurrent = false; for stmt in body.iter() { stmt.walk(&mut |stmt| concurrent |= matches!(stmt, Stmt::Fork { .. })); @@ -51,6 +60,7 @@ pub(super) fn keep_static_locals<'b, T>( state, body, statics, + &initialized, directions, &mut kept, &mut initializers, @@ -60,10 +70,74 @@ pub(super) fn keep_static_locals<'b, T>( Ok((kept, initializers)) } +/// The static locals of process `bodies` whose initializer is not constant +/// but reads no automatic variable, with the static locals they read. The +/// initializer of a static variable may be any run-time expression, and +/// runs once before any procedure starts (IEEE 1800-2023 6.8, 6.21); these +/// locals keep their value so that the time-zero initialization does that. +/// +/// 6.21 requires the `static` keyword on an initialized static variable of +/// a procedural block, to show that the initializer runs only once. Without +/// it, a non-constant initializer is accepted only in a process that runs +/// once, such as an `initial` procedure, where running it at time zero +/// rather than on entry cannot repeat; in an `always` procedure it remains +/// rejected, like one that reads an automatic variable. +fn initialized_at_time_zero( + state: &AnalysisState, + statics: &HashMap, + explicit: &HashSet, + bodies: &[(&mut Vec, bool)], +) -> HashSet { + let mut initializers = HashMap::default(); + let mut automatic = Vec::new(); + for (body, once) in bodies { + for stmt in body.iter() { + stmt.walk(&mut |stmt| { + if let Stmt::Local { name, init } = stmt { + if statics.contains_key(name) { + let allowed = *once || explicit.contains(name); + initializers.insert(name.as_str(), (init.as_ref(), allowed)); + } else { + automatic.push(name.as_str()); + } + } + }); + } + } + let runtime = |init: &Expr| { + !expr_is_constant(state, init) && !automatic.iter().any(|name| expr_reads(init, name)) + }; + let mut pending = initializers + .iter() + .filter(|(_, (init, allowed))| *allowed && init.is_some_and(runtime)) + .map(|(name, _)| *name) + .collect::>(); + let mut initialized = HashSet::default(); + while let Some(name) = pending.pop() { + let (init, allowed) = initializers.get(name).copied().unwrap_or_default(); + if init.is_some_and(|init| !expr_is_constant(state, init) && !(allowed && runtime(init))) + || !initialized.insert(name.to_string()) + { + continue; + } + if let Some(init) = init { + pending.extend( + initializers + .keys() + .filter(|other| expr_reads(init, other)) + .copied(), + ); + } + } + initialized +} + +#[allow(clippy::too_many_arguments)] fn keep_in( state: &AnalysisState, stmts: &mut Vec, statics: &HashMap, + initialized: &HashSet, directions: &Directions, kept: &mut Vec, initializers: &mut Vec, @@ -75,7 +149,8 @@ fn keep_in( // time slot (IEEE 1800-2023 16.5.1), which the local keeps. if let Stmt::Local { name, init } = &stmts[index] && statics.contains_key(name) - && (concurrent + && (initialized.contains(name) + || concurrent || sampled_reads(&stmts[index + 1..], name) || entry( state, @@ -109,6 +184,7 @@ fn keep_in( state, then_body, statics, + initialized, directions, kept, initializers, @@ -118,6 +194,7 @@ fn keep_in( state, else_body, statics, + initialized, directions, kept, initializers, @@ -130,6 +207,7 @@ fn keep_in( state, &mut item.body, statics, + initialized, directions, kept, initializers, @@ -141,6 +219,7 @@ fn keep_in( state, default, statics, + initialized, directions, kept, initializers, @@ -155,6 +234,7 @@ fn keep_in( state, init, statics, + initialized, directions, kept, initializers, @@ -164,6 +244,7 @@ fn keep_in( state, step, statics, + initialized, directions, kept, initializers, @@ -173,6 +254,7 @@ fn keep_in( state, body, statics, + initialized, directions, kept, initializers, @@ -181,7 +263,16 @@ fn keep_in( } Stmt::Fork { branches, .. } => { for branch in branches { - keep_in(state, branch, statics, directions, kept, initializers, true)?; + keep_in( + state, + branch, + statics, + initialized, + directions, + kept, + initializers, + true, + )?; } } _ => {} diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 2a7e94b0bc9..2502af44cd7 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -50,6 +50,8 @@ pub(super) struct BodyState<'a> { /// The locals declared with a static lifetime: their unique names and /// types. pub statics: Vec<(String, Type)>, + /// The statics declared with the `static` keyword. + pub explicit_statics: HashSet, /// 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). @@ -1134,6 +1136,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { _ => self.automatic, }; if !automatic { + if native.lifetime.as_deref() == Some("static") { + self.state.explicit_statics.insert(name.clone()); + } let r#type = scoped_type(signal.r#type().clone(), &self.dims.const_env); self.state.statics.push((name.clone(), r#type)); } @@ -2555,7 +2560,8 @@ pub(super) fn lower_subroutine( &tree.state, &retained_types, builder.state.subroutine_directions, - std::iter::once(&mut subroutine.body), + std::iter::once((&mut subroutine.body, false)), + None, )?; if retain_result { kept.extend(subroutine.return_var.clone()); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index 7c9482d730c..f1f8ee21e76 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -708,6 +708,7 @@ mod tests { subroutine_directions: &directions, automatic: false, statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index f83879faaf9..b5b67130277 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -1510,3 +1510,24 @@ (tick clk) (assert_eq result wide) (modify (set update 1)) (tick clk) (assert_eq result 0)) + +(case static_locals_with_run_time_initializers_run_before_procedures + (source "static_initializers.sv" #" + module Top(output bit [7:0] first, output bit [7:0] looped); + int m = 1; + initial m = 5; + initial begin + static int k = m + 1; + static int j = k * 10; + first = 8'(j); + for (int i = 0; i < 3; i++) begin + static int once = k; + once++; + looped = 8'(once); + end + end + endmodule + "#) + (top Top) (run_until 0) + (assert_eq first 20) + (assert_eq looped 5)) diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 669313f8044..60855e24280 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -88,6 +88,10 @@ sv_backends! { @case "procedural::static_function_scratch_arrays_are_filled_before_reads"; } + fn static_locals_with_run_time_initializers_run_before_procedures(sim) { + @case "procedural::static_locals_with_run_time_initializers_run_before_procedures"; + } + fn static_function_result_filled_by_constant_loops(sim) { @case "procedural::static_function_result_filled_by_constant_loops"; } diff --git a/crates/celox/tests/sv_lifetimes.rs b/crates/celox/tests/sv_lifetimes.rs index 7457e738a54..ab80e5e38bb 100644 --- a/crates/celox/tests/sv_lifetimes.rs +++ b/crates/celox/tests/sv_lifetimes.rs @@ -311,6 +311,111 @@ fn static_initializers_run_before_initial_blocks() { ); } +/// A static initializer may be any run-time expression; it runs once, +/// before any procedure starts (IEEE 1800-2023 6.8, 6.21). +#[test] +fn run_time_static_initializers_run_once_before_any_procedure() { + // The initializers read the module variable before the other `initial` + // procedure writes it, and in declaration order. Without the `static` + // keyword that 6.21 requires, an `initial` procedure's locals still + // follow this rule. + assert_eq!( + settled( + "module Top(output logic [31:0] y); + typedef enum {a, b, c} e; + int m = 1; + initial m = 5; + initial begin + e v = b; + string s = v.name(); + int k = m + 1; + static int j = k * 10 + v; + v = c; + y = {s.len() == 1 && s == \"b\", 7'(k), 8'(j), 8'(m)}; + end + endmodule" + ), + 0x82_1505 + ); + // Also when an edge process that makes a host request reorders the + // processes by creation. + assert_eq!( + settled( + "module Top(input logic clk, output logic [7:0] y); + int dummy; + int m = dummy + 4; + always @(posedge clk) $fflush; + initial begin static int k = m + 1; y = k; end + endmodule" + ), + 5 + ); + // A static in a loop is initialized once, not on each iteration. + assert_eq!( + settled( + "module Top(output logic [7:0] y); + int m = 1; + initial for (int i = 0; i < 3; i++) begin + static int once = m; + once++; + y = once; + end + endmodule" + ), + 4 + ); + // An explicitly static local of an `always` procedure as well. + assert_eq!( + ticks( + "module Top(input logic clk, output logic [7:0] y); + int m = 4; + always_ff @(posedge clk) begin static int c = m + 1; c++; y <= c; end + endmodule", + 2 + ), + [6, 7] + ); + // The statics of a function it calls are initialized before it. + assert_eq!( + settled( + "module Top(output logic [7:0] y); + int m = 1; + function int f(input int a); + static int c = 7; + c++; + return c + a; + endfunction + initial begin static int k = f(m); y = k + f(0); end + endmodule" + ), + 18 + ); +} + +/// An initializer that reads an automatic variable, or a keyword-less one +/// of a procedure that repeats, could only run on each entry. +#[test] +fn run_time_static_initializers_that_could_repeat_remain_unsupported() { + for source in [ + "module Top(output logic [7:0] y); + initial begin automatic int x = 3; int t = x + 1; y = t; end + endmodule", + "module Top(output logic [7:0] y); + initial begin automatic int x = 3; static int t = x + 1; y = t; end + endmodule", + "module Top(input logic clk, output logic [7:0] y); + int m = 4; + always_ff @(posedge clk) begin int c = m + 1; c++; y <= c; end + endmodule", + ] { + let detail = error(source); + assert!( + detail.contains("initializer that is not constant"), + "{detail}" + ); + } +} + #[test] fn concatenated_targets_select_with_the_entry_value() { assert_eq!( diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 4e1883e7610..b4b120ffe6a 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -872,8 +872,22 @@ 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 is a +A static local of a process may have a run-time initializer. It runs once, +in declaration order, before any procedure starts (IEEE 1800-2023 6.8), and +may read module variables and other static locals but no automatic variable. +IEEE 1800-2023 6.21 states that "an explicit static keyword shall be required +when an initialization value is specified as part of a static variable's +declaration". Celox also accepts the declaration without the keyword, as +existing sources often omit it (for example `string s = v.name();` in an +`initial` block): with a constant initializer in any procedure, and with a +run-time initializer in a procedure that runs once, such as `initial`. In an +`always` procedure a run-time initializer without the keyword is rejected, +because its author likely meant it to run on every entry; declare the local +`static` or `automatic` to state which. + +Task locals that keep their values and nonconstant initializers of static +function locals remain unsupported; declare those locals `automatic`. Package +function state is a package variable, which the processes of every instance may write. An interface whose default lifetime (`interface automatic`) differs from that of the module it is used in is rejected. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index aeac453a914..9eb08b0e6c7 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -468,7 +468,18 @@ static な output 引数も、代入しない経路では以前の値を保持 定数関数としての呼び出しは 毎回新しい値を使い、実行時の状態に影響しません(13.4.3)。 -値を保持する task ローカル変数と、定数でない static 初期化子は引き続き未対応です。 +プロセスの static なローカル変数には実行時の値を使う初期化子も書けます。初期化子は宣言順に、 +どの手続きよりも先に 1 回だけ実行し(IEEE 1800-2023 6.8)、モジュールの変数とほかの static な +ローカル変数を読めますが、automatic 変数は読めません。IEEE 1800-2023 6.21 は "an explicit static +keyword shall be required when an initialization value is specified as part of a static variable's +declaration" と定め、手続きブロック内で初期化子を持つ static 変数に `static` キーワードを要求します。 +既存のソースはこのキーワードを省くことが多いため(`initial` ブロック内の `string s = v.name();` など)、 +Celox はキーワードのない宣言も受け付けます。定数の初期化子はどの手続きでも、実行時の値を使う初期化子は +`initial` のように 1 回だけ実行する手続きで受け付けます。`always` 手続きでキーワードなしに実行時の値で +初期化すると、入るたびに実行する意図の可能性が高いためエラーになります。`static` か `automatic` を +指定して意図を示してください。 + +値を保持する task ローカル変数と、関数の static なローカル変数の定数でない初期化子は引き続き未対応です。 これらには `automatic` を指定してください。package 関数の状態は package 変数で、 すべてのインスタンスのプロセスが書き込めます。既定の寿命(`interface automatic`)が 使用先のモジュールと異なる interface は拒否します。