Skip to content
Closed
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 @@ -6488,6 +6488,7 @@ fn lower_bit_vector_function_slt<A: std::hash::Hash + Eq + Clone>(
| SystemFunction::UrandomRange
| SystemFunction::Fopen
| SystemFunction::ScopeRandomize
| SystemFunction::ScopeRandomizeEnum
| SystemFunction::Fread
| SystemFunction::Ftell
| SystemFunction::Fseek
Expand Down
67 changes: 67 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ impl<'p, 'a> Ff<'p, 'a> {
use sv::ir::SystemFunction;
match function {
SystemFunction::ScopeRandomize
| SystemFunction::ScopeRandomizeEnum
| SystemFunction::Urandom
| SystemFunction::UrandomRange => {
self.urandom_state();
Expand Down Expand Up @@ -903,6 +904,11 @@ impl<'p, 'a> Ff<'p, 'a> {
args,
..
} => self.fopen(args)?,
Expr::Call {
callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomizeEnum),
args,
..
} => self.randomize_enum(args)?,
Expr::Call {
callee: sv::ir::Callee::System(sv::ir::SystemFunction::ScopeRandomize),
args,
Expand Down Expand Up @@ -1412,6 +1418,67 @@ impl<'p, 'a> Ff<'p, 'a> {
Ok(result)
}

/// Randomize one scalar enum from the process stream. Arguments after the
/// writable destination are its declared values, supplied by the analyzer.
fn randomize_enum(
&mut self,
args: &[Option<sv::ir::Expr>],
) -> Result<sv::ir::Expr, sv::AnalyzerError> {
use sv::ir::{BinaryOp, Expr};
let Some(Some(Expr::Ident(name))) = args.first() else {
return Err(unsupported("scope enum randomize variable"));
};
let values = args[1..]
.iter()
.map(Option::as_ref)
.collect::<Option<Vec<_>>>()
.filter(|values| !values.is_empty())
.ok_or_else(|| unsupported("scope enum randomize domain"))?;
let count = u32::try_from(values.len())
.map_err(|_| unsupported("scope enum randomize domain size"))?;
let threshold = count.wrapping_neg() % count;
let draw_block = self.b.new_block();
let accepted = self.b.new_block();
self.jump(draw_block);
self.b.switch_to_block(draw_block);
let draw = self.randomize_word()?;
let rejected = Expr::Binary {
left: Box::new(draw.clone()),
op: BinaryOp::Lt,
right: Box::new(Expr::Literal(format!("32'd{threshold}"))),
};
let cond = self.eval_truth(&rejected)?.0;
self.b.seal_block(SIRTerminator::Branch {
cond,
true_block: (draw_block, Vec::new()),
false_block: (accepted, Vec::new()),
});
self.b.switch_to_block(accepted);
let index = self.hidden(
"enum_index",
&Expr::Binary {
left: Box::new(draw),
op: BinaryOp::Mod,
right: Box::new(Expr::Literal(format!("32'd{count}"))),
},
false,
)?;
let mut value = (*values.last().unwrap()).clone();
for (position, member) in values.iter().enumerate().rev().skip(1) {
value = Expr::Mux {
condition: Box::new(Expr::Binary {
left: Box::new(index.clone()),
op: BinaryOp::Eq,
right: Box::new(Expr::Literal(format!("32'd{position}"))),
}),
then_expr: Box::new((*member).clone()),
else_expr: Box::new(value),
};
}
self.assign(&sv::ir::LValue::Ident(name.clone()), &value)?;
Ok(Expr::Literal("32'sd1".into()))
}

/// A bijective 32-bit output permutation of the process RNG. Mixing
/// high bits into low bits prevents the LCG's short low-bit periods from
/// freezing bits when a wide variable consumes an even number of words.
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<i128>>,
kind: TypeKind,
is_signed: bool,
packed_ranges: Vec<PackedRange>,
Expand All @@ -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(),
Expand All @@ -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(),
Expand Down Expand Up @@ -2727,6 +2731,7 @@ struct UnpackedDimension {
#[derive(Debug, Clone, PartialEq, Eq)]
struct VariableDimensions {
randomizable: bool,
enum_values: Option<Vec<i128>>,
real: bool,
/// A `string`: each element is a heap handle, not packed bits.
string: bool,
Expand Down
7 changes: 5 additions & 2 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
));
}
}
Expand Down
12 changes: 10 additions & 2 deletions crates/celox-sv-analyzer/src/ast/dimensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ pub(super) fn packed_dimensions_from_ports_and_signals(
dimensions.insert(
port.name().to_string(),
VariableDimensions {
randomizable: !port.r#type().is_enum && port.randomizable,
randomizable: (!port.r#type().is_enum || port.r#type().enum_values.is_some())
&& port.randomizable,
enum_values: port.r#type().enum_values.clone(),
real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal),
string: matches!(port.r#type().kind(), TypeKind::String),
class: port.r#type().class().map(str::to_owned),
Expand All @@ -156,7 +158,10 @@ pub(super) fn packed_dimensions_from_ports_and_signals(
dimensions.insert(
signal.name().to_string(),
VariableDimensions {
randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const,
randomizable: (!signal.r#type().is_enum || signal.r#type().enum_values.is_some())
&& !signal.is_net()
&& !signal.is_const,
enum_values: signal.r#type().enum_values.clone(),
real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal),
string: matches!(signal.r#type().kind(), TypeKind::String),
class: signal.r#type().class().map(str::to_owned),
Expand Down Expand Up @@ -350,6 +355,7 @@ fn extend_variable_dimensions_from_const_env(
let packed_ranges = ranges.split_off(unpacked);
let ty = Type {
is_enum: false,
enum_values: None,
kind: TypeKind::Logic,
is_signed: variable_type_is_signed(const_env, name),
packed_ranges,
Expand All @@ -364,6 +370,7 @@ fn extend_variable_dimensions_from_const_env(
let mut shape = procedural::dimensions_from_type(&ty);
if let Some(existing) = context.get(name) {
shape.randomizable = existing.randomizable;
shape.enum_values = existing.enum_values.clone();
shape.members = existing.members.clone();
shape.is_2state = existing.is_2state;
shape.signed_element_depth = existing.signed_element_depth;
Expand Down Expand Up @@ -532,6 +539,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP
parameter.name.clone(),
VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down
68 changes: 56 additions & 12 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ pub(in crate::ast) fn cast_target_native(
}

enum Finish {
ScopeRandomize(Vec<Option<Vec<i128>>>),
Unary(String),
Binary(String),
Mux,
Expand All @@ -233,7 +234,7 @@ enum Finish {
/// A string operation on the bound children, see [`strings`].
StringCall(StringOp),
/// A read of property `property` of the object handle child.
ObjectLoad(crate::ast::classes::Property),
ObjectLoad(Box<crate::ast::classes::Property>),
/// A call of method subroutine `name` with `formals` formals; the first
/// child is the object handle when `receiver` is one.
MethodCall {
Expand Down Expand Up @@ -499,6 +500,7 @@ pub(in crate::ast) fn bind_value(
}
let actuals =
args.iter().filter_map(|arg| arg.value).collect::<Vec<_>>();
let mut domains = Vec::with_capacity(actuals.len());
for &actual in &actuals {
let ExprKind::Name(name) = &native.expression(actual).kind else {
return Err(unsupported(
Expand All @@ -509,11 +511,17 @@ pub(in crate::ast) fn bind_value(
let shape = dimensions
.get(&name)
.ok_or_else(|| unsupported("scope randomize variable"))?;
if !shape.unpacked.is_empty() || !shape.randomizable {
if !shape.unpacked.is_empty()
|| !shape.randomizable
|| shape.real
|| shape.string
|| shape.class.is_some()
{
return Err(unsupported(
"scope randomize requires a packed non-enum variable",
"scope randomize requires a packed variable with a supported enum domain",
));
}
domains.push(shape.enum_values.clone());
if !expressions::query_actual_is_writable(
&Expr::Ident(name),
dimensions,
Expand All @@ -524,12 +532,7 @@ pub(in crate::ast) fn bind_value(
}
}
jobs.push(Job::Finish(
Finish::Call {
name: "std::randomize".into(),
args: actuals.iter().copied().map(Some).collect(),
order: Vec::new(),
system: Some(SystemFunction::ScopeRandomize),
},
Finish::ScopeRandomize(domains),
actuals.len(),
scope.clone(),
));
Expand Down Expand Up @@ -756,9 +759,10 @@ pub(in crate::ast) fn bind_value(
let (property, receiver) = objects::property(tree, id, native, dimensions)?
.expect("checked by the guard");
match receiver {
Some(receiver) => {
(Finish::ObjectLoad(property), vec![(receiver, None)])
}
Some(receiver) => (
Finish::ObjectLoad(Box::new(property)),
vec![(receiver, None)],
),
None => {
values.push(objects::load(&property, objects::this()));
continue;
Expand Down Expand Up @@ -929,6 +933,46 @@ pub(in crate::ast) fn bind_value(
Finish::StringCall(op) => {
strings::call(op, strings::operands(op, operands, dimensions))
}
Finish::ScopeRandomize(domains) => {
// Preserve the original call when no enum is present.
// Every scalar operation succeeds and returns signed int 1;
// bitwise AND preserves that type and evaluates all operands.
if domains.iter().all(Option::is_none) {
Expr::Call {
callee: Callee::System(SystemFunction::ScopeRandomize),
args: operands.into_iter().map(Some).collect(),
arg_order: Vec::new(),
}
} else {
let mut calls =
operands.into_iter().zip(domains).map(|(operand, domain)| {
let mut args = vec![Some(operand)];
let function = if let Some(values) = domain {
args.extend(values.into_iter().map(|value| {
Some(Expr::Literal(format_typed_parameter_literal(
value,
64,
value < 0,
)))
}));
SystemFunction::ScopeRandomizeEnum
} else {
SystemFunction::ScopeRandomize
};
Expr::Call {
callee: Callee::System(function),
args,
arg_order: Vec::new(),
}
});
let first = calls.next().ok_or_else(disagreement)?;
calls.fold(first, |left, right| Expr::Binary {
left: Box::new(left),
op: BinaryOp::BitAnd,
right: Box::new(right),
})
}
}
Finish::ObjectLoad(property) => {
let handle = operands.pop().ok_or_else(disagreement)?;
objects::load(&property, handle)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
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 @@ -57,6 +57,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) -
name.to_string(),
VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down
6 changes: 5 additions & 1 deletion crates/celox-sv-analyzer/src/ast/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
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 @@ -502,6 +502,7 @@ fn pattern_items(
count as i128 - 1,
VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
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 @@ -137,6 +137,7 @@ fn select<'a>(
let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?;
let sub = Shape::Owned(Rc::new(VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down Expand Up @@ -244,6 +245,7 @@ fn select<'a>(
.ok_or_else(|| unsupported("assignment pattern target width"))?;
let bit = Shape::Owned(Rc::new(VariableDimensions {
randomizable: true,
enum_values: None,
real: false,
string: false,
class: None,
Expand Down
4 changes: 3 additions & 1 deletion crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ pub(super) struct BodyBuilder<'s, 't, 'a> {
/// The packed and unpacked shape of a declared type, as selects see it.
pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions {
VariableDimensions {
randomizable: !r#type.is_enum,
randomizable: !r#type.is_enum || r#type.enum_values.is_some(),
enum_values: r#type.enum_values.clone(),
real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal),
string: matches!(r#type.kind(), TypeKind::String),
class: r#type.class().map(str::to_owned),
Expand Down Expand Up @@ -115,6 +116,7 @@ pub(super) fn scoped_type(mut r#type: Type, const_env: &HashMap<String, i128>) -
pub(super) fn int_type() -> Type {
Type {
is_enum: false,
enum_values: None,
kind: TypeKind::Bit,
is_signed: true,
packed_ranges: vec![PackedRange::new(
Expand Down
Loading
Loading