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 \