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
34 changes: 27 additions & 7 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3279,17 +3279,19 @@ fn evaluated_parameter_overrides(
continue;
};
if !matches!(value, sv::ir::ConstExpr::Literal(value) if value == "$") {
sv::typecheck::eval_const_integral_literal_with_types(
let integral = sv::typecheck::eval_const_integral_literal_with_types(
value,
&constants,
&HashMap::default(),
)
.ok_or_else(|| {
sv::AnalyzerError::Unsupported(format!(
"non-integer module parameter override `{}`",
);
if integral.is_none()
&& sv::typecheck::eval_const_real_expr(value, &constants).is_none()
{
return Err(sv::AnalyzerError::Unsupported(format!(
"nonconstant module parameter override `{}`",
parameter.name
))
})?;
)));
}
}
evaluated.insert(parameter.name.clone(), value.clone());
}
Expand Down Expand Up @@ -9140,6 +9142,24 @@ pub(crate) fn unsupported_sv_inout(path: String) -> ParserError {
mod tests {
use super::*;

#[test]
fn parameter_override_validation_rejects_unresolved_values() {
let overrides = [LoweredSvParameterOverride {
name: "P".into(),
value: Some(sv::ir::ConstExpr::Ident("unresolved".into())),
bound_type: None,
bound_pattern: None,
}];
let error = evaluated_parameter_overrides(&overrides).unwrap_err();
assert_eq!(error.tracking_issue(), 461);
assert!(
error
.to_string()
.contains("nonconstant module parameter override `P`"),
"{error}"
);
}

/// The process kernels of `source`, other than declaration initializers.
fn procedure_kernels(source: &str) -> usize {
let scheduled = schedule_sources(
Expand Down
4 changes: 4 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
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
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ fn extend_variable_dimensions_from_const_env(
let packed_ranges = ranges.split_off(unpacked);
let ty = Type {
is_enum: false,
enum_values: None,
kind: TypeKind::Logic,
is_signed: variable_type_is_signed(const_env, name),
packed_ranges,
Expand Down
9 changes: 5 additions & 4 deletions crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ enum Finish {
/// A string operation on the bound children, see [`strings`].
StringCall(StringOp),
/// A read of property `property` of the object handle child.
ObjectLoad(crate::ast::classes::Property),
ObjectLoad(Box<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 @@ -756,9 +756,10 @@ pub(in crate::ast) fn bind_value(
let (property, receiver) = objects::property(tree, id, native, dimensions)?
.expect("checked by the guard");
match receiver {
Some(receiver) => {
(Finish::ObjectLoad(property), vec![(receiver, None)])
}
Some(receiver) => (
Finish::ObjectLoad(Box::new(property)),
vec![(receiver, None)],
),
None => {
values.push(objects::load(&property, objects::this()));
continue;
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
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/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,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
81 changes: 70 additions & 11 deletions crates/celox-sv-analyzer/src/ast/procedural/randomization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ pub(super) fn lower(
for property in &class.properties {
if property.constant
|| property.field.handle.is_some()
|| property.r#type.is_enum
|| (property.r#type.is_enum && property.r#type.enum_values.is_none())
{
continue;
}
Expand All @@ -150,16 +150,7 @@ pub(super) fn lower(
vec![Expr::Ident(this.clone())],
)),
},
then_body: vec![Stmt::Eval(classes::object_call(
ObjectOp::Store(property.field),
vec![
Expr::Ident(this.clone()),
classes::object_call(
ObjectOp::Random,
vec![Expr::Ident(this.clone())],
),
],
))],
then_body: random_property(&mut builder, property, &this),
else_body: Vec::new(),
});
}
Expand Down Expand Up @@ -264,3 +255,71 @@ pub(super) fn lower(
}
Ok(result)
}

/// Select a declared enum value with rejection sampling, so non-power-of-two
/// domains are uniform (IEEE 1800-2023 18.3, 18.4.1). Keep the draws inside the
/// mode guard: a disabled property must not consume its object's random stream.
fn random_property(
builder: &mut BodyBuilder<'_, '_, '_>,
property: &classes::Property,
this: &str,
) -> Vec<Stmt> {
let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]);
let mut body = Vec::new();
let value = if let Some(values) = &property.r#type.enum_values {
let count = values.len() as u64;
let threshold = count.wrapping_neg() % count;
let draw = builder.declare("$enum_draw", classes::unsigned_type(64));
body.push(Stmt::Loop {
kind: LoopKind::DoWhile,
init: Vec::new(),
condition: Some(Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Lt,
right: Box::new(Expr::Literal(format!("64'd{threshold}"))),
}),
step: Vec::new(),
body: vec![Stmt::Assign {
lhs: LValue::Ident(draw.clone()),
rhs: random(),
nonblocking: false,
}],
});
body.push(Stmt::Assign {
lhs: LValue::Ident(draw.clone()),
rhs: Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Mod,
right: Box::new(Expr::Literal(format!("64'd{count}"))),
},
nonblocking: false,
});
let literal = |value| {
Expr::Literal(format_typed_parameter_literal(
value,
property.field.width as usize,
property.field.signed,
))
};
let mut value = literal(*values.last().unwrap());
for (index, &member) in values.iter().enumerate().rev().skip(1) {
value = Expr::Mux {
condition: Box::new(Expr::Binary {
left: Box::new(Expr::Ident(draw.clone())),
op: BinaryOp::Eq,
right: Box::new(Expr::Literal(format!("64'd{index}"))),
}),
then_expr: Box::new(literal(member)),
else_expr: Box::new(value),
};
}
value
} else {
random()
};
body.push(Stmt::Eval(classes::object_call(
ObjectOp::Store(property.field),
vec![Expr::Ident(this.into()), value],
)));
body
}
73 changes: 70 additions & 3 deletions crates/celox-sv-analyzer/src/ast/type_binding/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub(in crate::ast) fn bind_in(
) -> Converted<Option<Type>> {
enum Job {
Enter(TypeId),
Enum(Vec<PackedRange>),
Enum(TypeId, Vec<PackedRange>),
Aggregate {
owner: Arc<str>,
union: bool,
Expand Down Expand Up @@ -78,11 +78,12 @@ pub(in crate::ast) fn bind_in(
}
DataTypeKind::Enum { base, .. } => {
if let Some(base) = base {
jobs.push(Job::Enum(ranges));
jobs.push(Job::Enum(id, ranges));
jobs.push(Job::Enter(*base));
} else {
let mut ty = builtin_type("int", None).unwrap();
ty.is_enum = true;
ty.enum_values = enum_values(id, native, tree, context, &ty);
ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect();
values.push(ty);
}
Expand Down Expand Up @@ -156,14 +157,15 @@ pub(in crate::ast) fn bind_in(
}
}
}
Job::Enum(ranges) => {
Job::Enum(id, ranges) => {
let Some(mut ty) = values.pop() else {
return Err(unsupported("enum base type"));
};
let mut outer = ranges;
outer.extend(ty.packed_ranges);
ty.packed_ranges = outer;
ty.is_enum = true;
ty.enum_values = enum_values(id, native, tree, context, &ty);
values.push(ty);
}
Job::Aggregate {
Expand Down Expand Up @@ -272,3 +274,68 @@ pub(in crate::ast) fn expression_type(
let value = expression_binding::bind(root, tree, &query)?;
Ok(dimensions::bound_bits_type(&tree.state, &value, &query))
}

/// Domain metadata is best-effort during signature discovery. Only a caller
/// requesting randomization requires a resolved domain; unused types must not
/// start reporting new errors merely because this metadata is collected.
fn enum_values(
id: TypeId,
native: &celox_sv_syntax::Declarations,
tree: &AnalysisContext<'_>,
context: &PackedDimensions,
ty: &Type,
) -> Option<Vec<i128>> {
let data = native.data_type(id);
if !data.packed_dimensions.is_empty() {
return None;
}
let DataTypeKind::Enum { items, .. } = &data.kind else {
return None;
};
let shape = casts::expr_type_from_type(&tree.state, ty, &context.const_env)?;
if shape.width > 64 {
return None;
}
let mut env = context.const_env.clone();
let mut next = 0i128;
let mut values = Vec::new();
for item in items {
if !item.dimensions.is_empty() {
return None;
}
let value = if let Some(id) = item.value {
let expr = constant_binding::expression(id, native, tree, &env, &context.type_aliases)
.ok()??;
// Unbased fills take the enum base's width and signedness, just
// as they do when resolving the declared enum constants (5.7.1).
let expr = match expr {
ConstExpr::Literal(literal) => ConstExpr::Literal(
resize_unbased_fill_literal_for_cast(&literal, shape.width, shape.signed)
.unwrap_or(literal),
),
expr => expr,
};
let value = eval_ast_const_expr(&tree.state, &expr, &env)?;
let value_type = infer_const_expr_type(&expr, &parameter_types_from_const_env(&env))?;
if !parameters::enum_initializer_fits_base_type(value, value_type, shape) {
return None;
}
value
} else {
if parameters::coerce_const_parameter_value(next, shape.width, shape.signed) != next {
return None;
}
next
};
let value = parameters::coerce_const_parameter_value(value, shape.width, shape.signed);
if values.contains(&value) {
return None;
}
values.push(value);
let name = normalize_identifier(&item.name.spelling);
env.insert(name.clone(), value);
dimensions::insert_parameter_type_markers(&mut env, &name, shape);
next = value.checked_add(1)?;
}
(!values.is_empty()).then_some(values)
}
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ pub(super) fn enclose_aliased_packed_type(
// array they form is unsigned, whatever its elements (IEEE 1800-2023
// 7.4.1); a type name takes no signing of its own.
if !direct_ranges.is_empty() {
r#type.enum_values = None;
r#type.signed_element_depth = if r#type.is_signed {
Some(direct_ranges.len())
} else {
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[
("gate primitive instantiation", 457),
("undriven net declaration", 460),
("non-integer module parameter override", 461),
("nonconstant module parameter override", 461),
("always_ff event expression", 464),
("package net", 1146),
];
Expand Down
Loading
Loading