diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 8499d376339..dc6be16deff 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -164,6 +164,12 @@ the initial 28 upstream checks passed. Arity and void-result rejection remain ch Queue slices, queue operands in concatenations, element-reference persistence, warning diagnostics, and queries on nonintegral pop results remain outside this change's support contract. +Logical equivalence (`<->`) now passes six generated cases in both state modes. +The binary-operator case passes elaboration; the five logical-operator cases +execute simulations and pass their assertions. A full run before the container +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 cover unknown operands and +evaluate both operands exactly once (IEEE 1800-2023 11.4.7). Logical implication (`->`) now passes six generated cases in both state modes. The binary-operator case passes elaboration; the five logical-operator cases @@ -172,6 +178,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..1645eeadf6a 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 @@ -1817,8 +1817,8 @@ generated/binary_op/11.4.6--binary_op_wild_neq.sv 2state pass generated/binary_op/11.4.6--binary_op_wild_neq.sv 4state pass generated/binary_op/11.4.7--binary_op_log_and.sv 2state pass generated/binary_op/11.4.7--binary_op_log_and.sv 4state pass -generated/binary_op/11.4.7--binary_op_log_equiv.sv 2state fail -generated/binary_op/11.4.7--binary_op_log_equiv.sv 4state fail +generated/binary_op/11.4.7--binary_op_log_equiv.sv 2state pass +generated/binary_op/11.4.7--binary_op_log_equiv.sv 4state pass generated/binary_op/11.4.7--binary_op_log_imp.sv 2state pass generated/binary_op/11.4.7--binary_op_log_imp.sv 4state pass generated/binary_op/11.4.7--binary_op_log_or.sv 2state pass @@ -2451,14 +2451,14 @@ generated/keywords/5.6.2--keyword_xnor.sv 2state pass generated/keywords/5.6.2--keyword_xnor.sv 4state pass generated/keywords/5.6.2--keyword_xor.sv 2state pass generated/keywords/5.6.2--keyword_xor.sv 4state pass -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 4state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 4state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 4state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 2state fail -generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 4state fail +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_0.sv 4state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_1.sv 4state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_2.sv 4state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 2state pass +generated/logical_equivalence_operator_sim/11.4.7--logical_equiv_operator_3.sv 4state pass generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_0.sv 2state pass generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_0.sv 4state pass generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_1.sv 2state pass @@ -2647,8 +2647,8 @@ generated/sampled_functions/20.13--steady_gclk.sv 2state fail generated/sampled_functions/20.13--steady_gclk.sv 4state fail generated/simple_logical_operators_sim/11.4.7--simple_and_logical_operator.sv 2state pass generated/simple_logical_operators_sim/11.4.7--simple_and_logical_operator.sv 4state pass -generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 2state fail -generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 4state fail +generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 2state pass +generated/simple_logical_operators_sim/11.4.7--simple_equiv_logical_operator.sv 4state pass generated/simple_logical_operators_sim/11.4.7--simple_impl_logical_operator.sv 2state pass generated/simple_logical_operators_sim/11.4.7--simple_impl_logical_operator.sv 4state pass generated/simple_logical_operators_sim/11.4.7--simple_or_logical_operator.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-sir-opt/src/lib.rs b/crates/celox-sir-opt/src/lib.rs index 57d173ca032..5995c8250ff 100644 --- a/crates/celox-sir-opt/src/lib.rs +++ b/crates/celox-sir-opt/src/lib.rs @@ -1,3 +1,10 @@ +#![cfg_attr( + test, + allow( + clippy::disallowed_macros, + reason = "thread-local verification counters exist only in unit tests; non-test builds enforce the ban" + ) +)] //! Backend-independent SIR optimization policy and pass pipeline. pub type HashMap = fxhash::FxHashMap; diff --git a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/coupled.rs b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/coupled.rs index 46fc7ca20c9..332cdc4d302 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/coupled.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/coupled.rs @@ -20,7 +20,9 @@ pub(super) fn branchify_coupled_state_updates( applied += plans.len(); apply_coupled_state_update_batch(eu, plans, next_block_id, reg_counter); } - + if applied != 0 { + verify_coupled_rewrites(eu); + } applied } @@ -43,9 +45,25 @@ pub(super) fn branchify_coupled_priority_chains( applied += 1; worklist.push_front(merge); } + if applied != 0 { + verify_coupled_rewrites(eu); + } applied } +/// Verify the complete rewrite once, rather than revisiting every unrelated +/// block and definition after each local state update or priority chain. +fn verify_coupled_rewrites(eu: &ExecutionUnit) { + debug_assert_eq!( + { + #[cfg(test)] + super::tests::COUPLED_BATCH_VERIFICATIONS.with(|count| count.set(count.get() + 1)); + eu.verify_result() + }, + Ok(()) + ); +} + fn find_coupled_priority_chain_in_block( eu: &ExecutionUnit, block_id: BlockId, @@ -286,7 +304,6 @@ fn apply_coupled_priority_chain( terminator: original.terminator, }, ); - debug_assert_eq!(eu.verify_result(), Ok(())); merge_id } @@ -758,5 +775,4 @@ fn apply_coupled_state_update_batch( terminator: original.terminator, }, ); - debug_assert_eq!(eu.verify_result(), Ok(())); } diff --git a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests.rs b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests.rs index 51612ab2aad..cf5a8bd9cce 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests.rs @@ -16,6 +16,10 @@ use crate::ir::{InstanceId, RegisterType, SIRValue}; use celox_design::StateObjectId as VarId; use num_bigint::BigUint; +thread_local! { + pub(super) static COUPLED_BATCH_VERIFICATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + fn addr(id: usize) -> RegionedAbsoluteAddr { RegionedAbsoluteAddr { region: 0, diff --git a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests/coupled.rs b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests/coupled.rs index 2c7665abefa..69a38bbc20a 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests/coupled.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_branchify_mux/tests/coupled.rs @@ -1,5 +1,97 @@ use super::*; +#[cfg(debug_assertions)] +#[test] +fn coupled_rewrites_verify_once_across_many_source_blocks() { + const COUNT: usize = 16; + for priority_chain in [false, true] { + let blocks = (0..COUNT) + .map(|lane| { + let base = 6 + lane * 4; + BasicBlock { + id: BlockId(lane), + params: if lane == 0 { + (0..6).map(RegisterId).collect() + } else { + Vec::new() + }, + instructions: vec![ + SIRInstruction::Mux( + RegisterId(base), + RegisterId(0), + RegisterId(4), + RegisterId(2), + ), + SIRInstruction::Mux( + RegisterId(base + 1), + RegisterId(0), + RegisterId(5), + RegisterId(3), + ), + SIRInstruction::Mux( + RegisterId(base + 2), + RegisterId(1), + RegisterId(4), + RegisterId(base), + ), + SIRInstruction::Mux( + RegisterId(base + 3), + RegisterId(1), + RegisterId(5), + RegisterId(base + 1), + ), + store(lane * 2, base + 2), + store(lane * 2 + 1, base + 3), + ], + terminator: if lane + 1 == COUNT { + SIRTerminator::Return + } else { + SIRTerminator::Jump(BlockId(lane + 1), Vec::new()) + }, + } + }) + .collect(); + let mut eu = cfg_unit(6 + COUNT * 4, &[0, 1], blocks); + eu.verify_result().unwrap(); + let counts = count_uses(&eu); + let mut next_block = COUNT; + let mut next_register = 5 + COUNT * 4; + COUPLED_BATCH_VERIFICATIONS.with(|count| count.set(0)); + let applied = if priority_chain { + super::super::coupled::branchify_coupled_priority_chains( + &mut eu, + &counts, + &mut next_block, + &mut next_register, + ) + } else { + super::super::coupled::branchify_coupled_state_updates( + &mut eu, + &counts, + &mut next_block, + &mut next_register, + ) + }; + assert_eq!(applied, COUNT * if priority_chain { 1 } else { 2 }); + assert_eq!(COUPLED_BATCH_VERIFICATIONS.with(|count| count.get()), 1); + eu.verify_result().unwrap(); + assert!(!eu.blocks.values().any(|block| { + block + .instructions + .iter() + .any(|inst| matches!(inst, SIRInstruction::Mux(..))) + })); + assert_eq!( + eu.blocks + .values() + .flat_map(|block| &block.instructions) + .filter(|inst| matches!(inst, SIRInstruction::Store(..))) + .count(), + COUNT * 2 + ); + } +} + #[test] fn branchifies_coupled_state_updates_with_interleaved_conditions() { let mut eu = cfg_unit( diff --git a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_guarded_region_sinking.rs b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_guarded_region_sinking.rs index 06e7d6007f1..6fa73fdf2ae 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_guarded_region_sinking.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/control_flow/pass_guarded_region_sinking.rs @@ -2129,6 +2129,21 @@ fn form_coupled_store_regions(eu: &mut ExecutionUnit) { apply_coupled_store_plan(eu, plan, next_block, &mut reg_counter); next_block += consumed; } + // Plans belong to distinct original blocks and were collected before any + // mutation. Check the completed batch once rather than rescanning every + // unrelated definition after each local rewrite. + verify_coupled_store_batch(eu); +} + +fn verify_coupled_store_batch(eu: &ExecutionUnit) { + debug_assert_eq!( + { + #[cfg(test)] + tests::COUPLED_BATCH_VERIFICATIONS.with(|count| count.set(count.get() + 1)); + eu.verify_result() + }, + Ok(()) + ); } fn best_coupled_store_plan( @@ -2714,7 +2729,6 @@ fn apply_coupled_store_plan( for value in dead_mux_values { eu.register_map.remove(&value); } - debug_assert_eq!(eu.verify_result(), Ok(())); } fn form_same_predicate_regions(eu: &mut ExecutionUnit) { @@ -4097,6 +4111,10 @@ fn instruction_has_effect(inst: &SIRInstruction) -> bool { #[cfg(test)] mod tests { + thread_local! { + pub(super) static COUPLED_BATCH_VERIFICATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + use super::*; use crate::ir::{DomainKind, InstanceId, SIRValue, TriggerIdWithKind}; use celox_design::StateObjectId as VarId; @@ -4561,6 +4579,99 @@ mod tests { assert_eq!(after.blocks, before.blocks); } + #[cfg(debug_assertions)] + #[test] + fn coupled_store_batches_verify_once_and_preserve_all_stores() { + const COUNT: usize = 16; + let mut registers = HashMap::from_iter([ + (RegisterId(0), bit(1)), + (RegisterId(1), bit(8)), + (RegisterId(2), bit(8)), + ]); + let mut blocks = HashMap::default(); + for lane in 0..COUNT { + let base = 3 + lane * 11; + let reg = |offset| RegisterId(base + offset); + for offset in 0..11 { + registers.insert(reg(offset), bit(8)); + } + let mut instructions = vec![SIRInstruction::Binary( + reg(0), + RegisterId(1), + BinaryOp::Mul, + RegisterId(1), + )]; + for offset in 1..7 { + instructions.push(SIRInstruction::Binary( + reg(offset), + reg(offset - 1), + BinaryOp::Mul, + RegisterId(1), + )); + } + instructions.extend([ + SIRInstruction::Imm(reg(7), SIRValue::new(85u8)), + SIRInstruction::Binary(reg(8), reg(6), BinaryOp::Add, RegisterId(2)), + SIRInstruction::Mux(reg(9), RegisterId(0), reg(6), reg(7)), + SIRInstruction::Mux(reg(10), RegisterId(0), reg(8), reg(7)), + SIRInstruction::Store( + address(100 + lane * 2), + SIROffset::Static(0), + 8, + reg(9), + vec![], + vec![], + ), + SIRInstruction::Store( + address(101 + lane * 2), + SIROffset::Static(0), + 8, + reg(10), + vec![], + vec![], + ), + ]); + insert_block( + &mut blocks, + lane, + if lane == 0 { + vec![RegisterId(0), RegisterId(1), RegisterId(2)] + } else { + vec![] + }, + instructions, + if lane + 1 == COUNT { + SIRTerminator::Return + } else { + SIRTerminator::Jump(BlockId(lane + 1), vec![]) + }, + ); + } + let mut eu = ExecutionUnit { + entry_block_id: BlockId(0), + blocks, + register_map: registers, + }; + eu.verify_result().unwrap(); + let before = eu.clone(); + COUPLED_BATCH_VERIFICATIONS.with(|count| count.set(0)); + form_coupled_store_regions(&mut eu); + assert_eq!(COUPLED_BATCH_VERIFICATIONS.with(|count| count.get()), 1); + assert_eq!( + eu.blocks.len(), + COUNT * 4, + "every independent store group should be transformed" + ); + eu.verify_result().unwrap(); + for condition in [0, 1] { + for input in [0, 1] { + let expected = execute_with_inputs(&before, condition, input, 7); + let actual = execute_with_inputs(&eu, condition, input, 7); + assert_eq!(actual, expected); + } + } + } + #[test] fn coupled_stores_recover_the_complete_shared_priority_spine() { let mut register_map = HashMap::default(); 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/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index ada0f98cb56..881680ca018 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -125,7 +125,9 @@ fn bind_in_context( operator, right, } => { - if operator != "->" && constants::binary_op_from_text(operator).is_none() { + if !matches!(operator.as_str(), "->" | "<->") + && constants::binary_op_from_text(operator).is_none() + { return Ok(None); } jobs.push(Job::Binary(operator.clone())); @@ -366,7 +368,7 @@ fn bind_in_context( Job::Binary(op) => { let right = values.pop().ok_or_else(disagreement)?; let left = values.pop().ok_or_else(disagreement)?; - let left = if op == "->" { + let left = if op == "->" || op == "<->" { ConstExpr::Unary { op: UnaryOp::LogicNot, expr: Box::new(left), @@ -374,9 +376,19 @@ fn bind_in_context( } else { left }; + let right = if op == "<->" { + ConstExpr::Unary { + op: UnaryOp::LogicNot, + expr: Box::new(right), + } + } else { + right + }; values.push(ConstExpr::Binary { left: Box::new(left), - op: if op == "->" { + op: if op == "<->" { + BinaryOp::Eq + } else if op == "->" { BinaryOp::LogicOr } else { constants::binary_op_from_text(&op).ok_or_else(disagreement)? diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index bc9d6de712d..407da9246c6 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -148,6 +148,22 @@ fn shape(context: &mut PackedDimensions, name: String, ty: &Type, local: bool) { context.insert(name, value); } } +// Binding the declaration's type/ranges may reenter discovery and needs the +// completed prefix. The following table edit itself performs no queries. Drop +// only our own old snapshot during that edit, so ScopedMap need not copy its +// growing overlay on every declaration, then publish before the next query. +fn publish_shape( + tree: &AnalysisContext<'_>, + key: &Key, + context: &mut PackedDimensions, + name: String, + ty: &Type, + local: bool, +) { + tree.state.dimensions.partial.borrow_mut().remove(key); + shape(context, name, ty, local); + publish(&tree.state.dimensions, key, context); +} fn variables( declaration: &celox_sv_syntax::VariableDeclaration, tree: &AnalysisContext<'_>, @@ -162,8 +178,7 @@ fn variables( type_binding::ordinary_variable(variable, declaration.data_type, tree.declarations()) }) { let ty = type_with_dimensions(base.clone(), &variable.dimensions, tree, context)?; - shape(context, name(&variable.name), &ty, local); - publish(&tree.state.dimensions, key, context); + publish_shape(tree, key, context, name(&variable.name), &ty, local); } Ok(()) } @@ -206,7 +221,7 @@ fn parameter( if !scalar_binding && let Some(base) = type_binding::bind(*data_type, tree, context)? { let ty = type_with_dimensions(base, dimensions, tree, context)?; if !dimensions.is_empty() || !ty.packed_ranges().is_empty() { - shape(context, n, &ty, local); + publish_shape(tree, key, context, n, &ty, local); } } } @@ -236,8 +251,7 @@ fn declaration( for variable in &data.variables { let ty = type_with_dimensions(base.clone(), &variable.dimensions, tree, context)?; - shape(context, name(&variable.name), &ty, false); - publish(&tree.state.dimensions, key, context); + publish_shape(tree, key, context, name(&variable.name), &ty, false); } } } @@ -689,8 +703,7 @@ fn statement_scope( for declaration in declarations { if let Some(ty) = type_binding::bind(declaration.data_type, tree, context)? { for variable in declaration.variables { - shape(context, name(&variable.name), &ty, true); - publish(&tree.state.dimensions, key, context); + publish_shape(tree, key, context, name(&variable.name), &ty, true); } } } @@ -699,8 +712,7 @@ fn statement_scope( let ty = type_binding::builtin_type("int", None) .ok_or_else(|| unsupported("foreach index type"))?; for n in names { - shape(context, name(&n), &ty, true); - publish(&tree.state.dimensions, key, context); + publish_shape(tree, key, context, name(&n), &ty, true); } } } @@ -824,8 +836,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( && let Ok(ty) = type_with_dimensions(base, &port.dimensions, tree, &context) && let celox_sv_syntax::PortKind::Named(n) = &port.kind { - shape(&mut context, name(n), &ty, false); - publish(&tree.state.dimensions, &key, &context); + publish_shape(tree, &key, &mut context, name(n), &ty, false); } } } @@ -842,8 +853,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( if let Some(id) = owners.subroutine { let subroutine = native.subroutine(id); for (argument, ty) in formal_types(subroutine, tree, &context)? { - shape(&mut context, argument.name, &ty, true); - publish(&tree.state.dimensions, &key, &context); + publish_shape(tree, &key, &mut context, argument.name, &ty, true); } if contains(subroutine.body_tokens, target) && subroutine.kind == SubroutineKind::Function @@ -853,8 +863,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( if matches!(native.data_type(id).kind, DataTypeKind::Implicit) { ty.kind = TypeKind::Logic; } - shape(&mut context, name(&subroutine.name), &ty, true); - publish(&tree.state.dimensions, &key, &context); + publish_shape(tree, &key, &mut context, name(&subroutine.name), &ty, true); } } statement_scope(&owners.statements, target, tree, &mut context, &key)?; 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/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index eeeac9bcae6..4263dd6f0a9 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -641,3 +641,39 @@ fn preliminary_literal_queries_do_not_discover_scope_declarations() { assert_eq!(direct, discovered); assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|count| count.get()), 0); } + +#[test] +fn discovery_prefix_does_not_copy_a_growing_symbol_overlay() { + const COUNT: usize = 128; + let declarations = (0..COUNT) + .map(|index| format!("logic [7:0] v{index};")) + .collect::(); + let code = format!( + "module Top; {declarations} localparam int WIDTH=$bits(v{}); endmodule", + COUNT - 1 + ); + let native = + crate::source_tree::parse_scope_fixture(&code, Path::new("query-prefix-copies.sv")) + .unwrap(); + let calls = native_calls(&native); + assert_eq!(calls.len(), 1); + let tree = AnalysisContext::unspecialized(&native); + super::super::scoped_map::COPIED_OVERLAY_BINDINGS.with(|count| count.set(0)); + SYNTAX_TYPE_DISCOVERIES.with(|count| count.set(0)); + assert_eq!( + query_number( + calls[0], + &tree, + &HashMap::default(), + &HashMap::default(), + None + ), + Some(8) + ); + assert!(SYNTAX_TYPE_DISCOVERIES.with(|count| count.get()) > 0); + let copied = super::super::scoped_map::COPIED_OVERLAY_BINDINGS.with(|count| count.get()); + assert!( + copied <= COUNT * 8, + "{copied} copied bindings for {COUNT} declarations" + ); +} 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..bc080e59848 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; @@ -961,12 +965,14 @@ pub(in crate::ast) fn bind_value( | "&&" | "||" | "->" + | "<->" ) { return Err(unsupported("operator on a real operand")); } let implication = op == "->"; - let left = if implication { + let equivalence = op == "<->"; + let left = if implication || equivalence { Expr::Unary { op: UnaryOp::LogicNot, expr: Box::new(left), @@ -974,10 +980,21 @@ pub(in crate::ast) fn bind_value( } else { left }; + // Each truth-value conversion evaluates its operand once (11.4.7). + let right = if equivalence { + Expr::Unary { + op: UnaryOp::LogicNot, + expr: Box::new(right), + } + } else { + right + }; let xnor = matches!(op.as_str(), "~^" | "^~"); let value = Expr::Binary { left: Box::new(left), - op: if implication { + op: if equivalence { + BinaryOp::Eq + } else if implication { BinaryOp::LogicOr } else if xnor { BinaryOp::BitXor 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/scoped_map.rs b/crates/celox-sv-analyzer/src/ast/scoped_map.rs index e39d271d8ed..a4749bb66f0 100644 --- a/crates/celox-sv-analyzer/src/ast/scoped_map.rs +++ b/crates/celox-sv-analyzer/src/ast/scoped_map.rs @@ -4,6 +4,11 @@ use std::sync::Arc; use fxhash::FxHashMap as HashMap; +#[cfg(test)] +thread_local! { + pub(super) static COPIED_OVERLAY_BINDINGS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Cloning a scope shares both tables. Mutation copies only local changes when /// another scope still shares the overlay, never the complete module table. /// `None` in the overlay hides a symbol in the shared table. @@ -57,6 +62,11 @@ impl ScopedMap { return base.insert(name, value); } let old = self.get(&name).cloned(); + #[cfg(test)] + if Arc::strong_count(&self.overlay) > 1 { + COPIED_OVERLAY_BINDINGS.with(|count| count.set(count.get() + self.overlay.len())); + } + Arc::make_mut(&mut self.overlay).insert(name, Some(value)); old } @@ -68,6 +78,11 @@ impl ScopedMap { return base.remove(name); } let old = self.get(name).cloned(); + #[cfg(test)] + if Arc::strong_count(&self.overlay) > 1 { + COPIED_OVERLAY_BINDINGS.with(|count| count.set(count.get() + self.overlay.len())); + } + if self.base.contains_key(name) { Arc::make_mut(&mut self.overlay).insert(name.to_string(), None); } else { 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-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index 5bc597caa33..fceded314db 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -1849,3 +1849,54 @@ endmodule (top Top) (assert_eq hit 0) (assert_eq y 1)) + +(case logical_equivalence + (source "logical_equivalence.sv" #" + module Top(input logic [3:0] a, b, output logic y, output logic c); + localparam bit C = 4 <-> 2; + assign y = a <-> b; + assign c = C; + endmodule + "#) + (top Top) + (modify (set a 0) (set b 0)) + (assert_eq y 1) + (assert_eq c 1) + (modify (set a 2) (set b 0)) + (assert_eq y 0) + (modify (set a 2) (set b 4)) + (assert_eq y 1) + (modify (set a 0) (set b 4)) + (assert_eq y 0)) + +(case logical_equivalence_unknown + (four_state) + (source "logical_equivalence_unknown.sv" #" + module Top(input logic [1:0] a, b, output logic y); + assign y = a <-> b; + endmodule + "#) + (top Top) + (modify (set a (fourstate 1 1)) (set b 0)) + (assert_eq y (fourstate 1 1)) + (set b 1) + (assert_eq y (fourstate 1 1)) + (set a (fourstate 3 1)) + (assert_eq y 1)) + +(case logical_equivalence_evaluates_operands_once + (source "logical_equivalence_calls.sv" #" + module Top(output logic [7:0] a_count, b_count, output logic y); + function automatic logic left(); a_count = a_count + 1; return 0; endfunction + function automatic logic right(); b_count = b_count + 1; return 1; endfunction + initial begin + a_count = 0; + b_count = 0; + y = left() <-> right(); + end + endmodule + "#) + (top Top) + (assert_eq a_count 1) + (assert_eq b_count 1) + (assert_eq y 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_logical_equivalence_once.sv b/crates/celox-test-suite/verification/repros/sv_logical_equivalence_once.sv new file mode 100644 index 00000000000..eaf5c845486 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_logical_equivalence_once.sv @@ -0,0 +1,11 @@ +module top; + int a_count = 0, b_count = 0; + function automatic bit left(); a_count++; return 0; endfunction + function automatic bit right(); b_count++; return 1; endfunction + initial begin + bit y; + y = left() <-> right(); + $display("y=%0d a=%0d b=%0d", y, a_count, b_count); + $finish; + end +endmodule diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 0ddd3479670..a3597307bc6 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1,4 +1,21 @@ [ + { + "id": "sv_verilator_logical_equivalence_side_effects", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "IEEE 1800-2023 11.4.7 requires each logical equivalence operand to be evaluated exactly once. Verilator 5.052 evaluates the left function twice in the standalone reproduction and emits SIDEEFFECT warnings; Icarus 13.0 evaluates both functions once.", + "upstream": [], + "evidence": [ + "verification/repros/sv_logical_equivalence_once.sv", + "src/sv/cases/operators.vtest" + ], + "cases": { + "verilator": [ + "operators::logical_equivalence_evaluates_operands_once" + ] + } + }, { "id": "sv_static_function_result_lifetime", "category": "simulator_disagreement", diff --git a/crates/celox-test-suite/verification/sv/verilator/operators.json b/crates/celox-test-suite/verification/sv/verilator/operators.json index 0a9e2636556..a71785fcc6f 100644 --- a/crates/celox-test-suite/verification/sv/verilator/operators.json +++ b/crates/celox-test-suite/verification/sv/verilator/operators.json @@ -44,6 +44,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Operators", + "detail": "IEEE 1800-2023 11.4.7 requires each logical equivalence operand to be evaluated exactly once. Verilator 5.052 evaluates the left function twice in the standalone reproduction and emits SIDEEFFECT warnings; Icarus 13.0 evaluates both functions once.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_logical_equivalence_once.sv", + "src/sv/cases/operators.vtest" + ], + "id": "sv_verilator_logical_equivalence_side_effects", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "IEEE 1800-2023 11.4.7 requires each logical equivalence operand to be evaluated exactly once. Verilator 5.052 evaluates the left function twice in the standalone reproduction and emits SIDEEFFECT warnings; Icarus 13.0 evaluates both functions once.", + "upstream": [] + }, + "name": "operators::logical_equivalence_evaluates_operands_once", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Operators", "detail": "", 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/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index ad4fcd8ce0f..7be6789e3d7 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -1,4 +1,7 @@ sv_backends! { + fn logical_equivalence(sim) { @case "operators::logical_equivalence"; } + fn logical_equivalence_unknown(sim) { @case "operators::logical_equivalence_unknown"; } + fn logical_equivalence_evaluates_operands_once(sim) { @case "operators::logical_equivalence_evaluates_operands_once"; } fn logical_implication_short_circuit(sim) { @case "operators::logical_implication_short_circuit"; } fn logical_implication_unknown(sim) { @case "operators::logical_implication_unknown"; } fn logical_implication(sim) { @case "operators::logical_implication"; } diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 79ca3a86a20..103d82b24d7 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