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
6 changes: 6 additions & 0 deletions conformance/sv-tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ The integral file-input extension updates six expectation rows: `21.3--feof`,
remaining file-input probes retain their measured verdicts; several still use
unsupported `final` constructs.

The six Annex N distribution probes (`20.15--dist_normal`, `dist_exponential`,
`dist_poisson`, `dist_chi_square`, `dist_t` and `dist_erlang`) now pass simulation
in both state modes, updating twelve more expectation rows. The scanner probes
retain failures caused by unsupported `final` constructs or internal data types;
no scanner expectation is changed.

The report contains each case’s state mode, verdict, selected execution mode,
tags, tool return code and path to the official log. The output directory retains
both the official log and runner diagnostics for each case and state mode.
Expand Down
24 changes: 12 additions & 12 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -681,18 +681,18 @@ chapter-20/20.10--warning.sv 2state pass
chapter-20/20.10--warning.sv 4state pass
chapter-20/20.14--coverage.sv 2state fail
chapter-20/20.14--coverage.sv 4state fail
chapter-20/20.15--dist_chi_square.sv 2state fail
chapter-20/20.15--dist_chi_square.sv 4state fail
chapter-20/20.15--dist_erlang.sv 2state fail
chapter-20/20.15--dist_erlang.sv 4state fail
chapter-20/20.15--dist_exponential.sv 2state fail
chapter-20/20.15--dist_exponential.sv 4state fail
chapter-20/20.15--dist_normal.sv 2state fail
chapter-20/20.15--dist_normal.sv 4state fail
chapter-20/20.15--dist_poisson.sv 2state fail
chapter-20/20.15--dist_poisson.sv 4state fail
chapter-20/20.15--dist_t.sv 2state fail
chapter-20/20.15--dist_t.sv 4state fail
chapter-20/20.15--dist_chi_square.sv 2state pass
chapter-20/20.15--dist_chi_square.sv 4state pass
chapter-20/20.15--dist_erlang.sv 2state pass
chapter-20/20.15--dist_erlang.sv 4state pass
chapter-20/20.15--dist_exponential.sv 2state pass
chapter-20/20.15--dist_exponential.sv 4state pass
chapter-20/20.15--dist_normal.sv 2state pass
chapter-20/20.15--dist_normal.sv 4state pass
chapter-20/20.15--dist_poisson.sv 2state pass
chapter-20/20.15--dist_poisson.sv 4state pass
chapter-20/20.15--dist_t.sv 2state pass
chapter-20/20.15--dist_t.sv 4state pass
chapter-20/20.15--dist_uniform.sv 2state pass
chapter-20/20.15--dist_uniform.sv 4state pass
chapter-20/20.15--random.sv 2state pass
Expand Down
6 changes: 5 additions & 1 deletion crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ pub enum HostRequestKind {
FileIo,
Vcd,
Scan,
Distribution,
}

