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
1 change: 1 addition & 0 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5497,6 +5497,7 @@ fn lower_bit_vector_function_slt<A: std::hash::Hash + Eq + Clone>(
| SystemFunction::Urandom
| SystemFunction::UrandomRange
| SystemFunction::Fopen
| SystemFunction::ScopeRandomize
| SystemFunction::Timeunit
| SystemFunction::Timeprecision
| SystemFunction::Isunbounded
Expand Down
66 changes: 65 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,9 @@ impl<'p, 'a> Ff<'p, 'a> {
sv::ir::Callee::System(function) => {
use sv::ir::SystemFunction;
match function {
SystemFunction::Urandom | SystemFunction::UrandomRange => {
SystemFunction::ScopeRandomize
| SystemFunction::Urandom
| SystemFunction::UrandomRange => {
self.urandom_state();
}
SystemFunction::Random if args.is_empty() => {
Expand Down Expand Up @@ -823,6 +825,30 @@ impl<'p, 'a> Ff<'p, 'a> {
args,
..
} => self.fopen(args)?,
Expr::Call {
callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize),
args,
..
} => {
for arg in args.iter().flatten() {
let Expr::Ident(name) = arg else {
return Err(unsupported("scope randomize variable"));
};
let target = sv::ir::LValue::Ident(name.clone());
let width = self.lvalue_width(&target)?;
let mut words = Vec::with_capacity(width.div_ceil(32));
for offset in (0..width).step_by(32) {
words.push(Expr::Resize {
expr: Box::new(self.randomize_word()?),
width: (width - offset).min(32),
signed: false,
});
}
words.reverse();
self.assign(&target, &Expr::Concat(words))?;
}
Expr::Literal("32'sd1".into())
}
Expr::Call {
callee: sv::ir::Callee::System(sv::ir::SystemFunction::Urandom),
args,
Expand Down Expand Up @@ -1283,6 +1309,44 @@ impl<'p, 'a> Ff<'p, 'a> {
Ok(result)
}

/// A bijective 32-bit output permutation of the process RNG. Mixing
/// high bits into low bits prevents the LCG's short low-bit periods from
/// freezing bits when a wide variable consumes an even number of words.
fn randomize_word(&mut self) -> Result<sv::ir::Expr, sv::AnalyzerError> {
use sv::ir::{BinaryOp, Expr};
let mut word = self.urandom(None)?;
for (shift, multiplier) in [(16, 0x7feb352du32), (15, 0x846ca68bu32)] {
let mixed = Expr::Binary {
left: Box::new(word.clone()),
op: BinaryOp::BitXor,
right: Box::new(Expr::Binary {
left: Box::new(word),
op: BinaryOp::Shr,
right: Box::new(Expr::Literal(shift.to_string())),
}),
};
word = self.hidden(
"randomize_mix",
&Expr::Binary {
left: Box::new(mixed),
op: BinaryOp::Mul,
right: Box::new(Expr::Literal(format!("32'd{multiplier}"))),
},
false,
)?;
}
let mixed = Expr::Binary {
left: Box::new(word.clone()),
op: BinaryOp::BitXor,
right: Box::new(Expr::Binary {
left: Box::new(word),
op: BinaryOp::Shr,
right: Box::new(Expr::Literal("16".into())),
}),
};
self.hidden("randomize_word", &mixed, false)
}

/// IEEE 1800-2023 18.13.2: a number of the `$urandom` stream between the
/// two bounds, in either order, inclusive.
fn urandom_range(
Expand Down
9 changes: 9 additions & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1609,6 +1609,7 @@ impl Parameter {

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Port {
randomizable: bool,
name: String,
direction: PortDirection,
r#type: Type,
Expand All @@ -1618,6 +1619,7 @@ pub struct Port {

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signal {
is_const: bool,
name: String,
r#type: Type,
is_net: bool,
Expand All @@ -1631,6 +1633,7 @@ impl Signal {
name,
r#type,
is_net: false,
is_const: false,
package_variable: None,
}
}
Expand All @@ -1640,6 +1643,7 @@ impl Signal {
name,
r#type,
is_net: true,
is_const: false,
package_variable: None,
}
}
Expand Down Expand Up @@ -1671,6 +1675,7 @@ impl Port {
name,
direction,
r#type,
randomizable: !is_net,
is_net,
default: None,
}
Expand Down Expand Up @@ -1863,6 +1868,7 @@ pub enum PortDirection {

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Type {
is_enum: bool,
kind: TypeKind,
is_signed: bool,
packed_ranges: Vec<PackedRange>,
Expand All @@ -1877,6 +1883,7 @@ pub struct Type {
impl Type {
fn implicit() -> Self {
Self {
is_enum: false,
kind: TypeKind::Implicit,
is_signed: false,
packed_ranges: Vec::new(),
Expand All @@ -1889,6 +1896,7 @@ impl Type {
fn new(kind: TypeKind) -> Self {
Self {
kind,
is_enum: false,
is_signed: false,
packed_ranges: Vec::new(),
unpacked_ranges: Vec::new(),
Expand Down Expand Up @@ -2567,6 +2575,7 @@ struct UnpackedDimension {

#[derive(Debug, Clone, PartialEq, Eq)]
struct VariableDimensions {
randomizable: bool,
packed: Vec<PackedDimension>,
unpacked: Vec<UnpackedDimension>,
signed: bool,
Expand Down
31 changes: 22 additions & 9 deletions crates/celox-sv-analyzer/src/ast/declarations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub(super) fn ports_from_scope(
let mut ports = Vec::new();
let mut inherited_direction = PortDirection::Unspecified;
let mut inherited_type = Type::implicit();
let mut inherited_variable = false;
for native in port_owners::scope(selected, syntax_tree)? {
let direction = native
.direction
Expand Down Expand Up @@ -69,15 +70,27 @@ pub(super) fn ports_from_scope(
.ok_or_else(|| unsupported("nonconstant input port default"))
})
.transpose()?;
ports.push(
Port::new(
native_port_name(native)?,
direction,
ty,
!explicit && !native.variable,
)
.with_default(default),
);
let variable = native.variable
|| (direction == PortDirection::Output
&& native.net_type.is_none()
&& (native.data_type.is_some_and(|id| {
!matches!(
syntax_tree.declarations().data_type(id).kind,
celox_sv_syntax::DataTypeKind::Implicit
)
}) || (native.direction.is_none()
&& native.data_type.is_none()
&& inherited_variable)));
inherited_variable = variable;
let mut port = Port::new(
native_port_name(native)?,
direction,
ty,
!explicit && !native.variable,
)
.with_default(default);
port.randomizable = variable && direction != PortDirection::Input;
ports.push(port);
}
Ok(ports)
}
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals(
dimensions.insert(
port.name().to_string(),
VariableDimensions {
randomizable: !port.r#type().is_enum && port.randomizable,
packed: signal_packed_dimension_widths(port.r#type().packed_ranges()),
unpacked: unpacked_dimension_widths(port.r#type().unpacked_ranges()),
signed: port.r#type().is_signed(),
Expand All @@ -144,6 +145,7 @@ pub(super) fn packed_dimensions_from_ports_and_signals(
dimensions.insert(
signal.name().to_string(),
VariableDimensions {
randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const,
packed: signal_packed_dimension_widths(signal.r#type().packed_ranges()),
unpacked: unpacked_dimension_widths(signal.r#type().unpacked_ranges()),
signed: signal.r#type().is_signed(),
Expand Down Expand Up @@ -326,6 +328,7 @@ fn extend_variable_dimensions_from_const_env(
}
let packed_ranges = ranges.split_off(unpacked);
let ty = Type {
is_enum: false,
kind: TypeKind::Logic,
is_signed: variable_type_is_signed(const_env, name),
packed_ranges,
Expand All @@ -338,6 +341,7 @@ fn extend_variable_dimensions_from_const_env(
};
let mut shape = procedural::dimensions_from_type(&ty);
if let Some(existing) = context.get(name) {
shape.randomizable = existing.randomizable;
shape.members = existing.members.clone();
shape.is_2state = existing.is_2state;
shape.signed_element_depth = existing.signed_element_depth;
Expand Down Expand Up @@ -505,6 +509,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP
(
parameter.name.clone(),
VariableDimensions {
randomizable: true,
packed: function_packed_dimension_widths(&parameter.packed_ranges),
unpacked: Vec::new(),
signed: parameter.declared_signed.unwrap_or(false),
Expand Down
57 changes: 57 additions & 0 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,62 @@ pub(in crate::ast) fn bind_value(
expression,
arguments: args,
} => {
if matches!(
call_name(&tree.state, *expression, native).as_deref(),
Some("randomize" | "std::randomize")
) {
if args
.iter()
.any(|arg| arg.name.is_some() || arg.value.is_none())
{
return Err(unsupported(
"scope randomize requires positional variable identifiers",
));
}
let actuals =
args.iter().filter_map(|arg| arg.value).collect::<Vec<_>>();
for &actual in &actuals {
let ExprKind::Name(name) = &native.expression(actual).kind else {
return Err(unsupported(
"scope randomize requires whole packed variable identifiers",
));
};
let name = instances::normalize_identifier(&name.spelling);
let shape = dimensions
.get(&name)
.ok_or_else(|| unsupported("scope randomize variable"))?;
if !shape.unpacked.is_empty() || !shape.randomizable {
return Err(unsupported(
"scope randomize requires a packed non-enum variable",
));
}
if !expressions::query_actual_is_writable(
&Expr::Ident(name),
dimensions,
) {
return Err(unsupported(
"scope randomize argument is not writable",
));
}
}
jobs.push(Job::Finish(
Finish::Call {
name: "std::randomize".into(),
args: actuals.iter().copied().map(Some).collect(),
order: Vec::new(),
system: Some(SystemFunction::ScopeRandomize),
},
actuals.len(),
scope.clone(),
));
jobs.extend(
actuals
.into_iter()
.rev()
.map(|id| Job::Enter(id, None, scope.clone())),
);
continue;
}
let name = bound_callable_name(tree, *expression, native, dimensions)?
.ok_or_else(|| unsupported("method or randomize call"))?;
if name.starts_with('$') && !name.contains("::") {
Expand Down Expand Up @@ -727,6 +783,7 @@ pub(in crate::ast) fn bind_value(
| SystemFunction::ValuePlusargs
| SystemFunction::Fopen
| SystemFunction::UrandomRange
| SystemFunction::ScopeRandomize
) {
for (position, arg) in operands.iter().enumerate() {
if expr_static_width(&tree.state, arg, dimensions).is_none()
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-sv-analyzer/src/ast/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ impl ScopeImports {
&& let celox_sv_syntax::ExprKind::Name(package) = &native.expression(*base).kind
{
let package = normalize_identifier(&package.spelling);
// std::randomize is a built-in scope function, not a
// user-declared package dependency (IEEE 1800-2023 18.12).
if package == "std" && normalize_identifier(&name.spelling) == "randomize" {
continue;
}
if !nested.iter().any(|(start, end, names)| {
(*start..*end).contains(&expression.tokens.start) && names.contains(&package)
}) {
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/interface_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,7 @@ pub(super) fn analyze_module(
name: port.name.clone(),
r#type: port.r#type.clone(),
is_net: port.is_net,
is_const: false,
package_variable: None,
};
module.symbols.as_mut().unwrap().signals.push(signal);
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) -
result.insert(
name.to_string(),
VariableDimensions {
randomizable: true,
packed: function_packed_dimension_widths(&r#type.packed_ranges),
unpacked: Vec::new(),
signed: r#type.is_signed,
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/parameters/skipped.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@ fn pattern_items(
0,
count as i128 - 1,
VariableDimensions {
randomizable: true,
packed: Vec::new(),
unpacked: Vec::new(),
members: Vec::new(),
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-sv-analyzer/src/ast/patterns/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ fn select<'a>(
{
let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?;
let sub = Shape::Owned(Rc::new(VariableDimensions {
randomizable: true,
packed: rest.to_vec(),
unpacked: Vec::new(),
signed: shape.signed_element_depth == Some(1),
Expand Down Expand Up @@ -236,6 +237,7 @@ fn select<'a>(
let width = shape_width(state, &shape, dims)
.ok_or_else(|| unsupported("assignment pattern target width"))?;
let bit = Shape::Owned(Rc::new(VariableDimensions {
randomizable: true,
packed: Vec::new(),
unpacked: Vec::new(),
signed: false,
Expand Down
Loading
Loading