From 78c9db2626eecbab4736dbd7bfa1d9a68fb035f5 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 16:18:39 +0900 Subject: [PATCH 1/9] test(vtest): run shared cases through an optimized executor Add an opt-in shared executor with runtime corpus loading while preserving existing libtest registrations and nextest scheduling. Avoid Rust rebuilds for vtest body edits and retain the embedded in-process path. Change-Id: I782a196b4d4b952a7c5122984f2f9785cc61d153 --- CONTRIBUTING.md | 35 ++++++ Cargo.lock | 1 + Cargo.toml | 6 ++ crates/celox-test-suite/Cargo.toml | 5 + crates/celox-test-suite/build.rs | 5 +- crates/celox-test-suite/src/lib.rs | 2 + crates/celox-test-suite/src/runtime_cases.rs | 101 ++++++++++++++++++ crates/celox-test-suite/src/sv/mod.rs | 11 +- crates/celox-test-suite/src/veryl/mod.rs | 9 +- crates/celox/Cargo.toml | 4 + crates/celox/examples/vtest-exec.rs | 42 ++++++++ .../tests/frontends/systemverilog/suite.rs | 5 +- crates/celox/tests/systemverilog.rs | 3 + crates/celox/tests/test_utils/mod.rs | 1 + crates/celox/tests/test_utils/suite.rs | 3 + crates/celox/tests/test_utils/vtest_exec.rs | 22 ++++ scripts/run-vtest.mjs | 55 ++++++++++ scripts/run-vtest.test.mjs | 42 ++++++++ 18 files changed, 347 insertions(+), 5 deletions(-) create mode 100644 crates/celox-test-suite/src/runtime_cases.rs create mode 100644 crates/celox/examples/vtest-exec.rs create mode 100644 crates/celox/tests/test_utils/vtest_exec.rs create mode 100644 scripts/run-vtest.mjs create mode 100644 scripts/run-vtest.test.mjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2c6b6912b76..2a4e01a30a6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,41 @@ 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, and CI continues to use that path. + +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-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/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/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 52af4da8702..e0331b436d1 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/scripts/run-vtest.mjs b/scripts/run-vtest.mjs new file mode 100644 index 00000000000..dd656fa444b --- /dev/null +++ b/scripts/run-vtest.mjs @@ -0,0 +1,55 @@ +import { spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { resolve } from "node:path"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const features = "systemverilog,celox-test-suite/runtime-cases"; + +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]; +} + +// 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 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 build.status ?? 1; + const executable = executorPath(build.stdout); + const tests = spawn("cargo", [ + "nextest", "run", "--locked", "-p", "celox", "--features", features, ...args, + ], { + cwd: root, + env: { ...env, CELOX_VTEST_RUNNER: executable, CELOX_VTEST_ROOT: resolve(root, "crates/celox-test-suite/src") }, + 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 { + 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..96c0e511018 --- /dev/null +++ b/scripts/run-vtest.test.mjs @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { executorPath, 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"); +}); From 3530b564efa13514556d7e34a19a59f8f1b4da63 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 16:36:48 +0900 Subject: [PATCH 2/9] ci(vtest): use the optimized executor for Rust test jobs Prepare the shared executor once for full and scoped Celox runs, fail when setup is missing, and warm both Cargo profiles under a matching cache key. Change-Id: I3bc134b06e3bf4fce8f1ed2e8a36ce7e0a6f629b --- .github/workflows/ci.yml | 7 +++++- .github/workflows/rust-cache.yml | 8 +++++- CONTRIBUTING.md | 5 +++- scripts/ci-workflow.test.mjs | 25 +++++++++++++++++-- scripts/run-ci-rust-scope.mjs | 9 ++++++- scripts/run-ci-rust-scope.test.mjs | 20 +++++++++++++++ scripts/run-vtest.mjs | 39 +++++++++++++++++++++++++----- scripts/run-vtest.test.mjs | 30 ++++++++++++++++++++++- 8 files changed, 130 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b1fde462a1..7240c48d8ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -220,6 +220,7 @@ jobs: - uses: Swatinem/rust-cache@v2 with: + key: vtest-v1 save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - uses: actions/setup-python@v7 @@ -236,6 +237,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` @@ -247,7 +252,7 @@ jobs: 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 if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_packages != '' 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/CONTRIBUTING.md b/CONTRIBUTING.md index 2a4e01a30a6..4266b5a98ee 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,7 +61,10 @@ 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, and CI continues to use that path. +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. For debugging a single case after building, the executor also accepts ` ` directly, for example: diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 45069ab5bf4..4371d744539 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -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,21 @@ 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("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..b604ee32a0f 100644 --- a/scripts/run-ci-rust-scope.mjs +++ b/scripts/run-ci-rust-scope.mjs @@ -1,5 +1,6 @@ import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; +import { runtimeCasesFeature } from "./run-vtest.mjs"; // Keep target flags local to their packages. Cargo applies --test to every -p. export function cargoCommands(mode, builds, filter) { @@ -17,7 +18,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"); @@ -31,6 +34,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) 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); const result = spawnSync("cargo", args, { stdio: "inherit" }); if (result.error) throw result.error; 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 index dd656fa444b..c16a4ae606c 100644 --- a/scripts/run-vtest.mjs +++ b/scripts/run-vtest.mjs @@ -1,9 +1,11 @@ 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)); -const features = "systemverilog,celox-test-suite/runtime-cases"; +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)) @@ -15,21 +17,43 @@ export function executorPath(output) { return paths[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) { +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 build.status ?? 1; + 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, CELOX_VTEST_RUNNER: executable, CELOX_VTEST_ROOT: resolve(root, "crates/celox-test-suite/src") }, + env: { ...env, ...result.environment }, stdio: "inherit", }); if (tests.error) throw tests.error; @@ -49,6 +73,9 @@ Examples: 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 index 96c0e511018..1bec1f1a200 100644 --- a/scripts/run-vtest.test.mjs +++ b/scripts/run-vtest.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { executorPath, run } from "./run-vtest.mjs"; +import { executorPath, prepareCi, run } from "./run-vtest.mjs"; const artifact = JSON.stringify({ reason: "compiler-artifact", target: { name: "vtest-exec", kind: ["example"] }, @@ -40,3 +40,31 @@ test("missing or ambiguous executors fail closed", () => { 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/); +}); From b9d58703fdb8f0ed27e3a14ef621b0b3b029baf3 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 09:52:35 +0900 Subject: [PATCH 3/9] feat(sv): support class enum randomization Allow rand enum properties and randomize(member) selection of enum properties in unconstrained classes. Preserve declared enum domains through type aliases and select only their declared values with rejection sampling, including sparse, negative, implicit, singleton, and 64-bit values. Normalize unbased fill initializers to the enum base width and signedness before evaluation. Keep rand_mode, inherited properties, dynamic dispatch, and per-object seeding behavior intact. Keep unsupported or unresolved enum domains explicit rather than randomizing the underlying integer. Reject duplicate values, overflowing implicit values, and X/Z domains. Scope randomization of enums, arrays, and class properties wider than 64 bits remain outside this change. Add four shared regression cases and an analyzer rejection test; update the English and Japanese references. Retain narrow external-tool failure evidence: Verilator 5.052 passes the direct enum, inheritance, and unbased fill cases but randomizes an enum typedef alias as raw integer bits. Icarus 13.0 cannot elaborate class randomization methods in these four cases. Shared assertions are unchanged. Validation: - Analyzer unit tests: 796 passed, 3 existing ignores. - Differential SystemVerilog class suite across backends: 179 passed. - Retained external evidence checks: 3 passed. - NAPI build and JavaScript integration: 432 passed. - Analyzer Clippy, formatting, and diff checks pass. - Unbased fill regression: all five backend variants fail before the fix and pass afterward; Verilator also passes the unchanged assertions. - All four new shared cases exercised with Verilator and Icarus; the limitations above are documented with original diagnostics in verification/repros. Change-Id: I076dfe023e39722af4f294144ffae2c202085d52 --- crates/celox-sv-analyzer/src/ast.rs | 4 + crates/celox-sv-analyzer/src/ast/classes.rs | 7 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 1 + .../src/ast/expression_binding/direct.rs | 9 +- .../src/ast/expression_binding/objects.rs | 7 +- .../celox-sv-analyzer/src/ast/parameters.rs | 6 +- .../celox-sv-analyzer/src/ast/procedural.rs | 1 + .../src/ast/procedural/randomization.rs | 81 ++++++++-- .../src/ast/type_binding/binding.rs | 73 ++++++++- crates/celox-sv-analyzer/src/ast/types.rs | 1 + crates/celox-sv-analyzer/src/tests.rs | 22 ++- crates/celox-test-suite/LIMITATIONS.md | 13 ++ .../celox-test-suite/src/sv/cases/class.vtest | 138 ++++++++++++++++++ .../repros/sv_enum_randomization_icarus.json | 55 +++++++ .../sv_enum_randomization_verilator.json | 22 +++ .../verification/sv/icarus/class.json | 92 ++++++++++++ .../verification/sv/limitations.json | 37 +++++ .../verification/sv/verilator/class.json | 23 +++ .../tests/frontends/systemverilog/class.rs | 10 ++ docs/guide/systemverilog-reference.md | 9 +- docs/ja/guide/systemverilog-reference.md | 6 +- 21 files changed, 588 insertions(+), 29 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json create mode 100644 crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 7b61af634ae..ca7fdc2114e 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1969,6 +1969,8 @@ pub enum PortDirection { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Type { is_enum: bool, + /// Resolved legal values for a scalar enum; None if its domain is unsupported. + enum_values: Option>, kind: TypeKind, is_signed: bool, packed_ranges: Vec, @@ -1986,6 +1988,7 @@ impl Type { fn implicit() -> Self { Self { is_enum: false, + enum_values: None, kind: TypeKind::Implicit, is_signed: false, packed_ranges: Vec::new(), @@ -2000,6 +2003,7 @@ impl Type { Self { kind, is_enum: false, + enum_values: None, is_signed: false, packed_ranges: Vec::new(), unpacked_ranges: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index a44fee5735b..4b92fe3940d 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -122,9 +122,12 @@ impl Class { if property.randc { return Err(unsupported("class randomize with randc properties")); } - if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) { + if property.rand + && (property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none())) + { return Err(unsupported( - "class randomize requires integral non-enum rand properties", + "class randomize requires integral rand properties with a supported enum domain", )); } } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index bcc9ca9afec..7fd131f1d42 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -350,6 +350,7 @@ fn extend_variable_dimensions_from_const_env( let packed_ranges = ranges.split_off(unpacked); let ty = Type { is_enum: false, + enum_values: None, kind: TypeKind::Logic, is_signed: variable_type_is_signed(const_env, name), packed_ranges, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 9ebd6e1001e..17b50ff3c53 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -233,7 +233,7 @@ enum Finish { /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), /// A read of property `property` of the object handle child. - ObjectLoad(crate::ast::classes::Property), + ObjectLoad(Box), /// A call of method subroutine `name` with `formals` formals; the first /// child is the object handle when `receiver` is one. MethodCall { @@ -756,9 +756,10 @@ pub(in crate::ast) fn bind_value( let (property, receiver) = objects::property(tree, id, native, dimensions)? .expect("checked by the guard"); match receiver { - Some(receiver) => { - (Finish::ObjectLoad(property), vec![(receiver, None)]) - } + Some(receiver) => ( + Finish::ObjectLoad(Box::new(property)), + vec![(receiver, None)], + ), None => { values.push(objects::load(&property, objects::this())); continue; diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index cfcd38f83ed..26d4e676a93 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -555,9 +555,12 @@ pub(super) fn random_selection( if property.constant { return Err(unsupported("randomize argument is a const property")); } - if property.field.handle.is_some() || property.r#type.is_enum || property.randc { + if property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) + || property.randc + { return Err(unsupported( - "randomize arguments require integral non-enum, non-randc properties", + "randomize arguments require integral, non-randc properties with a supported enum domain", )); } bits[index + 1] = '1'; diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index df53b14d48e..a2f4efd2aab 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -935,7 +935,11 @@ pub(super) fn coerce_const_parameter_value(value: i128, width: usize, signed: bo } } -fn enum_initializer_fits_base_type(value: i128, value_type: ExprType, base_type: ExprType) -> bool { +pub(super) fn enum_initializer_fits_base_type( + value: i128, + value_type: ExprType, + base_type: ExprType, +) -> bool { // A same-width initializer may change its numeric interpretation when // the enum base has different signedness, but it does not lose any bits. if value_type.width <= base_type.width || base_type.width >= 128 { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index f3eee42895d..47aeab7cdd8 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -115,6 +115,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - pub(super) fn int_type() -> Type { Type { is_enum: false, + enum_values: None, kind: TypeKind::Bit, is_signed: true, packed_ranges: vec![PackedRange::new( diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 2b8d305459e..597458d6c73 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -133,7 +133,7 @@ pub(super) fn lower( for property in &class.properties { if property.constant || property.field.handle.is_some() - || property.r#type.is_enum + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) { continue; } @@ -150,16 +150,7 @@ pub(super) fn lower( vec![Expr::Ident(this.clone())], )), }, - then_body: vec![Stmt::Eval(classes::object_call( - ObjectOp::Store(property.field), - vec![ - Expr::Ident(this.clone()), - classes::object_call( - ObjectOp::Random, - vec![Expr::Ident(this.clone())], - ), - ], - ))], + then_body: random_property(&mut builder, property, &this), else_body: Vec::new(), }); } @@ -264,3 +255,71 @@ pub(super) fn lower( } Ok(result) } + +/// Select a declared enum value with rejection sampling, so non-power-of-two +/// domains are uniform (IEEE 1800-2023 18.3, 18.4.1). Keep the draws inside the +/// mode guard: a disabled property must not consume its object's random stream. +fn random_property( + builder: &mut BodyBuilder<'_, '_, '_>, + property: &classes::Property, + this: &str, +) -> Vec { + let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]); + let mut body = Vec::new(); + let value = if let Some(values) = &property.r#type.enum_values { + let count = values.len() as u64; + let threshold = count.wrapping_neg() % count; + let draw = builder.declare("$enum_draw", classes::unsigned_type(64)); + body.push(Stmt::Loop { + kind: LoopKind::DoWhile, + init: Vec::new(), + condition: Some(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("64'd{threshold}"))), + }), + step: Vec::new(), + body: vec![Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: random(), + nonblocking: false, + }], + }); + body.push(Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("64'd{count}"))), + }, + nonblocking: false, + }); + let literal = |value| { + Expr::Literal(format_typed_parameter_literal( + value, + property.field.width as usize, + property.field.signed, + )) + }; + let mut value = literal(*values.last().unwrap()); + for (index, &member) in values.iter().enumerate().rev().skip(1) { + value = Expr::Mux { + condition: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal(format!("64'd{index}"))), + }), + then_expr: Box::new(literal(member)), + else_expr: Box::new(value), + }; + } + value + } else { + random() + }; + body.push(Stmt::Eval(classes::object_call( + ObjectOp::Store(property.field), + vec![Expr::Ident(this.into()), value], + ))); + body +} diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 30e61323785..6ff5bd6c541 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -18,7 +18,7 @@ pub(in crate::ast) fn bind_in( ) -> Converted> { enum Job { Enter(TypeId), - Enum(Vec), + Enum(TypeId, Vec), Aggregate { owner: Arc, union: bool, @@ -79,11 +79,12 @@ pub(in crate::ast) fn bind_in( } DataTypeKind::Enum { base, .. } => { if let Some(base) = base { - jobs.push(Job::Enum(ranges)); + jobs.push(Job::Enum(id, ranges)); jobs.push(Job::Enter(*base)); } else { let mut ty = builtin_type("int", None).unwrap(); ty.is_enum = true; + ty.enum_values = enum_values(id, native, tree, context, &ty); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); } @@ -159,7 +160,7 @@ pub(in crate::ast) fn bind_in( } } } - Job::Enum(ranges) => { + Job::Enum(id, ranges) => { let Some(mut ty) = values.pop() else { return Err(unsupported("enum base type")); }; @@ -167,6 +168,7 @@ pub(in crate::ast) fn bind_in( outer.extend(ty.packed_ranges); ty.packed_ranges = outer; ty.is_enum = true; + ty.enum_values = enum_values(id, native, tree, context, &ty); values.push(ty); } Job::Aggregate { @@ -282,3 +284,68 @@ pub(in crate::ast) fn expression_type( let value = expression_binding::bind(root, tree, &query)?; Ok(dimensions::bound_bits_type(&tree.state, &value, &query)) } + +/// Domain metadata is best-effort during signature discovery. Only a caller +/// requesting randomization requires a resolved domain; unused types must not +/// start reporting new errors merely because this metadata is collected. +fn enum_values( + id: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + ty: &Type, +) -> Option> { + let data = native.data_type(id); + if !data.packed_dimensions.is_empty() { + return None; + } + let DataTypeKind::Enum { items, .. } = &data.kind else { + return None; + }; + let shape = casts::expr_type_from_type(&tree.state, ty, &context.const_env)?; + if shape.width > 64 { + return None; + } + let mut env = context.const_env.clone(); + let mut next = 0i128; + let mut values = Vec::new(); + for item in items { + if !item.dimensions.is_empty() { + return None; + } + let value = if let Some(id) = item.value { + let expr = constant_binding::expression(id, native, tree, &env, &context.type_aliases) + .ok()??; + // Unbased fills take the enum base's width and signedness, just + // as they do when resolving the declared enum constants (5.7.1). + let expr = match expr { + ConstExpr::Literal(literal) => ConstExpr::Literal( + resize_unbased_fill_literal_for_cast(&literal, shape.width, shape.signed) + .unwrap_or(literal), + ), + expr => expr, + }; + let value = eval_ast_const_expr(&tree.state, &expr, &env)?; + let value_type = infer_const_expr_type(&expr, ¶meter_types_from_const_env(&env))?; + if !parameters::enum_initializer_fits_base_type(value, value_type, shape) { + return None; + } + value + } else { + if parameters::coerce_const_parameter_value(next, shape.width, shape.signed) != next { + return None; + } + next + }; + let value = parameters::coerce_const_parameter_value(value, shape.width, shape.signed); + if values.contains(&value) { + return None; + } + values.push(value); + let name = normalize_identifier(&item.name.spelling); + env.insert(name.clone(), value); + dimensions::insert_parameter_type_markers(&mut env, &name, shape); + next = value.checked_add(1)?; + } + (!values.is_empty()).then_some(values) +} diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index fa20c7e6cb5..22ed86204db 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -177,6 +177,7 @@ pub(super) fn enclose_aliased_packed_type( // array they form is unsigned, whatever its elements (IEEE 1800-2023 // 7.4.1); a type name takes no signing of its own. if !direct_ranges.is_empty() { + r#type.enum_values = None; r#type.signed_element_depth = if r#type.is_signed { Some(direct_ranges.len()) } else { diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 94015a571ce..81a99a92a65 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6610,7 +6610,11 @@ fn class_randomize_rejects_unsupported_semantics() { "c.f()", "object receiver", ), - ("rand string x;", "c.randomize()", "integral non-enum"), + ( + "rand string x;", + "c.randomize()", + "integral rand properties", + ), ( "rand int x;", "c.randomize() with { x == 1; }", @@ -6678,3 +6682,19 @@ fn randomization_signatures_do_not_force_unused_interface_class_layouts() { analyze_source(&source, Path::new("unused_interface_class.sv")).unwrap(); } } + +#[test] +fn class_randomize_rejects_unresolved_enum_domains() { + for members in ["A=3, B", "A=0, B=0", "A=2'bx, B=1"] { + let source = format!( + "module Top; + class C; rand enum bit [1:0] {{{members}}} value; endclass + C c; initial begin c = new; void'(c.randomize()); end + endmodule" + ); + assert!( + analyze_source(&source, Path::new("enum_domain.sv")).is_err(), + "{members}" + ); + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 6a96fd7d4de..8e44294ee77 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -696,6 +696,19 @@ Verilator 5.052 has two narrower exclusions, recorded in the 0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control, inline member selection and pre-hook control cases pass Verilator. +Enum class randomization (`sv_icarus_enum_randomization`) excludes the four +`class::randomization_enum_*` cases from Icarus 13.0 because it cannot elaborate +class randomization methods. [Original diagnostics](verification/repros/sv_enum_randomization_icarus.json) +retain the failures without changing the shared assertions. + +Verilator 5.052 passes the direct enum and inherited enum cases, but treats a +typedef alias of an enum as the underlying integer during randomization +(`sv_verilator_enum_alias_randomization`). The generated randomizer assigns raw +8-bit random values rather than selecting declared enum values, contrary to +IEEE 1800-2023 18.3. Only `class::randomization_enum_alias` is excluded; +[the mismatch evidence](verification/repros/sv_enum_randomization_verilator.json) +retains its unchanged domain assertion. + ## SystemVerilog packed unions The `unions` shared group covers hard and soft packed untagged unions. With diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 768617f2953..06c4057355b 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -929,3 +929,141 @@ module Top(output bit done, output int errors); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_domain + (source "enum_randomize.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=MID+89} sparse_t; + typedef enum bit [63:0] {LOW=64'h100000000, TOP=64'h8000000000000000} wide_t; + class Base; + rand sparse_t value; + sparse_t selected; + rand wide_t wide_value; + rand enum bit [2:0] {ONLY=5} single; + rand enum {FIRST=11, SECOND=35, THIRD} extra; + endclass + Base a, b; + Base base; + int seen; + int old_value; + initial begin + a = new; b = new; base = a; + a.srandom(123); b.srandom(123); + repeat (256) begin + if (!base.randomize() || !b.randomize()) errors++; + if (a.value != b.value || a.wide_value != b.wide_value || a.extra != b.extra) errors++; + case (a.value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + if (a.wide_value != LOW && a.wide_value != TOP) errors++; + if (a.single != 5) errors++; + if (a.extra != 11 && a.extra != 35 && a.extra != 36) errors++; + end + if (seen != 7) errors++; + a.value.rand_mode(0); + old_value = a.value; + if (!a.randomize() || a.value != old_value) errors++; + if (!a.randomize(selected)) errors++; + if (a.selected != NEG && a.selected != MID && a.selected != HIGH) errors++; + if (a.value != old_value || a.value.rand_mode() != 0) errors++; + if (!base.randomize(value)) errors++; + if (a.value != NEG && a.value != MID && a.value != HIGH) errors++; + if (a.value.rand_mode() != 0) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_inheritance + (source "enum_inheritance.sv" #" +module Top(output bit done, output int errors); + class Parent; + rand enum bit [7:0] {P=7, Q=93} x; + endclass + class Child extends Parent; + rand enum bit [7:0] {R=11, S=57, T=98} y; + endclass + Child child; + Parent parent; + int seen; + initial begin + child = new; parent = child; + repeat (128) begin + if (parent.randomize() != 1) errors++; + if (child.x != 7 && child.x != 93) errors++; + case (child.y) + 11: seen |= 1; + 57: seen |= 2; + 98: seen |= 4; + default: errors++; + endcase + end + if (seen != 7) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_alias + (source "enum_alias.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=91} original_t; + typedef original_t alias_t; + class Sample; + rand alias_t value; + endclass + Sample object; + int seen; + initial begin + object = new; + repeat (128) begin + if (object.randomize() != 1) errors++; + case (object.value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + end + if (seen != 7) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_fill_literals + (source "enum_fill.sv" #" +module Top(output bit done, output int errors); + typedef enum bit [63:0] {WIDE_ALL='1} wide_t; + typedef enum bit [3:0] {SMALL_ALL='1} small_t; + typedef enum bit signed [63:0] {SIGNED_ALL='1} signed_t; + typedef enum bit [63:0] {ZERO='0} zero_t; + class Sample; + rand wide_t wide_value; + rand small_t small_value; + rand signed_t signed_value; + rand zero_t zero_value; + endclass + Sample object; + initial begin + object = new; + repeat (8) begin + if (object.randomize() != 1) errors++; + if (object.wide_value != 64'hffffffffffffffff) errors++; + if (object.small_value != 4'hf) errors++; + if (object.signed_value != -64'sd1) errors++; + if (object.zero_value != 64'd0) errors++; + if (object.wide_value != WIDE_ALL || object.small_value != SMALL_ALL + || object.signed_value != SIGNED_ALL || object.zero_value != ZERO) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json b/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json new file mode 100644 index 00000000000..d0fa8229844 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json @@ -0,0 +1,55 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:13: Error: randomize is not a method of class Sample.\n/source_0.sv:13: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:13: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 24; see /build.log\n/source_0.sv:18: error: Can't find task srandom in class Base\n/source_0.sv:18: error: Enable of unknown task ``a.srandom''.\n/source_0.sv:18: error: Can't find task srandom in class Base\n/source_0.sv:18: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:20: Error: randomize is not a method of class Base.\n/source_0.sv:20: error: Object celox_suite_tb.dut.base has no method \"randomize(...)\".\n/source_0.sv:20: Error: randomize is not a method of class Base.\n/source_0.sv:20: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:20: error: Unable to elaborate condition expression.\n/source_0.sv:33: error: Can't find task rand_mode in class Base\n/source_0.sv:33: error: Enable of unknown task ``a.value.rand_mode''.\n/source_0.sv:35: Error: randomize is not a method of class Base.\n/source_0.sv:35: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:35: error: Unable to elaborate condition expression.\n/source_0.sv:36: Error: randomize is not a method of class Base.\n/source_0.sv:36: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:36: error: Unable to elaborate condition expression.\n/source_0.sv:38: sorry: Method name nesting is not supported yet.\n/source_0.sv:38: : method path: value.rand_mode\n/source_0.sv:38: error: Object celox_suite_tb.dut.a has no method \"value.rand_mode(...)\".\n/source_0.sv:38: error: Unable to elaborate condition expression.\n/source_0.sv:39: Error: randomize is not a method of class Base.\n/source_0.sv:39: error: Object celox_suite_tb.dut.base has no method \"randomize(...)\".\n/source_0.sv:39: error: Unable to elaborate condition expression.\n/source_0.sv:41: sorry: Method name nesting is not supported yet.\n/source_0.sv:41: : method path: value.rand_mode\n/source_0.sv:41: error: Object celox_suite_tb.dut.a has no method \"value.rand_mode(...)\".\n/source_0.sv:41: error: Unable to elaborate condition expression.\n24 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_domain", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:17: Error: randomize is not a method of class Sample.\n/source_0.sv:17: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:17: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_fill_literals", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:15: Error: randomize is not a method of class Parent.\n/source_0.sv:15: error: Object celox_suite_tb.dut.parent has no method \"randomize(...)\".\n/source_0.sv:15: error: Unable to elaborate condition expression.\n/source_0.sv:17: assert: dup_expr.cc:215: failed assertion 0\nAborted (core dumped)\n", + "expectation": "Simulation", + "name": "class::randomization_enum_inheritance", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json b/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json new file mode 100644 index 00000000000..c9062c4139b --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json @@ -0,0 +1,22 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "class::randomization_enum_alias at 1038:46: assert_eq errors: expected 0x0, got 0x7e", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052" +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 9e91a1b7c19..96bafddf611 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -309,6 +309,98 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_domain", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_fill_literals", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_inheritance", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "expectation": "Simulation", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index a026da63bf5..f4839f22972 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2210,5 +2210,42 @@ "timing::always_star_timed_task_calls_wait_on_folded_branch_reads" ] } + }, + { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomization_enum_alias", + "class::randomization_enum_domain", + "class::randomization_enum_fill_literals", + "class::randomization_enum_inheritance" + ] + } + }, + { + "id": "sv_verilator_enum_alias_randomization", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_enum_alias" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index a255bf9044d..67802610550 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -190,6 +190,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "known_issue": { + "id": "sv_verilator_enum_alias_randomization", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "expectation": "Simulation", diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 17b93891c46..b2c81061d78 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -378,3 +378,13 @@ sv_backends! { assert_eq!(sim.get(sim.signal("errors")), 0u8.into()); } } + +sv_backends! { + fn class_randomization_enum_inheritance(sim) { @case "class::randomization_enum_inheritance"; } + fn class_randomization_enum_alias(sim) { @case "class::randomization_enum_alias"; } + fn class_randomization_enum_domain(sim) { @case "class::randomization_enum_domain"; } +} + +sv_backends! { + fn class_randomization_enum_fill_literals(sim) { @case "class::randomization_enum_fill_literals"; } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 8daa10c3303..c765062dd74 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -110,8 +110,11 @@ constants, selects and concatenation arguments are unsupported and rejected. ### Class randomization `object.randomize()` randomizes enabled `rand` properties and returns signed -`int` value `1`. Supported properties are 2-state, non-enum integral values up -to 64 bits in classes without constraints. Inherited properties are included, +`int` value `1`. Supported properties are 2-state integral values, including scalar enums, up +to 64 bits in classes without constraints. Enum randomization selects uniformly +from the declared values, including sparse and negative values (18.3, 18.4.1). +Enums with unresolved or X/Z values and ranged enumerator declarations remain +unsupported for randomization. Inherited properties are included, and a call through a base handle uses the dynamic object's class and its `pre_randomize()` / `post_randomize()` hooks. A derived hook replaces the base hook; call `super.pre_randomize()` or `super.post_randomize()` explicitly to @@ -137,7 +140,7 @@ Each object has an independent random stream, seeded from its creating process. `object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve both RNG and mode state (18.13.3, 18.14.3). Random sequences are implementation-specific. `randc` randomization, constraints, `with`, static random properties, and random -enum/array/object/string properties remain unsupported. A constrained dynamic +array/object/string properties remain unsupported. A constrained dynamic subclass is rejected rather than silently randomizing only its base properties. A call through `null` is a runtime error. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index cf956ea3325..46185c6b8c8 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -99,7 +99,9 @@ select・連結式の引数は未対応として拒否します。 ### クラスの乱数化 `object.randomize()` は有効な `rand` プロパティを乱数化し、成功値の1(signed `int`)を返します。 -制約のないクラスで、64ビット以下の2値・非enum整数型に対応します。 +制約のないクラスで、スカラーenumを含む64ビット以下の2値整数型に対応します。 +enumは宣言された値だけから均等に抽選し、飛び飛びの値や負数にも対応します(18.3、18.4.1)。 +値が未解決またはX/Zを含むenum、列挙子の範囲指定は乱数化に未対応です。 継承したプロパティも対象になり、基底型のハンドルを通した呼び出しでも、実際のオブジェクトの クラスと `pre_randomize()` / `post_randomize()` を使います。子クラスでフックを定義すると 親のフックを置き換えるため、親の処理も必要なら `super.pre_randomize()` などを明示的に呼びます @@ -120,7 +122,7 @@ select・連結式の引数は未対応として拒否します。 オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します (18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 -`randc` の乱数化、制約、`with`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の +`randc` の乱数化、制約、`with`、staticな乱数プロパティ、配列・オブジェクト・文字列の 乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 `null` を通した呼び出しは実行時エラーです。 From 490502bb30f7d49f82042d0bdbd9a04fea87e8b3 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 12:52:43 +0900 Subject: [PATCH 4/9] feat(sv)!: support scope enum randomization Support scalar enums in randomize(e) and std::randomize(e), selecting only declared values with unbiased rejection sampling from the process RNG. Preserve enum domains through aliases and local variables, allow mixed enum/integer arguments, and retain short-circuit evaluation and checkpoint replay. Add shared domain and evaluation-order regressions plus Celox checkpoint and forced-rejection tests. Document the observed Icarus 13.0 compile limitation and Verilator 5.052 enum-domain mismatch with narrowly scoped exclusions and reproduction evidence. Validation: analyzer 796 and frontend 4 unit tests; 708 system-function regressions; 4 forced-rejection backend tests; retained-report checks (3); NAPI build and JS tests (432); affected-crate Clippy, cargo fmt and diff checks. Both new shared cases were exercised with Icarus and Verilator; their failures are retained as the tool limitations described above. BREAKING CHANGE: The public celox-sv-analyzer SystemFunction enum gains ScopeRandomizeEnum; downstream exhaustive matches must handle this variant. Change-Id: I2e07aafc25d024b216ce17760324265e3719055d --- crates/celox-frontend-sv/src/lowering.rs | 1 + crates/celox-frontend-sv/src/lowering/ff.rs | 67 +++++++++++++++++++ crates/celox-sv-analyzer/src/ast.rs | 1 + .../celox-sv-analyzer/src/ast/dimensions.rs | 11 ++- .../src/ast/expression_binding/direct.rs | 59 +++++++++++++--- .../src/ast/packed_structs/selects.rs | 1 + .../src/ast/parameters/skipped.rs | 1 + .../src/ast/patterns/binding.rs | 2 + .../celox-sv-analyzer/src/ast/procedural.rs | 3 +- .../celox-sv-analyzer/src/system_functions.rs | 8 ++- crates/celox-sv-analyzer/src/tests.rs | 9 ++- crates/celox-test-suite/LIMITATIONS.md | 11 +++ .../src/sv/cases/system_functions.vtest | 60 +++++++++++++++++ .../sv_scope_enum_randomize_icarus.json | 33 +++++++++ .../sv_scope_enum_randomize_verilator.json | 33 +++++++++ .../sv/icarus/system_functions.json | 46 +++++++++++++ .../verification/sv/limitations.json | 36 ++++++++++ .../sv/verilator/system_functions.json | 46 +++++++++++++ .../systemverilog/system_functions.rs | 63 +++++++++++++++++ docs/guide/systemverilog-reference.md | 7 +- docs/ja/guide/systemverilog-reference.md | 6 +- 21 files changed, 485 insertions(+), 19 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json create mode 100644 crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c44bd3b34c1..ccd2bc7faf5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -6488,6 +6488,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::UrandomRange | SystemFunction::Fopen | SystemFunction::ScopeRandomize + | SystemFunction::ScopeRandomizeEnum | SystemFunction::Fread | SystemFunction::Ftell | SystemFunction::Fseek diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b77cd77394d..ed885a57cd7 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -259,6 +259,7 @@ impl<'p, 'a> Ff<'p, 'a> { use sv::ir::SystemFunction; match function { SystemFunction::ScopeRandomize + | SystemFunction::ScopeRandomizeEnum | SystemFunction::Urandom | SystemFunction::UrandomRange => { self.urandom_state(); @@ -903,6 +904,11 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.fopen(args)?, + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomizeEnum), + args, + .. + } => self.randomize_enum(args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize), args, @@ -1412,6 +1418,67 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// Randomize one scalar enum from the process stream. Arguments after the + /// writable destination are its declared values, supplied by the analyzer. + fn randomize_enum( + &mut self, + args: &[Option], + ) -> Result { + use sv::ir::{BinaryOp, Expr}; + let Some(Some(Expr::Ident(name))) = args.first() else { + return Err(unsupported("scope enum randomize variable")); + }; + let values = args[1..] + .iter() + .map(Option::as_ref) + .collect::>>() + .filter(|values| !values.is_empty()) + .ok_or_else(|| unsupported("scope enum randomize domain"))?; + let count = u32::try_from(values.len()) + .map_err(|_| unsupported("scope enum randomize domain size"))?; + let threshold = count.wrapping_neg() % count; + let draw_block = self.b.new_block(); + let accepted = self.b.new_block(); + self.jump(draw_block); + self.b.switch_to_block(draw_block); + let draw = self.randomize_word()?; + let rejected = Expr::Binary { + left: Box::new(draw.clone()), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("32'd{threshold}"))), + }; + let cond = self.eval_truth(&rejected)?.0; + self.b.seal_block(SIRTerminator::Branch { + cond, + true_block: (draw_block, Vec::new()), + false_block: (accepted, Vec::new()), + }); + self.b.switch_to_block(accepted); + let index = self.hidden( + "enum_index", + &Expr::Binary { + left: Box::new(draw), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("32'd{count}"))), + }, + false, + )?; + let mut value = (*values.last().unwrap()).clone(); + for (position, member) in values.iter().enumerate().rev().skip(1) { + value = Expr::Mux { + condition: Box::new(Expr::Binary { + left: Box::new(index.clone()), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal(format!("32'd{position}"))), + }), + then_expr: Box::new((*member).clone()), + else_expr: Box::new(value), + }; + } + self.assign(&sv::ir::LValue::Ident(name.clone()), &value)?; + Ok(Expr::Literal("32'sd1".into())) + } + /// A bijective 32-bit output permutation of the process RNG. Mixing /// high bits into low bits prevents the LCG's short low-bit periods from /// freezing bits when a wide variable consumes an even number of words. diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index ca7fdc2114e..a33c623e978 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2731,6 +2731,7 @@ struct UnpackedDimension { #[derive(Debug, Clone, PartialEq, Eq)] struct VariableDimensions { randomizable: bool, + enum_values: Option>, real: bool, /// A `string`: each element is a heap handle, not packed bits. string: bool, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 7fd131f1d42..a5f17b392a4 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -132,7 +132,9 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( port.name().to_string(), VariableDimensions { - randomizable: !port.r#type().is_enum && port.randomizable, + randomizable: (!port.r#type().is_enum || port.r#type().enum_values.is_some()) + && port.randomizable, + enum_values: port.r#type().enum_values.clone(), real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(port.r#type().kind(), TypeKind::String), class: port.r#type().class().map(str::to_owned), @@ -156,7 +158,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( signal.name().to_string(), VariableDimensions { - randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const, + randomizable: (!signal.r#type().is_enum || signal.r#type().enum_values.is_some()) + && !signal.is_net() + && !signal.is_const, + enum_values: signal.r#type().enum_values.clone(), real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(signal.r#type().kind(), TypeKind::String), class: signal.r#type().class().map(str::to_owned), @@ -365,6 +370,7 @@ fn extend_variable_dimensions_from_const_env( let mut shape = procedural::dimensions_from_type(&ty); if let Some(existing) = context.get(name) { shape.randomizable = existing.randomizable; + shape.enum_values = existing.enum_values.clone(); shape.members = existing.members.clone(); shape.is_2state = existing.is_2state; shape.signed_element_depth = existing.signed_element_depth; @@ -533,6 +539,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP parameter.name.clone(), VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 17b50ff3c53..6f80370ce22 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -216,6 +216,7 @@ pub(in crate::ast) fn cast_target_native( } enum Finish { + ScopeRandomize(Vec>>), Unary(String), Binary(String), Mux, @@ -499,6 +500,7 @@ pub(in crate::ast) fn bind_value( } let actuals = args.iter().filter_map(|arg| arg.value).collect::>(); + let mut domains = Vec::with_capacity(actuals.len()); for &actual in &actuals { let ExprKind::Name(name) = &native.expression(actual).kind else { return Err(unsupported( @@ -509,11 +511,17 @@ pub(in crate::ast) fn bind_value( let shape = dimensions .get(&name) .ok_or_else(|| unsupported("scope randomize variable"))?; - if !shape.unpacked.is_empty() || !shape.randomizable { + if !shape.unpacked.is_empty() + || !shape.randomizable + || shape.real + || shape.string + || shape.class.is_some() + { return Err(unsupported( - "scope randomize requires a packed non-enum variable", + "scope randomize requires a packed variable with a supported enum domain", )); } + domains.push(shape.enum_values.clone()); if !expressions::query_actual_is_writable( &Expr::Ident(name), dimensions, @@ -524,12 +532,7 @@ pub(in crate::ast) fn bind_value( } } jobs.push(Job::Finish( - Finish::Call { - name: "std::randomize".into(), - args: actuals.iter().copied().map(Some).collect(), - order: Vec::new(), - system: Some(SystemFunction::ScopeRandomize), - }, + Finish::ScopeRandomize(domains), actuals.len(), scope.clone(), )); @@ -930,6 +933,46 @@ pub(in crate::ast) fn bind_value( Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } + Finish::ScopeRandomize(domains) => { + // Preserve the original call when no enum is present. + // Every scalar operation succeeds and returns signed int 1; + // bitwise AND preserves that type and evaluates all operands. + if domains.iter().all(Option::is_none) { + Expr::Call { + callee: Callee::System(SystemFunction::ScopeRandomize), + args: operands.into_iter().map(Some).collect(), + arg_order: Vec::new(), + } + } else { + let mut calls = + operands.into_iter().zip(domains).map(|(operand, domain)| { + let mut args = vec![Some(operand)]; + let function = if let Some(values) = domain { + args.extend(values.into_iter().map(|value| { + Some(Expr::Literal(format_typed_parameter_literal( + value, + 64, + value < 0, + ))) + })); + SystemFunction::ScopeRandomizeEnum + } else { + SystemFunction::ScopeRandomize + }; + Expr::Call { + callee: Callee::System(function), + args, + arg_order: Vec::new(), + } + }); + let first = calls.next().ok_or_else(disagreement)?; + calls.fold(first, |left, right| Expr::Binary { + left: Box::new(left), + op: BinaryOp::BitAnd, + right: Box::new(right), + }) + } + } Finish::ObjectLoad(property) => { let handle = operands.pop().ok_or_else(disagreement)?; objects::load(&property, handle) diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 26ba51430bd..382384aad5d 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -57,6 +57,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - name.to_string(), VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 3072f78cc24..1184772f60f 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -502,6 +502,7 @@ fn pattern_items( count as i128 - 1, VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 0253bcdeaec..79d17825612 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -137,6 +137,7 @@ fn select<'a>( let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, @@ -244,6 +245,7 @@ fn select<'a>( .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 47aeab7cdd8..11830353e22 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -73,7 +73,8 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { /// The packed and unpacked shape of a declared type, as selects see it. pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { - randomizable: !r#type.is_enum, + randomizable: !r#type.is_enum || r#type.enum_values.is_some(), + enum_values: r#type.enum_values.clone(), real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(r#type.kind(), TypeKind::String), class: r#type.class().map(str::to_owned), diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 3fda772fed5..dfdf49d219d 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -103,6 +103,8 @@ pub enum SystemFunction { Urandom, /// Scope randomization of packed variables, without constraints (18.12). ScopeRandomize, + /// Internal scalar enum randomization: destination followed by legal values. + ScopeRandomizeEnum, /// `$urandom_range` (18.13.2). UrandomRange, /// `$fopen` (21.3.1). @@ -280,6 +282,7 @@ impl SystemFunction { Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", Self::ScopeRandomize => "std::randomize", + Self::ScopeRandomizeEnum => "$__celox_randomize_enum", Self::UrandomRange => "$urandom_range", Self::Fopen => "$fopen", Self::Fread => "$fread", @@ -343,6 +346,7 @@ impl SystemFunction { | Self::Fscanf | Self::UrandomRange | Self::ScopeRandomize + | Self::ScopeRandomizeEnum ) } @@ -357,6 +361,7 @@ impl SystemFunction { /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { self == Self::ScopeRandomize + || (self == Self::ScopeRandomizeEnum && position == 0) || (matches!( self, Self::Random @@ -406,7 +411,8 @@ impl SystemFunction { | Self::Clog2 | Self::Countbits | Self::Countones - | Self::ScopeRandomize => Some((32, true)), + | Self::ScopeRandomize + | Self::ScopeRandomizeEnum => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), Self::Random | Self::DistUniform diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 81a99a92a65..4314adf6bae 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6303,11 +6303,10 @@ fn scope_randomize_validates_variable_arguments() { ("bit value[2];", "randomize(value)"), ("wire value;", "randomize(value)"), ("const bit value = 1;", "randomize(value)"), - ("enum bit [1:0] {A=0, B=3} value;", "randomize(value)"), - ( - "typedef enum bit [1:0] {A=0, B=3} E; E value;", - "std::randomize(value)", - ), + ("real value;", "randomize(value)"), + ("string value;", "randomize(value)"), + ("class C; endclass C value;", "randomize(value)"), + ("enum bit [1:0] {A=3, B} value;", "randomize(value)"), ("bit value;", "std::randomize(value) with {value == 1;}"), ] { let source = format!("module Top; {declaration} bit ok; initial ok = {call}; endmodule"); diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 8e44294ee77..97530f68a62 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -709,6 +709,17 @@ IEEE 1800-2023 18.3. Only `class::randomization_enum_alias` is excluded; [the mismatch evidence](verification/repros/sv_enum_randomization_verilator.json) retains its unchanged domain assertion. +Scope enum randomization has two narrow tool exclusions for +`system_functions::scope_randomize_enum_values` and +`system_functions::scope_randomize_enum_order`. Icarus 13.0 rejects scope +randomization calls (`sv_icarus_scope_enum_randomize`; +[compile diagnostics](verification/repros/sv_scope_enum_randomize_icarus.json)). +Verilator 5.052 generates `basicStdRandomization` calls using only integer widths, +without the enum domain, and draws undeclared values (`sv_verilator_scope_enum_randomize`; +[mismatch evidence](verification/repros/sv_scope_enum_randomize_verilator.json)). +IEEE 1800-2023 18.3 and 18.12 require the declared enum domain. The shared +assertions remain unchanged, including the direct-enum case without an alias. + ## SystemVerilog packed unions The `unions` shared group covers hard and soft packed untagged unions. With diff --git a/crates/celox-test-suite/src/sv/cases/system_functions.vtest b/crates/celox-test-suite/src/sv/cases/system_functions.vtest index 0990ccf7e9f..2463a162fa5 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2892,3 +2892,63 @@ endmodule (top Top) (run_to_finish) (assert_eq status 2)) + +(case scope_randomize_enum_values + (source "scope_enum.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=91} original_t; + typedef original_t alias_t; + typedef enum logic [63:0] {ALL='1} wide_t; + alias_t value; + wide_t wide; + int plain; + int seen; + function automatic int local_random(); + alias_t local_value; + if (randomize(local_value) != 1) return 0; + return local_value == NEG || local_value == MID || local_value == HIGH; + endfunction + initial begin + repeat (128) begin + if (std::randomize(value, plain, wide) != 1) errors++; + case (value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + if (wide != 64'hffffffffffffffff) errors++; + if (local_random() != 1) errors++; + end + if (seen != 7) errors++; + if ($bits(std::randomize(value)) != 32) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + + +(case scope_randomize_enum_order + (source "scope_enum_order.sv" #" +module Top(output bit done, output int errors); + typedef enum bit [7:0] {A=3, B=19, C=97} value_t; + value_t value; + int plain; + int result; + initial begin + value = A; plain = 17; + result = 0 && std::randomize(value, plain); + result = 1 || randomize(value); + if (value != A || plain != 17) errors++; + repeat (64) begin + result = (std::randomize(value, plain) == 1) + && (value == A || value == B || value == C); + if (result != 1) errors++; + if (randomize(value) != 1 || (value != A && value != B && value != C)) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json new file mode 100644 index 00000000000..b262a613b51 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json @@ -0,0 +1,33 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:13: syntax error\n/source_0.sv:14: error: Malformed statement\n", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: Malformed statement\n/source_0.sv:17: error: Malformed conditional expression.\n/source_0.sv:28: syntax error\n/source_0.sv:28: error: Malformed statement\n/source_0.sv:28: error: Malformed conditional expression.\n", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json new file mode 100644 index 00000000000..eabf478fa92 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json @@ -0,0 +1,33 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "system_functions::scope_randomize_enum_order at 2887:46: assert_eq errors: expected 0x0, got 0x7e", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::scope_randomize_enum_values at 2862:46: assert_eq errors: expected 0x0, got 0x181", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052" +} diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index eacfdc15b69..524ae2cac27 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1619,6 +1619,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "known_issue": { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "known_issue": { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index f4839f22972..76dc9455d36 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2247,5 +2247,41 @@ "class::randomization_enum_alias" ] } + }, + { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "system_functions::scope_randomize_enum_order", + "system_functions::scope_randomize_enum_values" + ] + } + }, + { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "system_functions::scope_randomize_enum_order", + "system_functions::scope_randomize_enum_values" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/system_functions.json b/crates/celox-test-suite/verification/sv/verilator/system_functions.json index 697545e7c70..93f263f8b17 100644 --- a/crates/celox-test-suite/verification/sv/verilator/system_functions.json +++ b/crates/celox-test-suite/verification/sv/verilator/system_functions.json @@ -920,6 +920,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "known_issue": { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "known_issue": { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 280d9aebc2f..e8d26fe9cd3 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -3226,3 +3226,66 @@ fn time_format_rejects_string_operands() { ); } } + +sv_backends! { + fn scope_randomize_enum_values(sim) { @case "system_functions::scope_randomize_enum_values"; } + fn scope_randomize_enum_order(sim) { @case "system_functions::scope_randomize_enum_order"; } +} + +sv_backends! { + fn scope_randomize_enum_checkpoint(sim) { + @setup { let source = r#" + module Top(input bit clk, output logic [63:0] value); + typedef enum logic signed [63:0] {NEG=-7, POS=2, ALL='1} E; + E e; + always @(posedge clk) begin + void'(std::randomize(e)); + value = e; + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("enum_checkpoint.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + let saved = sim.checkpoint().unwrap(); + let mut expected = Vec::new(); + for _ in 0..16 { + sim.tick(clk).unwrap(); + let (bits, mask) = sim.get_four_state(value); + assert_eq!(mask, 0u8.into()); + expected.push(bits); + } + assert!(expected.windows(2).any(|pair| pair[0] != pair[1])); + sim.restore(&saved).unwrap(); + for bits in expected { + sim.tick(clk).unwrap(); + assert_eq!(sim.get_four_state(value), (bits, 0u8.into())); + } + } +} + +sv_backends! { + fn scope_randomize_enum_retries_rejected_draw(sim) { + @setup { let source = r#" + module Top(output bit done, output int unsigned next); + typedef enum bit [7:0] {A=3, B=19, C=97} E; + E e; + int ignored; + initial begin + // The process LCG reaches zero on the next draw. Its + // bijective mixer preserves zero, rejected for 3 choices. + ignored = $urandom(32'd4150723358); + ignored = std::randomize(e); + next = $urandom(); + done = 1; + end + endmodule + "#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("enum_rejection.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + // Rejection consumes zero, then 1013904223, leaving the following + // LCG value for the explicit $urandom call. + assert_eq!(sim.get(sim.signal("next")), 1196435762u32.into()); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index c765062dd74..4e45062ed5c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -104,7 +104,12 @@ variable or advancing the random stream. Calls follow procedural statement order and short-circuit evaluation, and use the calling process's persistent random stream (IEEE 1800-2023 18.12). -Constraints (`with`), enum variables, unpacked arrays, nets, +Scalar enums up to 64 bits are also supported: randomization selects only their +known declared values, including typedef aliases and signed or sparse values. +The process random stream, short-circuit behavior, and checkpoint state apply +to enums as well. Mixed enum and integer argument lists are supported. + +Constraints (`with`), enums with unsupported or unresolved domains, unpacked arrays, nets, constants, selects and concatenation arguments are unsupported and rejected. ### Class randomization diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 46185c6b8c8..29a9a0e11d3 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -93,7 +93,11 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task プロセスごとの永続的な乱数列を使い、文の実行順序と短絡評価に従います (IEEE 1800-2023 18.12)。 -`with` 制約、enum 変数、unpacked 配列、net、定数、 +64ビット以下のスカラーenumにも対応し、既知の宣言値だけから抽選します。 +型エイリアス、負数、飛び飛びの値、整数との引数混在を扱えます。enumにもプロセス単位の +乱数列・短絡評価・チェックポイント復元が適用されます。 + +`with` 制約、値域が未対応または未解決のenum、unpacked 配列、net、定数、 select・連結式の引数は未対応として拒否します。 ### クラスの乱数化 From ce7e0151953955a71c6662c82bbfac895c39750a Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 17:59:13 +0900 Subject: [PATCH 5/9] ci: report Rust test results to Mergify CI Insights Change-Id: I28a4e411f6de79c7e30511682cd78111ff7f9490 --- .config/nextest.toml | 4 +++ .github/workflows/ci.yml | 29 ++++++++++++++++++ CONTRIBUTING.md | 9 ++++++ scripts/ci-rust-reports.mjs | 40 +++++++++++++++++++++++++ scripts/ci-rust-reports.test.mjs | 51 ++++++++++++++++++++++++++++++++ scripts/ci-workflow.test.mjs | 26 ++++++++++++++-- scripts/run-ci-rust-scope.mjs | 5 ++++ 7 files changed, 162 insertions(+), 2 deletions(-) create mode 100644 scripts/ci-rust-reports.mjs create mode 100644 scripts/ci-rust-reports.test.mjs 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 7240c48d8ff..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: @@ -223,6 +226,9 @@ jobs: 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: @@ -249,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,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 }} @@ -262,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/CONTRIBUTING.md b/CONTRIBUTING.md index 4266b5a98ee..1d2fa52bdfd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,6 +66,15 @@ workspace runs and scoped runs that include Celox. Scopes without Celox skip tha 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: 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 4371d744539..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"), @@ -461,6 +461,28 @@ test("CI prepares one executor for full runs and scopes containing Celox", () => "-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 b604ee32a0f..80850239528 100644 --- a/scripts/run-ci-rust-scope.mjs +++ b/scripts/run-ci-rust-scope.mjs @@ -1,6 +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) { @@ -31,6 +32,8 @@ 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, )) { @@ -39,7 +42,9 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) && !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); } From 18517ce1bfb87590bcc21199cbced83515b76e50 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 17:59:19 +0900 Subject: [PATCH 6/9] fix(sir-opt): keep the And width in the bit-extract peephole BitExtractPeephole rewrote `(load >> k) & mask` as a mask-width load and retyped the And's destination to the mask width. Its users still expected the And's own width, e.g. `((a >> 4) & 15) == 32'd9` compared a 4-bit register with a 32-bit one. Cranelift tolerated the ill-typed SIR; the native merged-chain verifier rejected it at O1/O2 (#1854). Keep the destination type: load the field into a fresh register and zero-extend it with a Concat when the mask is narrower than the result, and load only the result width when the mask is wider. Fixes #1854 Change-Id: Icc91ce47ea0358c2f3eb597eaf151257a7c536d7 --- .../dataflow/pass_bit_extract_peephole.rs | 70 ++++++++++++++----- .../src/sv/cases/operators.vtest | 23 ++++++ .../frontends/systemverilog/operators.rs | 4 ++ 3 files changed, 79 insertions(+), 18 deletions(-) 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-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/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! { From 31eedffe85e839b4f6c92ad70847cf6adb8d663c Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 15:26:34 +0900 Subject: [PATCH 7/9] perf(sv): publish only written elements of nonblocking array writes An edge process that writes an unpacked array by a nonblocking assignment at a run-time element seeded the whole array into its next state and committed all of it back on every edge. Each edge cost O(array size), and the generated code and compile time grew with the array (#1855). Such an array now uses the sparse next-state protocol that shared edge memories (and Veryl's dynamic writes) already use: element stores mark dirty 64-bit chunks, and the commit copies only those. Precondition, decided in `edge_only_memories()` (lowering.rs): - all local drivers of the array are edge processes of its module, and - the process writes it only by nonblocking constant-range or element writes, at least one at a run-time element (no blocking, whole-array or read-modify-write assignment). Every other array keeps the full next state. The function's doc comment is the hook for writers outside the module (hierarchical references, #1856). A write by another process between the evaluation and the NBA region (e.g. a `#0` resumption of an `initial`) is clobbered by the commit. This is pre-existing for every edge-process target, not only arrays, and is tracked and fixed separately in #1864. This change only narrows it: the sparse commit rewrites the dirty chunks, where the old one rewrote the whole array. Performance (100,000 cycles, `celox run --two-state --unlimited --backend cranelift`, release build, user time, `taskset -c 8-11`): | b3_mem_sweep | master | this | |---|---:|---:| | 2^10 | 0.12 s | 0.07 s | | 2^12 | 0.20 s | 0.07 s | | 2^14 | 0.64 s | 0.07 s | | 2^16 | 4.26 s | 0.09 s | | 2^22 (heliodor-dev) | 2-cycle startup alone 86.8 s user, 3.7 GB | full run 0.50 s, 125 MB | | 2^22 four-state (heliodor-dev) | - | full run 0.44 s | Startup of the 2-cycle variants (heliodor-dev): 2^16 0.88 s -> 0.01 s user; 2^22 110 s wall / 3.7 GB -> 0.36 s / 125 MB. Compile time and memory had the same cause. Unaffected workloads (callgrind, release): b2_vm_dispatch_bit.sv generates identical JIT code; whole-program 44.51 G -> 44.57 G instructions (+0.12%), all in compile-time functions this change does not touch, with identical call counts (e.g. `DriverScan::body` 56,773,692 calls in both). A Veryl 64K-word dynamic-index memory workload: identical JIT code, 188.40 M -> 188.80 M (+0.2%, about 4 host instructions per cycle in `testbench::clock_periods` and two runtime-event helpers this change does not touch). Both are code-layout differences of the LTO build. Validation: - `cargo test -p celox --features systemverilog --test systemverilog`: 4372 passed. - New shared case `procedural::nonblocking_runtime_element_writes_apply_in_order` (cranelift, native, wasm, parallel variants), passes on Verilator 5.052 and Icarus 13.0 (`verify-sv-verilator`, `verify-sv-icarus`). - New IR test `nonblocking_runtime_element_writes_use_sparse_next_state` (sparse for NBA element writes; full next state with a blocking or whole-array write). - A semantics stress design (multiple NBAs to one element, reads of old values, part-select merge, constant elements, X index) gives identical results to master on cranelift, interpreter, native O0 and wasm, two- and four-state; four-state matches xezim. - `cargo clippy -p celox-frontend-sv -p celox --features celox/systemverilog --tests`, `cargo fmt --check`. Closes #1855 Change-Id: I04824191d94b708b96866eab3e40f39eea515417 --- crates/celox-frontend-sv/src/lowering.rs | 62 +++++++++++++++++++ crates/celox-frontend-sv/src/lowering/ff.rs | 54 ++++++++++++++-- .../src/sv/cases/procedural.vtest | 47 ++++++++++++++ .../frontends/systemverilog/procedural.rs | 4 ++ .../systemverilog/review_regressions.rs | 56 +++++++++++++++++ 5 files changed, 219 insertions(+), 4 deletions(-) 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-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/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"] { From 3c4944a11075aeee0946804967c707ef66b3eb88 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 18:18:45 +0900 Subject: [PATCH 8/9] fix(sv): keep other processes' writes made before an edge's NBA region MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An edge process evaluates into a next state seeded from stable state, and its NBA commit copies the whole written range back. A process kernel that writes the same variable after the evaluation and before the NBA region, such as a `#0` resumption or a process the edge's blocking result wakes, lost its write, even in bits no nonblocking assignment touched and when no nonblocking assignment executed (#1864). An NBA update changes only the bits its lvalue names (IEEE 1800-2023 10.4.2), and the NBA region follows the active and inactive regions (4.4.2.4). Such a variable now goes through the exact staging that variables written both by blocking and nonblocking assignments already use: the nonblocking assignments write a staging value and mark a written-bit mask, and the NBA region merges `stable = (stable & ~mask) | (value & mask)`. The variable has no seed or whole-range commit. An unpacked array merges element by element in a loop, and its mask is cleared by a commit from its zero stable copy. The change is per signal. `kernel_window_writes()` (lowering.rs) collects the variables a process kernel of the module may write after it first suspends. Code before the first timing control of an `initial` runs at time zero before any domain evaluates, so memory initialization by `initial` loops or `$readmemh` does not count. A process stages only those of its nonblocking targets it does not also write by blocking assignments or in called subroutines. Every other signal keeps today's code, and #1855's sparse array publication still applies to arrays without such a writer. Writers from other modules (hierarchical references, #1856) have to be added to `kernel_window_writes()`. A staged array costs O(array size) per edge, as before #1855. Not covered, keeping the previous behavior: nonblocking assignments in subroutines the edge process calls, and host writes while a `$stop` suspends a round after a domain evaluated. Repros from #1864 (plain `always @(posedge clk)`; with `always_ff` a second writer is illegal, 9.2.2.4 → 9.2.2.2), `celox run --top --unlimited` on cranelift, interpreter, native O0 and wasm, two- and four-state, all now match Icarus 13.0: | Case | Expected (Icarus) | Before | After | |---|---|---|---| | win_c_al | `m0=00001122` | `m0=00001100` | expected | | win_d_al | `m0=00000011 m1=00000022 m5=00000033` | `m1=00000000 m5=00000000` | expected | | win_e_al | `q=00000022 r=00100008` | `q=00000000 r=00000008` | expected | | active-region wake | `q=22 p=44` | `q=00 p=44` | expected | Performance (callgrind, heliodor-dev, this vs #1855): no signal of these workloads is staged, and their JIT code executes the same instruction counts (b2_vm_dispatch_bit 411.55 M, Veryl 64K-word memory workload 15.19 M, b3_mem_sweep_14 0.43 M per run). Whole program: b2 46.686 G -> 46.683 G, Veryl 217.23 M -> 217.26 M, b3_mem_sweep_14 139.07 M -> 139.16 M (within 0.07%). Validation: - New shared cases `timing::edge_nonblocking_updates_keep_later_writes_of_other_bits`, `timing::edge_nonblocking_updates_follow_writes_their_blocking_results_wake` and `timing::edge_blocking_results_precede_later_process_writes` on cranelift, native, wasm and parallel variants. The first two fail without this change. All three pass on Verilator 5.052 and Icarus 13.0. - `cargo test -p celox --features systemverilog --test systemverilog`: 4462 passed. `cargo test -p celox-frontend-sv`. - `cargo clippy -p celox-frontend-sv -p celox --features celox/systemverilog --tests`, `cargo fmt --check`. Closes #1864 Change-Id: I8356911ef0608ae6eb0175147ca64ddc8881f7b9 --- crates/celox-frontend-sv/src/lowering.rs | 140 +++++++++++++ crates/celox-frontend-sv/src/lowering/ff.rs | 195 +++++++++++++++++- .../src/sv/cases/timing.vtest | 103 +++++++++ .../tests/frontends/systemverilog/timing.rs | 14 ++ 4 files changed, 446 insertions(+), 6 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 765af0db277..c1972fb7545 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1112,6 +1112,144 @@ fn edge_only_memories( .collect() } +/// The variables a process kernel of `module` may write after it first +/// suspends. Such a write can land between the evaluation of an edge +/// process and the NBA region that publishes its nonblocking assignments: +/// an inactive-region resumption (`#0`), or a process a domain's observed +/// blocking result wakes (IEEE 1800-2023 4.4.2.4, 4.5). The code before the +/// first suspension of an `initial` runs at time zero before any domain +/// evaluates, so its writes, such as memory initialization, are not +/// included. +/// +/// These are the writers within `module`. A writer outside it (a +/// hierarchical reference) that can write after it suspends has to be added +/// here. +fn kernel_window_writes(module: &sv::ir::Module) -> HashSet { + let subroutines = module.subroutines(); + let mut names = HashSet::default(); + for process in module + .initial_processes() + .iter() + .filter(|process| !process.is_initializer()) + { + let body = process.body(); + let first = if process.repeats() { + 0 + } else { + body.iter() + .position(|stmt| stmt_may_suspend(subroutines, stmt)) + .unwrap_or(body.len()) + }; + kernel_written_names( + subroutines, + &body[first..], + &mut names, + &mut HashSet::default(), + 0, + ); + } + names +} + +/// Whether `stmt` may suspend its process: a timing control, or a call of a +/// task, in it or in a subroutine it calls. +fn stmt_may_suspend(subroutines: &[sv::ir::Subroutine], stmt: &sv::ir::Stmt) -> bool { + let mut found = false; + let mut calls = Vec::new(); + stmt.walk(&mut |stmt| { + found |= matches!( + stmt, + sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::Wait(_) + ); + procedural::stmt_calls(stmt, &mut calls); + }); + let mut visited = HashSet::default(); + while !found && let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + let Some(subroutine) = subroutines + .iter() + .find(|subroutine| subroutine.name == name) + else { + continue; + }; + found |= subroutine.is_task; + procedural::default_calls(subroutine, &args, &mut calls); + if visited.insert(name) { + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| procedural::stmt_calls(stmt, &mut calls)); + } + } + } + found +} + +/// Adds the names of the variables `body` writes, directly or in the +/// subroutines it calls, to `names` (see [`DriverScan`]). +fn kernel_written_names( + subroutines: &[sv::ir::Subroutine], + body: &[sv::ir::Stmt], + names: &mut HashSet, + visited: &mut HashSet, + depth: usize, +) { + if depth > procedural::MAX_CALL_DEPTH { + return; + } + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| { + match stmt { + sv::ir::Stmt::Assign { lhs, .. } => { + names.insert(lhs.name().to_string()); + } + sv::ir::Stmt::AssignConcat { parts, .. } => { + names.extend(parts.iter().map(|part| part.name().to_string())); + } + sv::ir::Stmt::SystemTask { task, args, .. } => { + if let Some(destination) = procedural::readmem_destination(*task, args) { + names.insert(destination.to_string()); + } + } + _ => {} + } + procedural::stmt_calls(stmt, &mut calls); + }); + } + while let Some((callee, args)) = calls.pop() { + let name = match callee { + sv::ir::Callee::System(function) => { + names.extend( + procedural::written_system_arguments(function, &args) + .iter() + .map(|lvalue| lvalue.name().to_string()), + ); + continue; + } + sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => continue, + sv::ir::Callee::Subroutine(name) => name, + }; + let Some(subroutine) = subroutines + .iter() + .find(|subroutine| subroutine.name == name) + else { + continue; + }; + procedural::default_calls(subroutine, &args, &mut calls); + for (param, arg) in subroutine.params.iter().zip(&args) { + if param.direction.is_written() + && let Some(lvalues) = arg.as_ref().and_then(procedural::lvalue_from_expr) + { + names.extend(lvalues.iter().map(|lvalue| lvalue.name().to_string())); + } + } + if visited.insert(name) { + kernel_written_names(subroutines, &subroutine.body, names, visited, depth + 1); + } + } +} + fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, @@ -8490,6 +8628,7 @@ fn lower_ff_processes( } let edge_memories = edge_only_memories(module, pm.constants, pm.parameter_types); + let window_writes = kernel_window_writes(module); let random_seeds = process_random_seeds(module); for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { let mut events = events @@ -8517,6 +8656,7 @@ fn lower_ff_processes( } = ff::Ff::new(pm, random_seeds[&(0, index)]) .with_sparse_memories(shared_memories) .with_sparse_candidates(&edge_memories) + .with_window_writes(&window_writes) .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 61296800342..243ddfad3c1 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -48,6 +48,9 @@ pub(super) struct Ff<'p, 'a> { /// 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, + /// Variables a process kernel may write between the evaluation of this + /// process and the NBA region (see `kernel_window_writes`). + window_writes: HashSet, b: SIRBuilder, /// Variables read from the working region. working: HashSet, @@ -120,6 +123,7 @@ impl<'p, 'a> Ff<'p, 'a> { sparse_candidates: HashSet::default(), element_writes: HashSet::default(), other_writes: HashSet::default(), + window_writes: HashSet::default(), b: SIRBuilder::new(), working: HashSet::default(), nonblocking: HashSet::default(), @@ -164,6 +168,11 @@ impl<'p, 'a> Ff<'p, 'a> { self } + pub fn with_window_writes(mut self, names: &HashSet) -> Self { + self.window_writes = 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 { @@ -251,6 +260,44 @@ impl<'p, 'a> Ff<'p, 'a> { self.targets.push((id, access)); } + /// The variables the subroutines `body` calls assign, directly or + /// through further calls. + fn subroutine_assignments(&self, body: &[sv::ir::Stmt]) -> HashSet { + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + let mut assigned = HashSet::default(); + let mut visited = HashSet::default(); + while let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + let Some(subroutine) = self.m.subroutine(&name) else { + continue; + }; + default_calls(subroutine, &args, &mut calls); + if !visited.insert(name) { + continue; + } + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| { + match stmt { + sv::ir::Stmt::Assign { lhs, .. } => { + assigned.extend(self.m.id(lhs.name())); + } + sv::ir::Stmt::AssignConcat { parts, .. } => { + assigned.extend(parts.iter().filter_map(|part| self.m.id(part.name()))); + } + _ => {} + } + stmt_calls(stmt, &mut calls); + }); + } + } + assigned + } + /// Collect the variables a body writes, following calls into subroutines. fn scan(&mut self, stmts: &[sv::ir::Stmt], visited: &mut HashSet) { let mut writes: Vec<(sv::ir::LValue, bool)> = Vec::new(); @@ -3966,6 +4013,25 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result { let mut visited = HashSet::default(); self.scan(body, &mut visited); + // A variable only this process's nonblocking assignments write here, + // and that a process kernel may write before they are published, + // takes only the bits they wrote: the kernel's write stays in the + // others, even when no assignment executed (IEEE 1800-2023 10.4.2). + // Staging rewrites the assignments of the body; a variable a called + // subroutine assigns keeps its whole next state. + let called = self.subroutine_assignments(body); + let exact: HashSet = self + .nonblocking + .iter() + .copied() + .filter(|id| { + self.window_writes.contains(id) + && !called.contains(id) + && !self.working.contains(id) + && !self.m.is_hidden(*id) + && !self.sparse_memories.contains(id) + }) + .collect(); // 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 @@ -3977,6 +4043,7 @@ impl<'p, 'a> Ff<'p, 'a> { .copied() .filter(|id| { self.element_writes.contains(id) + && !exact.contains(id) && !self.working.contains(id) && !self.other_writes.contains(id) && !self.m.is_hidden(*id) @@ -4024,6 +4091,7 @@ impl<'p, 'a> Ff<'p, 'a> { .intersection(&self.working) .copied() .filter(|&id| !self.m.is_hidden(id) && self.m.var(id).array_dims.is_empty()) + .chain(exact.iter().copied()) .collect(); mixed.sort_by_key(|id| id.0); let staged: Vec = mixed @@ -4046,7 +4114,14 @@ impl<'p, 'a> Ff<'p, 'a> { } else { stage_nonblocking(body, &staged, self.m) }; - let ordinary_targets: Vec<_> = targets + // A variable staged for an exact publication has no next state of + // its own: only its merge publishes it. + let published: Vec<_> = targets + .iter() + .copied() + .filter(|target| !exact.contains(&target.id)) + .collect(); + let ordinary_targets: Vec<_> = published .iter() .copied() .filter(|target| !self.sparse_memories.contains(&target.id)) @@ -4054,9 +4129,21 @@ impl<'p, 'a> Ff<'p, 'a> { emit_ff_seeds(&mut self.b, &ordinary_targets); for stage in &staged { let width = self.m.var(stage.mask).width; - let zero = self.b.alloc_bit(width, false); - self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); - self.store(stage.mask, SIROffset::Static(0), width, zero); + if self.m.var(stage.id).array_dims.is_empty() { + let zero = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + self.store(stage.mask, SIROffset::Static(0), width, zero); + } else { + // Nothing writes the mask's stable state, which stays zero; + // a store may not span the elements of an array. + self.b.emit(SIRInstruction::Commit( + stable(stage.mask), + working(stage.mask), + SIROffset::Static(0), + width, + Vec::new(), + )); + } } if self.exec_block(&body)? { self.b.seal_block(SIRTerminator::Return); @@ -4078,14 +4165,14 @@ impl<'p, 'a> Ff<'p, 'a> { } } } - let (active_targets, nba_targets): (Vec<_>, Vec<_>) = targets + let (active_targets, nba_targets): (Vec<_>, Vec<_>) = published .iter() .copied() .partition(|target| self.working.contains(&target.id)); let mut apply = SIRBuilder::new(); emit_sparse_memory_commits( &mut apply, - &targets, + &published, &self.sparse_memories, self.m.variables, ); @@ -4328,6 +4415,12 @@ fn emit_nba_merges(builder: &mut SIRBuilder, staged: &[NbaStage], pm: &Pro for stage in staged { let _ = &stage.name; let variable = pm.var(stage.id); + if let Some(element_width) = + unpacked_element_width(variable).filter(|_| !variable.array_dims.is_empty()) + { + emit_array_nba_merge(builder, stage, variable, element_width); + continue; + } let width = variable.width; let current = if variable.is_4state { builder.alloc_logic(width) @@ -4389,6 +4482,96 @@ fn emit_nba_merges(builder: &mut SIRBuilder, staged: &[NbaStage], pm: &Pro } } +/// [`emit_nba_merges`] for an unpacked array: a loop merges each element, +/// since an access may not span elements. +fn emit_array_nba_merge( + builder: &mut SIRBuilder, + stage: &NbaStage, + variable: &SvVariable, + element_width: usize, +) { + let count = variable.width / element_width; + let four_state = variable.is_4state; + let alloc = |builder: &mut SIRBuilder| { + if four_state { + builder.alloc_logic(element_width) + } else { + builder.alloc_bit(element_width, false) + } + }; + let first = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm(first, SIRValue::new(0u8))); + let index = builder.alloc_bit(64, false); + let header = builder.new_block_with(vec![index]); + let body_index = builder.alloc_bit(64, false); + let body = builder.new_block_with(vec![body_index]); + let exit = builder.new_block(); + builder.seal_block(SIRTerminator::Jump(header, vec![first])); + + builder.switch_to_block(header); + let limit = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm(limit, SIRValue::new(count as u64))); + let more = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(more, index, BinaryOp::LtU, limit)); + builder.seal_block(SIRTerminator::Branch { + cond: more, + true_block: (body, vec![index]), + false_block: (exit, Vec::new()), + }); + + builder.switch_to_block(body); + let offset = SIROffset::Element { + index: body_index, + element_width, + bit_offset: 0, + dynamic_bit_offset: None, + }; + let current = alloc(builder); + builder.emit(SIRInstruction::Load( + current, + stable(stage.id), + offset.clone(), + element_width, + )); + let value = alloc(builder); + builder.emit(SIRInstruction::Load( + value, + working(stage.value), + offset.clone(), + element_width, + )); + let mask = builder.alloc_bit(element_width, false); + builder.emit(SIRInstruction::Load( + mask, + working(stage.mask), + offset.clone(), + element_width, + )); + let keep = builder.alloc_bit(element_width, false); + builder.emit(SIRInstruction::Unary(keep, UnaryOp::BitNot, mask)); + let kept = alloc(builder); + builder.emit(SIRInstruction::Binary(kept, current, BinaryOp::And, keep)); + let taken = alloc(builder); + builder.emit(SIRInstruction::Binary(taken, value, BinaryOp::And, mask)); + let merged = alloc(builder); + builder.emit(SIRInstruction::Binary(merged, kept, BinaryOp::Or, taken)); + builder.emit(SIRInstruction::Store( + stable(stage.id), + offset, + element_width, + merged, + Vec::new(), + Vec::new(), + )); + let one = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let next = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Binary(next, body_index, BinaryOp::Add, one)); + builder.seal_block(SIRTerminator::Jump(header, vec![next])); + + builder.switch_to_block(exit); +} + impl Ff<'_, '_> { /// Lower an `initial` body into a process kernel that runs it from time /// zero, reading and writing stable state directly. diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 500208661ae..9391d4b7673 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -2462,3 +2462,106 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (assert_eq q 0) (assert_eq m0 0) (assert_eq m1 0)) + +(case edge_nonblocking_updates_keep_later_writes_of_other_bits + ; An edge process evaluates, then a zero-delay resumption writes the same + ; variables before the NBA region (IEEE 1800-2023 4.4.2.4). The + ; nonblocking updates change only the bits they assign (10.4.2): the + ; resumption's writes to other bits, elements and variables stay, also + ; where no assignment executed, and an update of the same bits wins. + (source "nba_window.sv" #" + module Top(output logic [31:0] m0, m2, m3, m5, q, r); + bit clk = 1'b0; + bit en = 1'b0; + bit [3:0] i = 4'd0; + bit [4:0] k = 5'd3; + bit [31:0] mem [16]; + bit [31:0] q_, r_; + always #5 clk = ~clk; + always @(posedge clk) begin + mem[i][15:8] <= 8'h44; + mem[i + 2] <= 32'h11; + if (en) q_ <= 32'h11; + r_[k] <= 1'b1; + end + initial begin + for (int j = 0; j < 16; j++) mem[j] = 0; + q_ = 0; + r_ = 0; + @(posedge clk); + #0; + mem[0][7:0] = 8'h22; + mem[2][31:24] = 8'h77; + mem[3] = 32'h33; + mem[5][7:0] = 8'h55; + q_ = 32'h66; + r_[20] = 1'b1; + end + assign m0 = mem[0]; + assign m2 = mem[2]; + assign m3 = mem[3]; + assign m5 = mem[5]; + assign q = q_; + assign r = r_; + endmodule + "#) + (top Top) + (run_until 6) + (assert_eq m0 0x4422) + (assert_eq m2 0x11) + (assert_eq m3 0x33) + (assert_eq m5 0x55) + (assert_eq q 0x66 "no nonblocking assignment to q executed") + (assert_eq r 0x100008)) + +(case edge_nonblocking_updates_follow_writes_their_blocking_results_wake + ; The edge process's blocking result wakes a waiting process in the + ; active region, before the NBA region (IEEE 1800-2023 4.5). Its write + ; stays where no nonblocking assignment executed. + (source "nba_active_window.sv" #" + module Top(output logic [7:0] q, output logic [7:0] p); + bit clk = 1'b0; + bit flag = 1'b0; + bit en = 1'b0; + bit [7:0] q_ = 8'd0, p_ = 8'd0; + always #5 clk = ~clk; + always @(posedge clk) begin + flag = 1'b1; + if (en) q_ <= 8'h11; + p_ <= 8'h44; + end + initial begin + @(posedge flag); + q_ = 8'h22; + p_ = 8'h33; + end + assign q = q_; + assign p = p_; + endmodule + "#) + (top Top) + (run_until 6) + (assert_eq q 0x22) + (assert_eq p 0x44 "the nonblocking update is later")) + +(case edge_blocking_results_precede_later_process_writes + ; A blocking assignment of an edge process takes effect when it executes: + ; a zero-delay resumption that writes the variable afterwards, without + ; reading it, leaves its own value. + (source "blocking_window.sv" #" + module Top(output logic [7:0] t); + bit clk = 1'b0; + bit [7:0] t_ = 8'd0; + always #5 clk = ~clk; + always @(posedge clk) t_ = 8'h11; + initial begin + @(posedge clk); + #0; + t_ = 8'h22; + end + assign t = t_; + endmodule + "#) + (top Top) + (run_until 6) + (assert_eq t 0x22)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 83bcaca0f58..2ab8a3bccde 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -776,6 +776,20 @@ sv_backends! { } } +sv_backends! { + fn edge_nonblocking_updates_keep_later_writes_of_other_bits(sim) { + @case "timing::edge_nonblocking_updates_keep_later_writes_of_other_bits"; + } + + fn edge_nonblocking_updates_follow_writes_their_blocking_results_wake(sim) { + @case "timing::edge_nonblocking_updates_follow_writes_their_blocking_results_wake"; + } + + fn edge_blocking_results_precede_later_process_writes(sim) { + @case "timing::edge_blocking_results_precede_later_process_writes"; + } +} + /// An edge whose evaluation a `$fatal` ends before its commit leaves no /// held write of a watched variable behind: when the host continues, the /// later edges rewrite `y[0]` to its own value and wake no waiter. From 981aaa49eaeba75df71ac261166c356b5f2ba88b Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 15:21:49 +0900 Subject: [PATCH 9/9] perf(runtime)!: run the derived clock edges of ticks in generated units An edge of an event whose derived clock domains have a plan the derived-edge generator emits (two-state, gated clocks with gate programs) now runs as one generated unit per edge direction instead of the Rust walk of DerivedTickPlan: Simulator::edge, and so tick, posedge and negedge, move the signal, set the scheduler's dirty flag to tell the unit whether to settle first, and run the unit. Coincident edges (edges, tick_events) and other plans keep the walk, as do timed simulations with $finish sites, designs with comb observers or fatal comb assertions. The units are on by default from O1 up. A new selector, SirPass::DerivedEdgeUnits ("derived_edge_units", -sir:derived_edge_units in pass overrides), turns them off, trading tick speed for build time: they compile the clock's domain once more. The tiered backend's baseline image leaves them out and walks the plans until the optimizing image, which has them, is adopted (SimBackend::runs_derived_edge_units). tick_semantics now runs every host operation both ways against the timed reference, with a divider and a gate whose enable the clock's own domain raises. The coincident case of that gate is checked against Icarus and ignored until the timed reference sees its edge (#1860). BREAKING CHANGE: RuntimeSchema has a new field, derived_edges, and DerivedEdgeUnits is new; SirPass has a new variant, DerivedEdgeUnits. Native images use container format 34; images written by earlier versions must be rebuilt. Change-Id: I3436fa1ddc580c66794b40a26866c297ef9cde98 --- CLAUDE.md | 1 + crates/celox-design/src/lib.rs | 17 + .../src/symbolic/assembly.rs | 1 + crates/celox-runtime/src/backend.rs | 7 + crates/celox-sir-opt/src/policy.rs | 15 +- crates/celox/src/backend/native/backend.rs | 22 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/backend/tiered.rs | 21 +- crates/celox/src/derived_edge.rs | 420 ++++++++++++++---- crates/celox/src/lib.rs | 2 - crates/celox/src/simulator.rs | 103 +++++ crates/celox/src/simulator/builder.rs | 8 + crates/celox/tests/tick_semantics.rs | 101 ++++- crates/celox/tests/tiered.rs | 93 ++++ docs/internals/optimizations.md | 6 + packages/celox/src/types.ts | 5 +- 16 files changed, 690 insertions(+), 134 deletions(-) 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/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-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/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/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/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"] */