From f3f8a84b864e0e035b848cafded1a528e1f74d95 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 01:57:15 +0900 Subject: [PATCH] feat(sv)!: support integral array reduction methods Array calls such as values.sum and values.product() now evaluate for one-dimensional fixed integral arrays, dynamic arrays, queues and associative arrays. Preserve element width, signedness, packed query shape and X/Z propagation (IEEE 1800-2023 7.12.3), including overflow before widening to an assignment destination. Accept ordinary and discarded calls. Empty inputs use operation identities: product returns one, bitwise AND returns all bits set at the element width, and sum/OR/XOR return zero. Opt into the legacy all-zero behavior with SimulatorBuilder::legacy_empty_reductions(true) or AnalysisOptions::legacy_empty_reductions. The setting is local to each compilation and is encoded in the generated IR/native image. Nonempty results are identical in both modes. The current TypeScript API has no direct SV source compilation entry, so this option is exposed through Rust/frontend APIs. Use balanced expression trees for fixed arrays and heap traversal loops for dynamic containers. Add six shared cases across native, parallel native, Cranelift, parallel Cranelift and WASM. API regressions alternate identical source between default/legacy/default modes in two/four-state execution, exercise mixed hierarchies and round-trip both modes through native images. with expressions, iterator arguments, multidimensional unpacked receivers, nonintegral elements and array expression receivers remain unsupported. Five unmodified upstream reduction simulation cases pass the official sv-tests runner in both state modes at revision db159ad8e9cbbd62036569d240153f753258f640. Update exactly those ten expectations from fail to pass; preserve the other 3,290 rows. These upstream cases are nonempty and do not validate empty-input semantics. This was a focused run, not a full-corpus rerun. Rebase integration preserves the merged #2178 optional-parentheses support, packed pop-result queries, discarded container calls and existing shared cases. Validation: - Common SV suite: 5,712 passed, 20 existing ignored. Latest container suite: 141 passed, including the six shared cases and compatibility/image API tests. - Analyzer/frontend/simulator units: 839 / 8 / 234 passed, with 3 existing analyzer ignores. Default-feature simulator units: 151 passed. - Debug NAPI build and JS integration: 435 passed across 16 files. - Official upstream reduction cases: 10 simulation passes using the release driver; expectation/runner aggregate tests: 5 passed. - Affected-crate all-targets Clippy with -D warnings, cargo fmt --all -- --check and git diff --check passed. - The full SV suite, affected units and Clippy above were rerun after rebasing onto master with #2178 and the #2171 analyzer optimization. - The optional no-host check (--no-default-features --features systemverilog) fails in the unchanged SV parameter diagnostic: CodegenError::message is host-runtime-only. Host builds and standalone frontend units pass. Independent checks retain their assertions and exclusions: - Verilator 5.052: 1 pass, 2 mismatches, 1 compile error, 2 four-state adapter unsupported. Differences include the default empty identities (its empty product/AND return zero), fixed-array arithmetic widened by assignment or comparison context, and parser rejection of void-cast reduction calls. - Icarus 13.0: all six have compile errors; no independent passes claimed. - xezim 0.11.3: all six compile, 1 passes and 5 mismatch. Standalone probes reproduce negative-range fixed-array reduction, X/Z and packed query differences; its empty product is one but empty AND is zero. BREAKING CHANGE: ContainerOp adds seven reduction variants. AnalysisOptions and SimulatorOptions add a legacy_empty_reductions field; downstream exhaustive matches and full struct literals must account for these additions. Latest master synchronization preserves both reduction and logical-implication conformance notes. Revalidated 141 container tests including compatibility and native-image regressions, 839 analyzer tests (three existing ignores), affected-crate Clippy and formatting. Shared cases and external adapters are unchanged by this synchronization. Change-Id: Iec0f1a95026120fdb95b50e2eccea9cfc86bed6e --- conformance/sv-tests/README.md | 16 ++ conformance/sv-tests/expected.tsv | 20 +-- .../src/lowering/ff/containers.rs | 118 +++++++++++++++ crates/celox-sv-analyzer/src/ast.rs | 1 + .../src/ast/array_reductions.rs | 142 ++++++++++++++++++ crates/celox-sv-analyzer/src/ast/case.rs | 2 +- .../src/ast/dimensions/query_binding.rs | 4 + .../src/ast/expression_binding/direct.rs | 4 + .../celox-sv-analyzer/src/ast/procedural.rs | 11 ++ .../celox-sv-analyzer/src/ast/timescales.rs | 4 + crates/celox-sv-analyzer/src/lib.rs | 3 + .../celox-sv-analyzer/src/system_functions.rs | 29 +++- .../src/sv/cases/containers.vtest | 127 ++++++++++++++++ crates/celox/src/diagnostic_policy.rs | 2 + crates/celox/src/parser.rs | 6 +- crates/celox/src/simulator/builder.rs | 38 ++++- .../frontends/systemverilog/containers.rs | 111 ++++++++++++++ docs/guide/systemverilog-reference.md | 17 ++- 18 files changed, 637 insertions(+), 18 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/array_reductions.rs diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 8499d376339..d1f63002052 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -172,6 +172,22 @@ method changes above changed only these twelve verdicts, with no passing case regressing: 1,208 cases pass in 2state and 1,219 in 4state. Shared tests also cover short-circuiting and unknown operands (IEEE 1800-2023 11.4.7). +Integral array reductions (7.12.3) support `sum`, `product`, `and`, `or` and +`xor`, with or without empty parentheses. The five unmodified +`chapter-7/arrays/unpacked/reduction-methods` simulation cases pass the +official runner in both state modes at the pinned revision. Only those ten +reviewed expectations change from `fail` to `pass`; this is a focused run, +not a new full-corpus measurement. Shared regressions also exercise fixed +arrays, queues, integral- and string-indexed associative arrays, element-width +overflow, signed results, packed type queries and four-state propagation. +Empty reductions use the operation identity (`product`: one, `and`: all ones, +`sum` / `or` / `xor`: zero). An explicit `legacy_empty_reductions` build option +selects zero for all empty reductions. These empty-input cases are covered by +shared and simulator API regressions; the five upstream cases use nonempty +arrays and do not distinguish these modes. +`with` expressions, iterator arguments and +multidimensional unpacked receivers remain unsupported. + ## Running locally Use the locked development shell and install the pinned [`requirements.txt`](requirements.txt) in a Python environment. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 71a981ebf40..ea11ba4ad9e 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1383,16 +1383,16 @@ chapter-7/arrays/unpacked/ordering-methods/shuffle.sv 2state fail chapter-7/arrays/unpacked/ordering-methods/shuffle.sv 4state fail chapter-7/arrays/unpacked/ordering-methods/sort.sv 2state fail chapter-7/arrays/unpacked/ordering-methods/sort.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/and.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/and.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/or.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/or.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/product.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/product.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/sum.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/sum.sv 4state fail -chapter-7/arrays/unpacked/reduction-methods/xor.sv 2state fail -chapter-7/arrays/unpacked/reduction-methods/xor.sv 4state fail +chapter-7/arrays/unpacked/reduction-methods/and.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/and.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/or.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/or.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/product.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/product.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/sum.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/sum.sv 4state pass +chapter-7/arrays/unpacked/reduction-methods/xor.sv 2state pass +chapter-7/arrays/unpacked/reduction-methods/xor.sv 4state pass chapter-7/arrays/unpacked/slice-equality.sv 2state pass chapter-7/arrays/unpacked/slice-equality.sv 4state pass chapter-7/arrays/unpacked/slice.sv 2state pass diff --git a/crates/celox-frontend-sv/src/lowering/ff/containers.rs b/crates/celox-frontend-sv/src/lowering/ff/containers.rs index b4cb6765076..55e4da17f15 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/containers.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/containers.rs @@ -37,6 +37,9 @@ impl Ff<'_, '_> { string_key, ); let code = |opcode| encode(opcode, parameter); + if op.reduction().is_some() { + return self.container_reduction(op, layout, &args[0], parameter); + } let zero = self.constant64(0); let (width, signed) = op.result_type(layout); let element_result = matches!(op, Get | PopFront | PopBack); @@ -298,6 +301,121 @@ impl Ff<'_, '_> { Ok(sv::ir::Expr::Ident(name)) } + fn container_reduction( + &mut self, + op: ContainerOp, + layout: ContainerLayout, + receiver: &sv::ir::Expr, + parameter: u64, + ) -> Result { + let width = layout.width as usize; + let four_state = !layout.two_state && self.m.four_state; + let alloc = |b: &mut SIRBuilder| { + if four_state { + b.alloc_logic(width) + } else { + b.alloc_bit(width, layout.signed) + } + }; + let code = |opcode| encode(opcode, parameter); + // Keep one immutable snapshot of the receiver throughout the traversal. + let handle = self.handle(receiver)?; + let zero = self.constant64(0); + let one = self.constant64(1); + let length = self.heap_call(code(heap::LEN), &[handle]); + let associative = matches!(layout.kind, ContainerKind::Associative { .. }); + let first = if associative { + self.heap_call(code(heap::FIRST), &[handle, zero]) + } else { + zero + }; + let seed = alloc(&mut self.b); + let identity = match op { + ContainerOp::ReduceProduct | ContainerOp::LegacyReduceProduct => BigUint::from(1u8), + ContainerOp::ReduceAnd | ContainerOp::LegacyReduceAnd => { + (BigUint::from(1u8) << width) - BigUint::from(1u8) + } + _ => BigUint::zero(), + }; + self.b + .emit(SIRInstruction::Imm(seed, SIRValue::new(identity))); + let remaining = self.b.alloc_bit(64, false); + let key = self.b.alloc_bit(64, false); + let accumulator = alloc(&mut self.b); + let header = self.b.new_block_with(vec![remaining, key, accumulator]); + let body = self.b.new_block(); + let result = alloc(&mut self.b); + let exit = self.b.new_block_with(vec![result]); + self.b + .seal_block(SIRTerminator::Jump(header, vec![length, first, seed])); + self.b.switch_to_block(header); + let more = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(more, remaining, BinaryOp::Ne, zero)); + self.b.seal_block(SIRTerminator::Branch { + cond: more, + true_block: (body, Vec::new()), + false_block: (exit, vec![accumulator]), + }); + self.b.switch_to_block(body); + let raw = self.heap_call(code(heap::GET), &[handle, key, zero]); + let mask = self.heap_call(code(heap::GET_MASK), &[handle, key, zero]); + let element = self.container_join(raw, mask, width, four_state); + let combined = alloc(&mut self.b); + let binary = match op { + ContainerOp::ReduceSum => BinaryOp::Add, + ContainerOp::ReduceProduct | ContainerOp::LegacyReduceProduct => BinaryOp::Mul, + ContainerOp::ReduceAnd | ContainerOp::LegacyReduceAnd => BinaryOp::And, + ContainerOp::ReduceOr => BinaryOp::Or, + ContainerOp::ReduceXor => BinaryOp::Xor, + _ => unreachable!("reduction method"), + }; + self.b.emit(SIRInstruction::Binary( + combined, + accumulator, + binary, + element, + )); + let next = if associative { + self.heap_call(code(heap::NEXT), &[handle, key]) + } else { + let next = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Binary(next, key, BinaryOp::Add, one)); + next + }; + let fewer = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Binary(fewer, remaining, BinaryOp::Sub, one)); + self.b + .seal_block(SIRTerminator::Jump(header, vec![fewer, next, combined])); + self.b.switch_to_block(exit); + // The accumulator starts at the operation's identity. Only explicit + // legacy compatibility replaces an empty product/AND with zero. + let value = if matches!( + op, + ContainerOp::LegacyReduceProduct | ContainerOp::LegacyReduceAnd + ) { + let empty = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(empty, length, BinaryOp::Eq, zero)); + let empty_value = alloc(&mut self.b); + self.b + .emit(SIRInstruction::Imm(empty_value, SIRValue::new(0u8))); + let value = alloc(&mut self.b); + self.b + .emit(SIRInstruction::Mux(value, empty, empty_value, result)); + value + } else { + result + }; + let (temp, name) = self + .m + .temp("array_reduction", width, layout.signed, four_state); + self.store(temp, SIROffset::Static(0), width, value); + Ok(sv::ir::Expr::Ident(name)) + } + fn container_element( &mut self, expr: &sv::ir::Expr, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 1a54e524fcd..9f87f573325 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -163,6 +163,7 @@ mod port_owners; mod timing; mod type_binding; pub(crate) use parameters::unbounded_parameter_marker; +mod array_reductions; mod containers; mod patterns; mod procedural; diff --git a/crates/celox-sv-analyzer/src/ast/array_reductions.rs b/crates/celox-sv-analyzer/src/ast/array_reductions.rs new file mode 100644 index 00000000000..f9a69653396 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/array_reductions.rs @@ -0,0 +1,142 @@ +//! Integral unpacked array reductions (IEEE 1800-2023 7.12.3). +use super::*; +use celox_sv_syntax::{Declarations, ExprId, ExprKind}; +use system_functions::ContainerOp; + +pub(super) fn bind( + id: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Converted> { + let callee = match &native.expression(id).kind { + ExprKind::Call { expression, .. } => *expression, + _ => id, + }; + let ExprKind::Member { + expression: base, + separator, + name, + } = &native.expression(callee).kind + else { + return Ok(None); + }; + if separator != "." { + return Ok(None); + } + let mut op = match name.spelling.as_str() { + "sum" => ContainerOp::ReduceSum, + "product" => ContainerOp::ReduceProduct, + "and" => ContainerOp::ReduceAnd, + "or" => ContainerOp::ReduceOr, + "xor" => ContainerOp::ReduceXor, + _ => return Ok(None), + }; + if timescales::analysis_options(&tree.state.timescales).legacy_empty_reductions { + op = match op { + ContainerOp::ReduceProduct => ContainerOp::LegacyReduceProduct, + ContainerOp::ReduceAnd => ContainerOp::LegacyReduceAnd, + _ => op, + }; + } + let ExprKind::Name(receiver) = &native + .expression(expression_binding::ungroup(*base, native)) + .kind + else { + return Ok(None); + }; + let receiver = instances::normalize_identifier(&receiver.spelling); + let Some(shape) = dims.get(&receiver) else { + return Ok(None); + }; + if shape.container.is_none() && shape.unpacked.is_empty() { + return Ok(None); + } + if let ExprKind::Call { arguments, .. } = &native.expression(id).kind + && !arguments.is_empty() + { + return Err(unsupported( + "array reduction arguments require a with expression", + )); + } + if let Some(container) = shape.container.as_deref() { + if container.layout.handle.is_some() { + return Err(unsupported("array reduction requires integral elements")); + } + return Ok(Some(( + containers::call(op, container.layout, vec![Expr::Ident(receiver)]), + procedural::dimensions_from_type(&container.element), + ))); + } + if shape.unpacked.len() != 1 || shape.real || shape.string || shape.class.is_some() { + return Err(unsupported( + "array reduction requires one-dimensional integral elements", + )); + } + let width = shape + .packed + .iter() + .try_fold(1usize, |width, dim| { + width.checked_mul( + usize::try_from(eval_ast_const_expr( + &tree.state, + &dim.width, + &dims.const_env, + )?) + .ok()?, + ) + }) + .ok_or_else(|| unsupported("array reduction element width"))?; + let count = usize::try_from( + eval_ast_const_expr(&tree.state, &shape.unpacked[0].width, &dims.const_env) + .ok_or_else(|| unsupported("array reduction length"))?, + ) + .map_err(|_| unsupported("array reduction length"))?; + let elements = (0..count).map(|index| Expr::Select { + expr: Box::new(Expr::Ident(receiver.clone())), + msb: ConstExpr::Literal(((index + 1) * width - 1).to_string()), + lsb: ConstExpr::Literal((index * width).to_string()), + signed: shape.signed, + }); + let identity = match op { + ContainerOp::ReduceProduct | ContainerOp::LegacyReduceProduct => format!("{width}'d1"), + ContainerOp::ReduceAnd | ContainerOp::LegacyReduceAnd => { + format!("{width}'b{}", "1".repeat(width)) + } + _ => format!("{width}'d0"), + }; + let mut level = std::iter::once(Expr::Literal(identity)) + .chain(elements) + .collect::>(); + // A balanced tree keeps large fixed arrays from making expression depth + // proportional to the number of elements. + while level.len() > 1 { + let mut next = Vec::with_capacity(level.len().div_ceil(2)); + let mut values = level.into_iter(); + while let Some(left) = values.next() { + next.push(if let Some(right) = values.next() { + Expr::Binary { + left: Box::new(left), + op: op.reduction().expect("reduction method").into(), + right: Box::new(right), + } + } else { + left + }); + } + level = next; + } + let result = level.pop().expect("reduction identity"); + // A method result is self-determined: assignment context must not widen + // intermediate additions or products past the element type. + let mut result_shape = shape.clone(); + result_shape.unpacked.clear(); + Ok(Some(( + Expr::Resize { + expr: Box::new(result), + width, + signed: shape.signed, + }, + result_shape, + ))) +} diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index de0eb38e4c8..28701f62ad3 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -73,7 +73,7 @@ pub(super) fn expr_is_two_state( callee: Callee::Object(op), .. } => { - !matches!(**op, ObjectOp::Container { op: ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal, layout } if !layout.two_state) + !matches!(**op, ObjectOp::Container { op, layout } if !layout.two_state && (op.reduction().is_some() || matches!(op, ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal))) } Expr::Call { callee: Callee::Subroutine(name), diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index aefd8a330d5..576659c6776 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -715,6 +715,10 @@ pub(in crate::ast) fn shape( while let Some(job) = jobs.pop() { match job { Job::Enter(id) => { + if let Some((_, shape)) = array_reductions::bind(id, native, tree, context)? { + values.push(shape); + continue; + } let callee = match native.expression(id).kind { ExprKind::Call { expression, .. } => expression, _ => id, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index af888e0b3bf..5bbe5cd3dc5 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -296,6 +296,10 @@ pub(in crate::ast) fn bind_value( )); } } + if let Some((value, _)) = array_reductions::bind(id, native, tree, dimensions)? { + values.push(value); + continue; + } if let Some(value) = containers::value(id, native, tree, dimensions, false)? { values.push(value); continue; diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index ebd7f92adcb..37b5b938a0d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1199,6 +1199,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); + if let Some((mut value, _)) = array_reductions::bind(root, native, self.tree, &self.dims)? { + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } if let Some(mut value) = containers::value(root, native, self.tree, &self.dims, true)? { self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); @@ -1236,6 +1240,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { let query_root = expression_binding::call_statement_root(root, discarded, self.tree.declarations())?; + if discarded + && let Some((mut value, _)) = + array_reductions::bind(query_root, native, self.tree, &self.dims)? + { + self.rename_expr(&mut value); + return Ok(vec![Stmt::Eval(value)]); + } if discarded && let Some(mut value) = containers::value(query_root, native, self.tree, &self.dims, true)? diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 35f6c2a86f0..b15b24fd85d 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -122,6 +122,10 @@ pub(super) fn revision(state: &State) -> &generate::Revision { &state.revision } +pub(super) fn analysis_options(state: &State) -> crate::AnalysisOptions { + state.design.borrow().design.options +} + pub(super) fn with_interface_instance( state: &State, name: &str, diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 07f42be06d6..53a7d6d08f1 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -48,6 +48,9 @@ pub const DIV_ZERO_UNKNOWN_LITERAL: &str = "$celox_div_zero_unknown"; #[derive(Debug, Clone, Copy, Default)] pub struct AnalysisOptions { pub allow_mixed_timescales: bool, + /// Compatibility mode: return zero for every empty array reduction, + /// rather than the product/bitwise-AND identity. Disabled by default. + pub legacy_empty_reductions: bool, /// Default unit/precision exponents; precision also bounds global resolution. pub default_timescale: Option<(i32, i32)>, } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index d580fad8947..f5340fec3a0 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -844,6 +844,13 @@ pub enum ContainerKind { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ContainerOp { + ReduceSum, + ReduceProduct, + ReduceAnd, + LegacyReduceProduct, + LegacyReduceAnd, + ReduceOr, + ReduceXor, Equal, CaseEqual, New, @@ -866,6 +873,17 @@ pub enum ContainerOp { Prev, } impl ContainerOp { + pub fn reduction(self) -> Option { + use crate::ir::BinaryOp; + match self { + Self::ReduceSum => Some(BinaryOp::Add), + Self::ReduceProduct | Self::LegacyReduceProduct => Some(BinaryOp::Mul), + Self::ReduceAnd | Self::LegacyReduceAnd => Some(BinaryOp::BitAnd), + Self::ReduceOr => Some(BinaryOp::BitOr), + Self::ReduceXor => Some(BinaryOp::BitXor), + _ => None, + } + } pub fn mutates(self) -> bool { matches!( self, @@ -882,7 +900,16 @@ impl ContainerOp { pub fn result_type(self, layout: ContainerLayout) -> (usize, bool) { match self { Self::Equal | Self::CaseEqual => (1, false), - Self::Get | Self::PopFront | Self::PopBack => (layout.width as usize, layout.signed), + Self::Get + | Self::PopFront + | Self::PopBack + | Self::ReduceSum + | Self::ReduceProduct + | Self::ReduceAnd + | Self::LegacyReduceProduct + | Self::LegacyReduceAnd + | Self::ReduceOr + | Self::ReduceXor => (layout.width as usize, layout.signed), Self::Size | Self::Exists | Self::First | Self::Last | Self::Next | Self::Prev => { (32, true) } diff --git a/crates/celox-test-suite/src/sv/cases/containers.vtest b/crates/celox-test-suite/src/sv/cases/containers.vtest index 5a1010c002f..b0c27a2ac73 100644 --- a/crates/celox-test-suite/src/sv/cases/containers.vtest +++ b/crates/celox-test-suite/src/sv/cases/containers.vtest @@ -481,3 +481,130 @@ module Top(output bit [4:0] flags); endmodule "#) (top Top) (run_until 0) (assert_eq flags 31)) + +(case array_reduction_fixed + (source "array_reductions.sv" #" +module Top(output bit [7:0] flags); + byte ascending[-2:1], descending[5:2]; + bit [128:0] wide[2]; + bit [3:0] nibbles[3]; + int result; + initial begin + ascending = '{1, 2, 3, 4}; descending = '{1, 3, 5, 7}; + flags[0] = ascending.sum == 10 && ascending.product() == 24; + flags[1] = ascending.or() == 7 && ascending.xor == 4; + flags[2] = descending.and == 1 && descending.sum() == 16; + ascending = '{100, 100, 100, 100}; + result = ascending.sum(); + flags[3] = result == -112 && $bits(ascending.sum()) == 8; + ascending = '{-2, 3, 1, 1}; + flags[4] = ascending.product == -6 && ascending.sum == 3; + wide = '{129'h100000000000000000000000000000001, 129'h100000000000000000000000000000002}; + flags[5] = wide.sum() == 129'h200000000000000000000000000000003; + flags[6] = wide.xor() == 3 && wide.and() == 129'h100000000000000000000000000000000; + nibbles = '{15, 2, 3}; + flags[7] = nibbles.sum() == 4 && nibbles.product() == 10 && $bits(nibbles.sum) == 4; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case array_reduction_dynamic_queue + (source "array_reductions.sv" #" +module Top(output bit [7:0] flags); + byte values[], q[$]; + int result; + initial begin + values = '{1, 2, 3, 4}; q = {1, 3, 5, 7}; + flags[0] = values.sum == 10 && values.product() == 24; + flags[1] = values.and() == 0 && values.or == 7 && values.xor == 4; + flags[2] = q.sum() == 16 && q.product == 105 && q.and() == 1; + flags[3] = q.or == 7 && q.xor() == 0 && q.size() == 4 && q[0] == 1; + values = '{100, 100, 100, 100}; result = values.sum(); + flags[4] = result == -112 && $bits(values.sum) == 8; + q = {-2, 3}; + flags[5] = q.product == -6 && q.sum() == 1; + values.delete(); q.delete(); + flags[6] = values.sum == 0 && values.product == 1 && values.and == -1; + flags[7] = q.or() == 0 && q.xor() == 0 && q.size() == 0; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 255)) + +(case array_reduction_associative + (source "array_reductions.sv" #" +module Top(output bit [3:0] flags); + int numbers[int], words[string]; + initial begin + numbers[-10] = 1; numbers[0] = 3; numbers[1000] = 5; + flags[0] = numbers.sum == 9 && numbers.product() == 15 && numbers.and == 1; + flags[1] = numbers.or() == 7 && numbers.xor == 7 && numbers.num() == 3; + words["beta"] = 2; words["alpha"] = 4; words[""] = 6; + flags[2] = words.sum() == 12 && words.product == 48 && words.and() == 0; + flags[3] = words.or == 6 && words.xor() == 0 && words["beta"] == 2; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case array_reduction_four_state + (source "array_reductions.sv" #" +module Top(output bit [5:0] flags); + logic [3:0] fixed_values[2], dynamic_values[], q[$], assoc[int]; + initial begin + fixed_values = '{4'b0x1z, 4'b1010}; + dynamic_values = '{4'b0x1z, 4'b1010}; + q = {4'b0x1z, 4'b1010}; assoc[-1] = 4'b0x1z; assoc[5] = 4'b1010; + flags[0] = fixed_values.and() === 4'b0010 && dynamic_values.and === 4'b0010; + flags[1] = fixed_values.or === 4'b1x1x && q.or() === 4'b1x1x; + flags[2] = fixed_values.xor() === 4'b1x0x && assoc.xor === 4'b1x0x; + flags[3] = fixed_values.sum === 4'bxxxx && dynamic_values.sum() === 4'bxxxx; + flags[4] = q.product === 4'bxxxx && assoc.product() === 4'bxxxx; + fixed_values = '{4'bzzzz, 4'b0000}; dynamic_values = '{4'bzzzz, 4'b1111}; + flags[5] = fixed_values.and === 4'b0000 && dynamic_values.or === 4'b1111; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq flags 63)) + +(case array_reduction_type_queries + (source "array_reductions.sv" #" +module Top(output bit [3:0] flags); + bit [1:0][3:0] fixed_values[2], dynamic_values[]; + bit [7:0] single[1]; + initial begin + fixed_values = '{8'h12, 8'h23}; dynamic_values = '{8'h12, 8'h23}; single = '{8'h35}; + fixed_values.sum(); dynamic_values.product; + void'(fixed_values.xor); void'(dynamic_values.and()); + flags[0] = $bits(fixed_values.sum) == 8 && $bits(dynamic_values.sum()) == 8; + flags[1] = $dimensions(fixed_values.sum()) == 2 && $dimensions(dynamic_values.sum) == 2; + flags[2] = $size(fixed_values.sum) == 2 && $size(dynamic_values.sum(), 2) == 4; + flags[3] = fixed_values.sum() == single.sum && single.product() == 8'h35 && single.and == 8'h35; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 15)) + +(case array_reduction_empty_identities + (source "empty_reductions.sv" #" +module Top(output bit [7:0] flags); + bit [7:0] values[], q[$], numbers[int], words[string]; + bit [63:0] wide[]; + bit single[$]; + logic [7:0] logic_values[]; + initial begin + flags[0] = values.product() == 1 && values.and() == 8'hff; + flags[1] = q.product() == 1 && q.and() == 8'hff; + flags[2] = numbers.product() == 1 && numbers.and() == 8'hff; + flags[3] = words.product() == 1 && words.and() == 8'hff; + flags[4] = wide.product() == 64'd1 && wide.and() == 64'hffffffffffffffff; + flags[5] = single.product() == 1'b1 && single.and() == 1'b1; + flags[6] = values.sum() == 0 && values.or() == 0 && values.xor() == 0; + flags[7] = logic_values.product() === 8'h01 && logic_values.and() === 8'hff; + end +endmodule +"#) + (four_state) + (top Top) (run_until 0) (assert_eq flags 255)) diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index d00d5e69359..87dcd408b98 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -102,10 +102,12 @@ impl DiagnosticPolicy { pub(crate) fn sv_options( &self, timescale: Option, + legacy_empty_reductions: bool, ) -> celox_frontend_sv::AnalysisOptions { celox_frontend_sv::AnalysisOptions { allow_mixed_timescales: self.level("mixed_timescale") != DiagnosticLevel::Error, default_timescale: timescale.map(|scale| (scale.unit, scale.precision)), + legacy_empty_reductions, } } diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index cad4dd76b4c..fd3e655c203 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -591,6 +591,7 @@ pub fn parse_sv( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -619,7 +620,7 @@ pub fn parse_sv( trace.is_some().then_some(&mut frontend_trace), config.allow_inferred_latches, warnings, - diagnostic_policy.sv_options(sv_timescale), + diagnostic_policy.sv_options(sv_timescale, legacy_empty_reductions), force_signals, ) .map_err(|error| match error { @@ -695,6 +696,7 @@ pub fn parse_mixed( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -845,7 +847,7 @@ pub fn parse_mixed( &requests, config.allow_inferred_latches, &mut warnings, - diagnostic_policy.sv_options(sv_timescale), + diagnostic_policy.sv_options(sv_timescale, legacy_empty_reductions), ); let external = match external { Ok(external) => external, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index fbdf012dabb..8060be969e9 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -306,6 +306,7 @@ fn analyze( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], preserve_element_storage_layout: bool, recover_comb_loops: bool, @@ -319,7 +320,7 @@ fn analyze( Vec, ) { #[cfg(not(feature = "systemverilog"))] - let _ = (diagnostic_policy, sv_timescale); + let _ = (diagnostic_policy, sv_timescale, legacy_empty_reductions); symbol_table::clear(); attribute_table::clear(); @@ -401,7 +402,7 @@ fn analyze( sv_sources, Some(&references), &mut sv_probe_warnings, - diagnostic_policy.sv_options(sv_timescale), + diagnostic_policy.sv_options(sv_timescale, legacy_empty_reductions), ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Analyzer(error) => parser::sv_analysis_error(error), @@ -609,6 +610,7 @@ fn analyze( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, preserve_element_storage_layout, testbench_random_seed, component_libraries, @@ -868,6 +870,7 @@ pub fn compile_to_sir_with_diagnostic_policy( &crate::RuntimeDiagnostics::default(), diagnostic_policy, None, + false, &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -990,6 +993,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1025,6 +1029,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1087,6 +1092,7 @@ fn compile_to_sir_with_layout_mode( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1112,6 +1118,7 @@ fn compile_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1190,6 +1197,7 @@ pub fn compile_sv_to_sir( &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), None, + false, crate::backend::memory_layout::MemoryLayoutMode::Packed, false, &[], @@ -1226,6 +1234,7 @@ fn compile_sv_to_sir_with_layout_mode( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, _allow_inferred_latches: bool, force_signals: &[String], @@ -1272,6 +1281,7 @@ fn compile_sv_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, metadata.test.seed, component_libraries, @@ -1380,6 +1390,7 @@ pub fn compile_mixed_to_sir_with_file_dependencies( &crate::RuntimeDiagnostics::default(), &crate::DiagnosticPolicy::default(), None, + false, &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -1419,6 +1430,7 @@ fn compile_mixed_to_sir_with_layout_mode( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1444,6 +1456,7 @@ fn compile_mixed_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1509,6 +1522,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostics: &crate::RuntimeDiagnostics, diagnostic_policy: &crate::DiagnosticPolicy, sv_timescale: Option, + legacy_empty_reductions: bool, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1549,6 +1563,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, injected_manifests, layout_mode, recover_comb_loops, @@ -1575,6 +1590,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, injected_manifests, layout_mode, recover_comb_loops, @@ -1598,6 +1614,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, layout_mode, allow_inferred_latches, force_signals, @@ -1620,6 +1637,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostics, diagnostic_policy, sv_timescale, + legacy_empty_reductions, injected_manifests, layout_mode, recover_comb_loops, @@ -1677,6 +1695,8 @@ mod host { pub diagnostic_policy: crate::DiagnosticPolicy, /// Default SystemVerilog time unit and global scheduler precision. pub sv_timescale: Option, + /// Return zero from every empty SV array reduction for compatibility. + pub legacy_empty_reductions: bool, /// When true, JIT-compiled functions emit trigger detection code for /// edge-based event discovery. Only needed by [`crate::Simulation`]. pub emit_triggers: bool, @@ -1997,6 +2017,7 @@ mod host { diagnostics: Default::default(), diagnostic_policy: Default::default(), sv_timescale: None, + legacy_empty_reductions: false, emit_triggers: false, #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] derived_edge_units: None, @@ -2505,7 +2526,13 @@ mod host { self } - /// Override recoverable compilation diagnostic severities. + /// Use legacy zero results for all empty SV array reductions. + /// By default product returns one and bitwise AND returns all ones. + pub fn legacy_empty_reductions(mut self, enable: bool) -> Self { + self.options.legacy_empty_reductions = enable; + self + } + /// Set default SV timing and contribute its precision to the scheduler. /// Explicit source time declarations retain their units and rounding. pub fn sv_timescale(mut self, timescale: Option) -> Self { @@ -2513,6 +2540,7 @@ mod host { self } + /// Override recoverable compilation diagnostic severities. pub fn diagnostic_policy(mut self, policy: crate::DiagnosticPolicy) -> Self { self.options.diagnostic_policy = policy; self @@ -2888,6 +2916,7 @@ mod host { &self.options.diagnostics, &self.options.diagnostic_policy, self.options.sv_timescale, + self.options.legacy_empty_reductions, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -2914,6 +2943,7 @@ mod host { &self.options.diagnostics, &self.options.diagnostic_policy, self.options.sv_timescale, + self.options.legacy_empty_reductions, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3592,6 +3622,7 @@ mod host { &self.options.diagnostics, &self.options.diagnostic_policy, self.options.sv_timescale, + self.options.legacy_empty_reductions, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3618,6 +3649,7 @@ mod host { &self.options.diagnostics, &self.options.diagnostic_policy, self.options.sv_timescale, + self.options.legacy_empty_reductions, &injected_manifests, layout_mode, !self.options.native_force_support, diff --git a/crates/celox/tests/frontends/systemverilog/containers.rs b/crates/celox/tests/frontends/systemverilog/containers.rs index b00caad9ff0..4dd2b9880bf 100644 --- a/crates/celox/tests/frontends/systemverilog/containers.rs +++ b/crates/celox/tests/frontends/systemverilog/containers.rs @@ -5,6 +5,12 @@ sv_backends! { fn optional_parentheses(sim) { @case "containers::optional_parentheses"; } fn optional_parentheses_queries(sim) { @case "containers::optional_parentheses_queries"; } fn optional_parentheses_four_state(sim) { @case "containers::optional_parentheses_four_state"; } + fn array_reduction_empty_identities(sim) { @case "containers::array_reduction_empty_identities"; } + fn array_reduction_type_queries(sim) { @case "containers::array_reduction_type_queries"; } + fn array_reduction_fixed(sim) { @case "containers::array_reduction_fixed"; } + fn array_reduction_dynamic_queue(sim) { @case "containers::array_reduction_dynamic_queue"; } + fn array_reduction_associative(sim) { @case "containers::array_reduction_associative"; } + fn array_reduction_four_state(sim) { @case "containers::array_reduction_four_state"; } fn queue_argument_side_effects(sim) { @case "containers::queue_argument_side_effects"; } fn queue_argument_four_state(sim) { @case "containers::queue_argument_four_state"; } fn string_associative_foreach(sim) { @case "containers::string_associative_foreach"; } @@ -62,3 +68,108 @@ sv_backends! { assert!(error.contains("negative dynamic array size"), "{error}"); } } + +const EMPTY_REDUCTION_MODES: &str = r#" +module Top(output bit [63:0] dp, da, qp, qa, ap, aa, sp, sa, output bit [3:0] flags); + bit [63:0] values[], q[$], numbers[int], words[string]; + initial begin + dp = values.product(); da = values.and(); + qp = q.product(); qa = q.and(); + ap = numbers.product(); aa = numbers.and(); + sp = words.product(); sa = words.and(); + flags[0] = values.sum() == 0 && values.or() == 0 && values.xor() == 0; + q = {6, 3}; + flags[1] = q.product() == 18 && q.and() == 2; + numbers[-5] = 6; numbers[10] = 3; + flags[2] = numbers.product() == 18 && numbers.and() == 2; + words["alpha"] = 6; words["beta"] = 3; + flags[3] = words.product() == 18 && words.and() == 2; + end +endmodule +"#; + +fn check_empty_reduction_mode(mut sim: celox::Simulation, legacy: bool) { + sim.run_until(0).unwrap(); + for name in ["dp", "qp", "ap", "sp"] { + assert_eq!( + sim.get(sim.signal(name)), + BigUint::from(u8::from(!legacy)), + "{name}, legacy={legacy}" + ); + } + for name in ["da", "qa", "aa", "sa"] { + assert_eq!( + sim.get(sim.signal(name)), + BigUint::from(if legacy { 0 } else { u64::MAX }), + "{name}, legacy={legacy}" + ); + } + assert_eq!(sim.get(sim.signal("flags")), BigUint::from(15u8)); +} + +#[test] +fn empty_reduction_compatibility_is_local_to_each_build() { + // Alternate modes with identical source text, including defaults after opt-in. + for legacy in [false, true, false] { + for four_state in [false, true] { + let build = || { + celox::Simulation::from_sv_sources( + vec![(EMPTY_REDUCTION_MODES, Path::new("empty_modes.sv"))], + "Top", + ) + .legacy_empty_reductions(legacy) + .four_state(four_state) + }; + check_empty_reduction_mode(build().build_interpreter().unwrap(), legacy); + check_empty_reduction_mode(build().build_cranelift().unwrap(), legacy); + check_empty_reduction_mode(build().build_wasm().unwrap(), legacy); + check_empty_reduction_mode(build().build_native().unwrap(), legacy); + check_empty_reduction_mode( + build() + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_native() + .unwrap(), + legacy, + ); + } + } +} + +#[test] +fn empty_reduction_compatibility_survives_native_images() { + for legacy in [false, true] { + let image = celox::Simulation::from_sv_sources( + vec![(EMPTY_REDUCTION_MODES, Path::new("empty_modes.sv"))], + "Top", + ) + .legacy_empty_reductions(legacy) + .compile_native() + .unwrap() + .into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + check_empty_reduction_mode( + celox::Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + legacy, + ); + } +} + +#[test] +fn empty_reduction_compatibility_reaches_mixed_hierarchies() { + for legacy in [false, true] { + let sim = celox::Simulation::from_sources( + vec![("module Unused {}", Path::new("unused.veryl"))], + "Top", + ) + .with_sv_sources(vec![(EMPTY_REDUCTION_MODES, Path::new("empty_modes.sv"))]) + .legacy_empty_reductions(legacy) + .build_native() + .unwrap(); + check_empty_reduction_mode(sim, legacy); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6cb69aeb320..4c7d0db84f9 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -397,8 +397,23 @@ portable state files require a checkpoint instead. Strings and class objects held in elements remain reachable during heap collection. Array assignment copies elements while class handles retain their usual reference semantics. +Integral fixed arrays, dynamic arrays, queues and associative arrays support +`sum`, `product`, `and`, `or` and `xor`, with or without empty parentheses +(IEEE 1800-2023 7.12.3). The result retains the element width and signedness, +including overflow at that width, and propagates four-state unknowns. +Empty reductions return their identities: `product` returns one, `and` returns +all bits set at the element width, and `sum`, `or` and `xor` return zero. +For compatibility with tools using zero for all empty reductions, opt in with +Rust's `SimulatorBuilder::legacy_empty_reductions(true)` or the frontend's +`AnalysisOptions::legacy_empty_reductions`. The default is false. This setting +affects compilation and is preserved in generated native images; it does not +change nonempty reductions. +Fixed arrays may have elements wider than 64 bits. These methods currently +require a one-dimensional array variable; +`with` expressions and iterator arguments remain unsupported. + Multidimensional containers, elements wider than 64 bits, real elements, -wildcard or class keys, slices, array manipulation methods, keyed patterns, +wildcard or class keys, slices, array locator and ordering methods, keyed patterns, container operands within concatenations, compound or nonblocking element assignments, container ports / subroutine parameters / class properties and const containers remain unsupported. A `new[]` initializer currently requires