diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c24b1699178..204e1520b64 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 diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 2982ce71c1d..c3ff7ae31c5 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -522,6 +522,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 { @@ -740,6 +783,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 @@ -751,6 +801,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>, @@ -759,6 +814,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 a4742149e02..7581c99d08f 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..c177953bfcb 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::{ @@ -141,7 +141,7 @@ pub(crate) struct LoweredSvParameterOverride { pub value: Option, /// The data type resolved in the instantiating scope. pub bound_type: Option, - pub pattern_text: Option, + pub bound_pattern: Option, } #[derive(Clone)] @@ -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. @@ -1208,6 +1213,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( "__celox_foreign", &HashMap::default(), &[], + &[], &sv::ModuleInterfaces::default(), &sv::Packages::default(), )?; @@ -1295,7 +1301,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(value.expression()), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(); requested_roots.insert(name.clone(), key.clone()); @@ -1310,7 +1316,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(sv::ir::ConstExpr::Literal(value.to_string())), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(); } @@ -1371,7 +1377,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(value.expression()), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(); requested_roots.insert(name.clone(), dependency.clone()); @@ -1580,7 +1586,7 @@ pub fn schedule_sources( name: name.clone(), value: Some(sv::ir::ConstExpr::Literal(value.to_string())), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(), }; @@ -1773,16 +1779,13 @@ fn specialize_module( let pattern_overrides: Vec<_> = key .parameter_overrides .iter() - .filter_map(|parameter| Some((parameter.name.clone(), parameter.pattern_text.clone()?))) + .filter_map(|parameter| Some((parameter.name.clone(), parameter.bound_pattern.clone()?))) .collect(); - let pattern_source = module - .source - .with_pattern_parameter_overrides(&module.name, &pattern_overrides)?; - let source = pattern_source.as_ref().unwrap_or(&module.source); - let ir = source.analyze_module( + let ir = module.source.analyze_module( &module.name, &overrides, &type_overrides, + &pattern_overrides, &module.interfaces, &module.packages, )?; @@ -1791,12 +1794,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( @@ -1977,7 +2003,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, @@ -2060,6 +2086,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(), @@ -2082,7 +2110,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, @@ -2158,7 +2186,7 @@ fn lower_parameter_overrides( name: parameter.name().to_string(), value, bound_type: parameter.bound_type().cloned(), - pattern_text: parameter.pattern_text().map(str::to_string), + bound_pattern: parameter.bound_pattern().cloned(), } }) .collect() @@ -2740,9 +2768,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 +2825,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 +2879,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 a6a2b8cfbe7..dfcbac62065 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 1e727f1ea7d..3c8947420e5 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 @@ -2366,7 +2385,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) } @@ -2422,6 +2466,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. @@ -2860,7 +2912,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 { @@ -2891,10 +2945,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 { diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 597abeb4e3d..728194843a8 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -449,6 +449,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 a07a0fcd5b0..4db8c62de46 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, @@ -1127,6 +1128,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(); @@ -1156,6 +1158,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), }); @@ -1166,7 +1169,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 { @@ -1262,8 +1265,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 @@ -4344,6 +4351,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/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index f09c9a3f7f8..4cebe51c5e7 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -135,7 +135,7 @@ pub fn analyze_source(source: ast::Source) -> Result { parameter.name().to_string(), parameter.value().cloned().map(Into::into), parameter.bound_type().cloned(), - parameter.pattern_text().map(str::to_string), + parameter.bound_pattern().cloned(), ) }) .collect(), diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 404a9527c75..1cc7da990b6 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -25,9 +25,11 @@ use crate::{AnalyzerError, system_functions, typecheck}; mod array_compatibility; mod array_parameters; mod assignment_analysis; +mod bound_patterns; mod case; mod casts; mod comb_process; +pub use bound_patterns::BoundPattern; mod comb_rewrite; pub(crate) mod const_functions; mod constant_folding; @@ -205,6 +207,7 @@ pub struct Source { pub(crate) struct ModuleParameterBindings<'a> { pub values: &'a HashMap, pub types: &'a [(String, Type)], + pub patterns: &'a [(String, BoundPattern)], } impl Source { @@ -293,6 +296,7 @@ impl Source { ModuleParameterBindings { values: parameter_overrides, types: &[], + patterns: &[], }, extra_interfaces, &packages, @@ -329,6 +333,11 @@ impl Source { )?; imported.type_parameter_bindings = type_parameters::bind(node.clone(), syntax_tree, bindings.types)?; + imported.pattern_parameter_bindings = type_parameters::bind_patterns( + node.clone(), + syntax_tree, + bindings.patterns, + )?; modules.push(Module::from_module_node_with_parameter_overrides( node, syntax_tree, @@ -1070,6 +1079,7 @@ impl Module { // A package keeps its symbols for the scopes that use it. let symbols = is_package.then(|| scope::ScopeSymbols { type_parameter_bindings: HashMap::default(), + pattern_parameter_bindings: HashMap::default(), const_env: const_env.clone(), parameter_values: parameter_values.clone(), parameters: parameters.clone(), @@ -1579,7 +1589,7 @@ pub struct ParameterOverride { value: Option, /// The data type resolved in the instantiating scope. bound_type: Option, - pattern_text: Option, + bound_pattern: Option, } impl ParameterOverride { @@ -1588,7 +1598,7 @@ impl ParameterOverride { name, value, bound_type: None, - pattern_text: None, + bound_pattern: None, } } @@ -1597,13 +1607,13 @@ impl ParameterOverride { name, value: None, bound_type: Some(bound_type), - pattern_text: None, + bound_pattern: None, } } /// A constant assignment pattern, evaluated in the caller scope. - pub fn pattern_text(&self) -> Option<&str> { - self.pattern_text.as_deref() + pub fn bound_pattern(&self) -> Option<&BoundPattern> { + self.bound_pattern.as_ref() } pub fn name(&self) -> &str { @@ -2214,7 +2224,7 @@ struct FunctionLocalType { is_2state: bool, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Expr { Ident(String), Literal(String), @@ -2263,7 +2273,7 @@ pub enum Expr { } /// One item of an `inside` set. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum InsideItem { /// A value matched with wildcard equality (`==?`). Value(Expr), diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index ba8232a9b9f..75afe95e93d 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -10,13 +10,20 @@ use super::*; /// A parameter of unpacked array type, as the variable that holds it. pub(super) struct ArrayParameter<'a> { pub signal: Signal, - pattern: &'a sv_parser::AssignmentPatternExpression, + pattern: Option<&'a sv_parser::AssignmentPatternExpression>, + bound: Option, } /// Whether a parameter assignment declares an unpacked array, or a value /// given by an assignment pattern (a packed structure or array). pub(super) fn is_array_parameter(param: &sv_parser::ParamAssignment) -> bool { - !param.nodes.1.is_empty() || value_pattern(param).is_some() + !param.nodes.1.is_empty() + || value_pattern(param).is_some() + || identifier_locate(RefNode::ParameterIdentifier(¶m.nodes.0)).is_some_and(|loc| { + scope::imported() + .pattern_parameter_bindings + .contains_key(&loc.offset) + }) } fn declared_type( @@ -152,7 +159,14 @@ pub(super) fn array_parameters_from_declaration<'a>( let RefNode::ParamAssignment(param) = child else { continue; }; - if !is_array_parameter(param) { + let bound = + identifier_locate(RefNode::ParameterIdentifier(¶m.nodes.0)).and_then(|loc| { + scope::imported() + .pattern_parameter_bindings + .get(&loc.offset) + .cloned() + }); + if !is_array_parameter(param) && bound.is_none() { continue; } let name = parameter_name(RefNode::ParameterIdentifier(¶m.nodes.0), tree)?; @@ -166,12 +180,16 @@ pub(super) fn array_parameters_from_declaration<'a>( const_env, type_aliases, )?; - let pattern = value_pattern(param).ok_or_else(|| { - AnalyzerError::Unsupported(format!("value of array parameter `{name}`")) - })?; + let pattern = value_pattern(param); + if pattern.is_none() && bound.is_none() { + return Err(AnalyzerError::Unsupported(format!( + "value of array parameter `{name}`" + ))); + } let parameter = ArrayParameter { signal: Signal::new(name, type_with_unpacked_ranges(element, ranges)), pattern, + bound, }; // Publish before the next declarator can query this array's shape. publish(¶meter); @@ -189,11 +207,18 @@ impl ArrayParameter<'_> { ) -> Result { let name = self.signal.name().to_string(); let shape = procedural::dimensions_from_type(self.signal.r#type()); - let value = if self.pattern.nodes.0.is_some() { - patterns::typed_pattern(self.pattern, tree, dims) + let value = if let Some(bound) = &self.bound { + bound.lower(&shape, dims)? } else { - patterns::expr_from_pattern(&self.pattern.nodes.1, &shape, tree, dims) - }?; + let pattern = self + .pattern + .ok_or_else(|| unsupported("array parameter value"))?; + if pattern.nodes.0.is_some() { + patterns::typed_pattern(pattern, tree, dims)? + } else { + patterns::expr_from_pattern(&pattern.nodes.1, &shape, tree, dims)? + } + }; Ok(InitialProcess { creation_order: 0, condition: None, diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs new file mode 100644 index 00000000000..d79739839f0 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -0,0 +1,412 @@ +//! Assignment-pattern bindings retain structure, not generated source. Names, +//! keys and repetition counts bind in the caller; element sizing happens in +//! the receiving declaration's assignment context (IEEE 1800-2023 10.9). +use super::*; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct BoundPattern { + items: Items, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Items { + Value(Expr), + List(Vec), + Repeat(usize, Vec), + Keyed(Vec<(Key, Value)>), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Index(i128), + Member(String), + Default, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(super) enum Value { + Expression(Expr), + Pattern(BoundPattern), +} + +pub(super) fn from_param( + expression: &sv_parser::ParamExpression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { + let sv_parser::ParamExpression::MintypmaxExpression(expression) = expression else { + return Err(unsupported("parameter assignment pattern")); + }; + let sv_parser::MintypmaxExpression::Expression(expression) = expression.as_ref() else { + return Err(unsupported("parameter pattern mintypmax expression")); + }; + match value(expression, tree, dims)? { + Value::Pattern(pattern) => Ok(pattern), + Value::Expression(value) => Ok(BoundPattern { + items: Items::Value(value), + }), + } +} + +fn frozen(expr: Expr, dims: &PackedDimensions) -> Converted { + let freeze = |expr| frozen(expr, dims).map(Box::new); + Ok(match expr { + Expr::Literal(_) => expr, + Expr::Unary { op, expr } => Expr::Unary { + op, + expr: freeze(*expr)?, + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: freeze(*left)?, + op, + right: freeze(*right)?, + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: freeze(*condition)?, + then_expr: freeze(*then_expr)?, + else_expr: freeze(*else_expr)?, + }, + Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order, + } if arg_order.is_empty() => { + let args = args + .into_iter() + .map(|arg| { + let expr = frozen( + arg.ok_or_else(|| { + unsupported("default constant function argument in pattern") + })?, + dims, + )?; + expr_to_const(expr) + .map(Into::into) + .ok_or_else(|| unsupported("constant pattern function argument")) + }) + .collect::>>()?; + let literal = const_functions::eval_call_literal(&name, &args, &dims.const_env) + .ok_or_else(|| unsupported("constant parameter pattern function"))?; + Expr::Literal(typecheck::format_integral_literal_binary(&literal)) + } + value => { + let values = dims + .parameter_values + .iter() + .map(|(n, v)| (n.clone(), v.clone())) + .collect(); + let value = + substitute_expr_constants_with_parameter_literals(value, &dims.const_env, &values); + let folded = fold_const_integral_expr_preserving_mask(value, &dims.const_env); + if !matches!(folded, Expr::Literal(_)) { + return Err(unsupported("nonconstant parameter pattern element")); + } + folded + } + }) +} + +fn value( + expr: &sv_parser::Expression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { + if let Some(pattern) = patterns::pattern_expression(expr) { + value_pattern(pattern, tree, dims) + } else { + Ok(Value::Expression(frozen( + expr_from_expression_with_types(expr, tree, dims)?, + dims, + )?)) + } +} + +fn value_pattern( + pattern: &sv_parser::AssignmentPatternExpression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { + if pattern.nodes.0.is_some() { + return patterns::constant_typed_pattern_value(pattern, tree, dims); + } + let integer = |expr: &sv_parser::ConstantExpression| { + const_expr_from_ref_node_with_env( + RefNode::ConstantExpression(expr), + tree, + &dims.const_env, + &dims.type_aliases, + )? + .and_then(|expr| eval_ast_const_expr(&expr, &dims.const_env)) + .ok_or_else(|| unsupported("nonconstant assignment pattern key or count")) + }; + let values = |items: Vec<&sv_parser::Expression>| { + items + .into_iter() + .map(|expr| value(expr, tree, dims)) + .collect::>>() + }; + let default_key = |key: &sv_parser::AssignmentPatternKey| match key { + sv_parser::AssignmentPatternKey::Default(_) => Ok(Key::Default), + _ => Err(unsupported("assignment pattern type key")), + }; + let items = match &pattern.nodes.1 { + sv_parser::AssignmentPattern::List(list) => { + Items::List(values(list.nodes.0.nodes.1.contents())?) + } + sv_parser::AssignmentPattern::Repeat(repeat) => { + let (count, items) = &repeat.nodes.0.nodes.1; + let count = usize::try_from(integer(count)?) + .map_err(|_| unsupported("assignment pattern repetition count"))?; + let values = values(items.nodes.1.contents())?; + Items::Repeat(count, values) + } + sv_parser::AssignmentPattern::Array(array) => Items::Keyed( + array + .nodes + .0 + .nodes + .1 + .contents() + .into_iter() + .map(|(key, _, expr)| { + let key = match key { + sv_parser::ArrayPatternKey::ConstantExpression(index) => { + Key::Index(integer(index)?) + } + sv_parser::ArrayPatternKey::AssignmentPatternKey(key) => default_key(key)?, + }; + Ok((key, value(expr, tree, dims)?)) + }) + .collect::>()?, + ), + sv_parser::AssignmentPattern::Structure(structure) => Items::Keyed( + structure + .nodes + .0 + .nodes + .1 + .contents() + .into_iter() + .map(|(key, _, expr)| { + let key = match key { + sv_parser::StructurePatternKey::MemberIdentifier(member) => Key::Member( + identifier_text(RefNode::MemberIdentifier(member), tree) + .ok_or_else(|| unsupported("assignment pattern member name"))?, + ), + sv_parser::StructurePatternKey::AssignmentPatternKey(key) => { + default_key(key)? + } + }; + Ok((key, value(expr, tree, dims)?)) + }) + .collect::>()?, + ), + }; + Ok(Value::Pattern(BoundPattern { items })) +} + +impl Value { + pub(super) fn list(values: Vec) -> Self { + Self::Pattern(BoundPattern { + items: Items::List(values), + }) + } + fn lower( + &self, + shape: &VariableDimensions, + dims: &PackedDimensions, + default: bool, + ) -> Converted { + if let Self::Pattern(pattern) = self { + return pattern.lower(shape, dims); + } + let Self::Expression(value) = self else { + unreachable!() + }; + if default && let Some((dimension, rest)) = shape.unpacked.split_first() { + let count = eval_ast_const_expr(&dimension.width, &dims.const_env) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| unsupported("pattern target array size"))?; + let shape = VariableDimensions { + unpacked: rest.to_vec(), + ..shape.clone() + }; + return Ok(Expr::Concat(vec![self.lower(&shape, dims, true)?; count])); + } + if !shape.unpacked.is_empty() { + return Err(unsupported( + "scalar assignment pattern item for unpacked array", + )); + } + let width = patterns::shape_width(shape, dims) + .ok_or_else(|| unsupported("assignment pattern element width"))?; + let signed = + expr_signedness(value, &dims.expression_signedness, &dims.functions).unwrap_or(false); + Ok(Expr::Resize { + expr: Box::new(value.clone()), + width, + signed, + }) + } +} + +impl BoundPattern { + pub(super) fn lower( + &self, + shape: &VariableDimensions, + dims: &PackedDimensions, + ) -> Converted { + if let Items::Value(value) = &self.items { + return Ok(value.clone()); + } + let eval = |expr| { + eval_ast_const_expr(expr, &dims.const_env) + .ok_or_else(|| unsupported("assignment pattern target bounds")) + }; + let unpacked = !shape.unpacked.is_empty(); + let mut shapes = Vec::new(); + let keys; + if let Some((dim, rest)) = shape.unpacked.split_first() { + let left = eval(&dim.left)?; + let right = eval(&dim.right)?; + let count = usize::try_from(left.abs_diff(right) + 1) + .map_err(|_| unsupported("assignment pattern target size"))?; + shapes = vec![ + VariableDimensions { + unpacked: rest.to_vec(), + ..shape.clone() + }; + count + ]; + keys = (0..count) + .map(|i| { + Key::Index(if left <= right { + left + i as i128 + } else { + left - i as i128 + }) + }) + .collect::>(); + } else if !shape.members.is_empty() { + if shape.members.len() > 1 && shape.members.iter().all(|m| m.offset() == 0) { + return Err(unsupported("assignment pattern for a packed union")); + } + keys = shape + .members + .iter() + .map(|m| Key::Member(m.name().into())) + .collect(); + shapes.extend( + shape + .members + .iter() + .map(|m| procedural::dimensions_from_type(m.r#type())), + ); + } else if let Some((dim, rest)) = shape.packed.split_first() + && !rest.is_empty() + { + let left = eval(&dim.left)?; + let right = eval(&dim.right)?; + let count = usize::try_from(left.abs_diff(right) + 1) + .map_err(|_| unsupported("assignment pattern target size"))?; + shapes = vec![ + VariableDimensions { + packed: rest.to_vec(), + signed: shape.signed_element_depth == Some(1), + signed_element_depth: shape + .signed_element_depth + .and_then(|n| n.checked_sub(1)) + .filter(|n| *n > 0), + ..shape.clone() + }; + count + ]; + keys = (0..count) + .map(|i| { + Key::Index(if left <= right { + left + i as i128 + } else { + left - i as i128 + }) + }) + .collect(); + } else { + let width = patterns::shape_width(shape, dims) + .ok_or_else(|| unsupported("pattern target width"))?; + shapes = vec![ + VariableDimensions { + packed: Vec::new(), + signed: false, + signed_element_depth: None, + ..shape.clone() + }; + width + ]; + keys = (0..width).rev().map(|i| Key::Index(i as i128)).collect(); + } + let selected = match &self.items { + Items::Value(value) => return Ok(value.clone()), + Items::Repeat(count, values) => { + if count.checked_mul(values.len()) != Some(shapes.len()) { + return Err(unsupported( + "assignment pattern repetition size does not match target", + )); + } + (0..*count) + .flat_map(|_| values.iter().map(|v| (v, false))) + .collect() + } + Items::List(values) => { + if values.len() != shapes.len() { + return Err(unsupported(format!( + "assignment pattern with {} items for {} elements", + values.len(), + shapes.len() + ))); + } + values.iter().map(|v| (v, false)).collect::>() + } + Items::Keyed(items) => { + for (key, _) in items { + if *key != Key::Default && !keys.contains(key) { + return Err(unsupported("assignment pattern key outside target")); + } + } + keys.iter() + .map(|key| { + items + .iter() + .rev() + .find(|(k, _)| k == key) + .map(|(_, v)| (v, false)) + .or_else(|| { + items + .iter() + .rev() + .find(|(k, _)| *k == Key::Default) + .map(|(_, v)| (v, true)) + }) + .ok_or_else(|| unsupported("assignment pattern missing element")) + }) + .collect::>>()? + } + }; + let mut parts = selected + .into_iter() + .zip(shapes) + .map(|((v, default), shape)| v.lower(&shape, dims, default)) + .collect::>>()?; + if unpacked { + parts.reverse(); + } + Ok(if parts.len() == 1 { + parts.remove(0) + } else { + Expr::Concat(parts) + }) + } +} diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index d418d39f8ba..c380f993906 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -973,6 +973,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/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index aa2d08409df..1548d11804f 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -491,9 +491,9 @@ fn parameter_override( .into_iter() .any(|node| matches!(node, RefNode::AssignmentPatternExpression(_))) { - let text = constant_pattern_text(expr, syntax_tree, packed_dimensions)?; + let pattern = bound_patterns::from_param(expr, syntax_tree, packed_dimensions)?; let mut bound = ParameterOverride::new(name, None); - bound.pattern_text = Some(text); + bound.bound_pattern = Some(pattern); return Ok(bound); } // sv-parser accepts a single packed dimension on a named type as an @@ -552,186 +552,3 @@ fn parameter_override( } Ok(ParameterOverride::new(name, Some(value))) } - -fn constant_pattern_literal( - mut expression: ConstExpr, - dimensions: &PackedDimensions, - types: &HashMap, -) -> Converted { - fn freeze(expr: &mut ConstExpr, constants: &HashMap) { - match expr { - ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} - ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => { - freeze(expr, constants) - } - ConstExpr::Select { expr, bit } => { - freeze(expr, constants); - freeze(bit, constants); - } - ConstExpr::SelectRange { expr, msb, lsb, .. } => { - freeze(expr, constants); - freeze(msb, constants); - freeze(lsb, constants); - } - ConstExpr::Binary { left, right, .. } => { - freeze(left, constants); - freeze(right, constants); - } - ConstExpr::Mux { - condition, - then_expr, - else_expr, - } => { - freeze(condition, constants); - freeze(then_expr, constants); - freeze(else_expr, constants); - } - ConstExpr::Function { callee, args, .. } => { - for arg in args.iter_mut() { - freeze(arg, constants); - } - let lowered = args.iter().cloned().map(Into::into).collect::>(); - if let Callee::Subroutine(name) = callee - && let Some(literal) = - const_functions::eval_call_literal(name, &lowered, constants) - { - *expr = ConstExpr::Literal(typecheck::format_integral_literal_binary(&literal)); - } - } - } - } - // System/literal expressions retain their four-state masks. User functions - // run through the installed interpreter, with the caller's constant scope - // and their declared result widths, before the leaf is serialized. - freeze(&mut expression, &dimensions.const_env); - typecheck::eval_const_integral_literal_with_types( - &expression.into(), - &dimensions.const_env, - types, - ) - .ok_or_else(|| unsupported("nonconstant parameter pattern element")) -} - -/// Freeze pattern leaves in the instantiating module's constant environment. -/// Reparse in the callee to apply the target array/structure shape. -fn constant_pattern_text( - expression: &sv_parser::ParamExpression, - tree: &SyntaxTree, - dimensions: &PackedDimensions, -) -> Result { - let node = RefNode::ParamExpression(expression); - let tokens: Vec<_> = node - .clone() - .into_iter() - .filter_map(|node| { - if let RefNode::Locate(locate) = node { - Some(locate) - } else { - None - } - }) - .collect(); - let start = tokens - .iter() - .map(|locate| locate.offset) - .min() - .ok_or_else(|| unsupported("parameter pattern"))?; - let end = tokens - .iter() - .map(|locate| locate.offset + locate.len) - .max() - .unwrap(); - let original = tree - .get_str(&sv_parser::Locate { - offset: start, - line: 0, - len: end - start, - }) - .ok_or_else(|| unsupported("parameter pattern text"))?; - let types = parameter_types_from_const_env(&dimensions.const_env) - .into_iter() - .map(|(name, ty)| (name, (ty.width, ty.signed))) - .collect(); - let mut edits = Vec::new(); - for child in node { - let value = match child { - RefNode::AssignmentPatternExpression(pattern) if pattern.nodes.0.is_some() => Some( - patterns::constant_typed_pattern_text(pattern, tree, dimensions)?, - ), - RefNode::Primary(primary) - if !matches!( - primary, - sv_parser::Primary::PrimaryLiteral(_) - | sv_parser::Primary::MintypmaxExpression(_) - | sv_parser::Primary::AssignmentPatternExpression(_) - ) => - { - let expr = sv_parser::Expression::Primary(Box::new(primary.clone())); - let value = indexed_select_base(RefNode::Expression(&expr), tree, dimensions)?; - Some(format!( - "({})", - typecheck::format_integral_literal_binary(&constant_pattern_literal( - value, dimensions, &types - )?,) - )) - } - RefNode::ConstantPrimary(primary) - if !matches!( - primary, - sv_parser::ConstantPrimary::PrimaryLiteral(_) - | sv_parser::ConstantPrimary::MintypmaxExpression(_) - | sv_parser::ConstantPrimary::ConstantAssignmentPatternExpression(_) - ) => - { - let expr = - sv_parser::ConstantExpression::ConstantPrimary(Box::new(primary.clone())); - let value = - indexed_select_base(RefNode::ConstantExpression(&expr), tree, dimensions)?; - Some(format!( - "({})", - typecheck::format_integral_literal_binary(&constant_pattern_literal( - value, dimensions, &types - )?,) - )) - } - // Retain literals, operators and parentheses for the callee's - // assignment context, including unbased fills and wider arithmetic. - // Descendant primary references still bind in the caller, also - // inside constant-expression repetition counts and index keys. - _ => None, - }; - let Some(replacement) = value else { - continue; - }; - let tokens: Vec<_> = child - .into_iter() - .filter_map(|node| { - if let RefNode::Locate(locate) = node { - Some(locate) - } else { - None - } - }) - .collect(); - let low = tokens.iter().map(|locate| locate.offset).min().unwrap(); - let high = tokens - .iter() - .map(|locate| locate.offset + locate.len) - .max() - .unwrap(); - edits.push((low, high, replacement)); - } - edits.sort_by_key(|(low, high, _)| (*low, std::cmp::Reverse(*high))); - let mut result = String::new(); - let mut cursor = start; - for (low, high, replacement) in edits { - if low < cursor { - continue; - } - result.push_str(&original[cursor - start..low - start]); - result.push_str(&replacement); - cursor = high; - } - result.push_str(&original[cursor - start..]); - Ok(result) -} 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/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/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index f9f49f37ab0..f95528ec534 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -91,11 +91,11 @@ fn typed_pattern_type( /// Serialize a typed constant pattern as positional values already converted /// to its caller-side type (IEEE 1800-2023 10.9). Packed values become /// literals; only unpacked dimensions need positional patterns. -pub(super) fn constant_typed_pattern_text( +pub(super) fn constant_typed_pattern_value( pattern: &sv_parser::AssignmentPatternExpression, tree: &SyntaxTree, dims: &PackedDimensions, -) -> Converted { +) -> Converted { let r#type = typed_pattern_type(pattern, tree, dims)?; let shape = procedural::dimensions_from_type(&r#type); let value = expr_from_pattern(&pattern.nodes.1, &shape, tree, dims)?; @@ -112,15 +112,15 @@ pub(super) fn constant_typed_pattern_text( }; let value = typecheck::parse_integral_literal(&value) .ok_or_else(|| unsupported("typed parameter pattern value"))?; - pattern_value_text(&value, &shape, 0, dims) + pattern_value(&value, &shape, 0, dims) } -fn pattern_value_text( +fn pattern_value( value: &typecheck::IntegralLiteral, shape: &VariableDimensions, offset: usize, dims: &PackedDimensions, -) -> Converted { +) -> Converted { let mut parts = Vec::new(); if let Some((dimension, rest)) = shape.unpacked.split_first() { let (_, _, count) = dimension_bounds(&dimension.left, &dimension.right, dims)?; @@ -131,7 +131,7 @@ fn pattern_value_text( let width = shape_width(&element, dims) .ok_or_else(|| unsupported("typed pattern element width"))?; for position in 0..count { - parts.push(pattern_value_text( + parts.push(pattern_value( value, &element, offset + position * width, @@ -152,9 +152,11 @@ fn pattern_value_text( literal.value ^= &literal.value & &literal.mask; literal.mask = num_bigint::BigUint::default(); } - return Ok(typecheck::format_integral_literal_binary(&literal)); + return Ok(bound_patterns::Value::Expression(Expr::Literal( + typecheck::format_integral_literal_binary(&literal), + ))); } - Ok(format!("'{{{}}}", parts.join(", "))) + Ok(bound_patterns::Value::list(parts)) } /// The value of one element of a pattern, as a `shape`. diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index c51fd75dc29..12a4ccdbfa5 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/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index f6b51f36e3e..0987ddfbabd 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -24,6 +24,7 @@ pub(super) struct ScopeSymbols { pub type_aliases: HashMap, /// Bound type parameters, keyed by their declaration offset in this tree. pub type_parameter_bindings: HashMap, + pub pattern_parameter_bindings: HashMap, pub enum_constants: EnumMemberConstants, pub functions: HashMap, pub function_return_types: HashMap, @@ -376,6 +377,7 @@ impl ScopeSymbols { .collect(); ScopeSymbols { type_parameter_bindings: self.type_parameter_bindings.clone(), + pattern_parameter_bindings: self.pattern_parameter_bindings.clone(), const_env, parameter_values: self .parameter_values diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 86daae84697..921e99983d2 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 = [ @@ -1222,6 +1233,7 @@ mod tests { "Top", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -1468,6 +1480,7 @@ mod tests { "Child", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -1495,6 +1508,7 @@ mod tests { "Child", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages ) @@ -1643,6 +1657,7 @@ mod tests { "Child", &HashMap::default(), &[("T".into(), ty)], + &[], &ModuleInterfaces::default(), &packages, ) diff --git a/crates/celox-sv-analyzer/src/ast/type_parameters.rs b/crates/celox-sv-analyzer/src/ast/type_parameters.rs index 9667f335858..536d748e5c4 100644 --- a/crates/celox-sv-analyzer/src/ast/type_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/type_parameters.rs @@ -1,4 +1,4 @@ -//! Type parameter bindings and the remaining value-pattern source edits. +//! Declaration-scoped parameter bindings. use super::*; @@ -100,13 +100,6 @@ pub(super) fn resolve(mut ty: Type, env: &HashMap) -> Option Some(ty) } -/// A source text edit: replace `start..end` with `replacement`. -struct Edit { - start: usize, - end: usize, - replacement: String, -} - /// The span of `node` in the original source text. Token offsets refer to /// the preprocessed text, which can differ from the source (the preprocessor /// widens the space after `"DPI-C"`), so each token is mapped back and text @@ -136,54 +129,20 @@ pub(super) fn node_span(node: RefNode<'_>, syntax_tree: &SyntaxTree) -> Option<( range } -/// Apply the edits that fall inside `text[range]`, dropping any edit nested in -/// an earlier (outer) one. -fn apply_edits(text: &str, range: (usize, usize), mut edits: Vec) -> String { - edits.retain(|edit| edit.start >= range.0 && edit.end <= range.1); - edits.sort_by_key(|edit| (edit.start, std::cmp::Reverse(edit.end))); - let mut result = String::new(); - let mut cursor = range.0; - for edit in edits { - if edit.start < cursor { - continue; - } - result.push_str(&text[cursor..edit.start]); - result.push_str(&edit.replacement); - cursor = edit.end; - } - result.push_str(&text[cursor..range.1]); - result -} - -/// Override array/structure value parameters before their target shapes are -/// lowered. Only overridable module parameters may be rebound, never locals. -pub(crate) fn apply_pattern_parameter_overrides( - code: &str, +/// Locate value-pattern bindings by declaration, so nested names stay local. +pub(super) fn bind_patterns( + node: RefNode<'_>, tree: &SyntaxTree, - module_name: &str, - overrides: &[(String, String)], -) -> Result, AnalyzerError> { - if overrides.is_empty() { - return Ok(None); - } - for node in tree { - if !matches!( - node, - RefNode::ModuleDeclarationAnsi(_) | RefNode::ModuleDeclarationNonansi(_) - ) { - continue; - } - if module_name_from_node(node.clone(), tree)? != module_name { - continue; - } - let allowed = declarations::module_interface_from_node(node.clone(), tree)?.parameters; - let mut edits = Vec::new(); - let mut found = HashSet::default(); - let mut declarations = module_parameter_port_list(node.clone()) + overrides: &[(String, BoundPattern)], +) -> Converted> { + let allowed = declarations::module_interface_from_node(node.clone(), tree)?.parameters; + let mut declarations = module_parameter_port_list(node.clone()) + .into_iter() + .collect::>(); + declarations.extend( + scope_declarations(node) .into_iter() - .collect::>(); - declarations.extend(scope_declarations(node.clone()).into_iter().filter_map( - |declaration| { + .filter_map(|declaration| { if let sv_parser::PackageOrGenerateItemDeclaration::ParameterDeclaration( declaration, ) = declaration @@ -192,42 +151,39 @@ pub(crate) fn apply_pattern_parameter_overrides( } else { None } - }, - )); - for child in declarations.into_iter().flat_map(|node| node.into_iter()) { - let RefNode::ParamAssignment(param) = child else { - continue; - }; - let name = parameter_name(RefNode::ParameterIdentifier(¶m.nodes.0), tree)?; - let Some((_, bound)) = overrides.iter().find(|(candidate, _)| *candidate == name) - else { - continue; - }; - if !allowed.contains(&name) { - return Err(unsupported(format!( - "pattern override of non-overridable parameter `{name}`" - ))); - } - let Some((_, value)) = ¶m.nodes.2 else { - return Err(unsupported(format!( - "array parameter `{name}` without a default" - ))); - }; - let (start, end) = node_span(RefNode::ConstantParamExpression(value), tree) - .ok_or_else(|| unsupported("array parameter source span"))?; - edits.push(Edit { - start, - end, - replacement: bound.clone(), - }); - found.insert(name); + }), + ); + let mut bindings = HashMap::default(); + for (name, value) in overrides { + if !allowed.contains(name) { + return Err(unsupported(format!( + "pattern override of non-overridable parameter `{name}`" + ))); } - for (name, _) in overrides { - if !found.contains(name) { - return Err(unsupported(format!("unknown array parameter `{name}`"))); - } + let param = declarations + .iter() + .flat_map(|node| node.clone().into_iter()) + .find_map(|child| { + if let RefNode::ParamAssignment(param) = child + && parameter_name(RefNode::ParameterIdentifier(¶m.nodes.0), tree) + .ok() + .as_ref() + == Some(name) + { + Some(param) + } else { + None + } + }) + .ok_or_else(|| unsupported(format!("unknown array parameter `{name}`")))?; + let offset = identifier_locate(RefNode::ParameterIdentifier(¶m.nodes.0)) + .ok_or_else(|| unsupported("parameter location"))? + .offset; + if bindings.insert(offset, value.clone()).is_some() { + return Err(unsupported(format!( + "duplicate parameter override `{name}`" + ))); } - return Ok(Some(apply_edits(code, (0, code.len()), edits))); } - Err(unsupported(format!("module `{module_name}`"))) + Ok(bindings) } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 10bdcdf8c7e..ef9e6402a03 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..2a6252fef15 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; @@ -418,7 +419,7 @@ pub struct ParameterOverride { name: String, value: Option, bound_type: Option, - pattern_text: Option, + bound_pattern: Option, } impl ParameterOverride { @@ -426,19 +427,19 @@ impl ParameterOverride { name: String, value: Option, bound_type: Option, - pattern_text: Option, + bound_pattern: Option, ) -> Self { Self { name, value, bound_type, - pattern_text, + bound_pattern, } } /// A constant assignment pattern, evaluated in the caller scope. - pub fn pattern_text(&self) -> Option<&str> { - self.pattern_text.as_deref() + pub fn bound_pattern(&self) -> Option<&crate::ast::BoundPattern> { + self.bound_pattern.as_ref() } pub fn name(&self) -> &str { diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 2ad5920849f..23613967ae5 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), @@ -327,6 +328,7 @@ pub fn analyze_source_module_with_packages( module_name, &overrides, &[], + &[], &ModuleInterfaces::default(), packages, ) diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 86d87a19cff..052fe3b0658 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -14,7 +14,6 @@ use crate::{AnalyzerError, Ir, ModuleInterfaces, Packages, analyze, ast, ir, syn /// remain local to each analysis. Like `sv-parser`'s tree, this value is confined /// to the parsing thread; consumers can share it there with [`std::rc::Rc`]. pub struct ParsedSource { - code: String, path: PathBuf, tree: sv_parser::SyntaxTree, index: ast::module_index::ModuleIndex, @@ -25,30 +24,12 @@ impl ParsedSource { let tree = syntax::parse_source(code, path)?; let index = ast::with_call_sites(|| ast::module_index::ModuleIndex::new(&tree))?; Ok(Self { - code: code.to_string(), path: path.to_path_buf(), tree, index, }) } - /// Bind assignment-pattern parameters with values frozen in the caller. - pub fn with_pattern_parameter_overrides( - &self, - module_name: &str, - overrides: &[(String, String)], - ) -> Result, AnalyzerError> { - ast::type_parameters::apply_pattern_parameter_overrides( - &self.code, - &self.tree, - module_name, - overrides, - )? - .as_deref() - .map(|code| Self::parse(code, &self.path)) - .transpose() - } - pub fn module_names(&self) -> &[String] { self.index.names() } @@ -119,6 +100,7 @@ impl ParsedSource { module_name: &str, overrides: &HashMap, type_overrides: &[(String, ast::Type)], + pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, ) -> Result { @@ -126,6 +108,7 @@ impl ParsedSource { module_name, overrides, type_overrides, + pattern_overrides, interfaces, packages, ) @@ -140,7 +123,7 @@ impl ParsedSource { interfaces: &ModuleInterfaces, ) -> Result { let packages = Self::analyze_packages(&[self])?; - self.analyze_module_with_packages(module_name, overrides, &[], interfaces, &packages) + self.analyze_module_with_packages(module_name, overrides, &[], &[], interfaces, &packages) } fn analyze_module_with_packages( @@ -148,6 +131,7 @@ impl ParsedSource { module_name: &str, overrides: &HashMap, type_overrides: &[(String, ast::Type)], + pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, ) -> Result { @@ -164,6 +148,7 @@ impl ParsedSource { ast::ModuleParameterBindings { values: &overrides, types: type_overrides, + patterns: pattern_overrides, }, interfaces, packages, @@ -316,6 +301,7 @@ mod tests { "Top", &HashMap::default(), &types, + &[], &ModuleInterfaces::default(), &packages, ) @@ -361,6 +347,7 @@ mod tests { "Child", &HashMap::default(), &bindings, + &[], &ModuleInterfaces::default(), &packages, ) @@ -392,6 +379,7 @@ mod tests { "Child", &HashMap::default(), &[("T".into(), type_binding("bit signed [7:0]"))], + &[], &ModuleInterfaces::default(), &packages, ) @@ -426,6 +414,7 @@ mod tests { "Child", &HashMap::default(), &bindings, + &[], &ModuleInterfaces::default(), &packages ) @@ -437,6 +426,7 @@ mod tests { "Child", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -531,16 +521,24 @@ mod pattern_override_tests { Path::new("pattern_scope.sv"), ) .unwrap(); - let rebound = source - .with_pattern_parameter_overrides("Top", &[("Q".into(), "'{-3, -5}".into())]) + let caller = crate::analyze_source( + "module Caller; Top #(.Q('{-3, -5})) t(); endmodule", + Path::new("caller.sv"), + ) + .unwrap(); + let bound = caller.modules()[0].instances()[0].parameter_overrides()[0] + .bound_pattern() .unwrap() - .unwrap(); - assert!(rebound.code.contains("localparam int Q = 9;")); - let ir = rebound - .analyze_module_with_parameter_expr_overrides( + .clone(); + let packages = ParsedSource::analyze_packages(&[&source]).unwrap(); + let ir = source + .analyze_module( "Top", &HashMap::default(), + &[], + &[("Q".into(), bound)], &ModuleInterfaces::default(), + &packages, ) .unwrap(); assert_eq!(ir.modules()[0].initial_processes().len(), 1); @@ -570,22 +568,21 @@ mod pattern_override_tests { .find(|module| module.name() == "Top") .unwrap(); for instance in top.instances() { - let pattern = instance.parameter_overrides()[0].pattern_text().unwrap(); - assert!(!pattern.contains('N'), "{pattern}"); + let pattern = instance.parameter_overrides()[0].bound_pattern().unwrap(); let child = ParsedSource::parse( "module Child #(parameter int N = 1, parameter byte Q [2] = '{1, 2}); endmodule", Path::new("child.sv"), ) .unwrap(); - let rebound = child - .with_pattern_parameter_overrides("Child", &[("Q".into(), pattern.into())]) - .unwrap() - .unwrap(); - rebound - .analyze_module_with_parameter_expr_overrides( + let packages = ParsedSource::analyze_packages(&[&child]).unwrap(); + child + .analyze_module( "Child", &HashMap::default(), + &[], + &[("Q".into(), pattern.clone())], &ModuleInterfaces::default(), + &packages, ) .unwrap(); } 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..468d13d2ecb 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -1406,6 +1406,7 @@ fn resolves_imported_constant_parameter_part_selects() { "Top", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -3485,6 +3486,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( diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 9f02025d908..9349c2ffe17 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -469,3 +469,46 @@ (eval) (assert_eq value 9) (assert_eq raw (fourstate 13 6))) + +(case parameter_patterns_keep_original_declarations_and_isolated_bindings + (source "pattern_binding_isolation.sv" #" + `define ORIGINAL_VALUES '{1, 2} + module Child #(parameter int N = 9, parameter byte Q [2] = `ORIGINAL_VALUES) + (output logic [15:0] y, output logic [7:0] local_y); + assign y = {Q[0], Q[1]}; + always_comb begin + localparam byte Q = 7; + local_y = Q; + end + endmodule + module Top(output logic [15:0] defaults, repeated, keyed, + output logic [7:0] local_default, local_repeated, local_keyed); + localparam N = 2; + Child a(defaults, local_default); + Child #(.Q('{N{-N}})) b(repeated, local_repeated); + Child #(.Q('{N-2: -N, default: N+1})) c(keyed, local_keyed); + endmodule + `undef ORIGINAL_VALUES + "#) + (top Top) + (assert_eq defaults 0x0102) + (assert_eq repeated 0xfefe) + (assert_eq keyed 0xfe03) + (assert_eq local_default 7) + (assert_eq local_repeated 7) + (assert_eq local_keyed 7)) + +(case parameter_patterns_preserve_enclosing_expressions + (source "pattern_expressions.sv" #" + module Child #(parameter logic [15:0] P = 0)(output logic [15:0] y); + assign y = P; + endmodule + module Top(output logic [15:0] added, negated); + typedef logic [7:0] byte_t; + Child #(.P(byte_t'{default: 1} + 16'd1)) a(added); + Child #(.P(~(byte_t'{default: 0} | 16'd0))) b(negated); + endmodule + "#) + (top Top) + (assert_eq added 256) + (assert_eq negated 65535)) 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-test-suite/verification/sv/icarus/generate.json b/crates/celox-test-suite/verification/sv/icarus/generate.json index 8e62f79fb18..d04abdd4415 100644 --- a/crates/celox-test-suite/verification/sv/icarus/generate.json +++ b/crates/celox-test-suite/verification/sv/icarus/generate.json @@ -181,6 +181,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/hierarchy.json b/crates/celox-test-suite/verification/sv/icarus/hierarchy.json index 15a70b06b1a..ee5f58bdfcb 100644 --- a/crates/celox-test-suite/verification/sv/icarus/hierarchy.json +++ b/crates/celox-test-suite/verification/sv/icarus/hierarchy.json @@ -19,6 +19,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -42,6 +43,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -65,6 +67,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -88,6 +91,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -215,6 +219,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -238,6 +243,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -267,6 +273,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] } @@ -290,6 +297,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] } @@ -313,9 +321,58 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] } + }, + { + "name": "hierarchy::parameter_patterns_preserve_enclosing_expressions", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "known_issue": { + "id": "sv_icarus_syntax", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "name": "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "known_issue": { + "id": "sv_icarus_unpacked_array_parameters", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json index 0ca89492be7..1811d025379 100644 --- a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json +++ b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json @@ -36,6 +36,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -81,6 +82,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -115,6 +117,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -226,6 +229,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -249,6 +253,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/procedural.json b/crates/celox-test-suite/verification/sv/icarus/procedural.json index eb4a98cbe32..dd1f06d9948 100644 --- a/crates/celox-test-suite/verification/sv/icarus/procedural.json +++ b/crates/celox-test-suite/verification/sv/icarus/procedural.json @@ -8,6 +8,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", diff --git a/crates/celox-test-suite/verification/sv/icarus/review_regressions.json b/crates/celox-test-suite/verification/sv/icarus/review_regressions.json index c75b20bbe78..c820979706a 100644 --- a/crates/celox-test-suite/verification/sv/icarus/review_regressions.json +++ b/crates/celox-test-suite/verification/sv/icarus/review_regressions.json @@ -35,6 +35,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -180,6 +181,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/synthesizable.json b/crates/celox-test-suite/verification/sv/icarus/synthesizable.json index 1a4adf0dcf3..d93d7be4c81 100644 --- a/crates/celox-test-suite/verification/sv/icarus/synthesizable.json +++ b/crates/celox-test-suite/verification/sv/icarus/synthesizable.json @@ -328,6 +328,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index a99b8693025..a37381f1e66 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -279,6 +279,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -622,6 +623,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1233,6 +1235,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1256,6 +1259,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1302,6 +1306,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1417,6 +1422,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index cabc838a58e..cd555abd3a4 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -96,6 +96,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { @@ -111,7 +112,8 @@ "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", "hierarchy::parameter_patterns_transfer_packed_values", "hierarchy::parameter_patterns_override_scalar_defaults", - "hierarchy::parameter_patterns_preserve_packed_member_states" + "hierarchy::parameter_patterns_preserve_packed_member_states", + "hierarchy::parameter_patterns_preserve_enclosing_expressions" ] } }, @@ -145,6 +147,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { @@ -158,6 +161,7 @@ "system_functions::isunbounded_reports_bounded_array_parameters", "hierarchy::parameter_patterns_evaluate_caller_constant_functions", "hierarchy::parameter_patterns_override_body_declarations", + "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings", "system_functions::unpacked_dimensions_publishes_array_parameters_before_declarations", "system_functions::unpacked_dimensions_resolves_package_array_constants", "system_functions::unpacked_dimensions_resolves_types_and_constant_scopes", diff --git a/crates/celox-test-suite/verification/sv/limitations/pattern-bindings-icarus.json b/crates/celox-test-suite/verification/sv/limitations/pattern-bindings-icarus.json new file mode 100644 index 00000000000..6d86e8f383b --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/pattern-bindings-icarus.json @@ -0,0 +1,57 @@ +{ + "cases": [ + { + "case_fingerprint": "46e32699a44c76e09e170464362d07224abb6770e1a7e061babfe855a66dfbf4", + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:15: syntax error\n/source_0.sv:15: error: Syntax error in parameter value assignment list.\n/source_0.sv:15: error: Invalid module instantiation\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: Syntax error in parameter value assignment list.\n/source_0.sv:16: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings", + "phase": "compile", + "reused": false, + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792281566 + }, + { + "case_fingerprint": "b0224fd8ab450a706e01b2fb34f41f5218e61c9d7f04558216838fb4ecad6270", + "category": "Hierarchy", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in parameter value assignment list.\n/source_0.sv:7: error: Invalid module instantiation\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in parameter value assignment list.\n/source_0.sv:8: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_preserve_enclosing_expressions", + "phase": "compile", + "reused": false, + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792281566 + } + ], + "context_fingerprint": "210520fad7d12ef78257b83bd11d81ddda693f68bfdae0ee9de0cae78a0ab483", + "counts": { + "compile_error": 2, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "incremental": true, + "run_counts": { + "fresh": 2, + "reused": 0 + }, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "retained_selection": "The two newly added parameter-pattern regressions from the local parameter_patterns run; existing ignored cases are omitted." +} 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 73fd74ae014..680a8e3eab7 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 c22fc1f196b..2ce9ad8aee0 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 80b636b6991..f924bbcab9a 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1347,8 +1347,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); @@ -2332,8 +2336,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(); @@ -2374,8 +2382,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(); @@ -2420,8 +2432,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(); @@ -2480,8 +2496,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(); @@ -2675,8 +2695,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(); @@ -3031,8 +3055,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/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 5367c930e02..1c98894e89e 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,8 @@ use super::*; sv_backends! { + fn parameter_patterns_keep_original_declarations_and_isolated_bindings(sim) { @case "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings"; } + fn parameter_patterns_preserve_enclosing_expressions(sim) { @case "hierarchy::parameter_patterns_preserve_enclosing_expressions"; } fn widens_small_parameters_preserving_four_state_bits(sim) { @case "hierarchy::widens_small_parameters_preserving_four_state_bits"; } 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..27dfb7c846c 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -49,112 +49,86 @@ 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)"] + #[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"; - #[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"; } 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"); +});