From 13346c6140420234f23771c10314afa67689dadb Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 16:19:24 +0900 Subject: [PATCH] fix(sv): return typed defaults for invalid unpacked array reads Generated pipelines such as r[n] <= n == 0 ? d : r[n-1] rejected r[-1] in the unselected conditional operand. Route constant invalid integral unpacked indices through the existing bounds guard and fold invalid reads to the selected type's X or zero default. Invalid writes remain no-ops. Exclude wholly invalid constant writes from FF target collection before recording pending-state or latch-coverage targets. An empty constant range must not become a dynamic whole-array write and trigger an inferred latch. Update the large-index diagnostic regression to require successful builds without warnings under both error and warn policies. Preserve both conditional operands' width and signedness, as required by IEEE 1800-2023 7.4.5 and 11.4.11. Cover nonzero ascending/descending bounds, multidimensional indices, sequential writes, 129-bit defaults and two-state elements in a four-state simulator. Replace obsolete rejection expectations. Keep the invalid bit-array read regression in Celox's API tests because Icarus 13.0 returns X instead of the required zero for that case. Validation on master feba1a583c with the preceding Native fix: - Full SystemVerilog suite: 5,003 passed across five backends, with 20 existing exclusions; all 29 added regression variants passed. - SV analyzer: 806 passed, three existing ignored, plus both doctests. - Clippy for celox-sv-analyzer and celox, including the SV tests, passed. The unchanged shared cases passed Icarus during validation on master 644beacb20. Verilator passed the two-state pipeline; the four-state cases remain unsupported by that adapter. The external adapters are unchanged. Rebuilt NAPI: the threads E2E and all three runtime-event addon tests passed. Workspace check (excluding lydite-celox), formatting, lint and submodule checks passed. After restacking on the typed Native merge dispatch, all 12 added Native regression variants and rebuilt NAPI integration checks passed. The threads E2E initially exceeded its 5s limit while builds ran concurrently; an isolated rerun passed with the same 5s limit. All three addon event tests also passed. CI follow-up: the old diagnostic regression expected a range error. Its replacement exposed and now covers the false latch diagnostic above. Validation: all 5,003 SV cases, all 33 diagnostic-policy tests, six frontend unit tests, and clippy for both affected crates/consumers passed. Change-Id: Ib6ba45acc50166a08cbb7851d3efaa20c89de081 --- crates/celox-frontend-sv/src/lowering/ff.rs | 36 ++-- crates/celox-sv-analyzer/src/ast/selects.rs | 60 ++++-- .../celox-sv-analyzer/src/ast/statements.rs | 3 + .../src/sv/cases/indexed_select.vtest | 171 ++++++++++++++++++ crates/celox/tests/diagnostic_policy.rs | 17 +- .../frontends/systemverilog/indexed_select.rs | 28 +++ .../systemverilog/review_regressions.rs | 28 --- 7 files changed, 276 insertions(+), 67 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 6058fabcc4a..ddd3041030a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -280,6 +280,27 @@ impl<'p, 'a> Ff<'p, 'a> { let Some(id) = self.m.id(lvalue.name()) else { return; }; + let variable = self.m.var(id); + let constant = match lvalue { + sv::ir::LValue::Ident(_) => None, + sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types( + msb, + self.m.constants, + self.m.parameter_types, + ) + .zip(sv::typecheck::eval_const_expr_with_types( + lsb, + self.m.constants, + self.m.parameter_types, + )) + .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)), + }; + // An empty constant write is not a dynamic write of the whole + // variable. Keep it out of publication and latch-coverage targets. + if matches!(constant, Some((None, _))) { + return; + } + let constant = constant.and_then(|(access, _)| access); if blocking { self.working.insert(id); } else { @@ -288,7 +309,6 @@ impl<'p, 'a> Ff<'p, 'a> { if self.m.is_hidden(id) { return; } - let variable = self.m.var(id); // A run-time bit select within one array element writes only that // element (see `write`); a run-time element may be any of them. let element_write = dynamic_array_element_lvalue( @@ -312,20 +332,6 @@ impl<'p, 'a> Ff<'p, 'a> { .flatten() .and_then(|write| write.window) .unwrap_or(BitAccess::new(0, variable.width - 1)); - let constant = match lvalue { - sv::ir::LValue::Ident(_) => None, - sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types( - msb, - self.m.constants, - self.m.parameter_types, - ) - .zip(sv::typecheck::eval_const_expr_with_types( - lsb, - self.m.constants, - self.m.parameter_types, - )) - .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0), - }; if constant.is_none() { // `write` takes the same order: a constant range, then one // run-time element, then a read-modify-write of the variable. diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index c0c475936f4..7126968f141 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -88,7 +88,7 @@ pub(super) fn lvalue_from_indices( packed_dimensions: &PackedDimensions, ) -> Converted { if let Some((array_offset, packed_indices)) = - flatten_variable_select(state, &name, &indices, packed_dimensions) + flatten_variable_select(&name, &indices, packed_dimensions) { if !packed_indices.is_empty() { if let Some((msb, lsb)) = @@ -186,6 +186,43 @@ pub(super) fn lvalue_from_indices( Ok(LValue::Ident(name)) } +/// Fold the invalid-element sentinel emitted by `flatten_variable_select`. +/// Keep the selected integral type even in an unselected conditional arm: +/// both operands determine the conditional width and signedness (11.4.11). +pub(super) fn invalid_unpacked_read( + state: &AnalysisState, + lhs: &LValue, + dimensions: &PackedDimensions, +) -> Option { + let LValue::Select { + name, + msb, + lsb, + signed, + .. + } = lhs + else { + return None; + }; + let variable = dimensions.get(name)?; + if variable.unpacked.is_empty() || variable.real || variable.string || variable.class.is_some() + { + return None; + } + let full_width = lvalue_expr_type(state, &LValue::Ident(name.clone()), dimensions)?.width; + let msb = eval_ast_const_expr(state, msb, &dimensions.const_env)?; + let lsb = eval_ast_const_expr(state, lsb, &dimensions.const_env)?; + if msb < lsb || lsb < i128::try_from(full_width).ok()? { + return None; + } + let width = usize::try_from(msb.checked_sub(lsb)?) + .ok()? + .checked_add(1)?; + let signing = if *signed { "s" } else { "" }; + let digit = if variable.is_2state { "0" } else { "x" }; + Some(Expr::Literal(format!("{width}'{signing}b{digit}"))) +} + /// Shared syntax-independent assignment range flattening and array metadata. pub(super) fn lvalue_from_range( state: &AnalysisState, @@ -348,7 +385,6 @@ pub(super) fn indexed_range_values( } fn flatten_variable_select( - state: &AnalysisState, name: &str, indices: &[ConstExpr], packed_dimensions: &PackedDimensions, @@ -360,15 +396,9 @@ fn flatten_variable_select( let mut offset = ConstExpr::Literal("0".to_string()); let mut valid = None; for (index, value) in indices[..selected_unpacked_count].iter().enumerate() { - if const_expr_is_out_of_range( - state, - value, - &dimensions.unpacked[index].left, - &dimensions.unpacked[index].right, - &packed_dimensions.const_env, - ) { - return None; - } + // Constant and runtime invalid indices have the same semantics: + // read the element type's default value and ignore writes (7.4.5). + // Route both through the guard below instead of rejecting constants. let dimension = &dimensions.unpacked[index]; let descending = ConstExpr::Binary { left: Box::new(dimension.left.clone()), @@ -483,7 +513,7 @@ fn unpacked_select_range_metadata( ) { return None; } - let (_, packed_indices) = flatten_variable_select(state, name, indices, packed_dimensions)?; + let (_, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?; if !packed_indices.is_empty() { return None; } @@ -554,8 +584,7 @@ fn flatten_unpacked_select_range( ) { return None; } - let (array_offset, packed_indices) = - flatten_variable_select(state, name, indices, packed_dimensions)?; + let (array_offset, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?; if !packed_indices.is_empty() { return None; } @@ -642,8 +671,7 @@ fn flatten_select_range( packed_dimensions, ); } - let (array_offset, packed_indices) = - flatten_variable_select(state, name, indices, packed_dimensions)?; + let (array_offset, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?; let dimension = dimensions.packed.get(packed_indices.len())?; if const_expr_is_out_of_range( state, diff --git a/crates/celox-sv-analyzer/src/ast/statements.rs b/crates/celox-sv-analyzer/src/ast/statements.rs index 9ff4406572a..f256a9694e1 100644 --- a/crates/celox-sv-analyzer/src/ast/statements.rs +++ b/crates/celox-sv-analyzer/src/ast/statements.rs @@ -163,6 +163,9 @@ pub(super) fn expr_from_lvalue( lhs: &LValue, packed_dimensions: &PackedDimensions, ) -> Expr { + if let Some(value) = selects::invalid_unpacked_read(state, lhs, packed_dimensions) { + return value; + } let (base, array_slice_width, array_slice_reversed, signed) = match lhs { LValue::Ident(name) => return Expr::Ident(name.clone()), LValue::Select { 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 36ba67285b4..65c69699a08 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1959,6 +1959,177 @@ (run_until 1) (assert_eq s0 0) (assert_eq s1 0x42) (assert_eq s2 0)) +(case generated_pipeline_with_unselected_invalid_array_element + ; IEEE 1800-2023 7.4.5 and 11.4.11: an invalid element in the unused + ; conditional arm must not prevent elaboration or change the result type. + (source "generated_pipeline.sv" #" + module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d, + output logic [7:0] q); + if (N>0) begin : pipe + logic [7:0] r[3:N+2]; + for(genvar n=0;n cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0)) + (assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0)))) + +(case constant_invalid_unpacked_indices_read_defaults_and_ignore_writes + ; IEEE 1800-2023 7.4.5, Table 7-1. Invalid inner indices must never + ; wrap into a neighboring element, in either declaration direction. + (four_state) + (source "constant_invalid_array_indices.sv" #" + module Top(input logic clk, input logic [7:0] d, + output logic [7:0] above, below, inner, row, + output logic [7:0] written, written_ff, + output logic [128:0] wide); + logic [7:0] a[3:4]; + logic [7:0] b[4:3]; + logic [7:0] matrix[0:1][0:2]; + logic [7:0] w[3:4], f[3:4]; + logic [128:0] wide_array[2]; + assign wide=wide_array[2]; + always_comb begin + a[3]=d; a[4]=~d; + b[3]=d; b[4]=~d; + for (int i=0;i<2;i++) for (int j=0;j<3;j++) matrix[i][j]=d; + w[3]=d; w[4]=~d; + w[2]=8'hff; w[5]=8'hff; + end + always_ff @(posedge clk) begin + f[3]<=d; f[4]<=~d; + f[2]<=8'hff; f[5]<=8'hff; + end + assign below=a[2]; + assign above=b[5]; + assign inner=matrix[0][3]; + assign row=matrix[2][0]; + assign written=w[3]^w[4]; + assign written_ff=f[3]^f[4]; + endmodule + "#) + (top Top) + (for value (list 0x12 0xa5 0xff) + (modify (set d value)) + (assert_eq below (fourstate 255 255)) + (assert_eq above (fourstate 255 255)) + (assert_eq inner (fourstate 255 255)) + (assert_eq row (fourstate 255 255)) + (let wide_mask (- (<< 1 129) 1)) + (assert_eq wide (fourstate wide_mask wide_mask)) + (assert_eq written 255) + (tick clk) + (assert_eq written_ff 255))) + +(case generated_pipeline_with_unselected_invalid_array_element_four_state + ; IEEE 1800-2023 7.4.5 and 11.4.11: an invalid element in the unused + ; conditional arm must not prevent elaboration or change the result type. + (four_state) + (source "generated_pipeline.sv" #" + module Asc #(parameter N=0)(input logic clk, rst, input logic [7:0] d, + output logic [7:0] q); + if (N>0) begin : pipe + logic [7:0] r[3:N+2]; + for(genvar n=0;n cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0)) + (assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0)) + (assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0)))) + +(case invalid_unpacked_elements_preserve_type_in_conditionals + ; Both conditional operands contribute width and signedness even when + ; a constant condition selects the other operand (11.4.11, 11.8.2). + (four_state) + (source "invalid_array_element_types.sv" #" + module Top(output logic [15:0] mixed_sign, both_signed, + output logic [31:0] width); + logic [15:0] u[1]; + logic signed [15:0] s[1]; + assign mixed_sign=1'b1 ? 8'sh80 : u[-1]; + assign both_signed=1'b1 ? 8'sh80 : s[-1]; + assign width=$bits(1'b1 ? 8'sh80 : u[-1]); + endmodule + "#) + (top Top) + (assert_eq mixed_sign 0x0080) + (assert_eq both_signed 0xff80) + (assert_eq width 16)) + (case generated_pipeline_with_explicit_generate_branches ; Separate FF producers may share one array. Removing a task's staging ; must preserve publication of elements computed by other tasks (10.4.2). diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs index 49eb9853ce8..ffbc6bc5658 100644 --- a/crates/celox/tests/diagnostic_policy.rs +++ b/crates/celox/tests/diagnostic_policy.rs @@ -604,14 +604,15 @@ mod inferred_latch { #[test] fn out_of_bounds_state_writes_do_not_expand_diagnostic_masks() { let source = "module Top(output logic [7:0] q); logic [7:0] a[2]; always_comb begin q=$time; a[-1]=$time; a[2147483647]=$time; end endmodule"; - let error = Simulator::from_sv_sources(vec![(source, Path::new("oob_state.sv"))], "Top") - .diagnostic_policy(policy("inferred_latch", DiagnosticLevel::Warn)) - .build_interpreter() - .unwrap_err(); - assert!( - error.to_string().contains("outside its declared range"), - "{error}" - ); + // Invalid unpacked writes are ignored (IEEE 1800-2023 7.4.5). + // Their offsets must not enlarge coverage masks or create a latch. + for level in [DiagnosticLevel::Error, DiagnosticLevel::Warn] { + let sim = Simulator::from_sv_sources(vec![(source, Path::new("oob_state.sv"))], "Top") + .diagnostic_policy(policy("inferred_latch", level)) + .build_interpreter() + .unwrap(); + assert!(sim.warnings().is_empty(), "{:?}", sim.warnings()); + } } } diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index f1816a8b4ab..6350b87d6f7 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -370,6 +370,34 @@ fn continuous_part_selects_partly_outside_drive_the_bits_inside() { assert_eq!(sim.get(r), 0x5au8.into()); } +sv_backends! { + fn generated_pipeline_with_unselected_invalid_array_element(sim) { + @case "indexed_select::generated_pipeline_with_unselected_invalid_array_element"; + } + fn generated_pipeline_with_unselected_invalid_array_element_four_state(sim) { + @case "indexed_select::generated_pipeline_with_unselected_invalid_array_element_four_state"; + } + fn invalid_unpacked_elements_preserve_type_in_conditionals(sim) { + @case "indexed_select::invalid_unpacked_elements_preserve_type_in_conditionals"; + } + fn constant_invalid_unpacked_indices_read_defaults_and_ignore_writes(sim) { + @case "indexed_select::constant_invalid_unpacked_indices_read_defaults_and_ignore_writes"; + } +} + +// Icarus 13.0 returns X here, contrary to IEEE 1800-2023 7.4.5 Table 7-1. +// Keep this regression local, like the partial continuous-select check above. +sv_backends! { + fn constant_invalid_two_state_unpacked_read(sim) { + @setup { + let source = "module Top(output logic [7:0] q); bit [7:0] b[1]; assign q=b[1]; endmodule"; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("invalid_bit_element.sv"))], "Top").four_state(true); + let q=sim.signal("q"); + assert_eq!(sim.get_four_state(q), (BigUint::default(), BigUint::default())); + } +} + sv_backends! { fn generated_pipeline_with_explicit_generate_branches(sim) { @case "indexed_select::generated_pipeline_with_explicit_generate_branches"; diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 7c6b4f10ca6..7fe9af4dddb 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5258,25 +5258,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { module Top(input logic [1:0] a); Child child[0:-1](.a(a)); endmodule "#, ), - ( - "index 2 of `values` outside its declared range", - r#" - module Top(output logic y); - logic [7:0] values [0:1][0:2]; - assign y = values[0][3]; - endmodule - "#, - ), - ( - "index 2 of `values` outside its declared range", - r#" - module Top(output logic y); - localparam J = 3; - logic [7:0] values [0:1][0:2]; - assign y = values[0][J]; - endmodule - "#, - ), ( "combinational expression", r#" @@ -5625,15 +5606,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "index 2 of `values` outside its declared range", - r#" - module Top(output logic y); - logic [7:0] values [0:1][0:2]; - assign y = values[1][3]; - endmodule - "#, - ), ( "systemverilog inout port", r#"