diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 45e824749e0..d11a1ca6c1d 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -61,6 +61,9 @@ pub enum FrontendError { // from the source-facing hierarchy. The runtime image records their addresses. const FORCE_ENABLE: &str = "@force-enable:"; const FORCE_VALUE: &str = "@force-value:"; +/// The prefix of the variables `$event[k]` that hold the value of an event +/// expression, and of their copies of process-local operands. +const EVENT_PREFIX: &str = "$event["; #[derive(Clone)] struct SvVariable { @@ -107,9 +110,14 @@ impl SvVariable { } /// A hidden variable other than the time slot, whose value the lowered - /// code computes. The time slot is state the scheduler writes. + /// code computes. The time slot is state the scheduler writes, and an + /// event expression's variables are state its process and its + /// continuous assignment share. fn is_scratch(&self) -> bool { - self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() + self.hidden + && self.path != [TIME_SLOT] + && self.force_control.is_none() + && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -128,6 +136,9 @@ pub(crate) struct LoweredSvModule { package_variables: Vec<(SourceVarId, String, String)>, /// The hidden `(copy, signal)` event copies of [`FfEventVars`]. event_copies: Vec<(SourceVarId, SourceVarId)>, + /// The continuous assignments of the event expressions the processes + /// wait on, by their hidden target `$event[k]`. + event_assignments: Vec<(SourceVarId, Vec)>, } #[derive(Clone)] @@ -1536,6 +1547,7 @@ fn prepare_external_hierarchy_collecting( package_variables: Vec::new(), // The foreign module's own combinational blocks carry its copies. event_copies: Vec::new(), + event_assignments: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -2880,6 +2892,7 @@ fn lower_module_with_overrides( wait_sites, nba_sites, host_request_sites, + event_assignments, ) = lower_initial_processes( module, &mut variables, @@ -3007,6 +3020,7 @@ fn lower_module_with_overrides( instances, package_variables, event_copies: event_vars.copies, + event_assignments, }) } @@ -3389,6 +3403,9 @@ pub(crate) fn attach_instance_glue( .insert(*id, pm.variables[id].to_symbolic_variable()); } } + // An event expression is one more continuous assignment to a hidden + // buffer the processes watch. + port_assignments.extend(lowered.event_assignments.iter().cloned()); let (comb_blocks, arena, created, comb_observers, comb_sites) = lower_comb_processes( &lowered.source, &port_assignments, @@ -3734,19 +3751,12 @@ fn lower_initial_processes( Vec>, Vec>, Vec>, + Vec<(SourceVarId, Vec)>, ), sv::AnalyzerError, > { if module.initial_processes().is_empty() { - return Ok(( - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - Vec::new(), - )); + return Ok(Default::default()); } let mut values = Vec::new(); let mut declaration_values = Vec::new(); @@ -3814,6 +3824,7 @@ fn lower_initial_processes( Vec::new(), Vec::new(), Vec::new(), + Vec::new(), )); } @@ -3916,6 +3927,7 @@ fn lower_initial_processes( wait_sites, nba_sites, host_request_sites, + std::mem::take(&mut pm.event_assignments), )) } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index bf950285f04..860fdbc1da6 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4467,14 +4467,29 @@ impl Ff<'_, '_> { /// `@(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. + /// + /// An item other than a variable of the module is watched through the + /// variable `$event[k]` of a continuous assignment of the expression: + /// each update of its value is an occurrence, and an edge is one of the + /// least significant bit of the expression (Table 9-2). Before it + /// suspends, the process copies the process-local operands the + /// assignment reads and stores the expression's value, which the event + /// control samples as it begins. fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { let mut terms = Vec::new(); + let mut samples = 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"))?; + let expr = self.propagate(&item.expr); + 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)?, + // 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)?, + }; match item.edge { sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), sv::ir::EventEdge::Pos => terms.push((id, CounterKind::Rises)), @@ -4485,6 +4500,9 @@ impl Ff<'_, '_> { } } } + for (target, value) in samples { + self.assign(&sv::ir::LValue::Ident(target), &value)?; + } let site = self.wait_site(terms); self.with_kernel(|kernel| -> Result<(), ProcessKernelError> { kernel.suspend_wait(site)?; @@ -4498,6 +4516,116 @@ impl Ff<'_, '_> { .map_err(kernel_error) } + /// The variable `$event[k]` of a new event expression `expr`, with its + /// continuous assignment added to the module. `samples` gets the + /// assignments the process makes before it suspends: the copies of the + /// process-local operands, then `$event[k]` itself. + fn event_expression( + &mut self, + expr: &sv::ir::Expr, + samples: &mut Vec<(String, sv::ir::Expr)>, + ) -> Result { + if let Some(name) = impure_call(self.m, expr) { + return Err(unsupported(format!( + "impure call `{name}` in an event expression" + ))); + } + // A real expression keeps its payload bits, so a change too small + // to survive an integer conversion still wakes the process. + let float = self.m.expr_float_precision(expr); + let width = match float { + Some(celox_sir::FloatPrecision::F64) => 64, + Some(celox_sir::FloatPrecision::F32) => 32, + None => sv_expr_natural_width( + &self.m.typed_calls(expr), + self.m.variables, + self.m.name_to_id, + self.m.constants, + self.m.parameter_types, + ) + .ok_or_else(|| unsupported("event expression of unknown width"))?, + }; + let signed = self.expr_signed(expr); + let mut names = HashSet::default(); + expr_idents(expr, &mut names); + let mut locals: Vec<_> = names + .into_iter() + .filter_map(|name| { + let id = self.m.id(&name)?; + self.m.is_hidden(id).then_some((name, id)) + }) + .collect(); + locals.sort_unstable(); + // Another call can copy a new argument into a static formal while + // the process waits, which a copy taken now would not see. + if locals.iter().any(|&(_, id)| self.is_static_task_formal(id)) { + return Err(unsupported( + "event expression reading a static task argument", + )); + } + let index = self.m.next_event_index(); + let (event, event_name) = self.m.event_variable( + index, + None, + SvVariable { + float, + path: Vec::new(), + width, + signed, + is_4state: float.is_none(), + packed_ranges: vec![(width as i128 - 1, 0)], + array_dims: Vec::new(), + unpacked_ranges: Vec::new(), + domain_kind: DomainKind::Other, + kind: VariableKind::Variable, + type_kind: if float.is_some() { + PortTypeKind::Bit + } else { + PortTypeKind::Logic + }, + source: None, + hidden: true, + force_control: None, + }, + ); + let mut renames = HashMap::default(); + for (position, (name, id)) in locals.into_iter().enumerate() { + let variable = self.m.var(id).clone(); + let (copy, copy_name) = + self.m + .event_variable(index, Some(format!("arg[{position}]")), variable); + if let Some(width) = self.element_widths.get(&stable(id)).copied() { + self.element_widths.insert(stable(copy), width); + self.element_widths.insert(working(copy), width); + } + samples.push((copy_name.clone(), sv::ir::Expr::Ident(name.clone()))); + renames.insert(name, copy_name); + } + let value = rename_idents(expr, &renames); + samples.push((event_name.clone(), value.clone())); + self.m.event_assignments.push(( + event, + vec![sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(event_name), + rhs: value, + nonblocking: false, + }], + )); + Ok(event) + } + + /// Whether `id` is a static formal of a task, which keeps one + /// module-wide address for every call. + fn is_static_task_formal(&self, id: SourceVarId) -> bool { + self.m.subroutines.values().any(|subroutine| { + subroutine.is_task + && subroutine.params.iter().any(|param| { + !subroutine.automatic_locals.contains(¶m.name) + && self.m.id(¶m.name) == Some(id) + }) + }) + } + /// `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. @@ -4509,16 +4637,10 @@ impl Ff<'_, '_> { // in, but hidden local storage has no observable change counters yet. // Do not compile a wait that would silently miss that wakeup, including // dependencies read indirectly by a function in the condition. - if self.m.subroutines.values().any(|subroutine| { - subroutine.is_task - && subroutine.params.iter().any(|param| { - !subroutine.automatic_locals.contains(¶m.name) - && names.iter().any(|name| { - self.m.id(name).is_some_and(|id| { - self.m.is_hidden(id) && Some(id) == self.m.id(¶m.name) - }) - }) - }) + if names.iter().any(|name| { + self.m + .id(name) + .is_some_and(|id| self.m.is_hidden(id) && self.is_static_task_formal(id)) }) { return Err(unsupported("wait condition reading a static task argument")); } @@ -4669,6 +4791,226 @@ fn subroutine_reads(pm: &ProcModule<'_>, expr: &sv::ir::Expr, names: &mut HashSe } } +/// The name of a call in `expr` that has an effect or reads the state of the +/// simulation, directly or through the functions it calls: an event +/// expression must be a value of the variables it reads. +fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { + let mut pending = vec![expr.clone()]; + let mut visited = HashSet::default(); + while let Some(expr) = pending.pop() { + let callees = std::cell::RefCell::new(Vec::new()); + expr_calls(&expr, &|callee| { + callees.borrow_mut().push(callee.clone()); + false + }); + for callee in callees.into_inner() { + let name = match callee { + sv::ir::Callee::System(function) => { + if function.reads_simulation_state() { + return Some(function.name().to_string()); + } + continue; + } + sv::ir::Callee::Subroutine(name) => name, + }; + if !visited.insert(name.clone()) { + continue; + } + if let Some(import) = pm.dpi_imports.get(&name) { + if !import.is_pure() { + return Some(name); + } + continue; + } + let Some(subroutine) = pm.subroutine(&name) else { + return Some(name); + }; + if subroutine.is_task + || subroutine + .params + .iter() + .any(|param| param.direction.is_written()) + { + return Some(name); + } + pending.extend( + subroutine + .params + .iter() + .filter_map(|param| param.default.clone()), + ); + // Only the function's own variables may be written. + let local = + |lvalue: &sv::ir::LValue| pm.id(lvalue.name()).is_some_and(|id| pm.is_hidden(id)); + let mut effect = false; + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { lhs, .. } => effect |= !local(lhs), + sv::ir::Stmt::AssignConcat { parts, .. } => effect |= !parts.iter().all(local), + sv::ir::Stmt::Call { + name, + args, + arg_order, + } => pending.push(sv::ir::Expr::Call { + callee: sv::ir::Callee::Subroutine(name.clone()), + args: args.clone(), + arg_order: arg_order.clone(), + }), + sv::ir::Stmt::SystemTask { .. } + | sv::ir::Stmt::Delay { .. } + | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::Wait(_) => effect = true, + _ => {} + }); + stmt.clone().visit_mut( + &mut |expr| pending.push(expr.clone()), + &mut |_| {}, + &mut |_| {}, + ); + } + if effect { + return Some(name); + } + } + } + None +} + +/// `expr` with the identifiers in `renames` replaced. +fn rename_idents(expr: &sv::ir::Expr, renames: &HashMap) -> sv::ir::Expr { + fn constant(expr: &sv::ir::ConstExpr, renames: &HashMap) -> sv::ir::ConstExpr { + use sv::ir::ConstExpr; + let go = |expr: &ConstExpr| Box::new(constant(expr, renames)); + match expr { + ConstExpr::Ident(name) => ConstExpr::Ident(renames.get(name).unwrap_or(name).clone()), + ConstExpr::Literal(_) => expr.clone(), + ConstExpr::SelectRange { + expr, + msb, + lsb, + signed, + } => ConstExpr::SelectRange { + expr: go(expr), + msb: go(msb), + lsb: go(lsb), + signed: *signed, + }, + ConstExpr::Select { expr, bit } => ConstExpr::Select { + expr: go(expr), + bit: go(bit), + }, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), + site: *site, + args: args.iter().map(|arg| constant(arg, renames)).collect(), + }, + ConstExpr::Resize { + expr, + width, + signed, + } => ConstExpr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + ConstExpr::Unary { op, expr } => ConstExpr::Unary { + op: *op, + expr: go(expr), + }, + ConstExpr::Binary { left, op, right } => ConstExpr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => ConstExpr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, + } + } + use sv::ir::Expr; + let go = |expr: &Expr| Box::new(rename_idents(expr, renames)); + match expr { + Expr::Ident(name) => Expr::Ident(renames.get(name).unwrap_or(name).clone()), + Expr::Literal(_) => expr.clone(), + Expr::Select { + expr, + msb, + lsb, + signed, + } => Expr::Select { + expr: go(expr), + msb: constant(msb, renames), + lsb: constant(lsb, renames), + signed: *signed, + }, + Expr::Concat(parts) => Expr::Concat( + parts + .iter() + .map(|part| rename_idents(part, renames)) + .collect(), + ), + Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { + count: constant(count, renames), + parts: parts + .iter() + .map(|part| rename_idents(part, renames)) + .collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + Expr::Unary { op, expr } => Expr::Unary { + op: *op, + expr: go(expr), + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + callee: callee.clone(), + args: args + .iter() + .map(|arg| arg.as_ref().map(|arg| rename_idents(arg, renames))) + .collect(), + arg_order: arg_order.clone(), + }, + Expr::Inside { expr, items } => Expr::Inside { + expr: go(expr), + items: items + .iter() + .map(|item| item.map(&mut |operand| rename_idents(operand, renames))) + .collect(), + }, + } +} + /// 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()); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index f491b0efeba..68eec7b2149 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -43,6 +43,9 @@ pub(super) struct ProcModule<'a> { pub runtime_event_sites: Vec, /// Runtime errors (fatal assertions) of the module, by local code. pub runtime_errors: HashMap>, + /// The continuous assignments `$event[k] = expr` of the event + /// expressions the module's processes wait on, by target. + pub event_assignments: Vec<(SourceVarId, Vec)>, /// The declared bounds of each unpacked dimension, by variable. unpacked_bounds: HashMap>, /// Where the warnings found while lowering go. A process lowered more @@ -190,6 +193,7 @@ impl<'a> ProcModule<'a> { capture_counter: 0, runtime_event_sites: Vec::new(), runtime_errors: HashMap::default(), + event_assignments: Vec::new(), unpacked_bounds, warnings, } @@ -728,6 +732,47 @@ impl<'a> ProcModule<'a> { id } + /// A module-scope variable of event expression `index` with the shape + /// of `variable`: `$event[index]` itself for `slot == None`, otherwise + /// its copy `$event[index].slot`. Like a process slot it is no signal of + /// the design, but state that persists while processes wait. + pub fn event_variable( + &mut self, + index: usize, + slot: Option, + variable: SvVariable, + ) -> (SourceVarId, String) { + let path: Vec<_> = std::iter::once(format!("{EVENT_PREFIX}{index}]")) + .chain(slot) + .collect(); + let name = path.join("."); + let id = next_var_id(&mut self.next_id); + self.variables.insert( + id, + SvVariable { + path, + domain_kind: DomainKind::Other, + kind: VariableKind::Variable, + source: None, + hidden: true, + force_control: None, + ..variable + }, + ); + self.name_to_id.insert(name.clone(), id); + (id, name) + } + + /// The index of the next event expression of the module. + pub fn next_event_index(&self) -> usize { + (0..) + .take_while(|index| { + self.name_to_id + .contains_key(&format!("{EVENT_PREFIX}{index}]")) + }) + .count() + } + pub fn subroutine(&self, name: &str) -> Option<&sv::ir::Subroutine> { self.subroutines.get(name) } @@ -840,7 +885,7 @@ impl<'a> ProcModule<'a> { /// `expr` with each user function call replaced by a literal of its /// return type. - fn typed_calls(&self, expr: &sv::ir::Expr) -> sv::ir::Expr { + pub fn typed_calls(&self, expr: &sv::ir::Expr) -> sv::ir::Expr { use sv::ir::Expr; let go = |expr: &Expr| self.typed_calls(expr); match expr { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index c546db6d4e5..9f4de8c4bac 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -53,6 +53,13 @@ enum Job { loops: Vec<(String, i128, i128)>, start: usize, }, + /// The end of the statement an `@*` controls, which starts at `start` + /// of the output; `sensitivity` is where its constant-folded branches + /// start in the builder's sensitivity body. + ImplicitEvent { + start: usize, + sensitivity: usize, + }, AssertionThen { condition: Expr, keyword: String, @@ -211,8 +218,15 @@ impl BodyBuilder<'_, '_, '_> { jobs.push(Job::Enter(*body)); } StatementKind::Timing { control, body } => { - let timing = self.native_timing_control(*control)?; - output.push(timing); + if self.implicit_event_control(*control)? { + jobs.push(Job::ImplicitEvent { + start: output.len(), + sensitivity: self.sensitivity_body.len(), + }); + } else { + let timing = self.native_timing_control(*control)?; + output.push(timing); + } jobs.push(Job::Enter(*body)); } // Explicit typed assignments/calls/assertions/unsupported @@ -243,6 +257,13 @@ impl BodyBuilder<'_, '_, '_> { _ => output.extend(self.native_statement_leaf(&native.statement(id).kind)?), }, Job::EndScope => self.pop_scope(), + Job::ImplicitEvent { start, sensitivity } => { + let wait = timing::implicit_event( + &output[start..], + &self.sensitivity_body[sensitivity..], + ); + output.insert(start, wait); + } Job::AssertionThen { condition, keyword, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index 949d5cf551b..70494ce65d2 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -50,12 +50,30 @@ impl BodyBuilder<'_, '_, '_> { Ok(Stmt::WaitEvent(result)) } EventControl::Named(_) => Err(unsupported("named event")), - EventControl::Wildcard => Err(unsupported("`@*` event control in a process")), + // The statement it controls gives its event expression. + EventControl::Wildcard => Err(crate::ast::timing::disagreement()), } } } } + /// Whether `id` is `@*` (or `@(*)`), whose event expression the + /// statement it controls determines (see [`implicit_event`]). + pub(super) fn implicit_event_control( + &self, + id: TimingControlId, + ) -> Result { + let control = self.tree.declarations().timing_control(id); + if !matches!( + control.kind, + TimingControlKind::Event(EventControl::Wildcard) + ) { + return Ok(false); + } + self.allow_timing("event control")?; + Ok(true) + } + fn native_delay(&self, mut value: ExprId, parenthesized: bool) -> Result { let native = self.tree.declarations(); if parenthesized { @@ -105,3 +123,169 @@ 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. +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(), + ) +} diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs index 8e46fa7574d..4b10b9bf4e1 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/timing_controls.rs @@ -115,7 +115,6 @@ fn native_timing_event_membership_and_delay_roles_are_authoritative() { fn native_timing_preserves_existing_restrictions_including_ff_iff_validation() { for (body, diagnostic) in [ ("initial @(a iff en) q=1;", "iff-qualified event"), - ("initial @* q=1;", "`@*` event control"), ("always_comb #1 q=d;", "delay control"), ("always_ff @(edge clk) q<=d;", "always_ff event expression"), ( diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 5ee22548d72..7f81f933cb9 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3510,10 +3510,6 @@ fn rejects_unimplemented_timing_constructs() { ), ("initial begin : b disable b; end", "disable statement"), ("initial #1.5;", "delay value"), - ( - "logic a; initial @* a = 1;", - "`@*` event control in a process", - ), ( "logic a, y; always_latch y <= a;", "nonblocking assignment inside always_latch", @@ -3590,6 +3586,36 @@ fn analyzes_timing_controls_in_initial_blocks() { analyze_source(code, Path::new("timing.sv")).expect("timing controls in an initial block"); } +/// `@*` in a process waits on the variables its statement reads (IEEE +/// 1800-2023 9.4.2.2): right-hand sides, conditions, arguments and +/// left-hand-side indices, but not assignment targets or timing controls. +#[test] +fn implicit_event_controls_wait_on_the_reads_of_their_statement() { + let code = "module Top(input logic [7:0] a, b, c, d, i, output logic [7:0] y, z);\n\ + 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(); + 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::>(), + ); + } + }); + } + } + assert_eq!(waits, [vec!["c", "a", "b", "i"], vec!["d"]]); +} + #[test] fn analyzes_veryl_emitted_fifo_with_runtime_casts() { analyze_source( diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index efa5278592b..20c306de17f 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -426,6 +426,8 @@ four-state expectations; the assertions remain enabled on all Celox variants. | Group | Stage | Tool | Cases | Reason | | --- | --- | --- | ---: | --- | | `sv_icarus_automatic_task_arrays` | execute | icarus | 1 | Icarus 13.0 shares an automatic task's unpacked local array across overlapping calls. IEEE 1800-2023 13.3.1–13.3.2 require separate storage for each activation. The [pre-exclusion result](verification/repros/sv_timed_task_arrays_icarus.json) retains the first call returning 31 instead of 11. The scalar activation case remains enabled for Icarus. | +| `sv_icarus_expression_event_sample` | execute | icarus | 1 | Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (`a = 1; @(a ^ b);`). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression, and the write came before the event control. Verilator 5.052 agrees with the expected value. The [pre-exclusion result](verification/repros/sv_expression_event_sample_icarus.json) is retained. | +| `sv_verilator_implicit_event_in_process` | compile | verilator | 1 | Verilator 5.052 rejects `@*` in an `initial forever` ("Unsupported: Event control with implicit sensitivity (@*) in this context"); IEEE 1800-2023 9.4.2.2 permits it in any procedural timing control. Icarus 13.0 passes the case. The [pre-exclusion diagnostic](verification/repros/sv_implicit_event_in_process_verilator.json) is retained. | | `sv_icarus_genvar_dimensions` | execute | icarus | 1 | Icarus 13.0 returns 0 for `$dimensions` of a generated loop index's implicit integer localparam; IEEE 1800-2023 27.4 and 20.7 require one packed dimension. Celox and Verilator pass the unchanged assertions. The [standalone reproducer and pre-exclusion result](verification/repros/sv_genvar_dimensions.json) retain the observed disagreement. | | `sv_icarus_constant_array_queries` | compile | icarus | 1 | Icarus 13.0 rejects array queries of variables in constant expressions and typedef operands; IEEE 1800-2023 20.7 permits them. Verilator passes. | | `sv_icarus_runtime_array_queries` | execute | icarus | 1 | Icarus 13.0 aborts on a runtime dimension argument. A standalone reproducer also rejects an integer variable as the dimension. IEEE 1800-2023 20.7 permits querying fixed-size dimensions with runtime expressions. | diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 0d8d2319726..c6c9106baca 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1056,3 +1056,161 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (top Top) (run_to_finish) (assert_eq count 8)) + +(case expression_events_see_pulses_within_a_time_slot + ; IEEE 1800-2023 9.4.2: each change of the expression's value is an + ; event, also one the slot undoes before it ends. The waits begin after + ; time 0, where Icarus 13.0 reports an event of a new expression. + (source "expression_pulse.sv" #" + module Top(output bit [7:0] count, output bit hit); + bit a, b; + initial begin #1; forever begin @(a ^ b); count = count + 8'd1; end end + initial begin #1; @(a ^ b); hit = 1; end + initial begin #2; a = 1; #0; a = 0; #1; b = 1; a = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 0) + (run_until 2) + (assert_eq count 2 "the expression rose and fell at time 2") + (assert_eq hit 1) + (run_until 3) + (assert_eq count 2 "a and b changed together, so a ^ b did not change")) + +(case real_expression_events_see_fractional_changes + ; IEEE 1800-2023 9.4.2: a change of a real expression's value is an + ; event, also one that converting the value to an integer would lose. + (source "real_expression_event.sv" #" + module Top(output bit [7:0] count); + real r; + initial begin #1; forever begin @(r * 2.0); count = count + 8'd1; end end + initial begin #2; r = 0.125; #1; r = 0.25; #1; r = 0.25; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 0) + (run_until 3) + (assert_eq count 2 "r * 2.0 went to 0.25 and then to 0.5") + (run_until 4) + (assert_eq count 2 "writing the same value is no change")) + +(case bit_select_edges_follow_the_selected_bit + ; Table 9-2 judges an edge on the least significant bit of the + ; expression: of `v[3]`, not of `v`. + (source "bit_select_edge.sv" #" + module Top(output bit [7:0] selected, whole); + bit [3:0] v; + initial forever begin @(posedge v[3]); selected = selected + 8'd1; end + initial forever begin @(posedge v); whole = whole + 8'd1; end + initial begin #1; v = 4'b1000; #1; v = 4'b0000; #1; v = 4'b1000; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq selected 1) + (assert_eq whole 0) + (run_until 3) + (assert_eq selected 2) + (assert_eq whole 0)) + +(case part_select_events_see_pulses_of_the_selected_bits + (source "part_select_pulse.sv" #" + module Top(output bit [7:0] count); + bit [3:0] v; + initial forever begin @(v[2:1]); count = count + 8'd1; end + initial begin #1; v[1] = 1; #0; v[1] = 0; #1; v[3] = 1; v[0] = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq count 2 "v[2:1] went to 1 and back") + (run_until 2) + (assert_eq count 2 "bits outside the select are no events")) + +(case variable_index_events_follow_the_index + ; The value of `q[i]` changes when the index does, too. + (source "variable_index_event.sv" #" + module Top(output bit [7:0] count); + bit [3:0] q; + bit [1:0] i; + initial forever begin @(q[i]); count = count + 8'd1; end + initial begin #1; q[0] = 1; #1; i = 1; #1; q[0] = 0; #1; q[1] = 1; #1; i = 2; end + endmodule + "#) + (top Top) + (run_until 1) (assert_eq count 1) + (run_until 2) (assert_eq count 2 "q[1] differs from q[0]") + (run_until 3) (assert_eq count 2 "q[0] is not selected") + (run_until 4) (assert_eq count 3) + (run_until 5) (assert_eq count 4)) + +(case pure_function_events_change_with_the_result + (source "function_event.sv" #" + module Top(output bit [7:0] count); + bit [3:0] v; + function automatic bit [1:0] middle(bit [3:0] x); + return x[2:1]; + endfunction + initial begin #1; forever begin @(middle(v)); count = count + 8'd1; end end + initial begin #2; v = 4'b0010; #1; v = 4'b1011; #1; v = 4'b1101; end + endmodule + "#) + (top Top) + (run_until 2) (assert_eq count 1) + (run_until 3) (assert_eq count 1 "the result stayed 1") + (run_until 4) (assert_eq count 2)) + +(case event_expressions_read_automatic_task_locals + ; Each call waits on `q[i]` with its own `i`, sampled when the event + ; control begins: the second call does not wake because `q[1]` differs + ; from the `q[0]` the first one waited on. + (source "task_local_event.sv" #" + module Top(output int first, second); + bit [3:0] q; + task automatic await(input int i, output int at); + @(q[i]); + at = $time; + endtask + initial begin #2; await(0, first); await(1, second); end + initial begin #3; q[0] = 1; #3; q[1] = 1; end + endmodule + "#) + (top Top) + (run_until 3) (assert_eq first 3) (assert_eq second 0) + (run_until 5) (assert_eq second 0) + (run_until 6) (assert_eq second 6)) + +(case event_controls_sample_the_expression_when_they_begin + ; IEEE 1800-2023 9.4.2: the process's own write before the event + ; control is no event of it. + (source "event_sample.sv" #" + module Top(output bit hit); + bit a, b; + initial begin #1; a = 1; @(a ^ b); hit = 1; end + initial begin #2; b = 1; end + endmodule + "#) + (top Top) + (run_until 1) + (assert_eq hit 0) + (run_until 2) + (assert_eq hit 1)) + +(case implicit_event_controls_in_processes_wait_on_their_reads + ; IEEE 1800-2023 9.4.2.2: `@*` waits on the variables the statement it + ; controls reads, not on those it writes. + (source "implicit_event.sv" #" + module Top(output bit [7:0] y, z, count); + bit [7:0] a, b; + initial forever @* begin y = a + b; count = count + 8'd1; end + always @* begin #1; z = a; end + initial begin #2; a = 3; #2; b = 4; end + endmodule + "#) + (top Top) + (run_until 1) (assert_eq count 0) (assert_eq y 0) + (run_until 2) (assert_eq count 1) (assert_eq y 3) + (run_until 3) (assert_eq z 3) + (run_until 4) (assert_eq count 2) (assert_eq y 7) (assert_eq z 3)) diff --git a/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json b/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json new file mode 100644 index 00000000000..4032154b841 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_expression_event_sample_icarus.json @@ -0,0 +1,34 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "timing::event_controls_sample_the_expression_when_they_begin at 1179:3: assert_eq hit: expected 0x0, got 0x1", + "expectation": "Simulation", + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "compile_error": 0, + "emission_error": 0, + "ignored": 0, + "mismatch": 1, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "note": "Focused failure before the exclusion. The design writes a = 1 and then waits on @(a ^ b); Icarus 13.0 wakes the process at that time, Verilator 5.052 does not. IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression, and the change of a happened before the event control executed. A standalone probe also wakes in Icarus, and a new event expression reports an event at time 0 there." +} diff --git a/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json b/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json new file mode 100644 index 00000000000..e9d9e676a8f --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_implicit_event_in_process_verilator.json @@ -0,0 +1,34 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-UNSUPPORTED: /source_0.sv:4:23: Unsupported: Event control with implicit sensitivity (@*) in this context; use an explicit sensitivity list instead\n 4 | initial forever @* begin y = a + b; count = count + 8'd1; end\n | ^\n ... For error description see https://verilator.org/warn/UNSUPPORTED?v=5.052\n%Warning-ZERODLY: /testbench.sv:73:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 73 | if (t1 > $time) #(t1 - $time);\n | ^\n ... For warning description see https://verilator.org/warn/ZERODLY?v=5.052\n ... Use \"/* verilator lint_off ZERODLY */\" and lint_on around source to disable this message.\n%Warning-ZERODLY: /testbench.sv:114:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 114 | if (t2 > $time) #(t2 - $time);\n | ^\n%Warning-ZERODLY: /testbench.sv:155:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 155 | if (t3 > $time) #(t3 - $time);\n | ^\n%Warning-ZERODLY: /testbench.sv:185:25: Value of # delay control statically unknown. Assuming it can be #0.\n : ... If all # delays are non-zero at runtime,\n : ... use '--no-sched-zero-delay' for improved performance.\n : ... If a real #0 is expected at runtime,\n : ... use '--sched-zero-delay' to suppress this warning.\n 185 | if (t4 > $time) #(t4 - $time);\n | ^\n%Warning-INFINITELOOP: /source_0.sv:4:15: Infinite loop (condition always true)\n 4 | initial forever @* begin y = a + b; count = count + 8'd1; end\n | ^~~~~~~\n ... For warning description see https://verilator.org/warn/INFINITELOOP?v=5.052\n ... Use \"/* verilator lint_off INFINITELOOP */\" and lint_on around source to disable this message.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "counts": { + "compile_error": 1, + "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, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "note": "Focused failure before the exclusion. Verilator 5.052 rejects @* in an initial forever. A standalone always @* whose body has a delay compiles but does not terminate in Verilator, so the case cannot avoid the construct. Icarus 13.0 passes the case." +} diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index c6d6d4d721b..df08045c942 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::bit_select_edges_follow_the_selected_bit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -44,6 +55,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -242,6 +264,62 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_wake_on_rising_and_falling_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_expression_event_sample_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_expression_event_sample", + "observed_version": "Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "upstream": [] + }, + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_expressions_read_automatic_task_locals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::expression_events_see_pulses_within_a_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -319,6 +397,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -352,6 +441,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::long_process_loops_finish_within_one_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::min_typ_max_delays_wait_the_typical_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -385,6 +496,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_assignments_in_processes_update_in_the_nba_region", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -407,6 +529,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::part_select_events_see_pulses_of_the_selected_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -429,6 +562,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::pure_function_events_change_with_the_result", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -440,6 +584,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::real_expression_events_see_fractional_changes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -539,6 +694,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_actuals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_subroutines", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_functions_report_the_time_in_the_caller_unit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_literal_delays_accept_all_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Icarus 13.0 shares an unpacked local array across overlapping calls of an automatic task, including with an explicit automatic declaration. IEEE 1800-2023 13.3.1 and 13.3.2 require separate storage for each activation. The first call returns 31 instead of 11 after the second call overwrites its array; scalar task locals remain independent.", @@ -562,6 +761,61 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_scalar_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_four_state_storage_survives_suspension", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_in_edge_always_rearms_after_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_nested_copyback_wait_and_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_static_formals_remain_shared", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -595,6 +849,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_index_events_follow_the_index", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 0023e7b62c5..49ce5c92e65 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1492,6 +1492,40 @@ ] } }, + { + "id": "sv_icarus_expression_event_sample", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 wakes a process that writes an operand of an event expression and then waits on it (a = 1; @(a ^ b);). IEEE 1800-2023 9.4.2 synchronizes the statement with a value change of the expression; the write happened before the event control executed. Verilator 5.052 agrees with the expected value.", + "upstream": [], + "evidence": [ + "verification/repros/sv_expression_event_sample_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::event_controls_sample_the_expression_when_they_begin" + ] + } + }, + { + "id": "sv_verilator_implicit_event_in_process", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_implicit_event_in_process_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::implicit_event_controls_in_processes_wait_on_their_reads" + ] + } + }, { "id": "sv_verilator_dist_uniform_seed_width", "category": "simulator_compile_limitation", diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index cb48ee4a4a3..6058dfc509d 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::bit_select_edges_follow_the_selected_bit", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -44,6 +55,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -242,6 +264,50 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::edge_waits_wake_on_rising_and_falling_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_controls_sample_the_expression_when_they_begin", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::event_expressions_read_automatic_task_locals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::expression_events_see_pulses_within_a_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -319,6 +385,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_implicit_event_in_process_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_implicit_event_in_process", + "observed_version": "Verilator 5.052", + "phase": "compile", + "reason": "Verilator 5.052 rejects @* in an initial forever (\"Unsupported: Event control with implicit sensitivity (@*) in this context\"), which IEEE 1800-2023 9.4.2.2 permits in any procedural timing control statement. Icarus 13.0 passes the case.", + "upstream": [] + }, + "name": "timing::implicit_event_controls_in_processes_wait_on_their_reads", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -352,6 +441,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::long_process_loops_finish_within_one_time_slot", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::min_typ_max_delays_wait_the_typical_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -385,6 +496,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::nonblocking_assignments_in_processes_update_in_the_nba_region", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -407,6 +529,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::part_select_events_see_pulses_of_the_selected_bits", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -429,6 +562,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::pure_function_events_change_with_the_result", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -440,6 +584,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::real_expression_events_see_fractional_changes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", @@ -539,6 +694,28 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_actuals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_calls_in_child_port_subroutines", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "Verilator 5.052 evaluates an always_comb that reads $time again when the clocking event of the suite testbench fires, although no variable it reads has changed: at 3 ns y is 3 instead of 0. IEEE 1800-2023 9.2.2.2.1 makes always_comb sensitive to the variables it reads, and $time (20.3.1) is none. A standalone probe prints y=0 in Icarus 13.0 and Verilator without a clocking block, and y=3 in Verilator with one.", @@ -562,6 +739,83 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::time_literal_delays_accept_all_units", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_automatic_scalar_calls_keep_separate_storage", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "four-state expectations", + "expectation": "Simulation", + "name": "timing::timed_task_four_state_storage_survives_suspension", + "phase": "compile", + "status": "unsupported", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_in_edge_always_rearms_after_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_nested_copyback_wait_and_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::timed_task_static_formals_remain_shared", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "four-state expectations", @@ -595,6 +849,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::variable_index_events_follow_the_index", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Sequential", "detail": "", diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 957479e3b3f..2e76af89cd5 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -85,37 +85,23 @@ timed_cases! { fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; fn inactive_time_directives_do_not_change_scheduler_units = "timing::inactive_time_directives_do_not_change_scheduler_units"; - #[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"; fn finite_active_feedback_preserves_convergence = "timing::finite_active_feedback_preserves_convergence"; - #[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 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 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 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 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 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 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 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 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 frontend lowers only variables as event expressions (#1123)"] fn nba_woken_waiters_sample_before_continuations = "timing::nba_woken_waiters_sample_before_continuations"; fn negative_repeat_counts_do_not_run_the_body = "timing::negative_repeat_counts_do_not_run_the_body"; - #[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 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"; fn constant_variable_initializers_do_not_invent_clock_edges = "timing::constant_variable_initializers_do_not_invent_clock_edges"; fn repeated_active_edges_share_one_nba_batch = "timing::repeated_active_edges_share_one_nba_batch"; - #[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"; fn always_timed_task_without_inline_timing_executes = "timing::always_timed_task_without_inline_timing_executes"; fn constant_comb_if_discards_unreachable_pulse_branch = "timing::constant_comb_if_discards_unreachable_pulse_branch"; @@ -133,6 +119,15 @@ timed_cases! { 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"; + fn expression_events_see_pulses_within_a_time_slot = "timing::expression_events_see_pulses_within_a_time_slot"; + fn real_expression_events_see_fractional_changes = "timing::real_expression_events_see_fractional_changes"; + fn bit_select_edges_follow_the_selected_bit = "timing::bit_select_edges_follow_the_selected_bit"; + fn part_select_events_see_pulses_of_the_selected_bits = "timing::part_select_events_see_pulses_of_the_selected_bits"; + fn variable_index_events_follow_the_index = "timing::variable_index_events_follow_the_index"; + fn pure_function_events_change_with_the_result = "timing::pure_function_events_change_with_the_result"; + fn event_expressions_read_automatic_task_locals = "timing::event_expressions_read_automatic_task_locals"; + fn event_controls_sample_the_expression_when_they_begin = "timing::event_controls_sample_the_expression_when_they_begin"; + fn implicit_event_controls_in_processes_wait_on_their_reads = "timing::implicit_event_controls_in_processes_wait_on_their_reads"; } #[test] @@ -223,3 +218,115 @@ fn time_literal_delays_round_at_scope_precision() { sim.run_until(2800).unwrap(); assert_eq!(sim.get(coarse), 1u8.into()); } + +/// The variables of an event expression, `$event[k]` and its copies of +/// process-local operands, are state like the process slots: a state file +/// keeps them, while the signal listing and the waveform leave them out. +#[test] +fn event_expression_variables_are_hidden_state() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("events.vcd"); + let design = |dump: &str| { + format!( + r#" + module Top(output bit [7:0] count); + bit a; + task automatic await(input bit i); @(a ^ i); endtask + {dump} + initial forever begin await(1); count = count + 8'd1; end + initial begin #1; a = 1; end + endmodule + "# + ) + }; + let traced = design(&format!( + r#"initial begin $dumpfile("{}"); $dumpvars(0, Top); end"#, + path.display() + )); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(traced.as_str(), std::path::Path::new("events.sv"))], + "Top", + ) + .build() + .unwrap(); + simulation.run_until(2000).unwrap(); + assert_eq!(simulation.get(simulation.signal("count")), 1u8.into()); + simulation.flush_vcd().unwrap(); + let waveform = std::fs::read_to_string(&path).unwrap(); + assert!(waveform.contains(" count $end"), "{waveform}"); + assert!(!waveform.contains("$event"), "{waveform}"); + + let plain = design(""); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(plain.as_str(), std::path::Path::new("events.sv"))], + "Top", + ) + .build() + .unwrap(); + simulation.run_until(2000).unwrap(); + assert!( + simulation + .named_signals() + .iter() + .all(|signal| !signal.name.starts_with('$')), + "{:?}", + simulation + .named_signals() + .iter() + .map(|signal| &signal.name) + .collect::>() + ); + let state = simulation.save_state().unwrap(); + // A store of the process does not make the variable a counted signal. + assert!( + !state + .objects + .iter() + .any(|object| object.path.starts_with("$counter[$event")), + "{:?}", + state.objects + ); + for name in ["$event[0]", "$event[0].arg[0]", "$initial[0].status"] { + assert!( + state + .objects + .iter() + .any(|object| object.path == name && object.role == celox::StateRole::State), + "{name}: {:?}", + state.objects + ); + } +} + +#[test] +fn event_expressions_with_effects_are_rejected() { + for (event, construct) in [ + ( + "count_up(a)", + "impure call `count_up` in an event expression", + ), + ("$time", "impure call `$time` in an event expression"), + ("a ^ x", "event expression reading a static task argument"), + ] { + let source = format!( + r#" + module Top; + bit a; + int calls; + function automatic bit count_up(input bit v); calls++; return v; endfunction + task t(input bit x); @({event}); endtask + initial t(0); + endmodule + "# + ); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), std::path::Path::new("effects.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("`@({event})` must be rejected")) + .to_string(); + assert!(error.contains(construct), "{event}: {error}"); + } +}