From 6e06662ae8505ba828771dca2f39822ee29a23ed Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 09:32:34 +0900 Subject: [PATCH] fix(sv): fix structure defaults, record padding, bare pops and nested reads Review findings on the unpacked structure stack (#2415, #2422, #2424) that arrived after it merged: - A `default` pattern item descends into a structure member unless the value is a structure of that member's type (IEEE 1800-2023 10.9.2), so `c = '{default: a}` initializes the nested members of `a`'s type instead of rejecting it. - 4-state object fields store their complemented value and mask planes masked to the field width. Padding bits stay zero, so a default record of a field that is not byte-aligned (`logic flag`) is all zero bytes, and `finish_record` keeps it `null`: `d = new[1]; d[0] = d[0];` no longer wakes `@(d)`. - `q.pop_front` and `q.pop_back` without parentheses are whole elements of a queue of structures. - A `$` index of a queue read through a receiver with a side effect, such as `m[f()][$]`, is rejected: the size behind `$` reads the receiver again, which could name another queue. Change-Id: Ibd97e9c73adb7703a0734ca9fcdedeb66c0a2189 --- .../src/lowering/ff/objects.rs | 19 ++++-- .../celox-sv-analyzer/src/ast/containers.rs | 45 +++++++------- .../src/ast/patterns/binding.rs | 4 +- .../src/ast/unpacked_structs.rs | 9 ++- .../frontends/systemverilog/containers.rs | 46 ++++++++++++++ .../systemverilog/unpacked_structs.rs | 62 +++++++++++++++++++ 6 files changed, 154 insertions(+), 31 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index 46908086f68..e711b3fbea4 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -324,7 +324,7 @@ impl Ff<'_, '_> { let offset = self.constant64(u64::from(field.offset + plane)); let count = self.constant64(u64::from(field.bytes())); let stored = self.heap_call(opcode, &[object, offset, count]); - self.complement(stored) + self.complement(stored, field.width) }); return self.container_join(value, mask, width, true); } @@ -342,8 +342,8 @@ impl Ff<'_, '_> { let planes = if field.four_state && self.m.four_state { let (value, mask) = self.container_split(value); vec![ - (0, self.complement(value)), - (field.bytes(), self.complement(mask)), + (0, self.complement(value, field.width)), + (field.bytes(), self.complement(mask, field.width)), ] } else { let known = self.b.alloc_bit(field.width as usize, false); @@ -363,10 +363,19 @@ impl Ff<'_, '_> { /// A 4-state property holds the complement of its value and mask planes, /// so the zeroed bytes of a new object read as X (IEEE 1800-2023 6.8). - fn complement(&mut self, plane: RegisterId) -> RegisterId { + /// Bits past `width` stay zero, so a default value is all zero bytes. + fn complement(&mut self, plane: RegisterId, width: u32) -> RegisterId { let complement = self.b.alloc_bit(64, false); self.b .emit(SIRInstruction::Unary(complement, UnaryOp::BitNot, plane)); - complement + let bits = self.constant64(u64::MAX >> (64 - width.min(64))); + let masked = self.b.alloc_bit(64, false); + self.b.emit(SIRInstruction::Binary( + masked, + complement, + BinaryOp::And, + bits, + )); + masked } } diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index e314531afb4..3e2ffb06f60 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -374,6 +374,23 @@ fn element_value( value }) } +/// `$`, the last index of queue `receiver` of type `target`, read in an +/// index of an element of it. A read evaluates the receiver again for the +/// size, so a receiver with a side effect, such as `m[f()]`, could name +/// another queue. +fn last_index(target: &ContainerType, receiver: Expr) -> Converted { + if inlining::effectful(&receiver) { + return Err(unsupported( + "`$` index of a queue read through an expression with a side effect", + )); + } + Ok(Expr::Binary { + left: Box::new(call(ContainerOp::Size, target.layout, vec![receiver])), + op: BinaryOp::Sub, + right: Box::new(Expr::Literal("1".into())), + }) +} + fn index_value( id: ExprId, base: ExprId, @@ -411,15 +428,7 @@ fn index_value( if name.spelling == "$" && matches!(target.layout.kind, ContainerKind::Queue { .. }) => { - Expr::Binary { - left: Box::new(call( - ContainerOp::Size, - target.layout, - vec![expression_binding::value(base, native, tree, dims)?], - )), - op: BinaryOp::Sub, - right: Box::new(Expr::Literal("1".into())), - } + last_index(target, expression_binding::value(base, native, tree, dims)?)? } ExprKind::Binary { left, @@ -535,20 +544,10 @@ pub(super) fn value( expression_binding::value(*expression, native, tree, dims)?, match index { Some(index) => index_value(index, *expression, tree, dims, &target)?, - None => Expr::Binary { - left: Box::new(call( - ContainerOp::Size, - target.layout, - vec![expression_binding::value( - *expression, - native, - tree, - dims, - )?], - )), - op: BinaryOp::Sub, - right: Box::new(Expr::Literal("1".into())), - }, + None => last_index( + &target, + expression_binding::value(*expression, native, tree, dims)?, + )?, }, ], ), diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 8077603163b..64f18a95eb0 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -436,7 +436,9 @@ pub(in crate::ast) fn bind_native( { // A default that is not a structure of the member's type // applies to each of its members (IEEE 1800-2023 10.9.2). - if default && unpacked_structs::native_struct(id, native, tree, dims)?.is_none() + if default + && !unpacked_structs::native_struct(id, native, tree, dims)? + .is_some_and(|value| value.same_type(&aggregate)) { let members = aggregate.members(); jobs.push(Job::Finish { diff --git a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs index 19536904eae..180579d16b2 100644 --- a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs @@ -252,8 +252,13 @@ pub(in crate::ast) fn native_struct( ty.unpacked_struct().cloned() } // A class property of unpacked structure type. - None => expression_binding::object_aggregate_property(tree, id, native, dims)? - .and_then(|(aggregate, _, _)| aggregate.r#type.unpacked_struct().cloned()), + None if let Some((aggregate, _, _)) = + expression_binding::object_aggregate_property(tree, id, native, dims)? => + { + aggregate.r#type.unpacked_struct().cloned() + } + // An element popped by `q.pop_front` without parentheses. + None => containers::native_struct_element(id, native, tree, dims)?, }, ExprKind::Conditional { then_expression, diff --git a/crates/celox/tests/frontends/systemverilog/containers.rs b/crates/celox/tests/frontends/systemverilog/containers.rs index 343428e4ace..af6415f0527 100644 --- a/crates/celox/tests/frontends/systemverilog/containers.rs +++ b/crates/celox/tests/frontends/systemverilog/containers.rs @@ -108,6 +108,52 @@ sv_backends! { } } +#[test] +fn dollar_indices_reject_receivers_with_side_effects() { + // `$` reads the queue's size through the receiver again; with a call in + // the receiver, the two reads could name different queues. + for read in ["m[next_index()][$]", "m[next_index()][$ - 1]"] { + let source = format!( + "module Top; int m[int][$]; int calls; int v; + function automatic int next_index(); calls++; return calls; endfunction + initial v = {read}; + endmodule" + ); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("dollar-receiver.sv"))], + "Top", + ) + .build_cranelift() + .err() + .unwrap_or_else(|| panic!("`{read}` must be rejected")) + .to_string(); + assert!( + error.contains("`$` index of a queue read through"), + "{read}: {error}" + ); + } + // An explicit size query is a read of its own: both calls are made. + let source = r#"module Top(output int value); + int m[int][$]; + int calls; + int v; + function automatic int next_index(); calls++; return calls; endfunction + initial begin + m[1] = '{10, 11, 12}; + m[2] = '{20, 21}; + v = m[next_index()][m[next_index()].size() - 1]; + value = calls; + end + endmodule"#; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("explicit.sv"))], "Top") + .build_cranelift() + .unwrap(); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(2u8)); +} + #[test] fn container_element_events_reject_mutating_index_calls() { for event in ["q.pop_front", "q[q.pop_front()]", "q[q.pop_back]"] { diff --git a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs index dfd2fee522c..9db470da720 100644 --- a/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs +++ b/crates/celox/tests/frontends/systemverilog/unpacked_structs.rs @@ -341,6 +341,68 @@ sv_backends! { let value = sim.signal("value"); assert_eq!(sim.get(value), BigUint::from(1231u16)); } + fn structure_defaults_descend_to_members_of_their_type(sim) { + @setup { + let source = r#"module Top(output int value); + typedef struct { int n; string s; } A; + typedef struct { A x; A z; } B; + typedef struct { B b; A y; } C; + initial begin + A a; + C c; + a = '{3, "abc"}; + c = '{default: a}; + value = c.b.x.n * 1000 + c.b.z.s.len() * 100 + c.y.n * 10; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(3330u16)); + } + fn queue_pops_without_parentheses_are_whole_elements(sim) { + @setup { + let source = r#"module Top(output int value); + typedef struct { int a; string s; } row_t; + initial begin + row_t q[$]; + row_t r; + q = '{'{1, "a"}, '{2, "bb"}, '{3, "ccc"}}; + r = q.pop_front; + value = r.a * 10 + r.s.len(); + r = q.pop_back; + value = value * 100 + r.a * 10 + r.s.len() + q.size() * 1000; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top"); + sim.run_until(0).unwrap(); + let value = sim.signal("value"); + assert_eq!(sim.get(value), BigUint::from(2133u16)); + } + fn equal_four_state_record_updates_preserve_event_waits(sim) { + @setup { + let source = r#"`timescale 1ns/1ns + module Top(output bit done); + typedef struct { string name; logic flag; } row_t; + row_t d[]; + int count, before_count; + initial begin + d = new[1]; + #1 before_count = count; + d[0] = d[0]; + #1 done = count == before_count && $isunknown(d[0].flag); + end + always @(d) count = count + 1; + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("struct.sv"))], "Top") + .four_state(true); + sim.run_until(3).unwrap(); + let done = sim.signal("done"); + assert_eq!(sim.get(done), BigUint::from(1u8)); + } fn unpacked_struct_module_variables(sim) { @case "unpacked_structs::module_variables"; }