From 73bcc1acf90661995616bb3c6c19cd108d9b6bba Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:34:24 +0900 Subject: [PATCH 1/7] fix(sv)!: name Veryl declarations by their emitted SV names In a mixed design, SV referred to Veryl modules and interfaces by their Veryl source names, while the Veryl emitter names them `_` (or `` with `omit_project_prefix`). SV written against the emitted code did not link, and SV written for Celox did not build with other tools. SV now sees Veryl declarations only by their emitted names: declaration contracts, interface bindings and foreign roots use them, and the hierarchy linker maps each emitted name back to its Veryl body instead of matching names, so an SV module and an emitted Veryl name no longer shadow each other. An SV module named like an emitted Veryl module is reported as a duplicate. A Veryl top is still selected by its Veryl name, and instances keep Veryl module names. Validation: - cargo test -p celox -p celox-frontend-veryl --features celox/systemverilog --lib --test systemverilog - cargo clippy -p celox -p celox-frontend-veryl --all-targets --features celox/systemverilog --no-deps - cargo fmt --all -- --check - New mixed tests cover a custom project prefix, omit_project_prefix, rejection of source names, and emitted-name collisions BREAKING CHANGE: SV sources in a mixed design must instantiate Veryl modules and interfaces by their emitted names, such as `prj_Child`, instead of `Child`. parse_ir_with_external_hierarchy_and_native_modules takes a map from external module names to Veryl module names instead of a name set. Change-Id: Ib464695577c60ea747f010607b3bebf6671b2805 --- crates/celox-frontend-veryl/src/artifact.rs | 13 +- crates/celox-frontend-veryl/src/hierarchy.rs | 21 ++- crates/celox/src/parser.rs | 51 +++++-- crates/celox/src/simulator/builder.rs | 6 +- crates/celox/src/simulator/mixed.rs | 99 +++++++++---- .../tests/frontends/systemverilog/mixed.rs | 140 ++++++++++++++---- docs/guide/systemverilog.md | 10 +- docs/ja/guide/systemverilog.md | 6 +- 8 files changed, 257 insertions(+), 89 deletions(-) diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 1c01f52e657..597abeb4e3d 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -83,6 +83,8 @@ pub fn external_signatures( ExternalModule { sim_module, port_order, + // Veryl children link through the IR; only SV children are + // left for the SV frontend to resolve by name. unresolved_instances: module .declarations .iter() @@ -90,12 +92,13 @@ pub fn external_signatures( let veryl_analyzer::ir::Declaration::Inst(instance) = declaration else { return None; }; - let name = match instance.component.as_ref() { - Component::Module(module) => module.name, - Component::SystemVerilog(module) => module.name, - Component::Interface(_) => return None, + let Component::SystemVerilog(module) = instance.component.as_ref() else { + return None; }; - Some(veryl_parser::resource_table::get_str_value(name).unwrap_or_default()) + Some( + veryl_parser::resource_table::get_str_value(module.name) + .unwrap_or_default(), + ) }) .collect(), }, diff --git a/crates/celox-frontend-veryl/src/hierarchy.rs b/crates/celox-frontend-veryl/src/hierarchy.rs index b8da652c4e1..694584c8271 100644 --- a/crates/celox-frontend-veryl/src/hierarchy.rs +++ b/crates/celox-frontend-veryl/src/hierarchy.rs @@ -48,13 +48,15 @@ pub fn parse_ir_with_external_hierarchy<'a>( } /// Link the explicitly identified Veryl exports without matching SV namesakes. +/// `native_modules` maps each external module name that stands for a Veryl +/// body to the name of that body in `ir`. pub fn parse_ir_with_external_hierarchy_and_native_modules<'a>( ir: &'a veryl_analyzer::ir::Ir, loop_provenance: &LoopProvenance, external: &'a ExternalHierarchy, config: &BuildConfig, top: &StrId, - native_modules: &HashSet, + native_modules: &HashMap, ) -> Result, ParserError> { parse_external_hierarchy( ir, @@ -72,7 +74,7 @@ fn parse_external_hierarchy<'a>( external: &'a ExternalHierarchy, config: &BuildConfig, top: &StrId, - native_modules: Option<&HashSet>, + native_modules: Option<&HashMap>, ) -> Result, ParserError> { // Token-to-scope resolution uses process-global analyzer state and is not // safe while independent compilations run on other test threads. Snapshot @@ -116,7 +118,7 @@ fn parse_external_hierarchy<'a>( let top_name = resource_table::get_str_value(*top).unwrap_or_default(); let root_ir = name_to_ir.get(top).copied(); let external_root = external.roots.get(&top_name).copied().filter(|_| { - root_ir.is_none() || native_modules.is_none_or(|names| names.contains(&top_name)) + root_ir.is_none() || native_modules.is_none_or(|names| names.contains_key(&top_name)) }); if root_ir.is_none() && external_root.is_none() { return Err(ParserError::TopNotFound { name: top_name }); @@ -172,11 +174,18 @@ fn parse_external_hierarchy<'a>( binding.package = external_ids[&binding.package]; } module_names.insert(global_id, external_module.sim_module.name.clone()); - let native_name = resource_table::insert_str(&external_module.sim_module.name); - if let Some(&native_module) = name_to_ir.get(&native_name) - && native_modules.is_none_or(|names| names.contains(&external_module.sim_module.name)) + let native_name = match native_modules { + Some(names) => names.get(&external_module.sim_module.name).copied(), + None => Some(resource_table::insert_str(&external_module.sim_module.name)), + }; + if let Some(native_name) = native_name + && let Some(&native_module) = name_to_ir.get(&native_name) && !module_ir.contains_key(&global_id) { + module_names.insert( + global_id, + resource_table::get_str_value(native_name).unwrap_or_default(), + ); module_ir.insert(global_id, native_module); signature_to_id.insert(native_module.signature.clone(), global_id); worklist.push((global_id, native_module)); diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 4a4c4eda6de..493a8d0ead4 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -662,6 +662,7 @@ pub fn parse_mixed( requests: &[celox_frontend_sv::SvModuleRequest], sv_interfaces: &[celox_frontend_sv::InterfaceSignature], used_names: &mut fxhash::FxHashSet, + names: crate::simulator::mixed::EmittedNames, config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), @@ -699,8 +700,23 @@ pub fn parse_mixed( external_roots.insert(top_name.clone()); } let mut foreign = celox_frontend_veryl::external_signatures(ir, config)?; - let authored = celox_frontend_sv::module_interfaces(sv_sources).map_err(sv_analysis_error)?; - foreign.roots.retain(|name, _| !authored.contains_key(name)); + // SV instantiates a Veryl module by its emitted name. The linker binds + // that name back to the Veryl body; an SV module declaring the same name + // is a duplicate the SV analyzer reports. + let mut native_modules = crate::HashMap::default(); + let mut roots = std::mem::take(&mut foreign.roots); + for component in &ir.components { + let veryl_analyzer::ir::Component::Module(module) = component else { + continue; + }; + let Some(id) = roots.remove(&module.name.to_string()) else { + continue; + }; + let emitted = names.module(module); + foreign.modules.get_mut(&id).unwrap().sim_module.name = emitted.clone(); + foreign.roots.insert(emitted.clone(), id); + native_modules.insert(emitted, module.name); + } let sv_top_parameters = (!native_top).then_some((top_name.as_str(), top_parameters)); let base = ir.clone(); let mut specializations = Vec::new(); @@ -743,8 +759,19 @@ pub fn parse_mixed( )); } let mut prepare = || -> Result<_, ParserError> { + let native = native_modules.get(name).ok_or_else(|| { + ParserError::illegal_context( + "foreign module specialization", + format!("`{name}` is not a Veryl module"), + None, + ) + })?; let module = crate::simulator::mixed::specialize_foreign_module( - &base, context, name, parameters, used_names, + &base, + context, + &native.to_string(), + parameters, + used_names, )?; let mut specialized = veryl_analyzer::ir::Ir { components: vec![veryl_analyzer::ir::Component::Module(module)], @@ -767,6 +794,7 @@ pub fn parse_mixed( &joint_sources, context, used_names, + names, )?; let exported = celox_frontend_veryl::external_signatures(&specialized, config)?; let signature = exported.modules.values().next().cloned().ok_or_else(|| { @@ -818,17 +846,12 @@ pub fn parse_mixed( .map(|source| (source, std::path::PathBuf::from(""))), ); }; - ir.components.extend(specializations); - let mut native_modules = foreign.roots.keys().cloned().collect::>(); - native_modules.extend(ir.components.iter().filter_map(|component| { - if let veryl_analyzer::ir::Component::Module(module) = component - && !authored.contains_key(&module.name.to_string()) - { - Some(module.name.to_string()) - } else { - None + for component in &specializations { + if let veryl_analyzer::ir::Component::Module(module) = component { + native_modules.insert(module.name.to_string(), module.name); } - })); + } + ir.components.extend(specializations); parse_with_external_hierarchy( top, ir, @@ -856,7 +879,7 @@ pub fn parse_with_external_hierarchy( ir: &veryl_analyzer::ir::Ir, loop_provenance: &loop_provenance::LoopProvenance, external: &celox_frontend_core::symbolic::artifact::ExternalHierarchy, - native_modules: Option<&HashSet>, + native_modules: Option<&crate::HashMap>, config: &BuildConfig, ignored_loops: &[( (Vec<(String, usize)>, Vec), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index ba64dbdfa88..80b636b6991 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -497,7 +497,8 @@ fn analyze( { if let Some(sv_sources) = sv_sources { (|| { - let mut used_names = super::mixed::component_names(sv_sources)?; + let names = super::mixed::EmittedNames::new(&metadata); + let mut used_names = super::mixed::component_names(sv_sources, names)?; let behavior_sources = super::mixed::attach_sv_interface_behavior( &mut ir, &sv_interface_signatures, @@ -515,12 +516,14 @@ fn analyze( &joint_sources, &mut context, &mut used_names, + names, )?; let declarations = super::mixed::sv_declaration_contracts( &ir, &mut context, &joint_sources, &requests, + names, )?; parser::parse_mixed( &top, @@ -536,6 +539,7 @@ fn analyze( &requests, &sv_interface_signatures, &mut used_names, + names, &build_config, ignored_loops, true_loops, diff --git a/crates/celox/src/simulator/mixed.rs b/crates/celox/src/simulator/mixed.rs index ab2592c6331..d63f2c522b5 100644 --- a/crates/celox/src/simulator/mixed.rs +++ b/crates/celox/src/simulator/mixed.rs @@ -19,17 +19,54 @@ fn fresh_name(prefix: &str, used: &mut fxhash::FxHashSet, next: &mut usi } } +/// SystemVerilog sees Veryl declarations by the names the Veryl emitter gives +/// them, so SV written against the emitted code links unchanged. +#[derive(Clone, Copy)] +pub(crate) struct EmittedNames { + project: veryl_parser::resource_table::StrId, + omit_project_prefix: bool, +} + +impl EmittedNames { + pub(crate) fn new(metadata: &veryl_metadata::Metadata) -> Self { + Self { + project: veryl_parser::resource_table::insert_str(&metadata.project.name), + omit_project_prefix: metadata.build.omit_project_prefix, + } + } + + /// The emitted name of a top-level declaration. SV declarations seen + /// through `$sv` keep their own names. + pub(crate) fn symbol(&self, symbol: &veryl_analyzer::symbol::Symbol) -> String { + let name = symbol.token.text.to_string(); + let Some(&project) = symbol.namespace.paths.first() else { + return name; + }; + let project_text = project.to_string(); + if project_text == "$sv" || (self.omit_project_prefix && project == self.project) { + return name; + } + format!("{project_text}_{name}").replace("$std_", "__std_") + } + + pub(crate) fn module(&self, module: &veryl_analyzer::ir::Module) -> String { + veryl_analyzer::symbol_table::get(module.signature.symbol) + .map(|symbol| self.symbol(&symbol)) + .unwrap_or_else(|| module.name.to_string()) + } +} + pub(super) fn component_names( sources: &[(&str, &std::path::Path)], + names: EmittedNames, ) -> Result, ParserError> { - let mut names = + let mut used = celox_frontend_sv::component_names(sources).map_err(crate::parser::sv_analysis_error)?; - names.extend( - veryl_analyzer::symbol_table::get_all() - .iter() - .map(|symbol| symbol.token.text.to_string()), - ); - Ok(names) + for symbol in veryl_analyzer::symbol_table::get_all() { + used.insert(symbol.token.text.to_string()); + used.insert(names.symbol(&symbol)); + } + Ok(used) } pub(super) fn referenced_sv_components<'a>( @@ -942,6 +979,7 @@ pub(super) fn sv_declaration_contracts( context: &mut veryl_analyzer::Context, sources: &[(&str, &std::path::Path)], requests: &[celox_frontend_sv::SvModuleRequest], + names: EmittedNames, ) -> Result { use veryl_analyzer::{ ir::{Component, Signature, TypeKind, VarKind}, @@ -962,18 +1000,12 @@ pub(super) fn sv_declaration_contracts( })); for component in &ir.components { if let Component::Module(module) = component - && referenced.contains(&module.name.to_string()) - && !authored.contains_key(&module.name.to_string()) + && referenced.contains(&names.module(module)) { for (ty, _) in module.port_types.values() { if let TypeKind::Modport(signature, _) = &ty.kind { - needed_interfaces.insert( - symbol_table::get(signature.symbol) - .unwrap() - .token - .text - .to_string(), - ); + needed_interfaces + .insert(names.symbol(&symbol_table::get(signature.symbol).unwrap())); } } } @@ -987,7 +1019,8 @@ pub(super) fn sv_declaration_contracts( if symbol.namespace.to_string() == "$sv" || property.is_proto { continue; } - if !needed_interfaces.contains(&symbol.token.text.to_string()) { + let name = names.symbol(symbol); + if !needed_interfaces.contains(&name) { continue; } let signature = Signature::new(symbol.id); @@ -1003,7 +1036,7 @@ pub(super) fn sv_declaration_contracts( continue; }; let parameters = sv_parameters(&property.parameters, &interface.variables, context)?; - source.push_str(&format!("interface {}{parameters};\n", symbol.token.text)); + source.push_str(&format!("interface {name}{parameters};\n")); let mut variables = interface.variables.values().collect::>(); variables.sort_by_key(|variable| variable.id); for variable in variables { @@ -1055,9 +1088,10 @@ pub(super) fn sv_declaration_contracts( let Component::Module(module) = component else { continue; }; - if !referenced.contains(&module.name.to_string()) - || authored.contains_key(&module.name.to_string()) - { + let emitted = names.module(module); + // An authored SV module of the same name is a duplicate definition; + // the SV analyzer reports it when the foreign roots are linked. + if !referenced.contains(&emitted) || authored.contains_key(&emitted) { continue; } if module @@ -1067,9 +1101,10 @@ pub(super) fn sv_declaration_contracts( { continue; } - let Some(symbol) = symbols.iter().find(|symbol| { - symbol.token.text == module.name && matches!(symbol.kind, SymbolKind::Module(_)) - }) else { + let Some(symbol) = symbols + .iter() + .find(|symbol| symbol.id == module.signature.symbol) + else { continue; }; let SymbolKind::Module(property) = &symbol.kind else { @@ -1086,7 +1121,7 @@ pub(super) fn sv_declaration_contracts( let interface = symbol_table::get(signature.symbol).unwrap(); ports.push(format!( "{}.{modport} {name}{}", - interface.token.text, + names.symbol(&interface), sv_array(ty) )); } else if let Some(id) = module.ports.get(&path) { @@ -1106,8 +1141,7 @@ pub(super) fn sv_declaration_contracts( } let parameters = sv_parameters(&property.parameters, &module.variables, context)?; source.push_str(&format!( - "module {}{parameters}({}); endmodule\n", - module.name, + "module {emitted}{parameters}({}); endmodule\n", ports.join(", ") )); } @@ -1339,6 +1373,7 @@ pub(crate) fn specialize_sv_instances( sources: &[(&str, &std::path::Path)], context: &mut veryl_analyzer::Context, used_names: &mut fxhash::FxHashSet, + names: EmittedNames, ) -> Result, ParserError> { use veryl_analyzer::{ir::*, symbol::SymbolKind, symbol_table}; use veryl_parser::resource_table; @@ -1374,6 +1409,7 @@ pub(crate) fn specialize_sv_instances( requests: &mut Vec, used_names: &mut fxhash::FxHashSet, next_alias: &mut usize, + names: EmittedNames, ) -> Result<(), ParserError> { let mut evaluation = veryl_analyzer::Context::default(); evaluation.inherit(context); @@ -1398,7 +1434,9 @@ pub(crate) fn specialize_sv_instances( continue; }; if let Component::Module(child) = std::sync::Arc::make_mut(&mut instance.component) { - walk(child, interfaces, context, requests, used_names, next_alias)?; + walk( + child, interfaces, context, requests, used_names, next_alias, names, + )?; continue; } let Component::SystemVerilog(component) = instance.component.as_ref() else { @@ -1513,7 +1551,7 @@ pub(crate) fn specialize_sv_instances( }; signature.normalize(); let symbol = symbol_table::get(signature.symbol).unwrap(); - bindings.push((formal.clone(), symbol.token.text.to_string())); + bindings.push((formal.clone(), names.symbol(&symbol))); for (name, value) in &signature.parameters { let ValueVariant::Numeric(value) = value else { return Err(unsupported("foreign interface type parameter")); @@ -1552,6 +1590,7 @@ pub(crate) fn specialize_sv_instances( &mut requests, used_names, &mut next_alias, + names, )?; } } @@ -1940,7 +1979,7 @@ mod tests { let mut sibling = child.clone(); sibling.name = resource_table::insert_str("__sv_logic_bus_0"); module.declarations.push(Declaration::Inst(sibling)); - let mut names = component_names(&sources).unwrap(); + let mut names = component_names(&sources, EmittedNames::new(&metadata)).unwrap(); let generated = attach_sv_interface_behavior(&mut ir, &signatures, &mut context, &mut names).unwrap(); assert_eq!(generated.len(), 1); diff --git a/crates/celox/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index 1aa8d1bb4b0..fa62b1055ba 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -15,7 +15,7 @@ sv_backends! { fn reserves_authored_interface_names_for_generated_modules(sim) { @setup { let veryl = "module Child #(param K: u32 = 1)(a: input logic<8>, y: output logic<8>) { inst bus: $sv::Bus; assign bus.req = a; assign y = bus.rsp + K; }"; - let sv = "interface __celox_sv_interface_0; logic x; endinterface interface __celox_foreign_Child_0; logic x; endinterface interface Bus; logic [7:0] req, rsp; assign rsp = req + 1; endinterface module Top(input logic [7:0] a, output logic [7:0] y); Child #(.K(3)) child(a,y); endmodule"; + let sv = "interface __celox_sv_interface_0; logic x; endinterface interface __celox_foreign_Child_0; logic x; endinterface interface Bus; logic [7:0] req, rsp; assign rsp = req + 1; endinterface module Top(input logic [7:0] a, output logic [7:0] y); prj_Child #(.K(3)) child(a,y); endmodule"; } @build Simulator::from_mixed_sources(vec![(veryl, Path::new("child.veryl"))], vec![(sv, Path::new("top.sv"))], "Top"); let a = sim.signal("a"); @@ -49,7 +49,7 @@ sv_backends! { fn resolves_veryl_interface_parameter_types_after_prior_overrides(sim) { @setup { let veryl = "interface Bus #(param W: u32 = 8, param V: logic = 4) { var req: logic; var rsp: logic; modport slave { req: input, rsp: output, } } module Child(bus: modport Bus::slave) { assign bus.rsp = bus.req; }"; - let sv = "module Top(input logic [259:0] a, output logic [259:0] y); Bus #(.V(16'd260), .W(16)) bus(); assign bus.req = a; Child child(.bus(bus)); assign y = bus.rsp; endmodule"; + let sv = "module Top(input logic [259:0] a, output logic [259:0] y); prj_Bus #(.V(16'd260), .W(16)) bus(); assign bus.req = a; prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule"; } @build Simulator::from_mixed_sources(vec![(veryl, Path::new("bus.veryl"))], vec![(sv, Path::new("top.sv"))], "Top"); let a = sim.signal("a"); @@ -81,7 +81,7 @@ sv_backends! { } module Child(bus: modport Bus::slave) { assign bus.rsp = bus.req + 1; } "#; - let sv = "module Top(input logic [31:0] a, output logic [31:0] y); Bus #(.W(16)) bus(); assign bus.req = a; Child child(.bus(bus)); assign y = bus.rsp; endmodule"; + let sv = "module Top(input logic [31:0] a, output logic [31:0] y); prj_Bus #(.W(16)) bus(); assign bus.req = a; prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("bus.veryl"))], vec![(sv, Path::new("top.sv"))], "Top", @@ -108,7 +108,7 @@ sv_backends! { let sv = r#" module Top(output logic [255:0] y, negative); localparam logic [127:0] HIGH = 128'h8000_0000_0000_0000_0000_0000_0000_0001; - Child #(.K(HIGH), .S(-128'sd1)) child(.y(y), .negative(negative)); + prj_Child #(.K(HIGH), .S(-128'sd1)) child(.y(y), .negative(negative)); endmodule "#; } @@ -183,7 +183,7 @@ sv_backends! { let sv = r#" module Top(input logic [7:0] a, output logic [7:0] y); timeunit 1ns; timeprecision 1ps; - Child child(.a(a), .y(y)); + prj_Child child(.a(a), .y(y)); endmodule "#; } @@ -266,7 +266,7 @@ sv_backends! { assign y = a + 42; endmodule module Top(input logic [7:0] a, output logic [7:0] specialized, authored); - Child #(.K(5)) child(.a(a), .y(specialized)); + prj_Child #(.K(5)) child(.a(a), .y(specialized)); __celox_foreign_Child_0 other(.a(a), .y(authored)); endmodule "#; @@ -302,8 +302,8 @@ sv_backends! { assign y = a + W; endmodule module Top(input logic [15:0] a, output logic [15:0] y, output logic [7:0] narrow); - Mid #(.W(16)) wide(.a(a), .y(y)); - Mid normal(.a(a[7:0]), .y(narrow)); + prj_Mid #(.W(16)) wide(.a(a), .y(y)); + prj_Mid normal(.a(a[7:0]), .y(narrow)); endmodule "#; } @@ -325,8 +325,8 @@ sv_backends! { assign rsp = req + W; endinterface module Top(input logic [15:0] a, output logic [15:0] y, output logic [7:0] narrow); - Mid #(.W(16)) wide(.a(a), .y(y)); - Mid normal(.a(a[7:0]), .y(narrow)); + prj_Mid #(.W(16)) wide(.a(a), .y(y)); + prj_Mid normal(.a(a[7:0]), .y(narrow)); endmodule "#; } @@ -356,8 +356,8 @@ sv_backends! { let sv = r#" module Leaf(interface bus); assign bus.rsp = bus.req + bus.W; endmodule module Top(input logic [15:0] a, output logic [15:0] y, output logic [7:0] narrow); - Mid #(.W(16)) wide(.a(a), .y(y)); - Mid normal(.a(a[7:0]), .y(narrow)); + prj_Mid #(.W(16)) wide(.a(a), .y(y)); + prj_Mid normal(.a(a[7:0]), .y(narrow)); endmodule "#; } @@ -382,14 +382,14 @@ sv_backends! { "#; let sv = r#" module Hop #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); - Final #(.W(W)) child(.a(a), .y(y)); + prj_Final #(.W(W)) child(.a(a), .y(y)); endmodule module Leaf #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); assign y = a + W; endmodule module Top(input logic [31:0] a, output logic [31:0] y, output logic [15:0] narrow); - Mid #(.W(32)) wide(.a(a), .y(y)); - Mid #(.W(16)) other(.a(a[15:0]), .y(narrow)); + prj_Mid #(.W(32)) wide(.a(a), .y(y)); + prj_Mid #(.W(16)) other(.a(a[15:0]), .y(narrow)); endmodule "#; } @@ -438,7 +438,7 @@ sv_backends! { "#; let sv = r#" module Top(output logic [127:0] negative, output logic [95:0] positive); - Child #(.NEG(-128'sd1), .HIGH(96'h1_0000_0000_0000_0001)) child(.negative(negative), .positive(positive)); + prj_Child #(.NEG(-128'sd1), .HIGH(96'h1_0000_0000_0000_0001)) child(.negative(negative), .positive(positive)); endmodule "#; } @@ -495,7 +495,7 @@ sv_backends! { module Child #(param W: u32 = 8, param N: u32 = W * 2, param C: u32 = Defaults::increment()) (a: input logic, y: output logic) { assign y = a + C; } "#; - let sv = "module Top(input logic [31:0] a, output logic [31:0] y); Child #(.W(16)) child(.a(a), .y(y)); endmodule"; + let sv = "module Top(input logic [31:0] a, output logic [31:0] y); prj_Child #(.W(16)) child(.a(a), .y(y)); endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("child.veryl"))], vec![(sv, Path::new("top.sv"))], "Top", @@ -516,9 +516,9 @@ sv_backends! { "#; let sv = r#" module Top(input logic [31:0] a, output logic [31:0] y); - Bus #(.W(16)) bus(); + prj_Bus #(.W(16)) bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -573,7 +573,7 @@ sv_backends! { fn overrides_parameters_of_a_systemverilog_top_in_a_mixed_design(sim) { @setup { let veryl = "module Child (a: input logic<16>, y: output logic<16>) { assign y = a + 1; }"; - let sv = "module Top #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); Child child(.a(a), .y(y)); endmodule"; + let sv = "module Top #(parameter W = 8)(input logic [W-1:0] a, output logic [W-1:0] y); prj_Child child(.a(a), .y(y)); endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("child.veryl"))], @@ -668,7 +668,7 @@ sv_backends! { "#; let sv = r#" module Top(input logic [15:0] a, output logic [15:0] y); - Child #(.W(16)) child(.a(a), .y(y)); + prj_Child #(.W(16)) child(.a(a), .y(y)); endmodule "#; } @@ -696,7 +696,7 @@ sv_backends! { module Top(input logic [15:0] a, output logic [15:0] y); Bus #(.W(16)) bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -777,9 +777,9 @@ sv_backends! { "#; let sv = r#" module Top(input logic [7:0] a, output logic [7:0] y); - Bus bus(); + prj_Bus bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -808,7 +808,7 @@ sv_backends! { assign y = bus.rsp; } "#; - let sv = "module Slave(Bus.slave bus); assign bus.rsp = bus.req + 8'd1; endmodule"; + let sv = "module Slave(prj_Bus.slave bus); assign bus.rsp = bus.req + 8'd1; endmodule"; } @build Simulator::from_mixed_sources( vec![(veryl, Path::new("bus.veryl"))], @@ -834,7 +834,7 @@ sv_backends! { module Top(input logic [7:0] a, output logic [7:0] y); Bus bus(); assign bus.req = a; - Child child(.bus(bus)); + prj_Child child(.bus(bus)); assign y = bus.rsp; endmodule "#; @@ -888,7 +888,7 @@ sv_backends! { "#; let sv = r#" module Top(input logic [7:0] a, output logic [7:0] y); - VerylChild child(.y(y), .a(a)); + prj_VerylChild child(.y(y), .a(a)); endmodule module SvLeaf(input logic [7:0] a, output logic [7:0] y); assign y = a ^ 8'h55; @@ -1168,7 +1168,7 @@ sv_backends! { #[test] fn bounds_recursive_alternating_parameter_specializations() { let veryl = "module Mid #(param W: u32 = 0) { inst child: $sv::Hop #(W: W + 1); }"; - let sv = "module Hop #(parameter W = 0); Mid #(.W(W)) child(); endmodule module Top; Mid #(.W(1)) child(); endmodule"; + let sv = "module Hop #(parameter W = 0); prj_Mid #(.W(W)) child(); endmodule module Top; prj_Mid #(.W(1)) child(); endmodule"; let error = Simulator::from_mixed_sources( vec![(veryl, Path::new("mid.veryl"))], vec![(sv, Path::new("top.sv"))], @@ -1200,7 +1200,7 @@ fn rejects_missing_children_of_a_systemverilog_top_in_a_mixed_design() { #[test] fn rejects_cycles_that_cross_language_boundaries() { let veryl = "module Child { inst parent: $sv::Top; }"; - let sv = "module Top; Child child(); endmodule"; + let sv = "module Top; prj_Child child(); endmodule"; let error = Simulator::from_mixed_sources( vec![(veryl, Path::new("child.veryl"))], vec![(sv, Path::new("top.sv"))], @@ -1214,6 +1214,88 @@ fn rejects_cycles_that_cross_language_boundaries() { ); } +fn metadata(project: &str, omit_project_prefix: bool) -> veryl_metadata::Metadata { + let mut metadata = veryl_metadata::Metadata::create_default(project).unwrap(); + metadata.build.omit_project_prefix = omit_project_prefix; + metadata +} + +#[test] +fn names_veryl_declarations_by_their_emitted_project_prefix() { + let veryl = r#" + interface Bus { var req: logic<8>; var rsp: logic<8>; modport slave { req: input, rsp: output, } } + module Child (bus: modport Bus::slave) { assign bus.rsp = bus.req + 8'd1; } + "#; + let sv = "module Top(input logic [7:0] a, output logic [7:0] y); mylib_Bus bus(); assign bus.req = a; mylib_Child child(.bus(bus)); assign y = bus.rsp; endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("child.veryl"))], + vec![(sv, Path::new("top.sv"))], + "Top", + ) + .with_metadata(metadata("mylib", false)) + .build_cranelift() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 41u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 42u8.into()); +} + +#[test] +fn names_veryl_declarations_without_an_omitted_project_prefix() { + let veryl = "module Child (a: input logic<8>, y: output logic<8>) { assign y = a + 1; }"; + let sv = "module Top(input logic [7:0] a, output logic [7:0] y); Child child(.a(a), .y(y)); endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("child.veryl"))], + vec![(sv, Path::new("top.sv"))], + "Top", + ) + .with_metadata(metadata("prj", true)) + .build_cranelift() + .unwrap(); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 41u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 42u8.into()); +} + +#[test] +fn rejects_veryl_source_names_that_differ_from_emitted_names() { + let veryl = "module Child (a: input logic<8>, y: output logic<8>) { assign y = a + 1; }"; + let sv = "module Top(input logic [7:0] a, output logic [7:0] y); Child child(.a(a), .y(y)); endmodule"; + let error = Simulator::from_mixed_sources( + vec![(veryl, Path::new("child.veryl"))], + vec![(sv, Path::new("top.sv"))], + "Top", + ) + .build_cranelift() + .unwrap_err(); + assert!( + error + .to_string() + .contains("External module `Child` was not supplied"), + "{error}" + ); +} + +#[test] +fn rejects_sv_modules_named_like_an_emitted_veryl_module() { + let veryl = "module Top (a: input logic<8>, y: output logic<8>) { inst child: $sv::Child (a, y); } module Child (a: input logic<8>, y: output logic<8>) { assign y = a + 1; }"; + let sv = "module Child(input logic [7:0] a, output logic [7:0] y); assign y = a; endmodule"; + let error = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(sv, Path::new("child.sv"))], + "Top", + ) + .with_metadata(metadata("prj", true)) + .build_cranelift() + .unwrap_err(); + assert!( + error + .to_string() + .contains("Duplicate module declaration: Child"), + "{error}" + ); +} + // These assert the intended simulation results, so implementing the missing // bridge behavior only requires removing the ignore attributes. mod pending_interface_functions { diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 963940f0c26..4ecaef57c65 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -32,9 +32,13 @@ let mut sim = Simulator::from_sv_sources( ``` `Simulator::from_mixed_sources` combines both source lists in one simulation. -Veryl instantiates an SV module with `$sv::Module`; SV instantiates a Veryl -module by its name. A Veryl module and an SV module may share a name; -`$sv::Module` selects the SV definition. Numeric module parameters are resolved by the owning +Veryl instantiates an SV module with `$sv::Module`. SV refers to a Veryl module +or interface by the name the Veryl emitter gives it, as SV written against the +emitted code does: `prj_Module` for module `Module` of project `prj`, or +`Module` when `omit_project_prefix` is set in `Veryl.toml`. Without a +`Veryl.toml` the project is named `prj`. An SV module whose name equals the +emitted name of a Veryl module is a duplicate definition. A Veryl top is named +by its Veryl name. Numeric module parameters are resolved by the owning frontend, including parameters of Veryl children instantiated from SV. Interfaces and `input` / `output` modports may cross the boundary in either diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 52d84f87476..022c50c3cfe 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -31,7 +31,11 @@ let mut sim = Simulator::from_sv_sources( `Simulator::from_mixed_sources` は両言語のソースを組み合わせます。トップはどちらの言語でもよく、 階層は Veryl → SV → Veryl のように言語境界を複数回跨げます。Veryl では `$sv::Module`、 -SV では Veryl のモジュール名でインスタンス化します。数値パラメータは、それぞれの frontend が解決します。 +SV からは Veryl のモジュールや interface を Veryl の emitter が出力する名前で参照します。 +出力された SV に対して書いた SV コードがそのまま使えます。プロジェクト `prj` のモジュール `Module` は +`prj_Module`、`Veryl.toml` で `omit_project_prefix` を設定した場合は `Module` です。 +`Veryl.toml` がない場合のプロジェクト名は `prj` です。Veryl モジュールの出力名と同名の SV モジュールは +重複定義になります。Veryl のトップは Veryl の名前で指定します。数値パラメータは、それぞれの frontend が解決します。 interface と `input` / `output` modport のメンバー接続も双方向に対応します。SV の interface は Veryl で `inst bus: $sv::Bus;`、ポートで `bus: modport $sv::Bus::slave` と指定できます。 From d586dd69030eb12ba7d056953cf8db978a72d62f Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:15:52 +0900 Subject: [PATCH 2/7] feat(sv)!: analyze delays, event controls and waits in initial blocks The analyzer keeps `#delay`, `@(event list)` and `wait (condition)` in `initial` bodies as statements (`Delay`, `WaitEvent`, `Wait`) instead of rejecting every procedural timing control. Event items keep their edge (posedge, negedge, `edge`, any change); a `min:typ:max` delay uses its typical value. Fork-join, `wait fork`/`wait order`, named events and `->`, `iff`, cycle delays, intra-assignment timing, `disable` and real delays stay rejected under their own names; timing in `always` bodies and in subroutines is rejected until those are lowered. BREAKING CHANGE: `StmtBase` has the new variants `Delay`, `WaitEvent` and `Wait`. Change-Id: I030365a80c056b46e5768a1aa59b131031e5a970 --- .../src/ast/const_functions.rs | 2 + crates/celox-sv-analyzer/src/ast/lifetimes.rs | 12 ++ .../celox-sv-analyzer/src/ast/procedural.rs | 154 +++++++++++++++++- .../celox-sv-analyzer/src/ast/validation.rs | 16 ++ crates/celox-sv-analyzer/src/ir.rs | 3 +- crates/celox-sv-analyzer/src/lib.rs | 1 + crates/celox-sv-analyzer/src/procedural.rs | 48 ++++++ crates/celox-sv-analyzer/src/tests.rs | 61 +++++++ 8 files changed, 291 insertions(+), 6 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 71898334e11..f4edb75fc48 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -969,6 +969,8 @@ impl Frame<'_> { // Messages have no effect on the value. Unknown and unsupported // system tasks are rejected before elaboration. Stmt::SystemTask { .. } => {} + // A function has no timing controls (IEEE 1800-2023 13.4). + Stmt::Delay(_) | Stmt::WaitEvent(_) | Stmt::Wait(_) => return None, Stmt::AssignConcat { .. } | Stmt::Call { .. } => return None, } Some(Flow::Next) diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 84b66629b3a..d468b131f69 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -527,6 +527,16 @@ impl Flow<'_> { } Ok(Exits::next(written)) } + Stmt::Delay(expr) | Stmt::Wait(expr) => { + self.read(expr, written)?; + Ok(Exits::next(written)) + } + Stmt::WaitEvent(items) => { + for item in items { + self.read(&item.expr, written)?; + } + Ok(Exits::next(written)) + } } } @@ -660,6 +670,8 @@ fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { }) .collect(), Stmt::Local { init, .. } => init.iter().collect(), + Stmt::Delay(expr) | Stmt::Wait(expr) => vec![expr], + Stmt::WaitEvent(items) => items.iter().map(|item| &item.expr).collect(), Stmt::Break | Stmt::Continue => Vec::new(), } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 5961e9ffe82..ddc173a2fda 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -8,7 +8,8 @@ use super::*; use crate::procedural::{ - CaseItemBase, CaseKind, CaseLabel, LoopKind, ParamDirection, SystemTaskArg, + CaseItemBase, CaseKind, CaseLabel, EventEdge, EventItemBase, LoopKind, ParamDirection, + SystemTaskArg, }; /// One lexical scope: the locals it declares and the bindings they shadow. @@ -569,11 +570,23 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { sv_parser::StatementItem::ProceduralAssertionStatement(assertion) => { self.assertion(assertion) } - sv_parser::StatementItem::ProceduralTimingControlStatement(_) - | sv_parser::StatementItem::WaitStatement(_) - | sv_parser::StatementItem::EventTrigger(_) => { - Err(unsupported("procedural timing control")) + sv_parser::StatementItem::ProceduralTimingControlStatement(timing) => { + let mut stmts = vec![self.timing_control(&timing.nodes.0)?]; + stmts.extend(self.statement_or_null(&timing.nodes.1)?); + Ok(stmts) } + sv_parser::StatementItem::WaitStatement(wait) => match &**wait { + sv_parser::WaitStatement::Wait(wait) => { + self.allow_timing("wait statement")?; + let condition = self.expr(&wait.nodes.1.nodes.1)?; + let mut stmts = vec![Stmt::Wait(condition)]; + stmts.extend(self.statement_or_null(&wait.nodes.2)?); + Ok(stmts) + } + sv_parser::WaitStatement::Fork(_) => Err(unsupported("wait fork statement")), + sv_parser::WaitStatement::Order(_) => Err(unsupported("wait order statement")), + }, + sv_parser::StatementItem::EventTrigger(_) => Err(unsupported("event trigger")), sv_parser::StatementItem::ProceduralContinuousAssignment(_) => { Err(unsupported("procedural continuous assignment")) } @@ -583,6 +596,137 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } } + /// Timing controls suspend the process that executes them. An `initial` + /// body runs as a process; `always` bodies with timing controls and + /// subroutines with them are not lowered yet. + fn allow_timing(&self, construct: &str) -> Result<(), AnalyzerError> { + match self.body { + system_functions::Body::Initial => Ok(()), + system_functions::Body::Always => Err(unsupported(format!( + "always and always_latch processes with a {construct}" + ))), + system_functions::Body::Subroutine => { + Err(unsupported(format!("{construct} in a subroutine"))) + } + } + } + + /// The suspension a procedural timing control stands for: a delay or an + /// event control. + fn timing_control( + &self, + control: &sv_parser::ProceduralTimingControl, + ) -> Result { + match control { + sv_parser::ProceduralTimingControl::DelayControl(delay) => { + self.allow_timing("delay control")?; + self.delay_control(delay).map(Stmt::Delay) + } + sv_parser::ProceduralTimingControl::EventControl(control) => { + self.allow_timing("event control")?; + self.event_control(control).map(Stmt::WaitEvent) + } + sv_parser::ProceduralTimingControl::CycleDelay(_) => Err(unsupported("cycle delay")), + } + } + + /// The amount of a `#` delay control, in time units. Of a + /// `min:typ:max` delay the typical value is used, as simulators do by + /// default. + fn delay_control(&self, delay: &sv_parser::DelayControl) -> Result { + match delay { + sv_parser::DelayControl::Delay(delay) => match &delay.nodes.1 { + sv_parser::DelayValue::UnsignedNumber(number) => Ok(Expr::Literal( + self.tree + .get_str(&number.nodes.0) + .ok_or_else(|| unsupported("delay value"))? + .replace('_', ""), + )), + sv_parser::DelayValue::PsIdentifier(identifier) => { + if identifier.nodes.0.is_some() { + return Err(unsupported("package-scoped delay value")); + } + let name = identifier_text(RefNode::Identifier(&identifier.nodes.1), self.tree) + .ok_or_else(|| unsupported("delay value"))?; + let mut expr = Expr::Ident(name); + self.rename_expr(&mut expr); + Ok(expr) + } + sv_parser::DelayValue::HierarchicalIdentifier(identifier) => { + let name = + identifier_text(RefNode::HierarchicalIdentifier(identifier), self.tree) + .ok_or_else(|| unsupported("delay value"))?; + let mut expr = Expr::Ident(name); + self.rename_expr(&mut expr); + Ok(expr) + } + sv_parser::DelayValue::RealNumber(_) + | sv_parser::DelayValue::TimeLiteral(_) + | sv_parser::DelayValue::Step1(_) => Err(unsupported("delay value")), + }, + sv_parser::DelayControl::Mintypmax(delay) => match &delay.nodes.1.nodes.1 { + sv_parser::MintypmaxExpression::Expression(expr) => self.expr(expr), + sv_parser::MintypmaxExpression::Ternary(ternary) => self.expr(&ternary.nodes.2), + }, + } + } + + /// The items of an `@` event control. + fn event_control( + &self, + control: &sv_parser::EventControl, + ) -> Result>, AnalyzerError> { + match control { + sv_parser::EventControl::EventExpression(control) => { + let mut items = Vec::new(); + self.event_items(&control.nodes.1.nodes.1, &mut items)?; + Ok(items) + } + sv_parser::EventControl::EventIdentifier(_) => Err(unsupported("named event")), + sv_parser::EventControl::Asterisk(_) | sv_parser::EventControl::ParenAsterisk(_) => { + Err(unsupported("`@*` event control in a process")) + } + sv_parser::EventControl::SequenceIdentifier(_) => { + Err(unsupported("sequence event control")) + } + } + } + + fn event_items( + &self, + expr: &sv_parser::EventExpression, + items: &mut Vec>, + ) -> Result<(), AnalyzerError> { + match expr { + sv_parser::EventExpression::Expression(expr) => { + if expr.nodes.2.is_some() { + return Err(unsupported("iff-qualified event")); + } + let edge = match &expr.nodes.0 { + None => EventEdge::Any, + Some(sv_parser::EdgeIdentifier::Posedge(_)) => EventEdge::Pos, + Some(sv_parser::EdgeIdentifier::Negedge(_)) => EventEdge::Neg, + Some(sv_parser::EdgeIdentifier::Edge(_)) => EventEdge::Both, + }; + let expr = self.expr(&expr.nodes.1)?; + items.push(EventItemBase { edge, expr }); + Ok(()) + } + sv_parser::EventExpression::Or(expr) => { + self.event_items(&expr.nodes.0, items)?; + self.event_items(&expr.nodes.2, items) + } + sv_parser::EventExpression::Comma(expr) => { + self.event_items(&expr.nodes.0, items)?; + self.event_items(&expr.nodes.2, items) + } + sv_parser::EventExpression::Paren(expr) => { + self.event_items(&expr.nodes.0.nodes.1, items) + } + sv_parser::EventExpression::Sequence(_) => Err(unsupported("sequence event")), + } + } + fn seq_block(&mut self, block: &sv_parser::SeqBlock) -> Result, AnalyzerError> { let mut stmts = Vec::new(); for item in &block.nodes.2 { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 7111b507008..1fc7e5624ca 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -353,6 +353,20 @@ fn reject_silently_ignored_constructs_with_dimensions( .flat_map(|root| root.into_iter()) .filter(|child| matches!(child, RefNode::Cast(_))) .collect(); + // The `min:typ:max` value of a procedural delay control is lowered as its + // typical value; any other one is not supported. + let delay_mintypmax: Vec<_> = validation_nodes(node.clone(), is_module) + .flat_map(|root| root.into_iter()) + .filter_map(|child| match child { + RefNode::DelayControlMintypmax(delay) => Some(delay), + _ => None, + }) + .flat_map(|delay| RefNode::DelayControlMintypmax(delay).into_iter()) + .filter_map(|child| match child { + RefNode::MintypmaxExpressionTernary(ternary) => Some(ternary), + _ => None, + }) + .collect(); // Procedure locals, parameters and loop indices are installed by // BodyBuilder. Validate their queries while lowering that scoped body. let procedural_queries: Vec<_> = validation_nodes(node.clone(), is_module) @@ -587,6 +601,8 @@ fn reject_silently_ignored_constructs_with_dimensions( RefNode::SpecifyBlock(_) => { return Err(AnalyzerError::Unsupported("specify block".to_string())); } + RefNode::MintypmaxExpressionTernary(ternary) + if delay_mintypmax.iter().any(|delay| std::ptr::eq(*delay, ternary)) => {} RefNode::MintypmaxExpressionTernary(_) | RefNode::ConstantMintypmaxExpressionTernary(_) => { return Err(AnalyzerError::Unsupported( diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 715559ec782..ee3f523ec73 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -3,7 +3,7 @@ use crate::{ast, symbol::ModuleId, typecheck}; pub use crate::procedural::{ - CaseKind, CaseLabel, LoopKind, ParamDirection, StmtBase, SystemTaskArg, + CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, StmtBase, SystemTaskArg, }; pub use crate::system_functions::{ ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, @@ -12,6 +12,7 @@ pub use crate::system_functions::{ /// A procedural statement of the analyzed IR. pub type Stmt = StmtBase; pub type CaseItem = crate::procedural::CaseItemBase; +pub type EventItem = crate::procedural::EventItemBase; pub type LocalVariable = crate::procedural::LocalVariableBase; pub type Subroutine = crate::procedural::SubroutineBase; pub type SubroutineParam = crate::procedural::SubroutineParamBase; diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 2ad5920849f..75a1072e02e 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -142,6 +142,7 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ ("streaming concatenation", 447), ("loop-generate unroll limit exceeded", 448), ("iff-qualified always_ff event", 452), + ("iff-qualified event", 1444), ("nonblocking assignment inside always_comb", 453), ("genvar update operator", 455), ("reduction operator in parameter expression", 456), diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index f832b8def25..991b1f790ac 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -70,6 +70,36 @@ pub enum StmtBase { name: String, init: Option, }, + /// `#amount`: suspend the process for `amount` time units (IEEE + /// 1800-2023 9.4.1). + Delay(E), + /// `@(items)`: suspend the process until one of the events occurs + /// (9.4.2). + WaitEvent(Vec>), + /// `wait (condition)`: suspend the process until the condition is true + /// (9.4.3). + Wait(E), +} + +/// One item of an event control, `[edge] expr`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventItemBase { + pub edge: EventEdge, + pub expr: E, +} + +/// Which transitions of an event expression are events (IEEE 1800-2023 +/// 9.4.2, Table 9-2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EventEdge { + /// Any change of the value. + Any, + /// `posedge`: the least significant bit rises. + Pos, + /// `negedge`: the least significant bit falls. + Neg, + /// `edge`: the least significant bit rises or falls. + Both, } /// How a case statement compares its selector with the item labels. @@ -255,6 +285,17 @@ impl StmtBase { name, init: init.map(fe), }, + StmtBase::Delay(amount) => StmtBase::Delay(fe(amount)), + StmtBase::WaitEvent(items) => StmtBase::WaitEvent( + items + .into_iter() + .map(|item| EventItemBase { + edge: item.edge, + expr: fe(item.expr), + }) + .collect(), + ), + StmtBase::Wait(condition) => StmtBase::Wait(fe(condition)), } } @@ -360,6 +401,13 @@ impl StmtBase { fe(init); } } + StmtBase::Delay(amount) => fe(amount), + StmtBase::WaitEvent(items) => { + for item in items { + fe(&mut item.expr); + } + } + StmtBase::Wait(condition) => fe(condition), } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index b7f22392912..fd5de9e924c 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3485,6 +3485,67 @@ fn rejects_unlowered_constructs() { assert!(matches!(error, AnalyzerError::Unsupported(_)), "{error:?}"); } +/// Timing constructs that remain unimplemented are rejected with their +/// own construct names, not as a generic timing control. +#[test] +fn rejects_unimplemented_timing_constructs() { + for (body, construct) in [ + ("initial begin fork #1; join end", "fork-join block"), + ("initial wait fork;", "wait fork statement"), + // The `event` data type is rejected before its uses. + ("event e; initial @e;", "unsupported internal data type"), + ("event e; initial ->e;", "unsupported internal data type"), + ( + "logic clk, en; initial @(posedge clk iff en);", + "iff-qualified event", + ), + ( + "logic a, b; initial a = #1 b;", + "intra-assignment timing control", + ), + ( + "logic a, b; initial a <= #1 b;", + "intra-assignment timing control", + ), + ("initial begin : b disable b; end", "disable statement"), + ("initial #1.5;", "delay value"), + ( + "logic a; initial @* a = 1;", + "`@*` event control in a process", + ), + ( + "logic clk; always @(posedge clk) #1;", + "always and always_latch processes", + ), + ( + "task automatic t; #1; endtask", + "delay control in a subroutine", + ), + ] { + let code = format!("module Top; {body} endmodule"); + let error = analyze_source(&code, Path::new("timing.sv")) + .expect_err(&format!("`{body}` must be rejected")); + assert!( + matches!(&error, AnalyzerError::Unsupported(text) if text.starts_with(construct)), + "`{body}`: {error:?}" + ); + } + assert_eq!( + AnalyzerError::Unsupported("iff-qualified event".to_string()).tracking_issue(), + 1444 + ); +} + +/// Delays, event controls and waits in an `initial` block keep their +/// statement structure in the IR. +#[test] +fn analyzes_timing_controls_in_initial_blocks() { + let code = "module Top(input logic clk, output logic [7:0] y);\n\ + initial begin #3; @(posedge clk or negedge clk, y); @(edge clk); #(1:2:3); wait (y > 1); end\n\ + endmodule"; + analyze_source(code, Path::new("timing.sv")).expect("timing controls in an initial block"); +} + #[test] fn analyzes_veryl_emitted_fifo_with_runtime_casts() { analyze_source( From bae11e19184c1ab3f9b390506088347f6749b0fa Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:15:52 +0900 Subject: [PATCH 3/7] feat(sv): lower delays and waits in initial processes An `initial` block with timing controls runs as a process kernel on the timed runtime: - `#d` suspends with an inactive delay: the amount is read as an unsigned 64-bit time, and as zero when it has an unknown bit. - `@(...)` on whole variables declares a wait site whose terms are the variables with their edge kind; the runtime resumes the process at the first occurrence. - `wait (condition)` checks the condition and waits on the variables it reads, including those read by the functions it calls. - A kernel loop that may not suspend yields every 2^16 iterations, so a process that never suspends ends the step with the slot budget error. - A `repeat` count that is negative or unknown runs a kernel loop zero times. Event expressions other than whole variables are rejected for now. Change-Id: Ic219e74bf093953bd4ded797946f343bc5e57dd3 --- crates/celox-frontend-sv/src/lowering.rs | 35 +- crates/celox-frontend-sv/src/lowering/comb.rs | 4 + crates/celox-frontend-sv/src/lowering/ff.rs | 319 +++++++++++++++++- 3 files changed, 342 insertions(+), 16 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 10a5f1f5b66..a5b83f3e2fd 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -13,7 +13,7 @@ use celox_design::{ BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType, InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind, - RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, + RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, WaitSite, }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ @@ -1977,7 +1977,7 @@ fn lower_module_with_overrides( ) }; mark_ff_event_domains(&event_vars, &mut variables); - let (initial_values, processes) = lower_initial_processes( + let (initial_values, processes, wait_sites) = lower_initial_processes( module, &mut variables, &mut name_to_id, @@ -2082,7 +2082,7 @@ fn lower_module_with_overrides( processes, package_bindings: HashMap::default(), counter_slots: Vec::new(), - wait_sites: Vec::new(), + wait_sites, nba_sites: Vec::new(), }, variables, @@ -2740,9 +2740,16 @@ fn lower_initial_processes( runtime_event_sites: &mut Vec, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, -) -> Result<(Vec>, Vec), sv::AnalyzerError> { +) -> Result< + ( + Vec>, + Vec, + Vec>, + ), + sv::AnalyzerError, +> { if module.initial_processes().is_empty() { - return Ok((Vec::new(), Vec::new())); + return Ok((Vec::new(), Vec::new(), Vec::new())); } let mut values = Vec::new(); let mut runtime = Vec::new(); @@ -2790,7 +2797,7 @@ fn lower_initial_processes( } } if runtime.is_empty() { - return Ok((values, Vec::new())); + return Ok((values, Vec::new(), Vec::new())); } let mut next_id = SourceVarId( @@ -2844,21 +2851,25 @@ fn lower_initial_processes( pm.runtime_event_sites = std::mem::take(runtime_event_sites); pm.runtime_errors = std::mem::take(runtime_errors); pm.extern_functions = std::mem::take(extern_functions); + let mut wait_sites = Vec::new(); let processes = runtime .into_iter() .zip(slots) - .map(|((process, random_seed), slots)| { - Ok(SymbolicProcess { - kernel: ff::Ff::new(&mut pm, random_seed) - .lower_initial_kernel(process.body(), slots)?, + .enumerate() + .map(|(index, ((process, random_seed), slots))| { + let (kernel, sites) = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel( + process.body(), slots, - }) + index, + )?; + wait_sites.extend(sites); + Ok(SymbolicProcess { kernel, slots }) }) .collect::, sv::AnalyzerError>>(); *runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites); *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); - Ok((values, processes?)) + Ok((values, processes?, wait_sites)) } fn lower_comb_processes( diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index bb8fdea1ce8..1595e3eacc0 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -1788,6 +1788,10 @@ impl<'p, 'a> Comb<'p, 'a> { self.assign_concat(&mut store, frames, parts, rhs)?; Ok(store) } + // A timing control suspends a process; this lowering has none. + sv::ir::Stmt::Delay(_) | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::Wait(_) => { + Err(unsupported("procedural timing control")) + } sv::ir::Stmt::Local { name, init } => { let id = self .m diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 90d3adfda0d..745321e9274 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -11,7 +11,8 @@ use super::procedural::*; use super::*; -use celox_frontend_core::process::ProcessKernelBuilder; +use celox_design::{CounterKind, WaitSite}; +use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; use celox_slt::SLTToSIRLowerer; use num_traits::{ToPrimitive, Zero}; @@ -57,6 +58,10 @@ pub(super) struct Ff<'p, 'a> { /// body is lowered, and the process reads and writes stable state /// directly. kernel: Option, + /// The index of the process being lowered among the module's kernels. + process: usize, + /// The wait sites of the process, by local index. + wait_sites: Vec>, direct: bool, } @@ -101,6 +106,8 @@ impl<'p, 'a> Ff<'p, 'a> { dist_seed: None, kernel: None, direct: false, + process: 0, + wait_sites: Vec::new(), } } @@ -1811,6 +1818,18 @@ impl<'p, 'a> Ff<'p, 'a> { self.assign_concat(parts, rhs)?; Ok(true) } + sv::ir::Stmt::Delay(amount) => { + self.delay(amount)?; + Ok(true) + } + sv::ir::Stmt::WaitEvent(items) => { + self.wait_event(items)?; + Ok(true) + } + sv::ir::Stmt::Wait(condition) => { + self.wait_level(condition)?; + Ok(true) + } sv::ir::Stmt::Local { name, init } => { let id = self .m @@ -2353,7 +2372,32 @@ impl<'p, 'a> Ff<'p, 'a> { sv::ir::LoopKind::Repeat(count) => { let signed = self.expr_signed(count); let (id, name) = self.m.temp("repeat", 64, false, false); - let value = self.eval(count, Some((64, signed)))?; + let value = if self.kernel.is_some() { + // A count with an unknown bit, or a negative one, runs + // the body zero times (IEEE 1800-2023 12.7.2). + let count = if signed { + sv::ir::Expr::Mux { + condition: Box::new(sv::ir::Expr::Binary { + left: Box::new(count.clone()), + op: sv::ir::BinaryOp::Lt, + right: Box::new(sv::ir::Expr::Literal("0".to_string())), + }), + then_expr: Box::new(sv::ir::Expr::Literal("0".to_string())), + else_expr: Box::new(count.clone()), + } + } else { + count.clone() + }; + let mut arena = SLTNodeArena::new(); + let node = self.expr_slt(&count, None, &mut arena)?; + let original = self.lower_slt(&arena, node)?; + let node = + coerce_node_width(&mut arena, node, Some(64), signed).map_err(slt_error)?; + let value = self.lower_slt(&arena, node)?; + self.zero_if_unknown(value, original) + } else { + self.eval(count, Some((64, signed)))? + }; self.store(id, SIROffset::Static(0), 64, value); Some(name) } @@ -2409,6 +2453,14 @@ impl<'p, 'a> Ff<'p, 'a> { if falls? { self.jump(latch); } + // A kernel loop that may not suspend yields now and then, so the + // runtime charges it against the time slot's budget instead of + // spinning in the kernel. + let header = if self.kernel.is_some() && !always_suspends(body) { + self.yielding_back_edge(header)? + } else { + header + }; // Latch: the step, then the condition again. A counted loop whose // step leaves its variable unchanged would never end; it stops the // simulation with an error instead. @@ -2847,7 +2899,9 @@ impl Ff<'_, '_> { mut self, body: &[sv::ir::Stmt], slots: ProcessSlots, - ) -> Result, sv::AnalyzerError> { + process: usize, + ) -> Result<(ExecutionUnit, Vec>), sv::AnalyzerError> { + self.process = process; // A nonblocking update would take effect in a later region of the // time step, after the process has run on. for stmt in body { @@ -2878,10 +2932,267 @@ impl Ff<'_, '_> { std::mem::swap(&mut self.b, kernel.builder()); let mut unit = kernel.build(); prune_unreachable_blocks(&mut unit); - Ok(unit) + Ok((unit, self.wait_sites)) + } + + /// `#amount` (IEEE 1800-2023 9.4.1). The amount is self-determined and + /// read as an unsigned 64-bit time: a negative value as its two's + /// complement, and a value with an unknown bit as zero. `#0` resumes in + /// the inactive region. + fn delay(&mut self, amount: &sv::ir::Expr) -> Result<(), sv::AnalyzerError> { + let signed = self.expr_signed(amount); + let mut arena = SLTNodeArena::new(); + let node = self.expr_slt(amount, None, &mut arena)?; + let original = self.lower_slt(&arena, node)?; + let node = coerce_node_width(&mut arena, node, Some(PROCESS_DELAY_WIDTH), signed) + .map_err(slt_error)?; + let delay = self.lower_slt(&arena, node)?; + let delay = self.zero_if_unknown(delay, original); + self.with_kernel(|kernel| kernel.inactive_delay(delay)) + .map_err(kernel_error) + } + + /// `value` as a two-state register that is zero when `source` has an + /// unknown bit. + fn zero_if_unknown(&mut self, value: RegisterId, source: RegisterId) -> RegisterId { + let width = self.b.register(&value).width(); + if !matches!(self.b.register(&source), RegisterType::Logic { .. }) { + return value; + } + // The reduction XOR of a value is unknown exactly when a bit is. + let reduced = self.b.alloc_logic(1); + self.b + .emit(SIRInstruction::Unary(reduced, UnaryOp::Xor, source)); + let zero = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + let one = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let is_zero = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + is_zero, + reduced, + BinaryOp::EqCase, + zero, + )); + let is_one = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + is_one, + reduced, + BinaryOp::EqCase, + one, + )); + let known = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(known, is_zero, BinaryOp::Or, is_one)); + let value = match *self.b.register(&value) { + RegisterType::Logic { width } => { + let two_state = self.b.alloc_bit(width, false); + self.b + .emit(SIRInstruction::Unary(two_state, UnaryOp::ToTwoState, value)); + two_state + } + _ => value, + }; + let zero = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + let result = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Mux(result, known, value, zero)); + result + } + + /// `@(items)` (IEEE 1800-2023 9.4.2): the process waits for an + /// occurrence of any item, which the runtime detects on the watched + /// signals themselves, so nothing is left to check when it resumes. + fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { + let mut terms = Vec::new(); + for item in items { + let id = match &item.expr { + sv::ir::Expr::Ident(name) => self.m.id(name).filter(|&id| !self.m.is_hidden(id)), + _ => None, + } + .ok_or_else(|| unsupported("event expression other than a variable"))?; + match item.edge { + sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), + sv::ir::EventEdge::Pos => terms.push((id, CounterKind::Rises)), + sv::ir::EventEdge::Neg => terms.push((id, CounterKind::Falls)), + sv::ir::EventEdge::Both => { + terms.push((id, CounterKind::Rises)); + terms.push((id, CounterKind::Falls)); + } + } + } + let site = self.wait_site(terms); + self.with_kernel(|kernel| -> Result<(), ProcessKernelError> { + kernel.suspend_wait(site)?; + let woken = kernel.builder().alloc_bit(1, false); + kernel + .builder() + .emit(SIRInstruction::Imm(woken, SIRValue::new(1u8))); + kernel.wake_if(woken); + Ok(()) + }) + .map_err(kernel_error) + } + + /// `wait (condition)` (IEEE 1800-2023 9.4.3): the process goes on at once + /// if the condition holds, and otherwise checks it again whenever a + /// variable it reads changes. + fn wait_level(&mut self, condition: &sv::ir::Expr) -> Result<(), sv::AnalyzerError> { + let mut names = HashSet::default(); + expr_idents(condition, &mut names); + subroutine_reads(self.m, condition, &mut names); + let mut ids: Vec<_> = names + .iter() + .filter_map(|name| self.m.id(name)) + .filter(|&id| !self.m.is_hidden(id)) + .collect(); + ids.sort_unstable(); + ids.dedup(); + let site = self.wait_site( + ids.into_iter() + .map(|id| (id, CounterKind::Changes)) + .collect(), + ); + // The condition is lowered once per check: before the process + // suspends and at every resume. + let mut error = None; + let mut kernel = self.kernel.take().expect("lowering a process kernel"); + std::mem::swap(&mut self.b, kernel.builder()); + // The kernel is out of `self` while it builds the checks; reads go + // to stable state all the same. + let direct = std::mem::replace(&mut self.direct, true); + let result = kernel.wait_level(site, |builder| { + std::mem::swap(&mut self.b, builder); + let truth = self.eval_truth(condition).map(|(truth, _)| truth); + std::mem::swap(&mut self.b, builder); + truth.unwrap_or_else(|e| { + error = Some(e); + let never = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u8))); + never + }) + }); + self.direct = direct; + std::mem::swap(&mut self.b, kernel.builder()); + self.kernel = Some(kernel); + result.map_err(kernel_error)?; + error.map_or(Ok(()), Err) + } + + /// Declare a wait site of the process with the given terms and return + /// its local index. + fn wait_site(&mut self, terms: Vec<(SourceVarId, CounterKind)>) -> u32 { + let index = self.wait_sites.len() as u32; + self.wait_sites.push(WaitSite { + process: self.process, + terms, + }); + index + } + + /// The back edge of a kernel loop that may not suspend: count the + /// iteration, yield every 2^[`LOOP_YIELD_BITS`] of them, and continue at + /// `header`. Returns the block the loop's back edges jump to. + fn yielding_back_edge(&mut self, header: BlockId) -> Result { + let back = self.b.new_block(); + let (counter, _) = self.m.temp("loop", LOOP_YIELD_BITS, false, false); + self.b.switch_to_block(back); + let count = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b.emit(SIRInstruction::Load( + count, + stable(counter), + SIROffset::Static(0), + LOOP_YIELD_BITS, + )); + let one = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let next = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b + .emit(SIRInstruction::Binary(next, count, BinaryOp::Add, one)); + self.store(counter, SIROffset::Static(0), LOOP_YIELD_BITS, next); + let zero = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + let wrapped = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(wrapped, next, BinaryOp::Eq, zero)); + let yield_block = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: wrapped, + true_block: (yield_block, Vec::new()), + false_block: (header, Vec::new()), + }); + self.b.switch_to_block(yield_block); + self.with_kernel(ProcessKernelBuilder::yield_now) + .map_err(kernel_error)?; + self.jump(header); + Ok(back) } } +/// Iterations, as a power of two, between the yields of a kernel loop that +/// may not suspend. +const LOOP_YIELD_BITS: usize = 16; + +/// Whether every pass through `stmts` suspends the process. +fn always_suspends(stmts: &[sv::ir::Stmt]) -> bool { + stmts + .iter() + .any(|stmt| matches!(stmt, sv::ir::Stmt::Delay(_) | sv::ir::Stmt::WaitEvent(_))) +} + +/// The module variables the subroutines `expr` calls read, directly or +/// through further calls, besides their own formals and locals. +fn subroutine_reads(pm: &ProcModule<'_>, expr: &sv::ir::Expr, names: &mut HashSet) { + let mut pending = Vec::new(); + collect_call_names(expr, &mut pending); + let mut visited = HashSet::default(); + while let Some(name) = pending.pop() { + if !visited.insert(name.clone()) { + continue; + } + let Some(subroutine) = pm.subroutine(&name) else { + continue; + }; + for param in &subroutine.params { + if let Some(default) = ¶m.default { + expr_idents(default, names); + } + } + for stmt in &subroutine.body { + let mut stmt = stmt.clone(); + stmt.visit_mut( + &mut |expr| { + expr_idents(expr, names); + collect_call_names(expr, &mut pending); + }, + &mut |_| {}, + &mut |_| {}, + ); + stmt.walk(&mut |stmt| { + if let sv::ir::Stmt::Call { name, .. } = stmt { + pending.push(name.clone()); + } + }); + } + } +} + +/// The names of the user subroutines `expr` calls. +fn collect_call_names(expr: &sv::ir::Expr, names: &mut Vec) { + let called = std::cell::RefCell::new(Vec::new()); + expr_calls(expr, &|callee| { + if let Some(name) = callee.subroutine() { + called.borrow_mut().push(name.to_string()); + } + false + }); + names.extend(called.into_inner()); +} + +fn kernel_error(error: ProcessKernelError) -> sv::AnalyzerError { + unsupported(error.to_string()) +} + fn seal_drained(mut builder: SIRBuilder) -> ExecutionUnit { let (blocks, register_map, _) = builder.drain(); let mut unit = ExecutionUnit { From 6851e731baf8d634c68111a0deb7de2aa587b5a8 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:15:52 +0900 Subject: [PATCH 4/7] test(sv): run the timing cases of initial processes Enable the 28 timing cases that initial processes now pass, give each remaining exclusion its actual reason, and add cases for `edge` waits, `min:typ:max` delays and long process loops, checked against Icarus and Verilator. The timed suite backend settles the current time before a read, an eval and output collection, as the reference simulators' script adapters do. Change-Id: Idabc095b34aefc665610c336d5a2f26632c8df5f --- .../src/sv/cases/timing.vtest | 56 ++++++++++++++++ .../tests/frontends/systemverilog/suite.rs | 22 +++++-- .../tests/frontends/systemverilog/timing.rs | 65 ++++++------------- 3 files changed, 93 insertions(+), 50 deletions(-) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index e441ec138e7..a4a71ae644b 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -684,6 +684,62 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev module Top(output wire[7:0]qualified,imported);Qualified a(qualified);Imported b(imported);initial #2 $finish;endmodule "#)(top Top)(run_until 0)(assert_eq qualified 0)(assert_eq imported 0)(run_until 1)(assert_eq qualified 0)(assert_eq imported 0)(run_to_finish)) +(case edge_waits_wake_on_rising_and_falling_edges + (source "edge.sv" #" + module Top(output logic [7:0] seen); + logic clk = 1'b0; + initial begin + #3 clk = 1'b1; + #3 clk = 1'b0; + #3 clk = 1'b1; + end + initial begin + seen = 8'd0; + forever @(edge clk) seen = seen + 8'd1; + end + endmodule + "#) + (top Top) + (run_until 2) + (assert_eq seen 0) + (run_until 3) + (assert_eq seen 1) + (run_until 6) + (assert_eq seen 2 "a falling edge is an edge") + (run_until 9) + (assert_eq seen 3)) + +(case min_typ_max_delays_wait_the_typical_value + (source "mintypmax.sv" #" + module Top(output logic [7:0] a); + initial begin + a = 8'd1; + #(2:5:9) a = 8'd2; + end + endmodule + "#) + (top Top) + (run_until 4) + (assert_eq a 1) + (run_until 5) + (assert_eq a 2)) + +(case long_process_loops_finish_within_one_time_slot + (source "long_loop.sv" #" + module Top(output logic [31:0] count); + initial begin + count = 32'd0; + for (int i = 0; i < 200000; i++) count = count + 32'd1; + #1 count = count + 32'd1; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq count 200000) + (run_until 1) + (assert_eq count 200001)) + (case initial_blocks_run_at_time_zero (source "time_zero.sv" #" module Top(output bit [7:0] y); diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index f4126b657a6..e5d20fd137c 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -7,7 +7,7 @@ struct CeloxBackend(Simulator); /// A timed case: the design's own processes and clocks run in a /// [`Simulation`]. A host write is settled at the current time by the next -/// run operation. +/// run operation, read, eval or output collection. struct TimedBackend { sim: Simulation, /// Runtime events not yet taken as output. @@ -60,6 +60,20 @@ impl TimedBackend { } } + /// Settle host writes and the work they wake at the current time, as + /// the reference simulators do before a read, then capture events. + fn settled(&mut self, operation: &str) -> Result<()> { + let finished = self.finished; + if !finished { + self.sim.run_until(self.sim.time())?; + } + self.capture_events()?; + if !finished && self.finished { + return Err(format!("the design finished during {operation}").into()); + } + Ok(()) + } + /// Capture events after an operation that does not advance time. fn checked(&mut self, operation: &str) -> Result<()> { let finished = self.finished; @@ -104,14 +118,14 @@ impl Backend for TimedBackend { } fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { - self.checked("a read")?; + self.settled("a read")?; let signal = self.signal(path); Ok(self.sim.get_four_state(signal)) } fn eval_comb(&mut self) -> Result<()> { self.sim.eval_comb()?; - self.checked("eval") + self.settled("eval") } fn tick(&mut self, _event: &str) -> Result<()> { @@ -119,7 +133,7 @@ impl Backend for TimedBackend { } fn take_output(&mut self) -> Result> { - self.checked("output collection")?; + self.settled("output collection")?; collect_output(std::mem::take(&mut self.events)) } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 291bb088484..740b3e97584 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -49,112 +49,85 @@ macro_rules! timed_cases { } timed_cases! { - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn delays_resume_initial_blocks_at_later_times = "timing::delays_resume_initial_blocks_at_later_times"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn always_with_a_delay_generates_a_clock = "timing::always_with_a_delay_generates_a_clock"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn edge_waits_resume_before_the_registers_of_that_edge_update = "timing::edge_waits_resume_before_the_registers_of_that_edge_update"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn any_change_waits_wake_on_every_value_change = "timing::any_change_waits_wake_on_every_value_change"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn wait_statements_block_until_their_condition_holds = "timing::wait_statements_block_until_their_condition_holds"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn level_sensitive_always_runs_as_a_process = "timing::level_sensitive_always_runs_as_a_process"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn processes_wake_each_other_at_the_same_time = "timing::processes_wake_each_other_at_the_same_time"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn tasks_with_timing_controls_run_in_processes = "timing::tasks_with_timing_controls_run_in_processes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn edge_waits_see_the_signals_the_script_drives = "timing::edge_waits_see_the_signals_the_script_drives"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn finish_in_an_always_process_ends_the_simulation = "timing::finish_in_an_always_process_ends_the_simulation"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn waiting_processes_do_not_keep_an_idle_simulation_running = "timing::waiting_processes_do_not_keep_an_idle_simulation_running"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn four_state_edges_count_transitions_through_unknown = "timing::four_state_edges_count_transitions_through_unknown"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn unknown_delays_and_conditions_count_as_zero_and_false = "timing::unknown_delays_and_conditions_count_as_zero_and_false"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn direct_reads_settle_waiting_processes = "timing::direct_reads_settle_waiting_processes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn output_reads_settle_waiting_processes = "timing::output_reads_settle_waiting_processes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn run_until_drains_target_time_before_later_writes = "timing::run_until_drains_target_time_before_later_writes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn repeated_settles_do_not_advance_design_time = "timing::repeated_settles_do_not_advance_design_time"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn run_to_finish_has_no_simulated_time_deadline = "timing::run_to_finish_has_no_simulated_time_deadline"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "blocking stores of an edge-triggered always are not visible before the inactive region (#1123)"] fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "blocking stores of an edge-triggered always are not visible before the inactive region (#1123)"] fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn inactive_time_directives_do_not_change_scheduler_units = "timing::inactive_time_directives_do_not_change_scheduler_units"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_concatenation_publishes_one_event_update = "timing::blocking_concatenation_publishes_one_event_update"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn finite_active_feedback_preserves_convergence = "timing::finite_active_feedback_preserves_convergence"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn pure_function_rhs_preserves_distinct_write_times = "timing::pure_function_rhs_preserves_distinct_write_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn conditional_writes_preserve_distinct_activation_times = "timing::conditional_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn case_writes_preserve_distinct_activation_times = "timing::case_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_repeat_writes_preserve_distinct_activation_times = "timing::constant_repeat_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn separate_comb_assignments_preserve_selected_dependencies = "timing::separate_comb_assignments_preserve_selected_dependencies"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_for_writes_preserve_distinct_activation_times = "timing::constant_for_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_tasks_preserve_distinct_activation_times = "timing::untimed_tasks_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_task_copyback_preserves_distinct_activation_times = "timing::untimed_task_copyback_preserves_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn statically_satisfied_waits_preserve_distinct_activation_times = "timing::statically_satisfied_waits_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn nba_woken_waiters_sample_before_continuations = "timing::nba_woken_waiters_sample_before_continuations"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn negative_repeat_counts_do_not_run_the_body = "timing::negative_repeat_counts_do_not_run_the_body"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_ff_woken_waiters_sample_before_continuations = "timing::blocking_ff_woken_waiters_sample_before_continuations"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn direct_blocking_ff_woken_waiters_sample_before_continuations = "timing::direct_blocking_ff_woken_waiters_sample_before_continuations"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_variable_initializers_do_not_invent_clock_edges = "timing::constant_variable_initializers_do_not_invent_clock_edges"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn repeated_active_edges_share_one_nba_batch = "timing::repeated_active_edges_share_one_nba_batch"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn false_wait_preserves_separate_hierarchical_write_times = "timing::false_wait_preserves_separate_hierarchical_write_times"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn always_timed_task_without_inline_timing_executes = "timing::always_timed_task_without_inline_timing_executes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_comb_if_discards_unreachable_pulse_branch = "timing::constant_comb_if_discards_unreachable_pulse_branch"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_child_ff_case_discards_unreachable_pulse_arm = "timing::constant_child_ff_case_discards_unreachable_pulse_arm"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_child_loop_exit_keeps_one_write = "timing::constant_child_loop_exit_keeps_one_write"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_child_case_exit_keeps_one_write = "timing::constant_child_case_exit_keeps_one_write"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn four_state_child_if_keeps_one_write = "timing::four_state_child_if_keeps_one_write"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn selected_child_dependency_ignores_unreachable_reads = "timing::selected_child_dependency_ignores_unreachable_reads"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn selected_child_loop_exit_ignores_unreachable_suffix = "timing::selected_child_loop_exit_ignores_unreachable_suffix"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn finite_process_loop_preserves_continuation_values = "timing::finite_process_loop_preserves_continuation_values"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn zero_trip_child_dependencies_ignore_body_and_step = "timing::zero_trip_child_dependencies_ignore_body_and_step"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn cross_file_package_initializers_keep_static_clock_baseline = "timing::cross_file_package_initializers_keep_static_clock_baseline"; + fn edge_waits_wake_on_rising_and_falling_edges = "timing::edge_waits_wake_on_rising_and_falling_edges"; + fn min_typ_max_delays_wait_the_typical_value = "timing::min_typ_max_delays_wait_the_typical_value"; + fn long_process_loops_finish_within_one_time_slot = "timing::long_process_loops_finish_within_one_time_slot"; fn initial_blocks_run_at_time_zero = "timing::initial_blocks_run_at_time_zero"; fn host_edges_after_time_zero_clock_flip_flops = "timing::host_edges_after_time_zero_clock_flip_flops"; } From d7a4005aa546a924af0f4d83509fcce0c7a717e5 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:38:09 +0900 Subject: [PATCH 5/7] test(sv): expect the sv-tests delay and wait cases to pass `11.11--min_max_avg_delay`, `9.4.1--delay_control` and `9.4.3--event_sequence_controls` now elaborate. Simulated, they print "Done" at time 200, set `a` to 1..4 at 10..40, and copy `b` into `a` at 20 after `enable` rises at 10. Change-Id: I606c4785f3ea31ac2c640184e48ff43e50f48233 --- conformance/sv-tests/expected.tsv | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index df1c18dab94..52245a05b56 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -16,7 +16,7 @@ chapter-11/11.10.1--string_concat.sv fail chapter-11/11.10.1--string_copy.sv fail chapter-11/11.10.3--empty_string-sim.sv fail chapter-11/11.10.3--empty_string.sv fail -chapter-11/11.11--min_max_avg_delay.sv fail +chapter-11/11.11--min_max_avg_delay.sv pass chapter-11/11.12--let_construct.sv fail chapter-11/11.3.5--expr_short_circuit.sv pass chapter-11/11.3.6--assign_in_exp-sim.sv fail @@ -726,7 +726,7 @@ chapter-9/9.3.5--statement_labels_par.sv fail chapter-9/9.3.5--statement_labels_seq.sv pass chapter-9/9.4.1--delay_control-sim.sv fail chapter-9/9.4.1--delay_control-two-blocks-sim.sv fail -chapter-9/9.4.1--delay_control.sv fail +chapter-9/9.4.1--delay_control.sv pass chapter-9/9.4.2--event_control_edge.sv fail chapter-9/9.4.2--event_control_negedge.sv pass chapter-9/9.4.2--event_control_posedge.sv pass @@ -737,7 +737,7 @@ chapter-9/9.4.2.1--event_or_op.sv fail chapter-9/9.4.2.2--event_implicit.sv pass chapter-9/9.4.2.3--event_conditional.sv fail chapter-9/9.4.2.4--event_sequence.sv fail -chapter-9/9.4.3--event_sequence_controls.sv fail +chapter-9/9.4.3--event_sequence_controls.sv pass chapter-9/9.4.5--event_blocking_assignment_delay.sv fail chapter-9/9.4.5--event_nonblocking_assignment_delay.sv fail chapter-9/9.4.5--event_nonblocking_assignment_event.sv fail From ebfd1078fd315ff0fbda570223dffed4323b900a Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:58:55 +0900 Subject: [PATCH 6/7] test(sv): exclude the four-state flip-flop edge case under #1472 Change-Id: Ie8a00910036fd1305b3aea0c4e5b8aa2c0b1a14f --- crates/celox/tests/frontends/systemverilog/timing.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 740b3e97584..27dfb7c846c 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -65,6 +65,7 @@ timed_cases! { #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn finish_in_an_always_process_ends_the_simulation = "timing::finish_in_an_always_process_ends_the_simulation"; fn waiting_processes_do_not_keep_an_idle_simulation_running = "timing::waiting_processes_do_not_keep_an_idle_simulation_running"; + #[ignore = "flip-flop domains miss edges to and from z on a four-state clock (#1472)"] fn four_state_edges_count_transitions_through_unknown = "timing::four_state_edges_count_transitions_through_unknown"; fn unknown_delays_and_conditions_count_as_zero_and_false = "timing::unknown_delays_and_conditions_count_as_zero_and_false"; fn direct_reads_settle_waiting_processes = "timing::direct_reads_settle_waiting_processes"; From 02ef771f9ca5548d7fb69213519f6129162c0e61 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 10:46:29 +0900 Subject: [PATCH 7/7] 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"); +});