From 02ef771f9ca5548d7fb69213519f6129162c0e61 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:46:29 +0900 Subject: [PATCH] fix(sim)!: preserve global precision in VCD and VPI VCD headers labeled every timestamp as 1ns and VPI reported 1ps regardless of the design. Carry the analyzer's global precision through symbolic modules and assembly into the runtime design, and retain it in native images. Use it for VCD headers and null-handle VPI queries, including restarted waveforms and NAPI compiled-code cache hits. Retain local module units and precisions in reflected scopes so module and signal VPI queries report their own scales (IEEE 1800-2023 37.10 and 38.6), including after native-image reload. Default Veryl and scale-free frontend ticks to 1ps, matching SV's default. Update Playground VCD downloads and document the waveform compatibility change. Bump the native image container to version 14 for the added metadata. Validation: - Precision regressions on native, Cranelift, Wasm, interpreter, tiered, and native/Cranelift parallel configurations; mixed-language designs, package precision, image roundtrips, and VCD restarts. - Existing VCD and time-query regressions, Celox and affected frontend/runtime unit tests, VPI tests, Rust doctests, and the portable compiler configuration. - Live cocotb attached-image integration. - Rebuilt NAPI; simulator, simulation, checkpoint, e2e and timing-addon JS tests; cached-waveform precision regression. - Playground waveform export test and TypeScript checks; formatting, Clippy, and Biome. BREAKING CHANGE: Default VCD headers now use 1ps instead of 1ns. Recompile native images for container version 14. SimModule and ElaboratedDesign struct literals must provide the added timing metadata fields; ReflectionScope literals must provide time_scale. Fixes #1463 Change-Id: Ia5ff9cd5337ce608ea2f6fdd56fda0711d1a21bb --- crates/celox-design/src/lib.rs | 57 ++++++++ crates/celox-frontend-core/src/sdk.rs | 2 + .../src/symbolic/artifact.rs | 4 + .../src/symbolic/assembly.rs | 13 ++ crates/celox-frontend-sv/src/lowering.rs | 36 ++++- crates/celox-frontend-veryl/src/artifact.rs | 2 + crates/celox-napi/src/lib.rs | 42 +++++- crates/celox-runtime/src/reflection.rs | 1 + crates/celox-runtime/src/vcd.rs | 58 +++++++- crates/celox-sv-analyzer/src/ast/packages.rs | 10 ++ .../celox-sv-analyzer/src/ast/timescales.rs | 11 ++ crates/celox-vpi/Cargo.toml | 3 + crates/celox-vpi/src/lib.rs | 22 ++- crates/celox-vpi/tests/basic_vpi.rs | 78 +++++++++++ crates/celox/src/backend/native/backend.rs | 5 + crates/celox/src/backend/native/image_file.rs | 2 +- .../celox/src/backend/native/runtime_image.rs | 5 + crates/celox/src/ir.rs | 6 + crates/celox/src/simulator/builder.rs | 56 ++++++-- crates/celox/tests/time_precision.rs | 127 ++++++++++++++++++ docs/guide/writing-tests.md | 9 ++ docs/ja/guide/writing-tests.md | 9 ++ packages/playground/src/waveform-viewer.ts | 2 +- .../playground/test/waveform-viewer.test.ts | 8 ++ 24 files changed, 541 insertions(+), 27 deletions(-) create mode 100644 crates/celox/tests/time_precision.rs create mode 100644 packages/playground/test/waveform-viewer.test.ts diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 21bb5cc0f63..721479d3890 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -514,6 +514,49 @@ pub enum DeadStorePolicy { PreserveAllPorts, } +/// One simulation tick, expressed as a power of ten seconds. +/// Valid SystemVerilog/VCD scales range from 1 fs (-15) to 100 s (2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(try_from = "i32", into = "i32")] +pub struct TimePrecision(i32); + +impl TimePrecision { + pub fn exponent(self) -> i32 { + self.0 + } + + /// The magnitude and physical unit used by a VCD `$timescale` header. + pub fn vcd_timescale(self) -> (u8, &'static str) { + let magnitude = 10u8.pow(self.0.rem_euclid(3) as u32); + let unit = ["s", "ms", "us", "ns", "ps", "fs"][(-self.0.div_euclid(3)) as usize]; + (magnitude, unit) + } +} + +impl Default for TimePrecision { + /// Scale-free frontends use the same 1ps tick as the SV implementation default. + fn default() -> Self { + Self(-12) + } +} + +impl TryFrom for TimePrecision { + type Error = &'static str; + fn try_from(exponent: i32) -> Result { + if (-15..=2).contains(&exponent) { + Ok(Self(exponent)) + } else { + Err("time precision must be between 1fs and 100s") + } + } +} + +impl From for i32 { + fn from(precision: TimePrecision) -> Self { + precision.0 + } +} + /// Source-independent runtime diagnostics and observable event descriptions. #[derive(Clone, Debug)] pub struct RuntimeSchema { @@ -732,6 +775,13 @@ impl EventTopology { } } +/// Time unit and rounding precision of one source scope, in powers of ten seconds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TimeScale { + pub unit: TimePrecision, + pub precision: TimePrecision, +} + /// Backend-neutral semantic design data after hierarchy flattening. /// /// This is intentionally not a frontend lookup table: every state object is @@ -743,6 +793,11 @@ impl EventTopology { deserialize = "A: Deserialize<'de> + Eq + std::hash::Hash + Ord" ))] pub struct ElaboratedDesign { + /// Physical duration of one global simulation tick. + #[serde(default)] + pub time_precision: TimePrecision, + /// Local time units and precisions retained for reflected instance queries. + pub instance_time_scales: HashMap, pub state_objects: HashMap, pub events: EventTopology, pub initial_state: Vec>, @@ -751,6 +806,8 @@ pub struct ElaboratedDesign { impl Default for ElaboratedDesign { fn default() -> Self { Self { + time_precision: TimePrecision::default(), + instance_time_scales: HashMap::default(), state_objects: HashMap::default(), events: EventTopology::default(), initial_state: Vec::new(), diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index a73e773440e..aa42635fc38 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1897,6 +1897,8 @@ pub fn lower_frontend_artifact( let module_id = ModuleId(0); let sim_module = SimModule { + time_precision: None, + time_scale: celox_design::TimeScale::default(), name: artifact.module_name().to_string(), variables, ff_access_summaries: HashMap::default(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 2916167c90b..2baccec6144 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -56,6 +56,10 @@ pub struct SymbolicProcess { #[derive(Clone)] pub struct SimModule { + /// A frontend's global tick precision; absent for scale-free frontends. + pub time_precision: Option, + /// Local unit and precision; scale-free frontends use the 1ps default. + pub time_scale: celox_design::TimeScale, pub name: String, pub variables: HashMap, pub ff_access_summaries: diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 2c7e800be86..eafc9fbf6eb 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -572,6 +572,11 @@ pub fn schedule_symbolic_rtl( root_id, packages, } = symbolic; + let time_precision = modules + .values() + .filter_map(|module| module.time_precision) + .min() + .unwrap_or_default(); let flatten_timing = trace_opts.phase_timing; macro_rules! timed_sub { ($label:expr, $body:expr) => {{ @@ -603,6 +608,10 @@ pub fn schedule_symbolic_rtl( instance_modules.insert(id, *module_id); package_instances.insert(*module_id, id); } + let instance_time_scales = instance_modules + .iter() + .map(|(&instance, module)| (instance, modules[module].time_scale)) + .collect::>(); let bindings = &PackageBindings::new(&instance_modules, &modules, &package_instances)?; let global_boundaries = timed_sub!( "propagate_boundaries", @@ -1479,6 +1488,8 @@ pub fn schedule_symbolic_rtl( .collect(); let watches: Vec> = { let event_kinds = ElaboratedDesign { + time_precision, + instance_time_scales: HashMap::default(), state_objects: state_objects.clone(), events: events.clone(), initial_state: Vec::new(), @@ -1546,6 +1557,8 @@ pub fn schedule_symbolic_rtl( let scheduled = ScheduledRtl { sir, design: ElaboratedDesign { + time_precision, + instance_time_scales, state_objects, events, initial_state, diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 10a5f1f5b66..02726a64765 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -723,7 +723,12 @@ fn lower_package_states( .into_iter() .enumerate() .map(|(index, module)| { - let lowered = lower_module(module, four_state, true, ff_parts)?; + let mut lowered = lower_module(module, four_state, true, ff_parts)?; + lowered.sim_module.time_precision = Some( + celox_design::TimePrecision::try_from(packages.global_time_precision()) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, + ); + lowered.sim_module.time_scale = scope_time_scale(packages, module.name())?; // Declaration initializers run before every `initial` block // (IEEE 1800-2023 10.5); one that is not folded into an initial // value would run among them. @@ -1791,12 +1796,35 @@ fn specialize_module( .iter() .find(|candidate| candidate.name() == module.name) .ok_or_else(|| sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)))?; - lower_module( + let mut lowered = lower_module( specialized, four_state, module.implicit_nets_allowed, ff_parts, - ) + )?; + lowered.sim_module.time_precision = Some( + celox_design::TimePrecision::try_from(module.packages.global_time_precision()) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, + ); + lowered.sim_module.time_scale = scope_time_scale(&module.packages, &module.name)?; + Ok(lowered) +} + +fn scope_time_scale( + packages: &sv::Packages, + name: &str, +) -> Result { + let Some((unit, precision)) = packages.scope_time_scale(name) else { + return Ok(celox_design::TimeScale::default()); + }; + let convert = |exponent: i32| { + celox_design::TimePrecision::try_from(exponent) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string())) + }; + Ok(celox_design::TimeScale { + unit: convert(unit)?, + precision: convert(precision)?, + }) } fn lower_module( @@ -2060,6 +2088,8 @@ fn lower_module_with_overrides( source: module.clone(), implicit_nets_allowed, sim_module: SimModule { + time_precision: None, + time_scale: celox_design::TimeScale::default(), name, variables: shared_variables, ff_access_summaries: HashMap::default(), diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 1c01f52e657..c6d129e7832 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -446,6 +446,8 @@ pub(crate) fn project_module_with_ids( Ok(( crate::symbolic::artifact::SimModule { + time_precision: None, + time_scale: celox_design::TimeScale::default(), name: veryl_parser::resource_table::get_str_value(module.name).unwrap_or_default(), variables, ff_access_summaries: module diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index e2d8ccccfc3..8778c3206cb 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -684,6 +684,7 @@ struct CachedBuild { state_schema: Arc, /// Pre-computed VCD signal descriptors so VCD works on cache hits. vcd_descs: Vec, + time_precision: celox_design::TimePrecision, /// Derived clock domains per event, valid for every backend sharing /// `shared_code`. derived_ticks: celox::DerivedTickPlans, @@ -1126,6 +1127,7 @@ impl NativeSimulatorHandle { let state_fingerprint = sim.state_fingerprint(); let state_schema = sim.state_schema(); let vcd_descs = sim.build_vcd_descs(four_state); + let time_precision = sim.program().design.time_precision; let runtime_errors = runtime_errors_by_name(sim.program()); let derived_ticks = sim.derived_tick_plans(); let event_edges = sim.event_edges(); @@ -1155,6 +1157,7 @@ impl NativeSimulatorHandle { state_fingerprint, state_schema: Arc::clone(&state_schema), vcd_descs: vcd_descs.clone(), + time_precision, derived_ticks: Arc::clone(&derived_ticks), event_edges: Arc::clone(&event_edges), }); @@ -1165,7 +1168,7 @@ impl NativeSimulatorHandle { // Create VcdWriter if requested let vcd_writer = if let Some(path) = vcd_path { Some( - celox::VcdWriter::new(path, &vcd_descs) + celox::VcdWriter::new_with_time_precision(path, &vcd_descs, time_precision) .map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?, ) } else { @@ -1261,8 +1264,12 @@ impl NativeSimulatorHandle { ))); let vcd_writer = if let Some(path) = vcd_path { Some( - celox::VcdWriter::new(path, &cached.vcd_descs) - .map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?, + celox::VcdWriter::new_with_time_precision( + path, + &cached.vcd_descs, + cached.time_precision, + ) + .map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?, ) } else { None @@ -4332,6 +4339,35 @@ mod tests { ); } + #[test] + fn cached_waveforms_retain_explicit_time_precision() { + let dir = tempfile::tempdir().unwrap(); + let source = "module CachedPrecision(y: output logic) {}"; + let sources = make_sources(&[(source, "cached_precision.veryl")]); + let key = build_cache_key(&sources, "CachedPrecision", &default_opts(), None); + let sim = celox::Simulator::builder(source, "CachedPrecision") + .vcd(dir.path().join("initial.vcd")) + .build() + .unwrap(); + let handle = NativeSimulatorHandle::build_and_cache(sim, None, Some(key.clone())).unwrap(); + drop(handle); + let mut cached = JIT_CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&key) + .unwrap(); + // A frontend with a non-default scale supplies this cached metadata. + Arc::get_mut(&mut cached).unwrap().time_precision = + celox_design::TimePrecision::try_from(-15).unwrap(); + let path = dir.path().join("cached.vcd"); + let mut handle = NativeSimulatorHandle::from_cached(&cached, path.to_str()).unwrap(); + handle.dump(123.0).unwrap(); + handle.vcd_writer.as_mut().unwrap().flush().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("$timescale 1fs $end"), "{text}"); + assert!(text.contains("#123\n")); + } + #[test] fn vcd_paths_share_compiled_code_but_tracing_modes_do_not() { let src = make_sources(&[("module Top {}", "a.veryl")]); diff --git a/crates/celox-runtime/src/reflection.rs b/crates/celox-runtime/src/reflection.rs index d29ea346a56..272f81c49b3 100644 --- a/crates/celox-runtime/src/reflection.rs +++ b/crates/celox-runtime/src/reflection.rs @@ -24,6 +24,7 @@ pub struct ReflectionScope { pub name: String, pub full_name: String, pub module_name: String, + pub time_scale: celox_design::TimeScale, pub parent: Option, pub children: Vec, pub signals: Vec, diff --git a/crates/celox-runtime/src/vcd.rs b/crates/celox-runtime/src/vcd.rs index 3046e51329e..e79e493bc1b 100644 --- a/crates/celox-runtime/src/vcd.rs +++ b/crates/celox-runtime/src/vcd.rs @@ -117,6 +117,7 @@ pub struct VcdWriter { descs: Vec, external_descs: Vec, timestamp: u64, + time_precision: celox_design::TimePrecision, header_written: bool, initial_values_written: bool, external_count: usize, @@ -137,14 +138,27 @@ struct VcdOutput { impl VcdWriter { pub fn new>(path: P, descs: &[VcdSignalDesc]) -> std::io::Result { - Ok(Self::from_writer(File::create(path)?, descs)) + Self::new_with_time_precision(path, descs, celox_design::TimePrecision::default()) + } + + /// Create a waveform whose timestamps use the design's global tick precision. + pub fn new_with_time_precision>( + path: P, + descs: &[VcdSignalDesc], + time_precision: celox_design::TimePrecision, + ) -> std::io::Result { + Ok(Self::from_writer_with_time_precision( + File::create(path)?, + descs, + time_precision, + )) } /// Finish the current file and continue the waveform, with the same /// signals, in a new file at `path`. The first dump there records every /// value, and its timestamps start over. pub fn restart>(&mut self, path: P) -> std::io::Result<()> { - let mut next = Self::new(path, &self.descs)?; + let mut next = Self::new_with_time_precision(path, &self.descs, self.time_precision)?; next.add_external_signals(&self.external_descs)?; self.flush()?; *self = next; @@ -154,6 +168,15 @@ impl VcdWriter { impl VcdWriter { pub fn from_writer(writer: W, descs: &[VcdSignalDesc]) -> Self { + Self::from_writer_with_time_precision(writer, descs, celox_design::TimePrecision::default()) + } + + /// Create a writer with an explicit physical duration for each timestamp tick. + pub fn from_writer_with_time_precision( + writer: W, + descs: &[VcdSignalDesc], + time_precision: celox_design::TimePrecision, + ) -> Self { let mut plan = TracePlan::default(); let mut groups: fxhash::FxHashMap> = Default::default(); let headers = descs @@ -187,6 +210,7 @@ impl VcdWriter { descs: descs.to_vec(), external_descs: Vec::new(), timestamp: 0, + time_precision, header_written: false, initial_values_written: false, external_count: 0, @@ -317,7 +341,8 @@ impl VcdWriter { writeln!(self.output.encoded, "$version")?; writeln!(self.output.encoded, " celox")?; writeln!(self.output.encoded, "$end")?; - writeln!(self.output.encoded, "$timescale 1ns $end")?; + let (magnitude, unit) = self.time_precision.vcd_timescale(); + writeln!(self.output.encoded, "$timescale {magnitude}{unit} $end")?; let mut scope_order = Vec::::new(); let mut scope_groups = Vec::>::new(); @@ -711,6 +736,33 @@ const BINARY: [[u8; 8]; 256] = { mod tests { use super::*; + #[test] + fn headers_encode_supported_time_precisions() { + for (exponent, expected) in [ + (2, "100s"), + (0, "1s"), + (-1, "100ms"), + (-5, "10us"), + (-9, "1ns"), + (-12, "1ps"), + (-14, "10fs"), + (-15, "1fs"), + ] { + let precision = celox_design::TimePrecision::try_from(exponent).unwrap(); + let mut writer = VcdWriter::from_writer_with_time_precision(Vec::new(), &[], precision); + writer.dump_with_external(123, &[], &[]).unwrap(); + writer.flush().unwrap(); + let output = std::str::from_utf8(writer.get_ref()).unwrap(); + assert!( + output.contains(&format!("$timescale {expected} $end")), + "{output}" + ); + assert!(output.contains("#123\n")); + } + assert!(celox_design::TimePrecision::try_from(-16).is_err()); + assert!(celox_design::TimePrecision::try_from(3).is_err()); + } + #[test] fn appended_external_signals_survive_restart() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index b8fdd765396..028e6256092 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -102,6 +102,16 @@ impl Package { } impl Packages { + /// Global simulation precision, as a power of ten seconds (IEEE 1800-2023 3.14.3). + pub fn global_time_precision(&self) -> i32 { + self.timescales.global_precision() + } + + /// Resolved local time unit and precision of a module or package. + pub fn scope_time_scale(&self, name: &str) -> Option<(i32, i32)> { + self.timescales.scope_scale(name) + } + pub fn is_empty(&self) -> bool { self.packages.is_empty() } diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 86daae84697..02070326ff1 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -523,6 +523,17 @@ pub(crate) fn generated_source_declarations( } impl Timescales { + pub(super) fn scope_scale(&self, name: &str) -> Option<(i32, i32)> { + let scope = self + .definitions + .get(name) + .or_else(|| self.packages.get(name))?; + Some((scope.scale.unit, scope.scale.precision)) + } + + pub(super) fn global_precision(&self) -> i32 { + self.precision.unwrap_or(DEFAULT.precision) + } fn including_tree(&self, tree: &SyntaxTree) -> Converted { let local = Self::collect(&[(tree, Path::new(""))])?; let specified = [ diff --git a/crates/celox-vpi/Cargo.toml b/crates/celox-vpi/Cargo.toml index df83e9a7ca9..b4ac5a08050 100644 --- a/crates/celox-vpi/Cargo.toml +++ b/crates/celox-vpi/Cargo.toml @@ -8,6 +8,9 @@ license.workspace = true description.workspace = true edition.workspace = true +[features] +systemverilog = ["celox/systemverilog"] + [lib] crate-type = ["rlib", "cdylib"] diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 9855acdd8a5..840c44090de 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -609,8 +609,9 @@ fn object_type(object: ObjectRef) -> i32 { /// /// `reference` must be a live handle returned by this library. pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { - if matches!(property, VPI_TIME_UNIT | VPI_TIME_PRECISION) { - return -12; + if reference.is_null() && matches!(property, VPI_TIME_UNIT | VPI_TIME_PRECISION) { + return with_runtime(|runtime| runtime.time_precision().exponent()) + .unwrap_or_else(|| celox_design::TimePrecision::default().exponent()); } if reference.is_null() { return 0; @@ -631,6 +632,23 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { return 0; }; match property { + VPI_TIME_UNIT | VPI_TIME_PRECISION => with_runtime(|runtime| { + let reflection = runtime.reflection(); + let scope = match object { + ObjectRef::Scope(id) => reflection.scope(id), + ObjectRef::Signal(id) => reflection + .signal(id) + .and_then(|signal| reflection.scope(signal.parent)), + }; + scope.map_or(0, |scope| { + if property == VPI_TIME_UNIT { + scope.time_scale.unit.exponent() + } else { + scope.time_scale.precision.exponent() + } + }) + }) + .unwrap_or(0), VPI_TYPE => object_type(object), VPI_TOP_MODULE => i32::from(object == ObjectRef::Scope(ReflectionScopeId(0))), VPI_SIZE | VPI_SCALAR | VPI_VECTOR | VPI_DIRECTION | VPI_SIGNED => { diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index cdd09849e68..7f9935e3042 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -2292,3 +2292,81 @@ fn finish_during_queued_edge_replay_stops_remaining_callbacks_and_edges() { } clear_runtime(); } + +#[cfg(feature = "systemverilog")] +#[test] +fn vpi_time_properties_follow_the_attached_design_precision() { + for (declarations, unit, expected) in [ + ("", -9, -12), + ("timeunit 1ns; timeprecision 1fs;", -9, -15), + ("timeunit 1us; timeprecision 100ns;", -6, -7), + ] { + let source = format!("module Top(output logic y); {declarations} endmodule"); + let sim = + Simulator::from_sv_sources(vec![(&source, std::path::Path::new("time.sv"))], "Top") + .build_native() + .unwrap(); + let bytes = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = celox::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + install_runtime(trusted_instance(image)); + unsafe { + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + assert_eq!(vpi_get(VPI_TIME_UNIT, ptr::null_mut()), expected); + assert_eq!(vpi_get(VPI_TIME_PRECISION, ptr::null_mut()), expected); + assert_eq!(vpi_get(VPI_TIME_UNIT, top), unit); + assert_eq!(vpi_get(VPI_TIME_PRECISION, top), expected); + vpi_free_object(top); + } + clear_runtime(); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn vpi_time_properties_preserve_module_scales_in_native_images() { + let source = r#" + `timescale 10ns / 1ps + module Top(output logic y); + Coarse coarse(); + Fine fine(); + endmodule + module Coarse(output logic value); + timeunit 1us; timeprecision 100ns; + endmodule + module Fine(output logic value); + timeunit 1ns; timeprecision 1fs; + endmodule + "#; + let sim = Simulator::from_sv_sources(vec![(source, std::path::Path::new("scales.sv"))], "Top") + .build_native() + .unwrap(); + let bytes = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = celox::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + install_runtime(trusted_instance(image)); + unsafe { + assert_eq!(vpi_get(VPI_TIME_UNIT, ptr::null_mut()), -15); + assert_eq!(vpi_get(VPI_TIME_PRECISION, ptr::null_mut()), -15); + for (name, unit, precision) in [ + (c"Top", -8, -12), + (c"Top.coarse", -6, -7), + (c"Top.coarse.value", -6, -7), + (c"Top.fine", -9, -15), + (c"Top.fine.value", -9, -15), + ] { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!handle.is_null(), "{name:?}"); + assert_eq!(vpi_get(VPI_TIME_UNIT, handle), unit, "{name:?}"); + assert_eq!(vpi_get(VPI_TIME_PRECISION, handle), precision, "{name:?}"); + vpi_free_object(handle); + } + } + clear_runtime(); +} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 2267bf7793f..e336bfe84e9 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -427,6 +427,11 @@ pub struct NativeProgramImage { } impl NativeProgramImage { + /// Physical duration of one tick, retained in serialized native images. + pub fn time_precision(&self) -> celox_design::TimePrecision { + self.design.time_precision + } + /// Remap filesystem paths in the image's runtime and diagnostic metadata. /// This permits relative paths in stored artifacts and rebinding on load. /// Machine code and design-authored literal strings are not modified. diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index f68a8012e79..c2808088fe9 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 13; +const CONTAINER_VERSION: u16 = 14; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 7dfdf72d48e..3d7f0ce06ac 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -103,6 +103,11 @@ impl NativeProgramInstance { unsafe { Self::from_image(appended.image) } } + /// Physical duration of one tick in the attached design. + pub fn time_precision(&self) -> celox_design::TimePrecision { + self.shared.program_image().time_precision() + } + /// Elaborated hierarchy and signal metadata embedded by the compiler. pub fn reflection(&self) -> &DesignReflection { self.shared.program_image().reflection() diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 3f2b06e1fe5..5f93ce300f2 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -913,6 +913,12 @@ impl RuntimeProgram { name: scope.name.clone(), full_name: scope.full_name.clone(), module_name: scope.module_name.clone(), + time_scale: self + .design + .instance_time_scales + .get(&scope.instance_id) + .copied() + .unwrap_or_default(), parent: scope.parent_name.as_ref().map(|parent| scope_ids[parent]), children: Vec::new(), signals: Vec::new(), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index ba64dbdfa88..1f41e0594ac 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1343,8 +1343,12 @@ mod host { ))); } let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } let apply_initial_start = options.diagnostics.phase_timing.then(crate::timing::now); @@ -2328,8 +2332,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2370,8 +2378,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2416,8 +2428,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2476,8 +2492,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2671,8 +2691,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -3027,8 +3051,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); diff --git a/crates/celox/tests/time_precision.rs b/crates/celox/tests/time_precision.rs new file mode 100644 index 00000000000..15280c2b3d8 --- /dev/null +++ b/crates/celox/tests/time_precision.rs @@ -0,0 +1,127 @@ +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +use celox::{SimBackend, Simulator, SimulatorBuilder}; + +fn check_vcd(mut sim: Simulator, path: &Path, expected: &str) { + let signal = sim.signal("y"); + sim.modify(|io| io.set(signal, 1u8)).unwrap(); + sim.dump(123); + sim.flush_vcd().unwrap(); + let first = std::fs::read_to_string(path).unwrap(); + assert!( + first.contains(&format!("$timescale {expected} $end")), + "{first}" + ); + assert!( + first.contains("#123\n"), + "timestamps must remain global ticks" + ); + let next = path.with_extension("next.vcd"); + sim.switch_vcd(&next).unwrap(); + sim.dump(130); + sim.flush_vcd().unwrap(); + assert!( + std::fs::read_to_string(next) + .unwrap() + .contains(&format!("$timescale {expected} $end")) + ); +} + +fn check_backends<'source>( + build: impl Fn(&Path) -> SimulatorBuilder<'source, Simulator>, + expected: &str, +) { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("wave.vcd"); + check_vcd(build(&path).build_native().unwrap(), &path, expected); + check_vcd(build(&path).build_cranelift().unwrap(), &path, expected); + check_vcd(build(&path).build_wasm().unwrap(), &path, expected); + check_vcd(build(&path).build_interpreter().unwrap(), &path, expected); + check_vcd(build(&path).build_tiered().unwrap(), &path, expected); + check_vcd( + build(&path) + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_native() + .unwrap(), + &path, + expected, + ); + check_vcd( + build(&path) + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_cranelift() + .unwrap(), + &path, + expected, + ); +} + +#[test] +fn sv_waveforms_use_global_precision_across_backends() { + for (declarations, expected) in [ + ("", "1ps"), + ("timeunit 1ns; timeprecision 1fs;", "1fs"), + ("timeunit 1us; timeprecision 100ns;", "100ns"), + ] { + let source = format!("module Top(output logic y); {declarations} endmodule"); + check_backends( + |path| { + Simulator::from_sv_sources(vec![(&source, Path::new("top.sv"))], "Top").vcd(path) + }, + expected, + ); + } +} + +#[test] +fn package_precision_is_retained_by_native_images() { + let source = "package P; timeunit 1ns; timeprecision 10fs; endpackage + module Top(output logic y); timeunit 1ns; timeprecision 1ps; endmodule"; + let build = |path: &Path| { + Simulator::from_sv_sources(vec![(source, Path::new("packages.sv"))], "Top").vcd(path) + }; + check_backends(build, "10fs"); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("image.vcd"); + let image = build(&path).compile_native().unwrap().into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + assert_eq!(image.time_precision().exponent(), -14); + let sim = Simulator::from_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(image) + .unwrap(); + check_vcd(sim, &path, "10fs"); +} + +#[test] +fn veryl_waveforms_use_the_default_picosecond_tick() { + let source = "module Top(y: output logic) {}"; + check_backends(|path| Simulator::builder(source, "Top").vcd(path), "1ps"); +} + +#[test] +fn mixed_designs_keep_sv_precision_through_the_veryl_frontend() { + let veryl = "module Top(y: output logic) { inst child: $sv::Child (y); }"; + for (precision, expected) in [("1fs", "1fs"), ("100ns", "100ns")] { + let sv = format!( + "module Child(output logic y); timeunit 1us; timeprecision {precision}; assign y = 1; endmodule" + ); + check_backends( + |path| { + Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(&sv, Path::new("child.sv"))], + "Top", + ) + .vcd(path) + }, + expected, + ); + } +} diff --git a/docs/guide/writing-tests.md b/docs/guide/writing-tests.md index 986ac088860..ea59203ad16 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -100,6 +100,15 @@ and a falling one. ## Time-Based Simulation +Simulation timestamps and clock periods count global-precision ticks. Veryl +uses 1ps per tick. SystemVerilog uses the design's global time precision +(default 1ps). VCD headers and VPI time properties queried with a NULL handle +use that global precision. VPI queries on a module or its signals return the +module's own time unit and precision. +Existing Veryl VCD exports now declare 1ps instead of 1ns; their numeric +timestamps are unchanged. Native images compiled before this change must be +recompiled for the updated container format. + `Simulation` manages clock generation for you. This is the natural choice for sequential logic with clocked flip-flops. ```typescript diff --git a/docs/ja/guide/writing-tests.md b/docs/ja/guide/writing-tests.md index 08e05c0c2c2..23152ebf14b 100644 --- a/docs/ja/guide/writing-tests.md +++ b/docs/ja/guide/writing-tests.md @@ -61,6 +61,15 @@ module Reg ( ## タイムベースシミュレーション +時刻やクロック周期は global precision の tick 数です。Veryl は 1 tick = 1ps、 +SystemVerilog は設計の global time precision(既定は 1ps)を使用します。 +VCD のヘッダーと NULL ハンドルで問い合わせた VPI の時刻プロパティは、 +この全体の精度を示します。モジュールや信号のハンドルを指定した VPI の問い合わせは、 +そのモジュール自身の時間単位と精度を返します。 +Veryl の既存 VCD 出力は数値のタイムスタンプを保ったまま、宣言を 1ns から +1ps に変更します。ネイティブイメージの形式も更新するため、既存イメージは +再コンパイルしてください。 + `Simulation` はクロック生成を自動的に管理します。クロック付きフリップフロップを持つ順序回路に適しています。 ```typescript diff --git a/packages/playground/src/waveform-viewer.ts b/packages/playground/src/waveform-viewer.ts index d7c192621f2..52421f42be2 100644 --- a/packages/playground/src/waveform-viewer.ts +++ b/packages/playground/src/waveform-viewer.ts @@ -51,7 +51,7 @@ export function generateVcdText(trace: VcdTrace): string { const L: string[] = []; L.push("$date", ` ${new Date().toISOString()}`, "$end"); L.push("$version celox-playground $end"); - L.push("$timescale 1ns $end"); + L.push("$timescale 1ps $end"); L.push("$scope module top $end"); const ids = trace.signals.map((_, i) => vcdId(i)); for (let i = 0; i < trace.signals.length; i++) { diff --git a/packages/playground/test/waveform-viewer.test.ts b/packages/playground/test/waveform-viewer.test.ts new file mode 100644 index 00000000000..bb943165e74 --- /dev/null +++ b/packages/playground/test/waveform-viewer.test.ts @@ -0,0 +1,8 @@ +import { expect, test } from "vitest"; +import { generateVcdText } from "../src/waveform-viewer"; + +test("downloaded Veryl waveforms use picosecond simulation ticks", () => { + const text = generateVcdText({ signals: [{ name: "y", width: 1 }], snapshots: [{ timestamp: 123, values: [1n] }] }); + expect(text).toContain("$timescale 1ps $end"); + expect(text).toContain("#123\n"); +});