From 5a92951cb0b08a27f8c3039993b9fe2911eb9e78 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 14:03:30 +0900 Subject: [PATCH 1/4] perf(sir-opt): verify coupled rewrites once per batch Coupled store sinking and mux branchification rescanned the entire execution unit after each independent rewrite. Verify the completed batch once, retaining whole-unit validation while avoiding quadratic rescans on large designs. Validation: optimizer unit tests, including counter-based multi-block regressions that also compare execution results; owning-crate clippy and formatting. A profiled large compile previously spent 26.7 seconds in 338 repeated scans. Change-Id: Ided1728ddf74ef8e3fb871971bb00af112418892 --- crates/celox-sir-opt/src/lib.rs | 7 ++ .../pass_branchify_mux/coupled.rs | 22 +++- .../control_flow/pass_branchify_mux/tests.rs | 4 + .../pass_branchify_mux/tests/coupled.rs | 92 ++++++++++++++ .../pass_guarded_region_sinking.rs | 113 +++++++++++++++++- 5 files changed, 234 insertions(+), 4 deletions(-) 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(); From a724b6c7919827899254e9e69d7d517353c962aa Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 21:35:05 +0900 Subject: [PATCH 2/4] feat(sv): isolate deferred assertions in fork processes Give each dynamic process execution its own deferred assertion report queue. Event/wait resumption flushes only that process; disable fork cancels live children's reports, while natural completion preserves reports across slot reuse. Keep owner context around kernel and host-request execution, including error and stop paths, without changing the backend event ring ABI. Host-owned monotonic identities stay outside core checkpoints. Core restore starts fresh ownership without withdrawing host reports; mirror copies queues and identities together. Resolve deferred string arguments consumed by the raw drain before heap replacement or collection. Failed portable loads restore the previous ownership context. Preserve conservative lost-fatal handling for ordinary multi-queue contexts while a dynamic process flush clears its loss. Mature Observed reports before Reactive program work, so a later wakeup cannot flush them; keep Final reports flushable until Postponed. Actions remain single display/severity calls. Distinguish assert/assume/cover final from actual final procedures in the shared timed-case validator. Validation: 1,112 timing tests, all 104 deferred-assertion API tests, six host ownership/raw-drain/restore units, 20 state-file API regressions, 32 suite units, four retained-report tests and nine Node report tests passed. The nine new shared cases pass 55 registered backend tests (native, native-image, native-parallel, Cranelift, Cranelift-parallel, WASM, plus an actual interpreter loop). Runtime units passed all 78 tests. Affected all-target clippy and formatting passed. Debug NAPI built and all nine tests in the timing, cascaded clock and runtime-event JS consumer files passed. Direct SystemVerilog fork semantics are verified through Rust Simulation; the JS bridge has no SV-input API. External observations remain failures, with exact reviewed records: xezim 0.11.3 has 2 passes and 7 mismatches; Verilator 5.052 has 2 passes, 3 mismatches, 3 compiler faults and 1 unsupported four-state case; Icarus 13.0 rejects all 9 with unsupported-deferred-assertion diagnostics. A standalone xezim #0 probe reproduces missing reports against IEEE 1800-2023 16.4.1/16.4.2. No exclusions or passing expectations replace these failures. Rebased onto master 9261b312c3 after #2146, #2149 and #2134. Preserve both function-fork and deferred-fork registrations and retained evidence. Post-sync validation passed 1,149 timing tests, 104 deferred API tests, six host units, 20 final-procedure tests, 20 state-file tests, four retained report tests and nine Node report tests, plus affected all-target clippy and formatting. Runtime ownership and Observed/Reactive logic are unchanged by conflict resolution; external fixtures and adapters are unchanged. Completes deferred assertion composition portion of #2111. Latest master synchronization preserves compound-event tests and retained report entries. Revalidated 83 fork/deferred integration tests, all 104 deferred assertion API tests, 49 focused deferred tests including host units, four retained-report tests and seven report script tests. Affected-crate Clippy and formatting pass. Change-Id: I919ac183ed4c78ec100696954402308a01cb64ee --- crates/celox-frontend-sv/src/lowering/ff.rs | 5 - .../src/simulation/activation.rs | 12 +- crates/celox-runtime/src/simulation/host.rs | 15 ++ .../celox-runtime/src/simulation/process.rs | 21 +- crates/celox-runtime/src/simulation/time.rs | 4 + crates/celox-test-suite/LIMITATIONS.md | 30 +++ crates/celox-test-suite/src/script/timed.rs | 16 +- .../src/sv/cases/fork_deferred.vtest | 138 ++++++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../tests/retained_reports.rs | 34 +++ .../repros/fork_deferred_zero_delay.json | 13 + .../repros/fork_deferred_zero_delay.sv | 9 + .../verification/sv/icarus.json | 1 + .../verification/sv/icarus/fork_deferred.json | 103 +++++++ .../verification/sv/verilator.json | 1 + .../sv/verilator/fork_deferred.json | 103 +++++++ .../verification/sv/xezim.json | 1 + .../verification/sv/xezim/fork_deferred.json | 103 +++++++ .../verification/xezim-review.json | 60 +++++ crates/celox/src/simulation.rs | 24 +- crates/celox/src/simulator.rs | 254 ++++++++++++++++-- crates/celox/src/simulator/checkpoint.rs | 2 + .../src/simulator/host/deferred_tests.rs | 245 +++++++++++++++++ crates/celox/src/simulator/state_file.rs | 7 +- .../tests/frontends/systemverilog/timing.rs | 29 ++ crates/celox/tests/sv_deferred_assertions.rs | 133 +++++++++ docs/guide/systemverilog-reference.md | 22 +- docs/ja/guide/systemverilog-reference.md | 11 +- scripts/check-external-suite-report.test.mjs | 15 ++ 29 files changed, 1365 insertions(+), 50 deletions(-) create mode 100644 crates/celox-test-suite/src/sv/cases/fork_deferred.vtest create mode 100644 crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.json create mode 100644 crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.sv create mode 100644 crates/celox-test-suite/verification/sv/icarus/fork_deferred.json create mode 100644 crates/celox-test-suite/verification/sv/verilator/fork_deferred.json create mode 100644 crates/celox-test-suite/verification/sv/xezim/fork_deferred.json create mode 100644 crates/celox/src/simulator/host/deferred_tests.rs diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 0c5f6e9b40a..6056876e786 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -5944,11 +5944,6 @@ impl Ff<'_, '_> { self.urandom_state(); } let mut kernel = ProcessKernelBuilder::new(slots); - if self.forked && self.has_deferred_assertions(body, &mut HashSet::default()) { - return Err(unsupported( - "deferred assertions in a process with fork-join", - )); - } if let Some(site) = self.deferred_flush_site(body) { kernel.flush_deferred_at(site); } diff --git a/crates/celox-runtime/src/simulation/activation.rs b/crates/celox-runtime/src/simulation/activation.rs index 95fef814be9..cb1807649e2 100644 --- a/crates/celox-runtime/src/simulation/activation.rs +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -217,9 +217,9 @@ impl SimulationState { /// Follow ancestry through completed parents too (IEEE 1800-2023 9.6.3). /// Remove scheduler entries before releasing IDs for reuse. - pub(super) fn disable_children(&mut self, process: usize) { + pub(super) fn disable_children(&mut self, process: usize) -> Vec { if self.process_state.activations.is_empty() { - return; + return Vec::new(); } let mut cancelled = vec![false; self.process_state.activations.len()]; let mut pending = vec![process]; @@ -231,6 +231,13 @@ impl SimulationState { } } } + let live_cancelled = cancelled + .iter() + .enumerate() + .filter_map(|(id, &cancelled)| { + (cancelled && self.process_state.activations[id].live).then_some(id) + }) + .collect(); let state = &mut self.process_state; for (id, activation) in state.activations.iter_mut().enumerate() { activation.pending.retain(|&child| !cancelled[child]); @@ -252,6 +259,7 @@ impl SimulationState { self.retire_activation(id); } } + live_cancelled } pub(super) fn end_activation(&mut self, process: usize) { diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index 146bc75484b..42f46fc599a 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -24,6 +24,15 @@ pub trait UnitExecutor { Ok(self.backend_mut().run_process(index)?) } + /// Attribute deferred assertion records to this dynamic process execution. + fn enter_deferred_assertion_process(&mut self, _process: usize) {} + /// Consume this invocation's records before another execution context runs. + fn leave_deferred_assertion_process(&mut self) {} + /// A naturally completed process retains its pending assertion reports. + fn finish_deferred_assertion_process(&mut self, _process: usize) {} + /// Disabling a live process flushes its deferred assertion reports (16.4.4). + fn cancel_deferred_assertion_process(&mut self, _process: usize) {} + /// Prepare the declaration-only state before runtime static initializers. fn reset_declaration_startup(&mut self) -> Result<(), Halt> { Ok(()) @@ -138,6 +147,12 @@ pub trait HostBoundary: UnitExecutor { Ok(()) } + /// Active-region work has drained. Mature Observed deferred assertions + /// before entering Reactive, so a later wakeup cannot flush them (16.4.1). + fn try_observed_deferred_assertions(&mut self, _timestamp: u64) -> Result<(), Halt> { + Ok(()) + } + /// Called after [`Self::try_finish_timed_step`] when the time slot /// `timestamp` is over: no more work is due at that time. A step ends /// before its slot does when a process waits for zero time. The diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 826f0577c28..9dda1cb687a 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -149,7 +149,10 @@ impl SimulationState { E: SimulationExecutor, { { - executor.run_process(kernel)?; + executor.enter_deferred_assertion_process(process); + let result = executor.run_process(kernel); + executor.leave_deferred_assertion_process(); + result?; let status: u8 = executor .backend() .get_as(self.model.processes[process].status); @@ -177,12 +180,19 @@ impl SimulationState { } Some(ProcessStatus::Done) => { self.end_activation(process); + executor.finish_deferred_assertion_process(process); if self.model.processes[process].program.is_some() { self.program_kernel_ended(executor.backend())?; } } Some(ProcessStatus::Exit) => { self.exit_program(executor.backend_mut(), process)?; + let program = self.model.processes[process].program; + for (index, candidate) in self.model.processes.iter().enumerate() { + if candidate.program == program { + executor.finish_deferred_assertion_process(index); + } + } self.program_kernel_ended(executor.backend())?; } Some(ProcessStatus::Finish) => return Err(Halt::Finish), @@ -198,7 +208,9 @@ impl SimulationState { } Some(ProcessStatus::WaitFork) => return Ok(self.wait_for_children(process)), Some(ProcessStatus::DisableFork) => { - self.disable_children(process); + for child in self.disable_children(process) { + executor.cancel_deferred_assertion_process(child); + } return Ok(true); } Some(ProcessStatus::Local) => { @@ -222,7 +234,10 @@ impl SimulationState { .filter(|site| site.kind == kind) .nth(index as usize) .ok_or(SimulatorErrorCode::InternalError)?; - executor.host_request(request, current_time)?; + executor.enter_deferred_assertion_process(process); + let result = executor.host_request(request, current_time); + executor.leave_deferred_assertion_process(); + result?; *returns += 1; self.charge(*returns, Some(process))?; return Ok(true); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 902d5769654..2678517ec5f 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -195,6 +195,7 @@ impl SimulationState { loop { let ready = self.take_ready_processes(current_time); if ready.is_empty() && self.process_state.ready.is_empty() { + executor.try_observed_deferred_assertions(current_time)?; // The active region set is empty: the reactive region set // runs, and the design activity it creates runs in the active // region set again (IEEE 1800-2023 4.5). @@ -241,6 +242,9 @@ impl SimulationState { where E: SimulationExecutor, { + // Compiled slots without Reactive work reach this boundary directly. + // In the ordinary loop the Observed queue is already empty here. + executor.try_observed_deferred_assertions(current_time)?; executor.try_end_time_slot(current_time) } diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index fa2a2e8ecfa..a523b192871 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -839,3 +839,33 @@ not exclusions or passing assertions. Pinned xezim 0.11.3 passes all six; Verilator 5.052 passes the five two-state cases and its adapter does not support the four-state case. Reproduce with `verify-sv-icarus --filter fork_control::function_join_none_`. + +### Deferred assertions in fork processes + +`fork_deferred::` checks the process-local report queues of IEEE 1800-2023 +16.4.1, their event/wait flush points (16.4.2), and cancellation (16.4.4). +Natural completion retains queued reports; a zero-delay resumption does not +flush them. Observed reports mature before Reactive program activity and +cannot subsequently be flushed, while Final reports remain flushable until +Postponed. These cases remain executable with their original assertions. + +The reviewed [xezim observations](verification/sv/xezim/fork_deferred.json) +include missing sibling/parent reports, a cancelled child report surviving, +and missing reports after `#0`. The [standalone zero-delay source](verification/repros/fork_deferred_zero_delay.sv) +and [observed output](verification/repros/fork_deferred_zero_delay.json) +reproduce the latter without the suite emitter. The +[Verilator observations](verification/sv/verilator/fork_deferred.json) retain +incorrect sibling reports and internal compiler faults as mismatches and +compile errors respectively. The [Icarus observations](verification/sv/icarus/fork_deferred.json) +retain its explicit unsupported-deferred-assertion diagnostics as compile +errors; disabling assertions would not validate these cases. + +The daily gate matches these exact reviewed classifications and diagnostics; +none becomes an exclusion or a pass. Reproduce with `verify-sv-xezim`, +`verify-sv-verilator`, or `verify-sv-icarus` and `--filter fork_deferred::`. + +For these nine cases, xezim 0.11.3 records 2 passes and 7 mismatches; +Verilator 5.052 records 2 passes, 3 mismatches, 3 compiler faults, and +1 unsupported four-state case; Icarus 13.0 records 9 compile errors. +In the Reactive-wakeup case, xezim loses the matured Observed report, +while Verilator also emits the Final report that the wait resumption must flush. diff --git a/crates/celox-test-suite/src/script/timed.rs b/crates/celox-test-suite/src/script/timed.rs index 30016b1dc27..9531d6452c4 100644 --- a/crates/celox-test-suite/src/script/timed.rs +++ b/crates/celox-test-suite/src/script/timed.rs @@ -48,7 +48,7 @@ pub(crate) fn validate_timed_design_with_defines(design: &Design, names: &[&str] } // Final procedures run in an unspecified order relative to the // checks after run_to_finish (IEEE 1800-2023 9.2.3). - if token.text == "final" { + if token.text == "final" && !matches!(previous, "assert" | "assume" | "cover") { return Err("final procedures are not supported in timed shared cases".into()); } } @@ -110,6 +110,20 @@ mod tests { let source = "module Top; initial $display(\"final\"); endmodule"; assert!(validate_timed_design(&design(source)).is_ok()); } + #[test] + fn final_deferred_assertions_are_not_final_procedures() { + for assertion in ["assert", "assume", "cover"] { + let source = format!( + "module Top; initial {assertion} /* trivia */ final (1) $display(\"ok\"); endmodule" + ); + assert!(validate_timed_design(&design(&source)).is_ok(), "{source}"); + let source = format!( + "module Top; initial {assertion} final (1); final $display(\"done\"); endmodule" + ); + assert!(validate_timed_design(&design(&source)).is_err(), "{source}"); + } + } + #[test] fn source_order_controls_macro_hidden_scale_validation() { for directive in [ diff --git a/crates/celox-test-suite/src/sv/cases/fork_deferred.vtest b/crates/celox-test-suite/src/sv/cases/fork_deferred.vtest new file mode 100644 index 00000000000..6be0e16ef71 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/fork_deferred.vtest @@ -0,0 +1,138 @@ +(group fork_deferred (category sequential)) + +; A wait resumption flushes one child's reports, never its sibling's. +(case sibling_wait_queues_are_independent + (source "siblings.sv" #"module Top; + bit go; + task automatic worker(input bit flush_this); + assert #0 (0) else $display("observed %0d", flush_this); + assert final (0) else $display("final %0d", flush_this); + if (flush_this) wait(go); else #1; + endtask + initial begin + go=0; + fork worker(0); worker(1); join_none + #0; go=1; #2; + end +endmodule"#) + (top Top) (run_until 2) + (expect_output "observed 0\nfinal 0\n")) + +(case sibling_event_queues_are_independent + (source "siblings_event.sv" #"module Top; + bit go; + task automatic worker(input bit flush_this); + assert #0 (0) else $display("observed %0d", flush_this); + assert final (0) else $display("final %0d", flush_this); + if (flush_this) @(posedge go); else #1; + endtask + initial begin + go=0; + fork worker(0); worker(1); join_none + #0; go=1; #2; + end +endmodule"#) + (top Top) (run_until 2) + (expect_output "observed 0\nfinal 0\n")) + +(case child_flush_does_not_inherit_parent_reports + (source "parent.sv" #"module Top; + bit go; + initial begin + go=0; + assert #0 (1) $display("parent observed"); + assert final (1) $display("parent final"); + fork begin wait(go); end join_none + #0; go=1; + end +endmodule"#) + (top Top) (run_until 1) + (expect_output "parent observed\nparent final\n")) + +(case disable_fork_flushes_live_children_only + (source "cancel.sv" #"module Top; + initial begin + assert #0 (1) $display("parent"); + fork + begin assert #0 (0) else $display("cancelled"); #5; end + begin assert final (1) $display("completed"); end + join_none + #0; disable fork; + end +endmodule"#) + (top Top) (run_until 1) + (expect_output "parent\ncompleted\n")) + +(case reused_slot_cannot_flush_completed_reports + (source "reused.sv" #"module Top; + bit go; + initial begin + go=0; + fork begin assert #0 (1) $display("completed"); end join + fork begin wait(go); end join_none + #0; go=1; #1; + end +endmodule"#) + (top Top) (run_until 1) + (expect_output "completed\n")) + +(case zero_delay_is_not_a_flush_point + (source "delay.sv" #"module Top; + initial fork + begin + assert #0 (1) $display("observed"); + assert final (1) $display("final"); + #0; + end + join +endmodule"#) + (top Top) (run_until 1) + (expect_output "observed\nfinal\n")) + +(case repeated_static_site_keeps_completed_reports + (source "repeated.sv" #"module Top(input int count); + initial begin + wait(count > 0); + for (int i=0; i { + ( + "compile_error", + "compile", + "AstNode is not of expected type", + ) + } + ( + "verilator", + "fork_deferred::repeated_static_site_keeps_completed_reports" + | "fork_deferred::reused_slot_cannot_flush_completed_reports", + ) => ("compile_error", "compile", "Verilator internal fault"), + ( + "verilator", + "fork_deferred::reactive_wakeup_preserves_mature_observed_only" + | "fork_deferred::sibling_event_queues_are_independent" + | "fork_deferred::sibling_wait_queues_are_independent", + ) => ("mismatch", "execute", "expect_output: expected"), + ( + "icarus", + "fork_deferred::child_flush_does_not_inherit_parent_reports" + | "fork_deferred::disable_fork_flushes_live_children_only" + | "fork_deferred::four_state_arguments_are_captured_before_child_exit" + | "fork_deferred::reactive_wakeup_preserves_mature_observed_only" + | "fork_deferred::repeated_static_site_keeps_completed_reports" + | "fork_deferred::reused_slot_cannot_flush_completed_reports" + | "fork_deferred::sibling_event_queues_are_independent" + | "fork_deferred::sibling_wait_queues_are_independent" + | "fork_deferred::zero_delay_is_not_a_flush_point", + ) => ( + "compile_error", + "compile", + "Deferred assertions are not supported", + ), ( "verilator", "tagged_unions::conditional_struct_payload" diff --git a/crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.json b/crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.json new file mode 100644 index 00000000000..92133c83146 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.json @@ -0,0 +1,13 @@ +{ + "tool": "xezim", + "version": "xezim version 0.11.3", + "source": "fork_deferred_zero_delay.sv", + "command": "xezim -s Top fork_deferred_zero_delay.sv", + "expected_display_lines": [ + "after zero", + "observed", + "final" + ], + "review": "IEEE 1800-2023 16.4.2 does not make a zero-delay resumption a deferred-assertion flush point. Both reports should mature after the Inactive resumption, in Observed and Postponed respectively (16.4.1). The standalone source reproduces missing reports without the shared-suite emitter.", + "observed_output": "=== xezim 0.11.3 ===\ngit unknown (unknown)\nafter zero\nSimulation finished at time 1 ($finish called)\n" +} diff --git a/crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.sv b/crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.sv new file mode 100644 index 00000000000..56b6da27441 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/fork_deferred_zero_delay.sv @@ -0,0 +1,9 @@ +`timescale 1ns/1ns +module Top; +initial begin + assert #0 (1) $display("observed"); + assert final (1) $display("final"); + #0; $display("after zero"); + #1; $finish; +end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index 4d4268ff735..47d91edfa6d 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -5,6 +5,7 @@ "icarus/class.json", "icarus/fork.json", "icarus/fork_control.json", + "icarus/fork_deferred.json", "icarus/generate.json", "icarus/hierarchy.json", "icarus/indexed_select.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/fork_deferred.json b/crates/celox-test-suite/verification/sv/icarus/fork_deferred.json new file mode 100644 index 00000000000..69aa311bec4 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/fork_deferred.json @@ -0,0 +1,103 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:6: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::child_flush_does_not_inherit_parent_reports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:3: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:6: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::disable_fork_flushes_live_children_only", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:4: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:6: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::four_state_arguments_are_captured_before_child_exit", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:6: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::reactive_wakeup_preserves_mature_observed_only", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:6: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:7: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::repeated_static_site_keeps_completed_reports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::reused_slot_cannot_flush_completed_reports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::sibling_event_queues_are_independent", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::sibling_wait_queues_are_independent", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:4: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n/source_0.sv:5: sorry: Deferred assertions are not supported. Try -gno-assertions or -gsupported-assertions to turn this message off.\n", + "expectation": "Simulation", + "name": "fork_deferred::zero_delay_is_not_a_flush_point", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index 89e33179d0a..d631cc962a7 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -3,6 +3,7 @@ "verilator/always_comb.json", "verilator/class.json", "verilator/fork.json", + "verilator/fork_deferred.json", "verilator/generate.json", "verilator/hierarchical_references.json", "verilator/hierarchy.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/fork_deferred.json b/crates/celox-test-suite/verification/sv/verilator/fork_deferred.json new file mode 100644 index 00000000000..05e46be5af0 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/fork_deferred.json @@ -0,0 +1,103 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "fork_deferred::child_flush_does_not_inherit_parent_reports", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator build exit status: 1; see /build.log\n%Error: Internal Error: /source_0.sv:6:10: ../V3Ast.h:1113: AstNode is not of expected type, but instead has type 'IF'\n : ... note: In instance 'celox_suite_tb.dut'\n 6 | begin assert final (1) $display(\"completed\"); end\n | ^~~~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n", + "expectation": "Simulation", + "name": "fork_deferred::disable_fork_flushes_live_children_only", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "fork_deferred::four_state_arguments_are_captured_before_child_exit", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::reactive_wakeup_preserves_mature_observed_only at 138:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 10], got [111, 98, 115, 101, 114, 118, 101, 100, 10, 102, 105, 110, 97, 108, 10]", + "expectation": "Simulation", + "name": "fork_deferred::reactive_wakeup_preserves_mature_observed_only", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator build exit status: 139; see /build.log\n%Error: Verilator internal fault, sorry. Suggest trying --debug --gdbbt\n%Error: Command Failed ulimit -s unlimited 2>/dev/null; exec /nix/store/i5hjqqy2qk6jac8mnnaxnlh8yfi49wjh-verilator-5.052/bin/verilator_bin --cc --exe --build -j 1 --vpi --public-flat-rw --timing --assert --coverage-user -Wno-fatal --x-initial 0 --x-assign 0 --prefix Vdut --top-module celox_suite_tb --Mdir /obj -CFLAGS -O0 -MAKEFLAGS OPT_FAST=-O0\\ OPT_SLOW=-O0 /timescale.sv /source_0.sv /testbench.sv /harness.cpp\n", + "expectation": "Simulation", + "name": "fork_deferred::repeated_static_site_keeps_completed_reports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator build exit status: 139; see /build.log\n%Error: Verilator internal fault, sorry. Suggest trying --debug --gdbbt\n%Error: Command Failed ulimit -s unlimited 2>/dev/null; exec /nix/store/i5hjqqy2qk6jac8mnnaxnlh8yfi49wjh-verilator-5.052/bin/verilator_bin --cc --exe --build -j 1 --vpi --public-flat-rw --timing --assert --coverage-user -Wno-fatal --x-initial 0 --x-assign 0 --prefix Vdut --top-module celox_suite_tb --Mdir /obj -CFLAGS -O0 -MAKEFLAGS OPT_FAST=-O0\\ OPT_SLOW=-O0 /timescale.sv /source_0.sv /testbench.sv /harness.cpp\n", + "expectation": "Simulation", + "name": "fork_deferred::reused_slot_cannot_flush_completed_reports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::sibling_event_queues_are_independent at 36:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 32, 48, 10, 102, 105, 110, 97, 108, 32, 48, 10], got [111, 98, 115, 101, 114, 118, 101, 100, 32, 48, 10, 102, 105, 110, 97, 108, 32, 48, 10, 111, 98, 115, 101, 114, 118, 101, 100, 32, 49, 10, 102, 105, 110, 97, 108, 32, 49, 10]", + "expectation": "Simulation", + "name": "fork_deferred::sibling_event_queues_are_independent", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::sibling_wait_queues_are_independent at 19:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 32, 48, 10, 102, 105, 110, 97, 108, 32, 48, 10], got [111, 98, 115, 101, 114, 118, 101, 100, 32, 48, 10, 102, 105, 110, 97, 108, 32, 48, 10, 111, 98, 115, 101, 114, 118, 101, 100, 32, 49, 10, 102, 105, 110, 97, 108, 32, 49, 10]", + "expectation": "Simulation", + "name": "fork_deferred::sibling_wait_queues_are_independent", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "fork_deferred::zero_delay_is_not_a_flush_point", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/xezim.json b/crates/celox-test-suite/verification/sv/xezim.json index ef049ede69e..0ee84a36a27 100644 --- a/crates/celox-test-suite/verification/sv/xezim.json +++ b/crates/celox-test-suite/verification/sv/xezim.json @@ -10,6 +10,7 @@ "xezim/file_io.json", "xezim/floating_point.json", "xezim/fork.json", + "xezim/fork_deferred.json", "xezim/generate.json", "xezim/hierarchy.json", "xezim/indexed_select.json", diff --git a/crates/celox-test-suite/verification/sv/xezim/fork_deferred.json b/crates/celox-test-suite/verification/sv/xezim/fork_deferred.json new file mode 100644 index 00000000000..62dd6bcdd1e --- /dev/null +++ b/crates/celox-test-suite/verification/sv/xezim/fork_deferred.json @@ -0,0 +1,103 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "fork_deferred::child_flush_does_not_inherit_parent_reports at 50:2: expect_output: expected [112, 97, 114, 101, 110, 116, 32, 111, 98, 115, 101, 114, 118, 101, 100, 10, 112, 97, 114, 101, 110, 116, 32, 102, 105, 110, 97, 108, 10], got []", + "expectation": "Simulation", + "name": "fork_deferred::child_flush_does_not_inherit_parent_reports", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::disable_fork_flushes_live_children_only at 64:2: expect_output: expected [112, 97, 114, 101, 110, 116, 10, 99, 111, 109, 112, 108, 101, 116, 101, 100, 10], got [99, 97, 110, 99, 101, 108, 108, 101, 100, 10, 99, 111, 109, 112, 108, 101, 116, 101, 100, 10]", + "expectation": "Simulation", + "name": "fork_deferred::disable_fork_flushes_live_children_only", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::four_state_arguments_are_captured_before_child_exit at 120:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 32, 49, 48, 120, 122, 10, 102, 105, 110, 97, 108, 32, 49, 48, 120, 122, 10], got []", + "expectation": "Simulation", + "name": "fork_deferred::four_state_arguments_are_captured_before_child_exit", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::reactive_wakeup_preserves_mature_observed_only at 138:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 10], got []", + "expectation": "Simulation", + "name": "fork_deferred::reactive_wakeup_preserves_mature_observed_only", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "fork_deferred::repeated_static_site_keeps_completed_reports", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "fork_deferred::reused_slot_cannot_flush_completed_reports", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::sibling_event_queues_are_independent at 36:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 32, 48, 10, 102, 105, 110, 97, 108, 32, 48, 10], got []", + "expectation": "Simulation", + "name": "fork_deferred::sibling_event_queues_are_independent", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::sibling_wait_queues_are_independent at 19:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 32, 48, 10, 102, 105, 110, 97, 108, 32, 48, 10], got []", + "expectation": "Simulation", + "name": "fork_deferred::sibling_wait_queues_are_independent", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "fork_deferred::zero_delay_is_not_a_flush_point at 90:2: expect_output: expected [111, 98, 115, 101, 114, 118, 101, 100, 10, 102, 105, 110, 97, 108, 10], got []", + "expectation": "Simulation", + "name": "fork_deferred::zero_delay_is_not_a_flush_point", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index 6e0e153e3b3..b896e4d8c9c 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -654,6 +654,10 @@ "sv_fork-X1": { "title": "Compound events on automatic block locals wake before the expression changes or miss subsequent edges", "standard": "IEEE 1800-2023 9.4.2, Table 9-2" + }, + "sv_fork_deferred": { + "title": "Deferred assertion reports do not follow process ownership and flush-point rules", + "standard": "IEEE 1800-2023 16.4.1, 16.4.2, 16.4.4" } }, "cases": [ @@ -4007,6 +4011,62 @@ "classification": "xezim_bug", "bug": "sv_fork-X1", "note": "The shared case reports rises=0 instead of 3. Its assignments are separated by #1 delays, so transient coalescing cannot explain the mismatch. A reduced one-shot concatenation edge wait wakes at time 0, before any write. Clause 9.4.2 requires edge detection on the result LSB, including the X/Z transitions in Table 9-2. See verification/repros/sv_fork_compound_events.md." + }, + { + "suite": "sv", + "name": "fork_deferred::child_flush_does_not_inherit_parent_reports", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_fork_deferred", + "note": "The child wait must not flush the parent process reports; both parent reports are missing." + }, + { + "suite": "sv", + "name": "fork_deferred::disable_fork_flushes_live_children_only", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_fork_deferred", + "note": "disable fork must discard the live cancelled child report, retain naturally completed reports, and leave the parent report intact; output contains cancelled and omits parent." + }, + { + "suite": "sv", + "name": "fork_deferred::four_state_arguments_are_captured_before_child_exit", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_fork_deferred", + "note": "Arguments are captured at assertion execution and #0 is not a flush point; both captured reports are missing." + }, + { + "suite": "sv", + "name": "fork_deferred::sibling_event_queues_are_independent", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_fork_deferred", + "note": "An event-control resumption flushes only its own process queue; the sibling report is missing." + }, + { + "suite": "sv", + "name": "fork_deferred::sibling_wait_queues_are_independent", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_fork_deferred", + "note": "A wait resumption flushes only its own process queue; the sibling report is missing." + }, + { + "suite": "sv", + "name": "fork_deferred::zero_delay_is_not_a_flush_point", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_fork_deferred", + "note": "Zero-delay resumption is not among the flush points in16.4.2. Both reports are missing, also in verification/repros/fork_deferred_zero_delay.sv without the suite adapter." + }, + { + "suite": "sv", + "name": "fork_deferred::reactive_wakeup_preserves_mature_observed_only", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_fork_deferred", + "note": "The Observed report must mature before the Reactive program wakes the waiter; that wakeup can flush only its still-pending Final report. xezim emits neither." } ] } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 5136cc8848f..0e36beaa1a9 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -166,6 +166,19 @@ impl UnitExecutor for Simulator { self.runtime_finish() } + fn enter_deferred_assertion_process(&mut self, process: usize) { + self.enter_deferred_process(process); + } + fn leave_deferred_assertion_process(&mut self) { + self.leave_deferred_process(); + } + fn finish_deferred_assertion_process(&mut self, process: usize) { + self.finish_deferred_process(process); + } + fn cancel_deferred_assertion_process(&mut self, process: usize) { + self.cancel_deferred_process(process); + } + fn reset_declaration_startup(&mut self) -> Result<(), Halt> { self.reset_declaration_state(); Ok(()) @@ -333,10 +346,15 @@ impl HostBoundary for Simulator { Ok(()) } - /// Deferred assertions mature in the Observed and Postponed regions of - /// the slot (IEEE 1800-2023 16.4). + fn try_observed_deferred_assertions(&mut self, _timestamp: u64) -> Result<(), Halt> { + self.mature_deferred_assertion_region(celox_design::AssertionDeferral::Observed) + .map_err(Halt::Error) + } + + /// Final deferred assertions mature in Postponed, after Reactive activity. fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { - self.mature_deferred_assertions().map_err(Halt::Error) + self.mature_deferred_assertion_region(celox_design::AssertionDeferral::Final) + .map_err(Halt::Error) } fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 4b623c820b0..4d6e45f72f1 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -38,6 +38,8 @@ pub use state_file::{StateError, StateMismatch, StateSchema}; #[cfg(feature = "host-runtime")] mod host { mod declaration; + #[cfg(all(test, feature = "systemverilog"))] + mod deferred_tests; mod distribution; mod file_io; mod fread; @@ -409,6 +411,21 @@ mod host { }, } + /// Host identities are deliberately outside core checkpoints. A restored + /// activation slot must not flush reports left by a different execution. + #[derive(Clone, Default)] + pub(super) struct DeferredOwnerContext { + ordinary: u64, + current: Option, + processes: crate::HashMap, + } + + impl DeferredOwnerContext { + fn owner(&self) -> u64 { + self.current.unwrap_or(self.ordinary) + } + } + /// A bounded continuation of the backend ring. Records remain unformatted /// until the eventual consumer supplies its scope/time context. #[derive(Clone, Default)] @@ -416,6 +433,22 @@ mod host { events: std::collections::VecDeque, missed: u64, deferred: DeferredQueues, + deferred_owners: DeferredOwnerContext, + next_deferred_owner: u64, + } + + #[derive(Clone)] + struct DeferredReport { + queue: u32, + owner: u64, + region: celox_design::AssertionDeferral, + event: RawRuntimeEvent, + } + + #[derive(Clone)] + struct DeferredLoss { + region: celox_design::AssertionDeferral, + count: u64, } /// The actions of deferred assertions that wait in the queue of their @@ -426,13 +459,57 @@ mod host { /// fatal, by site id. Empty without deferred assertions. sites: Vec>, /// Waiting actions in issue order, with their queue and region. - waiting: Vec<(u32, celox_design::AssertionDeferral, RawRuntimeEvent)>, + waiting: Vec, /// Events lost to the ring since the last maturity, in a design with - /// fatal deferred actions: they may have held one. - missed: u64, + /// fatal deferred actions: they may have held one. Cancellation must + /// discard only losses belonging to that execution, too. + missed: crate::HashMap, } impl PendingRuntimeEvents { + fn resolve_deferred_handles(&mut self, heap: &celox_heap::Heap) { + // The raw drain can enqueue unresolved string arguments, but it + // cannot mature them. Resolve before the owning thread changes + // heap state or publishes the actions. + for report in &mut self.deferred.waiting { + report.event.resolve_handles(heap); + } + } + + fn new_deferred_owner(&mut self) -> u64 { + self.next_deferred_owner = self + .next_deferred_owner + .checked_add(1) + .expect("deferred assertion owner identity exhausted"); + self.next_deferred_owner + } + + fn enter_deferred_process(&mut self, process: usize) { + debug_assert!(self.deferred_owners.current.is_none()); + let owner = if let Some(&owner) = self.deferred_owners.processes.get(&process) { + owner + } else { + let owner = self.new_deferred_owner(); + self.deferred_owners.processes.insert(process, owner); + owner + }; + self.deferred_owners.current = Some(owner); + } + + fn cancel_deferred_process(&mut self, process: usize) { + if let Some(owner) = self.deferred_owners.processes.remove(&process) { + self.deferred.waiting.retain(|report| report.owner != owner); + self.deferred.missed.remove(&owner); + } + } + + fn replace_deferred_execution(&mut self) { + self.deferred_owners = DeferredOwnerContext { + ordinary: self.new_deferred_owner(), + ..Default::default() + }; + } + fn extend(&mut self, events: impl IntoIterator, capacity: usize) { for event in events { self.push(event, capacity); @@ -450,7 +527,12 @@ mod host { match *deferred { celox_design::DeferredSite::FlushPoint => self.flush(site), celox_design::DeferredSite::Action { queue, region } => { - self.deferred.waiting.push((queue, region, event)); + self.deferred.waiting.push(DeferredReport { + queue, + owner: self.deferred_owners.owner(), + region, + event, + }); } } return; @@ -463,40 +545,76 @@ mod host { .flatten() .any(|&(_, fatal)| fatal) { - self.deferred.missed += count; + // Lost records have no site identity. Fail conservatively in + // the earliest region that could have contained a fatal action. + let region = if self.deferred.sites.iter().flatten().any(|(site, fatal)| { + *fatal + && matches!( + site, + celox_design::DeferredSite::Action { + region: celox_design::AssertionDeferral::Observed, + .. + } + ) + }) { + celox_design::AssertionDeferral::Observed + } else { + celox_design::AssertionDeferral::Final + }; + self.deferred + .missed + .entry(self.deferred_owners.owner()) + .or_insert(DeferredLoss { region, count: 0 }) + .count += count; } self.push_ready(event, capacity); } /// Discard the actions waiting in queue `queue`. fn flush(&mut self, queue: u32) { + let owner = self.deferred_owners.owner(); self.deferred .waiting - .retain(|&(waiting, ..)| waiting != queue); + .retain(|report| report.queue != queue || report.owner != owner); + // A dynamic execution has exactly its process's queue. The + // ordinary context may mix unrelated comb/FF queues, so losses + // there must remain conservatively fatal until maturity. + if self.deferred_owners.current.is_some() { + self.deferred.missed.remove(&owner); + } } - /// The time slot ends: queue the waiting actions, those of the - /// Observed region (`#0`) before those of the Postponed region - /// (`final`), up to the first fatal one, which it returns, or - /// [`RawRuntimeEvent::Missed`] when events that may have been one were - /// lost. - fn mature(&mut self, capacity: usize) -> Option { + /// Mature one region. Matured actions leave the process queue and + /// cannot be flushed by activity in a later region (16.4.1). + fn mature( + &mut self, + region: celox_design::AssertionDeferral, + capacity: usize, + ) -> Option { let waiting = std::mem::take(&mut self.deferred.waiting); - let missed = std::mem::take(&mut self.deferred.missed); + let mut missed = 0; + self.deferred.missed.retain(|_, loss| { + if loss.region == region { + missed += loss.count; + false + } else { + true + } + }); let fatal = (missed > 0).then_some(RawRuntimeEvent::Missed { count: missed }); - for region in [ - celox_design::AssertionDeferral::Observed, - celox_design::AssertionDeferral::Final, - ] { - for (_, _, event) in waiting.iter().filter(|(_, r, _)| *r == region) { - self.push_ready(event.clone(), capacity); - // The simulation ends at a fatal action: the actions - // after it do not run. - if let RawRuntimeEvent::Event { site_id, .. } = event - && let Some(Some((_, true))) = self.deferred.sites.get(*site_id) - { - return fatal.or_else(|| Some(event.clone())); - } + for report in waiting { + if report.region != region { + self.deferred.waiting.push(report); + continue; + } + self.push_ready(report.event.clone(), capacity); + if let RawRuntimeEvent::Event { site_id, .. } = &report.event + && let Some(Some((_, true))) = self.deferred.sites.get(*site_id) + { + // No further actions run after a known fatal action. + self.deferred.waiting.clear(); + self.deferred.missed.clear(); + return fatal.or(Some(report.event)); } } fatal @@ -1462,6 +1580,7 @@ mod host { self.collect_backend_runtime_events(), self.backend.layout().runtime_event_capacity, ); + pending.resolve_deferred_handles(self.backend.heap()); let events = pending.drain(); drop(pending); events @@ -1486,6 +1605,7 @@ mod host { let mut pending = queue.lock().unwrap(); let capacity = self.backend.layout().runtime_event_capacity; pending.extend(self.collect_backend_runtime_events(), capacity); + pending.resolve_deferred_handles(self.backend.heap()); pending.push( RawRuntimeEvent::Host { site: Box::new(site), @@ -1599,6 +1719,14 @@ mod host { /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 /// 16.4). A fatal one ends the simulation with an error. pub(crate) fn mature_deferred_assertions(&mut self) -> Result<(), RuntimeErrorCode> { + self.mature_deferred_assertion_region(celox_design::AssertionDeferral::Observed)?; + self.mature_deferred_assertion_region(celox_design::AssertionDeferral::Final) + } + + pub(crate) fn mature_deferred_assertion_region( + &mut self, + region: celox_design::AssertionDeferral, + ) -> Result<(), RuntimeErrorCode> { // Terminal output draining must not execute actions left in the // Observed/Postponed queues after final procedures (9.2.3). if self.frozen || !self.deferred_assertions { @@ -1606,7 +1734,11 @@ mod host { } self.stash_runtime_events(); let capacity = self.backend.layout().runtime_event_capacity; - let fatal = self.pending_host_events.lock().unwrap().mature(capacity); + let fatal = self + .pending_host_events + .lock() + .unwrap() + .mature(region, capacity); if let Some(RawRuntimeEvent::Missed { count }) = fatal { return Err(RuntimeErrorCode::Runtime { message: format!( @@ -1633,12 +1765,78 @@ mod host { /// Move the events in the backend's buffer to the queue that /// [`Self::drain_runtime_events`] reads. pub(crate) fn stash_runtime_events(&mut self) { + // The raw drain shares this lock: consume and attribute records + // atomically, before the current process owner can change. + let queue = Arc::clone(&self.pending_host_events); + let mut pending = queue.lock().unwrap(); let events = self.collect_backend_runtime_events(); let capacity = self.backend.layout().runtime_event_capacity; + pending.extend(events, capacity); + pending.resolve_deferred_handles(self.backend.heap()); + } + + pub(crate) fn enter_deferred_process(&mut self, process: usize) { + if self.deferred_assertions { + self.stash_runtime_events(); + self.pending_host_events + .lock() + .unwrap() + .enter_deferred_process(process); + } + } + + pub(crate) fn leave_deferred_process(&mut self) { + if self.deferred_assertions { + self.stash_runtime_events(); + self.pending_host_events + .lock() + .unwrap() + .deferred_owners + .current = None; + } + } + + pub(crate) fn finish_deferred_process(&mut self, process: usize) { + if self.deferred_assertions { + self.pending_host_events + .lock() + .unwrap() + .deferred_owners + .processes + .remove(&process); + } + } + + pub(crate) fn cancel_deferred_process(&mut self, process: usize) { + if self.deferred_assertions { + self.pending_host_events + .lock() + .unwrap() + .cancel_deferred_process(process); + } + } + + pub(super) fn replace_deferred_execution(&mut self) { + if self.deferred_assertions { + self.stash_runtime_events(); + self.pending_host_events + .lock() + .unwrap() + .replace_deferred_execution(); + } + } + + pub(super) fn deferred_owner_context(&self) -> DeferredOwnerContext { self.pending_host_events .lock() .unwrap() - .extend(events, capacity); + .deferred_owners + .clone() + } + + pub(super) fn restore_deferred_owner_context(&mut self, owners: DeferredOwnerContext) { + self.stash_runtime_events(); + self.pending_host_events.lock().unwrap().deferred_owners = owners; } fn collect_backend_runtime_events(&mut self) -> Vec { diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index ecbd56e5388..6e713d6dae3 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -181,10 +181,12 @@ impl Simulator { checkpoint: &Checkpoint, ) -> Result<(), CheckpointError> { let fingerprint = self.state_fingerprint(); + self.stash_runtime_events(); self.frozen = checkpoint.frozen; checkpoint .image .restore_into(&mut self.backend, fingerprint)?; + self.replace_deferred_execution(); self.comb_observer_snapshots .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; diff --git a/crates/celox/src/simulator/host/deferred_tests.rs b/crates/celox/src/simulator/host/deferred_tests.rs new file mode 100644 index 00000000000..b186d34d256 --- /dev/null +++ b/crates/celox/src/simulator/host/deferred_tests.rs @@ -0,0 +1,245 @@ +//! Ownership tests which need the host queue and raw backend drain boundary. +use super::*; + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn raw_thread_deferred_string_is_resolved_before_core_heap_restore() { + let source = r#"module Top; + string message; + initial begin + message="retained"; + assert #0 (1) $display("%s", message); + #1; + end + endmodule"#; + let simulation = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("raw_deferred.sv"))], + "Top", + ) + .build_native() + .unwrap(); + let mut sim = simulation.simulator; + let checkpoint = sim.checkpoint().unwrap(); + let kernel = sim + .schedule + .processes + .iter() + .position(|process| process.slots.kind == celox_design::ProcessKind::Regular) + .unwrap(); + let mut drain = sim.runtime_event_drain().unwrap(); + sim.enter_deferred_process(7); + sim.run_process_checked(kernel).unwrap(); + // Deliberately consume the ring on another thread before the owning + // thread can stash/resolve the deferred action at leave. + let mut drain = std::thread::spawn(move || { + assert!(drain.drain().is_empty()); + drain + }) + .join() + .unwrap(); + { + let pending = sim.pending_host_events.lock().unwrap(); + assert_eq!(pending.deferred.waiting.len(), 1); + let RawRuntimeEvent::Event { args, .. } = &pending.deferred.waiting[0].event else { + panic!("deferred event"); + }; + assert!(args.iter().any(|arg| arg.handle)); + } + sim.leave_deferred_process(); + { + let pending = sim.pending_host_events.lock().unwrap(); + let RawRuntimeEvent::Event { args, .. } = &pending.deferred.waiting[0].event else { + panic!("deferred event"); + }; + assert!(args.iter().all(|arg| !arg.handle)); + } + sim.restore(&checkpoint).unwrap(); + // Reusing a restored slot cannot flush an earlier host-side report. + sim.enter_deferred_process(7); + { + let mut pending = sim.pending_host_events.lock().unwrap(); + let queue = pending.deferred.waiting[0].queue; + pending.flush(queue); + assert_eq!(pending.deferred.waiting.len(), 1); + } + sim.leave_deferred_process(); + sim.mature_deferred_assertions().unwrap(); + assert!( + matches!(drain.drain().as_slice(), [RuntimeEvent::Display { message }] if message == b"retained") + ); +} + +#[test] +fn deferred_process_context_is_cleared_after_kernel_error() { + let source = r#"module Top; + initial fork begin + assert #0 (1) $display("pending"); + $fatal(1, "kernel error"); + end join + endmodule"#; + let mut simulation = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("deferred_error.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + let error = simulation.run_until(0).unwrap_err(); + assert!(error.to_string().contains("kernel error"), "{error}"); + assert!( + simulation + .simulator + .pending_host_events + .lock() + .unwrap() + .deferred_owners + .current + .is_none() + ); +} + +#[test] +fn ordinary_deferred_queue_is_not_flushed_by_a_child_context() { + let mut pending = PendingRuntimeEvents::default(); + pending.deferred.sites = vec![ + Some((celox_design::DeferredSite::FlushPoint, false)), + Some(( + celox_design::DeferredSite::Action { + queue: 0, + region: celox_design::AssertionDeferral::Observed, + }, + false, + )), + ]; + pending.push( + RawRuntimeEvent::Event { + site_id: 1, + args: Vec::new(), + }, + 100, + ); + pending.enter_deferred_process(3); + pending.push( + RawRuntimeEvent::Event { + site_id: 1, + args: Vec::new(), + }, + 100, + ); + pending.flush(0); + assert_eq!(pending.deferred.waiting.len(), 1); + pending.deferred_owners.current = None; + pending.flush(0); + assert!(pending.deferred.waiting.is_empty()); +} + +#[test] +fn ordinary_flush_preserves_ambiguous_fatal_loss_until_its_region() { + let mut pending = PendingRuntimeEvents::default(); + pending.deferred.sites = vec![Some(( + celox_design::DeferredSite::Action { + queue: 7, + region: celox_design::AssertionDeferral::Final, + }, + true, + ))]; + pending.push(RawRuntimeEvent::Missed { count: 3 }, 100); + // The ordinary owner can cover several unrelated comb/FF queues. A + // flush has no evidence that these lost records belonged to its queue. + pending.flush(0); + assert!( + pending + .mature(celox_design::AssertionDeferral::Observed, 100) + .is_none() + ); + assert!(matches!( + pending.mature(celox_design::AssertionDeferral::Final, 100), + Some(RawRuntimeEvent::Missed { count: 3 }) + )); +} + +#[test] +fn mirrored_deferred_queues_keep_their_execution_owner_mapping() { + let source = "module Top; initial begin assert #0 (1) $display(\"pending\"); #1; end endmodule"; + let build = || { + crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("mirror_deferred.sv"))], + "Top", + ) + .build_interpreter() + .unwrap() + .simulator + }; + let mut original = build(); + let mut mirrored = build(); + let kernel = original + .schedule + .processes + .iter() + .position(|process| process.slots.kind == celox_design::ProcessKind::Regular) + .unwrap(); + original.enter_deferred_process(7); + original.run_process_checked(kernel).unwrap(); + original.leave_deferred_process(); + for process in [3, 7] { + mirrored.enter_deferred_process(process); + mirrored.leave_deferred_process(); + } + mirrored.mirror(&mut original); + mirrored.enter_deferred_process(7); + { + let mut pending = mirrored.pending_host_events.lock().unwrap(); + assert_eq!(pending.deferred.waiting.len(), 1); + let queue = pending.deferred.waiting[0].queue; + pending.flush(queue); + assert!(pending.deferred.waiting.is_empty()); + } + mirrored.leave_deferred_process(); + assert_eq!( + original + .pending_host_events + .lock() + .unwrap() + .deferred + .waiting + .len(), + 1 + ); +} + +#[test] +fn failed_portable_load_restores_deferred_owner_context() { + let source = r#"module Top(input bit a, output bit y); + logic [1:0] v; + assign v[0] = ~v[1] & a; + assign v[1] = v[0]; + assign y = v[0]; + always_comb assert #0 (1) $display("ordinary"); + endmodule"#; + let loop_net = (vec![], vec!["v".to_owned()]); + let mut sim = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("failed_load_deferred.sv"))], + "Top", + ) + .true_loop(loop_net.clone(), loop_net, 10) + .build_interpreter() + .unwrap(); + let mut file = sim.save_state().unwrap(); + let input = file + .objects + .iter_mut() + .find(|object| object.path == "a") + .unwrap(); + input.value = vec![1]; + sim.enter_deferred_process(7); + sim.leave_deferred_process(); + let before = sim.deferred_owner_context(); + assert!(!before.processes.is_empty()); + assert!(matches!( + sim.load_state(&file), + Err(crate::StateError::Runtime(_)) + )); + let after = sim.deferred_owner_context(); + assert_eq!(before.processes, after.processes); + assert_eq!(before.ordinary, after.ordinary); + assert_eq!(before.current, after.current); +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 7910b06b103..d20abf90315 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -411,9 +411,12 @@ impl Simulator { // Evaluating the loaded state can still fail (an oscillating // combinational loop), so keep the current state to return to. let previous = self.checkpoint()?; + let previous_deferred_owners = self.deferred_owner_context(); + self.stash_runtime_events(); self.state_schema() .load(&mut self.backend, file) .map_err(StateError::Mismatch)?; + self.replace_deferred_execution(); for address in &self.program.runtime_schema.time_slots { self.backend.set( SignalRef { @@ -429,7 +432,9 @@ impl Simulator { // observers take it as their baseline instead of reporting changes. if let Err(error) = self.backend.eval_comb() { let error = self.decorate_runtime_error(error); - self.restore(&previous)?; + let restored = self.restore(&previous); + self.restore_deferred_owner_context(previous_deferred_owners); + restored?; return Err(StateError::Runtime(error)); } self.comb_observer_snapshots = self.snapshot_all_comb_observers(); diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 5f08c3b7c46..65c51e7a7cf 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -1362,3 +1362,32 @@ fn fork_compound_event_rejects_implicit_expression_writes() { ); } } + +timed_cases! { + fn fork_deferred_four_state_arguments_are_captured_before_child_exit = "fork_deferred::four_state_arguments_are_captured_before_child_exit"; + fn fork_deferred_reactive_wakeup_preserves_mature_observed_only = "fork_deferred::reactive_wakeup_preserves_mature_observed_only"; + fn fork_deferred_sibling_wait_queues_are_independent = "fork_deferred::sibling_wait_queues_are_independent"; + fn fork_deferred_sibling_event_queues_are_independent = "fork_deferred::sibling_event_queues_are_independent"; + fn fork_deferred_child_flush_does_not_inherit_parent_reports = "fork_deferred::child_flush_does_not_inherit_parent_reports"; + fn fork_deferred_disable_fork_flushes_live_children_only = "fork_deferred::disable_fork_flushes_live_children_only"; + fn fork_deferred_reused_slot_cannot_flush_completed_reports = "fork_deferred::reused_slot_cannot_flush_completed_reports"; + fn fork_deferred_zero_delay_is_not_a_flush_point = "fork_deferred::zero_delay_is_not_a_flush_point"; + fn fork_deferred_repeated_static_site_keeps_completed_reports = "fork_deferred::repeated_static_site_keeps_completed_reports"; +} + +#[test] +fn fork_deferred_interpreter() { + for name in [ + "reactive_wakeup_preserves_mature_observed_only", + "four_state_arguments_are_captured_before_child_exit", + "sibling_wait_queues_are_independent", + "sibling_event_queues_are_independent", + "child_flush_does_not_inherit_parent_reports", + "disable_fork_flushes_live_children_only", + "reused_slot_cannot_flush_completed_reports", + "zero_delay_is_not_a_flush_point", + "repeated_static_site_keeps_completed_reports", + ] { + crate::suite::run_case(&format!("fork_deferred::{name}"), "interpreter"); + } +} diff --git a/crates/celox/tests/sv_deferred_assertions.rs b/crates/celox/tests/sv_deferred_assertions.rs index 6cc9c7493a3..aeb47136715 100644 --- a/crates/celox/tests/sv_deferred_assertions.rs +++ b/crates/celox/tests/sv_deferred_assertions.rs @@ -369,6 +369,108 @@ macro_rules! deferred { ); } + #[test] + fn fork_cancelled_fatal_does_not_mature_in_either_region() { + for region in ["#0", "final"] { + let body = format!("initial begin fork begin assert {region} (0) else $fatal(1, \"cancelled\"); #5; end join_none #0; disable fork; #1; a=1; end"); + let mut sim = simulation(&body); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("a")), 1u8.into()); + } + } + + #[test] + fn fork_completed_fatal_survives_disable_fork_in_either_region() { + for region in ["#0", "final"] { + let body = format!("initial begin fork begin assert {region} (0) else $fatal(1, \"completed\"); end join_none #0; disable fork; #1; a=1; end"); + let mut sim = simulation(&body); + let error = sim.run_until(2).unwrap_err(); + assert!(error.to_string().contains("completed"), "{error}"); + assert_eq!(sim.get(sim.signal("a")), 0u8.into()); + } + } + + #[test] + fn fork_stop_retains_owner_until_wait_flushes_only_that_child() { + let mut sim = simulation(r#" + initial begin + fork + begin assert #0 (1) $display("stopped"); $stop; wait(a); end + begin assert #0 (1) $display("sibling"); end + join_none + #0; a=1; #1; + end + "#); + sim.run_until(1).unwrap(); + assert!(sim.is_stopped()); + assert!(summary(sim.drain_runtime_events()).is_empty()); + sim.run_until(1).unwrap(); + assert!(!sim.is_stopped()); + assert_eq!(summary(sim.drain_runtime_events()), vec![("sibling".to_owned(), None)]); + } + + #[test] + fn fork_reactive_wakeup_cannot_cancel_an_observed_fatal() { + for region in ["#0", "final"] { + let source = format!(r#"`timescale 1ns/1ns + module Top(output bit done); + bit go; + Driver driver(go); + initial fork begin + assert {region} (0) else $fatal(1, "deferred fatal"); + wait(go); done=1; + end join + endmodule + program Driver(output bit go); + initial begin go=1; #10; end + endprogram"#); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("reactive_deferred.sv"))], "Top" + ).$backend().unwrap(); + let result = sim.run_until(1); + if region == "#0" { + let error = result.unwrap_err(); + assert!(error.to_string().contains("deferred fatal"), "{error}"); + } else { + result.unwrap(); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + } + } + } + + #[test] + fn fork_wait_flush_discards_its_lost_fatal_reports() { + let mut sim = simulation(r#" + initial begin + fork begin + assert final (0) else $fatal(1, "flushed"); + repeat (2000) $display("discarded"); + wait(a); + end join_none + #0; a=1; #1; b=1; + end + "#); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("b")), 1u8.into()); + assert!(sim.drain_runtime_events().iter().any(|event| matches!(event, RuntimeEvent::Missed { .. }))); + } + + #[test] + fn fork_cancelled_overflow_cannot_leave_a_fatal_in_another_owner() { + let mut sim = simulation(r#" + initial begin + fork begin + assert final (0) else $fatal(1, "cancelled"); + repeat (2000) $display("discarded"); + #5; + end join_none + #0; disable fork; #1; a=1; + end + "#); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("a")), 1u8.into()); + } + /// Events lost to a full event buffer may have held a deferred /// `$fatal`, which then still ends the simulation. #[test] @@ -546,3 +648,34 @@ fn deferred_actions_are_one_display_or_severity_task_call() { ); } } + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn fork_deferred_queues_follow_differential_scheduler_mirrors() { + let source = r#"`timescale 1ns/1ns + module Top; + bit go; + initial begin + fork + begin assert #0 (1) $display("kept"); #1; end + begin assert #0 (1) $display("flushed"); wait(go); end + join_none + #0; go=1; #2; + end + endmodule"#; + for four_state in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("deferred_differential.sv"))], + "Top", + ) + .four_state(four_state) + .scheduler_mode(celox::SchedulerMode::Differential) + .build_native() + .unwrap(); + sim.run_until(2).unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("kept".to_owned(), None)] + ); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6cb69aeb320..79ca3a86a20 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -149,7 +149,7 @@ random streams and pending joins. State files also preserve strings held only by suspended children or shared automatic locals. Non-null class objects or dynamic containers and nonempty string/object values in pending NBA writes, host writes or event-wait baselines remain unsupported in activation state files; use -`checkpoint()` / `restore()` for those states. Deferred assertions in a process containing forks remain unsupported. +`checkpoint()` / `restore()` for those states. Direct event controls, `wait` conditions, and compound event expressions over fork-shared automatic locals are supported. Compound expressions may use constants @@ -847,10 +847,22 @@ flushes the queue at its flush points (16.4.2): (one whose only timing control is its leading event control), each time it runs again. -When the time slot is over, the actions still waiting are executed: those of -`#0` ones first, then those of `final` ones. A deferred `$fatal` ends the -simulation then. A deferred assertion as a module item is the same assertion -in an `always_comb` (16.4.3). An action is one display or severity task +Fork children have independent deferred assertion queues. A child's event or +wait resumption cannot flush its parent or siblings. `disable fork` discards +pending reports from the live descendants it terminates (16.4.4); natural child +completion preserves pending reports, even when its process slot is reused. +Compiler yields, `$stop`/resume and `#0` delays do not flush these queues. + +Core checkpoint restore and portable state load preserve previously issued host +reports. Restored executions cannot cancel those reports by reusing a process +slot; pending host reports are not serialized into portable core state files. + +`#0` reports mature after Active work drains, before Reactive program code runs. +Once mature, they cannot be flushed by a later Reactive wakeup. Their display or +severity actions execute at that boundary. `final` reports remain flushable +until Postponed, after all Reactive activity. A deferred `$fatal` ends the +simulation when its action executes. A deferred assertion as a module item is +the same assertion in an `always_comb` (16.4.3). An action is one display or severity task call; a user subroutine, or more than one statement, is rejected. A `Simulator` call is a time slot: there, actions mature when the call settles combinational logic or runs a domain. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 6c0507119d2..4020fcca030 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -457,8 +457,15 @@ VPI ホストと `celox` コマンドが表示する形に整形します。`cel - `always_comb`、`always_latch`、組み合わせ回路として扱う `always`(タイミング制御が先頭の イベント制御だけのもの)は、再実行するたびに。 -タイムスロットが終わると、まだ待っているアクションを `#0` のもの、`final` のものの順に実行します。 -遅延付きの `$fatal` はそこでシミュレーションを終了します。モジュール直下の遅延付きアサーションは、 +fork の各子プロセスは独立した遅延レポートキューを持ちます。子がイベント制御や wait から +再開しても、親や兄弟のキューは消去しません。`disable fork` は終了させた実行中の子孫の +未確定レポートを取り消しますが、自然に終了した子のレポートは残します(16.4.4)。 +`#0` の遅延や `$stop` からの再開ではキューを消去しません。 + +`#0` のレポートは Active の処理がなくなった時点で確定し、Reactive の program を実行する前に +表示・報告のアクションを実行します。確定済みのレポートは、その後の Reactive からの起床では +取り消せません。`final` のレポートは Reactive の処理後の Postponed まで取り消し可能です。 +遅延付きの `$fatal` はアクションの実行時にシミュレーションを終了します。モジュール直下の遅延付きアサーションは、 `always_comb` に入れた同じアサーションです(16.4.3)。アクションは表示タスクか重大度タスクの 呼び出し 1 つで、ユーザーのサブルーチンや複数の文は拒否します。`Simulator` では呼び出し 1 回が タイムスロットで、組み合わせ回路が落ち着いたときやドメインを実行したときにアクションが成熟します。 diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index effdd2060f9..7eb2f628a7a 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -295,6 +295,15 @@ test("every retained baseline accepts only its existing failures", () => { "fork_control::function_join_none_event_driven_caller", "fork_control::function_join_none_preserves_expression_temporaries", "fork_control::function_join_none_retains_child_only_class_handle", + "fork_deferred::child_flush_does_not_inherit_parent_reports", + "fork_deferred::disable_fork_flushes_live_children_only", + "fork_deferred::four_state_arguments_are_captured_before_child_exit", + "fork_deferred::reactive_wakeup_preserves_mature_observed_only", + "fork_deferred::repeated_static_site_keeps_completed_reports", + "fork_deferred::reused_slot_cannot_flush_completed_reports", + "fork_deferred::sibling_event_queues_are_independent", + "fork_deferred::sibling_wait_queues_are_independent", + "fork_deferred::zero_delay_is_not_a_flush_point", "hierarchy::packed_pattern_parameter_arguments_keep_types_and_unknown_bits", "hierarchy::packed_pattern_parameter_arguments_preserve_wide_values", "hierarchy::packed_pattern_parameters_forward_whole_values", @@ -314,6 +323,12 @@ test("every retained baseline accepts only its existing failures", () => { ] : [ "fork::compound_event_activations_outlive_parent", + "fork_deferred::disable_fork_flushes_live_children_only", + "fork_deferred::reactive_wakeup_preserves_mature_observed_only", + "fork_deferred::repeated_static_site_keeps_completed_reports", + "fork_deferred::reused_slot_cannot_flush_completed_reports", + "fork_deferred::sibling_event_queues_are_independent", + "fork_deferred::sibling_wait_queues_are_independent", "tagged_unions::conditional_struct_payload", "tagged_unions::constructors_and_checked_members", "tagged_unions::default_arguments", From f3f8a84b864e0e035b848cafded1a528e1f74d95 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 01:57:15 +0900 Subject: [PATCH 3/4] 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 From a313934a50a3ce72ece7b9e907f0374b3e5655b1 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 04:18:54 +0900 Subject: [PATCH 4/4] feat(sv): support logical equivalence expressions Evaluate both operands exactly once and preserve four-state truth values. Six generated sv-tests cases now pass in both state modes. Validation: full sv-tests, operator and analyzer tests, Icarus and Verilator focused cases, formatting and analyzer Clippy. Verilator 5.052 evaluates one operand twice; retain a reviewed exclusion with a standalone reproduction. Rebased onto master after #2201 merged and removed its obsolete dependency marker. Revalidated 305 operator tests across enabled backends, 839 analyzer tests (three existing ignores), analyzer Clippy, workspace check, title/queue policy tests and formatting. The existing zstd/zstd-safe advisory failures are unrelated to this PR and remain unresolved. Change-Id: I918a75f01dff54bb45806788937909ae12075edb --- conformance/sv-tests/README.md | 6 +++ conformance/sv-tests/expected.tsv | 24 ++++----- .../src/ast/constant_binding.rs | 18 +++++-- .../src/ast/expression_binding/direct.rs | 17 ++++++- .../src/sv/cases/operators.vtest | 51 +++++++++++++++++++ .../repros/sv_logical_equivalence_once.sv | 11 ++++ .../verification/sv/limitations.json | 17 +++++++ .../verification/sv/verilator/operators.json | 23 +++++++++ .../frontends/systemverilog/operators.rs | 3 ++ 9 files changed, 153 insertions(+), 17 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_logical_equivalence_once.sv diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 8499d376339..1d0a8c7d61a 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 diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 71a981ebf40..89501cb5d10 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -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-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/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index af888e0b3bf..16b2b487c85 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -961,12 +961,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 +976,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-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/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"; }