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",