impl HostRequestKind {
Expand All @@ -313,6 +314,7 @@ impl HostRequestKind {
Self::FileIo => 2,
Self::Vcd => 3,
Self::Scan => 4,
Self::Distribution => 5,
};
(family << 32) | site as u64
}
Expand All @@ -324,6 +326,7 @@ impl HostRequestKind {
2 => Self::FileIo,
3 => Self::Vcd,
4 => Self::Scan,
5 => Self::Distribution,
_ => return None,
};
Some((family, request as u32))
Expand Down Expand Up @@ -1456,6 +1459,7 @@ mod tests {
HostRequestKind::FileIo,
HostRequestKind::Vcd,
HostRequestKind::Scan,
HostRequestKind::Distribution,
] {
for site in [0, 1, u32::MAX] {
assert_eq!(
Expand All @@ -1464,7 +1468,7 @@ mod tests {
);
}
}
for invalid in [0, u32::MAX as u64, 5u64 << 32, 1u64 << 63] {
for invalid in [0, u32::MAX as u64, 6u64 << 32, 1u64 << 63] {
assert_eq!(HostRequestKind::decode(invalid), None);
}
assert_eq!(
Expand Down
6 changes: 6 additions & 0 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5975,6 +5975,12 @@ fn lower_bit_vector_function_slt<A: std::hash::Hash + Eq + Clone>(
| SystemFunction::Stime
| SystemFunction::Random
| SystemFunction::DistUniform
| SystemFunction::DistNormal
| SystemFunction::DistExponential
| SystemFunction::DistPoisson
| SystemFunction::DistChiSquare
| SystemFunction::DistT
| SystemFunction::DistErlang
| SystemFunction::TestPlusargs
| SystemFunction::ValuePlusargs
| SystemFunction::Urandom
Expand Down
86 changes: 86 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,19 @@ impl<'p, 'a> Ff<'p, 'a> {
args,
..
} => self.plusargs(*function, args)?,
Expr::Call {
callee:
sv::ir::Callee::System(
function @ (sv::ir::SystemFunction::DistNormal
| sv::ir::SystemFunction::DistExponential
| sv::ir::SystemFunction::DistPoisson
| sv::ir::SystemFunction::DistChiSquare
| sv::ir::SystemFunction::DistT
| sv::ir::SystemFunction::DistErlang),
),
args,
..
} => self.distribution(*function, args)?,
Expr::Call {
callee: sv::ir::Callee::System(sv::ir::SystemFunction::DistUniform),
args,
Expand Down Expand Up @@ -1822,6 +1835,79 @@ impl<'p, 'a> Ff<'p, 'a> {
Ok((id, sv::ir::Expr::Ident(name)))
}

fn distribution(
&mut self,
function: sv::ir::SystemFunction,
args: &[Option<sv::ir::Expr>],
) -> Result<sv::ir::Expr, sv::AnalyzerError> {
use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue};
use sv::ir::{Expr, SystemFunction as F};
if self.kernel.is_none() {
return Err(unsupported(format!(
"{} outside a timed process",
function.name()
)));
}
let operation = match function {
F::DistNormal => 0,
F::DistExponential => 1,
F::DistPoisson => 2,
F::DistChiSquare => 3,
F::DistT => 4,
F::DistErlang => 5,
_ => unreachable!(),
};
let seed = args
.first()
.and_then(Option::as_ref)
.ok_or_else(|| unsupported("distribution seed"))?;
// Capture selectors once before evaluating the other actuals, and
// suspend with an int formal rather than writing the caller's storage.
let (lvalues, captured) = self.capture_system_actual(seed)?;
let formal = self.int_formal(captured);
let (seed_id, seed_result) =
self.host_hidden("distribution_seed", &formal, 32, true, true)?;
let value = |id| HostRequestValue {
float_precision: None,
id,
width: 32,
signed: true,
is_string: false,
};
let mut operands = vec![value(seed_id)];
for arg in args.iter().skip(1) {
let arg = self.hoist(
arg.as_ref()
.ok_or_else(|| unsupported("distribution argument"))?,
)?;
let formal = self.int_formal(arg);
let (id, _) = self.host_hidden("distribution_arg", &formal, 32, true, true)?;
operands.push(value(id));
}
let (ret_id, ret_name) = self.m.temp("distribution_result", 32, true, false);
let site = self
.host_request_sites
.iter()
.filter(|site| site.kind == HostRequestKind::Distribution)
.count() as u32;
self.host_request_sites.push(HostRequestSite {
process: 0,
kind: HostRequestKind::Distribution,
requires_timed_simulation: false,
operation,
args: operands,
results: vec![value(ret_id), value(seed_id)],
strings: Vec::new(),
});
self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Distribution, site))
.map_err(kernel_error)?;
match lvalues.as_slice() {
[lvalue] => self.assign(lvalue, &seed_result)?,
parts => self.assign_concat(parts, &seed_result)?,
}
Ok(Expr::Ident(ret_name))
}

fn plusargs(
&mut self,
function: sv::ir::SystemFunction,
Expand Down
199 changes: 199 additions & 0 deletions crates/celox-runtime/src/distribution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
//! Integer probabilistic distributions (IEEE 1800-2023 20.14.2, Annex N).
//!
//! The seed transition wraps at 32 bits. Floating point is only an internal
//! implementation detail; all SystemVerilog formals and results are signed int.

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Distribution {
Normal,
Exponential,
Poisson,
ChiSquare,
T,
Erlang,
}

impl Distribution {
pub fn from_code(code: u32) -> Option<Self> {
Some(match code {
0 => Self::Normal,
1 => Self::Exponential,
2 => Self::Poisson,
3 => Self::ChiSquare,
4 => Self::T,
5 => Self::Erlang,
_ => return None,
})
}

pub fn name(self) -> &'static str {
match self {
Self::Normal => "$dist_normal",
Self::Exponential => "$dist_exponential",
Self::Poisson => "$dist_poisson",
Self::ChiSquare => "$dist_chi_square",
Self::T => "$dist_t",
Self::Erlang => "$dist_erlang",
}
}

/// Draw one value, updating `seed` only after validating the int formals.
pub fn sample(self, seed: &mut i32, args: &[i32]) -> Result<i32, String> {
let arity = if matches!(self, Self::Normal | Self::Erlang) {
2
} else {
1
};
if args.len() != arity {
return Err(format!(
"{} requires {arity} distribution parameters",
self.name()
));
}
if self != Self::Normal && args.iter().any(|value| *value <= 0) {
return Err(format!(
"{} requires positive distribution parameters",
self.name()
));
}
let sample = match self {
Self::Normal => normal(seed) * f64::from(args[1]) + f64::from(args[0]),
Self::Exponential => exponential(seed) * f64::from(args[0]),
Self::Poisson => return Ok(poisson(seed, args[0])),
Self::ChiSquare => chi_square(seed, args[0]),
Self::T => {
let chi = chi_square(seed, args[0]);
normal(seed) / (chi / f64::from(args[0])).sqrt()
}
Self::Erlang => {
let mut product = 1.0;
for _ in 0..args[0] {
product *= uniform(seed, 0.0, 1.0);
}
-f64::from(args[1]) * product.ln() / f64::from(args[0])
}
};
// Annex N rounds symmetrically, halfway away from zero. Its 32-bit
// C conversion produces INT_MIN on an out-of-range result on the
// reference targets; make that behavior explicit instead of relying
// on Rust's saturating float-to-int conversion.
let rounded = sample.round();
Ok(
if !rounded.is_finite()
|| rounded < f64::from(i32::MIN)
|| rounded > f64::from(i32::MAX)
{
i32::MIN
} else {
rounded as i32
},
)
}
}

fn uniform(seed: &mut i32, start: f64, end: f64) -> f64 {
if *seed == 0 {
*seed = 259_341_593;
}
*seed = seed.wrapping_mul(69_069).wrapping_add(1);
let base = f64::from(f32::from_bits(((*seed as u32) >> 9) | 0x3f80_0000));
let adjusted = base + base * (1.0 / 8_388_608.0);
(end - start) * (adjusted - 1.0) + start
}

fn normal(seed: &mut i32) -> f64 {
loop {
let first = uniform(seed, -1.0, 1.0);
let second = uniform(seed, -1.0, 1.0);
let radius = first * first + second * second;
if radius < 1.0 && radius != 0.0 {
return first * (-2.0 * radius.ln() / radius).sqrt();
}
}
}

fn exponential(seed: &mut i32) -> f64 {
let value = uniform(seed, 0.0, 1.0);
if value == 0.0 { 0.0 } else { -value.ln() }
}

fn poisson(seed: &mut i32, mean: i32) -> i32 {
let threshold = (-f64::from(mean)).exp();
let mut product = uniform(seed, 0.0, 1.0);
let mut count = 0;
while threshold < product {
count += 1;
product *= uniform(seed, 0.0, 1.0);
}
count
}

fn chi_square(seed: &mut i32, degrees: i32) -> f64 {
let mut result = if degrees % 2 != 0 {
normal(seed).powi(2)
} else {
0.0
};
for _ in 0..degrees / 2 {
result += 2.0 * exponential(seed);
}
result
}

#[cfg(test)]
mod tests {
use super::Distribution::*;

#[test]
fn annex_n_fixed_seed_vectors() {
for (distribution, args, expected, next) in [
(Normal, vec![0, 10], -4, -642_763_923),
(Exponential, vec![10], 82, 1_174_174),
(Poisson, vec![10], 3, -642_763_923),
(ChiSquare, vec![5], 2, -1_369_077_693),
(T, vec![5], 0, -434_453_879),
(Erlang, vec![3, 10], 33, 861_173_020),
] {
let mut seed = 17;
assert_eq!(distribution.sample(&mut seed, &args).unwrap(), expected);
assert_eq!(seed, next);
}
}

#[test]
fn zero_negative_seeds_and_small_shape_parameters() {
for (distribution, initial, args, expected, next) in [
(Normal, 0, vec![-3, 5], -1, 1_082_744_015),
(Exponential, -1, vec![10], 0, -69_068),
(Poisson, -1, vec![1], 3, 1_486_841_147),
(ChiSquare, 1, vec![2], 22, 69_070),
(T, 1, vec![1], -4, 2_044_158_073),
(Erlang, 0, vec![1, 3], 2, -1_844_104_698),
] {
let mut seed = initial;
assert_eq!(distribution.sample(&mut seed, &args).unwrap(), expected);
assert_eq!(seed, next);
}
}

#[test]
fn invalid_parameters_do_not_advance_seed() {
for (distribution, args) in [
(Exponential, vec![0]),
(Poisson, vec![-1]),
(ChiSquare, vec![0]),
(T, vec![-2]),
(Erlang, vec![0, 10]),
(Erlang, vec![2, 0]),
] {
let mut seed = 17;
assert!(
distribution
.sample(&mut seed, &args)
.unwrap_err()
.contains("positive")
);
assert_eq!(seed, 17);
}
}
}
Loading
Loading