Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ 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::RandomCyclic { offset, count } => {
let object = self.handle(&args[0])?;
let count = self.constant64(u64::from(*count));
self.heap_call(
ops::encode(ops::OBJECT_RANDOM_CYCLIC, u64::from(*offset)),
&[object, count],
)
}
ObjectOp::Random
| ObjectOp::Check(_)
| ObjectOp::ModeGet(..)
Expand Down Expand Up @@ -121,6 +129,7 @@ impl Ff<'_, '_> {
ObjectOp::Store(_)
| ObjectOp::ClassOf
| ObjectOp::Random
| ObjectOp::RandomCyclic { .. }
| ObjectOp::Seed
| ObjectOp::Check(_)
| ObjectOp::ModeGet(..)
Expand Down
80 changes: 75 additions & 5 deletions crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub(crate) struct Object {
random_state: u64,
random_modes: RandomModes,
saved_random_modes: Vec<RandomModes>,
/// Remaining domain indices for each randc property, keyed by byte offset.
random_cycles: fxhash::FxHashMap<u32, Vec<u16>>,
bytes: Box<[u8]>,
/// Byte offsets of the handle properties, with what they refer to.
pub(crate) handles: Vec<(u32, HandleKind)>,
Expand All @@ -30,6 +32,14 @@ struct RandomModes {
}

impl Object {
fn random(&mut self) -> u64 {
self.random_state = self.random_state.wrapping_add(0x9e3779b97f4a7c15);
let mut word = self.random_state;
word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb);
word ^ (word >> 31)
}

pub(crate) fn size(&self) -> usize {
self.bytes.len()
}
Expand Down Expand Up @@ -71,6 +81,7 @@ impl Heap {
random_state: 0,
random_modes: RandomModes::default(),
saved_random_modes: Vec::new(),
random_cycles: Default::default(),
bytes: vec![0; size].into(),
handles: Vec::new(),
},
Expand All @@ -92,11 +103,36 @@ impl Heap {
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)
object.random()
}

/// Draw without replacement from an immutable domain (IEEE 1800-2023
/// 18.4.2). Lazy Fisher-Yates uses bounded storage and uniform draws.
/// Seeding changes the RNG, but does not discard an unfinished cycle.
pub(crate) fn random_cyclic_object(&mut self, handle: Handle, offset: u32, count: u64) -> u64 {
assert!((1..=256).contains(&count), "invalid randc domain size");
let Some(object) = self.object_mut(handle) else {
return 0;
};
let remaining = object.random_cycles.entry(offset).or_default();
if remaining.is_empty() {
remaining.extend(0..count as u16);
}
let count = remaining.len() as u64;
let threshold = count.wrapping_neg() % count;
let index = loop {
let draw = object.random();
if draw >= threshold {
break (draw % count) as usize;
}
};
u64::from(
object
.random_cycles
.get_mut(&offset)
.unwrap()
.swap_remove(index),
)
}

/// Random properties start enabled. Modes are shared by aliases of an
Expand Down Expand Up @@ -287,6 +323,40 @@ mod tests {
mod random_tests {
use super::*;

#[test]
fn cyclic_domains_survive_reseeding_and_checkpoint_restore() {
for count in [1, 3, 256] {
let mut heap = Heap::new();
let object = heap.new_object(1, 2);
let other = heap.new_object(1, 2);
heap.seed_object(object, 12);
heap.seed_object(other, 12);
let first = heap.random_cyclic_object(object, 0, count);
assert_eq!(first, heap.random_cyclic_object(other, 0, count));
let mut saved = heap.clone();
let mut seen = crate::HashSet::from_iter([first]);
for _ in 1..count {
// Seeding does not make consumed values eligible again.
heap.seed_object(object, 19);
saved.seed_object(object, 19);
let value = heap.random_cyclic_object(object, 0, count);
assert_eq!(value, saved.random_cyclic_object(object, 0, count));
assert!(seen.insert(value));
}
for offset in [0, 1, 0] {
let seen: crate::HashSet<_> = (0..count)
.map(|_| heap.random_cyclic_object(object, offset, count))
.collect();
assert_eq!(seen.len(), count as usize);
assert!(seen.iter().all(|&value| value < count));
}
assert_eq!(heap.take_fault(), None);
}
let mut heap = Heap::new();
assert_eq!(heap.random_cyclic_object(NULL, 0, 3), 0);
assert_eq!(heap.take_fault(), Some(Fault::NullDereference));
}

#[test]
fn random_streams_are_independent_and_checkpointed() {
let mut heap = Heap::new();
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ pub const OBJECT_MODE_POP: u64 = 59;
pub const OBJECT_MODE_SELECT: u64 = 60;
/// Whether a non-rand property is temporarily random in the active scope.
pub const OBJECT_MODE_SELECTED: u64 = 61;
/// Draw a randc domain index; parameter is the property offset, b its domain size.
pub const OBJECT_RANDOM_CYCLIC: u64 = 62;

/// The opcode word of `op` with parameter `parameter`.
pub const fn encode(op: u64, parameter: u64) -> u64 {
Expand Down Expand Up @@ -187,6 +189,7 @@ impl Heap {
}
OBJECT_CLASS => self.class_of(a as Handle).into(),
OBJECT_RANDOM => self.random_object(a as Handle),
OBJECT_RANDOM_CYCLIC => self.random_cyclic_object(a as Handle, parameter as u32, b),
OBJECT_SEED => {
self.seed_object(a as Handle, b as u32);
0
Expand Down
27 changes: 24 additions & 3 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,25 @@ pub(super) struct Property {
pub initializer: Option<celox_sv_syntax::ExprId>,
}

impl Property {
pub fn cyclic_domain_size(&self) -> Option<u16> {
if self.field.handle.is_some() {
return None;
}
if self.r#type.is_enum {
self.r#type.enum_values.as_ref().and_then(|values| {
(1..=256)
.contains(&values.len())
.then_some(values.len() as u16)
})
} else {
(1..=8)
.contains(&self.field.width)
.then(|| 1u16 << self.field.width)
}
}
}

/// A static property of a class: one variable of the module that declares
/// the class, shared by all of its objects (IEEE 1800-2023 8.9).
#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -119,10 +138,12 @@ impl Class {
return Err(unsupported("class randomize with constraints"));
}
for property in &self.properties {
if property.randc {
return Err(unsupported("class randomize with randc properties"));
if property.randc && property.cyclic_domain_size().is_none() {
return Err(unsupported(
"randc requires a 1-8 bit integer or an enum with at most 256 declared values",
));
}
if property.rand
if (property.rand || property.randc)
&& (property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none()))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -557,10 +557,10 @@ pub(super) fn random_selection(
}
if property.field.handle.is_some()
|| (property.r#type.is_enum && property.r#type.enum_values.is_none())
|| property.randc
|| (property.randc && property.cyclic_domain_size().is_none())
{
return Err(unsupported(
"randomize arguments require integral, non-randc properties with a supported enum domain",
"randomize arguments require integral properties with a supported enum domain",
));
}
bits[index + 1] = '1';
Expand Down
74 changes: 50 additions & 24 deletions crates/celox-sv-analyzer/src/ast/procedural/randomization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ pub(super) fn lower(
right: Box::new(Expr::Literal("1'b1".into())),
};
select.push(Stmt::Eval(classes::object_call(
ObjectOp::ModeSelect(property.field.offset, property.rand),
ObjectOp::ModeSelect(
property.field.offset,
property.rand || property.randc,
),
vec![Expr::Ident(this.clone()), selected],
)));
}
Expand All @@ -146,7 +149,10 @@ pub(super) fn lower(
}),
op: BinaryOp::LogicAnd,
right: Box::new(classes::object_call(
ObjectOp::ModeGet(property.field.offset, property.rand),
ObjectOp::ModeGet(
property.field.offset,
property.rand || property.randc,
),
vec![Expr::Ident(this.clone())],
)),
},
Expand Down Expand Up @@ -264,36 +270,56 @@ fn random_property(
property: &classes::Property,
this: &str,
) -> Vec<Stmt> {
let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]);
let random = || {
let op = if property.randc {
ObjectOp::RandomCyclic {
offset: property.field.offset,
count: property
.cyclic_domain_size()
.expect("validated randc domain"),
}
} else {
ObjectOp::Random
};
classes::object_call(op, vec![Expr::Ident(this.into())])
};
let mut body = Vec::new();
let value = if let Some(values) = &property.r#type.enum_values {
let 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 {
if property.randc {
body.push(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,
});
});
} else {
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,
Expand Down
8 changes: 7 additions & 1 deletion crates/celox-sv-analyzer/src/system_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,11 @@ pub enum ObjectOp {
ClassOf,
/// Advance the object's independent RNG, returning 64 random bits.
Random,
/// Draw a domain index without replacement for the property at `offset`.
RandomCyclic {
offset: u32,
count: u16,
},
/// Seed the object's RNG from the second argument.
Seed,
/// Validate a receiver; a nonzero class also rejects unsupported dynamic
Expand All @@ -811,7 +816,7 @@ impl ObjectOp {
/// The width and signedness of the result.
pub fn result_type(&self) -> (usize, bool) {
match self {
Self::Random => (64, false),
Self::Random | Self::RandomCyclic { .. } => (64, false),
Self::Seed
| Self::Check(_)
| Self::ModeSet(_)
Expand All @@ -834,6 +839,7 @@ impl fmt::Display for ObjectOp {
Self::Store(_) => "property write",
Self::ClassOf => "class query",
Self::Random => "object random bits",
Self::RandomCyclic { .. } => "object random cyclic index",
Self::Seed => "object random seed",
Self::Check(_) => "object receiver check",
Self::ModeGet(..) => "random mode query",
Expand Down
25 changes: 24 additions & 1 deletion crates/celox-sv-analyzer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6592,7 +6592,7 @@ fn class_randomize_rejects_unsupported_semantics() {
"c.randomize()",
"constraints",
),
("randc bit [1:0] x;", "c.randomize()", "randc"),
("randc bit [8:0] x;", "c.randomize()", "randc"),
("rand int x;", "c.srandom()", "argument"),
("rand int x;", "c.srandom(1, 2)", "arguments"),
(
Expand Down Expand Up @@ -6799,3 +6799,26 @@ endmodule
assert_eq!(ir.modules()[0].parameters()[0].resolved_value(), None);
}
}

#[test]
fn class_randc_checks_domain_limits() {
let values = (0..257)
.map(|i| format!("V{i}={i}"))
.collect::<Vec<_>>()
.join(",");
for (declarations, members) in [
(String::new(), "randc bit [8:0] x;"),
(
format!("typedef enum bit [15:0] {{{values}}} E;"),
"randc E x;",
),
] {
for call in ["c.randomize()", "c.randomize(x)"] {
let source = format!(
"module Top; {declarations} class C; {members} endclass C c; initial begin c=new; void'({call}); end endmodule"
);
let error = analyze_source(&source, Path::new("randc_limits.sv")).unwrap_err();
assert!(error.to_string().contains("randc"), "{error}");
}
}
}
8 changes: 8 additions & 0 deletions crates/celox-test-suite/LIMITATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,14 @@ without the enum domain, and draws undeclared values (`sv_verilator_scope_enum_r
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.

Cyclic randomization (IEEE 1800-2023 18.4.2) retains narrow external
exclusions: Icarus 13.0 cannot elaborate the three `randomization_cyclic_*`
cases ([diagnostics](verification/repros/sv_randc_icarus.json)). Verilator
5.052 passes the integer and direct-enum domain case, but emits duplicate
`srandom` declarations for the inheritance/control case and draws undeclared
values for an enum typedef alias ([evidence](verification/repros/sv_randc_verilator.json)).
The original cycle, mode and domain assertions remain unchanged.

## SystemVerilog packed unions

The `unions` shared group covers hard and soft packed untagged unions. With
Expand Down
Loading
Loading