From ea71f9682a7121b0b551c45d4028a331d347ce57 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 03:01:41 +0900 Subject: [PATCH] feat(sv)!: support unconstrained class randomization Calling object.randomize() randomizes 2-state, non-enum integral rand properties up to 64 bits and returns signed int success. Invoke pre_randomize and post_randomize around updates, preserve non-rand properties, and support srandom(seed) with independent per-object random streams seeded by the creating process. Register constructor seeding as a process RNG consumer before computing FF state targets, so checkpoint/restore replays object seeds from edge-triggered processes. Reject invalid receivers before hooks, random draws or property writes: a null or mismatched runtime class records a runtime fault and returns failure without those side effects. Retain rand/randc and constraint metadata so unsupported randomization is rejected explicitly. Constraints, randc, static random properties, randomize argument lists, non-integral random properties and inheritance remain outside this first subset. Preserve master's static properties, constructor chaining, virtual methods and interface classes when integrating this subset. Differential scheduler checks compare live class objects, including RNG state and future object allocation handles, so divergent random draws are detected before a subsequent property update. Add portable shared cases, backend and rejection regressions, and English/Japanese reference documentation. Record Icarus 13.0's missing randomize/srandom methods with original compile diagnostics and exact case exclusions. Validation on master d7bb5a329: - Reproduced the constructor checkpoint mismatch and rejected-receiver property mutation on all four applicable backend variants before their fixes. - Class integration tests: 110 passed, including checkpoint replay, null receiver hooks and base-handle mutation guards. - Existing urandom integration tests: 81 passed. - Syntax, analyzer, heap and SV frontend unit tests: 931 passed, 3 existing ignores. - Retained-report consistency tests: 3 passed. - NAPI debug build and JS tests: 432 passed across 15 files. - Formatting, diff checks and Clippy for the four changed implementation crates and SystemVerilog integration target. - Shared executable cases and external adapters are unchanged from their earlier validation: Verilator randomize filter passed 4 cases; Icarus rejected the two class cases for unsupported methods, recorded as limitations rather than passes. Additional P2 validation: heap tests (16), differential scheduler tests (5), and class integration tests in differential mode (110) pass. New tests reproduce RNG-only and object-content comparison omissions before the fix. Heap and Celox Clippy, formatting and diff checks pass. BREAKING CHANGE: Public SystemVerilog syntax structs gain constraint/randc metadata, and ObjectOp and heap Fault gain enum variants. Downstream struct literals and exhaustive matches must be updated. Change-Id: If4e53d32f02e495546c1154f9f0aad3897e71e9b --- crates/celox-frontend-sv/src/lowering/ff.rs | 6 + .../src/lowering/ff/objects.rs | 26 +++- crates/celox-heap/src/lib.rs | 36 +++++- crates/celox-heap/src/objects.rs | 68 +++++++++- crates/celox-heap/src/ops.rs | 13 ++ crates/celox-sv-analyzer/src/ast/classes.rs | 56 ++++++++ .../src/ast/dimensions/discovery.rs | 27 ++++ .../src/ast/expression_binding/direct.rs | 5 +- .../src/ast/expression_binding/objects.rs | 17 +++ .../celox-sv-analyzer/src/ast/procedural.rs | 26 ++++ .../src/ast/procedural/randomization.rs | 115 +++++++++++++++++ .../celox-sv-analyzer/src/system_functions.rs | 12 ++ crates/celox-sv-analyzer/src/tests.rs | 53 ++++++++ crates/celox-sv-syntax/src/nodes.rs | 3 + crates/celox-sv-syntax/src/parser/classes.rs | 4 +- .../celox-sv-syntax/src/parser/constraints.rs | 3 + crates/celox-sv-syntax/src/parser/tests.rs | 13 ++ crates/celox-test-suite/LIMITATIONS.md | 6 + .../celox-test-suite/src/sv/cases/class.vtest | 79 ++++++++++++ .../repros/sv_class_randomize_icarus.json | 31 +++++ .../verification/sv/icarus/class.json | 46 +++++++ .../verification/sv/limitations.json | 18 +++ crates/celox/src/simulation/differential.rs | 38 +++++- .../tests/frontends/systemverilog/class.rs | 121 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 19 ++- docs/ja/guide/systemverilog-reference.md | 17 ++- 26 files changed, 849 insertions(+), 9 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/procedural/randomization.rs create mode 100644 crates/celox-test-suite/verification/repros/sv_class_randomize_icarus.json diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 2784a824630..ad0ca48546b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -273,6 +273,12 @@ impl<'p, 'a> Ff<'p, 'a> { } continue; } + sv::ir::Callee::Object(op) if matches!(*op, sv::ir::ObjectOp::New { .. }) => { + // Constructor seeding consumes the process RNG. Register it + // before lower_process freezes the persistent target ranges. + self.urandom_state(); + continue; + } sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index 4ea69cf98bb..5dcfc5feaa7 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -32,6 +32,11 @@ impl Ff<'_, '_> { let size = self.constant64(u64::from(*size)); let object = self.heap_call(ops::encode(ops::OBJECT_NEW, u64::from(*class)), &[size]); + // Object seeding consumes the creating process's RNG once, + // before the constructor body (IEEE 1800-2023 18.14.3). + let seed = self.urandom(None)?; + let seed = self.integer_of_width(&seed, 32, false)?; + self.heap_call(ops::OBJECT_SEED, &[object, seed]); for &(offset, kind) in handles { let offset = self.constant64(u64::from(offset)); let kind = self.constant64(match kind { @@ -55,6 +60,21 @@ impl Ff<'_, '_> { let value = self.integer_of_width(&args[1], field.width as usize, field.signed)?; self.heap_call(ops::OBJECT_STORE, &[object, place, value]) } + ObjectOp::Random | ObjectOp::Check(_) => { + let object = self.handle(&args[0])?; + self.heap_call( + match op { + ObjectOp::Check(class) => ops::encode(ops::OBJECT_CHECK, u64::from(*class)), + _ => ops::OBJECT_RANDOM, + }, + &[object], + ) + } + ObjectOp::Seed => { + let object = self.handle(&args[0])?; + let seed = self.integer_of_width(&args[1], 32, false)?; + self.heap_call(ops::OBJECT_SEED, &[object, seed]) + } ObjectOp::ClassOf => { let object = self.handle(&args[0])?; self.heap_call(ops::OBJECT_CLASS, &[object]) @@ -70,7 +90,11 @@ impl Ff<'_, '_> { HandleProperty::String => celox_design::ValueKind::StrRef, HandleProperty::Object => celox_design::ValueKind::ObjRef, }), - ObjectOp::Store(_) | ObjectOp::ClassOf => None, + ObjectOp::Store(_) + | ObjectOp::ClassOf + | ObjectOp::Random + | ObjectOp::Seed + | ObjectOp::Check(_) => None, }; if let Some(kind) = kind { self.m.variables.get_mut(&temp).unwrap().value_kind = kind; diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index 644e75b2a20..b138661edd8 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -150,14 +150,17 @@ impl Heap { self.strings.contains_key(&handle) } - /// Whether `other` holds the same strings under the same handles, the - /// same strings under construction, and names new strings alike. + /// Whether `other` holds the same strings and objects under the same + /// handles, including object RNG state and strings under construction, + /// and assigns the same handles to future allocations. pub fn same_contents(&self, other: &Heap) -> bool { self.strings == other.strings && self.next == other.next && self.buffers == other.buffers && self.free_buffers == other.free_buffers && self.pinned == other.pinned + && self.objects == other.objects + && self.next_object == other.next_object } /// The number of live strings, including `""`. @@ -261,6 +264,35 @@ impl Heap { mod tests { use super::*; + #[test] + fn comparison_detects_object_rng_divergence_before_a_property_write() { + let mut heap = Heap::new(); + let object = heap.new_object(7, 8); + heap.seed_object(object, 42); + let mut other = heap.clone(); + assert!(heap.same_contents(&other)); + let drawn = other.random_object(object); + assert_eq!(heap.load(object, 0, 8), other.load(object, 0, 8)); + assert!(!heap.same_contents(&other)); + assert_eq!(heap.random_object(object), drawn); + assert!(heap.same_contents(&other)); + } + + #[test] + fn comparison_detects_object_contents_and_allocation_state() { + let mut heap = Heap::new(); + let object = heap.new_object(7, 8); + let mut other = heap.clone(); + other.store(object, 0, 8, 99); + assert!(!heap.same_contents(&other)); + heap.store(object, 0, 8, 99); + assert!(heap.same_contents(&other)); + other.new_object(7, 8); + other.collect([Root::object(object)]); + // The same live object remains, but future allocation handles differ. + assert!(!heap.same_contents(&other)); + } + #[test] fn interning_gives_equal_contents_equal_handles() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index 112083a86af..6913e0ccce7 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -11,9 +11,10 @@ use crate::{Handle, HandleKind, Heap}; /// The handle of `null`, the value of zero-initialized memory. pub const NULL: Handle = 0; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Object { class: u32, + random_state: u64, bytes: Box<[u8]>, /// Byte offsets of the handle properties, with what they refer to. pub(crate) handles: Vec<(u32, HandleKind)>, @@ -32,12 +33,17 @@ pub enum Fault { /// A property access or method call through `null` or a handle of no /// live object (IEEE 1800-2023 8.4). NullDereference, + /// The first randomization subset does not implement virtual dispatch. + RandomizationClassMismatch, } impl std::fmt::Display for Fault { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::NullDereference => f.write_str("null object handle dereferenced"), + Self::RandomizationClassMismatch => { + f.write_str("class randomization through a base handle is unsupported") + } } } } @@ -53,6 +59,7 @@ impl Heap { handle, Object { class, + random_state: 0, bytes: vec![0; size].into(), handles: Vec::new(), }, @@ -61,6 +68,37 @@ impl Heap { handle } + /// Seed an object's independent random stream (IEEE 1800-2023 18.13.3). + pub fn seed_object(&mut self, handle: Handle, seed: u32) { + if let Some(object) = self.object_mut(handle) { + object.random_state = u64::from(seed); + } + } + + /// SplitMix64: a full-period state transition with a bijective output + /// permutation, including seed zero. The language does not fix the RNG. + pub fn random_object(&mut self, handle: Handle) -> u64 { + let Some(object) = self.object_mut(handle) else { + return 0; + }; + object.random_state = object.random_state.wrapping_add(0x9e3779b97f4a7c15); + let mut word = object.random_state; + word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb); + word ^ (word >> 31) + } + + pub(crate) fn check_object(&mut self, handle: Handle, class: u32) -> bool { + let Some(object) = self.object_mut(handle) else { + return false; + }; + if class != 0 && object.class != class { + self.fault.get_or_insert(Fault::RandomizationClassMismatch); + return false; + } + true + } + /// Declare that the property of `object` at byte `offset` holds a handle /// of `kind`. pub fn declare_handle(&mut self, object: Handle, offset: u32, kind: HandleKind) { @@ -183,3 +221,31 @@ mod tests { assert!(!heap.contains(text)); } } + +#[cfg(test)] +mod random_tests { + use super::*; + + #[test] + fn random_streams_are_independent_and_checkpointed() { + let mut heap = Heap::new(); + let a = heap.new_object(1, 1); + let b = heap.new_object(1, 1); + heap.seed_object(a, 0); + heap.seed_object(b, 0); + let first = heap.random_object(a); + for _ in 0..10 { + heap.random_object(a); + } + assert_eq!(first, heap.random_object(b)); + heap.seed_object(a, 0); + assert_eq!(first, heap.random_object(a)); + let mut snapshot = heap.clone(); + for _ in 0..20 { + assert_eq!(heap.random_object(a), snapshot.random_object(a)); + } + assert_eq!(heap.take_fault(), None); + heap.random_object(NULL); + assert_eq!(heap.take_fault(), Some(Fault::NullDereference)); + } +} diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index e8680035a1f..705b4e71051 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -61,6 +61,13 @@ pub const OBJECT_LOAD: u64 = 50; pub const OBJECT_STORE: u64 = 51; /// `class_of(object)`: its class, or 0 for `null`. pub const OBJECT_CLASS: u64 = 52; +/// `random(object)`: 64 random bits from the object's RNG. +pub const OBJECT_RANDOM: u64 = 53; +/// `seed(object, seed)`: reset the object's RNG using the low 32 bits. +pub const OBJECT_SEED: u64 = 54; +/// `check(object)`: record a fault for an invalid receiver or, when the +/// parameter is nonzero, a different runtime class. Return 1 on success, 0 on failure. +pub const OBJECT_CHECK: u64 = 55; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -168,6 +175,12 @@ impl Heap { 0 } OBJECT_CLASS => self.class_of(a as Handle).into(), + OBJECT_RANDOM => self.random_object(a as Handle), + OBJECT_SEED => { + self.seed_object(a as Handle, b as u32); + 0 + } + OBJECT_CHECK => u64::from(self.check_object(a as Handle, parameter as u32)), other => panic!("unknown heap operation {other}"), } } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index aea08638043..d79431329a3 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -24,6 +24,8 @@ pub(super) struct Property { pub name: String, pub r#type: Type, pub field: ObjectField, + pub rand: bool, + pub randc: bool, /// The initializer of the declaration, evaluated by the constructor. pub initializer: Option, } @@ -88,9 +90,45 @@ pub(super) struct Class { pub methods: Vec, /// Bytes of an object. pub size: u32, + pub has_constraints: bool, } impl Class { + /// Validate the supported unconstrained subset before binding a call. + pub fn check_randomize(&self, tree: &AnalysisContext<'_>) -> Converted<()> { + if self.has_constraints { + return Err(unsupported("class randomize with constraints")); + } + if self.base.is_some() { + return Err(unsupported("class randomize with inheritance")); + } + for property in &self.properties { + if property.randc { + return Err(unsupported("class randomize with randc properties")); + } + if property.rand && (property.field.handle.is_some() || property.r#type.is_enum) { + return Err(unsupported( + "class randomize requires integral non-enum rand properties", + )); + } + } + for hook in ["pre_randomize", "post_randomize"] { + if let Some(method) = self.method(hook) { + let native = tree.declarations().subroutine(method.native); + if native.kind != celox_sv_syntax::SubroutineKind::Function + || native.ports.as_ref().is_some_and(|ports| !ports.is_empty()) + || method.qualifiers.is_static + || method.qualifiers.is_virtual + { + return Err(unsupported( + "randomization hooks require non-static, non-virtual functions without arguments", + )); + } + } + } + Ok(()) + } + /// The property `name`; one the class declares hides one of a base /// (IEEE 1800-2023 8.14). pub fn property(&self, name: &str) -> Option<&Property> { @@ -358,6 +396,14 @@ pub(super) fn class( .unwrap_or_default(); let mut size = base.as_ref().map_or(0, |base| base.size); for property in &declaration.properties { + if property.declaration.constant && (property.qualifiers.rand || property.qualifiers.randc) + { + return Err(unsupported("const random class property")); + } + if property.qualifiers.is_static && (property.qualifiers.rand || property.qualifiers.randc) + { + return Err(unsupported("static random class property")); + } let ty = type_binding::procedural_type( property.declaration.data_type, native, @@ -389,6 +435,8 @@ pub(super) fn class( name, r#type: ty.clone(), field, + rand: property.qualifiers.rand, + randc: property.qualifiers.randc, initializer: variable.value, }); } @@ -403,6 +451,11 @@ pub(super) fn class( for method in &declaration.methods { let subroutine = native.subroutine(method.subroutine); let method_name = instances::normalize_identifier(&subroutine.name.spelling); + if matches!(method_name.as_str(), "randomize" | "srandom") { + return Err(unsupported( + "overriding built-in class randomization methods", + )); + } // A method overriding a virtual method is virtual (8.20). let is_virtual = method.qualifiers.is_virtual || methods @@ -477,6 +530,8 @@ pub(super) fn class( let class = Rc::new(Class { name: name.to_owned(), id: class_id(name), + has_constraints: declaration.has_constraints + || base.as_ref().is_some_and(|base| base.has_constraints), base: base.map(|base| base.name.clone()), interfaces, is_abstract: declaration.virtual_class, @@ -561,6 +616,7 @@ fn interface_class( interfaces, is_abstract: true, is_interface: true, + has_constraints: false, properties: Vec::new(), base_properties: 0, statics: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index f7adf4d54f9..8b8d05203f3 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -469,6 +469,33 @@ fn class_signatures( context, ); } + for method in ["randomize", "srandom"] { + let mut formals = vec![( + FunctionArgumentMetadata { + name: classes::THIS.into(), + direction: ParamDirection::Input, + has_default: false, + }, + handle.clone(), + )]; + if method == "srandom" { + formals.push(( + FunctionArgumentMetadata { + name: "seed".into(), + direction: ParamDirection::Input, + has_default: false, + }, + procedural::int_type(), + )); + } + publish_signature( + classes::Class::subroutine_name(&class_name, method), + formals, + Some((method == "randomize").then(procedural::int_type)), + tree, + context, + ); + } if !constructor && !class.interface { publish_signature( classes::Class::subroutine_name(&class_name, "new"), 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 353394f99bd..5927fa59761 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -413,7 +413,10 @@ pub(in crate::ast) fn bind_value( let (name, formals, receiver) = objects::method(tree, *expression, native, dimensions)? .expect("checked by the guard"); - if args.len() > formals || args.iter().any(|arg| arg.name.is_some()) { + if args.len() > formals + || (name.ends_with("::srandom") && args.len() != 1) + || args.iter().any(|arg| arg.name.is_some()) + { return Err(unsupported(format!("arguments of method `{name}`"))); } let mut children = Vec::new(); 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 41b00e548c0..7d46726b339 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -280,6 +280,23 @@ pub(in crate::ast) fn method( )), }; } + if matches!(method_name.as_str(), "randomize" | "srandom") { + if receiver == Receiver::Static + || (receiver == Receiver::This && dimensions.get(THIS).is_none()) + { + return Err(unsupported( + "class randomization requires an object receiver", + )); + } + if method_name == "randomize" { + class.check_randomize(tree)?; + } + return Ok(Some(( + Class::subroutine_name(&class_name, &method_name), + usize::from(method_name == "srandom"), + receiver, + ))); + } let Some(method) = class.method(&method_name) else { return Ok(None); }; diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index f749276459d..986643713f1 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -10,6 +10,7 @@ use super::*; mod assertions; mod control; mod foreach; +mod randomization; pub(super) mod timed_tasks; mod timing; use crate::procedural::{ @@ -727,6 +728,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } expression_binding::ObjectReceiver::Static => Vec::new(), }; + if name.ends_with("::srandom") { + return Err(unsupported("srandom requires a seed argument")); + } args.resize( formals + usize::from(receiver != expression_binding::ObjectReceiver::Static), None, @@ -1627,6 +1631,21 @@ pub(super) fn subroutine_argument_names( params.into_iter().map(|(name, ..)| name).collect(), ); } + for method in ["randomize", "srandom"] { + let qualified = item.name(&classes::Class::subroutine_name(&class, method)); + let mut param_names = vec![classes::THIS.to_owned()]; + let mut param_shapes = vec![dimensions_from_type(&handle)]; + if method == "srandom" { + param_names.push("seed".into()); + param_shapes.push(dimensions_from_type(&int_type())); + } + directions.insert( + qualified.clone(), + vec![ParamDirection::Input; param_names.len()], + ); + shapes.insert(qualified.clone(), param_shapes); + names.insert(qualified, param_names); + } let handle = dimensions_from_type(&scoped_type(handle, &item.env)); if !constructor && !layout.is_some_and(|layout| layout.is_interface) { let qualified = item.name(&classes::Class::subroutine_name(&class, "new")); @@ -2444,6 +2463,13 @@ fn lower_class( state, item, )?); + subroutines.extend(randomization::lower( + &class, + tree, + item_dimensions, + state, + item, + )?); Ok(subroutines) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs new file mode 100644 index 00000000000..65201af5f5f --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -0,0 +1,115 @@ +//! Built-in class randomization methods (IEEE 1800-2023 18.6, 18.13.3). +use super::*; +use crate::system_functions::ObjectOp; + +/// Generate ordinary automatic subroutines so hooks and property updates use +/// the same call machinery as authored class methods. Unsupported randomization +/// is diagnosed at the call site, rather than rejecting an unused class. +pub(super) fn lower( + class: &classes::Class, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + state: &mut BodyState<'_>, + item: &generate::Item, +) -> Converted> { + let handle = classes::handle_type(tree, &class.name) + .ok_or_else(|| unsupported("class randomization receiver"))?; + let convert_type = |ty| { + crate::ir::Type::from_ast( + ty, + &const_functions::Environment { + constants: &*item.env, + functions: &tree.state.const_functions, + }, + ) + }; + let mut result = Vec::new(); + for method in ["randomize", "srandom"] { + if method == "randomize" && class.check_randomize(tree).is_err() { + continue; + } + let mut builder = + BodyBuilder::new(tree, dimensions, state, system_functions::Body::Subroutine); + builder.automatic = true; + let first_local = builder.state.locals.len(); + let this = builder.declare(classes::THIS, handle.clone()); + let mut params = vec![SubroutineParam { + name: this.clone(), + source_name: classes::THIS.into(), + direction: ParamDirection::Input, + r#type: convert_type(handle.clone()), + default: None, + }]; + // Heap faults are reported after the kernel completes. Return now so + // a rejected receiver cannot run hooks or mutate the object's state. + let mut body = vec![Stmt::If { + condition: classes::object_call( + ObjectOp::Check(if method == "randomize" { class.id } else { 0 }), + vec![Expr::Ident(this.clone())], + ), + then_body: Vec::new(), + else_body: vec![Stmt::Return( + (method == "randomize").then(|| Expr::Literal("32'sd0".into())), + )], + }]; + let return_var = if method == "srandom" { + let seed = builder.declare("seed", int_type()); + params.push(SubroutineParam { + name: seed.clone(), + source_name: "seed".into(), + direction: ParamDirection::Input, + r#type: convert_type(int_type()), + default: None, + }); + body.push(Stmt::Eval(classes::object_call( + ObjectOp::Seed, + vec![Expr::Ident(this.clone()), Expr::Ident(seed)], + ))); + None + } else { + let hook = |name| { + class.method(name).map(|method| Stmt::Call { + name: classes::Class::subroutine_name(&method.owner, &method.name), + args: vec![Some(Expr::Ident(this.clone()))], + arg_order: Vec::new(), + }) + }; + body.extend(hook("pre_randomize")); + for property in class.properties.iter().filter(|property| property.rand) { + body.push(Stmt::Eval(classes::object_call( + ObjectOp::Store(property.field), + vec![ + Expr::Ident(this.clone()), + classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.clone())]), + ], + ))); + } + body.extend(hook("post_randomize")); + let returned = builder.declare("randomize", int_type()); + body.push(Stmt::Assign { + lhs: LValue::Ident(returned.clone()), + rhs: Expr::Literal("32'sd1".into()), + nonblocking: false, + }); + Some(returned) + }; + for stmt in &mut body { + qualify_stmt(item, stmt); + } + result.push(Subroutine { + name: item.name(&classes::Class::subroutine_name(&class.name, method)), + is_task: false, + automatic_locals: builder.state.locals[first_local..] + .iter() + .map(|local| local.name.clone()) + .collect(), + persistent_locals: Vec::new(), + return_type: return_var.as_ref().map(|_| convert_type(int_type())), + params, + return_var, + body, + sensitivity_body: Vec::new(), + }); + } + Ok(result) +} diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 4418f7f1ab5..d1536006fcc 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -786,12 +786,21 @@ pub enum ObjectOp { Store(ObjectField), /// The run-time class of the object in the argument, 0 for `null`. ClassOf, + /// Advance the object's independent RNG, returning 64 random bits. + Random, + /// Seed the object's RNG from the second argument. + Seed, + /// Validate a receiver; a nonzero class also rejects unsupported dynamic + /// dispatch through a base handle before randomizing its properties. + Check(u32), } impl ObjectOp { /// The width and signedness of the result. pub fn result_type(&self) -> (usize, bool) { match self { + Self::Random => (64, false), + Self::Seed | Self::Check(_) => (32, false), Self::Load(field) => (field.width as usize, field.signed), Self::New { .. } | Self::ClassOf | Self::Store(_) => (32, false), } @@ -805,6 +814,9 @@ impl fmt::Display for ObjectOp { Self::Load(_) => "property read", Self::Store(_) => "property write", Self::ClassOf => "class query", + Self::Random => "object random bits", + Self::Seed => "object random seed", + Self::Check(_) => "object receiver check", }) } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index c08bf462526..774258ff613 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6564,3 +6564,56 @@ fn explicit_output_data_types_default_to_variables() { assert!(ports[3].is_net()); assert!(ports[4].is_net()); } + +#[test] +fn class_randomize_rejects_unsupported_semantics() { + for (members, call, expected) in [ + ( + "rand int x; constraint c { x == 1; }", + "c.randomize()", + "constraints", + ), + ("randc bit [1:0] x;", "c.randomize()", "randc"), + ("rand int x;", "c.srandom()", "argument"), + ("rand int x;", "c.srandom(1, 2)", "arguments"), + ( + "rand int x; extern constraint c;", + "c.randomize()", + "constraints", + ), + ("rand const int x;", "c.randomize()", "const"), + ("static rand int x;", "c.randomize()", "static random"), + ("rand int x;", "C::randomize()", "object receiver"), + ("rand int x;", "C::srandom(1)", "object receiver"), + ( + "static function int f(); return randomize(); endfunction", + "c.f()", + "object receiver", + ), + ("rand string x;", "c.randomize()", "integral non-enum"), + ( + "rand int x;", + "c.randomize() with { x == 1; }", + "unsupported", + ), + ("rand int x;", "c.randomize(x)", "arguments"), + ( + "rand int x; function void pre_randomize(int arg); endfunction", + "c.randomize()", + "hooks", + ), + ( + "function int randomize(); return 1; endfunction", + "c.randomize()", + "overriding", + ), + ] { + let source = format!( + "module Top; class C; {members} endclass C c; initial begin c = new; void'({call}); end endmodule" + ); + let error = analyze_source(&source, Path::new("randomize_unsupported.sv")) + .unwrap_err() + .to_string(); + assert!(error.to_lowercase().contains(expected), "{source}: {error}"); + } +} diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index e72c9d6fcee..b52c7abebc2 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -957,6 +957,8 @@ pub struct ClassDeclaration { /// The interface classes of `implements`, or those an interface class /// extends (8.26). pub interfaces: Vec, + /// Whether the class declares constraints, including prototypes. + pub has_constraints: bool, pub properties: Vec, pub methods: Vec, pub tokens: TokenRange, @@ -980,6 +982,7 @@ pub struct ClassQualifiers { pub local: bool, pub protected: bool, pub rand: bool, + pub randc: bool, } /// A property declaration of a class. diff --git a/crates/celox-sv-syntax/src/parser/classes.rs b/crates/celox-sv-syntax/src/parser/classes.rs index e9ea1f3df5f..821fed8c460 100644 --- a/crates/celox-sv-syntax/src/parser/classes.rs +++ b/crates/celox-sv-syntax/src/parser/classes.rs @@ -91,7 +91,8 @@ impl Parser<'_> { "extern" => &mut qualifiers.is_extern, "local" => &mut qualifiers.local, "protected" => &mut qualifiers.protected, - "rand" | "randc" => &mut qualifiers.rand, + "rand" => &mut qualifiers.rand, + "randc" => &mut qualifiers.randc, _ => return false, }; *flag = true; @@ -206,6 +207,7 @@ impl Parser<'_> { interface, base, interfaces, + has_constraints: false, properties: Vec::new(), methods: Vec::new(), tokens: TokenRange { start, end: start }, diff --git a/crates/celox-sv-syntax/src/parser/constraints.rs b/crates/celox-sv-syntax/src/parser/constraints.rs index 0c8b81cc54d..3dcdfc0bbc4 100644 --- a/crates/celox-sv-syntax/src/parser/constraints.rs +++ b/crates/celox-sv-syntax/src/parser/constraints.rs @@ -28,6 +28,9 @@ impl Parser<'_> { } pub(super) fn class_constraint(&mut self) -> Result<()> { + if let Some(class) = self.class_stack.last_mut() { + class.has_constraints = true; + } let prototype = self.eat("extern") || self.eat("pure"); self.eat("static"); self.expect("constraint")?; diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index f5aea670507..d66393e16f5 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2786,3 +2786,16 @@ fn class_declarations_record_names_bases_properties_and_method_qualifiers() { ); } } + +#[test] +fn class_random_qualifiers_and_constraints_are_preserved() { + let syntax = parse( + "class C; rand bit x; randc bit y; extern constraint limits; endclass module M; endmodule", + ); + let class = &syntax.classes[0]; + assert!(class.has_constraints); + assert!(class.properties[0].qualifiers.rand); + assert!(!class.properties[0].qualifiers.randc); + assert!(class.properties[1].qualifiers.randc); + assert!(!class.properties[1].qualifiers.rand); +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 99270bee0a2..05957bd608e 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -577,6 +577,12 @@ interface. Verilator 5.052 executes the same emitted Veryl design successfully. The [retained diagnostic](verification/repros/interface_nested_icarus.json) records this compile limitation. +Class randomization (`sv_icarus_class_randomize`) excludes the two cases +`class::unconstrained_randomize` and `class::randomize_without_rand_members` +from Icarus 13.0. It rejects the built-in `randomize` and `srandom` methods +during elaboration; [the original diagnostics](verification/repros/sv_class_randomize_icarus.json) +remain available. Both cases pass Verilator and Celox. + ## Veryl analyzer floating-point constant expressions Veryl analyzer 0.22 can fold negative `f32` casts and dependent floating-point diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 9aec1add777..a3bb34bf77c 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -711,3 +711,82 @@ endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (expect_output "1 8\n1 1\n0 8\n")) + +(case unconstrained_randomize + (source "randomize.sv" #" +module Top(output bit done, output int errors); + class Sample; + rand bit flag; + rand bit signed [6:0] narrow; + rand bit [63:0] wide; + int untouched = 42; + int phase; + bit [63:0] observed; + function void pre_randomize(); + if (phase != 0) untouched = -1; + phase = 1; + endfunction + function void post_randomize(); + if (phase != 1) untouched = -2; + observed = wide; + phase = 0; + endfunction + function int again(); + return randomize(); + endfunction + endclass + Sample a, b, alias_a; + bit [63:0] saved, changed; + bit saved_flag; + bit signed [6:0] saved_small; + int ignored; + initial begin + a = new; + b = new; + alias_a = a; + a.srandom(0); + if (a.randomize() != 1) errors++; + saved = a.wide; + saved_flag = a.flag; + saved_small = a.narrow; + if (a.observed != saved || a.untouched != 42 || a.phase != 0) errors++; + changed = 0; + repeat (12) begin + if (a.again() != 1) errors++; + changed |= saved ^ a.wide; + end + if (changed[63:32] == 0 || changed[31:0] == 0) errors++; + alias_a.srandom(0); + repeat (5) begin + ignored = $urandom; + ignored = b.randomize(); + end + if (a.randomize() != 1) errors++; + if (a.wide != saved || a.flag != saved_flag || a.narrow != saved_small) errors++; + if (a.observed != saved || a.untouched != 42 || a.phase != 0) errors++; + b.srandom(0); + if (b.randomize() != 1 || b.wide != saved) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomize_without_rand_members + (source "randomize_empty.sv" #" +module Top(output bit done, output int errors); + class Empty; + int value = 5; + function void pre_randomize(); value += 1; endfunction + function void post_randomize(); value *= 2; endfunction + endclass + Empty object; + initial begin + object = new; + if (object.randomize() != 1 || object.value != 12) errors++; + if (object.randomize() != 1 || object.value != 26) errors++; + 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_class_randomize_icarus.json b/crates/celox-test-suite/verification/repros/sv_class_randomize_icarus.json new file mode 100644 index 00000000000..653f13b2791 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_class_randomize_icarus.json @@ -0,0 +1,31 @@ +{ + "schema_version": 3, + "suite": "sv", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:11: Error: randomize is not a method of class Empty.\n/source_0.sv:11: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:11: error: Unable to elaborate condition expression.\n/source_0.sv:12: Error: randomize is not a method of class Empty.\n/source_0.sv:12: error: Object celox_suite_tb.dut.object has no method \"randomize(...)\".\n/source_0.sv:12: error: Unable to elaborate condition expression.\n6 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomize_without_rand_members", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 18; see /build.log\n/source_0.sv:20: error: No function named `randomize' found in this context (celox_suite_tb.dut.Sample.again).\n/source_0.sv:32: error: Can't find task srandom in class Sample\n/source_0.sv:32: error: Enable of unknown task ``a.srandom''.\n/source_0.sv:33: Error: randomize is not a method of class Sample.\n/source_0.sv:33: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:33: error: Unable to elaborate condition expression.\n/source_0.sv:44: error: Can't find task srandom in class Sample\n/source_0.sv:44: error: Enable of unknown task ``alias_a.srandom''.\n/source_0.sv:47: Error: randomize is not a method of class Sample.\n/source_0.sv:47: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:49: Error: randomize is not a method of class Sample.\n/source_0.sv:49: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:49: error: Unable to elaborate condition expression.\n/source_0.sv:52: error: Can't find task srandom in class Sample\n/source_0.sv:52: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:53: Error: randomize is not a method of class Sample.\n/source_0.sv:53: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:53: error: Unable to elaborate condition expression.\n18 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::unconstrained_randomize", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "note": "Focused unexcluded class randomization failures. Both shared cases pass Celox native, Cranelift, Wasm and Verilator." +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 7d66640caf0..2ffa43e125e 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -309,6 +309,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_class_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_randomize", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "upstream": [] + }, + "name": "class::randomize_without_rand_members", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 rejects class scope resolution with a syntax error: reading a static property (Counter::created), calling a static method (Counter::next()) and assigning a static property (Counter::last = \"set\"). IEEE 1800-2023 8.9, 8.10 and 8.23 define these accesses. Verilator passes the case.", @@ -355,6 +378,29 @@ "tag_reasons": {}, "tags": [] }, + { + "category": "Types", + "detail": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/repros/sv_class_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_class_randomize", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "upstream": [] + }, + "name": "class::unconstrained_randomize", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, { "category": "Types", "detail": "Icarus 13.0 binds a virtual function called through a base-class handle to the handle's class instead of the object's: the shared case prints area=0 for every shape, and the adapter-free source prints 1 1 1 3 where IEEE 1800-2023 8.20 requires 2 3 4 4. Verilator and Celox print 2 3 4 4 and pass the case.", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 70b36e60f7c..6688832b0de 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2068,5 +2068,23 @@ "timing::process_nonblocking_assignments_outside_their_target" ] } + }, + { + "id": "sv_icarus_class_randomize", + "category": "simulator_unsupported", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 rejects the built-in class randomize and srandom methods during elaboration. IEEE 1800-2023 18.6 and 18.13.3 define these methods. Verilator executes both shared cases successfully, including hooks and independent object random streams.", + "upstream": [], + "evidence": [ + "verification/repros/sv_class_randomize_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomize_without_rand_members", + "class::unconstrained_randomize" + ] + } } ] diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 5cbcd773323..1135f129784 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -185,7 +185,7 @@ fn difference( .heap() .same_contents(shadow.simulator.backend.heap()) { - return Some("the string heap".to_string()); + return Some("the runtime heap (strings or objects)".to_string()); } let (events, reference) = ( primary.peek_runtime_events(), @@ -503,6 +503,42 @@ mod tests { } } + #[test] + fn differential_mode_detects_object_rng_divergence_before_randomize() { + use crate::backend::SimBackend as _; + let source = r#" + module Top(output bit done); + timeunit 1ps / 1ps; + class C; rand int value; endclass + C c; + initial begin + c = new; + #5 done = 1; + #5 void'(c.randomize()); + end + endmodule + "#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("rng.sv"))], "Top") + .scheduler_mode(SchedulerMode::Differential) + .build() + .unwrap(); + sim.run_until(0).unwrap(); + let object = sim.get(sim.signal("c")).to_u32_digits()[0]; + use celox_runtime::StepObserver as _; + let mut check = + super::ShadowCheck::new(sim.shadow.as_mut().unwrap(), SchedulerMode::Differential); + check.before_step(&sim.state, &mut sim.simulator); + let result = sim.state.step_until(&mut sim.simulator, 5); + // Inject an extra draw after the primary step: before_step mirrors the + // heap, so a mutation between run_until calls would be overwritten. + sim.simulator.backend.heap_mut().random_object(object); + let error = check + .after_step(&sim.state, &mut sim.simulator, 5, &result) + .unwrap_err() + .to_string(); + assert!(error.contains("runtime heap"), "{error}"); + } + #[test] fn differential_mode_reports_a_diverging_step() { let mut sim = build(SchedulerMode::Differential); diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index d3ce2c4cdcb..cd7f9ab5212 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -193,3 +193,124 @@ fn incompatible_class_handle_assignments_are_rejected() { assert!(want.iter().all(|want| error.contains(want)), "{error}"); } } + +sv_backends! { + fn class_unconstrained_randomize(sim) { @case "class::unconstrained_randomize"; } + fn class_randomize_without_rand_members(sim) { @case "class::randomize_without_rand_members"; } + fn class_randomize_null_receiver(sim) { + @setup { + let source = r#"module Top(output int hooks, result); + class Empty; + static int calls; + function void pre_randomize(); calls++; endfunction + function void post_randomize(); calls++; endfunction + endclass + Empty object; + initial begin + result = object.randomize(); + hooks = Empty::calls; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("null_randomize.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("null object handle"), "{error}"); + assert_eq!(sim.get(sim.signal("hooks")), 0u8.into()); + assert_eq!(sim.get(sim.signal("result")), 0u8.into()); + } +} + +sv_backends! { + fn class_randomize_rejects_dynamic_base_handle(sim) { + @setup { + let source = r#"module Top(output int value, hooks, result); + class Base; + rand int x = 77; + static int calls; + function void pre_randomize(); calls++; endfunction + function void post_randomize(); calls++; endfunction + endclass + class Derived extends Base; + constraint c { x == 1; } + endclass + Base b; + Derived d; + initial begin + d = new; + b = d; + result = b.randomize(); + value = b.x; + hooks = Base::calls; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("base_randomize.sv"))], "Top"); + let error = sim.run_until(0).unwrap_err().to_string(); + assert!(error.contains("randomization through a base handle"), "{error}"); + assert_eq!(sim.get(sim.signal("value")), 77u8.into()); + assert_eq!(sim.get(sim.signal("hooks")), 0u8.into()); + assert_eq!(sim.get(sim.signal("result")), 0u8.into()); + } +} + +sv_backends! { + fn class_randomize_checkpoint_four_state(sim) { + @setup { + let source = r#"module Top(output bit [63:0] value); + timeunit 1ps / 1ps; + class C; rand bit [63:0] x; endclass + C c; + initial begin + c = new; + c.srandom(44); + void'(c.randomize()); + value = c.x; + #10; + void'(c.randomize()); + value = c.x; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("random_checkpoint.sv"))], "Top").four_state(true); + sim.run_until(5).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + let value = sim.signal("value"); + sim.run_until(15).unwrap(); + let expected = sim.get_four_state(value); + sim.restore(&checkpoint).unwrap(); + sim.run_until(15).unwrap(); + assert_eq!(sim.get_four_state(value), expected); + } +} + +sv_backends! { + fn class_constructor_checkpoint_restores_process_rng(sim) { + @setup { let source = r#" + module Top(input bit clk, output bit [63:0] value); + class C; rand bit [63:0] x; endclass + C c; + always @(posedge clk) begin + c = new; + void'(c.randomize()); + value = c.x; + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("constructor_rng.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let value = sim.signal("value"); + sim.tick(clk).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + let mut expected = Vec::new(); + for _ in 0..4 { + sim.tick(clk).unwrap(); + expected.push(sim.get_four_state(value)); + } + assert!(expected.windows(2).any(|pair| pair[0] != pair[1])); + sim.restore(&checkpoint).unwrap(); + for expected in expected { + sim.tick(clk).unwrap(); + assert_eq!(sim.get_four_state(value), expected); + } + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 2722e799c75..fff7ef4fb74 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -101,9 +101,26 @@ 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`), class methods, enum variables, unpacked arrays, nets, +Constraints (`with`), enum variables, unpacked arrays, nets, constants, selects and concatenation arguments are unsupported and rejected. +### Class randomization + +`object.randomize()` randomizes the object's `rand` properties and returns +signed `int` value `1`. This first subset supports classes without inheritance +or constraints, with 2-state non-enum integral `rand` properties up to 64 bits. +Other properties keep their values. Zero-argument, non-static, non-virtual +`pre_randomize()` and `post_randomize()` functions run before and after the +updates, including when there are no `rand` properties (IEEE 1800-2023 18.6). +Calls inside a class may use `randomize()` or `this.randomize()`. + +Each object has an independent random stream, seeded from its creating process. +`object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve it +(18.13.3, 18.14.3). Random sequences are implementation-specific. +`randc`, constraints, `with`, argument lists to `randomize`, `rand_mode`, +static random properties, random enum/array/object/string properties and randomization through inheritance +remain unsupported. A call through `null` is a runtime error. + ### Time literal delays {#time-literal-delays} Standalone delay controls accept time literals such as `#5ns`, `#(2.75ns)` and diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 2662f0b5f7b..358ccd70c5f 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -92,9 +92,24 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task プロセスごとの永続的な乱数列を使い、文の実行順序と短絡評価に従います (IEEE 1800-2023 18.12)。 -`with` 制約、class メソッド、enum 変数、unpacked 配列、net、定数、 +`with` 制約、enum 変数、unpacked 配列、net、定数、 select・連結式の引数は未対応として拒否します。 +### クラスの乱数化 + +`object.randomize()` は `rand` プロパティを乱数化し、成功値の1(signed `int`)を返します。 +最初の対応範囲は継承・制約のないクラスと、64ビット以下の2値・非enum整数型の `rand` プロパティです。 +それ以外のプロパティは保持します。引数なし・非static・非virtualの +`pre_randomize()` と `post_randomize()` を更新の前後に呼びます。 +`rand` プロパティがない場合もフックを呼びます(IEEE 1800-2023 18.6)。 +クラス内では `randomize()` や `this.randomize()` と書けます。 + +オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 +`object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態も保持します +(18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 +`randc`、制約、`with`、`randomize` の引数指定、`rand_mode`、staticな乱数プロパティ、enum・配列・オブジェクト・文字列の +乱数化、継承を使った乱数化は未対応です。`null` を通した呼び出しは実行時エラーです。 + ### 時間リテラルによる遅延 {#time-literal-delays} 遅延制御の時間リテラルは `#5ns`、`#(2.75ns)`、`#40ps` など、`fs` から `s` の6単位に