From b4072788d475209d41e1cfba97133674b33c3dbc Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 00:46:58 +0900 Subject: [PATCH 1/2] feat(cli)!: unify benchmark execution under celox run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Heliodor previously used a separate Celox executable with backend selection, parallel execution, timing, caching and native-image support that ordinary CLI users could not access. Move that execution path into celox run and remove the celox-heliodor binary. Heliodor now invokes celox run --report --unlimited; its tiered runner also requires compiled execution and retains the configured thread count. For both SystemVerilog and Veryl, expose native/tiered/interpreter/Cranelift/WASM selection with explicit thread and state modes. Add timed tiered construction that preserves initial scheduling and live state across promotion. Keep normal runs free of JIT timing overhead and preserve execution limits and failures. Veryl additionally supports compilation caching, image import/export, compiler diagnostics and opt-in machine-readable timing records. Accept Veryl project directories and explicit source selection through the normal project resolver. Include CLI parameter, diagnostic and signal-access settings in cache identity. Compile exported VPI artifacts without initializing executable memory, retaining their warnings and supporting cross-codegen builds. Update benchmark scripts, ARM profiling, CI selection and both language guides. Resolve source-file paths against celox.toml's directory, report native images' embedded state mode, and return usage status 2 for invalid execution options. Preserve warnings from fresh native compile-only builds and reject combining compile-only with dump-ir-and-run. Reject legacy profiling-run reuse early with rebuild instructions; comparison baselines still accept legacy executables. Clamp default benchmark threads to 2–64 and reset inherited overrides in the fixed gate. Validation: - cargo test --locked -p celox-vpi: 127 passed, including review regressions and all five CLI backends in two-state/four-state mode. - Timed process tests: 9 passed, including actual tiered promotion with pending delayed processes, NBA updates, and 1/4-thread configurations. - Clippy for celox and celox-vpi across all targets, formatting, API docs, script tests, Heliodor result/gate fixtures, workflow YAML parsing and syntax checks for all 19 shell steps passed. - Earlier validation also passed bench tests, the three explicit cocotb tests, ARM64 cross-codegen image export, and the CLI no-default-features check. ARM hardware Linux boot benchmarks were not run. Existing cargo-deny CI fails on Wasmtime 49.0.3 advisories; dependency remediation is outside this CLI change. BREAKING CHANGE: celox run now defaults to two-state simulation for both SystemVerilog and Veryl. Pass --four-state to retain X/Z tracking. The internal celox-heliodor executable is replaced by celox run. Change-Id: I7db09e5916dcec3a0173ad3df4901ff82eb72bb8 --- .github/workflows/heliodor-bench.yml | 25 +- Cargo.lock | 10 +- crates/celox-bench/Cargo.toml | 3 - crates/celox-vpi/Cargo.toml | 13 +- crates/celox-vpi/src/bin/celox.rs | 164 +++-- crates/celox-vpi/src/bin/celox/project.rs | 219 ++++--- .../src/bin/celox/runner.rs} | 570 ++++++++++-------- .../src/bin/celox/runner}/build_cache.rs | 18 +- crates/celox-vpi/src/driver.rs | 13 +- .../tests/run_build_cache.rs} | 19 +- crates/celox-vpi/tests/run_cli.rs | 212 ++++++- crates/celox-vpi/tests/run_cross_codegen.rs | 44 ++ .../tests/run_diagnostics.rs} | 49 +- crates/celox/src/backend/native/backend.rs | 2 +- crates/celox/src/simulation.rs | 63 +- crates/celox/src/simulator/builder.rs | 22 + docs/benchmarks/heliodor.md | 5 +- docs/guide/cocotb.md | 43 +- docs/ja/benchmarks/heliodor.md | 5 +- docs/ja/guide/cocotb.md | 30 +- scripts/benchmark-workflows.test.mjs | 10 + scripts/ci-changes.mjs | 3 +- scripts/ci-changes.test.mjs | 4 +- scripts/run-heliodor-bench.sh | 50 +- scripts/tests/run-heliodor-bench-gate.sh | 24 +- scripts/tests/run-heliodor-bench-results.sh | 6 + 26 files changed, 1111 insertions(+), 515 deletions(-) rename crates/{celox-bench/src/bin/celox-heliodor.rs => celox-vpi/src/bin/celox/runner.rs} (75%) rename crates/{celox-bench/src/bin/heliodor => celox-vpi/src/bin/celox/runner}/build_cache.rs (97%) rename crates/{celox-bench/tests/celox_heliodor_build_cache.rs => celox-vpi/tests/run_build_cache.rs} (97%) create mode 100644 crates/celox-vpi/tests/run_cross_codegen.rs rename crates/{celox-bench/tests/celox_heliodor_diagnostics.rs => celox-vpi/tests/run_diagnostics.rs} (52%) diff --git a/.github/workflows/heliodor-bench.yml b/.github/workflows/heliodor-bench.yml index f83b047a3f7..eae98ca9ccc 100644 --- a/.github/workflows/heliodor-bench.yml +++ b/.github/workflows/heliodor-bench.yml @@ -211,6 +211,15 @@ jobs: run-id: ${{ inputs.arm64_profile_run_id }} github-token: ${{ github.token }} + - name: Validate reused ARM64 profiling runner + if: inputs.arm64_profile && inputs.arm64_profile_run_id != '' + shell: bash + run: | + if [[ ! -f target/release/celox ]]; then + echo "::error::This profiling artifact predates the celox run CLI. Leave arm64_profile_run_id empty to build a compatible runner; legacy artifacts remain supported as comparison baselines." + exit 1 + fi + - name: Prepare ARM64 profiling if: inputs.arm64_profile shell: bash @@ -252,7 +261,13 @@ jobs: source scripts/run-heliodor-bench.sh trap cleanup_heliodor_fallback EXIT prepare - baseline_runner="$GITHUB_WORKSPACE/target/heliodor-arm64/baseline-runners/celox-heliodor" + baseline_runner="$GITHUB_WORKSPACE/target/heliodor-arm64/baseline-runners/celox" + baseline_args=(run --report --unlimited --top test_soc_linux_boot) + # Retained comparison artifacts may predate the CLI migration. + if [[ ! -f "$baseline_runner" ]]; then + baseline_runner="$GITHUB_WORKSPACE/target/heliodor-arm64/baseline-runners/celox-heliodor" + baseline_args=(--test test_soc_linux_boot) + fi veryl_runner="$GITHUB_WORKSPACE/target/heliodor-arm64/baseline-runners/veryl-heliodor" veryl_cache="$GITHUB_WORKSPACE/target/heliodor-arm64/compare-veryl-cache" chmod +x "$baseline_runner" "$CELOX_RUNNER_BIN" @@ -280,7 +295,9 @@ jobs: timeout 1200 "$veryl_runner" --project "$HELIODOR_DIR" --test test_soc_linux_boot \ "${args[@]}" > "$log" 2>&1 else - timeout 1200 "$runner" --project "$HELIODOR_DIR" --test test_soc_linux_boot \ + cli_args=(run --report --unlimited --top test_soc_linux_boot) + if [[ "$label" == baseline ]]; then cli_args=("${baseline_args[@]}"); fi + timeout 1200 "$runner" "${cli_args[@]}" --project "$HELIODOR_DIR" \ --backend native --opt-level o2 "${args[@]}" > "$log" 2>&1 fi echo "comparison=$label round=$comparison_round" @@ -301,7 +318,7 @@ jobs: for source in "${sources[@]}"; do args+=(--source-file "$source"); done cd "$HELIODOR_DIR" "$PERF_BIN" record -e cpu-clock:u -F 997 -o "$HELIODOR_RESULTS_DIR/perf.data" -- \ - timeout 1200 "$CELOX_RUNNER_BIN" --project "$HELIODOR_DIR" --test test_soc_linux_boot \ + timeout 1200 "$CELOX_RUNNER_BIN" run --report --unlimited --project "$HELIODOR_DIR" --top test_soc_linux_boot \ --backend native --opt-level o2 "${args[@]}" \ --dump-ir-dir "$HELIODOR_RESULTS_DIR/profile-ir" --dump-ir-and-run \ > "$HELIODOR_RESULTS_DIR/profile-linux.log" 2>&1 @@ -321,7 +338,7 @@ jobs: name: heliodor-arm64-profiling-runners retention-days: 7 path: | - target/release/celox-heliodor + target/release/celox target/release/veryl-heliodor - name: Upload nightly ARM64 Linux boot results diff --git a/Cargo.lock b/Cargo.lock index 6179911501e..c5df3d887e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -533,15 +533,12 @@ dependencies = [ name = "celox-bench" version = "0.11.0" dependencies = [ - "blake3", "celox", "celox-design", - "celox-frontend-veryl", "clap", "fxhash", "libc", "object 0.40.0", - "pathdiff", "serde", "serde_json", "tempfile", @@ -825,15 +822,22 @@ dependencies = [ name = "celox-vpi" version = "0.11.0" dependencies = [ + "blake3", "celox", "celox-design", + "celox-frontend-veryl", "celox-sv-analyzer", "clap", "fxhash", + "libc", "libloading", + "pathdiff", "serde", + "serde_json", "tempfile", + "thiserror 2.0.21", "toml", + "tracing-subscriber", "veryl-metadata", ] diff --git a/crates/celox-bench/Cargo.toml b/crates/celox-bench/Cargo.toml index b5fb5d4a37d..f60dc650a26 100644 --- a/crates/celox-bench/Cargo.toml +++ b/crates/celox-bench/Cargo.toml @@ -14,14 +14,11 @@ arm64-codegen = ["celox/arm64-codegen"] x86_64-codegen = ["celox/x86_64-codegen"] [dependencies] -blake3 = "1.8" celox = { path = "../celox" } -celox-frontend-veryl = { path = "../celox-frontend-veryl" } clap = { workspace = true } fxhash = { workspace = true } libc = { workspace = true } object = { version = "0.40", default-features = false, features = ["read_core", "elf", "std"] } -pathdiff = "0.2" serde = { workspace = true } serde_json = { workspace = true } tempfile = { workspace = true } diff --git a/crates/celox-vpi/Cargo.toml b/crates/celox-vpi/Cargo.toml index 2fbdfa3cc2f..19bba376bfb 100644 --- a/crates/celox-vpi/Cargo.toml +++ b/crates/celox-vpi/Cargo.toml @@ -10,6 +10,8 @@ edition.workspace = true [features] default = ["systemverilog"] +arm64-codegen = ["celox/arm64-codegen"] +x86_64-codegen = ["celox/x86_64-codegen"] systemverilog = ["celox/systemverilog", "dep:celox-sv-analyzer"] [lib] @@ -36,6 +38,14 @@ celox = { path = "../celox", features = ["systemverilog"] } celox = { path = "../celox", features = ["systemverilog"] } [dependencies] +blake3 = "1.8" +celox-frontend-veryl = { path = "../celox-frontend-veryl" } +libc.workspace = true +pathdiff = "0.2" +serde_json.workspace = true +thiserror.workspace = true +tempfile.workspace = true +tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "env-filter"] } celox-design.workspace = true celox-sv-analyzer = { workspace = true, optional = true } clap.workspace = true @@ -45,8 +55,7 @@ serde.workspace = true toml.workspace = true veryl-metadata.workspace = true -[dev-dependencies] -tempfile.workspace = true + [lints] workspace = true diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 89dde289003..040afeae2ab 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -16,6 +16,8 @@ use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand}; #[path = "celox/project.rs"] mod project; +#[path = "celox/runner.rs"] +mod runner; use project::{Design, DesignArgs}; #[derive(Parser)] @@ -44,6 +46,9 @@ struct RunArgs { #[command(flatten)] design: DesignArgs, + #[command(flatten)] + execution: runner::ExecutionArgs, + /// Maximum SV scheduler steps or Veryl ticks (default: project setting or 1000000). /// Does not bound compilation or work within a single step/tick. #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] @@ -51,6 +56,7 @@ struct RunArgs { } struct RunConfig { + execution: runner::ExecutionArgs, design: Design, opt_level: celox::OptLevel, max_steps: u64, @@ -92,8 +98,16 @@ fn parse_opt_level(value: &str) -> Result { } fn resolve_run_config(arguments: RunArgs) -> RunConfig { - let design = resolve_design(arguments.design); + let design = arguments + .design + .resolve_for_run(arguments.execution.native_image_input.is_some()) + .unwrap_or_else(|message| { + Cli::command() + .error(clap::error::ErrorKind::InvalidValue, message) + .exit() + }); RunConfig { + execution: arguments.execution, opt_level: design.opt_level.unwrap_or(celox::OptLevel::O2), max_steps: arguments .max_steps @@ -104,7 +118,8 @@ fn resolve_run_config(arguments: RunArgs) -> RunConfig { } fn run_testbench(arguments: RunArgs) -> Result<(), String> { - let arguments = resolve_run_config(arguments); + let mut arguments = resolve_run_config(arguments); + arguments.design.opt_level = Some(arguments.opt_level); if arguments.design.is_sv() { #[cfg(feature = "systemverilog")] return run_sv(arguments); @@ -114,112 +129,65 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { .to_string(), ); } - if arguments.design.sources.len() != 1 - || !arguments.design.sources[0] - .extension() - .is_some_and(|extension| extension == "veryl") - { - return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); - } - let source = &arguments.design.sources[0]; - let mut metadata = veryl_metadata::Metadata::search_from(source) - .ok() - .map(|path| { - veryl_metadata::Metadata::load(&path) - .map_err(|error| format!("failed to load {}: {error}", path.display())) + if arguments.execution.native_image_input.is_none() + && !arguments.design.sources.iter().all(|path| { + path.extension() + .is_some_and(|extension| extension == "veryl") }) - .transpose()?; - let mut paths: Vec = if let Some(metadata) = &mut metadata { - metadata - .paths::<&Path>(&[], false, true) - .map_err(|error| format!("failed to discover project sources: {error}"))? - .into_iter() - .map(|path| path.src) - .collect() - } else { - Vec::new() - }; - let entry = source - .canonicalize() - .map_err(|error| format!("failed to read {}: {error}", source.display()))?; - if !paths.iter().any(|path| path == &entry) { - paths.push(entry); - } - let sources = paths - .iter() - .map(|path| { - std::fs::read_to_string(path) - .map(|text| (text, path.as_path())) - .map_err(|error| format!("failed to read {}: {error}", path.display())) - }) - .collect::, _>>()?; - let mut builder = celox::Simulator::from_sources( - sources - .iter() - .map(|(text, path)| (text.as_str(), *path)) - .collect(), - &arguments.design.top, - ) - .four_state(true) - .opt_level(arguments.opt_level) - .diagnostic_policy(arguments.design.diagnostics.clone()) - .signal_access(arguments.design.signal_access.clone()); - builder = arguments.design.apply_parameters(builder); - if let Some(metadata) = metadata { - builder = builder.with_metadata(metadata); - } - let mut simulator = builder - .build() - .map_err(|error| format!("compilation failed:\n{error}"))?; - report_warnings(simulator.warnings())?; - let program = celox::testbench::compile_initial_testbench(&simulator).ok_or_else(|| { - "selected module has no native testbench; select a #[test] module with --top".to_string() - })?; - let result = celox::testbench::run_compiled_testbench_with_tick_limit( - &mut simulator, - &program, - arguments.max_steps, - ); - if result.tick_limit_reached { - return Err(format!( - "simulation reached --max-steps {} testbench ticks before completion", - arguments.max_steps - )); - } - match result.result { - celox::TestResult::Pass => Ok(()), - celox::TestResult::Fail(message) => Err(message), + { + return Err("pass .sv/.v sources, or Veryl project sources".into()); } + runner::run(arguments.execution, arguments.design, arguments.max_steps).map_err(|error| { + if let runner::RunError::InvalidConfiguration { .. } = &error { + clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, error.to_string()).exit(); + } + error.to_string() + }) } #[cfg(feature = "systemverilog")] fn run_sv(arguments: RunConfig) -> Result<(), String> { + arguments.execution.validate_sv().unwrap_or_else(|message| { + clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, message).exit() + }); let sources = arguments.design.sv_sources()?; let source_refs = sources .iter() .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); let builder = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) - .four_state(true) + .four_state(arguments.execution.four_state) + .threads(arguments.execution.threads as usize) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) .signal_access(arguments.design.signal_access.clone()); - let simulation = arguments - .design - .apply_parameters(builder) - .build() - .map_err(|error| format!("compilation failed:\n{error}"))?; - report_warnings(simulation.warnings())?; - simulate_sv( - simulation, - arguments.max_steps, - &mut std::io::stdout().lock(), - ) + let builder = arguments.design.apply_parameters(builder); + let max_steps = if arguments.execution.unlimited { + u64::MAX + } else { + arguments.max_steps + }; + macro_rules! execute { + ($build:ident) => {{ + let simulation = builder + .$build() + .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulation.warnings())?; + simulate_sv(simulation, max_steps, &mut std::io::stdout().lock()) + }}; + } + match arguments.execution.backend { + runner::Backend::Native => execute!(build), + runner::Backend::Cranelift => execute!(build_cranelift), + runner::Backend::Interpreter => execute!(build_interpreter), + runner::Backend::Wasm => execute!(build_wasm), + runner::Backend::Tiered => execute!(build_tiered), + } } #[cfg(feature = "systemverilog")] -fn simulate_sv( - mut simulation: celox::Simulation, +fn simulate_sv( + mut simulation: celox::Simulation, max_steps: u64, output: &mut impl Write, ) -> Result<(), String> { @@ -246,8 +214,8 @@ fn simulate_sv( } #[cfg(feature = "systemverilog")] -fn drain_sv_output( - simulation: &mut celox::Simulation, +fn drain_sv_output( + simulation: &mut celox::Simulation, output: &mut impl Write, failed: &mut bool, ) -> Result<(), String> { @@ -441,10 +409,10 @@ fn compile_native_design(design: &Design) -> Result .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); let simulator = design .apply_parameters(builder) - .build() + .compile_native() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulator.warnings())?; - return Ok(simulator.shared_code().program_image().clone()); + return Ok(simulator.into_program_image()); } #[cfg(not(feature = "systemverilog"))] return Err( @@ -834,6 +802,14 @@ fn run() -> Result { } fn main() -> ExitCode { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("off")), + ) + .with_writer(std::io::stderr) + .with_ansi(false) + .init(); match run() { Ok(code) => code, Err(error) => { diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index a3d8e4fa9a2..4a46c0528be 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -12,6 +12,9 @@ use serde::Deserialize; pub(super) struct DesignArgs { /// Ordered SV sources, or one Veryl project entry file. pub sources: Vec, + /// Select a Veryl source relative to --project (repeatable). + #[arg(long = "source-file")] + source_files: Vec, /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] diagnostics: Vec, @@ -38,7 +41,7 @@ pub(super) struct DesignArgs { /// Clear the project's force_signals list. #[arg(long)] no_force_signals: bool, - /// Project manifest (otherwise discover celox.toml when no inputs are given). + /// celox.toml manifest, Veryl.toml, or Veryl project directory. #[arg(long, value_name = "FILE")] project: Option, /// Named target in celox.toml. @@ -131,6 +134,7 @@ struct Target { #[derive(Default)] pub(super) struct Design { + pub project_root: Option, pub diagnostics: celox::DiagnosticPolicy, pub sources: Vec, pub include_dirs: Vec, @@ -164,10 +168,16 @@ impl DesignArgs { } pub fn resolve(self) -> Result { + self.resolve_for_run(false) + } + + pub fn resolve_for_run(self, image_input: bool) -> Result { let manifest_path = match self.project { Some(path) => Some(path), None if self.target.is_some() - || (self.sources.is_empty() && self.filelists.is_empty()) => + || (self.sources.is_empty() + && self.source_files.is_empty() + && self.filelists.is_empty()) => { let cwd = std::env::current_dir() .map_err(|error| format!("failed to locate current directory: {error}"))?; @@ -183,90 +193,134 @@ impl DesignArgs { ); } let mut design = Design::default(); + let mut manifest_source_root = None; if let Some(path) = manifest_path { - let path = path - .canonicalize() - .map_err(|error| format!("failed to open project {}: {error}", path.display()))?; - let text = std::fs::read_to_string(&path) - .map_err(|error| format!("failed to read project {}: {error}", path.display()))?; - let config: Manifest = toml::from_str(&text) - .map_err(|error| format!("invalid project {}: {error}", path.display()))?; - let base = path.parent().expect("canonical project has a parent"); - let target_name = self.target.as_ref().or(config.default_target.as_ref()); - let selected = match target_name { - Some(name) => Some(config.targets.get(name).ok_or_else(|| { - format!( - "unknown target `{name}` in {}; available targets: {}", - path.display(), - config - .targets - .keys() - .cloned() - .collect::>() - .join(", ") - ) - })?), - None if config.top.is_some() || config.targets.is_empty() => None, - None if config.targets.len() == 1 => config.targets.values().next(), - None => { - return Err(format!( - "select --target NAME; available targets: {}", - config - .targets - .keys() - .cloned() - .collect::>() - .join(", ") - )); + if path.is_dir() + || path.file_name().is_some_and(|name| name == "Veryl.toml") + || (image_input && !path.exists()) + { + if self.target.is_some() { + return Err("--target requires a celox.toml manifest".into()); } - }; - design.extend( - base, - &config.sources, - &config.filelists, - &config.include_dirs, - &config.defines, - )?; - design.extend_parameters(&config.parameters)?; - design.diagnostics = config.diagnostics.clone(); - design.top = config.top.clone().unwrap_or_default(); - let mut opt_level = config.opt_level.as_deref(); - design.signal_access.live_signals = config.live_signals.clone().unwrap_or_default(); - design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); - design.max_steps = config.max_steps; - if let Some(target) = selected { - design.extend_parameters(&target.parameters)?; - design.diagnostics.0.extend(target.diagnostics.0.clone()); + let root = if path.file_name().is_some_and(|name| name == "Veryl.toml") { + path.parent().unwrap_or(Path::new(".")).to_path_buf() + } else { + path.clone() + }; + design.project_root = Some(root.clone()); + if !image_input && self.source_files.is_empty() && self.sources.is_empty() { + let manifest = + veryl_metadata::Metadata::search_from(&path).map_err(|e| e.to_string())?; + let mut metadata = + veryl_metadata::Metadata::load(&manifest).map_err(|e| e.to_string())?; + design.sources = metadata + .paths::<&Path>(&[], false, false) + .map_err(|e| e.to_string())? + .into_iter() + .filter(|path| !path.example) + .map(|path| path.src) + .collect(); + } + } else { + let path = path.canonicalize().map_err(|error| { + format!("failed to open project {}: {error}", path.display()) + })?; + let text = std::fs::read_to_string(&path).map_err(|error| { + format!("failed to read project {}: {error}", path.display()) + })?; + let config: Manifest = toml::from_str(&text) + .map_err(|error| format!("invalid project {}: {error}", path.display()))?; + let base = path.parent().expect("canonical project has a parent"); + manifest_source_root = Some(base.to_path_buf()); + let target_name = self.target.as_ref().or(config.default_target.as_ref()); + let selected = match target_name { + Some(name) => Some(config.targets.get(name).ok_or_else(|| { + format!( + "unknown target `{name}` in {}; available targets: {}", + path.display(), + config + .targets + .keys() + .cloned() + .collect::>() + .join(", ") + ) + })?), + None if config.top.is_some() || config.targets.is_empty() => None, + None if config.targets.len() == 1 => config.targets.values().next(), + None => { + return Err(format!( + "select --target NAME; available targets: {}", + config + .targets + .keys() + .cloned() + .collect::>() + .join(", ") + )); + } + }; design.extend( base, - &target.sources, - &target.filelists, - &target.include_dirs, - &target.defines, + &config.sources, + &config.filelists, + &config.include_dirs, + &config.defines, )?; - if let Some(top) = &target.top { - design.top.clone_from(top); - } - opt_level = target.opt_level.as_deref().or(opt_level); - if let Some(paths) = &target.live_signals { - design.signal_access.live_signals.clone_from(paths); - } - if let Some(paths) = &target.force_signals { - design.signal_access.force_signals.clone_from(paths); + design.extend_parameters(&config.parameters)?; + design.diagnostics = config.diagnostics.clone(); + design.top = config.top.clone().unwrap_or_default(); + let mut opt_level = config.opt_level.as_deref(); + design.signal_access.live_signals = config.live_signals.clone().unwrap_or_default(); + design.signal_access.force_signals = + config.force_signals.clone().unwrap_or_default(); + design.max_steps = config.max_steps; + if let Some(target) = selected { + design.extend_parameters(&target.parameters)?; + design.diagnostics.0.extend(target.diagnostics.0.clone()); + design.extend( + base, + &target.sources, + &target.filelists, + &target.include_dirs, + &target.defines, + )?; + if let Some(top) = &target.top { + design.top.clone_from(top); + } + opt_level = target.opt_level.as_deref().or(opt_level); + if let Some(paths) = &target.live_signals { + design.signal_access.live_signals.clone_from(paths); + } + if let Some(paths) = &target.force_signals { + design.signal_access.force_signals.clone_from(paths); + } + design.max_steps = target.max_steps.or(design.max_steps); } - design.max_steps = target.max_steps.or(design.max_steps); - } - design.opt_level = opt_level - .map(|value| { - celox::OptLevel::parse(value).ok_or_else(|| { - format!("invalid opt_level `{value}`: expected O0, O1, or O2") + design.opt_level = opt_level + .map(|value| { + celox::OptLevel::parse(value).ok_or_else(|| { + format!("invalid opt_level `{value}`: expected O0, O1, or O2") + }) }) - }) - .transpose()?; - if design.max_steps == Some(0) { - return Err("max_steps must be positive".to_string()); + .transpose()?; + if design.max_steps == Some(0) { + return Err("max_steps must be positive".to_string()); + } } } + design.sources.extend(self.source_files.iter().map(|path| { + if path.is_absolute() { + path.clone() + } else { + design + .project_root + .as_deref() + .or(manifest_source_root.as_deref()) + .unwrap_or(Path::new(".")) + .join(path) + } + })); design.opt_level = self.opt_level.or(design.opt_level); if self.no_live_signals { design.signal_access.live_signals.clear(); @@ -310,7 +364,7 @@ impl DesignArgs { if let Some(top) = self.top { design.top = top; } - if design.sources.is_empty() { + if design.sources.is_empty() && !image_input { return Err( "provide sources, -f FILE, or a celox.toml project with sources".to_string(), ); @@ -402,10 +456,11 @@ impl Design { } pub fn is_sv(&self) -> bool { - self.sources.iter().all(|path| { - path.extension() - .is_some_and(|extension| extension == "sv" || extension == "v") - }) + !self.sources.is_empty() + && self.sources.iter().all(|path| { + path.extension() + .is_some_and(|extension| extension == "sv" || extension == "v") + }) } fn extend( diff --git a/crates/celox-bench/src/bin/celox-heliodor.rs b/crates/celox-vpi/src/bin/celox/runner.rs similarity index 75% rename from crates/celox-bench/src/bin/celox-heliodor.rs rename to crates/celox-vpi/src/bin/celox/runner.rs index caea5040226..b3bc75ac7ae 100644 --- a/crates/celox-bench/src/bin/celox-heliodor.rs +++ b/crates/celox-vpi/src/bin/celox/runner.rs @@ -12,7 +12,7 @@ use celox::{ OptLevel, OptimizeOptions, Simulator, SirPass, TestResult, TieredExecutionStats, TieredExecutionTier, TieredPromotionStatus, }; -use clap::{Parser, ValueEnum}; +use clap::{Args, ValueEnum}; use veryl_metadata::Metadata; #[cfg(any( @@ -20,24 +20,20 @@ use veryl_metadata::Metadata; feature = "arm64-codegen", target_arch = "aarch64" ))] -#[path = "heliodor/build_cache.rs"] +#[path = "runner/build_cache.rs"] mod build_cache; -#[derive(Parser)] -#[command(about = "Run a Heliodor test with Celox and report split benchmark timing")] -struct Cli { - #[arg(long)] - project: PathBuf, - #[arg(long)] - test: String, - #[arg(long = "source-file")] - source_files: Vec, - #[arg(long, value_enum, ignore_case = true, default_value = "o2")] - opt_level: OptimizationLevel, +// Structured records share the benchmark protocol; normal runs print only design output. +macro_rules! report { + ($enabled:expr, $($args:tt)*) => { if $enabled { println!($($args)*); } }; +} + +#[derive(Args, Default)] +pub(super) struct ExecutionArgs { #[arg(long, value_enum, default_value = "native")] - backend: Backend, + pub backend: Backend, #[arg(long)] - four_state: bool, + pub four_state: bool, #[arg(long)] compile_only: bool, /// Write a pointer-free native image during compile-only mode. @@ -45,15 +41,13 @@ struct Cli { native_image_output: Option, /// Load a pointer-free native image instead of generating machine code. #[arg(long, value_name = "PATH")] - native_image_input: Option, + pub native_image_input: Option, /// Reuse native compilation artifacts from this trusted local directory. #[arg(long, value_name = "DIR")] build_cache_dir: Option, - #[arg(long, value_parser = parse_positive_u64)] - tick_limit: Option, #[arg(long)] dump_ir_dir: Option, - #[arg(long)] + #[arg(long, conflicts_with = "compile_only")] dump_ir_and_run: bool, #[arg(long = "native-profile-block", value_parser = parse_native_profile_block)] native_profile_blocks: Vec, @@ -65,17 +59,51 @@ struct Cli { x86_slp: Option, /// Simulation threads, including the calling thread. #[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u32).range(1..=64))] - threads: u32, + pub threads: u32, + /// Emit machine-readable CELOX_* timing, configuration and result records. + #[arg(long)] + report: bool, + /// Require the tiered backend to adopt and execute generated code. + #[arg(long, requires = "report")] + require_compiled: bool, + /// Run without the default scheduler step/tick limit. + #[arg(long, conflicts_with = "max_steps")] + pub unlimited: bool, /// Partition every phase with independent work instead of only the /// phases with an estimated speedup. #[arg(long)] always_partition: bool, } +impl ExecutionArgs { + #[cfg(feature = "systemverilog")] + pub(super) fn validate_sv(&self) -> Result<(), String> { + if self.compile_only + || self.native_image_input.is_some() + || self.native_image_output.is_some() + || self.build_cache_dir.is_some() + || self.dump_ir_dir.is_some() + || self.dump_ir_and_run + || !self.native_profile_blocks.is_empty() + || !self.pass_overrides.is_empty() + || self.native_memory_width.is_some() + || self.x86_slp.is_some() + || self.always_partition + || self.report + || self.require_compiled + { + return Err("compilation artifacts, codegen tuning and --report currently require a Veryl testbench".into()); + } + Ok(()) + } +} + struct Options { + report: bool, + require_compiled: bool, + design: super::project::Design, project: PathBuf, test: String, - source_files: Vec, opt_level: OptLevel, backend: Backend, four_state: bool, @@ -95,12 +123,12 @@ struct Options { } #[derive(Debug, thiserror::Error)] -enum CeloxHeliodorError { +pub(super) enum RunError { #[error(transparent)] Metadata(#[from] veryl_metadata::MetadataError), #[error(transparent)] Io(#[from] std::io::Error), - #[error("Celox build failed: {source}")] + #[error("compilation failed:\n{source}")] Build { #[from] #[source] @@ -117,37 +145,22 @@ enum CeloxHeliodorError { InvalidConfiguration { message: &'static str }, #[error("{artifact} trace was not captured")] MissingTrace { artifact: &'static str }, - #[error("no initial block found — this module is not a native testbench")] + #[error("selected module has no native testbench; select a #[test] module with --top")] MissingInitialBlock, #[error("{message}")] TestFailed { message: String }, } -#[derive(Clone, Copy, ValueEnum)] -enum Backend { +#[derive(Clone, Copy, Default, PartialEq, ValueEnum)] +pub(super) enum Backend { + #[default] Native, Cranelift, Interpreter, + Wasm, Tiered, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] -enum OptimizationLevel { - O0, - O1, - O2, -} - -impl From for OptLevel { - fn from(value: OptimizationLevel) -> Self { - match value { - OptimizationLevel::O0 => Self::O0, - OptimizationLevel::O1 => Self::O1, - OptimizationLevel::O2 => Self::O2, - } - } -} - #[derive(Clone, Copy, ValueEnum)] enum OnOff { On, @@ -160,40 +173,36 @@ impl Backend { Backend::Native => "native", Backend::Cranelift => "cranelift", Backend::Interpreter => "interpreter", + Backend::Wasm => "wasm", Backend::Tiered => "tiered", } } } -fn main() { - tracing_subscriber::fmt() - .with_env_filter( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("off")), - ) - .with_writer(std::io::stderr) - .with_ansi(false) - .init(); - if let Err(e) = run() { - let _ = writeln!(std::io::stderr().lock(), "error: {e}"); - std::process::exit(1); - } -} - -fn run() -> Result<(), CeloxHeliodorError> { - let cli = Cli::parse(); - let opts = Options { - project: cli.project, - test: cli.test, - source_files: cli.source_files, - opt_level: cli.opt_level.into(), +pub(super) fn run( + cli: ExecutionArgs, + design: super::project::Design, + max_steps: u64, +) -> Result<(), RunError> { + let mut opts = Options { + report: cli.report, + require_compiled: cli.require_compiled, + project: design.project_root.clone().unwrap_or_else(|| { + design + .sources + .first() + .cloned() + .unwrap_or_else(|| PathBuf::from(".")) + }), + test: design.top.clone(), + opt_level: design.opt_level.unwrap_or(OptLevel::O2), backend: cli.backend, four_state: cli.four_state, compile_only: cli.compile_only, native_image_output: cli.native_image_output, native_image_input: cli.native_image_input, build_cache_dir: cli.build_cache_dir, - tick_limit: cli.tick_limit, + tick_limit: (!cli.unlimited).then_some(max_steps), dump_ir_dir: cli.dump_ir_dir, dump_ir_and_run: cli.dump_ir_and_run, native_profile_blocks: cli.native_profile_blocks, @@ -217,55 +226,61 @@ fn run() -> Result<(), CeloxHeliodorError> { ))), threads: cli.threads, always_partition: cli.always_partition, + design, }; + if opts.require_compiled && opts.backend != Backend::Tiered { + return Err(RunError::InvalidConfiguration { + message: "--require-compiled requires --backend tiered", + }); + } if opts.build_cache_dir.is_some() && (!matches!(opts.backend, Backend::Native) || opts.native_image_input.is_some() || opts.dump_ir_dir.is_some()) { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--build-cache-dir requires --backend native and cannot be combined with --native-image-input or --dump-ir-dir", }); } if opts.native_image_output.is_some() && !opts.compile_only { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--native-image-output requires --compile-only", }); } if opts.compile_only && matches!(opts.backend, Backend::Interpreter | Backend::Tiered) { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--compile-only requires a compiled backend", }); } if opts.native_image_input.is_some() && opts.compile_only { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--native-image-input cannot be used with --compile-only", }); } if opts.native_image_input.is_some() && opts.native_image_output.is_some() { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--native-image-input and --native-image-output are mutually exclusive", }); } if (opts.native_image_input.is_some() || opts.native_image_output.is_some()) && !matches!(opts.backend, Backend::Native) { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "native image options require --backend native", }); } if opts.native_image_input.is_some() && opts.dump_ir_dir.is_some() { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--native-image-input cannot be combined with --dump-ir-dir", }); } if !opts.native_profile_blocks.is_empty() && opts.dump_ir_dir.is_none() { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--native-profile-block requires --dump-ir-dir", }); } if opts.dump_ir_and_run && opts.dump_ir_dir.is_none() { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--dump-ir-and-run requires --dump-ir-dir", }); } @@ -274,19 +289,19 @@ fn run() -> Result<(), CeloxHeliodorError> { all(target_arch = "aarch64", feature = "x86_64-codegen") ))] if opts.dump_ir_and_run { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--dump-ir-and-run is unavailable during cross-codegen", }); } #[cfg(all(target_arch = "x86_64", feature = "arm64-codegen"))] if matches!(opts.backend, Backend::Native) && !opts.compile_only { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "AArch64 cross-codegen requires --compile-only on an x86-64 host", }); } #[cfg(all(target_arch = "aarch64", feature = "x86_64-codegen"))] if matches!(opts.backend, Backend::Native) && !opts.compile_only { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "x86-64 cross-codegen requires --compile-only on an AArch64 host", }); } @@ -296,7 +311,7 @@ fn run() -> Result<(), CeloxHeliodorError> { target_arch = "aarch64" )))] if matches!(opts.backend, Backend::Native) { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "the custom native backend is unavailable on this target", }); } @@ -330,6 +345,7 @@ fn run() -> Result<(), CeloxHeliodorError> { image.try_map_paths(|path| { Ok::<_, std::io::Error>(build_cache::bind_path(path, &root)) })?; + opts.four_state = image.four_state(); Some(image) } None => None, @@ -348,9 +364,13 @@ fn run() -> Result<(), CeloxHeliodorError> { // sources at all. (Vec::new(), None) } else { - let (sources, metadata) = load_sources(&opts.project, &opts.source_files)?; - (sources, Some(metadata)) + load_sources(&opts.design)? }; + if opts.build_cache_dir.is_some() && metadata.is_none() { + return Err(RunError::InvalidConfiguration { + message: "--build-cache-dir requires a Veryl.toml project", + }); + } let source_refs: Vec<(&str, &Path)> = sources .iter() .map(|(source, path)| (source.as_str(), path.as_path())) @@ -360,8 +380,12 @@ fn run() -> Result<(), CeloxHeliodorError> { feature = "arm64-codegen", target_arch = "aarch64" ))] - let project_root = metadata.as_ref().map(Metadata::project_path); - println!( + let project_root = metadata + .as_ref() + .map(Metadata::project_path) + .unwrap_or(std::env::current_dir()?); + report!( + opts.report, "CELOX_TEST_CONFIG test={} backend={} opt_level={} four_state={} compile_only={}", opts.test, opts.backend.as_str(), @@ -371,9 +395,11 @@ fn run() -> Result<(), CeloxHeliodorError> { ); // A separate record keeps the single-thread config line unchanged. if opts.threads > 1 { - println!( + report!( + opts.report, "CELOX_TEST_THREADS test={} threads={}", - opts.test, opts.threads + opts.test, + opts.threads ); } @@ -384,16 +410,15 @@ fn run() -> Result<(), CeloxHeliodorError> { target_arch = "aarch64" ))] let build_cache = opts.build_cache_dir.as_ref().and_then(|dir| { - match build_cache::BuildCache::new( - dir, - &opts, - &sources, - metadata.as_ref().expect("cache uses sources"), - ) { + match build_cache::BuildCache::new(dir, &opts, &sources, metadata.as_ref()?) { Ok(cache) => Some(cache), Err(error) => { let _ = writeln!(std::io::stderr().lock(), "build cache disabled: {error}"); - println!("CELOX_BUILD_CACHE test={} status=bypass", opts.test); + report!( + opts.report, + "CELOX_BUILD_CACHE test={} status=bypass", + opts.test + ); None } } @@ -405,7 +430,8 @@ fn run() -> Result<(), CeloxHeliodorError> { ))] if let Some(cache) = &build_cache { native_image = cache.load(); - println!( + report!( + opts.report, "CELOX_BUILD_CACHE test={} status={} path={}", opts.test, if native_image.is_some() { @@ -426,9 +452,12 @@ fn run() -> Result<(), CeloxHeliodorError> { .opt_level(opts.opt_level) .optimize_options(optimize_options) .x86_slp(opts.x86_slp) + .diagnostic_policy(opts.design.diagnostics.clone()) + .signal_access(opts.design.signal_access.clone()) .four_state(opts.four_state) .threads(opts.threads as usize) .diagnostics_from_env(); + builder = opts.design.apply_parameters(builder); if opts.always_partition { builder = builder.parallel_partition(celox::ParallelPartition::Always); } @@ -444,7 +473,7 @@ fn run() -> Result<(), CeloxHeliodorError> { } if let Some(output_dir) = opts.dump_ir_dir { if !matches!(opts.backend, Backend::Native) { - return Err(CeloxHeliodorError::InvalidConfiguration { + return Err(RunError::InvalidConfiguration { message: "--dump-ir-dir is only supported with --backend native", }); } @@ -475,12 +504,11 @@ fn run() -> Result<(), CeloxHeliodorError> { } build_cache::write_relative_image( compiled.program_image(), - project_root - .as_ref() - .expect("image export uses project sources"), + &project_root, output_path, )?; - println!( + report!( + opts.report, "CELOX_NATIVE_IMAGE test={} mode=generated path={}", opts.test, output_path.display() @@ -509,37 +537,35 @@ fn run() -> Result<(), CeloxHeliodorError> { sir_path.display() ); } - let _pre_optimized_sir = pre_optimized_sir.ok_or(CeloxHeliodorError::MissingTrace { + let _pre_optimized_sir = pre_optimized_sir.ok_or(RunError::MissingTrace { artifact: "pre-optimized SIR", })?; - let _sir = sir.ok_or(CeloxHeliodorError::MissingTrace { + let _sir = sir.ok_or(RunError::MissingTrace { artifact: "post-optimized SIR", })?; - let native_sir = - trace - .native_optimized_sir - .take() - .ok_or(CeloxHeliodorError::MissingTrace { - artifact: "native optimized SIR", - })?; + let native_sir = trace + .native_optimized_sir + .take() + .ok_or(RunError::MissingTrace { + artifact: "native optimized SIR", + })?; let mir = trace .mir .take() - .ok_or(CeloxHeliodorError::MissingTrace { artifact: "MIR" })?; + .ok_or(RunError::MissingTrace { artifact: "MIR" })?; let reactive_graph = trace .reactive_event_graph .take() - .ok_or(CeloxHeliodorError::MissingTrace { + .ok_or(RunError::MissingTrace { artifact: "reactive event graph", })?; - let state_layout = - trace - .native_state_layout - .take() - .ok_or(CeloxHeliodorError::MissingTrace { - artifact: "native state-layout analysis", - })?; + let state_layout = trace + .native_state_layout + .take() + .ok_or(RunError::MissingTrace { + artifact: "native state-layout analysis", + })?; let native_sir_path = output_dir.join("native_optimized.sir"); let mir_path = output_dir.join("mir.txt"); let reactive_graph_path = output_dir.join("reactive_event_graph.txt"); @@ -586,13 +612,15 @@ fn run() -> Result<(), CeloxHeliodorError> { )); if opts.dump_ir_and_run { let mut sim = compiled.initialize()?; - let testbench = compile_initial_testbench(&sim) - .ok_or(CeloxHeliodorError::MissingInitialBlock)?; + let testbench = + compile_initial_testbench(&sim).ok_or(RunError::MissingInitialBlock)?; #[cfg(any( all(target_arch = "x86_64", not(feature = "arm64-codegen")), all(target_arch = "aarch64", not(feature = "x86_64-codegen")) ))] - sim.start_native_execution_timing(); + if opts.report { + sim.start_native_execution_timing(); + } let execute_cpu_start = process_cpu_time(); let execute_start = Instant::now(); let (result, ticks, tick_limit_reached) = if let Some(limit) = opts.tick_limit { @@ -608,42 +636,52 @@ fn run() -> Result<(), CeloxHeliodorError> { ))] let jit_execute_elapsed = sim .finish_native_execution_timing() - .expect("native execution timing was started") - .elapsed(); + .map(|timing| timing.elapsed()); #[cfg(not(any( all(target_arch = "x86_64", not(feature = "arm64-codegen")), all(target_arch = "aarch64", not(feature = "x86_64-codegen")) )))] - let jit_execute_elapsed = Duration::ZERO; + let jit_execute_elapsed = None; let execute_elapsed = execute_start.elapsed(); let execute_cpu_elapsed = process_cpu_time() .zip(execute_cpu_start) .map(|(end, start)| end.saturating_sub(start)); print_celox_timing( + opts.report, &opts.test, compile_elapsed, execute_elapsed, - Some(jit_execute_elapsed), + jit_execute_elapsed, execute_cpu_elapsed, ); if opts.tick_limit.is_some() { - println!( + report!( + opts.report, "CELOX_TEST_TICK_LIMIT test={} ticks={} reached={}", - opts.test, ticks, tick_limit_reached + opts.test, + ticks, + tick_limit_reached ); } let elapsed = total_start.elapsed(); return match result { TestResult::Pass if tick_limit_reached => { - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=tick-limit elapsed_ns={}", opts.test, elapsed.as_nanos() ); - Ok(()) + Err(RunError::TestFailed { + message: format!( + "simulation reached --max-steps {} testbench ticks before completion", + opts.tick_limit.unwrap() + ), + }) } TestResult::Pass => { - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=pass elapsed_ns={}", opts.test, elapsed.as_nanos() @@ -651,16 +689,18 @@ fn run() -> Result<(), CeloxHeliodorError> { Ok(()) } TestResult::Fail(message) => { - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=fail elapsed_ns={}", opts.test, elapsed.as_nanos() ); - Err(CeloxHeliodorError::TestFailed { message }) + Err(RunError::TestFailed { message }) } }; } - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=trace-only elapsed_ns={}", opts.test, total_start.elapsed().as_nanos() @@ -687,10 +727,15 @@ fn run() -> Result<(), CeloxHeliodorError> { .compile_native() }); let compiled = compiled?; + super::report_warnings(compiled.warnings()) + .map_err(|message| RunError::TestFailed { message })?; cache.store(compiled.program_image(), &dependencies); compiled.into_program_image() } else { - builder.compile_native()?.into_program_image() + let compiled = builder.compile_native()?; + super::report_warnings(compiled.warnings()) + .map_err(|message| RunError::TestFailed { message })?; + compiled.into_program_image() }; if let Some(output_path) = &opts.native_image_output { if let Some(parent) = output_path @@ -699,14 +744,9 @@ fn run() -> Result<(), CeloxHeliodorError> { { fs::create_dir_all(parent)?; } - build_cache::write_relative_image( - &image, - project_root - .as_ref() - .expect("image export uses project sources"), - output_path, - )?; - println!( + build_cache::write_relative_image(&image, &project_root, output_path)?; + report!( + opts.report, "CELOX_NATIVE_IMAGE test={} mode=generated path={}", opts.test, output_path.display() @@ -719,6 +759,9 @@ fn run() -> Result<(), CeloxHeliodorError> { target_arch = "aarch64" )))] Backend::Native => unreachable!("native backend availability checked above"), + Backend::Wasm => { + builder.build_wasm()?; + } Backend::Cranelift => { let _sim = builder.build_cranelift()?; } @@ -729,13 +772,15 @@ fn run() -> Result<(), CeloxHeliodorError> { let compile_elapsed = compile_start.elapsed(); let elapsed = total_start.elapsed(); print_celox_timing( + opts.report, &opts.test, compile_elapsed, Duration::ZERO, matches!(opts.backend, Backend::Native).then_some(Duration::ZERO), None, ); - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=compile-only elapsed_ns={}", opts.test, elapsed.as_nanos() @@ -763,7 +808,8 @@ fn run() -> Result<(), CeloxHeliodorError> { Backend::Native => { let mut sim = if let Some(image) = native_image.take() { if let Some(image_path) = &opts.native_image_input { - println!( + report!( + opts.report, "CELOX_NATIVE_IMAGE test={} mode=loaded path={}", opts.test, image_path.display() @@ -783,10 +829,13 @@ fn run() -> Result<(), CeloxHeliodorError> { } else { builder.build_native()? }; - let testbench = - compile_initial_testbench(&sim).ok_or(CeloxHeliodorError::MissingInitialBlock)?; + super::report_warnings(sim.warnings()) + .map_err(|message| RunError::TestFailed { message })?; + let testbench = compile_initial_testbench(&sim).ok_or(RunError::MissingInitialBlock)?; let compile_elapsed = compile_start.elapsed(); - sim.start_native_execution_timing(); + if opts.report { + sim.start_native_execution_timing(); + } let execute_cpu_start = process_cpu_time(); let execute_start = Instant::now(); let (result, ticks, tick_limit_reached) = if let Some(limit) = opts.tick_limit { @@ -797,15 +846,14 @@ fn run() -> Result<(), CeloxHeliodorError> { }; let jit_execute_elapsed = sim .finish_native_execution_timing() - .expect("native execution timing was started") - .elapsed(); + .map(|timing| timing.elapsed()); ( result, ticks, tick_limit_reached, compile_elapsed, execute_start.elapsed(), - Some(jit_execute_elapsed), + jit_execute_elapsed, process_cpu_time() .zip(execute_cpu_start) .map(|(end, start)| end.saturating_sub(start)), @@ -821,8 +869,9 @@ fn run() -> Result<(), CeloxHeliodorError> { Backend::Native => unreachable!("native backend availability checked above"), Backend::Cranelift => { let mut sim = builder.build_cranelift()?; - let testbench = - compile_initial_testbench(&sim).ok_or(CeloxHeliodorError::MissingInitialBlock)?; + super::report_warnings(sim.warnings()) + .map_err(|message| RunError::TestFailed { message })?; + let testbench = compile_initial_testbench(&sim).ok_or(RunError::MissingInitialBlock)?; let compile_elapsed = compile_start.elapsed(); let execute_cpu_start = process_cpu_time(); let execute_start = Instant::now(); @@ -849,8 +898,38 @@ fn run() -> Result<(), CeloxHeliodorError> { } Backend::Interpreter => { let mut sim = builder.build_interpreter()?; - let testbench = - compile_initial_testbench(&sim).ok_or(CeloxHeliodorError::MissingInitialBlock)?; + super::report_warnings(sim.warnings()) + .map_err(|message| RunError::TestFailed { message })?; + let testbench = compile_initial_testbench(&sim).ok_or(RunError::MissingInitialBlock)?; + let compile_elapsed = compile_start.elapsed(); + let execute_cpu_start = process_cpu_time(); + let execute_start = Instant::now(); + let (result, ticks, tick_limit_reached) = if let Some(limit) = opts.tick_limit { + let limited = run_compiled_testbench_with_tick_limit(&mut sim, &testbench, limit); + (limited.result, limited.ticks, limited.tick_limit_reached) + } else { + (run_compiled_testbench(&mut sim, &testbench), 0, false) + }; + ( + result, + ticks, + tick_limit_reached, + compile_elapsed, + execute_start.elapsed(), + None, + process_cpu_time() + .zip(execute_cpu_start) + .map(|(end, start)| end.saturating_sub(start)), + None, + None, + None, + ) + } + Backend::Wasm => { + let mut sim = builder.build_wasm()?; + super::report_warnings(sim.warnings()) + .map_err(|message| RunError::TestFailed { message })?; + let testbench = compile_initial_testbench(&sim).ok_or(RunError::MissingInitialBlock)?; let compile_elapsed = compile_start.elapsed(); let execute_cpu_start = process_cpu_time(); let execute_start = Instant::now(); @@ -877,14 +956,17 @@ fn run() -> Result<(), CeloxHeliodorError> { } Backend::Tiered => { let mut sim = builder.build_tiered()?; - let testbench = - compile_initial_testbench(&sim).ok_or(CeloxHeliodorError::MissingInitialBlock)?; + super::report_warnings(sim.warnings()) + .map_err(|message| RunError::TestFailed { message })?; + let testbench = compile_initial_testbench(&sim).ok_or(RunError::MissingInitialBlock)?; // `build_tiered` returns after constructing the interpreter and // starting code generation. The execution interval therefore // includes the background compile and promotion, which is the // end-to-end latency tiered execution is intended to improve. let compile_elapsed = compile_start.elapsed(); - sim.start_tiered_execution_timing(); + if opts.report { + sim.start_tiered_execution_timing(); + } let execute_cpu_start = process_cpu_time(); let execute_start = Instant::now(); let (result, ticks, tick_limit_reached) = if let Some(limit) = opts.tick_limit { @@ -917,6 +999,7 @@ fn run() -> Result<(), CeloxHeliodorError> { }; let elapsed = total_start.elapsed(); print_celox_timing( + opts.report, &opts.test, compile_elapsed, execute_elapsed, @@ -924,8 +1007,9 @@ fn run() -> Result<(), CeloxHeliodorError> { execute_cpu_elapsed, ); if let Some(stats) = tiered_stats { - print_tiered_stats(&opts.test, stats, tiered_promotion_elapsed); - if !tick_limit_reached + print_tiered_stats(opts.report, &opts.test, stats, tiered_promotion_elapsed); + if opts.require_compiled + && !tick_limit_reached && (stats.tier != TieredExecutionTier::Compiled || stats.promotion != TieredPromotionStatus::Promoted || stats.compiled_evaluations == 0 @@ -934,34 +1018,45 @@ fn run() -> Result<(), CeloxHeliodorError> { let detail = tiered_promotion_error .as_deref() .unwrap_or("the compiled tier was not adopted and exercised"); - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=fail elapsed_ns={}", opts.test, elapsed.as_nanos() ); - return Err(CeloxHeliodorError::TestFailed { - message: format!("tiered JIT benchmark did not exercise generated code: {detail}"), + return Err(RunError::TestFailed { + message: format!("tiered execution did not exercise generated code: {detail}"), }); } } if opts.tick_limit.is_some() { - println!( + report!( + opts.report, "CELOX_TEST_TICK_LIMIT test={} ticks={} reached={}", - opts.test, ticks, tick_limit_reached + opts.test, + ticks, + tick_limit_reached ); } match result { TestResult::Pass if tick_limit_reached => { - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=tick-limit elapsed_ns={}", opts.test, elapsed.as_nanos() ); - Ok(()) + Err(RunError::TestFailed { + message: format!( + "simulation reached --max-steps {} testbench ticks before completion", + opts.tick_limit.unwrap() + ), + }) } TestResult::Pass => { - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=pass elapsed_ns={}", opts.test, elapsed.as_nanos() @@ -969,17 +1064,19 @@ fn run() -> Result<(), CeloxHeliodorError> { Ok(()) } TestResult::Fail(message) => { - println!( + report!( + opts.report, "CELOX_TEST_RESULT test={} status=fail elapsed_ns={}", opts.test, elapsed.as_nanos() ); - Err(CeloxHeliodorError::TestFailed { message }) + Err(RunError::TestFailed { message }) } } } fn print_tiered_stats( + report: bool, test: &str, stats: TieredExecutionStats, promotion_elapsed: Option, @@ -1003,7 +1100,8 @@ fn print_tiered_stats( let promotion_elapsed_ns = promotion_elapsed .map(|elapsed| elapsed.as_nanos().to_string()) .unwrap_or_else(|| "NA".to_string()); - println!( + report!( + report, "CELOX_TIERED_STATS test={test} tier={tier} promotion={promotion} interpreted_evaluations={} compiled_evaluations={} promoted_after_interpreted_evaluations={promoted_after} promotion_elapsed_ns={promotion_elapsed_ns} safe_point_polls={} split_apply_deferrals={} threshold_deferrals={}", stats.interpreted_evaluations, stats.compiled_evaluations, @@ -1014,6 +1112,7 @@ fn print_tiered_stats( } fn print_celox_timing( + report: bool, test: &str, compile_elapsed: Duration, execute_elapsed: Duration, @@ -1024,14 +1123,16 @@ fn print_celox_timing( .map(|elapsed| elapsed.as_nanos().to_string()) .unwrap_or_else(|| "NA".to_string()); if let Some(execute_cpu_elapsed) = execute_cpu_elapsed { - println!( + report!( + report, "CELOX_TEST_TIMING test={test} compile_ns={} execute_ns={} jit_execute_ns={jit_execute_ns} execute_cpu_ns={}", compile_elapsed.as_nanos(), execute_elapsed.as_nanos(), execute_cpu_elapsed.as_nanos() ); } else { - println!( + report!( + report, "CELOX_TEST_TIMING test={test} compile_ns={} execute_ns={} jit_execute_ns={jit_execute_ns}", compile_elapsed.as_nanos(), execute_elapsed.as_nanos() @@ -1061,14 +1162,6 @@ fn process_cpu_time() -> Option { #[derive(Debug, thiserror::Error)] enum CliValueError { - #[error("invalid positive integer: {value}")] - InvalidPositiveInteger { - value: String, - #[source] - source: std::num::ParseIntError, - }, - #[error("value must be greater than zero")] - NonPositiveInteger, #[error("invalid native memory width: {value}")] InvalidNativeMemoryWidth { value: String }, #[error("invalid native profile block: {value}")] @@ -1091,20 +1184,6 @@ enum CliValueError { UnknownSirPass { name: String }, } -fn parse_positive_u64(value: &str) -> Result { - let parsed = value - .parse::() - .map_err(|source| CliValueError::InvalidPositiveInteger { - value: value.to_owned(), - source, - })?; - if parsed == 0 { - Err(CliValueError::NonPositiveInteger) - } else { - Ok(parsed) - } -} - fn parse_native_memory_width(value: &str) -> Result { match value { "64" => Ok(64), @@ -1170,79 +1249,42 @@ fn parse_pass_override(value: &str) -> Result<(bool, SirPass), CliValueError> { } fn load_sources( - project_path: &Path, - source_files: &[PathBuf], -) -> Result<(Vec<(String, PathBuf)>, Metadata), CeloxHeliodorError> { - let toml_path = Metadata::search_from(project_path)?; - let mut metadata = Metadata::load(&toml_path)?; - let paths: Vec = if source_files.is_empty() { - metadata - .paths::<&str>(&[], false, false)? - .into_iter() - .filter(|path| !path.example) - .map(|path| path.src) - .collect() - } else { - source_files - .iter() - .map(|path| { - if path.is_absolute() { - path.clone() - } else { - project_path.join(path) + design: &super::project::Design, +) -> Result<(Vec<(String, PathBuf)>, Option), RunError> { + let entry = design + .project_root + .as_deref() + .or_else(|| design.sources.first().map(PathBuf::as_path)) + .unwrap_or(Path::new(".")); + let metadata = Metadata::search_from(entry) + .ok() + .map(|path| Metadata::load(&path)) + .transpose()?; + let mut paths = design.sources.clone(); + if design.project_root.is_none() { + if let Some(mut metadata) = metadata.clone() { + for path in metadata.paths::<&Path>(&[], false, true)? { + if !paths + .iter() + .any(|p| p.canonicalize().ok().as_ref() == Some(&path.src)) + { + paths.push(path.src); } - }) - .collect() - }; - let mut sources = Vec::with_capacity(paths.len()); - for path in paths { - let content = fs::read_to_string(&path)?; - sources.push((content, path)); - } - Ok((sources, metadata)) -} - -#[cfg(test)] -mod tests { - use std::error::Error as _; - - use clap::Parser; - - use super::{Cli, CliValueError, OptimizationLevel, parse_positive_u64}; - - #[test] - fn numeric_parser_preserves_parse_error_source() { - let error = parse_positive_u64("not-a-number").unwrap_err(); - - assert!(matches!( - &error, - CliValueError::InvalidPositiveInteger { .. } - )); - assert!(error.source().unwrap().is::()); - } - - #[test] - fn opt_level_is_case_insensitive() { - for (value, expected) in [ - ("O0", OptimizationLevel::O0), - ("o0", OptimizationLevel::O0), - ("O1", OptimizationLevel::O1), - ("o1", OptimizationLevel::O1), - ("O2", OptimizationLevel::O2), - ("o2", OptimizationLevel::O2), - ] { - let cli = Cli::try_parse_from([ - "celox-heliodor", - "--project", - ".", - "--test", - "test_soc_linux_boot", - "--opt-level", - value, - ]) - .unwrap(); - - assert_eq!(cli.opt_level, expected); + } } } + let sources = paths + .into_iter() + .map(|path| { + fs::read_to_string(&path) + .map_err(|error| { + std::io::Error::new( + error.kind(), + format!("failed to read {}: {error}", path.display()), + ) + }) + .map(|source| (source, path)) + }) + .collect::>()?; + Ok((sources, metadata)) } diff --git a/crates/celox-bench/src/bin/heliodor/build_cache.rs b/crates/celox-vpi/src/bin/celox/runner/build_cache.rs similarity index 97% rename from crates/celox-bench/src/bin/heliodor/build_cache.rs rename to crates/celox-vpi/src/bin/celox/runner/build_cache.rs index 613e63f3cbd..8ba249588e2 100644 --- a/crates/celox-bench/src/bin/heliodor/build_cache.rs +++ b/crates/celox-vpi/src/bin/celox/runner/build_cache.rs @@ -8,7 +8,7 @@ use std::{ use celox::NativeProgramImage; use celox_frontend_veryl::FileDependency; -use super::{CeloxHeliodorError, Options}; +use super::{Options, RunError}; #[derive(serde::Serialize, serde::Deserialize)] struct CachedFileDependency { @@ -93,7 +93,7 @@ pub(super) fn write_relative_image( image: &NativeProgramImage, root: &Path, output: &Path, -) -> Result<(), CeloxHeliodorError> { +) -> Result<(), RunError> { let mut image = image.clone(); image.try_map_paths(|path| relative_path(path, root))?; image.write_container(output)?; @@ -267,7 +267,7 @@ impl BuildCache { opts: &Options, sources: &[(String, PathBuf)], metadata: &veryl_metadata::Metadata, - ) -> Result { + ) -> Result { // Source loading deliberately excludes dependency discovery. Resolve // the same namespaces and properties as the compiler before hashing. let mut metadata = metadata.clone(); @@ -299,6 +299,14 @@ impl BuildCache { .as_encoded_bytes(), ); field(&mut hash, opts.test.as_bytes()); + field( + &mut hash, + format!( + "{:?}:{:?}:{:?}", + opts.design.parameters, opts.design.diagnostics, opts.design.signal_access + ) + .as_bytes(), + ); field( &mut hash, format!( @@ -387,7 +395,7 @@ impl BuildCache { } } - fn try_load(&self) -> Result, CeloxHeliodorError> { + fn try_load(&self) -> Result, RunError> { let bytes = match fs::read(&self.path) { Ok(bytes) => bytes, Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), @@ -439,7 +447,7 @@ impl BuildCache { &self, image: &NativeProgramImage, dependencies: &[FileDependency], - ) -> Result<(), CeloxHeliodorError> { + ) -> Result<(), RunError> { let dependencies = dependencies .iter() .map(|dependency| { diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index 9c7f09adb60..350ecd6912f 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -39,8 +39,8 @@ pub fn compile_native_sources(sources: &[&Path], top: &str) -> Result, ) -> Result<(NativeProgramImage, Vec), String> { - let simulator = if let Ok(metadata_path) = Metadata::search_from(source) { + let compiled = if let Ok(metadata_path) = Metadata::search_from(source) { let mut metadata = Metadata::load(&metadata_path) .map_err(|error| format!("failed to load {}: {error}", metadata_path.display()))?; let paths = metadata @@ -127,7 +127,7 @@ fn compile_native_image_configured( .fold(builder, |builder, (name, value)| { builder.param(name, *value) }) - .build() + .compile_native() } else { let contents = std::fs::read_to_string(source) .map_err(|error| format!("failed to read {}: {error}", source.display()))?; @@ -142,11 +142,10 @@ fn compile_native_image_configured( .fold(builder, |builder, (name, value)| { builder.param(name, *value) }) - .build() + .compile_native() } .map_err(|error| format!("compilation failed: {error}"))?; - let image = simulator.shared_code().program_image().clone(); - Ok((image, simulator.into_warnings())) + Ok(compiled.into_program_image_and_warnings()) } /// Run cocotb's VPI bootstrap against a compiled native program instance. diff --git a/crates/celox-bench/tests/celox_heliodor_build_cache.rs b/crates/celox-vpi/tests/run_build_cache.rs similarity index 97% rename from crates/celox-bench/tests/celox_heliodor_build_cache.rs rename to crates/celox-vpi/tests/run_build_cache.rs index 4684a539cd5..0e4fc2abf3a 100644 --- a/crates/celox-bench/tests/celox_heliodor_build_cache.rs +++ b/crates/celox-vpi/tests/run_build_cache.rs @@ -80,7 +80,7 @@ fn run_with_project( success: bool, environment: &[(&str, &std::ffi::OsStr)], ) -> String { - let mut command = Command::new(env!("CARGO_BIN_EXE_celox-heliodor")); + let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); // Isolate the test from user diagnostics and codegen environment switches. for (name, _) in std::env::vars_os() { if name.to_string_lossy().starts_with("CELOX_") { @@ -90,9 +90,10 @@ fn run_with_project( let output = command .envs(environment.iter().copied()) .current_dir(working_dir) + .args(["run", "--report"]) .arg("--project") .arg(project) - .args(["--test", "t", "--source-file", "src/test.veryl"]) + .args(["--top", "t", "--source-file", "src/test.veryl"]) .args(args) .output() .unwrap(); @@ -218,7 +219,7 @@ fn reuses_compilation_across_processes_and_invalidates_changed_inputs() { ); } // Execution-only limits do not change the generated program. - cached(path, &["--tick-limit", "100"], "hit", true); + cached(path, &["--max-steps", "100"], "hit", true); for args in [ vec!["--opt-level", "o0"], vec!["--four-state"], @@ -732,3 +733,15 @@ module t { cached(path, &args, "miss", true); cached(path, &args, "hit", true); } + +#[test] +fn cache_tracks_cli_parameter_overrides() { + let fixture = project( + "#[test(t)] module t #(param V: u32 = 1) { initial { $display(\"value=%0d\", V); $finish(); } }", + ); + for (value, status) in [("1", "miss"), ("7", "miss"), ("7", "hit"), ("1", "hit")] { + let parameter = format!("V={value}"); + let output = cached(fixture.path(), &["-G", ¶meter], status, true); + assert!(output.contains(&format!("value={value}")), "{output}"); + } +} diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index 1982a072831..7f180da6475 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -232,7 +232,7 @@ fn veryl_project_discovers_sibling_sources() { fn rejects_mixed_sources_and_veryl_without_a_testbench() { let output = run(&[("top.sv", ""), ("top.veryl", "")], &[]); assert_eq!(output.status.code(), Some(1)); - assert!(String::from_utf8_lossy(&output.stderr).contains("one .veryl")); + assert!(String::from_utf8_lossy(&output.stderr).contains("Veryl project sources")); let output = run(&[("top.veryl", "module Top {}")], &[]); assert_eq!(output.status.code(), Some(1)); assert!( @@ -330,3 +330,213 @@ fn sv_stop_is_not_reported_as_successful_completion() { ); assert_eq!(output.stdout, b"before stop\n"); } + +#[test] +fn veryl_backends_share_cli_execution_and_opt_in_reports() { + let source = + "#[test(Top)] module Top { inst clk: $tb::clock_gen; initial { clk.next(4); $finish(); } }"; + for backend in ["native", "tiered", "interpreter", "cranelift", "wasm"] { + for four_state in [false, true] { + let mut args = vec!["--backend", backend, "--threads", "2", "--report"]; + if four_state { + args.push("--four-state"); + } + let output = run(&[("top.veryl", source)], &args); + assert!(output.status.success(), "{backend}: {output:?}"); + let report = String::from_utf8(output.stdout).unwrap(); + assert!( + report.contains(&format!( + "backend={backend} opt_level=O2 four_state={four_state}" + )), + "{report}" + ); + assert!( + report.contains("CELOX_TEST_THREADS test=Top threads=2"), + "{report}" + ); + assert!( + report.contains("CELOX_TEST_RESULT test=Top status=pass"), + "{report}" + ); + } + } + let output = run(&[("top.veryl", source)], &[]); + assert!(output.status.success(), "{output:?}"); + assert!(output.stdout.is_empty(), "{output:?}"); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_defaults_to_two_state_and_four_state_is_explicit() { + for (args, expected) in [(vec![], "0"), (vec!["--four-state"], "x")] { + let source = format!( + "module Top; logic value; initial begin #1; assert (value === 1'b{expected}) else $fatal(1, \"state mode\"); $finish; end endmodule" + ); + let output = run(&[("top.sv", &source)], &args); + assert!(output.status.success(), "{args:?}: {output:?}"); + } +} + +#[test] +fn cli_compiles_images_and_loads_without_sources() { + let temporary = tempfile::tempdir().unwrap(); + let source = temporary.path().join("top.veryl"); + let image = temporary.path().join("top.image"); + std::fs::write( + &source, + "#[test(Top)] module Top { initial { $finish(); } }", + ) + .unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .args([ + "run", + "--top", + "Top", + "--compile-only", + "--native-image-output", + ]) + .arg(&image) + .arg(&source) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + std::fs::remove_file(source).unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .current_dir(temporary.path()) + .args(["run", "--top", "Top", "--native-image-input"]) + .arg(image) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); +} + +#[test] +fn execution_option_conflicts_are_rejected() { + for args in [ + vec!["--threads", "0"], + vec!["--threads", "65"], + vec!["--max-steps", "1", "--unlimited"], + vec!["--require-compiled"], + vec!["--report", "--require-compiled", "--backend", "native"], + vec!["--compile-only", "--backend", "tiered"], + vec![ + "--compile-only", + "--dump-ir-dir", + "unused", + "--dump-ir-and-run", + ], + ] { + let output = run( + &[( + "top.veryl", + "#[test(Top)] module Top { initial { $finish(); } }", + )], + &args, + ); + assert_eq!(output.status.code(), Some(2), "{args:?}: {output:?}"); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_backends_preserve_timed_nba_execution_and_failures() { + let source = r#" + module Top; + logic clk = 0; + logic [7:0] count = 0; + always #5 clk = ~clk; + always @(posedge clk) count <= count + 1; + initial begin + #16; + assert (count == 2) else $fatal(1, "NBA count"); + $display("count=%0d", count); + $finish; + end + endmodule + "#; + for backend in ["native", "cranelift", "interpreter", "wasm", "tiered"] { + for four_state in [false, true] { + let mut args = vec!["--backend", backend, "--threads", "2"]; + if four_state { + args.push("--four-state"); + } + let output = run(&[("top.sv", source)], &args); + assert!(output.status.success(), "{args:?}: {output:?}"); + assert_eq!(output.stdout, b"count=2\n", "{args:?}"); + let limited = run( + &[("top.sv", source)], + &[args.clone(), vec!["--max-steps", "1"]].concat(), + ); + assert!(!limited.status.success(), "{args:?}: {limited:?}"); + assert!(String::from_utf8_lossy(&limited.stderr).contains("exceeded --max-steps")); + let failing = source.replace("count == 2", "count == 3"); + let output = run(&[("top.sv", &failing)], &args); + assert!(!output.status.success(), "{args:?}: {output:?}"); + assert!(String::from_utf8_lossy(&output.stdout).contains("NBA count")); + } + } +} + +#[test] +fn image_reports_its_embedded_state_mode() { + let temporary = tempfile::tempdir().unwrap(); + let source = temporary.path().join("top.veryl"); + let image = temporary.path().join("top.image"); + std::fs::write( + &source, + "#[test(Top)] module Top { initial { $finish(); } }", + ) + .unwrap(); + for four_state in [false, true] { + let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); + command + .args([ + "run", + "--top", + "Top", + "--compile-only", + "--native-image-output", + ]) + .arg(&image) + .arg(&source); + if four_state { + command.arg("--four-state"); + } + let output = command.output().unwrap(); + assert!(output.status.success(), "{output:?}"); + let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); + command + .args(["run", "--top", "Top", "--report", "--native-image-input"]) + .arg(&image); + if !four_state { + command.arg("--four-state"); + } + let output = command.output().unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stdout).contains(&format!("four_state={four_state}")), + "{output:?}" + ); + } +} + +#[test] +fn source_file_is_relative_to_celox_manifest_from_another_directory() { + let project = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + std::fs::create_dir(project.path().join("src")).unwrap(); + std::fs::write( + project.path().join("src/top.veryl"), + "#[test(Top)] module Top { initial { $finish(); } }", + ) + .unwrap(); + std::fs::write(project.path().join("celox.toml"), "top = 'Top'\n").unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .current_dir(elsewhere.path()) + .args(["run", "--project"]) + .arg(project.path().join("celox.toml")) + .args(["--source-file", "src/top.veryl"]) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); +} diff --git a/crates/celox-vpi/tests/run_cross_codegen.rs b/crates/celox-vpi/tests/run_cross_codegen.rs new file mode 100644 index 00000000000..f5232fdbb40 --- /dev/null +++ b/crates/celox-vpi/tests/run_cross_codegen.rs @@ -0,0 +1,44 @@ +//! Cross-codegen uses the normal CLI and must never initialize foreign code. +#![cfg(any( + all(target_arch = "x86_64", feature = "arm64-codegen"), + all(target_arch = "aarch64", feature = "x86_64-codegen") +))] + +use std::{fs, process::Command}; + +#[test] +fn exports_foreign_native_image_and_rejects_execution() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("top.veryl"); + let image = root.path().join("top.image"); + fs::write( + &source, + "#[test(Top)] module Top { initial { $finish(); } }", + ) + .unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .args([ + "run", + "--top", + "Top", + "--compile-only", + "--native-image-output", + ]) + .arg(&image) + .arg(&source) + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + celox::NativeProgramImage::from_container_bytes(&fs::read(image).unwrap()).unwrap(); + + let output = Command::new(env!("CARGO_BIN_EXE_celox")) + .args(["run", "--top", "Top"]) + .arg(source) + .output() + .unwrap(); + assert!(!output.status.success(), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("cross-codegen requires --compile-only"), + "{output:?}" + ); +} diff --git a/crates/celox-bench/tests/celox_heliodor_diagnostics.rs b/crates/celox-vpi/tests/run_diagnostics.rs similarity index 52% rename from crates/celox-bench/tests/celox_heliodor_diagnostics.rs rename to crates/celox-vpi/tests/run_diagnostics.rs index ce2fb81dfce..73a5d6c5e31 100644 --- a/crates/celox-bench/tests/celox_heliodor_diagnostics.rs +++ b/crates/celox-vpi/tests/run_diagnostics.rs @@ -24,11 +24,12 @@ fn diagnostics_reach_stderr_only_when_logging_is_enabled() { .unwrap(); for logging in [false, true] { - let mut command = Command::new(env!("CARGO_BIN_EXE_celox-heliodor")); + let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); command + .args(["run", "--report"]) .arg("--project") .arg(project.path()) - .args(["--test", "t", "--backend", "interpreter"]) + .args(["--top", "t", "--backend", "interpreter"]) .env("CELOX_PHASE_TIMING", "1") .env("CELOX_TESTBENCH_PROGRESS", "2") .env_remove("RUST_LOG"); @@ -49,3 +50,47 @@ fn diagnostics_reach_stderr_only_when_logging_is_enabled() { assert!(!stdout.contains("[testbench-progress]")); } } + +#[test] +fn compile_only_preserves_warnings_with_and_without_cache() { + let project = tempfile::tempdir().unwrap(); + fs::write( + project.path().join("Veryl.toml"), + "[project]\nname = 'warnings'\nversion = '0.1.0'\n", + ) + .unwrap(); + fs::write( + project.path().join("top.veryl"), + r#" +module Top (tmp: output logic<8>, out: output logic) { + function write_outputs(first: output logic<8>, second: output logic<8>) -> logic { + first = 8'd1; + second = 8'd2; + return 1'b1; + } + always_comb { + tmp = 0; + out = write_outputs(second: tmp, first: tmp) & 1'b1; + } +} +"#, + ) + .unwrap(); + for cached in [false, true] { + let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); + command + .args(["run", "--top", "Top", "--compile-only", "--project"]) + .arg(project.path()); + if cached { + command + .arg("--build-cache-dir") + .arg(project.path().join("cache")); + } + let output = command.output().unwrap(); + assert!(output.status.success(), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("unspecified_output_copy_order"), + "{output:?}" + ); + } +} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 568a1ca1c40..d69a4d92f1a 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -482,7 +482,7 @@ impl NativeProgramImage { } /// Whether the image's generated code and state layout use four-state data. - pub(crate) fn four_state(&self) -> bool { + pub fn four_state(&self) -> bool { self.options.four_state } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 220ac82b9e8..c95881c8018 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -58,7 +58,7 @@ impl std::fmt::Debug for SimulationCheckpoint { /// /// The default type parameter uses the host's [`crate::DefaultBackend`]. /// The builder also offers `build_native`, `build_cranelift`, `build_wasm`, -/// and `build_interpreter`; thread and partition options apply to timed builds. +/// `build_interpreter`, and `build_tiered`; thread and partition options apply to timed builds. pub struct Simulation { pub(crate) simulator: Simulator, pub(crate) state: SimulationState, @@ -770,10 +770,7 @@ mod process_tests { .unwrap(), steps as u64, ); - check( - Simulation::new(builder(four_state, steps).build_tiered().unwrap()), - steps as u64, - ); + check(timed().build_tiered().unwrap(), steps as u64); #[cfg(any( all(target_arch = "x86_64", not(feature = "arm64-codegen")), all(target_arch = "aarch64", not(feature = "x86_64-codegen")) @@ -808,6 +805,62 @@ mod process_tests { } } + #[cfg(feature = "systemverilog")] + #[test] + fn timed_tiered_promotion_preserves_suspended_processes_and_nba() { + let source = r#" + `timescale 1fs/1fs + module Top(output logic [7:0] count); + logic clk = 0; + initial count = 0; + always #5 clk = ~clk; + always @(posedge clk) count <= count + 1; + initial begin #36; $finish; end + endmodule + "#; + for four_state in [false, true] { + for threads in [1, 4] { + let mut sim = Simulation::from_sv_sources( + vec![(source, std::path::Path::new("tiered.sv"))], + "Top", + ) + .four_state(four_state) + .threads(threads) + .parallel_partition(crate::ParallelPartition::Always) + .tier_promotion(crate::TierPromotion::AfterSteps(1000)) + .build_tiered() + .unwrap(); + let count = sim.signal("count"); + sim.run_until(10).unwrap(); + assert!(!sim.simulator.is_compiled()); + assert_eq!(sim.get(count), 1u8.into()); + // Poll at the same simulation time while future delayed processes + // remain suspended. The tier transition must retain their resume + // positions and subsequent Active/NBA ordering (IEEE 1800-2023 4.5). + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !sim.simulator.is_compiled() { + sim.eval_comb().unwrap(); + assert!( + sim.simulator.promotion_error().is_none(), + "{:?}", + sim.simulator.promotion_error() + ); + assert!( + std::time::Instant::now() < deadline, + "tiered compilation timed out" + ); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(sim.time(), 10); + assert_eq!(sim.get_four_state(count), (1u8.into(), 0u8.into())); + sim.run_until(40).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.get_four_state(count), (4u8.into(), 0u8.into())); + assert!(sim.simulator.tiered_execution_stats().compiled_evaluations > 0); + } + } + } + #[test] fn processes_run_on_every_backend() { check_all_backends(false, 37); diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index a76a0547bbf..7308f98bf04 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1664,6 +1664,17 @@ mod host { self.image } + /// Consume the compilation without initializing executable memory, + /// retaining both the native artifact and its compilation warnings. + pub fn into_program_image_and_warnings( + self, + ) -> ( + crate::backend::native::NativeProgramImage, + Vec, + ) { + (self.image, self.warnings) + } + /// Write the generated native image as a standalone binary container. pub fn write_image( &self, @@ -3355,6 +3366,17 @@ mod host { ) } + /// Builds a timed simulation that starts interpreted and adopts compiled + /// code at a scheduler safe point once background compilation completes. + pub fn build_tiered( + self, + ) -> Result, SimulatorError> { + let layout = crate::backend::tiered::tiered_layout_mode(self.vcd_path.is_some()); + self.build_with_backend(layout, |program, options| { + Ok(crate::backend::TieredBackend::new(program, options)) + }) + } + fn build_with_backend( mut self, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, diff --git a/docs/benchmarks/heliodor.md b/docs/benchmarks/heliodor.md index 2b1fdb2663a..bacadc571ec 100644 --- a/docs/benchmarks/heliodor.md +++ b/docs/benchmarks/heliodor.md @@ -155,9 +155,12 @@ same VM within each group below (36 jobs for the complete suite): | 8 harts, either architecture | Four jobs, one per backend | | Every SMP workload (2, 4, 8 harts) | One more job: `celox-parallel` | +Celox measurements use the normal `celox run` CLI with `--report --unlimited`. +The runner defaults to two-state; the benchmark no longer builds a dedicated Celox executable. + `celox-parallel` is the native backend with [multi-threaded simulation](../guide/parallel-simulation.md), using one thread per -host vCPU (`HELIODOR_CELOX_THREADS`, default `nproc`). Its own job keeps the +host vCPU (`HELIODOR_CELOX_THREADS`, default `nproc` clamped to 2–64). Its own job keeps the comparison groups' time budgets unchanged. The dashboard shows it as "multi-threaded" next to single-threaded native execution. diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index a6946a7e75d..a8e5e399c5e 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -33,10 +33,10 @@ target/release/celox run test/Top.veryl --top Top ``` For SystemVerilog, pass `.sv` or `.v` sources in compilation order. The command -uses four-state simulation and runs until `$finish` or no scheduled events +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` and collects the project's sources and dependencies. A standalone -Veryl file also works. Select the native testbench module with `--top`. +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 falling through its initial blocks. @@ -57,7 +57,44 @@ testbench executor sends its HDL output to stderr. scheduler steps for SV and testbench ticks for Veryl. Reaching the Veryl tick limit before completion fails the command. This limit does not bound compilation or work within a single step/tick; use an external process timeout when a wall -clock limit is needed. Source languages cannot be mixed in one invocation. +clock limit is needed. `--unlimited` removes the step/tick limit. Source languages cannot be mixed in one invocation. + +## Select execution and collect measurements + +`celox run` accepts `--threads N` (1–64, default 1) and `--four-state` for both +languages. Both languages support `--backend native|tiered|interpreter|cranelift|wasm` +(default: native). Tiered starts interpreted and adopts compiled code at a scheduler +safe point while preserving pending events. For example: + +```sh +celox run test/Top.sv --top Top --backend tiered --threads 4 +``` + +For Veryl native testbenches it also provides: + +| Options | Purpose | +| --- | --- | +| `--report` | Emit machine-readable `CELOX_*` configuration, timing, tiered statistics and result records on stdout. | +| `--require-compiled` | With `--report --backend tiered`, require generated code to be exercised in a completed run. Normal tiered runs can finish on the interpreter. | +| `--compile-only` | Compile native, Cranelift or WASM code without executing the testbench. | +| `--build-cache-dir DIR` | Cache native compilation for a Veryl.toml project in a trusted local directory. | +| `--native-image-output FILE` | Export a native image with `--compile-only`. | +| `--native-image-input FILE` | Execute an image without reading HDL sources. | +| `--dump-ir-dir DIR` | Write native compiler diagnostics; add `--dump-ir-and-run` to execute as well. | + +```sh +celox run --project /path/to/veryl-project --top smoke --backend tiered --threads 4 +celox run test/Top.veryl --top Top --four-state +celox run --project /path/to/veryl-project --top smoke --report --unlimited +``` + +`--project` accepts a Veryl project directory or `Veryl.toml` as well as +`celox.toml`. `--source-file PATH` selects a Veryl source relative to the project; +repeat it to select multiple files. Heliodor benchmarks invoke this same CLI +with `--report --unlimited`; no separate Celox benchmark executable is used. +The report preserves compile/execute/generated-code timing intervals, and tiered +execution time includes background compilation and promotion. Short tiered runs +need not promote unless `--require-compiled` is requested. ## Manage a multi-file project diff --git a/docs/ja/benchmarks/heliodor.md b/docs/ja/benchmarks/heliodor.md index 88337d3efd7..d70e7c94a05 100644 --- a/docs/ja/benchmarks/heliodor.md +++ b/docs/ja/benchmarks/heliodor.md @@ -143,8 +143,11 @@ Linux バージョンはシミュレーション内で起動するゲストの | 両アーキテクチャの 8 hart | バックエンドごとに別ジョブ | | すべての SMP 構成(2・4・8 hart) | `celox-parallel` の 1 ジョブを追加 | +Celoxの計測は通常の`celox run --report --unlimited`を使います。 +既定は2値で、ベンチ専用のCelox実行バイナリはビルドしません。 + `celox-parallel` は native バックエンドを[並列シミュレーション](../guide/parallel-simulation.md)で -実行し、ホストの vCPU ごとに 1 スレッドを使います(`HELIODOR_CELOX_THREADS`、既定値は `nproc`)。 +実行し、ホストの vCPU ごとに 1 スレッドを使います(`HELIODOR_CELOX_THREADS`、既定値は `nproc` を2〜64に収めた値)。 別ジョブにすることで、比較グループの実行時間の上限は変わりません。ダッシュボードでは シングルスレッドの native 実行と並べて「multi-threaded」として表示します。 diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index f29a09e3a43..d0a26bd0fe6 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -30,10 +30,10 @@ 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`をコンパイル順に指定します。4値シミュレーションを使い、 +SVは`.sv`または`.v`をコンパイル順に指定します。既定では2値シミュレーションを使い(`--four-state`でX/Zを扱う4値に切り替え)、 `$finish`または実行待ちイベントがなくなるまで実行します。 Verylはプロジェクト内の1ファイルを指定すると、`Veryl.toml`から -ソースと依存関係を収集します。単独のVerylファイルも使用できます。 +ソースと依存関係を収集します。単独のVerylファイルも使用でき、Verylも既定は2値です。 `--top`にはnative testbenchのモジュール名を指定します。 既存のnative testbench実行器を使うため、initialブロックの末尾への到達でも完了します。 @@ -53,6 +53,32 @@ Verylでは完了前にtick上限に達すると失敗します。 コンパイルや1ステップ・tick内の処理時間は制限しないため、実時間の制限が必要な場合は 外部のタイムアウト機能を使ってください。1回の実行で言語を混在させることはできません。 +両言語とも`--backend native|tiered|interpreter|cranelift|wasm`で実行方式を選べます(既定native)。 +tieredはインタープリターで開始し、待機中のイベントを保ちながら生成コードへ移行します。 +両言語とも`--threads N`(1〜64、既定1)で並列度を指定できます。 +`--unlimited`で実行ステップ・tick数の上限を解除します。 + +```sh +celox run test/Top.sv --top Top --backend tiered --threads 4 +celox run --project /path/to/veryl-project --top smoke --backend tiered --threads 4 +celox run test/Top.veryl --top Top --four-state +celox run --project /path/to/veryl-project --top smoke --report --unlimited +``` + +Veryl用の`--report`は設定・コンパイル時間・実行時間・tiered昇格統計・結果を +機械可読な`CELOX_*`レコードとして標準出力に出します。通常実行では出しません。 +Heliodorベンチも専用Celoxバイナリではなく、このCLIを呼びます。 +`--report --backend tiered --require-compiled`では生成コードの実行を必須にできます。 +通常の短いtiered実行はインタープリターのまま終了しても成功です。 + +`--project`は`celox.toml`のほか、Verylプロジェクトディレクトリや`Veryl.toml`を受け取ります。 +`--source-file PATH`はプロジェクトからの相対パスでVerylソースを選択します(複数指定可)。 +native用の`--build-cache-dir DIR`はVeryl.tomlプロジェクトのコンパイルをキャッシュし、 +`--compile-only --native-image-output FILE`でイメージを書き出し、 +`--native-image-input FILE`でHDLソースなしに実行できます。 +`--dump-ir-dir DIR`でIRを保存し、`--dump-ir-and-run`でそのまま実行できます。 + + ## 複数ファイルのプロジェクトを管理する 共通の入力と名前付きターゲットを`celox.toml`に保存できます。 diff --git a/scripts/benchmark-workflows.test.mjs b/scripts/benchmark-workflows.test.mjs index 6e43919e1b1..5f58b398e90 100644 --- a/scripts/benchmark-workflows.test.mjs +++ b/scripts/benchmark-workflows.test.mjs @@ -155,3 +155,13 @@ test("failed manual validation and cancellation cannot start expensive jobs", () assert.equal(runs(name, "schedule", "master", {}, "skipped", true), false, name); } }); + + +test("profiling reuse rejects pre-CLI artifacts before capture", () => { + const arm = job(heliodor, "arm64-linux-boot-full"); + const check = arm.slice(arm.indexOf("- name: Validate reused ARM64 profiling runner"), arm.indexOf("- name: Prepare ARM64 profiling")); + assert.match(check, /if: inputs.arm64_profile && inputs.arm64_profile_run_id != ''/); + assert.match(check, /if \[\[ ! -f target\/release\/celox \]\]/); + assert.match(check, /predates the celox run CLI/); + assert.match(check, /exit 1/); +}); diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index c9dba7304cd..3defbd38d10 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -83,11 +83,12 @@ export function affectsHeliodorArm64(files) { "crates/celox-backend-arm64/", "crates/celox-backend-common/", "crates/celox/src/backend/native/", + "crates/celox-vpi/src/bin/celox/", "scripts/ci-changes.", ]) || [ "crates/celox/src/backend.rs", - "crates/celox-bench/src/bin/celox-heliodor.rs", + "crates/celox-vpi/src/bin/celox.rs", "scripts/run-heliodor-bench.sh", "scripts/heliodor-revision", "scripts/setup-arm64-backend-dev.sh", diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index b07098c3090..d00b604c03a 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -52,7 +52,7 @@ test("Rust test infrastructure skips bindings while retaining Rust checks", () = "crates/celox-napi/tests/fixture.json", "crates/celox/benches/simulation.rs", "crates/celox/examples/sv_tests.rs", - "crates/celox-bench/src/bin/celox-heliodor.rs", + "crates/celox-bench/src/bin/veryl-heliodor.rs", "crates/celox-bench-sv/src/main.rs", "crates/celox-vpi/src/lib.rs", "crates/celox-wasm/src/lib.rs", @@ -444,7 +444,7 @@ test("ARM64 Heliodor changes include backend and harness integration", () => { "crates/celox-backend-common/src/lib.rs", "crates/celox/src/backend/native/backend.rs", "crates/celox/src/backend.rs", - "crates/celox-bench/src/bin/celox-heliodor.rs", + "crates/celox-vpi/src/bin/celox/runner.rs", "scripts/run-heliodor-bench.sh", "scripts/heliodor-revision", ".github/actions/setup-rust/action.yml", diff --git a/scripts/run-heliodor-bench.sh b/scripts/run-heliodor-bench.sh index 342c8717639..0ea4d27095b 100755 --- a/scripts/run-heliodor-bench.sh +++ b/scripts/run-heliodor-bench.sh @@ -43,13 +43,13 @@ fi CELOX_TARGET_ROOT="${HELIODOR_CELOX_TARGET_DIR:-$CELOX_ROOT/target}" if [[ -z "$CELOX_RUNNER_BIN" ]]; then if [[ -n "$HELIODOR_CELOX_EXECUTION_TARGET" ]]; then - CELOX_RUNNER_BIN="$CELOX_TARGET_ROOT/$HELIODOR_CELOX_EXECUTION_TARGET/$HELIODOR_CELOX_CARGO_PROFILE/celox-heliodor" + CELOX_RUNNER_BIN="$CELOX_TARGET_ROOT/$HELIODOR_CELOX_EXECUTION_TARGET/$HELIODOR_CELOX_CARGO_PROFILE/celox" else - CELOX_RUNNER_BIN="$CELOX_TARGET_ROOT/$HELIODOR_CELOX_CARGO_PROFILE/celox-heliodor" + CELOX_RUNNER_BIN="$CELOX_TARGET_ROOT/$HELIODOR_CELOX_CARGO_PROFILE/celox" fi fi if [[ -z "$CELOX_CODEGEN_RUNNER_BIN" ]]; then - CELOX_CODEGEN_RUNNER_BIN="$CELOX_TARGET_ROOT/$HELIODOR_CELOX_CARGO_PROFILE/celox-heliodor" + CELOX_CODEGEN_RUNNER_BIN="$CELOX_TARGET_ROOT/$HELIODOR_CELOX_CARGO_PROFILE/celox" fi if [[ -z "$VERYL_TIMED_RUNNER_BIN" ]]; then VERYL_TIMED_RUNNER_BIN="$CELOX_TARGET_ROOT/$HELIODOR_CELOX_CARGO_PROFILE/veryl-heliodor" @@ -57,7 +57,14 @@ fi HELIODOR_COMPILE_ONLY="${HELIODOR_COMPILE_ONLY:-${HELIODOR_CELOX_COMPILE_ONLY:-0}}" HELIODOR_COMPILE_TIMEOUT_SEC="${HELIODOR_COMPILE_TIMEOUT_SEC:-${HELIODOR_CELOX_COMPILE_TIMEOUT_SEC:-}}" HELIODOR_CELOX_TIMEOUT_MULTIPLIER="${HELIODOR_CELOX_TIMEOUT_MULTIPLIER:-2}" -HELIODOR_CELOX_THREADS="${HELIODOR_CELOX_THREADS:-$(nproc 2>/dev/null || echo 2)}" +default_celox_threads() { + local count + count=$(nproc 2>/dev/null || echo 2) + ((count > 64)) && count=64 + ((count < 2)) && count=2 + echo "$count" +} +HELIODOR_CELOX_THREADS="${HELIODOR_CELOX_THREADS:-$(default_celox_threads)}" HELIODOR_INSTALL_TOOLS="${HELIODOR_INSTALL_TOOLS:-1}" HELIODOR_VERYL_VERSION="${HELIODOR_VERYL_VERSION:-0.20.3}" VERYL_BIN="${VERYL_BIN:-}" @@ -119,7 +126,7 @@ Environment: HELIODOR_CELOX_TIMEOUT_MULTIPLIER timeout Celox after N times the fastest successful Veryl baseline HELIODOR_CELOX_THREADS - simulation threads of celox-parallel and celox-tiered (default: nproc) + simulation threads of celox-parallel and celox-tiered (default: nproc clamped to 2..64) CELOX_OPT_LEVEL O0, O1, or O2 for the Celox runner (default: O2) CELOX_SIR_PASS_OVERRIDES space-separated SIR pass overrides, e.g. "-vectorize_concat +gvn" @@ -1231,8 +1238,8 @@ build_celox_runner() { fi fi if ! env -u CARGO_TARGET_DIR -u CARGO_BUILD_TARGET \ - cargo build --manifest-path "$CELOX_ROOT/Cargo.toml" -p celox-bench \ - --bin celox-heliodor --profile "$HELIODOR_CELOX_CARGO_PROFILE" --locked \ + cargo build --manifest-path "$CELOX_ROOT/Cargo.toml" -p celox-vpi \ + --bin celox --profile "$HELIODOR_CELOX_CARGO_PROFILE" --locked \ "${feature_args[@]}" "${target_args[@]}" "${target_dir_args[@]}" >"$log" 2>&1; then tail -n 80 "$log" >&2 || true return 1 @@ -1263,8 +1270,8 @@ build_celox_codegen_runner() { feature_args=(--features "$HELIODOR_CELOX_CODEGEN_CARGO_FEATURES") fi if ! env -u CARGO_TARGET_DIR -u CARGO_BUILD_TARGET \ - cargo build --manifest-path "$CELOX_ROOT/Cargo.toml" -p celox-bench \ - --bin celox-heliodor --profile "$HELIODOR_CELOX_CARGO_PROFILE" --locked \ + cargo build --manifest-path "$CELOX_ROOT/Cargo.toml" -p celox-vpi \ + --bin celox --profile "$HELIODOR_CELOX_CARGO_PROFILE" --locked \ "${feature_args[@]}" "${target_dir_args[@]}" >"$log" 2>&1; then tail -n 80 "$log" >&2 || true return 1 @@ -1463,7 +1470,7 @@ run_one() { local veryl_aot_cache_dir="" local -a source_files celox_args celox_cache_args celox_execution_command timed_veryl_args collect_test_source_files "$test" source_files || return "$?" - celox_args=() + celox_args=(--report --unlimited) celox_cache_args=() if [[ "$runner" == celox && -n "$HELIODOR_CELOX_BUILD_CACHE_DIR" ]]; then celox_cache_args+=(--build-cache-dir "$HELIODOR_CELOX_BUILD_CACHE_DIR") @@ -1485,9 +1492,9 @@ run_one() { # disabled pass as a new command-line flag. celox_args+=(--sir-pass="$pass_override") done - celox_execution_command=("$CELOX_RUNNER_BIN") + celox_execution_command=("$CELOX_RUNNER_BIN" run) if [[ "$HELIODOR_CELOX_NATIVE_IMAGE_MODE" == host-qemu ]]; then - celox_execution_command=("${CELOX_EXECUTION_PREFIX[@]}" "$CELOX_RUNNER_BIN") + celox_execution_command=("${CELOX_EXECUTION_PREFIX[@]}" "$CELOX_RUNNER_BIN" run) fi if [[ "$HELIODOR_COMPILE_ONLY" == 1 ]]; then celox_args+=(--compile-only) @@ -1534,7 +1541,7 @@ run_one() { celox) if [[ "$HELIODOR_CELOX_NATIVE_IMAGE_MODE" == host-qemu ]]; then run_in_heliodor "$timeout_sec" "$native_codegen_log" \ - "$CELOX_CODEGEN_RUNNER_BIN" --project "$HELIODOR_DIR" --test "$test" \ + "$CELOX_CODEGEN_RUNNER_BIN" run --project "$HELIODOR_DIR" --top "$test" \ "${celox_args[@]}" --backend native --opt-level "${CELOX_OPT_LEVEL,,}" \ "${celox_cache_args[@]}" \ --compile-only --native-image-output "$native_image_path" @@ -1546,7 +1553,7 @@ run_one() { fi run_in_heliodor "$timeout_sec" "$log" \ "${celox_execution_command[@]}" \ - --project "$HELIODOR_DIR" --test "$test" \ + --project "$HELIODOR_DIR" --top "$test" \ "${celox_args[@]}" --backend native --opt-level "${CELOX_OPT_LEVEL,,}" \ --native-image-input "$native_image_path" process_status="$?" @@ -1556,7 +1563,7 @@ run_one() { else run_in_heliodor "$timeout_sec" "$log" \ "${celox_execution_command[@]}" \ - --project "$HELIODOR_DIR" --test "$test" \ + --project "$HELIODOR_DIR" --top "$test" \ "${celox_args[@]}" "${celox_cache_args[@]}" --backend native --opt-level "${CELOX_OPT_LEVEL,,}" process_status="$?" fi @@ -1564,7 +1571,7 @@ run_one() { celox-parallel) run_in_heliodor "$timeout_sec" "$log" \ "${celox_execution_command[@]}" \ - --project "$HELIODOR_DIR" --test "$test" \ + --project "$HELIODOR_DIR" --top "$test" \ "${celox_args[@]}" --backend native --opt-level "${CELOX_OPT_LEVEL,,}" \ --threads "$HELIODOR_CELOX_THREADS" process_status="$?" @@ -1572,22 +1579,22 @@ run_one() { celox-cranelift) run_in_heliodor "$timeout_sec" "$log" \ "${celox_execution_command[@]}" \ - --project "$HELIODOR_DIR" --test "$test" \ + --project "$HELIODOR_DIR" --top "$test" \ "${celox_args[@]}" --backend cranelift --opt-level "${CELOX_OPT_LEVEL,,}" process_status="$?" ;; celox-tiered) run_in_heliodor "$timeout_sec" "$log" \ "${celox_execution_command[@]}" \ - --project "$HELIODOR_DIR" --test "$test" \ - "${celox_args[@]}" --backend tiered --opt-level "${CELOX_OPT_LEVEL,,}" \ + --project "$HELIODOR_DIR" --top "$test" \ + "${celox_args[@]}" --require-compiled --backend tiered --opt-level "${CELOX_OPT_LEVEL,,}" \ --threads "$HELIODOR_CELOX_THREADS" process_status="$?" ;; celox-interpreter) run_in_heliodor "$timeout_sec" "$log" \ "${celox_execution_command[@]}" \ - --project "$HELIODOR_DIR" --test "$test" \ + --project "$HELIODOR_DIR" --top "$test" \ "${celox_args[@]}" --backend interpreter --opt-level "${CELOX_OPT_LEVEL,,}" process_status="$?" ;; @@ -2132,6 +2139,7 @@ run_gate() { HELIODOR_RUNNERS="veryl-cc-sync celox celox-tiered veryl-cc-tiered" HELIODOR_TIMEOUT_SEC="$GATE_TIMEOUT_SEC" HELIODOR_CELOX_TIMEOUT_MULTIPLIER=1 + HELIODOR_CELOX_THREADS=$(default_celox_threads) HELIODOR_COMPILE_ONLY=0 HELIODOR_CELOX_BUILD_CACHE_DIR="" HELIODOR_COMPILE_TIMEOUT_SEC="" @@ -2171,7 +2179,7 @@ run_gate() { invocation_dir="$(mktemp -d "$base_results_dir/gate_$(date -u +%Y%m%dT%H%M%SZ).XXXXXX")" HELIODOR_RESULTS_DIR="$invocation_dir" HELIODOR_CELOX_TARGET_DIR="$invocation_dir/celox-target" - CELOX_RUNNER_BIN="$HELIODOR_CELOX_TARGET_DIR/release/celox-heliodor" + CELOX_RUNNER_BIN="$HELIODOR_CELOX_TARGET_DIR/release/celox" VERYL_TIMED_RUNNER_BIN="$HELIODOR_CELOX_TARGET_DIR/release/veryl-heliodor" ensure_results_schema "$HELIODOR_RESULTS_DIR/results.tsv" || return "$?" diff --git a/scripts/tests/run-heliodor-bench-gate.sh b/scripts/tests/run-heliodor-bench-gate.sh index 60f69a18b10..c22c07d44c0 100644 --- a/scripts/tests/run-heliodor-bench-gate.sh +++ b/scripts/tests/run-heliodor-bench-gate.sh @@ -24,6 +24,11 @@ assert_eq() { || fail "$context: expected <$expected>, got <$actual>" } +# Many-core hosts must stay within the CLI range, including the fixed gate. +assert_eq "$(nproc() { echo 192; }; default_celox_threads)" 64 "cap derived thread count" +assert_eq "$(nproc() { echo 8; }; default_celox_threads)" 8 "preserve ordinary host parallelism" +assert_eq "$(nproc() { echo 1; }; default_celox_threads)" 2 "gate keeps parallel execution" + write_valid_gate_logs() { local directory="$1" local veryl_compile="${2:-30}" @@ -339,7 +344,7 @@ chmod +x "$mock_cargo_dir/cargo" export PATH="$mock_cargo_dir:$PATH" export CARGO_ARGS_LOG="$TMP/cargo-args" export CARGO_ENV_LOG="$TMP/cargo-env" - export MOCK_CARGO_RUNNER="$TMP/fixed-gate-target/release/celox-heliodor" + export MOCK_CARGO_RUNNER="$TMP/fixed-gate-target/release/celox" export CARGO_TARGET_DIR="$TMP/hostile-cargo-target" export CARGO_BUILD_TARGET=hostile-target-triple HELIODOR_RESULTS_DIR="$TMP/mock-build-results" @@ -347,7 +352,7 @@ chmod +x "$mock_cargo_dir/cargo" export HELIODOR_CELOX_CARGO_FEATURES= HELIODOR_CELOX_TARGET_DIR="$TMP/fixed-gate-target" HELIODOR_CELOX_CARGO_PROFILE=release - CELOX_RUNNER_BIN="$TMP/fixed-gate-target/release/celox-heliodor" + CELOX_RUNNER_BIN="$TMP/fixed-gate-target/release/celox" build_celox_runner >/dev/null ) target_arg_line="$(grep -n -x -- '--target-dir' "$TMP/cargo-args" | cut -d: -f1)" @@ -358,8 +363,8 @@ grep -qx -- '--locked' "$TMP/cargo-args" || fail "Celox build omitted --locked" if grep -qx -- '--features' "$TMP/cargo-args"; then fail "default Celox build unexpectedly passed --features" fi -grep -qx -- 'celox-bench' "$TMP/cargo-args" || fail "Celox build did not select celox-bench" -grep -qx -- 'celox-heliodor' "$TMP/cargo-args" || fail "Celox build did not select celox-heliodor" +grep -qx -- 'celox-vpi' "$TMP/cargo-args" || fail "Celox build did not select celox-vpi" +grep -qx -- 'celox' "$TMP/cargo-args" || fail "Celox build did not select celox" assert_eq "$(sed -n '1p' "$TMP/cargo-env")" unset "CARGO_TARGET_DIR neutralization" assert_eq "$(sed -n '2p' "$TMP/cargo-env")" unset "CARGO_BUILD_TARGET neutralization" @@ -518,11 +523,11 @@ build_celox_runner() { "$HELIODOR_RESULTS_DIR/celox-target" \ "fresh invocation-owned gate Cargo target directory" assert_eq "$CELOX_RUNNER_BIN" \ - "$HELIODOR_CELOX_TARGET_DIR/release/celox-heliodor" \ + "$HELIODOR_CELOX_TARGET_DIR/release/celox" \ "gate executes the just-built target-dir artifact" [[ ! -e "$HELIODOR_CELOX_TARGET_DIR" ]] \ || fail "gate Cargo target directory was not fresh" - [[ "$CELOX_RUNNER_BIN" != "$CELOX_ROOT/target/release/celox-heliodor" ]] \ + [[ "$CELOX_RUNNER_BIN" != "$CELOX_ROOT/target/release/celox" ]] \ || fail "gate selected a stale default-target runner" mkdir -p "$(dirname "$CELOX_RUNNER_BIN")" printf '%s\n' '#!/bin/sh' 'exit 0' >"$CELOX_RUNNER_BIN" @@ -660,8 +665,8 @@ run_gate_fixture() { mkdir -p "$CELOX_ROOT" mkdir -p "$CELOX_ROOT/target/release" printf '%s\n' '#!/bin/sh' 'echo stale runner; exit 9' \ - >"$CELOX_ROOT/target/release/celox-heliodor" - chmod +x "$CELOX_ROOT/target/release/celox-heliodor" + >"$CELOX_ROOT/target/release/celox" + chmod +x "$CELOX_ROOT/target/release/celox" HELIODOR_DIR="$TMP/hostile-heliodor" HELIODOR_RESULTS_DIR="$TMP/hostile-results" HELIODOR_TOOLS_DIR="$TMP/hostile-tools" @@ -688,7 +693,10 @@ run_gate_fixture() { assert_eq "$MOCK_RUNNERS" "veryl-cc-sync celox celox-tiered veryl-cc-tiered" "$name runner order" } +# The fixed gate must ignore an inherited sequential override. +HELIODOR_CELOX_THREADS=1 run_gate_fixture success 1 +assert_eq "$HELIODOR_CELOX_THREADS" "$(default_celox_threads)" "gate resets inherited threads" assert_eq "$(find "$LAST_GATE_RESULTS_ROOT" -name results.tsv | wc -l)" 1 \ "one isolated result file" success_results="$(find "$LAST_GATE_RESULTS_ROOT" -name results.tsv)" diff --git a/scripts/tests/run-heliodor-bench-results.sh b/scripts/tests/run-heliodor-bench-results.sh index 66a5409ffd5..1ae0147cb04 100644 --- a/scripts/tests/run-heliodor-bench-results.sh +++ b/scripts/tests/run-heliodor-bench-results.sh @@ -470,6 +470,12 @@ run_one celox-tiered integration_tiered >/dev/null \ || fail "tiered runner did not select the tiered backend" [[ " ${FIXTURE_RUN_ARGS[*]} " == *" --threads 4 "* ]] \ || fail "tiered runner did not request parallel execution" +[[ " ${FIXTURE_RUN_ARGS[*]} " == *" run "* && " ${FIXTURE_RUN_ARGS[*]} " == *" --top integration_tiered "* ]] \ + || fail "tiered runner did not use the normal CLI" +for flag in --report --unlimited --require-compiled; do + [[ " ${FIXTURE_RUN_ARGS[*]} " == *" $flag "* ]] \ + || fail "tiered runner omitted $flag" +done assert_eq "$(awk -F '\t' 'NR == 9 { print $1 }' "$integration_results/results.tsv")" \ celox-tiered "run_one tiered runner name" assert_eq "$(awk -F '\t' 'NR == 9 { print $12 }' "$integration_results/results.tsv")" NA \ From 27d7218f9c6965f4e464c437c4977fb38570f68d Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 05:29:14 +0900 Subject: [PATCH 2/2] fix(sv): resolve Taxi elaboration and cocotb visibility failures Taxi designs fail elaboration on constant concatenations, parameter actuals, input defaults, generate-local types, memory word part-selects and static scratch arrays that are completely overwritten before use. Resolve those cases while preserving parameter specialization, expression widths and X/Z. Expose integral parameters as read-only VPI objects and restore interface array hierarchy from declared source paths. Parameter references remain compile-time constants at O2. Reset the callback iteration budget whenever physical time advances, retaining the guard against nonadvancing loops. Aggregate input defaults remain errors by default; the unpacked_port_default diagnostic can enable this extension with warn or allow. Validation includes the SV regressions across available backends, analyzer and VPI package tests, affected-crate Clippy, and Verilator/Icarus checks for new shared cases. Icarus 13 does not support packed array parameters or the generate-scoped enum regression; those stronger O2 API cases are checked with Verilator instead. This is partial Taxi compatibility work. The cumulative audit after these fixes and the dependent CLI changes has 90 passing configurations across 50 pytest modules (879 original cocotb tests). It is not a full rerun of all 1561 configurations on the final tree. AXI crossbar, LFSR, dual-port RAM, Ethernet and other cases still expose unsupported behavior. Upstream's 4003 original source and test files remain unchanged. Change-Id: Icccf0dcafb4cec3c9476049601ae3f12a0023e39 --- .../src/symbolic/flattening.rs | 9 + crates/celox-frontend-sv/src/lib.rs | 4 +- crates/celox-frontend-sv/src/lowering.rs | 190 +++++++++- crates/celox-frontend-sv/src/warning.rs | 7 + crates/celox-runtime/src/reflection.rs | 2 + crates/celox-sv-analyzer/src/analyze.rs | 27 +- crates/celox-sv-analyzer/src/ast.rs | 11 + crates/celox-sv-analyzer/src/ast/casts.rs | 20 +- .../src/ast/const_functions.rs | 60 ++- .../src/ast/constant_binding.rs | 39 +- .../src/ast/constant_folding.rs | 25 +- .../celox-sv-analyzer/src/ast/declarations.rs | 51 ++- .../celox-sv-analyzer/src/ast/dimensions.rs | 31 +- crates/celox-sv-analyzer/src/ast/generate.rs | 162 ++++++++- .../src/ast/generate/elaboration.rs | 2 +- .../src/ast/generate/scope_views.rs | 19 +- .../celox-sv-analyzer/src/ast/interfaces.rs | 41 ++- crates/celox-sv-analyzer/src/ast/lifetimes.rs | 19 + .../src/ast/lifetimes/bit_result.rs | 344 ++++++++++++++++++ .../celox-sv-analyzer/src/ast/parameters.rs | 47 ++- .../celox-sv-analyzer/src/ast/procedural.rs | 10 +- crates/celox-sv-analyzer/src/ast/scope.rs | 1 + crates/celox-sv-analyzer/src/ast/selects.rs | 47 ++- crates/celox-sv-analyzer/src/ast/types.rs | 38 +- .../celox-sv-analyzer/src/ast/validation.rs | 3 - crates/celox-sv-analyzer/src/ir.rs | 11 + crates/celox-sv-analyzer/src/lib.rs | 3 +- .../source_tree/tests/instance_ownership.rs | 1 - crates/celox-sv-analyzer/src/typecheck.rs | 107 ++++++ .../src/sv/cases/generate.vtest | 55 +++ .../src/sv/cases/hierarchy.vtest | 106 ++++++ .../src/sv/cases/indexed_select.vtest | 69 ++++ .../src/sv/cases/literals.vtest | 27 ++ .../src/sv/cases/operators.vtest | 99 +++++ .../src/sv/cases/procedural.vtest | 96 +++++ crates/celox-vpi/src/callbacks.rs | 14 +- crates/celox-vpi/src/lib.rs | 83 +++-- crates/celox-vpi/tests/basic_vpi.rs | 173 ++++++++- crates/celox-vpi/tests/diagnostics.rs | 58 +++ crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/diagnostic_policy.rs | 11 +- crates/celox/src/ir.rs | 6 +- .../tests/frontends/systemverilog/generate.rs | 96 +++++ .../frontends/systemverilog/hierarchy.rs | 20 + .../frontends/systemverilog/indexed_select.rs | 18 +- .../tests/frontends/systemverilog/literals.rs | 4 + .../frontends/systemverilog/operators.rs | 16 + .../frontends/systemverilog/procedural.rs | 16 + .../systemverilog/review_regressions.rs | 4 +- 49 files changed, 2135 insertions(+), 169 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs diff --git a/crates/celox-frontend-core/src/symbolic/flattening.rs b/crates/celox-frontend-core/src/symbolic/flattening.rs index b31cfe65896..8d0f7c79af9 100644 --- a/crates/celox-frontend-core/src/symbolic/flattening.rs +++ b/crates/celox-frontend-core/src/symbolic/flattening.rs @@ -518,6 +518,12 @@ fn collect_inputs_with_window( set: &mut crate::HashSet>, visited: &mut HashMap>, ) { + // IEEE 1800-2023 11.4.12.1: a zero-count replication contributes no + // bits to its enclosing concatenation. There is no dependency window + // to visit, and constructing one would underflow its inclusive MSB. + if get_width(expr, arena) == 0 { + return; + } let requested = window.unwrap_or_else(|| BitAccess::new(0, get_width(expr, arena) - 1)); let uncovered = claim_uncovered_window(visited.entry(expr).or_default(), requested); @@ -596,6 +602,9 @@ fn collect_inputs_with_window( // Walk from LSB side to map the requested window to each part. let mut part_lsb = 0usize; for (part, width) in parts.iter().rev() { + if *width == 0 { + continue; + } let part_msb = part_lsb + width - 1; if win.overlaps(&BitAccess::new(part_lsb, part_msb)) { let ov_lsb = std::cmp::max(win.lsb, part_lsb); diff --git a/crates/celox-frontend-sv/src/lib.rs b/crates/celox-frontend-sv/src/lib.rs index bc6ad7f6c91..0d655719cf8 100644 --- a/crates/celox-frontend-sv/src/lib.rs +++ b/crates/celox-frontend-sv/src/lib.rs @@ -54,4 +54,6 @@ pub use lowering::{ prepare_external_hierarchy_with_foreign_resolver_with_options, schedule_sources_with_options, }; -pub use lowering::schedule_sources_with_force_signals; +pub use lowering::{ + schedule_sources_with_force_signals, schedule_sources_with_parameter_expressions, +}; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b065fabd633..7b440f50b12 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -128,7 +128,7 @@ pub(crate) struct LoweredSvModule { #[derive(Clone)] struct AnalyzedSvModule { name: String, - interface_member_paths: HashMap>, + interface_member_paths: HashMap, source: std::rc::Rc, implicit_nets_allowed: bool, /// The positional interface of every module in all sources, used to bind @@ -1788,6 +1788,49 @@ pub fn schedule_sources_with_force_signals( warnings: &mut Vec, analysis_options: sv::AnalysisOptions, force_signals: &[String], +) -> Result { + let parameters = parameter_overrides + .iter() + .map(|(name, value)| (name.clone(), sv::ir::ConstExpr::Literal(value.to_string()))) + .collect::>(); + schedule_sources_with_parameter_expressions( + sources, + top, + ¶meters, + ignored_loops, + true_loops, + four_state, + parallel, + trace_options, + trace, + warnings, + analysis_options, + force_signals, + ) +} + +/// Schedule a design with typed SV constant expressions as top parameters. +#[allow(clippy::too_many_arguments)] +pub fn schedule_sources_with_parameter_expressions( + sources: &[(&str, &Path)], + top: &str, + parameter_overrides: &[(String, sv::ir::ConstExpr)], + ignored_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + )], + true_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + usize, + )], + four_state: bool, + parallel: &celox_frontend_core::ParallelScheduleOptions, + trace_options: &FrontendTraceOptions, + trace: Option<&mut FrontendTrace>, + warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, + force_signals: &[String], ) -> Result { let mut found = Vec::new(); let scheduled = schedule_sources_collecting( @@ -1813,7 +1856,7 @@ pub fn schedule_sources_with_force_signals( fn schedule_sources_collecting( sources: &[(&str, &Path)], top: &str, - parameter_overrides: &[(String, u64)], + parameter_overrides: &[(String, sv::ir::ConstExpr)], ignored_loops: &[( (Vec<(String, usize)>, Vec), (Vec<(String, usize)>, Vec), @@ -1845,7 +1888,7 @@ fn schedule_sources_collecting( .iter() .map(|(name, value)| LoweredSvParameterOverride { name: name.clone(), - value: Some(sv::ir::ConstExpr::Literal(value.to_string())), + value: Some(value.clone()), bound_type: None, bound_pattern: None, }) @@ -1990,7 +2033,13 @@ fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvMod source .interface_member_paths .get(segment) - .cloned() + .and_then(|path| path.restore(segment)) + .or_else(|| { + source + .interface_member_paths + .values() + .find_map(|path| path.restore(segment)) + }) .unwrap_or_else(|| vec![segment.clone()]) }) .collect(); @@ -2091,7 +2140,7 @@ fn specialize_module( module .interface_member_paths .iter() - .find(|(_, segments)| segments.join(".") == *path) + .find(|(_, segments)| segments.segments.join(".") == *path) .map_or_else(|| path.clone(), |(flat, _)| flat.clone()) }) .collect::>(); @@ -2313,7 +2362,38 @@ fn lower_module_with_overrides( }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); - if port.is_net() || type_info.is_4state { + if let Some(default) = port.default() { + if !variable.array_dims.is_empty() { + warnings.push(( + crate::FrontendWarningKind::UnpackedPortDefault { + module: name.clone(), + port: port.name().to_string(), + }, + None, + )); + } + let literal = sv::typecheck::context_size_const_integral_literal( + default, + &constants, + ¶meter_types, + type_info.width, + type_info.signed, + ) + .ok_or_else(|| { + sv::AnalyzerError::Unsupported(format!( + "nonconstant input port default `{}`", + port.name() + )) + })?; + initial_memory_values.push(InitialStateValue { + address: id, + data: InitialStateData::Packed { + value: literal.value, + mask: literal.mask, + written_mask: (BigUint::from(1u8) << type_info.width) - BigUint::from(1u8), + }, + }); + } else if port.is_net() || type_info.is_4state { let written_mask = (BigUint::from(1u8) << type_info.width) - BigUint::from(1u8); let value = if port.is_net() { BigUint::default() @@ -2381,9 +2461,66 @@ fn lower_module_with_overrides( variables.insert(id, variable); } + // Retain integral parameters for external observation, without adding them + // to name_to_id: HDL expressions must still fold parameter references as + // constants rather than introduce runtime loads. + for parameter in module.parameters() { + let Some(width) = parameter.resolved_width().filter(|width| *width > 0) else { + continue; + }; + let signed = parameter.resolved_signed().unwrap_or(false); + let expr = parameter.value().cloned().or_else(|| { + constants + .get(parameter.name()) + .copied() + .map(const_expr_from_i128) + }); + let Some(literal) = expr.and_then(|expr| { + sv::typecheck::context_size_const_integral_literal( + &expr, + &constants, + ¶meter_types, + width, + signed, + ) + }) else { + continue; + }; + let id = next_var_id(&mut next_id); + let written_mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + initial_memory_values.push(InitialStateValue { + address: id, + data: InitialStateData::Packed { + value: literal.value, + mask: literal.mask, + written_mask, + }, + }); + variables.insert( + id, + SvVariable { + path: vec![parameter.name().to_string()], + width, + signed, + is_4state: true, + packed_ranges: vec![(width as i128 - 1, 0)], + array_dims: Vec::new(), + domain_kind: DomainKind::Other, + kind: VariableKind::Parameter, + type_kind: PortTypeKind::Logic, + source: None, + hidden: false, + force_control: None, + }, + ); + } + let forceable = variables .iter() .filter_map(|(&id, var)| { + if var.kind == VariableKind::Parameter { + return None; + } let name = &var.path[0]; force_signals.iter().any(|path| name == path).then_some(id) }) @@ -3914,6 +4051,39 @@ fn build_instance_glue( ), )?; (expr, sources, source_ids) + } else if let Some(default) = child + .source + .ports() + .iter() + .find(|port| port.name() == formal) + .and_then(|port| port.default()) + { + // IEEE 1800-2023 23.2.2.4: defaults belong to the child's + // parameter scope, and apply only to omitted connections. + let literal = sv::typecheck::context_size_const_integral_literal( + default, + &child.constants, + &child.parameter_types, + width, + child_var.signed, + ) + .ok_or_else(|| { + ParserError::illegal_context( + "systemverilog input port default", + formal.clone(), + None, + ) + })?; + ( + arena.alloc(SLTNode::Constant( + literal.value, + literal.mask, + width, + child_var.signed, + ))?, + HashSet::default(), + Vec::new(), + ) } else { let unknown_mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); ( @@ -4387,7 +4557,9 @@ fn lower_glue_parent_expr( )? }; let width = celox_slt::get_width(node, arena); - nodes.push((node, width)); + if width != 0 { + nodes.push((node, width)); + } sources.extend(part_sources); source_ids.extend(part_source_ids); } @@ -5574,7 +5746,9 @@ fn lower_expr_with_context( None, )?; let width = celox_slt::get_width(node, arena); - nodes.push((node, width)); + if width != 0 { + nodes.push((node, width)); + } sources.extend(part_sources); } Some((arena.alloc(SLTNode::Concat(nodes)).ok()?, sources)) diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 3ae40680a8f..5024c2dc46d 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, + /// 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 }, /// A memory file without address directives holds a different number of /// words than the address range of `$readmemh`/`$readmemb` /// (IEEE 1800-2023 21.4). @@ -141,6 +144,7 @@ impl miette::Diagnostic for FrontendWarning { fn code<'a>(&'a self) -> Option> { Some(Box::new(match self.kind { FrontendWarningKind::MixedTimescale => "mixed_timescale", + FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default", FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", })) @@ -155,6 +159,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::MixedTimescale => { "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" } + 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" + } FrontendWarningKind::MemoryFileWordCount { .. } => { "give one word per address of the range, or place the words with `@address` directives" } diff --git a/crates/celox-runtime/src/reflection.rs b/crates/celox-runtime/src/reflection.rs index 272f81c49b3..1ea8cfb1cf1 100644 --- a/crates/celox-runtime/src/reflection.rs +++ b/crates/celox-runtime/src/reflection.rs @@ -32,6 +32,8 @@ pub struct ReflectionScope { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ReflectionSignal { + /// An elaboration constant exposed as a read-only VPI parameter. + pub is_parameter: bool, pub name: String, pub full_name: String, pub parent: ReflectionScopeId, diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index f31aefea4d5..f574291b4e3 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -108,18 +108,21 @@ fn analyze_source_impl(source: ast::Source) -> Result { let mut ports = Vec::new(); for port in module.ports() { port_table.insert(module, port)?; - ports.push(ir::Port::new( - port.name().to_string(), - port.direction().into(), - ir::Type::from_ast( - port.r#type().clone(), - &ast::const_functions::Environment { - constants: &constants, - functions: &state.const_functions, - }, - ), - port.is_net(), - )); + ports.push( + ir::Port::new( + port.name().to_string(), + port.direction().into(), + ir::Type::from_ast( + port.r#type().clone(), + &ast::const_functions::Environment { + constants: &constants, + functions: &state.const_functions, + }, + ), + port.is_net(), + ) + .with_default(port.default().cloned().map(Into::into)), + ); } let signals = module .signals() diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 09423e4e817..220496f725f 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1613,6 +1613,7 @@ pub struct Port { direction: PortDirection, r#type: Type, is_net: bool, + default: Option, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -1671,6 +1672,7 @@ impl Port { direction, r#type, is_net, + default: None, } } @@ -1689,6 +1691,15 @@ impl Port { pub fn is_net(&self) -> bool { self.is_net } + + pub(crate) fn with_default(mut self, default: Option) -> Self { + self.default = default; + self + } + + pub fn default(&self) -> Option<&ConstExpr> { + self.default.as_ref() + } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index ed034a5723d..940dd8a3d0c 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -73,24 +73,8 @@ pub(super) fn runtime_cast_target_expr( two_state, } => (target, numeric_size, two_state), }; - let operand_signed = expr_signedness_with_return_types( - &expr, - &packed_dimensions.expression_signedness, - &packed_dimensions.functions, - &packed_dimensions.function_return_types, - ) - .or_else(|| { - // A genvar or an untyped constant is an `int`. - let Expr::Ident(name) = &expr else { - return None; - }; - const_env.contains_key(name).then(|| { - parameter_types_from_const_env(const_env) - .get(name) - .is_none_or(|r#type| r#type.signed) - }) - }) - .ok_or_else(|| unsupported("cast of an operand whose signedness is unknown"))?; + let operand_signed = dimensions::expression_signedness(&expr, packed_dimensions, const_env) + .ok_or_else(|| unsupported("cast of an operand whose signedness is unknown"))?; let expr = if two_state { Expr::Unary { op: UnaryOp::ToTwoState, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 51f69c82a0a..9216fbbc5d2 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -7,6 +7,7 @@ //! calls that are not system functions. Bodies are interpreted from their //! procedural statements. +use num_bigint::BigUint; use std::cell::{Cell, RefCell}; use super::*; @@ -1101,7 +1102,64 @@ impl Frame<'_> { } ConstExpr::Literal(format!("1'b{}", u8::from(found))) } - Expr::Concat(_) | Expr::RepeatConcat { .. } => return None, + Expr::Concat(_) | Expr::RepeatConcat { .. } => { + let literal = self.concat_literal(expr)?; + if literal.width == 0 { + return None; + } + let value = crate::typecheck::integral_literal_as_i128(&literal, false)?; + self.temporary(value, literal.width, false) + } + }) + } + + /// Fold concatenations with each operand's own width before the surrounding + /// assignment can resize the value. This interpreter stores at most 128 bits. + fn concat_literal(&mut self, expr: &Expr) -> Option { + self.tick()?; + let (parts, count) = match expr { + Expr::Concat(parts) => (parts, 1), + Expr::RepeatConcat { count, parts } => { + let count = usize::try_from(self.eval_lowered(&count.clone().into())?).ok()?; + (parts, count) + } + _ => { + let lowered: crate::ir::ConstExpr = self.lower(expr)?.into(); + return crate::typecheck::eval_const_integral_literal_in_env( + &lowered, + self, + &|name| self.type_of(name), + ); + } + }; + let mut width = 0usize; + let mut value = BigUint::default(); + let mut mask = BigUint::default(); + for part in parts { + let literal = self.concat_literal(part)?; + width = width.checked_add(literal.width)?; + if width > 128 { + return None; + } + value = (value << literal.width) | literal.value; + mask = (mask << literal.width) | literal.mask; + } + let total = width.checked_mul(count)?; + if total > 128 { + return None; + } + let mut result_value = BigUint::default(); + let mut result_mask = BigUint::default(); + // A zero-width group remains empty for any count, without iterating. + for _ in 0..if width == 0 { 0 } else { count } { + result_value = (result_value << width) | &value; + result_mask = (result_mask << width) | &mask; + } + Some(crate::typecheck::IntegralLiteral { + width: total, + signed: false, + value: result_value, + mask: result_mask, }) } diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 79213285077..74a629b0e14 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -28,7 +28,7 @@ pub(super) fn value_expression( let mut context = dimensions.clone(); context.const_env = HashMap::default().into(); context.type_aliases = HashMap::default(); - bind_in_context(root, native, tree, &context, dimensions, true) + bind_in_context(root, native, tree, &context, dimensions) } pub(super) fn bind( root: ExprId, @@ -55,7 +55,7 @@ fn bind_in( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, ) -> Converted> { - bind_in_context(root, native, tree, dimensions, dimensions, false) + bind_in_context(root, native, tree, dimensions, dimensions) } fn bind_in_context( root: ExprId, @@ -63,7 +63,6 @@ fn bind_in_context( tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, query_dimensions: &PackedDimensions, - value_actual: bool, ) -> Converted> { enum Job { Enter(ExprId), @@ -123,7 +122,6 @@ fn bind_in_context( jobs.push(Job::Enter(*right)); jobs.push(Job::Enter(*left)); } - ExprKind::Conditional { .. } if value_actual => return Ok(None), ExprKind::Conditional { condition, then_expression, @@ -140,7 +138,7 @@ fn bind_in_context( *expression, native, tree, - dimensions, + query_dimensions, ) { Ok(target) => target, Err(AnalyzerError::Unsupported(_)) => return Ok(None), @@ -149,6 +147,20 @@ fn bind_in_context( jobs.push(Job::Cast(target)); jobs.push(Job::Enter(*expression)); } + ExprKind::Concatenation(_) | ExprKind::Replication { .. } => { + // Actual values retain the parent's specialization context. + // The symbolic context deliberately omits its numeric env, + // but a concat must be folded to a typed literal here. + let expr = + expression_binding::bind_value(id, native, tree, query_dimensions, None)?; + let Some(value) = + selects::indexed_expression_value(&tree.state, expr, query_dimensions) + else { + return Ok(None); + }; + values.push(value); + } + ExprKind::Call { expression, arguments, @@ -242,14 +254,14 @@ fn bind_in_context( )); jobs.extend(indices.into_iter().rev().map(Job::Enter)); } else { - let value = match expression_binding::bind_value( - id, native, tree, dimensions, None, - ) { + let value = match indexed_expression(id, native, tree, query_dimensions) { Ok(value) => value, Err(AnalyzerError::Unsupported(_)) => return Ok(None), Err(error) => return Err(error), }; - let Some(value) = expr_to_const(&tree.state, value) else { + let Some(value) = + selects::indexed_expression_value(&tree.state, value, query_dimensions) + else { return Ok(None); }; values.push(value); @@ -294,9 +306,12 @@ fn bind_in_context( }, Job::Cast(target) => { let value = values.pop().ok_or_else(disagreement)?; - let Some(value) = - casts::cast_constant_target(&tree.state, value, target, &dimensions.const_env) - else { + let Some(value) = casts::cast_constant_target( + &tree.state, + value, + target, + &query_dimensions.const_env, + ) else { return Ok(None); }; values.push(value); diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding.rs b/crates/celox-sv-analyzer/src/ast/constant_folding.rs index aaf8f2d27e8..7246b76e780 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding.rs @@ -407,13 +407,24 @@ fn constant_with_folded_selections_with_lookup( then_expr: Box::new(convert(then_expr)?), else_expr: Box::new(convert(else_expr)?), }), - Expr::Call { callee, args, .. } => Some(ConstExpr::call( - state, - callee.clone(), - args.iter() - .map(|arg| convert(arg.as_ref()?)) - .collect::>>()?, - )), + Expr::Call { callee, args, .. } => { + // Materialize a constant function's self-determined return type + // before the enclosing selection/arithmetic receives its context. + if let Some(literal) = + const_functions::eval_expression_literal(&state.const_functions, expr, const_env) + { + return Some(ConstExpr::Literal( + typecheck::format_integral_literal_binary(&literal), + )); + } + Some(ConstExpr::call( + state, + callee.clone(), + args.iter() + .map(|arg| convert(arg.as_ref()?)) + .collect::>>()?, + )) + } _ => expr_to_const(state, expr.clone()), } } diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index bba54816cd4..b6d9aebd366 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -33,12 +33,51 @@ pub(super) fn ports_from_scope( type_aliases, )?, ); - ports.push(Port::new( - native_port_name(native)?, - direction, - ty, - !explicit && !native.variable, - )); + let default = native + .default + .map(|value| { + if direction != PortDirection::Input { + return Err(unsupported("default value on a non-input port")); + } + if !ty.unpacked_ranges().is_empty() { + let name = native_port_name(native)?; + let mut dimensions = + PackedDimensions::new(HashMap::default(), const_env, type_aliases); + dimensions.insert(name.clone(), procedural::dimensions_from_type(&ty)); + let expression = expression_binding::expression( + value, + syntax_tree.declarations(), + &LValue::Ident(name), + syntax_tree, + &dimensions, + )?; + let value = fold_const_integral_expr_preserving_mask( + &syntax_tree.state, + expression, + const_env, + ); + return expr_to_const(&syntax_tree.state, value) + .ok_or_else(|| unsupported("nonconstant unpacked input port default")); + } + constant_binding::expression( + value, + syntax_tree.declarations(), + syntax_tree, + const_env, + type_aliases, + )? + .ok_or_else(|| unsupported("nonconstant input port default")) + }) + .transpose()?; + ports.push( + Port::new( + native_port_name(native)?, + direction, + ty, + !explicit && !native.variable, + ) + .with_default(default), + ); } Ok(ports) } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 0c04886874a..f62510932aa 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -52,21 +52,30 @@ fn bound_query_type( packed_dimensions: &PackedDimensions, const_env: &HashMap, ) -> Option { - let signed = expr_signedness_with_return_types( - expression, - &SizeQuerySignedness { - dimensions: packed_dimensions, - const_env, - }, - &HashMap::default(), - &packed_dimensions.function_return_types, - )?; + let signed = expression_signedness(expression, packed_dimensions, const_env)?; Some(ExprType { width: width.max(1), signed, }) } +/// Resolve signedness recursively from lexical declarations and parameter types. +pub(super) fn expression_signedness( + expression: &Expr, + dimensions: &PackedDimensions, + const_env: &HashMap, +) -> Option { + expr_signedness_with_return_types( + expression, + &SizeQuerySignedness { + dimensions, + const_env, + }, + &dimensions.functions, + &dimensions.function_return_types, + ) +} + /// The same precedence as the former eagerly collected signedness table, /// looking up only the identifiers used by the query operand. struct SizeQuerySignedness<'a> { @@ -82,7 +91,9 @@ impl Signedness for SizeQuerySignedness<'_> { if let Some(signed) = self.const_env.get(&variable_signed_marker(name)) { return Some(*signed != 0); } - parameter_type_from_const_env(self.const_env, name).map(|ty| ty.signed) + parameter_type_from_const_env(self.const_env, name) + .map(|ty| ty.signed) + .or_else(|| self.const_env.contains_key(name).then_some(true)) } } diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 0020b69d294..d2ebefd8a09 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -60,6 +60,7 @@ pub(super) struct Item { pub env: SharedMap, pub literals: SharedMap, parameter_dimensions: Arc, + qualified_types: SharedMap, names: SharedMap, imports: SharedMap, shadowed: Arc>, @@ -189,7 +190,16 @@ impl Item { &self, aliases: &'m HashMap, ) -> Cow<'m, HashMap> { - self.block_imports().type_aliases(aliases) + if self.qualified_types.is_empty() { + return self.block_imports().type_aliases(aliases); + } + let mut all = aliases.clone(); + all.extend( + self.qualified_types + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())), + ); + Cow::Owned(self.block_imports().type_aliases(&all).into_owned()) } /// Make the constant functions this item sees the installed ones, until @@ -503,12 +513,29 @@ struct Scope { literals: SharedMap, parameters: Vec, parameter_dimensions: Arc, + qualified_types: SharedMap, names: SharedMap, imports: SharedMap, shadowed: Arc>, } impl Scope { + fn type_aliases<'m>( + &self, + aliases: &'m HashMap, + ) -> Cow<'m, HashMap> { + if self.qualified_types.is_empty() { + return self.block_imports().type_aliases(aliases); + } + let mut all = aliases.clone(); + all.extend( + self.qualified_types + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())), + ); + Cow::Owned(self.block_imports().type_aliases(&all).into_owned()) + } + fn block_imports(&self) -> BlockImports<'_> { BlockImports { state: &self.state, @@ -817,6 +844,7 @@ impl<'a> Elaborator<'a, '_> { env: scope.env.clone(), literals: scope.literals.clone(), parameter_dimensions: scope.parameter_dimensions.clone(), + qualified_types: scope.qualified_types.clone(), names: scope.names.clone(), imports: scope.imports.clone(), shadowed: scope.shadowed.clone(), @@ -1147,15 +1175,106 @@ impl<'a> Elaborator<'a, '_> { Expr::Literal(format_typed_parameter_literal(value, 32, true)), ); } - // Reject unsupported local types before signal precollection tries to - // resolve their uses. Native membership owns the declaration class. - if children.iter().any(|id| { - matches!( - self.tree.declarations().body_item(*id).kind, - celox_sv_syntax::BodyItemKind::TypeAlias(_) - ) - }) { - return Err(unsupported("type declaration inside generate scope")); + // Native declarations remain in their owning scope. Carry qualified + // bindings with every item rather than leaking a sibling's typedefs. + let type_names = children + .iter() + .filter_map(|id| { + if let celox_sv_syntax::BodyItemKind::TypeAlias(alias) = + self.tree.declarations().body_item(*id).kind + { + Some(instances::normalize_identifier( + &self.tree.declarations().type_alias(alias).name.spelling, + )) + } else { + None + } + }) + .collect::>(); + if !type_names.is_empty() { + let mut enum_names = HashSet::default(); + for id in children { + if let celox_sv_syntax::BodyItemKind::TypeAlias(alias) = + self.tree.declarations().body_item(*id).kind + && let celox_sv_syntax::TypeAliasTarget::DataType(ty) = + self.tree.declarations().type_alias(alias).target + && let celox_sv_syntax::DataTypeKind::Enum { items, .. } = + &self.tree.declarations().data_type(ty).kind + { + for item in items { + let name = instances::normalize_identifier(&item.name.spelling); + if !enum_names.insert(name.clone()) { + return Err(unsupported(format!( + "duplicate generate-local declaration `{name}`" + ))); + } + } + } + } + let mut aliases = types::type_aliases_from_body_with_env( + self.tree, + children, + &scope.env, + &self.aliases, + )?; + let enums = parameters::enum_member_constants_from_items( + self.tree, + children, + &scope.env, + &aliases, + &HashMap::default(), + )?; + for name in type_names { + if !declared.insert(name.clone()) { + return Err(unsupported(format!( + "duplicate generate-local declaration `{name}`" + ))); + } + let ty = aliases + .get(&name) + .ok_or_else(|| { + unsupported(format!("unresolved generate-local typedef `{name}`")) + })? + .clone(); + // Freeze definition-site dimensions before a nested block or + // another loop iteration shadows the names in their bounds. + let ty = procedural::scoped_type(ty, &scope.env); + if ty.packed_ranges().iter().any(|range| { + eval_ast_const_expr(&self.tree.state, range.left(), &scope.env).is_none() + || eval_ast_const_expr(&self.tree.state, range.right(), &scope.env) + .is_none() + }) { + return Err(unsupported(format!( + "unresolved generate-local typedef bounds `{name}`" + ))); + } + let qualified = format!("{}.{}", scope.path, scope_component(&name)); + scope.qualified_types.insert(qualified.clone(), ty.clone()); + scope.names.insert(name.clone(), qualified.clone()); + scope.imports.insert(name.clone(), qualified.clone()); + Arc::make_mut(&mut scope.shadowed).insert(name.clone()); + aliases.insert(qualified, ty.clone()); + aliases.insert(name, ty); + } + for (name, number) in enums.numbers { + if !declared.insert(name.clone()) { + return Err(unsupported(format!( + "duplicate generate-local declaration `{name}`" + ))); + } + scope.env.insert(name.clone(), number); + insert_parameter_type_markers(&mut scope.env, &name, enums.types[&name]); + scope.env.insert(enum_marker(&name), 1); + scope + .literals + .insert(name.clone(), enums.exprs[&name].clone()); + scope.names.insert( + name.clone(), + format!("{}.{}", scope.path, scope_component(&name)), + ); + Arc::make_mut(&mut scope.shadowed).insert(name); + } + self.aliases = Cow::Owned(aliases); } self.constants_and_signal_types(children, &mut scope, &mut declared)?; for id in children { @@ -1309,6 +1428,7 @@ fn module_constant_functions( env: env.clone().into(), literals: literals.clone().into(), parameter_dimensions: Arc::default(), + qualified_types: SharedMap::default(), names: SharedMap::default(), imports: SharedMap::default(), shadowed: Arc::default(), @@ -2217,8 +2337,24 @@ mod tests { "duplicate case-generate default", ), ( - "if (1) begin typedef logic T; T tmp; end", - "type declaration inside generate scope", + "if (1) begin typedef logic T; typedef bit T; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin typedef enum logic { A,B } T; typedef enum logic { A,C } U; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin typedef logic T; logic T; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin typedef enum logic { A,B } T; localparam A=1; end", + "duplicate generate-local declaration", + ), + ( + "if (1) begin parameter type T=logic; end", + "generate-local type parameter", ), ( "for (genvar i=0; i<1; i++) begin function automatic logic f(); return 0; endfunction end", @@ -2543,7 +2679,7 @@ mod tests { fn subroutine_projection_preserves_generate_diagnostics() { for body in [ "if (UNKNOWN) begin : g logic x; end", - "if (1) begin : g typedef logic T; T x; end", + "if (1) begin : g parameter type T=logic; end", "for (genvar i=0; i<1; i++) begin : g function logic f(); return 0; endfunction end", "if (1) begin : g localparam P=Q; localparam Q=P; end", ] { diff --git a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs index 879408cbefe..70a2e2f20e9 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs @@ -393,7 +393,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { } let index_ref = index.as_ref().map(|(name, value)| (name.as_str(), *value)); let functions = scope.block_imports().install_constant_functions(); - let aliases = scope.block_imports().type_aliases(self.module_aliases); + let aliases = scope.type_aliases(self.module_aliases); let outer = std::mem::replace(&mut self.aliases, aliases); contexts.0.push(Context { outer, diff --git a/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs b/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs index 83b64247e90..bbe7e925066 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs @@ -2,7 +2,7 @@ use super::*; -type Key = [usize; 5]; +type Key = [usize; 6]; pub(in crate::ast) struct ScopeViews<'a> { dimensions: &'a PackedDimensions, @@ -60,6 +60,7 @@ fn key(item: &Item) -> Key { item.names.identity(), Arc::as_ptr(&item.shadowed) as usize, Arc::as_ptr(&item.parameter_dimensions) as usize, + item.qualified_types.identity(), ] } @@ -109,7 +110,7 @@ mod tests { ); let inherited = HashMap::from_iter([("P".into(), Expr::Literal("99".into()))]); let original = &active[0]; - let mut changed: Vec<_> = (0..5).map(|_| original.clone()).collect(); + let mut changed: Vec<_> = (0..6).map(|_| original.clone()).collect(); changed[0].env.insert("P".into(), 8); changed[1] .literals @@ -117,14 +118,24 @@ mod tests { changed[2].names.insert("alias".into(), "g.x".into()); Arc::make_mut(&mut changed[3].shadowed).insert("extra".into()); Arc::make_mut(&mut changed[4].parameter_dimensions).clear(); + changed[5] + .qualified_types + .insert("g.T".into(), Type::implicit()); let mut views = ScopeViews::with_literals(&dimensions, &inherited); for item in active.iter().chain(&changed) { let (cached_dimensions, cached_literals) = views.get(item); assert_eq!(cached_dimensions, &item.dimensions(&dimensions)); assert_eq!(&**cached_literals, &item.parameter_literals(&inherited)); } - assert_eq!(views.views.len(), 8); - assert_eq!(views.literal_views.len(), 8); + assert!(!views.dimensions(original).type_aliases.contains_key("g.T")); + assert!( + views + .dimensions(&changed[5]) + .type_aliases + .contains_key("g.T") + ); + assert_eq!(views.views.len(), 9); + assert_eq!(views.literal_views.len(), 9); // Collector inputs also bound the cache: a different inherited context // must never see the materialization from the preceding collector. let other = HashMap::from_iter([("P".into(), Expr::Literal("7".into()))]); diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 945f9e1528d..a57b12356e5 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -3073,7 +3073,41 @@ pub fn plan_interfaces( } /// Original paths of flattened interface fields, indexed by bound module name. -pub type InterfaceMemberPaths = HashMap>>; +pub type InterfaceMemberPaths = HashMap>; + +/// Provenance for a field flattened from an interface instance or instance array. +#[derive(Clone, Debug)] +pub struct InterfaceMemberPath { + pub segments: Vec, + pub arrayed: bool, +} + +impl InterfaceMemberPath { + /// Recover element indices only for a source-declared interface array. + pub fn restore(&self, flattened: &str) -> Option> { + let [handle, member] = self.segments.as_slice() else { + return None; + }; + if flattened == format!("{handle}{SEPARATOR}{member}") { + return Some(self.segments.clone()); + } + if !self.arrayed { + return None; + } + let indexed = flattened.strip_suffix(&format!("{SEPARATOR}{member}"))?; + let mut indices = indexed.strip_prefix(handle)?; + if indices.is_empty() { + return None; + } + while !indices.is_empty() { + let rest = indices.strip_prefix('[')?; + let (index, tail) = rest.split_once(']')?; + index.parse::().ok()?; + indices = tail; + } + Some(vec![indexed.to_string(), member.clone()]) + } +} /// Build the interface plan and retain source member paths for reflection. pub fn plan_interfaces_with_member_paths( @@ -3420,7 +3454,10 @@ pub fn plan_interfaces_with_member_paths( for member in &design.interfaces[&handle.interface].members { member_paths.insert( format!("{handle_name}{SEPARATOR}{}", member.name), - vec![handle_name.clone(), member.name.clone()], + InterfaceMemberPath { + segments: vec![handle_name.clone(), member.name.clone()], + arrayed: handle.arrayed, + }, ); } } diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index a1fc0113ff7..1ed46598ace 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -11,6 +11,7 @@ //! locals of subroutines that keep their value are not supported. use super::*; +mod bit_result; /// The argument directions of each subroutine, by the names calls use. pub(super) type Directions = HashMap>; @@ -129,6 +130,8 @@ fn keep_in( pub(super) fn check_subroutine_statics( state: &AnalysisState, subroutine: &Subroutine, + constants: &HashMap, + locals: &[LocalVariable], statics: &HashSet, directions: &Directions, ) -> Result<(), AnalyzerError> { @@ -153,6 +156,18 @@ pub(super) fn check_subroutine_statics( ) .and_then(|entry| match entry { Entry::Unobserved => Ok(()), + Entry::Observed + if init.is_none() + && bit_result::proves_local( + state, + name, + &stmts[index + 1..], + constants, + locals, + ) => + { + Ok(()) + } Entry::Observed => Err(AnalyzerError::Unsupported(format!( "static variable `{}` of subroutine `{}` that keeps its value \ between calls (declare it `automatic`)", @@ -199,6 +214,9 @@ pub(super) fn check_subroutine_statics( /// a static function the variable named after it is static too, so a call /// that does not assign it returns the result of an earlier call. pub(super) fn check_static_result( + state: &AnalysisState, + constants: &HashMap, + locals: &[LocalVariable], subroutine: &Subroutine, directions: &Directions, ) -> Result<(), AnalyzerError> { @@ -214,6 +232,7 @@ pub(super) fn check_static_result( // `return value;` assigns the result as it leaves. match flow.block(&subroutine.body, false) { Ok(exits) if exits.next != Some(false) => Ok(()), + _ if bit_result::proves(state, subroutine, constants, locals) => Ok(()), _ => Err(AnalyzerError::Unsupported(format!( "static function `{}` whose result keeps its value between calls (assign it on \ every path, or declare the function `automatic`)", diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs new file mode 100644 index 00000000000..b0458e14acd --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs @@ -0,0 +1,344 @@ +//! Bounded bit coverage for static results and scratch locals filled by constant loops. +use super::*; +use num_bigint::BigUint; + +const MAX_BITS: usize = 65536; +const MAX_STEPS: usize = 65536; + +pub(super) fn proves( + state: &AnalysisState, + subroutine: &Subroutine, + constants: &HashMap, + locals: &[LocalVariable], +) -> bool { + let Some(name) = subroutine.return_var.as_deref() else { + return false; + }; + let Some(width) = subroutine + .return_type + .as_ref() + .and_then(|ty| ty.resolved_width()) + .filter(|width| (1..=MAX_BITS).contains(width)) + else { + return false; + }; + proves_variable(state, name, width, &subroutine.body, constants, locals) +} + +pub(super) fn proves_local( + state: &AnalysisState, + name: &str, + body: &[Stmt], + constants: &HashMap, + locals: &[LocalVariable], +) -> bool { + let Some(local) = locals.iter().find(|local| local.name == name) else { + return false; + }; + // The lowered local type's width already includes unpacked dimensions. + let Some(width) = local.r#type.resolved_width() else { + return false; + }; + proves_variable(state, name, width, body, constants, locals) +} + +pub(super) fn proves_variable( + state: &AnalysisState, + name: &str, + width: usize, + body: &[Stmt], + constants: &HashMap, + locals: &[LocalVariable], +) -> bool { + if !(1..=MAX_BITS).contains(&width) { + return false; + } + let mut env = constants.clone(); + let mut types = HashMap::default(); + for local in locals { + env.remove(&local.name); + if local.r#type.unpacked_ranges().is_empty() + && let Some(width) = local + .r#type + .resolved_width() + .filter(|width| (1..=64).contains(width)) + { + let signed = local.r#type.is_signed(); + types.insert(local.name.clone(), (width, signed)); + env.insert( + dimensions::parameter_width_marker(&local.name), + width as i128, + ); + env.insert( + dimensions::parameter_signed_marker(&local.name), + i128::from(signed), + ); + } + } + let mut proof = Proof { + state, + name, + width, + written: BigUint::default(), + full: (BigUint::from(1u8) << width) - BigUint::from(1u8), + env, + types, + remaining: MAX_STEPS, + }; + proof.block(body) == Some(true) +} + +struct Proof<'a> { + state: &'a AnalysisState, + name: &'a str, + width: usize, + written: BigUint, + full: BigUint, + env: HashMap, + types: HashMap, + remaining: usize, +} + +impl Proof<'_> { + fn readable(&self, expression: &Expr) -> bool { + pure(expression) && (self.written == self.full || !expr_reads(expression, self.name)) + } + + fn value(&self, expression: &Expr) -> Option { + if !self.readable(expression) { + return None; + } + let dims = PackedDimensions::new(HashMap::default(), &self.env, &HashMap::default()); + let value = expr_to_index_const(self.state, expression.clone(), &dims)?; + eval_ast_const_expr(self.state, &value, &self.env) + } + + fn store(&mut self, name: &str, value: Option) -> Option<()> { + self.env.remove(name); + if let Some(value) = value { + let (width, signed) = *self.types.get(name)?; + let low = if signed { -(1i128 << (width - 1)) } else { 0 }; + let high = if signed { + (1i128 << (width - 1)) - 1 + } else { + (1i128 << width) - 1 + }; + // Refuse to prove through assignment truncation. This keeps the + // abstract loop's iteration sequence equal to the declared type's. + if !(low..=high).contains(&value) { + return None; + } + self.env.insert(name.to_string(), value); + } + Some(()) + } + + /// `true` means no entry bit can subsequently be observed. Unknown control + /// flow or calls give no proof; the ordinary lifetime check still rejects. + fn block(&mut self, statements: &[Stmt]) -> Option { + for statement in statements { + self.remaining = self.remaining.checked_sub(1)?; + match statement { + Stmt::Local { name, init } if name != self.name => { + let value = init.as_ref().and_then(|value| self.value(value)); + if let Some(init) = init { + if !self.readable(init) { + return None; + } + } + self.store(name, value)?; + } + Stmt::Assign { + lhs, + rhs, + nonblocking: false, + } => { + if !self.readable(rhs) { + return None; + } + if lhs.name() == self.name { + match lhs { + LValue::Ident(_) => self.written = self.full.clone(), + LValue::Select { msb, lsb, .. } => { + if !pure_constant(msb) || !pure_constant(lsb) { + return None; + } + let left = eval_ast_const_expr(self.state, msb, &self.env)?; + let right = eval_ast_const_expr(self.state, lsb, &self.env)?; + let low = usize::try_from(left.min(right)).ok()?; + let high = usize::try_from(left.max(right)).ok()?; + if high >= self.width { + return None; + } + for bit in low..=high { + self.written.set_bit(bit as u64, true); + } + } + } + } else if let LValue::Ident(name) = lhs { + let value = self.value(rhs); + self.store(name, value)?; + } else if let LValue::Select { name, msb, lsb, .. } = lhs { + // A partial store loses our numeric value for this + // other local, but does not read its previous bits. + if !pure_constant(msb) + || !pure_constant(lsb) + || const_expr_reads(msb, self.name) + || const_expr_reads(lsb, self.name) + { + return None; + } + self.env.remove(name); + } + } + Stmt::Loop { + kind: crate::procedural::LoopKind::For, + init, + condition: Some(condition), + step, + body, + } => { + if self.block(init)? { + return Some(true); + } + while self.value(condition)? != 0 { + self.remaining = self.remaining.checked_sub(1)?; + if self.block(body)? || self.block(step)? { + return Some(true); + } + } + } + Stmt::If { + condition, + then_body, + else_body, + } => { + let branch = if self.value(condition)? != 0 { + then_body + } else { + else_body + }; + if self.block(branch)? { + return Some(true); + } + } + Stmt::Return(Some(value)) if self.readable(value) => return Some(true), + _ => return None, + } + if self.written == self.full { + return Some(true); + } + } + Some(self.written == self.full) + } +} + +fn pure_constant(expression: &ConstExpr) -> bool { + match expression { + ConstExpr::Ident(_) | ConstExpr::Literal(_) => true, + ConstExpr::Function { .. } => false, + ConstExpr::Select { expr, bit } => pure_constant(expr) && pure_constant(bit), + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + pure_constant(expr) && pure_constant(msb) && pure_constant(lsb) + } + ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => pure_constant(expr), + ConstExpr::Binary { left, right, .. } => pure_constant(left) && pure_constant(right), + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => pure_constant(condition) && pure_constant(then_expr) && pure_constant(else_expr), + } +} + +fn pure(expression: &Expr) -> bool { + match expression { + Expr::Ident(_) | Expr::Literal(_) => true, + Expr::Call { .. } => false, + Expr::Select { expr, msb, lsb, .. } => { + pure(expr) && pure_constant(msb) && pure_constant(lsb) + } + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => pure(expr), + Expr::Binary { left, right, .. } => pure(left) && pure(right), + Expr::Mux { + condition, + then_expr, + else_expr, + } => pure(condition) && pure(then_expr) && pure(else_expr), + Expr::Concat(parts) => parts.iter().all(pure), + Expr::RepeatConcat { count, parts } => pure_constant(count) && parts.iter().all(pure), + Expr::Inside { expr, items } => { + pure(expr) && items.iter().all(|item| item.exprs().into_iter().all(pure)) + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn incomplete_or_entry_dependent_scratch_arrays_stay_rejected() { + for body in [ + "for(integer i=0;i<1;i=i+1) words[i]=a;", + "for(integer i=0;i<2;i=i+1) words[0]=a;", + "for(integer i=0;i<2;i=i+1) words[i]=words[i]^a;", + "if(a[0]) for(integer i=0;i<2;i=i+1) words[i]=a;", + "other[words[0]]=0; for(integer i=0;i<2;i=i+1) words[i]=a;", + ] { + let source = format!( + "module Top(input logic[7:0] a, output logic[7:0] y); \ + function [7:0] f(input logic[7:0] a); \ + logic[7:0] words[1:0]; logic[7:0] other; {body} \ + f=words[0]+words[1]; endfunction assign y=f(a); endmodule" + ); + let error = crate::analyze_source(&source, std::path::Path::new("partial-scratch.sv")) + .unwrap_err() + .to_string(); + assert!(error.contains("static variable `words`"), "{body}: {error}"); + } + } + + #[test] + fn incomplete_or_entry_dependent_results_stay_rejected() { + for body in [ + "for(integer i=0;i<3;i=i+1) f[i]=a[i];", + "for(integer i=0;i<4;i=i+1) f[0]=a[i];", + "for(integer i=0;i<0;i=i+1) f[i]=a[i];", + "if(a[0]) for(integer i=0;i<4;i=i+1) f[i]=a[i];", + "for(integer i=0;i<4;i=i+1) begin if(i==2) break; f[i]=a[i]; end", + "for(integer i=0;i<4;i=i+1) f[i]=f[i]^a[i];", + "for(byte i=127;i<129;i=i+1) f[i%4]=a[i%4];", + ] { + let source = format!( + "module Top(input logic[3:0] a, output logic[3:0] y); \ + function [3:0] f(input logic[3:0] a); {body} endfunction \ + assign y=f(a); endmodule" + ); + let error = crate::analyze_source(&source, std::path::Path::new("partial-result.sv")) + .unwrap_err() + .to_string(); + assert!( + error.contains("whose result keeps its value"), + "{body}: {error}" + ); + } + } + + #[test] + fn index_calls_do_not_prove_bit_coverage() { + let source = r#" + module Top(input logic[3:0] a, output logic[3:0] y); + function automatic integer mutate(inout integer index); + index=3; return 0; + endfunction + function [3:0] f(input logic[3:0] a); + for(integer i=0;i<4;i=i+1) f[mutate(i)]=a[i]; + endfunction + assign y=f(a); + endmodule + "#; + let error = crate::analyze_source(source, std::path::Path::new("index-call.sv")) + .unwrap_err() + .to_string(); + assert!(error.contains("whose result keeps its value"), "{error}"); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 4445dcde46d..8bd0afb46cf 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -806,7 +806,7 @@ pub(super) fn parameter_element_literal( }; let element_width = width_from(indices.len())?; let total_width = width_from(0)?; - if total_width > 127 { + if total_width > 128 { return None; } let signed = env @@ -826,8 +826,15 @@ pub(super) fn parameter_element_literal( let from_right = usize::try_from(index.abs_diff(right)).ok()?; offset = offset.checked_add(from_right.checked_mul(width_from(position + 1)?)?)?; } - let value = *env.get(name)? as u128 & ((1u128 << total_width) - 1); - let element = (value >> offset) & ((1u128 << element_width) - 1); + let mask = |width| { + if width == 128 { + u128::MAX + } else { + (1u128 << width) - 1 + } + }; + let value = *env.get(name)? as u128 & mask(total_width); + let element = (value >> offset) & mask(element_width); Some(format!( "{element_width}'{signing}b{element:0element_width$b}" )) @@ -878,10 +885,26 @@ pub(super) fn enum_member_constants_from_scope( base_const_env: &HashMap, type_aliases: &HashMap, parameter_overrides: &HashMap, +) -> Result { + let items = syntax_tree.body_membership()?; + enum_member_constants_from_items( + syntax_tree, + &items, + base_const_env, + type_aliases, + parameter_overrides, + ) +} + +pub(super) fn enum_member_constants_from_items( + syntax_tree: &AnalysisContext<'_>, + declarations: &[celox_sv_syntax::BodyItemId], + base_const_env: &HashMap, + type_aliases: &HashMap, + parameter_overrides: &HashMap, ) -> Result { use celox_sv_syntax::{BodyItemKind, DataTypeKind, TypeAliasTarget}; let native = syntax_tree.declarations(); - let declarations = syntax_tree.body_membership()?; let enum_type = |id| { let BodyItemKind::TypeAlias(alias) = native.body_item(id).kind else { return None; @@ -899,7 +922,7 @@ pub(super) fn enum_member_constants_from_scope( let mut resolved_type_aliases = type_aliases.clone(); let mut parameters = Vec::new(); let no_overrides = HashMap::default(); - for id in declarations { + for &id in declarations { if let BodyItemKind::Parameter(_) = native.body_item(id).kind { let authored = ownership::body(id, syntax_tree)?; let local = authored.first().is_some_and(|parameter| parameter.local); @@ -917,7 +940,12 @@ pub(super) fn enum_member_constants_from_scope( }, )?; extend_const_env_with_parameters(&syntax_tree.state, &mut eval_env, ¶meters); - resolved_type_aliases = type_aliases_from_scope_with_env(syntax_tree, &eval_env)?; + resolved_type_aliases = types::type_aliases_from_body_with_env( + syntax_tree, + declarations, + &eval_env, + &resolved_type_aliases, + )?; continue; } let Some(id) = enum_type(id) else { @@ -1006,7 +1034,12 @@ pub(super) fn enum_member_constants_from_scope( // A later typedef may use a cast or range that depends on this // enum's members. Rebuild aliases from the enriched environment // before resolving a subsequent enum base through that typedef. - resolved_type_aliases = type_aliases_from_scope_with_env(syntax_tree, &eval_env)?; + resolved_type_aliases = types::type_aliases_from_body_with_env( + syntax_tree, + declarations, + &eval_env, + &resolved_type_aliases, + )?; } Ok(constants) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 1ce0ac90e77..3d5af5962cc 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1458,11 +1458,19 @@ pub(super) fn lower_subroutine( lifetimes::check_subroutine_statics( &tree.state, &subroutine, + &builder.dims.const_env, + builder.state.locals, &statics, builder.state.subroutine_directions, )?; if !builder.automatic { - lifetimes::check_static_result(&subroutine, builder.state.subroutine_directions)?; + lifetimes::check_static_result( + &tree.state, + &builder.dims.const_env, + builder.state.locals, + &subroutine, + builder.state.subroutine_directions, + )?; } Ok(subroutine) } diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 30dea33af77..7bce362fd3d 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -524,6 +524,7 @@ impl ScopeSymbols { rename.r#type(port.r#type.clone()), port.is_net, ) + .with_default(port.default.clone().map(|value| rename.const_expr(value))) }) .collect(), signals: self diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index 505cbca70f9..09b1184363f 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -979,8 +979,45 @@ pub(super) fn indexed_select_bounds_values( .unwrap_or(false); // The base is self-determined; endpoint arithmetic must not inherit its // unsigned type or truncate a carry across the base expression's width. - let base = eval_ast_const_expr(state, &base, &dimensions.const_env) - .ok_or_else(|| unsupported("indexed part-select start"))?; + let Some(base_value) = eval_ast_const_expr(state, &base, &dimensions.const_env) else { + // A procedural loop index is not constant while its body is bound. + // Keep the endpoints in declared coordinates so normal memory range + // flattening retains the element offset. Lowering can then unroll the + // loop before requiring a constant selection inside each memory word. + let memory_word = name + .and_then(|name| dimensions.get(name)) + .is_some_and(|shape| { + !shape.unpacked.is_empty() + && index_count == shape.unpacked.len() + && shape.packed.len() == 1 + }); + let ty = self_determined_type(state, &base, dimensions).filter(|ty| ty.0 <= 32); + let Some(ty) = ty.filter(|_| memory_word) else { + return Err(unsupported("indexed part-select start")); + }; + let base = ConstExpr::Resize { + expr: Box::new(self_determined_index(state, base, dimensions)), + width: 64, + signed: ty.1, + }; + // Zero-extend unsigned indices before using signed endpoint arithmetic. + let base = ConstExpr::Resize { + expr: Box::new(base), + width: 64, + signed: true, + }; + let other = ConstExpr::Binary { + left: Box::new(base.clone()), + op: if plus { BinaryOp::Add } else { BinaryOp::Sub }, + right: Box::new(ConstExpr::Literal(format!("64'sd{}", width - 1))), + }; + return Ok(if plus == ascending { + (base, other) + } else { + (other, base) + }); + }; + let base = base_value; let overflow = || unsupported("indexed part-select bounds"); let offset = width - 1; let other = if plus { @@ -1315,7 +1352,11 @@ fn self_determined_type( Some((literal.width, literal.signed)) } ConstExpr::Ident(name) => { - let variable = dimensions.get(name)?; + let Some(variable) = dimensions.get(name) else { + return dimensions::parameter_type_from_const_env(const_env, name) + .map(|ty| (ty.width, ty.signed)) + .or_else(|| const_env.contains_key(name).then_some((32, true))); + }; if !variable.unpacked.is_empty() { return None; } diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 48811337dad..fa20c7e6cb5 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -10,9 +10,35 @@ pub(super) fn type_aliases_from_scope( pub(super) fn type_aliases_from_scope_with_env( syntax_tree: &AnalysisContext<'_>, const_env: &HashMap, +) -> Converted> { + type_aliases_in_scope(syntax_tree, const_env, &HashMap::default(), true, None) +} + +/// Resolve a selected body while retaining its enclosing lexical type bindings. +pub(super) fn type_aliases_from_body_with_env( + syntax_tree: &AnalysisContext<'_>, + items: &[celox_sv_syntax::BodyItemId], + const_env: &HashMap, + inherited: &HashMap, +) -> Converted> { + type_aliases_in_scope(syntax_tree, const_env, inherited, false, Some(items)) +} + +fn type_aliases_in_scope( + syntax_tree: &AnalysisContext<'_>, + const_env: &HashMap, + inherited: &HashMap, + include_header: bool, + items: Option<&[celox_sv_syntax::BodyItemId]>, ) -> Converted> { let mut aliases = scope::imported(&syntax_tree.state).type_aliases.clone(); - if syntax_tree.scope_handle() != crate::source_tree::ScopeHandle::Compilation { + aliases.extend( + inherited + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())), + ); + if include_header && syntax_tree.scope_handle() != crate::source_tree::ScopeHandle::Compilation + { for parameter in syntax_tree.root_unit()?.parameters.iter().flatten() { add_type_parameter( parameter, @@ -23,11 +49,11 @@ pub(super) fn type_aliases_from_scope_with_env( )?; } } - let mut pending = syntax_tree - .body_membership()? - .into_iter() - .rev() - .collect::>(); + let members = match items { + Some(items) => items.to_vec(), + None => syntax_tree.body_membership()?, + }; + let mut pending = members.into_iter().rev().collect::>(); while let Some(id) = pending.pop() { match &syntax_tree.declarations().body_item(id).kind { BodyItemKind::Region(items) => pending.extend(items.iter().rev()), diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index ec2eab0ac6c..c68a5d34ca4 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -305,9 +305,6 @@ fn validate_scope( if !selected(port.tokens) { continue; } - if port.default.is_some() { - return Err(unsupported("ANSI port default value")); - } if port .data_type .is_some_and(|id| matches!(native.data_type(id).kind, DataTypeKind::Enum { .. })) diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 9f2f486daba..8043ee03782 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -328,6 +328,7 @@ pub struct Port { direction: PortDirection, r#type: Type, is_net: bool, + default: Option, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -384,6 +385,7 @@ impl Port { direction, r#type, is_net, + default: None, } } @@ -402,6 +404,15 @@ impl Port { pub fn is_net(&self) -> bool { self.is_net } + + pub(crate) fn with_default(mut self, default: Option) -> Self { + self.default = default; + self + } + + pub fn default(&self) -> Option<&ConstExpr> { + self.default.as_ref() + } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 4f8fa0b85bb..a9deafc2c07 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -28,7 +28,8 @@ pub mod system_functions; pub mod typecheck; pub use ast::interfaces::{ - InterfaceMemberPaths, NativeInterfacePlan, plan_interfaces, plan_interfaces_with_member_paths, + InterfaceMemberPath, InterfaceMemberPaths, NativeInterfacePlan, plan_interfaces, + plan_interfaces_with_member_paths, }; pub use ast::interfaces::{ InterfacePrototype, interface_prototypes, interface_prototypes_for, diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs b/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs index 3ac913da8ec..cb6fad3d153 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/instance_ownership.rs @@ -423,7 +423,6 @@ mod parameter_tests { #[test] fn native_override_special_forms_preserve_existing_diagnostics() { for (value, diagnostic) in [ - ("1?2:3", "parameter override expression"), ("1:2:3", "mintypmax expression"), ("1 inside {1,2}", "parameter override expression"), ] { diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 5c157f76050..5eb7cb7aa24 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -1481,6 +1481,9 @@ fn literal_as_i128(value: &str) -> Option { /// Static type of a syntax-validated literal, without expanding a sized value. /// Type queries need only the size/sign prefix, including for huge operands. pub(crate) fn integral_literal_type_metadata(value: &str) -> Option<(usize, bool)> { + if value.trim().starts_with('"') { + return parse_string_literal(value.trim()).map(|literal| (literal.width, false)); + } let normalized = value.trim().replace('_', ""); if let Some((size, based)) = normalized.split_once('\'') && !size.is_empty() @@ -1498,6 +1501,9 @@ pub(crate) fn integral_literal_type_metadata(value: &str) -> Option<(usize, bool } pub fn parse_integral_literal(value: &str) -> Option { + if value.trim().starts_with('"') { + return parse_string_literal(value.trim()); + } let normalized = value.trim().replace('_', ""); if let Some(literal) = parse_unbased_unsized_literal(&normalized) { return Some(literal); @@ -1509,6 +1515,107 @@ pub fn parse_integral_literal(value: &str) -> Option { } } +/// Parse a single SV literal, optionally preceded by a unary sign. +/// Parameter overrides use this instead of accepting arbitrary source text. +pub fn parse_parameter_literal(text: &str) -> Option { + let text = text.trim(); + let (op, literal) = if let Some(value) = text.strip_prefix('-') { + (Some(UnaryOp::Minus), value.trim()) + } else if let Some(value) = text.strip_prefix('+') { + (Some(UnaryOp::Plus), value.trim()) + } else { + (None, text) + }; + let mut sources = celox_sv_syntax::SourceMap::default(); + let file = sources.add("", literal); + let tokens = celox_sv_syntax::lex(&sources, file).ok()?; + let [token] = tokens.as_slice() else { + return None; + }; + if !matches!( + token.kind, + celox_sv_syntax::TokenKind::Number | celox_sv_syntax::TokenKind::String + ) { + return None; + } + parse_integral_literal(literal)?; + let value = ConstExpr::Literal(literal.to_string()); + Some(match op { + Some(op) => ConstExpr::Unary { + op, + expr: Box::new(value), + }, + None => value, + }) +} + +// IEEE 1800-2023 5.9 and 5.9.1: in integral expressions a string +// literal is an unsigned packed sequence of bytes, including decoded escapes. +fn parse_string_literal(text: &str) -> Option { + let body = text.strip_prefix('"')?.strip_suffix('"')?; + let mut input = body.bytes().peekable(); + let mut bytes = Vec::new(); + while let Some(byte) = input.next() { + let byte = match byte { + b'\\' => match input.next()? { + b'\n' => continue, + b'\r' if input.peek() == Some(&b'\n') => { + input.next(); + continue; + } + b'n' => b'\n', + b't' => b'\t', + b'v' => 11, + b'f' => 12, + b'a' => 7, + first @ b'0'..=b'7' => { + let mut value = u16::from(first - b'0'); + for _ in 0..2 { + let Some(next @ b'0'..=b'7') = input.peek().copied() else { + break; + }; + input.next(); + value = value * 8 + u16::from(next - b'0'); + } + value as u8 + } + b'x' => { + let mut value = 0; + let mut count = 0; + for _ in 0..2 { + let Some(next) = input + .peek() + .copied() + .and_then(|b| char::from(b).to_digit(16)) + else { + break; + }; + input.next(); + value = value * 16 + next as u8; + count += 1; + } + if count == 0 { + return None; + } + value + } + escaped if escaped.is_ascii() => escaped, + _ => return None, + }, + b'"' | b'\n' | b'\r' => return None, + byte if byte.is_ascii() => byte, + _ => return None, + }; + bytes.push(byte); + } + Some(IntegralLiteral { + width: bytes.len().max(1).checked_mul(8)?, + signed: false, + value: BigUint::from_bytes_be(&bytes), + mask: BigUint::default(), + }) +} + fn parse_unbased_unsized_literal(value: &str) -> Option { let mut chars = value.chars(); (chars.next()? == '\'' && chars.clone().count() == 1).then_some(())?; diff --git a/crates/celox-test-suite/src/sv/cases/generate.vtest b/crates/celox-test-suite/src/sv/cases/generate.vtest index 07807734aaa..db206a46a8b 100644 --- a/crates/celox-test-suite/src/sv/cases/generate.vtest +++ b/crates/celox-test-suite/src/sv/cases/generate.vtest @@ -871,3 +871,58 @@ (top Top) (eval) (assert_eq y 4)) + +(case generate_local_typedefs_keep_lexical_scope + (source "generate_types.sv" #" + module Top(input logic[7:0] a, output logic[7:0] y,z,widths, + output logic[3:0] root_value, output logic[7:0] parent_value); + typedef logic[3:0] T; + T root; + assign root=a[3:0]; + assign root_value=root; + if(1) begin:left + typedef logic[7:0] T; + typedef logic[1:0] state_t; localparam LEFT_ON=3; + T temp; + state_t state; + assign state=LEFT_ON; + assign temp=a; + assign y=(state==3) ? temp : 0; + T after_inner; + if(1) begin:inner + typedef logic[1:0] inner_t; + inner_t tiny; + assign tiny=a[1:0]; + end + assign after_inner=a; + assign parent_value=after_inner; + end + if(1) begin:right + typedef logic[3:0] T; + typedef logic[1:0] state_t; localparam RIGHT_ON=2; + T temp; + state_t state; + assign state=RIGHT_ON; + assign temp=a[3:0]; + assign z=(state==2) ? {4'hc,temp} : 0; + end + for(genvar i=0;i<2;i=i+1) begin:lanes + typedef logic[i+2:0] lane_t; + lane_t temp; + assign temp=a; + assign widths[4*i+:4]=$bits(temp); + end + endmodule + "#) + (top Top) + (modify (set a 0xa7)) + (assert_eq y 0xa7) + (assert_eq z 0xc7) + (assert_eq root_value 7) + (assert_eq parent_value 0xa7) + (assert_eq widths 0x43) + (modify (set a 0x5c)) + (assert_eq y 0x5c) + (assert_eq z 0xcc) + (assert_eq root_value 0xc) + (assert_eq parent_value 0x5c)) diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index b9e4bb1b180..ef8a2439d0c 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1,5 +1,34 @@ (group hierarchy (category hierarchy)) +(case input_port_defaults_use_child_scope_and_only_omitted_connections + (source "default_input.sv" #" + module Child #(parameter D=8'ha5)(output logic [7:0] y, + input logic [7:0] a=D); + assign y=a; + endmodule + module Fill(output logic [7:0] y, input logic [7:0] a='1); + assign y=a; + endmodule + module Top #(parameter D=0)(input logic [7:0] a, + output logic [7:0] omitted, open, connected, positional, fill); + Child #(.D(8'h96)) c0(.y(omitted)); + Child c1(.a(),.y(open)); + Child c2(.a(a),.y(connected)); + Child c3(positional); + Fill c4(.y(fill)); + endmodule + "#) + (top Top) + (modify (set a 0)) + (assert_eq omitted 0x96) + (assert_eq open 0xa5) + (assert_eq connected 0) + (assert_eq positional 0xa5) + (assert_eq fill 0xff) + (modify (set a 0x5a)) + (assert_eq connected 0x5a) + (assert_eq omitted 0x96)) + (case drives_omitted_and_open_child_inputs_with_z (four_state) (source "open_input.sv" #" @@ -558,3 +587,80 @@ (assert_eq override_var 5) (assert_eq override_type 15) (assert_eq override_array 15)) + +(case concatenated_parameter_actuals_use_each_parent_specialization + (source "concat_actual.sv" #" + module Child #(parameter P=0)(output logic [31:0] y); + assign y=P; + endmodule + module Parent #(parameter N=1, parameter logic[7:0] V=8'ha5)( + output logic[31:0] repeated, combined); + Child #(.P({N{V}})) c0(repeated); + Child #(.P({V,8'(N)})) c1(combined); + endmodule + module Top(output logic[31:0] a, b, c, d); + Parent #(.N(1),.V(8'h12)) p0(a,b); + Parent #(.N(3),.V(8'hc3)) p1(c,d); + endmodule + "#) + (top Top) + (assert_eq a 0x12) + (assert_eq b 0x1201) + (assert_eq c 0xc3c3c3) + (assert_eq d 0xc303)) + +(case conditional_parameter_actuals_follow_parent_specialization + (source "conditional_actual.sv" #" + module Child #(parameter P=0)(output logic [31:0] y); + assign y=P; + endmodule + module Parent #(parameter N=1)(output logic [31:0] y, z); + Child #(.P(N > 2 ? N+10 : 3)) c0(y); + Child #(.P(N > 2 ? (N > 4 ? 8 : 7) : 6)) c1(z); + endmodule + module Top(output logic [31:0] a,b,c,d); + Parent p0(a,b); + Parent #(.N(4)) p1(c,d); + endmodule + "#) + (top Top) + (assert_eq a 3) + (assert_eq b 6) + (assert_eq c 14) + (assert_eq d 7)) + +(case generated_parameter_part_select_actuals + (source "selected_actual.sv" #" + module Child #(parameter P=0)(output logic [1:0] y); + assign y=P; + endmodule + module Parent #(parameter logic [7:0] P=8'he4)(output logic [7:0] y); + for(genvar i=0;i<4;i=i+1) begin:g + Child #(.P(P[i*2 +: 2])) c(y[i*2 +: 2]); + end + endmodule + module Top(output logic [7:0] a,b); + Parent p0(a); + Parent #(.P(8'h1b)) p1(b); + endmodule + "#) + (top Top) + (assert_eq a 0xe4) + (assert_eq b 0x1b)) + +(case sized_parameter_actuals_follow_parent_specialization + (source "sized_actual.sv" #" + module Child #(parameter P=0)(output logic [31:0] y); + assign y=P; + endmodule + module Parent #(parameter N=8)(output logic [31:0] y); + Child #(.P(N'(16'hfedc))) c(y); + endmodule + module Top(output logic [31:0] a,b); + Parent p0(a); + Parent #(.N(12)) p1(b); + endmodule + "#) + (top Top) + (assert_eq a 0xdc) + (assert_eq b 0xedc)) diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 06570bc4e76..34f641f537e 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -1667,3 +1667,72 @@ (assert_eq wrapped (& (>> by_index (* next 8)) 255)) (tick clk) (assert_eq registered value))) + +(case procedural_loop_writes_memory_word_part_selects + (source "memory_byte_enables.sv" #" + module Top #(parameter BYTE_W=8)(input logic clk, rst, input logic [1:0] addr, strobe, + input logic [15:0] data, output logic [15:0] q, ascending_q); + logic [15:0] mem[0:3]; + logic [0:15] ascending_mem[3:0]; + always_ff @(posedge clk) begin + if (rst) begin + for (integer i=0; i<4; i=i+1) begin + mem[i] <= 0; + ascending_mem[i] <= 0; + end + end else begin + for (integer i=0; i<2; i=i+1) begin + if (strobe[i]) begin + mem[addr][BYTE_W*i +: BYTE_W] <= data[BYTE_W*i +: BYTE_W]; + ascending_mem[addr][2*BYTE_W-1-BYTE_W*i -: BYTE_W] <= data[BYTE_W*i +: BYTE_W]; + end + end + end + end + assign q=mem[addr]; + assign ascending_q=ascending_mem[addr]; + endmodule + "#) + (top Top) + (modify (set rst 1) (set addr 0) (set strobe 0) (set data 0)) + (tick clk) + (assert_eq q 0) + (assert_eq ascending_q 0) + (modify (set rst 0) (set strobe 3) (set data 0x1234)) + (tick clk) + (assert_eq q 0x1234) + (assert_eq ascending_q 0x1234) + (modify (set addr 1) (set strobe 1) (set data 0xabcd)) + (tick clk) + (assert_eq q 0x00cd) + (assert_eq ascending_q 0x00cd) + (modify (set strobe 2) (set data 0x5678)) + (tick clk) + (assert_eq q 0x56cd) + (assert_eq ascending_q 0x56cd) + (modify (set strobe 0) (set data 0xffff)) + (tick clk) + (assert_eq q 0x56cd) + (assert_eq ascending_q 0x56cd) + (modify (set addr 0)) + (assert_eq q 0x1234) + (assert_eq ascending_q 0x1234) + (modify (set addr 2)) + (assert_eq q 0) + (assert_eq ascending_q 0)) + +(case indexed_selections_in_constant_declaration_contexts + (source "declaration_select.sv" #" + module Top(output logic [3:0] enumeration, output logic [31:0] width); + localparam logic [7:0] P=8'hab; + logic [P[4 +: 4]-1:0] y; + typedef enum logic [3:0] { E=P[4 +: 4] } nibble; + nibble state; + assign state=E; + assign enumeration=state; + assign width=$bits(y); + endmodule + "#) + (top Top) + (assert_eq enumeration 10) + (assert_eq width 10)) diff --git a/crates/celox-test-suite/src/sv/cases/literals.vtest b/crates/celox-test-suite/src/sv/cases/literals.vtest index b5164bc0b56..9c90d6c3820 100644 --- a/crates/celox-test-suite/src/sv/cases/literals.vtest +++ b/crates/celox-test-suite/src/sv/cases/literals.vtest @@ -47,3 +47,30 @@ (let mask (xmask (get y))) (assert (== value 0b1011)) (assert (== mask 0b0011))) + +(case string_literals_are_unsigned_packed_bytes + (source "string_literals.sv" #" + module Child #(parameter P="fallback")(output logic [63:0] y); + assign y=P; + endmodule + module Top #(parameter VENDOR="XILINX")( + output logic matched, output logic [63:0] forwarded, + output logic [47:0] escaped, output logic [23:0] underscore, + output logic [7:0] empty_width, output logic [15:0] extended); + localparam TEXT="A_B"; + localparam COPY=TEXT; + assign matched=(VENDOR == "XILINX") && (COPY == "A_B"); + Child #(.P(VENDOR)) child(forwarded); + assign escaped={"\101", "\x42", "\n", "\t", "\\", "\""}; + assign underscore=COPY; + assign empty_width=$bits(""); + assign extended="\200"; + endmodule + "#) + (top Top) + (assert_eq matched 1) + (assert_eq forwarded 0x58494c494e58) + (assert_eq escaped 0x41420a095c22) + (assert_eq underscore 0x415f42) + (assert_eq empty_width 8) + (assert_eq extended 0x80)) diff --git a/crates/celox-test-suite/src/sv/cases/operators.vtest b/crates/celox-test-suite/src/sv/cases/operators.vtest index be1e0c90737..8af35d60f9a 100644 --- a/crates/celox-test-suite/src/sv/cases/operators.vtest +++ b/crates/celox-test-suite/src/sv/cases/operators.vtest @@ -937,6 +937,105 @@ (modify (set a 0b10)) (assert_eq y 0xaa)) +(case forwards_replicated_parameter_values + (source "replicated_parameter.sv" #" + module Child #(parameter P=0)(output logic [63:0] y); + assign y=P; + endmodule + module Top #(parameter N=2, parameter P={N{32'h12345678}})( + output logic [63:0] y); + Child #(.P(P)) child(.y(y)); + endmodule + "#) + (top Top) + (assert_eq y 0x1234567812345678)) + +(case size_casts_resolve_generated_locals_and_parameter_expressions + (source "scoped_cast.sv" #" + module Child #(parameter N=2, parameter signed S=-3)(input logic [7:0] bus_data, + input logic select, input logic [7:0] data, + output logic [15:0] y, signed_value, unsigned_value); + if (N>1) begin : g + logic [7:0] saved; + assign saved=data; + assign y=16'(select ? saved : bus_data); + assign signed_value=16'(S+1); + assign unsigned_value=16'(8'(8'(N)-8'd3)); + end + endmodule + module Top(input logic select, input logic [7:0] data, + output logic [15:0] y, signed_value, unsigned_value); + Child child(8'h80, select, data, y, signed_value, unsigned_value); + endmodule + "#) + (top Top) + (modify (set select 0) (set data 0xf1)) + (assert_eq y 0x80) + (assert_eq signed_value 0xfffe) + (assert_eq unsigned_value 0xff) + (modify (set select 1)) + (assert_eq y 0xf1)) + +(case parameter_size_casts_in_generate_conditions + (source "generate_cast.sv" #" + module Top #(parameter W=3, parameter MASK=3'b100)( + output logic [7:0] y, output logic signed_test, output logic guard); + if ((W'(MASK) & {W{1'b1}}) == 0) assign y=8'h11; + else assign y=8'hab; + if (W'(-1) < 0) assign signed_test=1'b1; + else assign signed_test=1'b0; + if ((0 || 0) && (W'(MASK) & {W{1'b1}}) == 0) assign guard=1'b0; + else assign guard=1'b1; + endmodule + "#) + (top Top) + (assert_eq y 0xab) + (assert_eq signed_test 1) + (assert_eq guard 1)) + +(case zero_count_replications_preserve_concat_bits + (source "zero_replication.sv" #" + module Top #(parameter PAD=0)(input logic [3:0] a, + output logic [7:0] front, middle, back); + assign front = {{PAD{1'bx}}, a, 4'h5}; + assign middle = {4'ha, {PAD{1'bz}}, a}; + assign back = {a, 4'hc, {PAD{1'b1}}}; + endmodule + "#) + (top Top) + (modify (set a 9)) + (assert_eq front 0x95) + (assert_eq middle 0xa9) + (assert_eq back 0x9c) + (modify (set a 3)) + (assert_eq front 0x35) + (assert_eq middle 0xa3) + (assert_eq back 0x3c)) + +(case zero_count_replications_preserve_unknown_bits + (four_state) + (source "zero_replication.sv" #" + module Top #(parameter PAD=0)(input logic [3:0] a, + output logic [7:0] front, middle, back); + assign front = {{PAD{1'bx}}, a, 4'h5}; + assign middle = {4'ha, {PAD{1'bz}}, a}; + assign back = {a, 4'hc, {PAD{1'b1}}}; + endmodule + "#) + (top Top) + (modify (set a 9)) + (assert_eq front 0x95) + (assert_eq middle 0xa9) + (assert_eq back 0x9c) + (modify (set a 3)) + (assert_eq front 0x35) + (assert_eq middle 0xa3) + (assert_eq back 0x3c) + (modify (set a (fourstate 0xa 0x5))) + (assert_eq front (fourstate 0xa5 0x50)) + (assert_eq middle (fourstate 0xaa 0x05)) + (assert_eq back (fourstate 0xac 0x50))) + (case preserves_unknown_complement_and_converts_bit_function_arguments (four_state) (source "four_state_unary.sv" #" diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 12890845ac2..3b571e71fee 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -705,3 +705,99 @@ "#) (top Top) (assert_eq partial (fourstate 0xd 0x5))) + +(case static_function_result_filled_by_constant_loops + (source "static_result.sv" #" + module Top #(parameter W=5)(input logic [W-1:0] gray, + output logic [W-1:0] binary, reversed); + function [W-1:0] gray_to_binary(input logic [W-1:0] g); + for (integer i=0; i> i); + endfunction + function [W-1:0] reverse_bits(input logic [W-1:0] g); + for (integer i=W-1; i>=0; i=i-1) + reverse_bits[W-1-i]=g[i]; + endfunction + assign binary=gray_to_binary(gray); + assign reversed=reverse_bits(gray); + endmodule + "#) + (top Top) + (modify (set gray 0x00)) + (assert_eq binary 0x00) + (assert_eq reversed 0x00) + (modify (set gray 0x10)) + (assert_eq binary 0x1f) + (assert_eq reversed 0x01) + (modify (set gray 0x04)) + (assert_eq binary 0x07) + (assert_eq reversed 0x04) + (modify (set gray 0x1b)) + (assert_eq binary 0x12) + (assert_eq reversed 0x1b)) + +(case static_function_scratch_arrays_are_filled_before_reads + (source "scratch_array.sv" #" + module Top(input logic [7:0] a, output logic [7:0] y); + function [7:0] transform(input logic [7:0] value); + logic [7:0] words [1:0]; + for(integer i=0;i<2;i=i+1) begin + words[i]='0; + words[i][i]=value[i]; + end + transform=words[0]+words[1]; + endfunction + assign y=transform(a); + endmodule + "#) + (top Top) + (set a 3) + (eval) + (assert_eq y 3) + (set a 0) + (eval) + (assert_eq y 0) + (set a 2) + (eval) + (assert_eq y 2)) + +(case constant_functions_preserve_concat_operand_widths + (source "constant_concat.sv" #" + module Top(output logic [15:0] a,b, output logic [7:0] zero_part); + function automatic [15:0] expand(input logic [3:0] value); + expand={{2{value}},value,4'h5}; + endfunction + function automatic [7:0] trim(input logic [3:0] value); + trim={4'hd,{0{value}},value}; + endfunction + localparam A=expand(4'h2), B=expand(4'ha), Z=trim(4'h3); + assign a=A; + assign b=B; + assign zero_part=Z; + endmodule + "#) + (top Top) + (assert_eq a 0x2225) + (assert_eq b 0xaaa5) + (assert_eq zero_part 0xd3)) + +(case constant_functions_inside_selected_parameter_initializers + (source "selected_constant_function.sv" #" + module Parent #(parameter W=8)(output logic [31:0] y); + localparam logic [31:0] WIDTHS=W; + function automatic [31:0] make_mask(input integer unused); + integer width; + width=WIDTHS[0 +: 8]; + make_mask={32{1'b1}}>>(32-width); + endfunction + localparam logic [31:0] MASK=(W==0) ? 32'(0) : make_mask(0); + assign y=MASK; + endmodule + module Top(output logic [31:0] a,b); + Parent p0(a); + Parent #(.W(4)) p1(b); + endmodule + "#) + (top Top) + (assert_eq a 255) + (assert_eq b 15)) diff --git a/crates/celox-vpi/src/callbacks.rs b/crates/celox-vpi/src/callbacks.rs index d92de3fbb29..0088f8a35a7 100644 --- a/crates/celox-vpi/src/callbacks.rs +++ b/crates/celox-vpi/src/callbacks.rs @@ -292,7 +292,10 @@ pub(super) fn run() -> bool { } iterations += 1; if iterations > 1_000_000 { - fail("VPI callback scheduler exceeded 1000000 iterations".to_string()); + fail( + "VPI callback scheduler exceeded 1000000 iterations without advancing time" + .to_string(), + ); break; } @@ -362,7 +365,14 @@ pub(super) fn run() -> bool { let Some(next_time) = next_time else { break; }; - with_host(|host| borrow_cell_mut(&host.callbacks, |state| state.time = next_time)); + with_host(|host| { + borrow_cell_mut(&host.callbacks, |state| { + if next_time > state.time { + iterations = 0; + } + state.time = next_time; + }) + }); fire_all(CB_NEXT_SIM_TIME); if !finish_requested() { super::flush_pending_writes(); diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 4d31bbed865..7b72d33a241 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -50,6 +50,9 @@ pub const VPI_X: i32 = 3; pub const VPI_ITERATOR: i32 = 27; pub const VPI_CONSTANT: i32 = 7; pub const VPI_MODULE: i32 = 32; +pub const VPI_PARAMETER: i32 = 41; +pub const VPI_CONST_TYPE: i32 = 40; +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; @@ -723,29 +726,33 @@ pub unsafe extern "C" fn vpi_iterate(kind: i32, reference: VpiHandle) -> VpiHand .collect() }) .unwrap_or_default(), - (VPI_PORT | VPI_REG | VPI_NET | VPI_VARIABLES, Some(ObjectRef::Scope(id))) => { - reflection - .scope(id) - .map(|scope| { - scope - .signals - .iter() - .copied() - .filter(|signal_id| { - let signal = reflection.signal(*signal_id).unwrap(); - match kind { - VPI_PORT => signal.direction != SignalDirection::Internal, - VPI_REG => true, - VPI_VARIABLES => signal.direction == SignalDirection::Internal, - VPI_NET => false, - _ => false, - } - }) - .map(ObjectRef::Signal) - .collect() - }) - .unwrap_or_default() - } + ( + VPI_PORT | VPI_REG | VPI_NET | VPI_VARIABLES | VPI_PARAMETER, + Some(ObjectRef::Scope(id)), + ) => reflection + .scope(id) + .map(|scope| { + scope + .signals + .iter() + .copied() + .filter(|signal_id| { + let signal = reflection.signal(*signal_id).unwrap(); + if signal.is_parameter { + return kind == VPI_PARAMETER; + } + match kind { + VPI_PORT => signal.direction != SignalDirection::Internal, + VPI_REG => true, + VPI_VARIABLES => signal.direction == SignalDirection::Internal, + VPI_NET => false, + _ => false, + } + }) + .map(ObjectRef::Signal) + .collect() + }) + .unwrap_or_default(), _ => Vec::new(), } }) @@ -784,7 +791,18 @@ pub unsafe extern "C" fn vpi_scan(iterator: VpiHandle) -> VpiHandle { fn object_type(object: ObjectRef) -> i32 { match object { ObjectRef::Scope(_) => VPI_MODULE, - ObjectRef::Signal(_) => VPI_REG, + ObjectRef::Signal(id) => with_runtime(|runtime| { + if runtime + .reflection() + .signal(id) + .is_some_and(|signal| signal.is_parameter) + { + VPI_PARAMETER + } else { + VPI_REG + } + }) + .unwrap_or(VPI_REG), } } @@ -836,6 +854,13 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { }) .unwrap_or(0), VPI_TYPE => object_type(object), + VPI_CONST_TYPE => { + if object_type(object) == VPI_PARAMETER { + VPI_BINARY_CONST + } else { + 0 + } + } VPI_TOP_MODULE => i32::from(object == ObjectRef::Scope(ReflectionScopeId(0))), VPI_SIZE | VPI_SCALAR | VPI_VECTOR | VPI_DIRECTION | VPI_SIGNED => { with_runtime(|runtime| { @@ -1220,6 +1245,16 @@ pub unsafe extern "C" fn vpi_put_value( let Some(ObjectRef::Signal(id)) = (unsafe { object_ref(reference) }) else { return ptr::null_mut(); }; + if with_runtime(|runtime| { + runtime + .reflection() + .signal(id) + .is_some_and(|signal| signal.is_parameter) + }) + .unwrap_or(false) + { + return ptr::null_mut(); + } let identity = with_runtime(|runtime| runtime.signal_identity(id)).flatten(); let Some(identity) = identity else { return ptr::null_mut(); diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index 4fa69954160..fe2ef1926b0 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -8,6 +8,143 @@ use celox::{NativeProgramInstance, SimBackend, Simulator}; use celox_vpi::*; static VPI_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +static LONG_CALLBACK_COUNT: AtomicUsize = AtomicUsize::new(0); +static LONG_CALLBACK_DELAY: AtomicUsize = AtomicUsize::new(1); + +#[cfg(feature = "systemverilog")] +#[test] +fn systemverilog_parameters_are_typed_read_only_objects_at_o2() { + let _serial = lock_vpi(); + let source = "module Top #(parameter WIDTH=8, parameter signed NEG=-3, + parameter logic [64:0] WIDE=65'h10000000000000001, + parameter logic [3:0] FOUR=4'b10xz)(output logic [7:0] y); + assign y=WIDTH; endmodule"; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("params.sv"))], "Top") + .param("WIDTH", 9) + .four_state(true) + .opt_level(celox::OptLevel::O2) + .build() + .unwrap(); + let _session = install_runtime(trusted_instance( + simulator.shared_code().program_image().clone(), + )) + .unwrap(); + unsafe { + for (name, expected) in [ + (c"Top.WIDTH", "00000000000000000000000000001001"), + (c"Top.NEG", "11111111111111111111111111111101"), + ( + c"Top.WIDE", + "10000000000000000000000000000000000000000000000000000000000000001", + ), + (c"Top.FOUR", "10xz"), + ] { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!handle.is_null(), "{name:?}"); + assert_eq!(vpi_get(VPI_TYPE, handle), VPI_PARAMETER); + assert_eq!(vpi_get(VPI_CONST_TYPE, handle), VPI_BINARY_CONST); + let mut value = VpiValue { + format: VPI_BIN_STR_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(handle, &mut value); + assert_eq!(CStr::from_ptr(value.value.str_).to_str().unwrap(), expected); + let replacement = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_put_value(handle, &replacement, ptr::null(), VPI_NO_DELAY); + vpi_get_value(handle, &mut value); + assert_eq!(CStr::from_ptr(value.value.str_).to_str().unwrap(), expected); + vpi_free_object(handle); + } + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + let iterator = vpi_iterate(VPI_PARAMETER, top); + let mut count = 0; + loop { + let parameter = vpi_scan(iterator); + if parameter.is_null() { + break; + } + count += 1; + vpi_free_object(parameter); + } + assert_eq!(count, 4); + vpi_free_object(top); + } + clear_runtime(); +} + +unsafe extern "C" fn reschedule_long_callback(data: *mut VpiCbData) -> i32 { + let count = LONG_CALLBACK_COUNT.fetch_add(1, Ordering::SeqCst) + 1; + let delay = LONG_CALLBACK_DELAY.load(Ordering::SeqCst); + if delay != 0 && count == 500_010 { + vpi_control(VPI_FINISH); + return 0; + } + let mut time = VpiTime { + type_: VPI_SIM_TIME, + low: delay as u32, + ..VpiTime::default() + }; + // Safety: dispatch owns readable callback data, and registration copies time. + let next = unsafe { + VpiCbData { + time: &mut time, + ..*data + } + }; + unsafe { + vpi_register_cb(&next); + } + 0 +} + +#[test] +fn callback_iteration_limit_only_bounds_nonadvancing_time() { + let _serial = lock_vpi(); + for delay in [1, 0] { + let simulator = Simulator::builder(DESIGN, "Top").build().unwrap(); + let _session = install_runtime(trusted_instance( + simulator.shared_code().program_image().clone(), + )) + .unwrap(); + LONG_CALLBACK_COUNT.store(0, Ordering::SeqCst); + LONG_CALLBACK_DELAY.store(delay, Ordering::SeqCst); + let mut time = VpiTime { + type_: VPI_SIM_TIME, + low: delay as u32, + ..VpiTime::default() + }; + let callback = VpiCbData { + reason: CB_AFTER_DELAY, + cb_rtn: Some(reschedule_long_callback), + obj: ptr::null_mut(), + time: &mut time, + value: ptr::null_mut(), + index: 0, + user_data: ptr::null_mut(), + }; + unsafe { + assert!(!vpi_register_cb(&callback).is_null()); + } + let result = run_callbacks_result(); + if delay != 0 { + assert!(result.unwrap()); + assert_eq!(LONG_CALLBACK_COUNT.load(Ordering::SeqCst), 500_010); + assert_eq!(celox_vpi_current_time(), 500_010); + } else { + assert!( + result + .unwrap_err() + .to_string() + .contains("without advancing time") + ); + } + clear_runtime(); + } +} fn lock_vpi() -> std::sync::MutexGuard<'static, ()> { VPI_TEST_LOCK @@ -366,7 +503,21 @@ fn compile_time_objects_are_not_exposed_as_writable_registers() { .unwrap(); unsafe { - assert!(vpi_handle_by_name(c"Top.WIDTH".as_ptr(), ptr::null_mut()).is_null()); + let width = vpi_handle_by_name(c"Top.WIDTH".as_ptr(), ptr::null_mut()); + assert!(!width.is_null()); + assert_eq!(vpi_get(VPI_TYPE, width), VPI_PARAMETER); + let replacement = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + assert!(vpi_put_value(width, &replacement, ptr::null(), VPI_NO_DELAY).is_null()); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(width, &mut value); + assert_eq!(value.value.integer, 8); + vpi_free_object(width); assert!(vpi_handle_by_name(c"Top.BIAS".as_ptr(), ptr::null_mut()).is_null()); let output = vpi_handle_by_name(c"Top.y".as_ptr(), ptr::null_mut()); assert!(!output.is_null()); @@ -2820,7 +2971,10 @@ fn interface_members_are_navigable_after_native_image_round_trip() { assign y = s_axis.valid ? s_axis.data + 1 : 0; endmodule module Top(output logic [7:0] y); - Axis s_axis(), s$axis(); + Axis s_axis(), s$axis(), lanes[2](), shifted[-1:1](); + assign lanes[0].data=8'h34; + assign lanes[1].data=8'h56; + assign shifted[-1].data=8'h78; logic [7:0] cash$flow; assign cash$flow = 3; Child uut(s_axis, y); @@ -2842,6 +2996,21 @@ fn interface_members_are_navigable_after_native_image_round_trip() { let _session = install_runtime(runtime).unwrap(); unsafe { let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + for (name, expected) in [ + (c"Top.lanes[0].data", 0x34), + (c"Top.lanes[1].data", 0x56), + (c"Top.shifted[-1].data", 0x78), + ] { + let member = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!member.is_null(), "{name:?}"); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(member, &mut value); + assert_eq!(value.value.integer, expected); + vpi_free_object(member); + } let bus = vpi_handle_by_name(c"s_axis".as_ptr(), top); assert!(!bus.is_null(), "the declared interface must have a scope"); let data = vpi_handle_by_name(c"data".as_ptr(), bus); diff --git a/crates/celox-vpi/tests/diagnostics.rs b/crates/celox-vpi/tests/diagnostics.rs index 82bfae2c8ce..be874d50d0b 100644 --- a/crates/celox-vpi/tests/diagnostics.rs +++ b/crates/celox-vpi/tests/diagnostics.rs @@ -87,3 +87,61 @@ fn run_and_build_share_project_target_and_cli_diagnostic_precedence() { assert!(!denied.status.success()); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn aggregate_input_defaults_can_be_enabled_with_diagnostic_policy() { + let project = tempfile::tempdir().unwrap(); + fs::write( + project.path().join("top.sv"), + r#" + module Child(input logic [7:0] a[2]='{8'ha5,8'h5a}, output logic [15:0] y); + assign y={a[0],a[1]}; + endmodule + module Top(output logic [15:0] omitted, connected); + logic [7:0] a[2]; + assign a[0]=8'h12; + assign a[1]=8'h34; + Child c0(.y(omitted)); + Child c1(.a(a),.y(connected)); + initial begin #1; + assert(omitted===16'ha55a && connected===16'h1234) else $fatal(1,"defaults"); + $display("ok"); $finish; + end + endmodule + "#, + ) + .unwrap(); + fs::write( + project.path().join("celox.toml"), + "sources=['top.sv']\ntop='Top'\n[diagnostics]\nunpacked_port_default='warn'\n", + ) + .unwrap(); + let run = |overrides: &[&str]| { + Command::new(env!("CARGO_BIN_EXE_celox")) + .current_dir(project.path()) + .arg("run") + .args(overrides) + .output() + .unwrap() + }; + let warned = run(&[]); + assert!( + warned.status.success(), + "{}", + String::from_utf8_lossy(&warned.stderr) + ); + assert_eq!(warned.stdout, b"ok\n"); + assert!(String::from_utf8_lossy(&warned.stderr).contains("unpacked_port_default")); + let allowed = run(&["--diagnostic", "unpacked_port_default=allow"]); + assert!( + allowed.status.success(), + "{}", + String::from_utf8_lossy(&allowed.stderr) + ); + assert_eq!(allowed.stdout, b"ok\n"); + assert!(!String::from_utf8_lossy(&allowed.stderr).contains("unpacked_port_default")); + let rejected = run(&["--diagnostic", "unpacked_port_default=error"]); + assert!(!rejected.status.success()); + assert!(String::from_utf8_lossy(&rejected.stderr).contains("unpacked_port_default")); +} diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 608c8c4bc75..f0ab19b077a 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 = 19; +const CONTAINER_VERSION: u16 = 20; 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/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index b417d2b7dc0..a5e56e04cb0 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -18,7 +18,7 @@ pub enum DiagnosticLevel { /// Overrides keyed by the code shown in a compilation diagnostic. /// Unlisted diagnostics retain their default severity. Only explicitly -/// recoverable errors (currently `mixed_timescale`) can be relaxed. +/// recoverable errors can be relaxed. #[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(transparent)] pub struct DiagnosticPolicy(pub BTreeMap); @@ -70,14 +70,13 @@ impl DiagnosticPolicy { } pub(crate) fn level(&self, code: &str) -> DiagnosticLevel { - self.0 - .get(code) - .copied() - .unwrap_or(if code == "mixed_timescale" { + self.0.get(code).copied().unwrap_or( + if matches!(code, "mixed_timescale" | "unpacked_port_default") { DiagnosticLevel::Error } else { DiagnosticLevel::Warn - }) + }, + ) } #[cfg(feature = "systemverilog")] diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 89dd6f342ef..00743b70397 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -988,10 +988,7 @@ impl RuntimeProgram { let instance = self.design.instance(scope.instance_id).unwrap(); for state_address in instance.state_addresses() { let variable = self.design.variable(state_address).unwrap(); - if matches!( - variable.var_kind, - VariableKind::Parameter | VariableKind::Constant - ) { + if variable.var_kind == VariableKind::Constant { continue; } if instance.path_index.get(&variable.path) != Some(&Some(*state_address)) { @@ -1024,6 +1021,7 @@ impl RuntimeProgram { _ => SignalDirection::Internal, }; signals.push(ReflectionSignal { + is_parameter: variable.var_kind == VariableKind::Parameter, full_name: format!("{parent_name}.{name}"), name: name.clone(), parent: scope_ids[&parent_name], diff --git a/crates/celox/tests/frontends/systemverilog/generate.rs b/crates/celox/tests/frontends/systemverilog/generate.rs index ff43db4c49b..f62f64887a3 100644 --- a/crates/celox/tests/frontends/systemverilog/generate.rs +++ b/crates/celox/tests/frontends/systemverilog/generate.rs @@ -1,6 +1,40 @@ use super::*; sv_backends! { + fn generated_constants_select_words_from_128_bit_parameters_at_o2(sim) { + @setup { + // Icarus 13 rejects packed array parameters; the same source is + // independently checked with Verilator. + let source = r#" + module Top #(parameter logic [3:0][31:0] WORDS={4{32'd4}})( + output logic [15:0] widths, output logic [31:0] first,last,edge_first,edge_last); + for(genvar i=0;i<4;i=i+1) begin:g + localparam C=$clog2(WORDS[i]+1); + assign widths[i*4 +: 4]=C; + end + localparam FIRST=WORDS[0], LAST=WORDS[3]; + localparam logic [3:0][31:0] EDGE=128'h80000000000000040000000480000000; + localparam E0=EDGE[0], E3=EDGE[3]; + assign edge_first=E0; + assign edge_last=E3; + assign first=FIRST; + assign last=LAST; + endmodule + "#; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("constant_word.sv"))], "Top") + .opt_level(celox::OptLevel::O2); + assert_eq!(sim.get(sim.signal("widths")), BigUint::from(0x3333u32)); + assert_eq!(sim.get(sim.signal("first")), BigUint::from(4u8)); + assert_eq!(sim.get(sim.signal("last")), BigUint::from(4u8)); + assert_eq!(sim.get(sim.signal("edge_first")), BigUint::from(0x80000000u32)); + assert_eq!(sim.get(sim.signal("edge_last")), BigUint::from(0x80000000u32)); + } + + fn generate_local_typedefs_keep_lexical_scope(sim) { + @case "generate::generate_local_typedefs_keep_lexical_scope"; + } + fn bits_of_generate_local_array_element_localparam(sim) { @case "generate::bits_of_generate_local_array_element_localparam"; } @@ -236,3 +270,65 @@ fn keeps_four_state_generate_function_guards_nonexhaustive() { "{error}" ); } + +// Icarus 13 rejects enum labels inside generate scopes and crashes while +// elaborating this source. Keep O2 isolation coverage in the API harness; +// the portable suite separately checks generated typedef layouts. +sv_backends! { + fn generated_enum_and_shadowed_type_scopes_survive_o2(sim) { + @setup { + let source=r#" + module Top(input logic[7:0] a, output logic[7:0] y,z,widths, + output logic[3:0] root_value, output logic[7:0] parent_value); + typedef logic[3:0] T; + T root; + assign root=a[3:0]; + assign root_value=root; + if(1) begin:left + typedef logic[7:0] T; + typedef enum logic[1:0] { OFF=0, ON=3 } state_t; + T temp; + state_t state; + assign state=ON; + assign temp=a; + assign y=(state==3) ? temp : 0; + if(1) begin:inner + typedef logic[1:0] T; + T tiny; + assign tiny=a[1:0]; + end + T after_inner; + assign after_inner=a; + assign parent_value=after_inner; + end + if(1) begin:right + typedef logic[3:0] T; + typedef enum logic[1:0] { OFF=1, ON=2 } state_t; + T temp; + state_t state; + assign state=ON; + assign temp=a[3:0]; + assign z=(state==2) ? {4'hc,temp} : 0; + end + for(genvar i=0;i<2;i=i+1) begin:lanes + typedef logic[i+2:0] lane_t; + lane_t temp; + assign temp=a; + assign widths[4*i+:4]=$bits(temp); + end + endmodule + "#; + } + @build Simulator::from_sv_sources(vec![(source,Path::new("generated_enum.sv"))],"Top") + .opt_level(celox::OptLevel::O2); + let a=sim.signal("a"); + for value in [0xa7u8,0x5c] { + sim.modify(|io| io.set(a,value)).unwrap(); + assert_eq!(sim.get(sim.signal("y")),BigUint::from(value)); + assert_eq!(sim.get(sim.signal("z")),BigUint::from(0xc0|(value&15))); + assert_eq!(sim.get(sim.signal("parent_value")),BigUint::from(value)); + assert_eq!(sim.get(sim.signal("root_value")),BigUint::from(value&15)); + assert_eq!(sim.get(sim.signal("widths")),BigUint::from(0x43u8)); + } + } +} diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index da8731c3e55..87930fcef09 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,26 @@ use super::*; sv_backends! { + fn sized_parameter_actuals_follow_parent_specialization(sim) { + @case "hierarchy::sized_parameter_actuals_follow_parent_specialization"; + } + + fn generated_parameter_part_select_actuals(sim) { + @case "hierarchy::generated_parameter_part_select_actuals"; + } + + fn conditional_parameter_actuals_follow_parent_specialization(sim) { + @case "hierarchy::conditional_parameter_actuals_follow_parent_specialization"; + } + + fn concatenated_parameter_actuals_use_each_parent_specialization(sim) { + @case "hierarchy::concatenated_parameter_actuals_use_each_parent_specialization"; + } + + fn input_port_defaults_use_child_scope_and_only_omitted_connections(sim) { + @case "hierarchy::input_port_defaults_use_child_scope_and_only_omitted_connections"; + } + fn bits_query_parameter_overrides_follow_caller_specialization(sim) { @case "hierarchy::bits_query_parameter_overrides_follow_caller_specialization"; } diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 1647d3ca132..9acf8d49142 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -3,6 +3,10 @@ use super::*; // IEEE 1800-2023 11.5.1: the index operator and declaration direction // independently determine the endpoints of the selected range. sv_backends! { + fn procedural_loop_writes_memory_word_part_selects(sim) { + @case "indexed_select::procedural_loop_writes_memory_word_part_selects"; + } + fn constant_parameter_initializers_preserve_inferred_dimensions(sim) { @case "indexed_select::constant_parameter_initializers_preserve_inferred_dimensions"; } @@ -278,17 +282,9 @@ fn rejects_selected_widths_that_are_nonpositive() { } } -#[test] -fn rejects_indexed_selections_in_unlowered_constant_contexts() { - for declaration in [ - "logic [P[4 +: 4]-1:0] y; assign y = '0;", - "typedef enum logic [3:0] { E = P[4 +: 4] } nibble; nibble y; assign y = E;", - ] { - let source = - format!("module Top; localparam logic [7:0] P = 8'hab; {declaration} endmodule"); - Simulator::from_sv_sources(vec![(&source, Path::new("unlowered_constant.sv"))], "Top") - .build_cranelift() - .expect_err("unlowered indexed constants must be rejected"); +sv_backends! { + fn indexed_selections_in_constant_declaration_contexts(sim) { + @case "indexed_select::indexed_selections_in_constant_declaration_contexts"; } } diff --git a/crates/celox/tests/frontends/systemverilog/literals.rs b/crates/celox/tests/frontends/systemverilog/literals.rs index 9ee04036847..c1b77cb5bec 100644 --- a/crates/celox/tests/frontends/systemverilog/literals.rs +++ b/crates/celox/tests/frontends/systemverilog/literals.rs @@ -28,6 +28,10 @@ fn simulates_systemverilog_literals_with_widths_and_masks() { } sv_backends! { + fn string_literals_are_unsigned_packed_bytes(sim) { + @case "literals::string_literals_are_unsigned_packed_bytes"; + } + fn simulates_systemverilog_unbased_unsized_literals(sim) { @case "literals::simulates_systemverilog_unbased_unsized_literals"; } diff --git a/crates/celox/tests/frontends/systemverilog/operators.rs b/crates/celox/tests/frontends/systemverilog/operators.rs index 58533bc3e51..39132557e13 100644 --- a/crates/celox/tests/frontends/systemverilog/operators.rs +++ b/crates/celox/tests/frontends/systemverilog/operators.rs @@ -1,4 +1,20 @@ sv_backends! { + fn size_casts_resolve_generated_locals_and_parameter_expressions(sim) { + @case "operators::size_casts_resolve_generated_locals_and_parameter_expressions"; + } + + fn parameter_size_casts_in_generate_conditions(sim) { + @case "operators::parameter_size_casts_in_generate_conditions"; + } + fn forwards_replicated_parameter_values(sim) { + @case "operators::forwards_replicated_parameter_values"; + } + fn zero_count_replications_preserve_unknown_bits(sim) { + @case "operators::zero_count_replications_preserve_unknown_bits"; + } + fn zero_count_replications_preserve_concat_bits(sim) { + @case "operators::zero_count_replications_preserve_concat_bits"; + } fn multidimensional_packed_declared_ranges_four_state(sim) { @case "operators::multidimensional_packed_declared_ranges_four_state"; } fn multidimensional_packed_declared_ranges(sim) { @case "operators::multidimensional_packed_declared_ranges"; } fn multidimensional_packed_declared_range_writes(sim) { @case "operators::multidimensional_packed_declared_range_writes"; } diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 6dbb86aa139..f8b1c45eb35 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -1,4 +1,20 @@ sv_backends! { + fn constant_functions_inside_selected_parameter_initializers(sim) { + @case "procedural::constant_functions_inside_selected_parameter_initializers"; + } + + fn constant_functions_preserve_concat_operand_widths(sim) { + @case "procedural::constant_functions_preserve_concat_operand_widths"; + } + + fn static_function_scratch_arrays_are_filled_before_reads(sim) { + @case "procedural::static_function_scratch_arrays_are_filled_before_reads"; + } + + fn static_function_result_filled_by_constant_loops(sim) { + @case "procedural::static_function_result_filled_by_constant_loops"; + } + fn typedef_declaration_initializers(sim) { @case "procedural::typedef_declaration_initializers"; } diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index f42d819d4a5..67750546b12 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5827,9 +5827,9 @@ fn rejects_constructs_that_are_not_yet_lowered() { "#, ), ( - "ANSI port default value", + "default value on a non-input port", r#" - module Top(input wire a = 1'b1, output wire y); assign y = a; endmodule + module Top(input wire a, output wire y = 1'b1); assign y = a; endmodule "#, ), (