diff --git a/CLAUDE.md b/CLAUDE.md index 4b006d7bd54..40fa5b29d36 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -101,6 +101,7 @@ GCC-style optimization level presets with per-pass overrides. | `IdentityStoreBypass` | Detects identity copies and registers address aliases | | `TailCallSplit` | Splits large functions into tail-call chains (enabled even at O0) | | `DerivedEdgeUnits` | Runs edges of gated/divided clocks in generated units instead of the Rust plan walk (not a SIR transform; costs build time, `-sir:derived_edge_units` to opt out) | +| `PartitionedSettle` | Splits the combinational settle into partitions that run only when state they read changed (not a SIR transform; off unless enabled, `+sir:partitioned_settle`; `SimulatorBuilder::settle_check` cross-checks it) | ### Cranelift Backend Optimization diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index a6186810a34..404b148ae0e 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -777,18 +777,18 @@ chapter-21/21.2--write-boh.sv 2state pass chapter-21/21.2--write-boh.sv 4state pass chapter-21/21.2--write.sv 2state pass chapter-21/21.2--write.sv 4state pass -chapter-21/21.3--fdisplay-boh.sv 2state fail -chapter-21/21.3--fdisplay-boh.sv 4state fail -chapter-21/21.3--fdisplay.sv 2state fail -chapter-21/21.3--fdisplay.sv 4state fail +chapter-21/21.3--fdisplay-boh.sv 2state pass +chapter-21/21.3--fdisplay-boh.sv 4state pass +chapter-21/21.3--fdisplay.sv 2state pass +chapter-21/21.3--fdisplay.sv 4state pass chapter-21/21.3--feof.sv 2state pass chapter-21/21.3--feof.sv 4state pass chapter-21/21.3--ferror.sv 2state fail chapter-21/21.3--ferror.sv 4state fail chapter-21/21.3--fflush.sv 2state pass chapter-21/21.3--fflush.sv 4state pass -chapter-21/21.3--fgetc.sv 2state fail -chapter-21/21.3--fgetc.sv 4state fail +chapter-21/21.3--fgetc.sv 2state pass +chapter-21/21.3--fgetc.sv 4state pass chapter-21/21.3--fgets.sv 2state fail chapter-21/21.3--fgets.sv 4state fail chapter-21/21.3--file.sv 2state pass @@ -797,16 +797,16 @@ chapter-21/21.3--fmonitor.sv 2state fail chapter-21/21.3--fmonitor.sv 4state fail chapter-21/21.3--fpos.sv 2state pass chapter-21/21.3--fpos.sv 4state pass -chapter-21/21.3--fread.sv 2state fail -chapter-21/21.3--fread.sv 4state fail -chapter-21/21.3--fscanf.sv 2state fail -chapter-21/21.3--fscanf.sv 4state fail +chapter-21/21.3--fread.sv 2state pass +chapter-21/21.3--fread.sv 4state pass +chapter-21/21.3--fscanf.sv 2state pass +chapter-21/21.3--fscanf.sv 4state pass chapter-21/21.3--fstrobe.sv 2state fail chapter-21/21.3--fstrobe.sv 4state fail -chapter-21/21.3--fwrite-boh.sv 2state fail -chapter-21/21.3--fwrite-boh.sv 4state fail -chapter-21/21.3--fwrite.sv 2state fail -chapter-21/21.3--fwrite.sv 4state fail +chapter-21/21.3--fwrite-boh.sv 2state pass +chapter-21/21.3--fwrite-boh.sv 4state pass +chapter-21/21.3--fwrite.sv 2state pass +chapter-21/21.3--fwrite.sv 4state pass chapter-21/21.3--sscanf.sv 2state pass chapter-21/21.3--sscanf.sv 4state pass chapter-21/21.3--ungetc.sv 2state fail @@ -1579,8 +1579,8 @@ chapter-9/9.2.2.3--always_latch.sv 2state fail chapter-9/9.2.2.3--always_latch.sv 4state fail chapter-9/9.2.2.4--always_ff.sv 2state pass chapter-9/9.2.2.4--always_ff.sv 4state pass -chapter-9/9.2.3--final.sv 2state fail -chapter-9/9.2.3--final.sv 4state fail +chapter-9/9.2.3--final.sv 2state pass +chapter-9/9.2.3--final.sv 4state pass chapter-9/9.3.1--sequential_block.sv 2state pass chapter-9/9.3.1--sequential_block.sv 4state pass chapter-9/9.3.2--parallel_block_join.sv 2state fail @@ -1735,46 +1735,46 @@ generated/assignment_op/11.4.1--plus_assignment.sv 2state pass generated/assignment_op/11.4.1--plus_assignment.sv 4state pass generated/assignment_op/11.4.1--xor_assignment.sv 2state pass generated/assignment_op/11.4.1--xor_assignment.sv 4state pass -generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state fail -generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state fail +generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--and_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--and_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--div_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--div_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--log_shl_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--log_shr_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--minus_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--mod_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--mul_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--or_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--or_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--plus_assignment-sim-1.sv 4state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 2state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-0.sv 4state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 2state pass +generated/assignment_sim/11.4.1--xor_assignment-sim-1.sv 4state pass generated/binary_op/11.4.10--binary_op_arith_shl.sv 2state pass generated/binary_op/11.4.10--binary_op_arith_shl.sv 4state pass generated/binary_op/11.4.10--binary_op_arith_shr.sv 2state pass @@ -2467,22 +2467,22 @@ generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 2s generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_2.sv 4state fail generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 2state fail generated/logical_implication_operator_sim/11.4.7--logical_impl_operator_3.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state fail -generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state fail -generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state fail +generated/logical_operators_sim/11.4.7--logical_operator_0.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_0.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_1.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_1.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_2.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_2.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_3.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_3.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_4.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_4.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_5.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_5.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_6.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_6.sv 4state pass +generated/logical_operators_sim/11.4.7--logical_operator_7.sv 2state pass +generated/logical_operators_sim/11.4.7--logical_operator_7.sv 4state pass generated/nets/6.6.1--net_tri.sv 2state pass generated/nets/6.6.1--net_tri.sv 4state pass generated/nets/6.6.1--net_wire.sv 2state pass @@ -2507,42 +2507,42 @@ generated/nets/6.6.6--net_supply0.sv 2state fail generated/nets/6.6.6--net_supply0.sv 4state fail generated/nets/6.6.6--net_supply1.sv 2state fail generated/nets/6.6.6--net_supply1.sv 4state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.10--log_shl_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.10--log_shr_operator_sim_1.sv 4state pass generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 2state pass generated/operators_sim/11.4.10--simple_log_shl_operator_sim.sv 4state pass generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 2state pass generated/operators_sim/11.4.10--simple_log_shr_operator_sim.sv 4state pass -generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.3--div_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--div_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--div_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--div_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--exp_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--exp_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--exp_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--exp_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--minus_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--minus_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--minus_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--minus_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--mod_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--mod_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--mod_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--mod_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--mul_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--mul_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--mul_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--mul_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.3--plus_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.3--plus_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.3--plus_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.3--plus_operator_sim_1.sv 4state pass generated/operators_sim/11.4.3--simple_div_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_div_operator_sim.sv 4state pass generated/operators_sim/11.4.3--simple_exp_operator_sim.sv 2state pass @@ -2555,22 +2555,22 @@ generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_mul_operator_sim.sv 4state pass generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 2state pass generated/operators_sim/11.4.3--simple_plus_operator_sim.sv 4state pass -generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.4--ge_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--ge_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--ge_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--ge_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--gt_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--gt_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--gt_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--gt_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--le_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--le_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--le_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--le_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.4--lt_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.4--lt_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.4--lt_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.4--lt_operator_sim_1.sv 4state pass generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_ge_operator_sim.sv 4state pass generated/operators_sim/11.4.4--simple_gt_operator_sim.sv 2state pass @@ -2579,14 +2579,14 @@ generated/operators_sim/11.4.4--simple_le_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_le_operator_sim.sv 4state pass generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 2state pass generated/operators_sim/11.4.4--simple_lt_operator_sim.sv 4state pass -generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.5--log_eq_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.5--log_neq_operator_sim_1.sv 4state pass generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_eq_operator_sim.sv 4state pass generated/operators_sim/11.4.5--simple_eq_xz_operator_sim.sv 2state pass @@ -2595,18 +2595,18 @@ generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_neq_operator_sim.sv 4state pass generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 2state pass generated/operators_sim/11.4.5--simple_neq_xz_operator_sim.sv 4state pass -generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state fail -generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state fail +generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_and_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_or_operator_sim_1.sv 4state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 2state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_0.sv 4state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 2state pass +generated/operators_sim/11.4.8--bit_xor_operator_sim_1.sv 4state pass generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 2state pass generated/operators_sim/11.4.8--simple_bit_and_operator_sim.sv 4state pass generated/operators_sim/11.4.8--simple_bit_or_operator_sim.sv 2state pass diff --git a/crates/celox-backend-arm64/src/isel/tests.rs b/crates/celox-backend-arm64/src/isel/tests.rs index 3456a2c8be1..92e7fc934be 100644 --- a/crates/celox-backend-arm64/src/isel/tests.rs +++ b/crates/celox-backend-arm64/src/isel/tests.rs @@ -16,6 +16,7 @@ fn layout_for(address: AbsoluteAddr, width: usize, four_state: bool) -> MemoryLa let total_size = plane_size * if four_state { 2 } else { 1 }; MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-wasm/src/lib.rs b/crates/celox-backend-wasm/src/lib.rs index 5b146b76b5a..cc010904637 100644 --- a/crates/celox-backend-wasm/src/lib.rs +++ b/crates/celox-backend-wasm/src/lib.rs @@ -6488,6 +6488,7 @@ mod bit_count_tests { MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests.rs b/crates/celox-backend-x86/src/backend/native/isel/tests.rs index 19b3c5d844b..8d513fecf0b 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests.rs @@ -16,6 +16,7 @@ use num_bigint::BigUint; fn empty_layout() -> MemoryLayout { MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs index 7ed5e929daa..db8fe2abd3f 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/bit_count.rs @@ -196,6 +196,7 @@ fn compile_bit_count(op: UnaryOp, source_width: usize, four_state: bool) -> Comp let layout = MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs index aed958745c1..97a0c5cf9e5 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/memory.rs @@ -800,6 +800,7 @@ fn narrowed_wide_binary_store_does_not_write_source_width() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1130,6 +1131,7 @@ fn execute_unaligned_64_bit_load(dynamic: bool) -> u64 { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1295,6 +1297,7 @@ fn verify_scalar_alignment_matrix(dynamic: bool, four_state: bool) { eu.verify(); let layout = MemoryLayout { trace: None, + settle: None, four_state, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -1511,6 +1514,7 @@ fn verify_wide_alignment_matrix(dynamic: bool) { eu.verify(); let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs index ddce616c2bb..37503198e34 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/selection.rs @@ -511,6 +511,7 @@ fn lowers_shared_selector_roots_to_cached_indexed_table_loads() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs index 51d1ae82584..3f94d1bda99 100644 --- a/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs +++ b/crates/celox-backend-x86/src/backend/native/isel/tests/wide.rs @@ -660,6 +660,7 @@ fn narrow_wide_shift_uses_only_chunks_covered_by_the_result() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), @@ -836,6 +837,7 @@ fn wide_shift_result_is_canonical_before_mux_condition() { let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs index fd1e45ec7e1..e0b20af1d78 100644 --- a/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs +++ b/crates/celox-backend-x86/src/backend/native/sparse_write_state.rs @@ -1426,6 +1426,7 @@ mod tests { .collect(); MemoryLayout { trace: None, + settle: None, four_state: false, mode: MemoryLayoutMode::Packed, unpacked_arrays: HashMap::default(), diff --git a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs index 437eff6db62..0c82cb95455 100644 --- a/crates/celox-backend-x86/tests/support/packed_index_fixture.rs +++ b/crates/celox-backend-x86/tests/support/packed_index_fixture.rs @@ -145,6 +145,7 @@ pub fn compile(recover: bool) -> CompiledUpdate { )]; let layout = MemoryLayout { trace: None, + settle: None, four_state: false, mode: celox_state_layout::MemoryLayoutMode::Packed, offsets: [ diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 7294c286a4e..7cb6fdda1da 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -616,6 +616,17 @@ impl std::fmt::Display for ProcessOrigin { } } +/// When a procedural kernel is invoked by the runtime. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ProcessKind { + /// Static declarations run before ordinary HDL procedures. + Initializer, + #[default] + Regular, + /// A final procedure runs only when simulation ends (IEEE 1800-2023 9.2.3). + Final, +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to @@ -625,9 +636,9 @@ impl std::fmt::Display for ProcessOrigin { /// checkpoints capture a suspended process. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { - /// A static declaration initializer, executed before all HDL procedures. - pub is_initializer: bool, - /// This kernel originated from an edge procedure and must execute in Simulation. + /// The phase in which the runtime invokes this kernel. + pub kind: ProcessKind, + /// This kernel requires Simulation's process scheduler rather than Simulator. pub requires_timed_simulation: bool, /// Every delay the kernel suspends for is a constant of at least one /// time unit. @@ -646,7 +657,7 @@ pub struct ProcessSlots { impl ProcessSlots { pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots { ProcessSlots { - is_initializer: self.is_initializer, + kind: self.kind, requires_timed_simulation: self.requires_timed_simulation, const_delays: self.const_delays, program: self.program.map(&mut map), @@ -1053,6 +1064,27 @@ pub struct RuntimeSchema { /// Generated units that run an edge of an event with every derived /// clock domain it reaches, for the events that have them. pub derived_edges: Vec>, + /// The partitions of a partitioned combinational settle, when it is + /// partitioned. + pub settle_partitions: Option>, +} + +/// A combinational settle split into partitions that run only when state +/// they read changed since they last ran. +/// +/// Byte `p` of `flags` is partition `p`'s dirty flag; the byte after the +/// last partition's is the untracked byte, set once state may change +/// without anyone setting flags (a retained raw view), after which every +/// partition always runs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SettlePartitions { + pub flags: A, + pub partitions: u32, + /// State the settle reads or writes, with the partitions to mark when + /// something other than the settle writes it. A written object lists + /// its writers as well, so that, as in a single pass, the settle + /// recomputes it. + pub marks: Vec<(A, Vec)>, } /// The process units that run the edges of one event together with its @@ -1279,6 +1311,7 @@ impl Default for RuntimeSchema { time_slots: Vec::new(), scheduler: None, derived_edges: Vec::new(), + settle_partitions: None, } } } diff --git a/crates/celox-frontend-core/src/lib.rs b/crates/celox-frontend-core/src/lib.rs index 05e833c6575..5a208e3e8c1 100644 --- a/crates/celox-frontend-core/src/lib.rs +++ b/crates/celox-frontend-core/src/lib.rs @@ -18,7 +18,7 @@ pub use shared::{ pub use trace::{FrontendTrace, FrontendTraceOptions, TraceSimModule}; pub use symbolic::flattening; -pub use symbolic::parallel::ParallelScheduleOptions; +pub use symbolic::parallel::{ParallelScheduleOptions, SettlePartitionMode}; pub(crate) type HashMap = fxhash::FxHashMap; pub(crate) type HashSet = fxhash::FxHashSet; diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index f955fda9e87..c5c89c1135f 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1729,7 +1729,7 @@ fn lower_processes( for (index, process) in artifact.processes().iter().enumerate() { let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; let slots = ProcessSlots { - is_initializer: false, + kind: celox_design::ProcessKind::Regular, requires_timed_simulation: false, const_delays: false, program: None, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 2e8b3db9b56..aa5104fcb87 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -8,7 +8,7 @@ use crate::symbolic::artifact::{ use crate::{ FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap, HashSet, InstancePath, ParallelScheduleOptions, ParserError, ScheduledRtl, ScheduledRtlOutput, - SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening, + SettlePartitionMode, SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening, }; use celox_design::{ BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign, @@ -1507,6 +1507,29 @@ pub fn schedule_symbolic_rtl_reporting_loops( } } let parallel_comb_blocks = parallel.enabled().then(|| comb_blocks.clone()); + // The flag object of a partitioned settle is declared once the + // partitions are known; reserve its address now. + let root_instance = expanded[&InstancePath(Vec::new())]; + let settle_flags = + settle_partitioning(parallel, &comb_blocks, &global_arena, eval_apply_ffs.len()).map( + |target_cost| { + let var_id = SourceVarId( + modules[&root_id] + .variables + .keys() + .map(|id| id.0 + 1) + .max() + .unwrap_or(0), + ); + scheduler::SettlePartitioning { + flags: AbsoluteAddr { + instance_id: root_instance, + var_id, + }, + target_cost, + } + }, + ); let sched_start = flatten_timing.then(std::time::Instant::now); let schedule = match scheduler::sort_with_unpacked_element_widths( comb_blocks, @@ -1517,6 +1540,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( &var_widths, &unpacked_element_widths, next_runtime_error_code, + settle_flags, ) { Ok(schedule) => schedule, Err(error) => { @@ -1557,6 +1581,19 @@ pub fn schedule_symbolic_rtl_reporting_loops( }); } }; + let settle_partitions = schedule.partitions.clone(); + + let settle_flags = settle_flags.filter(|_| !settle_partitions.is_empty()); + if let Some(settle) = &settle_flags { + // The flags carry what changed from one settle to the next. + persistent_comb_state.insert(settle.flags); + declare_settle_flags( + &mut modules, + root_id, + settle.flags.var_id, + settle_partitions.len(), + ); + } let object_sizes = super::parallel::ObjectSizes { widths: &var_widths, element_widths: &unpacked_element_widths, @@ -1677,7 +1714,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( // events; that copy lets the FF part use comb values in registers. // Beyond that the copies would multiply the design by its event count, // so the ticks share the one `eval_comb` program instead. - let merge_comb_apply = eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS; + // A merged program drops comb stores the next full settle would redo; + // a partitioned settle keeps what its skipped partitions stored. + let merge_comb_apply = + eval_apply_ffs.len() <= MERGED_COMB_APPLY_EVENTS && settle_flags.is_none(); let mut eval_comb_apply_ffs = HashMap::default(); let mut fused_direct_ff_writes = HashMap::default(); if let ( @@ -1920,6 +1960,21 @@ pub fn schedule_symbolic_rtl_reporting_loops( .chain(bound_initials) .map(|(_, init)| init) .collect(); + if let Some(settle) = &settle_flags { + // Every partition runs at the first settle. + let partitions = settle_partitions.len(); + let value = (0..partitions).fold(BigUint::default(), |value, partition| { + value | (BigUint::from(1u8) << (partition * 8)) + }); + initial_memory_values.push(InitialStateValue { + address: settle.flags, + data: InitialStateData::Packed { + value, + mask: BigUint::default(), + written_mask: (BigUint::from(1u8) << ((partitions + 1) * 8)) - 1u8, + }, + }); + } let state_objects: HashMap = instance_modules .iter() .flat_map(|(&instance_id, module_id)| { @@ -1940,7 +1995,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(); let declaration_startup = processes .iter() - .any(|process| process.slots.is_initializer) + .any(|process| process.slots.kind == celox_design::ProcessKind::Initializer) .then(|| { let targets: BTreeSet<_> = folded_initials.iter().map(|init| init.address).collect(); let mut reset = targets @@ -2326,6 +2381,32 @@ pub fn schedule_symbolic_rtl_reporting_loops( let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); let root_instance = expanded[&InstancePath(Vec::new())]; + let settle_partitions = settle_flags.map(|settle| { + let mut marks: HashMap> = HashMap::default(); + for (index, partition) in settle_partitions.iter().enumerate() { + let index = index as u32; + for addr in &partition.reads { + if let Some(&state) = source_to_state.get(addr) { + marks.entry(state).or_default().insert(index); + } + } + for addr in &partition.writes { + if let Some(&state) = source_to_state.get(addr) { + marks.entry(state).or_default().insert(index); + } + } + } + let mut marks = marks + .into_iter() + .map(|(state, partitions)| (state, partitions.into_iter().collect())) + .collect::>(); + marks.sort_unstable(); + celox_design::SettlePartitions { + flags: project(settle.flags), + partitions: settle_partitions.len() as u32, + marks, + } + }); let scheduler = scheduler_slots.map(|slots| celox_design::SchedulerSchema { slots: slots.map(|var_id| { project(AbsoluteAddr { @@ -2468,6 +2549,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( time_slots, scheduler, derived_edges: Vec::new(), + settle_partitions, }, }; @@ -2485,6 +2567,77 @@ pub fn schedule_symbolic_rtl_reporting_loops( }) } +/// Smallest combinational program, in expression nodes, whose settle +/// [`SettlePartitionMode::Estimated`] partitions. +const MIN_PARTITIONED_SETTLE_COST: usize = 20_000; +/// Expression nodes per partition of an estimated partitioned settle. +const SETTLE_PARTITION_COST: usize = 2_000; + +/// The cost per partition of a partitioned settle of `comb_blocks`, or +/// `None` to keep one pass. +/// +/// A partition costs a flag test per settle and flag stores in every writer +/// of what it reads, and pays off when most of the program is idle in most +/// settles. A design with few event domains drives most of its logic from +/// one clock, so it keeps the single pass, as does a small program. +fn settle_partitioning( + parallel: &ParallelScheduleOptions, + comb_blocks: &[LogicPath], + arena: &SLTNodeArena, + events: usize, +) -> Option { + // Lane-partitioned kernels run the comb program as lane tasks. + if parallel.enabled() { + return None; + } + match parallel.settle { + SettlePartitionMode::Off => None, + SettlePartitionMode::Always => Some(1), + SettlePartitionMode::Estimated => { + if events <= MERGED_COMB_APPLY_EVENTS { + return None; + } + let cost: usize = comb_blocks + .iter() + .map(|path| scheduler::path_cost(arena, path)) + .sum(); + (cost >= MIN_PARTITIONED_SETTLE_COST).then_some(SETTLE_PARTITION_COST) + } + } +} + +/// Declare the flags of a settle of `partitions` partitions, one byte each +/// plus the untracked byte, as a hidden variable of the top module. +fn declare_settle_flags( + modules: &mut HashMap, + root: ModuleId, + var_id: SourceVarId, + partitions: usize, +) { + let width = (partitions + 1) * 8; + let variables = &mut modules.get_mut(&root).expect("top module").variables; + variables.insert( + var_id, + crate::symbolic::artifact::SymbolicVariable { + path: vec!["$settle".to_string(), "flags".to_string()], + kind: crate::VariableKind::Variable, + signed: false, + metadata: VariableMetadata { + width, + is_4state: false, + kind: DomainKind::Other, + type_kind: celox_design::PortTypeKind::Bit, + array_dims: Vec::new(), + value_kind: Default::default(), + }, + packed_dims: vec![width], + unpacked_ranges: Vec::new(), + source: None, + module_affiliated: false, + }, + ); +} + /// Declare the hidden objects a compiled scheduler exchanges with the /// runtime (`RuntimeSchema::scheduler`) as variables of the top module, for /// a design with `process_count` process kernels. A design without kernels diff --git a/crates/celox-frontend-core/src/symbolic/parallel.rs b/crates/celox-frontend-core/src/symbolic/parallel.rs index dccfada3730..f0824ef3d88 100644 --- a/crates/celox-frontend-core/src/symbolic/parallel.rs +++ b/crates/celox-frontend-core/src/symbolic/parallel.rs @@ -27,6 +27,22 @@ pub struct ParallelScheduleOptions { /// Smallest accepted estimated speedup of a partitioned phase, in /// percent of its single-lane cost. pub minimum_speedup_percent: u64, + /// Whether the combinational settle may be split into partitions that + /// run only when what they read changed. Only a host that reports its + /// writes and instruments the units it generates may request it. + pub settle: SettlePartitionMode, +} + +/// Whether a settle is partitioned ([`ParallelScheduleOptions::settle`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SettlePartitionMode { + /// One pass over the whole combinational program. + #[default] + Off, + /// Partition designs with many event domains and a large program. + Estimated, + /// Partition every program into the smallest partitions. For tests. + Always, } impl ParallelScheduleOptions { @@ -35,6 +51,7 @@ impl ParallelScheduleOptions { lanes: 1, synchronization_cost: 400, minimum_speedup_percent: 125, + settle: SettlePartitionMode::Off, }; /// Request `lanes` simulation lanes with the default cost model. diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b5b0d177f4c..11a49c86e24 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1348,7 +1348,7 @@ fn kernel_window_writes( for process in module .initial_processes() .iter() - .filter(|process| !process.is_initializer()) + .filter(|process| !process.is_initializer() && !process.is_final()) { let body = process.body(); let first = if process.repeats() { @@ -4978,6 +4978,7 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig let construct = match process.site() { Some(site) => site.construct, None if process.is_initializer() => "declaration initializer", + None if process.is_final() => "final", None if process.repeats() => "always", None => "initial", }; @@ -4988,9 +4989,9 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig } } -/// The `initial` blocks and declaration initializers (IEEE 1800-2023 9.2.1, -/// 10.5): the initial state they define, and the processes that run the -/// others from time zero. +/// Lower declaration initializers and procedural kernels. Final procedures +/// retain kernels but execute only at simulation termination (9.2.3); they +/// must never contribute folded initial state. /// /// A block whose writes have constant values defines initial state, with /// the hidden variables used while executing it discarded. Declaration @@ -5062,7 +5063,10 @@ fn lower_initial_processes( // initial state. A program's `initial` procedure runs in the reactive // region set (IEEE 1800-2023 24.3.1), after the design's processes of // time zero, so it is not folded either. - if process.repeats() || (module.is_program() && !process.is_initializer()) { + if process.is_final() + || process.repeats() + || (module.is_program() && !process.is_initializer()) + { runtime.push((process, random_seed)); continue; } @@ -5138,8 +5142,8 @@ fn lower_initial_processes( id }; ProcessSlots { - is_initializer: process.is_initializer(), - requires_timed_simulation: process.is_scheduled_edge(), + kind: process.kind(), + requires_timed_simulation: process.is_scheduled_edge() || process.is_final(), const_delays: false, program: None, resume: declare("resume", PROCESS_RESUME_WIDTH), @@ -5155,10 +5159,10 @@ fn lower_initial_processes( let program = slots .iter() .zip(&runtime) - .find(|(_, (process, _))| !process.is_initializer()) + .find(|(_, (process, _))| !process.is_initializer() && !process.is_final()) .map(|(slots, _)| slots.status); for (slots, (process, _)) in slots.iter_mut().zip(&runtime) { - if !process.is_initializer() { + if !process.is_initializer() && !process.is_final() { slots.program = program; } } @@ -10725,7 +10729,7 @@ endmodule .runtime_schema .processes .iter() - .filter(|process| !process.is_initializer) + .filter(|process| process.kind != celox_design::ProcessKind::Initializer) .count() } diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 94ba20cf12e..05bb918ca1e 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -119,6 +119,27 @@ pub trait SimBackend { assert!(offset + bytes.len() <= len, "write past the memory image"); // Safety: the backend exposes `len` writable bytes at `ptr`. unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr.add(offset), bytes.len()) }; + self.mark_settle_range(offset, bytes.len()); + } + + /// Set the flags of the settle partitions reading `offset..offset + len`, + /// which the host wrote. + fn mark_settle_range(&mut self, offset: usize, len: usize) { + if let Some(settle) = self.layout().settle.as_ref() { + let (ptr, _) = self.memory_as_ptr(); + // SAFETY: the settle layout describes this backend's state image. + unsafe { settle.mark_range(ptr.cast_mut(), offset, len) }; + } + } + + /// From now on run every settle partition on every settle: a raw view + /// of the state can change it without reporting. + fn mark_settle_untracked(&mut self) { + if let Some(settle) = self.layout().settle.as_ref() { + let (ptr, _) = self.memory_as_ptr(); + // SAFETY: the settle layout describes this backend's state image. + unsafe { settle.mark_untracked(ptr.cast_mut()) }; + } } /// Return an opaque owner that keeps the memory allocation alive. @@ -200,17 +221,18 @@ pub trait SimBackend { /// Called by host setters, which share the generated-store notification ABI. fn mark_vcd_signal(&mut self, signal: SignalRef) { + let len = signal.array_layout.map_or_else( + || celox_state_layout::get_byte_size(signal.width), + |array| array.element_count * array.element_stride, + ); if let Some(trace) = self.layout().trace.as_ref() { - let len = signal.array_layout.map_or_else( - || celox_state_layout::get_byte_size(signal.width), - |array| array.element_count * array.element_stride, - ); let (ptr, _) = self.memory_as_ptr(); // SAFETY: layout homes and metadata fit in the writable state image. unsafe { trace.mark_range(ptr.cast_mut(), signal.offset, len); } } + self.mark_settle_range(signal.offset, len); } } diff --git a/crates/celox-runtime/src/error.rs b/crates/celox-runtime/src/error.rs index 33603a87ee6..5cb9f3f2f03 100644 --- a/crates/celox-runtime/src/error.rs +++ b/crates/celox-runtime/src/error.rs @@ -5,6 +5,11 @@ pub enum SimulatorErrorCode { DetectedTrueLoopAt { signals: Vec, }, + /// `$fatal` also implicitly requests simulation termination. + Fatal { + message: String, + signals: Vec, + }, Runtime { message: String, signals: Vec, @@ -36,6 +41,16 @@ impl PartialEq for SimulatorErrorCode { signals: sb, }, ) => a == b && sa == sb, + ( + Self::Fatal { + message: a, + signals: sa, + }, + Self::Fatal { + message: b, + signals: sb, + }, + ) => a == b && sa == sb, (Self::NotAnEvent(a), Self::NotAnEvent(b)) => a == b, _ => false, } @@ -54,8 +69,12 @@ impl std::fmt::Display for SimulatorErrorCode { Self::DetectedTrueLoopAt { signals } => { write!(f, "Detected True Loop: {}", signals.join(", ")) } - Self::Runtime { message, signals } if signals.is_empty() => write!(f, "{message}"), - Self::Runtime { message, signals } => { + Self::Fatal { message, signals } | Self::Runtime { message, signals } + if signals.is_empty() => + { + write!(f, "{message}") + } + Self::Fatal { message, signals } | Self::Runtime { message, signals } => { write!(f, "{}: {}", message, signals.join(", ")) } Self::InternalError => write!(f, "Internal Error"), diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 064c9049bad..99e07af4d2a 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -198,7 +198,7 @@ impl ResolvedSchedule { .processes .iter() .map(|process| ProcessRefs { - is_initializer: process.slots.is_initializer, + kind: process.slots.kind, program: process.slots.program.as_ref().map(resolve), resume: resolve(&process.slots.resume), starts_with_event_wait: process.slots.requires_timed_simulation, @@ -312,7 +312,9 @@ impl ResolvedSchedule { program_processes: processes .iter() .enumerate() - .filter(|(_, process)| process.program.is_some()) + .filter(|(_, process)| { + process.kind == celox_design::ProcessKind::Regular && process.program.is_some() + }) .map(|(index, _)| index) .collect(), processes, diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 7173050bca6..852dd20dd2e 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -161,6 +161,10 @@ impl SimulationState { } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } let _ = self.finish_timed_boundary(executor, self.scheduler.time); let _ = executor.flush_output(); Err(error) diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index dded48af181..a0e68d89208 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -10,6 +10,7 @@ mod persist; mod process; mod round; mod stats; +mod terminal; mod time; mod wait; @@ -146,6 +147,8 @@ pub struct SimulationState { host_pending: bool, /// A process requested the end of the simulation. finished: bool, + /// Next final procedure while terminal execution is suspended by `$stop`. + finalizing: Option, /// A process suspended the simulation (`$stop`) in the last step. stopped: bool, /// The round a `$stop` suspended, which the next step continues. @@ -193,7 +196,9 @@ impl SimulationState { .processes .iter() .enumerate() - .filter_map(|(index, process)| process.is_initializer.then_some(index)) + .filter_map(|(index, process)| { + (process.kind == celox_design::ProcessKind::Initializer).then_some(index) + }) .collect(); let declarations_pending = !declaration_processes.is_empty(); let mut state = Self { @@ -202,6 +207,7 @@ impl SimulationState { last_clock_unknown: BitSet::new(), four_state: backend.layout().four_state, process_wakeups: (0..model.processes.len()) + .filter(|&index| model.processes[index].kind != celox_design::ProcessKind::Final) .map(|process| Reverse((0, process))) .collect(), model, @@ -210,6 +216,7 @@ impl SimulationState { declarations_pending, host_pending: false, finished: false, + finalizing: None, stopped: false, suspended: None, scratch: None, @@ -253,6 +260,13 @@ impl SimulationState { E: SimulationExecutor, { self.stopped = false; + if self.finalizing.is_some() { + if self.scheduler.time > limit { + return Ok(None); + } + self.finalize_terminal(executor)?; + return Ok(Some(self.scheduler.time)); + } match self.step_time(executor, limit) { Ok(time) => Ok(time), Err(Halt::Finish) => { @@ -262,6 +276,10 @@ impl SimulationState { // The time slot goes on when the simulation continues. Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } // Preserve the primary runtime failure even if diagnostic // waveform output also fails. This does not resume processes. let _ = self.finish_timed_boundary(executor, self.scheduler.time); @@ -312,7 +330,10 @@ impl SimulationState { // A process the scheduler does not run waits: the slot stays in // the reference loop. Test that first, as designs with such // processes fail it at every step. - let compiled = if compiles && self.process_state.waiters.len() <= waiting_kernels { + let compiled = if self.finalizing.is_none() + && compiles + && self.process_state.waiters.len() <= waiting_kernels + { self.compiled_limit(executor, end, observer.one_slot()) } else { None @@ -405,9 +426,14 @@ impl SimulationState { { match executor.try_finish_timed_step(time) { Ok(()) => Ok(()), - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + } + Err(error) + } Err(Halt::Finish) => { - self.finish_checked(executor)?; + self.finalize_terminal(executor)?; Ok(()) } Err(Halt::Stop) => { @@ -417,34 +443,6 @@ impl SimulationState { } } - fn finish_checked(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> - where - E: SimulationExecutor, - { - self.finished = true; - executor.try_freeze() - } - - /// Once $finish is consumed, output errors must not make execution resumable. - pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> - where - E: SimulationExecutor, - { - self.finished = true; - let output = self.finish_timed_boundary(executor, self.scheduler.time); - let frozen = executor.try_freeze(); - output.and(frozen) - } - - /// End the simulation where it is. - pub fn finish(&mut self, executor: &mut E) - where - E: SimulationExecutor, - { - self.finished = true; - executor.freeze(); - } - /// Whether a process requested the end of the simulation. pub fn is_finished(&self) -> bool { self.finished @@ -461,7 +459,8 @@ impl SimulationState { /// Whether the simulation is suspended in the middle of a time slot, so /// that its scheduling state cannot be captured. pub fn is_suspended(&self) -> bool { - self.suspended.is_some() || (self.stopped && self.declarations_pending) + self.suspended.is_some() + || (self.stopped && (self.declarations_pending || self.finalizing.is_some())) } /// Settle externally driven state against the previous edge baseline even @@ -486,6 +485,10 @@ impl SimulationState { } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } // Preserve the primary runtime failure even if diagnostic // waveform output also fails. This does not resume processes. let _ = self.finish_timed_boundary(executor, self.scheduler.time); @@ -556,7 +559,7 @@ impl SimulationState { return None; } // Host writes are work of the current time. - if self.host_pending { + if self.host_pending || self.finalizing.is_some() { return Some(self.scheduler.time); } self.next_work_time() diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index aa0a94ff8e9..d652d9f9e82 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -26,6 +26,7 @@ impl SimulationState { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, } } @@ -63,6 +64,7 @@ impl SimulationState { self.declarations_pending = snapshot.declarations_pending; self.host_pending = snapshot.host_pending; self.finished = snapshot.finished; + self.finalizing = snapshot.finalizing; self.stopped = false; self.suspended = None; Ok(()) @@ -190,17 +192,14 @@ impl SimulationState { .map(|(process, time)| Reverse((time, process))) .collect(); self.process_state = parts.process_state; - self.declarations_pending = self - .process_wakeups - .iter() - .any(|Reverse((_, index))| self.model.processes[*index].is_initializer) - || self - .process_state - .ready - .iter() - .any(|&index| self.model.processes[index].is_initializer); + self.declarations_pending = self.process_wakeups.iter().any(|Reverse((_, index))| { + self.model.processes[*index].kind == celox_design::ProcessKind::Initializer + }) || self.process_state.ready.iter().any(|&index| { + self.model.processes[index].kind == celox_design::ProcessKind::Initializer + }); self.host_pending = parts.host_pending; self.finished = parts.finished; + self.finalizing = None; self.stopped = false; self.suspended = None; } @@ -218,6 +217,7 @@ pub struct SimulationSnapshot { declarations_pending: bool, host_pending: bool, finished: bool, + finalizing: Option, } impl Clone for SimulationSnapshot { @@ -233,6 +233,7 @@ impl Clone for SimulationSnapshot { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, } } } @@ -300,6 +301,7 @@ impl SimulationState { declarations_pending: self.declarations_pending, host_pending: self.host_pending, finished: self.finished, + finalizing: self.finalizing, stopped: self.stopped, suspended: self.suspended.is_some(), } @@ -329,6 +331,7 @@ pub struct ScheduleKey { pub declarations_pending: bool, pub host_pending: bool, pub finished: bool, + pub finalizing: Option, pub stopped: bool, pub suspended: bool, } diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index bc74b2729d8..e8a7324dabd 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -29,7 +29,12 @@ impl SimulationState { self.stopped = true; Ok(()) } - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + } + Err(error) + } } } diff --git a/crates/celox-runtime/src/simulation/terminal.rs b/crates/celox-runtime/src/simulation/terminal.rs new file mode 100644 index 00000000000..8d2553e935d --- /dev/null +++ b/crates/celox-runtime/src/simulation/terminal.rs @@ -0,0 +1,99 @@ +//! Terminal procedures run sequentially, without scheduling another HDL event. + +use celox_design::{HostRequestKind, ProcessKind, ProcessStatus}; + +use super::{SimulationExecutor, SimulationState}; +use crate::{SimulatorErrorCode, backend::SimBackend, timing::Halt}; + +impl SimulationState { + /// Finish once, running final procedures before flushing output and freezing. + /// A `$stop` in a final procedure suspends this phase; the next step resumes it. + pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + if self.finished { + return Ok(()); + } + self.stopped = false; + if self.finalizing.is_none() { + // An explicit host finish may replace a stopped ordinary round. + self.suspended = None; + self.host_pending = false; + self.finalizing = Some(0); + } + let result = self.run_final_procedures(executor); + if matches!(result, Err(Halt::Stop)) { + self.stopped = true; + return Ok(()); + } + // A failed final procedure or output flush cannot make termination resumable. + self.finished = true; + self.finalizing = None; + let output = self.finish_timed_boundary(executor, self.scheduler.time); + let frozen = executor.try_freeze(); + match result { + Ok(()) | Err(Halt::Finish) => output.and(frozen), + Err(Halt::Error(error)) => Err(error), + Err(Halt::Stop) => unreachable!(), + } + } + + /// Explicitly end simulation at its current time. Merely exhausting currently + /// scheduled work does not end an externally driven simulation. + pub fn finish(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.finalize_terminal(executor) + } + + fn run_final_procedures(&mut self, executor: &mut E) -> Result<(), Halt> + where + E: SimulationExecutor, + { + let mut returns = 0; + while let Some(index) = self + .finalizing + .filter(|&index| index < self.model.processes.len()) + { + let process = &self.model.processes[index]; + if process.kind != ProcessKind::Final { + self.finalizing = Some(index + 1); + continue; + } + executor.run_process(index)?; + returns += 1; + self.charge(returns, Some(index))?; + let status: u8 = executor.backend().get_as(process.status); + match ProcessStatus::from_code(status) { + Some(ProcessStatus::Done) => self.finalizing = Some(index + 1), + Some(ProcessStatus::Finish) => return Err(Halt::Finish), + Some(ProcessStatus::Stop) => return Err(Halt::Stop), + Some(ProcessStatus::HostRequest) => { + let encoded: u64 = executor.backend().get_as(process.delay); + let (kind, site) = HostRequestKind::decode(encoded) + .ok_or(SimulatorErrorCode::InternalError)?; + let request = process + .host_requests + .iter() + .filter(|request| request.kind == kind) + .nth(site as usize) + .ok_or(SimulatorErrorCode::InternalError)?; + executor.host_request(request, self.scheduler.time)?; + } + // Yield is an implementation boundary, not an HDL timing control. + // NBA events created by a final never run after termination (9.2.3). + Some(ProcessStatus::Yield | ProcessStatus::Nba) => {} + _ => { + return Err(SimulatorErrorCode::Runtime { + message: "final procedure cannot suspend for HDL timing".into(), + signals: Vec::new(), + } + .into()); + } + } + } + Ok(()) + } +} diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index e25822ae243..89f621c1e8d 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -299,7 +299,10 @@ impl SimulationState { if self.finished { return None; } - if !self.process_state.ready.is_empty() || !self.process_state.reactive.is_empty() { + if self.finalizing.is_some() + || !self.process_state.ready.is_empty() + || !self.process_state.reactive.is_empty() + { return Some(self.scheduler.time); } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 9edb4ed0927..20cdc112493 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -153,7 +153,7 @@ pub struct NbaSiteRefs { /// Control slots and sites of one process kernel. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { - pub is_initializer: bool, + pub kind: celox_design::ProcessKind, /// The status slot naming the program instance of a program kernel /// ([`celox_design::ProcessSlots::program`]), which runs in the reactive /// region set. @@ -175,7 +175,7 @@ impl ProcessRefs { /// A process without wait or nonblocking sites. pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { - is_initializer: false, + kind: celox_design::ProcessKind::Regular, program: None, resume: status, starts_with_event_wait: false, diff --git a/crates/celox-sir-opt/src/lib.rs b/crates/celox-sir-opt/src/lib.rs index 352f3cbc005..57d173ca032 100644 --- a/crates/celox-sir-opt/src/lib.rs +++ b/crates/celox-sir-opt/src/lib.rs @@ -102,5 +102,6 @@ pub fn optimize( mod policy; pub use policy::{ - OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SirDiagnostics, SirPass, + OptLevel, OptimizeOptions, ParallelPartition, PassOptions, SettlePartition, SirDiagnostics, + SirPass, }; diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs index 7ec294253c5..8d6b6973002 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_identity_store_bypass.rs @@ -44,6 +44,14 @@ struct StoreCandidate { struct GlobalIdentityFacts { accesses: HashMap, stores: Vec, + /// In a partitioned settle, where each address is loaded and the + /// immediate dominators of every unit (see [`reads_follow_store`]). + settle_loads: Option, +} + +struct SettleLoads { + sites: HashMap>, + immediate_dominators: Vec>, } /// Analyze all combinational units before selecting any whole-program address @@ -69,15 +77,27 @@ pub(in crate::optimizer) fn optimize_program_identity_stores( ); blocked_aliases.extend(program.design.initial_state.iter().map(|init| init.address)); + let settle_flags = settle_flags(program); optimize_eval_comb_identity_stores( &mut program.sir.eval_comb, &metadata, &blocked_aliases, program.layout_requirements.state_aliases(), four_state, + settle_flags, ) } +/// The flags of a partitioned settle, whose guards skip a partition only +/// when it would store what memory already holds. +fn settle_flags(program: &OptimizationContext) -> Option { + program + .runtime_schema + .settle_partitions + .as_ref() + .map(|settle| settle.flags) +} + fn address_metadata(program: &OptimizationContext) -> HashMap { program .design @@ -101,8 +121,9 @@ fn optimize_eval_comb_identity_stores( blocked_aliases: &HashSet, existing_aliases: &HashMap, four_state: bool, + settle_flags: Option, ) -> HashMap { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); let aliases = select_aliases( &facts, metadata, @@ -129,20 +150,36 @@ pub(crate) fn retain_final_identity_aliases(program: &mut OptimizationContext, f let aliases = program.layout_requirements.state_aliases().clone(); let mut valid = aliases.keys().copied().collect::>(); + let settle_flags = settle_flags(program); retain_aliases_valid_for_units( &program.sir.eval_comb, &aliases, &metadata, four_state, + settle_flags, &mut valid, ); for units in program.sir.eval_comb_apply_ffs.values() { - retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid); + retain_aliases_valid_for_units( + units, + &aliases, + &metadata, + four_state, + settle_flags, + &mut valid, + ); } // The lane-partitioned combinational kernel is one more projection of the // same comb logic, lowered and optimized independently. with_parallel_comb_units(program, |units| { - retain_aliases_valid_for_units(units, &aliases, &metadata, four_state, &mut valid); + retain_aliases_valid_for_units( + units, + &aliases, + &metadata, + four_state, + settle_flags, + &mut valid, + ); }); program .layout_requirements @@ -190,17 +227,31 @@ pub(crate) fn remove_final_identity_alias_stores( return; } let metadata = address_metadata(program); + let settle_flags = settle_flags(program); remove_proven_alias_stores( &mut program.sir.eval_comb, validated_aliases, &metadata, four_state, + settle_flags, ); for units in program.sir.eval_comb_apply_ffs.values_mut() { - remove_proven_alias_stores(units, validated_aliases, &metadata, four_state); + remove_proven_alias_stores( + units, + validated_aliases, + &metadata, + four_state, + settle_flags, + ); } with_parallel_comb_units(program, |units| { - remove_proven_alias_stores(units, validated_aliases, &metadata, four_state); + remove_proven_alias_stores( + units, + validated_aliases, + &metadata, + four_state, + settle_flags, + ); }); } @@ -263,9 +314,10 @@ fn retain_aliases_valid_for_units( aliases: &HashMap, metadata: &HashMap, four_state: bool, + settle_flags: Option, valid: &mut HashSet, ) { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); valid.retain(|alias| { aliases .get(alias) @@ -316,8 +368,9 @@ fn remove_proven_alias_stores( aliases: &HashMap, metadata: &HashMap, four_state: bool, + settle_flags: Option, ) { - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, settle_flags); let mut sites = aliases .iter() .filter_map(|(&alias, &canonical)| proven_alias_store(&facts, alias, canonical).flatten()) @@ -373,7 +426,7 @@ fn analyze_eval_comb_aliases( ) -> HashMap { // Phase 1: collect every read/write and every syntactic store candidate. // No alias decision is made while the scan is incomplete. - let facts = collect_global_facts(units, metadata, four_state); + let facts = collect_global_facts(units, metadata, four_state, None); // Phase 2: require the completed global facts for both identity and // duplicate-store proofs. @@ -390,9 +443,14 @@ fn collect_global_facts( units: &[ExecutionUnit], metadata: &HashMap, four_state: bool, + settle_flags: Option, ) -> GlobalIdentityFacts { let mut accesses = HashMap::::default(); let mut stores = Vec::new(); + let mut settle_loads = settle_flags.map(|_| SettleLoads { + sites: HashMap::default(), + immediate_dominators: units.iter().map(immediate_dominators).collect(), + }); for (eu_index, eu) in units.iter().enumerate() { let mut defs = HashMap::default(); @@ -408,7 +466,7 @@ fn collect_global_facts( // each candidate applies a sparse decrement map rather than cloning // this whole table. let use_counts = register_use_counts(eu); - let must_execute = must_execute_blocks(eu); + let must_execute = must_execute_blocks(eu, settle_flags); for block in eu.blocks.values() { for (instruction_index, inst) in block.instructions.iter().enumerate() { @@ -417,6 +475,13 @@ fn collect_global_facts( increment_saturating( &mut accesses.entry(address.absolute_addr()).or_default().reads, ); + if let Some(loads) = &mut settle_loads { + loads + .sites + .entry(address.absolute_addr()) + .or_default() + .push((eu_index, block.id, instruction_index)); + } } SIRInstruction::Store( address, @@ -477,6 +542,14 @@ fn collect_global_facts( increment_saturating( &mut accesses.entry(source.absolute_addr()).or_default().reads, ); + if let Some(loads) = &mut settle_loads { + // A commit reads its source outside any proof here. + loads + .sites + .entry(source.absolute_addr()) + .or_default() + .push((usize::MAX, block.id, instruction_index)); + } increment_saturating( &mut accesses .entry(destination.absolute_addr()) @@ -498,7 +571,108 @@ fn collect_global_facts( store.address, ) }); - GlobalIdentityFacts { accesses, stores } + GlobalIdentityFacts { + accesses, + stores, + settle_loads, + } +} + +/// Whether every read of `store`'s address comes after the store: later in +/// its block, in a block it dominates, or in a later unit, which the +/// topological order runs after it. Then an alias reads what the store +/// would have written. +/// +/// Only a partitioned settle relaxes the unread rule this way: there a +/// reader in a later partition loads a copy's target from memory, where the +/// single pass forwards the stored register. +fn reads_follow_store(facts: &GlobalIdentityFacts, store: &StoreCandidate) -> bool { + let Some(loads) = &facts.settle_loads else { + return false; + }; + let address = store.address.absolute_addr(); + let Some(sites) = loads.sites.get(&address) else { + return true; + }; + sites.iter().all(|&(eu_index, block, instruction_index)| { + if eu_index == usize::MAX { + return false; + } + if eu_index != store.eu_index { + return eu_index > store.eu_index; + } + if block == store.block { + return instruction_index > store.instruction_index; + } + let dominators = &loads.immediate_dominators[eu_index]; + let mut current = block; + while let Some(&parent) = dominators.get(¤t) { + if parent == store.block { + return true; + } + if parent == current { + return false; + } + current = parent; + } + false + }) +} + +/// The immediate dominator of every block of `eu` reachable from its entry; +/// the entry is its own. +fn immediate_dominators(eu: &ExecutionUnit) -> HashMap { + let blocks = reverse_postorder_with(eu, &terminator_successors); + let indices = blocks + .iter() + .copied() + .enumerate() + .map(|(index, block)| (block, index)) + .collect::>(); + let mut predecessors = vec![Vec::new(); blocks.len()]; + for (index, block_id) in blocks.iter().enumerate() { + if let Some(block) = eu.blocks.get(block_id) { + for successor in terminator_successors(&block.terminator) { + if let Some(&successor_index) = indices.get(&successor) { + predecessors[successor_index].push(index); + } + } + } + } + let mut immediate_dominator = vec![None; blocks.len()]; + if blocks.is_empty() { + return HashMap::default(); + } + immediate_dominator[0] = Some(0); + let mut changed = true; + while changed { + changed = false; + for block in 1..blocks.len() { + let mut defined = predecessors[block] + .iter() + .copied() + .filter(|&predecessor| immediate_dominator[predecessor].is_some()); + let Some(mut new_dominator) = defined.next() else { + continue; + }; + for predecessor in defined { + if let Some(intersection) = + intersect_dominators(predecessor, new_dominator, &immediate_dominator) + { + new_dominator = intersection; + } + } + if immediate_dominator[block] != Some(new_dominator) { + immediate_dominator[block] = Some(new_dominator); + changed = true; + } + } + } + immediate_dominator + .into_iter() + .enumerate() + .filter_map(|(index, dominator)| Some((blocks[index], blocks[dominator?]))) + .collect() } fn identity_commit_is_profitable( @@ -645,7 +819,12 @@ fn select_aliases( || !store.effects_are_removable || blocked_aliases.contains(&alias) || existing_aliases.contains_key(&alias) - || !is_unique_unread_alias(alias, &facts.accesses) + || !(is_unique_unread_alias(alias, &facts.accesses) + || (facts + .accesses + .get(&alias) + .is_some_and(|access| access.writes == 1) + && reads_follow_store(facts, store))) || facts .accesses .get(&canonical) @@ -910,8 +1089,35 @@ fn ff_referenced_addresses(program: &OptimizationContext) -> HashSet) -> HashSet { - let blocks = reverse_postorder(eu); +/// +/// A partitioned settle skips a partition only when its stores would write +/// what memory already holds, so for an identity copy the partition counts +/// as executed: its guard (a branch into a block that stores to +/// `settle_flags`) is treated as always taken. +fn must_execute_blocks( + eu: &ExecutionUnit, + settle_flags: Option, +) -> HashSet { + let successors = |terminator: &SIRTerminator| { + if let ( + Some(flags), + SIRTerminator::Branch { + true_block: (body, _), + .. + }, + ) = (settle_flags, terminator) + && eu.blocks.get(body).is_some_and(|block| { + block.instructions.iter().any(|instruction| { + matches!(instruction, SIRInstruction::Store(address, ..) + if address.region == STABLE_REGION && address.absolute_addr() == flags) + }) + }) + { + return vec![*body]; + } + terminator_successors(terminator) + }; + let blocks = reverse_postorder_with(eu, &successors); if blocks.is_empty() { return HashSet::default(); } @@ -927,7 +1133,7 @@ fn must_execute_blocks(eu: &ExecutionUnit) -> HashSet) -> Vec { +fn reverse_postorder_with( + eu: &ExecutionUnit, + successors_of: &dyn Fn(&SIRTerminator) -> Vec, +) -> Vec { if !eu.blocks.contains_key(&eu.entry_block_id) { return Vec::new(); } @@ -1029,7 +1238,7 @@ fn reverse_postorder(eu: &ExecutionUnit) -> Vec { return Vec::new(); }; stack.push((block_id, true)); - let mut successors = terminator_successors(&block.terminator); + let mut successors = successors_of(&block.terminator); successors.reverse(); stack.extend(successors.into_iter().map(|successor| (successor, false))); } @@ -1429,6 +1638,7 @@ mod tests { &HashSet::default(), existing_aliases, four_state, + None, ) } @@ -2349,7 +2559,7 @@ mod tests { .collect(); let metadata = metadata(&[(source, 8), (destination, 8)]); - remove_proven_alias_stores(&mut units, &aliases, &metadata, false); + remove_proven_alias_stores(&mut units, &aliases, &metadata, false, None); assert_eq!( units[0].blocks[&BlockId(0)].instructions, @@ -2374,7 +2584,7 @@ mod tests { &[(0, 8)], )]; let metadata = metadata(&[(source, 8), (destination, 8)]); - let facts = collect_global_facts(&units, &metadata, false); + let facts = collect_global_facts(&units, &metadata, false, None); assert!( proven_alias_store(&facts, destination.absolute_addr(), source.absolute_addr()) diff --git a/crates/celox-sir-opt/src/policy.rs b/crates/celox-sir-opt/src/policy.rs index 90c1664ed84..caa5fca0305 100644 --- a/crates/celox-sir-opt/src/policy.rs +++ b/crates/celox-sir-opt/src/policy.rs @@ -30,7 +30,8 @@ impl OptLevel { pub fn default_enabled(self, pass: SirPass) -> bool { match self { OptLevel::O0 => matches!(pass, SirPass::TailCallSplit), - OptLevel::O1 | OptLevel::O2 => true, + // Opt-in until it pays off on its own (#2013). + OptLevel::O1 | OptLevel::O2 => !matches!(pass, SirPass::PartitionedSettle), } } @@ -122,6 +123,10 @@ define_sir_passes! { /// clock's domain once more, so disabling it trades tick speed for build /// time. DerivedEdgeUnits => "derived_edge_units", + /// Split the combinational settle of designs with many event domains + /// into partitions that run only when state they read changed. Not a + /// SIR transform: the frontend consumes it. Off unless enabled. + PartitionedSettle => "partitioned_settle", } /// Diagnostics and additional verification for the SIR optimizer. /// @@ -167,9 +172,21 @@ pub struct OptimizeOptions { max_native_memory_width: usize, parallel_lanes: u32, parallel_partition: ParallelPartition, + settle_partition: SettlePartition, pub diagnostics: SirDiagnostics, } +/// How the compiler decides whether to partition the combinational settle +/// ([`SirPass::PartitionedSettle`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SettlePartition { + /// Partition designs with many event domains and a large program. + #[default] + Estimated, + /// Partition every program as finely as possible. For tests. + Always, +} + /// How the compiler decides whether a phase gets a lane-partitioned kernel. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum ParallelPartition { @@ -202,6 +219,7 @@ impl OptimizeOptions { }, parallel_lanes: 1, parallel_partition: ParallelPartition::Estimated, + settle_partition: SettlePartition::Estimated, diagnostics: SirDiagnostics::default(), } } @@ -273,6 +291,15 @@ impl OptimizeOptions { self.parallel_partition } + pub fn with_settle_partition(mut self, partition: SettlePartition) -> Self { + self.settle_partition = partition; + self + } + + pub fn settle_partition(&self) -> SettlePartition { + self.settle_partition + } + /// Query whether a specific pass is active. pub fn is_enabled(&self, pass: SirPass) -> bool { if self.enabled.contains(&pass) { @@ -285,10 +312,13 @@ impl OptimizeOptions { } /// Returns true if any SIR transform is enabled: any pass other than - /// the TailCallSplit and DerivedEdgeUnits selectors. + /// the TailCallSplit, DerivedEdgeUnits and PartitionedSettle selectors. pub fn any_enabled(&self) -> bool { SirPass::ALL.iter().any(|&p| { - !matches!(p, SirPass::TailCallSplit | SirPass::DerivedEdgeUnits) && self.is_enabled(p) + !matches!( + p, + SirPass::TailCallSplit | SirPass::DerivedEdgeUnits | SirPass::PartitionedSettle + ) && self.is_enabled(p) }) } diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs index c0aa948bae2..4f2f1390dd8 100644 --- a/crates/celox-slt/src/scheduler.rs +++ b/crates/celox-slt/src/scheduler.rs @@ -2420,6 +2420,37 @@ pub struct ScheduleResult { /// comb/FF schedule. These Stores are semantic state updates rather than /// disposable comb publications. pub direct_ff_writes: Vec>, + /// The partitions of a partitioned settle, in schedule order; empty when + /// the schedule runs as one pass. + pub partitions: Vec>, +} + +/// Request to split a combinational schedule into partitions that run only +/// when state they read changed since they last ran. +/// +/// Byte `p` of `flags`, a two-state object, is partition `p`'s dirty flag: +/// the settle runs the partition only when it is not zero, and clears it. +/// A partition that runs sets the flags of the partitions reading what it +/// writes; every other writer of state a partition reads must set its flag +/// too ([`SettlePartition::reads`]). +#[derive(Clone, Copy, Debug)] +pub struct SettlePartitioning { + pub flags: Addr, + /// Approximate expression nodes per partition. + pub target_cost: usize, +} + +/// One partition of a partitioned settle. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SettlePartition { + /// The state objects the partition reads. A change to any of them must + /// set the partition's flag before the next settle. + pub reads: Vec, + /// The state objects the partition writes. + pub writes: Vec, + /// Whether the partition runs on every settle, because it has effects + /// beyond its stores. + pub pinned: bool, } pub trait ClockFfLowering { @@ -3464,6 +3495,333 @@ const UNROLL_THRESHOLD: usize = 32; /// compatibility matrix for a long run of independent roots. const MAX_JOINT_FOLD_ROOTS: usize = 16; +/// One partition of a settle plan. +struct PlannedPartition { + reads: Vec, + writes: Vec, + /// The partitions whose flags it sets when it runs: those reading what + /// it writes, itself included when it reads the previous value of its + /// own writes. + marks: Vec, + pinned: bool, +} + +/// The partitions of a settle, each a contiguous run of scheduled work. +struct PartitionPlan { + /// The first scheduled work of each partition. + first_work: Vec, + partitions: Vec>, +} + +/// The paths of one piece of scheduled combinational work. +fn work_paths(work: &ScheduledWork) -> &[usize] { + match work { + ScheduledWork::CombPath(path) => std::slice::from_ref(path), + ScheduledWork::CombScc(paths) | ScheduledWork::GuardedComb { paths, .. } => paths, + ScheduledWork::Ff(_) => &[], + } +} + +/// The approximate lowering cost of a path: its distinct expression nodes, +/// or a process unit's instructions. +pub fn path_cost( + arena: &SLTNodeArena, + path: &LogicPath, +) -> usize { + if let LogicPathTarget::Process { unit, .. } = &path.target { + return unit + .blocks + .values() + .map(|block| block.instructions.len() + 1) + .sum(); + } + let mut seen = HashSet::default(); + let mut stack = vec![path.expr]; + let mut cost = 0; + while let Some(node) = stack.pop() { + if !seen.insert(node) { + continue; + } + cost += 1; + match arena.get(node) { + SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]), + SLTNode::Unary(_, operand) + | SLTNode::Slice { expr: operand, .. } + | SLTNode::Capture { expr: operand, .. } => stack.push(*operand), + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => stack.extend([*cond, *then_expr, *else_expr]), + SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)), + // A loop's cost scales with its trip count; count it as large. + SLTNode::ForFold { .. } | SLTNode::ForFoldGroup { .. } => cost += 64, + SLTNode::Input { .. } | SLTNode::Constant(..) => {} + } + } + cost +} + +/// Whether a path's expression captures a value at an evaluation position. +fn path_has_capture( + arena: &SLTNodeArena, + path: &LogicPath, +) -> bool { + if matches!(path.target, LogicPathTarget::CombCaptureEvent { .. }) { + return true; + } + let mut seen = HashSet::default(); + let mut stack = vec![path.expr]; + while let Some(node) = stack.pop() { + if !seen.insert(node) { + continue; + } + match arena.get(node) { + SLTNode::Capture { .. } => return true, + SLTNode::Binary(lhs, _, rhs) => stack.extend([*lhs, *rhs]), + SLTNode::Unary(_, operand) | SLTNode::Slice { expr: operand, .. } => { + stack.push(*operand) + } + SLTNode::Mux { + cond, + then_expr, + else_expr, + } => stack.extend([*cond, *then_expr, *else_expr]), + SLTNode::Concat(parts) => stack.extend(parts.iter().map(|(part, _)| *part)), + _ => {} + } + } + false +} + +/// Whether a path does more than store its value: comb capture events, +/// activation of capture sites, and process units with runtime events or +/// extern calls. A partition holding one runs on every settle. +fn path_has_effects(path: &LogicPath) -> bool { + if !path.comb_capture_enable_sites.is_empty() || path.comb_capture_enable_always { + return true; + } + match &path.target { + LogicPathTarget::CombCaptureEvent { .. } => true, + LogicPathTarget::Process { unit, .. } => unit.blocks.values().any(|block| { + block + .instructions + .iter() + .any(|instruction| match instruction { + SIRInstruction::RuntimeEvent { .. } + | SIRInstruction::CombCaptureEvent { .. } + | SIRInstruction::CombCaptureEnableIfChanged { .. } + | SIRInstruction::ExternCall { .. } => true, + SIRInstruction::Store(.., capture_sites) => !capture_sites.is_empty(), + _ => false, + }) + }), + LogicPathTarget::Var(_) => false, + } +} + +/// Cut a combinational schedule into partitions of about +/// `partitioning.target_cost`, or `None` when it would be one. +fn plan_settle_partitions( + prepared: &PreparedSchedule, + arena: &SLTNodeArena, + var_widths: &HashMap, + partitioning: SettlePartitioning, +) -> Option<(PartitionPlan, Addr)> { + let input = &prepared.input; + // A captured value or a pre-lowered node is materialized at one place + // and reused at a later one through the lowering cache, which a + // partition boundary between them would clear. + if input + .iter() + .any(|path| !path.pre_lower_nodes.is_empty() || path_has_capture(arena, path)) + { + return None; + } + // Whole-variable copies, by target. + let mut copy_source: HashMap = HashMap::default(); + for work in &prepared.scheduled_work { + if let ScheduledWork::CombPath(path) = work + && let Some((target, source)) = whole_variable_copy(arena, &input[*path], var_widths) + { + copy_source.insert(target, source); + } + } + let mut first_work = Vec::new(); + let mut cost = 0; + for (index, work) in prepared.scheduled_work.iter().enumerate() { + if first_work.is_empty() || cost >= partitioning.target_cost { + first_work.push(index); + cost = 0; + } + cost += work_paths(work) + .iter() + .map(|&path| path_cost(arena, &input[path])) + .sum::(); + } + if first_work.len() < 2 { + return None; + } + let mut partition_of_work = vec![0; prepared.scheduled_work.len()]; + for (partition, &first) in first_work.iter().enumerate() { + let end = first_work + .get(partition + 1) + .copied() + .unwrap_or(prepared.scheduled_work.len()); + partition_of_work[first..end].fill(partition); + } + let count = first_work.len(); + let mut reads = vec![BTreeSet::new(); count]; + let mut writes = vec![BTreeSet::new(); count]; + let mut previous = vec![BTreeSet::new(); count]; + let mut pinned = vec![false; count]; + for (index, work) in prepared.scheduled_work.iter().enumerate() { + let partition = partition_of_work[index]; + for &path_index in work_paths(work) { + let path = &input[path_index]; + pinned[partition] |= path_has_effects(path); + let atoms = path + .sources + .iter() + .chain(&path.address_sources) + .chain(&path.previous_sources); + reads[partition].extend(atoms.map(|atom| atom.id)); + // A process's activation guard reads its occurrence counters and + // startup slots as well. + if let LogicPathTarget::Process { + sensitivity_counters, + startup, + unit, + .. + } = &path.target + { + // The unit may read more than its listed sources, such as + // force controls. It runs at its process's first projection + // and writes every output there. + for block in unit.blocks.values() { + for instruction in &block.instructions { + match instruction { + SIRInstruction::Load(_, address, ..) => { + reads[partition].insert(*address); + } + SIRInstruction::Store(address, ..) => { + writes[partition].insert(*address); + } + SIRInstruction::Commit(source, target, ..) => { + reads[partition].insert(*source); + writes[partition].insert(*target); + } + _ => {} + } + } + } + for (atom, counter) in sensitivity_counters { + reads[partition].extend([atom.id, *counter]); + } + if let Some(startup) = startup { + reads[partition].insert(startup.initialized); + for (atom, slot) in &startup.inputs { + reads[partition].extend([atom.id, *slot]); + } + for (counter, slot) in &startup.counters { + reads[partition].extend([*counter, *slot]); + } + } + } + previous[partition].extend(path.previous_sources.iter().map(|atom| atom.id)); + if let Some(target) = path.target.var() { + writes[partition].insert(target.id); + } + } + } + // Reading a copy's target reads its source: the copy may become an + // alias of its source, whose changes then reach the target without the + // copy running. + for read in &mut reads { + let mut sources = Vec::new(); + for &addr in read.iter() { + let mut current = addr; + let mut steps = 0; + while let Some(&source) = copy_source.get(¤t) { + sources.push(source); + current = source; + steps += 1; + if steps > copy_source.len() { + break; + } + } + } + read.extend(sources); + } + let mut readers: HashMap> = HashMap::default(); + for (partition, read) in reads.iter().enumerate() { + for &addr in read { + readers.entry(addr).or_default().push(partition); + } + } + let partitions = (0..count) + .map(|partition| { + let mut marks = BTreeSet::new(); + for addr in &writes[partition] { + for &reader in readers.get(addr).into_iter().flatten() { + if reader != partition || previous[partition].contains(addr) { + marks.insert(reader); + } + } + } + PlannedPartition { + reads: reads[partition].iter().copied().collect(), + writes: writes[partition].iter().copied().collect(), + marks: marks.into_iter().collect(), + pinned: pinned[partition], + } + }) + .collect(); + Some(( + PartitionPlan { + first_work, + partitions, + }, + partitioning.flags, + )) +} + +/// The `(target, source)` of a path that copies one whole variable into +/// another of the same width. +fn whole_variable_copy( + arena: &SLTNodeArena, + path: &LogicPath, + var_widths: &HashMap, +) -> Option<(Addr, Addr)> { + if !path.transparent_copy || !path.previous_sources.is_empty() { + return None; + } + let target = match &path.target { + LogicPathTarget::Var(target) => target, + _ => return None, + }; + let width = *var_widths.get(&target.id)?; + if target.access.lsb != 0 || target.access.msb + 1 != width { + return None; + } + match arena.get(path.expr) { + SLTNode::Input { + variable, + index, + access, + .. + } if index.is_empty() + && access.lsb == 0 + && access.msb + 1 == width + && var_widths.get(variable) == Some(&width) + && *variable != target.id => + { + Some((target.id, *variable)) + } + _ => None, + } +} + /// Lowering state for one sequence of scheduled work emitted through one SIR /// builder. Register numbers and the expression cache are local to it. struct WorkLowering<'a, Addr: Clone + Eq + Hash> { @@ -3478,6 +3836,11 @@ struct WorkLowering<'a, Addr: Clone + Eq + Hash> { /// The processes whose unit an acyclic projection has run (see /// [`Self::lower`]). run_processes: HashSet, + /// Inside a partition of a partitioned settle, which units must not + /// split. + in_partition: bool, + /// Where a guarded partition continues when it is skipped. + partition_merge: Option, } impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a, Addr> { @@ -3492,9 +3855,102 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a pending_fold_indices: Vec::new(), pending_fold_roots: HashSet::default(), run_processes: HashSet::default(), + in_partition: false, + partition_merge: None, } } + /// Open partition `index`: run it only when its flag or the untracked + /// byte (`untracked`) is set, and clear its flag. Values computed before + /// it may be reused inside, but not the other way round, so the + /// expression cache starts over. + fn begin_partition( + &mut self, + flags: Addr, + index: usize, + untracked: usize, + partition: &PlannedPartition, + ) { + self.flush_pending_folds(); + if self.context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT { + if let Some(eu) = self.builder.flush_eu() { + self.execution_units.push(eu); + } + } + self.lower_cache.clear(); + self.in_partition = true; + let offset = SIROffset::Static(index * 8); + if !partition.pinned { + let own = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Load(own, flags, offset.clone(), 8)); + let all = self.builder.alloc_bit(8, false); + self.builder.emit(SIRInstruction::Load( + all, + flags, + SIROffset::Static(untracked * 8), + 8, + )); + let flag = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Binary(flag, own, BinaryOp::Or, all)); + let zero = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(zero, SIRValue::new(0u64))); + let dirty = self.builder.alloc_bit(1, false); + self.builder + .emit(SIRInstruction::Binary(dirty, flag, BinaryOp::Ne, zero)); + let body = self.builder.new_block(); + let merge = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: dirty, + true_block: (body, Vec::new()), + false_block: (merge, Vec::new()), + }); + self.builder.switch_to_block(body); + self.partition_merge = Some(merge); + } + let clean = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(clean, SIRValue::new(0u64))); + self.builder.emit(SIRInstruction::Store( + flags, + offset, + 8, + clean, + Vec::new(), + Vec::new(), + )); + } + + /// Close a partition: set the flags of the partitions reading what it + /// wrote, then join the path that skipped it. + fn end_partition(&mut self, flags: Addr, partition: &PlannedPartition) { + self.flush_pending_folds(); + if !partition.marks.is_empty() { + let one = self.builder.alloc_bit(8, false); + self.builder + .emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); + for &reader in &partition.marks { + self.builder.emit(SIRInstruction::Store( + flags, + SIROffset::Static(reader * 8), + 8, + one, + Vec::new(), + Vec::new(), + )); + } + } + if let Some(merge) = self.partition_merge.take() { + self.builder + .seal_block(SIRTerminator::Jump(merge, Vec::new())); + self.builder.switch_to_block(merge); + } + self.lower_cache.clear(); + self.in_partition = false; + } + /// Lower the buffered run of exact grouped-fold paths. fn flush_pending_folds(&mut self) { let context = self.context; @@ -3854,7 +4310,10 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a } } else { // DAG Part — flush before emitting if the EU has grown too large - if context.split_large_units && self.builder.block_count() >= EU_BLOCK_LIMIT { + if context.split_large_units + && !self.in_partition + && self.builder.block_count() >= EU_BLOCK_LIMIT + { self.flush_pending_folds(); if let Some(eu) = self.builder.flush_eu() { self.execution_units.push(eu); @@ -3932,6 +4391,7 @@ fn sort_impl( unpacked_element_widths: &HashMap, first_runtime_error_code: i64, mut ff: Option<&mut dyn ClockFfLowering>, + partitioning: Option>, ) -> Result, ClockSortError> { let prepared = prepare_schedule( input, @@ -3972,7 +4432,25 @@ fn sort_impl( } let mut runtime_errors: HashMap> = HashMap::default(); let mut next_runtime_error_code = first_runtime_error_code; - for work in &prepared.scheduled_work { + let plan = partitioning + .filter(|_| ff.is_none()) + .and_then(|partitioning| { + plan_settle_partitions(&prepared, arena, var_widths, partitioning) + }); + for (index, work) in prepared.scheduled_work.iter().enumerate() { + if let Some((plan, flags)) = &plan { + if let Some(partition) = plan.first_work.iter().position(|&first| first == index) { + if partition > 0 { + lowering.end_partition(*flags, &plan.partitions[partition - 1]); + } + lowering.begin_partition( + *flags, + partition, + plan.partitions.len(), + &plan.partitions[partition], + ); + } + } lowering.lower( work, ff.as_deref_mut(), @@ -3980,6 +4458,11 @@ fn sort_impl( &mut next_runtime_error_code, )?; } + if let Some((plan, flags)) = &plan + && let Some(last) = plan.partitions.last() + { + lowering.end_partition(*flags, last); + } // Flush the final exact grouped-fold run after the SCC loop. lowering.flush_pending_folds(); if let Some(ff_lowering) = ff { @@ -3991,6 +4474,18 @@ fn sort_impl( execution_units: lowering.finish(), runtime_errors, direct_ff_writes, + partitions: plan + .map(|(plan, _)| { + plan.partitions + .into_iter() + .map(|partition| SettlePartition { + reads: partition.reads, + writes: partition.writes, + pinned: partition.pinned, + }) + .collect() + }) + .unwrap_or_default(), }) } @@ -4013,6 +4508,7 @@ pub fn sort( var_widths, &HashMap::default(), first_runtime_error_code, + None, ) } @@ -4025,6 +4521,7 @@ pub fn sort_with_unpacked_element_widths, unpacked_element_widths: &HashMap, first_runtime_error_code: i64, + partitioning: Option>, ) -> Result, SchedulerError> { match sort_impl::( input, @@ -4036,6 +4533,7 @@ pub fn sort_with_unpacked_element_widths Ok(result), Err(ClockSortError::Scheduler(error)) => Err(error), @@ -4066,6 +4564,7 @@ pub fn sort_clock( unpacked_element_widths, first_runtime_error_code, Some(ff), + None, ) } @@ -4085,7 +4584,7 @@ mod tests { LogicPath, LogicPathTarget, SLTForFoldGroupState, SLTNode, SLTNodeArena, SLTToSIRLowerer, }; use celox_design::{BinaryOp, BitAccess, VarAtomBase}; - use celox_sir::{SIRBuilder, SIRInstruction, SIRTerminator}; + use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator}; #[test] fn deep_input_dependencies_use_heap_and_preserve_inverse_index() { @@ -4629,6 +5128,105 @@ mod tests { assert_eq!(adj, vec![vec![1], vec![2], Vec::new()]); } + fn partitioned_sort( + paths: Vec>, + arena: &SLTNodeArena, + ) -> super::ScheduleResult { + let widths = (10..14).map(|id| (id, 8)).collect(); + super::sort_with_unpacked_element_widths( + paths, + arena, + &crate::HashSet::default(), + &crate::HashMap::default(), + false, + &widths, + &crate::HashMap::default(), + 1, + Some(super::SettlePartitioning { + flags: 99, + target_cost: 1, + }), + ) + .unwrap() + } + + #[test] + fn settle_partitions_follow_schedule_and_guard_on_their_flags() { + let mut arena = SLTNodeArena::new(); + let paths = vec![ + simple_path(&mut arena, 13, Some(12)), + simple_path(&mut arena, 12, Some(11)), + simple_path(&mut arena, 11, Some(10)), + ]; + let result = partitioned_sort(paths, &arena); + let plan = result + .partitions + .iter() + .map(|partition| (partition.reads.clone(), partition.writes.clone())) + .collect::>(); + assert_eq!( + plan, + vec![ + (vec![10], vec![11]), + (vec![11], vec![12]), + (vec![12], vec![13]), + ] + ); + assert!(result.partitions.iter().all(|partition| !partition.pinned)); + // Each partition loads its own flag and the untracked-writes flag + // after them; a partition sets its reader's. + let mut loaded = Vec::new(); + let mut stored = Vec::new(); + for unit in &result.execution_units { + for block in unit.blocks.values() { + for instruction in &block.instructions { + match instruction { + SIRInstruction::Load(_, 99, SIROffset::Static(byte), 8) => { + loaded.push(*byte) + } + SIRInstruction::Store(99, SIROffset::Static(byte), 8, ..) => { + stored.push(*byte) + } + _ => {} + } + } + } + } + loaded.sort_unstable(); + stored.sort_unstable(); + assert_eq!(loaded, vec![0, 8, 16, 24, 24, 24]); + // The clears of all three flags, and the marks of partitions 1 and 2. + assert_eq!(stored, vec![0, 8, 8, 16, 16]); + } + + #[test] + fn settle_copy_readers_read_the_copied_source() { + let mut arena = SLTNodeArena::new(); + let mut copy = simple_path(&mut arena, 12, Some(11)); + copy.transparent_copy = true; + let paths = vec![ + simple_path(&mut arena, 13, Some(12)), + copy, + simple_path(&mut arena, 11, Some(10)), + ]; + let result = partitioned_sort(paths, &arena); + let plan = result + .partitions + .iter() + .map(|partition| (partition.reads.clone(), partition.writes.clone())) + .collect::>(); + // The copy is guarded like other work, and its reader reads the + // copied source too. + assert_eq!( + plan, + vec![ + (vec![10], vec![11]), + (vec![11], vec![12]), + (vec![11, 12], vec![13]), + ] + ); + } + #[test] fn memory_ssa_scheduler_lowers_independent_single_use_chains_contiguously() { let mut arena = SLTNodeArena::new(); diff --git a/crates/celox-state-layout/src/lib.rs b/crates/celox-state-layout/src/lib.rs index ff2fbef6463..f296da09d27 100644 --- a/crates/celox-state-layout/src/lib.rs +++ b/crates/celox-state-layout/src/lib.rs @@ -11,7 +11,9 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use serde::{Deserialize, Serialize}; use std::hash::Hash; +mod settle; mod trace; +pub use settle::{SettleLayout, SettleObject}; pub use trace::{TRACE_GROUP_BYTES, TraceLayout}; pub const RUNTIME_EVENT_CAPACITY: usize = 1024; @@ -191,6 +193,9 @@ pub trait LayoutSource { pub struct MemoryLayout { /// Present only in builds that record waveforms. pub trace: Option, + /// Present when the combinational settle is partitioned. + #[serde(default)] + pub settle: Option, pub four_state: bool, pub mode: MemoryLayoutMode, /// Stable region offsets. Includes all declared state objects. @@ -338,6 +343,15 @@ fn place_region( align_up(current + LANE_SEGMENT_GUARD, LANE_SEGMENT_ALIGN) } +impl MemoryLayout { + /// Whether each settle runs a second time to cross-check its partitions + /// ([`SettleLayout::check`]). + #[inline] + pub fn settle_check(&self) -> bool { + self.settle.as_ref().is_some_and(|settle| settle.check) + } +} + impl MemoryLayout where A: Copy + Eq + Hash + Ord, @@ -553,6 +567,7 @@ where Self { trace: None, + settle: None, four_state, mode, offsets, diff --git a/crates/celox-state-layout/src/settle.rs b/crates/celox-state-layout/src/settle.rs new file mode 100644 index 00000000000..652d5009930 --- /dev/null +++ b/crates/celox-state-layout/src/settle.rs @@ -0,0 +1,74 @@ +//! Dirty flags of a partitioned combinational settle. +//! +//! Generated code sets the flags of the partitions reading the state it +//! writes; host writes go through [`SettleLayout::mark_range`]. Writes no +//! one reports, through a retained raw view of the state, set the untracked +//! byte, after which every partition runs on every settle. +use serde::{Deserialize, Serialize}; + +/// State written outside generated code and the partitions reading it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SettleObject { + /// Byte range of the object, both planes. + pub start: usize, + pub end: usize, + pub partitions: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SettleLayout { + /// One byte per partition, then the untracked byte. + pub flags_offset: usize, + pub partitions: usize, + /// Sorted by `start`, disjoint. + pub objects: Vec, + /// Debug cross-check: the backends run each settle again with every + /// partition flagged and panic where the results differ. + #[serde(default)] + pub check: bool, +} + +impl SettleLayout { + pub fn new(flags_offset: usize, partitions: usize, mut objects: Vec) -> Self { + objects.sort_unstable_by_key(|object| object.start); + Self { + flags_offset, + partitions, + objects, + check: false, + } + } + + /// Set the flags of the partitions reading state in `offset..offset + len`. + /// + /// # Safety + /// `memory` must point to the writable state image this layout describes. + pub unsafe fn mark_range(&self, memory: *mut u8, offset: usize, len: usize) { + let end = offset + len.max(1); + let first = self.objects.partition_point(|object| object.end <= offset); + for object in self.objects[first..] + .iter() + .take_while(|object| object.start < end) + { + for &partition in &object.partitions { + // SAFETY: flags lie inside the image (caller contract). + unsafe { *memory.add(self.flags_offset + partition as usize) = 1 }; + } + } + } + + /// The bytes of the flags, the untracked byte included. + pub fn flags(&self) -> std::ops::Range { + self.flags_offset..self.flags_offset + self.partitions + 1 + } + + /// Run every partition on every settle from now on: a raw view of the + /// state can change it without reporting. + /// + /// # Safety + /// `memory` must point to the writable state image this layout describes. + pub unsafe fn mark_untracked(&self, memory: *mut u8) { + // SAFETY: the untracked byte follows the flags (caller contract). + unsafe { *memory.add(self.flags_offset + self.partitions) = 1 }; + } +} diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index cb6cbe72434..9472313a755 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1331,7 +1331,7 @@ impl Module { // Declaration initializers run before the other initial blocks. let first_block = initial_processes .iter() - .position(|process| !process.initializer) + .position(|process| !process.is_initializer()) .unwrap_or(initial_processes.len()); initial_processes.insert( first_block, @@ -1340,7 +1340,8 @@ impl Module { site: None, condition: None, body: static_initializers, - initializer: true, + kind: celox_design::ProcessKind::Initializer, + validation_body: Vec::new(), synthetic: false, repeats: false, }, @@ -1379,6 +1380,7 @@ impl Module { } for process in &mut initial_processes { process.body = body(std::mem::take(&mut process.body)); + process.validation_body = body(std::mem::take(&mut process.validation_body)); } for subroutine in &mut subroutines { *subroutine = rename.subroutine(subroutine.clone()); @@ -2535,14 +2537,16 @@ impl FfProcess { } } -/// An `initial` process. +/// A scheduled procedure, including initial/always processes and final procedures. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, site: Option, condition: Option, body: Vec, - initializer: bool, + kind: celox_design::ProcessKind, + /// Folded-away statements retained only for final-procedure legality checks. + validation_body: Vec, synthetic: bool, /// An `always` process: its body runs forever. repeats: bool, @@ -2562,6 +2566,16 @@ impl InitialProcess { self.condition.as_ref() } + /// The procedure's simulation phase. + pub fn kind(&self) -> celox_design::ProcessKind { + self.kind + } + + /// A final procedure runs once when the simulation finishes (9.2.3). + pub fn is_final(&self) -> bool { + self.kind == celox_design::ProcessKind::Final + } + /// Compiler-generated storage initialization, without a user static process. pub fn is_synthetic(&self) -> bool { self.synthetic @@ -2569,7 +2583,7 @@ impl InitialProcess { /// Whether this process holds variable declaration initializers. pub fn is_initializer(&self) -> bool { - self.initializer + self.kind == celox_design::ProcessKind::Initializer } /// Whether this is an `always` process, which runs its body forever and diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index 6dfd67cbc94..8429bf932e9 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -220,7 +220,8 @@ impl ArrayParameter { rhs: value, nonblocking: false, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: true, repeats: false, }) diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index d958288a35a..4bc6aaf825e 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -295,7 +295,10 @@ fn comb_process_from_procedure( parameter_literals: &HashMap, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { - if procedure.kind == celox_sv_syntax::ProcedureKind::Initial { + if matches!( + procedure.kind, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final + ) { return Ok(None); } let Some(body) = always_comb_body(procedure, syntax_tree.declarations())? else { diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index e61dbe425db..a30bc59d28b 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -613,10 +613,10 @@ fn simulation_state_readers(functions: &[Subroutine]) -> HashMap HashMap { + Expressions(&'a [Option]), + Constants(&'a [ConstExpr]), +} + +impl CallArguments<'_> { + pub(in crate::ast) fn is_present(self, index: usize) -> bool { + match self { + Self::Expressions(args) => args.get(index).is_some_and(Option::is_some), + Self::Constants(args) => index < args.len(), + } + } +} + /// Calls in an expression, including the index expressions represented by /// ConstExpr. Those indices can contain runtime calls in procedural code. -fn visit_expr_callees<'a>(expr: &'a Expr, f: &mut impl FnMut(&'a Callee)) { +pub(in crate::ast) fn visit_expr_calls<'a>( + expr: &'a Expr, + f: &mut impl FnMut(&'a Callee, CallArguments<'a>), +) { match expr { Expr::Ident(_) | Expr::Literal(_) => {} Expr::Call { callee, args, .. } => { - f(callee); + f(callee, CallArguments::Expressions(args)); for arg in args.iter().flatten() { - visit_expr_callees(arg, f); + visit_expr_calls(arg, f); } } Expr::Select { expr, msb, lsb, .. } => { - visit_expr_callees(expr, f); - visit_const_callees(msb, f); - visit_const_callees(lsb, f); + visit_expr_calls(expr, f); + visit_const_calls(msb, f); + visit_const_calls(lsb, f); } - Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => visit_expr_callees(expr, f), + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => visit_expr_calls(expr, f), Expr::Concat(parts) => { for part in parts { - visit_expr_callees(part, f); + visit_expr_calls(part, f); } } Expr::RepeatConcat { count, parts } => { - visit_const_callees(count, f); + visit_const_calls(count, f); for part in parts { - visit_expr_callees(part, f); + visit_expr_calls(part, f); } } Expr::Binary { left, right, .. } => { - visit_expr_callees(left, f); - visit_expr_callees(right, f); + visit_expr_calls(left, f); + visit_expr_calls(right, f); } Expr::Mux { condition, then_expr, else_expr, } => { - visit_expr_callees(condition, f); - visit_expr_callees(then_expr, f); - visit_expr_callees(else_expr, f); + visit_expr_calls(condition, f); + visit_expr_calls(then_expr, f); + visit_expr_calls(else_expr, f); } Expr::Inside { expr, items } => { - visit_expr_callees(expr, f); + visit_expr_calls(expr, f); for item in items { for expr in item.exprs() { - visit_expr_callees(expr, f); + visit_expr_calls(expr, f); } } } } } -fn visit_const_callees<'a>(expr: &'a ConstExpr, f: &mut impl FnMut(&'a Callee)) { +pub(in crate::ast) fn visit_const_calls<'a>( + expr: &'a ConstExpr, + f: &mut impl FnMut(&'a Callee, CallArguments<'a>), +) { match expr { ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} ConstExpr::Function { callee, args, .. } => { - f(callee); + f(callee, CallArguments::Constants(args)); for arg in args { - visit_const_callees(arg, f); + visit_const_calls(arg, f); } } ConstExpr::Select { expr, bit } => { - visit_const_callees(expr, f); - visit_const_callees(bit, f); + visit_const_calls(expr, f); + visit_const_calls(bit, f); } ConstExpr::SelectRange { expr, msb, lsb, .. } => { - visit_const_callees(expr, f); - visit_const_callees(msb, f); - visit_const_callees(lsb, f); + visit_const_calls(expr, f); + visit_const_calls(msb, f); + visit_const_calls(lsb, f); } ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => { - visit_const_callees(expr, f) + visit_const_calls(expr, f) } ConstExpr::Binary { left, right, .. } => { - visit_const_callees(left, f); - visit_const_callees(right, f); + visit_const_calls(left, f); + visit_const_calls(right, f); } ConstExpr::Mux { condition, then_expr, else_expr, } => { - visit_const_callees(condition, f); - visit_const_callees(then_expr, f); - visit_const_callees(else_expr, f); + visit_const_calls(condition, f); + visit_const_calls(then_expr, f); + visit_const_calls(else_expr, f); } } } diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index c4b8cb131dd..610a7de1bbf 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -60,7 +60,10 @@ fn ff_process_from_procedure( packed_dimensions: &PackedDimensions, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { - if procedure.kind == celox_sv_syntax::ProcedureKind::Initial { + if matches!( + procedure.kind, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final + ) { return Ok(None); } if always_kind(procedure, syntax_tree.declarations())? != AlwaysKind::Ff { diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index 16cbbb7cb00..fc29d6586be 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -113,8 +113,13 @@ pub(super) fn analyze_module( return Ok(None); } let array_scope = if interface_ports.iter().any(|port| port.array_rank != 0) { - let (header_ports, header_tree) = - binding_declaration_view(&view_ports, &instantiations, tree, &imported)?; + let (header_ports, header_tree) = binding_declaration_view( + &view_ports, + &instantiations, + interface_ports, + tree, + &imported, + )?; let mut header_imports = imported.clone(); header_imports.declarations_only = true; Some(Module::from_selected_scope( @@ -257,8 +262,13 @@ pub(super) fn analyze_module( } } // Resolve the caller's declarations before evaluating instance overrides. - let (header_ports, header_tree) = - binding_declaration_view(&view_ports, &instantiations, tree, &imported)?; + let (header_ports, header_tree) = binding_declaration_view( + &view_ports, + &instantiations, + interface_ports, + tree, + &imported, + )?; let mut header_imports = imported.clone(); header_imports.declarations_only = true; let caller = Module::from_selected_scope( @@ -324,8 +334,13 @@ pub(super) fn analyze_module( if generated_item.is_none() { // Newly bound instances may unlock declarations used by the next // instance's overrides. Keep only still-unbound dependencies out. - let (header_ports, header_tree) = - binding_declaration_view(&view_ports, &instantiations, tree, &imported)?; + let (header_ports, header_tree) = binding_declaration_view( + &view_ports, + &instantiations, + interface_ports, + tree, + &imported, + )?; let mut header_imports = imported.clone(); header_imports.declarations_only = true; let caller = Module::from_selected_scope( @@ -817,11 +832,12 @@ fn native_body_items(tree: &SyntaxTree) -> Converted( selected: &port_owners::Selection<'a>, instances: &[celox_sv_syntax::BodyItemId], + ports: &[interfaces::NativePortPlan], tree: &AnalysisContext<'_>, imported: &scope::ScopeSymbols, ) -> Converted<(port_owners::Selection<'a>, SyntaxTree)> { @@ -831,6 +847,7 @@ fn binding_declaration_view<'a>( .filter_map(|id| instances::declaration_from_item(*id, tree).ok()) .flat_map(|instance| instance.instances.iter()) .map(|instance| instances::normalize_identifier(&instance.name.spelling)) + .chain(ports.iter().map(|port| port.name.clone())) .filter(|name| { !imported.interface_types.contains_key(name) && !imported.interface_arrays.contains_key(name) diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 8adc8f68e14..4d97adbc841 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -9,6 +9,7 @@ use super::*; mod assertions; mod control; +mod final_procedures; mod foreach; mod randomization; pub(super) mod timed_tasks; @@ -1001,6 +1002,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { fn allow_timing(&self, construct: &'static str) -> Result<(), AnalyzerError> { match self.body { system_functions::Body::Initial => Ok(()), + system_functions::Body::Final => Err(AnalyzerError::TimingControlOutsideProcess { + construct, + context: "a final procedure", + }), system_functions::Body::Always => Err(AnalyzerError::TimingControlOutsideProcess { construct, context: "an always_comb or always_ff body", @@ -3021,7 +3026,8 @@ pub(super) fn initial_processes_from_scope( ), condition: None, body, - initializer: true, + kind: celox_design::ProcessKind::Initializer, + validation_body: Vec::new(), synthetic: false, repeats: false, }); @@ -3033,10 +3039,13 @@ pub(super) fn initial_processes_from_scope( }; let construct = match procedure.kind { celox_sv_syntax::ProcedureKind::Initial => "initial", + celox_sv_syntax::ProcedureKind::Final => "final", _ => "always", }; let repeats = match procedure.kind { - celox_sv_syntax::ProcedureKind::Initial => false, + celox_sv_syntax::ProcedureKind::Initial | celox_sv_syntax::ProcedureKind::Final => { + false + } celox_sv_syntax::ProcedureKind::Always if validation::always_kind(procedure, tree.declarations())? == validation::AlwaysKind::Process @@ -3047,15 +3056,23 @@ pub(super) fn initial_processes_from_scope( _ => continue, }; let (item_dimensions, literals) = views.get(item); - // A process statement runs in the body kind of an `initial` block: - // it may suspend and call any task. + let is_final = procedure.kind == celox_sv_syntax::ProcedureKind::Final; let mut builder = BodyBuilder::new( tree, item_dimensions, state, - system_functions::Body::Initial, + if is_final { + system_functions::Body::Final + } else { + system_functions::Body::Initial + }, ); let body = builder.native_body(&[procedure.body], &procedure.authored_statements)?; + let mut validation_body = if is_final { + std::mem::take(&mut builder.sensitivity_body) + } else { + Vec::new() + }; let mut body = if repeats { vec![Stmt::Loop { kind: LoopKind::Forever, @@ -3067,7 +3084,7 @@ pub(super) fn initial_processes_from_scope( } else { body }; - for stmt in &mut body { + for stmt in body.iter_mut().chain(&mut validation_body) { substitute_stmt_constants(&tree.state, stmt, &item.env, literals); qualify_stmt(item, stmt); substitute_stmt_constants(&tree.state, stmt, const_env, parameter_literals); @@ -3081,7 +3098,12 @@ pub(super) fn initial_processes_from_scope( ), condition: None, body, - initializer: false, + kind: if is_final { + celox_design::ProcessKind::Final + } else { + celox_design::ProcessKind::Regular + }, + validation_body, synthetic: false, repeats, }); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs b/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs new file mode 100644 index 00000000000..64466d163fe --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/procedural/final_procedures.rs @@ -0,0 +1,182 @@ +//! Function-statement restrictions across calls from final procedures (9.2.3). +use super::*; +use const_functions::CallArguments; + +pub(super) fn validate(subroutines: &[&Subroutine], processes: &[InitialProcess]) -> Converted<()> { + if !processes.iter().any(InitialProcess::is_final) { + return Ok(()); + } + let definitions = subroutines + .iter() + .map(|subroutine| (subroutine.name.as_str(), *subroutine)) + .collect(); + let mut forbidden = HashSet::default(); + let mut calls = Vec::new(); + let mut schedules = HashSet::default(); + let mut runtime_calls = Vec::new(); + for subroutine in subroutines { + let (invalid, _, callees) = effects( + subroutine.body.iter().chain(&subroutine.sensitivity_body), + &definitions, + ); + // Functions cannot enable even an untimed task (13.4 b). + if subroutine.is_task || invalid { + forbidden.insert(subroutine.name.clone()); + } + calls.push((&subroutine.name, callees)); + // Unlike the function-statement restrictions, 13.4.4 concerns an + // executed event scheduling operation. A folded-away NBA is harmless. + let (_, nba, callees) = effects(subroutine.body.iter(), &definitions); + if nba { + schedules.insert(subroutine.name.clone()); + } + runtime_calls.push((&subroutine.name, callees)); + } + loop { + let previous = (forbidden.len(), schedules.len()); + for (name, callees) in &calls { + if callees.iter().any(|callee| forbidden.contains(callee)) { + forbidden.insert((*name).clone()); + } + } + for (name, callees) in &runtime_calls { + if callees.iter().any(|callee| schedules.contains(callee)) { + schedules.insert((*name).clone()); + } + } + if previous == (forbidden.len(), schedules.len()) { + break; + } + } + for process in processes.iter().filter(|process| process.is_final()) { + let (invalid, _, callees) = effects( + process.body.iter().chain(&process.validation_body), + &definitions, + ); + if invalid { + return Err(unsupported("timing control in a final procedure")); + } + if let Some(callee) = callees + .iter() + .filter(|callee| forbidden.contains(*callee)) + .min() + { + return Err(unsupported(format!( + "call to `{callee}` in a final procedure does not obey function-statement restrictions" + ))); + } + let (_, _, callees) = effects(process.body.iter(), &definitions); + if let Some(callee) = callees + .iter() + .filter(|callee| schedules.contains(*callee)) + .min() + { + return Err(unsupported(format!( + "call to `{callee}` from a final procedure schedules an event after the function returns; IEEE 1800-2023 13.4.4 requires an initial/always process" + ))); + } + } + Ok(()) +} + +/// Include discarded branches, expression calls and lvalue selectors: legality +/// is a property of the authored procedure, not just the path executed now. +fn effects<'a>( + body: impl Iterator, + definitions: &HashMap<&str, &Subroutine>, +) -> (bool, bool, HashSet) { + let mut invalid = false; + let mut nba = false; + let mut calls = Calls { + definitions, + names: HashSet::default(), + defaults: Vec::new(), + expanded: HashSet::default(), + }; + for statement in body { + statement.walk(&mut |statement| { + invalid |= matches!( + statement, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) + ); + nba |= matches!( + statement, + Stmt::Assign { + nonblocking: true, + .. + } | Stmt::AssignConcat { + nonblocking: true, + .. + } + ); + if let Stmt::Call { name, args, .. } = statement { + calls.record(name, CallArguments::Expressions(args)); + } + let mut call = |callee: &Callee, args| { + if let Callee::Subroutine(name) = callee { + calls.record(name, args); + } + }; + for expr in lifetimes::stmt_exprs(statement) { + const_functions::visit_expr_calls(expr, &mut call); + } + let targets = match statement { + Stmt::Assign { lhs, .. } => std::slice::from_ref(lhs), + Stmt::AssignConcat { parts, .. } => parts.as_slice(), + _ => &[], + }; + for target in targets { + if let LValue::Select { + msb, + lsb, + array_slice_width, + .. + } = target + { + for index in [Some(msb), Some(lsb), array_slice_width.as_ref()] + .into_iter() + .flatten() + { + const_functions::visit_const_calls(index, &mut call); + } + } + } + }); + } + calls.expand_defaults(); + (invalid, nba, calls.names) +} + +struct Calls<'map, 'definition> { + definitions: &'map HashMap<&'definition str, &'definition Subroutine>, + names: HashSet, + defaults: Vec<&'definition Expr>, + expanded: HashSet<(String, usize)>, +} + +impl Calls<'_, '_> { + fn record(&mut self, name: &str, args: CallArguments<'_>) { + self.names.insert(name.to_owned()); + let Some(&subroutine) = self.definitions.get(name) else { + return; + }; + for (index, parameter) in subroutine.params.iter().enumerate() { + if !args.is_present(index) + && let Some(default) = ¶meter.default + && self.expanded.insert((name.to_owned(), index)) + { + self.defaults.push(default); + } + } + } + + fn expand_defaults(&mut self) { + while let Some(default) = self.defaults.pop() { + const_functions::visit_expr_calls(default, &mut |callee, args| { + if let Callee::Subroutine(name) = callee { + self.record(name, args); + } + }); + } + } +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs index 76e37f3c563..06f9181f7e6 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -8,6 +8,7 @@ pub(in crate::ast) fn classify<'a>( processes: &mut Vec, ) -> Result<(), AnalyzerError> { let subroutines: Vec<_> = subroutines.collect(); + super::final_procedures::validate(&subroutines, processes)?; let mut timed = HashSet::default(); loop { let previous = timed.len(); @@ -132,7 +133,8 @@ pub(in crate::ast) fn classify<'a>( step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: false, repeats: true, }); @@ -172,14 +174,15 @@ pub(in crate::ast) fn classify<'a>( step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, + validation_body: Vec::new(), synthetic: false, repeats: true, }); } *ff = retained; if processes.len() != initial_count { - processes.sort_by_key(|process| (!process.initializer, process.creation_order)); + processes.sort_by_key(|process| (!process.is_initializer(), process.creation_order)); } Ok(()) } diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 2c1bd94a779..3e324055c7d 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -355,7 +355,13 @@ impl ScopeSymbols { .cloned() .map(|stmt| rename.stmt(stmt)) .collect(), - initializer: process.initializer, + kind: process.kind, + validation_body: process + .validation_body + .iter() + .cloned() + .map(|stmt| rename.stmt(stmt)) + .collect(), synthetic: process.synthetic, repeats: process.repeats, }) @@ -596,7 +602,13 @@ impl ScopeSymbols { .cloned() .map(|stmt| rename.stmt(stmt)) .collect(), - initializer: process.initializer, + kind: process.kind, + validation_body: process + .validation_body + .iter() + .cloned() + .map(|stmt| rename.stmt(stmt)) + .collect(), synthetic: process.synthetic, repeats: process.repeats, }) @@ -609,7 +621,7 @@ impl ScopeSymbols { /// Whether `process` assigns the signal `name`. pub(super) fn initializes(process: &InitialProcess, name: &str) -> bool { - process.body.iter().any(|stmt| stmt_initializes(stmt, name)) + !process.is_final() && process.body.iter().any(|stmt| stmt_initializes(stmt, name)) } fn stmt_initializes(stmt: &Stmt, name: &str) -> bool { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 669af79e830..3d981ce9419 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -126,7 +126,7 @@ fn validate_procedure( use celox_sv_syntax::{EventControl, ProcedureKind, StatementKind, TimingControlKind}; let kind = match procedure.kind { ProcedureKind::Initial => return Ok(()), - ProcedureKind::Final => return Err(unsupported("final construct")), + ProcedureKind::Final => return validate_final(procedure.body, native), _ => always_kind(procedure, native)?, }; let mut pending = vec![procedure.body]; @@ -166,6 +166,46 @@ fn validate_procedure( Ok(()) } +/// Final restrictions are syntactic, so even branches later folded away +/// must obey the function-statement rules (IEEE 1800-2023 9.2.3, 13.4). +fn validate_final( + root: celox_sv_syntax::StatementId, + native: &celox_sv_syntax::Declarations, +) -> Converted<()> { + use celox_sv_syntax::StatementKind; + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + let statement = native.statement(id); + let forbidden = match &statement.kind { + StatementKind::Assignment { + timing: Some(_), .. + } + | StatementKind::Assignment { + event_control: Some(_), + .. + } + | StatementKind::Timing { .. } => Some("timing control"), + StatementKind::Wait { .. } + | StatementKind::WaitFork + | StatementKind::WaitOrder { .. } => Some("wait statement"), + StatementKind::Parallel { join, .. } if join != "join_none" => Some("fork-join block"), + // 13.4.4 permits join_none in functions. Its child statements + // obey task rules, so leave the whole construct to the existing + // unsupported parallel-process binder rather than rejecting it. + StatementKind::Parallel { .. } => continue, + StatementKind::Assertion { keyword, .. } if keyword == "expect" => { + Some("expect statement") + } + _ => None, + }; + if let Some(construct) = forbidden { + return Err(unsupported(format!("{construct} in a final procedure"))); + } + pending.extend(statement.kind.children()); + } + Ok(()) +} + /// Root module inspection skips control branches. The subsequent active-item /// inspection visits an opaque checker's complete captured syntax, matching the /// existing validation contract without implementing checker elaboration. diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 32df6c7df93..f094e067c62 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -125,14 +125,14 @@ impl Module { step: Vec::new(), body, }], - initializer: false, + kind: celox_design::ProcessKind::Regular, synthetic: false, repeats: true, }); } self.ff_processes = retained; self.initial_processes - .sort_by_key(|process| (!process.initializer, process.creation_order)); + .sort_by_key(|process| (!process.is_initializer(), process.creation_order)); self } @@ -1146,7 +1146,7 @@ impl FfProcess { } } -/// An `initial` process. +/// A scheduled procedure, including initial/always processes and final procedures. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, @@ -1154,7 +1154,7 @@ pub struct InitialProcess { scheduled_edge: bool, condition: Option, body: Vec, - initializer: bool, + kind: celox_design::ProcessKind, synthetic: bool, /// An `always` process: its body runs forever. repeats: bool, @@ -1176,19 +1176,33 @@ impl InitialProcess { self.site.as_ref() } - pub(crate) fn new(condition: Option, body: Vec, initializer: bool) -> Self { + pub(crate) fn new( + condition: Option, + body: Vec, + kind: celox_design::ProcessKind, + ) -> Self { Self { creation_order: 0, site: None, scheduled_edge: false, condition, body, - initializer, + kind, synthetic: false, repeats: false, } } + /// The procedure's simulation phase. + pub fn kind(&self) -> celox_design::ProcessKind { + self.kind + } + + /// A final procedure runs once when the simulation finishes (9.2.3). + pub fn is_final(&self) -> bool { + self.kind == celox_design::ProcessKind::Final + } + /// Compiler-generated storage initialization, without a user static process. pub fn is_synthetic(&self) -> bool { self.synthetic @@ -1197,7 +1211,7 @@ impl InitialProcess { /// Whether this process holds variable declaration initializers, which /// run before every `initial` and `always` procedure. pub fn is_initializer(&self) -> bool { - self.initializer + self.kind == celox_design::ProcessKind::Initializer } /// Whether this is an `always` process, which runs its body forever and @@ -1602,7 +1616,7 @@ impl From for InitialProcess { .cloned() .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), - process.is_initializer(), + process.kind(), ); result.creation_order = process.creation_order(); result.site = process.site().cloned(); diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 143a76ffce4..6fff884e774 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -1339,7 +1339,7 @@ mod declaration_tests { &ModuleInterfaces::default(), &packages ) - .is_err() + .is_ok() ); let ir = source .analyze_module_declarations("Top", &overrides, &packages) diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs b/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs index 401b8012f3c..be3717fa014 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/process_roots.rs @@ -204,7 +204,7 @@ fn native_process_restrictions_apply_only_to_active_generate_items() { #[test] fn native_direct_nested_unit_restrictions_are_preserved_for_selected_parent() { for (process, expected) in [ - ("final begin end", "final construct"), + ("final #1;", "timing control in a final procedure"), ( "always_latch begin int y;y<=1;end", "nonblocking assignment inside always_latch", @@ -229,7 +229,7 @@ fn native_direct_nested_unit_restrictions_are_preserved_for_selected_parent() { #[test] fn unconverted_checker_processes_retain_existing_restriction_diagnostics() { for (process, expected) in [ - ("final begin end", "final construct"), + ("final #1;", "timing control in a final procedure"), ( "always_latch begin int y;y<=1;end", "nonblocking assignment inside always_latch", @@ -248,26 +248,17 @@ fn unconverted_checker_processes_retain_existing_restriction_diagnostics() { #[test] fn checker_and_nested_unit_validation_keep_the_legacy_root_and_active_leaf_contract() { for (body, rejected) in [ - ("checker C;final begin end endchecker", true), - ("checker C;if(0)final begin end endchecker", true), + ("checker C;final #1; endchecker", true), + ("checker C;if(0)final #1; endchecker", true), + ("if(0)begin:g checker C;final #1; endchecker end", false), + ("if(1)begin:g checker C;final #1; endchecker end", true), + ("module N;checker C;final #1; endchecker endmodule", true), ( - "if(0)begin:g checker C;final begin end endchecker end", + "module N;checker C;if(0)final #1; endchecker endmodule", false, ), ( - "if(1)begin:g checker C;final begin end endchecker end", - true, - ), - ( - "module N;checker C;final begin end endchecker endmodule", - true, - ), - ( - "module N;checker C;if(0)final begin end endchecker endmodule", - false, - ), - ( - "module N;checker C;if(1)final begin end endchecker endmodule", + "module N;checker C;if(1)final #1; endchecker endmodule", false, ), ] { @@ -281,7 +272,9 @@ fn checker_and_nested_unit_validation_keep_the_legacy_root_and_active_leaf_contr if rejected { let error = result.unwrap_err(); assert!( - error.to_string().contains("final construct"), + error + .to_string() + .contains("timing control in a final procedure"), "{body}: {error}" ); } else { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 6b3b0ef51fb..f6e85cb53f9 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -1465,6 +1465,8 @@ pub enum Body { /// `always`, `always_comb`, or `always_ff`. Always, Initial, + /// A final procedure, restricted to function statements (9.2.3). + Final, /// A function or task. Subroutine, } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index c9385650f3d..10ebdfcfbd0 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -7031,3 +7031,213 @@ fn preserves_legal_enum_declaration_initializers() { .unwrap_or_else(|error| panic!("{source}: {error}")); } } + +#[test] +fn final_procedures_preserve_phase_and_active_generate_order() { + let ir = analyze_source( + r#"module Top; + int value = 3; + function int read_value(); return value; endfunction + initial value = 5; + final begin value = read_value(); $display("final %d", value); end + if (0) begin: inactive final #1; end + for (genvar i = 0; i < 2; i++) begin: active + final $display("generated %d", i); + end + endmodule"#, + Path::new("final_procedures.sv"), + ) + .unwrap(); + assert!(ir.modules()[0].comb_processes().is_empty()); + assert!(ir.modules()[0].ff_processes().is_empty()); + let processes = ir.modules()[0].initial_processes(); + assert_eq!( + processes + .iter() + .filter(|process| process.is_initializer()) + .count(), + 1 + ); + assert_eq!( + processes + .iter() + .filter(|process| process.is_final()) + .count(), + 3 + ); + let finals: Vec<_> = processes + .iter() + .filter(|process| process.is_final()) + .collect(); + assert!( + finals + .windows(2) + .all(|pair| pair[0].creation_order() < pair[1].creation_order()) + ); + assert!( + finals.iter().all(|process| !process.repeats() + && !process.is_initializer() + && !process.is_synthetic()) + ); + assert!( + finals + .iter() + .all(|process| process.kind() == celox_design::ProcessKind::Final) + ); +} + +#[test] +fn final_procedures_reject_timing_before_folding() { + for statement in [ + "#1 value = 1;", + "@(value) value = 1;", + "wait(value) value = 1;", + "wait fork;", + "fork value = 1; join", + "value = #1 2;", + ] { + for body in [ + statement.to_string(), + format!("if (0) begin {statement} end"), + ] { + let source = format!("module Top; int value; final begin {body} end endmodule"); + let error = analyze_source(&source, Path::new("illegal_final.sv")).unwrap_err(); + assert!( + error.to_string().contains("final procedure"), + "{source}: {error}" + ); + } + } +} + +#[test] +fn final_procedures_reject_task_and_nba_through_function_calls() { + for declarations in [ + "task work(); endtask", + "task work(); #1; endtask", + "task t(); endtask function void work(); t(); endfunction", + "function void work(); value <= 1; endfunction", + "function void bad(); value <= 1; endfunction function void work(); bad(); endfunction", + ] { + for body in ["work();", "if (0) work();"] { + if declarations.contains("<=") && body.starts_with("if (0)") { + continue; + } + let source = + format!("module Top; int value; {declarations} final begin {body} end endmodule"); + let error = analyze_source(&source, Path::new("illegal_final_call.sv")).unwrap_err(); + if declarations.contains("<=") { + assert!(error.to_string().contains("13.4.4"), "{source}: {error}"); + } + assert!( + error.to_string().contains("final procedure"), + "{source}: {error}" + ); + } + } + let source = "module Top; int value; function int bad(); value <= 1; return value; endfunction final value = bad(); endmodule"; + let error = analyze_source(source, Path::new("illegal_final_expression.sv")).unwrap_err(); + assert!(error.to_string().contains("final procedure"), "{error}"); + let source = "package p; task work(); endtask endpackage module Top; import p::*; final work(); endmodule"; + let error = analyze_source(source, Path::new("illegal_imported_final_call.sv")).unwrap_err(); + assert!(error.to_string().contains("final procedure"), "{error}"); +} + +#[test] +fn final_procedures_preserve_legal_functions_and_finish() { + for body in [ + "value = compute();", + "report();", + "$finish;", + "$stop;", + "$fatal;", + "$fclose(value);", + "$sscanf(\"1\", \"%d\", value);", + "begin int local_value; local_value = value; $display(local_value); end", + ] { + let source = format!( + "module Top; int value; function int compute(); return value + 1; endfunction function void report(); $display(value); endfunction final {body} endmodule" + ); + let ir = analyze_source(&source, Path::new("legal_final.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + assert_eq!( + ir.modules()[0] + .initial_processes() + .iter() + .filter(|process| process.is_final()) + .count(), + 1 + ); + } +} + +#[test] +fn final_procedures_allow_direct_nba_and_unexecuted_scheduling_calls() { + for body in ["value <= 1;", "if (0) schedule();", "no_schedule();"] { + let source = format!( + "module Top; int value; function void schedule(); value <= 1; endfunction function void no_schedule(); if (0) value <= 1; endfunction final {body} endmodule" + ); + let ir = analyze_source(&source, Path::new("final_nba.sv")) + .unwrap_or_else(|error| panic!("{source}: {error}")); + let process = ir.modules()[0] + .initial_processes() + .iter() + .find(|process| process.is_final()) + .unwrap(); + if body == "value <= 1;" { + assert!(matches!( + process.body(), + [ir::Stmt::Assign { + nonblocking: true, + .. + }] + )); + } + } +} + +#[test] +fn final_join_none_is_unsupported_rather_than_a_function_statement_violation() { + let error = analyze_source( + "module Top; final fork #1; join_none endmodule", + Path::new("final_join_none.sv"), + ) + .unwrap_err(); + assert_eq!( + error.to_string(), + "Unsupported SystemVerilog construct: fork-join block" + ); +} + +#[test] +fn final_procedures_only_follow_defaults_for_omitted_arguments() { + let declarations = r#" + int value; + function int schedule(); value <= 1; return 0; endfunction + function int take(input int a = schedule(), input int b = 0); return a + b; endfunction + function int nested(input int a = take()); return a; endfunction + function void explicit_wrapper(); value = take(0); endfunction + function void omitted_wrapper(); value = take(); endfunction + "#; + for (body, rejected) in [ + ("value = take();", true), + ("value = take(, 1);", true), + ("value = take(.b(1));", true), + ("value = nested();", true), + ("omitted_wrapper();", true), + ("value = take(0);", false), + ("value = take(.a(0));", false), + ("value = nested(0);", false), + ("explicit_wrapper();", false), + ("if (0) value = take();", false), + ] { + let source = format!("module Top; {declarations} final {body} endmodule"); + let result = analyze_source(&source, Path::new("final_default_arguments.sv")); + if rejected { + let error = result.unwrap_err(); + assert!(error.to_string().contains("13.4.4"), "{body}: {error}"); + } else { + result.unwrap_or_else(|error| panic!("{body}: {error}")); + } + } +} diff --git a/crates/celox-test-suite/src/sv/cases/interfaces.vtest b/crates/celox-test-suite/src/sv/cases/interfaces.vtest index 3995c29368c..2d80947667f 100644 --- a/crates/celox-test-suite/src/sv/cases/interfaces.vtest +++ b/crates/celox-test-suite/src/sv/cases/interfaces.vtest @@ -946,3 +946,39 @@ (<< (trunc 8 (+ value 4)) 8) (trunc 8 (+ value 5)))) (assert_eq first (| (<< (trunc 8 (+ value 1)) 8) (trunc 8 (+ value 2)))) (assert_eq second (| (<< (trunc 8 (+ value 3)) 8) (trunc 8 (+ value 4)))))) + +(case defers_interface_dependent_declarations_before_binding_array_ports + (source "interface_array_declarations.sv" #" + interface Bus #(parameter int W = 8); + logic [W-1:0] data; + modport sink(input data); + endinterface + module Reader #(parameter int LEFT = 3, RIGHT = 2)( + Bus.sink a[LEFT:RIGHT], Bus.sink b, + input logic [b.W-1:0] delta, output wire [31:0] y); + localparam SCALAR_W = b.W; + localparam ARRAY_W = a[LEFT].W; + localparam TOTAL_W = SCALAR_W + ARRAY_W; + typedef logic [TOTAL_W-1:0] sum_t; + sum_t sum; + assign sum = b.data + a[LEFT].data + a[RIGHT].data + delta; + assign y = sum + TOTAL_W; + endmodule + module Top(input logic [7:0] value, + output wire [31:0] descending, ascending); + Bus #(.W(8)) scalar(); + Bus #(.W(12)) down[3:2](), up[5:6](); + assign scalar.data = value; + assign down[3].data = 12'h100; + assign down[2].data = 12'h200; + assign up[5].data = 12'h400; + assign up[6].data = 12'h800; + Reader d(down, scalar, value, descending); + Reader #(.LEFT(5), .RIGHT(6)) u(up, scalar, value, ascending); + endmodule + "#) + (top Top) + (for value (list 0 1 0x7f 0xff) + (modify (set value value)) + (assert_eq descending (+ (* value 2) 0x300 20)) + (assert_eq ascending (+ (* value 2) 0xc00 20)))) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index a996e6eb580..c68196a6dda 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -288,6 +288,9 @@ fn simulate_sv( saves.after_step(&mut simulation)?; steps += 1; } + let finished = simulation.finish(); + drain_sv_output(&mut simulation, output, &mut failed)?; + finished.map_err(|error| error.to_string())?; saves.finish(&mut simulation)?; if failed { return Err("SystemVerilog testbench reported an assertion failure or $error".to_string()); @@ -1164,8 +1167,7 @@ mod tests { #[cfg(feature = "systemverilog")] #[test] fn sv_scheduler_limit_fails_and_preserves_scheduled_output() { - let source = - "module Top(input bit clk); always @(posedge clk) $display(\"tick\"); endmodule"; + let source = "module Top(input bit clk); always @(posedge clk) $display(\"tick\"); final $display(\"finalized\"); endmodule"; let mut simulation = celox::Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") .build() @@ -1174,7 +1176,28 @@ mod tests { let mut output = Vec::new(); let error = simulate_sv(simulation, 3, StateSaves::default(), &mut output).unwrap_err(); assert!(error.contains("exceeded --max-steps 3")); - assert!(String::from_utf8(output).unwrap().contains("tick")); + let output = String::from_utf8(output).unwrap(); + assert!(output.contains("tick")); + assert!(!output.contains("finalized")); + } + + #[cfg(feature = "systemverilog")] + #[test] + fn sv_batch_runs_final_output_on_quiescence_and_finish() { + for ending in ["", "$finish;"] { + let source = format!( + "module Top; int value; initial begin value=42; {ending} end final $display(\"final=%0d\", value); endmodule" + ); + let simulation = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("top.sv"))], + "Top", + ) + .build() + .unwrap(); + let mut output = Vec::new(); + simulate_sv(simulation, 10, StateSaves::default(), &mut output).unwrap(); + assert_eq!(String::from_utf8(output).unwrap(), "final=42\n"); + } } /// Only `$error` and `$fatal` fail a run; every report is printed with diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index b87450b0b2f..f0726b032cd 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -237,6 +237,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { use std::io::Write as _; let mut stdout = std::io::stdout().lock(); let mut output = |sim: &mut celox::Simulation| -> Result<(), String> { + let mut fatal = None; for event in sim.drain_runtime_events() { match event { celox::RuntimeEvent::Report(celox::Report { @@ -246,7 +247,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { }) => { stdout.write_all(&message).unwrap(); stdout.write_all(b"\n").unwrap(); - return Err(format!( + fatal = Some(format!( "$fatal: {}", std::str::from_utf8(&message) .map(str::to_owned) @@ -265,7 +266,7 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { } } } - Ok(()) + fatal.map_or(Ok(()), Err) }; let initial = sim.eval_comb().map_err(|error| error.to_string()); output(&mut sim)?; @@ -279,6 +280,13 @@ fn simulate(mut sim: celox::Simulation) -> Result<(), String> { break; } } + if !sim.is_stopped() { + // Quiescence ends this batch run, but is not itself terminal for the + // reusable Simulation API (a host can still supply new inputs). + let finished = sim.finish().map_err(|error| error.to_string()); + output(&mut sim)?; + finished?; + } Ok(()) } @@ -421,6 +429,19 @@ mod tests { ); } + #[test] + fn simulation_runs_final_on_quiescence_but_elaboration_does_not() { + let dir = tempfile::tempdir().unwrap(); + let path = fixture( + dir.path(), + "final.sv", + "module Top; initial #2; final $fatal(1, \"from final\"); endmodule", + ); + run(&fixture_options(vec![path.clone()], Mode::Elaboration)).unwrap(); + let error = run(&fixture_options(vec![path], Mode::Simulation)).unwrap_err(); + assert!(error.contains("from final"), "{error}"); + } + #[test] fn simulation_variants_use_separate_arguments_and_fresh_state() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 6a7c6a613bd..2a17b1cf19a 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1983,10 +1983,12 @@ impl SimBackend for InterpBackend { } fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { - ( + let view = ( self.memory.expose_mut_ptr() as *mut u8, self.layout.merged_total_size, - ) + ); + self.mark_settle_untracked(); + view } fn memory_owner(&self) -> Option> { @@ -1995,6 +1997,10 @@ impl SimBackend for InterpBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/memory_image.rs b/crates/celox/src/backend/memory_image.rs index d24445e881b..aa1abc8e54a 100644 --- a/crates/celox/src/backend/memory_image.rs +++ b/crates/celox/src/backend/memory_image.rs @@ -134,6 +134,12 @@ impl MemoryImage { unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.logical_words) } } + pub(crate) fn as_mut_bytes(&mut self) -> &mut [u8] { + let words = self.as_mut_slice(); + // SAFETY: the words are initialized, and bytes have no alignment. + unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast(), words.len() * 8) } + } + pub(crate) fn len_words(&self) -> usize { self.logical_words } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 020fc779b31..f1bca202fb7 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -536,6 +536,7 @@ impl NativeProgramImage { time_slots: self.runtime_schema.time_slots.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), + settle_partitions: None, }, testbench: self.testbench.clone(), } @@ -2589,6 +2590,9 @@ pub struct NativeBackend { /// Boxed so the address in the state header survives moves. heap: Box, execution_timing: Option, + /// Whether generated calls go through [`Self::call_func_slow`]: timing + /// is on, or settles are cross-checked. + slow_calls: bool, /// Worker threads for lane-partitioned kernels, started on first use. lane_pool: Option, /// Per-kernel choice between partitioned and sequential code. @@ -2807,6 +2811,7 @@ impl NativeBackend { } } + let slow_calls = shared.layout.settle_check(); let mut backend = Self { compiled: shared, memory, @@ -2814,6 +2819,7 @@ impl NativeBackend { comb_capture_enabled, heap: Default::default(), execution_timing: None, + slow_calls, lane_pool: None, lane_selectors: Default::default(), }; @@ -2836,6 +2842,7 @@ impl NativeBackend { comb_capture_enabled: Vec, heap: Box, ) -> Self { + let slow_calls = shared.layout.settle_check(); let mut backend = Self { compiled: shared, memory, @@ -2843,6 +2850,7 @@ impl NativeBackend { comb_capture_enabled, heap, execution_timing: None, + slow_calls, lane_pool: None, lane_selectors: Default::default(), }; @@ -2948,6 +2956,7 @@ impl NativeBackend { /// Start a fresh opt-in measurement of generated native function calls. pub fn start_execution_timing(&mut self) { self.execution_timing = Some(NativeExecutionTiming::default()); + self.slow_calls = true; } /// Total capacity of the live image in `u64` words. @@ -2967,10 +2976,12 @@ impl NativeBackend { self.memory.resize_zeroed_within_capacity(mem_size_words); } self.compiled = shared; + self.slow_calls = self.execution_timing.is_some() || self.compiled.layout.settle_check(); } /// Stop timing and return the accumulated generated-code interval. pub fn finish_execution_timing(&mut self) -> Option { + self.slow_calls = self.compiled.layout.settle_check(); self.execution_timing.take() } @@ -3145,6 +3156,29 @@ impl NativeBackend { } fn call_func_timed(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { + if !self.slow_calls { + return Self::call_func(self.memory.as_mut_slice(), func); + } + self.call_func_slow(func) + } + + #[cold] + fn call_func_slow(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { + if func as usize == self.compiled.comb_func as usize && self.compiled.layout.settle_check() + { + let compiled = Arc::clone(&self.compiled); + return crate::settle::run_checked( + self, + compiled.layout.settle.as_ref().expect("checked settle"), + compiled.layout.total_size, + |backend| backend.memory.as_mut_bytes(), + |backend| backend.call_func_measured(func), + ); + } + self.call_func_measured(func) + } + + fn call_func_measured(&mut self, func: NativeSimFunc) -> Result<(), SimulatorErrorCode> { let Some(_) = self.execution_timing else { return Self::call_func(self.memory.as_mut_slice(), func); }; @@ -3514,10 +3548,12 @@ impl super::super::SimBackend for NativeBackend { } fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { - ( + let view = ( self.memory.expose_mut_ptr().cast(), self.memory.len_words() * 8, - ) + ); + self.mark_settle_untracked(); + view } fn memory_owner(&self) -> Option> { @@ -3526,6 +3562,10 @@ impl super::super::SimBackend for NativeBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 984c26ba14a..ae25f64d4a2 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 38; +const CONTAINER_VERSION: u16 = 39; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/runtime.rs b/crates/celox/src/backend/runtime.rs index 49e879915c7..ebc6e902a1c 100644 --- a/crates/celox/src/backend/runtime.rs +++ b/crates/celox/src/backend/runtime.rs @@ -912,7 +912,18 @@ impl JitBackend { |backend| backend.run_sim_func(comb_func), ); } - self.run_sim_func(self.comb_func) + let comb_func = self.comb_func; + if self.shared.layout.settle_check() { + let shared = Arc::clone(&self.shared); + return crate::settle::run_checked( + self, + shared.layout.settle.as_ref().expect("checked settle"), + shared.layout.total_size, + |backend| backend.memory.as_mut_bytes(), + |backend| backend.run_sim_func(comb_func), + ); + } + self.run_sim_func(comb_func) } /// Resolves an `AbsoluteAddr` into a performance-optimized [`SignalRef`]. @@ -1230,7 +1241,9 @@ impl JitBackend { /// Returns a mutable raw pointer to the JIT memory and its total size in bytes. pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { let size = self.shared.layout.merged_total_size; - (self.memory.expose_mut_ptr() as *mut u8, size) + let view = (self.memory.expose_mut_ptr() as *mut u8, size); + celox_runtime::backend::SimBackend::mark_settle_untracked(self); + view } pub fn runtime_event_buffer_as_ptr(&self) -> (*const u8, usize) { @@ -1415,6 +1428,10 @@ impl super::SimBackend for JitBackend { fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.write_bytes(offset, bytes); + self.mark_settle_range(offset, bytes.len()); + if !self.memory.vcd_tracking_enabled() { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 45cbdac4913..506bbabcaa3 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -111,6 +111,10 @@ impl super::traits::SimBackend for WasmBackend { } fn write_memory(&mut self, offset: usize, bytes: &[u8]) { self.memory.data_mut(&mut self.store)[offset..offset + bytes.len()].copy_from_slice(bytes); + self.mark_settle_range(offset, bytes.len()); + if self.raw_view_exposed { + self.mark_settle_untracked(); + } } fn vcd_tracking_enabled(&self) -> bool { !self.raw_view_exposed @@ -683,6 +687,7 @@ impl WasmBackend { pub fn memory_as_mut_ptr(&mut self) -> (*mut u8, usize) { self.raw_view_exposed = true; + celox_runtime::backend::SimBackend::mark_settle_untracked(self); let data = self.memory.data_mut(&mut self.store); (data.as_mut_ptr(), self.layout.merged_total_size) } diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 5b45f5b093e..3ebc630ef97 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -1077,8 +1077,24 @@ mod tests { generated_dirty = stale(generated_dirty, outcome); assert_eq!(generated_dirty, walked_dirty, "step {step}"); let (left, right) = (state(&generated.backend), state(&walked.backend)); - if let Some(offset) = left.iter().zip(&right).position(|(a, b)| a != b) { - let offset = offset + celox_state_layout::STATE_HEADER_SIZE; + // The settle's partition flags hold only what is left to + // recompute. + let flags = walked + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags()); + if let Some(offset) = left + .iter() + .zip(&right) + .enumerate() + .map(|(offset, pair)| (offset + celox_state_layout::STATE_HEADER_SIZE, pair)) + .find(|(offset, (a, b))| { + a != b && !flags.as_ref().is_some_and(|flags| flags.contains(offset)) + }) + .map(|(offset, _)| offset) + { let name = walked .named_signals() .into_iter() diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 718e9675d66..f226fc20aa6 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -566,6 +566,18 @@ pub struct LaidOutProgram { } impl LaidOutProgram { + /// The units, with the layout and runtime metadata they are checked + /// against, borrowed apart. + pub(crate) fn split_mut( + &mut self, + ) -> ( + &mut SirProgram, + &crate::backend::MemoryLayout, + &RuntimeProgram, + ) { + (&mut self.sir, &self.layout, &self.runtime) + } + #[cfg(feature = "host-runtime")] pub(crate) fn enable_vcd_tracking(&mut self) { self.layout.enable_trace(); @@ -575,6 +587,15 @@ impl LaidOutProgram { &self.layout } + /// Cross-check every partitioned settle (see + /// [`celox_state_layout::SettleLayout::check`]). + #[cfg(feature = "host-runtime")] + pub(crate) fn set_settle_check(&mut self, check: bool) { + if let Some(settle) = self.layout.settle.as_mut() { + settle.check = check; + } + } + pub fn runtime(&self) -> &RuntimeProgram { &self.runtime } @@ -701,7 +722,8 @@ impl OptimizedSir { }); } crate::optimizer::sir::retain_final_identity_aliases(&mut program, four_state); - let layout = crate::backend::MemoryLayout::build(&program, four_state, mode); + let mut layout = crate::backend::MemoryLayout::build(&program, four_state, mode); + layout.settle = crate::settle::layout(&program, &layout); // Classify before alias stores disappear: an identity alias is a // combinational copy even once it only shares its source's storage. collect_comb_writes(&mut program); @@ -747,11 +769,13 @@ impl OptimizedSir { layout_requirements, } = program; debug_assert!(layout_requirements.is_empty()); - LaidOutProgram { + let mut laid_out = LaidOutProgram { sir, runtime, layout, - } + }; + crate::settle::instrument(&mut laid_out); + laid_out } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 474221fabfc..79ebb562df4 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -37,6 +37,7 @@ pub(crate) mod portable; // Builds without the host runtime run every slot in the reference loop. #[cfg(feature = "host-runtime")] mod scheduler; +mod settle; #[cfg(feature = "host-runtime")] mod simulation; mod simulator; @@ -90,6 +91,7 @@ pub use num_bigint::BigUint; pub use optimizer::OptLevel; pub use optimizer::OptimizeOptions; pub use optimizer::ParallelPartition; +pub use optimizer::SettlePartition; pub use optimizer::SirDiagnostics; pub use optimizer::SirPass; pub use simulator::render_diagnostic; diff --git a/crates/celox/src/optimizer.rs b/crates/celox/src/optimizer.rs index ed23d101223..97b35bfc831 100644 --- a/crates/celox/src/optimizer.rs +++ b/crates/celox/src/optimizer.rs @@ -1,4 +1,6 @@ -pub use celox_sir_opt::{OptLevel, OptimizeOptions, ParallelPartition, SirDiagnostics, SirPass}; +pub use celox_sir_opt::{ + OptLevel, OptimizeOptions, ParallelPartition, SettlePartition, SirDiagnostics, SirPass, +}; pub mod sir; @@ -98,5 +100,12 @@ pub(crate) fn parallel_schedule_options( parallel.synchronization_cost = 0; parallel.minimum_speedup_percent = 0; } + parallel.settle = if !options.is_enabled(SirPass::PartitionedSettle) { + celox_frontend_core::SettlePartitionMode::Off + } else if options.settle_partition() == SettlePartition::Always { + celox_frontend_core::SettlePartitionMode::Always + } else { + celox_frontend_core::SettlePartitionMode::Estimated + }; parallel } diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 94da9e00dc9..cad4dd76b4c 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -600,6 +600,12 @@ pub fn parse_sv( ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); + let mut schedule_options = crate::optimizer::parallel_schedule_options(optimize_options); + if !force_signals.is_empty() { + // Native code applies explicit forces to reads the SLT has already + // folded, outside any partition's dependencies. + schedule_options.settle = celox_frontend_core::SettlePartitionMode::Off; + } let scheduled = celox_frontend_sv::schedule_sources_with_parameter_expressions_and_latch_policy( sources, @@ -608,7 +614,7 @@ pub fn parse_sv( ignored_loops, true_loops, four_state, - &crate::optimizer::parallel_schedule_options(optimize_options), + &schedule_options, &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), config.allow_inferred_latches, diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 05002091ffb..f3dcfc3baa6 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -425,8 +425,10 @@ impl Plan { for (index, slots) in schema.processes.iter().enumerate() { let process = &model.processes[index]; let unit = &sir.processes[index]; - let reason = if slots.is_initializer { + let reason = if slots.kind == celox_design::ProcessKind::Initializer { Some("a declaration initializer") + } else if slots.kind == celox_design::ProcessKind::Final { + Some("a final procedure") } else if slots.program.is_some() { Some("a program process runs in the reactive region set") } else if slots.requires_timed_simulation { diff --git a/crates/celox/src/settle.rs b/crates/celox/src/settle.rs new file mode 100644 index 00000000000..24a5bf6bde5 --- /dev/null +++ b/crates/celox/src/settle.rs @@ -0,0 +1,238 @@ +//! Partitioned combinational settle (`RuntimeSchema::settle_partitions`): +//! the flag layout, and the flag stores of the units outside the settle. +//! +//! A partition of the settle runs only when its flag is set. The settle's +//! own partitions set the flags of their readers; every other writer of +//! state the settle reads or writes sets them here, at each store or commit +//! to the state, and host writes set them through +//! [`celox_state_layout::SettleLayout`]. +use crate::ir::{ + ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, RegisterType, SIRInstruction, + SIROffset, STABLE_REGION, +}; +use celox_sir::SIRValue; +use celox_state_layout::{SettleLayout, SettleObject}; + +/// The flag layout of `program`'s partitioned settle, if it has one. +pub(crate) fn layout( + program: &crate::ir::OptimizedSir, + layout: &crate::backend::MemoryLayout, +) -> Option { + let settle = program.runtime.runtime_schema.settle_partitions.as_ref()?; + let planes = |address| { + if layout.four_state && layout.is_4states.get(address).copied().unwrap_or(false) { + 2 + } else { + 1 + } + }; + let mut objects: Vec = Vec::new(); + for (address, partitions) in &settle.marks { + let Some(&start) = layout.offsets.get(address) else { + continue; + }; + let end = start + layout.plane_size(address) * planes(address); + objects.push(SettleObject { + start, + end, + partitions: partitions.clone(), + }); + } + // Aliases share storage: one entry per home, with every reader. + objects.sort_unstable_by_key(|object| (object.start, object.end)); + let mut merged: Vec = Vec::new(); + for object in objects { + match merged.last_mut() { + Some(last) if last.start == object.start => { + last.end = last.end.max(object.end); + last.partitions.extend(object.partitions); + last.partitions.sort_unstable(); + last.partitions.dedup(); + } + _ => merged.push(object), + } + } + Some(SettleLayout::new( + layout.offsets[&settle.flags], + settle.partitions as usize, + merged, + )) +} + +/// Run a settle through `run` and cross-check it ([`SettleLayout::check`]): +/// run it again from the same state with every partition flagged, and panic +/// at the first byte of design state (below `state_end`) the two runs leave +/// differently. The state continues from the first run. +// The backends that cross-check: native and Cranelift. +#[cfg(any( + feature = "cranelift", + all( + feature = "host-runtime", + any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ) + ) +))] +#[cold] +pub(crate) fn run_checked( + backend: &mut B, + settle: &SettleLayout, + state_end: usize, + memory: impl Fn(&mut B) -> &mut [u8], + mut run: impl FnMut(&mut B) -> Result<(), E>, +) -> Result<(), E> { + let flags = settle.flags(); + let before = memory(backend).to_vec(); + run(backend)?; + let partial = memory(backend).to_vec(); + let state = memory(backend); + state.copy_from_slice(&before); + state[flags.start..flags.end - 1].fill(1); + run(backend)?; + let full = memory(backend); + if let Some(offset) = (celox_state_layout::STATE_HEADER_SIZE..state_end) + .find(|offset| full[*offset] != partial[*offset] && !flags.contains(offset)) + { + let object = settle + .objects + .iter() + .find(|object| (object.start..object.end).contains(&offset)); + let dirty: Vec = (0..settle.partitions) + .filter(|&partition| before[flags.start + partition] != 0) + .collect(); + panic!( + "partitioned settle: state byte {offset} is {} after the partitions that ran, {} \ + after all ({}; flagged at entry: {dirty:?} of {})", + partial[offset], + full[offset], + object.map_or_else( + || "not read or written by the settle".to_string(), + |object| format!( + "object {}..{} of partitions {:?}", + object.start, object.end, object.partitions + ) + ), + settle.partitions + ); + } + full.copy_from_slice(&partial); + Ok(()) +} + +/// Add the flag stores to every unit outside the settle. +pub(crate) fn instrument(program: &mut LaidOutProgram) { + instrument_processes_from(program, 0, true); +} + +/// Add the flag stores to the processes from index `first` on, and to the +/// other units outside the settle when `all`. +pub(crate) fn instrument_processes_from(program: &mut LaidOutProgram, first: usize, all: bool) { + let (sir, layout, runtime) = program.split_mut(); + let Some(marker) = Marker::new(layout, runtime) else { + return; + }; + if all { + for unit in sir + .eval_apply_ffs + .values_mut() + .chain(sir.eval_comb_apply_ffs.values_mut()) + .chain(sir.eval_only_ffs.values_mut()) + .chain(sir.apply_ffs.values_mut()) + .flatten() + { + marker.instrument(unit); + } + } + for unit in sir.processes.iter_mut().skip(first) { + marker.instrument(unit); + } +} + +struct Marker<'a> { + settle: &'a SettleLayout, + layout: &'a crate::backend::MemoryLayout, + flags: RegionedAbsoluteAddr, +} + +impl<'a> Marker<'a> { + fn new( + layout: &'a crate::backend::MemoryLayout, + runtime: &'a crate::ir::RuntimeProgram, + ) -> Option { + let settle = layout.settle.as_ref()?; + let schema = runtime.runtime_schema.settle_partitions.as_ref()?; + Some(Self { + settle, + layout, + flags: RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, schema.flags), + }) + } + + /// The partitions reading the stable state `address` names. + fn readers(&self, address: &RegionedAbsoluteAddr) -> Vec { + if address.region != STABLE_REGION { + return Vec::new(); + } + let Some(&start) = self.layout.offsets.get(&address.absolute_addr()) else { + return Vec::new(); + }; + let index = self + .settle + .objects + .partition_point(|object| object.start < start); + match self.settle.objects.get(index) { + Some(object) if object.start == start => object.partitions.clone(), + _ => Vec::new(), + } + } + + fn instrument(&self, unit: &mut ExecutionUnit) { + let mut next_register = unit + .register_map + .keys() + .map(|register| register.0 + 1) + .max() + .unwrap_or(0); + for block in unit.blocks.values_mut() { + let mut one = None; + let mut instructions = Vec::with_capacity(block.instructions.len()); + for instruction in std::mem::take(&mut block.instructions) { + let readers = match &instruction { + SIRInstruction::Store(address, ..) => self.readers(address), + SIRInstruction::Commit(_, address, ..) => self.readers(address), + _ => Vec::new(), + }; + instructions.push(instruction); + if readers.is_empty() { + continue; + } + let one = *one.get_or_insert_with(|| { + let register = RegisterId(next_register); + next_register += 1; + unit.register_map.insert( + register, + RegisterType::Bit { + width: 8, + signed: false, + }, + ); + instructions.push(SIRInstruction::Imm(register, SIRValue::new(1u64))); + register + }); + for partition in readers { + instructions.push(SIRInstruction::Store( + self.flags, + SIROffset::Static(partition as usize * 8), + 8, + one, + Vec::new(), + Vec::new(), + )); + } + } + block.instructions = instructions; + } + } +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 967e6da71b4..56bd3dfcdaa 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -158,9 +158,7 @@ impl UnitExecutor for Simulator { } fn run_process(&mut self, index: usize) -> Result<(), Halt> { - self.backend - .run_process(index) - .map_err(|e| self.decorate_runtime_error(e))?; + self.run_process_checked(index)?; self.runtime_finish() } @@ -474,9 +472,22 @@ impl Simulation { if self.state.is_suspended() { return Err(CheckpointError::Stopped.into()); } - let mut file = self.simulator.save_state()?; + if let Err(error) = self.simulator.prepare_save_state() { + if let StateError::Runtime(error) = &error { + self.finalize_fatal(error); + } + return Err(error); + } // Settling for the file may have executed a `$finish`. self.sync_finish_checked().map_err(StateError::Runtime)?; + // A final procedure can write state or suspend with `$stop`. + if self.state.is_suspended() { + return Err(CheckpointError::Stopped.into()); + } + let mut file = self + .simulator + .state_schema() + .capture(&self.simulator.backend)?; let parts = self.state.export_schedule(&self.simulator.backend); let mut record = self.simulator.name_schedule(parts); record.processes.host_writes = self.simulator.name_host_writes(); @@ -537,11 +548,19 @@ impl Simulation { /// step, during a direct settle, read or dump, ends the simulation too. fn sync_finish_checked(&mut self) -> Result<(), RuntimeErrorCode> { if !self.state.is_finished() && self.simulator.take_runtime_finish() { - self.state.finalize_terminal(&mut self.simulator)?; + self.finish()?; } Ok(()) } + /// A fatal report implicitly calls `$finish`; retain the original diagnostic + /// even if a final procedure or output flush fails during termination. + fn finalize_fatal(&mut self, error: &RuntimeErrorCode) { + if matches!(error, RuntimeErrorCode::Fatal { .. }) { + let _ = self.finish(); + } + } + /// Publish diagnostic state without replacing a primary evaluation error /// or freezing a simulation whose caller may recover. fn flush_error_output(&mut self) { @@ -556,13 +575,17 @@ impl Simulation { /// Captures the current state of all signals and writes them to the VCD file. pub fn dump(&mut self, timestamp: u64) { - self.simulator.dump(timestamp); - self.sync_finish(); + if let Err(error) = self.try_dump(timestamp) { + panic!("VCD dump at {timestamp} failed: {error}"); + } } /// See [`Simulator::try_dump`]. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), crate::simulator::DumpError> { let result = self.simulator.try_dump(timestamp); + if let Err(crate::simulator::DumpError::Runtime(error)) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); if matches!(&result, Err(crate::simulator::DumpError::Runtime(_))) { self.flush_error_output(); @@ -615,6 +638,9 @@ impl Simulation { F: FnOnce(&mut crate::IOContext), { let result = self.simulator.modify(f); + if let Err(error) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); result?; finished?; @@ -716,6 +742,7 @@ impl Simulation { Ok(()) }; if let Err(error) = result.and_then(|()| self.simulator.mature_deferred_assertions()) { + self.finalize_fatal(&error); self.flush_error_output(); return Err(error); } @@ -801,6 +828,9 @@ impl Simulation { /// that wake no process, at the current time, and watch its reports. A /// watched run does this before it moves to a later time. fn watch_settle(&mut self) -> Result<(), RuntimeErrorCode> { + if self.state.is_finished() { + return Ok(()); + } // The run leaves the time or ends at it: the slot is over, and the // deferred actions waiting from any settle at that time mature // before the reports are watched. @@ -811,6 +841,7 @@ impl Simulation { } if self.simulator.dirty { if let Err(error) = self.simulator.eval_comb_checked() { + self.finalize_fatal(&error); self.flush_error_output(); return Err(error); } @@ -821,6 +852,9 @@ impl Simulation { } else { Ok(()) }; + if let Err(error) = &matured { + self.finalize_fatal(error); + } self.watch_reports(); if let Err(error) = matured { self.flush_error_output(); @@ -906,7 +940,8 @@ impl Simulation { return Ok(()); } if let Err(error) = self.simulator.try_dump_unless_rewound(end_time) { - if matches!(&error, crate::simulator::DumpError::Runtime(_)) { + if let crate::simulator::DumpError::Runtime(runtime_error) = &error { + self.finalize_fatal(runtime_error); self.flush_error_output(); } return Err(vcd_dump_runtime_error(error)); @@ -984,9 +1019,28 @@ impl Simulation { Ok(!self.state.is_stopped()) } - /// Whether a process of the design requested the end of the simulation. - /// Once it has, [`Self::step`] returns `None` and [`Self::run_until`] - /// stops at the time of the request. + /// End simulation at its current time, running final procedures once. + /// Idle steps and bounded runs remain resumable until this is requested. + /// If a final procedure executes `$stop`, a later step resumes finalization. + pub fn finish(&mut self) -> Result<(), RuntimeErrorCode> { + use celox_runtime::StepObserver; + let Some(mut shadow) = self.shadow.take() else { + return self.state.finish(&mut self.simulator); + }; + let mut check = differential::ShadowCheck::new(&mut shadow, self.mode()); + check.before_step(&self.state, &mut self.simulator); + let result = self.state.finish(&mut self.simulator); + let comparison = check.after_finish(&self.state, &mut self.simulator, &result); + self.checked_steps += check.checked; + self.shadow = Some(shadow); + comparison?; + result + } + + /// Whether simulation has terminated and its final procedures have completed. + /// Termination can be requested by the design or by [`Self::finish`]. + /// Once complete, [`Self::step`] returns `None` and [`Self::run_until`] + /// stops at the termination time. pub fn is_finished(&self) -> bool { self.state.is_finished() } @@ -1014,18 +1068,32 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + // Keep termination visible to the timed owner before collecting reports. + // The untimed drain intentionally turns immediate fatals into reports. + if self.simulator.dirty { + let settled = self.simulator.eval_comb_checked(); + self.simulator.dirty = false; + match settled.and_then(|()| self.sync_finish_checked()) { + Err(error @ RuntimeErrorCode::Fatal { .. }) => self.finalize_fatal(&error), + result => result.unwrap(), + } + } // A slot with nothing more due is over, also before the first step: // the initial settle of combinational logic belongs to time zero. // A fatal action is drained as a fatal report. - if self.simulator.deferred_assertions + if !self.state.is_finished() + && self.simulator.deferred_assertions && self.state.next_event_time() != Some(self.state.time()) { - // Lazily settled logic runs in the slot too. - self.simulator.settle_for_runtime_event_drain(); - let _ = self.simulator.mature_deferred_assertions(); + if let Err(error) = self.simulator.mature_deferred_assertions() { + self.finalize_fatal(&error); + } } let mut events = std::mem::take(&mut self.reports.events); - events.extend(self.simulator.drain_runtime_events()); + events.extend( + self.simulator + .drain_settled_runtime_events_with_context(crate::RuntimeFormatContext::default()), + ); events } @@ -1037,6 +1105,9 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { let result = self.simulator.eval_comb(); + if let Err(error) = &result { + self.finalize_fatal(error); + } let finished = self.sync_finish_checked(); if result.is_err() { self.flush_error_output(); diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ceb3ba86f99..439955bc62e 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -69,6 +69,28 @@ impl<'a, B: SimBackend> ShadowCheck<'a, B> { } } +impl ShadowCheck<'_, B> { + pub(super) fn after_finish( + &mut self, + state: &SimulationState, + primary: &mut Simulator, + result: &Result<(), RuntimeErrorCode>, + ) -> Result<(), RuntimeErrorCode> { + let shadow = &mut *self.shadow; + let reference = shadow.state.finish(&mut shadow.simulator); + self.checked += 1; + let result = result.clone().map(|()| Some(state.time())); + let reference = reference.map(|()| Some(shadow.state.time())); + match difference(state, primary, shadow, &result, &reference) { + None => Ok(()), + Some(message) => Err(RuntimeErrorCode::Runtime { + message: format!("finalization diverged from the reference: {message}"), + signals: Vec::new(), + }), + } + } +} + impl StepObserver> for ShadowCheck<'_, B> { fn one_slot(&self) -> bool { self.one_slot @@ -163,8 +185,9 @@ fn difference( "scheduling state {key:?}, the reference {reference:?}" )); } - // The compiled scheduler's slots hold nothing between runs. - let scheduler: Vec<_> = primary + // The compiled scheduler's slots hold nothing between runs, and the + // settle's partition flags only what is left to recompute. + let excluded: Vec<_> = primary .program .runtime_schema .scheduler @@ -174,9 +197,16 @@ fn difference( let signal = primary.backend.resolve_signal(address); signal.offset..signal.offset + celox_state_layout::get_byte_size(signal.width) }) + .chain( + primary + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags()), + ) .collect(); - if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend, &scheduler) - { + if let Some(offset) = first_difference(&primary.backend, &shadow.simulator.backend, &excluded) { let signal = primary .named_signals() .into_iter() diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 2b497812fd2..53d13ef05df 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -796,7 +796,7 @@ endmodule .runtime_schema .processes .iter() - .filter(|slots| !slots.is_initializer) + .filter(|slots| slots.kind != celox_design::ProcessKind::Initializer) .map(|slots| slots.const_delays) .collect(); // `initial clk = 1'b0` folds into an initial value. A real delay diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 6e1d6ae5327..0eed2799e5d 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -952,7 +952,7 @@ mod host { match err { RuntimeErrorCode::DetectedTrueLoopCode(code) => { if self.comb_fatal_site(code).is_some() { - return RuntimeErrorCode::Runtime { + return RuntimeErrorCode::Fatal { message: "Fatal assertion (runtime event record overwritten)" .to_string(), signals: Vec::new(), @@ -1288,6 +1288,7 @@ mod host { ); } } + self.backend.mark_settle_range(signal.offset, 1); } /// Drain runtime events, lazily evaluating dirty combinational logic. @@ -1470,7 +1471,9 @@ 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> { - if !self.deferred_assertions { + // 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 { return Ok(()); } self.stash_runtime_events(); @@ -1493,7 +1496,7 @@ mod host { }) else { return Ok(()); }; - Err(RuntimeErrorCode::Runtime { + Err(RuntimeErrorCode::Fatal { message: message_diagnostic(&report.message), signals: Vec::new(), }) @@ -1584,6 +1587,9 @@ mod host { } fn runtime_event_write_seq(&self) -> u64 { + if self.program.runtime_schema.runtime_event_sites.is_empty() { + return 0; + } if let Some(buffer) = self.backend.runtime_event_buffer() { buffer.load_atomic_u64(0, std::sync::atomic::Ordering::Acquire) } else { @@ -1822,7 +1828,7 @@ mod host { return Err(error); } if fatal_status { - return Err(RuntimeErrorCode::Runtime { + return Err(RuntimeErrorCode::Fatal { message: "Fatal assertion (runtime event record overwritten)".to_string(), signals: Vec::new(), }); @@ -1835,7 +1841,9 @@ mod host { ) -> (Result<(), RuntimeErrorCode>, Vec) { // Event-drain writes use this entry directly instead of the // checked facade. Leave observers and runtime events untouched. - if self.declaration_phase { + // A boundary observer may have marked the state dirty immediately + // before freezing; draining output must not activate HDL afterwards. + if self.frozen || self.declaration_phase { return (Ok(()), Vec::new()); } if self.program.runtime_schema.runtime_event_sites.is_empty() { @@ -1931,7 +1939,7 @@ mod host { if !site.kind.is_fatal() || site.deferred.is_some() { return None; } - Some(RuntimeErrorCode::Runtime { + Some(RuntimeErrorCode::Fatal { message: message_diagnostic(&render_runtime_event_message( site, args, @@ -1942,40 +1950,62 @@ mod host { }) } + /// Keep a fatal report distinct from ordinary runtime faults before its + /// backend status is decorated into a diagnostic. + fn checked_kernel_result( + &self, + result: Result<(), RuntimeErrorCode>, + start: u64, + ) -> Result<(), RuntimeErrorCode> { + result.map_err(|error| { + if self.program.runtime_schema.runtime_event_sites.is_empty() { + return self.decorate_runtime_error(error); + } + self.fatal_comb_capture_error(&self.peek_backend_runtime_events_from(start)) + .unwrap_or_else(|| self.decorate_runtime_error(error)) + }) + } + + pub(crate) fn run_process_checked(&mut self, index: usize) -> Result<(), RuntimeErrorCode> { + let start = self.runtime_event_write_seq(); + let result = self.backend.run_process(index); + self.checked_kernel_result(result, start) + } + pub(crate) fn eval_apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_apply_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn eval_comb_apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_comb_apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_comb_apply_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn eval_only_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .eval_only_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.eval_only_ff_at(event); + self.checked_kernel_result(result, start) } pub(crate) fn apply_ff_at_checked( &mut self, event: B::Event, ) -> Result<(), RuntimeErrorCode> { - self.backend - .apply_ff_at(event) - .map_err(|e| self.decorate_runtime_error(e)) + let start = self.runtime_event_write_seq(); + let result = self.backend.apply_ff_at(event); + self.checked_kernel_result(result, start) } /// One clock period of an event's signal: its active edge, then its @@ -3535,7 +3565,7 @@ mod host { assert!(sim.fatal_comb_capture_error(&events).is_none()); assert!(sim.check_comb_backend_result(result.clone()).is_ok()); assert!(matches!(sim.decorate_runtime_error(result.unwrap_err()), - RuntimeErrorCode::Runtime { message, .. } if message.contains("overwritten"))); + RuntimeErrorCode::Fatal { message, .. } if message.contains("overwritten"))); let drained = sim.drain_runtime_events(); assert!(matches!( drained.first(), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 75e1a4f61a5..c1d98a11ac8 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1686,6 +1686,9 @@ mod host { /// Emit the additional combinational entries needed to reapply foreign /// force overrides between procedural store boundaries. pub native_force_support: bool, + /// Cross-check every partitioned settle against one that runs every + /// partition (see [`SimulatorBuilder::settle_check`]). + pub settle_check: bool, /// Explicit hierarchical observation and native force targets. pub signal_access: crate::SignalAccessOptions, /// Dead store elimination policy. @@ -1991,6 +1994,7 @@ mod host { emit_triggers: false, #[cfg(all(test, feature = "cranelift", feature = "systemverilog"))] derived_edge_units: None, + settle_check: false, native_force_support: false, signal_access: crate::SignalAccessOptions::default(), dead_store_policy: DeadStorePolicy::Off, @@ -2221,9 +2225,11 @@ mod host { pub fn opt_level(mut self, level: crate::optimizer::OptLevel) -> Self { let lanes = self.options.optimize_options.parallel_lanes(); let partition = self.options.optimize_options.parallel_partition(); + let settle = self.options.optimize_options.settle_partition(); self.options.optimize_options = crate::optimizer::OptimizeOptions::new(level) .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self.options.cranelift_options = crate::backend::CraneliftOptions::for_speed_optimization( level != crate::optimizer::OptLevel::O0, @@ -2258,13 +2264,15 @@ mod host { pub fn optimize(mut self, enable: bool) -> Self { let lanes = self.options.optimize_options.parallel_lanes(); let partition = self.options.optimize_options.parallel_partition(); + let settle = self.options.optimize_options.settle_partition(); self.options.optimize_options = if enable { crate::optimizer::OptimizeOptions::all() } else { crate::optimizer::OptimizeOptions::none() } .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self } @@ -2284,9 +2292,15 @@ mod host { } else { self.options.optimize_options.parallel_partition() }; + let settle = if options.settle_partition() == crate::SettlePartition::Always { + crate::SettlePartition::Always + } else { + self.options.optimize_options.settle_partition() + }; self.options.optimize_options = options .with_parallel_lanes(lanes) - .with_parallel_partition(partition); + .with_parallel_partition(partition) + .with_settle_partition(settle); self } @@ -2328,6 +2342,34 @@ mod host { self } + /// Debug cross-check of a partitioned settle: the native and + /// Cranelift backends run each settle a second time from the same + /// state with every partition flagged, and panic at the first state + /// byte the two runs leave differently. Slow; for testing the + /// partitioning. Effects of the partitions that run in both passes, + /// such as runtime events, happen twice. + pub fn settle_check(mut self, enable: bool) -> Self { + self.options.settle_check = enable; + self + } + + /// Cut the combinational settle into partitions that run only when + /// state they read changed ([`crate::SirPass::PartitionedSettle`]). + /// + /// [`crate::SettlePartition::Estimated`] partitions a large settle of + /// a design with several clock events; + /// [`crate::SettlePartition::Always`] partitions every settle it can, + /// for testing. + pub fn settle_partition(mut self, partition: crate::SettlePartition) -> Self { + self.options.optimize_options = self + .options + .optimize_options + .clone() + .enable(crate::optimizer::SirPass::PartitionedSettle) + .with_settle_partition(partition); + self + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -2902,6 +2944,8 @@ mod host { } } + // Units generated from here on write state the settle may read. + let first_generated_process = laid_out.sir.processes.len(); // A timed simulation runs the slots of kernels that only delay // in a compiled scheduler, generated from the final units. #[cfg(feature = "host-runtime")] @@ -2922,6 +2966,8 @@ mod host { if let Some(sink) = &self.options.derived_edge_units { crate::derived_edge::attach_test_units(&mut laid_out, sink); } + crate::settle::instrument_processes_from(&mut laid_out, first_generated_process, false); + laid_out.set_settle_check(self.options.settle_check); // Link DPI-C imports before code generation, so a missing C // function fails the build early; the backends reuse the result. @@ -4061,7 +4107,7 @@ mod host { .runtime_schema .processes .iter() - .any(|slots| slots.is_initializer) + .any(|slots| slots.kind == celox_design::ProcessKind::Initializer) { sim.modify(|_| {}).map_err(|error| { SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 803b46afdaa..55120c284c9 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -303,6 +303,13 @@ impl Simulator { /// Combinational values are settled first, so the file shows the values /// a read would return. pub fn save_state(&mut self) -> Result { + self.prepare_save_state()?; + self.state_schema().capture(&self.backend) + } + + /// Validate support and settle before a timed owner synchronizes termination. + /// Capture must follow that synchronization, since final procedures can write state. + pub(crate) fn prepare_save_state(&mut self) -> Result<(), StateError> { self.check_host_checkpoint_support()?; if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); @@ -311,7 +318,7 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - self.state_schema().capture(&self.backend) + Ok(()) } /// Load the state saved in `file`, matching objects by path. @@ -376,7 +383,9 @@ impl Simulator { let comb_writes = &self.program.runtime_schema.comb_writes; // A timed simulation stores its time into the time slots, and a state // file keeps the time in its schedule; an untimed one reads zero. - // A compiled scheduler's slots hold nothing between runs. + // A compiled scheduler's slots hold nothing between runs, and the + // flags of a partitioned settle describe how this build settles, + // not the design: loading state sets them. let time_slots: crate::HashSet<_> = self .program .runtime_schema @@ -390,12 +399,19 @@ impl Simulator { .flat_map(|scheduler| scheduler.slots.iter()), ) .collect(); + let settle_flags = self + .backend + .layout() + .settle + .as_ref() + .map(|settle| settle.flags_offset); let mut objects: Vec<_> = self .backend .layout() .offsets .keys() .filter(|address| !time_slots.contains(address)) + .filter(|address| Some(self.backend.layout().offsets[*address]) != settle_flags) .map(|&address| (self.program.get_path(&address), address)) .collect(); objects.sort_unstable(); diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index b01452f8fc2..0d5c205b104 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -116,7 +116,7 @@ pub(crate) fn eval_backend_expr( |offset, len| writes.push((offset, len)), ); if let Some(trace) = backend.layout().trace.as_ref() { - for (offset, len) in writes { + for &(offset, len) in &writes { // SAFETY: bound bytecode writes valid locations in this image, and // the simulator cannot execute concurrently with this evaluation. unsafe { @@ -124,6 +124,9 @@ pub(crate) fn eval_backend_expr( } } } + for (offset, len) in writes { + backend.mark_settle_range(offset, len); + } value } diff --git a/crates/celox/tests/comb_observer.rs b/crates/celox/tests/comb_observer.rs index ae525ef7dbf..47f1ca24605 100644 --- a/crates/celox/tests/comb_observer.rs +++ b/crates/celox/tests/comb_observer.rs @@ -783,7 +783,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "constant fail".to_string(), signals: Vec::new(), }, @@ -806,7 +806,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "initial fatal".to_string(), signals: Vec::new(), }, @@ -831,7 +831,7 @@ module Top ( let err = sim.modify(|io| io.set(trigger, 1u8)).unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "constant fatal after modify".to_string(), signals: Vec::new(), }, @@ -853,7 +853,7 @@ module Top { let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "user says for-loop step does not advance the loop variable".to_string(), signals: Vec::new(), }, @@ -899,7 +899,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "a must be set".to_string(), signals: Vec::new(), }, @@ -1205,7 +1205,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "fatal y".to_string(), signals: Vec::new(), }, @@ -1718,7 +1718,7 @@ module Top ( let err = sim.eval_comb().unwrap_err(); assert_eq!( err, - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "x1 became 1".to_string(), signals: Vec::new(), }, diff --git a/crates/celox/tests/fixtures/final/finish.sv b/crates/celox/tests/fixtures/final/finish.sv new file mode 100644 index 00000000000..cfb9816211f --- /dev/null +++ b/crates/celox/tests/fixtures/final/finish.sv @@ -0,0 +1,19 @@ +`timescale 1ns/1ns +// Whichever final runs first must terminate the current and remaining finals. +module Top(output int calls, after_finish); + initial begin calls = 0; after_finish = 0; #1; $finish; end + final begin + calls = calls + 1; + $display("final calls=%0d", calls); + $finish; + after_finish = 1; + $display("unreachable first"); + end + final begin + calls = calls + 1; + $display("final calls=%0d", calls); + $finish; + after_finish = 2; + $display("unreachable second"); + end +endmodule diff --git a/crates/celox/tests/fixtures/final/hierarchy.sv b/crates/celox/tests/fixtures/final/hierarchy.sv new file mode 100644 index 00000000000..32b84b938ff --- /dev/null +++ b/crates/celox/tests/fixtures/final/hierarchy.sv @@ -0,0 +1,15 @@ +`timescale 1ns/1ns +// The order of final procedures is unspecified. Each emits a distinct +// label so an external check can compare the labels without ordering them. +module Child(output bit done); + final begin done = 1; $display("child"); end +endmodule +module Top(output bit first, second, child_done, output bit [1:0] generated); + Child child(child_done); + initial begin #1; $finish; end + final begin first = 1; $display("top first"); end + final begin second = 1; $display("top second"); end + for (genvar i = 0; i < 2; i++) begin : g + final begin generated[i] = 1; $display("generate %0d", i); end + end +endmodule diff --git a/crates/celox/tests/fixtures/final/state.sv b/crates/celox/tests/fixtures/final/state.sv new file mode 100644 index 00000000000..ae4e6549072 --- /dev/null +++ b/crates/celox/tests/fixtures/final/state.sv @@ -0,0 +1,16 @@ +`timescale 1ns/1ns +// IEEE 1800-2023 9.2.3: final observes the last state and runs once. +module Top(output int value, calls); + initial begin + value = 3; calls = 0; + $display("initial calls=%0d", calls); + #2 value = 7; + $finish; + end + final begin + calls = calls + 1; + value = value + 10; + if (value != 17 || calls != 1) $fatal(1, "bad final state"); + $display("final value=%0d calls=%0d", value, calls); + end +endmodule diff --git a/crates/celox/tests/frontends/systemverilog/final.rs b/crates/celox/tests/frontends/systemverilog/final.rs new file mode 100644 index 00000000000..f904597200c --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/final.rs @@ -0,0 +1,521 @@ +use celox::{RuntimeEvent, SimBackend, Simulation}; +use std::path::Path; + +// The shared timed-suite emitter uses its own final checker and therefore +// rejects final procedures whose order relative to that checker is unspecified. +// These portable fixtures are also suitable for direct external execution; +// API checks here inspect state only after finalization has completed. +// Every source uses 1ns/1ns so API ticks and HDL delay units coincide. +const STATE: &str = include_str!("../../fixtures/final/state.sv"); +const HIERARCHY: &str = include_str!("../../fixtures/final/hierarchy.sv"); +const FINISH: &str = include_str!("../../fixtures/final/finish.sv"); + +#[test] +fn final_procedures_require_the_simulation_api() { + let source = "module Top(input logic done); final assert (done); endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("final.sv"))], "Top") + .build_interpreter() + .unwrap_err(); + assert!( + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" + ); +} + +fn displays(events: Vec) -> Vec> { + events + .into_iter() + .filter_map(|event| match event { + RuntimeEvent::Display { message } => Some(message), + _ => None, + }) + .collect() +} + +fn check_final_state(mut sim: Simulation) { + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 17u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![ + b"initial calls=0".to_vec(), + b"final value=17 calls=1".to_vec(), + ] + ); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert!(displays(sim.drain_runtime_events()).is_empty()); +} + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn final_procedures_survive_native_image_roundtrip() { + let image = Simulation::from_sv_sources(vec![(STATE, Path::new("final_state.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + check_final_state( + Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(), + ); +} + +macro_rules! check_backends { + ($source:expr, $check:ident) => { + for four_state in [false, true] { + let build = || { + Simulation::from_sv_sources(vec![($source, Path::new("final.sv"))], "Top") + .four_state(four_state) + }; + $check(build().build_interpreter().unwrap()); + $check(build().build_cranelift().unwrap()); + $check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + { + $check(build().build_native().unwrap()); + $check(build().build_tiered().unwrap()); + $check( + build() + .scheduler_mode(celox::SchedulerMode::Differential) + .build_native() + .unwrap(), + ); + } + } + }; +} + +#[test] +fn final_nonblocking_updates_do_not_run_after_termination() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, observed); + initial begin value=3; #1; $finish; end + final begin value <= 99; observed = value; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("value")), 3u8.into()); + assert_eq!(sim.get(sim.signal("observed")), 3u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn explicit_finish_runs_final_with_last_state() { + check_backends!(STATE, check_final_state); +} + +#[test] +fn final_procedures_run_in_modules_and_generate_blocks() { + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + for name in ["first", "second"] { + assert_eq!(sim.get(sim.signal(name)), 1u8.into(), "{name}"); + } + // Output variable ports connect through implicit continuous + // assignments (4.9.6, 23.2.2.3). Finalization does not run another + // scheduled settle (9.2.3), so inspect the child's own final write. + let child_done = sim.child_signal(&[("child", 0)], "done"); + assert_eq!(sim.get(child_done), 1u8.into()); + assert_eq!(sim.get(sim.signal("generated")), 3u8.into()); + let mut labels = displays(sim.drain_runtime_events()); + labels.sort(); + assert_eq!( + labels, + [ + "child", + "generate 0", + "generate 1", + "top first", + "top second" + ] + .map(|text| text.as_bytes().to_vec()) + ); + } + check_backends!(HIERARCHY, check); +} + +#[test] +fn finish_in_final_stops_remaining_execution() { + fn check(mut sim: Simulation) { + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("after_finish")), 0u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final calls=1".to_vec()] + ); + } + check_backends!(FINISH, check); +} + +#[test] +fn host_finish_is_explicit_and_runs_final_only_once() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, calls); + initial begin value = 3; calls = 0; #2 value = 7; end + final begin calls = calls + 1; value = value + 10; $display("final"); end + endmodule"#; + fn check(mut sim: Simulation) { + let value = sim.signal("value"); + let calls = sim.signal("calls"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(calls), 0u8.into()); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(value), 3u8.into()); + assert_eq!(sim.get(calls), 0u8.into()); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(value), 7u8.into()); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(calls), 0u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + sim.finish().unwrap(); + assert_eq!(sim.get(value), 17u8.into()); + assert_eq!(sim.get(calls), 1u8.into()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final".to_vec()] + ); + sim.finish().unwrap(); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(calls), 1u8.into()); + assert!(sim.drain_runtime_events().is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn stop_in_final_resumes_at_the_cursor_without_running_scheduled_events() { + let source = r#"`timescale 1ns/1ns + module Top(output int calls, other_calls, late_event); + initial begin calls = 0; other_calls = 0; late_event = 0; #10 late_event = 1; end + final begin calls = calls + 1; $stop; calls = calls + 1; end + final other_calls = other_calls + 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.finish().unwrap(); + assert!(sim.is_stopped()); + assert!(sim.checkpoint().is_err()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("late_event")), 0u8.into()); + // The other final may precede or follow the suspended one. After + // resumption both must be complete, with no restart of either body. + sim.step().unwrap(); + assert!(!sim.is_stopped()); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!(sim.get(sim.signal("other_calls")), 1u8.into()); + let finished = sim.checkpoint().unwrap(); + sim.restore(&finished).unwrap(); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + sim.run_until(100).unwrap(); + sim.finish().unwrap(); + assert_eq!(sim.step().unwrap(), None); + assert_eq!(sim.get(sim.signal("late_event")), 0u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 2u8.into()); + assert_eq!(sim.get(sim.signal("other_calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn stop_suspends_without_running_final() { + let source = r#"`timescale 1ns/1ns + module Top(output int value, calls); + initial begin value = 3; calls = 0; #1 $stop; value = 7; $finish; end + final begin calls = calls + 1; value = value + 10; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(10).unwrap(); + assert!(sim.is_stopped()); + assert_eq!(sim.get(sim.signal("calls")), 0u8.into()); + assert_eq!(sim.get(sim.signal("value")), 3u8.into()); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!(sim.get(sim.signal("value")), 17u8.into()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn fatal_runs_final_and_preserves_the_original_error() { + // IEEE 1800-2023 20.10: $fatal implicitly calls $finish. + let source = r#"`timescale 1ns/1ns + module Top(output int calls); + initial begin calls = 0; #1 $fatal(1, "initial fatal"); end + final begin calls = calls + 1; $display("final after fatal"); end + endmodule"#; + fn check(mut sim: Simulation) { + let error = sim.run_until(2).unwrap_err(); + assert!(error.to_string().contains("initial fatal"), "{error}"); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + let events = sim.drain_runtime_events(); + assert!(events.iter().any(|event| matches!(event, + RuntimeEvent::Report(report) + if report.severity == celox::Severity::Fatal && report.message == b"initial fatal" + )), "{events:?}"); + assert!( + events.iter().any(|event| matches!(event, + RuntimeEvent::Display { message } if message == b"final after fatal" + )), + "{events:?}" + ); + } + check_backends!(source, check); +} + +#[test] +fn final_order_is_sequential_and_repeatable() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin #1; $finish; end + final begin $write("A"); $display("a"); end + final begin $write("B"); $display("b"); end + final begin $write("C"); $display("c"); end + endmodule"#; + fn transcript(mut sim: Simulation) -> Vec { + sim.run_until(2).unwrap(); + sim.drain_runtime_events() + .into_iter() + .filter(|event| { + matches!( + event, + RuntimeEvent::Write { .. } | RuntimeEvent::Display { .. } + ) + }) + .collect() + } + // Order is implementation-defined; require complete procedure pairs and + // stability between fresh instances, not a particular source order. + for four_state in [false, true] { + let build = || { + Simulation::from_sv_sources(vec![(source, Path::new("final_order.sv"))], "Top") + .four_state(four_state) + }; + let first = transcript(build().build_interpreter().unwrap()); + assert_eq!(first, transcript(build().build_interpreter().unwrap())); + assert_eq!(first.len(), 6); + let mut labels = Vec::new(); + for pair in first.as_chunks::<2>().0 { + let [ + RuntimeEvent::Write { message: upper }, + RuntimeEvent::Display { message: lower }, + ] = pair + else { + panic!("interleaved final procedures: {first:?}"); + }; + assert_eq!(upper.len(), 1); + assert_eq!(lower, &upper.to_ascii_lowercase()); + labels.push(upper[0]); + } + labels.sort_unstable(); + assert_eq!(labels, b"ABC"); + } +} + +#[test] +fn watched_idle_deferred_fatal_runs_final_and_preserves_the_error() { + let source = r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb assert final (!fail) else $fatal(1, "deferred fatal"); + final calls = calls + 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.set_fail_on(Some(celox::Severity::Error)); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + // No timed process is scheduled: run_until must finalize a fatal + // deferred report matured while settling watched host writes. + let error = sim.run_until(1).unwrap_err(); + assert!(error.to_string().contains("deferred fatal"), "{error}"); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn pending_deferred_output_does_not_run_after_final() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin assert final (0) else $display("late"); $finish; end + final $display("final"); + endmodule"#; + fn check(mut sim: Simulation) { + sim.step().unwrap(); + assert!(sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"final".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + assert_eq!(sim.step().unwrap(), None); + assert!(displays(sim.drain_runtime_events()).is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn pending_deferred_output_does_not_run_while_final_is_stopped() { + let source = r#"`timescale 1ns/1ns + module Top; + initial begin assert final (0) else $display("late"); $finish; end + final begin $display("before"); $stop; $display("after"); end + endmodule"#; + fn check(mut sim: Simulation) { + sim.step().unwrap(); + assert!(sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"before".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + sim.step().unwrap(); + assert!(!sim.is_stopped()); + assert!(sim.is_finished()); + assert_eq!( + displays(sim.drain_runtime_events()), + vec![b"after".to_vec()] + ); + assert!(displays(sim.drain_runtime_events()).is_empty()); + } + check_backends!(source, check); +} + +#[test] +fn event_drain_finalizes_immediate_fatal_before_deferred_actions() { + for deferred in [ + "", + "always_comb assert final (!fail) else $display(\"deferred\");", + ] { + let source = format!( + r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb if (fail) $fatal(1, "drain fatal"); + {deferred} + final begin calls += 1; $display("final"); end + endmodule"# + ); + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + sim.drain_runtime_events(); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + let events = sim.drain_runtime_events(); + assert!(sim.is_finished(), "{events:?}"); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + assert_eq!( + events + .iter() + .filter(|event| matches!(event, + RuntimeEvent::Report(report) if report.severity == celox::Severity::Fatal + && report.message == b"drain fatal" + )) + .count(), + 1, + "{events:?}" + ); + assert_eq!(displays(events), vec![b"final".to_vec()]); + assert!(sim.drain_runtime_events().is_empty()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source.as_str(), check); + } +} + +#[test] +fn saved_state_contains_final_updates_after_lazy_finish() { + let source = r#"`timescale 1ns/1ns + module Top(input bit go, output int result, calls); + initial begin result = 7; calls = 0; end + always_comb if (go) $finish; + final begin result = 42; calls += 1; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let before = sim.save_state().unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let finished = sim.save_state().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + sim.load_state(&before).unwrap(); + assert!(!sim.is_finished()); + sim.load_state(&finished).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + sim.finish().unwrap(); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn saving_state_rejects_a_stop_reached_inside_final() { + let source = r#"`timescale 1ns/1ns + module Top(input bit go, output int result); + initial result = 0; + always_comb if (go) $finish; + final begin result = 7; $stop; result = 42; end + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + assert!(matches!( + sim.save_state(), + Err(celox::StateError::Checkpoint( + celox::CheckpointError::Stopped + )) + )); + assert!(sim.is_stopped()); + assert!(!sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 7u8.into()); + sim.step().unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + let finished = sim.save_state().unwrap(); + sim.load_state(&finished).unwrap(); + assert_eq!(sim.get(sim.signal("result")), 42u8.into()); + } + check_backends!(source, check); +} + +#[test] +fn saving_state_preserves_fatal_and_runs_final() { + let source = r#"`timescale 1ns/1ns + module Top(input bit fail, output int calls); + initial calls = 0; + always_comb if (fail) $fatal(1, "save fatal"); + final calls += 1; + endmodule"#; + fn check(mut sim: Simulation) { + sim.run_until(0).unwrap(); + let fail = sim.signal("fail"); + sim.modify(|io| io.set(fail, 1u8)).unwrap(); + assert!(matches!(sim.save_state(), + Err(celox::StateError::Runtime(celox::RuntimeErrorCode::Fatal { message, .. })) + if message == "save fatal" + )); + assert!(sim.is_finished()); + assert_eq!(sim.get(sim.signal("calls")), 1u8.into()); + } + check_backends!(source, check); +} diff --git a/crates/celox/tests/frontends/systemverilog/interfaces.rs b/crates/celox/tests/frontends/systemverilog/interfaces.rs index 6c3c216bd41..bd1bc1737c5 100644 --- a/crates/celox/tests/frontends/systemverilog/interfaces.rs +++ b/crates/celox/tests/frontends/systemverilog/interfaces.rs @@ -1,6 +1,9 @@ use super::*; sv_backends! { + fn defers_interface_dependent_declarations_before_binding_array_ports(sim) { + @case "interfaces::defers_interface_dependent_declarations_before_binding_array_ports"; + } fn connects_interface_array_slices_in_declaration_order(sim) { @case "interfaces::connects_interface_array_slices_in_declaration_order"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index e34c6124f7a..9000b8ab688 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5486,14 +5486,6 @@ fn rejects_constructs_that_are_not_yet_lowered() { endmodule "#, ), - ( - "final construct", - r#" - module Top(input logic done); - final assert (done); - endmodule - "#, - ), ( "non-ANSI port expressions", r#" diff --git a/crates/celox/tests/runtime_api.rs b/crates/celox/tests/runtime_api.rs index d88637e469c..4e34e8420a9 100644 --- a/crates/celox/tests/runtime_api.rs +++ b/crates/celox/tests/runtime_api.rs @@ -13,7 +13,7 @@ all_backends! { @build Simulator::builder(r#" module Top { always_comb { $assert(1'd0, "site zero"); } } "#, "Top"); - assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Runtime { message, .. }) if message == "site zero")); + assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Fatal { message, .. }) if message == "site zero")); assert_eq!(bare(sim.drain_runtime_events()), vec![RuntimeEvent::Report(Report::new(Severity::Fatal, b"site zero".to_vec()))]); assert!(bare(sim.drain_runtime_events()).is_empty()); } @@ -30,7 +30,7 @@ module Top { } } "#, "Top"); - assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Runtime { message, .. }) if message == "site two")); + assert!(matches!(sim.eval_comb(), Err(RuntimeErrorCode::Fatal { message, .. }) if message == "site two")); assert_eq!(bare(sim.drain_runtime_events()), vec![ RuntimeEvent::Display { message: b"first".to_vec() }, RuntimeEvent::Display { message: b"second".to_vec() }, diff --git a/crates/celox/tests/settle_partitions.rs b/crates/celox/tests/settle_partitions.rs new file mode 100644 index 00000000000..3e9fa3dba0f --- /dev/null +++ b/crates/celox/tests/settle_partitions.rs @@ -0,0 +1,297 @@ +//! A partitioned settle runs a partition only when state it reads changed +//! (#2013). Forced on every settle it can cut, it must match the single-pass +//! settle on every backend, whatever wrote the state: a register update, a +//! host write, a loaded state file. +use celox::{BigUint, SettlePartition, Simulator, SirPass}; + +/// Two clock domains feeding a combinational network deep enough to cut into +/// many partitions, with a memory read through a run-time index and a +/// combinational output depending on a host input only. +const DESIGN: &str = r#" +module Top ( + clk_a: input 'a clock, + clk_b: input 'b clock, + rst: input 'a reset, + din: input 'a logic<8>, + sel: input 'a logic<2>, + bypass: input 'a logic<8>, + sum: output 'a logic<8>, + mixed: output 'a logic<8>, + picked: output 'a logic<8>, + direct: output 'a logic<8>, + slow: output 'b logic<8>, +) { + var ra: 'a logic<8>; + var mem: 'a logic<8> [4]; + var rb: 'b logic<8>; + var s1: 'a logic<8>; + var s2: 'a logic<8>; + var s3: 'a logic<8>; + var s4: 'a logic<8>; + always_ff (clk_a, rst) { + if_reset { + ra = 0; + } else { + ra = ra + din; + mem[ra[1:0]] = ra ^ din; + } + } + unsafe (cdc) { + always_ff (clk_b) { + rb = rb + s4; + } + assign s2 = s1 ^ rb; + assign slow = rb; + } + assign s1 = ra + 8'd1; + assign s3 = {s2[3:0], s1[7:4]}; + assign s4 = s3 + bypass; + assign sum = s4 + s1; + assign mixed = s3 ^ s2; + assign picked = mem[sel]; + assign direct = bypass + 8'd3; +} +"#; + +const OUTPUTS: [&str; 5] = ["sum", "mixed", "picked", "direct", "slow"]; + +fn partitioned() -> celox::SimulatorBuilder<'static, Simulator> { + Simulator::builder(DESIGN, "Top") + .settle_partition(SettlePartition::Always) + .settle_check(true) +} + +fn single_pass() -> celox::SimulatorBuilder<'static, Simulator> { + Simulator::builder(DESIGN, "Top").disable_pass(SirPass::PartitionedSettle) +} + +/// Drive both clocks and the inputs with a fixed pseudo-random sequence, +/// reading every output after each host write and each tick. +macro_rules! trace { + ($sim:expr) => {{ + let sim = &mut $sim; + let clk_a = sim.event("clk_a"); + let clk_b = sim.event("clk_b"); + let rst = sim.signal("rst"); + let din = sim.signal("din"); + let sel = sim.signal("sel"); + let bypass = sim.signal("bypass"); + let outputs = OUTPUTS.map(|name| sim.signal(name)); + let mut trace = Vec::new(); + macro_rules! read { + () => { + outputs + .iter() + .map(|&signal| sim.get(signal)) + .collect::>() + }; + } + sim.modify(|io| io.set(rst, 0u8)).unwrap(); + sim.tick(clk_a).unwrap(); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + let mut seed = 0x2013u32; + for _ in 0..64 { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + let bits = seed >> 8; + // A host write alone must reach the combinational outputs. + sim.modify(|io| { + io.set(din, bits as u8); + io.set(sel, (bits >> 8) as u8 & 3); + io.set(bypass, (bits >> 10) as u8); + }) + .unwrap(); + trace.push(read!()); + match bits >> 18 & 3 { + 0 => sim.tick(clk_a).unwrap(), + 1 => sim.tick(clk_b).unwrap(), + 2 => sim.tick_events(&[clk_a, clk_b]).unwrap(), + _ => {} + } + trace.push(read!()); + } + trace + }}; +} + +fn reference() -> Vec> { + trace!(single_pass().build().unwrap()) +} + +#[test] +fn partitioned_interpreter_matches_single_pass() { + assert_eq!( + trace!(partitioned().build_interpreter().unwrap()), + reference() + ); +} + +#[test] +fn partitioned_cranelift_matches_single_pass() { + assert_eq!( + trace!(partitioned().build_cranelift().unwrap()), + reference() + ); +} + +#[test] +fn partitioned_wasm_matches_single_pass() { + assert_eq!(trace!(partitioned().build_wasm().unwrap()), reference()); +} + +#[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) +))] +#[test] +fn partitioned_native_matches_single_pass() { + assert_eq!(trace!(partitioned().build_native().unwrap()), reference()); +} + +/// Loading a state file writes every object, so every partition reading one +/// must run again; the settle's flags themselves are not state. +#[test] +fn loaded_state_reaches_partitions() { + let mut source = partitioned().build().unwrap(); + trace!(source); + let file = source.save_state().unwrap(); + assert!( + file.objects + .iter() + .all(|object| !object.path.contains("$settle")), + "the settle flags are saved as state" + ); + let mut target = partitioned().build().unwrap(); + // Settle once before the load, so no partition is pending. + trace!(target); + target.load_state(&file).unwrap(); + let mut plain = single_pass().build().unwrap(); + plain.load_state(&file).unwrap(); + assert_eq!(trace!(target), trace!(plain)); +} + +#[cfg(feature = "systemverilog")] +mod systemverilog { + use std::path::Path; + + use celox::{BigUint, SettlePartition, Simulation, SirPass}; + + /// A clock gated through a latch (Xilinx BUFGCE): the latch is a process + /// of the settle, and the gated clock's edge runs another domain. + const GATED: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [7:0] fast, + output logic [7:0] gated, + output logic [7:0] view +); + logic clk = 0; + logic en = 0; + logic en_l; + logic [7:0] din = 0; + always #5 clk = ~clk; + always #7 en = ~en; + always #3 din = din + 8'd29; + always_latch begin + if (!clk) en_l = en; + end + wire gclk = clk & en_l; + initial begin fast = 0; gated = 0; end + always_ff @(posedge clk) fast <= fast + din; + always_ff @(posedge gclk) gated <= gated ^ fast; + assign view = gated + fast; +endmodule +"#; + + /// A process writing two outputs runs at its first output's place in + /// the schedule, so the second output changes there too. + const SPLIT: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [3:0] y, + output logic [3:0] b, + output logic [1:0] w, + output int n +); + logic [3:0] a = 4'b0101; + logic c = 0; + always_comb begin y = 4'b0; if (c) y = a; b = a; end + assign w = y[1:0]; + initial begin n = 0; #1 forever begin @(y); n++; end end + initial begin + #2 c = 1; + #1 a = 4'b0110; + #1 a = 4'b0111; + #2 c = 0; + #1 a = 4'b1001; + end +endmodule +"#; + + /// A whole-variable copy of a process output, read by another process. + const COPY: &str = r#" +`timescale 1ns/1ns +module Top ( + output logic [7:0] r, + output logic [7:0] q +); + logic [7:0] a = 8'd3; + logic s = 0; + logic [7:0] p; + logic [7:0] pc; + always_comb begin p = 8'd0; q = 8'd0; if (s) begin p = a; q = ~a; end end + assign pc = p; + always_comb r = pc + 8'd1; + always #2 a = a + 8'd5; + always #3 s = ~s; +endmodule +"#; + + fn trace( + source: &str, + outputs: &[&str], + end: u64, + settle: Option, + ) -> Vec> { + let builder = Simulation::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + let builder = match settle { + Some(settle) => builder.settle_partition(settle).settle_check(true), + None => builder.disable_pass(SirPass::PartitionedSettle), + }; + let mut sim = builder.build().unwrap(); + let outputs: Vec<_> = outputs.iter().map(|name| sim.signal(name)).collect(); + let mut trace = Vec::new(); + for time in 0..end { + sim.run_until(time).unwrap(); + trace.push(outputs.iter().map(|&signal| sim.get(signal)).collect()); + } + trace + } + + fn matches_single_pass(source: &str, outputs: &[&str], end: u64) -> Vec> { + let single = trace(source, outputs, end, None); + assert_eq!( + trace(source, outputs, end, Some(SettlePartition::Always)), + single + ); + single + } + + #[test] + fn latch_gated_clock_matches_single_pass() { + let single = matches_single_pass(GATED, &["fast", "gated", "view"], 200); + // The gated domain must have run. + assert_ne!(single.last().unwrap()[1], BigUint::from(0u8)); + } + + #[test] + fn multi_output_process_matches_single_pass() { + let single = matches_single_pass(SPLIT, &["y", "b", "w", "n"], 10); + // At 5, y and w follow a through the intermediate 0. + assert_eq!(single[5][2], BigUint::from(3u8)); + } + + #[test] + fn copy_of_a_process_output_matches_single_pass() { + matches_single_pass(COPY, &["r", "q"], 40); + } +} diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 43766a4dabe..1bf274b058a 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -678,6 +678,25 @@ fn native_program_image_rejects_v19_before_loading_float_helper_abi() { )); } +/// Version 39 replaces the initializer flag with a process phase. +#[test] +fn native_program_image_rejects_v38_before_decoding_process_kinds() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&38u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(38)) + )); +} + /// Version 38 adds host operand value kinds to the runtime metadata. #[test] fn native_program_image_rejects_v37_before_decoding_host_operand_value_kinds() { diff --git a/crates/celox/tests/sv_vcd.rs b/crates/celox/tests/sv_vcd.rs index c642322ee11..bef605a10ed 100644 --- a/crates/celox/tests/sv_vcd.rs +++ b/crates/celox/tests/sv_vcd.rs @@ -681,8 +681,8 @@ fn scoped_parameter_dump_does_not_select_imported_state() { } #[test] -fn direct_fatal_errors_publish_waveform_without_freezing_recovery() { - for action in ["eval_comb", "try_dump"] { +fn direct_fatal_errors_publish_waveform_and_terminate() { + for action in ["eval_comb", "try_dump", "dump"] { check_direct_fatal_waveform(action); } } @@ -701,9 +701,10 @@ fn check_direct_fatal_waveform(action: &str) { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("direct-fatal.vcd"); let source = format!( - r#"module Top(input logic fail_now, output logic value); - initial begin $dumpfile("{}"); $dumpvars(0,Top.value); end + r#"module Top(input logic fail_now, output logic value, output int final_calls); + initial begin final_calls=0; $dumpfile("{}"); $dumpvars(0,Top.value); end always_comb begin value=fail_now; if(fail_now) $fatal(1,"direct primary"); end + final final_calls += 1; endmodule"#, path.display() ); @@ -716,6 +717,13 @@ fn check_direct_fatal_waveform(action: &str) { let error = match action { "eval_comb" => format!("{:?}", simulation.eval_comb().unwrap_err()), "try_dump" => format!("{:?}", simulation.try_dump(0).unwrap_err()), + "dump" => { + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + simulation.dump(0); + })) + .unwrap_err(); + *panic.downcast::().unwrap() + } "run_until" => format!("{:?}", simulation.run_until(1).unwrap_err()), "run_until_bounded" => format!("{:?}", simulation.run_until_bounded(1, 10).unwrap_err()), _ => unreachable!(), @@ -723,11 +731,17 @@ fn check_direct_fatal_waveform(action: &str) { assert!(error.contains("direct primary"), "{action}: {error}"); let text = std::fs::read_to_string(path).unwrap(); assert!(text.contains("1!"), "{action}: {text}"); + // $fatal implicitly calls $finish (20.10), including when lazy + // combinational evaluation was triggered by a waveform API. + assert!(simulation.is_finished(), "{action}"); + let final_calls = simulation.signal("final_calls"); + assert_eq!(simulation.get(final_calls), 1u8.into(), "{action}"); simulation.modify(|io| io.set(fail, 0u8)).unwrap(); simulation.eval_comb().unwrap(); let value = simulation.signal("value"); - assert_eq!(simulation.get(value), 0u8.into()); - assert!(!simulation.is_finished()); + assert_eq!(simulation.get(value), 1u8.into(), "{action}"); + simulation.finish().unwrap(); + assert_eq!(simulation.get(final_calls), 1u8.into(), "{action}"); } #[test] diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index e33f385b835..541cfe4ae39 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -113,6 +113,8 @@ mod edges; mod file_core; #[path = "frontends/systemverilog/file_io.rs"] mod file_io; +#[path = "frontends/systemverilog/final.rs"] +mod final_procedures; #[path = "frontends/systemverilog/generate.rs"] mod generate; #[path = "frontends/systemverilog/hierarchical_references.rs"] diff --git a/crates/celox/tests/test_utils/veryl_sim.rs b/crates/celox/tests/test_utils/veryl_sim.rs index e19773cfad0..ed3eb9010ea 100644 --- a/crates/celox/tests/test_utils/veryl_sim.rs +++ b/crates/celox/tests/test_utils/veryl_sim.rs @@ -148,7 +148,7 @@ fn take_runtime_error() -> Result<(), RuntimeErrorCode> { if is_non_progressing_loop_diagnostic(&message) { Err(RuntimeErrorCode::DetectedTrueLoop) } else { - Err(RuntimeErrorCode::Runtime { + Err(RuntimeErrorCode::Fatal { message, signals: Vec::new(), }) diff --git a/crates/celox/tests/veryl_reference_adapter.rs b/crates/celox/tests/veryl_reference_adapter.rs index 2955afbbce7..af26db3177d 100644 --- a/crates/celox/tests/veryl_reference_adapter.rs +++ b/crates/celox/tests/veryl_reference_adapter.rs @@ -87,7 +87,7 @@ fn empty_modify_still_reports_initial_fatal_diagnostics() { let mut sim = build_veryl_adapter(&[(code, Path::new("test.veryl"))], "Top", false); assert_eq!( sim.modify(|_| {}).unwrap_err(), - celox::RuntimeErrorCode::Runtime { + celox::RuntimeErrorCode::Fatal { message: "initial fatal from empty modify".to_string(), signals: Vec::new(), }, diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ebf89de8f3b..ec4f308a543 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -193,7 +193,7 @@ it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). - Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, specializations of a parameterized class outside the package or compilation unit that declares it, and properties that are 4-state, `real`, arrays or wider than 64 bits. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. -- Behavioral and verification constructs: `final`, intra-assignment timing controls (`a = #1 b`), +- Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. - Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), @@ -599,6 +599,28 @@ simulation is suspended (`CheckpointError::Stopped`). In an `always` process, `$ Its diagnostic level argument prints nothing. Batch hosts without an interactive mode, such as the VPI host, end the run at `$stop`. +### Final procedures {#final-procedures} + +`final` procedures require `Simulation`. They run once, sequentially at the +termination time, on `$finish`, `$fatal` or an explicit `Simulation::finish()` +call (IEEE 1800-2023 9.2.3, 20.10). Their relative order is deterministic but +unspecified. The CLI and sv-tests batch driver finish when scheduled work runs +out. An idle `step()` or the end of `run_until()` does not terminate the reusable +Rust simulation; a host can supply more inputs or call `finish()`. + +Ordinary `$stop` does not run final procedures. A `$stop` inside a final +procedure suspends finalization, and a later step or `finish()` resumes it. +`$finish` inside a final procedure immediately ends that procedure and skips +all remaining finals. The original `$fatal` error is preserved when it starts +termination. + +No scheduled HDL events run after final procedures. In particular, a +nonblocking assignment made directly in a final procedure never applies its +queued update. Timing controls and calls to user tasks are rejected, including +through functions. Calls to functions that schedule events after returning +require an initial/always process context and are rejected from final +procedures (13.4.4). `fork` / `join_none` remains unsupported. + ### Programs {#programs} A `program` (IEEE 1800-2023 Clause 24) is declared and instantiated like a @@ -626,8 +648,8 @@ so a program that resumes after `#0` reads their new values, whereas 4.5 evaluates them only once the reactive region set is empty; programs nested in modules and anonymous programs are rejected; a program that no module instantiates is not an implicit top level next to the design's top -module; `final` procedures and clocking blocks are unsupported in programs as -everywhere. +module; clocking blocks are unsupported. Program `final` procedures run during +termination, including the implicit `$finish` after the last initial procedure. ### `$exit` diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 952eb064d73..f148c3826f0 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -55,12 +55,12 @@ compilation unit; choose the top by its SystemVerilog module name. | What your test needs | API | | --- | --- | | Set inputs, evaluate logic and advance clock events from Rust | `Simulator::from_sv_sources` | -| Advance simulation time and run `initial` and `always` processes with timing controls | `Simulation::from_sv_sources` | +| Advance simulation time, run timed processes and execute `final` procedures | `Simulation::from_sv_sources` | | Include both Veryl and SystemVerilog sources | `Simulator::from_mixed_sources` | `Simulator::tick` drives the rising edge of the selected event. `Simulation` tracks time and runs scheduled edges. Constant initialization applies to both. -`initial` blocks that read design state or call system tasks, processes with +`final` procedures, `initial` blocks that read design state or call system tasks, processes with timing controls and `always` blocks whose sensitivity list is neither `@*` nor [the variables they read](./systemverilog-reference#timing-controls) run as processes and need `Simulation`. A `Simulator` runs no process, so building @@ -85,6 +85,7 @@ The main supported areas are: | Timed processes | `initial` and `always` with `#delay` (also time literals such as `#5ns`), `@(...)` on variables, edges, selects, expressions and `@*`, `wait (...)`, nonblocking assignments and task calls with timing controls | | Computation | Arithmetic, selects, assignment patterns, branches, loops and functions | | Simulation helpers | Immediate and deferred immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | +| Termination | `final` procedures on `$finish`, `$fatal` or explicit `Simulation::finish()`; see [termination semantics](./systemverilog-reference#final-procedures) | Each area has restrictions. Use the [detailed support list](./systemverilog-reference#what-is-supported) to check diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index a10c48ca3b5..fc8608038ba 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -101,6 +101,15 @@ unnecessary: compile the clock's domain once more; the `derived_edge_units` selector (`-sir:derived_edge_units`, `SirPass::DerivedEdgeUnits`) turns them off to trade tick speed for build time. +- the combinational settle can be cut into partitions, contiguous ranges of + its schedule, that run only when their dirty flag is set + (`partitioned_settle`, off unless enabled). A partition that runs sets the + flags of the partitions reading what it writes; every other writer sets them + too: generated stores and commits of state a partition reads or writes, host + writes, state loads, and a retained raw view of the state, after which every + partition runs. `SimulatorBuilder::settle_check` runs each settle a second + time with every partition flagged and panics where the two differ; effects + of partitions that run twice, such as runtime events, then happen twice. - in the time slots a compiled scheduler runs, a combinational settle waits until its results are read: it runs, where the reference loop last settled, before a process kernel or domain that reads combinational outputs diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index b358062dc33..466b8f0b6ae 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -394,7 +394,9 @@ export interface SimulatorOptions { * split_coalesced_stores, partial_forward, identity_store_bypass, tail_call_split, * derived_edge_units (generated units for the edges of gated and divided * clocks; "-sir:derived_edge_units" walks their plans instead, which - * builds faster and ticks slower) + * builds faster and ticks slower), partitioned_settle (settle only the + * partitions of the combinational logic whose inputs changed; off unless + * enabled with "+sir:partitioned_settle") * * @example ["-sir:reschedule", "+sir:gvn"] */