diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index cc10985fc16..921f9972b72 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2049,9 +2049,10 @@ impl<'p, 'a> Comb<'p, 'a> { 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::Delay { .. } + | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) + | 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 ad0ca48546b..3d57c5e018e 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2629,7 +2629,10 @@ impl<'p, 'a> Ff<'p, 'a> { fn exec(&mut self, stmt: &sv::ir::Stmt) -> Result { if matches!( stmt, - sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::Wait(_) + sv::ir::Stmt::Delay { .. } + | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) + | sv::ir::Stmt::Wait(_) ) && (self.kernel.is_none() || self.active_calls.iter().any(|name| { self.m @@ -2676,6 +2679,10 @@ impl<'p, 'a> Ff<'p, 'a> { self.wait_event(items)?; Ok(true) } + sv::ir::Stmt::WaitImplicit(reads) => { + self.wait_implicit(reads)?; + Ok(true) + } sv::ir::Stmt::Wait(condition) => { self.wait_level(condition)?; Ok(true) @@ -4937,6 +4944,65 @@ impl Ff<'_, '_> { fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { let mut terms = Vec::new(); let mut samples = Vec::new(); + self.event_terms(items, &mut terms, &mut samples)?; + self.suspend_on(terms, samples) + } + + /// `@*` (IEEE 1800-2023 9.4.2.2): wait for a change of a variable that + /// `reads` read. The module variables are those a combinational + /// `always @*` is sensitive to, from the same analysis, so folded + /// branches and the defaults of omitted subroutine arguments count. A + /// process-local variable it reads is sampled like an operand of an + /// event expression. + fn wait_implicit(&mut self, reads: &[sv::ir::Stmt]) -> Result<(), sv::AnalyzerError> { + // The expressions of timing controls are not part of the event list. + let reads = without_timing_controls(reads); + let reads = reads.as_slice(); + let mut ids: Vec = self + .m + .implicit_reads(reads, false) + .into_iter() + .map(|atom| atom.id) + .collect(); + ids.sort_unstable(); + ids.dedup(); + let mut terms: Vec<_> = ids + .into_iter() + .map(|id| (id, CounterKind::Changes)) + .collect(); + let mut names = HashSet::default(); + for stmt in reads { + stmt.clone().visit_mut( + &mut |expr: &mut sv::ir::Expr| expr_idents(expr, &mut names), + &mut |_: &mut sv::ir::LValue| {}, + &mut |_: &mut String| {}, + ); + } + let mut locals: Vec = names + .into_iter() + .filter(|name| self.m.id(name).is_some_and(|id| self.m.is_hidden(id))) + .collect(); + locals.sort_unstable(); + let locals: Vec<_> = locals + .into_iter() + .map(|name| sv::ir::EventItem { + edge: sv::ir::EventEdge::Any, + expr: sv::ir::Expr::Ident(name), + }) + .collect(); + let mut samples = Vec::new(); + self.event_terms(&locals, &mut terms, &mut samples)?; + self.suspend_on(terms, samples) + } + + /// The counter terms of `items` and the samples the process takes of + /// their expressions before it suspends. + fn event_terms( + &mut self, + items: &[sv::ir::EventItem], + terms: &mut Vec<(SourceVarId, CounterKind)>, + samples: &mut Vec<(String, sv::ir::Expr)>, + ) -> Result<(), sv::AnalyzerError> { for item in items { let expr = self.propagate(&item.expr); let edge = match item.edge { @@ -4953,12 +5019,12 @@ impl Ff<'_, '_> { let id = match &expr { sv::ir::Expr::Ident(name) => match self.m.id(name) { Some(id) if !self.m.is_hidden(id) => id, - Some(_) => self.event_expression(&expr, &mut samples)?, + Some(_) => self.event_expression(&expr, samples)?, // A constant never changes. None if self.m.constants.contains_key(name) => continue, None => return Err(unsupported(format!("event expression `{name}`"))), }, - _ => self.event_expression(&expr, &mut samples)?, + _ => self.event_expression(&expr, samples)?, }; match item.edge { sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), @@ -4970,6 +5036,15 @@ impl Ff<'_, '_> { } } } + Ok(()) + } + + /// Suspend until one of `terms` counts, after taking `samples`. + fn suspend_on( + &mut self, + terms: Vec<(SourceVarId, CounterKind)>, + samples: Vec<(String, sv::ir::Expr)>, + ) -> Result<(), sv::AnalyzerError> { for (target, value) in samples { self.assign(&sv::ir::LValue::Ident(target), &value)?; } @@ -5217,12 +5292,68 @@ pub(super) struct KernelUnit { /// may not suspend. const LOOP_YIELD_BITS: usize = 16; +/// `stmts` without their delays, event controls and waits, at any depth. +fn without_timing_controls(stmts: &[sv::ir::Stmt]) -> Vec { + use sv::ir::Stmt; + stmts + .iter() + .filter(|stmt| { + !matches!( + stmt, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) + ) + }) + .map(|stmt| match stmt { + Stmt::If { + condition, + then_body, + else_body, + } => Stmt::If { + condition: condition.clone(), + then_body: without_timing_controls(then_body), + else_body: without_timing_controls(else_body), + }, + Stmt::Case { + kind, + selector, + items, + default, + } => Stmt::Case { + kind: *kind, + selector: selector.clone(), + items: items + .iter() + .map(|item| sv::ir::CaseItem { + labels: item.labels.clone(), + body: without_timing_controls(&item.body), + }) + .collect(), + default: default.as_deref().map(without_timing_controls), + }, + Stmt::Loop { + kind, + init, + condition, + step, + body, + } => Stmt::Loop { + kind: kind.clone(), + init: without_timing_controls(init), + condition: condition.clone(), + step: without_timing_controls(step), + body: without_timing_controls(body), + }, + stmt => stmt.clone(), + }) + .collect() +} + /// 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(_) + sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::WaitImplicit(_) ) }) } @@ -5336,6 +5467,7 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { sv::ir::Stmt::SystemTask { .. } | sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) | sv::ir::Stmt::Wait(_) => effect = true, _ => {} }); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 54a49321b97..71ab51281e9 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -349,6 +349,7 @@ impl<'a> ProcModule<'a> { stmt, sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) | sv::ir::Stmt::Wait(_) | sv::ir::Stmt::Assign { nonblocking: true, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 3d026b99fd7..7b61af634ae 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1300,7 +1300,7 @@ impl Module { } procedural::timed_tasks::classify( subroutines.iter().chain(imported.subroutines.iter()), - &comb_processes, + &mut comb_processes, &mut ff_processes, &mut initial_processes, )?; @@ -2254,6 +2254,9 @@ impl LValue { pub struct CombProcess { creation_order: usize, site: Option, + /// Where the procedure is written, for an `always @*` that becomes a + /// process when it calls a timed task. + process_site: Option, kind: CombProcessKind, condition: Option, assignments: Vec, @@ -2292,6 +2295,7 @@ impl CombProcess { Self { creation_order: 0, site: None, + process_site: None, sensitivity_body: Vec::new(), kind, condition, @@ -2304,6 +2308,7 @@ impl CombProcess { Self { creation_order: 0, site: None, + process_site: None, sensitivity_body: Vec::new(), kind, condition, diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 23ac807196a..d958288a35a 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -38,10 +38,9 @@ pub(super) fn comb_processes_from_scope( )?; for process in &mut processes[start..] { process.creation_order = creation_order; - process.site = procedural::source_span( - syntax_tree.declarations().body_item(item.id).tokens, - syntax_tree, - ); + let tokens = syntax_tree.declarations().body_item(item.id).tokens; + process.site = procedural::source_span(tokens, syntax_tree); + process.process_site = procedural::process_site("always", tokens, syntax_tree); for assignment in &mut process.assignments { item.assignment(assignment); } diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 66c9f602e7e..0ddd4912b4f 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -1345,7 +1345,9 @@ impl Frame<'_> { // diagnostic belongs to the declaration, not to evaluation. Stmt::SystemTask { .. } => {} // A function has no timing controls (IEEE 1800-2023 13.4). - Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::Wait(_) => return None, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { + return None; + } Stmt::AssignConcat { .. } | Stmt::Call { .. } => return None, } Some(Flow::Next) diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index d78ed34fa7c..f915a50fdf3 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -118,6 +118,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( return CombProcess { creation_order: process.creation_order, site: process.site, + process_site: process.process_site, sensitivity_body, ..CombProcess::procedural(process.kind, condition, body) }; @@ -140,6 +141,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( ); result.creation_order = process.creation_order; result.site = process.site; + result.process_site = process.process_site; result.sensitivity_body = sensitivity_body; result } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index d3fe2977483..353055ff483 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -26,7 +26,16 @@ pub(in crate::ast) fn query_context_for_operand( tree: &AnalysisContext<'_>, context: &PackedDimensions, ) -> Converted { - if context.scope_types_complete { + // Literals carry their type in their spelling and cannot reference lexical + // declarations. Pattern elements otherwise rediscover the whole scope for + // each literal while the surrounding declaration is still being bound. + let operand = expression_binding::ungroup(root, tree.declarations()); + if context.scope_types_complete + || matches!( + tree.declarations().expression(operand).kind, + ExprKind::Literal(_) + ) + { return Ok(query_context(context)); } Ok(query_context(&query_operand_dimensions_id( diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index 10c9d8a9e4f..f29dadcf3e5 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -517,3 +517,59 @@ fn recursive_generate_dimension_discovery_uses_explicit_specialization() { ); } } + +#[test] +fn preliminary_literal_queries_do_not_discover_scope_declarations() { + let tree = crate::source_tree::parse_scope_fixture( + r#"module Top; + logic [7:0] unrelated [0:31]; + localparam A = $bits(123); + localparam B = $bits((8'shff)); + localparam C = $bits(4'bx); + localparam D = $bits("ab"); + localparam E = $bits('1); + endmodule"#, + Path::new("literal_query.sv"), + ) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + let input = PackedDimensions::default(); + let calls = native_calls(&tree); + assert_eq!(calls.len(), 5); + // Keep the discovery path as an independent reference for the result. + let discovered = calls + .iter() + .map(|call| { + let celox_sv_syntax::ExprKind::Call { arguments, .. } = + &tree.declarations().expression(*call).kind + else { + unreachable!() + }; + let context = + query_operand_dimensions_id(arguments[0].value.unwrap(), &tree, &input).unwrap(); + query_number( + *call, + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&context), + ) + }) + .collect::>(); + SYNTAX_TYPE_DISCOVERIES.with(|count| count.set(0)); + let direct = calls + .iter() + .map(|call| { + query_number( + *call, + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&input), + ) + }) + .collect::>(); + assert_eq!(&direct[..4], &[Some(32), Some(8), Some(4), Some(16)]); + assert_eq!(direct, discovered); + assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|count| count.get()), 0); +} diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index dae02b92839..884c9ebcffe 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -611,6 +611,17 @@ impl Flow<'_> { } Ok(Exits::next(written)) } + // An `@*` samples what its statements read; they do not run. + Stmt::WaitImplicit(reads) => { + let mut exprs = Vec::new(); + for stmt in reads { + stmt.walk(&mut |stmt| exprs.extend(stmt_exprs(stmt))); + } + for expr in exprs { + self.read(expr, written)?; + } + Ok(Exits::next(written)) + } } } @@ -749,7 +760,8 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { Stmt::Local { init, .. } => init.iter().collect(), Stmt::Delay { amount: expr, .. } | Stmt::Wait(expr) => vec![expr], Stmt::WaitEvent(items) => items.iter().map(|item| &item.expr).collect(), - Stmt::Break | Stmt::Continue => Vec::new(), + // The statements of an `@*` describe its reads and do not run. + Stmt::WaitImplicit(_) | Stmt::Break | Stmt::Continue => Vec::new(), } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs index 58bfe2b180a..76e37f3c563 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -3,7 +3,7 @@ use super::*; pub(in crate::ast) fn classify<'a>( subroutines: impl Iterator, - comb: &[CombProcess], + comb: &mut Vec, ff: &mut Vec, processes: &mut Vec, ) -> Result<(), AnalyzerError> { @@ -86,11 +86,59 @@ pub(in crate::ast) fn classify<'a>( )); } } - if comb.iter().any(|process| suspends(&process.body, &timed)) { - return Err(unsupported("timed task call in a combinational process")); - } let initial_count = processes.len(); let mut retained = Vec::new(); + for process in std::mem::take(comb) { + if !suspends(&process.body, &timed) { + if process.kind == CombProcessKind::AlwaysStar && assigns_nonblocking(&process.body) { + return Err(unsupported("nonblocking assignment inside always_comb")); + } + retained.push(process); + continue; + } + // An `always @*` is an ordinary `always` procedure (IEEE 1800-2023 + // 9.2.2.2.2): calling a timed task makes it a process that waits on + // its implicit event list before each run of its statement. + // `always_comb` and `always_latch` may not suspend (9.2.2.2). + let context = match process.kind { + CombProcessKind::AlwaysStar => None, + CombProcessKind::AlwaysLatch => Some("an always_latch body"), + CombProcessKind::AlwaysComb | CombProcessKind::ContinuousAssign => { + Some("an always_comb body") + } + }; + if let Some(context) = context { + return Err(AnalyzerError::TimingControlOutsideProcess { + construct: "timed task call", + context, + }); + } + // The frontend reads the wait's statements as it reads those of a + // combinational `always @*`, folded branches and the defaults of + // omitted arguments included. + let mut body = vec![timing::implicit_event( + &process.body, + &process.sensitivity_body, + )]; + body.extend(process.body); + processes.push(InitialProcess { + creation_order: process.creation_order, + site: process.process_site, + condition: process.condition, + body: vec![Stmt::Loop { + kind: LoopKind::Forever, + init: Vec::new(), + condition: None, + step: Vec::new(), + body, + }], + initializer: false, + synthetic: false, + repeats: true, + }); + } + *comb = retained; + let mut retained = Vec::new(); for process in std::mem::take(ff) { if !suspends(&process.body, &timed) { retained.push(process); @@ -141,7 +189,9 @@ fn suspends(body: &[Stmt], timed: &HashSet) -> bool { for statement in body { statement.walk(&mut |statement| { result |= match statement { - Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::Wait(_) => true, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { + true + } Stmt::Call { name, .. } => timed.contains(name), _ => false, }; @@ -149,3 +199,22 @@ fn suspends(body: &[Stmt], timed: &HashSet) -> bool { } result } + +fn assigns_nonblocking(body: &[Stmt]) -> bool { + let mut result = false; + for statement in body { + statement.walk(&mut |statement| { + result |= matches!( + statement, + Stmt::Assign { + nonblocking: true, + .. + } | Stmt::AssignConcat { + nonblocking: true, + .. + } + ); + }); + } + result +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index 1389fa550f7..6820026a578 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -102,6 +102,7 @@ impl BodyBuilder<'_, '_, '_> { Ok(result) } ExprKind::Member { .. } => { + let delay = value; let mut parts = Vec::new(); loop { match &native.expression(value).kind { @@ -113,8 +114,10 @@ impl BodyBuilder<'_, '_, '_> { parts.push(instances::normalize_identifier(&name.spelling)); value = *expression; } + // A package-scoped identifier (A.6.5 delay_value, + // ps_identifier) is bound like any other value. ExprKind::Member { separator, .. } if separator == "::" => { - return Err(unsupported("package-scoped delay value")); + return self.native_value(delay); } ExprKind::Name(name) => { parts.push(instances::normalize_identifier(&name.spelling)); @@ -136,165 +139,9 @@ impl BodyBuilder<'_, '_, '_> { /// The wait of an `@*` that controls the statement lowered to `body`, with /// the branches constant folding removed from it in `removed`: an event of /// any change of each variable the statement reads (IEEE 1800-2023 -/// 9.4.2.2). That is every identifier in an expression, a subroutine -/// argument or a left-hand-side index, but not in a timing control (a -/// delay, wait or event control) and not an assignment target itself. Names that turn out not to -/// denote a variable, such as parameters, never change. +/// 9.4.2.2). The frontend reads the statements with the analysis that gives +/// a combinational `always @*` its sensitivity, so both count the same +/// reads, the defaults of omitted subroutine arguments included. pub(super) fn implicit_event(body: &[Stmt], removed: &[Stmt]) -> Stmt { - fn constant(expr: &ConstExpr, names: &mut Vec) { - match expr { - ConstExpr::Ident(name) => push(name, names), - ConstExpr::Literal(_) => {} - ConstExpr::Select { expr, bit } => { - constant(expr, names); - constant(bit, names); - } - ConstExpr::SelectRange { expr, msb, lsb, .. } => { - constant(expr, names); - constant(msb, names); - constant(lsb, names); - } - ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => constant(expr, names), - ConstExpr::Function { args, .. } => args.iter().for_each(|arg| constant(arg, names)), - ConstExpr::Binary { left, right, .. } => { - constant(left, names); - constant(right, names); - } - ConstExpr::Mux { - condition, - then_expr, - else_expr, - } => { - constant(condition, names); - constant(then_expr, names); - constant(else_expr, names); - } - } - } - fn expression(expr: &Expr, names: &mut Vec) { - match expr { - Expr::Ident(name) => push(name, names), - Expr::Literal(_) => {} - Expr::Select { expr, msb, lsb, .. } => { - expression(expr, names); - constant(msb, names); - constant(lsb, names); - } - Expr::Concat(parts) => parts.iter().for_each(|part| expression(part, names)), - Expr::RepeatConcat { count, parts } => { - constant(count, names); - parts.iter().for_each(|part| expression(part, names)); - } - Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => expression(expr, names), - Expr::Binary { left, right, .. } => { - expression(left, names); - expression(right, names); - } - Expr::Mux { - condition, - then_expr, - else_expr, - } => { - expression(condition, names); - expression(then_expr, names); - expression(else_expr, names); - } - // A function's own reads are not part of the event expression. - Expr::Call { args, .. } => args.iter().flatten().for_each(|arg| expression(arg, names)), - Expr::Inside { expr, items } => { - expression(expr, names); - for item in items { - item.exprs() - .into_iter() - .for_each(|operand| expression(operand, names)); - } - } - } - } - fn target(lvalue: &LValue, names: &mut Vec) { - if let LValue::Select { - msb, - lsb, - array_slice_width, - .. - } = lvalue - { - constant(msb, names); - constant(lsb, names); - if let Some(width) = array_slice_width { - constant(width, names); - } - } - } - fn push(name: &str, names: &mut Vec) { - if !names.iter().any(|known| known == name) { - names.push(name.to_string()); - } - } - let mut names = Vec::new(); - for stmt in body.iter().chain(removed) { - stmt.walk(&mut |stmt| match stmt { - Stmt::Assign { lhs, rhs, .. } => { - target(lhs, &mut names); - expression(rhs, &mut names); - } - Stmt::AssignConcat { parts, rhs, .. } => { - parts.iter().for_each(|part| target(part, &mut names)); - expression(rhs, &mut names); - } - Stmt::If { condition, .. } => expression(condition, &mut names), - Stmt::Case { - selector, items, .. - } => { - expression(selector, &mut names); - for label in items.iter().flat_map(|item| &item.labels) { - match label { - CaseLabel::Value(value) => expression(value, &mut names), - CaseLabel::Range { low, high } => { - expression(low, &mut names); - expression(high, &mut names); - } - } - } - } - Stmt::Loop { - kind, condition, .. - } => { - if let LoopKind::Repeat(count) = kind { - expression(count, &mut names); - } - if let Some(condition) = condition { - expression(condition, &mut names); - } - } - Stmt::Return(value) => value.iter().for_each(|value| expression(value, &mut names)), - Stmt::Call { args, .. } => args - .iter() - .flatten() - .for_each(|arg| expression(arg, &mut names)), - Stmt::Eval(expr) => expression(expr, &mut names), - Stmt::SystemTask { args, .. } => { - for arg in args { - if let SystemTaskArg::Expr(expr) = arg { - expression(expr, &mut names); - } - } - } - Stmt::Local { init, .. } => init.iter().for_each(|init| expression(init, &mut names)), - Stmt::Break - | Stmt::Continue - | Stmt::Delay { .. } - | Stmt::WaitEvent(_) - | Stmt::Wait(_) => {} - }); - } - Stmt::WaitEvent( - names - .into_iter() - .map(|name| EventItemBase { - edge: EventEdge::Any, - expr: Expr::Ident(name), - }) - .collect(), - ) + Stmt::WaitImplicit(body.iter().chain(removed).cloned().collect()) } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 1ccf521aeb4..629730d0fc0 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -131,9 +131,12 @@ fn validate_procedure( while let Some(id) = pending.pop() { let statement = native.statement(id); match &statement.kind { + // A plain `always @*` that calls a timed task runs as a process, + // which may assign nonblocking; timed task classification + // rejects the assignment in one that stays combinational. StatementKind::Assignment { nonblocking: true, .. - } if kind == AlwaysKind::Comb => { + } if kind == AlwaysKind::Comb && procedure.kind != ProcedureKind::Always => { return Err(unsupported( if procedure.kind == ProcedureKind::AlwaysLatch { "nonblocking assignment inside always_latch" diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index b9822da6e37..16d579a9d31 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -114,6 +114,12 @@ pub enum StmtBase { /// `@(items)`: suspend the process until one of the events occurs /// (9.4.2). WaitEvent(Vec>), + /// `@*` (9.4.2.2): suspend the process until a variable that the + /// statements read changes. They are the statements the control covers, + /// branches that constant folding removed included, and only describe + /// the reads: they do not execute here, and [`StmtBase::walk`] does not + /// visit them. + WaitImplicit(Vec>), /// `wait (condition)`: suspend the process until the condition is true /// (9.4.3). Wait(E), @@ -343,6 +349,7 @@ impl StmtBase { .collect(), ), StmtBase::Wait(condition) => StmtBase::Wait(fe(condition)), + StmtBase::WaitImplicit(reads) => StmtBase::WaitImplicit(body(reads, fe, fl)), } } @@ -455,6 +462,7 @@ impl StmtBase { } } StmtBase::Wait(condition) => fe(condition), + StmtBase::WaitImplicit(reads) => body(reads, fe, fl, fname), } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index dcc648cb2c5..94015a571ce 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3591,25 +3591,30 @@ fn implicit_event_controls_wait_on_the_reads_of_their_statement() { initial forever @* begin if (c > 0) y = a; else y = b; z[i] = 1; @(d); #(d); end\n\ endmodule"; let ir = analyze_source(code, Path::new("implicit.sv")).expect("`@*` in a process"); - let mut waits = Vec::new(); + // The frontend reads the statements of an `@*` with the analysis that + // gives a combinational `always @*` its sensitivity; the analyzer keeps + // the statements the control covers. + let mut implicit = Vec::new(); + let mut explicit = Vec::new(); for process in ir.modules()[0].initial_processes() { for stmt in process.body() { - stmt.walk(&mut |stmt| { - if let ir::Stmt::WaitEvent(items) = stmt { - waits.push( - items - .iter() - .map(|item| match &item.expr { - ir::Expr::Ident(name) => name.clone(), - expr => panic!("unexpected event expression {expr:?}"), - }) - .collect::>(), - ); - } + stmt.walk(&mut |stmt| match stmt { + ir::Stmt::WaitImplicit(reads) => implicit.push(!reads.is_empty()), + ir::Stmt::WaitEvent(items) => explicit.push( + items + .iter() + .map(|item| match &item.expr { + ir::Expr::Ident(name) => name.clone(), + expr => panic!("unexpected event expression {expr:?}"), + }) + .collect::>(), + ), + _ => {} }); } } - assert_eq!(waits, [vec!["c", "a", "b", "i"], vec!["d"]]); + assert_eq!(implicit, [true], "one @* over the statements of the block"); + assert_eq!(explicit, [vec!["d"]]); } #[test] @@ -6070,7 +6075,6 @@ fn native_system_task_arguments_preserve_strings_omissions_and_query_operands() fn timed_task_calls_require_a_suspendable_context() { for caller in [ "always_comb outer();", - "always @* outer();", "always_ff @(posedge clk) outer();", "function void f(); outer(); endfunction initial f();", ] { @@ -6084,6 +6088,15 @@ fn timed_task_calls_require_a_suspendable_context() { "{caller}: {error}" ); } + // A plain `always @*` is an ordinary always procedure: the call makes it + // a process (IEEE 1800-2023 9.2.2.2.2). + let ir = analyze_source( + "module Top; task automatic pause(); #1; endtask task automatic outer(); pause(); endtask always @* outer(); endmodule", + Path::new("timed_task_star.sv"), + ) + .unwrap(); + assert!(ir.modules()[0].comb_processes().is_empty()); + assert_eq!(ir.modules()[0].initial_processes().len(), 1); } #[test] diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 51e04377b4c..518436a082f 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -407,6 +407,32 @@ both checks in Verilator and passes in Icarus 13.0, which also passes the unchanged shared assertions. The [retained observation](verification/repros/process_nba_positions_verilator.json) records both failures; `--include-ignored` retains their assertions. +Verilator 5.052 schedules an `always @*` that calls a timed task differently +from its event control in `timing::always_star_timed_task_calls_run_as_processes`: +the call for `a = 5` at 3 ns writes `y` at 6 ns instead of 5 ns, and in +`timing::always_star_timed_task_calls_assign_nonblocking` a nonblocking update +after the task's 1 ns delay lands at 2 ns instead of 3 ns. A standalone +probe also shows it rerunning the call for a change made while the task was +suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 +makes the implicit event list the variables the statement reads, and 9.4.2 +waits only for changes after the event control is reached. Icarus 13.0 passes +the unchanged shared assertions. + +IEEE 1800-2023 9.4.2.2 defines the event list of an `always @*` by the +identifiers that appear in its statement, so a branch that constant folding +removes still contributes, and Celox's combinational and process `always @*` +count it, with the reads of the defaults of omitted arguments. Icarus 13.0 +leaves the folded branch out in +`timing::always_star_timed_task_calls_wait_on_folded_branch_reads`. Verilator +5.052 leaves out both the folded branch and the default of a nested call in +`timing::always_star_timed_task_calls_wait_on_nested_call_defaults`, and runs +the process at time zero; Icarus passes the nested-default case. + +Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay +value (`#delays::D;`) in `timing::package_scoped_delay_values_wait_their_value`; +IEEE 1800-2023 A.6.5 permits a `ps_identifier` as a `delay_value`. Verilator +passes the case. + Verilator 5.052 repeats activation of the self-reading latch in `latch::guarded_activation`, producing 3 where one `seed`/`en` change should produce 1. The [adapter-free reproduction](verification/repros/latch_activation.sv) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 6700235ed25..500208661ae 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1211,6 +1211,128 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (run_until 7) (assert_eq count 1) (run_until 8) (assert_eq count 2)) +; A plain `always @*` that calls a timed task runs as a process (IEEE +; 1800-2023 9.2.2.2.2): its event list is the variables its statement +; reads, including the task's arguments but not what the task body reads +; (9.4.2.2), and it waits for one of them to change before each run. +(case always_star_timed_task_calls_run_as_processes + (source "star_tasks.sv" #" + module Top(output logic [7:0] y, z, w); + logic [7:0] a = 8'd0, b = 8'd0; + logic [7:0] y_r = 8'd0, z_r = 8'd0, w_r = 8'd0; + task automatic delayed(input logic [7:0] v); + #2 y_r = v; + endtask + task automatic mark(input logic [7:0] v); + #1 w_r = v; + endtask + always @* delayed(a); + always @* begin z_r = b; mark(b); end + initial begin + #3 a = 8'd5; + b = 8'd1; + #3 a = 8'd7; + end + assign y = y_r; + assign z = z_r; + assign w = w_r; + endmodule + "#) + (top Top) + (run_until 3) (assert_eq y 0) (assert_eq z 1) (assert_eq w 0) + (run_until 4) (assert_eq w 1) (assert_eq y 0) + (run_until 5) (assert_eq y 5 "the task resumes two units after a changed") + (run_until 7) (assert_eq y 5) + (run_until 8) (assert_eq y 7)) + +; Such a process may assign nonblocking, as any `always` process may. +(case always_star_timed_task_calls_assign_nonblocking + (source "star_task_nba.sv" #" + module Top(output logic [7:0] q); + logic [7:0] d = 8'd0, q_r = 8'd0; + task automatic pause(); + #1; + endtask + always @* begin + pause(); + q_r <= d; + end + initial #2 d = 8'd5; + assign q = q_r; + endmodule + "#) + (top Top) + (run_until 2) (assert_eq q 0) + (run_until 3) (assert_eq q 5 "the update follows the task's delay")) + +; The event list of such a process comes from the analysis that gives a +; combinational `always @*` its sensitivity: it counts what the defaults of +; omitted arguments read, of calls nested in arguments too. +(case always_star_timed_task_calls_wait_on_nested_call_defaults + (source "star_nested_default.sv" #" + module Top(output logic [7:0] y); + logic [7:0] a = 8'd0, y_r = 8'd0; + function automatic logic [7:0] pick(input logic [7:0] v = a); + return v; + endfunction + task automatic delayed(input logic [7:0] v); + #1 y_r = v; + endtask + always @* delayed(pick()); + initial #2 a = 8'd5; + assign y = y_r; + endmodule + "#) + (top Top) + (run_until 2) (assert_eq y 0) + (run_until 3) (assert_eq y 5 "a change of what pick's default reads wakes the process")) + +; It counts the reads of branches that constant folding removed, as the +; syntactic event list does (IEEE 1800-2023 9.4.2.2). +(case always_star_timed_task_calls_wait_on_folded_branch_reads + (source "star_folded_default.sv" #" + module Top(output logic [7:0] y); + logic [7:0] a = 8'd0, b = 8'd1, y_r = 8'd0; + task automatic delayed(input logic [7:0] v = a); + #1 y_r = v; + endtask + always @* begin + if (0) delayed(); + delayed(b); + end + initial #2 a = 8'd5; + assign y = y_r; + endmodule + "#) + (top Top) + (run_until 2) (assert_eq y 0) + (run_until 3) (assert_eq y 1 "a change of what a folded call's default reads wakes the process")) + +; A package-scoped identifier is a delay value (IEEE 1800-2023 A.6.5, +; ps_identifier), with or without parentheses. +(case package_scoped_delay_values_wait_their_value + (source "package_delays.sv" #" + package delays; + parameter int D = 3; + localparam int E = 2; + endpackage + module Top(output int at_d, at_e, at_paren); + initial begin + at_d = 0; at_e = 0; at_paren = 0; + #delays::D; + at_d = 1; + #delays::E; + at_e = 1; + #(delays::D) at_paren = 1; + end + endmodule + "#) + (top Top) + (run_until 2) (assert_eq at_d 0) + (run_until 3) (assert_eq at_d 1) (assert_eq at_e 0) + (run_until 5) (assert_eq at_e 1) (assert_eq at_paren 0) + (run_until 8) (assert_eq at_paren 1)) + (case timed_task_four_state_storage_survives_suspension (four_state) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index ebe8418ed61..0a0b6efdeb2 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -1333,6 +1333,85 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_assign_nonblocking", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 leaves the reads of a branch that constant folding removes out of the event list of an always @*: a change of a, which the default of the call in `if (0) delayed();` reads, does not wake the process. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, so a constant-false branch still contributes. Celox's combinational and process always @* both count it.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_always_star_folded_branches", + "observed_version": "Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 leaves the reads of a branch that constant folding removes out of the event list of an always @*: a change of a, which the default of the call in `if (0) delayed();` reads, does not wake the process. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, so a constant-false branch still contributes. Celox's combinational and process always @* both count it.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay value such as #delays::D. IEEE 1800-2023 A.6.5 permits a ps_identifier as a delay_value. Verilator passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_package_delay_value", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay value such as #delays::D. IEEE 1800-2023 A.6.5 permits a ps_identifier as a delay_value. Verilator passes the case.", + "upstream": [] + }, + "name": "timing::package_scoped_delay_values_wait_their_value", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index b9acfdf7286..a026da63bf5 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2140,5 +2140,75 @@ "class::randomization_mode_bit_argument" ] } + }, + { + "id": "sv_verilator_always_star_timed_task", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "reason": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::always_star_timed_task_calls_run_as_processes", + "timing::always_star_timed_task_calls_assign_nonblocking" + ] + } + }, + { + "id": "sv_icarus_package_delay_value", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay value such as #delays::D. IEEE 1800-2023 A.6.5 permits a ps_identifier as a delay_value. Verilator passes the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::package_scoped_delay_values_wait_their_value" + ] + } + }, + { + "id": "sv_icarus_always_star_folded_branches", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 leaves the reads of a branch that constant folding removes out of the event list of an always @*: a change of a, which the default of the call in `if (0) delayed();` reads, does not wake the process. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, so a constant-false branch still contributes. Celox's combinational and process always @* both count it.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::always_star_timed_task_calls_wait_on_folded_branch_reads" + ] + } + }, + { + "id": "sv_verilator_always_star_implicit_reads", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "timing::always_star_timed_task_calls_wait_on_folded_branch_reads" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 52658fffaa6..fd6bb918a35 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -7,9 +7,9 @@ "passed": 0, "rejected": 0, "unexpected_accept": 1, - "mismatch": 16, + "mismatch": 17, "emission_error": 0, - "compile_error": 119, + "compile_error": 120, "runtime_error": 8, "unsupported": 0, "ignored": 0 @@ -1343,6 +1343,22 @@ "name": "class::methods_called_through_interface_class_handles", "phase": "compile", "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Malformed statement\n", + "expectation": "Simulation", + "name": "timing::package_scoped_delay_values_wait_their_value", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads at 1309:17: assert_eq y: expected 0x1, got 0x0 (a change of what a folded call's default reads wakes the process)", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "execute", + "status": "mismatch" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index a18b6d80f40..baf0c215a6a 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -7,7 +7,7 @@ "passed": 0, "rejected": 0, "unexpected_accept": 0, - "mismatch": 24, + "mismatch": 28, "emission_error": 0, "compile_error": 18, "runtime_error": 2, @@ -450,6 +450,38 @@ "name": "indexed_select::known_run_time_selects_stay_within_their_element", "phase": "execute", "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_run_as_processes at 1244:17: assert_eq y: expected 0x5, got 0x0 (the task resumes two units after a changed)", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_run_as_processes", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_assign_nonblocking at 1265:17: assert_eq q: expected 0x0, got 0x5", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_assign_nonblocking", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults at 1288:17: assert_eq y: expected 0x5, got 0x0 (a change of what pick's default reads wakes the process)", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads at 1308:17: assert_eq y: expected 0x0, got 0x1", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "execute", + "status": "mismatch" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 35f824e434c..7c115851699 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -1469,6 +1469,109 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_timed_task", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_run_as_processes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_timed_task", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_assign_nonblocking", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_implicit_reads", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_implicit_reads", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::package_scoped_delay_values_wait_their_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/tests/frontends/systemverilog/synthesizable.rs b/crates/celox/tests/frontends/systemverilog/synthesizable.rs index b80ee583c0a..db5c6a7c056 100644 --- a/crates/celox/tests/frontends/systemverilog/synthesizable.rs +++ b/crates/celox/tests/frontends/systemverilog/synthesizable.rs @@ -171,7 +171,11 @@ fn task_timing_control_is_rejected() { .build_cranelift() .expect_err("a task with a delay must be rejected") .to_string(); - assert!(error.contains("Unsupported"), "{error}"); + // IEEE 1800-2023 9.2.2.2: always_comb may not suspend. + assert!( + error.contains("timed task call in an always_comb body"), + "{error}" + ); } #[test] diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index b3916379346..83bcaca0f58 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -55,6 +55,11 @@ timed_cases! { fn timed_task_nested_copyback_wait_and_return = "timing::timed_task_nested_copyback_wait_and_return"; fn timed_task_static_formals_remain_shared = "timing::timed_task_static_formals_remain_shared"; fn timed_task_in_edge_always_rearms_after_return = "timing::timed_task_in_edge_always_rearms_after_return"; + fn always_star_timed_task_calls_run_as_processes = "timing::always_star_timed_task_calls_run_as_processes"; + fn always_star_timed_task_calls_assign_nonblocking = "timing::always_star_timed_task_calls_assign_nonblocking"; + fn always_star_timed_task_calls_wait_on_nested_call_defaults = "timing::always_star_timed_task_calls_wait_on_nested_call_defaults"; + fn always_star_timed_task_calls_wait_on_folded_branch_reads = "timing::always_star_timed_task_calls_wait_on_folded_branch_reads"; + fn package_scoped_delay_values_wait_their_value = "timing::package_scoped_delay_values_wait_their_value"; fn time_calls_in_child_port_subroutines = "timing::time_calls_in_child_port_subroutines"; fn time_calls_in_child_port_actuals = "timing::time_calls_in_child_port_actuals"; fn time_literal_delays_accept_all_units = "timing::time_literal_delays_accept_all_units"; @@ -491,12 +496,6 @@ fn unimplemented_timing_features_are_rejected() { "always_ff event control", 88, ), - // #1710 - ( - "bit q; task t(); #1 q = 1; endtask always @* t();", - "timed task call in a combinational process", - 88, - ), ] { let source = format!("module Top; {body} endmodule"); let error = celox::Simulation::from_sv_sources( @@ -571,6 +570,14 @@ fn timing_controls_outside_suspendable_processes_are_rejected() { "bit a; function automatic bit f(); #1; return a; endfunction", "delay control in a function", ), + ( + "bit q; task t(); #1 q = 1; endtask always_comb t();", + "timed task call in an always_comb body", + ), + ( + "bit q, e; task t(); #1 q = 1; endtask always_latch if (e) t();", + "timed task call in an always_latch body", + ), ] { let source = format!("module Top; {body} endmodule"); let error = celox::Simulation::from_sv_sources( @@ -585,6 +592,76 @@ fn timing_controls_outside_suspendable_processes_are_rejected() { } } +/// The default of an omitted task argument is read by the call, so an +/// `always @*` that calls the task waits on what the default reads, as for a +/// combinational `always @*`. Icarus 13.0 agrees; Verilator 5.052 does not +/// wake the process. +#[test] +fn always_star_timed_task_calls_wait_on_omitted_argument_defaults() { + let source = r#" + module Top(output logic [7:0] y); + timeunit 1ns / 1ns; + logic [7:0] a = 8'd0; + logic [7:0] y_r = 8'd0; + task automatic delayed(input logic [7:0] v = a); + #1 y_r = v; + endtask + always @* delayed(); + initial #2 a = 8'd5; + assign y = y_r; + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("star_default.sv"))], + "Top", + ) + .build() + .unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 0u8.into()); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 5u8.into()); +} + +/// An `always @*` that is still in a timed task when a variable of its event +/// list changes misses the change: its event control waits only for changes +/// after it is reached again (IEEE 1800-2023 9.4.2). Icarus 13.0 agrees; +/// Verilator 5.052 reruns the call for the missed change. +#[test] +fn always_star_timed_task_calls_miss_changes_while_suspended() { + let source = r#" + module Top(output logic [7:0] y); + timeunit 1ns / 1ns; + logic [7:0] a = 8'd0; + logic [7:0] y_r = 8'd0; + task automatic delayed(input logic [7:0] v); + #2 y_r = v + 8'd1; + endtask + always @* delayed(a); + initial begin + #1 a = 8'd5; + #1 a = 8'd6; + #5 a = 8'd7; + end + assign y = y_r; + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("star_missed.sv"))], + "Top", + ) + .build() + .unwrap(); + sim.run_until(6).unwrap(); + assert_eq!( + sim.get(sim.signal("y")), + 6u8.into(), + "a = 6 came while suspended" + ); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 8u8.into()); +} + /// A nonblocking site stages its value (`NbaSite::pending`) only if its /// target has no other writer and nothing observes the order of the /// updates in the NBA region: no wait reads the target, directly or through diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index af7fea78edf..c4f7756f189 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -50,7 +50,7 @@ In a timed `Simulation`, `initial` and plain `always` processes can suspend: | Control | Supported | | --- | --- | -| `#delay` | integral and real delays, `#(min:typ:max)` (the typical value) and [time literals](#time-literal-delays); an X or Z delay counts as zero | +| `#delay` | integral and real delays, `#(min:typ:max)` (the typical value), package-scoped values such as `#pkg::D`, and [time literals](#time-literal-delays); an X or Z delay counts as zero | | `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, and `@*` / `@(*)`, which waits on the variables its statement reads | | `wait (condition)` | any condition; an X or Z condition counts as false | | Assignments | blocking and nonblocking, to any target a blocking assignment takes, including unpacked array elements and run-time positions; nonblocking updates take effect in the NBA region of the time slot, at the position evaluated when the assignment executes, and bits outside the target or at a position with an X or Z bit are not written | @@ -78,8 +78,11 @@ An `initial` or ordinary `always` process can call tasks containing `#delay`, `@(event)` and `wait (condition)`, including through nested tasks. Calls are inlined into the caller's resumable state machine. A normal edge-sensitive `always` that calls a timed task waits for that task to return before rearming -its event control. Functions, `always_comb` and `always_ff` cannot call a timed -task, and `always @*` cannot yet ([#1710](https://github.com/celox-sim/celox/issues/1710)). +its event control. An `always @*` that calls a timed task runs as a process +too: it waits for a change of a variable its statement reads, the task's +arguments among them but not what the task body reads, and misses changes +while the task is suspended. Functions, `always_comb`, `always_latch` and +`always_ff` cannot call a timed task. Automatic task arguments and locals have separate storage for each activation and survive suspension. Module-local static task arguments remain shared. Inputs and inouts @@ -173,8 +176,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. - Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), - package-scoped delay values - ([#1710](https://github.com/celox-sim/celox/issues/1710)), impure function calls in event expressions, and + impure function calls in event expressions, and `wait` or event expressions reading a static task argument. - Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. - Inferred latches inside `always_comb` are rejected by default. Set `inferred_latch = "warn"` or `"allow"` in `celox.toml` under `[diagnostics]` to permit retained blocking assignments. Ordinary `always @*` and explicit `always_latch` do not require this option. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index c10c355185b..187b9710432 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -49,7 +49,7 @@ outline: [2, 3] | 制御 | 対応範囲 | | --- | --- | -| `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | +| `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、`#pkg::D` のような package スコープの値、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | | `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、文が読む変数を待つ `@*` / `@(*)` | | `wait (condition)` | 任意の条件。X / Z の条件は偽として扱う | | 代入 | ブロッキング代入とノンブロッキング代入。代入先はブロッキング代入と同じで、unpacked 配列の要素や実行時に決まる位置も使えます。ノンブロッキング代入は代入を実行した時点で評価した位置に、そのタイムスロットの NBA 領域で反映します。代入先の範囲外のビットと、X や Z のビットを含む位置には書き込みません | @@ -73,8 +73,9 @@ outline: [2, 3] `initial` と通常の `always` から、`#delay`・`@(event)`・`wait (condition)` を 含む task を呼び出せます。task のネストも可能です。呼び出しは呼び出し元の状態機械に インライン展開されます。エッジ待ちの `always` は task の完了後に次のエッジを待ちます。 -function・`always_comb`・`always_ff` からの時間待ち task 呼び出しは拒否します。 -`always @*` からの呼び出しも現在は拒否します([#1710](https://github.com/celox-sim/celox/issues/1710))。 +時間待ち task を呼ぶ `always @*` もプロセスとして実行します。文が読む変数(task の引数を含み、 +task 本体が読む変数は含まない)の変化を待ち、task の実行中に起きた変化は見送ります。 +function・`always_comb`・`always_latch`・`always_ff` からの時間待ち task 呼び出しは拒否します。 automatic な引数とローカル変数は呼び出しごとに独立し、中断中も保持されます。 module 内の static task の引数は共有されます。input/inout は呼び出し時にコピーされ、output/inout は @@ -157,8 +158,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 named event と `->`、`fork` / `join`、`wait fork` / `disable fork`、並行アサーション、`force` / `release`。 - プロセス内のタイミング制御:`iff` 修飾([#1444](https://github.com/celox-sim/celox/issues/1444))、 - package スコープの遅延値 - ([#1710](https://github.com/celox-sim/celox/issues/1710))、イベント式内の impure な関数呼び出し、 + イベント式内の impure な関数呼び出し、 static task 引数を読む `wait` 条件とイベント式。 - `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。