diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 7b61af634ae..ca7fdc2114e 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(), 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..7fd131f1d42 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -350,6 +350,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, 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..17b50ff3c53 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -233,7 +233,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 { @@ -756,9 +756,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; 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/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/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index f3eee42895d..47aeab7cdd8 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -115,6 +115,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/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 94015a571ce..81a99a92a65 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6610,7 +6610,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 +6682,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..8e44294ee77 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -696,6 +696,19 @@ 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. + ## 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/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/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/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index a026da63bf5..f4839f22972 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2210,5 +2210,42 @@ "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" + ] + } } ] 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/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/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 8daa10c3303..c765062dd74 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -110,8 +110,11 @@ 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 +140,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..46185c6b8c8 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -99,7 +99,9 @@ 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 +122,7 @@ select・連結式の引数は未対応として拒否します。 オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します (18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 -`randc` の乱数化、制約、`with`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の +`randc` の乱数化、制約、`with`、staticな乱数プロパティ、配列・オブジェクト・文字列の 乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 `null` を通した呼び出しは実行時エラーです。