diff --git a/.config/nextest.toml b/.config/nextest.toml index 7251480628b..fa2e9835b73 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -11,6 +11,10 @@ fail-fast = false slow-timeout = { period = "60s", terminate-after = 10 } failure-output = "immediate-final" +[profile.ci.junit] +path = "junit.xml" +store-success-output = false + [[profile.ci.overrides]] # Deep per-bit graphs consume substantial compiler memory and CPU. Reserve the # pool so these regressions retain the same timeout without competing builds. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b1fde462a1..a77cd3fe13a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -211,6 +211,9 @@ jobs: needs: changes if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') }} runs-on: ubuntu-latest + env: + CELOX_CI_REPORT_DIR: work/ci-reports/rust + HAS_MERGIFY_TOKEN: ${{ secrets.MERGIFY_TOKEN != '' }} steps: - uses: actions/checkout@v7 with: @@ -220,8 +223,12 @@ jobs: - uses: Swatinem/rust-cache@v2 with: + key: vtest-v1 save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + - name: Initialize Rust test reports + run: node scripts/ci-rust-reports.mjs reset + - uses: actions/setup-python@v7 if: needs.changes.outputs.rust_vpi_e2e != 'false' with: @@ -236,6 +243,10 @@ jobs: with: tool: cargo-nextest@0.9.144 + - name: Build the optimized vtest executor + if: needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_packages), ' celox ') + run: node scripts/run-vtest.mjs --prepare-ci + # Enable the frontend and suite features together so common integration # tests run once, rather than once per Cargo feature combination. # nextest schedules tests from all binaries on one pool; `cargo test` @@ -244,12 +255,14 @@ jobs: # (scripts/ci-rust-scope.mjs); merge groups and the daily run keep the # Celox workspace. lydite-checks.yml owns Lydite tests at its own cadence. - name: Run workspace tests with CI features + id: workspace-tests if: needs.changes.outputs.rust_full != 'false' run: >- cargo nextest run --locked --workspace --exclude 'lydite*' --profile ci - --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus + --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/runtime-cases - name: Run the tests this pull request can affect + id: scoped-tests if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_packages != '' env: BUILDS: ${{ needs.changes.outputs.rust_builds }} @@ -257,6 +270,27 @@ jobs: run: | node scripts/run-ci-rust-scope.mjs test + - name: Collect Rust test reports + if: success() || failure() + run: node scripts/ci-rust-reports.mjs collect + + - name: Retain Rust test reports + if: (success() || failure()) && hashFiles('work/ci-reports/rust/*.xml') != '' + uses: actions/upload-artifact@v7 + with: + name: rust-test-results + path: work/ci-reports/rust/*.xml + retention-days: 14 + + - name: Upload Rust test results to Mergify + if: (success() || failure()) && env.HAS_MERGIFY_TOKEN == 'true' && hashFiles('work/ci-reports/rust/*.xml') != '' + uses: mergifyio/gha-mergify-ci@392d123d84a27960993927aec1f2cbb059fb95c1 # v27 + with: + token: ${{ secrets.MERGIFY_TOKEN }} + report_path: work/ci-reports/rust/*.xml + job_name: rust-tests + test_step_outcome: ${{ steps.workspace-tests.outcome != 'skipped' && steps.workspace-tests.outcome || steps.scoped-tests.outcome }} + # nextest does not run documentation tests. - name: Run workspace documentation tests with CI features if: needs.changes.outputs.rust_full != 'false' diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml index a5d8b9f0de3..b7113223635 100644 --- a/.github/workflows/rust-cache.yml +++ b/.github/workflows/rust-cache.yml @@ -13,6 +13,7 @@ on: - ".github/actions/setup-rust/**" - ".github/workflows/rust-cache.yml" - ".github/workflows/ci.yml" + - "scripts/run-vtest.mjs" workflow_dispatch: permissions: @@ -39,14 +40,19 @@ jobs: - uses: ./.github/actions/setup-rust - uses: Swatinem/rust-cache@v2 id: cache + with: + key: vtest-v1 - name: Install cargo-nextest if: steps.cache.outputs.cache-hit != 'true' uses: taiki-e/install-action@v2 with: tool: cargo-nextest@0.9.144 + - name: Build the optimized vtest executor to populate dependencies + if: steps.cache.outputs.cache-hit != 'true' + run: node scripts/run-vtest.mjs --prepare-ci - name: Build test targets to populate dependencies if: steps.cache.outputs.cache-hit != 'true' run: >- cargo nextest list --locked --workspace --message-format json - --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus + --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/runtime-cases > /dev/null diff --git a/CLAUDE.md b/CLAUDE.md index 65c5bff5124..4b006d7bd54 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -100,6 +100,7 @@ GCC-style optimization level presets with per-pass overrides. | `PartialForward` | Partial store-load forwarding in combinational blocks | | `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) | ### Cranelift Backend Optimization diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2c6b6912b76..1d2fa52bdfd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,53 @@ Use the actual affected case or group as the filter. For SystemVerilog cases, use the `verify-sv-verilator` and `verify-sv-icarus` binaries. Missing tools, empty selections, compilation failures, and simulator errors are not passes. +For repeated local vtest runs, use the optimized shared executor: + +```sh +node scripts/run-vtest.mjs --test counter +node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' +``` + +This builds `vtest-exec` with the `vtest` Cargo profile (`opt-level = 1`, +development assertions and overflow checks enabled), then runs the existing +Celox test registrations with nextest. Both builds enable `systemverilog` and +`celox-test-suite/runtime-cases`. Cases execute in the shared binary, while +Rust API tests execute normally. Existing test names, filters, backend omissions, +ignored cases and nextest's parallel scheduling/timeouts are preserved. Additional +arguments are passed to `cargo nextest run`; use `--run-ignored all` to include +ignored registrations deliberately. + +With `runtime-cases`, `.vtest` bodies are read from disk instead of embedded in +Rust binaries, so edits to an existing case do not require recompilation. Adding +a test registration or changing Rust still requires a build. The first run builds +both the optimized executor and ordinary test binaries; the executor profile has +its own Cargo cache. Ordinary Cargo test commands retain the embedded, in-process +path. CI's Rust Tests job prepares the executor once and uses it for both full +workspace runs and scoped runs that include Celox. Scopes without Celox skip that +build. The default-branch cache warmer builds both executor and test dependencies +under the same cache key; vtest preparation failures fail the test job. + +The CI nextest profile also emits JUnit results. The Rust Tests job preserves +each scoped invocation separately under `work/ci-reports/rust/`, retains the XML +as the `rust-test-results` artifact for 14 days, and uploads it to Mergify CI +Insights when the repository's `MERGIFY_TOKEN` secret is available. The secret +must be a Mergify application key with `ci` scope, and CI Insights must be enabled +for the repository. Tests keep their normal failure status; reporting does not +enable retries or quarantine. Forks without the secret still run tests and retain +the artifact. `cargo test`/doctest invocations are not part of this nextest report. + +For debugging a single case after building, the executor also accepts +` ` directly, for example: + +```sh +target/vtest/examples/vtest-exec veryl counter::test_counter_n4_basic native +``` + +Direct invocations do not apply registration-level ignores. `CELOX_VTEST_ROOT` +can point to an alternative corpus root containing `veryl/cases` and `sv/cases`; +otherwise the executor uses the suite's source directory from its build checkout. +The script sets that root and `CELOX_VTEST_RUNNER` for its test invocation only. + External results are reused locally by default, including between worktrees, when the case, verifier and tool fingerprints match. New/changed cases and prior failures run again; `--fresh` forces execution. A Celox implementation diff --git a/Cargo.lock b/Cargo.lock index a7bb33ff72b..248419dde03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -799,6 +799,7 @@ dependencies = [ "num-traits", "serde_json", "sha2 0.11.1", + "tempfile", "veryl-analyzer", "veryl-emitter", "veryl-metadata", diff --git a/Cargo.toml b/Cargo.toml index 76c0db9690d..8c770d54d64 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -166,6 +166,12 @@ incremental = true [profile.bench] debug = true +# Optimize the shared vtest executor while keeping development checks enabled. +# External dependencies retain the dev profile's package-specific optimization. +[profile.vtest] +inherits = "dev" +opt-level = 1 + # Profile for wasm-pack builds. LTO is disabled to avoid a known issue # where proc-macro dependencies (syn) get incorrectly compiled for the # wasm32 target under full LTO. diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index db823a8e54f..5e45cf13916 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -876,6 +876,22 @@ pub struct RuntimeSchema { /// scheduler itself once one is generated. Present when the design has /// process kernels. pub scheduler: Option>, + /// 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 process units that run the edges of one event together with its +/// derived clock domains, the signal having already moved. Each reads +/// [`SchedulerSlots::dirty`] to know whether combinational logic must +/// settle before the domains evaluate. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct DerivedEdgeUnits { + /// The canonical event. + pub event: A, + /// Indices among the process units of the rising and the falling edge. + pub rising: usize, + pub falling: usize, } /// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`], @@ -1084,6 +1100,7 @@ impl Default for RuntimeSchema { active_commits: Vec::new(), time_slots: Vec::new(), scheduler: None, + derived_edges: Vec::new(), } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index bfb7ab5f61a..7682ec5627d 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2201,6 +2201,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( active_commits, time_slots, scheduler, + derived_edges: Vec::new(), }, }; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c44bd3b34c1..765af0db277 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1052,6 +1052,66 @@ fn shared_edge_memories( memories } +/// The unpacked arrays that only edge-triggered processes of `module` drive. +/// A process that writes one of them only by nonblocking assignments, at +/// least one of them at a run-time element, publishes just the elements it +/// wrote (see `Ff::lower_process`) instead of seeding and committing the +/// whole array on every edge. +/// +/// This uses the drivers within `module`. The sparse commit copies back +/// only the 64-bit chunks the process wrote, so a write from another scope +/// that lands between the evaluation and the commit of the process can be +/// lost only within those chunks, where a whole-array commit loses it +/// everywhere. A writer outside `module` (a hierarchical reference) that +/// must not lose such writes has to be excluded here. +fn edge_only_memories( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, +) -> HashSet { + let first_ff = module.comb_processes().len(); + let end_ff = first_ff + module.ff_processes().len(); + // Only an array a nonblocking assignment of an edge process writes can + // qualify; the driver scan is for those. + let mut nonblocking = HashSet::default(); + for process in module.ff_processes() { + for stmt in process.body() { + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { + lhs, + nonblocking: true, + .. + } => { + nonblocking.insert(lhs.name()); + } + sv::ir::Stmt::AssignConcat { + parts, + nonblocking: true, + .. + } => nonblocking.extend(parts.iter().map(sv::ir::LValue::name)), + _ => {} + }); + } + } + module + .signals() + .iter() + .filter(|s| { + !s.is_net() + && !s.r#type().unpacked_ranges().is_empty() + && nonblocking.contains(s.name()) + }) + .filter(|signal| { + let drivers = local_driver_ranges(module, signal.name(), constants, parameter_types); + !drivers.is_empty() + && drivers + .iter() + .all(|(id, _)| (first_ff..end_ff).contains(id)) + }) + .map(|signal| signal.name().to_string()) + .collect() +} + fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, @@ -8429,6 +8489,7 @@ fn lower_ff_processes( } } + let edge_memories = edge_only_memories(module, pm.constants, pm.parameter_types); let random_seeds = process_random_seeds(module); for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { let mut events = events @@ -8455,6 +8516,7 @@ fn lower_ff_processes( staged, } = ff::Ff::new(pm, random_seeds[&(0, index)]) .with_sparse_memories(shared_memories) + .with_sparse_candidates(&edge_memories) .lower_process(process.body())?; repeated_writes.extend(repeated_ff_writes(&eval_only, &staged)); // A process without writes still runs for its runtime events and diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b77cd77394d..61296800342 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -39,6 +39,15 @@ struct FunctionBlocks { pub(super) struct Ff<'p, 'a> { pub m: &'p mut ProcModule<'a>, sparse_memories: HashSet, + /// Arrays only edge-triggered processes drive. One this process writes + /// only by nonblocking element writes, at least one at a run-time + /// element, joins `sparse_memories`. + sparse_candidates: HashSet, + /// Variables written at a run-time element of an unpacked array. + element_writes: HashSet, + /// Variables written other than at a constant range or one element of + /// an unpacked array, which a sparse publication does not support. + other_writes: HashSet, b: SIRBuilder, /// Variables read from the working region. working: HashSet, @@ -108,6 +117,9 @@ impl<'p, 'a> Ff<'p, 'a> { Self { m, sparse_memories: HashSet::default(), + sparse_candidates: HashSet::default(), + element_writes: HashSet::default(), + other_writes: HashSet::default(), b: SIRBuilder::new(), working: HashSet::default(), nonblocking: HashSet::default(), @@ -147,6 +159,11 @@ impl<'p, 'a> Ff<'p, 'a> { self } + pub fn with_sparse_candidates(mut self, names: &HashSet) -> Self { + self.sparse_candidates = names.iter().filter_map(|name| self.m.id(name)).collect(); + self + } + /// Where a write of `id`, and a read of a value the process wrote, go: /// the working region, or stable state in a process kernel. fn target(&self, id: SourceVarId) -> Addr { @@ -204,8 +221,8 @@ impl<'p, 'a> Ff<'p, 'a> { .flatten() .and_then(|write| write.window) .unwrap_or(BitAccess::new(0, variable.width - 1)); - let access = match lvalue { - sv::ir::LValue::Ident(_) => BitAccess::new(0, variable.width - 1), + let constant = match lvalue { + sv::ir::LValue::Ident(_) => None, sv::ir::LValue::Select { msb, lsb, .. } => sv::typecheck::eval_const_expr_with_types( msb, self.m.constants, @@ -216,8 +233,20 @@ impl<'p, 'a> Ff<'p, 'a> { self.m.constants, self.m.parameter_types, )) - .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0) - .unwrap_or(whole), + .and_then(|(msb, lsb)| constant_select_write(variable, msb, lsb)?.0), + }; + if constant.is_none() { + // `write` takes the same order: a constant range, then one + // run-time element, then a read-modify-write of the variable. + if element_write { + self.element_writes.insert(id); + } else { + self.other_writes.insert(id); + } + } + let access = match lvalue { + sv::ir::LValue::Ident(_) => BitAccess::new(0, variable.width - 1), + sv::ir::LValue::Select { .. } => constant.unwrap_or(whole), }; self.targets.push((id, access)); } @@ -3937,6 +3966,23 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result { let mut visited = HashSet::default(); self.scan(body, &mut visited); + // Publish only the written elements of an array this process alone + // updates by nonblocking element writes, rather than seeding and + // committing all of it on every edge. The element stores keep + // statement order, so the last write to an element wins, and reads + // see stable state (IEEE 1800-2023 4.6, 10.4.2). + let sparse: Vec<_> = self + .sparse_candidates + .iter() + .copied() + .filter(|id| { + self.element_writes.contains(id) + && !self.working.contains(id) + && !self.other_writes.contains(id) + && !self.m.is_hidden(*id) + }) + .collect(); + self.sparse_memories.extend(sparse); if self .working .iter() diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 511a3310d32..19ffd8e1567 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -151,6 +151,13 @@ pub trait SimBackend { true } + /// Whether the code now running has the generated derived-edge units + /// (`RuntimeSchema::derived_edges`); otherwise a host walks the + /// derived-tick plans. + fn runs_derived_edge_units(&self) -> bool { + true + } + // ── event enumeration ─────────────────────────────────────── fn id_to_addr_slice(&self) -> &[AbsoluteAddr]; fn id_to_event_slice(&self) -> &[Self::Event]; diff --git a/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs b/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs index 20c9b779892..96eec63be7a 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/dataflow/pass_bit_extract_peephole.rs @@ -69,9 +69,11 @@ fn optimize_bit_extracts( // Collect replacements: (and_inst_idx) -> replacement Load instruction struct Replacement { and_idx: usize, - load_inst: SIRInstruction, - result_reg: RegisterId, - result_width: usize, + r_result: RegisterId, + addr: RegionedAbsoluteAddr, + bit_offset: usize, + // Bits read from memory: the mask width, truncated to the And's width. + load_width: usize, // Dead instruction indices to no-op (Shr + Imm(shift) + Imm(mask)) dead_indices: Vec, } @@ -135,7 +137,11 @@ fn optimize_bit_extracts( continue; } - let new_load = SIRInstruction::Load(*r_result, *addr, SIROffset::Static(base + k), w); + // The And keeps its own width: a mask narrower than the result + // zero-extends the extracted field, and a wider one is truncated. + let Some(result_width) = register_map.get(r_result).map(RegisterType::width) else { + continue; + }; let dead = vec![ shifted_def_idx, // Shr instruction @@ -145,9 +151,10 @@ fn optimize_bit_extracts( replacements.push(Replacement { and_idx: idx, - load_inst: new_load, - result_reg: *r_result, - result_width: w, + r_result: *r_result, + addr: *addr, + bit_offset: base + k, + load_width: w.min(result_width), dead_indices: dead, }); } @@ -207,16 +214,43 @@ fn optimize_bit_extracts( } // Build replacement map - let mut replacement_map: HashMap> = + let mut next_register = register_map.keys().map(|reg| reg.0).max().unwrap_or(0); + let mut fresh_register = |register_map: &mut HashMap, width| { + next_register += 1; + let reg = RegisterId(next_register); + register_map.insert(reg, RegisterType::Logic { width }); + reg + }; + let mut replacement_map: HashMap>> = HashMap::default(); for repl in replacements { - replacement_map.insert(repl.and_idx, repl.load_inst); - register_map.insert( - repl.result_reg, - RegisterType::Logic { - width: repl.result_width, - }, - ); + let load = |dst| { + SIRInstruction::Load( + dst, + repl.addr, + SIROffset::Static(repl.bit_offset), + repl.load_width, + ) + }; + let result_width = register_map[&repl.r_result].width(); + let new_insts = if repl.load_width == result_width { + register_map.insert( + repl.r_result, + RegisterType::Logic { + width: repl.load_width, + }, + ); + vec![load(repl.r_result)] + } else { + let field = fresh_register(register_map, repl.load_width); + let zeros = fresh_register(register_map, result_width - repl.load_width); + vec![ + load(field), + SIRInstruction::Imm(zeros, SIRValue::new(0u64)), + SIRInstruction::Concat(repl.r_result, vec![zeros, field]), + ] + }; + replacement_map.insert(repl.and_idx, new_insts); } // Rebuild instructions @@ -225,8 +259,8 @@ fn optimize_bit_extracts( if dead_set.contains(&i) { continue; } - if let Some(new_inst) = replacement_map.remove(&i) { - out.push(new_inst); + if let Some(new_insts) = replacement_map.remove(&i) { + out.extend(new_insts); } else { out.push(inst); } @@ -380,7 +414,7 @@ mod tests { }, ]; let mut register_map = HashMap::default(); - register_map.insert(RegisterId(4), RegisterType::Logic { width: 8 }); + register_map.insert(RegisterId(4), RegisterType::Logic { width: 2 }); let mut use_count = HashMap::default(); for inst in &instructions { record_uses(inst, &mut use_count); diff --git a/crates/celox-sir-opt/src/policy.rs b/crates/celox-sir-opt/src/policy.rs index fbb387bf896..90c1664ed84 100644 --- a/crates/celox-sir-opt/src/policy.rs +++ b/crates/celox-sir-opt/src/policy.rs @@ -116,6 +116,12 @@ define_sir_passes! { /// Compatibility selector for Cranelift oversized-function planning. /// This is not a SIR transform and is consumed at the backend boundary. TailCallSplit => "tail_call_split", + /// Run the edges of events with derived clock domains (gated clocks, + /// dividers) in generated units instead of walking their plans in Rust. + /// Not a SIR transform: the builder consumes it. The units compile the + /// clock's domain once more, so disabling it trades tick speed for build + /// time. + DerivedEdgeUnits => "derived_edge_units", } /// Diagnostics and additional verification for the SIR optimizer. /// @@ -278,11 +284,12 @@ impl OptimizeOptions { self.opt_level.default_enabled(pass) } - /// Returns true if any pass other than TailCallSplit is enabled. + /// Returns true if any SIR transform is enabled: any pass other than + /// the TailCallSplit and DerivedEdgeUnits selectors. pub fn any_enabled(&self) -> bool { - SirPass::ALL - .iter() - .any(|&p| p != SirPass::TailCallSplit && self.is_enabled(p)) + SirPass::ALL.iter().any(|&p| { + !matches!(p, SirPass::TailCallSplit | SirPass::DerivedEdgeUnits) && self.is_enabled(p) + }) } /// The base optimization level. diff --git a/crates/celox-test-suite/Cargo.toml b/crates/celox-test-suite/Cargo.toml index 7f5b893d5e0..989f9adf23b 100644 --- a/crates/celox-test-suite/Cargo.toml +++ b/crates/celox-test-suite/Cargo.toml @@ -12,6 +12,8 @@ readme = "README.md" [features] default = [] +# Load the corpus from disk so editing a case does not rebuild Rust runners. +runtime-cases = [] # Emit the Veryl cases to SystemVerilog. emit = ["dep:veryl-analyzer", "dep:veryl-emitter", "dep:veryl-parser", "dep:veryl-metadata"] # The external-simulator runners shared by both suites. Port shapes of the @@ -62,5 +64,8 @@ veryl-std.workspace = true serde_json = { workspace = true, optional = true } sha2 = { version = "0.11", optional = true } +[dev-dependencies] +tempfile.workspace = true + [lints] workspace = true diff --git a/crates/celox-test-suite/build.rs b/crates/celox-test-suite/build.rs index 6ac733d981f..3d94cad2b64 100644 --- a/crates/celox-test-suite/build.rs +++ b/crates/celox-test-suite/build.rs @@ -1,7 +1,10 @@ // Fingerprint the compiled verifier independently of the embedded case corpus. // Hashing the executable itself would invalidate every case after adding one. #[cfg(not(feature = "external"))] -fn main() {} +fn main() { + // Do not let Cargo's default package-wide scan track runtime-only cases. + println!("cargo:rerun-if-changed=build.rs"); +} #[cfg(feature = "external")] fn main() { diff --git a/crates/celox-test-suite/src/lib.rs b/crates/celox-test-suite/src/lib.rs index bd2186df8fb..186da9925d9 100644 --- a/crates/celox-test-suite/src/lib.rs +++ b/crates/celox-test-suite/src/lib.rs @@ -2,6 +2,8 @@ #![forbid(unsafe_code)] mod backend; +#[cfg(feature = "runtime-cases")] +mod runtime_cases; mod scalar; pub mod script; pub mod sv; diff --git a/crates/celox-test-suite/src/runtime_cases.rs b/crates/celox-test-suite/src/runtime_cases.rs new file mode 100644 index 00000000000..e619f52e2a1 --- /dev/null +++ b/crates/celox-test-suite/src/runtime_cases.rs @@ -0,0 +1,101 @@ +//! Runtime corpus loading for the development executor. + +use crate::{StdResolver, TestCase}; +use std::path::Path; + +#[allow( + clippy::disallowed_methods, + reason = "test corpus configuration boundary" +)] +pub(crate) fn load(language: &str, resolver: StdResolver) -> Vec<&'static TestCase> { + let root = std::env::var_os("CELOX_VTEST_ROOT") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("src")); + load_directory(&root.join(language).join("cases"), resolver) +} + +fn load_directory(directory: &Path, resolver: StdResolver) -> Vec<&'static TestCase> { + let mut paths = std::fs::read_dir(directory) + .unwrap_or_else(|error| panic!("read {}: {error}", directory.display())) + .map(|entry| entry.expect("read corpus entry").path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "vtest") + }) + .collect::>(); + paths.sort(); + assert!( + !paths.is_empty(), + "no .vtest files in {}", + directory.display() + ); + let mut names = std::collections::BTreeSet::new(); + paths + .into_iter() + .flat_map(|path| { + let text = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("read {}: {error}", path.display())); + crate::load_group(&path.to_string_lossy(), &text, resolver) + }) + .inspect(|case| { + assert!( + names.insert(case.name), + "duplicate vtest case: {}", + case.name + ); + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn case(group: &str, source: &str) -> String { + format!( + "(group {group} (category operators)) (case t (source \"top.sv\" \"{source}\") (top Top))" + ) + } + + #[test] + fn discovers_files_in_order_and_reads_edited_sources() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("b.vtest"), case("b", "before")).unwrap(); + std::fs::write(directory.path().join("a.vtest"), case("a", "a")).unwrap(); + std::fs::write(directory.path().join("ignored.txt"), "not a vtest").unwrap(); + let cases = load_directory(directory.path(), crate::no_std_library); + assert_eq!( + cases.iter().map(|case| case.name).collect::>(), + ["a::t", "b::t"] + ); + assert_eq!(cases[1].design().sources[0].text, "before"); + std::fs::write(directory.path().join("b.vtest"), case("b", "after")).unwrap(); + let cases = load_directory(directory.path(), crate::no_std_library); + assert_eq!(cases[1].design().sources[0].text, "after"); + } + + #[test] + #[should_panic(expected = "duplicate vtest case: a::t")] + fn duplicate_names_are_errors() { + let directory = tempfile::tempdir().unwrap(); + for file in ["a.vtest", "b.vtest"] { + std::fs::write(directory.path().join(file), case("a", "")).unwrap(); + } + load_directory(directory.path(), crate::no_std_library); + } + + #[test] + #[should_panic(expected = "no .vtest files")] + fn empty_corpus_is_an_error() { + let directory = tempfile::tempdir().unwrap(); + load_directory(directory.path(), crate::no_std_library); + } + + #[test] + #[should_panic(expected = "broken.vtest:")] + fn malformed_cases_report_the_file() { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("broken.vtest"), "(case").unwrap(); + load_directory(directory.path(), crate::no_std_library); + } +} diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index 28f734e4535..78a54d85cf2 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -1759,3 +1759,26 @@ endmodule (assert_eq remainder (fourstate 0xffffffff 0xffffffff)) (assert_eq nested (fourstate 0xffffffff 0xffffffff)) (assert_eq two_state 0)) + +(case masked_shift_fields_keep_expression_width + ; IEEE 1800-2023 11.6.1: `(a >> 4) & 15` is 32 bits wide; the extracted + ; field is zero-extended before comparisons, subtraction and indexing. + (source "masked_shift_fields.sv" #" + module Top(input logic clk, input logic [31:0] a, input logic [7:0] d, + output logic hit, output logic [31:0] field_minus_one, output logic [7:0] q); + logic [7:0] mem [16]; + assign hit = ((a >> 4) & 15) == 32'd9; + assign field_minus_one = ((a >> 4) & 15) - 1; + always_ff @(posedge clk) mem[(a >> 4) & 15] <= d; + assign q = mem[a[3:0]]; + endmodule + "#) + (top Top) + (modify (set a 0x95) (set d 0xab)) + (assert_eq hit 1) + (assert_eq field_minus_one 8) + (tick clk) + (modify (set a 0x09)) + (assert_eq hit 0) + (assert_eq field_minus_one 0xffffffff) + (assert_eq q 0xab)) diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index a0a35cf1779..30c65da968d 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -478,6 +478,53 @@ (assert_eq next 0) (assert_eq picked (? (< i 8) 0 (fourstate 1 1))))) +(case nonblocking_runtime_element_writes_apply_in_order + ; Nonblocking writes to run-time elements of one array apply after the + ; process in statement order: reads see the old values, the last write to + ; an element wins, also through different index expressions, and a later + ; part-select write merges into an earlier whole element write (IEEE + ; 1800-2023 10.4.2). Elements next to written ones keep their values. + (source "nba_runtime_elements.sv" #" + module Top(input logic clk, input logic we, input logic [3:0] a, b, + input logic [3:0] c, input logic [31:0] d, + input logic [3:0] ra, rb, + output logic [31:0] qa, qb, old); + logic [31:0] mem [16]; + initial for (int i = 0; i < 16; i++) mem[i] = i; + always_ff @(posedge clk) begin + old <= mem[a]; + if (we) begin + mem[a] <= d; + mem[b] <= mem[a] + 32'd1; + mem[a][7:0] <= 8'h5a; + end + mem[c] <= 32'hffff_ffff; + end + assign qa = mem[ra]; + assign qb = mem[rb]; + endmodule + "#) + (top Top) + (for (w x y z v r s ea eb eo) + (list (1 2 5 11 0x1000 2 5 0x105a 3 2) + (1 7 7 6 0x2000 7 6 0x5a 0xffffffff 7) + (0 2 0 11 0 3 4 3 4 0x105a) + (1 4 5 11 0xabcd0000 4 5 0xabcd005a 5 4) + (1 4 0 4 1 4 0 0xffffffff 0xabcd005b 0xabcd005a) + (0 0 0 11 0 2 11 0x105a 0xffffffff 0xabcd005b)) + (modify + (set we w) + (set a x) + (set b y) + (set c z) + (set d v) + (set ra r) + (set rb s)) + (tick clk) + (assert_eq qa ea) + (assert_eq qb eb) + (assert_eq old eo))) + (case declaration_initializers_define_the_initial_state (source "initializers.sv" #" module Top(input logic clk, input logic [1:0] index, diff --git a/crates/celox-test-suite/src/sv/mod.rs b/crates/celox-test-suite/src/sv/mod.rs index e2284608bf4..49b6e80302b 100644 --- a/crates/celox-test-suite/src/sv/mod.rs +++ b/crates/celox-test-suite/src/sv/mod.rs @@ -1,5 +1,6 @@ //! The SystemVerilog suite: cases whose designs are SystemVerilog source. +#[cfg(not(feature = "runtime-cases"))] mod cases; #[cfg(feature = "external")] @@ -7,12 +8,18 @@ pub mod verification; use crate::TestCase; -/// All cases in deterministic declaration order. A case's design is -/// SystemVerilog source; build it with your SystemVerilog frontend. +/// All cases in deterministic order (file-name order with `runtime-cases`, +/// otherwise catalogue declaration order). A case's design is SystemVerilog +/// source; build it with your SystemVerilog frontend. pub fn cases() -> impl Iterator { static CASES: std::sync::OnceLock> = std::sync::OnceLock::new(); CASES .get_or_init(|| { + #[cfg(feature = "runtime-cases")] + { + crate::runtime_cases::load("sv", crate::no_std_library) + } + #[cfg(not(feature = "runtime-cases"))] cases::GROUPS .iter() .flat_map(|group| crate::load_group(group.file, group.text, crate::no_std_library)) diff --git a/crates/celox-test-suite/src/veryl/mod.rs b/crates/celox-test-suite/src/veryl/mod.rs index e10decffab0..1b933014da7 100644 --- a/crates/celox-test-suite/src/veryl/mod.rs +++ b/crates/celox-test-suite/src/veryl/mod.rs @@ -1,5 +1,6 @@ //! The Veryl suite: cases whose designs are Veryl source. +#[cfg(not(feature = "runtime-cases"))] mod cases; #[cfg(feature = "emit")] @@ -69,12 +70,18 @@ fn std_source(path: &str) -> String { .unwrap_or_else(|err| panic!("failed to read {}: {err}", src.src.display())) } -/// All cases in deterministic declaration order. Filter by category or name in the +/// All cases in deterministic order (file-name order with `runtime-cases`, +/// otherwise catalogue declaration order). Filter by category or name in the /// host test runner; nothing is silently skipped by the suite itself. pub fn cases() -> impl Iterator { static CASES: std::sync::OnceLock> = std::sync::OnceLock::new(); CASES .get_or_init(|| { + #[cfg(feature = "runtime-cases")] + { + crate::runtime_cases::load("veryl", std_source) + } + #[cfg(not(feature = "runtime-cases"))] cases::GROUPS .iter() .flat_map(|group| crate::load_group(group.file, group.text, std_source)) diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index c854d2ed803..6ba5486a1b6 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -146,5 +146,9 @@ name = "frontend_binary" path = "examples/frontend_binary.rs" required-features = ["host-runtime"] +[[example]] +name = "vtest-exec" +required-features = ["host-runtime"] + [lints] workspace = true diff --git a/crates/celox/examples/vtest-exec.rs b/crates/celox/examples/vtest-exec.rs new file mode 100644 index 00000000000..66e69731bc6 --- /dev/null +++ b/crates/celox/examples/vtest-exec.rs @@ -0,0 +1,42 @@ +//! One case per process; libtest/nextest owns selection, ignores and scheduling. + +use clap::{Parser, ValueEnum}; + +#[path = "../tests/test_utils/suite.rs"] +mod suite; +#[path = "../tests/test_utils/veryl_sim.rs"] +mod veryl_sim; +#[path = "../tests/test_utils/veryl_sv.rs"] +mod veryl_sv; +#[path = "../tests/test_utils/vtest_exec.rs"] +mod vtest_exec; + +#[cfg(feature = "systemverilog")] +#[allow(dead_code)] +#[path = "../tests/frontends/systemverilog/suite.rs"] +mod sv_suite; + +#[derive(Clone, ValueEnum)] +enum Language { + Veryl, + #[cfg(feature = "systemverilog")] + Sv, +} + +#[derive(Parser)] +#[command(about = "Execute a runtime vtest case using the shared test adapters")] +struct Args { + #[arg(value_enum)] + language: Language, + case: String, + backend: String, +} + +fn main() { + let args = Args::parse(); + match args.language { + Language::Veryl => suite::run_case(&args.case, &args.backend), + #[cfg(feature = "systemverilog")] + Language::Sv => sv_suite::run_case(&args.case, &args.backend), + } +} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index cb7cff24b0f..28811acbea5 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -410,6 +410,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) active_commits: Vec, pub(crate) time_slots: Vec, pub(crate) scheduler: Option>, + pub(crate) derived_edges: Vec>, } /// Pointer-free native compiler artifact which can be attached to the @@ -526,6 +527,7 @@ impl NativeProgramImage { active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), scheduler: self.runtime_schema.scheduler.clone(), + derived_edges: self.runtime_schema.derived_edges.clone(), }, testbench: self.testbench.clone(), } @@ -621,12 +623,19 @@ impl NativeProgramImage { usize::MAX } }); - if self.process_offsets.len() - != self - .runtime_schema - .processes - .len() - .saturating_add(scheduler_units) + // The derived-edge units follow the kernels and the scheduler. + let derived_units = 2 * self.runtime_schema.derived_edges.len(); + let derived_in_range = self.runtime_schema.derived_edges.iter().all(|units| { + units.rising < self.process_offsets.len() && units.falling < self.process_offsets.len() + }); + if !derived_in_range + || self.process_offsets.len() + != self + .runtime_schema + .processes + .len() + .saturating_add(scheduler_units) + .saturating_add(derived_units) { return Err("process kernels and their control slots disagree".into()); } @@ -2443,6 +2452,7 @@ fn compile_program( active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), scheduler: sir.runtime().runtime_schema.scheduler.clone(), + derived_edges: sir.runtime().runtime_schema.derived_edges.clone(), }, layout: layout.clone(), native_memory_size, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index f587c107ec1..0c95b249cc8 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 = 33; +const CONTAINER_VERSION: u16 = 34; 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/tiered.rs b/crates/celox/src/backend/tiered.rs index 38c5e94aefc..bff1dcf143e 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -540,6 +540,10 @@ pub struct TieredBackend { /// first stage adopts a low-latency baseline image, this receiver yields /// the optimizing image for an in-place shared-code replacement. upgrade_receiver: Option>>, + /// The adopted code has the generated derived-edge units: a single-stage + /// image or the optimizing one. The baseline image leaves them out, so + /// their build cost lands in the optimizing tier. + derived_edges_live: bool, /// Evaluate-only events whose apply phase has not run yet. Promotion is /// deferred while this is non-zero so the compiled apply phase always /// observes the interpreted evaluate-only results through an intact @@ -799,6 +803,7 @@ impl TieredBackend { cancel, compiler_worker, upgrade_receiver: None, + derived_edges_live: false, pending_split_applies: 0, promotion_threshold, interpreted_steps: 0, @@ -859,6 +864,8 @@ impl TieredBackend { let (baseline_sender, baseline_receiver) = mpsc::channel(); let (upgrade_sender, upgrade_receiver) = mpsc::channel(); let background_laid_out = laid_out.clone(); + // The baseline image runs derived edges by walking their plans. + let baseline_laid_out = crate::derived_edge::without_units(laid_out); let worker_baseline_options = baseline_options.clone(); // A failed spawn keeps the interpreter as the permanent tier with the // reason recorded, matching the single-stage background-failure policy. @@ -868,11 +875,7 @@ impl TieredBackend { let span = tracing::info_span!("celox.tiered.compile", target = "native"); span.in_scope(|| { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - compile( - &background_laid_out, - &worker_baseline_options, - &worker_cancel, - ) + compile(&baseline_laid_out, &worker_baseline_options, &worker_cancel) })) .unwrap_or_else(|_| { Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError)) @@ -929,6 +932,7 @@ impl TieredBackend { cancel, compiler_worker, upgrade_receiver: Some(upgrade_receiver), + derived_edges_live: false, pending_split_applies: 0, promotion_threshold, interpreted_steps: 0, @@ -1141,6 +1145,8 @@ impl TieredBackend { } } self.phase = Phase::Compiled(compiled); + // A second stage still to come means this is the baseline image. + self.derived_edges_live = self.upgrade_receiver.is_none(); self.promotion = Promotion::Promoted; self.promoted_after_interpreted_steps = Some(self.interpreted_steps); if let Some(timing) = &mut self.execution_timing @@ -1205,6 +1211,7 @@ impl TieredBackend { && compiled.replace_native_code(code) { tracing::info!("tiered backend adopted optimizing native code"); + self.derived_edges_live = true; } } } @@ -1225,6 +1232,10 @@ impl SimBackend for TieredBackend { matches!(self.phase, Phase::Compiled(_)) } + fn runs_derived_edge_units(&self) -> bool { + matches!(self.phase, Phase::Compiled(_)) && self.derived_edges_live + } + type Event = TieredEventRef; fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode> { diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 2debba1c98c..32c2c0ae4f9 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -14,7 +14,10 @@ //! without settling for gates: two-state designs whose gated clocks all have //! gate programs. -use celox_design::{DomainKind, GateOp, STABLE_REGION, schedule::ScheduleModel}; +use celox_design::{ + DomainKind, GateOp, SCHEDULER_FLAG_WIDTH, STABLE_REGION, edges::active_level, + schedule::ScheduleModel, +}; use celox_sir::{BinaryOp, BlockId, SIRBuilder, SIRTerminator, SIRValue, UnaryOp}; use crate::ir::{ @@ -114,6 +117,28 @@ impl EdgePlan { if layout.four_state { return Err("the design is four-state"); } + // A host checks these after each unit it runs; a generated edge runs + // its units without returning in between. + if !program.runtime.runtime_schema.comb_observers.is_empty() { + return Err("the design observes combinational processes"); + } + let comb_fatal = program.sir.eval_comb.iter().any(|unit| { + unit.blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!( + inst, + SIRInstruction::CombCaptureEvent { + fatal_error_code: Some(_), + .. + } + ) + }) + }); + if comb_fatal { + return Err("combinational logic has fatal assertions"); + } if domains.len() + gated.len() + 1 > MAX_ENTRIES { return Err("an edge reaches too many derived domains"); } @@ -183,6 +208,20 @@ impl EdgePlan { 1 + self.domains.len() + index } + /// Whether entry `entry` can fire together with another: the event's own + /// domain with gated clocks that are not independent, the derived ones + /// in a round with another derived one or at the edge with the event's + /// own. + fn fires_with_others(&self, entry: usize) -> bool { + let derived = self.domains.len() + self.gated.len(); + let gated_together = !self.gated.is_empty() && !self.independent; + if entry == 0 { + gated_together + } else { + derived > 1 || (entry > self.domains.len() && gated_together) + } + } + /// Emit one edge of the event's signal, which has already moved from /// level `from` to `to` (one-bit registers). `fires` says whether the /// event's own domain sees its active edge, `settle` whether @@ -270,23 +309,47 @@ impl EdgePlan { let gated_ready = e.binary(MAX_ENTRIES, mask, BinaryOp::And, gated_bits); let any_gated = e.binary(1, gated_ready, BinaryOp::Ne, zero); let in_turn = e.binary(1, alone, BinaryOp::And, any_gated); - let one_at_a_time = e.b.new_block(); + // Each domain's units appear once in the unit: the one-domain path + // also serves the independent gated domains one at a time, and only + // domains that can fire with another get the several-domain path. + let one_mask = e.b.alloc_bit(MAX_ENTRIES, false); + let remaining = e.b.alloc_bit(MAX_ENTRIES, false); + let turn = e.b.alloc_bit(1, false); + let one_domain = e.b.new_block_with(vec![one_mask, remaining, turn]); + let rest = e.b.alloc_bit(MAX_ENTRIES, false); + let next_turn = e.b.new_block_with(vec![rest]); let together = e.b.new_block(); e.b.seal_block(SIRTerminator::Branch { cond: in_turn, - true_block: (one_at_a_time, Vec::new()), + true_block: (next_turn, vec![mask]), false_block: (together, Vec::new()), }); - // Independent gated domains, then the event's own, each fused. - e.b.switch_to_block(one_at_a_time); + // Independent gated domains, then the event's own, each fused, one + // at a time (`fire_with_gated`). + e.b.switch_to_block(next_turn); let order: Vec = (0..self.gated.len()) .map(|index| self.gated_bit(index)) .chain(std::iter::once(0)) .collect(); for entry in order { - let units = self.entries().nth(entry).expect("an entry of the mask"); - e.if_bit(mask, entry, |e| e.inline_all(&units.eval_apply)); + let bit = e.constant(1 << entry, MAX_ENTRIES); + let selected = e.binary(MAX_ENTRIES, rest, BinaryOp::And, bit); + let set = e.binary(1, selected, BinaryOp::Ne, zero); + let take = e.b.new_block(); + let skip = e.b.new_block(); + e.b.seal_block(SIRTerminator::Branch { + cond: set, + true_block: (take, Vec::new()), + false_block: (skip, Vec::new()), + }); + e.b.switch_to_block(take); + let all = e.constant(u64::MAX, MAX_ENTRIES); + let others = e.binary(MAX_ENTRIES, bit, BinaryOp::Xor, all); + let left = e.binary(MAX_ENTRIES, rest, BinaryOp::And, others); + let yes = e.constant(1, 1); + e.b.seal_block(SIRTerminator::Jump(one_domain, vec![bit, left, yes])); + e.b.switch_to_block(skip); } e.b.seal_block(SIRTerminator::Jump(fire_end, Vec::new())); @@ -297,27 +360,37 @@ impl EdgePlan { let lower = e.binary(MAX_ENTRIES, mask, BinaryOp::Sub, one); let others = e.binary(MAX_ENTRIES, mask, BinaryOp::And, lower); let single = e.binary(1, others, BinaryOp::Eq, zero); - let one_domain = e.b.new_block(); let several = e.b.new_block(); + let no = e.constant(0, 1); + let none_left = e.constant(0, MAX_ENTRIES); e.b.seal_block(SIRTerminator::Branch { cond: single, - true_block: (one_domain, Vec::new()), + true_block: (one_domain, vec![mask, none_left, no]), false_block: (several, Vec::new()), }); e.b.switch_to_block(one_domain); for (entry, units) in self.entries().enumerate() { - e.if_bit(mask, entry, |e| e.inline_all(&units.eval_apply)); + e.if_bit(one_mask, entry, |e| e.inline_all(&units.eval_apply)); } - e.b.seal_block(SIRTerminator::Jump(fire_end, Vec::new())); + e.b.seal_block(SIRTerminator::Branch { + cond: turn, + true_block: (next_turn, vec![remaining]), + false_block: (fire_end, Vec::new()), + }); e.b.switch_to_block(several); + let joint: Vec = (0..self.domains.len() + self.gated.len() + 1) + .map(|entry| self.fires_with_others(entry)) + .collect(); for (entry, units) in self.entries().enumerate() { - e.if_bit(mask, entry, |e| match &units.eval_only { - Some(eval_only) => e.inline_all(eval_only), - None => e.inline_all(&units.eval_apply), - }); + if joint[entry] { + e.if_bit(mask, entry, |e| match &units.eval_only { + Some(eval_only) => e.inline_all(eval_only), + None => e.inline_all(&units.eval_apply), + }); + } } for (entry, units) in self.entries().enumerate() { - if let Some(apply) = &units.apply { + if let (true, Some(apply)) = (joint[entry], &units.apply) { e.if_bit(mask, entry, |e| e.inline_all(apply)); } } @@ -640,26 +713,63 @@ impl Emitter<'_> { } } +/// Where a generated edge unit learns whether combinational logic must +/// settle before the domains evaluate. +#[derive(Clone, Copy, Debug)] +enum Settle { + #[cfg_attr(not(all(test, feature = "systemverilog")), allow(dead_code))] + Fixed(bool), + /// A flag object, not zero when it must. + Flag(AbsoluteAddr), +} + impl EdgePlan { /// A unit that runs one edge of the event whose signal its caller - /// already moved, rising or falling, with `settle` and `fires` fixed. - #[cfg(all(test, feature = "systemverilog"))] - fn unit(&self, comb: &[Unit], rising: bool, settle: bool, fires: bool) -> Unit { + /// already moved, rising or falling; `fires` says whether the event's own + /// domain sees its active edge. + fn unit(&self, comb: &[Unit], rising: bool, fires: bool, settle: Settle) -> Unit { let mut b = Builder::new(); - let constant = |b: &mut Builder, value: bool| { - let register = b.alloc_bit(1, false); - b.emit(SIRInstruction::Imm( - register, - SIRValue::new(u64::from(value)), - )); + let constant = |b: &mut Builder, value: u64, width: usize| { + let register = b.alloc_bit(width, false); + b.emit(SIRInstruction::Imm(register, SIRValue::new(value))); register }; - let from = constant(&mut b, !rising); - let to = constant(&mut b, rising); - let fires = constant(&mut b, fires); - let settle = constant(&mut b, settle); + let from = constant(&mut b, u64::from(!rising), 1); + let to = constant(&mut b, u64::from(rising), 1); + let source_fires = fires; + let fires = constant(&mut b, u64::from(fires), 1); + let settle = match settle { + Settle::Fixed(value) => constant(&mut b, u64::from(value), 1), + Settle::Flag(flag) => { + let value = b.alloc_bit(SCHEDULER_FLAG_WIDTH, false); + b.emit(SIRInstruction::Load( + value, + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, flag), + SIROffset::Static(0), + SCHEDULER_FLAG_WIDTH, + )); + let zero = constant(&mut b, 0, SCHEDULER_FLAG_WIDTH); + let set = b.alloc_bit(1, false); + b.emit(SIRInstruction::Binary(set, value, BinaryOp::Ne, zero)); + set + } + }; let done = b.new_block(); - self.emit(&mut b, comb, from, to, fires, settle, done, done); + // An edge that never fires the event's own domain leaves its units + // out of the unit. + let plan = if source_fires { + std::borrow::Cow::Borrowed(self) + } else { + std::borrow::Cow::Owned(EdgePlan { + source: DomainUnits { + eval_apply: Vec::new(), + eval_only: None, + apply: None, + }, + ..self.clone() + }) + }; + plan.emit(&mut b, comb, from, to, fires, settle, done, done); b.switch_to_block(done); b.seal_block(SIRTerminator::Return); let (blocks, register_map, _) = b.drain(); @@ -671,6 +781,75 @@ impl EdgePlan { } } +/// Generate the edge units of every event whose plan this module emits and +/// record them in [`celox_design::RuntimeSchema::derived_edges`]. A unit +/// reads the scheduler's dirty flag to know whether to settle first. +pub(crate) fn attach(program: &mut LaidOutProgram) { + let schema = &program.runtime.runtime_schema; + let Some(flag) = schema + .scheduler + .as_ref() + .map(|scheduler| scheduler.slots.dirty) + else { + return; + }; + let model = ScheduleModel::derive(&program.design, schema); + let mut edges = Vec::new(); + for event in crate::edge_plans::event_addresses(program) { + let Ok(Some(plan)) = EdgePlan::new(program, &model, event) else { + continue; + }; + // An edge of a clock or reset fires its domain when it is the active + // one; any other moved two-state signal always does. + let kind = model.kind(&event); + let fires = |rising: bool| match kind { + Some( + DomainKind::ClockPosedge + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncHigh + | DomainKind::ResetAsyncLow, + ) => rising == (active_level(kind) == 1), + _ => true, + }; + let mut indices = [0usize; 2]; + for (index, rising) in [true, false].into_iter().enumerate() { + let unit = plan.unit( + &program.sir.eval_comb, + rising, + fires(rising), + Settle::Flag(flag), + ); + indices[index] = program.sir.processes.len(); + program.sir.processes.push(unit); + } + edges.push(celox_design::DerivedEdgeUnits { + event, + rising: indices[0], + falling: indices[1], + }); + } + program.runtime.runtime_schema.derived_edges = edges; +} + +/// `program` without its derived-edge units, for a tier whose host walks +/// the derived-tick plans instead. The units follow every other process +/// unit, so the others keep their indices. +pub(crate) fn without_units(program: &LaidOutProgram) -> LaidOutProgram { + let mut program = program.clone(); + let first = program + .runtime + .runtime_schema + .derived_edges + .iter() + .map(|units| units.rising.min(units.falling)) + .min(); + if let Some(first) = first { + program.sir.processes.truncate(first); + program.runtime.runtime_schema.derived_edges.clear(); + } + program +} + /// A generated edge unit and the edge it runs, for the tests. #[cfg(all(test, feature = "systemverilog"))] #[derive(Clone, Copy, Debug)] @@ -697,7 +876,8 @@ pub(crate) fn attach_test_units(program: &mut LaidOutProgram, sink: &TestEdgeUni for rising in [false, true] { for settle in [false, true] { for fires in [false, true] { - let unit = plan.unit(&program.sir.eval_comb, rising, settle, fires); + let unit = + plan.unit(&program.sir.eval_comb, rising, fires, Settle::Fixed(settle)); let index = program.sir.processes.len(); program.sir.processes.push(unit); sink.lock().expect("unpoisoned").push(TestEdgeUnit { @@ -727,6 +907,66 @@ mod tests { backend::{EventHandle, SimBackend}, }; + const GATED: &str = "module Top(input logic clk, input logic en, output logic [7:0] q); + logic gclk; + logic [7:0] r = 0; + logic [7:0] g = 0; + logic [7:0] w; + assign gclk = clk & en; + // A value the host's writes of `en` change through logic. + assign w = en ? 8'd3 : 8'd1; + always_ff @(posedge clk) r <= r + w; + always_ff @(posedge gclk) g <= g + r; + assign q = g; + endmodule"; + + const INVERTED: &str = "module Top(input logic clk, input logic en, output logic [7:0] q); + logic nclk; + logic gclk; + logic [7:0] r = 0; + logic [7:0] n = 0; + logic [7:0] g = 0; + assign nclk = ~clk; + assign gclk = clk & en; + always_ff @(posedge clk) r <= r + 8'd1; + always_ff @(posedge nclk) n <= n + r; + always_ff @(negedge gclk) g <= g ^ n; + assign q = n + g; + endmodule"; + + const DIVIDERS: &str = "module Top(input logic clk, output logic [7:0] q); + logic half = 0; + logic quarter = 0; + logic [7:0] h = 0; + logic [7:0] w = 0; + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) quarter <= ~quarter; + always_ff @(posedge half) h <= h + 8'd1; + always_ff @(posedge quarter) w <= w + h; + assign q = h + w; + endmodule"; + + const RAISED_ENABLE: &str = "module Top(input logic clk, output logic [7:0] q); + logic en = 0; + logic gclk; + logic [7:0] g = 0; + assign gclk = clk & en; + always_ff @(posedge clk) en <= ~en; + always_ff @(posedge gclk) g <= g + 8'd1; + assign q = g; + endmodule"; + + const INDEPENDENT: &str = + "module Top(input logic clk, input logic en, input logic [7:0] d, output logic [7:0] q); + logic gclk; + logic [7:0] r = 0; + logic [7:0] g = 0; + assign gclk = clk & en; + always_ff @(posedge clk) r <= r + d; + always_ff @(posedge gclk) g <= g + 8'd3; + assign q = r ^ g; + endmodule"; + /// The design state: the stable region after its header. fn state(backend: &B) -> Vec { let (ptr, len) = backend.memory_as_ptr(); @@ -851,84 +1091,80 @@ mod tests { } } + /// Drive `source` through the `Simulator` API, with derived domains run + /// by the generated edge units and by the plan walk, and compare every + /// named signal after each operation: ticks of `clk`, single and + /// repeated edges, and host writes of `en` when the design has it. + fn ticks_agree(source: &str) { + let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + let mut generated = build().build().unwrap(); + let mut walked = build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build() + .unwrap(); + assert!( + !generated.program.runtime_schema.derived_edges.is_empty(), + "no edge unit was generated" + ); + assert!(walked.program.runtime_schema.derived_edges.is_empty()); + let clk = generated.event("clk"); + let en = generated.try_signal("en").ok(); + let names: Vec<_> = walked.named_signals(); + for step in 0..80usize { + for sim in [&mut generated, &mut walked] { + if let Some(en) = en + && step % 7 < 2 + { + sim.modify(|io| io.set(en, u8::from(step % 3 != 0))) + .unwrap(); + } + match step % 5 { + 0 | 1 => sim.tick(clk).unwrap(), + 2 => sim.edge(clk, Edge::Rising).unwrap(), + 3 => sim.edge(clk, Edge::Rising).unwrap(), + _ => sim.edge(clk, Edge::Falling).unwrap(), + } + } + for named in &names { + assert_eq!( + generated.get(named.signal), + walked.get(named.signal), + "step {step}: {}", + named.name + ); + } + } + } + + #[test] + fn simulator_ticks_run_generated_edges_as_the_plan_walk() { + for source in [GATED, INVERTED, DIVIDERS, RAISED_ENABLE, INDEPENDENT] { + ticks_agree(source); + } + } + #[test] fn gated_clocks_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, input logic en, output logic [7:0] q); - logic gclk; - logic [7:0] r = 0; - logic [7:0] g = 0; - assign gclk = clk & en; - always_ff @(posedge clk) r <= r + 8'd1; - always_ff @(posedge gclk) g <= g + r; - assign q = g; - endmodule", - ); + agrees(GATED); } #[test] fn inverted_and_falling_gated_clocks_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, input logic en, output logic [7:0] q); - logic nclk; - logic gclk; - logic [7:0] r = 0; - logic [7:0] n = 0; - logic [7:0] g = 0; - assign nclk = ~clk; - assign gclk = clk & en; - always_ff @(posedge clk) r <= r + 8'd1; - always_ff @(posedge nclk) n <= n + r; - always_ff @(negedge gclk) g <= g ^ n; - assign q = n + g; - endmodule", - ); + agrees(INVERTED); } #[test] fn dividers_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, output logic [7:0] q); - logic half = 0; - logic quarter = 0; - logic [7:0] h = 0; - logic [7:0] w = 0; - always_ff @(posedge clk) half <= ~half; - always_ff @(posedge half) quarter <= ~quarter; - always_ff @(posedge half) h <= h + 8'd1; - always_ff @(posedge quarter) w <= w + h; - assign q = h + w; - endmodule", - ); + agrees(DIVIDERS); } #[test] fn enables_the_commit_raises_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, output logic [7:0] q); - logic en = 0; - logic gclk; - logic [7:0] g = 0; - assign gclk = clk & en; - always_ff @(posedge clk) en <= ~en; - always_ff @(posedge gclk) g <= g + 8'd1; - assign q = g; - endmodule", - ); + agrees(RAISED_ENABLE); } #[test] fn independent_gated_domains_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, input logic en, input logic [7:0] d, output logic [7:0] q); - logic gclk; - logic [7:0] r = 0; - logic [7:0] g = 0; - assign gclk = clk & en; - always_ff @(posedge clk) r <= r + d; - always_ff @(posedge gclk) g <= g + 8'd3; - assign q = r ^ g; - endmodule", - ); + agrees(INDEPENDENT); } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index ae4fb81ffe3..28c216b193e 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -19,9 +19,7 @@ pub use component::{ register_static_component_manifest, }; mod debug; -// Only its tests run the generator until a host does. #[cfg(feature = "host-runtime")] -#[cfg_attr(not(all(test, feature = "systemverilog")), allow(dead_code))] mod derived_edge; mod edge_plans; pub use edge_plans::{ diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 2ce6b6afe92..ffccc1394d2 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -163,6 +163,12 @@ mod host { derived_ticks: celox_runtime::DerivedTickPlans, /// Boxed, so that taking it out for a tick moves one pointer. derived_scratch: Option>, + /// Per event ID, the generated units that run an edge of the event + /// with its derived domains. Empty without them. + derived_units: Arc<[Option]>, + /// The flag a derived-edge unit reads to settle combinational logic + /// before the domains evaluate. + derived_settle: Option, /// The design finished a timed simulation (`$finish`). Evaluation, /// host writes and waveform dumps no longer change anything. pub(crate) frozen: bool, @@ -850,6 +856,8 @@ mod host { celox_runtime::build_derived_tick_plans(&backend, &schedule); let event_edges = celox_runtime::build_event_edges(&backend, &schedule.events, &schedule.kinds); + let (derived_units, derived_settle) = + derived_edge_units(&backend, &program.runtime_schema, &derived_ticks); let comb_observer_reads = crate::comb_activation::ObserverReads::new( &backend, &program.runtime_schema.comb_observers, @@ -884,6 +892,8 @@ mod host { tick_timing_eval_comb_ns: 0, derived_ticks, derived_scratch: Some(Box::new(derived_scratch)), + derived_units, + derived_settle, frozen: false, host_watch: Default::default(), finish_scan_seq: 0, @@ -1848,6 +1858,12 @@ mod host { } return Ok(()); } + if let Some(Some(unit)) = self.derived_units.get(event.id()).copied() + && !self.finish_sites + && self.backend.runs_derived_edge_units() + { + return self.edge_unit(info, edge, unit); + } let plans = std::sync::Arc::clone(&self.derived_ticks); let plan = plans.get(event.id()).and_then(Option::as_ref); let mut scratch = self.derived_scratch.take().unwrap_or_default(); @@ -1861,6 +1877,53 @@ mod host { self.note_edge(result) } + /// [`Self::edge`] of an event with a generated derived-edge unit: + /// move the signal, then run the unit of the edge, which judges the + /// gated clocks, runs the domains and the cascade rounds, as the plan + /// walk does. + #[inline(never)] + fn edge_unit( + &mut self, + info: celox_runtime::EventEdge, + edge: celox_runtime::Edge, + unit: DerivedEdgeUnit, + ) -> Result<(), RuntimeErrorCode> { + let mut watch = std::mem::take(&mut self.host_watch); + let moved = celox_runtime::move_signal( + &mut self.backend, + &info, + edge, + watched_write(&mut watch), + ); + self.host_watch = watch; + let Some(old) = moved else { + return Ok(()); + }; + let fires = info.fires(old, edge); + if let Some(flag) = self.derived_settle { + self.backend + .set(flag, u8::from(self.dirty || info.comb_read)); + } + let index = match edge { + celox_runtime::Edge::Rising => unit.rising, + celox_runtime::Edge::Falling => unit.falling, + }; + if let Err(error) = self.backend.run_process(index) { + self.dirty = true; + return Err(self.decorate_runtime_error(error)); + } + // Without a gated clock and the event's own edge nothing ran, as + // in the plan walk. + let outcome = if unit.gated || fires { + celox_runtime::EdgeOutcome::Settled + } else if info.comb_read { + celox_runtime::EdgeOutcome::Moved + } else { + celox_runtime::EdgeOutcome::Stored + }; + self.note_edge(Ok(outcome)) + } + fn note_edge( &mut self, outcome: Result, @@ -2830,6 +2893,46 @@ mod host { } } + /// The generated units of one event's edges with its derived domains. + #[derive(Clone, Copy, Debug)] + struct DerivedEdgeUnit { + rising: usize, + falling: usize, + /// The event gates derived clocks, so an edge always runs domains. + gated: bool, + } + + /// Per event ID, the generated derived-edge units of `schema`, and the flag + /// they read to settle first. + fn derived_edge_units( + backend: &B, + schema: &celox_design::RuntimeSchema, + plans: &celox_runtime::DerivedTickPlans, + ) -> (Arc<[Option]>, Option) { + if schema.derived_edges.is_empty() { + return (Arc::from([]), None); + } + let mut units = vec![None; backend.num_events()]; + for edges in &schema.derived_edges { + let Some(event) = backend.resolve_event_opt(&edges.event) else { + continue; + }; + let Some(Some(plan)) = plans.get(event.id()) else { + continue; + }; + units[event.id()] = Some(DerivedEdgeUnit { + rising: edges.rising, + falling: edges.falling, + gated: plan.lever_signals().next().is_some(), + }); + } + let flag = schema + .scheduler + .as_ref() + .map(|scheduler| backend.resolve_signal(&scheduler.slots.dirty)); + (units.into(), flag) + } + /// The host's write of an event signal's level, observed by a timed /// simulation's waits and counters as [`IOContext`] writes are. fn watched_write( diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 68400436bc8..7f8b600c462 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2848,6 +2848,14 @@ mod host { { crate::scheduler::attach(&mut laid_out); } + #[cfg(feature = "host-runtime")] + if self + .options + .optimize_options + .is_enabled(crate::optimizer::SirPass::DerivedEdgeUnits) + { + crate::derived_edge::attach(&mut laid_out); + } #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] if let Some(sink) = &self.options.derived_edge_units { crate::derived_edge::attach_test_units(&mut laid_out, sink); diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index 04f2499e68f..d19f42f5af4 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -189,6 +189,10 @@ sv_backends! { fn wide_wildcard_comparisons_normalize_unknown_to_x(sim) { @case "operators::wide_wildcard_comparisons_normalize_unknown_to_x"; } + + fn masked_shift_fields_keep_expression_width(sim) { + @case "operators::masked_shift_fields_keep_expression_width"; + } } sv_backends! { diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 709c06a182f..dd47e78f796 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -93,6 +93,10 @@ sv_backends! { @case "procedural::runtime_bits_stay_within_their_element"; } + fn nonblocking_runtime_element_writes_apply_in_order(sim) { + @case "procedural::nonblocking_runtime_element_writes_apply_in_order"; + } + fn declaration_initializers_define_the_initial_state(sim) { @case "procedural::declaration_initializers_define_the_initial_state"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 286bcb3b487..0b5bcf1427b 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8760,6 +8760,62 @@ fn shared_ff_memories_keep_native_sparse_next_state() { } } +/// An array one edge process updates only by nonblocking element writes +/// publishes the written elements, not a seed and commit of the whole array +/// per edge (#1855). A blocking write keeps the whole-array next state. +#[test] +fn nonblocking_runtime_element_writes_use_sparse_next_state() { + use celox_design::{SPARSE_WORKING_REGION, WORKING_REGION}; + use celox_sir::SIRInstruction; + + for (body, sparse) in [ + ("mem[addr] <= data; mem[3][7:0] <= data[7:0];", true), + ("mem[addr] = data;", false), + ("mem[addr] <= data; mem <= '{default: 0};", false), + ] { + let source = format!( + r#"module Top(input bit clk, input bit [11:0] addr, input bit [31:0] data, + output wire [31:0] q); + bit [31:0] mem[4096]; + always_ff @(posedge clk) begin {body} end + assign q = mem[addr]; + endmodule"# + ); + let result = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("nba_ram.sv"))], "Top") + .trace_pre_optimized_sir() + .build_with_trace(); + let sim = result.res.unwrap(); + let memory = sim.program().get_addr(&[], &["mem"]).unwrap(); + let program = result.trace.pre_optimized_sir.unwrap(); + let mut regions = Vec::new(); + for instruction in program + .sir + .eval_apply_ffs + .values() + .flatten() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + { + match instruction { + SIRInstruction::Store(address, ..) if address.absolute_addr() == memory => { + regions.push(address.region); + } + SIRInstruction::Commit(source, destination, ..) + if source.absolute_addr() == memory + || destination.absolute_addr() == memory => + { + regions.push(source.region); + regions.push(destination.region); + } + _ => {} + } + } + assert_eq!(regions.contains(&SPARSE_WORKING_REGION), sparse, "{body}"); + assert_eq!(regions.contains(&WORKING_REGION), !sparse, "{body}"); + } +} + #[test] fn rejects_overlapping_continuous_concatenation_drivers() { for declaration in ["wire [7:0] q", "logic [7:0] q"] { diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index d3f41052704..f10ac99fc15 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -363,7 +363,10 @@ fn build(design: &Design, backend: &str) -> Result> { /// Run the suite case `name` on `backend`. The SV frontend is recursive, so /// the case runs on a thread with room on its stack. -pub fn run_case(name: &'static str, backend: &'static str) { +pub fn run_case(name: &str, backend: &str) { + if super::vtest_exec::dispatch("sv", name, backend) { + return; + } std::thread::scope(|scope| { std::thread::Builder::new() .stack_size(8 * 1024 * 1024) diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 5edb5ce8c0b..de1a3301960 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -3,6 +3,9 @@ use std::path::Path; use celox::Simulator; use num_bigint::BigUint; +#[path = "test_utils/vtest_exec.rs"] +mod vtest_exec; + // Each entry is either a suite case, `@case "group::name";`, or a test written // against the Celox API with `@setup` and `@build`. Either runs on every backend. macro_rules! sv_backends { diff --git a/crates/celox/tests/test_utils/mod.rs b/crates/celox/tests/test_utils/mod.rs index dda3390ee2d..141a34687f5 100644 --- a/crates/celox/tests/test_utils/mod.rs +++ b/crates/celox/tests/test_utils/mod.rs @@ -1,6 +1,7 @@ pub mod suite; pub mod veryl_sim; pub mod veryl_sv; +pub mod vtest_exec; #[path = "../fixtures/veryl_std.rs"] #[allow(dead_code)] diff --git a/crates/celox/tests/test_utils/suite.rs b/crates/celox/tests/test_utils/suite.rs index 95aa93d426c..a152d50d399 100644 --- a/crates/celox/tests/test_utils/suite.rs +++ b/crates/celox/tests/test_utils/suite.rs @@ -221,6 +221,9 @@ fn build_sv(design: &Design, sources: &[(&str, &std::path::Path)]) -> Result bool { + let Some(executable) = std::env::var_os("CELOX_VTEST_RUNNER") else { + return false; + }; + let status = std::process::Command::new(&executable) + .args([language, name, backend]) + // The executor shares these adapters. Do not dispatch recursively. + .env_remove("CELOX_VTEST_RUNNER") + .status() + .unwrap_or_else(|error| panic!("start vtest executor {executable:?}: {error}")); + assert!( + status.success(), + "vtest {language}/{name}/{backend}: {status}" + ); + true +} diff --git a/crates/celox/tests/tick_semantics.rs b/crates/celox/tests/tick_semantics.rs index 78ebf514fac..e25afb59e0f 100644 --- a/crates/celox/tests/tick_semantics.rs +++ b/crates/celox/tests/tick_semantics.rs @@ -31,10 +31,22 @@ module Dut ( output logic [7:0] r, output logic [7:0] c2, output logic [7:0] s, + output logic [7:0] d, + output logic [7:0] e, output logic lvl ); logic gclk; + logic half = 1'b0; + logic ren = 1'b0; + logic rclk; assign gclk = clk & en; + // A clock divided from `clk`, and a gate whose enable `clk`'s own domain + // toggles. + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) d <= d + 8'd1; + always_ff @(posedge clk) ren <= ~ren; + assign rclk = clk & ren; + always_ff @(posedge rclk) e <= e + 8'd1; always_ff @(posedge clk) p <= p + 8'd1; always_ff @(negedge clk) n <= n + 8'd1; always_ff @(posedge gclk) g <= g + 8'd1; @@ -48,7 +60,7 @@ module Dut ( endmodule "#; -const OUTPUTS: [&str; 8] = ["p", "n", "g", "ng", "r", "c2", "s", "lvl"]; +const OUTPUTS: [&str; 10] = ["p", "n", "g", "ng", "r", "c2", "s", "d", "e", "lvl"]; /// Event signals with their active levels. const EVENTS: [(&str, u8); 3] = [("clk", 1), ("clk2", 1), ("rst_n", 0)]; @@ -93,10 +105,10 @@ fn reference(ops: &[Op]) -> Vec> { `timescale 1ns/1ns module Top; logic clk, clk2, en, rst_n; - wire [7:0] p, n, g, ng, r, c2, s; + wire [7:0] p, n, g, ng, r, c2, s, d, e; wire lvl; Dut u ( - .clk, .clk2, .en, .rst_n, .p, .n, .g, .ng, .r, .c2, .s, .lvl + .clk, .clk2, .en, .rst_n, .p, .n, .g, .ng, .r, .c2, .s, .d, .e, .lvl ); initial begin {body} end @@ -124,11 +136,18 @@ endmodule .collect() } -fn hosted(ops: &[Op]) -> Vec> { - let mut sim = Simulator::from_sv_sources(vec![(DUT, Path::new("dut.sv"))], "Dut") - .four_state(false) - .build() - .unwrap(); +/// The values of `OUTPUTS` after each operation through the `Simulator` +/// API, with derived clock domains run by their generated edge units, or by +/// walking their plans when `walk`. +fn hosted(ops: &[Op], walk: bool) -> Vec> { + let builder = + Simulator::from_sv_sources(vec![(DUT, Path::new("dut.sv"))], "Dut").four_state(false); + let builder = if walk { + builder.disable_pass(celox::SirPass::DerivedEdgeUnits) + } else { + builder + }; + let mut sim = builder.build().unwrap(); ops.iter() .map(|&op| { match op { @@ -166,14 +185,26 @@ fn hosted(ops: &[Op]) -> Vec> { } fn check(ops: &[Op]) { + check_except(ops, &[]); +} + +/// [`check`] of every output but `skipped`. +fn check_except(ops: &[Op], skipped: &[&str]) { + let kept: Vec = (0..OUTPUTS.len()) + .filter(|&index| !skipped.contains(&OUTPUTS[index])) + .collect(); + let select = |values: &Vec| kept.iter().map(|&index| values[index]).collect::>(); let expected = reference(ops); - let actual = hosted(ops); - for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate() { - assert_eq!( - actual, expected, - "after {:?} (operation {k}), outputs {OUTPUTS:?}", - ops[k] - ); + for walk in [false, true] { + let actual = hosted(ops, walk); + for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate() { + assert_eq!( + select(actual), + select(expected), + "after {:?} (operation {k}, walk {walk}), outputs {OUTPUTS:?} without {skipped:?}", + ops[k] + ); + } } } @@ -207,14 +238,38 @@ fn a_tick_from_the_active_level_takes_only_the_inactive_edge() { ]); } -/// Coincident ticks sample each other's values from before the edge. +const COINCIDENT: [Op; 5] = [ + Op::Edge("rst_n", 1), + Op::Tick(&["clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk"]), +]; + +/// Coincident ticks sample each other's values from before the edge. The +/// commit-raised gate's domain (`e`) is checked against Icarus below until +/// the timed reference sees its edge in a coincident batch (#1860). #[test] fn ticks_of_several_events_are_coincident() { - check(&[ - Op::Edge("rst_n", 1), - Op::Tick(&["clk2"]), - Op::Tick(&["clk", "clk2"]), - Op::Tick(&["clk", "clk2"]), - Op::Tick(&["clk"]), - ]); + check_except(&COINCIDENT, &["e"]); +} + +/// At the second coincident tick `clk` rises while `ren` is already high, so +/// `rclk` rises in the active region and `e` counts: Icarus 13.0 gives +/// `e` = 0 0 1 2 3 after the operations. The timed reference gives 0 0 1 1 2 +/// (#1860); both `Simulator` paths agree with Icarus. +#[test] +#[ignore = "#1860"] +fn coincident_ticks_run_the_domain_of_a_gate_the_commit_raised() { + let e = OUTPUTS.iter().position(|name| *name == "e").unwrap(); + let values = |rows: Vec>| rows.iter().map(|row| row[e]).collect::>(); + let icarus = vec![0, 0, 1, 2, 3]; + assert_eq!( + values(reference(&COINCIDENT)), + icarus, + "the timed reference" + ); + for walk in [false, true] { + assert_eq!(values(hosted(&COINCIDENT, walk)), icarus, "walk {walk}"); + } } diff --git a/crates/celox/tests/tiered.rs b/crates/celox/tests/tiered.rs index 894bec229a6..8873c86fe5d 100644 --- a/crates/celox/tests/tiered.rs +++ b/crates/celox/tests/tiered.rs @@ -394,3 +394,96 @@ endmodule assert!(sim.promotion_error().is_none()); assert_eq!(sim.get_four_state(neq), expected); } + +const DERIVED: &str = r#" +module Top ( + clk: input clock, + rst: input reset, + en: input logic, + cnt: output logic<8>, + extra: output logic<8>, + more: output logic<8>, +) { + var c: logic<8>; + var e: logic<8>; + var m: logic<8>; + var half: logic; + let gated: '_ clock = clk & en; + let divided: '_ clock = half; + always_ff (clk, rst) { + if_reset { + c = 0; + half = 0; + } else { + c += 1; + half = ~half; + } + } + always_ff (gated) { + e += c; + } + always_ff (divided) { + m += 1; + } + assign cnt = c; + assign extra = e; + assign more = m; +} +"#; + +/// Derived clock edges walk their plans until the tier with the generated +/// derived-edge units runs (the optimizing image of a two-stage build), then +/// run the units, matching the plan walk throughout. +#[test] +fn tiered_derived_edges_switch_to_generated_units() { + use celox::SimBackend as _; + let mut tiered: Simulator = SimulatorBuilder::new(DERIVED, "Top") + .build_tiered() + .unwrap(); + let mut walked = Simulator::builder(DERIVED, "Top") + .disable_pass(celox::SirPass::DerivedEdgeUnits) + .build() + .unwrap(); + let outputs = ["cnt", "extra", "more"]; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + let mut live_ticks = 0u32; + let mut step = 0u32; + while live_ticks < 32 { + assert!( + std::time::Instant::now() < deadline, + "the generated derived-edge units never became live" + ); + let (rst, en) = (u8::from(step > 1), u8::from(!step.is_multiple_of(5))); + let reset = tiered.signal("rst"); + let enable = tiered.signal("en"); + tiered + .modify(|io| { + io.set(reset, rst); + io.set(enable, en); + }) + .unwrap(); + let reset = walked.signal("rst"); + let enable = walked.signal("en"); + walked + .modify(|io| { + io.set(reset, rst); + io.set(enable, en); + }) + .unwrap(); + let clk = tiered.event("clk"); + tiered.tick(clk).unwrap(); + let clk = walked.event("clk"); + walked.tick(clk).unwrap(); + for name in outputs { + let left = tiered.get_as::(tiered.signal(name)); + let right = walked.get_as::(walked.signal(name)); + assert_eq!(left, right, "step {step}: {name}"); + } + if tiered.backend_ref().runs_derived_edge_units() { + live_ticks += 1; + } else { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + step += 1; + } +} diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index 2359f540469..7ecea17951a 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -95,6 +95,12 @@ unnecessary: - an event that does not match the required edge does not evaluate its domain; - a non-cascaded single domain may use a combined evaluate-and-commit kernel; - cascaded evaluation continues only while newly triggered domains exist. +- an edge of an event with derived clock domains (gated clocks, dividers) runs + as generated units, which judge the gated clocks, run the domains and the + cascade rounds, instead of a walk of the derived-tick plan in Rust. These units + 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. These choices preserve the ordering model defined in [Runtime Semantics](./cascade-limitations.md). They do not change signal values or diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index e151864feb8..7dfee70b78f 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -346,7 +346,10 @@ export interface SimulatorOptions { * bit_extract_peephole, optimize_blocks, split_wide_commits, commit_sinking, * inline_commit_forwarding, eliminate_dead_working_stores, reschedule, * coalesce_stores, gvn, concat_folding, xor_chain_folding, vectorize_concat, - * split_coalesced_stores, partial_forward, identity_store_bypass, tail_call_split + * 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) * * @example ["-sir:reschedule", "+sir:gvn"] */ diff --git a/scripts/ci-rust-reports.mjs b/scripts/ci-rust-reports.mjs new file mode 100644 index 00000000000..ddfb851c8ee --- /dev/null +++ b/scripts/ci-rust-reports.mjs @@ -0,0 +1,40 @@ +import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +function currentReport(root) { + return resolve(root, "target/nextest/ci/junit.xml"); +} + +// Only remove nextest's report; never create target/ before Cargo/mbx runs. +export function clearCurrentReport(source = currentReport(process.cwd())) { + rmSync(source, { force: true }); +} + +export function resetReports(directory, source = currentReport(process.cwd())) { + clearCurrentReport(source); + if (!existsSync(directory)) return; + for (const name of readdirSync(directory)) { + if (/^nextest-(?:full|\d+)\.xml$/.test(name)) rmSync(resolve(directory, name)); + } +} + +export function saveCurrentReport(directory, name, source = currentReport(process.cwd())) { + if (!/^(?:full|\d+)$/.test(name)) throw new Error("Invalid Rust report name"); + // A build failure or an empty selection may produce no report. Keep the + // Cargo exit status and any earlier reports; never reuse a previous result. + if (!existsSync(source)) return; + mkdirSync(directory, { recursive: true }); + const destination = resolve(directory, `nextest-${name}.xml`); + copyFileSync(source, destination); + rmSync(source); + return destination; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const directory = process.env.CELOX_CI_REPORT_DIR; + if (!directory) throw new Error("CELOX_CI_REPORT_DIR is required"); + if (process.argv[2] === "reset") resetReports(directory); + else if (process.argv[2] === "collect") saveCurrentReport(directory, "full"); + else throw new Error("Expected reset or collect"); +} diff --git a/scripts/ci-rust-reports.test.mjs b/scripts/ci-rust-reports.test.mjs new file mode 100644 index 00000000000..e0ef8709eef --- /dev/null +++ b/scripts/ci-rust-reports.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import test from "node:test"; +import { clearCurrentReport, resetReports, saveCurrentReport } from "./ci-rust-reports.mjs"; + +function fixture(t) { + const root = mkdtempSync(join(tmpdir(), "celox-ci-reports-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + return { source: join(root, "junit.xml"), directory: join(root, "reports") }; +} + +test("each scoped run keeps its own report, including failures", (t) => { + const { source, directory } = fixture(t); + const passed = ''; + const failed = ''; + for (const [name, text] of [["0", passed], ["1", failed]]) { + writeFileSync(source, text); + const saved = saveCurrentReport(directory, name, source); + assert.equal(readFileSync(saved, "utf8"), text); + assert.ok(!existsSync(source)); + } + assert.deepEqual(readdirSync(directory).sort(), ["nextest-0.xml", "nextest-1.xml"]); + assert.equal(readFileSync(join(directory, "nextest-0.xml"), "utf8"), passed); + // A subsequent compilation failure must not relabel an earlier report. + clearCurrentReport(source); + assert.equal(saveCurrentReport(directory, "2", source), undefined); + assert.equal(readdirSync(directory).length, 2); +}); + +test("initialization removes only this job's stale reports and creates no target directory", (t) => { + const { source, directory } = fixture(t); + resetReports(directory, source); + assert.ok(!existsSync(directory)); + mkdirSync(directory); + for (const name of ["nextest-full.xml", "nextest-0.xml", "unrelated.xml"]) + writeFileSync(join(directory, name), "old"); + writeFileSync(source, "old"); + resetReports(directory, source); + assert.deepEqual(readdirSync(directory), ["unrelated.xml"]); + assert.ok(!existsSync(source)); +}); + +test("full runs use a stable report name and reject invalid paths", (t) => { + const { source, directory } = fixture(t); + writeFileSync(source, ""); + assert.throws(() => saveCurrentReport(directory, "../escape", source), /Invalid Rust report name/); + assert.ok(existsSync(source)); + assert.equal(saveCurrentReport(directory, "full", source), join(directory, "nextest-full.xml")); +}); diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 45069ab5bf4..ed9ff3e9e7c 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -248,11 +248,11 @@ test("queue CI retains the whole workspace and ordinary PRs use scoped tests", ( // Anything but an explicit scope, including a failed detection, runs all. assert.match( rust, - /name: Run workspace tests with CI features\n if: needs\.changes\.outputs\.rust_full != 'false'\n/, + /name: Run workspace tests with CI features\n id: workspace-tests\n if: needs\.changes\.outputs\.rust_full != 'false'\n/, ); assert.match( rust, - /name: Run the tests this pull request can affect\n if: needs\.changes\.outputs\.rust_full == 'false' && /, + /name: Run the tests this pull request can affect\n id: scoped-tests\n if: needs\.changes\.outputs\.rust_full == 'false' && /, ); assert.match( job("changes"), @@ -381,6 +381,12 @@ test("cache warming shares the Rust Tests key and builds without running tests", /pull_request:|cargo nextest run|cargo test|shared-key:/, ); assert.match(warm, /steps.cache.outputs.cache-hit != 'true'/); + for (const text of [warm, job("rust-tests")]) { + assert.match(text, /key: vtest-v1/); + assert.match(text, /run: node scripts\/run-vtest.mjs --prepare-ci/); + } + assert.match(warm, /name: Build the optimized vtest executor to populate dependencies\n if: steps.cache.outputs.cache-hit != 'true'/); + assert.match(warm, /"scripts\/run-vtest.mjs"/); assert.match( warm, /cargo nextest list --locked --workspace --message-format json/, @@ -408,7 +414,7 @@ function cargoArguments(jobName, stepName, env) { features: (env.FEATURES ?? "").split(",").filter(Boolean), }]); const result = spawnSync("bash", ["-e", "-c", script], { - env: { ...process.env, ...env, BUILDS: builds, PATH: `${directory}:${process.env.PATH}` }, encoding: "utf8", + env: { ...process.env, CELOX_VTEST_RUNNER: "/ci/vtest-exec", ...env, BUILDS: builds, PATH: `${directory}:${process.env.PATH}` }, encoding: "utf8", }); assert.ifError(result.error); assert.equal(result.status, 0, result.stderr); @@ -425,7 +431,7 @@ test("scoped Cargo commands build only the selected integration targets", () => }; assert.deepEqual(cargoArguments("rust-tests", "Run the tests this pull request can affect", env), [ "nextest", "run", "--locked", "--profile", "ci", "--no-tests=pass", - "-p", "celox", "--features", "celox/systemverilog", + "-p", "celox", "--features", "celox/systemverilog,celox-test-suite/runtime-cases", "--test", "flip_flop", "--test", "systemverilog", "-E", env.FILTER, ]); assert.deepEqual(cargoArguments("lint", "Lint the crates this pull request can affect", env), [ @@ -440,6 +446,43 @@ test("scoped Cargo commands build only the selected integration targets", () => }), ["doc", "--locked", "--no-deps", "-p", "celox-runtime", "-p", "celox"]); }); +test("CI prepares one executor for full runs and scopes containing Celox", () => { + const rust = job("rust-tests"); + const step = rust.split(" - name: Build the optimized vtest executor\n")[1] + .split("\n #")[0]; + assert.match(step, /if: needs.changes.outputs.rust_full != 'false' \|\| contains\(format\(' \{0\} ', needs.changes.outputs.rust_packages\), ' celox '\)/); + assert.match(step, /run: node scripts\/run-vtest.mjs --prepare-ci/); + assert.ok(rust.indexOf("Build the optimized vtest executor") < rust.indexOf("Run workspace tests")); + assert.match(rust, /cargo nextest run[^\n]*\n[^\n]*celox-test-suite\/runtime-cases/); + assert.deepEqual(cargoArguments("rust-tests", "Run the tests this pull request can affect", { + PACKAGES: "celox-heap", FEATURES: "", TARGETS: "", FILTER: "package(celox-heap)", + CELOX_VTEST_RUNNER: "", + }), ["nextest", "run", "--locked", "--profile", "ci", "--no-tests=pass", + "-p", "celox-heap", "-E", "package(celox-heap)"]); +}); + +test("CI reports each Rust run to Mergify without weakening test failures", () => { + const rust = job("rust-tests"); + assert.match(rust, /CELOX_CI_REPORT_DIR: work\/ci-reports\/rust/); + assert.match(rust, /HAS_MERGIFY_TOKEN: \$\{\{ secrets.MERGIFY_TOKEN != '' \}\}/); + assert.match(rust, /run: node scripts\/ci-rust-reports.mjs reset/); + assert.match(rust, /name: Collect Rust test reports\n if: success\(\) \|\| failure\(\)/); + assert.match(rust, /run: node scripts\/ci-rust-reports.mjs collect/); + assert.match(rust, /name: Run workspace tests with CI features\n id: workspace-tests/); + assert.match(rust, /name: Run the tests this pull request can affect\n id: scoped-tests/); + assert.doesNotMatch(rust, /continue-on-error/); + const upload = rust.split(" - name: Upload Rust test results to Mergify\n")[1] + .split("\n #")[0]; + assert.match(upload, /if: \(success\(\) \|\| failure\(\)\) && env.HAS_MERGIFY_TOKEN == 'true' && hashFiles\('work\/ci-reports\/rust\/\*.xml'\) != ''/); + assert.match(upload, /uses: mergifyio\/gha-mergify-ci@[0-9a-f]{40} # v27/); + assert.match(upload, /report_path: work\/ci-reports\/rust\/\*.xml/); + assert.match(upload, /job_name: rust-tests/); + assert.match(upload, /test_step_outcome: .*steps.workspace-tests.outcome.*steps.scoped-tests.outcome/); + assert.match(rust, /name: rust-test-results\n path: work\/ci-reports\/rust\/\*.xml\n retention-days: 14/); + const nextest = readFileSync(new URL("../.config/nextest.toml", import.meta.url), "utf8"); + assert.match(nextest, /\[profile.ci.junit\]\npath = "junit.xml"/); +}); + test("scoped checks preserve full-run fallbacks and use their own package scopes", () => { const lint = job("lint"); assert.match(lint, /name: cargo clippy\n if: .*outputs\.rust_full != 'false'/); diff --git a/scripts/run-ci-rust-scope.mjs b/scripts/run-ci-rust-scope.mjs index 1904120f991..80850239528 100644 --- a/scripts/run-ci-rust-scope.mjs +++ b/scripts/run-ci-rust-scope.mjs @@ -1,5 +1,7 @@ import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; +import { runtimeCasesFeature } from "./run-vtest.mjs"; +import { clearCurrentReport, saveCurrentReport } from "./ci-rust-reports.mjs"; // Keep target flags local to their packages. Cargo applies --test to every -p. export function cargoCommands(mode, builds, filter) { @@ -17,7 +19,9 @@ export function cargoCommands(mode, builds, filter) { ? ["nextest", "run", "--locked", "--profile", "ci", "--no-tests=pass"] : ["clippy", "--locked"]; for (const name of packages) args.push("-p", name); - if (features.length) args.push("--features", features.join(",")); + const enabled = mode === "test" && packages.includes("celox") + ? [...new Set([...features, runtimeCasesFeature])] : features; + if (enabled.length) args.push("--features", enabled.join(",")); for (const target of targets) args.push("--test", target); if (mode === "lint") { if (!targets.length) args.push("--all-targets"); @@ -28,11 +32,19 @@ export function cargoCommands(mode, builds, filter) { } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const reportDirectory = process.argv[2] === "test" && process.env.CELOX_CI_REPORT_DIR; + let reportIndex = 0; for (const args of cargoCommands( process.argv[2], JSON.parse(process.env.BUILDS), process.env.FILTER, )) { + if (process.argv[2] === "test" + && args.some((arg, index) => arg === "celox" && args[index - 1] === "-p") + && !process.env.CELOX_VTEST_RUNNER) + throw new Error("Celox CI tests require the prepared vtest executor"); console.log("cargo", ...args); + if (reportDirectory) clearCurrentReport(); const result = spawnSync("cargo", args, { stdio: "inherit" }); + if (reportDirectory) saveCurrentReport(reportDirectory, String(reportIndex++)); if (result.error) throw result.error; if (result.status !== 0) process.exit(result.status ?? 1); } diff --git a/scripts/run-ci-rust-scope.test.mjs b/scripts/run-ci-rust-scope.test.mjs index 7d83ce37198..0058198d5cf 100644 --- a/scripts/run-ci-rust-scope.test.mjs +++ b/scripts/run-ci-rust-scope.test.mjs @@ -35,6 +35,26 @@ test("empty or invalid plans cannot silently pass CI", () => { assert.throws(() => cargoCommands("test", builds, "")); }); +test("runtime loading is enabled only for Celox test builds, without changing scope", () => { + const original = structuredClone(builds); + const tests = cargoCommands("test", builds, filter); + const lint = cargoCommands("lint", builds, filter); + assert.equal(tests[0][tests[0].indexOf("--features") + 1], "celox-test-suite/icarus"); + assert.equal(tests[1][tests[1].indexOf("--features") + 1], + "celox/systemverilog,celox-test-suite/runtime-cases"); + assert.equal(lint[1][lint[1].indexOf("--features") + 1], "celox/systemverilog"); + assert.deepEqual(builds, original); +}); + +test("Celox CI tests reject missing executor setup before launching Cargo", () => { + const result = spawnSync(process.execPath, ["scripts/run-ci-rust-scope.mjs", "test"], { + env: { ...process.env, BUILDS: JSON.stringify([builds[1]]), FILTER: filter, + CELOX_VTEST_RUNNER: "" }, encoding: "utf8", + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /require the prepared vtest executor/); +}); + test("the runner stops and propagates a failed scoped Cargo invocation", () => { const directory = mkdtempSync(join(tmpdir(), "celox-cargo-failure-")); try { diff --git a/scripts/run-vtest.mjs b/scripts/run-vtest.mjs new file mode 100644 index 00000000000..c16a4ae606c --- /dev/null +++ b/scripts/run-vtest.mjs @@ -0,0 +1,82 @@ +import { spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { resolve } from "node:path"; +import { appendFileSync } from "node:fs"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +export const runtimeCasesFeature = "celox-test-suite/runtime-cases"; +const features = `celox/systemverilog,${runtimeCasesFeature}`; + +export function executorPath(output) { + const paths = output.split("\n").filter(Boolean).map((line) => JSON.parse(line)) + .filter((message) => message.reason === "compiler-artifact" + && message.target.name === "vtest-exec" + && message.target.kind.includes("example") && message.executable) + .map((message) => message.executable); + if (paths.length !== 1) throw new Error("Cargo did not report one vtest executor"); + return paths[0]; +} + +export function buildExecutor(spawn = spawnSync, env = process.env) { + const build = spawn("cargo", [ + "build", "--locked", "-p", "celox", "--example", "vtest-exec", + "--profile", "vtest", "--features", features, "--message-format=json-render-diagnostics", + ], { cwd: root, env, encoding: "utf8", stdio: ["inherit", "pipe", "inherit"], maxBuffer: 64 * 1024 * 1024 }); + if (build.error) throw build.error; + if (build.status !== 0) return { status: build.status ?? 1 }; + const executable = executorPath(build.stdout); + return { + status: 0, + environment: { CELOX_VTEST_RUNNER: executable, CELOX_VTEST_ROOT: resolve(root, "crates/celox-test-suite/src") }, + }; +} + +// Prepare once per CI job, even when scoped tests need several Cargo invocations. +export function prepareCi(spawn = spawnSync, env = process.env, append = appendFileSync) { + if (!env.GITHUB_ENV) throw new Error("--prepare-ci requires GITHUB_ENV"); + const result = buildExecutor(spawn, env); + if (result.status !== 0) return result.status; + const lines = Object.entries(result.environment).map(([name, value]) => { + if (/[\r\n]/.test(value)) throw new Error("Invalid executor environment path"); + return `${name}=${value}\n`; + }); + append(env.GITHUB_ENV, lines.join("")); + return 0; +} + +// Keep the registrations in libtest: nextest still owns filters, ignores, +// process isolation, timeouts and parallel scheduling, including Rust API tests. +export function run(args, spawn = spawnSync, env = process.env) { + const result = buildExecutor(spawn, env); + if (result.status !== 0) return result.status; + const tests = spawn("cargo", [ + "nextest", "run", "--locked", "-p", "celox", "--features", features, ...args, + ], { + cwd: root, + env: { ...env, ...result.environment }, + stdio: "inherit", + }); + if (tests.error) throw tests.error; + return tests.status ?? 1; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + if (process.argv.includes("--help")) { + console.log(`Usage: node scripts/run-vtest.mjs [cargo nextest run options] + +Build the shared vtest executor with opt-level=1, then run Celox tests through +nextest. Case bodies are read from disk; Rust API tests run in their test binary. +Examples: + node scripts/run-vtest.mjs --test counter + node scripts/run-vtest.mjs --test operators -E 'test(::native$)' + node scripts/run-vtest.mjs --test systemverilog -E 'test(operators::)' + +The runner and registrations both enable systemverilog and runtime-cases. +Use ordinary cargo nextest run for the existing in-process test path.`); + } else if (process.argv[2] === "--prepare-ci") { + if (process.argv.length !== 3) throw new Error("--prepare-ci accepts no test arguments"); + process.exitCode = prepareCi(); + } else { + process.exitCode = run(process.argv.slice(2)); + } +} diff --git a/scripts/run-vtest.test.mjs b/scripts/run-vtest.test.mjs new file mode 100644 index 00000000000..1bec1f1a200 --- /dev/null +++ b/scripts/run-vtest.test.mjs @@ -0,0 +1,70 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { executorPath, prepareCi, run } from "./run-vtest.mjs"; + +const artifact = JSON.stringify({ + reason: "compiler-artifact", target: { name: "vtest-exec", kind: ["example"] }, + executable: "/managed target/vtest/examples/vtest-exec", +}); + +test("builds the optimized executor and preserves nextest selection and environment", () => { + const calls = []; + const status = run(["--test", "counter", "-E", "test(::native$)", "--run-ignored", "all"], + (...call) => { + calls.push(call); + return calls.length === 1 ? { status: 0, stdout: `${artifact}\n` } : { status: 7 }; + }, { PATH: "/tools", CELOX_VTEST_ROOT: "/stale", CELOX_VTEST_RUNNER: "/stale" }); + assert.equal(status, 7); + assert.equal(calls.length, 2); + const [[, build, options], [, tests, testOptions]] = calls; + assert.equal(build[build.indexOf("--profile") + 1], "vtest"); + assert.equal(build[build.indexOf("--features") + 1], tests[tests.indexOf("--features") + 1]); + assert.deepEqual(tests.slice(-6), ["--test", "counter", "-E", "test(::native$)", "--run-ignored", "all"]); + assert.equal(testOptions.cwd, options.cwd); + assert.equal(testOptions.env.PATH, "/tools"); + assert.equal(testOptions.env.CELOX_VTEST_RUNNER, "/managed target/vtest/examples/vtest-exec"); + assert.ok(testOptions.env.CELOX_VTEST_ROOT.endsWith("/crates/celox-test-suite/src")); +}); + +test("failed or interrupted builds never launch tests", () => { + for (const status of [1, null]) { + let calls = 0; + assert.equal(run([], () => { calls++; return { status }; }), 1); + assert.equal(calls, 1); + } + assert.throws(() => run([], () => ({ error: new Error("no cargo") })), /no cargo/); +}); + +test("missing or ambiguous executors fail closed", () => { + assert.throws(() => executorPath('{"reason":"build-finished"}\n'), /one vtest executor/); + assert.throws(() => executorPath(`${artifact}\n${artifact}`), /one vtest executor/); + assert.equal(executorPath(`{"reason":"build-finished"}\n${artifact}\n`), "/managed target/vtest/examples/vtest-exec"); +}); + +test("CI preparation only builds and exports the executor for later test steps", () => { + const calls = []; + const writes = []; + assert.equal(prepareCi((...args) => { + calls.push(args); + return { status: 0, stdout: artifact }; + }, { GITHUB_ENV: "/job/environment" }, (...args) => writes.push(args)), 0); + assert.equal(calls.length, 1); + assert.equal(calls[0][1][0], "build"); + assert.ok(calls[0][1].includes("vtest")); + assert.equal(writes.length, 1); + assert.equal(writes[0][0], "/job/environment"); + assert.match(writes[0][1], /^CELOX_VTEST_RUNNER=\/managed target\/vtest\/examples\/vtest-exec\n/); + assert.match(writes[0][1], /\nCELOX_VTEST_ROOT=.*\/crates\/celox-test-suite\/src\n$/); +}); + +test("failed CI preparation cannot export a stale executor or silently skip setup", () => { + const unexpected = () => assert.fail("unexpected build or environment export"); + assert.throws(() => prepareCi(unexpected, {}, unexpected), /requires GITHUB_ENV/); + assert.equal(prepareCi(() => ({ status: 17 }), { GITHUB_ENV: "/job/env" }, unexpected), 17); + assert.throws(() => prepareCi(() => ({ status: 0, stdout: "" }), + { GITHUB_ENV: "/job/env" }, unexpected), /one vtest executor/); + const message = JSON.parse(artifact); + message.executable += "\nUNRELATED=value"; + assert.throws(() => prepareCi(() => ({ status: 0, stdout: JSON.stringify(message) }), + { GITHUB_ENV: "/job/env" }, unexpected), /Invalid executor environment/); +});