diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index ae00542eef2..aad26f6f9c8 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1177,18 +1177,18 @@ chapter-6/6.19.4--enum_numerical_expr_cast.sv 2state pass chapter-6/6.19.4--enum_numerical_expr_cast.sv 4state pass chapter-6/6.19.4--enum_numerical_expr_no_cast.sv 2state fail chapter-6/6.19.4--enum_numerical_expr_no_cast.sv 4state fail -chapter-6/6.19.5.1--enum_first.sv 2state fail -chapter-6/6.19.5.1--enum_first.sv 4state fail -chapter-6/6.19.5.2--enum_last.sv 2state fail -chapter-6/6.19.5.2--enum_last.sv 4state fail -chapter-6/6.19.5.3--enum_next.sv 2state fail -chapter-6/6.19.5.3--enum_next.sv 4state fail -chapter-6/6.19.5.4--enum_prev.sv 2state fail -chapter-6/6.19.5.4--enum_prev.sv 4state fail -chapter-6/6.19.5.5--enum_num.sv 2state fail -chapter-6/6.19.5.5--enum_num.sv 4state fail -chapter-6/6.19.5.6--enum_name.sv 2state fail -chapter-6/6.19.5.6--enum_name.sv 4state fail +chapter-6/6.19.5.1--enum_first.sv 2state pass +chapter-6/6.19.5.1--enum_first.sv 4state pass +chapter-6/6.19.5.2--enum_last.sv 2state pass +chapter-6/6.19.5.2--enum_last.sv 4state pass +chapter-6/6.19.5.3--enum_next.sv 2state pass +chapter-6/6.19.5.3--enum_next.sv 4state pass +chapter-6/6.19.5.4--enum_prev.sv 2state pass +chapter-6/6.19.5.4--enum_prev.sv 4state pass +chapter-6/6.19.5.5--enum_num.sv 2state pass +chapter-6/6.19.5.5--enum_num.sv 4state pass +chapter-6/6.19.5.6--enum_name.sv 2state pass +chapter-6/6.19.5.6--enum_name.sv 4state pass chapter-6/6.20.2--parameter.sv 2state pass chapter-6/6.20.2--parameter.sv 4state pass chapter-6/6.20.2--parameter_aggregate.sv 2state pass @@ -1557,10 +1557,10 @@ chapter-8/8.5--properties_enum.sv 2state fail chapter-8/8.5--properties_enum.sv 4state fail chapter-8/8.6--methods.sv 2state pass chapter-8/8.6--methods.sv 4state pass -chapter-8/8.7--constructor.sv 2state fail -chapter-8/8.7--constructor.sv 4state fail -chapter-8/8.7--constructor_param.sv 2state fail -chapter-8/8.7--constructor_param.sv 4state fail +chapter-8/8.7--constructor.sv 2state pass +chapter-8/8.7--constructor.sv 4state pass +chapter-8/8.7--constructor_param.sv 2state pass +chapter-8/8.7--constructor_param.sv 4state pass chapter-8/8.7--constructor_super.sv 2state pass chapter-8/8.7--constructor_super.sv 4state pass chapter-8/8.8--typed_constructor.sv 2state pass diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 3d2e810cfc2..8a2322b0314 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1467,7 +1467,8 @@ fn kernel_written_names( } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = subroutines @@ -1671,7 +1672,8 @@ impl DriverScan<'_> { } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self @@ -4944,6 +4946,56 @@ pub(crate) fn attach_instance_glue( Ok(()) } +/// A [`sv::ir::Callee::Lookup`] call as nested multiplexers of case +/// equalities. The selector is lowered once and its node shared by every +/// comparison, so nested lookups lower in linear time. `lower` lowers an +/// operand with a context width and signedness. +fn lower_lookup( + args: &[Option], + width: usize, + signed: bool, + arena: &mut SLTNodeArena, + lower: &mut dyn FnMut( + &sv::ir::Expr, + &mut SLTNodeArena, + Option, + Option, + ) -> Option, +) -> Option { + let (selector, rest) = args.split_first()?; + let (default, pairs) = rest.split_last()?; + let (pairs, []) = pairs.as_chunks::<2>() else { + return None; + }; + let selector = lower(selector.as_ref()?, arena, None, None)?; + let resized = |expr: &Option| { + Some(sv::ir::Expr::Resize { + expr: Box::new(expr.clone()?), + width, + signed, + }) + }; + let mut result = lower(&resized(default)?, arena, Some(width), Some(signed))?; + for [key, value] in pairs.iter().rev() { + let key = lower(key.as_ref()?, arena, None, None)?; + let compared = celox_slt::get_width(selector, arena).max(celox_slt::get_width(key, arena)); + let left = coerce_node_width(arena, selector, Some(compared), false).ok()?; + let right = coerce_node_width(arena, key, Some(compared), false).ok()?; + let cond = arena + .alloc(SLTNode::Binary(left, BinaryOp::EqCase, right)) + .ok()?; + let then_expr = lower(&resized(value)?, arena, Some(width), Some(signed))?; + result = arena + .alloc(SLTNode::Mux { + cond, + then_expr, + else_expr: result, + }) + .ok()?; + } + Some(result) +} + /// `expr inside { items }` as the comparisons the language defines: a value /// matches by wildcard equality, a range by an inclusive bounds check. fn inside_as_comparisons(expr: &sv::ir::Expr, items: &[sv::ir::InsideItem]) -> sv::ir::Expr { @@ -7231,6 +7283,38 @@ fn lower_glue_parent_expr( source_ids, )) } + sv::ir::Expr::Call { + callee: sv::ir::Callee::Lookup { width, signed }, + args, + .. + } => { + let mut sources = HashSet::default(); + let mut source_ids = Vec::new(); + let node = lower_lookup( + args, + *width, + *signed, + arena, + &mut |expr, arena, context_width, context_signed| { + let (node, expr_sources, expr_source_ids) = lower_glue_parent_expr( + expr, + variables, + name_to_id, + constants, + parameter_types, + arena, + context_width, + context_signed, + )?; + sources.extend(expr_sources); + source_ids.extend(expr_source_ids); + Some(node) + }, + )?; + source_ids.sort(); + source_ids.dedup(); + Some((node, sources, source_ids)) + } sv::ir::Expr::Inside { expr, items } => lower_glue_parent_expr( &inside_as_comparisons(expr, items), variables, @@ -8634,6 +8718,34 @@ fn lower_expr_with_context( sources, )) } + sv::ir::Expr::Call { + callee: sv::ir::Callee::Lookup { width, signed }, + args, + .. + } => { + let mut sources = HashSet::default(); + let node = lower_lookup( + args, + *width, + *signed, + arena, + &mut |expr, arena, context_width, context_signed| { + let (node, expr_sources) = lower_expr_with_context( + expr, + variables, + name_to_id, + constants, + parameter_types, + arena, + context_width, + context_signed, + )?; + sources.extend(expr_sources); + Some(node) + }, + )?; + Some((node, sources)) + } sv::ir::Expr::Inside { expr, items } => lower_expr_with_context( &inside_as_comparisons(expr, items), variables, @@ -10856,7 +10968,8 @@ mod tests { } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index d7854a35b65..311f4f1bce8 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3425,6 +3425,7 @@ impl<'p, 'a> Comb<'p, 'a> { // Copy the inputs in, left to right, in the caller's scope. let mut outputs = Vec::new(); let mut copied = Vec::new(); + let mut references = Vec::new(); let positions: Vec<_> = if arg_order.is_empty() { (0..subroutine.params.len()).collect() } else { @@ -3445,6 +3446,19 @@ impl<'p, 'a> Comb<'p, 'a> { .cloned() .flatten() .or_else(|| param.default.clone()); + if param.direction.is_reference() { + // A reference formal names the actual variable itself + // (IEEE 1800-2023 13.5.2); other actuals fall back to Ff. + let target = match &actual { + Some(sv::ir::Expr::Ident(actual)) => self.m.id(actual), + _ => None, + } + .ok_or_else(|| { + unsupported(format!("ref argument `{}` of `{name}`", param.source_name)) + })?; + references.push((param.name.clone(), id, target)); + continue; + } if param.direction.is_written() { let actual = actual.as_ref().and_then(lvalue_from_expr).ok_or_else(|| { unsupported(format!( @@ -3510,6 +3524,9 @@ impl<'p, 'a> Comb<'p, 'a> { let width = self.m.var(id).width; self.write(store, id, full(width), value)?; } + for (formal, _, target) in &references { + self.m.name_to_id.insert(formal.clone(), *target); + } let return_var = match &subroutine.return_var { Some(name) => { let id = self @@ -3533,6 +3550,9 @@ impl<'p, 'a> Comb<'p, 'a> { self.active_calls.push(name.to_string()); let result = self.exec_block(store.fork(), &call_frames, &subroutine.body); self.active_calls.pop(); + for (formal, original, _) in references { + self.m.name_to_id.insert(formal, original); + } *store = result?; // Copy the outputs back. for (id, lvalues) in outputs { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 7306b081347..d0a962166cc 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -14,6 +14,7 @@ mod file_io; mod fread; mod objects; mod process; +mod references; mod scan; mod strings; @@ -90,6 +91,9 @@ pub(super) struct Ff<'p, 'a> { /// directly. kernel: Option, forked: bool, + /// Whether [`Self::freeze_lvalue`] keeps its copies in the activation + /// frame of a forked process. + frame_positions: bool, process_control: bool, process_predicate: bool, frame_locals: Vec, @@ -191,6 +195,7 @@ impl<'p, 'a> Ff<'p, 'a> { dist_seed: None, kernel: None, forked: false, + frame_positions: false, process_control: false, process_predicate: false, frame_locals: Vec::new(), @@ -928,7 +933,8 @@ impl<'p, 'a> Ff<'p, 'a> { } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) - | sv::ir::Callee::Checked { .. } => continue, + | sv::ir::Callee::Checked { .. } + | sv::ir::Callee::Lookup { .. } => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self.m.subroutine(&name).cloned() else { @@ -1411,6 +1417,23 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(lvalue) } + /// A copy of a position for [`Self::freeze_const`]. + fn position_temp( + &mut self, + width: usize, + signed: bool, + is_4state: bool, + ) -> Result<(SourceVarId, String), sv::AnalyzerError> { + let (temp, name) = self.m.temp("position", width, signed, is_4state); + if self.frame_positions && self.forked { + let slot = self.frame_locals.len(); + self.frame_locals.push(temp); + self.with_kernel(|kernel| kernel.local(slot)) + .map_err(kernel_error)?; + } + Ok((temp, name)) + } + /// `lvalue` with the variables its select positions read replaced by /// copies of their current values, so a later write to one does not move /// the target. @@ -1449,7 +1472,7 @@ impl<'p, 'a> Ff<'p, 'a> { let variable = self.m.var(id); let (width, signed, is_4state) = (variable.width, variable.signed, variable.is_4state); - let (temp, temp_name) = self.m.temp("position", width, signed, is_4state); + let (temp, temp_name) = self.position_temp(width, signed, is_4state)?; let value = self.eval(&sv::ir::Expr::Ident(name.clone()), Some((width, signed)))?; self.store(temp, SIROffset::Static(0), width, value); ConstExpr::Ident(temp_name) @@ -1474,7 +1497,13 @@ impl<'p, 'a> Ff<'p, 'a> { }; let value = self.eval(&read, None)?; let width = self.b.register(&value).width(); - let (temp, temp_name) = self.m.temp("position", width, *signed, is_4state); + let (temp, temp_name) = self.position_temp(width, *signed, is_4state)?; + // A frame slot starts a new block: read the bits there. + let value = if self.frame_positions && self.forked { + self.eval(&read, None)? + } else { + value + }; self.store(temp, SIROffset::Static(0), width, value); ConstExpr::Ident(temp_name) } @@ -1491,8 +1520,8 @@ impl<'p, 'a> Ff<'p, 'a> { lsb: bit, signed: false, }; + let (temp, temp_name) = self.position_temp(1, false, is_4state)?; let value = self.eval(&read, Some((1, false)))?; - let (temp, temp_name) = self.m.temp("position", 1, false, is_4state); self.store(temp, SIROffset::Static(0), 1, value); ConstExpr::Ident(temp_name) } @@ -4536,6 +4565,14 @@ impl<'p, 'a> Ff<'p, 'a> { let mut activation = Vec::new(); if self.kernel.is_some() && (subroutine.is_task || self.forked) { for name in &subroutine.automatic_locals { + // A reference formal has no storage of its own. + if subroutine + .params + .iter() + .any(|param| ¶m.name == name && param.direction.is_reference()) + { + continue; + } let original = self .m .id(name) @@ -4572,16 +4609,50 @@ impl<'p, 'a> Ff<'p, 'a> { // read a formal of an enclosing call of another subroutine. let mut outputs = Vec::new(); let mut inputs = Vec::new(); + let mut references = Vec::new(); + let mut aliases = Vec::new(); + let mut property_outputs = Vec::new(); let positions: Vec<_> = if arg_order.is_empty() { (0..subroutine.params.len()).collect() } else { arg_order.to_vec() }; + // The objects and positions that references capture come first (the + // order of evaluation of arguments is undefined, IEEE 1800-2023 + // 13.5): keeping one in a forked activation's frame starts a new + // resume point, which no evaluated input may span. + for &position in &positions { + let Some(param) = subroutine + .params + .get(position) + .filter(|param| param.direction.is_reference()) + else { + continue; + }; + let id = self + .m + .id(¶m.name) + .ok_or_else(|| unsupported(format!("argument `{}`", param.source_name)))?; + let actual = args + .get(position) + .cloned() + .flatten() + .or_else(|| param.default.clone()); + match self.reference(name, param, actual)? { + Reference::Variable(target) => { + references.push((param.name.clone(), id, target)); + } + Reference::Alias(alias) => aliases.push(*alias), + } + } for position in positions { let param = subroutine .params .get(position) .ok_or_else(|| unsupported(format!("argument position of `{name}`")))?; + if param.direction.is_reference() { + continue; + } let id = self .m .id(¶m.name) @@ -4595,15 +4666,21 @@ impl<'p, 'a> Ff<'p, 'a> { let reference = actual .as_ref() .ok_or_else(|| unsupported("missing output argument"))?; - let lvalues = lvalue_from_expr(reference).ok_or_else(|| { - unsupported(format!( - "output argument `{}` of `{name}`", - param.source_name - )) - })?; - let guards = tagged_actual_guards(reference); - self.check_tagged_guards(&guards)?; - outputs.push((param.name.clone(), id, lvalues, guards)); + // A reference formal bound to a class property, forwarded: + // its object was evaluated when the reference was made. + if let Some(store) = forwarded_property(reference, ¶m.name) { + property_outputs.push(store); + } else { + let lvalues = lvalue_from_expr(reference).ok_or_else(|| { + unsupported(format!( + "output argument `{}` of `{name}`", + param.source_name + )) + })?; + let guards = tagged_actual_guards(reference); + self.check_tagged_guards(&guards)?; + outputs.push((param.name.clone(), id, lvalues, guards)); + } } if param.direction.is_read() { let actual = actual.ok_or_else(|| { @@ -4668,6 +4745,12 @@ impl<'p, 'a> Ff<'p, 'a> { let offset = sv_memory_offset(self.m.var(id), 0, width); self.store(id, offset, width, value); } + // The body names each reference formal's actual itself, so its reads + // and writes are those of the actual, also across suspensions of a + // task and through any other name of it (IEEE 1800-2023 13.5.2). + for (formal, _, target) in &references { + self.m.name_to_id.insert(formal.clone(), *target); + } if let Some(return_var) = &subroutine.return_var { let id = self .m @@ -4683,10 +4766,21 @@ impl<'p, 'a> Ff<'p, 'a> { return_var: subroutine.return_var.clone(), loop_depth: self.loops.len(), }); + let mut body = subroutine.body; + let (constants, parameter_types) = (self.m.constants, self.m.parameter_types); + let constant = |position: &sv::ir::ConstExpr| { + sv::typecheck::eval_const_expr_with_types(position, constants, parameter_types) + }; + for alias in &aliases { + body = alias.rewrite(body, &constant)?; + } self.active_calls.push(name.to_string()); - let falls = self.exec_block(&subroutine.body); + let falls = self.exec_block(&body); self.active_calls.pop(); self.functions.pop(); + for (formal, original, _) in references { + self.m.name_to_id.insert(formal, original); + } if falls? { self.jump(return_block); } @@ -4702,6 +4796,9 @@ impl<'p, 'a> Ff<'p, 'a> { } self.observe_assignment(&lvalues)?; } + for store in property_outputs { + self.exec_block(&[store])?; + } let result = subroutine.return_var.as_ref().map(|name| { if activation.iter().any(|(local, _)| local == name) { self.m.var(self.m.id(name).unwrap()).path[0].clone() @@ -4715,6 +4812,98 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// What reference formal `param` of `name` refers to for a call with + /// `actual`. The object of a property is evaluated here, at the call. + fn reference( + &mut self, + name: &str, + param: &sv::ir::SubroutineParam, + actual: Option, + ) -> Result { + match actual { + Some(sv::ir::Expr::Ident(actual)) => self + .m + .id(&actual) + .map(Reference::Variable) + .ok_or_else(|| unsupported(format!("reference to `{actual}`"))), + Some(sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(op), + args, + .. + }) if matches!(*op, sv::ir::ObjectOp::Load(_)) => { + let sv::ir::ObjectOp::Load(field) = *op else { + unreachable!() + }; + let [Some(object)] = args.as_slice() else { + return Err(unsupported("class property receiver")); + }; + let (handle, handle_name) = self.m.temp(references::OBJECT_TEMP, 32, false, false); + self.m.variables.get_mut(&handle).unwrap().value_kind = + celox_design::ValueKind::ObjRef; + // A forked activation keeps its own object. + if self.forked { + let slot = self.frame_locals.len(); + self.frame_locals.push(handle); + self.with_kernel(|kernel| kernel.local(slot)) + .map_err(kernel_error)?; + } + let object = self.handle(object)?; + self.store(handle, SIROffset::Static(0), 32, object); + Ok(Reference::Alias(Box::new(references::Alias { + formal: param.name.clone(), + source_name: param.source_name.clone(), + target: references::Target::Property { + handle: handle_name, + field, + }, + }))) + } + // An element of a fixed-size unpacked array, which the analyzer + // has checked: its index is evaluated at the call. + Some(actual @ sv::ir::Expr::Select { .. }) => { + let signed = self.expr_signed(&actual); + let element = match lvalue_from_expr(&actual).as_deref() { + Some([element @ sv::ir::LValue::Select { .. }]) => element.clone(), + _ => { + return Err(unsupported(format!( + "ref argument `{}` of `{name}`", + param.source_name + ))); + } + }; + let element = self.hoist_lvalue(&element)?; + // A forked activation keeps its own copies of the positions. + self.frame_positions = true; + let element = self.freeze_lvalue(element); + self.frame_positions = false; + let element = element?; + let width = self.m.var(self.m.id(¶m.name).expect("a formal")).width; + let total = self + .m + .var(self.m.id(element.name()).expect("an array")) + .width; + Ok(Reference::Alias(Box::new(references::Alias { + formal: param.name.clone(), + source_name: param.source_name.clone(), + target: references::Target::Element { + element: Box::new(element), + signed, + width, + total, + }, + }))) + } + Some(_) => Err(unsupported(format!( + "ref argument `{}` of `{name}` bound to a structure member", + param.source_name + ))), + None => Err(unsupported(format!( + "missing argument `{}` of `{name}`", + param.source_name + ))), + } + } + // -------------------------------------------------------------- process /// Lower a stateful combinational process. Its memory guard records the @@ -7556,8 +7745,8 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { } continue; } - // A string operation is a value of its operands. - sv::ir::Callee::String(_) => continue, + // A string operation or lookup is a value of its operands. + sv::ir::Callee::String(_) | sv::ir::Callee::Lookup { .. } => continue, // Container contents are immutable: reading an element is a // value of the container handle and index, unlike a class // property that can change without its handle changing. @@ -8093,3 +8282,38 @@ fn past_depth_and_gate( }; Ok((depth, args.get(2).cloned().flatten())) } + +/// What a reference formal names during an inlined call. +enum Reference { + Variable(SourceVarId), + Alias(Box), +} + +/// The store that copies formal `formal` back into the class property that +/// `actual` reads through the object of a reference formal (see +/// [`references::Alias`]), when it is such a read. +fn forwarded_property(actual: &sv::ir::Expr, formal: &str) -> Option { + let sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(op), + args, + .. + } = actual + else { + return None; + }; + let (sv::ir::ObjectOp::Load(field), [Some(sv::ir::Expr::Ident(handle))]) = + (&**op, args.as_slice()) + else { + return None; + }; + handle.starts_with(references::OBJECT_TEMP).then(|| { + sv::ir::Stmt::Eval(sv::ir::Expr::Call { + callee: sv::ir::Callee::Object(Box::new(sv::ir::ObjectOp::Store(*field))), + args: vec![ + Some(sv::ir::Expr::Ident(handle.clone())), + Some(sv::ir::Expr::Ident(formal.to_owned())), + ], + arg_order: Vec::new(), + }) + }) +} diff --git a/crates/celox-frontend-sv/src/lowering/ff/references.rs b/crates/celox-frontend-sv/src/lowering/ff/references.rs new file mode 100644 index 00000000000..3efdf8207b6 --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/references.rs @@ -0,0 +1,671 @@ +//! Reference formals bound to class properties and array elements (IEEE +//! 1800-2023 13.5.2). +//! +//! A call evaluates the object handle of an actual `h.p`, or the index of an +//! actual `a[i]`, once; the inlined body then reads and writes that property +//! of that object, or that element, wherever it names the formal. + +use super::*; +use sv::ir::{ConstExpr, Expr, LValue, ObjectOp, Stmt}; + +/// The purpose of the hidden variables holding the object of a reference +/// formal bound to a class property. +pub(super) const OBJECT_TEMP: &str = "ref_object"; + +/// What a reference formal stands for in the inlined body. +pub(super) struct Alias { + pub formal: String, + /// The formal's name as written, for diagnostics. + pub source_name: String, + pub target: Target, +} + +pub(super) enum Target { + /// Property `field` of the object whose handle hidden variable `handle` + /// holds. + Property { + handle: String, + field: sv::ir::ObjectField, + }, + /// An element of an unpacked array, its positions fixed at the call. + /// The element is `width` bits of an array of `total` bits. + Element { + element: Box, + signed: bool, + width: usize, + total: usize, + }, +} + +impl Alias { + fn load(&self) -> Expr { + match &self.target { + Target::Property { handle, field } => Expr::Call { + callee: sv::ir::Callee::Object(Box::new(ObjectOp::Load(*field))), + args: vec![Some(Expr::Ident(handle.clone()))], + arg_order: Vec::new(), + }, + Target::Element { + element, signed, .. + } => { + let LValue::Select { name, msb, lsb, .. } = &**element else { + unreachable!("an element is a select") + }; + Expr::Select { + expr: Box::new(Expr::Ident(name.clone())), + msb: msb.clone(), + lsb: lsb.clone(), + signed: *signed, + } + } + } + } + + fn load_const(&self) -> ConstExpr { + match &self.target { + Target::Property { handle, field } => ConstExpr::Function { + callee: sv::ir::Callee::Object(Box::new(ObjectOp::Load(*field))), + args: vec![ConstExpr::Ident(handle.clone())], + site: None, + }, + Target::Element { + element, signed, .. + } => { + let LValue::Select { name, msb, lsb, .. } = &**element else { + unreachable!("an element is a select") + }; + ConstExpr::SelectRange { + expr: Box::new(ConstExpr::Ident(name.clone())), + msb: Box::new(msb.clone()), + lsb: Box::new(lsb.clone()), + signed: *signed, + } + } + } + } + + /// `formal = value`. + fn store(&self, value: Expr, nonblocking: bool) -> Stmt { + match &self.target { + Target::Property { handle, field } => Stmt::Eval(Expr::Call { + callee: sv::ir::Callee::Object(Box::new(ObjectOp::Store(*field))), + args: vec![Some(Expr::Ident(handle.clone())), Some(value)], + arg_order: Vec::new(), + }), + Target::Element { element, .. } => Stmt::Assign { + lhs: (**element).clone(), + rhs: value, + nonblocking, + }, + } + } + + /// `body` with the formal replaced by what it refers to. `constant` is + /// the value of a constant position expression. + pub fn rewrite( + &self, + body: Vec, + constant: &dyn Fn(&ConstExpr) -> Option, + ) -> Result, sv::AnalyzerError> { + let body = self.constant_positions(body, constant)?; + let unsupported_write = || { + unsupported(format!( + "write to part of ref argument `{}` bound to a class property or an element", + self.source_name + )) + }; + let mut error = None; + let mut body = body; + for stmt in &mut body { + stmt.walk_mut(&mut |stmt| match stmt { + Stmt::Assign { + lhs: LValue::Ident(name), + rhs, + nonblocking, + } if *name == self.formal => { + let value = std::mem::replace(rhs, Expr::Literal(String::new())); + *stmt = self.store(value, *nonblocking); + } + Stmt::Assign { lhs, .. } if lhs.name() == self.formal => { + let guard = match lhs { + LValue::Select { msb, .. } if !matches!(msb, ConstExpr::Literal(_)) => { + match self.inside(msb) { + Some(inside) => Some(inside), + None => { + error.get_or_insert_with(unsupported_write); + return; + } + } + } + _ => None, + }; + match self.within(lhs) { + Some(within) => *lhs = within, + None => { + error.get_or_insert_with(unsupported_write); + return; + } + } + // Past the element, a write at a run-time position + // writes nothing. + if let Some(inside) = guard { + let write = std::mem::replace(stmt, Stmt::Break); + *stmt = Stmt::If { + condition: inside, + then_body: vec![write], + else_body: Vec::new(), + }; + } + } + Stmt::AssignConcat { parts, .. } + if parts.iter().any(|part| part.name() == self.formal) => + { + for part in parts.iter_mut().filter(|part| part.name() == self.formal) { + match self.within(part) { + Some(within) => *part = within, + None => { + error.get_or_insert_with(unsupported_write); + } + } + } + } + _ => {} + }); + } + if let Some(error) = error { + return Err(error); + } + Ok(body + .into_iter() + .map(|stmt| { + stmt.map(&mut |expr| self.expr(expr), &mut |lvalue| { + self.lvalue(lvalue) + }) + }) + .collect()) + } + + /// `body` with the constant positions of every select of an element + /// formal as literals, and each read at a run-time position guarded: past + /// the element it reads like a select past the array. Writes are guarded + /// in [`Self::rewrite`]. + fn constant_positions( + &self, + body: Vec, + constant: &dyn Fn(&ConstExpr) -> Option, + ) -> Result, sv::AnalyzerError> { + let Target::Element { width, .. } = &self.target else { + return Ok(body); + }; + let literal = |position: ConstExpr| match constant(&position) { + Some(value) => ConstExpr::Literal(value.to_string()), + None => position, + }; + // The width of a select at a run-time position, which does not + // depend on that position. + let select_width = |msb: &ConstExpr, lsb: &ConstExpr| { + let sample = |position: &ConstExpr| constant(&sampled(position)); + Some(sample(msb)?.abs_diff(sample(lsb)?) + 1) + }; + let failed = std::cell::Cell::new(false); + let read = |msb: ConstExpr, lsb: ConstExpr, signed: bool| { + let (msb, lsb) = (literal(msb), literal(lsb)); + let select = |msb, lsb| Expr::Select { + expr: Box::new(Expr::Ident(self.formal.clone())), + msb, + lsb, + signed, + }; + if matches!(msb, ConstExpr::Literal(_)) { + return select(msb, lsb); + } + let (Some(inside), Some(bits)) = (self.inside(&msb), select_width(&msb, &lsb)) else { + failed.set(true); + return select(msb, lsb); + }; + let past = |offset: u128| ConstExpr::Literal((*width as u128 + offset).to_string()); + Expr::Mux { + condition: Box::new(inside), + then_expr: Box::new(select(msb, lsb)), + else_expr: Box::new(select(past(bits - 1), past(0))), + } + }; + let body: Vec = body + .into_iter() + .map(|stmt| { + stmt.map( + &mut |expr| self.select_positions(expr, &read), + &mut |lvalue| match lvalue { + LValue::Select { + name, + msb, + lsb, + array_slice_width, + array_slice_reversed, + } if name == self.formal => LValue::Select { + name, + msb: literal(msb), + lsb: literal(lsb), + array_slice_width, + array_slice_reversed, + }, + lvalue => lvalue, + }, + ) + }) + .collect(); + if failed.get() { + return Err(unsupported(format!( + "run-time select of ref argument `{}` bound to an array element", + self.source_name + ))); + } + Ok(body) + } + + fn select_positions( + &self, + expr: Expr, + read: &dyn Fn(ConstExpr, ConstExpr, bool) -> Expr, + ) -> Expr { + let mut inner = |expr| self.select_positions(expr, read); + match expr { + Expr::Select { + expr, + msb, + lsb, + signed, + } if matches!(&*expr, Expr::Ident(name) if *name == self.formal) => { + read(msb, lsb, signed) + } + expr => map_operands(expr, &mut inner), + } + } + + /// Whether the select of an element formal whose highest bit is at `msb` + /// stays within the element. + fn inside(&self, msb: &ConstExpr) -> Option { + let Target::Element { width, .. } = &self.target else { + return None; + }; + Some(Expr::Binary { + left: Box::new(expr_from_const_expr(msb)?), + op: sv::ir::BinaryOp::Lt, + right: Box::new(Expr::Literal(width.to_string())), + }) + } + + /// The element bits that `lvalue`, a target naming the formal, writes. + fn within(&self, lvalue: &LValue) -> Option { + let Target::Element { element, .. } = &self.target else { + return None; + }; + let LValue::Select { name, .. } = &**element else { + return None; + }; + Some(match lvalue { + LValue::Ident(_) => (**element).clone(), + LValue::Select { + msb, + lsb, + array_slice_width, + array_slice_reversed, + .. + } => { + let (msb, lsb) = + self.place(self.const_expr(msb.clone()), self.const_expr(lsb.clone())); + LValue::Select { + name: name.clone(), + msb, + lsb, + array_slice_width: array_slice_width + .clone() + .map(|width| self.const_expr(width)), + array_slice_reversed: *array_slice_reversed, + } + } + }) + } + + /// The array positions of bits `msb:lsb` of an element formal, which + /// [`Self::constant_positions`] has made literals. A select beyond the + /// element stays beyond the array, so it reads and writes nothing instead + /// of reaching a neighbouring element. + fn place(&self, msb: ConstExpr, lsb: ConstExpr) -> (ConstExpr, ConstExpr) { + let Target::Element { + element, + width, + total, + .. + } = &self.target + else { + unreachable!("only an element formal has positions") + }; + let LValue::Select { lsb: base, .. } = &**element else { + unreachable!("an element is a select") + }; + let value = |position: &ConstExpr| match position { + ConstExpr::Literal(value) => value.parse::().ok(), + _ => None, + }; + // A select past the element moves past the whole array. + match (value(&msb), value(&lsb)) { + (Some(high), Some(low)) if high >= *width as i128 || low >= *width as i128 => { + let total = *total as i128; + ( + ConstExpr::Literal((total + high - low.min(high)).to_string()), + ConstExpr::Literal((total + low - low.min(high)).to_string()), + ) + } + _ => (offset(base, msb), offset(base, lsb)), + } + } + + fn lvalue(&self, lvalue: LValue) -> LValue { + match lvalue { + LValue::Select { + name, + msb, + lsb, + array_slice_width, + array_slice_reversed, + } => LValue::Select { + name, + msb: self.const_expr(msb), + lsb: self.const_expr(lsb), + array_slice_width: array_slice_width.map(|width| self.const_expr(width)), + array_slice_reversed, + }, + lvalue => lvalue, + } + } + + fn expr(&self, expr: Expr) -> Expr { + let boxed = |expr: Box| Box::new(self.expr(*expr)); + match expr { + Expr::Ident(name) if name == self.formal => self.load(), + Expr::Ident(_) | Expr::Literal(_) => expr, + // A select of an element formal selects bits of the element. + Expr::Select { + expr, + msb, + lsb, + signed, + } if matches!(&*expr, Expr::Ident(name) if *name == self.formal) + && matches!(self.target, Target::Element { .. }) => + { + let Target::Element { element, .. } = &self.target else { + unreachable!("checked by the guard") + }; + let LValue::Select { name, .. } = &**element else { + unreachable!("an element is a select") + }; + let (msb, lsb) = self.place(self.const_expr(msb), self.const_expr(lsb)); + Expr::Select { + expr: Box::new(Expr::Ident(name.clone())), + msb, + lsb, + signed, + } + } + Expr::Select { + expr, + msb, + lsb, + signed, + } => Expr::Select { + expr: boxed(expr), + msb: self.const_expr(msb), + lsb: self.const_expr(lsb), + signed, + }, + Expr::Concat(parts) => { + Expr::Concat(parts.into_iter().map(|part| self.expr(part)).collect()) + } + Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { + count: self.const_expr(count), + parts: parts.into_iter().map(|part| self.expr(part)).collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: boxed(expr), + width, + signed, + }, + Expr::Unary { op, expr } => Expr::Unary { + op, + expr: boxed(expr), + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: boxed(left), + op, + right: boxed(right), + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: boxed(condition), + then_expr: boxed(then_expr), + else_expr: boxed(else_expr), + }, + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + callee, + args: args + .into_iter() + .map(|arg| arg.map(|arg| self.expr(arg))) + .collect(), + arg_order, + }, + Expr::Inside { expr, items } => Expr::Inside { + expr: boxed(expr), + items: items + .iter() + .map(|item| item.map(&mut |e| self.expr(e.clone()))) + .collect(), + }, + } + } + + fn const_expr(&self, expr: ConstExpr) -> ConstExpr { + let boxed = |expr: Box| Box::new(self.const_expr(*expr)); + match expr { + ConstExpr::Ident(name) if name == self.formal => self.load_const(), + ConstExpr::Ident(_) | ConstExpr::Literal(_) => expr, + ConstExpr::Select { expr, bit } => ConstExpr::Select { + expr: boxed(expr), + bit: boxed(bit), + }, + ConstExpr::SelectRange { + expr, + msb, + lsb, + signed, + } => ConstExpr::SelectRange { + expr: boxed(expr), + msb: boxed(msb), + lsb: boxed(lsb), + signed, + }, + ConstExpr::Resize { + expr, + width, + signed, + } => ConstExpr::Resize { + expr: boxed(expr), + width, + signed, + }, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee, + args: args.into_iter().map(|arg| self.const_expr(arg)).collect(), + site, + }, + ConstExpr::Unary { op, expr } => ConstExpr::Unary { + op, + expr: boxed(expr), + }, + ConstExpr::Binary { left, op, right } => ConstExpr::Binary { + left: boxed(left), + op, + right: boxed(right), + }, + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => ConstExpr::Mux { + condition: boxed(condition), + then_expr: boxed(then_expr), + else_expr: boxed(else_expr), + }, + } + } +} + +/// Position `position` of an element that starts at `base`. +fn offset(base: &ConstExpr, position: ConstExpr) -> ConstExpr { + ConstExpr::Binary { + left: Box::new(base.clone()), + op: sv::ir::BinaryOp::Add, + right: Box::new(position), + } +} + +/// `expr` with `f` applied to each operand expression. +fn map_operands(expr: Expr, f: &mut dyn FnMut(Expr) -> Expr) -> Expr { + let mut boxed = |expr: Box| Box::new(f(*expr)); + match expr { + Expr::Ident(_) | Expr::Literal(_) => expr, + Expr::Select { + expr, + msb, + lsb, + signed, + } => Expr::Select { + expr: boxed(expr), + msb, + lsb, + signed, + }, + Expr::Concat(parts) => Expr::Concat(parts.into_iter().map(f).collect()), + Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { + count, + parts: parts.into_iter().map(f).collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: boxed(expr), + width, + signed, + }, + Expr::Unary { op, expr } => Expr::Unary { + op, + expr: boxed(expr), + }, + Expr::Binary { left, op, right } => { + let left = boxed(left); + Expr::Binary { + left, + op, + right: boxed(right), + } + } + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + let condition = boxed(condition); + let then_expr = boxed(then_expr); + Expr::Mux { + condition, + then_expr, + else_expr: boxed(else_expr), + } + } + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + callee, + args: args.into_iter().map(|arg| arg.map(&mut *f)).collect(), + arg_order, + }, + Expr::Inside { expr, items } => Expr::Inside { + expr: boxed(expr), + items: items + .iter() + .map(|item| item.map(&mut |e| f(e.clone()))) + .collect(), + }, + } +} + +/// `position` with every variable it reads replaced by 0. +fn sampled(position: &ConstExpr) -> ConstExpr { + let boxed = |expr: &ConstExpr| Box::new(sampled(expr)); + match position { + ConstExpr::Ident(_) => ConstExpr::Literal("0".into()), + ConstExpr::Literal(_) => position.clone(), + ConstExpr::Select { expr, bit } => ConstExpr::Select { + expr: boxed(expr), + bit: boxed(bit), + }, + ConstExpr::SelectRange { + expr, + msb, + lsb, + signed, + } => ConstExpr::SelectRange { + expr: boxed(expr), + msb: boxed(msb), + lsb: boxed(lsb), + signed: *signed, + }, + ConstExpr::Resize { + expr, + width, + signed, + } => ConstExpr::Resize { + expr: boxed(expr), + width: *width, + signed: *signed, + }, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), + args: args.iter().map(sampled).collect(), + site: *site, + }, + ConstExpr::Unary { op, expr } => ConstExpr::Unary { + op: *op, + expr: boxed(expr), + }, + ConstExpr::Binary { left, op, right } => ConstExpr::Binary { + left: boxed(left), + op: *op, + right: boxed(right), + }, + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => ConstExpr::Mux { + condition: boxed(condition), + then_expr: boxed(then_expr), + else_expr: boxed(else_expr), + }, + } +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 523b8aa3312..b36fe6adf4f 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -288,6 +288,8 @@ impl<'a> ProcModule<'a> { } continue; } + // A lookup is a value of its operands. + sv::ir::Callee::Lookup { .. } => continue, // String operations use the simulator's heap. sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) @@ -1147,6 +1149,7 @@ impl<'a> ProcModule<'a> { pub fn is_callee(&self, callee: &sv::ir::Callee) -> bool { match callee { sv::ir::Callee::System(function) => function.reads_simulation_state(), + sv::ir::Callee::Lookup { .. } => false, sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) | sv::ir::Callee::Checked { .. } => true, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 0dd6ccb287b..bce87c08b8a 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -120,6 +120,7 @@ impl Deref for AnalysisContext<'_> { } } +use crate::procedural::ParamDirection; pub use crate::system_functions::{ ArrayQuery, Callee, ContainerKind, ContainerLayout, ContainerOp, ObjectOp, StringOp, SystemFunction, SystemTask, @@ -144,6 +145,7 @@ mod constants; mod declarations; mod dimensions; mod dpi; +mod enums; mod expression_binding; mod expressions; mod ff_process; @@ -1204,6 +1206,7 @@ impl Module { is_2state: function.return_is_2state, string: function.return_string, pattern_type: function.return_type.clone(), + enum_domain: function.return_enum_domain.clone(), }, ) })); @@ -1223,6 +1226,7 @@ impl Module { is_2state: !r#type.is_4state(), string: false, pattern_type: None, + enum_domain: None, }, )) })); @@ -1259,6 +1263,7 @@ impl Module { subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(syntax_tree), statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; @@ -1326,18 +1331,25 @@ impl Module { &subroutine_directions, comb_processes .iter_mut() - .map(|process| &mut process.body) - .chain(ff_processes.iter_mut().map(|process| &mut process.body)) + .map(|process| (&mut process.body, false)) + .chain( + ff_processes + .iter_mut() + .map(|process| (&mut process.body, false)), + ) .chain( initial_processes .iter_mut() - .map(|process| &mut process.body), + .map(|process| (&mut process.body, !process.repeats)), ), + Some(&body_state.explicit_statics), )?; for subroutine in &subroutines { kept.extend(subroutine.persistent_locals.iter().cloned()); } - static_initializers.append(&mut body_state.static_initializers); + // Statics of subroutines are initialized first: a run-time + // initializer of a process local may call the subroutine. + static_initializers.splice(0..0, body_state.static_initializers.drain(..)); locals.retain(|local| !kept.contains(&local.name)); for name in kept { signals.push(Signal::new(name.clone(), statics[&name].clone())); @@ -1348,10 +1360,18 @@ impl Module { .iter() .position(|process| !process.is_initializer()) .unwrap_or(initial_processes.len()); + // They may read module variables, so they also stay after those + // initializers when processes are reordered by creation. + let creation_order = initial_processes + .iter() + .filter(|process| process.is_initializer()) + .map(|process| process.creation_order) + .max() + .unwrap_or(0); initial_processes.insert( first_block, InitialProcess { - creation_order: 0, + creation_order, site: None, condition: None, body: static_initializers, @@ -1406,6 +1426,21 @@ impl Module { } } } + let nets = signals + .iter() + .filter(|signal| signal.is_net()) + .map(Signal::name) + .chain(ports.iter().filter(|port| port.is_net).map(Port::name)) + .collect(); + procedural::references::validate( + subroutines.iter().chain(imported.subroutines.iter()), + &comb_processes, + &ff_processes, + &initial_processes, + &subroutine_directions, + &subroutine_params, + &nets, + )?; procedural::timed_tasks::classify( subroutines.iter().chain(imported.subroutines.iter()), &mut comb_processes, @@ -1651,6 +1686,8 @@ pub struct Parameter { is_local: bool, /// See [`Type::signed_element_depth`]. signed_element_depth: Option, + /// The enumerated type the parameter is declared with. + enum_domain: Option>, } impl Parameter { @@ -1675,6 +1712,7 @@ impl Parameter { has_declared_type, is_local, signed_element_depth: None, + enum_domain: None, } } @@ -2144,8 +2182,11 @@ pub enum PortDirection { pub struct Type { container: Option>, is_enum: bool, - /// Resolved legal values for a scalar enum; None if its domain is unsupported. - enum_values: Option>, + /// Resolved members of a scalar enum; None if its domain is unsupported. + enum_domain: Option>, + /// A packed array whose elements are of an enumerated type, whose + /// methods are not supported on its elements. + packed_enum: bool, kind: TypeKind, is_signed: bool, packed_ranges: Vec, @@ -2191,7 +2232,8 @@ impl Type { fn implicit() -> Self { Self { is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, kind: TypeKind::Implicit, is_signed: false, packed_ranges: Vec::new(), @@ -2208,7 +2250,8 @@ impl Type { Self { kind, is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, is_signed: false, packed_ranges: Vec::new(), unpacked_ranges: Vec::new(), @@ -2771,6 +2814,8 @@ struct Function { return_dimensions: Option, return_signed: bool, return_is_2state: bool, + /// The members of an enumerated return type, for its methods. + return_enum_domain: Option>, } fn function_argument_metadata(params: &[FunctionParam]) -> Arc<[FunctionArgumentMetadata]> { @@ -2796,21 +2841,6 @@ fn dpi_argument_metadata(import: &crate::ir::DpiImport) -> Arc<[FunctionArgument .collect() } -/// How a function argument is passed. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ParamDirection { - Input, - Output, - Inout, -} - -impl ParamDirection { - /// Whether the call writes the actual argument back. - fn is_written(self) -> bool { - !matches!(self, ParamDirection::Input) - } -} - #[derive(Debug, Clone, PartialEq, Eq)] struct FunctionParam { has_default: bool, @@ -2997,7 +3027,9 @@ struct UnpackedDimension { struct VariableDimensions { container: Option>, randomizable: bool, - enum_values: Option>, + enum_domain: Option>, + /// See [`Type::packed_enum`]. + packed_enum: bool, real: bool, /// A `string`: each element is a heap handle, not packed bits. string: bool, @@ -3034,6 +3066,8 @@ struct FunctionReturnMetadata { string: bool, /// Declared aggregate type, available before function bodies are inlined. pattern_type: Option, + /// The members of an enumerated return type, for its methods. + enum_domain: Option>, } #[derive(Debug, Clone, Default, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index 28701f62ad3..2fbcb574320 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -69,6 +69,21 @@ pub(super) fn expr_is_two_state( callee: Callee::Checked { .. }, .. } => false, + // The selector is compared with case equality; the result is a value + // or the default. + Expr::Call { + callee: Callee::Lookup { .. }, + args, + .. + } => { + let key = |index: usize| index % 2 == 1 && index + 1 != args.len(); + args.iter().enumerate().skip(1).all(|(index, arg)| { + key(index) + || arg + .as_ref() + .is_some_and(|arg| expr_is_two_state(state, arg, packed_dimensions)) + }) + } Expr::Call { callee: Callee::Object(op), .. diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 2b4716c8a28..d4ab21cf3d8 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -43,7 +43,8 @@ impl Property { return None; } if self.r#type.is_enum { - self.r#type.enum_values.as_ref().and_then(|values| { + self.r#type.enum_domain.as_ref().and_then(|domain| { + let values = &domain.members; (1..=256) .contains(&values.len()) .then_some(values.len() as u16) @@ -167,7 +168,7 @@ impl Class { } if (property.rand || property.randc) && (property.field.handle.is_some() - || (property.r#type.is_enum && property.r#type.enum_values.is_none())) + || (property.r#type.is_enum && property.r#type.enum_domain.is_none())) { return Err(unsupported( "class randomize requires integral rand properties with a supported enum domain", diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index 68e6e82b630..e9fa1ed0109 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -112,7 +112,7 @@ pub(super) fn expr_static_width( .. } => Some(op.result_type().0), Expr::Call { - callee: Callee::Checked { width, .. }, + callee: Callee::Checked { width, .. } | Callee::Lookup { width, .. }, .. } => Some(*width), Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 6c5de5936bb..22a41a5f0ba 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -503,6 +503,7 @@ fn collect_module_constant_functions( subroutine_directions: &subroutine_directions, automatic: lifetimes::automatic_by_default(tree), statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: true, }; @@ -637,7 +638,8 @@ fn simulation_state_readers(functions: &[Subroutine]) -> HashMap {} + | Callee::Checked { .. } + | Callee::Lookup { .. } => {} Callee::Subroutine(callee) => calls.push(callee.as_str()), } } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 4b6c56b87d2..6a9c799395f 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -134,9 +134,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals( VariableDimensions { container: port.r#type().container.clone(), randomizable: port.r#type().container.is_none() - && (!port.r#type().is_enum || port.r#type().enum_values.is_some()) + && (!port.r#type().is_enum || port.r#type().enum_domain.is_some()) && port.randomizable, - enum_values: port.r#type().enum_values.clone(), + enum_domain: port.r#type().enum_domain.clone(), + packed_enum: port.r#type().packed_enum, real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(port.r#type().kind(), TypeKind::String), class: port.r#type().class().map(str::to_owned), @@ -163,10 +164,11 @@ pub(super) fn packed_dimensions_from_ports_and_signals( VariableDimensions { container: signal.r#type().container.clone(), randomizable: signal.r#type().container.is_none() - && (!signal.r#type().is_enum || signal.r#type().enum_values.is_some()) + && (!signal.r#type().is_enum || signal.r#type().enum_domain.is_some()) && !signal.is_net() && !signal.is_const, - enum_values: signal.r#type().enum_values.clone(), + enum_domain: signal.r#type().enum_domain.clone(), + packed_enum: signal.r#type().packed_enum, real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(signal.r#type().kind(), TypeKind::String), class: signal.r#type().class().map(str::to_owned), @@ -362,7 +364,8 @@ fn extend_variable_dimensions_from_const_env( let ty = Type { container: None, is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, kind: TypeKind::Logic, is_signed: variable_type_is_signed(const_env, name), packed_ranges, @@ -379,7 +382,8 @@ fn extend_variable_dimensions_from_const_env( if let Some(existing) = context.get(name) { shape.container = existing.container.clone(); shape.randomizable = existing.randomizable; - shape.enum_values = existing.enum_values.clone(); + shape.enum_domain = existing.enum_domain.clone(); + shape.packed_enum = existing.packed_enum; shape.members = existing.members.clone(); shape.is_2state = existing.is_2state; shape.signed_element_depth = existing.signed_element_depth; @@ -543,14 +547,15 @@ mod tests; pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariablePackedDimensions { parameters .iter() - .filter(|parameter| !parameter.packed_ranges.is_empty()) + .filter(|parameter| !parameter.packed_ranges.is_empty() || parameter.enum_domain.is_some()) .map(|parameter| { ( parameter.name.clone(), VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: parameter.enum_domain.clone(), + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 5ba75332b4d..8ff37fa3313 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -309,14 +309,10 @@ fn formal_types( for ports in groups { for port in ports { if let Some(d) = port.direction { - direction = match d { - celox_sv_syntax::Direction::Input => ParamDirection::Input, - celox_sv_syntax::Direction::Output => ParamDirection::Output, - celox_sv_syntax::Direction::Inout => ParamDirection::Inout, - celox_sv_syntax::Direction::Ref => { - return Err(unsupported("ref subroutine argument")); - } - }; + if port.static_reference { + return Err(unsupported("ref static subroutine argument")); + } + direction = ParamDirection::declared(d, port.constant); } let data = tree.declarations().data_type(port.data_type); let omitted = matches!(data.kind, DataTypeKind::Implicit) @@ -395,6 +391,9 @@ fn return_metadata( signed: ty.is_some_and(Type::is_signed), is_2state: ty.is_some_and(|ty| ty.kind() == TypeKind::Bit), string: ty.is_some_and(|ty| ty.kind() == TypeKind::String), + enum_domain: ty + .filter(|ty| ty.unpacked_ranges.is_empty()) + .and_then(|ty| ty.enum_domain.clone()), pattern_type: ty .filter(|ty| { !ty.members.is_empty() @@ -739,6 +738,7 @@ fn settle( is_2state: !ty.is_4state(), string: false, pattern_type: None, + enum_domain: None, }, ); publish(&tree.state.dimensions, key, context); 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 c7b9cb3c8c6..e883ba38ec0 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -1016,6 +1016,7 @@ mod tests { is_2state: false, string: false, pattern_type: None, + enum_domain: None, }, ); for declaration in &tree.declarations().data_declarations { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index c437030ae2a..cd08ca70634 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -194,6 +194,7 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( is_2state: f.return_is_2state, string: f.return_string, pattern_type: f.return_type.clone(), + enum_domain: None, }, ) })); diff --git a/crates/celox-sv-analyzer/src/ast/enums.rs b/crates/celox-sv-analyzer/src/ast/enums.rs new file mode 100644 index 00000000000..0ccf4289278 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/enums.rs @@ -0,0 +1,27 @@ +//! Enumerated types (IEEE 1800-2023 6.19) and their methods (6.19.5). + +/// One named member of an enumerated type. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(super) struct EnumMember { + pub name: String, + pub value: i128, +} + +/// The members of an enumerated type in declaration order, with the shape +/// of its base type. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(super) struct EnumDomain { + pub members: Vec, + pub width: usize, + pub signed: bool, + /// Whether the base type is 4-state, whose default initial value is + /// `'x` rather than `'0` (Table 6-7). + pub four_state: bool, +} + +impl EnumDomain { + /// The values of the members, in declaration order. + pub fn values(&self) -> Vec { + self.members.iter().map(|member| member.value).collect() + } +} diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 2914256434d..a6e911ac35a 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -3,8 +3,10 @@ use super::*; use celox_sv_syntax::{Declarations, DimensionKind, ExprId, ExprKind}; mod calls; mod direct; +mod enums; mod lvalues; mod objects; +mod references; #[cfg(test)] mod selected; mod strings; diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 094ee60b2bd..2c95136577f 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -234,6 +234,13 @@ enum Finish { Inside(Vec), /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), + /// An enumerated type method; the children are the receiver, then the + /// count when one is given. + EnumMethod { + method: enums::Method, + domain: std::sync::Arc, + count: bool, + }, /// A read of property `property` of the object handle child. ObjectLoad(Box), /// A call of method subroutine `name` with `formals` formals; the first @@ -296,6 +303,53 @@ pub(in crate::ast) fn bind_value( )); } } + let enum_method = match &native.expression(id).kind { + ExprKind::Call { + expression, + arguments, + } => enums::method(tree, *expression, native, dimensions)? + .map(|method| (method, arguments.as_slice())), + ExprKind::Member { .. } => { + enums::method(tree, id, native, dimensions)?.map(|method| (method, &[][..])) + } + _ => None, + }; + if let Some(((method, receiver, domain), arguments)) = enum_method { + // `v.next()` lists one empty argument. + let arguments = match arguments { + [argument] if argument.name.is_none() && argument.value.is_none() => &[], + arguments => arguments, + }; + let counts = arguments + .iter() + .map(|argument| argument.value.filter(|_| argument.name.is_none())) + .collect::>>() + .filter(|counts| counts.len() <= method.formals()) + .ok_or_else(|| { + unsupported(format!( + "arguments of enumerated type method `{}`", + native.token_text(native.expression(id).tokens).trim() + )) + })?; + let mut children = vec![receiver]; + children.extend(&counts); + jobs.push(Job::Finish( + Finish::EnumMethod { + method, + domain, + count: !counts.is_empty(), + }, + children.len(), + scope.clone(), + )); + jobs.extend( + children + .into_iter() + .rev() + .map(|id| Job::Enter(id, None, scope.clone())), + ); + continue; + } if let Some(call) = super::super::processes::value(tree, id, native, dimensions, false)? { @@ -488,12 +542,23 @@ pub(in crate::ast) fn bind_value( if let objects::Receiver::Handle(handle) = receiver { children.push((handle, None)); } - for arg in args.iter().filter(|_| selection.is_none()) { + let first = usize::from(receiver != objects::Receiver::Static); + for (position, arg) in + args.iter().filter(|_| selection.is_none()).enumerate() + { let Some(value) = arg.value else { return Err(unsupported(format!( "omitted argument of method `{name}`" ))); }; + references::check_actual( + &name, + first + position, + value, + native, + tree, + dimensions, + )?; children.push((value, None)); } ( @@ -573,7 +638,8 @@ pub(in crate::ast) fn bind_value( "scope randomize requires a packed variable with a supported enum domain", )); } - domains.push(shape.enum_values.clone()); + domains + .push(shape.enum_domain.as_ref().map(|domain| domain.values())); if !expressions::query_actual_is_writable( &Expr::Ident(name), dimensions, @@ -743,6 +809,11 @@ pub(in crate::ast) fn bind_value( } else { let (actuals, order) = arguments(&name, args, dimensions)?; for (position, id) in actuals.iter().enumerate() { + if let Some(id) = id { + references::check_actual( + &name, position, *id, native, tree, dimensions, + )?; + } if let Some(id) = id && let Some(shape) = dimensions .subroutine_param_shapes @@ -1068,6 +1139,21 @@ pub(in crate::ast) fn bind_value( strings::call(StringOp::Concat, operands) } Finish::Concat => Expr::Concat(operands), + Finish::EnumMethod { + method, + domain, + count, + } => { + let count = count.then(|| operands.pop()).flatten(); + enums::call( + &tree.state, + method, + &domain, + operands.pop(), + count, + dimensions, + )? + } Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs new file mode 100644 index 00000000000..0771dd19d61 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs @@ -0,0 +1,497 @@ +//! Enumerated type methods (IEEE 1800-2023 6.19.5). +//! +//! The methods are values of the members of the receiver's type. They bind +//! to [`Callee::Lookup`] calls, which evaluate the receiver once and compare +//! it with the members by case equality, so a value that is no member of +//! the type, including one with unknown bits, matches none of them. + +use std::sync::Arc; + +use super::direct::call_name; +use super::*; +use crate::ast::enums::EnumDomain; + +/// An enumerated type method. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Method { + First, + Last, + Next, + Prev, + Num, + Name, +} + +impl Method { + fn parse(name: &str) -> Option { + Some(match name { + "first" => Self::First, + "last" => Self::Last, + "next" => Self::Next, + "prev" => Self::Prev, + "num" => Self::Num, + "name" => Self::Name, + _ => return None, + }) + } + + /// Whether the result is a string. + pub(super) fn returns_string(self) -> bool { + self == Self::Name + } + + /// Whether the result is a value of the enumerated type. + fn returns_member(self) -> bool { + matches!(self, Self::First | Self::Last | Self::Next | Self::Prev) + } + + /// The number of arguments the method takes at most: `next` and `prev` + /// take a count, which defaults to 1. + pub(super) fn formals(self) -> usize { + usize::from(matches!(self, Self::Next | Self::Prev)) + } +} + +/// The enumerated type method that native callee expression `id` names, +/// with the expression it is called on and that expression's type. +pub(super) fn method( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted)>> { + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(ungroup(id, native)).kind + else { + return Ok(None); + }; + if separator != "." { + return Ok(None); + } + let Some(method) = Method::parse(&instances::normalize_identifier(&name.spelling)) else { + return Ok(None); + }; + Ok(domain(tree, *expression, native, dimensions)?.map(|domain| (method, *expression, domain))) +} + +/// The enumerated type of native expression `id`, judged before it is +/// bound: a variable, an element of an array, a class property, a call of +/// a function, method or enumerated type method, a cast, or the status of a +/// process. +pub(super) fn domain( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted>> { + // `process::state` (9.7). + if let Some(domain) = processes::state(tree, id, native, dimensions) { + return Ok(Some(domain)); + } + Ok(match &native.expression(ungroup(id, native)).kind { + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + match dimensions.get(&name) { + Some(shape) => variable(shape), + None => match objects::property(tree, id, native, dimensions)? { + Some((property, _)) => scalar(&property.r#type), + None => constant(&tree.state, &name, dimensions), + }, + } + } + ExprKind::Member { .. } => match method(tree, id, native, dimensions)? { + // A method called without parentheses (6.19.5.7). + Some((method, _, domain)) => method.returns_member().then_some(domain), + None => match objects::static_property(tree, id, native, dimensions)? + .or_else(|| call_name(&tree.state, id, native)) + .and_then(|name| dimensions.get(&name)) + { + // A static property or a package variable. + Some(shape) => variable(shape), + // A package-qualified enum constant. + None if let Some(domain) = call_name(&tree.state, id, native) + .and_then(|name| constant(&tree.state, &name, dimensions)) => + { + Some(domain) + } + None => match objects::property(tree, id, native, dimensions)? { + Some((property, _)) => scalar(&property.r#type), + // A member of a packed struct. + None => dimensions::operand_shape(id, tree, dimensions) + .ok() + .flatten() + .and_then(|shape| variable(&shape)), + }, + }, + }, + ExprKind::Select { .. } => element(tree, id, native, dimensions)?, + ExprKind::Call { expression, .. } => { + if let Some((method, _, domain)) = method(tree, *expression, native, dimensions)? { + method.returns_member().then_some(domain) + } else if let ExprKind::Member { + expression: base, + name, + .. + } = &native.expression(ungroup(*expression, native)).kind + && matches!(name.spelling.as_str(), "pop_front" | "pop_back") + && let Some(container) = containers::native_type(*base, native, tree, dimensions)? + { + // An element popped from a queue (7.10.2.4, 7.10.2.5). + scalar(&container.element) + } else { + let name = match objects::method(tree, *expression, native, dimensions)? { + Some((name, _, _)) => Some(name), + None => call_name(&tree.state, *expression, native), + }; + name.and_then(|name| { + dimensions + .function_return_types + .get(&name) + .and_then(|metadata| metadata.enum_domain.clone()) + .or_else(|| { + dimensions + .functions + .get(&name) + .and_then(|function| function.return_enum_domain.clone()) + }) + }) + } + } + ExprKind::Cast { target, .. } => { + let target = ungroup(*target, native); + let ty = if let Some(name) = call_name(&tree.state, target, native) { + dimensions.type_aliases.get(&name).cloned() + } else if let ExprKind::Type(id) = native.expression(target).kind { + type_binding::binding::bind_in(id, native, tree, dimensions)? + } else { + None + }; + ty.as_ref().and_then(scalar) + } + ExprKind::Conditional { + then_expression, + else_expression, + .. + } => { + let then_domain = domain(tree, *then_expression, native, dimensions)?; + let else_domain = domain(tree, *else_expression, native, dimensions)?; + then_domain.filter(|domain| else_domain.as_ref() == Some(domain)) + } + _ => None, + }) +} + +/// The enumerated type of a value of type `ty`. +fn scalar(ty: &Type) -> Option> { + (ty.unpacked_ranges.is_empty() && ty.container.is_none()) + .then(|| ty.enum_domain.clone()) + .flatten() +} + +/// The enumerated type of a value of a variable of shape `shape`. +fn variable(shape: &VariableDimensions) -> Option> { + (shape.unpacked.is_empty() && shape.container.is_none()) + .then(|| shape.enum_domain.clone()) + .flatten() +} + +/// The enumerated type of enum constant `name`: the named type of its scope +/// declaring a member of that name and value. A qualified constant is one +/// of a type of the scope that qualifies it, and an unqualified one that no +/// local type declares is the package item an import makes visible; other +/// scopes may declare members of the same name and value. +fn constant( + state: &AnalysisState, + name: &str, + dimensions: &PackedDimensions, +) -> Option> { + let value = *dimensions.const_env.get(name)?; + let find = |scope: Option<&str>, member: &str| { + let mut candidates = dimensions + .type_aliases + .iter() + .filter(|(alias, _)| match scope { + Some(scope) => alias + .strip_prefix(scope) + .is_some_and(|rest| rest.starts_with("::")), + None => !alias.contains("::"), + }) + .filter_map(|(_, ty)| ty.enum_domain.as_ref()) + .filter(|domain| { + domain + .members + .iter() + .any(|candidate| candidate.name == member && candidate.value == value) + }); + let domain = candidates.next()?; + candidates + .all(|other| other == domain) + .then(|| domain.clone()) + }; + match name.rsplit_once("::") { + Some((scope, member)) => find(Some(scope), member), + None => find(None, name).or_else(|| { + let qualified = scope::imported(state).aliases.get(name)?.clone(); + let (scope, member) = qualified.rsplit_once("::")?; + find(Some(scope), member) + }), + } +} + +/// The enumerated type of an element select `id` of an unpacked array or +/// container whose elements are of one. +fn element( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Converted>> { + let mut root = ungroup(id, native); + let mut selects = 0; + while let ExprKind::Select { + expression, + dimension, + } = &native.expression(root).kind + { + if !matches!(dimension.kind, DimensionKind::Index(_)) { + return Ok(None); + } + if selects == 0 + && let Some(container) = containers::native_type(*expression, native, tree, dimensions)? + { + return Ok(scalar(&container.element)); + } + selects += 1; + root = ungroup(*expression, native); + } + let (unpacked, domain, packed_enum) = match &native.expression(root).kind { + ExprKind::Name(name) + if let Some(shape) = + dimensions.get(&instances::normalize_identifier(&name.spelling)) => + { + if shape.container.is_some() { + return Ok(None); + } + ( + shape.unpacked.len(), + shape.enum_domain.clone(), + shape.packed_enum, + ) + } + // A static property or a package variable. + ExprKind::Member { .. } + if let Some(shape) = objects::static_property(tree, root, native, dimensions)? + .or_else(|| call_name(&tree.state, root, native)) + .and_then(|name| dimensions.get(&name)) => + { + if shape.container.is_some() { + return Ok(None); + } + ( + shape.unpacked.len(), + shape.enum_domain.clone(), + shape.packed_enum, + ) + } + ExprKind::Name(_) | ExprKind::Member { .. } => { + match objects::property(tree, root, native, dimensions)? { + Some((property, _)) if property.r#type.container.is_none() => ( + property.r#type.unpacked_ranges.len(), + property.r#type.enum_domain.clone(), + property.r#type.packed_enum, + ), + _ => return Ok(None), + } + } + _ => return Ok(None), + }; + if packed_enum && selects > unpacked { + return Err(unsupported( + "method of an element of a packed array of enums", + )); + } + Ok(domain.filter(|_| unpacked == selects)) +} + +/// The value of `method` of `domain` called on `receiver` with `count`. +pub(super) fn call( + state: &AnalysisState, + method: Method, + domain: &EnumDomain, + receiver: Option, + count: Option, + dimensions: &PackedDimensions, +) -> Converted { + let members = &domain.members; + let member = |index: usize| { + Expr::Literal(format_typed_parameter_literal( + members[index].value, + domain.width, + domain.signed, + )) + }; + let int = |value: usize| Expr::Literal(format_typed_parameter_literal(value as i128, 32, true)); + let wide = + |value: usize| Expr::Literal(format_typed_parameter_literal(value as i128, 64, false)); + let lookup = |width, signed, selector, pairs: Vec<(Expr, Expr)>, default| Expr::Call { + callee: Callee::Lookup { width, signed }, + args: std::iter::once(Some(selector)) + .chain( + pairs + .into_iter() + .flat_map(|(key, value)| [Some(key), Some(value)]), + ) + .chain(std::iter::once(Some(default))) + .collect(), + arg_order: Vec::new(), + }; + let count_members = members.len(); + let receiver = receiver.ok_or_else(disagreement)?; + // A result that does not depend on the receiver still evaluates it once, + // for the effects of the calls it makes. + let evaluated = |value: Expr, width, signed| { + let mut effects = false; + lifetimes::visit_calls(&receiver, &mut |callee, _| effects |= callee.is_effectful()); + if effects { + lookup(width, signed, receiver.clone(), Vec::new(), value) + } else { + value + } + }; + Ok(match method { + Method::First => evaluated(member(0), domain.width, domain.signed), + Method::Last => evaluated(member(count_members - 1), domain.width, domain.signed), + Method::Num => evaluated(int(count_members), 32, true), + Method::Next | Method::Prev => { + // A value that is no member gives the default initial value of + // the base type (6.19.5.3, 6.19.5.4, Table 6-7). + let default = Expr::Literal(if domain.four_state { + format!("{}'bx", domain.width) + } else { + format!("{}'b0", domain.width) + }); + // `int unsigned N`: only N modulo the number of members matters. + // The count converts to the formal's type as in an assignment, + // extended by its own signedness; the type is 2-state, so unknown + // bits become 0. + let count = casts::runtime_cast_target_expr( + state, + casts::RuntimeCastTarget::Integral { + target: ExprType { + width: 32, + signed: false, + }, + numeric_size: false, + two_state: true, + }, + count.unwrap_or_else(|| int(1)), + dimensions, + )?; + let constant = expr_to_const(state, count.clone()) + .and_then(|count| eval_ast_const_expr(state, &count, &dimensions.const_env)) + .map(|count| (count as u32 as usize) % count_members); + if let Some(shift) = constant { + let shift = if method == Method::Next { + shift + } else { + count_members - shift + }; + let pairs = (0..count_members) + .map(|index| (member(index), member((index + shift) % count_members))) + .collect(); + lookup( + domain.width, + domain.signed, + receiver.clone(), + pairs, + default, + ) + } else { + // The receiver's index, or 2N for a value that is no member, + // plus the shift selects from the members repeated twice. + let index = lookup( + 64, + false, + receiver.clone(), + (0..count_members) + .map(|index| (member(index), wide(index))) + .collect(), + wide(2 * count_members), + ); + let shift = Expr::Resize { + expr: Box::new(Expr::Binary { + left: Box::new(count), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format_typed_parameter_literal( + count_members as i128, + 32, + false, + ))), + }), + width: 64, + signed: false, + }; + let position = if method == Method::Next { + Expr::Binary { + left: Box::new(index), + op: BinaryOp::Add, + right: Box::new(shift), + } + } else { + Expr::Binary { + left: Box::new(Expr::Binary { + left: Box::new(index), + op: BinaryOp::Add, + right: Box::new(wide(count_members)), + }), + op: BinaryOp::Sub, + right: Box::new(shift), + } + }; + let pairs = (0..2 * count_members) + .map(|position| (wide(position), member(position % count_members))) + .collect(); + lookup(domain.width, domain.signed, position, pairs, default) + } + } + Method::Name => { + // The bytes of each name, which a value that is no member + // replaces by the empty string (6.19.5.6). + let width = 8 * members + .iter() + .map(|member| member.name.len()) + .max() + .unwrap_or(0) + .max(1); + let pairs = (0..count_members) + .map(|index| { + let bytes = members[index].name.as_bytes(); + let name = if bytes.is_empty() { + "8'h0".to_string() + } else { + format!( + "{}'h{}", + 8 * bytes.len(), + bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::() + ) + }; + (member(index), Expr::Literal(name)) + }) + .collect(); + let bytes = lookup( + width, + false, + receiver.clone(), + pairs, + Expr::Literal(format!("{width}'h0")), + ); + strings::call(StringOp::FromBits, vec![bytes]) + } + }) +} diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 8366951d85e..fa9c870bdf0 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -857,7 +857,7 @@ pub(super) fn random_selection( return Err(unsupported("randomization of a 4-state class property")); } if property.field.handle.is_some() - || (property.r#type.is_enum && property.r#type.enum_values.is_none()) + || (property.r#type.is_enum && property.r#type.enum_domain.is_none()) || (property.randc && property.cyclic_domain_size().is_none()) { return Err(unsupported( diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs new file mode 100644 index 00000000000..9354c71e6c2 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs @@ -0,0 +1,222 @@ +//! Actual arguments of `ref` and `const ref` formals (IEEE 1800-2023 +//! 13.5.2): only a variable, a class property, a member of an unpacked +//! structure, or an element of an unpacked array, of a type equivalent to the +//! formal's (6.22.2). +use super::*; + +/// Check actual `actual` of formal `position` of subroutine `name` when that +/// formal is passed by reference. +pub(super) fn check_actual( + name: &str, + position: usize, + actual: ExprId, + native: &Declarations, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, +) -> Converted<()> { + if !dimensions + .subroutine_directions + .get(name) + .and_then(|directions| directions.get(position)) + .is_some_and(|direction| direction.is_reference()) + { + return Ok(()); + } + let invalid = |detail: &str| AnalyzerError::InvalidRefArgument { + subroutine: name.to_owned(), + argument: dimensions + .subroutine_param_names + .get(name) + .and_then(|names| names.get(position)) + .cloned() + .unwrap_or_else(|| (position + 1).to_string()), + detail: detail.to_owned(), + }; + let actual = ungroup(actual, native); + let shape = match &native.expression(actual).kind { + ExprKind::Name(variable) => { + let variable = instances::normalize_identifier(&variable.spelling); + match dimensions.get(&variable) { + Some(shape) + if !dimensions.const_env.contains_key(&variable) + && !dimensions.parameter_values.contains_key(&variable) => + { + Some(shape.clone()) + } + Some(_) => { + return Err(invalid( + "a constant is not a variable (IEEE 1800-2023 13.5.2)", + )); + } + None => objects::property(tree, actual, native, dimensions)? + .map(|(property, _)| procedural::dimensions_from_type(&property.r#type)), + } + } + ExprKind::Member { .. } => match objects::property(tree, actual, native, dimensions)? { + Some((property, _)) => Some(procedural::dimensions_from_type(&property.r#type)), + // A static property is a variable of its class's scope. + None if let Some(variable) = + objects::static_property(tree, actual, native, dimensions)? => + { + match dimensions.get(&variable) { + Some(shape) => Some(shape.clone()), + None => return Ok(()), + } + } + None => { + return Err(unsupported(format!( + "ref argument of `{name}` bound to a structure member or hierarchical name" + ))); + } + }, + ExprKind::Select { + expression, + dimension, + } if matches!(dimension.kind, DimensionKind::Index(_)) => { + let mut indices = 1; + let mut base = ungroup(*expression, native); + while let ExprKind::Select { + expression, + dimension, + } = &native.expression(base).kind + && matches!(dimension.kind, DimensionKind::Index(_)) + { + indices += 1; + base = ungroup(*expression, native); + } + let ExprKind::Name(variable) = &native.expression(base).kind else { + return Err(unsupported(format!( + "ref argument of `{name}` bound to a member or element of an expression" + ))); + }; + let variable = instances::normalize_identifier(&variable.spelling); + let Some(array) = dimensions.get(&variable) else { + return Err(unsupported(format!( + "ref argument of `{name}` bound to an element of a class property" + ))); + }; + if array.container.is_some() { + if indices == 1 { + // Elements of dynamically sized arrays: their reference + // must outlive a resize or a deletion of the element. + return Err(unsupported(format!( + "ref argument of `{name}` bound to an element of a dynamic array, queue, or associative array" + ))); + } + return Err(invalid("a select of a container element is not a variable")); + } + if indices > array.unpacked.len() { + return Err(invalid( + "a select of packed bits is not a variable (IEEE 1800-2023 13.5.2)", + )); + } + array_compatibility::selected_unpacked_shape(&variable, indices, dimensions).or_else( + || { + (indices == array.unpacked.len()).then(|| VariableDimensions { + unpacked: Vec::new(), + ..array.clone() + }) + }, + ) + } + _ => { + return Err(invalid( + "only a variable, a class property, a member of an unpacked structure, or an element of an unpacked array can be passed by reference (IEEE 1800-2023 13.5.2)", + )); + } + }; + let Some(shape) = shape else { + return Err(invalid( + "only a variable, a class property, a member of an unpacked structure, or an element of an unpacked array can be passed by reference (IEEE 1800-2023 13.5.2)", + )); + }; + let formal = dimensions + .subroutine_param_shapes + .get(name) + .and_then(|shapes| shapes.get(position)); + // Bounded and unbounded queues are equivalent (6.22.2), but a formal's + // operations would apply its own bound to the actual. + if let (Some(formal), Some(actual)) = ( + formal.and_then(|formal| formal.container.as_deref()), + shape.container.as_deref(), + ) && let ( + system_functions::ContainerKind::Queue { capacity: bound }, + system_functions::ContainerKind::Queue { capacity }, + ) = (formal.layout.kind, actual.layout.kind) + && bound != capacity + { + return Err(unsupported(format!( + "ref argument of `{name}` binding queues with different bounds" + ))); + } + if formal.is_some_and(|formal| !equivalent(&tree.state, formal, &shape, &dimensions.const_env)) + { + return Err(invalid( + "the actual's type is not equivalent to the formal's (IEEE 1800-2023 6.22.2)", + )); + } + Ok(()) +} + +/// Whether variables of shapes `a` and `b` have equivalent types (IEEE +/// 1800-2023 6.22.2). Integral types compare by total width, signedness and +/// state count; an enumeration only by its values. +fn equivalent( + state: &AnalysisState, + a: &VariableDimensions, + b: &VariableDimensions, + env: &HashMap, +) -> bool { + let count = |width: &ConstExpr| eval_ast_const_expr(state, width, env); + match (&a.container, &b.container) { + (None, None) => {} + (Some(a), Some(b)) => { + use system_functions::ContainerKind; + let same_kind = match (a.layout.kind, b.layout.kind) { + (ContainerKind::Dynamic, ContainerKind::Dynamic) + | (ContainerKind::Queue { .. }, ContainerKind::Queue { .. }) => true, + (ContainerKind::Associative { .. }, ContainerKind::Associative { .. }) => { + match (&a.key, &b.key) { + (Some(x), Some(y)) => equivalent( + state, + &procedural::dimensions_from_type(x), + &procedural::dimensions_from_type(y), + env, + ), + (None, None) => true, + _ => false, + } + } + _ => false, + }; + return same_kind + && equivalent( + state, + &procedural::dimensions_from_type(&a.element), + &procedural::dimensions_from_type(&b.element), + env, + ); + } + _ => return false, + } + if a.unpacked.len() != b.unpacked.len() + || a.unpacked + .iter() + .zip(&b.unpacked) + .any(|(a, b)| count(&a.width).is_none() || count(&a.width) != count(&b.width)) + { + return false; + } + if a.real != b.real || a.string != b.string || a.class != b.class { + return false; + } + if (a.enum_values.is_some() || b.enum_values.is_some()) && a.enum_values != b.enum_values { + return false; + } + let width = |shape: &VariableDimensions| { + shape.packed.iter().try_fold(1i128, |width, dimension| { + Some(width * count(&dimension.width)?) + }) + }; + width(a).is_some() && width(a) == width(b) && a.signed == b.signed && a.is_2state == b.is_2state +} diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs index 5e4a83e2b54..74b0acb2d54 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -171,7 +171,10 @@ pub(in crate::ast) fn native_string( } ExprKind::Call { expression, .. } => { method(tree, *expression, native, dimensions).is_some_and(|(op, _)| op.returns_string()) + || enum_name(tree, *expression, native, dimensions) } + // `e.name` without parentheses (6.19.5.6, 6.19.5.7). + ExprKind::Member { .. } if enum_name(tree, id, native, dimensions) => true, // A string property of a class object. _ => objects::property(tree, id, native, dimensions) .ok() @@ -182,6 +185,20 @@ pub(in crate::ast) fn native_string( } } +/// Whether native callee expression `id` names the `name` method of an +/// enumerated type (6.19.5.6). +fn enum_name( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> bool { + enums::method(tree, id, native, dimensions) + .ok() + .flatten() + .is_some_and(|(method, _, _)| method.returns_string()) +} + /// The string method that native callee expression `id` names, with the /// expression it is called on. pub(in crate::ast) fn method( diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index f349f66b33c..0c0813c79aa 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -41,18 +41,8 @@ pub(super) fn native_functions( .chain(native.port_declarations.iter().flat_map(|decl| &decl.ports)) { if let Some(direction) = port.direction { - previous = match direction { - celox_sv_syntax::Direction::Input => { - crate::procedural::ParamDirection::Input - } - celox_sv_syntax::Direction::Output => { - crate::procedural::ParamDirection::Output - } - celox_sv_syntax::Direction::Inout => { - crate::procedural::ParamDirection::Inout - } - _ => continue, - }; + previous = + crate::procedural::ParamDirection::declared(direction, port.constant); } if let Some(name) = &port.name { arguments.push(instances::normalize_identifier(&name.spelling)); @@ -85,6 +75,7 @@ pub(super) fn native_functions( subroutine_directions: &directions, automatic, statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; @@ -195,12 +186,7 @@ fn native_signature( .flat_map(|group| &group.ports), ) { if let Some(value) = port.direction { - direction = match value { - celox_sv_syntax::Direction::Input => ParamDirection::Input, - celox_sv_syntax::Direction::Output => ParamDirection::Output, - celox_sv_syntax::Direction::Inout => ParamDirection::Inout, - _ => direction, - }; + direction = ParamDirection::declared(value, port.constant); } let Some(name) = &port.name else { continue }; let data = tree.declarations().data_type(port.data_type); @@ -268,6 +254,10 @@ fn native_signature( }), return_signed: result.is_some_and(|ty| ty.signed), return_is_2state: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::Bit), + return_enum_domain: ty + .as_ref() + .filter(|ty| ty.unpacked_ranges.is_empty()) + .and_then(|ty| ty.enum_domain.clone()), return_type: ty .filter(|ty| { !ty.members.is_empty() diff --git a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs index 148f6407015..88aa54998a0 100644 --- a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs +++ b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs @@ -311,7 +311,14 @@ pub(super) fn body( subroutine: &Subroutine, locals: &[LocalVariable], ) -> Option<(Expr, Vec<(String, Expr)>)> { - if !subroutine.persistent_locals.is_empty() { + // An expression of the arguments copies them; a reference formal must + // name the actual for the whole call (IEEE 1800-2023 13.5.2). + if !subroutine.persistent_locals.is_empty() + || subroutine + .params + .iter() + .any(|param| param.direction.is_reference()) + { return None; } let mut types = HashMap::default(); diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 68627134adb..a88b3e7d17a 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -2089,6 +2089,7 @@ mod tests { is_2state: false, string: false, pattern_type: None, + enum_domain: None, }; let inner = FunctionReturnMetadata { arguments: None, @@ -2099,6 +2100,7 @@ mod tests { is_2state: true, string: false, pattern_type: None, + enum_domain: None, }; let dimensions = PackedDimensions { function_return_types: [ diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs index 7b3088d9d89..f44b20d91d2 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs @@ -150,7 +150,8 @@ impl CallSites for Type { fn call_sites(&self, visit: &mut dyn FnMut(usize)) { let Type { is_enum: _, - enum_values: _, + enum_domain: _, + packed_enum: _, kind: _, is_signed: _, packed_ranges, @@ -189,7 +190,8 @@ impl CallSites for VariableDimensions { let VariableDimensions { container: _, randomizable: _, - enum_values: _, + enum_domain: _, + packed_enum: _, real: _, string: _, class: _, diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index bcbffdacd43..da4b901db5a 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -124,7 +124,7 @@ pub(super) fn expr_signedness_with_return_types( .. } => Some(op.result_type().1), Expr::Call { - callee: Callee::Checked { signed, .. }, + callee: Callee::Checked { signed, .. } | Callee::Lookup { signed, .. }, .. } => Some(*signed), Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 55824a2b4d6..fed3e3d3183 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -31,18 +31,27 @@ enum Entry { /// time-zero initializations. /// `directions` gives the argument directions of the subroutines a body /// may call. +/// For the bodies of processes, `explicit` gives the statics declared with +/// the `static` keyword, and each body tells whether its process runs once; +/// see [`initialized_at_time_zero`]. pub(super) fn keep_static_locals<'b, T>( state: &AnalysisState, statics: &HashMap, directions: &Directions, - bodies: impl IntoIterator>, + bodies: impl IntoIterator, bool)>, + explicit: Option<&HashSet>, ) -> Result<(Vec, Vec), AnalyzerError> { let mut kept = Vec::new(); let mut initializers = Vec::new(); if statics.is_empty() { return Ok((kept, initializers)); } - for body in bodies { + let mut bodies = bodies.into_iter().collect::>(); + let initialized = match explicit { + Some(explicit) => initialized_at_time_zero(state, statics, explicit, &bodies), + None => HashSet::default(), + }; + for (body, _) in &mut bodies { let mut concurrent = false; for stmt in body.iter() { stmt.walk(&mut |stmt| concurrent |= matches!(stmt, Stmt::Fork { .. })); @@ -51,6 +60,7 @@ pub(super) fn keep_static_locals<'b, T>( state, body, statics, + &initialized, directions, &mut kept, &mut initializers, @@ -60,10 +70,74 @@ pub(super) fn keep_static_locals<'b, T>( Ok((kept, initializers)) } +/// The static locals of process `bodies` whose initializer is not constant +/// but reads no automatic variable, with the static locals they read. The +/// initializer of a static variable may be any run-time expression, and +/// runs once before any procedure starts (IEEE 1800-2023 6.8, 6.21); these +/// locals keep their value so that the time-zero initialization does that. +/// +/// 6.21 requires the `static` keyword on an initialized static variable of +/// a procedural block, to show that the initializer runs only once. Without +/// it, a non-constant initializer is accepted only in a process that runs +/// once, such as an `initial` procedure, where running it at time zero +/// rather than on entry cannot repeat; in an `always` procedure it remains +/// rejected, like one that reads an automatic variable. +fn initialized_at_time_zero( + state: &AnalysisState, + statics: &HashMap, + explicit: &HashSet, + bodies: &[(&mut Vec, bool)], +) -> HashSet { + let mut initializers = HashMap::default(); + let mut automatic = Vec::new(); + for (body, once) in bodies { + for stmt in body.iter() { + stmt.walk(&mut |stmt| { + if let Stmt::Local { name, init } = stmt { + if statics.contains_key(name) { + let allowed = *once || explicit.contains(name); + initializers.insert(name.as_str(), (init.as_ref(), allowed)); + } else { + automatic.push(name.as_str()); + } + } + }); + } + } + let runtime = |init: &Expr| { + !expr_is_constant(state, init) && !automatic.iter().any(|name| expr_reads(init, name)) + }; + let mut pending = initializers + .iter() + .filter(|(_, (init, allowed))| *allowed && init.is_some_and(runtime)) + .map(|(name, _)| *name) + .collect::>(); + let mut initialized = HashSet::default(); + while let Some(name) = pending.pop() { + let (init, allowed) = initializers.get(name).copied().unwrap_or_default(); + if init.is_some_and(|init| !expr_is_constant(state, init) && !(allowed && runtime(init))) + || !initialized.insert(name.to_string()) + { + continue; + } + if let Some(init) = init { + pending.extend( + initializers + .keys() + .filter(|other| expr_reads(init, other)) + .copied(), + ); + } + } + initialized +} + +#[allow(clippy::too_many_arguments)] fn keep_in( state: &AnalysisState, stmts: &mut Vec, statics: &HashMap, + initialized: &HashSet, directions: &Directions, kept: &mut Vec, initializers: &mut Vec, @@ -75,7 +149,8 @@ fn keep_in( // time slot (IEEE 1800-2023 16.5.1), which the local keeps. if let Stmt::Local { name, init } = &stmts[index] && statics.contains_key(name) - && (concurrent + && (initialized.contains(name) + || concurrent || sampled_reads(&stmts[index + 1..], name) || entry( state, @@ -109,6 +184,7 @@ fn keep_in( state, then_body, statics, + initialized, directions, kept, initializers, @@ -118,6 +194,7 @@ fn keep_in( state, else_body, statics, + initialized, directions, kept, initializers, @@ -130,6 +207,7 @@ fn keep_in( state, &mut item.body, statics, + initialized, directions, kept, initializers, @@ -141,6 +219,7 @@ fn keep_in( state, default, statics, + initialized, directions, kept, initializers, @@ -155,6 +234,7 @@ fn keep_in( state, init, statics, + initialized, directions, kept, initializers, @@ -164,6 +244,7 @@ fn keep_in( state, step, statics, + initialized, directions, kept, initializers, @@ -173,6 +254,7 @@ fn keep_in( state, body, statics, + initialized, directions, kept, initializers, @@ -181,7 +263,16 @@ fn keep_in( } Stmt::Fork { branches, .. } => { for branch in branches { - keep_in(state, branch, statics, directions, kept, initializers, true)?; + keep_in( + state, + branch, + statics, + initialized, + directions, + kept, + initializers, + true, + )?; } } _ => {} @@ -747,7 +838,7 @@ impl Flow<'_> { Stmt::AssignConcat { parts, .. } => { writes |= parts.iter().any(|part| part.name() == self.name) } - // A task may write an output or inout argument; one of a + // A task may write an output, inout, or ref argument; one of a // subroutine whose directions are unknown may be either. Stmt::Call { name, args, .. } => { let directions = self.directions.get(name); @@ -755,15 +846,13 @@ impl Flow<'_> { arg.as_ref().is_some_and(|arg| expr_reads(arg, self.name)) && directions .and_then(|directions| directions.get(index)) - .is_none_or(|direction| { - *direction != crate::procedural::ParamDirection::Input - }) + .is_none_or(|direction| direction.is_written()) }) } _ => {} }); - // A function called in an expression may write an output or - // inout argument too. + // A function called in an expression may write an output, + // inout, or ref argument too. stmt.walk(&mut |stmt| { for expr in stmt_exprs(stmt) { writes |= self.call_writes(expr); @@ -774,7 +863,7 @@ impl Flow<'_> { } /// Whether a function called in `expr` writes the local through an - /// output or inout argument. + /// output, inout, or ref argument. fn call_writes(&self, expr: &Expr) -> bool { let mut writes = false; visit_calls(expr, &mut |callee, args| { @@ -786,9 +875,7 @@ impl Flow<'_> { arg.as_ref().is_some_and(|arg| expr_reads(arg, self.name)) && directions .and_then(|directions| directions.get(index)) - .is_some_and(|direction| { - *direction != crate::procedural::ParamDirection::Input - }) + .is_some_and(|direction| direction.is_written()) }); }); writes @@ -916,7 +1003,7 @@ pub(super) fn visit_calls<'e>(expr: &'e Expr, f: &mut impl FnMut(&'e Callee, &'e } } -fn expr_reads(expr: &Expr, name: &str) -> bool { +pub(super) fn expr_reads(expr: &Expr, name: &str) -> bool { match expr { Expr::Ident(ident) => ident == name, Expr::Literal(_) => false, diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 19bba63f9ca..3c033e560da 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -76,7 +76,8 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 4e1615ca057..7f519807931 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -567,6 +567,10 @@ pub(super) fn parameters_from_native_with_environment( parameter.packed_ranges = parameter_ranges.clone(); parameter.members = parameter_members.clone(); parameter.signed_element_depth = parameter_signed_element_depth; + parameter.enum_domain = declared_alias + .as_ref() + .filter(|_| !alias_has_use_site_dimensions) + .and_then(|alias| alias.enum_domain.clone()); validate_parameter_materialization_width( parameter .resolved_type(&environment.types) diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index bfb477f6249..f05a05e2eb9 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -516,7 +516,8 @@ fn pattern_items( VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 8d0254a853d..0e5444bf9a0 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -139,7 +139,8 @@ fn select<'a>( let sub = Shape::Owned(Rc::new(VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, @@ -250,7 +251,8 @@ fn select<'a>( let bit = Shape::Owned(Rc::new(VariableDimensions { container: None, randomizable: true, - enum_values: None, + enum_domain: None, + packed_enum: false, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index bd96070de1a..2502af44cd7 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -13,6 +13,7 @@ mod final_procedures; mod foreach; use foreach::ForeachLoop; pub(super) mod randomization; +pub(super) mod references; pub(super) mod timed_tasks; mod timing; use crate::procedural::{ @@ -49,6 +50,8 @@ pub(super) struct BodyState<'a> { /// The locals declared with a static lifetime: their unique names and /// types. pub statics: Vec<(String, Type)>, + /// The statics declared with the `static` keyword. + pub explicit_statics: HashSet, /// Function static declarations initialized once at time zero. pub static_initializers: Vec, /// Constant calls get a fresh frame, even for static declarations (13.4.3). @@ -78,8 +81,9 @@ pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { container: r#type.container.clone(), randomizable: r#type.container.is_none() - && (!r#type.is_enum || r#type.enum_values.is_some()), - enum_values: r#type.enum_values.clone(), + && (!r#type.is_enum || r#type.enum_domain.is_some()), + enum_domain: r#type.enum_domain.clone(), + packed_enum: r#type.packed_enum, real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(r#type.kind(), TypeKind::String), class: r#type.class().map(str::to_owned), @@ -122,7 +126,8 @@ pub(super) fn int_type() -> Type { Type { container: None, is_enum: false, - enum_values: None, + enum_domain: None, + packed_enum: false, kind: TypeKind::Bit, is_signed: true, packed_ranges: vec![PackedRange::new( @@ -1131,6 +1136,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { _ => self.automatic, }; if !automatic { + if native.lifetime.as_deref() == Some("static") { + self.state.explicit_statics.insert(name.clone()); + } let r#type = scoped_type(signal.r#type().clone(), &self.dims.const_env); self.state.statics.push((name.clone(), r#type)); } @@ -2305,6 +2313,19 @@ pub(super) fn lower_subroutine( // Methods are automatic (IEEE 1800-2023 8.6). None => builder.automatic || class.is_some(), }; + if !builder.automatic + && let Some((argument, ..)) = params + .iter() + .find(|(_, direction, ..)| direction.is_reference()) + { + return Err(AnalyzerError::InvalidRefArgument { + subroutine: name.clone(), + argument: argument.clone(), + detail: "a subroutine with a static lifetime cannot pass arguments by reference \ + (IEEE 1800-2023 13.5.2)" + .into(), + }); + } let first_static = builder.state.statics.len(); builder.push_scope(); if let Some(class) = class { @@ -2539,7 +2560,8 @@ pub(super) fn lower_subroutine( &tree.state, &retained_types, builder.state.subroutine_directions, - std::iter::once(&mut subroutine.body), + std::iter::once((&mut subroutine.body, false)), + None, )?; if retain_result { kept.extend(subroutine.return_var.clone()); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index 7c9482d730c..f1f8ee21e76 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -708,6 +708,7 @@ mod tests { subroutine_directions: &directions, automatic: false, statics: Vec::new(), + explicit_statics: HashSet::default(), static_initializers: Vec::new(), constant_evaluation: false, }; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 7cf4e43d484..1b0503e0a00 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -229,7 +229,7 @@ fn lower_methods( if property.constant || property.field.handle.is_some() || (property.r#type.is_enum - && property.r#type.enum_values.is_none()) + && property.r#type.enum_domain.is_none()) { continue; } @@ -383,7 +383,12 @@ fn random_property( classes::object_call(op, vec![Expr::Ident(this.into())]) }; let mut body = Vec::new(); - let value = if let Some(values) = &property.r#type.enum_values { + let value = if let Some(values) = property + .r#type + .enum_domain + .as_ref() + .map(|domain| domain.values()) + { let count = values.len() as u64; let threshold = count.wrapping_neg() % count; let draw = builder.declare("$enum_draw", classes::unsigned_type(64)); diff --git a/crates/celox-sv-analyzer/src/ast/procedural/references.rs b/crates/celox-sv-analyzer/src/ast/procedural/references.rs new file mode 100644 index 00000000000..42208409462 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/procedural/references.rs @@ -0,0 +1,467 @@ +//! Uses of reference formals and calls passing by reference that IEEE +//! 1800-2023 forbids, checked once the bodies are bound. +use super::*; +use crate::procedural::ParamDirection; +use lifetimes::{expr_reads, stmt_exprs, visit_calls}; + +pub(in crate::ast) fn validate<'a>( + subroutines: impl Iterator, + comb: &[CombProcess], + ff: &[FfProcess], + processes: &[InitialProcess], + directions: &lifetimes::Directions, + names: &HashMap>, + nets: &HashSet<&str>, +) -> Result<(), AnalyzerError> { + let formal = |name: &str, position: usize| { + names + .get(name) + .and_then(|names| names.get(position)) + .cloned() + .unwrap_or_else(|| (position + 1).to_string()) + }; + let invalid = + |subroutine: &str, argument: &str, detail: &str| AnalyzerError::InvalidRefArgument { + subroutine: subroutine.to_owned(), + argument: argument.to_owned(), + detail: detail.to_owned(), + }; + let direction = |name: &str, position: usize| { + directions + .get(name) + .and_then(|directions| directions.get(position)) + .copied() + }; + // A net is never passed by reference (13.5.2). + let check_call = |name: &str, args: &[Option]| -> Result<(), AnalyzerError> { + for (position, arg) in args.iter().enumerate() { + if let Some(actual) = arg.as_ref().and_then(root_variable) + && direction(name, position).is_some_and(ParamDirection::is_reference) + && nets.contains(actual) + { + return Err(invalid( + name, + &formal(name, position), + "a net cannot be passed by reference (IEEE 1800-2023 13.5.2)", + )); + } + } + Ok(()) + }; + let check_exprs = |exprs: &mut dyn Iterator| -> Result<(), AnalyzerError> { + let mut result = Ok(()); + for expr in exprs { + visit_calls(expr, &mut |callee, args| { + if let Callee::Subroutine(name) = callee + && result.is_ok() + { + result = check_call(name, args); + } + }); + } + result + }; + let check_body = |body: &[Stmt]| -> Result<(), AnalyzerError> { + let mut result = Ok(()); + for stmt in body { + stmt.walk(&mut |stmt| { + if result.is_err() { + return; + } + if let Stmt::Call { name, args, .. } = stmt { + result = check_call(name, args); + } + if result.is_ok() { + result = check_exprs(&mut stmt_exprs(stmt).into_iter()); + } + }); + } + result + }; + // A function with a ref argument is called only from procedural code, + // and never in an event expression (13.4.1); const ref is allowed. + let passes_reference = |expr: &Expr| { + let mut found = None; + visit_calls(expr, &mut |callee, args| { + if let Callee::Subroutine(name) = callee + && let Some(position) = (0..args.len()) + .find(|position| direction(name, *position) == Some(ParamDirection::Ref)) + { + found.get_or_insert_with(|| procedural_only(name, &formal(name, position))); + } + }); + found + }; + for process in comb { + for assignment in process.assignments() { + if let Some(error) = passes_reference(assignment.rhs()) { + return Err(error); + } + check_exprs(&mut std::iter::once(assignment.rhs()))?; + } + // A continuous assignment to a concatenation is a statement. + if process.kind() == CombProcessKind::ContinuousAssign { + for stmt in process.body() { + let mut found = None; + stmt.walk(&mut |stmt| { + for expr in stmt_exprs(stmt) { + if found.is_none() { + found = passes_reference(expr); + } + } + }); + if let Some(error) = found { + return Err(error); + } + } + } + check_body(process.body())?; + } + for process in ff { + check_body(process.body())?; + } + for process in processes { + check_body(process.body())?; + let mut found = None; + for stmt in process.body() { + stmt.walk(&mut |stmt| { + if let Stmt::WaitEvent(items) = stmt { + for item in items { + for expr in std::iter::once(&item.expr).chain(&item.iff) { + if found.is_none() { + found = passes_reference(expr); + } + } + } + } + }); + } + if let Some(error) = found { + return Err(error); + } + } + for subroutine in subroutines { + check_body(&subroutine.body)?; + for param in subroutine + .params + .iter() + .filter(|param| param.direction.is_reference()) + { + let formal = param.name.as_str(); + let mut error = None; + for stmt in &subroutine.body { + check_formal(stmt, formal, param.direction, directions, &mut error); + } + if let Some(detail) = error { + return Err(invalid(&subroutine.name, ¶m.source_name, detail)); + } + } + } + Ok(()) +} + +fn procedural_only(name: &str, argument: &str) -> AnalyzerError { + AnalyzerError::InvalidRefArgument { + subroutine: name.to_owned(), + argument: argument.to_owned(), + detail: "a function with a ref argument can only be called in a procedural statement \ + outside an event expression (IEEE 1800-2023 13.4.1)" + .into(), + } +} + +/// The variable that an actual names or selects from. +fn root_variable(actual: &Expr) -> Option<&str> { + match actual { + Expr::Ident(name) => Some(name), + Expr::Select { expr, .. } | Expr::Resize { expr, .. } => root_variable(expr), + _ => None, + } +} + +/// Whether an actual passed to a writable formal writes variable `name`: +/// the variable itself, a select of it, or a part of a concatenation. +fn writes_through(actual: &Expr, name: &str) -> bool { + match actual { + Expr::Ident(ident) => ident == name, + Expr::Select { expr, .. } | Expr::Resize { expr, .. } => writes_through(expr, name), + Expr::Concat(parts) => parts.iter().any(|part| writes_through(part, name)), + Expr::Call { + callee: Callee::Checked { .. }, + args, + .. + } => args + .last() + .and_then(Option::as_ref) + .is_some_and(|value| writes_through(value, name)), + _ => false, + } +} + +/// Record in `error` why statement `stmt` cannot use reference formal +/// `formal` of direction `direction`. +fn check_formal( + stmt: &Stmt, + formal: &str, + direction: ParamDirection, + directions: &lifetimes::Directions, + error: &mut Option<&'static str>, +) { + let constant = direction == ParamDirection::ConstRef; + let written_by_call = |callee: &Callee, args: &[Option]| { + args.iter().enumerate().any(|(position, arg)| { + arg.as_ref().is_some_and(|arg| writes_through(arg, formal)) + && match callee { + Callee::Subroutine(name) => directions + .get(name) + .and_then(|directions| directions.get(position)) + .is_none_or(|direction| direction.is_written()), + Callee::System(function) => function.writes_argument(position), + Callee::Object(op) => op.writes_argument(position), + Callee::String(_) | Callee::Checked { .. } => false, + } + }) + }; + stmt.walk(&mut |stmt| { + if error.is_some() { + return; + } + let (targets, nonblocking): (Vec<&LValue>, bool) = match stmt { + Stmt::Assign { + lhs, nonblocking, .. + } => (vec![lhs], *nonblocking), + Stmt::AssignConcat { + parts, nonblocking, .. + } => (parts.iter().collect(), *nonblocking), + _ => (Vec::new(), false), + }; + if targets.iter().any(|target| target.name() == formal) { + if nonblocking { + *error = Some( + "a ref argument cannot be written by a nonblocking assignment \ + (IEEE 1800-2023 6.21, 13.5.2)", + ); + } else if constant { + *error = Some("a const ref argument cannot be written (IEEE 1800-2023 13.5.2)"); + } + } + if constant && error.is_none() { + let mut written = match stmt { + Stmt::Call { name, args, .. } => { + written_by_call(&Callee::Subroutine(name.clone()), args) + } + Stmt::SystemTask { task, args, .. } => { + args.iter().enumerate().any(|(position, arg)| { + task.writes_argument(position) + && matches!(arg, crate::procedural::SystemTaskArg::Expr(arg) + if writes_through(arg, formal)) + }) + } + _ => false, + }; + for expr in stmt_exprs(stmt) { + visit_calls(expr, &mut |callee, args| { + written |= written_by_call(callee, args); + }); + } + if written { + *error = Some("a const ref argument cannot be written (IEEE 1800-2023 13.5.2)"); + } + } + // Processes a fork-join_any or fork-join_none spawns may outlive + // the call (9.3.2). + if let Stmt::Fork { join, branches } = stmt + && *join != celox_design::ForkJoin::All + { + let mut used = false; + for branch in branches { + for stmt in branch { + stmt.walk(&mut |stmt| { + // Variables of the fork may be initialized from it. + if matches!(stmt, Stmt::Local { .. }) { + return; + } + used |= stmt_exprs(stmt).iter().any(|expr| expr_reads(expr, formal)) + || match stmt { + Stmt::Assign { lhs, .. } => lhs.name() == formal, + Stmt::AssignConcat { parts, .. } => { + parts.iter().any(|part| part.name() == formal) + } + _ => false, + }; + }); + } + } + if used { + *error = Some( + "a ref argument cannot be used in a fork-join_any or fork-join_none block \ + (IEEE 1800-2023 9.3.2)", + ); + } + } + }); +} + +#[cfg(test)] +mod tests { + use crate::{AnalyzerError, analyze_source}; + use std::path::Path; + + fn invalid(body: &str) -> String { + let source = format!("module Top; {body} endmodule"); + match analyze_source(&source, Path::new("ref_arguments.sv")) { + Err(error @ AnalyzerError::InvalidRefArgument { .. }) => error.to_string(), + other => panic!("{body}: expected an invalid ref argument, got {other:?}"), + } + } + + #[test] + fn reference_formals_need_automatic_subroutines() { + let error = invalid("int g; function void f(ref int x); x = 1; endfunction initial f(g);"); + assert!(error.contains("static lifetime"), "{error}"); + } + + #[test] + fn only_variables_are_passed_by_reference() { + for (declarations, actual) in [ + ("int g;", "g + 1"), + ("int g;", "3"), + ("logic [31:0] g;", "g[7:0]"), + ("parameter int P = 1;", "P"), + ] { + let error = invalid(&format!( + "{declarations} function automatic void f(ref int x); x = 1; endfunction \ + initial f({actual});" + )); + assert!(error.contains("13.5.2"), "{actual}: {error}"); + } + let error = invalid( + "wire [31:0] w; function automatic void f(ref logic [31:0] x); $display(x); \ + endfunction initial f(w);", + ); + assert!(error.contains("net"), "{error}"); + let error = invalid( + "wire [31:0] w[2]; function automatic void f(ref logic [31:0] x); x = 1; \ + endfunction initial f(w[0]);", + ); + assert!(error.contains("net"), "{error}"); + } + + #[test] + fn actuals_have_equivalent_types() { + for declaration in [ + "logic [31:0] g;", + "shortint g;", + "int unsigned g;", + "typedef enum {A, B} e_t; e_t g;", + "int g[$];", + ] { + let error = invalid(&format!( + "{declaration} function automatic void f(ref int x); x = 1; endfunction \ + initial f(g);" + )); + assert!(error.contains("6.22.2"), "{declaration}: {error}"); + } + let error = invalid( + "class A; endclass class B extends A; endclass \ + function automatic void f(ref A x); x = null; endfunction \ + initial begin automatic B b; f(b); end", + ); + assert!(error.contains("6.22.2"), "{error}"); + for declaration in ["bit signed [31:0] g;", "int g;"] { + analyze_source( + &format!( + "module Top; {declaration} function automatic void f(ref int x); x = 1; \ + endfunction initial f(g); endmodule" + ), + Path::new("ref_equivalent.sv"), + ) + .unwrap_or_else(|error| panic!("{declaration}: {error}")); + } + } + + #[test] + fn queues_of_different_bounds_are_not_bound_by_reference() { + let result = analyze_source( + "module Top; int q[$:1]; function automatic void f(ref int x[$]); \ + x.push_back(3); endfunction initial f(q); endmodule", + Path::new("ref_queue_bounds.sv"), + ); + assert!( + matches!(&result, Err(AnalyzerError::Unsupported(construct)) if construct.contains("different bounds")), + "{result:?}" + ); + } + + #[test] + fn const_ref_formals_are_read_only() { + for body in ["x = 1;", "x++;", "h(x);", "{x, y} = 64'd1;"] { + let error = invalid(&format!( + "int g, y; function automatic void h(ref int z); z = 2; endfunction \ + function automatic void f(const ref int x); {body} endfunction initial f(g);" + )); + assert!(error.contains("const ref"), "{body}: {error}"); + } + let error = invalid( + "int a[2]; function automatic void set(ref int x); x = 1; endfunction \ + function automatic void f(const ref int v[2]); set(v[0]); endfunction \ + initial f(a);", + ); + assert!(error.contains("const ref"), "{error}"); + let error = invalid( + "int a[2]; task automatic load(const ref int v[2]); $readmemh(\"data.hex\", v); \ + endtask initial load(a);", + ); + assert!(error.contains("const ref"), "{error}"); + let error = invalid( + "int q[$]; function automatic void f(const ref int x[$]); x.push_back(1); \ + endfunction initial f(q);", + ); + assert!(error.contains("const ref"), "{error}"); + // `const` is part of the direction the next formal inherits (13.3). + let error = invalid( + "int g, h; function automatic void f(const ref int a, b); b = 1; endfunction \ + initial f(g, h);", + ); + assert!(error.contains("`b`"), "{error}"); + } + + #[test] + fn reference_formals_follow_automatic_variable_rules() { + let error = invalid("int g; task automatic f(ref int x); x <= 1; endtask initial f(g);"); + assert!(error.contains("nonblocking"), "{error}"); + for join in ["join_none", "join_any"] { + let error = invalid(&format!( + "int g; task automatic f(ref int x); fork x = 1; {join} endtask initial f(g);" + )); + assert!(error.contains("9.3.2"), "{join}: {error}"); + } + analyze_source( + "module Top; int g; task automatic f(ref int x); \ + fork automatic int k = x; $display(k); join_none \ + fork x = 2; join endtask initial f(g); endmodule", + Path::new("ref_fork_initializer.sv"), + ) + .unwrap(); + } + + #[test] + fn functions_with_ref_arguments_are_called_procedurally() { + let error = invalid( + "int g, r; function automatic int f(ref int x); return x; endfunction \ + assign r = f(g);", + ); + assert!(error.contains("13.4.1"), "{error}"); + let error = invalid( + "int g; logic [15:0] a, b; function automatic int f(ref int x); return x; \ + endfunction assign {a, b} = f(g);", + ); + assert!(error.contains("13.4.1"), "{error}"); + analyze_source( + "module Top; int g, r; function automatic int f(const ref int x); return x; \ + endfunction assign r = f(g); endmodule", + Path::new("const_ref_continuous.sv"), + ) + .unwrap(); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/processes.rs b/crates/celox-sv-analyzer/src/ast/processes.rs index 8e3e6265a3d..199a93cd92a 100644 --- a/crates/celox-sv-analyzer/src/ast/processes.rs +++ b/crates/celox-sv-analyzer/src/ast/processes.rs @@ -5,10 +5,25 @@ use celox_sv_syntax::{Declarations, ExprId, ExprKind}; pub(super) const CLASS: &str = "$builtin::process"; +/// `enum state { FINISHED, RUNNING, WAITING, SUSPENDED, KILLED }` (9.7). +const STATES: [&str; 5] = ["FINISHED", "RUNNING", "WAITING", "SUSPENDED", "KILLED"]; + pub(super) fn state_type() -> Type { let mut ty = procedural::int_type(); ty.is_enum = true; - ty.enum_values = Some((0..5).collect()); + ty.enum_domain = Some(Arc::new(enums::EnumDomain { + members: STATES + .into_iter() + .zip(0..) + .map(|(name, value)| enums::EnumMember { + name: name.into(), + value, + }) + .collect(), + width: 32, + signed: true, + four_state: false, + })); ty } @@ -66,6 +81,45 @@ pub(super) fn qualified_type(path: &[celox_sv_syntax::TypeSegment]) -> Option, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Option> { + let id = expression_binding::ungroup(id, native); + let (callee, called) = match &native.expression(id).kind { + ExprKind::Call { expression, .. } => (*expression, true), + _ => (id, false), + }; + let ExprKind::Member { + expression: receiver, + separator, + name, + } = &native.expression(callee).kind + else { + return None; + }; + let member = instances::normalize_identifier(&name.spelling); + let state = match separator.as_str() { + "::" => { + !called + && STATES.contains(&member.as_str()) + && scope(tree, *receiver, native, dimensions) + } + "." => { + member == "status" + && expression_binding::object_native_class(tree, *receiver, native, dimensions) + .as_deref() + == Some(CLASS) + } + _ => false, + }; + state.then(|| state_type().enum_domain).flatten() +} + pub(super) fn value( tree: &AnalysisContext<'_>, root: ExprId, @@ -96,11 +150,7 @@ pub(super) fn value( return Ok(None); } let method = instances::normalize_identifier(&name.spelling); - if static_receiver - && let Some(code) = ["FINISHED", "RUNNING", "WAITING", "SUSPENDED", "KILLED"] - .iter() - .position(|&n| n == method) - { + if static_receiver && let Some(code) = STATES.iter().position(|&n| n == method) { if !args.is_empty() { return Err(unsupported("call of process state constant")); } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 9cfab268185..f58f4205990 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -229,7 +229,8 @@ fn bind_in_mode( if matches!(mode, BindingMode::Use) { validate_enum_initializers(id, native, tree, context, &ty)?; } - ty.enum_values = enum_values(id, native, tree, context, &ty); + ty.enum_domain = enum_values(id, native, tree, context, &ty); + ty.packed_enum = !native.data_type(id).packed_dimensions.is_empty(); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); } @@ -330,7 +331,8 @@ fn bind_in_mode( outer.extend(ty.packed_ranges); ty.packed_ranges = outer; ty.is_enum = true; - ty.enum_values = enum_values(id, native, tree, context, &ty); + ty.enum_domain = enum_values(id, native, tree, context, &ty); + ty.packed_enum = !native.data_type(id).packed_dimensions.is_empty(); values.push(ty); } Job::Aggregate { @@ -661,7 +663,7 @@ fn enum_values( tree: &AnalysisContext<'_>, context: &PackedDimensions, ty: &Type, -) -> Option> { +) -> Option> { let data = native.data_type(id); if !data.packed_dimensions.is_empty() { return None; @@ -676,6 +678,7 @@ fn enum_values( let mut env = context.const_env.clone(); let mut next = 0i128; let mut values = Vec::new(); + let mut members = Vec::new(); for item in items { if !item.dimensions.is_empty() { return None; @@ -710,9 +713,20 @@ fn enum_values( } values.push(value); let name = normalize_identifier(&item.name.spelling); + members.push(enums::EnumMember { + name: name.clone(), + value, + }); env.insert(name.clone(), value); dimensions::insert_parameter_type_markers(&mut env, &name, shape); next = value.checked_add(1)?; } - (!values.is_empty()).then_some(values) + (!members.is_empty()).then(|| { + Arc::new(enums::EnumDomain { + members, + width: shape.width, + signed: shape.signed, + four_state: !matches!(ty.kind(), TypeKind::Bit), + }) + }) } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs b/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs index 26786420e84..ff4fa982e29 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs @@ -24,12 +24,10 @@ pub(in crate::ast) fn subroutine_formals( .flat_map(|group| &group.ports), ) { if let Some(declared) = port.direction { - direction = match declared { - celox_sv_syntax::Direction::Input => ParamDirection::Input, - celox_sv_syntax::Direction::Output => ParamDirection::Output, - celox_sv_syntax::Direction::Inout => ParamDirection::Inout, - _ => return Err(unsupported("reference subroutine parameter")), - }; + if port.static_reference { + return Err(unsupported("ref static subroutine argument")); + } + direction = ParamDirection::declared(declared, port.constant); } let Some(name) = &port.name else { continue }; let data = tree.declarations().data_type(port.data_type); @@ -54,9 +52,15 @@ pub(in crate::ast) fn subroutine_formals( ty.kind = TypeKind::Logic; } previous_type = Some(ty.clone()); - let unpacked = constant_binding::bind_unpacked_ranges(&port.dimensions, tree, context)?; - ty = type_with_unpacked_ranges(ty, unpacked); - if ty.container.is_some() { + // A reference formal names the caller's container; passing one by + // value would need a copy of the container. + ty = if direction.is_reference() { + containers::with_dimensions(ty, &port.dimensions, tree, context)? + } else { + let unpacked = constant_binding::bind_unpacked_ranges(&port.dimensions, tree, context)?; + type_with_unpacked_ranges(ty, unpacked) + }; + if ty.container.is_some() && !direction.is_reference() { return Err(unsupported("dynamic container subroutine parameter")); } result.push(( diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 95e10b03d5f..85f0915df12 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -243,7 +243,8 @@ pub(super) fn enclose_aliased_packed_type( // array they form is unsigned, whatever its elements (IEEE 1800-2023 // 7.4.1); a type name takes no signing of its own. if !direct_ranges.is_empty() { - r#type.enum_values = None; + r#type.packed_enum |= r#type.is_enum; + r#type.enum_domain = None; r#type.signed_element_depth = if r#type.is_signed { Some(direct_ranges.len()) } else { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 40a3ddacbda..6e352d6afe1 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -829,24 +829,6 @@ fn validate_scope( return Err(unsupported("wildcard port connection")); } } - for index in spans.subroutines.within(&ranges) { - let function = &native.subroutines[index]; - if selected(function.tokens) - && function - .ports - .iter() - .flatten() - .chain( - function - .port_declarations - .iter() - .flat_map(|declaration| &declaration.ports), - ) - .any(|port| port.direction == Some(celox_sv_syntax::Direction::Ref)) - { - return Err(unsupported("ref function argument")); - } - } for id in spans.types.within(&ranges) { let data = native.data_type(id); if !selected(data.tokens) { diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 87dcbdb60d7..ae7b1992bd4 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -207,6 +207,14 @@ pub enum AnalyzerError { /// (IEEE 1800-2023 8.25). #[error("class `{class}` has no parameter `{name}` that a specialization may assign")] UnknownClassParameter { class: String, name: String }, + /// A `ref` or `const ref` formal bound to an actual, or used in a way, + /// that IEEE 1800-2023 13.5.2 forbids. + #[error("ref argument `{argument}` of `{subroutine}`: {detail}")] + InvalidRefArgument { + subroutine: String, + argument: String, + detail: String, + }, } impl miette::Diagnostic for AnalyzerError {} diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index cd641d7f9a0..9117e78ae3a 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -221,17 +221,40 @@ pub enum ParamDirection { Input, Output, Inout, + /// `ref`: the formal names the actual itself (IEEE 1800-2023 13.5.2). + Ref, + /// `const ref`: a reference the subroutine only reads. + ConstRef, } impl ParamDirection { - /// Whether the call copies the argument's value in. + /// The direction a formal declares with `direction`, `const` (only + /// meaningful with `ref`) and `static` (`ref static`). + pub fn declared(direction: celox_sv_syntax::Direction, constant: bool) -> Self { + match direction { + celox_sv_syntax::Direction::Input => ParamDirection::Input, + celox_sv_syntax::Direction::Output => ParamDirection::Output, + celox_sv_syntax::Direction::Inout => ParamDirection::Inout, + celox_sv_syntax::Direction::Ref if constant => ParamDirection::ConstRef, + celox_sv_syntax::Direction::Ref => ParamDirection::Ref, + } + } + + /// Whether the callee may read the actual: the call copies it in, or + /// the formal refers to it. pub fn is_read(self) -> bool { !matches!(self, ParamDirection::Output) } - /// Whether the call writes the actual argument back. + /// Whether the callee may change the actual: the call copies the formal + /// back, or the formal refers to it. pub fn is_written(self) -> bool { - !matches!(self, ParamDirection::Input) + !matches!(self, ParamDirection::Input | ParamDirection::ConstRef) + } + + /// Whether the formal refers to the actual instead of holding a copy. + pub fn is_reference(self) -> bool { + matches!(self, ParamDirection::Ref | ParamDirection::ConstRef) } } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 086ce99ab8c..78810f3ad73 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -620,6 +620,12 @@ impl Radix { } impl SystemTask { + /// Whether the task writes argument `position`, as `$readmemh` loads + /// its memory argument (IEEE 1800-2023 21.4). + pub fn writes_argument(self, position: usize) -> bool { + matches!(self, Self::Readmem(_)) && position == 1 + } + /// Tasks executed synchronously by the timed simulation host. pub fn is_host_request(self) -> bool { matches!( @@ -748,10 +754,11 @@ impl StringOp { } /// The width and signedness of the result; a string is a 32-bit handle. + /// A character is a `byte`, which is signed (6.16, 6.11). pub fn result_type(self) -> (usize, bool) { match self { Self::Compare | Self::ICompare | Self::Len | Self::Atoi(_) => (32, true), - Self::Getc => (8, false), + Self::Getc => (8, true), _ => (32, false), } } @@ -1068,6 +1075,15 @@ pub enum Callee { width: usize, signed: bool, }, + /// A table lookup with the arguments `selector, key, value, ..., + /// default`: the value of the first key the selector matches with case + /// equality, else the default, resized to `width` and `signed`. The + /// selector is evaluated once. Used for enumerated type methods + /// (IEEE 1800-2023 6.19.5). + Lookup { + width: usize, + signed: bool, + }, /// A user function or a DPI import, by its resolved name. Subroutine(String), System(SystemFunction), @@ -1083,14 +1099,22 @@ impl Callee { pub fn subroutine(&self) -> Option<&str> { match self { Self::Subroutine(name) => Some(name), - Self::System(_) | Self::String(_) | Self::Object(_) | Self::Checked { .. } => None, + Self::System(_) + | Self::String(_) + | Self::Object(_) + | Self::Checked { .. } + | Self::Lookup { .. } => None, } } /// The system function, if this is one. pub fn system(&self) -> Option { match self { - Self::Subroutine(_) | Self::String(_) | Self::Object(_) | Self::Checked { .. } => None, + Self::Subroutine(_) + | Self::String(_) + | Self::Object(_) + | Self::Checked { .. } + | Self::Lookup { .. } => None, Self::System(function) => Some(*function), } } @@ -1099,7 +1123,9 @@ impl Callee { /// lowered as an integral operation; see [`SystemFunction::result_type`]. pub fn result_type(&self) -> Option<(usize, bool)> { match self { - Self::Checked { width, signed } => Some((*width, *signed)), + Self::Checked { width, signed } | Self::Lookup { width, signed } => { + Some((*width, *signed)) + } Self::String(op) => Some(op.result_type()), Self::Object(op) => Some(op.result_type()), _ => self.system()?.result_type(), @@ -1109,7 +1135,7 @@ impl Callee { /// Rename a user subroutine with `rename`. pub fn map_subroutine(self, rename: impl FnOnce(String) -> String) -> Self { match self { - Self::Checked { .. } => self, + Self::Checked { .. } | Self::Lookup { .. } => self, Self::Subroutine(name) => Self::Subroutine(rename(name)), Self::System(function) => Self::System(function), Self::String(op) => Self::String(op), @@ -1121,7 +1147,8 @@ impl Callee { /// the analyzer must not run it twice: user subroutines may have side /// effects, as do the random number functions. pub fn is_effectful(&self) -> bool { - self.system().is_none_or(SystemFunction::is_effectful) + !matches!(self, Self::Lookup { .. }) + && self.system().is_none_or(SystemFunction::is_effectful) } } @@ -1129,6 +1156,7 @@ impl fmt::Display for Callee { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Checked { .. } => f.write_str("tagged union access"), + Self::Lookup { .. } => f.write_str("enumeration lookup"), Self::Subroutine(name) => f.write_str(name), Self::System(function) => f.write_str(function.name()), Self::String(op) => op.fmt(f), diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index dc900c8f812..4035abd9cde 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -239,6 +239,29 @@ pub(crate) fn eval_const_expr_in_env( constants, ) } + Callee::Lookup { width, signed } => { + let (selector, rest) = args.split_first()?; + let (default, pairs) = rest.split_last()?; + let selector = eval_const_expr_in_env(selector, constants)?; + let (pairs, []) = pairs.as_chunks::<2>() else { + return None; + }; + let mut value = default; + for [key, candidate] in pairs { + if eval_const_expr_in_env(key, constants)? == selector { + value = candidate; + break; + } + } + eval_const_expr_in_env( + &ConstExpr::Resize { + expr: Box::new(value.clone()), + width: *width, + signed: *signed, + }, + constants, + ) + } Callee::String(_) | Callee::Object(_) => None, }, ConstExpr::Unary { op, expr: operand } => { diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 323381f68bb..06ad9192ab3 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -548,7 +548,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_interface_array_connections` | compile | icarus | 3 | Icarus 13.0 rejects distributed unpacked actuals and multidimensional instances, and aborts on interface array ports. See the focused interface-array evidence above. | | `sv_icarus_interfaces` | compile | icarus | 16 | Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports ("sorry: modport task/function ports are not yet supported") and multidimensional interface instance arrays ("sorry: Multi-dimensional arrays of instances are not yet supported"). Verilator passes these cases. The implicit named interface cases have [focused pre-exclusion evidence](verification/sv/limitations/implicit-interface-ports-icarus.json). The mixed module-contract/local-interface case retains its [port-declaration diagnostics](verification/repros/sv_mixed_interface_connections_icarus.json). | | `sv_icarus_packed_inner_index_range` | execute | icarus | 1 | Icarus 13.0 flattens an out-of-range inner index of a multidimensional packed array into the neighbouring element: a read gives a known value instead of X, and a write lands in that element; IEEE 1800-2023 7.4.6 and 11.5.1 make the select out of range. Verilator cannot check four-state values, and it truncates out-of-range packed indices. | -| `sv_icarus_string_methods` | compile | icarus | 3 | Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa ("Method getc is not a string method"), and requires a constant replication count for a string ("A reference to a net or variable is not allowed in a constant expression"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases. | +| `sv_icarus_string_methods` | compile | icarus | 4 | Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa ("Method getc is not a string method"), and requires a constant replication count for a string ("A reference to a net or variable is not allowed in a constant expression"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases. | | `sv_icarus_unpacked_subroutine_ports` | compile | icarus | 2 | Icarus 13.0 reports that subroutine ports with unpacked dimensions are not yet supported. Verilator passes the valid case. | | `sv_icarus_classes` | compile | icarus | 5 | Icarus 13.0 does not support extern methods ("sorry: External methods are not yet supported") or string methods called on a class property ("Can't find task itoa in class Named") or comparisons of class handles ("SORRY: Compare class handles not implemented"), aborts on a failed assertion in dup_expr.cc while compiling objects_referring_to_objects, and crashes with a segmentation fault while compiling implicit_constructors_and_this. IEEE 1800-2023 8.4, 8.7, 8.8 and 8.24 define these constructs. Verilator passes all but the string-method case, see sv_verilator_class_property_string_methods. | | `sv_icarus_nested_class_members` | execute | icarus | 1 | Icarus 13.0 reads an empty string through a nested property path (kept.inner.text) after reporting "sorry: Nested member path not yet supported for class properties" for its assignment. IEEE 1800-2023 8.5 permits accessing a property of an object referred to by a property. Verilator passes the case. | @@ -621,6 +621,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_iff_event_controls` | compile | icarus | 15 | Icarus 13.0 rejects `iff` in an event control with "syntax error" and "Malformed event control expression." IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; [Standalone probe](verification/repros/sv_iff_event_controls_icarus.json); Verilator 5.052 runs the cases and gives the asserted counts. | | `sv_icarus_static_property_wait` | execute | icarus | 1 | Icarus 13.0 compiles a `wait` on a static class property in a class task but vvp cannot load the result ("unresolved vvp_net reference", "Program not runnable"); IEEE 1800-2023 8.9 and 9.4.3 make the property one variable that the wait watches. [Standalone probe](verification/repros/sv_static_property_wait_icarus.json); Verilator 5.052 and xezim 0.11.3 pass the case. | | `sv_verilator_iff_late_conditions` | execute | verilator | 4 | Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. [Standalone probes](verification/repros/sv_iff_late_conditions_verilator.json) print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls. | +| `sv_verilator_string_character_signedness` | execute | verilator | 1 | Verilator 5.052 reads a string character (`s[i]`, `s.getc(i)`) as unsigned, so code 255 converts to `int` 255. IEEE 1800-2023 6.16 makes a character a `byte`, which 6.11 makes signed (-1); xezim 0.11.3 agrees, Icarus 13.0 also reads 255. [Standalone probe](verification/repros/sv_string_character_signedness.json). | The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json) retains the failed Icarus runs and minimal sources. Cover comparisons enable @@ -1184,3 +1185,31 @@ reproduce it as both Top and Wrapped. The two exact failures remain executed evidence in the [Icarus](verification/sv/icarus/class.json) and [xezim](verification/sv/xezim/class.json) class reports. No assertions or exclusions are weakened. +### Reference arguments + +The 18 `references::*` cases check that `ref` and `const ref` formals are the +actual itself (IEEE 1800-2023 13.5.2): variables, queues, strings, class handles, +class and static properties (also passed on to `output` and `inout` arguments) and +fixed-size array elements, with selects past the element writing nothing, across +task suspensions and concurrent activations. Celox passes all of them on every backend. + +Verilator 5.052 passes 15. It rejects an `int` formal bound to a `bit signed [31:0]` +actual with "Ref argument requires matching types", although 6.22.2 makes the +types equivalent, and rejects two functions that also write a module variable with +`%Error-IMPURE` "External variable referenced by non-inlined function/task". +Icarus 13.0 compiles none: it reports "Reference ports not supported yet", a syntax +error for `const ref` or a `C::p` task argument, or "Overriding the default variable lifetime is not yet +supported" for the `automatic` locals. These are executed compile failures. + +The installed xezim 0.11.3 build gives copy-in/copy-out results in nine cases: a +write through the formal is not seen through another name of the actual before the +return, two formals of one actual do not alias, suspended tasks miss concurrent +writes, and an element's index is evaluated again. A formal bound to a subarray +element neither reads nor writes it in a tenth. They are recorded as +`sv_ref_copy_semantics` and `sv_ref_subarray_element` in +[the review](verification/xezim-review.json) and remain +executed mismatches in [the report](verification/sv/xezim/references.json). The +[adapter-free Top/Wrapped probe](verification/repros/ref_arguments.sv) and +[its observations](verification/repros/ref_arguments.json) reproduce the same +values without the suite adapters; the observations are from the installed build, +not a current-pin validation. diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 1a29b8aa592..e9d2ee6887c 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -31,6 +31,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/tagged_unions.vtest", text: include_str!("tagged_unions.vtest"), }, + Group { + file: "src/sv/cases/references.vtest", + text: include_str!("references.vtest"), + }, Group { file: "src/sv/cases/unions.vtest", text: include_str!("unions.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index f83879faaf9..b5b67130277 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -1510,3 +1510,24 @@ (tick clk) (assert_eq result wide) (modify (set update 1)) (tick clk) (assert_eq result 0)) + +(case static_locals_with_run_time_initializers_run_before_procedures + (source "static_initializers.sv" #" + module Top(output bit [7:0] first, output bit [7:0] looped); + int m = 1; + initial m = 5; + initial begin + static int k = m + 1; + static int j = k * 10; + first = 8'(j); + for (int i = 0; i < 3; i++) begin + static int once = k; + once++; + looped = 8'(once); + end + end + endmodule + "#) + (top Top) (run_until 0) + (assert_eq first 20) + (assert_eq looped 5)) diff --git a/crates/celox-test-suite/src/sv/cases/references.vtest b/crates/celox-test-suite/src/sv/cases/references.vtest new file mode 100644 index 00000000000..935e196ff22 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/references.vtest @@ -0,0 +1,407 @@ +(group references (category functions)) + +; IEEE 1800-2023 13.5.2: a ref or const ref formal is the actual itself, not a +; copy. Writes through it are seen at once, other names of the actual alias it, +; and a task keeps the reference while it is suspended. + +(case ref_writes_are_seen_before_the_return + (source "ref_writes_are_seen_before_the_return.sv" #"module Top(output int q, output int seen); + int g; + function automatic void bump(ref int x); + x = x + 1; + seen = g; + endfunction + initial begin + g = 10; + bump(g); + q = g; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 11) + (assert_eq seen 11)) + +(case ref_formals_of_one_actual_alias_each_other + (source "ref_formals_of_one_actual_alias_each_other.sv" #"module Top(output int q, output int b_seen); + int g; + function automatic void f(ref int a, ref int b); + a = 5; + b_seen = b; + b = a + 1; + endfunction + initial begin f(g, g); q = g; end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 6) + (assert_eq b_seen 5)) + +(case ref_task_keeps_the_reference_while_suspended + (source "ref_task_keeps_the_reference_while_suspended.sv" #" +module Top(output int early, output int late, output int q); + task automatic watch(ref int x); + #1 early = x; + #4 late = x; + x = x + 100; + endtask + initial begin + automatic int local_value = 3; + fork + watch(local_value); + begin #2 local_value = 7; end + join + q = local_value; + end +endmodule"#) + (top Top) + (run_until 10) + (assert_eq early 3) + (assert_eq late 7) + (assert_eq q 107)) + +(case ref_fills_caller_queues + (source "ref_fills_caller_queues.sv" #"module Top(output int count, output int total, output int names); + function automatic void fill(ref int values[$], ref string paths[$], input int n); + for (int i = 1; i <= n; i++) begin + values.push_back(i); + paths.push_back("p"); + end + endfunction + function automatic void forward(ref int values[$], ref string paths[$]); + fill(values, paths, 2); + endfunction + initial begin + automatic int q[$]; + automatic string s[$]; + fill(q, s, 3); + forward(q, s); + count = q.size(); + total = 0; + foreach (q[i]) total += q[i]; + names = s.size(); + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq count 5) + (assert_eq total 9) + (assert_eq names 5)) + +(case ref_replaces_a_class_handle + (source "ref_replaces_a_class_handle.sv" #"module Top(output int q, output int same); + class Item; + int value; + function new(int v); value = v; endfunction + endclass + function automatic void make(ref Item item, input int v); + item = new(v); + endfunction + initial begin + automatic Item h = new(1); + automatic Item old = h; + make(h, 42); + q = h.value; + same = h == old; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 42) + (assert_eq same 0)) + +(case const_ref_reads_the_current_value + (source "const_ref_reads_the_current_value.sv" #"module Top(output int q, output int sum); + int g; + int a[4]; + function automatic int observe(const ref int x); + g = 9; + return x; + endfunction + function automatic int total(const ref int values[4]); + int s = 0; + foreach (values[i]) s += values[i]; + return s; + endfunction + initial begin + g = 1; + a = '{1, 2, 3, 4}; + q = observe(g); + sum = total(a); + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 9) + (assert_eq sum 10)) + +(case const_ref_in_a_continuous_assignment + (source "const_ref_in_a_continuous_assignment.sv" #" +module Top(output int early, output int late); + int g = 3; + int r; + function automatic int next(const ref int x); + return x + 1; + endfunction + assign r = next(g); + initial begin + #1 early = r; + g = 7; + #1 late = r; + end +endmodule"#) + (top Top) + (run_until 5) + (assert_eq early 4) + (assert_eq late 8)) + +(case ref_default_and_named_arguments + (source "ref_default_and_named_arguments.sv" #"module Top(output int q, output int h_out); + int g = 1; + int h = 10; + function automatic void inc(ref int x = g); + x++; + endfunction + function automatic void move(ref int a, ref int b); + a += b; + b = 0; + endfunction + initial begin + inc(); + move(.b(g), .a(h)); + q = g; + h_out = h; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 0) + (assert_eq h_out 12)) + +(case ref_actual_of_an_equivalent_type + (source "ref_actual_of_an_equivalent_type.sv" #"module Top(output int q); + bit signed [31:0] word; + function automatic void set(ref int x); + x = -5; + endfunction + initial begin set(word); q = word == -5 && word < 0; end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 1)) + +(case ref_class_property_names_the_object_of_the_call + (source "ref_class_property_names_the_object_of_the_call.sv" #"module Top(output int first, output int second, output int names); + class Node; + int count; + string labels[$]; + function new(int c); count = c; endfunction + endclass + function automatic void retarget(ref int x, ref Node node); + node = new(77); + x = 9; + endfunction + function automatic void label(ref string out[$]); + out.push_back("a"); + out.push_back("b"); + endfunction + initial begin + automatic Node node = new(1); + automatic Node old = node; + retarget(node.count, node); + label(old.labels); + first = old.count; + second = node.count; + names = old.labels.size(); + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq first 9) + (assert_eq second 77) + (assert_eq names 2)) + +(case ref_property_of_this + (source "ref_property_of_this.sv" #"module Top(output int q); + function automatic void bump(ref int x); + x = x + 1; + endfunction + class Counter; + int value; + function void twice(); + bump(value); + bump(this.value); + endfunction + endclass + initial begin + automatic Counter c = new; + c.twice(); + q = c.value; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 2)) + +(case ref_task_keeps_a_property_while_suspended + (source "ref_task_keeps_a_property_while_suspended.sv" #"module Top(output int q); + class Node; int count; endclass + task automatic later(ref int x); + #2 x = x + 10; + endtask + initial begin + automatic Node k = new; + k.count = 1; + fork later(k.count); join_none + #1 k.count = 100; + #3 q = k.count; + end +endmodule"#) + (top Top) + (run_until 10) + (assert_eq q 110)) + +(case ref_array_element_index_is_fixed_at_the_call + (source "ref_array_element_index_is_fixed_at_the_call.sv" #"module Top(output int e1, output int e3, output int row_sum, output int swapped); + int arr[4]; + int m[2][3]; + int i; + function automatic void bump(ref int x); + x = x + 10; + i = 3; + x = x + 1; + endfunction + function automatic void row(ref int r[3]); + foreach (r[k]) r[k] = k + 7; + endfunction + function automatic void swap(ref int a, ref int b); + int t = a; + a = b; + b = t; + endfunction + initial begin + arr = '{1, 2, 3, 4}; + i = 1; + bump(arr[i]); + e1 = arr[1]; + e3 = arr[3]; + row(m[1]); + row_sum = m[1][0] + m[1][1] + m[1][2] + m[0][0]; + swap(arr[0], arr[3]); + swapped = arr[0] * 10 + arr[3]; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq e1 13) + (assert_eq e3 4) + (assert_eq row_sum 24) + (assert_eq swapped 41)) + +(case ref_elements_of_concurrent_task_activations + (source "ref_elements_of_concurrent_task_activations.sv" #"module Top(output int q); + int arr[4]; + task automatic add_later(ref int x, input int d); + #(d) x = x + d; + endtask + initial begin + arr = '{10, 20, 30, 40}; + for (int k = 0; k < 3; k++) begin + automatic int j = k; + fork add_later(arr[j], j + 1); join_none + end + #5 q = arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3]; + end +endmodule"#) + (top Top) + (run_until 10) + (assert_eq q 13570)) + +(case ref_static_class_properties + (source "ref_static_class_properties.sv" #"module Top(output int count, output int inst); + function automatic void bump(ref int x); + x++; + endfunction + class Counter; + static int total; + int own; + function void go(); + bump(total); + bump(Counter::total); + bump(own); + endfunction + endclass + initial begin + automatic Counter c = new; + c.go(); + bump(Counter::total); + count = Counter::total; + inst = c.own; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq count 3) + (assert_eq inst 1)) + +(case ref_property_forwarded_to_output_and_inout + (source "ref_property_forwarded_to_output_and_inout.sv" #"module Top(output int q); + class Item; int value; endclass + function automatic void set(output int y); + y = 21; + endfunction + function automatic void twice(inout int y); + y = y * 2; + endfunction + function automatic void forward(ref int x); + set(x); + twice(x); + endfunction + initial begin + automatic Item item = new; + forward(item.value); + q = item.value; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq q 42)) + +(case ref_element_select_past_the_element + (source "ref_element_select_past_the_element.sv" #"module Top(output int kept, output int past, output int next_row); + int m[2][3]; + function automatic int touch(ref int r[3]); + r[3] = 99; + r[1] = 5; + return r[3]; + endfunction + initial begin + past = touch(m[0]); + kept = m[0][1]; + next_row = m[1][0]; + end +endmodule"#) + (top Top) + (run_until 1) + (assert_eq kept 5) + (assert_eq past 0) + (assert_eq next_row 0)) + +(case ref_element_after_an_input_in_forked_activations + (source "ref_element_after_an_input_in_forked_activations.sv" #"module Top(output int q); + int arr[4]; + task automatic add_later(input int d, ref int x); + #(d) x = x + d; + endtask + initial begin + arr = '{10, 20, 30, 40}; + for (int k = 0; k < 3; k++) begin + automatic int j = k; + fork add_later(j + 1, arr[j]); join_none + end + #5 q = arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3]; + end +endmodule"#) + (top Top) + (run_until 10) + (assert_eq q 13570)) diff --git a/crates/celox-test-suite/src/sv/cases/string.vtest b/crates/celox-test-suite/src/sv/cases/string.vtest index b784c73f0de..58c606be196 100644 --- a/crates/celox-test-suite/src/sv/cases/string.vtest +++ b/crates/celox-test-suite/src/sv/cases/string.vtest @@ -171,3 +171,22 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq same 1) (expect_output "[a longer name] [ab] [a longer name] 13\n")) + +; 6.16, 6.16.3: a character of a string is a `byte`, which is signed: a +; character code above 127 reads as a negative value. +(case characters_are_signed_bytes + (source "string_bytes.sv" #" +module Top(output bit done); + string s; + int n, m; + initial begin + s = {string'(8'hff), "A"}; + n = s[0]; + m = s.getc(0); + $display("%0d %0d %0d %0d %0d", n, m, s[0], s.getc(1), s[0] < 0); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "-1 -1 -1 65 1\n")) diff --git a/crates/celox-test-suite/src/sv/cases/types.vtest b/crates/celox-test-suite/src/sv/cases/types.vtest index abdd5e37810..4f509043de1 100644 --- a/crates/celox-test-suite/src/sv/cases/types.vtest +++ b/crates/celox-test-suite/src/sv/cases/types.vtest @@ -460,3 +460,68 @@ (top Top) (eval) (assert_eq y 0) (assert_eq array_values 0)) + +(case enum_methods_iterate_members + (source "enum_methods.sv" #" + module Top(output bit done); + typedef enum {red, green, blue, yellow} Colors; + Colors c, first, last; + initial begin + c = c.first; + forever begin + $display("%s : %0d", c.name, c); + if (c == c.last) break; + c = c.next; + end + first = c.first(); + last = c.last(); + $display("num=%0d first=%s last=%s", c.num(), first.name(), last.name()); + done = 1; + end + endmodule + "#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "red : 0\ngreen : 1\nblue : 2\nyellow : 3\nnum=4 first=red last=yellow\n")) + +(case enum_methods_wrap_and_count + (source "enum_methods.sv" #" + module Top(output bit done); + typedef enum bit [2:0] {A = 3'd1, B = 3'd4, C = 3'd6} E; + E e; + initial begin + e = B; + $display("%0d %0d %0d %0d %0d", e.next(), e.next(2), e.prev(), e.prev(4), e.next(3)); + e = E'(3'd5); + $display("[%s] %0d %0d", e.name(), e.next(), e.prev()); + done = 1; + end + endmodule + "#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "6 1 1 1 4\n[] 0 0\n")) + +(case enum_methods_in_combinational_and_sequential_logic + (source "enum_methods.sv" #" + module Top(input bit clk, input bit [1:0] sel, + output bit [1:0] following, output bit [1:0] preceding, + output bit [1:0] state); + typedef enum bit [1:0] {IDLE, RUN, DONE} S; + S current, register; + always_comb current = S'(sel); + always_comb following = current.next(2); + always_comb preceding = current.prev(); + always_ff @(posedge clk) register <= register.next(); + assign state = register; + endmodule + "#) + (top Top) + (set sel 1) (set clk 0) (eval) + (assert_eq following 0) + (assert_eq preceding 0) + (set sel 2) (eval) + (assert_eq following 1) + (assert_eq preceding 1) + (tick clk) (tick clk) + (assert_eq state 2) + (tick clk) + (assert_eq state 0)) diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index 636b8f0565e..2a1f937dece 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -471,6 +471,55 @@ fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { "compile", "Unsupported: tristate in top-level IO", ), + ("verilator", "references::ref_actual_of_an_equivalent_type") => ( + "compile_error", + "compile", + "Ref argument requires matching types", + ), + ( + "verilator", + "references::ref_array_element_index_is_fixed_at_the_call" + | "references::ref_class_property_names_the_object_of_the_call", + ) => ( + "compile_error", + "compile", + "External variable referenced by non-inlined function/task", + ), + ( + "icarus", + "references::const_ref_in_a_continuous_assignment" + | "references::const_ref_reads_the_current_value" + | "references::ref_static_class_properties", + ) => ("compile_error", "compile", "syntax error"), + ( + "icarus", + "references::ref_actual_of_an_equivalent_type" + | "references::ref_array_element_index_is_fixed_at_the_call" + | "references::ref_default_and_named_arguments" + | "references::ref_element_select_past_the_element" + | "references::ref_formals_of_one_actual_alias_each_other" + | "references::ref_writes_are_seen_before_the_return", + ) => ( + "compile_error", + "compile", + "Reference ports not supported yet", + ), + ( + "icarus", + "references::ref_class_property_names_the_object_of_the_call" + | "references::ref_element_after_an_input_in_forked_activations" + | "references::ref_elements_of_concurrent_task_activations" + | "references::ref_fills_caller_queues" + | "references::ref_property_forwarded_to_output_and_inout" + | "references::ref_property_of_this" + | "references::ref_replaces_a_class_handle" + | "references::ref_task_keeps_a_property_while_suspended" + | "references::ref_task_keeps_the_reference_while_suspended", + ) => ( + "compile_error", + "compile", + "Overriding the default variable lifetime is not yet supported", + ), _ => panic!("unreviewed failure: {tool} {name}: {status}"), }; assert_eq!(status, expected_status, "{name}"); diff --git a/crates/celox-test-suite/verification/repros/ref_arguments.json b/crates/celox-test-suite/verification/repros/ref_arguments.json new file mode 100644 index 00000000000..5e2d51f5221 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/ref_arguments.json @@ -0,0 +1,96 @@ +{ + "standard": "IEEE 1800-2023 13.5.2, 13.3, 13.5.3", + "xezim_build": "/nix/store/1869dyxd44fz4kh02dmng33gyxdx5m61-xezim-0.11.3/bin/xezim", + "xezim_limitation": "Available installed 0.11.3 build, git unknown. No claim of current-pin validation.", + "probes": [ + { + "case": "references::*", + "source": "ref_arguments.sv", + "expected_output": "seen=11\nb_seen=5 g=6\nobserve=9\ndefault g=2\narr1=13 arr3=4\nrow=5 read=5\nearly=3 late=7 local=107\nproperty=110", + "observations": [ + { + "top": "Top", + "verilator_compile": { + "command": [ + "/nix/store/i5hjqqy2qk6jac8mnnaxnlh8yfi49wjh-verilator-5.052/bin/verilator", + "--binary", + "--timing", + "-Wno-fatal", + "--top-module", + "Top", + "--Mdir", + "/work/ref-probes/Top/obj", + "/crates/celox-test-suite/verification/repros/ref_arguments.sv" + ], + "exit_code": 1, + "output": "%Error-IMPURE: /crates/celox-test-suite/verification/repros/ref_arguments.sv:11:26: Unsupported: External variable referenced by non-inlined function/task: 'elem'\n : ... note: In instance 'Top'\n 11 | function automatic void elem(ref int x); x = x + 10; i = 3; x = x + 1; endfunction\n | ^~~~\n /crates/celox-test-suite/verification/repros/ref_arguments.sv:11:55: ... Location of the external reference: 'i'\n 11 | function automatic void elem(ref int x); x = x + 10; i = 3; x = x + 1; endfunction\n | ^\n ... For error description see https://verilator.org/warn/IMPURE?v=5.052\n%Error: Exiting due to 1 error(s)\n" + }, + "icarus_compile": { + "command": [ + "/nix/store/l2wn6zv7pwybn4vi7q2xgw8snzla1azh-iverilog-13.0/bin/iverilog", + "-g2012", + "-s", + "Top", + "-o", + "/work/ref-probes/Top/probe.vvp", + "/crates/celox-test-suite/verification/repros/ref_arguments.sv" + ], + "exit_code": 4, + "output": "/crates/celox-test-suite/verification/repros/ref_arguments.sv:9: syntax error\n/crates/celox-test-suite/verification/repros/ref_arguments.sv:20: error: Syntax error in task/function port declaration.\n/crates/celox-test-suite/verification/repros/ref_arguments.sv:41: syntax error\nI give up.\n" + }, + "xezim_run": { + "command": [ + "/nix/store/1869dyxd44fz4kh02dmng33gyxdx5m61-xezim-0.11.3/bin/xezim", + "-s", + "Top", + "/crates/celox-test-suite/verification/repros/ref_arguments.sv" + ], + "exit_code": 0, + "output": "=== xezim 0.11.3 ===\ngit unknown (unknown)\nseen=10\nb_seen=0 g=6\nobserve=1\ndefault g=1\narr1=2 arr3=13\nrow=0 read=0\nearly=3 late=3 local=103\nproperty=11\nSimulation finished at time 9 ($finish called)\n" + } + }, + { + "top": "Wrapped", + "verilator_compile": { + "command": [ + "/nix/store/i5hjqqy2qk6jac8mnnaxnlh8yfi49wjh-verilator-5.052/bin/verilator", + "--binary", + "--timing", + "-Wno-fatal", + "--top-module", + "Wrapped", + "--Mdir", + "/work/ref-probes/Wrapped/obj", + "/crates/celox-test-suite/verification/repros/ref_arguments.sv" + ], + "exit_code": 1, + "output": "%Error-IMPURE: /crates/celox-test-suite/verification/repros/ref_arguments.sv:11:26: Unsupported: External variable referenced by non-inlined function/task: 'elem'\n : ... note: In instance 'Wrapped.dut'\n 11 | function automatic void elem(ref int x); x = x + 10; i = 3; x = x + 1; endfunction\n | ^~~~\n /crates/celox-test-suite/verification/repros/ref_arguments.sv:11:55: ... Location of the external reference: 'i'\n 11 | function automatic void elem(ref int x); x = x + 10; i = 3; x = x + 1; endfunction\n | ^\n ... For error description see https://verilator.org/warn/IMPURE?v=5.052\n%Error: Exiting due to 1 error(s)\n" + }, + "icarus_compile": { + "command": [ + "/nix/store/l2wn6zv7pwybn4vi7q2xgw8snzla1azh-iverilog-13.0/bin/iverilog", + "-g2012", + "-s", + "Wrapped", + "-o", + "/work/ref-probes/Wrapped/probe.vvp", + "/crates/celox-test-suite/verification/repros/ref_arguments.sv" + ], + "exit_code": 4, + "output": "/crates/celox-test-suite/verification/repros/ref_arguments.sv:9: syntax error\n/crates/celox-test-suite/verification/repros/ref_arguments.sv:20: error: Syntax error in task/function port declaration.\n/crates/celox-test-suite/verification/repros/ref_arguments.sv:41: syntax error\nI give up.\n" + }, + "xezim_run": { + "command": [ + "/nix/store/1869dyxd44fz4kh02dmng33gyxdx5m61-xezim-0.11.3/bin/xezim", + "-s", + "Wrapped", + "/crates/celox-test-suite/verification/repros/ref_arguments.sv" + ], + "exit_code": 0, + "output": "=== xezim 0.11.3 ===\ngit unknown (unknown)\nseen=10\nb_seen=0 g=6\nobserve=1\ndefault g=1\narr1=2 arr3=13\nrow=0 read=0\nearly=3 late=3 local=103\nproperty=11\nSimulation finished at time 9 ($finish called)\n" + } + } + ] + } + ] +} \ No newline at end of file diff --git a/crates/celox-test-suite/verification/repros/ref_arguments.sv b/crates/celox-test-suite/verification/repros/ref_arguments.sv new file mode 100644 index 00000000000..3dd4a0bd7f2 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/ref_arguments.sv @@ -0,0 +1,43 @@ +module Top; + class Node; int count; endclass + int g, seen, b_seen, early, late, local_q, h; + int arr[4]; + int m[2][3]; + int i, row_read; + function automatic void bump(ref int x); x = x + 1; seen = g; endfunction + function automatic void both(ref int a, ref int b); a = 5; b_seen = b; b = a + 1; endfunction + function automatic int observe(const ref int x); g = 9; return x; endfunction + function automatic void inc(ref int x = g); x++; endfunction + function automatic void elem(ref int x); x = x + 10; i = 3; x = x + 1; endfunction + function automatic int row(ref int r[3]); r[1] = 5; return r[1]; endfunction + task automatic watch(ref int x); #1 early = x; #4 late = x; x = x + 100; endtask + task automatic later(ref int x); #2 x = x + 10; endtask + initial begin + automatic int local_value = 3; + automatic Node k = new; + automatic int o; + g = 10; bump(g); + $display("seen=%0d", seen); + g = 0; both(g, g); + $display("b_seen=%0d g=%0d", b_seen, g); + g = 1; o = observe(g); + $display("observe=%0d", o); + g = 1; inc(); + $display("default g=%0d", g); + arr = '{1, 2, 3, 4}; i = 1; elem(arr[i]); + $display("arr1=%0d arr3=%0d", arr[1], arr[3]); + row_read = row(m[1]); + $display("row=%0d read=%0d", m[1][1], row_read); + fork + watch(local_value); + begin #2 local_value = 7; end + join + $display("early=%0d late=%0d local=%0d", early, late, local_value); + k.count = 1; + fork later(k.count); join_none + #1 k.count = 100; + #3 $display("property=%0d", k.count); + $finish; + end +endmodule +module Wrapped; Top dut(); endmodule diff --git a/crates/celox-test-suite/verification/repros/sv_string_character_signedness.json b/crates/celox-test-suite/verification/repros/sv_string_character_signedness.json new file mode 100644 index 00000000000..dcaf8d30e89 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_string_character_signedness.json @@ -0,0 +1,29 @@ +{ + "case": "string::characters_are_signed_bytes", + "source": "src/sv/cases/string.vtest", + "method": "Standalone source run with verilator --binary, iverilog -g2012 -s Top / vvp -n, and xezim -s Top.", + "standard": "IEEE 1800-2023 6.16: a single character of a string variable is of type byte; 6.11: byte is signed; 6.16.3: getc returns byte.", + "reduced_source": "module Top;\n string s;\n int n;\n initial begin\n s = {string'(8'hff), \"A\"};\n n = s[0];\n $display(\"%0d %0d %0d\", n, s[0], s[0] < 0);\n end\nendmodule\n", + "observations": [ + { + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "stdout": "255 255 0\n" + }, + { + "tool": "icarus", + "version": "Icarus Verilog 13.0", + "stdout": "255 255 0\n", + "note": "The shared case also calls getc, which Icarus does not implement (sv_icarus_string_methods)." + }, + { + "tool": "xezim", + "version": "xezim 0.11.3", + "stdout": "-1 -1 1\n" + }, + { + "tool": "celox", + "stdout": "-1 -1 1\n" + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index d27f7bde6ad..d59bfb262de 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -17,6 +17,7 @@ "icarus/procedural.json", "icarus/program.json", "icarus/random_plusargs.json", + "icarus/references.json", "icarus/review_regressions.json", "icarus/scan.json", "icarus/string.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/references.json b/crates/celox-test-suite/verification/sv/icarus/references.json new file mode 100644 index 00000000000..394943b9701 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/references.json @@ -0,0 +1,202 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "Icarus build exit status: 5; see /build.log\n/source_0.sv:5: syntax error\n/testbench.sv:17: error: Syntax error in task/function port declaration.\n/testbench.sv:17: error: ';' is an invalid port declaration separator.\n/testbench.sv:24: syntax error\n/source_0.sv:5: error: Syntax error defining function.\n", + "expectation": "Simulation", + "name": "references::const_ref_in_a_continuous_assignment", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 5; see /build.log\n/source_0.sv:4: syntax error\n/testbench.sv:17: error: Syntax error in task/function port declaration.\n/testbench.sv:17: error: ';' is an invalid port declaration separator.\n/testbench.sv:24: syntax error\n/source_0.sv:4: error: Syntax error defining function.\n", + "expectation": "Simulation", + "name": "references::const_ref_reads_the_current_value", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Reference ports not supported yet.\n/source_0.sv:3: error: Function celox_suite_tb.dut.set port x is not an input port.\n/source_0.sv:3: : Function arguments must be input ports.\n2 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "references::ref_actual_of_an_equivalent_type", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 11; see /build.log\n/source_0.sv:5: sorry: Reference ports not supported yet.\n/source_0.sv:5: error: Function celox_suite_tb.dut.bump port x is not an input port.\n/source_0.sv:5: : Function arguments must be input ports.\n/source_0.sv:10: sorry: Reference ports not supported yet.\n/source_0.sv:10: error: Function celox_suite_tb.dut.row port r is not an input port.\n/source_0.sv:10: : Function arguments must be input ports.\n/source_0.sv:10: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:13: sorry: Reference ports not supported yet.\n/source_0.sv:13: sorry: Reference ports not supported yet.\n/source_0.sv:13: error: Function celox_suite_tb.dut.swap port a is not an input port.\n/source_0.sv:13: : Function arguments must be input ports.\n/source_0.sv:13: error: Function celox_suite_tb.dut.swap port b is not an input port.\n/source_0.sv:13: : Function arguments must be input ports.\n/source_0.sv:24: error: Array m['sd1] needs 2 indices, but got only 1.\n/source_0.sv:24: sorry: Assignment to an array slice is not yet supported.\n/source_0.sv:24: error: I give up on task port 1 expression: m['sd1]\n11 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "references::ref_array_element_index_is_fixed_at_the_call", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:16: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:17: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_class_property_names_the_object_of_the_call", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 8; see /build.log\n/source_0.sv:4: sorry: Reference ports not supported yet.\n/source_0.sv:4: sorry: Default arguments for subroutine output or inout ports are not yet supported.\n/source_0.sv:4: error: Function celox_suite_tb.dut.inc port x is not an input port.\n/source_0.sv:4: : Function arguments must be input ports.\n/source_0.sv:7: sorry: Reference ports not supported yet.\n/source_0.sv:7: sorry: Reference ports not supported yet.\n/source_0.sv:7: error: Function celox_suite_tb.dut.move port a is not an input port.\n/source_0.sv:7: : Function arguments must be input ports.\n/source_0.sv:7: error: Function celox_suite_tb.dut.move port b is not an input port.\n/source_0.sv:7: : Function arguments must be input ports.\n/source_0.sv:12: error: Missing argument 1 of call to task.\n8 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "references::ref_default_and_named_arguments", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:9: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_element_after_an_input_in_forked_activations", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:3: sorry: Reference ports not supported yet.\n/source_0.sv:3: error: Function celox_suite_tb.dut.touch port r is not an input port.\n/source_0.sv:3: : Function arguments must be input ports.\n/source_0.sv:3: sorry: Subroutine ports with unpacked dimensions are not yet supported.\n/source_0.sv:4: warning: ignoring out of bounds l-value array access r[3].\n/source_0.sv:6: warning: returning 'bx for out of bounds array access r[3].\n/source_0.sv:9: error: Array m['sd0] needs 2 indices, but got only 1.\n4 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "references::ref_element_select_past_the_element", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:9: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_elements_of_concurrent_task_activations", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:12: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:13: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_fills_caller_queues", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:3: sorry: Reference ports not supported yet.\n/source_0.sv:3: sorry: Reference ports not supported yet.\n/source_0.sv:3: error: Function celox_suite_tb.dut.f port a is not an input port.\n/source_0.sv:3: : Function arguments must be input ports.\n/source_0.sv:3: error: Function celox_suite_tb.dut.f port b is not an input port.\n/source_0.sv:3: : Function arguments must be input ports.\n4 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "references::ref_formals_of_one_actual_alias_each_other", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:14: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_property_forwarded_to_output_and_inout", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:13: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_property_of_this", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:10: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:11: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_replaces_a_class_handle", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:10: syntax error\n/source_0.sv:10: error: Syntax error in task arguments.\n/source_0.sv:15: sorry: Overriding the default variable lifetime is not yet supported.\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: Syntax error in task arguments.\n/source_0.sv:18: syntax error\n/source_0.sv:18: error: Malformed statement\n", + "expectation": "Simulation", + "name": "references::ref_static_class_properties", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:7: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_task_keeps_a_property_while_suspended", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:9: sorry: Overriding the default variable lifetime is not yet supported.\n", + "expectation": "Simulation", + "name": "references::ref_task_keeps_the_reference_while_suspended", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:3: sorry: Reference ports not supported yet.\n/source_0.sv:3: error: Function celox_suite_tb.dut.bump port x is not an input port.\n/source_0.sv:3: : Function arguments must be input ports.\n2 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "references::ref_writes_are_seen_before_the_return", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/string.json b/crates/celox-test-suite/verification/sv/icarus/string.json index 6960ae9cd9e..46c2fea0b72 100644 --- a/crates/celox-test-suite/verification/sv/icarus/string.json +++ b/crates/celox-test-suite/verification/sv/icarus/string.json @@ -45,6 +45,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_string_methods", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "upstream": [] + }, + "name": "string::characters_are_signed_bytes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 1ed492b94c2..6f0af362d25 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1805,7 +1805,8 @@ "icarus": [ "string::character_access", "string::concatenation_and_replication", - "string::methods" + "string::methods", + "string::characters_are_signed_bytes" ] } }, @@ -2863,5 +2864,22 @@ "concurrent_assertions::disable_iff_after_nba" ] } + }, + { + "id": "sv_verilator_string_character_signedness", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 reads a string character, s[i] and s.getc(i), as an unsigned 8-bit value: a character code of 255 converts to int 255 and compares greater than 0. IEEE 1800-2023 6.16 makes a character a byte and 6.11 makes byte signed, so the code reads as -1; xezim 0.11.3 agrees with the expected values and Icarus 13.0 also reads it as 255.", + "upstream": [], + "evidence": [ + "verification/repros/sv_string_character_signedness.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "string::characters_are_signed_bytes" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index b4cd4f10e7f..c684981b25b 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -18,6 +18,7 @@ "verilator/procedural.json", "verilator/program.json", "verilator/random_plusargs.json", + "verilator/references.json", "verilator/review_regressions.json", "verilator/scan.json", "verilator/string.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/references.json b/crates/celox-test-suite/verification/sv/verilator/references.json new file mode 100644 index 00000000000..d501e932aae --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/references.json @@ -0,0 +1,202 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::const_ref_in_a_continuous_assignment", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::const_ref_reads_the_current_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Verilator build exit status: 1; see /build.log\n%Error: /source_0.sv:6:20: Ref argument requires matching types; port 'x' requires 'int' but connection is 'bit[31:0]'.\n : ... note: In instance 'celox_suite_tb.dut'\n 6 | initial begin set(word); q = word == -5 && word < 0; end\n | ^~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Warning-WIDTHEXPAND: /source_0.sv:6:29: Operator ASSIGN expects 32 bits on the Assign RHS, but Assign RHS's LOGAND generates 1 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 6 | initial begin set(word); q = word == -5 && word < 0; end\n | ^\n ... For warning description see https://verilator.org/warn/WIDTHEXPAND?v=5.052\n ... Use \"/* verilator lint_off WIDTHEXPAND */\" and lint_on around source to disable this message.\n%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "references::ref_actual_of_an_equivalent_type", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-IMPURE: /source_0.sv:5:26: Unsupported: External variable referenced by non-inlined function/task: 'celox_suite_tb.dut.bump'\n 5 | function automatic void bump(ref int x);\n | ^~~~\n /source_0.sv:7:3: ... Location of the external reference: 'celox_suite_tb.dut.i'\n 7 | i = 3;\n | ^\n ... For error description see https://verilator.org/warn/IMPURE?v=5.052\n%Warning-ZERODLY: /testbench.sv:103: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 103 | 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%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "references::ref_array_element_index_is_fixed_at_the_call", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Verilator build exit status: 1; see /build.log\n%Error-IMPURE: /source_0.sv:7:26: Unsupported: External variable referenced by non-inlined function/task: 'retarget'\n : ... note: In instance 'celox_suite_tb.dut'\n 7 | function automatic void retarget(ref int x, ref Node node);\n | ^~~~~~~~\n /source_0.sv:5:24: ... Location of the external reference: 'count'\n 5 | function new(int c); count = c; endfunction\n | ^~~~~\n ... For error description see https://verilator.org/warn/IMPURE?v=5.052\n%Warning-ZERODLY: /testbench.sv:103: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 103 | 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%Error: Exiting due to 1 error(s)\n", + "expectation": "Simulation", + "name": "references::ref_class_property_names_the_object_of_the_call", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_default_and_named_arguments", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_element_after_an_input_in_forked_activations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_element_select_past_the_element", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_elements_of_concurrent_task_activations", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_fills_caller_queues", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_formals_of_one_actual_alias_each_other", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_property_forwarded_to_output_and_inout", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_property_of_this", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_replaces_a_class_handle", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_static_class_properties", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_task_keeps_a_property_while_suspended", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_task_keeps_the_reference_while_suspended", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_writes_are_seen_before_the_return", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/verilator/string.json b/crates/celox-test-suite/verification/sv/verilator/string.json index 2d9d77227a6..4d47a231867 100644 --- a/crates/celox-test-suite/verification/sv/verilator/string.json +++ b/crates/celox-test-suite/verification/sv/verilator/string.json @@ -33,6 +33,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Verilator 5.052 reads a string character, s[i] and s.getc(i), as an unsigned 8-bit value: a character code of 255 converts to int 255 and compares greater than 0. IEEE 1800-2023 6.16 makes a character a byte and 6.11 makes byte signed, so the code reads as -1; xezim 0.11.3 agrees with the expected values and Icarus 13.0 also reads it as 255.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_string_character_signedness.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_string_character_signedness", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 reads a string character, s[i] and s.getc(i), as an unsigned 8-bit value: a character code of 255 converts to int 255 and compares greater than 0. IEEE 1800-2023 6.16 makes a character a byte and 6.11 makes byte signed, so the code reads as -1; xezim 0.11.3 agrees with the expected values and Icarus 13.0 also reads it as 255.", + "upstream": [] + }, + "name": "string::characters_are_signed_bytes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/sv/xezim.json b/crates/celox-test-suite/verification/sv/xezim.json index c0699b02e69..a5aa0a73791 100644 --- a/crates/celox-test-suite/verification/sv/xezim.json +++ b/crates/celox-test-suite/verification/sv/xezim.json @@ -26,6 +26,7 @@ "xezim/real_extensions.json", "xezim/real_math.json", "xezim/realtime.json", + "xezim/references.json", "xezim/review_regressions.json", "xezim/scan.json", "xezim/string.json", diff --git a/crates/celox-test-suite/verification/sv/xezim/references.json b/crates/celox-test-suite/verification/sv/xezim/references.json new file mode 100644 index 00000000000..fdff173173c --- /dev/null +++ b/crates/celox-test-suite/verification/sv/xezim/references.json @@ -0,0 +1,202 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::const_ref_in_a_continuous_assignment", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::const_ref_reads_the_current_value at 135:2: assert_eq q: expected 0x9, got 0x1", + "expectation": "Simulation", + "name": "references::const_ref_reads_the_current_value", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_actual_of_an_equivalent_type", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_array_element_index_is_fixed_at_the_call at 296:2: assert_eq e1: expected 0xd, got 0x2", + "expectation": "Simulation", + "name": "references::ref_array_element_index_is_fixed_at_the_call", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_class_property_names_the_object_of_the_call", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_default_and_named_arguments at 179:2: assert_eq h_out: expected 0xc, got 0xb", + "expectation": "Simulation", + "name": "references::ref_default_and_named_arguments", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_element_after_an_input_in_forked_activations at 407:2: assert_eq q: expected 0x3502, got 0x47a4", + "expectation": "Simulation", + "name": "references::ref_element_after_an_input_in_forked_activations", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_element_select_past_the_element at 386:2: assert_eq kept: expected 0x5, got 0x0", + "expectation": "Simulation", + "name": "references::ref_element_select_past_the_element", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_elements_of_concurrent_task_activations at 318:2: assert_eq q: expected 0x3502, got 0x47a4", + "expectation": "Simulation", + "name": "references::ref_elements_of_concurrent_task_activations", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_fills_caller_queues", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_formals_of_one_actual_alias_each_other at 38:2: assert_eq b_seen: expected 0x5, got 0x0", + "expectation": "Simulation", + "name": "references::ref_formals_of_one_actual_alias_each_other", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_property_forwarded_to_output_and_inout", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_property_of_this", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_replaces_a_class_handle", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "references::ref_static_class_properties", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_task_keeps_a_property_while_suspended at 262:2: assert_eq q: expected 0x6e, got 0xb", + "expectation": "Simulation", + "name": "references::ref_task_keeps_a_property_while_suspended", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_task_keeps_the_reference_while_suspended at 60:2: assert_eq late: expected 0x7, got 0x3", + "expectation": "Simulation", + "name": "references::ref_task_keeps_the_reference_while_suspended", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "references::ref_writes_are_seen_before_the_return at 23:2: assert_eq seen: expected 0xb, got 0xa", + "expectation": "Simulation", + "name": "references::ref_writes_are_seen_before_the_return", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/xezim/string.json b/crates/celox-test-suite/verification/sv/xezim/string.json index eeb3afd19ae..91c6fb0bd74 100644 --- a/crates/celox-test-suite/verification/sv/xezim/string.json +++ b/crates/celox-test-suite/verification/sv/xezim/string.json @@ -33,6 +33,17 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::characters_are_signed_bytes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "", diff --git a/crates/celox-test-suite/verification/xezim-review.json b/crates/celox-test-suite/verification/xezim-review.json index c5398a258dc..fb459cb7395 100644 --- a/crates/celox-test-suite/verification/xezim-review.json +++ b/crates/celox-test-suite/verification/xezim-review.json @@ -730,6 +730,14 @@ "sv_process-X9": { "title": "A compound event on shared automatic operands wakes at time zero without a value change", "standard": "IEEE 1800-2023 9.4.2, 6.21" + }, + "sv_ref_copy_semantics": { + "title": "ref and const ref formals behave as copies of the actual", + "standard": "IEEE 1800-2023 13.5.2" + }, + "sv_ref_subarray_element": { + "title": "A ref formal bound to a subarray element neither reads nor writes that element", + "standard": "IEEE 1800-2023 13.5.2, 7.4.6" } }, "cases": [ @@ -4371,6 +4379,86 @@ "classification": "xezim_bug", "bug": "sv_process-X6", "note": "Producer exits at2 after suspending a delay waiter. Consumer remains live until10, resumes its FINISHED handle at3, and checks it after the original deadline at6. IEEE24.7 ends only Producer and9.7 makes resume a no-op on a finished process. xezim instead ends the whole simulation at2, before Consumer or the shared checks at9. Adapter-free Top/Wrapped sv_process_resume_after_program_exit.sv/.json reproduces final at2 instead of late=0/checks=3/state=0 and final at9. Assertions/exclusions are unchanged." + }, + { + "suite": "sv", + "name": "references::const_ref_reads_the_current_value", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "A function writes the global that its const ref formal names, then returns the formal; xezim returns the value copied at the call (1) instead of 9. The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_array_element_index_is_fixed_at_the_call", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "Writes through a ref formal bound to arr[i] land in arr[3] after the callee changes i, as if copied out with a re-evaluated index; 13.5.2 refers to the element of the call and gives arr[1]=13, arr[3]=4. The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_default_and_named_arguments", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "inc() with a ref formal defaulting to g does not change g (copy semantics), so move(.b(g), .a(h)) adds 1 instead of 2 to h. The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_elements_of_concurrent_task_activations", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "Concurrent task activations holding ref formals bound to different array elements do not update the elements as references; 13.5.2 gives 11, 22, 33, 40. The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_formals_of_one_actual_alias_each_other", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "Two ref formals bound to one variable do not alias: b reads 0 after a = 5. The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_task_keeps_a_property_while_suspended", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "A suspended task's ref formal bound to a class property neither sees the caller's later write (100) nor writes the property until it returns, giving 11 instead of 110. The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_task_keeps_the_reference_while_suspended", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "A suspended task's ref formal does not see a concurrent write to the caller's automatic actual (late=3 instead of 7). The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_writes_are_seen_before_the_return", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "A write through a ref formal is not visible through the global it names before the function returns (seen=10 instead of 11). The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json prints the same values from the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_element_select_past_the_element", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_subarray_element", + "note": "With `ref int r[3]` bound to m[0], the in-range write r[1] = 5 does not reach m[0][1] (kept=0 instead of 5); the out-of-range r[3] correctly reads 0 and leaves m[1][0] alone. The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json shows that even an in-range write and read through a formal bound to m[1] give row=0 read=0 instead of 5 and 5 in the installed xezim 0.11.3 build; this is not current-pin validation." + }, + { + "suite": "sv", + "name": "references::ref_element_after_an_input_in_forked_activations", + "status": "mismatch", + "classification": "xezim_bug", + "bug": "sv_ref_copy_semantics", + "note": "The same concurrent task activations as references::ref_elements_of_concurrent_task_activations with the input argument first: ref formals bound to different array elements do not update them as references (q=18340 instead of 13570, which 13.5.2 gives with 11, 22, 33, 40). The adapter-free Top/Wrapped probe in verification/repros/ref_arguments.json shows the copy semantics in the installed xezim 0.11.3 build; this is not current-pin validation." } ] } diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 58899198424..ada92725bbd 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -354,8 +354,9 @@ enum HandleKind { /// Opaque allocation referenced by the C `vpiHandle` pointer type. pub struct VpiHandleObject { kind: HandleKind, - name: CString, - full_name: CString, + // Unnamed temporary handles share the empty C string without allocating it. + name: Option, + full_name: Option, value_string: Vec, value_vector: Vec, } @@ -528,6 +529,16 @@ struct PendingWrites { settle: bool, } +impl PendingWrites { + // An open batch follows the current deposits. Freeze its map only when a + // member transitions again or before replay, rather than after every write. + fn close_edge_batch(&mut self) { + if let Some(index) = self.open_edge_batch.take() { + self.edge_batches[index].deposits = self.deposits.clone(); + } + } +} + struct PendingEdgeBatch { active_signals: Vec, transition_signals: Vec, @@ -597,7 +608,7 @@ fn record_pending_write( }); if open_contains_signal && event_transition { - pending.open_edge_batch = None; + pending.close_edge_batch(); } pending @@ -611,17 +622,14 @@ fn record_pending_write( if active { pending.edge_batches[index].active_signals.push(identity); } - pending.edge_batches[index].deposits = pending.deposits.clone(); } else { pending.edge_batches.push(PendingEdgeBatch { active_signals: active.then_some(identity).into_iter().collect(), transition_signals: vec![identity], - deposits: pending.deposits.clone(), + deposits: HashMap::default(), }); pending.open_edge_batch = Some(pending.edge_batches.len() - 1); } - } else if let Some(index) = pending.open_edge_batch { - pending.edge_batches[index].deposits = pending.deposits.clone(); } pending.settle = true; } @@ -868,8 +876,8 @@ fn new_object_handle(object: ObjectRef) -> VpiHandle { .unwrap_or_default(); Box::into_raw(Box::new(VpiHandleObject { kind: HandleKind::Object(object), - name: c_string(&name), - full_name: c_string(&full_name), + name: Some(c_string(&name)), + full_name: Some(c_string(&full_name)), value_string: Vec::new(), value_vector: Vec::new(), })) @@ -881,8 +889,8 @@ fn new_iterator_handle(objects: Vec) -> VpiHandle { } Box::into_raw(Box::new(VpiHandleObject { kind: HandleKind::Iterator { objects, next: 0 }, - name: c_string(""), - full_name: c_string(""), + name: None, + full_name: None, value_string: Vec::new(), value_vector: Vec::new(), })) @@ -891,8 +899,8 @@ fn new_iterator_handle(objects: Vec) -> VpiHandle { fn new_constant_handle(value: i32) -> VpiHandle { Box::into_raw(Box::new(VpiHandleObject { kind: HandleKind::Constant(value), - name: c_string(""), - full_name: c_string(""), + name: None, + full_name: None, value_string: Vec::new(), value_vector: Vec::new(), })) @@ -901,8 +909,8 @@ fn new_constant_handle(value: i32) -> VpiHandle { fn new_callback_handle(id: u64) -> VpiHandle { Box::into_raw(Box::new(VpiHandleObject { kind: HandleKind::Callback(id), - name: c_string(""), - full_name: c_string(""), + name: None, + full_name: None, value_string: Vec::new(), value_vector: Vec::new(), })) @@ -1272,8 +1280,13 @@ pub unsafe extern "C" fn vpi_get_str(property: i32, reference: VpiHandle) -> *mu return ptr::null_mut(); }; match property { - VPI_NAME => handle.name.as_ptr().cast_mut(), - VPI_FULL_NAME => handle.full_name.as_ptr().cast_mut(), + VPI_NAME => handle.name.as_deref().unwrap_or(c"").as_ptr().cast_mut(), + VPI_FULL_NAME => handle + .full_name + .as_deref() + .unwrap_or(c"") + .as_ptr() + .cast_mut(), VPI_DEF_NAME => { let HandleKind::Object(ObjectRef::Scope(id)) = handle.kind else { return ptr::null_mut(); @@ -2015,7 +2028,10 @@ fn flush_inertial_writes_for_host(host: &VpiHost) -> bool { } fn flush_pending_writes_for_host(host: &VpiHost) -> bool { - let pending = borrow_cell_mut(&host.pending_writes, std::mem::take); + let pending = borrow_cell_mut(&host.pending_writes, |pending| { + pending.close_edge_batch(); + std::mem::take(pending) + }); if !pending.settle { return true; } diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index ec7d936b646..64b2056b795 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -1031,6 +1031,8 @@ fn vpi_discovers_hierarchy_and_reads_and_writes_values() { assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, top)), c"Top"); let modules = vpi_iterate(VPI_MODULE, top); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, modules)), c""); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, modules)), c""); let child = vpi_scan(modules); assert!(!child.is_null()); assert_eq!( @@ -1940,6 +1942,11 @@ fn callback_registration_owns_copied_time_and_value_records() { let a = vpi_handle_by_name(c"Top.a".as_ptr(), ptr::null_mut()); let value_change = register_stack_value_callback(a); assert!(!value_change.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, value_change)), c""); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, value_change)), + c"" + ); register_stack_timer(a); // Reuse the caller stack after both registration functions returned. @@ -2467,10 +2474,14 @@ unsafe extern "C" fn drive_two_edges_with_distinct_data(data: *mut VpiCbData) -> let d = EDGE_DATA_HANDLE.load(Ordering::SeqCst) as VpiHandle; unsafe { put_int(clk, 1); + put_int(d, 7); put_int(d, 1); put_int(clk, 0); + put_int(d, 9); put_int(d, 2); put_int(clk, 1); + put_int(d, 8); + put_int(d, 2); } 0 } diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 669313f8044..60855e24280 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -88,6 +88,10 @@ sv_backends! { @case "procedural::static_function_scratch_arrays_are_filled_before_reads"; } + fn static_locals_with_run_time_initializers_run_before_procedures(sim) { + @case "procedural::static_locals_with_run_time_initializers_run_before_procedures"; + } + fn static_function_result_filled_by_constant_loops(sim) { @case "procedural::static_function_result_filled_by_constant_loops"; } diff --git a/crates/celox/tests/frontends/systemverilog/references.rs b/crates/celox/tests/frontends/systemverilog/references.rs new file mode 100644 index 00000000000..d7a97b99a53 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/references.rs @@ -0,0 +1,56 @@ +sv_backends! { + fn ref_writes_are_seen_before_the_return(sim) { + @case "references::ref_writes_are_seen_before_the_return"; + } + fn ref_formals_of_one_actual_alias_each_other(sim) { + @case "references::ref_formals_of_one_actual_alias_each_other"; + } + fn ref_task_keeps_the_reference_while_suspended(sim) { + @case "references::ref_task_keeps_the_reference_while_suspended"; + } + fn ref_fills_caller_queues(sim) { + @case "references::ref_fills_caller_queues"; + } + fn ref_replaces_a_class_handle(sim) { + @case "references::ref_replaces_a_class_handle"; + } + fn const_ref_reads_the_current_value(sim) { + @case "references::const_ref_reads_the_current_value"; + } + fn const_ref_in_a_continuous_assignment(sim) { + @case "references::const_ref_in_a_continuous_assignment"; + } + fn ref_default_and_named_arguments(sim) { + @case "references::ref_default_and_named_arguments"; + } + fn ref_actual_of_an_equivalent_type(sim) { + @case "references::ref_actual_of_an_equivalent_type"; + } + fn ref_class_property_names_the_object_of_the_call(sim) { + @case "references::ref_class_property_names_the_object_of_the_call"; + } + fn ref_property_of_this(sim) { + @case "references::ref_property_of_this"; + } + fn ref_task_keeps_a_property_while_suspended(sim) { + @case "references::ref_task_keeps_a_property_while_suspended"; + } + fn ref_array_element_index_is_fixed_at_the_call(sim) { + @case "references::ref_array_element_index_is_fixed_at_the_call"; + } + fn ref_elements_of_concurrent_task_activations(sim) { + @case "references::ref_elements_of_concurrent_task_activations"; + } + fn ref_static_class_properties(sim) { + @case "references::ref_static_class_properties"; + } + fn ref_property_forwarded_to_output_and_inout(sim) { + @case "references::ref_property_forwarded_to_output_and_inout"; + } + fn ref_element_select_past_the_element(sim) { + @case "references::ref_element_select_past_the_element"; + } + fn ref_element_after_an_input_in_forked_activations(sim) { + @case "references::ref_element_after_an_input_in_forked_activations"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/string.rs b/crates/celox/tests/frontends/systemverilog/string.rs index a1a23e71533..c55637fc1a1 100644 --- a/crates/celox/tests/frontends/systemverilog/string.rs +++ b/crates/celox/tests/frontends/systemverilog/string.rs @@ -6,6 +6,7 @@ sv_backends! { fn string_concatenation_and_replication(sim) { @case "string::concatenation_and_replication"; } fn string_character_access(sim) { @case "string::character_access"; } fn string_methods(sim) { @case "string::methods"; } + fn string_characters_are_signed_bytes(sim) { @case "string::characters_are_signed_bytes"; } fn string_casts_from_integral_values(sim) { @case "string::casts_from_integral_values"; } fn strings_across_clock_edges(sim) { @case "string::strings_across_clock_edges"; } } diff --git a/crates/celox/tests/frontends/systemverilog/types.rs b/crates/celox/tests/frontends/systemverilog/types.rs index c13f8dbd4dc..54233f3da0f 100644 --- a/crates/celox/tests/frontends/systemverilog/types.rs +++ b/crates/celox/tests/frontends/systemverilog/types.rs @@ -1,3 +1,5 @@ +use super::*; + sv_backends! { fn inherited_parameter_aliases_materialize_replication_masks(sim) { @case "types::inherited_parameter_aliases_materialize_replication_masks"; @@ -73,3 +75,198 @@ sv_backends! { @case "types::undriven_internal_nets_convert_to_two_state_zero"; } } + +sv_backends! { + fn enum_methods_iterate_members(sim) { + @case "types::enum_methods_iterate_members"; + } + + fn enum_methods_wrap_and_count(sim) { + @case "types::enum_methods_wrap_and_count"; + } + + fn enum_methods_in_combinational_and_sequential_logic(sim) { + @case "types::enum_methods_in_combinational_and_sequential_logic"; + } +} + +// Receivers, counts and contexts that the external simulators of the shared +// suite do not accept: Verilator rejects non-constant counts and methods of +// casts, constants and call results; Icarus rejects methods of call results +// and of class properties, and methods in continuous assignments; xezim calls a method +// of an array element as one of a class handle and returns 0 instead of the +// 4-state base's 'x for a value that is no member (IEEE 1800-2023 6.19.5.3, +// 6.19.5.4, Table 6-7). +sv_backends! { + fn enum_methods_of_any_enum_expression(sim) { + @setup { + let source = r#" +package p; + typedef enum {PA, PB, PC} P; + typedef enum {SHARED, OTHER} Q; + P states[2] = '{PB, PC}; + localparam P START = PB; +endpackage +package r; + typedef enum {SHARED, MIDDLE, LAST} R; +endpackage +module Top(output bit ok, output logic [1:0] unknown_next, output logic [1:0] unknown_prev, + output bit unnamed, output bit [1:0] continuous, output bit [1:0] gap_next, + output bit [3:0] chained); + typedef enum bit [3:0] {W0, W1, W2, W3, W4, W5, W6, W7, W8, W9, W10, W11, W12, W13, W14, W15} W; + W wide; + // Each nested lookup lowers its selector once, not once per member. + assign chained = wide.next().next().next().next().next().next().next().next(); + typedef enum logic [1:0] {IDLE, RUN, DONE} S; + typedef enum bit [1:0] {K0, K1, K2} K; + typedef enum bit [2:0] {A = 3'd1, B = 3'd4, C = 3'd6} E; + S unknown; + S queue[$]; + S states[3]; + E e; + K current, gap; + bit [2:0] steps; + logic signed [2:0] signed_count; + typedef enum logic [1:0] {LA, LB, LC} L; + L le; + // Parameters of an enumerated type. + localparam S INITIAL = RUN; + localparam E LAST = C; + logic [1:0] unknown_count; + int unsigned n; + int calls; + class Machine; + static S initial_state = DONE; + K state; + function K current(); + return state; + endfunction + function string describe(); + return state.name(); + endfunction + endclass + function automatic S advance(); + calls++; + return RUN; + endfunction + assign continuous = current.next(steps); + assign gap_next = gap.next(2); + initial begin + Machine m; + process running; + ok = 1; + e = B; + ok &= e.next(2).name() == "A" && e.next.next.name == "A" && e.prev.name == "A"; + ok &= S'(0).name() == "IDLE" && E'(3'd6).prev().name() == "B"; + ok &= DONE.prev().name() == "RUN" && RUN.num() == 3 && C.next() == A; + states[1] = DONE; + ok &= states[1].name() == "DONE" && states[1].next.name == "IDLE"; + ok &= Machine::initial_state.name() == "DONE"; + queue.push_back(RUN); + ok &= queue[0].prev().name() == "IDLE"; + ok &= advance().next(2).name() == "IDLE" && calls == 1; + // Results that do not depend on the receiver still evaluate it once. + ok &= advance().first() == IDLE && advance().last() == DONE && advance().num() == 3; + ok &= calls == 4; + ok &= p::PA.next().name() == "PB" && p::PC.prev(2).name() == "PA" && p::PB.num() == 3; + // Each package's enumeration, though both declare SHARED = 0. + ok &= p::states[0].name() == "PB" && p::states[1].next() == p::PA; + ok &= p::SHARED.num() == 2 && r::SHARED.num() == 3 && r::SHARED.next().name() == "MIDDLE"; + queue = '{RUN, DONE}; + ok &= queue.pop_front().name() == "RUN" && queue.pop_back().next() == IDLE; + ok &= DONE.name().len() == 4 && DONE.name().tolower() == "done"; + ok &= RUN.name.toupper() == "RUN" && RUN.next.name.tolower() == "done"; + m = new; + m.state = K1; + ok &= m.current().next().name() == "K2" && m.state.next() == K2; + ok &= m.state.name() == "K1" && m.describe() == "K1"; + n = 5; + ok &= e.next(n) == A && e.prev(n) == C; + n = 32'hffff_ffff; + ok &= e.next(n) == B && e.prev(n) == B; + // A signed count converts to `int unsigned` with sign extension, at + // run time as for a constant: -1 is a multiple of 3 and -2 is 2 more. + signed_count = -1; + ok &= e.next(signed_count) == B && e.next(3'sb111) == B; + signed_count = -2; + ok &= e.prev(signed_count) == C && e.prev(3'sb110) == C; + // `int unsigned` is 2-state: an unknown count converts to 0. + le = LB; + unknown_count = 'x; + ok &= le.next(unknown_count) === LB && le.prev(unknown_count) === LB; + unknown_count = 2'bz1; + ok &= le.next(unknown_count) === LC; + ok &= INITIAL.next().name() == "DONE" && INITIAL.name() == "RUN"; + ok &= LAST.next() == A && LAST.num() == 3 && p::START.next() == p::PC; + // The status of a process and the constants of its `state` type (9.7). + running = process::self(); + ok &= running.status().name() == "RUNNING" && running.status.next() == process::WAITING; + ok &= process::KILLED.next().name() == "FINISHED" && std::process::RUNNING.num() == 5; + e = E'(3'd5); + ok &= e.prev(n) == 0 && e.next(n) == 0; + unknown_next = unknown.next(); + unknown_prev = unknown.prev(2); + unnamed = unknown.name() == ""; + current = K1; + wide = W3; + gap = K'(3); + steps = 4; + end +endmodule +"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("enum_methods.sv"))], "Top") + .four_state(true); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + for name in ["unknown_next", "unknown_prev"] { + let signal = sim.signal(name); + assert_eq!( + sim.get_four_state(signal), + (BigUint::from(3u8), BigUint::from(3u8)), + "{name}" + ); + } + let unnamed = sim.signal("unnamed"); + assert_eq!(sim.get(unnamed), BigUint::from(1u8)); + let continuous = sim.signal("continuous"); + assert_eq!(sim.get(continuous), BigUint::from(2u8)); + let chained = sim.signal("chained"); + assert_eq!(sim.get(chained), BigUint::from(11u8)); + let gap_next = sim.signal("gap_next"); + assert_eq!(sim.get(gap_next), BigUint::from(0u8)); + } +} + +/// Methods of an element of a packed array of enums are not supported yet; +/// they are rejected, not given the members of another type. +#[test] +fn enum_methods_of_packed_array_elements_are_rejected() { + for (declaration, call) in [ + ( + "typedef enum bit [1:0] {A, B, C} E; E [1:0] states;", + "states[0].next()", + ), + ( + "typedef enum bit [1:0] {A, B, C} E; E [1:0] states;", + "states[1].name() == \"B\"", + ), + ("enum bit [1:0] {X, Y} [1:0] states;", "states[0].first()"), + ] { + let source = + format!("module Top(output bit [1:0] y); {declaration} initial y = {call}; endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("packed_enum_methods.sv"))], + "Top", + ) + .build() + .err() + .unwrap_or_else(|| panic!("{source} must be rejected")) + .to_string(); + assert!( + error.contains("method of an element of a packed array of enums"), + "{error}" + ); + } +} diff --git a/crates/celox/tests/sv_lifetimes.rs b/crates/celox/tests/sv_lifetimes.rs index 7457e738a54..ab80e5e38bb 100644 --- a/crates/celox/tests/sv_lifetimes.rs +++ b/crates/celox/tests/sv_lifetimes.rs @@ -311,6 +311,111 @@ fn static_initializers_run_before_initial_blocks() { ); } +/// A static initializer may be any run-time expression; it runs once, +/// before any procedure starts (IEEE 1800-2023 6.8, 6.21). +#[test] +fn run_time_static_initializers_run_once_before_any_procedure() { + // The initializers read the module variable before the other `initial` + // procedure writes it, and in declaration order. Without the `static` + // keyword that 6.21 requires, an `initial` procedure's locals still + // follow this rule. + assert_eq!( + settled( + "module Top(output logic [31:0] y); + typedef enum {a, b, c} e; + int m = 1; + initial m = 5; + initial begin + e v = b; + string s = v.name(); + int k = m + 1; + static int j = k * 10 + v; + v = c; + y = {s.len() == 1 && s == \"b\", 7'(k), 8'(j), 8'(m)}; + end + endmodule" + ), + 0x82_1505 + ); + // Also when an edge process that makes a host request reorders the + // processes by creation. + assert_eq!( + settled( + "module Top(input logic clk, output logic [7:0] y); + int dummy; + int m = dummy + 4; + always @(posedge clk) $fflush; + initial begin static int k = m + 1; y = k; end + endmodule" + ), + 5 + ); + // A static in a loop is initialized once, not on each iteration. + assert_eq!( + settled( + "module Top(output logic [7:0] y); + int m = 1; + initial for (int i = 0; i < 3; i++) begin + static int once = m; + once++; + y = once; + end + endmodule" + ), + 4 + ); + // An explicitly static local of an `always` procedure as well. + assert_eq!( + ticks( + "module Top(input logic clk, output logic [7:0] y); + int m = 4; + always_ff @(posedge clk) begin static int c = m + 1; c++; y <= c; end + endmodule", + 2 + ), + [6, 7] + ); + // The statics of a function it calls are initialized before it. + assert_eq!( + settled( + "module Top(output logic [7:0] y); + int m = 1; + function int f(input int a); + static int c = 7; + c++; + return c + a; + endfunction + initial begin static int k = f(m); y = k + f(0); end + endmodule" + ), + 18 + ); +} + +/// An initializer that reads an automatic variable, or a keyword-less one +/// of a procedure that repeats, could only run on each entry. +#[test] +fn run_time_static_initializers_that_could_repeat_remain_unsupported() { + for source in [ + "module Top(output logic [7:0] y); + initial begin automatic int x = 3; int t = x + 1; y = t; end + endmodule", + "module Top(output logic [7:0] y); + initial begin automatic int x = 3; static int t = x + 1; y = t; end + endmodule", + "module Top(input logic clk, output logic [7:0] y); + int m = 4; + always_ff @(posedge clk) begin int c = m + 1; c++; y <= c; end + endmodule", + ] { + let detail = error(source); + assert!( + detail.contains("initializer that is not constant"), + "{detail}" + ); + } +} + #[test] fn concatenated_targets_select_with_the_entry_value() { assert_eq!( diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index fefb98b050e..c2dee963cd6 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -251,6 +251,9 @@ mod unions; #[path = "frontends/systemverilog/tagged_unions.rs"] mod tagged_unions; +#[path = "frontends/systemverilog/references.rs"] +mod references; + #[path = "frontends/systemverilog/containers.rs"] mod containers; diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 46cb4c3a12c..b4b120ffe6a 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -27,7 +27,7 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs, hard and soft packed untagged unions, enums (with implicit values), `typedef`, unpacked arrays used as memories, signed and unsigned | +| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs, hard and soft packed untagged unions, enums (with implicit values) and their methods `first`, `last`, `next`, `prev`, `num` and `name` on any enum-typed expression except an element of a packed array of enums ([#2417](https://github.com/celox-sim/celox/issues/2417)), `typedef`, unpacked arrays used as memories, signed and unsigned | | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | @@ -45,7 +45,7 @@ synthesis and is tested at the design level. | Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | | Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if`, `$readmemh` / `$readmemb`, and loops whose trip count is known before they run (`repeat`, and `for`, `while` or `do`-`while` loops that step one variable by a constant up to a fixed bound), defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | | Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate and deferred immediate assertions | -| Functions | `function` and `task` with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | +| Functions | `function` and `task` with `input`, `output`, `inout`, `ref` and `const ref` arguments (see [reference arguments](#reference-arguments)), `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | ### Timing controls {#timing-controls} @@ -331,7 +331,7 @@ Celox reports an `Unsupported` error naming the construct instead of ignoring it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). -- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, specializations of a parameterized class outside the package or compilation unit that declares it, properties that are `real`, arrays or wider than 64 bits, and randomization or constraints over 4-state properties. Timed tasks with static local declarations, recursive calls and `ref` arguments remain unsupported. +- Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, enumeration constants declared in a class, enumeration, struct and union types and named four-state or string constants as class parameter values, specializations of a parameterized class outside the package or compilation unit that declares it, properties that are `real`, arrays or wider than 64 bits, and randomization or constraints over 4-state properties. Timed tasks with static local declarations and recursive calls remain unsupported. - Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `wait fork` / `disable fork`, temporal concurrent assertions beyond the Boolean subset below, `force` / `release`. @@ -433,7 +433,8 @@ same as for a 32-bit integer; operations that read or build text call into the runtime. Strings are collected between time slots and after each `tick`. As IEEE 1800-2023 6.16 requires, NUL bytes are removed when text becomes a string, and an integral value assigned or cast to a string contributes its -bytes from the most significant one. +bytes from the most significant one. A character read as `s[i]` or `s.getc(i)` is a `byte`, +which is signed (6.16, 6.11): a code above 127 reads as a negative value. Not yet supported: `$sformat` / `$sformatf`, `atoreal` / `realtoa`, string arguments of `$value$plusargs`, file I/O and DPI-C, and string values in VPI, @@ -713,6 +714,33 @@ Mixed `bit`/`logic` unions retain four-state storage, with X/Z converted to zero when reading or writing a two-state member. Tagged and unpacked unions remain unsupported. +### Reference arguments {#reference-arguments} + +A `ref` or `const ref` formal is the actual itself, not a copy (IEEE 1800-2023 +13.5.2). Writes through it are visible at once, other names of the actual +alias it, and a task keeps the reference while it is suspended. The actual can +be a variable, including a string, class handle, queue, dynamic or associative +array, or unpacked array; a property of a class object, whose handle is +evaluated at the call; or an element of a fixed-size unpacked array, whose +index is evaluated at the call. A `const` qualifier, like the direction, carries +over to the following formals (13.3). + +These are rejected as the standard requires: `ref` formals of subroutines with +static lifetime; actuals that are expressions, constants, part-selects, nets, +or of a type not equivalent to the formal's (6.22.2); writes to a `const ref` +formal; nonblocking assignments to a `ref` formal (6.21); a `ref` formal used +in a `fork ... join_any` or `join_none` block other than in the initializer of +a fork variable (9.3.2); and calls of a function with a `ref` argument in a +continuous assignment or an event expression (13.4.1; `const ref` is allowed). + +`ref static`, elements of dynamic arrays, queues and associative arrays (whose +references would have to outlive a resize, 13.5.2), elements of class +properties, members of unpacked structures, writes to part of a formal bound to +a class property, and selects of a formal bound to an array element at a +position only known at run time (positions of unrolled loops are known) are +unsupported and rejected. A formal bound to a class property can be passed on +to an `output` or `inout` argument; it is written back when that call returns. + ### Named subroutine arguments Named subroutine arguments bind by formal name. Input evaluation and output @@ -844,8 +872,22 @@ stateful function require `Simulation` or a native testbench to execute the initialization process. Constant function calls use fresh values and do not affect runtime storage (13.4.3). -Task locals that keep their values and nonconstant static initializers remain -unsupported; declare those locals `automatic`. Package function state is a +A static local of a process may have a run-time initializer. It runs once, +in declaration order, before any procedure starts (IEEE 1800-2023 6.8), and +may read module variables and other static locals but no automatic variable. +IEEE 1800-2023 6.21 states that "an explicit static keyword shall be required +when an initialization value is specified as part of a static variable's +declaration". Celox also accepts the declaration without the keyword, as +existing sources often omit it (for example `string s = v.name();` in an +`initial` block): with a constant initializer in any procedure, and with a +run-time initializer in a procedure that runs once, such as `initial`. In an +`always` procedure a run-time initializer without the keyword is rejected, +because its author likely meant it to run on every entry; declare the local +`static` or `automatic` to state which. + +Task locals that keep their values and nonconstant initializers of static +function locals remain unsupported; declare those locals `automatic`. Package +function state is a package variable, which the processes of every instance may write. An interface whose default lifetime (`interface automatic`) differs from that of the module it is used in is rejected. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f540ad6bb28..9eb08b0e6c7 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -25,7 +25,7 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard / soft packed untagged union、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | +| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard / soft packed untagged union、enum(暗黙値を含む)と enum 型の任意の式(enum の packed 配列の要素を除く、[#2417](https://github.com/celox-sim/celox/issues/2417))に対するメソッド `first`・`last`・`next`・`prev`・`num`・`name`、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | @@ -42,7 +42,7 @@ outline: [2, 3] | 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | | initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if`、`$readmemh` / `$readmemb`、実行前に反復回数が分かるループ(`repeat` と、1 つの変数を定数ずつ固定の境界まで進める `for` / `while` / `do`-`while`)を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | | 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーションと遅延付き即時アサーション | -| 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | +| 関数 | `input` / `output` / `inout` / `ref` / `const ref` 引数([参照渡しの引数](#reference-arguments)を参照)を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | ### タイミング制御 {#timing-controls} @@ -210,7 +210,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 その構文を追跡する issue の番号が含まれます。専用の issue がない構文は、フロントエンドの ロードマップ [#88](https://github.com/celox-sim/celox/issues/88) を指します。 -- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、宣言した package やコンパイル単位の外でのパラメータ付きクラスの特殊化、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し、`ref` 引数。 +- [対応範囲](#classes)外のクラスの機能:クラスハンドル以外の変数への `$cast`、クラス内で宣言した列挙定数、クラスパラメータの値としての列挙型・構造体型・共用体型と名前付きの 4 値・文字列定数、宣言した package やコンパイル単位の外でのパラメータ付きクラスの特殊化、4 値・`real`・配列・64 ビットを超えるプロパティ。時間待ちを含む task の static ローカル宣言、再帰呼び出し。 - `inout` / `ref` / 式を使う modport、virtual interface など。 ANSI ヘッダーのポートは、クロック入力やパラメータ依存の幅も含めて modport 経由で渡せます。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 @@ -349,6 +349,26 @@ union 全体の演算は宣言時の符号指定に従います(既定は unsi 読み書きする際には X/Z を 0 に変換します。 tagged union と unpacked union は未対応です。 +### 参照渡しの引数 {#reference-arguments} + +`ref` と `const ref` の仮引数はコピーではなく実引数そのものです(IEEE 1800-2023 13.5.2)。 +仮引数への書き込みはすぐに見え、実引数の別の名前とも別名になり、task は待ちの間も参照を保ちます。 +実引数には、変数(`string`、クラスハンドル、キュー、動的配列、連想配列、unpacked 配列を含む)、 +呼び出し時にハンドルを評価するクラスオブジェクトのプロパティ、呼び出し時に添字を評価する +固定長 unpacked 配列の要素を渡せます。`const` は方向と同様に後続の仮引数に引き継がれます(13.3)。 + +規格どおり次を拒否します:static な寿命のサブルーチンの `ref` 仮引数、式・定数・部分選択・ネット、 +または仮引数と等価でない型(6.22.2)の実引数、`const ref` 仮引数への書き込み、`ref` 仮引数への +ノンブロッキング代入(6.21)、fork 変数の初期値以外での `fork ... join_any` / `join_none` 内の +`ref` 仮引数の使用(9.3.2)、連続代入やイベント式での `ref` 引数を持つ関数の呼び出し +(13.4.1。`const ref` は可)。 + +`ref static`、動的配列・キュー・連想配列の要素(参照がサイズ変更より長く生きる必要がある、13.5.2)、 +クラスプロパティの要素、unpacked 構造体のメンバ、クラスプロパティに束縛した仮引数の一部への書き込み、 +配列要素に束縛した仮引数の実行時にしか決まらない位置での選択(展開されるループの位置は決まる)は +未対応として拒否します。クラスプロパティに束縛した仮引数は `output` / `inout` 引数に渡せ、その呼び出しが +戻るときに書き戻します。 + ### 名前付きサブルーチン引数 名前付きサブルーチン引数は仮引数の名前で束縛し、入力の評価と出力のコピーアウトは @@ -448,7 +468,18 @@ static な output 引数も、代入しない経路では以前の値を保持 定数関数としての呼び出しは 毎回新しい値を使い、実行時の状態に影響しません(13.4.3)。 -値を保持する task ローカル変数と、定数でない static 初期化子は引き続き未対応です。 +プロセスの static なローカル変数には実行時の値を使う初期化子も書けます。初期化子は宣言順に、 +どの手続きよりも先に 1 回だけ実行し(IEEE 1800-2023 6.8)、モジュールの変数とほかの static な +ローカル変数を読めますが、automatic 変数は読めません。IEEE 1800-2023 6.21 は "an explicit static +keyword shall be required when an initialization value is specified as part of a static variable's +declaration" と定め、手続きブロック内で初期化子を持つ static 変数に `static` キーワードを要求します。 +既存のソースはこのキーワードを省くことが多いため(`initial` ブロック内の `string s = v.name();` など)、 +Celox はキーワードのない宣言も受け付けます。定数の初期化子はどの手続きでも、実行時の値を使う初期化子は +`initial` のように 1 回だけ実行する手続きで受け付けます。`always` 手続きでキーワードなしに実行時の値で +初期化すると、入るたびに実行する意図の可能性が高いためエラーになります。`static` か `automatic` を +指定して意図を示してください。 + +値を保持する task ローカル変数と、関数の static なローカル変数の定数でない初期化子は引き続き未対応です。 これらには `automatic` を指定してください。package 関数の状態は package 変数で、 すべてのインスタンスのプロセスが書き込めます。既定の寿命(`interface automatic`)が 使用先のモジュールと異なる interface は拒否します。 diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index 5b44181ff61..94d6f0673a4 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -334,6 +334,24 @@ test("every retained baseline accepts only its existing failures", () => { "hierarchy::packed_pattern_parameter_arguments_keep_types_and_unknown_bits", "hierarchy::packed_pattern_parameter_arguments_preserve_wide_values", "hierarchy::packed_pattern_parameters_forward_whole_values", + "references::const_ref_in_a_continuous_assignment", + "references::const_ref_reads_the_current_value", + "references::ref_actual_of_an_equivalent_type", + "references::ref_array_element_index_is_fixed_at_the_call", + "references::ref_class_property_names_the_object_of_the_call", + "references::ref_default_and_named_arguments", + "references::ref_element_after_an_input_in_forked_activations", + "references::ref_element_select_past_the_element", + "references::ref_elements_of_concurrent_task_activations", + "references::ref_fills_caller_queues", + "references::ref_formals_of_one_actual_alias_each_other", + "references::ref_property_forwarded_to_output_and_inout", + "references::ref_property_of_this", + "references::ref_replaces_a_class_handle", + "references::ref_static_class_properties", + "references::ref_task_keeps_a_property_while_suspended", + "references::ref_task_keeps_the_reference_while_suspended", + "references::ref_writes_are_seen_before_the_return", "tagged_unions::casts_ports_and_registers", "tagged_unions::conditional_struct_payload", "tagged_unions::constructors_and_checked_members", @@ -374,6 +392,9 @@ test("every retained baseline accepts only its existing failures", () => { "operators::two_state_case_equality_keeps_unknown_expression_bits", "operators::two_state_case_equality_preserves_conditional_unknowns", "operators::two_state_case_equality_preserves_unknown_literals", + "references::ref_actual_of_an_equivalent_type", + "references::ref_array_element_index_is_fixed_at_the_call", + "references::ref_class_property_names_the_object_of_the_call", "tagged_unions::conditional_struct_payload", "tagged_unions::constructors_and_checked_members", "tagged_unions::default_arguments",