From 7df0ef730228f785a5cbc1f7e47447cab280eb02 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 10:00:00 +0900 Subject: [PATCH 1/2] feat(sv): support $random and $urandom_range $random follows the algorithm of IEEE 1800-2023 Annex N, computed with integer operations that are exact for every seed, and updates its seed variable; without an argument, each process continues its own seed from 0. $urandom_range draws from the $urandom stream and scales the number into its inclusive bounds, swapping reversed bounds. Add shared cases that Icarus Verilog passes, and record Verilator's different $random algorithm as a reviewed limitation. --- crates/celox-frontend-sv/src/lowering.rs | 18 +- crates/celox-frontend-sv/src/lowering/ff.rs | 275 +++++++++++++++--- .../src/lowering/procedural.rs | 20 +- .../celox-sv-analyzer/src/ast/expressions.rs | 89 +++--- .../celox-sv-analyzer/src/ast/validation.rs | 5 +- .../celox-sv-analyzer/src/system_functions.rs | 23 +- crates/celox-test-suite/LIMITATIONS.md | 1 + .../src/sv/cases/system_functions.vtest | 121 ++++++++ .../verification/repros/sv_random.json | 53 ++++ .../verification/sv/limitations.json | 18 ++ .../systemverilog/system_functions.rs | 9 + docs/guide/systemverilog.md | 11 +- docs/ja/guide/systemverilog.md | 10 +- 13 files changed, 569 insertions(+), 84 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_random.json diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 366e7817e60..51ac23e8498 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -970,8 +970,14 @@ impl DriverScan<'_> { }); } while let Some((callee, args)) = calls.pop() { - let sv::ir::Callee::Subroutine(name) = callee else { - continue; + let name = match callee { + sv::ir::Callee::System(function) => { + for lvalue in procedural::written_system_arguments(function, &args) { + record(drivers, &lvalue); + } + continue; + } + sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self .subroutines @@ -4620,9 +4626,11 @@ fn lower_bit_vector_function_slt( arena.alloc(SLTNode::Binary(count, op, one)).ok()? } } - // `$urandom` needs process state, and the analyzer folds the other - // functions to constants. - SystemFunction::Urandom + // The random number functions need process state, and the analyzer + // folds the other functions to constants. + SystemFunction::Random + | SystemFunction::Urandom + | SystemFunction::UrandomRange | SystemFunction::Timeunit | SystemFunction::Timeprecision | SystemFunction::Isunbounded diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 66d33279f6b..90d3adfda0d 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -46,10 +46,13 @@ pub(super) struct Ff<'p, 'a> { /// Read-modify-write views of a variable's working value: alias -> var. aliases: HashMap, next_alias: u32, - /// One persistent RNG shared by every call from this process, including - /// calls in inlined subroutines. Bit 32 distinguishes an unseeded state. + /// One persistent RNG of `$urandom` and `$urandom_range` shared by every + /// call from this process, including calls in inlined subroutines. Bit + /// 32 distinguishes an unseeded state. random: Option<(SourceVarId, String)>, random_seed: u32, + /// The seed of this process's `$random` calls without a seed argument. + dist_seed: Option<(SourceVarId, String)>, /// The kernel of a process being lowered. Its builder is `b` while the /// body is lowered, and the process reads and writes stable state /// directly. @@ -95,6 +98,7 @@ impl<'p, 'a> Ff<'p, 'a> { next_alias: u32::MAX, random: None, random_seed, + dist_seed: None, kernel: None, direct: false, } @@ -214,11 +218,18 @@ impl<'p, 'a> Ff<'p, 'a> { while let Some((callee, args)) = calls.pop() { let name = match callee { sv::ir::Callee::System(function) => { - if function == sv::ir::SystemFunction::Urandom && self.random.is_none() { - let (id, name) = self.m.temp("urandom_state", 33, false, false); - self.working.insert(id); - self.targets.push((id, BitAccess::new(0, 32))); - self.random = Some((id, name)); + use sv::ir::SystemFunction; + match function { + SystemFunction::Urandom | SystemFunction::UrandomRange => { + self.urandom_state(); + } + SystemFunction::Random if args.is_empty() => { + self.dist_seed(); + } + _ => {} + } + for lvalue in written_system_arguments(function, &args) { + self.record_target(&lvalue, true); } continue; } @@ -790,7 +801,23 @@ impl<'p, 'a> Ff<'p, 'a> { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Urandom), args, .. - } => self.urandom(args)?, + } => { + let seed = match args.first().and_then(Option::as_ref) { + Some(seed) => Some(self.hoist(seed)?), + None => None, + }; + self.urandom(seed)? + } + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::UrandomRange), + args, + .. + } => self.urandom_range(args)?, + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Random), + args, + .. + } => self.random(args.first().and_then(Option::as_ref))?, Expr::Call { callee: sv::ir::Callee::Subroutine(name), args, @@ -1044,21 +1071,62 @@ impl<'p, 'a> Ff<'p, 'a> { // ---------------------------------------------------------------- stores + /// The state of this process's `$urandom` stream. + fn urandom_state(&mut self) -> (SourceVarId, String) { + if self.random.is_none() { + let (id, name) = self.m.temp("urandom_state", 33, false, false); + self.working.insert(id); + self.targets.push((id, BitAccess::new(0, 32))); + self.random = Some((id, name)); + } + self.random.clone().expect("a process RNG") + } + + /// The seed of this process's `$random` calls without a seed argument. + /// It starts at 0, as the seed variable of `$random(seed)` typically + /// does, so a design whose one process calls `$random` gets the same + /// numbers as other simulators that use one seed for the whole design. + fn dist_seed(&mut self) -> (SourceVarId, String) { + if self.dist_seed.is_none() { + let (id, name) = self.m.temp("random_seed", 32, false, false); + self.working.insert(id); + self.targets.push((id, BitAccess::new(0, 31))); + self.dist_seed = Some((id, name)); + } + self.dist_seed.clone().expect("a process seed") + } + + /// Evaluate `expr` into a new hidden variable. + fn hidden( + &mut self, + purpose: &str, + expr: &sv::ir::Expr, + signed: bool, + ) -> Result { + let value = self.eval(expr, Some((32, signed)))?; + let (id, name) = self.m.temp(purpose, 32, signed, false); + self.store(id, SIROffset::Static(0), 32, value); + Ok(sv::ir::Expr::Ident(name)) + } + + /// `expr` converted to a 32-bit `int` or `int unsigned` formal. + fn int_formal(&self, expr: sv::ir::Expr) -> sv::ir::Expr { + let signed = self.expr_signed(&expr); + sv::ir::Expr::Resize { + expr: Box::new(expr), + width: 32, + signed, + } + } + /// IEEE 1800-2023 18.13.1/18.14: a deterministic, process-local stream. /// This full-period 32-bit LCG is implementation-defined; tests compare /// repeatability rather than assuming another simulator's sequence. - fn urandom( - &mut self, - args: &[Option], - ) -> Result { + fn urandom(&mut self, seed: Option) -> Result { use sv::ir::{BinaryOp, Expr}; - if self.random.is_none() { - let random = self.m.temp("urandom_state", 33, false, false); - self.random = Some(random); - } - let (id, name) = self.random.clone().expect("a process RNG"); - let initial = match args.first().and_then(Option::as_ref) { - Some(seed) => self.hoist(seed)?, + let (id, name) = self.urandom_state(); + let initial = match seed { + Some(seed) => seed, None => Expr::Mux { condition: Box::new(Expr::Binary { left: Box::new(Expr::Ident(name.clone())), @@ -1071,17 +1139,12 @@ impl<'p, 'a> Ff<'p, 'a> { }; // The int seed formal preserves a narrow signed operand's sign bits // before its 32-bit representation becomes unsigned RNG state. - let seed_signed = self.expr_signed(&initial); let next = Expr::Resize { width: 32, signed: false, expr: Box::new(Expr::Binary { left: Box::new(Expr::Binary { - left: Box::new(Expr::Resize { - expr: Box::new(initial), - width: 32, - signed: seed_signed, - }), + left: Box::new(self.int_formal(initial)), op: BinaryOp::Mul, right: Box::new(Expr::Literal("32'd1664525".into())), }), @@ -1089,16 +1152,162 @@ impl<'p, 'a> Ff<'p, 'a> { right: Box::new(Expr::Literal("32'd1013904223".into())), }), }; - let result = self.eval(&next, Some((32, false)))?; - let (temp, temp_name) = self.m.temp("urandom_result", 32, false, false); - self.store(temp, SIROffset::Static(0), 32, result); - let state = Expr::Concat(vec![ - Expr::Literal("1'b1".into()), - Expr::Ident(temp_name.clone()), - ]); + let result = self.hidden("urandom_result", &next, false)?; + let state = Expr::Concat(vec![Expr::Literal("1'b1".into()), result.clone()]); let state = self.eval(&state, Some((33, false)))?; self.store(id, SIROffset::Static(0), 33, state); - Ok(Expr::Ident(temp_name)) + Ok(result) + } + + /// IEEE 1800-2023 18.13.2: a number of the `$urandom` stream between the + /// two bounds, in either order, inclusive. + fn urandom_range( + &mut self, + args: &[Option], + ) -> Result { + use sv::ir::{BinaryOp, Expr}; + let bound = |this: &mut Self, arg: Option<&Expr>| match arg { + Some(arg) => { + let arg = this.hoist(arg)?; + let arg = this.int_formal(arg); + this.hidden("urandom_range_bound", &arg, false) + } + None => Ok(Expr::Literal("32'd0".into())), + }; + let max = bound(self, args.first().and_then(Option::as_ref))?; + let min = bound(self, args.get(1).and_then(Option::as_ref))?; + let value = self.urandom(None)?; + let widen = |expr: Expr, width| Expr::Resize { + expr: Box::new(expr), + width, + signed: false, + }; + let binary = |left, op, right| Expr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + let reversed = binary(max.clone(), BinaryOp::Lt, min.clone()); + let pick = |when_reversed: &Expr, otherwise: &Expr| Expr::Mux { + condition: Box::new(reversed.clone()), + then_expr: Box::new(when_reversed.clone()), + else_expr: Box::new(otherwise.clone()), + }; + let (high, low) = (pick(&min, &max), pick(&max, &min)); + // The span is 2**32 for the full range, so it takes 33 bits. Scaling + // takes the offset from the high bits of the number: the low bits of + // the LCG have short periods. + let span = binary( + binary(widen(high, 33), BinaryOp::Sub, widen(low.clone(), 33)), + BinaryOp::Add, + Expr::Literal("33'd1".into()), + ); + let offset = binary( + binary(widen(value, 65), BinaryOp::Mul, widen(span, 65)), + BinaryOp::Shr, + Expr::Literal("65'd32".into()), + ); + let result = Expr::Resize { + expr: Box::new(binary(widen(low, 65), BinaryOp::Add, offset)), + width: 32, + signed: false, + }; + self.hidden("urandom_range_result", &result, false) + } + + /// IEEE 1800-2023 20.14.1 and Annex N: `$random` is + /// `rtl_dist_uniform(seed, LONG_MIN, LONG_MAX)` with a 32-bit `long`. + /// + /// Annex N computes the number in floating point from bits 31:9 of the + /// next seed, `m`; the result is exactly `512 * (m + 1) + m / 16384 - + /// 2**31`, one less where that is negative and `m` is a multiple of + /// 16384 (Annex N takes `r - 1` of a negative integral `r`), and + /// `LONG_MIN` where `m` is all ones and the conversion overflows, as the + /// reference code returns on x86 and Icarus Verilog does. + fn random(&mut self, seed: Option<&sv::ir::Expr>) -> Result { + use sv::ir::{BinaryOp, Expr}; + let (current, store_back) = match seed { + Some(seed) => { + let lvalues = lvalue_from_expr(seed) + .ok_or_else(|| unsupported("seed variable of `$random`"))?; + (self.hoist(seed)?, Some(lvalues)) + } + None => (Expr::Ident(self.dist_seed().1), None), + }; + let literal = |value: u32| Expr::Literal(format!("32'd{value}")); + let binary = |left, op, right| Expr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + let current = self.int_formal(current); + let current = self.hidden("random_seed", ¤t, false)?; + let seeded = Expr::Mux { + condition: Box::new(binary(current.clone(), BinaryOp::Eq, literal(0))), + then_expr: Box::new(literal(259_341_593)), + else_expr: Box::new(current), + }; + let next = binary( + binary(seeded, BinaryOp::Mul, literal(69_069)), + BinaryOp::Add, + literal(1), + ); + let next = self.hidden("random_seed", &next, false)?; + // `{m, 9'b0} + 512 + m / 16384`, which wraps only for the all-ones `m`. + let scaled = binary( + binary( + binary(next.clone(), BinaryOp::BitAnd, literal(0xffff_fe00)), + BinaryOp::Add, + literal(512), + ), + BinaryOp::Add, + binary(next.clone(), BinaryOp::Shr, literal(23)), + ); + let scaled = self.hidden("random_scaled", &scaled, false)?; + let integral_negative = binary( + binary(scaled.clone(), BinaryOp::Lt, literal(0x8000_0000)), + BinaryOp::LogicAnd, + binary( + binary(next.clone(), BinaryOp::BitAnd, literal(0x007f_fe00)), + BinaryOp::Eq, + literal(0), + ), + ); + let value = Expr::Mux { + condition: Box::new(binary( + binary(next.clone(), BinaryOp::Shr, literal(9)), + BinaryOp::Eq, + literal(0x007f_ffff), + )), + then_expr: Box::new(literal(0x8000_0000)), + else_expr: Box::new(binary( + binary(scaled, BinaryOp::BitXor, literal(0x8000_0000)), + BinaryOp::Sub, + Expr::Mux { + condition: Box::new(integral_negative), + then_expr: Box::new(literal(1)), + else_expr: Box::new(literal(0)), + }, + )), + }; + let value = Expr::Resize { + expr: Box::new(value), + width: 32, + signed: true, + }; + let result = self.hidden("random_result", &value, true)?; + match store_back { + Some(lvalues) => match lvalues.as_slice() { + [lvalue] => self.assign(lvalue, &next)?, + parts => self.assign_concat(parts, &next)?, + }, + None => { + let (id, _) = self.dist_seed(); + let next = self.eval(&next, Some((32, false)))?; + self.store(id, SIROffset::Static(0), 32, next); + } + } + Ok(result) } fn store(&mut self, id: SourceVarId, offset: SIROffset, width: usize, value: RegisterId) { diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index f8178cc7e65..b0ef1ea6cfd 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -143,8 +143,8 @@ impl<'a> ProcModule<'a> { } } - /// Whether a process calls the random function, including through user - /// subroutines and omitted argument defaults. + /// Whether a process calls a random number function, including through + /// user subroutines and omitted argument defaults. pub fn uses_random(&self, body: &[sv::ir::Stmt]) -> bool { let mut calls = Vec::new(); for stmt in body { @@ -154,7 +154,7 @@ impl<'a> ProcModule<'a> { while let Some((callee, args)) = calls.pop() { let name = match callee { sv::ir::Callee::System(function) => { - if function == sv::ir::SystemFunction::Urandom { + if function.is_effectful() { return true; } continue; @@ -2001,6 +2001,20 @@ pub(super) fn written_names(stmts: &[sv::ir::Stmt], names: &mut HashSet) } /// The lvalue an output argument writes back to. +/// The variables a call of `function` writes through its arguments, such as +/// the seed of `$random(seed)`. +pub(super) fn written_system_arguments( + function: sv::ir::SystemFunction, + args: &[Option], +) -> Vec { + args.iter() + .enumerate() + .filter(|(position, _)| function.writes_argument(*position)) + .filter_map(|(_, arg)| arg.as_ref().and_then(lvalue_from_expr)) + .flatten() + .collect() +} + pub(super) fn lvalue_from_expr(expr: &sv::ir::Expr) -> Option> { match expr { sv::ir::Expr::Ident(name) => Some(vec![sv::ir::LValue::Ident(name.clone())]), diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 1982bc90b25..98916c99900 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -597,44 +597,36 @@ fn expr_from_system_function_call( )?; let operand_error = || unsupported(format!("operand of `{name}`")); match function { - SystemFunction::Urandom => { - let args = match call { + SystemFunction::Urandom | SystemFunction::Random | SystemFunction::UrandomRange => { + let arguments = match call { + _ if args.as_deref() == Some(&[]) => Vec::new(), sv_parser::SystemTfCall::ArgOptionl(call) if call.nodes.1.is_none() => Vec::new(), - _ => match single_expression_argument(call) { - Some(argument) => { - if dimensions::unpacked_expression_dimensions( - argument, - syntax_tree, - &packed_dimensions.const_env, - &packed_dimensions.type_aliases, - Some(packed_dimensions), - ) - .is_some_and(|rank| rank != 0) - { - return Err(operand_error()); - } - let argument = expr_from_expression_with_types( - argument, - syntax_tree, - packed_dimensions, - ) - .map_err(|error| { - AnalyzerError::InvalidSystemTfCall { - name: name.into(), - detail: format!("seed must be an integral expression: {error}"), - } - })?; - expr_static_width(&argument, packed_dimensions) - .ok_or_else(operand_error)?; - vec![Some(argument)] - } - None if args.as_deref() == Some(&[]) => Vec::new(), - None => return Err(operand_error()), - }, + sv_parser::SystemTfCall::ArgExpression(call) + if call.nodes.1.nodes.1.1.is_none() => + { + call.nodes.1.nodes.1.0.contents() + } + _ => return Err(operand_error()), }; + let mut converted = Vec::new(); + for (position, argument) in arguments.into_iter().enumerate() { + let argument = argument.as_ref().ok_or_else(operand_error)?; + let argument = integral_argument(name, argument, syntax_tree, packed_dimensions)?; + // 20.14.1: the seed of `$random` is an integral variable, + // which the call updates. + if function.writes_argument(position) + && !query_actual_is_writable(&argument, packed_dimensions) + { + return Err(AnalyzerError::InvalidSystemTfCall { + name: name.into(), + detail: "seed must be an integral variable".into(), + }); + } + converted.push(Some(argument)); + } Ok(Expr::Call { callee: Callee::System(function), - args, + args: converted, arg_order: Vec::new(), }) } @@ -752,6 +744,35 @@ fn expr_from_system_function_call( } } +/// An integral argument of a random number function, such as the seed of +/// `$urandom`. +fn integral_argument( + name: &str, + argument: &sv_parser::Expression, + syntax_tree: &SyntaxTree, + packed_dimensions: &PackedDimensions, +) -> Converted { + let operand_error = || unsupported(format!("operand of `{name}`")); + if dimensions::unpacked_expression_dimensions( + argument, + syntax_tree, + &packed_dimensions.const_env, + &packed_dimensions.type_aliases, + Some(packed_dimensions), + ) + .is_some_and(|rank| rank != 0) + { + return Err(operand_error()); + } + let argument = expr_from_expression_with_types(argument, syntax_tree, packed_dimensions) + .map_err(|error| AnalyzerError::InvalidSystemTfCall { + name: name.into(), + detail: format!("argument must be an integral expression: {error}"), + })?; + expr_static_width(&argument, packed_dimensions).ok_or_else(operand_error)?; + Ok(argument) +} + /// The one expression argument of a system function call such as `$clog2(x)`. pub(super) fn single_expression_argument( call: &sv_parser::SystemTfCall, diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index ff1a9a8f9fc..7111b507008 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -838,11 +838,12 @@ fn reject_constant_random_calls(node: RefNode<'_>, tree: &SyntaxTree) -> Convert constant.push(in_constant); if in_constant && let RefNode::SystemTfCall(call) = child - && called_system_function(call, tree) == Some(SystemFunction::Urandom) + && let Some(function) = called_system_function(call, tree) + && function.is_effectful() && !unevaluated.contains(&(call as *const _)) { return Err(AnalyzerError::InvalidSystemTfCall { - name: SystemFunction::Urandom.name().into(), + name: function.name().into(), detail: "not permitted in a constant-value expression".into(), }); } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 11bdd0b0a9e..1eade455720 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -50,8 +50,12 @@ pub enum SystemFunction { Onehot0, /// `$isunknown` (20.9). Isunknown, + /// `$random` (20.14.1), with the algorithm of Annex N. + Random, /// `$urandom` (18.13.1). Urandom, + /// `$urandom_range` (18.13.2). + UrandomRange, } /// An array query function that selects one bound of a dimension (20.7). @@ -88,7 +92,9 @@ impl SystemFunction { Self::Onehot => "$onehot", Self::Onehot0 => "$onehot0", Self::Isunknown => "$isunknown", + Self::Random => "$random", Self::Urandom => "$urandom", + Self::UrandomRange => "$urandom_range", } } @@ -116,7 +122,13 @@ impl SystemFunction { /// Whether each call has an effect, so that copies of one call made by /// the analyzer must not run it twice. pub fn is_effectful(self) -> bool { - self == Self::Urandom + matches!(self, Self::Random | Self::Urandom | Self::UrandomRange) + } + + /// Whether the call writes argument `position` back, as `$random(seed)` + /// updates its seed variable. + pub fn writes_argument(self, position: usize) -> bool { + self == Self::Random && position == 0 } /// The width and signedness of a call that is lowered as an integral @@ -131,7 +143,8 @@ impl SystemFunction { | Self::Countbits | Self::Countones => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), - Self::Urandom => Some((32, false)), + Self::Random => Some((32, true)), + Self::Urandom | Self::UrandomRange => Some((32, false)), Self::Signed | Self::Unsigned | Self::Bits @@ -302,7 +315,7 @@ impl Callee { /// Whether each call has an effect, so that copies of one call made by /// the analyzer must not run it twice: user subroutines may have side - /// effects, as does `$urandom`. + /// effects, as do the random number functions. pub fn is_effectful(&self) -> bool { self.system().is_none_or(SystemFunction::is_effectful) } @@ -550,7 +563,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$set_coverage_db_name", Task), unsupported("$load_coverage_db", Task), // 20.14 Probabilistic distribution functions - unsupported("$random", Function), + function(SystemFunction::Random, 0, Some(1)), unsupported("$dist_uniform", Function), unsupported("$dist_normal", Function), unsupported("$dist_exponential", Function), @@ -720,7 +733,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$inferred_disable", Function), // 18.13 Random number system functions and methods function(SystemFunction::Urandom, 0, Some(1)), - unsupported("$urandom_range", Function), + function(SystemFunction::UrandomRange, 1, Some(2)), // 32.9 Loading timing data from an SDF file unsupported("$sdf_annotate", Task), // Annex D Optional system tasks and system functions, which the standard diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 06ea500687e..07151d82933 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -436,6 +436,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_verilator_urandom_statement_order` | execute | verilator | 2 | Verilator 5.052 moves an unseeded $urandom draw before the preceding seeded call when optimizing the clocked body, breaking the reseeded reference sequence. Its generated C++ assigns second from VL_RANDOM_I before the preceding VL_URANDOM_SEEDED_II call. IEEE 1800-2023 18.13.1 requires the seed to determine the following stream; 18.14.2 localizes its state to the calling process. The original sequential assertions, short circuits and indexed draw are preserved. | | `sv_icarus_urandom_seed_expression` | execute | icarus | 3 | Icarus 13.0 requires the $urandom seed to be a writable integer/time variable or register and terminates simulation for a constant or input-net operand. IEEE 1800-2023 18.13.1 accepts any integral expression and gives a literal seed as an example. A standalone literal-seed probe compiles but vvp exits with the seed-must-be-a-variable error; variable seeds reproduce their streams. | | `sv_icarus_urandom_narrow_seed` | execute | icarus | 1 | Icarus 13.0 terminates for an 8-bit $urandom seed variable with 'seed variable is less than 32 bits (8)'. IEEE 1800-2023 18.13.1 accepts any integral expression, converted to the int seed formal. A standalone signed/unsigned 8-bit seed probe compiles, then vvp exits with this width error; Verilator passes the same nonzero-seed extension checks. | +| `sv_verilator_random_algorithm` | execute | verilator | 2 | Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator. | The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json) retains the failed Icarus runs and minimal sources. Cover comparisons enable diff --git a/crates/celox-test-suite/src/sv/cases/system_functions.vtest b/crates/celox-test-suite/src/sv/cases/system_functions.vtest index d058e89b145..dff1230348c 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2622,3 +2622,124 @@ endmodule (tick clk) (assert_eq ff_ok 1) (assert_eq comb_ok 1))) + +; IEEE 1800-2023 20.14.1 and Annex N: `$random(seed)` returns +; `rtl_dist_uniform(seed, LONG_MIN, LONG_MAX)` and updates the seed variable. +; A zero seed starts from 259341593. The other seeds reach the integral +; negative results Annex N decrements, the overflowing conversion at the top of +; the range, and the first nonnegative integral result. +(case random_follows_annex_n_and_updates_its_seed + (source "random_seed.sv" #" + module Top(input logic clk, input int start, output int comb_value, comb_seed); + int seed, value; + always_ff @(posedge clk) begin + seed = start; + for (int k = 0; k < 3; k++) begin + value = $random(seed); + $display("%0d %0d", value, seed); + end + end + always_comb begin + comb_seed = start; + comb_value = $random(comb_seed); + end + endmodule + "#) + (top Top) + (modify (set start 0)) + (assert_eq comb_value 303379748) + (assert_eq comb_seed (trunc 32 -1844104698)) + (tick clk) + (expect_output #"303379748 -1844104698 +-1064739199 1082744015 +-2071669239 75814084 +"#) + (modify (set start (trunc 32 -1752523756))) + (assert_eq comb_value (trunc 32 -2147483137)) + (tick clk) + (expect_output #"-2147483137 5 +-2147138048 345346 +230383387 -1917100901 +"#) + (modify (set start (trunc 32 -593667845))) + (tick clk) + (expect_output #"-2139094528 8388608 +1719665613 -427819007 +-1803481559 344001998 +"#) + (modify (set start (trunc 32 -1271221770))) + (tick clk) + (expect_output #"-2147483648 -1 +2147415551 -69068 +1671993799 -475490395 +"#) + (modify (set start (trunc 32 -635610885))) + (tick clk) + (expect_output #"768 -2147483648 +768 -2147483647 +69376 -2147414578 +"#)) + +; IEEE 1800-2023 20.14.1: without a seed argument, `$random` continues one +; stream. A process that is the design's only caller draws the sequence of a +; zero seed. +(case random_without_a_seed_continues_its_stream + (source "random_stream.sv" #" + module Top(input logic clk); + int a, b; + always_ff @(posedge clk) begin + a = $random; + b = $random(); + $display("%0d %0d", a, b); + end + endmodule + "#) + (top Top) + (tick clk) + (expect_output "303379748 -1064739199\n") + (tick clk) + (expect_output "-2071669239 -1309649309\n")) + +; IEEE 1800-2023 18.13.2: `$urandom_range` returns a value between its bounds, +; inclusive, swaps reversed bounds, and defaults the minimum to 0. +(case urandom_range_stays_within_its_bounds + (source "urandom_range.sv" #" + module Top(input logic clk, input int unsigned low, high, output logic ok, covered, + output int unsigned width); + int unsigned value, reversed, single, full; + logic [3:0] seen; + always_ff @(posedge clk) begin + ok = 1; + seen = 0; + for (int k = 0; k < 64; k++) begin + value = $urandom_range(high, low); + reversed = $urandom_range(low, high); + single = $urandom_range(low, low); + full = $urandom_range(32'hffffffff); + ok &= value >= low && value <= high; + ok &= reversed >= low && reversed <= high; + ok &= single == low; + if (value - low < 4) seen[value - low] = 1; + end + ok &= $urandom_range(3) <= 3; + covered = &seen; + width = $bits($urandom_range(1)); + end + endmodule + "#) + (top Top) + (modify (set low 0) (set high 3)) + (tick clk) + (assert_eq ok 1) + (assert_eq covered 1) + (assert_eq width 32) + (modify (set low 5) (set high 8)) + (tick clk) + (assert_eq ok 1) + (assert_eq covered 1) + (assert_eq width 32) + (modify (set low 0xfffffffc) (set high 0xffffffff)) + (tick clk) + (assert_eq ok 1) + (assert_eq covered 1) + (assert_eq width 32)) diff --git a/crates/celox-test-suite/verification/repros/sv_random.json b/crates/celox-test-suite/verification/repros/sv_random.json new file mode 100644 index 00000000000..895f87cde3d --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_random.json @@ -0,0 +1,53 @@ +{ + "standard": "IEEE 1800-2023 20.14.1 and Annex N", + "source": "module Top;\n int seed, a, b, c;\n initial begin\n seed = 0; a = $random(seed); b = $random(seed); c = $random(seed);\n $display(\"seeded=%0d,%0d,%0d seed=%0d\", a, b, c, seed);\n a = $random; b = $random;\n $display(\"unseeded=%0d,%0d\", a, b);\n $finish;\n end\nendmodule\n", + "expected": [ + "seeded=303379748,-1064739199,-2071669239 seed=75814084", + "unseeded=303379748,-1064739199" + ], + "verilator_compile": { + "command": "verilator --binary --timing -Wno-fatal --top-module Top --Mdir /obj /probe.sv", + "exit_code": 0 + }, + "verilator_run": { + "command": "/obj/VTop", + "exit_code": 0, + "output": "seeded=1631467331,-1457234074,-1292847975 seed=201238671\nunseeded=-491736939,795631877\n- /probe.sv:8: Verilog $finish\n- S i m u l a t i o n R e p o r t: Verilator 5.052 2026-09-05\n- Verilator: $finish at 0s; walltime 0.000 s; speed 0.000 s/s\n- Verilator: cpu 0.000 s on 1 threads; allocated 4 MB\n" + }, + "icarus_compile": { + "command": "iverilog -g2012 -s Top -o /probe.vvp /probe.sv", + "exit_code": 0 + }, + "icarus_run": { + "command": "vvp /probe.vvp", + "exit_code": 0, + "output": "seeded=303379748,-1064739199,-2071669239 seed=75814084\nunseeded=303379748,-1064739199\n/probe.sv:8: $finish called at 0 (1s)\n" + }, + "note": "The expected values are those of the Annex N C source compiled with a 32-bit long. Focused shared failures were reviewed against the locally supplied IEEE 1800-2023; passing or unrelated baseline rows are not refreshed.", + "shared_failures": { + "verilator": [ + { + "category": "Functions", + "detail": "system_functions::random_follows_annex_n_and_updates_its_seed at 2650:3: assert_eq comb_value: expected 0x12153524, got 0x4f36f2dc", + "expectation": "Simulation", + "name": "system_functions::random_follows_annex_n_and_updates_its_seed", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::random_without_a_seed_continues_its_stream at 2699:3: expect_output: expected [51, 48, 51, 51, 55, 57, 55, 52, 56, 32, 45, 49, 48, 54, 52, 55, 51, 57, 49, 57, 57, 10], got [49, 54, 48, 52, 52, 54, 57, 56, 52, 48, 32, 54, 49, 50, 51, 54, 57, 52, 57, 55, 10]", + "expectation": "Simulation", + "name": "system_functions::random_without_a_seed_continues_its_stream", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] + } +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 9a22f120523..0368a3ab5fb 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1354,5 +1354,23 @@ "system_functions::urandom_extends_signed_seed_values" ] } + }, + { + "id": "sv_verilator_random_algorithm", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 does not compute with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator.", + "upstream": [], + "evidence": [ + "verification/repros/sv_random.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "system_functions::random_follows_annex_n_and_updates_its_seed", + "system_functions::random_without_a_seed_continues_its_stream" + ] + } } ] diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 94b0dbc1f31..24e485fbba5 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -437,6 +437,15 @@ sv_backends! { fn urandom_keeps_process_and_instance_streams_independent(sim) { @case "system_functions::urandom_keeps_process_and_instance_streams_independent"; } + fn random_follows_annex_n_and_updates_its_seed(sim) { + @case "system_functions::random_follows_annex_n_and_updates_its_seed"; + } + fn random_without_a_seed_continues_its_stream(sim) { + @case "system_functions::random_without_a_seed_continues_its_stream"; + } + fn urandom_range_stays_within_its_bounds(sim) { + @case "system_functions::urandom_range_stays_within_its_bounds"; + } fn display_expressions_propagate_operand_widths(sim) { @case "system_functions::display_expressions_propagate_operand_widths"; } diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 0063b5b5d62..321dc9591a6 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -85,7 +85,7 @@ synthesis and is tested at the design level. | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | | Parameters | integral parameters, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | -| Random numbers | `$urandom` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed, a 32-bit unsigned result and a separate stream per process | +| Random numbers | `$urandom`, `$urandom_range` and `$random` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | State | two-state and four-state simulation | @@ -382,3 +382,12 @@ activates: `always_comb` runs once at time zero and on implicit sensitivity changes, while `always @*` waits for a sensitivity change. Repeated evaluation with unchanged inputs does not advance the stream. Constant-value contexts report a diagnostic. + +`$urandom_range(maxval, minval)` draws from the `$urandom` stream and returns a +value between the bounds, inclusive, swapping reversed bounds; `minval` +defaults to 0 (18.13.2). `$random` follows the algorithm of IEEE 1800-2023 +Annex N, so it returns the same values as other simulators that implement it, +such as Icarus Verilog. `$random(seed)` updates its seed variable. Without an +argument, each process continues its own seed, which starts at 0, so a design +whose one process calls `$random` matches simulators that keep one seed for +the whole design. diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 286a9ae8ed5..f7eadfb5f38 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -71,7 +71,7 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | | パラメータ | 整数のパラメータと、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | -| 乱数 | `$urandom` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。任意の整数式によるシードと、プロセスごとに独立した32bit符号なしの乱数列 | +| 乱数 | `$urandom`、`$urandom_range`、`$random` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 状態 | 2 値・4 値シミュレーション | @@ -234,3 +234,11 @@ interface型から解決します。generic interfaceポートとgenerate内の `always_comb` は時刻0と暗黙の感度リストの入力変化時に実行され、 `always @*` は入力変化を待ちます。入力が変わらない再評価では乱数列は進みません。 定数値を要求する文脈では診断を返します。 + +`$urandom_range(maxval, minval)` は `$urandom` の列から両端を含む範囲の値を返し、 +逆順の範囲は入れ替えます。`minval` の既定値は0です(18.13.2)。 +`$random` は IEEE 1800-2023 附属書 N のアルゴリズムに従うため、 +Icarus Verilog などそれを実装するシミュレータと同じ値を返します。 +`$random(seed)` はシード変数を更新します。引数がなければプロセスごとのシードを +使い、その初期値は0です。そのため `$random` を呼ぶプロセスが1つだけの設計では、 +設計全体で1つのシードを持つシミュレータと一致します。 From eee54f54f6ab2755b1d2a25bd365f2d5bf6edb29 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 17 Oct 2026 10:37:13 +0900 Subject: [PATCH 2/2] test(suite): retain the $random exclusion and sv-tests result Record the reviewed Verilator exclusion of the two $random cases in its retained report, restore "$random" in the exclusion reason, and accept chapter-20/20.15--random.sv, which now passes. --- conformance/sv-tests/expected.tsv | 2 +- .../verification/sv/limitations.json | 2 +- .../sv/verilator/system_functions.json | 46 +++++++++++++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 92b593277b3..df1c18dab94 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -344,7 +344,7 @@ chapter-20/20.15--dist_normal.sv fail chapter-20/20.15--dist_poisson.sv fail chapter-20/20.15--dist_t.sv fail chapter-20/20.15--dist_uniform.sv fail -chapter-20/20.15--random.sv fail +chapter-20/20.15--random.sv pass chapter-20/20.2--exit.sv fail chapter-20/20.2--finish.sv pass chapter-20/20.2--stop.sv fail diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 0368a3ab5fb..cabc838a58e 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1360,7 +1360,7 @@ "category": "simulator_disagreement", "phase": "execute", "observed_version": "Verilator 5.052", - "reason": "Verilator 5.052 does not compute with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator.", + "reason": "Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator.", "upstream": [], "evidence": [ "verification/repros/sv_random.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/system_functions.json b/crates/celox-test-suite/verification/sv/verilator/system_functions.json index f88ffba69b0..5f54ad2fe17 100644 --- a/crates/celox-test-suite/verification/sv/verilator/system_functions.json +++ b/crates/celox-test-suite/verification/sv/verilator/system_functions.json @@ -830,6 +830,52 @@ "observed_version": "Verilator 5.052", "reason": "Verilator 5.052 treats a zero $urandom seed as an entropy request, so reseeding with zero does not reproduce the sequence. IEEE 1800-2023 18.13.1 permits any integral seed and requires the same sequence for the same seed. A standalone run reports zero_seed_repeat=0 in Verilator and 1 in Icarus; nonzero seeding repeats in both." } + }, + { + "category": "Functions", + "detail": "Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_random.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_random_algorithm", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator.", + "upstream": [] + }, + "name": "system_functions::random_follows_annex_n_and_updates_its_seed", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/repros/sv_random.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_random_algorithm", + "observed_version": "Verilator 5.052", + "phase": "execute", + "reason": "Verilator 5.052 does not compute $random with the Annex N algorithm: seeding with 0 returns 1631467331 instead of 303379748, and an unseeded $random draws from its own RNG. IEEE 1800-2023 20.14.1 and Annex N define $random as rtl_dist_uniform(seed, LONG_MIN, LONG_MAX) so that implementations repeat the same values. A standalone probe prints the Annex N sequence in Icarus 13.0 and different values in Verilator.", + "upstream": [] + }, + "name": "system_functions::random_without_a_seed_continues_its_stream", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] }