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..13aea80aff2 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(), @@ -1411,6 +1416,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 +1471,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 +1496,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 +1519,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 +4564,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 +4608,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 +4665,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 +4744,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 +4765,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 +4795,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 +4811,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 @@ -8093,3 +8281,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-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 0dd6ccb287b..e6b88f385ae 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, @@ -1406,6 +1407,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, @@ -2796,21 +2812,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, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 5ba75332b4d..4e1da8f54a4 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) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 2914256434d..0f30decf9ce 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -5,6 +5,7 @@ mod calls; mod direct; 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..bbf0009b7b8 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -488,12 +488,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)); } ( @@ -743,6 +754,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 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/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index f349f66b33c..541048b79e3 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)); @@ -195,12 +185,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); 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/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 55824a2b4d6..9d191a2934c 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -747,7 +747,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 +755,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 +772,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 +784,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 +912,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/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index bd96070de1a..ae82c8c776e 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::{ @@ -2305,6 +2306,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 { 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/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/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..82a7feacd2e 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), } } 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/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/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/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/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..4bb6f1f82b0 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -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 diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f540ad6bb28..31f649466a9 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -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` 引数に渡せ、その呼び出しが +戻るときに書き戻します。 + ### 名前付きサブルーチン引数 名前付きサブルーチン引数は仮引数の名前で束縛し、入力の評価と出力のコピーアウトは 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",