From 397d9c13b7adaebbc496d639f7bd630502efba0e Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 01:36:38 +0900 Subject: [PATCH 1/8] ci(sv): run upstream popcount testbench in daily checks Extend the existing pinned common_cells gate from Gray code to include the unmodified cc_popcount_tb. Its widths 1, 5, 16, 32, 64 and 981 exercise unconstrained scope randomization, #5ns delays and assertions against $countones through celox run --project. No 981-bit limit is imposed by the randomizer. Require both original testbenches to pass, then mutate separate RTL copies and require both to fail with their own assertion diagnostics and the CLI's runtime assertion-failure summary. Compilation errors quoting the diagnostic text cannot satisfy a negative control. Keep the existing upstream pin, per-run timeout and result fields, and list both testbenches in the final report. Extend script tests to cover failures specific to the popcount positive and negative executions and quoted compile diagnostics. Document reproduction and retained logs. The existing scheduled/manual CI job picks up the expanded gate. Validation: Node script tests; all four real executions against common_cells e73baaec2ca665cd80c3c384e9258e35242b829c passed their positive/negative expectations; upstream tracked files remain unchanged. Formatting and affected Rust checks passed in the lower stack members. Change-Id: Ib70fd8211aa5a1a6cdfc2641409e0da8db0b35f2 --- conformance/common-cells/README.md | 15 +++++++++++---- scripts/run-common-cells.mjs | 24 ++++++++++++++++++++---- scripts/run-common-cells.test.mjs | 18 +++++++++++++++--- 3 files changed, 46 insertions(+), 11 deletions(-) diff --git a/conformance/common-cells/README.md b/conformance/common-cells/README.md index e4105d2da11..eec535ddb97 100644 --- a/conformance/common-cells/README.md +++ b/conformance/common-cells/README.md @@ -1,6 +1,6 @@ # Upstream SystemVerilog testbench smoke test -Daily full CI runs the unmodified `cc_graycode_tb` from +Daily full CI runs the unmodified `cc_graycode_tb` and `cc_popcount_tb` from [PULP common_cells](https://github.com/pulp-platform/common_cells), pinned by [`revision`](revision). The same job runs on manual `ci.yml` dispatches and on develop's nightly full CI. It exercises the `celox run --project` CLI with the @@ -11,9 +11,15 @@ task, and immediate assertions. It checks binary/Gray round trips and changes in the Gray code population count. This is a small combinational design smoke test, not coverage of all common_cells modules or clocked testbenches. +The popcount TB covers widths 1, 5, 16, 32, 64, and 981 with unconstrained +scope randomization, explicit-unit `#5ns` delays, and immediate assertions +comparing the RTL with `$countones`. The randomizer supports arbitrary packed +widths; 981 is this upstream test's largest vector, not an implementation limit. + The gate first requires the original RTL/TB to exit successfully. It then forces -the Gray encoder output to zero in a separate RTL copy and requires exit code 1 -with an assertion diagnostic. Compilation errors, crashes and timeouts do not +the Gray encoder output to zero and disables popcount accumulation in separate +RTL copies, requiring exit code 1 with the corresponding assertion diagnostic +for each. Compilation errors, crashes and timeouts do not satisfy this negative control. Upstream files are never edited. Each execution has a two-minute wall timeout and the CLI's default scheduler step limit. @@ -29,7 +35,8 @@ node scripts/run-common-cells.mjs work/common-cells target/debug/celox work/comm ``` The output directory contains the generated `celox.toml`, negative-control -sources, both logs, and a `result.json` written only after both checks pass. +sources, the popcount manifests, four logs, and a `result.json` written only after all +four executions pass their positive or negative expectations. Use a fresh output directory for each run. CI retains this directory for 14 days, including on failure; failures feed the existing Full CI issue reporter. diff --git a/scripts/run-common-cells.mjs b/scripts/run-common-cells.mjs index ca6bb5333f8..c6e4d3ca0cb 100644 --- a/scripts/run-common-cells.mjs +++ b/scripts/run-common-cells.mjs @@ -22,18 +22,19 @@ export function run({ source, celox, output }) { if (head.status !== 0 || head.stdout.trim() !== revision) { throw new Error(`Expected common_cells revision ${revision}; fetch the pinned checkout first`); } - const manifest = (files) => `sources = [${files.map((file) => JSON.stringify(file)).join(", ")}]\ntop = "cc_graycode_tb"\n`; + const manifest = (files, top = "cc_graycode_tb") => `sources = [${files.map((file) => JSON.stringify(file)).join(", ")}]\ntop = ${JSON.stringify(top)}\n`; const original = sources.map((file) => join(source, file)); const project = join(output, "celox.toml"); writeFileSync(project, manifest(original)); - const execute = (name, projectFile, negative = false) => { + const execute = (name, projectFile, negative = false, diagnostic = "assert failed") => { const result = spawnSync(celox, ["run", "--project", projectFile], { encoding: "utf8", timeout: 120_000, maxBuffer: 8 * 1024 * 1024, }); const log = `${result.stdout ?? ""}${result.stderr ?? ""}`; writeFileSync(join(output, `${name}.log`), log); if (result.error || result.signal || (negative - ? result.status !== 1 || !log.includes("assert failed") + ? result.status !== 1 || !log.includes(diagnostic) + || !log.includes("SystemVerilog testbench reported an assertion failure or $error") : result.status !== 0)) { throw new Error(`${name} failed (exit ${result.status}, signal ${result.signal}): ${result.error ?? log}`); } @@ -49,10 +50,25 @@ export function run({ source, celox, output }) { const negativeProject = join(output, "negative.toml"); writeFileSync(negativeProject, manifest([broken, ...original.slice(1)])); execute("graycode-negative", negativeProject, true); + const popcount = join(source, "src/cc_popcount.sv"); + const popcountTb = join(source, "test/cc_popcount_tb.sv"); + const popcountProject = join(output, "popcount.toml"); + writeFileSync(popcountProject, manifest([popcount, popcountTb], "cc_popcount_tb")); + execute("popcount", popcountProject); + + const popcountText = readFileSync(popcount, "utf8"); + const increment = "popcount_o += data_i[i];"; + if (popcountText.split(increment).length !== 2) throw new Error("Cannot locate the pinned popcount accumulation"); + const brokenPopcount = join(output, "negative_popcount.sv"); + writeFileSync(brokenPopcount, popcountText.replace(increment, "popcount_o += 0;")); + const negativePopcountProject = join(output, "popcount-negative.toml"); + writeFileSync(negativePopcountProject, manifest([brokenPopcount, popcountTb], "cc_popcount_tb")); + execute("popcount-negative", negativePopcountProject, true, "Popcount of"); writeFileSync(join(output, "result.json"), `${JSON.stringify({ revision, top: "cc_graycode_tb", positive: "passed", negative: "assertion failure detected", + testbenches: ["cc_graycode_tb", "cc_popcount_tb"], }, null, 2)}\n`); - console.log(`common_cells ${revision}: upstream Gray code TB passed; broken RTL rejected`); + console.log(`common_cells ${revision}: upstream Gray code and popcount TBs passed; both broken RTL copies rejected`); } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { diff --git a/scripts/run-common-cells.test.mjs b/scripts/run-common-cells.test.mjs index 35948733316..6614de22602 100644 --- a/scripts/run-common-cells.test.mjs +++ b/scripts/run-common-cells.test.mjs @@ -18,20 +18,28 @@ test("upstream gate rejects wrong revisions, broken positives, and false negativ writeFileSync(join(source, "src/cc_binary_to_gray.sv"), original); writeFileSync(join(source, "src/cc_gray_to_binary.sv"), ""); writeFileSync(join(source, "test/cc_graycode_tb.sv"), ""); + const popcountOriginal = "popcount_o += data_i[i];"; + writeFileSync(join(source, "src/cc_popcount.sv"), popcountOriginal); + writeFileSync(join(source, "test/cc_popcount_tb.sv"), ""); writeFileSync(join(bin, "git"), `#!/usr/bin/env node\nconsole.log(process.env.TEST_REVISION || ${JSON.stringify(revision)});\n`); const celox = join(bin, "celox"); writeFileSync(celox, `#!/usr/bin/env node const negative = process.argv.at(-1).endsWith("negative.toml"); const mode = process.env.TEST_MODE; +const popcount = process.argv.at(-1).endsWith("popcount.toml") || process.argv.at(-1).endsWith("popcount-negative.toml"); +if (popcount && mode === "popcount-positive-failure" && !negative) process.exit(1); +if (popcount && mode === "popcount-false-pass" && negative) process.exit(0); if (!negative) process.exit(mode === "positive-failure" ? 1 : 0); if (mode === "false-pass") process.exit(0); if (mode === "compile-error") { console.error("compilation failed"); process.exit(1); } +if (mode === "quoted-compile-error") { console.error("compilation failed: source contains assert failed / Popcount of"); process.exit(1); } if (mode === "crash") { process.kill(process.pid, "SIGTERM"); } -console.error("assert failed"); process.exit(1); +console.error(popcount ? "Popcount of 1 was 0 but should be 1" : "assert failed"); +console.error("SystemVerilog testbench reported an assertion failure or $error"); process.exit(1); `); chmodSync(join(bin, "git"), 0o755); chmodSync(celox, 0o755); - for (const mode of ["success", "positive-failure", "false-pass", "compile-error", "crash", "wrong-revision"]) { + for (const mode of ["success", "positive-failure", "false-pass", "compile-error", "quoted-compile-error", "crash", "wrong-revision", "popcount-positive-failure", "popcount-false-pass"]) { const output = join(root, mode); const result = spawnSync(process.execPath, [resolve("scripts/run-common-cells.mjs"), source, celox, output], { encoding: "utf8", @@ -40,11 +48,15 @@ console.error("assert failed"); process.exit(1); }); assert.equal(result.status, mode === "success" ? 0 : 1, `${mode}: ${result.stderr}`); if (mode === "success") { - assert.equal(JSON.parse(readFileSync(join(output, "result.json"))).positive, "passed"); + const report = JSON.parse(readFileSync(join(output, "result.json"))); + assert.equal(report.positive, "passed"); + assert.deepEqual(report.testbenches, ["cc_graycode_tb", "cc_popcount_tb"]); + assert.match(readFileSync(join(output, "popcount-negative.log"), "utf8"), /Popcount of/); assert.match(readFileSync(join(output, "graycode-negative.log"), "utf8"), /assert failed/); } } assert.equal(readFileSync(join(source, "src/cc_binary_to_gray.sv"), "utf8"), original); + assert.equal(readFileSync(join(source, "src/cc_popcount.sv"), "utf8"), popcountOriginal); } finally { rmSync(root, { recursive: true, force: true }); } From 96e0a9efe34ce43ece4b95b02cd82750197d6668 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 05:29:27 +0900 Subject: [PATCH 2/8] feat(cli): configure SV parameter literals and simulation state modes Allow CLI and project parameter overrides to preserve signed values, packed strings, explicit widths, unbased fills and X/Z bits. Add the corresponding SimulatorBuilder::param_literal API; numeric overrides keep their existing API and last-value-wins behavior. Reject SV literals for Veryl inputs. Add --two-state/--four-state and four_state in project and target settings, with project < target < CLI precedence. Use two-state simulation as the default. Serialize the selected mode into native executables and normalize VPI X/Z deposits and forces using the effective runtime mode. This lets Taxi's APB-to-AXI-Lite and AXI-to-AXI-Lite adapter tests use the same two-state condition as their upstream Verilator runs. The original 8-bit configurations pass all 12 cocotb tests each at O1; the AXI adapter run takes about 419 seconds. Other remaining Taxi failures are not hidden by this setting. Validation: O2 literal-parameter API regressions across backends; all project CLI tests, including merge precedence, native image round trips and Veryl input rejection; VPI deposits/forces and package tests; affected-crate Clippy and formatting. Also check celox without default features to preserve builds without SystemVerilog support. Change-Id: I349bbcdce9d4747dcac4c19b985b5a29622022b3 --- crates/celox-vpi/src/bin/celox.rs | 7 +- crates/celox-vpi/src/bin/celox/project.rs | 104 +++++++- crates/celox-vpi/src/bin/celox/runner.rs | 4 +- crates/celox-vpi/src/driver.rs | 46 +++- crates/celox-vpi/src/lib.rs | 10 +- crates/celox-vpi/tests/basic_vpi.rs | 66 +++++ crates/celox-vpi/tests/project_cli.rs | 233 +++++++++++++++++- .../celox/src/backend/native/runtime_image.rs | 5 + crates/celox/src/parser.rs | 4 +- crates/celox/src/simulator/builder.rs | 146 +++++++---- .../frontends/systemverilog/hierarchy.rs | 25 ++ docs/guide/cocotb.md | 5 +- docs/ja/guide/cocotb.md | 3 +- 13 files changed, 574 insertions(+), 84 deletions(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 040afeae2ab..99295fba55a 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -156,7 +156,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); let builder = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) - .four_state(arguments.execution.four_state) + .four_state(arguments.design.four_state.unwrap_or(false)) .threads(arguments.execution.threads as usize) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) @@ -403,7 +403,7 @@ fn compile_native_design(design: &Design) -> Result .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); let builder = celox::Simulator::from_sv_sources(refs, &design.top) - .four_state(true) + .four_state(design.four_state.unwrap_or(false)) .diagnostic_policy(design.diagnostics.clone()) .signal_access(design.signal_access.clone()) .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); @@ -427,13 +427,14 @@ fn compile_native_design(design: &Design) -> Result { return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); } - let (image, warnings) = celox_vpi::driver::compile_native_image_with_parameters( + let (image, warnings) = celox_vpi::driver::compile_native_image_with_state( &design.sources[0], &design.top, design.diagnostics.clone(), design.opt_level.unwrap_or(celox::OptLevel::O1), design.signal_access.clone(), &design.parameters, + design.four_state.unwrap_or(false), )?; report_warnings(&warnings)?; Ok(image) diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index 4a46c0528be..f3082b12cb5 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -18,6 +18,12 @@ pub(super) struct DesignArgs { /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] diagnostics: Vec, + /// Use two-state simulation, resolving X/Z to zero. + #[arg(long, conflicts_with = "four_state")] + two_state: bool, + /// Use four-state simulation, overriding the project (default: two-state). + #[arg(long)] + four_state: bool, /// Optimization level: O0, O1, O2 (default: project setting or O2 for run, O1 for vpi build). #[arg(short = 'O', long, value_parser = super::parse_opt_level)] opt_level: Option, @@ -56,7 +62,7 @@ pub(super) struct DesignArgs { /// SystemVerilog macro, NAME or NAME=VALUE (repeatable; last value wins). #[arg(short = 'D', long = "define", value_name = "NAME[=VALUE]")] defines: Vec, - /// Override a numeric top parameter (repeatable; last value wins). + /// Override a top parameter with an integer or SV literal (repeatable; last value wins). #[arg( short = 'G', long = "parameter", @@ -95,6 +101,7 @@ struct Manifest { parameters: BTreeMap, top: Option, opt_level: Option, + four_state: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -127,6 +134,7 @@ struct Target { parameters: BTreeMap, top: Option, opt_level: Option, + four_state: Option, live_signals: Option>, force_signals: Option>, max_steps: Option, @@ -140,8 +148,10 @@ pub(super) struct Design { pub include_dirs: Vec, pub defines: BTreeMap, pub parameters: BTreeMap, + sv_parameters: BTreeMap, pub top: String, pub opt_level: Option, + pub four_state: Option, pub signal_access: celox::SignalAccessOptions, pub max_steps: Option, } @@ -275,6 +285,7 @@ impl DesignArgs { design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); design.max_steps = config.max_steps; + design.four_state = config.four_state; if let Some(target) = selected { design.extend_parameters(&target.parameters)?; design.diagnostics.0.extend(target.diagnostics.0.clone()); @@ -296,6 +307,7 @@ impl DesignArgs { design.signal_access.force_signals.clone_from(paths); } design.max_steps = target.max_steps.or(design.max_steps); + design.four_state = target.four_state.or(design.four_state); } design.opt_level = opt_level .map(|value| { @@ -322,6 +334,12 @@ impl DesignArgs { } })); design.opt_level = self.opt_level.or(design.opt_level); + if self.two_state { + design.four_state = Some(false); + } + if self.four_state { + design.four_state = Some(true); + } if self.no_live_signals { design.signal_access.live_signals.clear(); } else if !self.live_signals.is_empty() { @@ -359,7 +377,7 @@ impl DesignArgs { let (name, value) = parameter .split_once('=') .ok_or_else(|| format!("invalid parameter `{parameter}`: expected NAME=VALUE"))?; - design.set_parameter(name, parse_parameter_value(value)?)?; + design.set_parameter_text(name, value, false)?; } if let Some(top) = self.top { design.top = top; @@ -372,6 +390,9 @@ impl DesignArgs { if design.top.trim().is_empty() { return Err("provide --top MODULE or set top in celox.toml".to_string()); } + if !design.is_sv() && !design.sv_parameters.is_empty() { + return Err("SV parameter literals require .sv/.v sources".to_string()); + } if !design.is_sv() && (!design.include_dirs.is_empty() || !design.defines.is_empty()) { return Err( "include directories and defines require SystemVerilog sources".to_string(), @@ -381,12 +402,13 @@ impl DesignArgs { } } -/// TOML integers cover ordinary values; strings also permit radix prefixes -/// and the full unsigned 64-bit range supported by SimulatorBuilder::param. +/// Preserve ordinary integer settings while admitting signed SV literals and +/// textual parameters without losing their width or signedness. #[derive(Deserialize)] #[serde(untagged)] enum ParameterValue { Integer(u64), + Signed(i64), String(String), } @@ -424,6 +446,9 @@ impl Design { for (name, value) in &self.parameters { builder = builder.param(name, *value); } + for (name, literal) in &self.sv_parameters { + builder = builder.param_literal(name, literal); + } builder } @@ -432,16 +457,25 @@ impl Design { parameters: &BTreeMap, ) -> Result<(), String> { for (name, value) in parameters { - let value = match value { - ParameterValue::Integer(value) => *value, - ParameterValue::String(value) => parse_parameter_value(value)?, - }; - self.set_parameter(name, value)?; + match value { + ParameterValue::Integer(value) => self.set_parameter(name, *value)?, + ParameterValue::Signed(value) => { + self.set_parameter_text(name, &value.to_string(), false)? + } + ParameterValue::String(value) => self.set_parameter_text(name, value, true)?, + } } Ok(()) } fn set_parameter(&mut self, name: &str, value: u64) -> Result<(), String> { + Self::validate_parameter_name(name)?; + self.sv_parameters.remove(name); + self.parameters.insert(name.to_string(), value); + Ok(()) + } + + fn validate_parameter_name(name: &str) -> Result<(), String> { if name.is_empty() || !name.bytes().enumerate().all(|(index, byte)| { byte == b'_' @@ -451,10 +485,60 @@ impl Design { { return Err(format!("invalid top parameter name `{name}`")); } - self.parameters.insert(name.to_string(), value); Ok(()) } + fn set_parameter_text( + &mut self, + name: &str, + text: &str, + bare_string: bool, + ) -> Result<(), String> { + if let Ok(value) = parse_parameter_value(text) { + return self.set_parameter(name, value); + } + #[cfg(feature = "systemverilog")] + { + let literal = if celox_sv_analyzer::typecheck::parse_parameter_literal(text).is_some() { + text.to_string() + } else if bare_string { + // TOML strings are ordinary string values unless they spell a + // numeric literal. Encode bytes using SV's escape rules. + let mut quoted = String::from("\""); + for byte in text.bytes() { + match byte { + b'"' => quoted.push_str("\\\""), + b'\\' => quoted.push_str("\\\\"), + b'\n' => quoted.push_str("\\n"), + b'\t' => quoted.push_str("\\t"), + 32..=126 => quoted.push(char::from(byte)), + 0..=127 => quoted.push_str(&format!("\\{byte:03o}")), + _ => return Err(format!("non-ASCII string parameter `{name}`")), + } + } + quoted.push('"'); + quoted + } else { + return Err(format!( + "invalid parameter value `{text}`: expected an unsigned 64-bit integer or SV literal" + )); + }; + // Reuse the name validation and remove whichever representation a + // lower-precedence project or target setting used. + Self::validate_parameter_name(name)?; + self.parameters.remove(name); + self.sv_parameters.insert(name.to_string(), literal); + Ok(()) + } + #[cfg(not(feature = "systemverilog"))] + { + let _ = (name, bare_string); + Err(format!( + "invalid parameter value `{text}`: SV literals require the systemverilog feature" + )) + } + } + pub fn is_sv(&self) -> bool { !self.sources.is_empty() && self.sources.iter().all(|path| { diff --git a/crates/celox-vpi/src/bin/celox/runner.rs b/crates/celox-vpi/src/bin/celox/runner.rs index b3bc75ac7ae..802e60033c9 100644 --- a/crates/celox-vpi/src/bin/celox/runner.rs +++ b/crates/celox-vpi/src/bin/celox/runner.rs @@ -33,8 +33,6 @@ pub(super) struct ExecutionArgs { #[arg(long, value_enum, default_value = "native")] pub backend: Backend, #[arg(long)] - pub four_state: bool, - #[arg(long)] compile_only: bool, /// Write a pointer-free native image during compile-only mode. #[arg(long, value_name = "PATH")] @@ -197,7 +195,7 @@ pub(super) fn run( test: design.top.clone(), opt_level: design.opt_level.unwrap_or(OptLevel::O2), backend: cli.backend, - four_state: cli.four_state, + four_state: design.four_state.unwrap_or(false), compile_only: cli.compile_only, native_image_output: cli.native_image_output, native_image_input: cli.native_image_input, diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index 350ecd6912f..c7bd819169c 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -60,7 +60,10 @@ pub fn compile_native_image_with_diagnostics( policy, celox::OptLevel::O0, celox::SignalAccessOptions::default(), - true, + CompileMode { + legacy_force: true, + four_state: true, + }, &BTreeMap::new(), ) } @@ -85,16 +88,45 @@ pub fn compile_native_image_with_parameters( access: celox::SignalAccessOptions, parameters: &BTreeMap, ) -> Result<(NativeProgramImage, Vec), String> { - compile_native_image_configured(source, top, policy, level, access, false, parameters) + compile_native_image_with_state(source, top, policy, level, access, parameters, true) } -fn compile_native_image_configured( +/// Compile numeric parameters with an explicit four-state simulation mode. +pub fn compile_native_image_with_state( source: &Path, top: &str, policy: DiagnosticPolicy, level: celox::OptLevel, access: celox::SignalAccessOptions, + parameters: &BTreeMap, + four_state: bool, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured( + source, + top, + policy, + level, + access, + CompileMode { + legacy_force: false, + four_state, + }, + parameters, + ) +} + +struct CompileMode { legacy_force: bool, + four_state: bool, +} + +fn compile_native_image_configured( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, + mode: CompileMode, parameters: &BTreeMap, ) -> Result<(NativeProgramImage, Vec), String> { let compiled = if let Ok(metadata_path) = Metadata::search_from(source) { @@ -118,8 +150,8 @@ fn compile_native_image_configured( let builder = Simulator::from_sources(source_refs, top) .with_metadata(metadata) .diagnostic_policy(policy.clone()) - .four_state(true) - .native_force_support(legacy_force) + .four_state(mode.four_state) + .native_force_support(mode.legacy_force) .signal_access(access.clone()) .opt_level(level); parameters @@ -133,8 +165,8 @@ fn compile_native_image_configured( .map_err(|error| format!("failed to read {}: {error}", source.display()))?; let builder = Simulator::from_sources(vec![(contents.as_str(), source)], top) .diagnostic_policy(policy.clone()) - .four_state(true) - .native_force_support(legacy_force) + .four_state(mode.four_state) + .native_force_support(mode.legacy_force) .signal_access(access.clone()) .opt_level(level); parameters diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 7b72d33a241..b35a0804a69 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -1312,10 +1312,12 @@ pub unsafe extern "C" fn vpi_put_value( } let signal_info = with_runtime(|runtime| { - runtime - .reflection() - .signal(id) - .map(|signal| (signal.signal.width, signal.signal.is_4state)) + runtime.reflection().signal(id).map(|signal| { + ( + signal.signal.width, + signal.signal.is_4state && runtime.four_state(), + ) + }) }) .flatten(); let Some((width, is_4state)) = signal_info else { diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index fe2ef1926b0..b0dd703a978 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3088,3 +3088,69 @@ fn interface_members_are_navigable_after_native_image_round_trip() { } } } + +#[cfg(feature = "systemverilog")] +#[test] +fn two_state_image_converts_unknown_logic_deposits_and_forces() { + let _serial = lock_vpi(); + let source = "module Top(input logic[3:0] a,output logic[3:0] y); assign y=a; endmodule"; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("two_state.sv"))], "Top") + .four_state(false) + .native_force_support(true) + .build() + .unwrap(); + let _session = install_runtime(trusted_instance( + simulator.shared_code().program_image().clone(), + )) + .unwrap(); + unsafe { + let a = vpi_handle_by_name(c"Top.a".as_ptr(), ptr::null_mut()); + let y = vpi_handle_by_name(c"Top.y".as_ptr(), ptr::null_mut()); + let mut word = VpiVecVal { aval: 15, bval: 10 }; + let input = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { vector: &mut word }, + }; + let mut output = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { integer: 0 }, + }; + assert_eq!(vpi_put_value(a, &input, ptr::null(), VPI_NO_DELAY), a); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 5); + assert_eq!((*output.value.vector).bval, 0); + let mut force_word = VpiVecVal { aval: 15, bval: 5 }; + let force_value = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { + vector: &mut force_word, + }, + }; + assert_eq!( + vpi_put_value(a, &force_value, ptr::null(), VPI_FORCE_FLAG), + a + ); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 10); + assert_eq!((*output.value.vector).bval, 0); + let mut deposited_word = VpiVecVal { aval: 15, bval: 12 }; + let deposited_value = VpiValue { + format: VPI_VECTOR_VAL, + value: VpiValueData { + vector: &mut deposited_word, + }, + }; + assert_eq!( + vpi_put_value(a, &deposited_value, ptr::null(), VPI_NO_DELAY), + a + ); + assert_eq!(vpi_put_value(a, &input, ptr::null(), VPI_RELEASE_FLAG), a); + vpi_get_value(y, &mut output); + assert_eq!((*output.value.vector).aval, 3); + assert_eq!((*output.value.vector).bval, 0); + vpi_free_object(a); + vpi_free_object(y); + } + clear_runtime(); +} diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index bf043129c4f..06be274810f 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -583,18 +583,231 @@ fn top_parameters_reach_veryl_run_and_native_build() { fn invalid_parameter_assignments_are_rejected() { let root = tempfile::tempdir().unwrap(); for value in [ - "V", - "=1", - "x.y=1", - "V=", - "V=-1", - "V=1+2", - "V=18446744073709551616", - "V=0x", - "V=0b2", - "V=_1", + "V", "=1", "x.y=1", "V=", "V=--1", "V=1+2", "V=8'hG", "V=0x", "V=0b2", "V=_1", ] { let output = invoke(root.path(), &["run", "dut.sv", "--top", "Top", "-G", value]); rejected(&output, "parameter"); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { + let root = tempfile::tempdir().unwrap(); + let source = r#" + module Top #(parameter VENDOR="GENERIC", parameter NEG=3, + parameter logic [64:0] WIDE=0, parameter logic [11:0] FILL=0, + parameter logic [3:0] UNKNOWN=0)(output logic matched); + assign matched=(VENDOR == "XILINX") && (NEG == -8) && (NEG < 0) + && ($bits(NEG) == 32) && ($bits(VENDOR) == 48) + && (WIDE == 65'h10000000000000001) && (FILL == 12'hfff) + && (UNKNOWN === 4'b10xz); + initial begin #1; assert(matched) else $fatal(1,"literal parameter types"); + $display("ok"); $finish; end + endmodule + "#; + fs::write(root.path().join("top.sv"), source).unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" + sources=["top.sv"] + top="Top" + [parameters] + VENDOR="GENERIC" + NEG=3 + FILL=0 + [targets.literals.parameters] + VENDOR="XILINX" + NEG=-8 + WIDE="65'h10000000000000001" + FILL="'1" + UNKNOWN="4'b10xz" + "#, + ) + .unwrap(); + let output = invoke(root.path(), &["run", "--target", "literals"]); + success(&output); + assert_eq!(output.stdout, b"ok\n"); + let args = [ + "--target", + "literals", + "-GVENDOR=0", + "-GVENDOR=\"XILINX\"", + "-GNEG=8", + "-GNEG=-8", + "-GFILL=0", + "-GFILL='1", + ]; + let output = invoke(root.path(), &[&["run"][..], &args].concat()); + success(&output); + assert_eq!(output.stdout, b"ok\n"); + success(&invoke( + root.path(), + &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into the image above. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + let matched = instance.signal_ref("Top.matched").unwrap(); + assert_eq!( + celox::SimBackend::get_as::(instance.backend(), matched), + 1 + ); + assert_eq!( + fs::read_to_string(root.path().join("top.sv")).unwrap(), + source + ); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn state_mode_merges_project_target_and_cli_for_run_and_native_build() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#" + module Top(output logic[3:0] y); + logic[3:0] uninitialized; + assign y=uninitialized; + initial begin #1; $display("value=%b",y); $finish; end + endmodule + "#, + ) + .unwrap(); + fs::write( + root.path().join("celox.toml"), + "sources=['top.sv']\ntop='Top'\nfour_state=true\n[targets.two]\nfour_state=false\n", + ) + .unwrap(); + for (args, expected, is_four) in [ + (vec![], "value=xxxx\n", true), + (vec!["--two-state"], "value=0000\n", false), + (vec!["--target", "two"], "value=0000\n", false), + ( + vec!["--target", "two", "--four-state"], + "value=xxxx\n", + true, + ), + ] { + let run = invoke(root.path(), &[&["run"][..], &args].concat()); + success(&run); + assert_eq!(String::from_utf8(run.stdout).unwrap(), expected); + success(&invoke( + root.path(), + &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into this image. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert_eq!(instance.four_state(), is_four); + let (value, mask) = celox::SimBackend::get_four_state( + instance.backend(), + instance.signal_ref("Top.y").unwrap(), + ); + assert_eq!( + mask.to_u64_digits(), + if is_four { vec![15] } else { vec![] } + ); + if !is_four { + assert_eq!(value.to_u64_digits(), Vec::::new()); + } + } +} + +#[test] +fn sv_literal_parameters_are_rejected_for_veryl_in_both_commands() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "module Top #(param W:u32=8) (y:output logic) { assign y=0; }", + ) + .unwrap(); + for prefix in [&["run"][..], &["vpi", "build"][..]] { + let output = invoke( + root.path(), + &[prefix, &["top.veryl", "--top", "Top", "-GW=-8"]].concat(), + ); + rejected(&output, "SV parameter literals require"); + } +} + +#[test] +fn veryl_native_images_preserve_the_selected_state_mode() { + for with_metadata in [false, true] { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "module Top (y:output logic<4>) { assign y=3; }", + ) + .unwrap(); + if with_metadata { + fs::write( + root.path().join("Veryl.toml"), + "[project]\nname='state_mode'\nversion='0.1.0'\n", + ) + .unwrap(); + } + for (flag, four_state) in [("--two-state", false), ("--four-state", true)] { + let output = invoke( + root.path(), + &[ + "vpi", + "build", + "top.veryl", + "--top", + "Top", + flag, + "-o", + "sim", + ], + ); + success(&output); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI compiled this test's source into this image. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert_eq!(instance.four_state(), four_state); + } + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_cli_defaults_to_two_state_for_run_and_native_images() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.sv"), + r#"module Top(output logic[3:0] y); + logic[3:0] uninitialized; + assign y=uninitialized; + initial begin #1; $display("value=%b", y); $finish; end + endmodule"#, + ) + .unwrap(); + let run = invoke(root.path(), &["run", "top.sv", "--top", "Top"]); + success(&run); + assert_eq!(run.stdout, b"value=0000\n"); + success(&invoke( + root.path(), + &["vpi", "build", "top.sv", "--top", "Top", "-o", "sim"], + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: this test compiled the source into the image above. + let instance = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + assert!(!instance.four_state()); +} diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 271f4523a44..3e1bc73d563 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -108,6 +108,11 @@ impl NativeProgramInstance { self.shared.program_image().time_precision() } + /// Whether the attached image executes with four-state values. + pub fn four_state(&self) -> bool { + self.shared.program_image().four_state() + } + /// Elaborated hierarchy and signal metadata embedded by the compiler. pub fn reflection(&self) -> &DesignReflection { self.shared.program_image().reflection() diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 1072ec8ad5f..36c5b0bc558 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -573,7 +573,7 @@ pub fn parse( pub fn parse_sv( sources: &[(&str, &std::path::Path)], top: &str, - parameter_overrides: &[(String, u64)], + parameter_overrides: &[(String, celox_frontend_sv::analyzer_ir::ConstExpr)], _config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), @@ -599,7 +599,7 @@ pub fn parse_sv( ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); - let scheduled = celox_frontend_sv::schedule_sources_with_force_signals( + let scheduled = celox_frontend_sv::schedule_sources_with_parameter_expressions( sources, top, parameter_overrides, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 96414337517..89059ee1f19 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1081,6 +1081,7 @@ pub fn compile_sv_to_sir( &crate::DiagnosticPolicy::default(), crate::backend::memory_layout::MemoryLayoutMode::Packed, &[], + &[], ) } @@ -1110,7 +1111,24 @@ fn compile_sv_to_sir_with_layout_mode( diagnostic_policy: &crate::DiagnosticPolicy, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, force_signals: &[String], + sv_param_literals: &[(String, String)], ) -> Result<(OptimizedSir, Vec), SimulatorError> { + let mut parameters = param_overrides + .iter() + .map(|(name, value)| { + ( + name.clone(), + celox_frontend_sv::analyzer_ir::ConstExpr::Literal(value.to_string()), + ) + }) + .collect::>(); + for (name, literal) in sv_param_literals { + let value = celox_frontend_sv::analyzer_typecheck::parse_parameter_literal(literal) + .ok_or_else(|| { + crate::CodegenError::message(format!("invalid SV parameter literal `{literal}`")) + })?; + parameters.push((name.clone(), value)); + } let metadata = metadata.unwrap_or_else(|| Metadata::create_default("prj").unwrap()); let mut build_config = BuildConfig::from(&metadata.build); if let Some(clock_type) = clock_type { @@ -1124,7 +1142,7 @@ fn compile_sv_to_sir_with_layout_mode( let sir = parser::parse_sv( sources, top, - param_overrides, + ¶meters, &build_config, ignored_loops, true_loops, @@ -1366,7 +1384,14 @@ fn compile_hdl_to_sir_with_layout_mode( allow_always_ff_function_effects: bool, file_dependencies: &celox_frontend_veryl::FileDependencyCollector, force_signals: &[String], + sv_param_literals: &[(String, String)], ) -> Result<(OptimizedSir, Vec), SimulatorError> { + if !sv_param_literals.is_empty() && (!sources.is_empty() || sv_sources.is_empty()) { + return Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", + ) + .into()); + } if !force_signals.is_empty() && !sources.is_empty() { return Err(crate::CodegenError::message( "force_signals currently require pure SystemVerilog sources", @@ -1438,6 +1463,7 @@ fn compile_hdl_to_sir_with_layout_mode( diagnostic_policy, layout_mode, force_signals, + sv_param_literals, ), (false, false) => compile_mixed_to_sir_with_layout_mode( sources, @@ -1804,6 +1830,7 @@ mod host { clock_type: Option, reset_type: Option, param_overrides: Vec<(String, u64)>, + sv_param_literals: Vec<(String, String)>, live_signals: Vec<(Vec<(String, usize)>, Vec)>, injected_components: crate::InjectedComponents, frontend_artifact: Option, @@ -1885,10 +1912,22 @@ mod host { /// Override a top-level module parameter value. pub fn param(mut self, name: &str, value: u64) -> Self { + self.sv_param_literals.retain(|(key, _)| key != name); self.param_overrides.push((name.to_string(), value)); self } + /// Override a pure SV top parameter with a literal, such as `-8`, + /// `8'hff`, `'1`, or `"XILINX"`. The literal's width and signedness + /// are preserved. Invalid literals are reported when building. + pub fn param_literal(mut self, name: &str, literal: &str) -> Self { + self.param_overrides.retain(|(key, _)| key != name); + self.sv_param_literals.retain(|(key, _)| key != name); + self.sv_param_literals + .push((name.to_string(), literal.to_string())); + self + } + /// Make in-process component implementations available as `$comp::`. pub fn with_injected_components(mut self, components: crate::InjectedComponents) -> Self { self.injected_components = components; @@ -2332,6 +2371,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2353,6 +2393,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2375,6 +2416,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2402,6 +2444,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -2428,6 +2471,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), @@ -2455,6 +2499,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), @@ -2509,7 +2554,13 @@ mod host { let phase_timing = self.options.diagnostics.phase_timing; let compile_start = phase_timing.then(crate::timing::now); let injected_manifests = self.injected_components.manifests(); - let compiled = if let Some(artifact) = &self.frontend_artifact { + let compiled = if !self.sv_param_literals.is_empty() && self.frontend_artifact.is_some() + { + Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", + ) + .into()) + } else if let Some(artifact) = &self.frontend_artifact { if self.sources.is_empty() { compile_frontend_to_sir_with_layout_mode( artifact, @@ -2568,6 +2619,7 @@ mod host { self.options.allow_always_ff_function_effects, &self.file_dependencies, &self.options.signal_access.force_signals, + &self.sv_param_literals, ) }; let (program, mut warnings) = compiled @@ -3162,23 +3214,52 @@ mod host { layout_mode }; let injected_manifests = self.injected_components.manifests(); - let program_res = if let Some(artifact) = &self.frontend_artifact { - if self.sources.is_empty() { - compile_frontend_to_sir_with_layout_mode( - artifact, - &self.ignored_loops, - &self.true_loops, - self.options.four_state, - &self.options.trace, - Some(&mut trace), - &self.options.optimize_options, - &self.options.diagnostics, - layout_mode, + let program_res = + if !self.sv_param_literals.is_empty() && self.frontend_artifact.is_some() { + Err(crate::CodegenError::message( + "parameter literals require pure SystemVerilog sources", ) + .into()) + } else if let Some(artifact) = &self.frontend_artifact { + if self.sources.is_empty() { + compile_frontend_to_sir_with_layout_mode( + artifact, + &self.ignored_loops, + &self.true_loops, + self.options.four_state, + &self.options.trace, + Some(&mut trace), + &self.options.optimize_options, + &self.options.diagnostics, + layout_mode, + ) + } else { + compile_frontend_testbench_to_sir_with_layout_mode( + artifact, + &self.sources, + self.top, + &self.ignored_loops, + &self.true_loops, + self.options.four_state, + &self.options.trace, + Some(&mut trace), + self.metadata, + self.clock_type, + self.reset_type, + &self.options.optimize_options, + &self.options.diagnostics, + &self.options.diagnostic_policy, + &injected_manifests, + layout_mode, + !self.options.native_force_support, + self.options.allow_always_ff_function_effects, + &self.file_dependencies, + ) + } } else { - compile_frontend_testbench_to_sir_with_layout_mode( - artifact, + compile_hdl_to_sir_with_layout_mode( &self.sources, + &self.sv_sources, self.top, &self.ignored_loops, &self.true_loops, @@ -3188,6 +3269,7 @@ mod host { self.metadata, self.clock_type, self.reset_type, + &self.param_overrides, &self.options.optimize_options, &self.options.diagnostics, &self.options.diagnostic_policy, @@ -3196,33 +3278,10 @@ mod host { !self.options.native_force_support, self.options.allow_always_ff_function_effects, &self.file_dependencies, + &self.options.signal_access.force_signals, + &self.sv_param_literals, ) - } - } else { - compile_hdl_to_sir_with_layout_mode( - &self.sources, - &self.sv_sources, - self.top, - &self.ignored_loops, - &self.true_loops, - self.options.four_state, - &self.options.trace, - Some(&mut trace), - self.metadata, - self.clock_type, - self.reset_type, - &self.param_overrides, - &self.options.optimize_options, - &self.options.diagnostics, - &self.options.diagnostic_policy, - &injected_manifests, - layout_mode, - !self.options.native_force_support, - self.options.allow_always_ff_function_effects, - &self.file_dependencies, - &self.options.signal_access.force_signals, - ) - }; + }; let program_res = program_res .map_err(|error| error.apply_diagnostic_policy(&self.options.diagnostic_policy)); @@ -3336,6 +3395,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -3357,6 +3417,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: None, @@ -3380,6 +3441,7 @@ mod host { clock_type: None, reset_type: None, param_overrides: Vec::new(), + sv_param_literals: Vec::new(), live_signals: Vec::new(), injected_components: Default::default(), frontend_artifact: Some(artifact), diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 87930fcef09..f1baf76a403 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -362,3 +362,28 @@ fn rejects_feedback_through_the_same_bit_of_child_input() { "#, ); } + +sv_backends! { + fn literal_parameter_api_preserves_width_sign_and_unknowns(sim) { + @setup { + let source = r#" + module Top #(parameter TEXT="default", parameter NEG=0, + parameter logic [11:0] FILL=0, parameter logic [3:0] UNKNOWN=0, + parameter logic [64:0] WIDE=0, parameter FINAL=0)(output logic matched); + assign matched=(TEXT=="XILINX") && ($bits(TEXT)==48) + && (NEG==-8) && (NEG<0) && ($bits(NEG)==32) + && (FILL==12'hfff) && (UNKNOWN===4'b10xz) + && (WIDE==65'h10000000000000001) && (FINAL==7); + endmodule + "#; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("parameter_api.sv"))], "Top") + .param_literal("TEXT", "\"XILINX\"") + .param("NEG", 3).param_literal("NEG", "-8") + .param_literal("FILL", "'1").param_literal("UNKNOWN", "4'b10xz") + .param_literal("WIDE", "65'h10000000000000001") + .param_literal("FINAL", "-1").param("FINAL", 7) + .four_state(true).opt_level(celox::OptLevel::O2); + assert_eq!(sim.get(sim.signal("matched")), BigUint::from(1u8)); + } +} diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index a8e5e399c5e..196f4527c89 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -33,8 +33,9 @@ target/release/celox run test/Top.veryl --top Top ``` For SystemVerilog, pass `.sv` or `.v` sources in compilation order. The command -uses two-state simulation by default (`--four-state` enables X/Z tracking) and runs until `$finish` or no scheduled events -remain. For Veryl, pass one project entry file: Celox discovers `Veryl.toml` +uses two-state simulation by default and runs until `$finish` or no scheduled +events remain. Use `--four-state` or `four_state = true` in `celox.toml` to retain +X/Z values. For Veryl, pass one project entry file: Celox discovers `Veryl.toml` and collects the project's sources and dependencies. A standalone Veryl file also works. Both languages default to two-state simulation. Select the native testbench module with `--top`. Veryl uses the existing native testbench executor; a test may also complete by diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index d0a26bd0fe6..0f37fae4f4b 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -30,8 +30,9 @@ target/release/celox run src/types.sv src/Dut.sv test/Top.sv --top Top target/release/celox run test/Top.veryl --top Top ``` -SVは`.sv`または`.v`をコンパイル順に指定します。既定では2値シミュレーションを使い(`--four-state`でX/Zを扱う4値に切り替え)、 +SVは`.sv`または`.v`をコンパイル順に指定します。既定では2値シミュレーションを使い、 `$finish`または実行待ちイベントがなくなるまで実行します。 +X/Zを保持する場合は`--four-state`または`celox.toml`の`four_state = true`を指定します。 Verylはプロジェクト内の1ファイルを指定すると、`Veryl.toml`から ソースと依存関係を収集します。単独のVerylファイルも使用でき、Verylも既定は2値です。 `--top`にはnative testbenchのモジュール名を指定します。 From 82942e3a1b46af985351740b63b057852346858e Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:35:11 +0900 Subject: [PATCH 3/8] fix(sir-opt): preserve memory and type semantics when hoisting loads Common branch-load hoisting could reuse a predecessor load from before an intervening store, so a subsequent display or comparison observed the old value. It also merged different register types and could move definitions across a successor with another predecessor. Reuse only the latest available matching load, stop across overlapping writes and host interactions, preserve result types, and require the predecessor to dominate both successors. Add direct SIR regressions for intervening stores, bit/logic result types, and multiple predecessors. Validation: optimizer unit suite and all-target clippy; the complete Celox suite also exercises this fix with the dependent FP changes (12,458 passed before updating the stack base). The dependent PR includes the end-to-end combinational display/assertion reproduction. Change-Id: Ic942e7594efecccfac235fdc894549cd151ae4ea --- .../src/optimizer/passes/analysis/shared.rs | 221 +++++++++++++++++- 1 file changed, 211 insertions(+), 10 deletions(-) diff --git a/crates/celox-sir-opt/src/optimizer/passes/analysis/shared.rs b/crates/celox-sir-opt/src/optimizer/passes/analysis/shared.rs index c7f1780afed..0f4b60daba3 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/analysis/shared.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/analysis/shared.rs @@ -192,7 +192,10 @@ pub(in crate::optimizer) fn hoist_common_branch_loads( ) { let mut reg_counter: usize = eu.register_map.keys().map(|r| r.0).max().unwrap_or(0); - #[derive(Clone, Copy)] + let Ok(cfg) = crate::ir::cfg::SirCfg::analyze(eu) else { + return; + }; + #[derive(Clone)] struct Candidate { pred: BlockId, true_block: BlockId, @@ -202,6 +205,7 @@ pub(in crate::optimizer) fn hoist_common_branch_loads( dst_true: RegisterId, dst_false: RegisterId, addr: RegionedAbsoluteAddr, + result_type: RegisterType, } loop { @@ -222,6 +226,18 @@ pub(in crate::optimizer) fn hoist_common_branch_loads( continue; }; + // A single new definition in the predecessor must dominate every + // use formerly reached through either successor's load. + if true_block.0 == false_block.0 + || true_block.0 == bid + || false_block.0 == bid + || [true_block.0, false_block.0].iter().any(|successor| { + *successor == eu.entry_block_id + || cfg.predecessors[cfg.index[successor]].as_slice() != [cfg.index[&bid]] + }) + { + continue; + } let Some(t_block) = eu.blocks.get(&true_block.0) else { continue; }; @@ -240,7 +256,11 @@ pub(in crate::optimizer) fn hoist_common_branch_loads( continue; }; - if addr_t == addr_f && off_t == off_f && bits_t == bits_f { + if addr_t == addr_f + && off_t == off_f + && bits_t == bits_f + && eu.register_map.get(dst_t) == eu.register_map.get(dst_f) + { candidates.push(Candidate { pred: bid, true_block: true_block.0, @@ -250,6 +270,7 @@ pub(in crate::optimizer) fn hoist_common_branch_loads( dst_true: *dst_t, dst_false: *dst_f, addr: *addr_t, + result_type: eu.register_map[dst_t].clone(), }); } } @@ -286,20 +307,34 @@ pub(in crate::optimizer) fn hoist_common_branch_loads( } let existing_reg = eu.blocks.get(&c.pred).and_then(|pred_block| { - pred_block.instructions.iter().find_map(|inst| match inst { - SIRInstruction::Load(dst, addr, SIROffset::Static(off), bits) - if *addr == c.addr && *off == c.offset && *bits == c.bits => + for inst in pred_block.instructions.iter().rev() { + if inst.is_host_interaction() { + return None; + } + if let Some(write) = inst.memory_write() + && *write.addr == c.addr + && write.offset.constant_bit_offset().is_none_or(|offset| { + offset < c.offset.saturating_add(c.bits) + && c.offset < offset.saturating_add(write.width) + }) { - Some(*dst) + return None; } - _ => None, - }) + if let SIRInstruction::Load(dst, addr, SIROffset::Static(off), bits) = inst + && *addr == c.addr + && *off == c.offset + && *bits == c.bits + && eu.register_map.get(dst) == Some(&c.result_type) + { + return Some(*dst); + } + } + None }); let hoisted_reg = existing_reg.unwrap_or_else(|| { let new_reg = next_register_id(&mut eu.register_map, &mut reg_counter); - eu.register_map - .insert(new_reg, RegisterType::Logic { width: c.bits }); + eu.register_map.insert(new_reg, c.result_type.clone()); if let Some(pred_block) = eu.blocks.get_mut(&c.pred) { pred_block.instructions.push(SIRInstruction::Load( @@ -408,3 +443,169 @@ pub(in crate::optimizer) fn batch_replace_in_terminator( SIRTerminator::Return | SIRTerminator::Error(_) => {} } } + +#[cfg(test)] +mod hoist_tests { + use super::*; + use celox_design::{InstanceId, StateObjectId}; + fn fixture( + old_type: RegisterType, + branch_type: RegisterType, + ) -> ExecutionUnit { + let addr = RegionedAbsoluteAddr::from_absolute_addr( + STABLE_REGION, + AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId::default(), + }, + ); + let bit = |width| RegisterType::Bit { + width, + signed: false, + }; + ExecutionUnit { + entry_block_id: BlockId(0), + register_map: [ + (RegisterId(0), old_type), + (RegisterId(1), bit(64)), + (RegisterId(2), bit(1)), + (RegisterId(3), branch_type.clone()), + (RegisterId(4), branch_type), + ] + .into_iter() + .collect(), + blocks: [ + ( + BlockId(0), + BasicBlock { + id: BlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load(RegisterId(0), addr, SIROffset::Static(0), 64), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(1.5f64.to_bits())), + SIRInstruction::Store( + addr, + SIROffset::Static(0), + 64, + RegisterId(1), + vec![], + vec![], + ), + SIRInstruction::Imm(RegisterId(2), SIRValue::new(1u8)), + ], + terminator: SIRTerminator::Branch { + cond: RegisterId(2), + true_block: (BlockId(1), vec![]), + false_block: (BlockId(2), vec![]), + }, + }, + ), + ( + BlockId(1), + BasicBlock { + id: BlockId(1), + params: vec![], + instructions: vec![ + SIRInstruction::Load(RegisterId(3), addr, SIROffset::Static(0), 64), + SIRInstruction::RuntimeEvent { + site_id: 0, + args: vec![RegisterId(3)], + }, + ], + terminator: SIRTerminator::Return, + }, + ), + ( + BlockId(2), + BasicBlock { + id: BlockId(2), + params: vec![], + instructions: vec![ + SIRInstruction::Load(RegisterId(4), addr, SIROffset::Static(0), 64), + SIRInstruction::RuntimeEvent { + site_id: 0, + args: vec![RegisterId(4)], + }, + ], + terminator: SIRTerminator::Return, + }, + ), + ] + .into_iter() + .collect(), + } + } + #[test] + fn hoisting_preserves_read_after_write_and_bit_logic_result_types() { + for old_type in [ + RegisterType::Bit { + width: 64, + signed: false, + }, + RegisterType::Logic { width: 64 }, + ] { + for branch_type in [ + RegisterType::Bit { + width: 64, + signed: false, + }, + RegisterType::Logic { width: 64 }, + ] { + let mut unit = fixture(old_type.clone(), branch_type.clone()); + unit.verify(); + hoist_common_branch_loads(&mut unit); + unit.verify(); + let pred = &unit.blocks[&BlockId(0)]; + let store = pred + .instructions + .iter() + .position(|inst| matches!(inst, SIRInstruction::Store(..))) + .unwrap(); + let SIRInstruction::Load(new, _, _, _) = pred.instructions.last().unwrap() else { + panic!("fresh load must follow the write") + }; + assert!(store < pred.instructions.len() - 1); + assert_ne!(*new, RegisterId(0)); + assert_eq!(unit.register_map[new], branch_type); + for bid in [BlockId(1), BlockId(2)] { + assert!( + matches!(&unit.blocks[&bid].instructions[0],SIRInstruction::RuntimeEvent{args,..}if args==&vec![*new]) + ); + } + } + } + } + #[test] + fn mismatched_branch_load_types_are_not_merged() { + let mut unit = fixture( + RegisterType::Bit { + width: 64, + signed: false, + }, + RegisterType::Logic { width: 64 }, + ); + unit.register_map.insert( + RegisterId(3), + RegisterType::Bit { + width: 64, + signed: false, + }, + ); + let before = unit.clone(); + hoist_common_branch_loads(&mut unit); + assert_eq!(unit, before); + } + #[test] + fn successor_with_another_predecessor_keeps_its_load() { + let mut unit = fixture( + RegisterType::Logic { width: 64 }, + RegisterType::Logic { width: 64 }, + ); + unit.blocks.get_mut(&BlockId(2)).unwrap().terminator = + SIRTerminator::Jump(BlockId(1), vec![]); + let before = unit.clone(); + hoist_common_branch_loads(&mut unit); + unit.verify(); + assert_eq!(unit, before); + } +} From 7407115b2750fcf2ee09ce9b5a083e68155fce0a Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:22:41 +0900 Subject: [PATCH 4/8] fix(sv): preserve Taxi aggregates and sparse FF memories Preserve packed parameter shapes and constant selects, evaluate continuous concatenated assignments once, and allow dynamic scratch writes inside functions used by continuous assignments. Narrow constant-masked reads before combinational dependency analysis while retaining procedural wakeups. Lower unpacked memories shared by ordinary edge-triggered processes through the existing sparse next-state protocol, avoiding whole-memory seeds and publishing each complete dirty set once. Reject blocking/read-modify-write forms that the sparse protocol cannot represent. Keep conflicting always_ff writers diagnosed, with an explicit multiple_always_ff_drivers policy. Validation: full SystemVerilog suite across five backends (3242 passed, 90 ignored); analyzer tests (760 passed, 3 ignored); diagnostic policy and project CLI regressions; retained exclusion metadata tests; affected-crate Clippy and formatting. New portable cases were checked with Icarus and Verilator where their four-state support permits; the changed automatic-function case passes both simulators. Upstream Taxi at O1: APB/AXI-Lite/AXI dual-port RAMs pass 12/24/24 tests; stats_collect passes 8 tests; the 1x1 eight-bit crossbar passes 12 tests. Two selected BASE-R cases pass (2 executed, 238 skipped). Its complete matrix is not verified: gearbox cases require the upstream runner's 1fs precision override, which the current CLI harness does not apply, and the full run also timed out. Crossbar_1s now passes all 12 upstream tests at O1 with the optimized release VPI host (381 seconds wall time under load). Static function result persistence is deferred. Change-Id: I009aa8782e9855976a5638cfeb87a835b9526ba4 --- crates/celox-frontend-sv/src/lowering.rs | 185 +++++++++--- crates/celox-frontend-sv/src/lowering/comb.rs | 132 ++++++++- crates/celox-frontend-sv/src/lowering/ff.rs | 111 +++++++- crates/celox-frontend-sv/src/warning.rs | 7 + crates/celox-sv-analyzer/src/ast.rs | 6 + .../celox-sv-analyzer/src/ast/comb_process.rs | 79 ++++-- .../src/ast/constant_binding.rs | 16 ++ crates/celox-sv-analyzer/src/ast/constants.rs | 19 +- .../celox-sv-analyzer/src/ast/ff_process.rs | 1 + crates/celox-sv-analyzer/src/ast/instances.rs | 3 +- crates/celox-sv-analyzer/src/ir.rs | 8 + .../src/source_tree/tests/constant_selects.rs | 15 +- .../src/sv/cases/aggregate_regressions.vtest | 265 ++++++++++++++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../verification/sv/icarus.json | 1 + .../sv/icarus/aggregate_regressions.json | 50 ++++ .../verification/sv/limitations.json | 4 +- crates/celox/src/diagnostic_policy.rs | 5 +- crates/celox/tests/diagnostic_policy.rs | 38 +++ .../systemverilog/review_regressions.rs | 138 +++++++++ docs/guide/celox-toml.md | 7 + docs/ja/guide/celox-toml.md | 2 + 22 files changed, 1016 insertions(+), 80 deletions(-) create mode 100644 crates/celox-test-suite/src/sv/cases/aggregate_regressions.vtest create mode 100644 crates/celox-test-suite/verification/sv/icarus/aggregate_regressions.json diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 7b440f50b12..d9bc370afc4 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -741,9 +741,18 @@ fn validate_net_driver_ranges( .iter() .any(|(_, local_range)| net_driver_ranges_overlap(*child_range, *local_range)) }); + // Each concatenation operand is a continuous driver, even when two + // operands occur in the same authored assignment. + let overlapping_continuous = driver_ranges_overlap(&continuous_driver_ranges( + &module.source, + signal_name, + &module.constants, + &module.parameter_types, + )); if driver_ranges_overlap(child_driver_ranges) || child_local_overlap || overlapping_local_drivers + || overlapping_continuous { return Err(sv::AnalyzerError::Unsupported(format!( "multiple net drivers for `{signal_name}`" @@ -940,10 +949,61 @@ fn driver_ranges_overlap(drivers: &[(usize, Option<(i128, i128)>)]) -> bool { }) } +/// Memories may have several edge-sensitive writers. Their NBA stores update +/// selected elements; always_ff additionally requires a single writing process. +fn shared_edge_memories( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, + warnings: &mut Vec, +) -> HashSet { + let mut memories = HashSet::default(); + let first_ff = module.comb_processes().len(); + let end_ff = first_ff + module.ff_processes().len(); + for signal in module + .signals() + .iter() + .filter(|s| !s.is_net() && !s.r#type().unpacked_ranges().is_empty()) + { + let drivers = local_driver_ranges(module, signal.name(), constants, parameter_types); + if drivers + .iter() + .any(|(id, _)| !(first_ff..end_ff).contains(id)) + { + continue; + } + let overlaps = drivers.iter().enumerate().any(|(i, a)| { + drivers[i + 1..] + .iter() + .any(|b| a.0 != b.0 && net_driver_ranges_overlap(a.1, b.1)) + }); + if !overlaps { + continue; + } + let mut restricted = false; + for (id, _) in drivers { + let process = &module.ff_processes()[id - first_ff]; + restricted |= process.is_always_ff(); + } + if restricted { + warnings.push(( + crate::FrontendWarningKind::MultipleAlwaysFfDrivers { + module: module.name().into(), + signal: signal.name().into(), + }, + None, + )); + } + memories.insert(signal.name().into()); + } + memories +} + fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, parameter_types: &HashMap, + shared_memories: &HashSet, ) -> Result<(), sv::AnalyzerError> { for port in module .ports() @@ -977,7 +1037,13 @@ fn validate_variable_driver_ranges( .iter() .any(|right| left.0 != right.0 && net_driver_ranges_overlap(left.1, right.1)) }); - if has_overlap { + let overlapping_continuous = driver_ranges_overlap(&continuous_driver_ranges( + module, + signal_name, + constants, + parameter_types, + )); + if overlapping_continuous || (has_overlap && !shared_memories.contains(signal_name)) { return Err(sv::AnalyzerError::Unsupported(format!( "multiple variable drivers for `{signal_name}`" ))); @@ -2301,6 +2367,23 @@ fn lower_module_with_overrides( }); } } + let parameter_types = module + .imported_parameters() + .iter() + .chain(module.parameters()) + .filter_map(|parameter| { + Some(( + parameter.name().to_string(), + ( + parameter.resolved_width()?, + parameter.resolved_signed().unwrap_or(false), + ), + )) + }) + .collect(); + let constants = module_constants_with_overrides(module, parameter_overrides); + let shared_memories = shared_edge_memories(module, &constants, ¶meter_types, warnings); + validate_variable_driver_ranges(module, &constants, ¶meter_types, &shared_memories)?; let scheduled = module .ff_processes() .iter() @@ -2318,22 +2401,6 @@ fn lower_module_with_overrides( let mut name_to_id = HashMap::default(); let mut port_order = Vec::new(); let mut initial_memory_values = Vec::new(); - let parameter_types = module - .imported_parameters() - .iter() - .chain(module.parameters()) - .filter_map(|parameter| { - Some(( - parameter.name().to_string(), - ( - parameter.resolved_width()?, - parameter.resolved_signed().unwrap_or(false), - ), - )) - }) - .collect(); - let constants = module_constants_with_overrides(module, parameter_overrides); - validate_variable_driver_ranges(module, &constants, ¶meter_types)?; for port in module.ports() { if name_to_id.contains_key(port.name()) { @@ -2598,7 +2665,8 @@ fn lower_module_with_overrides( four_state, warnings, ); - let blocks = lower_ff_processes(module, &mut pm, ff_parts, &ff_event_roles)?; + let blocks = + lower_ff_processes(module, &mut pm, ff_parts, &ff_event_roles, &shared_memories)?; ( blocks, std::mem::take(&mut pm.runtime_event_sites), @@ -6561,6 +6629,32 @@ fn runtime_select_position( (i128::try_from(width).ok()?.checked_sub(1)?, 0) } }; + runtime_select_position_in_range( + left, + right, + window, + whole_array, + msb, + lsb, + variables, + name_to_id, + constants, + parameter_types, + ) +} + +fn runtime_select_position_in_range( + left: i128, + right: i128, + window: Option, + whole_array: bool, + msb: &sv::ir::ConstExpr, + lsb: &sv::ir::ConstExpr, + variables: &HashMap, + name_to_id: &HashMap, + constants: &HashMap, + parameter_types: &HashMap, +) -> Option { if right < 0 { return None; } @@ -6634,20 +6728,33 @@ fn runtime_select_as_shift( parameter_types: &HashMap, flat_arrays: bool, ) -> Option { - let sv::ir::Expr::Ident(name) = expr else { - return None; + let position = if let sv::ir::Expr::Ident(name) = expr { + runtime_select_position( + name, + msb, + lsb, + variables, + name_to_id, + constants, + parameter_types, + flat_arrays, + flat_arrays, + )? + } else { + let width = sv_expr_natural_width(expr, variables, name_to_id, constants, parameter_types)?; + runtime_select_position_in_range( + i128::try_from(width).ok()?.checked_sub(1)?, + 0, + None, + false, + msb, + lsb, + variables, + name_to_id, + constants, + parameter_types, + )? }; - let position = runtime_select_position( - name, - msb, - lsb, - variables, - name_to_id, - constants, - parameter_types, - flat_arrays, - flat_arrays, - )?; let shift = |value: sv::ir::Expr, op, amount: sv::ir::Expr| sv::ir::Expr::Binary { left: Box::new(value), op, @@ -6678,10 +6785,13 @@ fn runtime_select_as_shift( let moved = move_down(vector); // Shifting fills the missing bits with 0, which is what a two-state // vector (or a parameter) reads. - let four_state = name_to_id - .get(name) - .and_then(|id| variables.get(id)) - .is_some_and(|variable| variable.is_4state); + let four_state = match expr { + sv::ir::Expr::Ident(name) => name_to_id + .get(name) + .and_then(|id| variables.get(id)) + .is_some_and(|variable| variable.is_4state), + _ => true, + }; if !four_state { return Some(sv::ir::Expr::Select { expr: Box::new(moved), @@ -7166,6 +7276,7 @@ fn lower_ff_processes( pm: &mut procedural::ProcModule<'_>, ff_parts: bool, ff_event_roles: &[FfEventRole], + shared_memories: &HashSet, ) -> Result { let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default(); let mut eval_only_ff_blocks = HashMap::default(); @@ -7275,7 +7386,9 @@ fn lower_ff_processes( active, nba, targets, - } = ff::Ff::new(pm, random_seeds[&(0, index)]).lower_process(process.body())?; + } = ff::Ff::new(pm, random_seeds[&(0, index)]) + .with_sparse_memories(shared_memories) + .lower_process(process.body())?; // A process without writes still runs for its runtime events and // extern calls. let has_effects = diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 633ef544b4a..9b9e3489141 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -609,6 +609,100 @@ impl<'p, 'a> Comb<'p, 'a> { self.m.expr_signed(expr) } + /// Replace bits absorbed by a constant zero mask by literal zeros before + /// dependency analysis (IEEE 1800-2023 Table 11-11, including X/Z inputs). + fn masked_and_operand( + &mut self, + store: &Store, + operand: NodeId, + constant: NodeId, + ) -> Result, sv::AnalyzerError> { + let Some((value, mask, width)) = slt_const4(self.arena, &mut self.consts, constant) else { + return Ok(None); + }; + if self.width(operand) != width { + return Ok(None); + } + self.masked_input(store, operand, &(value | mask)) + } + + fn masked_input( + &mut self, + store: &Store, + node: NodeId, + active: &BigUint, + ) -> Result, sv::AnalyzerError> { + if active.is_zero() { + return Ok(Some(( + self.constant(0, self.width(node))?, + Sources::default(), + ))); + } + match self.arena.get(node).clone() { + SLTNode::Constant(..) => Ok(Some((node, Sources::default()))), + SLTNode::Input { + variable, + index, + access, + .. + } if index.is_empty() => { + let mut sources = Sources::default(); + let mut parts = Vec::new(); + let width = access.msb - access.lsb + 1; + let mut bit = 0; + while bit < width { + let selected = active.bit(bit as u64); + let first = bit; + while bit < width && active.bit(bit as u64) == selected { + bit += 1; + } + let part = if selected { + let (part, read_sources) = self.read( + store, + variable, + BitAccess::new(access.lsb + first, access.lsb + bit - 1), + )?; + sources.extend(read_sources); + part + } else { + self.constant(0, bit - first)? + }; + parts.push((part, bit - first)); + } + Ok(Some((self.concat_lsb_first(parts)?, sources))) + } + SLTNode::Concat(parts) => { + let mut sources = Sources::default(); + let mut replacement = Vec::new(); + let mut offset = 0usize; + for (part, width) in parts.into_iter().rev() { + let selected = + (active >> offset) & ((BigUint::from(1u8) << width) - BigUint::from(1u8)); + if self.width(part) != width { + return Ok(None); + } + let Some((part, part_sources)) = self.masked_input(store, part, &selected)? + else { + return Ok(None); + }; + sources.extend(part_sources); + replacement.push((part, width)); + offset += width; + } + Ok(Some((self.concat_lsb_first(replacement)?, sources))) + } + SLTNode::Slice { expr, access } => { + let Some((expr, sources)) = + self.masked_input(store, expr, &(active << access.lsb))? + else { + return Ok(None); + }; + Ok(Some((self.slice(expr, access)?, sources))) + } + _ => Ok(None), + } + } + /// Rewrite the module-state reads of a freshly lowered tree to the values /// the store holds. fn resolve( @@ -722,8 +816,26 @@ impl<'p, 'a> Comb<'p, 'a> { } SLTNode::Constant(..) => (node, Sources::default()), SLTNode::Binary(left, op, right) => { - let (l, mut sources) = self.resolve(store, left, memo)?; - let (r, r_sources) = self.resolve(store, right, memo)?; + let (mut l, mut sources) = self.resolve(store, left, memo)?; + let (mut r, mut r_sources) = self.resolve(store, right, memo)?; + if op == BinaryOp::And + && !(node_is_signed(self.arena, l) && node_is_signed(self.arena, r)) + { + // A procedural observer still wakes on the original reads, + // even when a masked bit cannot affect the assigned value. + self.effect_sensitivity.extend(sources.iter().copied()); + self.effect_sensitivity.extend(r_sources.iter().copied()); + if let Some((masked, read_sources)) = self.masked_and_operand(store, left, r)? { + l = masked; + sources = read_sources; + } + if let Some((masked, read_sources)) = + self.masked_and_operand(store, right, l)? + { + r = masked; + r_sources = read_sources; + } + } sources.extend(r_sources); let rebuilt = if l == left && r == right { node @@ -1502,7 +1614,9 @@ impl<'p, 'a> Comb<'p, 'a> { Target::Static { access, .. } => access.msb - access.lsb + 1, Target::Dynamic { width, .. } => *width, }; - if self.continuous && matches!(target, Target::Dynamic { .. }) { + if self.continuous + && matches!(&target, Target::Dynamic { id, .. } if !self.m.is_hidden(*id)) + { return Err(unsupported(format!( "combinational assignment target `{}` at a run-time position", lhs.name() @@ -3461,7 +3575,12 @@ impl<'p, 'a> Comb<'p, 'a> { .is_ok_and(|parts| parts.iter().all(|(value, _)| value.is_some())) }); if !defined { - return Err(unsupported("latch inference inside always_comb")); + return Err(unsupported(format!( + "latch inference inside always_comb for `{}` (bits {}:{})", + self.m.var(id).path.join("."), + access.msb, + access.lsb + ))); } } let mut written: Vec = store @@ -3502,7 +3621,10 @@ impl<'p, 'a> Comb<'p, 'a> { .iter() .any(|source| source.id == id && source.access.overlaps(&target)) { - return Err(unsupported("latch inference inside always_comb")); + return Err(unsupported(format!( + "latch inference inside always_comb for `{}` (self dependency at bits {msb}:{lsb})", + self.m.var(id).path.join(".") + ))); } let previous_sources = sources .iter() diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 64b54726a4a..1bd4cc42a6f 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -13,7 +13,7 @@ mod file_io; use super::procedural::*; use super::*; -use celox_design::{CounterKind, NbaSite, WaitSite}; +use celox_design::{CounterKind, NbaSite, SPARSE_WORKING_REGION, WaitSite}; use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; use celox_slt::SLTToSIRLowerer; @@ -34,6 +34,7 @@ struct FunctionBlocks { pub(super) struct Ff<'p, 'a> { pub m: &'p mut ProcModule<'a>, + sparse_memories: HashSet, b: SIRBuilder, /// Variables read from the working region. working: HashSet, @@ -97,6 +98,7 @@ impl<'p, 'a> Ff<'p, 'a> { } Self { m, + sparse_memories: HashSet::default(), b: SIRBuilder::new(), working: HashSet::default(), nonblocking: HashSet::default(), @@ -121,6 +123,11 @@ impl<'p, 'a> Ff<'p, 'a> { } } + pub fn with_sparse_memories(mut self, names: &HashSet) -> Self { + self.sparse_memories = 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 { @@ -2203,6 +2210,20 @@ impl<'p, 'a> Ff<'p, 'a> { bit_offset: 0, dynamic_bit_offset: None, }; + if self.sparse_memories.contains(&id) { + let part = self.b.alloc_logic(packed_element_width); + self.b.emit(SIRInstruction::Slice( + part, + value, + inner_index * packed_element_width, + packed_element_width, + )); + self.when(valid, |this| { + this.store(id, offset, packed_element_width, part); + Ok(()) + })?; + continue; + } let old = self.b.alloc_logic(packed_element_width); let target = self.target(id); self.b.emit(SIRInstruction::Load( @@ -2230,6 +2251,12 @@ impl<'p, 'a> Ff<'p, 'a> { bit_offset: access.lsb, dynamic_bit_offset: None, }; + if self.sparse_memories.contains(&id) { + return self.when(valid, |this| { + this.store(id, offset, target_width, value); + Ok(()) + }); + } let old = self.b.alloc_logic(target_width); let target = self.target(id); self.b.emit(SIRInstruction::Load( @@ -3463,6 +3490,15 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result { let mut visited = HashSet::default(); self.scan(body, &mut visited); + if self + .working + .iter() + .any(|id| self.sparse_memories.contains(id)) + { + return Err(unsupported( + "blocking writes to a shared edge-triggered memory", + )); + } // Merge the written ranges of each variable. let mut ranges: HashMap> = HashMap::default(); for (id, access) in std::mem::take(&mut self.targets) { @@ -3517,7 +3553,12 @@ impl<'p, 'a> Ff<'p, 'a> { } else { stage_nonblocking(body, &staged, self.m) }; - emit_ff_seeds(&mut self.b, &targets); + let ordinary_targets: Vec<_> = targets + .iter() + .copied() + .filter(|target| !self.sparse_memories.contains(&target.id)) + .collect(); + 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); @@ -3527,18 +3568,44 @@ impl<'p, 'a> Ff<'p, 'a> { if self.exec_block(&body)? { self.b.seal_block(SIRTerminator::Return); } - let eval = seal_drained(self.b); + let mut eval = seal_drained(self.b); + if eval.blocks.values().flat_map(|block| &block.instructions).any(|instruction| { + matches!(instruction, SIRInstruction::Load(_, address, ..) + if address.region == WORKING_REGION && self.sparse_memories.contains(&address.var_id)) + }) { + return Err(unsupported("read-modify-write destination in a shared FF memory")); + } + for block in eval.blocks.values_mut() { + for instruction in &mut block.instructions { + if let SIRInstruction::Store(address, ..) = instruction + && address.region == WORKING_REGION + && self.sparse_memories.contains(&address.var_id) + { + address.region = SPARSE_WORKING_REGION; + } + } + } let (active_targets, nba_targets): (Vec<_>, Vec<_>) = targets .iter() .copied() .partition(|target| self.working.contains(&target.id)); let mut apply = SIRBuilder::new(); - emit_ff_commits(&mut apply, &targets); + emit_sparse_memory_commits( + &mut apply, + &targets, + &self.sparse_memories, + self.m.variables, + ); emit_nba_merges(&mut apply, &staged, self.m); let mut active = SIRBuilder::new(); emit_ff_commits(&mut active, &active_targets); let mut nba = SIRBuilder::new(); - emit_ff_commits(&mut nba, &nba_targets); + emit_sparse_memory_commits( + &mut nba, + &nba_targets, + &self.sparse_memories, + self.m.variables, + ); emit_nba_merges(&mut nba, &staged, self.m); Ok(FfProcessUnits { eval, @@ -3550,6 +3617,40 @@ impl<'p, 'a> Ff<'p, 'a> { } } +/// Reuse the sparse next-state protocol used by the Veryl frontend: no whole +/// memory seed, and publication touches only the dirty ranges. +fn emit_sparse_memory_commits( + builder: &mut SIRBuilder, + targets: &[VarAtomBase], + sparse: &HashSet, + variables: &HashMap, +) { + let mut committed = HashSet::default(); + for target in targets { + if sparse.contains(&target.id) { + if !committed.insert(target.id) { + continue; + } + // Sparse publication consumes this memory's complete dirty set, + // including updates from other processes evaluated before commit. + // Describe the full object, and publish it once even if this + // process writes several disjoint static ranges. + builder.emit(SIRInstruction::Commit( + Addr { + region: SPARSE_WORKING_REGION, + var_id: target.id, + }, + stable(target.id), + SIROffset::Static(0), + variables[&target.id].width, + Vec::new(), + )); + } else { + emit_ff_commits(builder, std::slice::from_ref(target)); + } + } +} + /// The units of an edge-triggered process: its evaluation, the commit of /// all its results, and that commit split into the blocking results (the /// active region) and the nonblocking ones (the NBA region). diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 5024c2dc46d..f104b7966ef 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -38,6 +38,9 @@ pub enum FrontendWarningKind { /// IEEE 1800-2023 3.14.2.3 requires consistent explicit timing declarations. #[error("mixed explicit and default time units or precisions across design elements")] MixedTimescale, + /// IEEE 1800-2023 9.2.2.4 restricts writes by other processes. + #[error("multiple variable drivers for `{signal}` in `{module}` include an always_ff process")] + MultipleAlwaysFfDrivers { module: String, signal: String }, /// Aggregate defaults are a compatibility extension to IEEE 1800-2023 23.2.2.4. #[error("default value on unpacked input port `{module}.{port}` is a language extension")] UnpackedPortDefault { module: String, port: String }, @@ -144,6 +147,7 @@ impl miette::Diagnostic for FrontendWarning { fn code<'a>(&'a self) -> Option> { Some(Box::new(match self.kind { FrontendWarningKind::MixedTimescale => "mixed_timescale", + FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => "multiple_always_ff_drivers", FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default", FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", @@ -159,6 +163,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::MixedTimescale => { "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" } + FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => { + "IEEE 1800-2023 9.2.2.4 prohibits overlapping writers; use ordinary always procedures, or multiple_always_ff_drivers=warn or allow for compatibility" + } FrontendWarningKind::UnpackedPortDefault { .. } => { "IEEE 1800-2023 23.2.2.4 permits defaults on singular input ports; use unpacked_port_default=warn or allow to enable aggregate defaults" } diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 220496f725f..27c9493cca7 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2207,6 +2207,7 @@ pub enum CombProcessKind { #[derive(Debug, Clone, PartialEq, Eq)] pub struct FfProcess { + always_ff: bool, suspendable: bool, creation_order: usize, events: Vec, @@ -2214,6 +2215,10 @@ pub struct FfProcess { } impl FfProcess { + pub fn is_always_ff(&self) -> bool { + self.always_ff + } + /// Position among the elaborated module items, shared across process kinds. pub fn creation_order(&self) -> usize { self.creation_order @@ -2221,6 +2226,7 @@ impl FfProcess { fn new(events: Vec, body: Vec) -> Self { Self { + always_ff: false, suspendable: false, creation_order: 0, events, diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 79f874c3490..e5bea37f837 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -61,31 +61,19 @@ fn comb_processes_from_item( ) -> Result<(), AnalyzerError> { match &syntax_tree.declarations().body_item(item.id).kind { celox_sv_syntax::BodyItemKind::Assign(id) => { - processes.extend( - continuous_assignments( - syntax_tree.declarations().assign_statement(*id), - syntax_tree, - packed_dimensions, - )? - .into_iter() - .map(|assignment| { - substitute_assignment_constants_with_parameter_literals( - &syntax_tree.state, - assignment, - const_env, - parameter_literals, - ) - }) - .map(|assignment| { - CombProcess::new( - CombProcessKind::ContinuousAssign, - condition - .clone() - .map(|condition| substitute_const_expr_constants(condition, const_env)), - vec![assignment], - ) - }), - ); + for mut process in continuous_assignments( + syntax_tree.declarations().assign_statement(*id), + syntax_tree, + packed_dimensions, + )? { + process.condition = condition.clone(); + processes.push(substitute_process_constants_with_parameter_literals( + &syntax_tree.state, + process, + const_env, + parameter_literals, + )); + } } celox_sv_syntax::BodyItemKind::Procedure(id) => { let local_packed_dimensions = @@ -190,7 +178,7 @@ fn continuous_assignments( native: &celox_sv_syntax::AssignSyntax, tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, -) -> Converted> { +) -> Converted> { if native.assignments.is_empty() { return Err(AnalyzerError::Parse( "native continuous assignment has no operands".into(), @@ -216,6 +204,39 @@ fn continuous_assignments( .assignments .iter() .map(|assignment| { + let native_tree = tree.declarations(); + if matches!( + native_tree.expression(assignment.left).kind, + celox_sv_syntax::ExprKind::Concatenation(_) + ) { + let mut pending = vec![assignment.left]; + let mut parts = Vec::new(); + while let Some(id) = pending.pop() { + if let celox_sv_syntax::ExprKind::Concatenation(items) = + &native_tree.expression(id).kind + { + pending.extend(items.iter().rev().copied()); + } else { + parts.push(expression_binding::net_lvalue( + id, + native_tree, + tree, + dimensions, + )?); + } + } + let rhs = + expression_binding::value(assignment.right, native_tree, tree, dimensions)?; + return Ok(CombProcess::procedural( + CombProcessKind::ContinuousAssign, + None, + vec![Stmt::AssignConcat { + parts, + rhs, + nonblocking: false, + }], + )); + } if let Some(shape) = array_compatibility::native_unpacked_shape( assignment.left, tree.declarations(), @@ -254,7 +275,11 @@ fn continuous_assignments( } else { rhs }; - Ok(Assignment::new(lhs, rhs)) + Ok(CombProcess::new( + CombProcessKind::ContinuousAssign, + None, + vec![Assignment::new(lhs, rhs)], + )) }) .collect() } diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 74a629b0e14..31c1698cce2 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -247,6 +247,22 @@ fn bind_in_context( base = *expression; } if let ExprKind::Name(name) = &native.expression(base).kind { + // Override expressions retain symbolic values, but a packed + // element still has its declared width and coordinates. + // The symbolic context deliberately has no numeric env. + let name_key = instances::normalize_identifier(&name.spelling); + if dimensions.const_env.is_empty() + && query_dimensions.get(&name_key).is_some_and(|shape| { + shape.packed.len() > 1 || !shape.unpacked.is_empty() + }) + { + let value = indexed_expression(id, native, tree, query_dimensions)?; + values.push( + expr_to_index_const(&tree.state, value, query_dimensions) + .ok_or_else(|| unsupported("parameter selection shape"))?, + ); + continue; + } indices.reverse(); jobs.push(Job::Select( instances::normalize_identifier(&name.spelling), diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index 6324346940d..added3f24d0 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -739,9 +739,24 @@ pub(super) fn expr_to_index_const( }; assemble_index_bits(bits) } - Expr::Select { .. } | Expr::Concat(_) | Expr::RepeatConcat { .. } | Expr::Inside { .. } => { - None + expr @ (Expr::Concat(_) | Expr::RepeatConcat { .. }) => { + // Bit extraction retains self-determined operand widths and X/Z. + // Never duplicate a call whose effects have not been expanded. + if inlining::calls_subroutine(&expr) { + return None; + } + let source = IndexBitSource::from_expr(state, expr, dimensions)?; + let width = source.width(); + if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { + return None; + } + assemble_index_bits( + (0..width) + .map(|bit| source.bit(bit as i128)) + .collect::>()?, + ) } + Expr::Select { .. } | Expr::Inside { .. } => None, } } diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index ec988f583ed..0b24fc075c2 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -78,6 +78,7 @@ fn ff_process_from_procedure( } Ok((!events.is_empty()).then(|| { let mut process = FfProcess::new(events, body); + process.always_ff = procedure.kind == celox_sv_syntax::ProcedureKind::AlwaysFf; process.suspendable = procedure.kind == celox_sv_syntax::ProcedureKind::Always; process })) diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 780b010cff8..5b878ebaefe 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -86,12 +86,13 @@ fn instances_from_native_declaration( const_env, ¶meter_types_from_const_env(const_env), ); - let value = expr_to_const( + let value = expr_to_index_const( &syntax_tree.state, substitute_expr_idents( const_expr_to_expr(value), &packed_dimensions.parameter_values, ), + packed_dimensions, ) .ok_or_else(|| { AnalyzerError::Unsupported(format!( diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 8043ee03782..fcc19b24952 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -958,12 +958,18 @@ pub enum CombProcessKind { #[derive(Debug, Clone, PartialEq, Eq)] pub struct FfProcess { + always_ff: bool, creation_order: usize, events: Vec, body: Vec, } impl FfProcess { + /// Whether the source used the restricted always_ff procedure. + pub fn is_always_ff(&self) -> bool { + self.always_ff + } + /// Position among elaborated module items, shared across process kinds. pub fn creation_order(&self) -> usize { self.creation_order @@ -971,6 +977,7 @@ impl FfProcess { pub(crate) fn new(events: Vec, body: Vec) -> Self { Self { + always_ff: false, creation_order: 0, events, body, @@ -1370,6 +1377,7 @@ impl From for FfProcess { .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), ); + result.always_ff = process.is_always_ff(); result.creation_order = process.creation_order(); result } diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs b/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs index 8bcd579c6ae..518261d1f11 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs @@ -82,9 +82,20 @@ fn native_lightweight_value_indices_drive_instance_overrides() { let value = module.instances()[0].parameter_overrides()[0] .value() .unwrap(); - let ConstExpr::Select { bit, .. } = value else { - panic!("{value:?}") + let bit = match value { + ConstExpr::Select { bit, .. } => bit, + ConstExpr::SelectRange { + msb, + lsb, + signed: false, + .. + } if msb == lsb => lsb, + _ => panic!("{value:?}"), }; + assert_eq!( + crate::typecheck::eval_const_expr(&value.clone().into(), &HashMap::default()), + Some(1) + ); assert!(matches!( bit.as_ref(), ConstExpr::Binary { diff --git a/crates/celox-test-suite/src/sv/cases/aggregate_regressions.vtest b/crates/celox-test-suite/src/sv/cases/aggregate_regressions.vtest new file mode 100644 index 00000000000..751266d2394 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/aggregate_regressions.vtest @@ -0,0 +1,265 @@ +(group aggregate_regressions (category regression)) + +(case continuous_nested_concatenated_targets + (four_state) + (source "concat_targets.sv" #" + module Top(input logic [15:0] data, + output wire [3:0] a, b, output wire [7:0] c, swapped); + assign {{a,b},c} = data; + assign {swapped[3:0],swapped[7:4]} = data[7:0]; + endmodule + "#) + (top Top) + (for value (list 0 0xabcd 0xffff 0x1234) + (modify (set data value)) + (assert_eq a (& (>> value 12) 15)) + (assert_eq b (& (>> value 8) 15)) + (assert_eq c (& value 255)) + (assert_eq swapped (| (<< (& value 15) 4) (& (>> value 4) 15))))) + +(case concatenated_runtime_index + (four_state) + (source "concat_index.sv" #" + module Top(input logic [3:0][7:0] data, input logic sel, ptr, + output wire [7:0] y); + assign y=data[{sel,ptr}]; + endmodule + "#) + (top Top) + (modify (set data 0x44332211)) + (for index (range 0 4) + (modify (set sel (>> index 1)) (set ptr (& index 1))) + (assert_eq y (* (+ index 1) 0x11))) + (modify (set sel (fourstate 1 1))) + (assert (== (xmask (get y)) 255))) + +(case concatenated_static_loop_initializer + (source "concat_loop.sv" #" + module Top(input logic [3:0] x, output wire [3:0] y); + function automatic [3:0] f(input logic [3:0] value); + logic [3:0] mask; integer i; + i=0; + for(mask={1'b1,{3{1'b0}}};mask!=0;mask=mask>>1) begin + f[i]=value[i]; i=i+1; + end + endfunction + assign y=f(x); + endmodule + "#) + (top Top) + (for value (range 0 16) + (modify (set x value)) + (assert_eq y value))) + +(case parameter_element_forwarding + (source "parameter_element.sv" #" + module Child #(parameter A=16)(output wire [7:0] y); + localparam W=$clog2(A+1); + wire [W-1:0] value=W'(A); + assign y=value; + endmodule + module Parent #(parameter N=2, V={32'd8,32'd16})(output wire [N*8-1:0] y); + localparam [N-1:0][31:0] WORDS=V; + for(genvar n=0;n> 10 index) 1))) + (modify (set i 4)) + (assert (== (xmask (get y)) 1)) + (modify (set i (fourstate 7 7))) + (assert (== (xmask (get y)) 1))) + +(case independent_clock_memory_writers + (four_state) + (source "dual_clock_memory.sv" #" + module Top(input logic a_clk,b_clk,a_en,b_en, + input logic[1:0] a_addr,b_addr, input logic[7:0] a_data,b_data, + output wire[7:0] q0,q1,q2,q3); + logic[7:0] mem[4]; + initial for(integer i=0;i<4;i=i+1) mem[i]=0; + always @(posedge a_clk) if(a_en) mem[a_addr]<=a_data; + always @(posedge b_clk) if(b_en) mem[b_addr]<=b_data; + assign q0=mem[0]; assign q1=mem[1]; assign q2=mem[2]; assign q3=mem[3]; + endmodule + "#) + (top Top) + (run_until 0) + (modify (set a_clk 0) (set b_clk 0) (set a_en 1) (set b_en 1) + (set a_addr 0) (set b_addr 1) (set a_data 0x12) (set b_data 0x34)) + (modify (set a_clk 1) (set b_clk 1)) + (assert_eq q0 0x12) (assert_eq q1 0x34) + (modify (set a_clk 0) (set b_clk 0) (set a_addr 2) (set b_addr 3) + (set a_data 0x56) (set b_data 0x78)) + (modify (set a_clk 1)) + (run_until 1) + (modify (set a_clk 0)) + (assert_eq q0 0x12) (assert_eq q1 0x34) (assert_eq q2 0x56) (assert_eq q3 0) + (modify (set b_clk 1)) + (run_until 2) + (modify (set b_clk 0)) + (assert_eq q2 0x56) (assert_eq q3 0x78) + ; Concurrent processes may enqueue competing NBAs in either order (4.6/4.7). + ; A complete word wins; untouched elements retain their previous values. + (modify (set a_clk 0) (set b_clk 0) (set a_addr 2) (set b_addr 2) + (set a_data 0x9a) (set b_data 0xbc)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 3) + (assert (|| (== (get q2) 0x9a) (== (get q2) 0xbc))) + (assert_eq q0 0x12) (assert_eq q1 0x34) (assert_eq q3 0x78) + (modify (set a_clk 0) (set b_clk 0) (set a_en 0) (set b_addr 3) + (set b_data (fourstate 0xa5 0xff))) + (modify (set b_clk 1)) + (run_until 4) + (assert_eq (xmask (get q3)) 0xff) + (modify (set b_clk 0) (set a_en 1) (set b_en 0) (set a_addr 0) (set a_data 0x42)) + (modify (set a_clk 1)) + (run_until 5) + (assert_eq q0 0x42) (assert_eq q1 0x34) + (assert_eq (xmask (get q3)) 0xff)) + +(case independent_clock_byte_writers + (four_state) + (source "dual_clock_bytes.sv" #" + module Top(input logic a_clk,b_clk, input logic[1:0] en, + input logic[2:0] addr, input logic[15:0] data, + output wire[15:0] q0,q1); + localparam BYTE_W=8; + logic[15:0] mem[2]; + initial begin mem[0]=0; mem[1]=0; end + always @(posedge a_clk) begin + for(integer i=0;i<2;i=i+1) + if(en[i]) mem[addr][BYTE_W*i+:BYTE_W]<=data[BYTE_W*i+:BYTE_W]; + end + always @(posedge b_clk) if(en[0]) mem[1]<=16'h1234; + assign q0=mem[0]; assign q1=mem[1]; + endmodule + "#) + (top Top) + (run_until 0) + (modify (set a_clk 0) (set b_clk 0) (set en 3) (set addr 0) (set data 0xabcd)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 1) + (assert_eq q0 0xabcd) (assert_eq q1 0x1234) + (modify (set a_clk 0) (set en 2) (set data 0x5678)) + (modify (set a_clk 1)) + (run_until 2) + (assert_eq q0 0x56cd) + (modify (set a_clk 0) (set en 3) (set addr 2) (set data 0xffff)) + (modify (set a_clk 1)) + (run_until 3) + (assert_eq q0 0x56cd) (assert_eq q1 0x1234) + (modify (set a_clk 0) (set addr (fourstate 7 7))) + (modify (set a_clk 1)) + (run_until 4) + (assert_eq q0 0x56cd) (assert_eq q1 0x1234)) + +(case coincident_disjoint_byte_writers + (four_state) + (source "shared_bytes.sv" #" + module Top(input logic a_clk,b_clk, input logic[1:0] addr, + input logic[15:0] data, output wire[15:0] q0,q1); + logic[15:0] mem[2]; + initial begin mem[0]=0; mem[1]=0; end + always @(posedge a_clk) mem[addr][15:8]<=data[15:8]; + always @(posedge b_clk) mem[addr][7:0]<=data[7:0]; + assign q0=mem[0]; assign q1=mem[1]; + endmodule + "#) + (top Top) + (run_until 0) + (modify (set a_clk 0) (set b_clk 0) (set addr 0) (set data 0xabcd)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 1) + (assert_eq q0 0xabcd) (assert_eq q1 0) + (modify (set a_clk 0) (set b_clk 0) (set addr 1) (set data 0x1234)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 2) + (assert_eq q0 0xabcd) (assert_eq q1 0x1234)) + +(case shared_memory_reads_pre_edge_values + (four_state) + (source "shared_snapshot.sv" #" + module Top(input bit a_clk,b_clk, input bit[1:0] addr, + input bit[7:0] data, output wire[31:0] q); + logic[7:0] mem[4]; + initial begin mem[0]=1; mem[1]=2; mem[2]=3; mem[3]=4; end + always @(posedge a_clk) + for(integer i=0;i<4;i=i+1) mem[i]<=mem[(i+3)%4]; + always @(posedge b_clk) mem[addr]<=data; + assign q={mem[3],mem[2],mem[1],mem[0]}; + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq q 0x04030201) + (modify (set a_clk 0) (set b_clk 0) (set addr 0) (set data 0x55)) + (modify (set a_clk 1)) + (run_until 1) + (assert_eq q 0x03020104) + (modify (set a_clk 0) (set b_clk 1)) + (run_until 2) + (assert_eq q 0x03020155) + (modify (set b_clk 0) (set a_clk 1)) + (run_until 3) + (assert_eq q 0x02015503)) + + +(case masked_feed_forward_dependencies + (four_state) + (source "masked_dependencies.sv" #" + module Top(input logic [3:0] enable, output wire [3:0] grant, grant_swapped); + for (genvar n=0; n<4; n=n+1) begin:g + assign grant[n] = enable[n] && ((grant & (4'b1111 >> (4-n))) == 0); + assign grant_swapped[n] = enable[n] && (((4'b1111 >> (4-n)) & grant_swapped) == 0); + end + endmodule + "#) + (top Top) + (for value (range 0 16) + (modify (set enable value)) + (assert_eq grant (& value (- 16 value))) + (assert_eq grant_swapped (& value (- 16 value)))) + (modify (set enable (fourstate 8 8))) + (assert_eq grant (fourstate 8 8)) + (assert_eq grant_swapped (fourstate 8 8))) + + +(case continuous_function_dynamic_scratch_write + (four_state) + (source "continuous_function_scratch.sv" #" + module Top(input logic [2:0] index, input logic value, output wire [7:0] y); + function automatic [7:0] f(input logic [2:0] position, input logic data); + f=0; + f[position]=data; + endfunction + assign y=f(index,value); + endmodule + "#) + (top Top) + (modify (set value 1)) + (for position (range 0 8) + (modify (set index position)) + (assert_eq y (<< 1 position))) + (modify (set index (fourstate 7 7))) + (assert_eq y 0)) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 76c42a71d52..fb9e4950d4a 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -7,6 +7,10 @@ pub(super) struct Group { } pub(super) const GROUPS: &[Group] = &[ + Group { + file: "src/sv/cases/aggregate_regressions.vtest", + text: include_str!("aggregate_regressions.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index 1dedf339e68..c92647951db 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -1,5 +1,6 @@ { "case_files": [ + "icarus/aggregate_regressions.json", "icarus/always_comb.json", "icarus/generate.json", "icarus/hierarchy.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/aggregate_regressions.json b/crates/celox-test-suite/verification/sv/icarus/aggregate_regressions.json new file mode 100644 index 00000000000..443bf824a93 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/aggregate_regressions.json @@ -0,0 +1,50 @@ +{ + "cases": [ + { + "category": "Regression", + "detail": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_packed_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "upstream": [] + }, + "name": "aggregate_regressions::parameter_element_forwarding", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Regression", + "detail": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_packed_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "upstream": [] + }, + "name": "aggregate_regressions::parameter_runtime_element_bit", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 40f8787d4b0..bae9f681e4d 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -134,7 +134,9 @@ "review_regressions::preserves_use_site_dimensions_in_function_alias_types", "system_functions::dimensions_is_independent_of_unknown_values", "system_functions::isunbounded_restores_procedural_parameter_type_metadata", - "types::packed_parameters_of_signed_named_types_have_signed_elements" + "types::packed_parameters_of_signed_named_types_have_signed_elements", + "aggregate_regressions::parameter_element_forwarding", + "aggregate_regressions::parameter_runtime_element_bit" ] } }, diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index a5e56e04cb0..181e0a112e6 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -71,7 +71,10 @@ impl DiagnosticPolicy { pub(crate) fn level(&self, code: &str) -> DiagnosticLevel { self.0.get(code).copied().unwrap_or( - if matches!(code, "mixed_timescale" | "unpacked_port_default") { + if matches!( + code, + "mixed_timescale" | "unpacked_port_default" | "multiple_always_ff_drivers" + ) { DiagnosticLevel::Error } else { DiagnosticLevel::Warn diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs index f50e0db70f8..b4a830de12a 100644 --- a/crates/celox/tests/diagnostic_policy.rs +++ b/crates/celox/tests/diagnostic_policy.rs @@ -176,3 +176,41 @@ mod sv { ); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn overlapping_always_ff_memories_require_explicit_relaxation() { + const SOURCE: &str = r#"module Top(input bit a, b, input bit[1:0] x, y, + output wire[7:0] q); + logic[7:0] mem[4]; + always_ff @(posedge a) mem[x] <= 8'h12; + always_ff @(posedge b) mem[y] <= 8'h34; + assign q=mem[0]; + endmodule"#; + let build = |level| { + celox::Simulation::from_sv_sources( + vec![(SOURCE, std::path::Path::new("shared_ff_memory.sv"))], + "Top", + ) + .diagnostic_policy(policy("multiple_always_ff_drivers", level)) + .build_cranelift() + }; + let error = build(DiagnosticLevel::Error).err().unwrap().to_string(); + assert!(error.contains("multiple variable drivers"), "{error}"); + for level in [DiagnosticLevel::Warn, DiagnosticLevel::Allow] { + let sim = build(level).unwrap(); + assert_eq!( + sim.warnings().len(), + usize::from(level == DiagnosticLevel::Warn) + ); + } + let error = celox::Simulation::from_sv_sources( + vec![(SOURCE, std::path::Path::new("shared_ff_memory.sv"))], + "Top", + ) + .build_cranelift() + .err() + .unwrap() + .to_string(); + assert!(error.contains("multiple variable drivers"), "{error}"); +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 67750546b12..d6d4f49497c 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8694,3 +8694,141 @@ fn timed_task_edge_drivers_of_package_variables_are_checked_across_instances() { "{error}" ); } + +mod aggregate_regressions { + sv_backends! { + fn continuous_function_dynamic_scratch_write(sim) { @case "aggregate_regressions::continuous_function_dynamic_scratch_write"; } + fn masked_feed_forward_dependencies(sim) { @case "aggregate_regressions::masked_feed_forward_dependencies"; } + fn shared_memory_reads_pre_edge_values(sim) { @case "aggregate_regressions::shared_memory_reads_pre_edge_values"; } + fn coincident_disjoint_byte_writers(sim) { @case "aggregate_regressions::coincident_disjoint_byte_writers"; } + fn independent_clock_byte_writers(sim) { @case "aggregate_regressions::independent_clock_byte_writers"; } + + fn continuous_nested_concatenated_targets(sim) { @case "aggregate_regressions::continuous_nested_concatenated_targets"; } + fn concatenated_runtime_index(sim) { @case "aggregate_regressions::concatenated_runtime_index"; } + fn concatenated_static_loop_initializer(sim) { @case "aggregate_regressions::concatenated_static_loop_initializer"; } + fn parameter_element_forwarding(sim) { @case "aggregate_regressions::parameter_element_forwarding"; } + fn parameter_runtime_element_bit(sim) { @case "aggregate_regressions::parameter_runtime_element_bit"; } + fn independent_clock_memory_writers(sim) { @case "aggregate_regressions::independent_clock_memory_writers"; } + } +} + +#[test] +fn shared_ff_memories_keep_native_sparse_next_state() { + use celox_design::{SPARSE_WORKING_REGION, STABLE_REGION, WORKING_REGION}; + use celox_sir::SIRInstruction; + + let source = r#"module Top(input bit a, b, en, + input bit [11:0] addr, input bit [7:0] data, output wire [7:0] q); + logic [7:0] mem[4096]; + always @(posedge a) if (en) begin mem[0] <= data; mem[2] <= data; end + always @(posedge b) if (en) mem[addr] <= data; + assign q = mem[addr]; + endmodule"#; + for level in [ + celox::OptLevel::O0, + celox::OptLevel::O1, + celox::OptLevel::O2, + ] { + let result = Simulator::from_sv_sources(vec![(source, Path::new("sparse_ram.sv"))], "Top") + .opt_level(level) + .trace_pre_optimized_sir() + .build_with_trace(); + let mut sim = result.res.unwrap(); + let memory = sim.program().get_addr(&[], &["mem"]).unwrap(); + let program = result.trace.pre_optimized_sir.unwrap(); + let mut sparse_writes = 0; + let mut sparse_commits = 0; + 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 => { + assert_eq!(address.region, SPARSE_WORKING_REGION); + sparse_writes += 1; + } + SIRInstruction::Commit(source, destination, offset, width, _) + if destination.absolute_addr() == memory => + { + assert_ne!(source.region, WORKING_REGION); + assert_ne!(destination.region, WORKING_REGION); + assert_eq!(destination.region, STABLE_REGION); + assert_eq!(source.region, SPARSE_WORKING_REGION); + assert_eq!(*offset, celox_sir::SIROffset::Static(0)); + assert_eq!(*width, 4096 * 8); + sparse_commits += 1; + } + _ => {} + } + } + assert!(sparse_writes >= 3); + assert_eq!(sparse_commits, 2, "one memory commit per clock domain"); + let a = sim.event("a"); + let b = sim.event("b"); + let en = sim.signal("en"); + let addr = sim.signal("addr"); + let data = sim.signal("data"); + let q = sim.signal("q"); + for (event, index, value) in [(a, 0u32, 0x12u32), (b, 4095, 0x34), (a, 2, 0x56)] { + sim.modify(|io| { + io.set(en, 1u8); + io.set(addr, index); + io.set(data, value); + }) + .unwrap(); + sim.tick(event).unwrap(); + assert_eq!(sim.get(q), value.into()); + } + sim.modify(|io| io.set(addr, 4095u32)).unwrap(); + assert_eq!(sim.get(q), 0x34u32.into()); + } +} + +#[test] +fn rejects_overlapping_continuous_concatenation_drivers() { + for declaration in ["wire [7:0] q", "logic [7:0] q"] { + let source = format!( + "module Top(output {declaration}); assign {{q[7:0],q[3:0]}}=12'habc; endmodule" + ); + let error = cranelift_build_error(&source); + assert!( + error.contains("multiple net drivers") || error.contains("multiple variable drivers"), + "{error}" + ); + } +} + +#[test] +fn masked_reads_preserve_observer_sensitivity_and_real_self_dependencies() { + for mask in ["1'b1", "1'bx", "1'bz"] { + let source = format!("module Top(output logic q); always_comb q=q & {mask}; endmodule"); + let error = four_state_cranelift_build_error(&source); + assert!( + error.contains("latch inference inside always_comb"), + "{error}" + ); + } + let source = r#"module Top(input logic a, output logic y); + always_comb begin y=a & 1'b0; $display("tick"); end + endmodule"#; + let mut sim = + Simulator::from_sv_sources(vec![(source, Path::new("masked_observer.sv"))], "Top") + .four_state(true) + .build_cranelift() + .unwrap(); + let a = sim.signal("a"); + sim.drain_runtime_events(); + for value in [1u8, 0] { + sim.modify(|io| io.set(a, value)).unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"tick".to_vec() + }] + ); + } +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 7709d31d8b9..97239f5edcc 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -154,6 +154,13 @@ explicit settings remain effective, and the global precision includes default scopes. Syntax errors, unsupported constructs and invalid precision declarations remain errors. +`multiple_always_ff_drivers` defaults to `error` for shared memories written by +an `always_ff` and another edge process (IEEE 1800-2023 §9.2.2.4). With `warn` +or `allow`, Celox stages their nonblocking writes in sparse next-state storage +and commits dirty chunks. Ordinary `always` procedures can share a memory +without this diagnostic. Simultaneous +writes to the same bits from different processes have no portable ordering. + Project simulator constructors load this table alongside `Veryl.toml`. Native compilation also supports standalone SystemVerilog projects: diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index df0b71e3556..e50629a9358 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -132,6 +132,8 @@ memory_file_word_count = "error" エラーの緩和は、コンパイラが継続時の動作を定義している診断に対応します。現在の対象は `mixed_timescale` です。IEEE 1800-2023 §3.14.2.3 が求める時間単位・精度の明示指定の一貫性を検査し、既定では `error` になります。`warn` または `allow` を選ぶと、未指定部分には Celox の既定値(単位 1ns、精度 1ps)を適用します。明示した値は維持し、全体の精度には既定値を使うスコープも含めます。構文エラー、未対応の構文、不正な精度指定は引き続きエラーになります。 +`multiple_always_ff_drivers` は、`always_ff` と別のエッジプロセスが同じメモリへ書く場合に既定で `error` になります(IEEE 1800-2023 §9.2.2.4)。`warn` または `allow` では、非ブロッキング代入の変更範囲を次状態領域に保持してコミットします。通常の `always` 同士による共有にはこの診断は出ません。異なるプロセスが同時に同じビットへ書く順序は、移植可能な動作として保証されません。 + プロジェクトのシミュレータ生成時は `Veryl.toml` と同じ場所の設定を読み込みます。CLI は単独の SystemVerilog プロジェクトにも対応します。 ```sh From d77308ffbc644a1c0937809e4ee23d27e344a6c4 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:27:16 +0900 Subject: [PATCH 5/8] fix(vpi): expose unpacked arrays through lazy element handles Preserve declared unpacked bounds through frontend metadata, reflection and native images. Expose multidimensional VPI arrays with lazy indexed handles, correct names and bounds, per-element deposits and value-change callbacks. Allocate metadata only for requested handles, including large sparse RAMs. Keep original four-state mask offsets for strided subviews and restrict partial writes to selected elements. For bit-packed arrays, use byte-window read/modify/write so sibling elements and boundary bits remain intact without copying the entire memory. Bump the native image schema to version 21 and reject older images before decoding their payload. Validation: VPI package and opt-in cocotb integration tests with cocotb 2.0.1 and 2.1.0; check packed element values and widths without requiring a version-specific handle class. Cover widths 1/8/9/65 in two-state and four-state modes, multidimensional and descending bounds, sibling preservation and callback identity; native executable/cache round trips; frontend/runtime unit tests; NAPI/JS integration; formatting and Clippy. Change-Id: Ibb49f1242a780dc1b9ef369b9841def4678fbad2 --- crates/celox-frontend-core/src/sdk.rs | 2 + .../celox-frontend-core/src/shared/lookup.rs | 2 + .../src/symbolic/artifact.rs | 2 + .../src/symbolic/assembly.rs | 1 + crates/celox-frontend-core/src/watch.rs | 1 + crates/celox-frontend-sv/src/lowering.rs | 15 + .../src/lowering/procedural.rs | 3 + crates/celox-frontend-veryl/src/artifact.rs | 1 + crates/celox-frontend-veryl/src/testbench.rs | 1 + crates/celox-runtime/src/backend.rs | 2 +- crates/celox-runtime/src/reflection.rs | 15 + crates/celox-vpi/src/callbacks.rs | 14 +- crates/celox-vpi/src/lib.rs | 434 ++++++++++++++---- crates/celox-vpi/tests/basic_vpi.rs | 120 +++++ crates/celox-vpi/tests/cocotb_e2e.rs | 8 +- .../celox-vpi/tests/fixtures/cocotb/arrays.sv | 11 + .../tests/fixtures/cocotb/test_arrays.py | 43 ++ crates/celox/src/backend/native/backend.rs | 2 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/ir.rs | 13 + crates/celox/tests/shared_jit_cache.rs | 19 + 21 files changed, 603 insertions(+), 108 deletions(-) create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/arrays.sv create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/test_arrays.py diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 90b0f717afb..c5056045cb6 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1059,6 +1059,7 @@ impl HiddenObjects<'_> { }, array_dims: Vec::new(), }, + unpacked_ranges: Vec::new(), packed_dims: vec![width], source: None, module_affiliated: false, @@ -1817,6 +1818,7 @@ pub fn lower_frontend_artifact( type_kind, array_dims: Vec::new(), }, + unpacked_ranges: Vec::new(), packed_dims: vec![signal.value_type().width()], source: None, module_affiliated: true, diff --git a/crates/celox-frontend-core/src/shared/lookup.rs b/crates/celox-frontend-core/src/shared/lookup.rs index d8faf9d8542..71b1b6cf661 100644 --- a/crates/celox-frontend-core/src/shared/lookup.rs +++ b/crates/celox-frontend-core/src/shared/lookup.rs @@ -66,6 +66,8 @@ pub struct VariableInfo { /// arrays because that is the source-independent storage shape. The /// testbench adapter also needs packed shape for chained selects. pub packed_dims: Vec, + /// Declared unpacked bounds, in storage order; empty uses zero-based dimensions. + pub unpacked_ranges: Vec<(i128, i128)>, } impl std::ops::Deref for VariableInfo { diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 57723894725..d51a615090d 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -22,6 +22,8 @@ pub struct SymbolicVariable { pub signed: bool, pub metadata: VariableMetadata, pub packed_dims: Vec, + /// Declared unpacked bounds, in storage order; empty uses zero-based dimensions. + pub unpacked_ranges: Vec<(i128, i128)>, pub source: Option, pub module_affiliated: bool, } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 487b7e05f77..a52ea6fbb21 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1690,6 +1690,7 @@ fn module_variables( var_kind: variable.kind, signed: variable.signed, packed_dims: variable.packed_dims.clone(), + unpacked_ranges: variable.unpacked_ranges.clone(), metadata: variable.metadata.clone(), }, ); diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 3d9b80a809e..ce6ca4bf68e 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -476,6 +476,7 @@ pub fn declare_counter_slots( type_kind: PortTypeKind::Bit, array_dims: Vec::new(), }, + unpacked_ranges: Vec::new(), packed_dims: vec![EVENT_COUNTER_WIDTH], source: None, module_affiliated: false, diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d9bc370afc4..a5a99218b23 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -68,6 +68,7 @@ struct SvVariable { is_4state: bool, packed_ranges: Vec<(i128, i128)>, array_dims: Vec, + unpacked_ranges: Vec<(i128, i128)>, domain_kind: DomainKind, kind: VariableKind, type_kind: PortTypeKind, @@ -91,6 +92,7 @@ impl SvVariable { type_kind: self.type_kind, array_dims: self.array_dims.clone(), }, + unpacked_ranges: self.unpacked_ranges.clone(), packed_dims: self .packed_ranges .iter() @@ -1443,6 +1445,7 @@ fn prepare_external_hierarchy_collecting( .map(|&width| ((width - 1) as i128, 0)) .collect(), array_dims: variable.metadata.array_dims.clone(), + unpacked_ranges: variable.unpacked_ranges.clone(), domain_kind: variable.metadata.kind, kind: variable.kind, type_kind: variable.metadata.type_kind, @@ -2420,6 +2423,7 @@ fn lower_module_with_overrides( is_4state: type_info.is_4state, packed_ranges: type_info.packed_ranges, array_dims: type_info.array_dims, + unpacked_ranges: type_info.unpacked_ranges, domain_kind: DomainKind::Other, kind, type_kind: type_info.type_kind, @@ -2500,6 +2504,7 @@ fn lower_module_with_overrides( is_4state: type_info.is_4state, packed_ranges: type_info.packed_ranges, array_dims: type_info.array_dims, + unpacked_ranges: type_info.unpacked_ranges, domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: type_info.type_kind, @@ -2572,6 +2577,7 @@ fn lower_module_with_overrides( is_4state: true, packed_ranges: vec![(width as i128 - 1, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Parameter, type_kind: PortTypeKind::Logic, @@ -3607,6 +3613,7 @@ fn lower_initial_processes( is_4state: false, packed_ranges: vec![(width as i128 - 1, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: PortTypeKind::Bit, @@ -3956,6 +3963,7 @@ fn ensure_parent_output_signals( is_4state: true, packed_ranges: Vec::new(), array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: PortTypeKind::Logic, @@ -5151,6 +5159,7 @@ struct SvSignalType { is_4state: bool, packed_ranges: Vec<(i128, i128)>, array_dims: Vec, + unpacked_ranges: Vec<(i128, i128)>, type_kind: PortTypeKind, } @@ -5214,6 +5223,11 @@ fn signal_type_from_sv( .ok_or_else(|| { sv::AnalyzerError::Unsupported("unresolved unpacked array dimension".to_string()) })?; + let unpacked_ranges = typ + .unpacked_ranges() + .iter() + .filter_map(|range| unpacked_range_bounds(range, constants, parameter_types)) + .collect(); let element_count = array_dims .iter() .copied() @@ -5253,6 +5267,7 @@ fn signal_type_from_sv( is_4state, packed_ranges, array_dims, + unpacked_ranges, type_kind, }) } diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 4ea8560a97d..8960d107d1a 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -565,6 +565,7 @@ impl<'a> ProcModule<'a> { is_4state, packed_ranges: vec![(i128::try_from(width.max(1)).unwrap_or(1) - 1, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: if is_4state { @@ -631,6 +632,7 @@ impl<'a> ProcModule<'a> { is_4state: source.is_4state, packed_ranges: vec![(0, 0)], array_dims: Vec::new(), + unpacked_ranges: Vec::new(), domain_kind: kind, kind: VariableKind::Variable, type_kind: source.type_kind, @@ -1033,6 +1035,7 @@ pub(super) fn register_locals( is_4state: type_info.is_4state, packed_ranges: type_info.packed_ranges, array_dims: type_info.array_dims, + unpacked_ranges: type_info.unpacked_ranges, domain_kind: DomainKind::Other, kind: VariableKind::Variable, type_kind: type_info.type_kind, diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index b0a0ce5fea2..572c817eb7a 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -446,6 +446,7 @@ pub(crate) fn project_module_with_ids( .collect(), }, packed_dims, + unpacked_ranges: Vec::new(), source: Some(celox_frontend_core::SourceLocation { path: variable.token.beg.source.to_string(), text: source_texts diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 1c008f4e210..097a8059a4a 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -3821,6 +3821,7 @@ mod tests { path: path.clone(), var_kind: VariableKind::Variable, signed: false, + unpacked_ranges: Vec::new(), packed_dims: vec![8], metadata: VariableMetadata { width: 8, diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 20f1aea095c..fa03abdd57a 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -179,7 +179,7 @@ pub trait SimBackend { if let Some(trace) = self.layout().trace.as_ref() { let len = signal.array_layout.map_or_else( || celox_state_layout::get_byte_size(signal.width), - |array| array.plane_size, + |array| array.element_count * array.element_stride, ); let (ptr, _) = self.memory_as_ptr(); // SAFETY: layout homes and metadata fit in the writable state image. diff --git a/crates/celox-runtime/src/reflection.rs b/crates/celox-runtime/src/reflection.rs index 1ea8cfb1cf1..6b16ec8999c 100644 --- a/crates/celox-runtime/src/reflection.rs +++ b/crates/celox-runtime/src/reflection.rs @@ -44,6 +44,7 @@ pub struct ReflectionSignal { pub signed: bool, pub packed_dims: Vec, pub unpacked_dims: Vec, + pub unpacked_ranges: Vec<(i128, i128)>, pub type_kind: PortTypeKind, } @@ -127,6 +128,20 @@ impl DesignReflection { signal.full_name )); } + if signal.unpacked_dims.len() != signal.unpacked_ranges.len() + || signal + .unpacked_dims + .iter() + .zip(&signal.unpacked_ranges) + .any(|(&size, &(left, right))| { + size == 0 || left.abs_diff(right).checked_add(1) != Some(size as u128) + }) + { + return Err(format!( + "signal `{}` has invalid unpacked bounds", + signal.full_name + )); + } if index > 0 && self.signals[index - 1].full_name >= signal.full_name { return Err("reflection signals are not uniquely name-sorted".into()); } diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index 0088f8a35a7..cf97ddd89e4 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -94,7 +94,7 @@ pub(super) struct VlogStorage { arg_ptrs: Vec<*mut c_char>, } -fn callback_signal(data: &VpiCbData) -> Option { +fn callback_signal(data: &VpiCbData) -> Option { if data.reason != CB_VALUE_CHANGE { return None; } @@ -626,8 +626,16 @@ pub unsafe extern "C" fn vpi_chk_error(_info: *mut VpiErrorInfo) -> i32 { /// # Safety /// /// A non-null `reference` must be a live handle returned by this library. -pub unsafe extern "C" fn vpi_handle_by_index(_reference: VpiHandle, _index: i32) -> VpiHandle { - ptr::null_mut() +pub unsafe extern "C" fn vpi_handle_by_index(reference: VpiHandle, index: i32) -> VpiHandle { + // Safety: forwarded from the caller under the VPI handle contract. + let Some(ObjectRef::Signal(selection)) = (unsafe { object_ref(reference) }) else { + return ptr::null_mut(); + }; + super::with_runtime(|runtime| selection.select(runtime, index)) + .flatten() + .map_or(ptr::null_mut(), |selection| { + super::new_object_handle(ObjectRef::Signal(selection)) + }) } #[unsafe(no_mangle)] diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index b35a0804a69..c2453493604 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -56,6 +56,7 @@ pub const VPI_BINARY_CONST: i32 = 3; pub const VPI_NET: i32 = 36; pub const VPI_PORT: i32 = 44; pub const VPI_REG: i32 = 48; +pub const VPI_REG_ARRAY: i32 = 116; pub const VPI_LEFT_RANGE: i32 = 79; pub const VPI_PARENT: i32 = 81; pub const VPI_RIGHT_RANGE: i32 = 83; @@ -113,10 +114,206 @@ pub struct VpiValue { pub value: VpiValueData, } +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct VpiSignalIdentity { + storage: NativeSignalIdentity, + slice: Option<(usize, usize)>, +} + +/// A lazy view of an unpacked array. Storage grows with requested handles, +/// rather than with the number of elements in reflected memories. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct SignalSelection { + root: ReflectionSignalId, + first: usize, + depth: usize, +} + +impl SignalSelection { + fn root(root: ReflectionSignalId) -> Self { + Self { + root, + first: 0, + depth: 0, + } + } + + fn resolve(self, runtime: &NativeProgramInstance) -> Option { + let mut signal = runtime.reflection().signal(self.root)?.clone(); + if self.depth == 0 { + return Some(signal); + } + let count = signal.unpacked_dims.iter().product::(); + let element_width = signal.signal.width / count; + let remaining = signal + .unpacked_dims + .get(self.depth..)? + .iter() + .product::(); + if self.first.checked_add(remaining)? > count { + return None; + } + let mut stride = count; + for (&size, &(left, right)) in signal + .unpacked_dims + .iter() + .zip(&signal.unpacked_ranges) + .take(self.depth) + { + stride /= size; + let position = (self.first / stride) % size; + let index = if left <= right { + left + position as i128 + } else { + left - position as i128 + }; + let suffix = format!("[{index}]"); + signal.name.push_str(&suffix); + signal.full_name.push_str(&suffix); + } + if let Some(mut array) = signal.signal.array_layout { + signal.signal.offset = signal + .signal + .offset + .checked_add(self.first.checked_mul(array.element_stride)?)?; + signal.signal.width = remaining.checked_mul(element_width)?; + array.element_count = remaining; + signal.signal.array_layout = Some(array); + } + signal.unpacked_dims.drain(..self.depth); + signal.unpacked_ranges.drain(..self.depth); + signal.domain_kind = DomainKind::Other; + Some(signal) + } + + fn select(self, runtime: &NativeProgramInstance, index: i32) -> Option { + let root = runtime.reflection().signal(self.root)?; + let &(left, right) = root.unpacked_ranges.get(self.depth)?; + let index = i128::from(index); + if index < left.min(right) || index > left.max(right) { + return None; + } + let position = usize::try_from(if left <= right { + index - left + } else { + left - index + }) + .ok()?; + let stride = root + .unpacked_dims + .get(self.depth + 1..)? + .iter() + .product::(); + Some(Self { + root: self.root, + first: self.first.checked_add(position.checked_mul(stride)?)?, + depth: self.depth + 1, + }) + } + + // Some arrays use contiguous bits instead of a byte stride (including + // scalar arrays and arrays whose uses cannot be lowered as strided loads). + fn slice(self, runtime: &NativeProgramInstance) -> Option<(usize, usize)> { + let root = runtime.reflection().signal(self.root)?; + if self.depth == 0 || root.signal.array_layout.is_some() { + return None; + } + let element_width = root.signal.width / root.unpacked_dims.iter().product::(); + let remaining = root + .unpacked_dims + .get(self.depth..)? + .iter() + .product::(); + Some((self.first * element_width, remaining * element_width)) + } + + fn width(self, runtime: &NativeProgramInstance) -> Option { + Some( + self.slice(runtime) + .map_or(self.resolve(runtime)?.signal.width, |(_, width)| width), + ) + } + + fn identity(self, runtime: &NativeProgramInstance) -> Option { + let storage = if self.depth == 0 || self.slice(runtime).is_some() { + runtime.signal_identity(self.root)? + } else { + NativeSignalIdentity::State(self.resolve(runtime)?.signal) + }; + Some(VpiSignalIdentity { + storage, + slice: self.slice(runtime), + }) + } + + fn read(self, runtime: &NativeProgramInstance) -> Option<(BigUint, BigUint)> { + let signal = self.resolve(runtime)?.signal; + let Some((offset, width)) = self.slice(runtime) else { + return Some(runtime.backend().get_four_state(signal)); + }; + let (window, shift) = bit_window(signal, offset, width); + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + let bits = (runtime.backend().get_four_state(window).0 >> shift) & &mask; + let unknowns = if signal.is_4state && runtime.four_state() { + let mut mask_window = window; + mask_window.offset += signal.width.div_ceil(8); + (runtime.backend().get_four_state(mask_window).0 >> shift) & mask + } else { + BigUint::default() + }; + Some((bits, unknowns)) + } + + fn write(self, runtime: &mut NativeProgramInstance, bits: BigUint, mask: BigUint) { + let Some(signal) = self.resolve(runtime).map(|signal| signal.signal) else { + return; + }; + let Some((offset, width)) = self.slice(runtime) else { + runtime.backend_mut().set_four_state(signal, bits, mask); + return; + }; + let (window, shift) = bit_window(signal, offset, width); + let selected = ((BigUint::from(1u8) << width) - BigUint::from(1u8)) << shift; + let whole = (BigUint::from(1u8) << window.width) - BigUint::from(1u8); + let retained = &whole ^ &selected; + let old = runtime.backend().get_four_state(window).0; + runtime.backend_mut().set_four_state( + window, + (old & &retained) | ((bits << shift) & &selected), + BigUint::default(), + ); + if signal.is_4state && runtime.four_state() { + let mut mask_window = window; + mask_window.offset += signal.width.div_ceil(8); + let old = runtime.backend().get_four_state(mask_window).0; + runtime.backend_mut().set_four_state( + mask_window, + (old & retained) | ((mask << shift) & selected), + BigUint::default(), + ); + } + } +} + +/// Small byte-aligned window around a logical bit slice. Preserve the boundary +/// bits on writes; even a huge bit-packed RAM needs only the selected bytes. +fn bit_window(signal: celox::SignalRef, offset: usize, width: usize) -> (celox::SignalRef, usize) { + let shift = offset % 8; + ( + celox::SignalRef { + offset: signal.offset + offset / 8, + width: (shift + width).div_ceil(8) * 8, + is_4state: false, + array_layout: None, + }, + shift, + ) +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ObjectRef { Scope(ReflectionScopeId), - Signal(ReflectionSignalId), + Signal(SignalSelection), } #[derive(Debug)] @@ -146,7 +343,7 @@ pub type VpiHandle = *mut VpiHandleObject; #[derive(Default)] struct VpiHost { runtime: RefCell>, - forced_values: RefCell>, + forced_values: RefCell>, pending_writes: RefCell, callbacks: RefCell, vlog: RefCell>, @@ -282,21 +479,21 @@ struct ForcedValue { #[derive(Default)] struct PendingWrites { - deposits: HashMap, + deposits: HashMap, edge_batches: Vec, open_edge_batch: Option, settle: bool, } struct PendingEdgeBatch { - active_signals: Vec, - transition_signals: Vec, - deposits: HashMap, + active_signals: Vec, + transition_signals: Vec, + deposits: HashMap, } #[derive(Clone)] struct PendingDeposit { - id: ReflectionSignalId, + id: SignalSelection, value: BigUint, mask: BigUint, } @@ -340,8 +537,8 @@ fn is_active_edge(kind: DomainKind, old: LogicLevel, new: LogicLevel) -> bool { fn record_pending_write( pending: &mut PendingWrites, - id: ReflectionSignalId, - identity: NativeSignalIdentity, + id: SignalSelection, + identity: VpiSignalIdentity, value: BigUint, mask: BigUint, domain_kind: DomainKind, @@ -389,19 +586,12 @@ fn record_pending_write( fn apply_pending_deposits( runtime: &mut NativeProgramInstance, - deposits: &HashMap, + deposits: &HashMap, ) { - let writes = deposits - .values() - .filter_map(|deposit| { - runtime - .reflection() - .signal(deposit.id) - .map(|signal| (signal.signal, deposit.value.clone(), deposit.mask.clone())) - }) - .collect::>(); - for (signal, value, mask) in writes { - runtime.backend_mut().set_four_state(signal, value, mask); + for deposit in deposits.values() { + deposit + .id + .write(runtime, deposit.value.clone(), deposit.mask.clone()); } } @@ -527,9 +717,8 @@ fn new_object_handle(object: ObjectRef) -> VpiHandle { .reflection() .scope(id) .map(|scope| (scope.name.clone(), scope.full_name.clone())), - ObjectRef::Signal(id) => runtime - .reflection() - .signal(id) + ObjectRef::Signal(id) => id + .resolve(runtime) .map(|signal| (signal.name.clone(), signal.full_name.clone())), }) .flatten() @@ -596,16 +785,28 @@ unsafe fn object_ref(handle: VpiHandle) -> Option { fn object_by_full_name(name: &str) -> Option { with_runtime(|runtime| { - runtime - .reflection() - .scope_by_name(name) - .map(|(id, _)| ObjectRef::Scope(id)) - .or_else(|| { - runtime - .reflection() - .signal_by_name(name) - .map(|(id, _)| ObjectRef::Signal(id)) - }) + let reflection = runtime.reflection(); + if let Some((id, _)) = reflection.scope_by_name(name) { + return Some(ObjectRef::Scope(id)); + } + if let Some((id, _)) = reflection.signal_by_name(name) { + return Some(ObjectRef::Signal(SignalSelection::root(id))); + } + let mut prefix = name; + let mut indices = Vec::new(); + while let Some(end) = prefix.strip_suffix(']') { + let (base, index) = end.rsplit_once('[')?; + indices.push(index.parse::().ok()?); + prefix = base; + if let Some((id, _)) = reflection.signal_by_name(prefix) { + let mut selection = SignalSelection::root(id); + for index in indices.iter().rev() { + selection = selection.select(runtime, *index)?; + } + return Some(ObjectRef::Signal(selection)); + } + } + None }) .flatten() } @@ -658,20 +859,22 @@ pub unsafe extern "C" fn vpi_handle(kind: i32, reference: VpiHandle) -> VpiHandl let Some(ObjectRef::Signal(id)) = (unsafe { object_ref(reference) }) else { return ptr::null_mut(); }; - let width = with_runtime(|runtime| { - runtime - .reflection() - .signal(id) - .map(|signal| signal.signal.width) + let bounds = with_runtime(|runtime| { + let signal = id.resolve(runtime)?; + Some( + signal + .unpacked_ranges + .first() + .copied() + .unwrap_or((id.width(runtime)?.saturating_sub(1) as i128, 0)), + ) }) .flatten(); - return match (kind, width) { - (VPI_LEFT_RANGE, Some(width)) => { - new_constant_handle(i32::try_from(width.saturating_sub(1)).unwrap_or(i32::MAX)) - } - (VPI_RIGHT_RANGE, Some(_)) => new_constant_handle(0), - _ => ptr::null_mut(), - }; + return bounds + .and_then(|(left, right)| { + i32::try_from(if kind == VPI_LEFT_RANGE { left } else { right }).ok() + }) + .map_or(ptr::null_mut(), new_constant_handle); } // Safety: reference follows the VPI handle contract. let Some(object) = (unsafe { object_ref(reference) }) else { @@ -686,10 +889,15 @@ pub unsafe extern "C" fn vpi_handle(kind: i32, reference: VpiHandle) -> VpiHandl .scope(id) .and_then(|scope| scope.parent) .map(ObjectRef::Scope), - ObjectRef::Signal(id) => runtime - .reflection() - .signal(id) - .map(|signal| ObjectRef::Scope(signal.parent)), + ObjectRef::Signal(id) => { + if kind == VPI_PARENT { + // IEEE 1800-2023 37.17: largest containing unpacked array. + (id.depth != 0).then(|| ObjectRef::Signal(SignalSelection::root(id.root))) + } else { + id.resolve(runtime) + .map(|signal| ObjectRef::Scope(signal.parent)) + } + } }) .flatten(); parent.map_or(ptr::null_mut(), new_object_handle) @@ -727,7 +935,7 @@ pub unsafe extern "C" fn vpi_iterate(kind: i32, reference: VpiHandle) -> VpiHand }) .unwrap_or_default(), ( - VPI_PORT | VPI_REG | VPI_NET | VPI_VARIABLES | VPI_PARAMETER, + VPI_PORT | VPI_REG | VPI_REG_ARRAY | VPI_NET | VPI_VARIABLES | VPI_PARAMETER, Some(ObjectRef::Scope(id)), ) => reflection .scope(id) @@ -743,13 +951,14 @@ pub unsafe extern "C" fn vpi_iterate(kind: i32, reference: VpiHandle) -> VpiHand } match kind { VPI_PORT => signal.direction != SignalDirection::Internal, - VPI_REG => true, + VPI_REG => signal.unpacked_dims.is_empty(), + VPI_REG_ARRAY => !signal.unpacked_dims.is_empty(), VPI_VARIABLES => signal.direction == SignalDirection::Internal, VPI_NET => false, _ => false, } }) - .map(ObjectRef::Signal) + .map(|id| ObjectRef::Signal(SignalSelection::root(id))) .collect() }) .unwrap_or_default(), @@ -792,17 +1001,18 @@ fn object_type(object: ObjectRef) -> i32 { match object { ObjectRef::Scope(_) => VPI_MODULE, ObjectRef::Signal(id) => with_runtime(|runtime| { - if runtime - .reflection() - .signal(id) - .is_some_and(|signal| signal.is_parameter) - { + let Some(signal) = id.resolve(runtime) else { + return 0; + }; + if !signal.unpacked_dims.is_empty() { + VPI_REG_ARRAY + } else if signal.is_parameter { VPI_PARAMETER } else { VPI_REG } }) - .unwrap_or(VPI_REG), + .unwrap_or(0), } } @@ -841,7 +1051,7 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { let scope = match object { ObjectRef::Scope(id) => reflection.scope(id), ObjectRef::Signal(id) => reflection - .signal(id) + .signal(id.root) .and_then(|signal| reflection.scope(signal.parent)), }; scope.map_or(0, |scope| { @@ -867,13 +1077,28 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { let ObjectRef::Signal(id) = object else { return 0; }; - let Some(signal) = runtime.reflection().signal(id) else { + let Some(signal) = id.resolve(runtime) else { return 0; }; match property { - VPI_SIZE => i32::try_from(signal.signal.width).unwrap_or(i32::MAX), - VPI_SCALAR => i32::from(signal.signal.width == 1), - VPI_VECTOR => i32::from(signal.signal.width != 1), + VPI_SIZE => i32::try_from( + signal + .unpacked_dims + .first() + .copied() + .unwrap_or(id.width(runtime).unwrap_or(0)), + ) + .unwrap_or(i32::MAX), + VPI_SCALAR => i32::from( + id.width(runtime).unwrap_or(0) + / signal.unpacked_dims.iter().product::() + == 1, + ), + VPI_VECTOR => i32::from( + id.width(runtime).unwrap_or(0) + / signal.unpacked_dims.iter().product::() + != 1, + ), VPI_SIGNED => i32::from(signal.signed), VPI_DIRECTION => match signal.direction { SignalDirection::Input => VPI_INPUT, @@ -926,6 +1151,7 @@ pub unsafe extern "C" fn vpi_get_str(property: i32, reference: VpiHandle) -> *mu HandleKind::Object(object) => match object_type(object) { VPI_MODULE => c"vpiModule".as_ptr().cast_mut(), VPI_REG => c"vpiReg".as_ptr().cast_mut(), + VPI_REG_ARRAY => c"vpiRegArray".as_ptr().cast_mut(), _ => ptr::null_mut(), }, HandleKind::Constant(_) => c"vpiConstant".as_ptr().cast_mut(), @@ -936,23 +1162,25 @@ pub unsafe extern "C" fn vpi_get_str(property: i32, reference: VpiHandle) -> *mu } } -fn value_bits(id: ReflectionSignalId) -> Option<(BigUint, BigUint, usize)> { - let (identity, width) = with_runtime(|runtime| { - Some(( - runtime.signal_identity(id)?, - runtime.reflection().signal(id)?.signal.width, - )) +fn value_bits(id: SignalSelection) -> Option<(BigUint, BigUint, usize)> { + if !with_runtime(|runtime| { + id.resolve(runtime) + .is_some_and(|signal| signal.unpacked_dims.is_empty()) }) - .flatten()?; + .unwrap_or(false) + { + return None; + } + let (identity, width) = + with_runtime(|runtime| Some((id.identity(runtime)?, id.width(runtime)?))).flatten()?; if let Some(forced) = with_host(|host| borrow_cell(&host.forced_values, |forced| forced.get(&identity).cloned())) { return Some((forced.value, forced.mask, width)); } with_runtime(|runtime| { - let signal = runtime.reflection().signal(id)?; - let (value, mask) = runtime.backend().get_four_state(signal.signal); - Some((value, mask, signal.signal.width)) + let (value, mask) = id.read(runtime)?; + Some((value, mask, id.width(runtime)?)) }) .flatten() } @@ -1062,10 +1290,8 @@ unsafe fn write_snapshot_value( return; }; let metadata = with_runtime(|runtime| { - runtime - .reflection() - .signal(id) - .map(|signal| (signal.signal.width, signal.signed)) + id.resolve(runtime) + .and_then(|signal| Some((id.width(runtime)?, signal.signed))) }) .flatten(); let Some((width, signed)) = metadata else { @@ -1104,10 +1330,9 @@ pub unsafe extern "C" fn vpi_get_value(reference: VpiHandle, value: *mut VpiValu let Some((bits, mask, width)) = value_bits(id) else { return; }; - let signed = - with_runtime(|runtime| runtime.reflection().signal(id).map(|signal| signal.signed)) - .flatten() - .unwrap_or(false); + let signed = with_runtime(|runtime| id.resolve(runtime).map(|signal| signal.signed)) + .flatten() + .unwrap_or(false); // Safety: checked non-null above; caller owns the `VpiValue` allocation. encode_signal_value(handle, unsafe { &mut *value }, &bits, &mask, width, signed); } @@ -1246,16 +1471,23 @@ pub unsafe extern "C" fn vpi_put_value( return ptr::null_mut(); }; if with_runtime(|runtime| { - runtime - .reflection() - .signal(id) + id.resolve(runtime) .is_some_and(|signal| signal.is_parameter) }) .unwrap_or(false) { return ptr::null_mut(); } - let identity = with_runtime(|runtime| runtime.signal_identity(id)).flatten(); + if !with_runtime(|runtime| { + id.resolve(runtime) + .is_some_and(|signal| signal.unpacked_dims.is_empty()) + }) + .unwrap_or(false) + || (id.depth != 0 && matches!(flags, VPI_FORCE_FLAG | VPI_RELEASE_FLAG)) + { + return ptr::null_mut(); + } + let identity = with_runtime(|runtime| id.identity(runtime)).flatten(); let Some(identity) = identity else { return ptr::null_mut(); }; @@ -1265,7 +1497,7 @@ pub unsafe extern "C" fn vpi_put_value( }); let succeeded = released.is_none_or(|released| { with_runtime_mut(|runtime| { - let Some(signal) = runtime.reflection().signal(id).cloned() else { + let Some(signal) = id.resolve(runtime) else { return false; }; let (released_value, released_mask) = if matches!( @@ -1279,7 +1511,7 @@ pub unsafe extern "C" fn vpi_put_value( } else { (released.deposited_value, released.deposited_mask) }; - runtime.release_signal(id); + runtime.release_signal(id.root); let (old_value, old_mask) = runtime.backend().get_four_state(signal.signal); let old_level = logic_level(&old_value, &old_mask); let new_level = logic_level(&released_value, &released_mask); @@ -1312,11 +1544,11 @@ pub unsafe extern "C" fn vpi_put_value( } let signal_info = with_runtime(|runtime| { - runtime.reflection().signal(id).map(|signal| { - ( - signal.signal.width, + id.resolve(runtime).and_then(|signal| { + Some(( + id.width(runtime)?, signal.signal.is_4state && runtime.four_state(), - ) + )) }) }) .flatten(); @@ -1353,7 +1585,7 @@ pub unsafe extern "C" fn vpi_put_value( }) .or_else(|| { with_runtime(|runtime| { - let signal = runtime.reflection().signal(id)?; + let signal = id.resolve(runtime)?; Some(runtime.backend().get_four_state(signal.signal)) }) .flatten() @@ -1376,20 +1608,20 @@ pub unsafe extern "C" fn vpi_put_value( None }; let succeeded = with_runtime_mut(|runtime| { - let Some(signal) = runtime.reflection().signal(id).cloned() else { + let Some(signal) = id.resolve(runtime) else { + return false; + }; + let Some((old_value, old_mask)) = id.read(runtime) else { return false; }; - let (old_value, old_mask) = runtime.backend().get_four_state(signal.signal); let old_level = logic_level(&old_value, &old_mask); let new_level = logic_level(&bits, &mask); if flags == VPI_FORCE_FLAG { - if !runtime.force_signal(id, bits.clone(), mask.clone()) { + if !runtime.force_signal(id.root, bits.clone(), mask.clone()) { return false; } } else { - runtime - .backend_mut() - .set_four_state(signal.signal, bits.clone(), mask.clone()); + id.write(runtime, bits.clone(), mask.clone()); } with_host(|host| { borrow_cell_mut(&host.pending_writes, |pending| { @@ -1439,7 +1671,7 @@ fn flush_pending_writes() -> bool { return true; } let mut final_deposits = pending.deposits; - let mut replay_overrides: HashMap = HashMap::default(); + let mut replay_overrides: HashMap = HashMap::default(); for mut batch in pending.edge_batches { for (id, value) in &replay_overrides { batch.deposits.insert(*id, value.clone()); @@ -1453,7 +1685,7 @@ fn flush_pending_writes() -> bool { .into_iter() .filter_map(|identity| { let deposit = batch.deposits.get(&identity)?; - let signal = runtime.reflection().signal(deposit.id)?; + let signal = deposit.id.resolve(runtime)?; if overridden.contains(&identity) { let (old_value, old_mask) = runtime.backend().get_four_state(signal.signal); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index b0dd703a978..97d8035e9b8 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -3154,3 +3154,123 @@ fn two_state_image_converts_unknown_logic_deposits_and_forces() { } clear_runtime(); } + +#[cfg(feature = "systemverilog")] +#[test] +fn unpacked_array_handles_preserve_declared_indices_and_neighbor_values() { + let _serial = lock_vpi(); + let source = r#"module Top( + input logic [7:0] words [3:2][-1:1], + output logic [7:0] first, middle, last + ); + assign first=words[3][-1]; + assign middle=words[2][0]; + assign last=words[2][1]; + endmodule"#; + for (four_state, width) in [false, true] + .into_iter() + .flat_map(|four| [1, 8, 9, 65].map(|width| (four, width))) + { + let source = source.replace("[7:0]", &format!("[{}:0]", width - 1)); + let simulator = Simulator::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("arrays.sv"))], + "Top", + ) + .four_state(four_state) + .opt_level(celox::OptLevel::O1) + .build() + .unwrap(); + let bytes = simulator + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let runtime = unsafe { NativeProgramInstance::from_attached_bytes(&bytes) }.unwrap(); + let metadata = runtime.signal("Top.words").unwrap(); + assert_eq!(metadata.unpacked_ranges, [(3, 2), (-1, 1)]); + assert_eq!(runtime.reflection().signals().len(), 4); + let _session = install_runtime(runtime).unwrap(); + unsafe { + let array = vpi_handle_by_name(c"Top.words".as_ptr(), ptr::null_mut()); + assert_eq!(vpi_get(VPI_TYPE, array), VPI_REG_ARRAY); + assert_eq!(vpi_get(VPI_SIZE, array), 2); + assert!(vpi_handle_by_index(array, 1).is_null()); + for (kind, expected) in [(VPI_LEFT_RANGE, 3), (VPI_RIGHT_RANGE, 2)] { + let bound = vpi_handle(kind, array); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(bound, &mut value); + assert_eq!(value.value.integer, expected); + vpi_free_object(bound); + } + let row = vpi_handle_by_index(array, 2); + assert_eq!(vpi_get(VPI_SIZE, row), 3); + assert!(vpi_handle_by_index(row, -2).is_null()); + let middle = vpi_handle_by_index(row, 0); + let last = vpi_handle_by_index(row, 1); + let first = vpi_handle_by_name(c"Top.words[3][-1]".as_ptr(), ptr::null_mut()); + assert!(!first.is_null()); + assert_eq!(vpi_get(VPI_TYPE, middle), VPI_REG); + assert_eq!(vpi_get(VPI_SIZE, middle), width as i32); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, middle)), + c"Top.words[2][0]" + ); + let parent = vpi_handle(VPI_PARENT, middle); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, parent)), + c"Top.words" + ); + assert!(vpi_handle(VPI_PARENT, array).is_null()); + let val = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0xa5 }, + }; + assert!(!vpi_put_value(first, &val, ptr::null(), VPI_NO_DELAY).is_null()); + assert!(!vpi_put_value(last, &val, ptr::null(), VPI_NO_DELAY).is_null()); + let xz = VpiValue { + format: VPI_BIN_STR_VAL, + value: VpiValueData { + str_: if width == 1 { c"x" } else { c"10xz0101" } + .as_ptr() + .cast_mut(), + }, + }; + assert!(!vpi_put_value(middle, &xz, ptr::null(), VPI_NO_DELAY).is_null()); + assert!(vpi_put_value(array, &val, ptr::null(), VPI_NO_DELAY).is_null()); + assert!(vpi_put_value(middle, &val, ptr::null(), VPI_FORCE_FLAG).is_null()); + for (name, expected) in [ + (c"Top.first", if width == 1 { "1" } else { "10100101" }), + (c"Top.last", if width == 1 { "1" } else { "10100101" }), + ( + c"Top.middle", + match (four_state, width) { + (true, 1) => "x", + (false, 1) => "0", + (true, _) => "10xz0101", + (false, _) => "10000101", + }, + ), + ] { + let output = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + let mut value = VpiValue { + format: VPI_BIN_STR_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(output, &mut value); + assert_eq!( + CStr::from_ptr(value.value.str_).to_str().unwrap(), + format!("{expected:0>width$}"), + "{name:?}, width={width}" + ); + vpi_free_object(output); + } + for handle in [array, row, middle, last, first, parent] { + vpi_free_object(handle); + } + } + clear_runtime(); + } +} diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index 3b4b66860d9..ba7ef9a8ff6 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -143,7 +143,7 @@ fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { .arg(&results) .current_dir(&fixture) .env("COCOTB_TESTCASE", "inherited_selector_must_be_cleared") - .env("PYTHONPATH", python_path) + .env("PYTHONPATH", &python_path) .output() .unwrap(); assert!( @@ -530,3 +530,9 @@ fn cocotb_uses_declared_force_targets_in_an_optimized_native_image() { assert!(!xml.contains("> (element * array.element_width)) & &element_mask; let value_bytes = element_value.to_bytes_le(); diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index f0ab19b077a..2aeba1395d7 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 = 20; +const CONTAINER_VERSION: u16 = 21; 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/ir.rs b/crates/celox/src/ir.rs index 00743b70397..718e9675d66 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -54,6 +54,8 @@ pub struct RuntimeVariable { pub var_kind: VariableKind, pub signed: bool, pub packed_dims: Vec, + /// Declared unpacked bounds, in storage order; empty uses zero-based dimensions. + pub unpacked_ranges: Vec<(i128, i128)>, } /// One elaborated runtime instance with direct state-address indices. @@ -153,6 +155,7 @@ impl RuntimeDesign { var_kind: info.var_kind, signed: info.signed, packed_dims: info.packed_dims.clone(), + unpacked_ranges: info.unpacked_ranges.clone(), }, ); } @@ -253,6 +256,7 @@ impl RuntimeDesign { signed: variable.signed, metadata: self.semantic.state_objects.get(address)?.clone(), packed_dims: variable.packed_dims.clone(), + unpacked_ranges: variable.unpacked_ranges.clone(), }) } @@ -1049,6 +1053,15 @@ impl RuntimeProgram { }, signed: variable.signed, packed_dims: variable.packed_dims.clone(), + unpacked_ranges: if variable.unpacked_ranges.is_empty() { + metadata + .array_dims + .iter() + .map(|size| (0, *size as i128 - 1)) + .collect() + } else { + variable.unpacked_ranges.clone() + }, unpacked_dims: metadata.array_dims.clone(), type_kind: metadata.type_kind, }); diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 0ea1dda00d7..b8783be3342 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -674,6 +674,25 @@ fn native_program_image_rejects_v16_before_decoding_host_request_schema() { )); } +/// Version 21 retains declared unpacked bounds in runtime and VPI metadata. +#[test] +fn native_program_image_rejects_v20_before_decoding_unpacked_bound_schema() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&20u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(20)) + )); +} + #[test] fn native_program_image_rejects_v3_before_decoding_changed_schema() { let sim = Simulator::builder(ADDER, "Top").build().unwrap(); From 15351aea5f3fb56bb44df643d83070ef391257db Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:29:54 +0900 Subject: [PATCH 6/8] fix(cli): reject empty cocotb test selections Parse cocotb JUnit results with Python's standard library and require at least one executed test. Report failures and errors with a nonzero process status, including statuses that previously wrapped to zero on Unix. Accept successful runs that also contain skipped tests. Validation: checked the embedded result parser against seven XML fixtures, including empty/all-skipped, mixed, failure/error, 256 failures and malformed results; opt-in cocotb end-to-end regression tests include an unmatched filter and verify that the generated executable rejects it; formatting and affected-crate Clippy. Change-Id: I93316d15fc83f37bc786288376446d3ae825c1ed --- crates/celox-vpi/src/bin/celox.rs | 14 +++++++++++++- crates/celox-vpi/tests/cocotb_e2e.rs | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 99295fba55a..46d2a3882eb 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -571,7 +571,19 @@ fn discover_vpi(python: &Path) -> Result { fn check_results(python: &Path, results_file: &Path) -> Result<(), String> { let output = Command::new(python) - .args([OsStr::new("-m"), OsStr::new("cocotb_tools.check_results")]) + .args(["-c", r#" +import sys +from xml.etree import ElementTree + +cases = list(ElementTree.parse(sys.argv[1]).getroot().iter("testcase")) +executed = [case for case in cases if case.find("skipped") is None] +failed = [case for case in executed if case.find("failure") is not None or case.find("error") is not None] +if not executed: + sys.exit("no cocotb tests were executed (check the test filter and skip settings)") +if failed: + names = ", ".join(case.get("name", "") for case in failed[:8]) + sys.exit(f"{len(failed)} cocotb test(s) failed: {names}") +"#]) .arg(results_file) .output() .map_err(|error| format!("failed to check cocotb results: {error}"))?; diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index ba7ef9a8ff6..d2049d78e88 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -155,6 +155,31 @@ fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) { assert!(results.is_file()); + let unmatched = Command::new(&executable) + .args([ + "--test-module", + module, + "--test-filter", + "^no_such_cocotb_test$", + "--python", + &python, + ]) + .arg("--results-file") + .arg(&results) + .current_dir(&fixture) + .env("PYTHONPATH", &python_path) + .output() + .unwrap(); + assert!( + !unmatched.status.success(), + "an empty test selection was reported as successful" + ); + assert!( + String::from_utf8_lossy(&unmatched.stderr).contains("no cocotb tests were executed"), + "{}", + String::from_utf8_lossy(&unmatched.stderr) + ); + let failed_runtime = Command::new(&executable) .args(["--test-module", "missing_test_module", "--python", &python]) .arg("--results-file") From 69645dc605bf172fe25f0c009cabdeccddf6d7f5 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:44:00 +0900 Subject: [PATCH 7/8] perf(vpi): avoid metadata cloning during value access Resolve compact signal storage separately from owned reflection metadata. Read widths, signedness and array leaf status without copying signal names or dimensions, and acquire the active host once per value snapshot. Copy only the forced value/mask needed by a read instead of its deposited-value history. Keep lazy array addressing, four-state mask offsets, callback identity and write ordering unchanged. A release profile of Taxi's eight-bit 1x1 crossbar shows value_bits taking about 12% of sampled CPU time before this change and about 7% afterwards. Four alternating fixed-seed runs of the no-pause stress test per version reduce median user CPU time from 28.34s to 26.47s (6.6%); each run executes one test and skips the other eleven. Validation: VPI unit/API tests (46 passed), opt-in cocotb integration tests (4 passed), formatting and affected-crate Clippy. Existing regressions cover multidimensional and bit-packed arrays, sibling preservation, alias identity, forces, callbacks and session ownership. Change-Id: I64bd0bd37b50d4aeef39f321aed85612dcdeae9b --- crates/celox-vpi/src/lib.rs | 142 +++++++++++++++++++++--------------- 1 file changed, 82 insertions(+), 60 deletions(-) diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index c2453493604..157fd95dcb2 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -138,14 +138,15 @@ impl SignalSelection { } } - fn resolve(self, runtime: &NativeProgramInstance) -> Option { - let mut signal = runtime.reflection().signal(self.root)?.clone(); + /// Resolve storage without cloning hierarchy names or dimension metadata. + fn signal(self, runtime: &NativeProgramInstance) -> Option { + let root = runtime.reflection().signal(self.root)?; + let mut signal = root.signal; if self.depth == 0 { return Some(signal); } - let count = signal.unpacked_dims.iter().product::(); - let element_width = signal.signal.width / count; - let remaining = signal + let count = root.unpacked_dims.iter().product::(); + let remaining = root .unpacked_dims .get(self.depth..)? .iter() @@ -153,6 +154,33 @@ impl SignalSelection { if self.first.checked_add(remaining)? > count { return None; } + if let Some(mut array) = signal.array_layout { + signal.offset = signal + .offset + .checked_add(self.first.checked_mul(array.element_stride)?)?; + signal.width = remaining.checked_mul(root.signal.width / count)?; + array.element_count = remaining; + signal.array_layout = Some(array); + } + Some(signal) + } + + fn domain_kind(self, runtime: &NativeProgramInstance) -> Option { + let root = runtime.reflection().signal(self.root)?; + Some(if self.depth == 0 { + root.domain_kind + } else { + DomainKind::Other + }) + } + + fn resolve(self, runtime: &NativeProgramInstance) -> Option { + let mut signal = runtime.reflection().signal(self.root)?.clone(); + signal.signal = self.signal(runtime)?; + if self.depth == 0 { + return Some(signal); + } + let count = signal.unpacked_dims.iter().product::(); let mut stride = count; for (&size, &(left, right)) in signal .unpacked_dims @@ -171,15 +199,6 @@ impl SignalSelection { signal.name.push_str(&suffix); signal.full_name.push_str(&suffix); } - if let Some(mut array) = signal.signal.array_layout { - signal.signal.offset = signal - .signal - .offset - .checked_add(self.first.checked_mul(array.element_stride)?)?; - signal.signal.width = remaining.checked_mul(element_width)?; - array.element_count = remaining; - signal.signal.array_layout = Some(array); - } signal.unpacked_dims.drain(..self.depth); signal.unpacked_ranges.drain(..self.depth); signal.domain_kind = DomainKind::Other; @@ -228,17 +247,18 @@ impl SignalSelection { } fn width(self, runtime: &NativeProgramInstance) -> Option { - Some( - self.slice(runtime) - .map_or(self.resolve(runtime)?.signal.width, |(_, width)| width), - ) + if let Some((_, width)) = self.slice(runtime) { + Some(width) + } else { + Some(self.signal(runtime)?.width) + } } fn identity(self, runtime: &NativeProgramInstance) -> Option { let storage = if self.depth == 0 || self.slice(runtime).is_some() { runtime.signal_identity(self.root)? } else { - NativeSignalIdentity::State(self.resolve(runtime)?.signal) + NativeSignalIdentity::State(self.signal(runtime)?) }; Some(VpiSignalIdentity { storage, @@ -247,7 +267,7 @@ impl SignalSelection { } fn read(self, runtime: &NativeProgramInstance) -> Option<(BigUint, BigUint)> { - let signal = self.resolve(runtime)?.signal; + let signal = self.signal(runtime)?; let Some((offset, width)) = self.slice(runtime) else { return Some(runtime.backend().get_four_state(signal)); }; @@ -265,7 +285,7 @@ impl SignalSelection { } fn write(self, runtime: &mut NativeProgramInstance, bits: BigUint, mask: BigUint) { - let Some(signal) = self.resolve(runtime).map(|signal| signal.signal) else { + let Some(signal) = self.signal(runtime) else { return; }; let Some((offset, width)) = self.slice(runtime) else { @@ -1163,26 +1183,22 @@ pub unsafe extern "C" fn vpi_get_str(property: i32, reference: VpiHandle) -> *mu } fn value_bits(id: SignalSelection) -> Option<(BigUint, BigUint, usize)> { - if !with_runtime(|runtime| { - id.resolve(runtime) - .is_some_and(|signal| signal.unpacked_dims.is_empty()) - }) - .unwrap_or(false) - { - return None; - } - let (identity, width) = - with_runtime(|runtime| Some((id.identity(runtime)?, id.width(runtime)?))).flatten()?; - if let Some(forced) = - with_host(|host| borrow_cell(&host.forced_values, |forced| forced.get(&identity).cloned())) - { - return Some((forced.value, forced.mask, width)); - } - with_runtime(|runtime| { - let (value, mask) = id.read(runtime)?; - Some((value, mask, id.width(runtime)?)) + with_host(|host| { + borrow_cell(&host.runtime, |runtime| { + let runtime = runtime.as_ref()?; + let signal = runtime.reflection().signal(id.root)?; + if id.depth != signal.unpacked_dims.len() { + return None; + } + let width = id.width(runtime)?; + let identity = id.identity(runtime)?; + if let Some(forced) = host.forced_values.borrow().get(&identity) { + return Some((forced.value.clone(), forced.mask.clone(), width)); + } + let (value, mask) = id.read(runtime)?; + Some((value, mask, width)) + }) }) - .flatten() } fn format_binary(value: &BigUint, mask: &BigUint, width: usize) -> String { @@ -1290,7 +1306,9 @@ unsafe fn write_snapshot_value( return; }; let metadata = with_runtime(|runtime| { - id.resolve(runtime) + runtime + .reflection() + .signal(id.root) .and_then(|signal| Some((id.width(runtime)?, signal.signed))) }) .flatten(); @@ -1330,9 +1348,14 @@ pub unsafe extern "C" fn vpi_get_value(reference: VpiHandle, value: *mut VpiValu let Some((bits, mask, width)) = value_bits(id) else { return; }; - let signed = with_runtime(|runtime| id.resolve(runtime).map(|signal| signal.signed)) - .flatten() - .unwrap_or(false); + let signed = with_runtime(|runtime| { + runtime + .reflection() + .signal(id.root) + .map(|signal| signal.signed) + }) + .flatten() + .unwrap_or(false); // Safety: checked non-null above; caller owns the `VpiValue` allocation. encode_signal_value(handle, unsafe { &mut *value }, &bits, &mask, width, signed); } @@ -1471,7 +1494,9 @@ pub unsafe extern "C" fn vpi_put_value( return ptr::null_mut(); }; if with_runtime(|runtime| { - id.resolve(runtime) + runtime + .reflection() + .signal(id.root) .is_some_and(|signal| signal.is_parameter) }) .unwrap_or(false) @@ -1479,8 +1504,10 @@ pub unsafe extern "C" fn vpi_put_value( return ptr::null_mut(); } if !with_runtime(|runtime| { - id.resolve(runtime) - .is_some_and(|signal| signal.unpacked_dims.is_empty()) + runtime + .reflection() + .signal(id.root) + .is_some_and(|signal| id.depth == signal.unpacked_dims.len()) }) .unwrap_or(false) || (id.depth != 0 && matches!(flags, VPI_FORCE_FLAG | VPI_RELEASE_FLAG)) @@ -1544,12 +1571,10 @@ pub unsafe extern "C" fn vpi_put_value( } let signal_info = with_runtime(|runtime| { - id.resolve(runtime).and_then(|signal| { - Some(( - id.width(runtime)?, - signal.signal.is_4state && runtime.four_state(), - )) - }) + Some(( + id.width(runtime)?, + id.signal(runtime)?.is_4state && runtime.four_state(), + )) }) .flatten(); let Some((width, is_4state)) = signal_info else { @@ -1584,11 +1609,8 @@ pub unsafe extern "C" fn vpi_put_value( }) }) .or_else(|| { - with_runtime(|runtime| { - let signal = id.resolve(runtime)?; - Some(runtime.backend().get_four_state(signal.signal)) - }) - .flatten() + with_runtime(|runtime| Some(runtime.backend().get_four_state(id.signal(runtime)?))) + .flatten() }); let Some((deposited_value, deposited_mask)) = deposited else { return ptr::null_mut(); @@ -1608,7 +1630,7 @@ pub unsafe extern "C" fn vpi_put_value( None }; let succeeded = with_runtime_mut(|runtime| { - let Some(signal) = id.resolve(runtime) else { + let Some(domain_kind) = id.domain_kind(runtime) else { return false; }; let Some((old_value, old_mask)) = id.read(runtime) else { @@ -1631,7 +1653,7 @@ pub unsafe extern "C" fn vpi_put_value( identity, bits.clone(), mask.clone(), - signal.domain_kind, + domain_kind, old_level, new_level, ); From 0bbfaa140318e28358ac623238d662b0a97dd253 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:49:06 +0900 Subject: [PATCH 8/8] perf(sv): reuse constants when expression contexts match Constant evaluation first computed each operand in its own context and then walked the same subtree again even when width and signedness were unchanged. Nested casts repeated this work, causing pathological growth in deep trees. Reuse the computed value for matching contexts and for casts that do not widen their operand. Reevaluate operands when width or signedness changes, preserving context-dependent carries, division and four-state values under IEEE 1800-2023 11.8.2. Taxi BASE-R compilation with the debug host and generated O1 code decreases from 174 seconds to 55 seconds. The release host improves from 30.9 seconds to 8.4 seconds (user CPU 25.95s to 8.01s); generated code remains at O1. The release baseline attributes about 60% of sampled CPU time to context_binary_operands. The unchanged selected upstream cocotb cases both pass after the optimization (2 executed, 238 skipped). The full BASE-R matrix still needs the upstream 1fs precision override, which the current CLI harness does not support; no all-matrix pass is claimed. Validation: deep 48-layer constant casts including X/Z, widening carries and signedness-changing division; 36 focused literal tests; full analyzer tests (762 passed, 3 ignored); full SystemVerilog suite across five backends (3242 passed, 90 ignored); formatting and affected-crate Clippy. Change-Id: I2bdbf133a10a898df17646cf566fa5a24496ff15 --- crates/celox-sv-analyzer/src/typecheck.rs | 79 +++++++++++++++++++++-- 1 file changed, 74 insertions(+), 5 deletions(-) diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 5eb7cb7aa24..ae2df0d402f 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -615,9 +615,21 @@ fn context_binary_operands( let (left_type, right_type) = integral_binary_operands(left, right)?; let width = left_type.width.max(right_type.width); let signed = left_type.signed && right_type.signed; - let left = eval_integral_in_context(left, width, signed)?; - let right = eval_integral_in_context(right, width, signed)?; - Some((left, right, signed)) + // These values were already evaluated in their own expression contexts. + // IEEE 1800-2023 11.8.2 requires another descent only when the enclosing + // context changes their size or signedness. + let in_context = |expr, literal: IntegralLiteral| { + if literal.width == width && literal.signed == signed { + Some(literal) + } else { + eval_integral_in_context(expr, width, signed) + } + }; + Some(( + in_context(left, left_type)?, + in_context(right, right_type)?, + signed, + )) } fn eval_literal_binary( @@ -987,8 +999,11 @@ fn integral_literal_from_const_expr(expr: &ConstExpr) -> Option return Some(literal); } let operand = self_determined_integral_literal(expr)?; - let operand = - eval_integral_in_context(expr, (*width).max(operand.width), operand.signed)?; + let operand = if *width <= operand.width { + operand + } else { + eval_integral_in_context(expr, *width, operand.signed)? + }; let extension = signed_extension(&operand, operand.signed); Some(resize_integral_literal(operand, *width, *signed, extension)) } @@ -1802,6 +1817,60 @@ fn extension_for_leading_digit(ch: char) -> (bool, bool) { mod literal_tests { use super::*; + #[test] + fn evaluates_deep_constant_casts_without_repeated_context_walks() { + for (value, expected) in [("32'h12", "32'h12"), ("32'h1z", "32'h1x")] { + let mut expr = ConstExpr::Literal(value.into()); + // Each layer used to evaluate every inner layer twice. Keep this + // deep enough to catch that growth without a wall-clock assertion. + for _ in 0..48 { + expr = ConstExpr::Resize { + expr: Box::new(ConstExpr::Binary { + left: Box::new(expr), + op: BinaryOp::BitXor, + right: Box::new(ConstExpr::Literal("32'hf".into())), + }), + width: 32, + signed: false, + }; + } + assert_eq!( + integral_literal_from_const_expr(&expr), + parse_integral_literal(expected) + ); + } + } + + #[test] + fn changed_constant_contexts_recompute_width_and_signedness() { + let binary = |left, op, right| ConstExpr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + let carry = binary( + ConstExpr::Literal("32'hffffffff".into()), + BinaryOp::Add, + ConstExpr::Literal("32'd1".into()), + ); + let widened = binary(carry, BinaryOp::Add, ConstExpr::Literal("64'd0".into())); + assert_eq!( + integral_literal_from_const_expr(&widened), + parse_integral_literal("64'h100000000") + ); + + let quotient = binary( + ConstExpr::Literal("32'shffffffff".into()), + BinaryOp::Div, + ConstExpr::Literal("32'sd2".into()), + ); + let unsigned = binary(quotient, BinaryOp::Add, ConstExpr::Literal("32'd0".into())); + assert_eq!( + integral_literal_from_const_expr(&unsigned), + parse_integral_literal("32'h7fffffff") + ); + } + #[test] fn evaluates_nested_logical_parameter_chains() { let constants = HashMap::from_iter([("P".to_string(), 1)]);