diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c44bd3b34c1..ccd2bc7faf5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -6488,6 +6488,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::UrandomRange | SystemFunction::Fopen | SystemFunction::ScopeRandomize + | SystemFunction::ScopeRandomizeEnum | SystemFunction::Fread | SystemFunction::Ftell | SystemFunction::Fseek diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b77cd77394d..ed885a57cd7 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -259,6 +259,7 @@ impl<'p, 'a> Ff<'p, 'a> { use sv::ir::SystemFunction; match function { SystemFunction::ScopeRandomize + | SystemFunction::ScopeRandomizeEnum | SystemFunction::Urandom | SystemFunction::UrandomRange => { self.urandom_state(); @@ -903,6 +904,11 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.fopen(args)?, + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomizeEnum), + args, + .. + } => self.randomize_enum(args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize), args, @@ -1412,6 +1418,67 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// Randomize one scalar enum from the process stream. Arguments after the + /// writable destination are its declared values, supplied by the analyzer. + fn randomize_enum( + &mut self, + args: &[Option], + ) -> Result { + use sv::ir::{BinaryOp, Expr}; + let Some(Some(Expr::Ident(name))) = args.first() else { + return Err(unsupported("scope enum randomize variable")); + }; + let values = args[1..] + .iter() + .map(Option::as_ref) + .collect::>>() + .filter(|values| !values.is_empty()) + .ok_or_else(|| unsupported("scope enum randomize domain"))?; + let count = u32::try_from(values.len()) + .map_err(|_| unsupported("scope enum randomize domain size"))?; + let threshold = count.wrapping_neg() % count; + let draw_block = self.b.new_block(); + let accepted = self.b.new_block(); + self.jump(draw_block); + self.b.switch_to_block(draw_block); + let draw = self.randomize_word()?; + let rejected = Expr::Binary { + left: Box::new(draw.clone()), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("32'd{threshold}"))), + }; + let cond = self.eval_truth(&rejected)?.0; + self.b.seal_block(SIRTerminator::Branch { + cond, + true_block: (draw_block, Vec::new()), + false_block: (accepted, Vec::new()), + }); + self.b.switch_to_block(accepted); + let index = self.hidden( + "enum_index", + &Expr::Binary { + left: Box::new(draw), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("32'd{count}"))), + }, + false, + )?; + let mut value = (*values.last().unwrap()).clone(); + for (position, member) in values.iter().enumerate().rev().skip(1) { + value = Expr::Mux { + condition: Box::new(Expr::Binary { + left: Box::new(index.clone()), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal(format!("32'd{position}"))), + }), + then_expr: Box::new((*member).clone()), + else_expr: Box::new(value), + }; + } + self.assign(&sv::ir::LValue::Ident(name.clone()), &value)?; + Ok(Expr::Literal("32'sd1".into())) + } + /// A bijective 32-bit output permutation of the process RNG. Mixing /// high bits into low bits prevents the LCG's short low-bit periods from /// freezing bits when a wide variable consumes an even number of words. diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 7b61af634ae..a33c623e978 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1969,6 +1969,8 @@ pub enum PortDirection { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Type { is_enum: bool, + /// Resolved legal values for a scalar enum; None if its domain is unsupported. + enum_values: Option>, kind: TypeKind, is_signed: bool, packed_ranges: Vec, @@ -1986,6 +1988,7 @@ impl Type { fn implicit() -> Self { Self { is_enum: false, + enum_values: None, kind: TypeKind::Implicit, is_signed: false, packed_ranges: Vec::new(), @@ -2000,6 +2003,7 @@ impl Type { Self { kind, is_enum: false, + enum_values: None, is_signed: false, packed_ranges: Vec::new(), unpacked_ranges: Vec::new(), @@ -2727,6 +2731,7 @@ struct UnpackedDimension { #[derive(Debug, Clone, PartialEq, Eq)] struct VariableDimensions { randomizable: bool, + enum_values: Option>, real: bool, /// A `string`: each element is a heap handle, not packed bits. string: bool, diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index a44fee5735b..4b92fe3940d 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -122,9 +122,12 @@ impl Class { if property.randc { return Err(unsupported("class randomize with randc properties")); } - if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) { + if property.rand + && (property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none())) + { return Err(unsupported( - "class randomize requires integral non-enum rand properties", + "class randomize requires integral rand properties with a supported enum domain", )); } } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index bcc9ca9afec..a5f17b392a4 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -132,7 +132,9 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( port.name().to_string(), VariableDimensions { - randomizable: !port.r#type().is_enum && port.randomizable, + randomizable: (!port.r#type().is_enum || port.r#type().enum_values.is_some()) + && port.randomizable, + enum_values: port.r#type().enum_values.clone(), real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(port.r#type().kind(), TypeKind::String), class: port.r#type().class().map(str::to_owned), @@ -156,7 +158,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals( dimensions.insert( signal.name().to_string(), VariableDimensions { - randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const, + randomizable: (!signal.r#type().is_enum || signal.r#type().enum_values.is_some()) + && !signal.is_net() + && !signal.is_const, + enum_values: signal.r#type().enum_values.clone(), real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(signal.r#type().kind(), TypeKind::String), class: signal.r#type().class().map(str::to_owned), @@ -350,6 +355,7 @@ fn extend_variable_dimensions_from_const_env( let packed_ranges = ranges.split_off(unpacked); let ty = Type { is_enum: false, + enum_values: None, kind: TypeKind::Logic, is_signed: variable_type_is_signed(const_env, name), packed_ranges, @@ -364,6 +370,7 @@ fn extend_variable_dimensions_from_const_env( let mut shape = procedural::dimensions_from_type(&ty); if let Some(existing) = context.get(name) { shape.randomizable = existing.randomizable; + shape.enum_values = existing.enum_values.clone(); shape.members = existing.members.clone(); shape.is_2state = existing.is_2state; shape.signed_element_depth = existing.signed_element_depth; @@ -532,6 +539,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP parameter.name.clone(), VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, 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 9ebd6e1001e..6f80370ce22 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -216,6 +216,7 @@ pub(in crate::ast) fn cast_target_native( } enum Finish { + ScopeRandomize(Vec>>), Unary(String), Binary(String), Mux, @@ -233,7 +234,7 @@ enum Finish { /// A string operation on the bound children, see [`strings`]. StringCall(StringOp), /// A read of property `property` of the object handle child. - ObjectLoad(crate::ast::classes::Property), + ObjectLoad(Box), /// A call of method subroutine `name` with `formals` formals; the first /// child is the object handle when `receiver` is one. MethodCall { @@ -499,6 +500,7 @@ pub(in crate::ast) fn bind_value( } let actuals = args.iter().filter_map(|arg| arg.value).collect::>(); + let mut domains = Vec::with_capacity(actuals.len()); for &actual in &actuals { let ExprKind::Name(name) = &native.expression(actual).kind else { return Err(unsupported( @@ -509,11 +511,17 @@ pub(in crate::ast) fn bind_value( let shape = dimensions .get(&name) .ok_or_else(|| unsupported("scope randomize variable"))?; - if !shape.unpacked.is_empty() || !shape.randomizable { + if !shape.unpacked.is_empty() + || !shape.randomizable + || shape.real + || shape.string + || shape.class.is_some() + { return Err(unsupported( - "scope randomize requires a packed non-enum variable", + "scope randomize requires a packed variable with a supported enum domain", )); } + domains.push(shape.enum_values.clone()); if !expressions::query_actual_is_writable( &Expr::Ident(name), dimensions, @@ -524,12 +532,7 @@ pub(in crate::ast) fn bind_value( } } jobs.push(Job::Finish( - Finish::Call { - name: "std::randomize".into(), - args: actuals.iter().copied().map(Some).collect(), - order: Vec::new(), - system: Some(SystemFunction::ScopeRandomize), - }, + Finish::ScopeRandomize(domains), actuals.len(), scope.clone(), )); @@ -756,9 +759,10 @@ pub(in crate::ast) fn bind_value( let (property, receiver) = objects::property(tree, id, native, dimensions)? .expect("checked by the guard"); match receiver { - Some(receiver) => { - (Finish::ObjectLoad(property), vec![(receiver, None)]) - } + Some(receiver) => ( + Finish::ObjectLoad(Box::new(property)), + vec![(receiver, None)], + ), None => { values.push(objects::load(&property, objects::this())); continue; @@ -929,6 +933,46 @@ pub(in crate::ast) fn bind_value( Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) } + Finish::ScopeRandomize(domains) => { + // Preserve the original call when no enum is present. + // Every scalar operation succeeds and returns signed int 1; + // bitwise AND preserves that type and evaluates all operands. + if domains.iter().all(Option::is_none) { + Expr::Call { + callee: Callee::System(SystemFunction::ScopeRandomize), + args: operands.into_iter().map(Some).collect(), + arg_order: Vec::new(), + } + } else { + let mut calls = + operands.into_iter().zip(domains).map(|(operand, domain)| { + let mut args = vec![Some(operand)]; + let function = if let Some(values) = domain { + args.extend(values.into_iter().map(|value| { + Some(Expr::Literal(format_typed_parameter_literal( + value, + 64, + value < 0, + ))) + })); + SystemFunction::ScopeRandomizeEnum + } else { + SystemFunction::ScopeRandomize + }; + Expr::Call { + callee: Callee::System(function), + args, + arg_order: Vec::new(), + } + }); + let first = calls.next().ok_or_else(disagreement)?; + calls.fold(first, |left, right| Expr::Binary { + left: Box::new(left), + op: BinaryOp::BitAnd, + right: Box::new(right), + }) + } + } Finish::ObjectLoad(property) => { let handle = operands.pop().ok_or_else(disagreement)?; objects::load(&property, handle) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index cfcd38f83ed..26d4e676a93 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -555,9 +555,12 @@ pub(super) fn random_selection( if property.constant { return Err(unsupported("randomize argument is a const property")); } - if property.field.handle.is_some() || property.r#type.is_enum || property.randc { + if property.field.handle.is_some() + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) + || property.randc + { return Err(unsupported( - "randomize arguments require integral non-enum, non-randc properties", + "randomize arguments require integral, non-randc properties with a supported enum domain", )); } bits[index + 1] = '1'; diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 26ba51430bd..382384aad5d 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -57,6 +57,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - name.to_string(), VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index df53b14d48e..a2f4efd2aab 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -935,7 +935,11 @@ pub(super) fn coerce_const_parameter_value(value: i128, width: usize, signed: bo } } -fn enum_initializer_fits_base_type(value: i128, value_type: ExprType, base_type: ExprType) -> bool { +pub(super) fn enum_initializer_fits_base_type( + value: i128, + value_type: ExprType, + base_type: ExprType, +) -> bool { // A same-width initializer may change its numeric interpretation when // the enum base has different signedness, but it does not lose any bits. if value_type.width <= base_type.width || base_type.width >= 128 { diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 3072f78cc24..1184772f60f 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -502,6 +502,7 @@ fn pattern_items( count as i128 - 1, VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 0253bcdeaec..79d17825612 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -137,6 +137,7 @@ fn select<'a>( let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, @@ -244,6 +245,7 @@ fn select<'a>( .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, + enum_values: None, real: false, string: false, class: None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index f3eee42895d..11830353e22 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -73,7 +73,8 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { /// The packed and unpacked shape of a declared type, as selects see it. pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { - randomizable: !r#type.is_enum, + randomizable: !r#type.is_enum || r#type.enum_values.is_some(), + enum_values: r#type.enum_values.clone(), real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), string: matches!(r#type.kind(), TypeKind::String), class: r#type.class().map(str::to_owned), @@ -115,6 +116,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap) - pub(super) fn int_type() -> Type { Type { is_enum: false, + enum_values: None, kind: TypeKind::Bit, is_signed: true, packed_ranges: vec![PackedRange::new( diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 2b8d305459e..597458d6c73 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -133,7 +133,7 @@ pub(super) fn lower( for property in &class.properties { if property.constant || property.field.handle.is_some() - || property.r#type.is_enum + || (property.r#type.is_enum && property.r#type.enum_values.is_none()) { continue; } @@ -150,16 +150,7 @@ pub(super) fn lower( vec![Expr::Ident(this.clone())], )), }, - then_body: vec![Stmt::Eval(classes::object_call( - ObjectOp::Store(property.field), - vec![ - Expr::Ident(this.clone()), - classes::object_call( - ObjectOp::Random, - vec![Expr::Ident(this.clone())], - ), - ], - ))], + then_body: random_property(&mut builder, property, &this), else_body: Vec::new(), }); } @@ -264,3 +255,71 @@ pub(super) fn lower( } Ok(result) } + +/// Select a declared enum value with rejection sampling, so non-power-of-two +/// domains are uniform (IEEE 1800-2023 18.3, 18.4.1). Keep the draws inside the +/// mode guard: a disabled property must not consume its object's random stream. +fn random_property( + builder: &mut BodyBuilder<'_, '_, '_>, + property: &classes::Property, + this: &str, +) -> Vec { + let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]); + let mut body = Vec::new(); + let value = if let Some(values) = &property.r#type.enum_values { + let count = values.len() as u64; + let threshold = count.wrapping_neg() % count; + let draw = builder.declare("$enum_draw", classes::unsigned_type(64)); + body.push(Stmt::Loop { + kind: LoopKind::DoWhile, + init: Vec::new(), + condition: Some(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("64'd{threshold}"))), + }), + step: Vec::new(), + body: vec![Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: random(), + nonblocking: false, + }], + }); + body.push(Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("64'd{count}"))), + }, + nonblocking: false, + }); + let literal = |value| { + Expr::Literal(format_typed_parameter_literal( + value, + property.field.width as usize, + property.field.signed, + )) + }; + let mut value = literal(*values.last().unwrap()); + for (index, &member) in values.iter().enumerate().rev().skip(1) { + value = Expr::Mux { + condition: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal(format!("64'd{index}"))), + }), + then_expr: Box::new(literal(member)), + else_expr: Box::new(value), + }; + } + value + } else { + random() + }; + body.push(Stmt::Eval(classes::object_call( + ObjectOp::Store(property.field), + vec![Expr::Ident(this.into()), value], + ))); + body +} diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 30e61323785..6ff5bd6c541 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -18,7 +18,7 @@ pub(in crate::ast) fn bind_in( ) -> Converted> { enum Job { Enter(TypeId), - Enum(Vec), + Enum(TypeId, Vec), Aggregate { owner: Arc, union: bool, @@ -79,11 +79,12 @@ pub(in crate::ast) fn bind_in( } DataTypeKind::Enum { base, .. } => { if let Some(base) = base { - jobs.push(Job::Enum(ranges)); + jobs.push(Job::Enum(id, ranges)); jobs.push(Job::Enter(*base)); } else { let mut ty = builtin_type("int", None).unwrap(); ty.is_enum = true; + ty.enum_values = enum_values(id, native, tree, context, &ty); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); } @@ -159,7 +160,7 @@ pub(in crate::ast) fn bind_in( } } } - Job::Enum(ranges) => { + Job::Enum(id, ranges) => { let Some(mut ty) = values.pop() else { return Err(unsupported("enum base type")); }; @@ -167,6 +168,7 @@ pub(in crate::ast) fn bind_in( outer.extend(ty.packed_ranges); ty.packed_ranges = outer; ty.is_enum = true; + ty.enum_values = enum_values(id, native, tree, context, &ty); values.push(ty); } Job::Aggregate { @@ -282,3 +284,68 @@ pub(in crate::ast) fn expression_type( let value = expression_binding::bind(root, tree, &query)?; Ok(dimensions::bound_bits_type(&tree.state, &value, &query)) } + +/// Domain metadata is best-effort during signature discovery. Only a caller +/// requesting randomization requires a resolved domain; unused types must not +/// start reporting new errors merely because this metadata is collected. +fn enum_values( + id: TypeId, + native: &celox_sv_syntax::Declarations, + tree: &AnalysisContext<'_>, + context: &PackedDimensions, + ty: &Type, +) -> Option> { + let data = native.data_type(id); + if !data.packed_dimensions.is_empty() { + return None; + } + let DataTypeKind::Enum { items, .. } = &data.kind else { + return None; + }; + let shape = casts::expr_type_from_type(&tree.state, ty, &context.const_env)?; + if shape.width > 64 { + return None; + } + let mut env = context.const_env.clone(); + let mut next = 0i128; + let mut values = Vec::new(); + for item in items { + if !item.dimensions.is_empty() { + return None; + } + let value = if let Some(id) = item.value { + let expr = constant_binding::expression(id, native, tree, &env, &context.type_aliases) + .ok()??; + // Unbased fills take the enum base's width and signedness, just + // as they do when resolving the declared enum constants (5.7.1). + let expr = match expr { + ConstExpr::Literal(literal) => ConstExpr::Literal( + resize_unbased_fill_literal_for_cast(&literal, shape.width, shape.signed) + .unwrap_or(literal), + ), + expr => expr, + }; + let value = eval_ast_const_expr(&tree.state, &expr, &env)?; + let value_type = infer_const_expr_type(&expr, ¶meter_types_from_const_env(&env))?; + if !parameters::enum_initializer_fits_base_type(value, value_type, shape) { + return None; + } + value + } else { + if parameters::coerce_const_parameter_value(next, shape.width, shape.signed) != next { + return None; + } + next + }; + let value = parameters::coerce_const_parameter_value(value, shape.width, shape.signed); + if values.contains(&value) { + return None; + } + values.push(value); + let name = normalize_identifier(&item.name.spelling); + env.insert(name.clone(), value); + dimensions::insert_parameter_type_markers(&mut env, &name, shape); + next = value.checked_add(1)?; + } + (!values.is_empty()).then_some(values) +} diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index fa20c7e6cb5..22ed86204db 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -177,6 +177,7 @@ pub(super) fn enclose_aliased_packed_type( // array they form is unsigned, whatever its elements (IEEE 1800-2023 // 7.4.1); a type name takes no signing of its own. if !direct_ranges.is_empty() { + r#type.enum_values = None; r#type.signed_element_depth = if r#type.is_signed { Some(direct_ranges.len()) } else { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 3fda772fed5..dfdf49d219d 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -103,6 +103,8 @@ pub enum SystemFunction { Urandom, /// Scope randomization of packed variables, without constraints (18.12). ScopeRandomize, + /// Internal scalar enum randomization: destination followed by legal values. + ScopeRandomizeEnum, /// `$urandom_range` (18.13.2). UrandomRange, /// `$fopen` (21.3.1). @@ -280,6 +282,7 @@ impl SystemFunction { Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", Self::ScopeRandomize => "std::randomize", + Self::ScopeRandomizeEnum => "$__celox_randomize_enum", Self::UrandomRange => "$urandom_range", Self::Fopen => "$fopen", Self::Fread => "$fread", @@ -343,6 +346,7 @@ impl SystemFunction { | Self::Fscanf | Self::UrandomRange | Self::ScopeRandomize + | Self::ScopeRandomizeEnum ) } @@ -357,6 +361,7 @@ impl SystemFunction { /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { self == Self::ScopeRandomize + || (self == Self::ScopeRandomizeEnum && position == 0) || (matches!( self, Self::Random @@ -406,7 +411,8 @@ impl SystemFunction { | Self::Clog2 | Self::Countbits | Self::Countones - | Self::ScopeRandomize => Some((32, true)), + | Self::ScopeRandomize + | Self::ScopeRandomizeEnum => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), Self::Random | Self::DistUniform diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 94015a571ce..4314adf6bae 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6303,11 +6303,10 @@ fn scope_randomize_validates_variable_arguments() { ("bit value[2];", "randomize(value)"), ("wire value;", "randomize(value)"), ("const bit value = 1;", "randomize(value)"), - ("enum bit [1:0] {A=0, B=3} value;", "randomize(value)"), - ( - "typedef enum bit [1:0] {A=0, B=3} E; E value;", - "std::randomize(value)", - ), + ("real value;", "randomize(value)"), + ("string value;", "randomize(value)"), + ("class C; endclass C value;", "randomize(value)"), + ("enum bit [1:0] {A=3, B} value;", "randomize(value)"), ("bit value;", "std::randomize(value) with {value == 1;}"), ] { let source = format!("module Top; {declaration} bit ok; initial ok = {call}; endmodule"); @@ -6610,7 +6609,11 @@ fn class_randomize_rejects_unsupported_semantics() { "c.f()", "object receiver", ), - ("rand string x;", "c.randomize()", "integral non-enum"), + ( + "rand string x;", + "c.randomize()", + "integral rand properties", + ), ( "rand int x;", "c.randomize() with { x == 1; }", @@ -6678,3 +6681,19 @@ fn randomization_signatures_do_not_force_unused_interface_class_layouts() { analyze_source(&source, Path::new("unused_interface_class.sv")).unwrap(); } } + +#[test] +fn class_randomize_rejects_unresolved_enum_domains() { + for members in ["A=3, B", "A=0, B=0", "A=2'bx, B=1"] { + let source = format!( + "module Top; + class C; rand enum bit [1:0] {{{members}}} value; endclass + C c; initial begin c = new; void'(c.randomize()); end + endmodule" + ); + assert!( + analyze_source(&source, Path::new("enum_domain.sv")).is_err(), + "{members}" + ); + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 6a96fd7d4de..97530f68a62 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -696,6 +696,30 @@ Verilator 5.052 has two narrower exclusions, recorded in the 0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control, inline member selection and pre-hook control cases pass Verilator. +Enum class randomization (`sv_icarus_enum_randomization`) excludes the four +`class::randomization_enum_*` cases from Icarus 13.0 because it cannot elaborate +class randomization methods. [Original diagnostics](verification/repros/sv_enum_randomization_icarus.json) +retain the failures without changing the shared assertions. + +Verilator 5.052 passes the direct enum and inherited enum cases, but treats a +typedef alias of an enum as the underlying integer during randomization +(`sv_verilator_enum_alias_randomization`). The generated randomizer assigns raw +8-bit random values rather than selecting declared enum values, contrary to +IEEE 1800-2023 18.3. Only `class::randomization_enum_alias` is excluded; +[the mismatch evidence](verification/repros/sv_enum_randomization_verilator.json) +retains its unchanged domain assertion. + +Scope enum randomization has two narrow tool exclusions for +`system_functions::scope_randomize_enum_values` and +`system_functions::scope_randomize_enum_order`. Icarus 13.0 rejects scope +randomization calls (`sv_icarus_scope_enum_randomize`; +[compile diagnostics](verification/repros/sv_scope_enum_randomize_icarus.json)). +Verilator 5.052 generates `basicStdRandomization` calls using only integer widths, +without the enum domain, and draws undeclared values (`sv_verilator_scope_enum_randomize`; +[mismatch evidence](verification/repros/sv_scope_enum_randomize_verilator.json)). +IEEE 1800-2023 18.3 and 18.12 require the declared enum domain. The shared +assertions remain unchanged, including the direct-enum case without an alias. + ## SystemVerilog packed unions The `unions` shared group covers hard and soft packed untagged unions. With diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 768617f2953..06c4057355b 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -929,3 +929,141 @@ module Top(output bit done, output int errors); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_domain + (source "enum_randomize.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=MID+89} sparse_t; + typedef enum bit [63:0] {LOW=64'h100000000, TOP=64'h8000000000000000} wide_t; + class Base; + rand sparse_t value; + sparse_t selected; + rand wide_t wide_value; + rand enum bit [2:0] {ONLY=5} single; + rand enum {FIRST=11, SECOND=35, THIRD} extra; + endclass + Base a, b; + Base base; + int seen; + int old_value; + initial begin + a = new; b = new; base = a; + a.srandom(123); b.srandom(123); + repeat (256) begin + if (!base.randomize() || !b.randomize()) errors++; + if (a.value != b.value || a.wide_value != b.wide_value || a.extra != b.extra) errors++; + case (a.value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + if (a.wide_value != LOW && a.wide_value != TOP) errors++; + if (a.single != 5) errors++; + if (a.extra != 11 && a.extra != 35 && a.extra != 36) errors++; + end + if (seen != 7) errors++; + a.value.rand_mode(0); + old_value = a.value; + if (!a.randomize() || a.value != old_value) errors++; + if (!a.randomize(selected)) errors++; + if (a.selected != NEG && a.selected != MID && a.selected != HIGH) errors++; + if (a.value != old_value || a.value.rand_mode() != 0) errors++; + if (!base.randomize(value)) errors++; + if (a.value != NEG && a.value != MID && a.value != HIGH) errors++; + if (a.value.rand_mode() != 0) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_inheritance + (source "enum_inheritance.sv" #" +module Top(output bit done, output int errors); + class Parent; + rand enum bit [7:0] {P=7, Q=93} x; + endclass + class Child extends Parent; + rand enum bit [7:0] {R=11, S=57, T=98} y; + endclass + Child child; + Parent parent; + int seen; + initial begin + child = new; parent = child; + repeat (128) begin + if (parent.randomize() != 1) errors++; + if (child.x != 7 && child.x != 93) errors++; + case (child.y) + 11: seen |= 1; + 57: seen |= 2; + 98: seen |= 4; + default: errors++; + endcase + end + if (seen != 7) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_alias + (source "enum_alias.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=91} original_t; + typedef original_t alias_t; + class Sample; + rand alias_t value; + endclass + Sample object; + int seen; + initial begin + object = new; + repeat (128) begin + if (object.randomize() != 1) errors++; + case (object.value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + end + if (seen != 7) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_enum_fill_literals + (source "enum_fill.sv" #" +module Top(output bit done, output int errors); + typedef enum bit [63:0] {WIDE_ALL='1} wide_t; + typedef enum bit [3:0] {SMALL_ALL='1} small_t; + typedef enum bit signed [63:0] {SIGNED_ALL='1} signed_t; + typedef enum bit [63:0] {ZERO='0} zero_t; + class Sample; + rand wide_t wide_value; + rand small_t small_value; + rand signed_t signed_value; + rand zero_t zero_value; + endclass + Sample object; + initial begin + object = new; + repeat (8) begin + if (object.randomize() != 1) errors++; + if (object.wide_value != 64'hffffffffffffffff) errors++; + if (object.small_value != 4'hf) errors++; + if (object.signed_value != -64'sd1) errors++; + if (object.zero_value != 64'd0) errors++; + if (object.wide_value != WIDE_ALL || object.small_value != SMALL_ALL + || object.signed_value != SIGNED_ALL || object.zero_value != ZERO) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/src/sv/cases/system_functions.vtest b/crates/celox-test-suite/src/sv/cases/system_functions.vtest index 0990ccf7e9f..2463a162fa5 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2892,3 +2892,63 @@ endmodule (top Top) (run_to_finish) (assert_eq status 2)) + +(case scope_randomize_enum_values + (source "scope_enum.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [7:0] {NEG=-7, MID=2, HIGH=91} original_t; + typedef original_t alias_t; + typedef enum logic [63:0] {ALL='1} wide_t; + alias_t value; + wide_t wide; + int plain; + int seen; + function automatic int local_random(); + alias_t local_value; + if (randomize(local_value) != 1) return 0; + return local_value == NEG || local_value == MID || local_value == HIGH; + endfunction + initial begin + repeat (128) begin + if (std::randomize(value, plain, wide) != 1) errors++; + case (value) + NEG: seen |= 1; + MID: seen |= 2; + HIGH: seen |= 4; + default: errors++; + endcase + if (wide != 64'hffffffffffffffff) errors++; + if (local_random() != 1) errors++; + end + if (seen != 7) errors++; + if ($bits(std::randomize(value)) != 32) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + + +(case scope_randomize_enum_order + (source "scope_enum_order.sv" #" +module Top(output bit done, output int errors); + typedef enum bit [7:0] {A=3, B=19, C=97} value_t; + value_t value; + int plain; + int result; + initial begin + value = A; plain = 17; + result = 0 && std::randomize(value, plain); + result = 1 || randomize(value); + if (value != A || plain != 17) errors++; + repeat (64) begin + result = (std::randomize(value, plain) == 1) + && (value == A || value == B || value == C); + if (result != 1) errors++; + if (randomize(value) != 1 || (value != A && value != B && value != C)) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json b/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json new file mode 100644 index 00000000000..d0fa8229844 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_enum_randomization_icarus.json @@ -0,0 +1,55 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:13: Error: randomize is not a method of class Sample.\n/source_0.sv:13: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:13: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 24; see /build.log\n/source_0.sv:18: error: Can't find task srandom in class Base\n/source_0.sv:18: error: Enable of unknown task ``a.srandom''.\n/source_0.sv:18: error: Can't find task srandom in class Base\n/source_0.sv:18: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:20: Error: randomize is not a method of class Base.\n/source_0.sv:20: error: Object celox_suite_tb.dut.base has no method \"randomize(...)\".\n/source_0.sv:20: Error: randomize is not a method of class Base.\n/source_0.sv:20: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:20: error: Unable to elaborate condition expression.\n/source_0.sv:33: error: Can't find task rand_mode in class Base\n/source_0.sv:33: error: Enable of unknown task ``a.value.rand_mode''.\n/source_0.sv:35: Error: randomize is not a method of class Base.\n/source_0.sv:35: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:35: error: Unable to elaborate condition expression.\n/source_0.sv:36: Error: randomize is not a method of class Base.\n/source_0.sv:36: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:36: error: Unable to elaborate condition expression.\n/source_0.sv:38: sorry: Method name nesting is not supported yet.\n/source_0.sv:38: : method path: value.rand_mode\n/source_0.sv:38: error: Object celox_suite_tb.dut.a has no method \"value.rand_mode(...)\".\n/source_0.sv:38: error: Unable to elaborate condition expression.\n/source_0.sv:39: Error: randomize is not a method of class Base.\n/source_0.sv:39: error: Object celox_suite_tb.dut.base has no method \"randomize(...)\".\n/source_0.sv:39: error: Unable to elaborate condition expression.\n/source_0.sv:41: sorry: Method name nesting is not supported yet.\n/source_0.sv:41: : method path: value.rand_mode\n/source_0.sv:41: error: Object celox_suite_tb.dut.a has no method \"value.rand_mode(...)\".\n/source_0.sv:41: error: Unable to elaborate condition expression.\n24 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_domain", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:17: Error: randomize is not a method of class Sample.\n/source_0.sv:17: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:17: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_enum_fill_literals", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 134; see /build.log\n/source_0.sv:15: Error: randomize is not a method of class Parent.\n/source_0.sv:15: error: Object celox_suite_tb.dut.parent has no method \"randomize(...)\".\n/source_0.sv:15: error: Unable to elaborate condition expression.\n/source_0.sv:17: assert: dup_expr.cc:215: failed assertion 0\nAborted (core dumped)\n", + "expectation": "Simulation", + "name": "class::randomization_enum_inheritance", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json b/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json new file mode 100644 index 00000000000..c9062c4139b --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_enum_randomization_verilator.json @@ -0,0 +1,22 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "class::randomization_enum_alias at 1038:46: assert_eq errors: expected 0x0, got 0x7e", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052" +} diff --git a/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json new file mode 100644 index 00000000000..b262a613b51 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_icarus.json @@ -0,0 +1,33 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:13: syntax error\n/source_0.sv:14: error: Malformed statement\n", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:17: syntax error\n/source_0.sv:17: error: Malformed statement\n/source_0.sv:17: error: Malformed conditional expression.\n/source_0.sv:28: syntax error\n/source_0.sv:28: error: Malformed statement\n/source_0.sv:28: error: Malformed conditional expression.\n", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)" +} diff --git a/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json new file mode 100644 index 00000000000..eabf478fa92 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_scope_enum_randomize_verilator.json @@ -0,0 +1,33 @@ +{ + "cases": [ + { + "category": "Functions", + "detail": "system_functions::scope_randomize_enum_order at 2887:46: assert_eq errors: expected 0x0, got 0x7e", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::scope_randomize_enum_values at 2862:46: assert_eq errors: expected 0x0, got 0x181", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "exclude_stronger_than_sv": false, + "include_ignored": false, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052" +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 9e91a1b7c19..96bafddf611 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -309,6 +309,98 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_domain", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_fill_literals", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_inheritance", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "known_issue": { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "expectation": "Simulation", diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index eacfdc15b69..524ae2cac27 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1619,6 +1619,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "known_issue": { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "known_issue": { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index a026da63bf5..76dc9455d36 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2210,5 +2210,78 @@ "timing::always_star_timed_task_calls_wait_on_folded_branch_reads" ] } + }, + { + "id": "sv_icarus_enum_randomization", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects class randomize, srandom and rand_mode calls in these enum randomization cases. IEEE 1800-2023 18.3, 18.6 and 18.8 define these operations. The original compile diagnostics are retained.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomization_enum_alias", + "class::randomization_enum_domain", + "class::randomization_enum_fill_literals", + "class::randomization_enum_inheritance" + ] + } + }, + { + "id": "sv_verilator_enum_alias_randomization", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_enum_alias" + ] + } + }, + { + "id": "sv_icarus_scope_enum_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 rejects scope randomize and std::randomize calls before simulation. IEEE 1800-2023 18.12 permits randomization of visible scope variables, including enums under 18.3.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "system_functions::scope_randomize_enum_order", + "system_functions::scope_randomize_enum_values" + ] + } + }, + { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "system_functions::scope_randomize_enum_order", + "system_functions::scope_randomize_enum_values" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index a255bf9044d..67802610550 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -190,6 +190,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "expectation": "Simulation", + "name": "class::randomization_enum_alias", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "known_issue": { + "id": "sv_verilator_enum_alias_randomization", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 randomizes an enum typedef alias as its underlying 8-bit integer, producing values outside the declared set {-7, 2, 91}. Generated __VBasicRand assigns a masked VL_RANDOM_RNG_I value instead of selecting from an enum table. IEEE 1800-2023 18.3 restricts enum randomization to declared values; the direct enum and inheritance cases pass unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_enum_randomization_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, { "category": "Types", "expectation": "Simulation", diff --git a/crates/celox-test-suite/verification/sv/verilator/system_functions.json b/crates/celox-test-suite/verification/sv/verilator/system_functions.json index 697545e7c70..93f263f8b17 100644 --- a/crates/celox-test-suite/verification/sv/verilator/system_functions.json +++ b/crates/celox-test-suite/verification/sv/verilator/system_functions.json @@ -920,6 +920,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_order", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "known_issue": { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::scope_randomize_enum_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "known_issue": { + "id": "sv_verilator_scope_enum_randomize", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 scope randomization produces values outside the declared enum domain. Its generated scope helper calls basicStdRandomization with the integer bit width and no enum value table, including for a direct enum variable without a typedef alias. IEEE 1800-2023 18.3 and 18.12 require enum draws to stay in the declared set. Both shared cases retain their original domain assertions.", + "upstream": [], + "evidence": [ + "verification/repros/sv_scope_enum_randomize_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index 17b93891c46..b2c81061d78 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -378,3 +378,13 @@ sv_backends! { assert_eq!(sim.get(sim.signal("errors")), 0u8.into()); } } + +sv_backends! { + fn class_randomization_enum_inheritance(sim) { @case "class::randomization_enum_inheritance"; } + fn class_randomization_enum_alias(sim) { @case "class::randomization_enum_alias"; } + fn class_randomization_enum_domain(sim) { @case "class::randomization_enum_domain"; } +} + +sv_backends! { + fn class_randomization_enum_fill_literals(sim) { @case "class::randomization_enum_fill_literals"; } +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 280d9aebc2f..e8d26fe9cd3 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -3226,3 +3226,66 @@ fn time_format_rejects_string_operands() { ); } } + +sv_backends! { + fn scope_randomize_enum_values(sim) { @case "system_functions::scope_randomize_enum_values"; } + fn scope_randomize_enum_order(sim) { @case "system_functions::scope_randomize_enum_order"; } +} + +sv_backends! { + fn scope_randomize_enum_checkpoint(sim) { + @setup { let source = r#" + module Top(input bit clk, output logic [63:0] value); + typedef enum logic signed [63:0] {NEG=-7, POS=2, ALL='1} E; + E e; + always @(posedge clk) begin + void'(std::randomize(e)); + value = e; + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("enum_checkpoint.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + let saved = sim.checkpoint().unwrap(); + let mut expected = Vec::new(); + for _ in 0..16 { + sim.tick(clk).unwrap(); + let (bits, mask) = sim.get_four_state(value); + assert_eq!(mask, 0u8.into()); + expected.push(bits); + } + assert!(expected.windows(2).any(|pair| pair[0] != pair[1])); + sim.restore(&saved).unwrap(); + for bits in expected { + sim.tick(clk).unwrap(); + assert_eq!(sim.get_four_state(value), (bits, 0u8.into())); + } + } +} + +sv_backends! { + fn scope_randomize_enum_retries_rejected_draw(sim) { + @setup { let source = r#" + module Top(output bit done, output int unsigned next); + typedef enum bit [7:0] {A=3, B=19, C=97} E; + E e; + int ignored; + initial begin + // The process LCG reaches zero on the next draw. Its + // bijective mixer preserves zero, rejected for 3 choices. + ignored = $urandom(32'd4150723358); + ignored = std::randomize(e); + next = $urandom(); + done = 1; + end + endmodule + "#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("enum_rejection.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("done")), 1u8.into()); + // Rejection consumes zero, then 1013904223, leaving the following + // LCG value for the explicit $urandom call. + assert_eq!(sim.get(sim.signal("next")), 1196435762u32.into()); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 8daa10c3303..4e45062ed5c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -104,14 +104,22 @@ variable or advancing the random stream. Calls follow procedural statement order and short-circuit evaluation, and use the calling process's persistent random stream (IEEE 1800-2023 18.12). -Constraints (`with`), enum variables, unpacked arrays, nets, +Scalar enums up to 64 bits are also supported: randomization selects only their +known declared values, including typedef aliases and signed or sparse values. +The process random stream, short-circuit behavior, and checkpoint state apply +to enums as well. Mixed enum and integer argument lists are supported. + +Constraints (`with`), enums with unsupported or unresolved domains, unpacked arrays, nets, constants, selects and concatenation arguments are unsupported and rejected. ### Class randomization `object.randomize()` randomizes enabled `rand` properties and returns signed -`int` value `1`. Supported properties are 2-state, non-enum integral values up -to 64 bits in classes without constraints. Inherited properties are included, +`int` value `1`. Supported properties are 2-state integral values, including scalar enums, up +to 64 bits in classes without constraints. Enum randomization selects uniformly +from the declared values, including sparse and negative values (18.3, 18.4.1). +Enums with unresolved or X/Z values and ranged enumerator declarations remain +unsupported for randomization. Inherited properties are included, and a call through a base handle uses the dynamic object's class and its `pre_randomize()` / `post_randomize()` hooks. A derived hook replaces the base hook; call `super.pre_randomize()` or `super.post_randomize()` explicitly to @@ -137,7 +145,7 @@ Each object has an independent random stream, seeded from its creating process. `object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve both RNG and mode state (18.13.3, 18.14.3). Random sequences are implementation-specific. `randc` randomization, constraints, `with`, static random properties, and random -enum/array/object/string properties remain unsupported. A constrained dynamic +array/object/string properties remain unsupported. A constrained dynamic subclass is rejected rather than silently randomizing only its base properties. A call through `null` is a runtime error. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index cf956ea3325..29a9a0e11d3 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -93,13 +93,19 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task プロセスごとの永続的な乱数列を使い、文の実行順序と短絡評価に従います (IEEE 1800-2023 18.12)。 -`with` 制約、enum 変数、unpacked 配列、net、定数、 +64ビット以下のスカラーenumにも対応し、既知の宣言値だけから抽選します。 +型エイリアス、負数、飛び飛びの値、整数との引数混在を扱えます。enumにもプロセス単位の +乱数列・短絡評価・チェックポイント復元が適用されます。 + +`with` 制約、値域が未対応または未解決のenum、unpacked 配列、net、定数、 select・連結式の引数は未対応として拒否します。 ### クラスの乱数化 `object.randomize()` は有効な `rand` プロパティを乱数化し、成功値の1(signed `int`)を返します。 -制約のないクラスで、64ビット以下の2値・非enum整数型に対応します。 +制約のないクラスで、スカラーenumを含む64ビット以下の2値整数型に対応します。 +enumは宣言された値だけから均等に抽選し、飛び飛びの値や負数にも対応します(18.3、18.4.1)。 +値が未解決またはX/Zを含むenum、列挙子の範囲指定は乱数化に未対応です。 継承したプロパティも対象になり、基底型のハンドルを通した呼び出しでも、実際のオブジェクトの クラスと `pre_randomize()` / `post_randomize()` を使います。子クラスでフックを定義すると 親のフックを置き換えるため、親の処理も必要なら `super.pre_randomize()` などを明示的に呼びます @@ -120,7 +126,7 @@ select・連結式の引数は未対応として拒否します。 オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します (18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 -`randc` の乱数化、制約、`with`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の +`randc` の乱数化、制約、`with`、staticな乱数プロパティ、配列・オブジェクト・文字列の 乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 `null` を通した呼び出しは実行時エラーです。