diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index ab3d9e84a5f..cc0b161173d 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -311,6 +311,9 @@ pub struct RuntimeSchema { /// derived from the other state, so state files recompute rather than /// compare them. pub comb_writes: HashSet, + /// Stateful combinational process writes, excluded from derived-value + /// classification when the optimizer builds `comb_writes`. + pub persistent_comb_state: HashSet, /// Dead store elimination policy the program was compiled with. Together /// with `live_signals` and the design it decides which combinationally /// written state the host may observe. @@ -331,6 +334,7 @@ impl Default for RuntimeSchema { testbench_read_roots: HashSet::default(), rtl_writes: HashSet::default(), comb_writes: HashSet::default(), + persistent_comb_state: HashSet::default(), dead_store_policy: DeadStorePolicy::Off, live_signals: HashSet::default(), processes: Vec::new(), diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 6a51de2a556..b8e5edb9a06 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -415,7 +415,7 @@ fn check_package_variable_drivers( } // A continuous driver overlaps every other write. for path in comb_blocks { - let celox_slt::LogicPathTarget::Var(target) = &path.target else { + let Some(target) = path.target.var() else { continue; }; if ff_writes @@ -753,6 +753,7 @@ pub fn schedule_symbolic_rtl( &mut comb_observers, &runtime_event_sites, &mut global_arena, + &unpacked_element_widths, )?; for (site_id, site) in runtime_event_sites.iter().enumerate() { if !matches!(site.kind, RuntimeEventKind::AssertFatal) { @@ -869,6 +870,18 @@ pub fn schedule_symbolic_rtl( ) .collect::>() }); + let mut persistent_comb_state = HashSet::default(); + for path in &comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &path.target { + for block in unit.blocks.values() { + for inst in &block.instructions { + if let SIRInstruction::Store(address, ..) = inst { + persistent_comb_state.insert(*address); + } + } + } + } + } let parallel_comb_blocks = parallel.enabled().then(|| comb_blocks.clone()); let sched_start = flatten_timing.then(std::time::Instant::now); let schedule = match scheduler::sort_with_unpacked_element_widths( @@ -1381,6 +1394,7 @@ pub fn schedule_symbolic_rtl( .map(|(source, state)| (*state, *source)) .collect(); + let persistent_comb_state = persistent_comb_state.into_iter().map(project).collect(); let scheduled = ScheduledRtl { sir, design: ElaboratedDesign { @@ -1408,6 +1422,7 @@ pub fn schedule_symbolic_rtl( testbench_read_roots: Default::default(), rtl_writes, comb_writes: Default::default(), + persistent_comb_state, dead_store_policy: Default::default(), live_signals: Default::default(), processes: process_slots, @@ -1756,7 +1771,9 @@ fn unify_clock_domains( // Internal aliases (e.g. `assign clk_internal = clk_port;`) for logic_path in &sim_module.comb_blocks { // Only unify direct aliases, not complex logic like gated clocks - if logic_path.sources.len() == 1 { + if matches!(logic_path.target, celox_slt::LogicPathTarget::Var(_)) + && logic_path.sources.len() == 1 + { let expr_node = sim_module.arena.get(logic_path.expr); let is_alias = matches!( expr_node, @@ -1919,6 +1936,55 @@ fn build_fused_ff_actions( result } +/// always_comb starts after every initial procedure has reached its first +/// suspension or completion (IEEE 1800-2023 9.2.2.2). Initial status is zero +/// until that happens; all control slots are ordinary checkpointed state. +fn after_initial_processes( + unit: &ExecutionUnit, + statuses: &[AbsoluteAddr], +) -> ExecutionUnit { + use celox_sir::{SIRBuilder, SIROffset, SIRValue}; + let mut b = SIRBuilder::new(); + let mut ready = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(ready, SIRValue::new(1u8))); + for status in statuses { + let value = b.alloc_bit(celox_design::PROCESS_STATUS_WIDTH, false); + b.emit(SIRInstruction::Load( + value, + *status, + SIROffset::Static(0), + celox_design::PROCESS_STATUS_WIDTH, + )); + let started = b.alloc_bit(1, false); + b.emit(SIRInstruction::Unary( + started, + celox_design::UnaryOp::Or, + value, + )); + let next = b.alloc_bit(1, false); + b.emit(SIRInstruction::Binary( + next, + ready, + celox_design::BinaryOp::And, + started, + )); + ready = next; + } + let execute = b.new_block(); + let done = b.new_block(); + b.seal_block(SIRTerminator::Branch { + cond: ready, + true_block: (execute, vec![]), + false_block: (done, vec![]), + }); + b.switch_to_block(execute); + b.inline_execution_unit(unit); + b.seal_block(SIRTerminator::Jump(done, vec![])); + b.switch_to_block(done); + b.flush_eu() + .expect("process activation gate has instructions") +} + fn relocate_units( bindings: &PackageBindings, expanded: &HashMap, @@ -1971,6 +2037,17 @@ fn relocate_units( let mut extern_function_indices = HashMap::::default(); let mut next_runtime_error_code = 2000; let mut parallel_ff_units = parallel_ff_units; + let mut initial_statuses: Vec<_> = expanded + .values() + .flat_map(|id| { + modules[&instance_modules[id]] + .processes + .iter() + .map(|process| bindings.locate(*id, process.slots.status)) + }) + .collect(); + initial_statuses.sort(); + initial_statuses.dedup(); for (path, id) in expanded { let module_id = &instance_modules[id]; @@ -2155,6 +2232,25 @@ fn relocate_units( observer.site_id = runtime_event_site_map[&observer.site_id]; observer.activation_group = runtime_event_site_map[&observer.activation_group]; } + for path in &mut relocated_module.comb_blocks { + if let celox_slt::LogicPathTarget::Process { + unit, + after_initials, + .. + } = &mut path.target + { + **unit = relocate_executation_unit_with_errors( + unit, + &|addr| *addr, + &runtime_error_codes, + &runtime_event_site_map, + &extern_function_map, + ); + if *after_initials && !initial_statuses.is_empty() { + **unit = after_initial_processes(unit, &initial_statuses); + } + } + } comb_blocks.extend(relocated_module.comb_blocks); comb_observers.extend(relocated_module.comb_observers); @@ -2337,12 +2433,13 @@ fn build_comb_observer_capture_paths( observers: &mut [CombObserver], sites: &[RuntimeEventSite], arena: &mut SLTNodeArena, + unpacked_element_widths: &HashMap, ) -> Result<(), ParserError> { if observers.is_empty() { return Ok(()); } - annotate_comb_capture_enable_sites(comb_blocks, observers); + annotate_comb_capture_enable_sites(comb_blocks, observers, unpacked_element_widths); let mut group_members: HashMap> = HashMap::default(); for (idx, observer) in observers.iter().enumerate() { @@ -2806,6 +2903,7 @@ fn capture_contains_nested_snapshot(node: NodeId, arena: &SLTNodeArena], observers: &[CombObserver], + unpacked_element_widths: &HashMap, ) { let mut group_sites: HashMap> = HashMap::default(); for observer in observers { @@ -2830,6 +2928,109 @@ fn annotate_comb_capture_enable_sites( } } } + // A process executes all its writes on its first output projection. + // Compare exactly the observed bits around each store: a dynamic select + // may change another bit of the same object without waking the observer. + use celox_sir::{RegisterId, RegisterType, SIROffset}; + let mut process_writes: HashMap>> = + HashMap::default(); + for path in comb_blocks.iter() { + if let LogicPathTarget::Process { + process, target, .. + } = &path.target + { + process_writes.entry(*process).or_default().push(*target); + } + } + for path in comb_blocks.iter_mut() { + let LogicPathTarget::Process { process, unit, .. } = &mut path.target else { + continue; + }; + let mut probes: Vec<(VarAtomBase, Vec)> = Vec::new(); + for observer in observers { + for atom in &observer.sensitivity { + if !process_writes[&*process] + .iter() + .any(|written| written.id == atom.id && written.access.overlaps(&atom.access)) + { + continue; + } + let index = match probes.iter().position(|(probe, _)| probe == atom) { + Some(index) => index, + None => { + probes.push((*atom, Vec::new())); + probes.len() - 1 + } + }; + for site in &group_sites[&observer.activation_group] { + if !probes[index].1.contains(site) { + probes[index].1.push(*site); + } + } + } + } + let unit = &mut **unit; + let mut next_register = unit + .register_map + .keys() + .map(|reg| reg.0 + 1) + .max() + .unwrap_or(0); + for block in unit.blocks.values_mut() { + let mut instructions = Vec::new(); + for inst in std::mem::take(&mut block.instructions) { + let mut captures = Vec::new(); + if let SIRInstruction::Store(address, offset, width, ..) = &inst { + let written = offset.constant_bit_offset().and_then(|lsb| { + Some(BitAccess::new(lsb, lsb.checked_add(width.checked_sub(1)?)?)) + }); + for (atom, sites) in &probes { + if atom.id != *address + || written.is_some_and(|written| !written.overlaps(&atom.access)) + { + continue; + } + let width = atom.access.msb - atom.access.lsb + 1; + let offset = match unpacked_element_widths.get(address) { + Some(element_width) + if width > *element_width + && atom.access.lsb.is_multiple_of(*element_width) + && width.is_multiple_of(*element_width) => + { + SIROffset::PackedElements { + bit_offset: atom.access.lsb, + element_width: *element_width, + } + } + _ => SIROffset::Static(atom.access.lsb), + }; + let old = RegisterId(next_register); + let new = RegisterId(next_register + 1); + next_register += 2; + unit.register_map.insert(old, RegisterType::Logic { width }); + unit.register_map.insert(new, RegisterType::Logic { width }); + instructions.push(SIRInstruction::Load( + old, + *address, + offset.clone(), + width, + )); + captures.push((old, new, *address, offset, width, sites)); + } + } + instructions.push(inst); + for (old, new, address, offset, width, sites) in captures { + instructions.push(SIRInstruction::Load(new, address, offset, width)); + instructions.push(SIRInstruction::CombCaptureEnableIfChanged { + old, + new, + sites: sites.clone(), + }); + } + } + block.instructions = instructions; + } + } } fn observer_order_after( @@ -3022,7 +3223,11 @@ fn analyze_clock_dependencies( }; let target_abs = target.id; let mut sources = HashSet::default(); - crate::flattening::collect_inputs(path.expr, arena, &mut sources); + if matches!(path.target, celox_slt::LogicPathTarget::Process { .. }) { + sources.extend(path.sources.iter().cloned()); + } else { + crate::flattening::collect_inputs(path.expr, arena, &mut sources); + } for source in sources { comb_deps.entry(target_abs).or_default().insert(source.id); } diff --git a/crates/celox-frontend-core/src/symbolic/flattening.rs b/crates/celox-frontend-core/src/symbolic/flattening.rs index 921aac93822..b31cfe65896 100644 --- a/crates/celox-frontend-core/src/symbolic/flattening.rs +++ b/crates/celox-frontend-core/src/symbolic/flattening.rs @@ -309,6 +309,10 @@ fn atomize_logic_paths( let mut atomized_paths = Vec::new(); for path in paths { + if matches!(path.target, LogicPathTarget::Process { .. }) { + atomized_paths.push(path.clone()); + continue; + } let Some(target_var) = path.target.var() else { atomized_paths.push(path.clone()); continue; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 411ea37dcd5..0ca7bcdd834 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -2422,6 +2422,8 @@ pub(crate) fn attach_instance_glue( &lowered.constants, &lowered.parameter_types, four_state, + &mut module.runtime_errors, + &mut module.extern_functions, ) .map_err(|error| match error { sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile { @@ -2463,6 +2465,17 @@ pub(crate) fn attach_instance_glue( ) })?; } + for path in &mut module.comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &mut path.target { + for block in unit.blocks.values_mut() { + for inst in &mut block.instructions { + if let SIRInstruction::RuntimeEvent { site_id, .. } = inst { + *site_id += site_base; + } + } + } + } + } for mut observer in comb_observers { observer.site_id += site_base; observer.activation_group += site_base; @@ -2653,6 +2666,42 @@ fn expr_for_state_mode(expr: &sv::ir::Expr, four_state: bool) -> sv::ir::Expr { } } +/// Process kind and index identify a thread without merging the lowering paths. +/// Each instance owns an initialization RNG seeded with the same default +/// (IEEE 1800-2023 18.14.1); relocation keeps sibling RNG states independent. +fn process_random_seeds(module: &sv::ir::Module) -> HashMap<(u8, usize), u32> { + let mut processes: Vec<_> = module + .ff_processes() + .iter() + .enumerate() + .map(|(i, p)| (p.creation_order(), 0u8, i)) + .chain( + module + .initial_processes() + .iter() + .enumerate() + .filter(|(_, p)| !p.is_synthetic()) + .map(|(i, p)| (p.creation_order(), 1, i)), + ) + .chain( + module + .comb_processes() + .iter() + .enumerate() + .map(|(i, p)| (p.creation_order(), 2, i)), + ) + .collect(); + processes.sort_by_key(|&(order, kind, i)| (order, kind, i)); + let mut state = 0x4d59_5df4u32; + processes + .into_iter() + .map(|(_, kind, index)| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + ((kind, index), state) + }) + .collect() +} + /// The `initial` blocks and declaration initializers (IEEE 1800-2023 9.2.1, /// 10.5): the initial state they define, and the processes that run the /// others from time zero. @@ -2690,7 +2739,8 @@ fn lower_initial_processes( ); let mut arena = SLTNodeArena::new(); let mut seed = comb::Store::default(); - for process in module.initial_processes() { + let random_seeds = process_random_seeds(module); + for (index, process) in module.initial_processes().iter().enumerate() { if let Some(condition) = process.condition() { let condition = sv::typecheck::eval_const_expr_with_types(condition, constants, parameter_types) @@ -2701,6 +2751,10 @@ fn lower_initial_processes( continue; } } + let random_seed = random_seeds + .get(&(1, index)) + .copied() + .unwrap_or(0x4d59_5df4); let mut comb = comb::Comb::new(&mut pm, &mut arena); match comb.lower_initial(process.body(), process.is_initializer(), &seed) { Ok((written, store)) => { @@ -2709,7 +2763,7 @@ fn lower_initial_processes( seed = store; } } - Err(_) => runtime.push(process), + Err(_) => runtime.push((process, random_seed)), } } let created = std::mem::take(&mut pm.created); @@ -2776,9 +2830,10 @@ fn lower_initial_processes( let processes = runtime .into_iter() .zip(slots) - .map(|(process, slots)| { + .map(|((process, random_seed), slots)| { Ok(SymbolicProcess { - kernel: ff::Ff::new(&mut pm).lower_initial_kernel(process.body(), slots)?, + kernel: ff::Ff::new(&mut pm, random_seed) + .lower_initial_kernel(process.body(), slots)?, slots, }) }) @@ -2796,6 +2851,8 @@ fn lower_comb_processes( constants: &HashMap, parameter_types: &HashMap, four_state: bool, + runtime_errors: &mut HashMap>, + extern_functions: &mut Vec, ) -> Result< ( Vec>, @@ -2818,7 +2875,10 @@ fn lower_comb_processes( parameter_types, four_state, ); - for process in module.comb_processes() { + pm.runtime_errors = std::mem::take(runtime_errors); + pm.extern_functions = std::mem::take(extern_functions); + let random_seeds = process_random_seeds(module); + for (index, process) in module.comb_processes().iter().enumerate() { if let Some(condition) = process.condition() { let condition = sv::typecheck::eval_const_expr_with_types(condition, constants, parameter_types) @@ -2831,10 +2891,65 @@ fn lower_comb_processes( continue; } } + if pm.uses_random(process.body()) { + pm.runtime_event_sites = std::mem::take(&mut sites); + comb_blocks.extend( + ff::Ff::new(&mut pm, random_seeds[&(2, index)]).lower_comb_process( + process.body(), + process.sensitivity_body(), + process.kind(), + &mut arena, + )?, + ); + sites = std::mem::take(&mut pm.runtime_event_sites); + continue; + } let mut comb = comb::Comb::new(&mut pm, &mut arena); comb.site_base = sites.len() as u32; comb.continuous = process.kind() == sv::ir::CombProcessKind::ContinuousAssign; comb_blocks.extend(comb.lower_process(process.body())?); + if comb.observers.iter().any(|observer| { + observer + .sensitivity + .iter() + .any(|atom| !comb.m.var(atom.id).array_dims.is_empty()) + }) { + // Symbolic array reads may conservatively depend on every element. + // Process activation follows the syntactic static selection instead. + let include_functions = process.kind() != sv::ir::CombProcessKind::AlwaysStar; + let mut reads = comb.m.implicit_reads(process.body(), include_functions); + reads.extend( + comb.m + .implicit_reads(process.sensitivity_body(), include_functions), + ); + for observer in &mut comb.observers { + observer.sensitivity = observer + .sensitivity + .iter() + .flat_map(|atom| { + if comb.m.var(atom.id).array_dims.is_empty() { + return vec![*atom]; + } + let selected: Vec<_> = reads + .iter() + .filter(|read| read.id == atom.id && read.access.overlaps(&atom.access)) + .map(|read| { + VarAtomBase::new( + atom.id, + read.access.lsb.max(atom.access.lsb), + read.access.msb.min(atom.access.msb), + ) + }) + .collect(); + if selected.is_empty() { + vec![*atom] + } else { + selected + } + }) + .collect(); + } + } // The sites of one process activate together. let base = sites.len() as u32; for mut observer in std::mem::take(&mut comb.observers) { @@ -2843,6 +2958,8 @@ fn lower_comb_processes( } sites.append(&mut comb.sites); } + *runtime_errors = std::mem::take(&mut pm.runtime_errors); + *extern_functions = std::mem::take(&mut pm.extern_functions); let created = std::mem::take(&mut pm.created); Ok((comb_blocks, arena, created, observers, sites)) } @@ -6074,7 +6191,8 @@ fn lower_ff_processes( let mut clock_edges = HashMap::default(); let mut reset_edges = HashMap::default(); - for process in module.ff_processes() { + let random_seeds = process_random_seeds(module); + for (index, process) in module.ff_processes().iter().enumerate() { let clock = clock_event_from_ff_process(process) .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".to_string()))?; let clock_id = pm @@ -6142,7 +6260,8 @@ fn lower_ff_processes( } let sites_before = pm.runtime_event_sites.len(); let extern_calls_before = pm.extern_calls; - let (eval_only, apply, targets) = ff::Ff::new(pm).lower_process(process.body())?; + let (eval_only, apply, targets) = + ff::Ff::new(pm, random_seeds[&(0, index)]).lower_process(process.body())?; // A process without writes still runs for its runtime events and // extern calls. let has_effects = diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 11c4a1975d2..325df6e9087 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -846,6 +846,9 @@ impl<'p, 'a> Comb<'p, 'a> { expr_from_const_expr(expr).ok_or_else(|| unsupported("operand in a select")) }; Ok(match expr { + ConstExpr::Function { name, .. } if name == "$urandom" => { + return Err(unsupported("$urandom called in combinational logic")); + } ConstExpr::Function { name, args, .. } if self.m.subroutines.contains_key(name) || self.m.dpi_imports.contains_key(name) => @@ -1147,6 +1150,9 @@ impl<'p, 'a> Comb<'p, 'a> { return Ok(expr.clone()); } Ok(match expr { + Expr::Call { name, .. } if name == "$urandom" => { + return Err(unsupported("$urandom called in combinational logic")); + } Expr::Call { name, .. } if self.m.dpi_imports.contains_key(name) => { return Err(unsupported(format!( "DPI-C function `{name}` called in combinational logic" @@ -3460,7 +3466,10 @@ impl<'p, 'a> Comb<'p, 'a> { } /// `atoms` without the bits in `written`. -fn subtract_written_sensitivity(atoms: Sources, written: &[VarAtomBase]) -> Sources { +pub(super) fn subtract_written_sensitivity( + atoms: Sources, + written: &[VarAtomBase], +) -> Sources { let mut result = Sources::default(); for atom in atoms { let mut ranges = vec![(atom.access.lsb, atom.access.msb)]; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 3eb2e2450a8..8a88829027e 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -46,10 +46,15 @@ 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. + random: Option<(SourceVarId, String)>, + random_seed: u32, /// 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. kernel: Option, + direct: bool, } fn stable(var_id: SourceVarId) -> Addr { @@ -67,7 +72,7 @@ fn working(var_id: SourceVarId) -> Addr { } impl<'p, 'a> Ff<'p, 'a> { - pub fn new(m: &'p mut ProcModule<'a>) -> Self { + pub fn new(m: &'p mut ProcModule<'a>, random_seed: u32) -> Self { let mut element_widths = HashMap::default(); for (&id, variable) in m.variables.iter() { if let Some(width) = unpacked_element_width(variable) { @@ -88,14 +93,17 @@ impl<'p, 'a> Ff<'p, 'a> { unrolled: 0, aliases: HashMap::default(), next_alias: u32::MAX, + random: None, + random_seed, kernel: None, + direct: false, } } /// Where a write of `id`, and a read of a value the process wrote, go: /// the working region, or stable state in a process kernel. fn target(&self, id: SourceVarId) -> Addr { - if self.kernel.is_some() { + if self.kernel.is_some() || self.direct { stable(id) } else { working(id) @@ -204,6 +212,12 @@ impl<'p, 'a> Ff<'p, 'a> { stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); } while let Some((name, args)) = calls.pop() { + if name == "$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)); + } let Some(subroutine) = self.m.subroutine(&name).cloned() else { continue; }; @@ -235,7 +249,7 @@ impl<'p, 'a> Ff<'p, 'a> { let aliases = &self.aliases; let working_set = &self.working; let variables = &*self.m.variables; - let direct = self.kernel.is_some(); + let direct = self.kernel.is_some() || self.direct; let map = |id: &SourceVarId| -> Addr { if direct { stable(*aliases.get(id).unwrap_or(id)) @@ -488,10 +502,7 @@ impl<'p, 'a> Ff<'p, 'a> { expr_from_const_expr(expr).ok_or_else(|| unsupported("operand in a select")) }; Ok(match expr { - ConstExpr::Function { name, args, .. } - if self.m.subroutines.contains_key(name) - || self.m.dpi_imports.contains_key(name) => - { + ConstExpr::Function { name, args, .. } if self.m.is_callee(name) => { if let Some((_, result)) = calls.iter().find(|(call, _)| call == expr) { return Ok(result.clone()); } @@ -771,6 +782,7 @@ impl<'p, 'a> Ff<'p, 'a> { return Ok(expr.clone()); } Ok(match expr { + Expr::Call { name, args, .. } if name == "$urandom" => self.urandom(args)?, Expr::Call { name, args, @@ -1024,6 +1036,63 @@ impl<'p, 'a> Ff<'p, 'a> { // ---------------------------------------------------------------- stores + /// 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 { + 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)?, + None => Expr::Mux { + condition: Box::new(Expr::Binary { + left: Box::new(Expr::Ident(name.clone())), + op: BinaryOp::Eq, + right: Box::new(Expr::Literal("33'd0".into())), + }), + then_expr: Box::new(Expr::Literal(format!("32'd{}", self.random_seed))), + else_expr: Box::new(Expr::Ident(name.clone())), + }, + }; + // 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, + }), + op: BinaryOp::Mul, + right: Box::new(Expr::Literal("32'd1664525".into())), + }), + op: BinaryOp::Add, + 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 state = self.eval(&state, Some((33, false)))?; + self.store(id, SIROffset::Static(0), 33, state); + Ok(Expr::Ident(temp_name)) + } + fn store(&mut self, id: SourceVarId, offset: SIROffset, width: usize, value: RegisterId) { let target = self.target(id); self.b.emit(SIRInstruction::Store( @@ -2293,6 +2362,218 @@ impl<'p, 'a> Ff<'p, 'a> { // -------------------------------------------------------------- process + /// Lower a stateful combinational process. Its memory guard records the + /// implicit sensitivity values, independently of internal settling calls. + pub fn lower_comb_process( + mut self, + body: &[sv::ir::Stmt], + sensitivity_body: &[sv::ir::Stmt], + kind: sv::ir::CombProcessKind, + arena: &mut SLTNodeArena, + ) -> Result>, sv::AnalyzerError> { + let always_comb = kind != sv::ir::CombProcessKind::AlwaysStar; + self.direct = true; + let mut reads = self.m.implicit_reads(body, always_comb); + reads.extend(self.m.implicit_reads(sensitivity_body, always_comb)); + for stmt in body { + let mut nonblocking = false; + stmt.walk(&mut |stmt| { + nonblocking |= matches!( + stmt, + sv::ir::Stmt::Assign { + nonblocking: true, + .. + } | sv::ir::Stmt::AssignConcat { + nonblocking: true, + .. + } + ) + }); + if nonblocking { + return Err(unsupported("nonblocking assignment inside always_comb")); + } + } + self.scan(body, &mut HashSet::default()); + if self.exec_block(body)? { + self.b.seal_block(SIRTerminator::Return); + } + let body_unit = seal_drained(std::mem::replace(&mut self.b, SIRBuilder::new())); + let mut targets: Vec<_> = self + .targets + .iter() + .filter(|(id, _)| !self.m.is_hidden(*id)) + .map(|(id, access)| VarAtomBase::new(*id, access.lsb, access.msb)) + .collect(); + targets.sort_by_key(|atom| (atom.id.0, atom.access.lsb, atom.access.msb)); + let mut merged: Vec> = Vec::new(); + for target in targets { + match merged.last_mut() { + Some(last) if last.id == target.id && target.access.lsb <= last.access.msb + 1 => { + last.access.msb = last.access.msb.max(target.access.msb) + } + _ => merged.push(target), + } + } + let mut targets = merged; + let dependencies = super::comb::subtract_written_sensitivity(reads.clone(), &targets); + let mut sources: Vec<_> = if always_comb { + dependencies.clone() + } else { + reads + } + .into_iter() + .collect(); + sources.sort_by_key(|atom| (atom.id.0, atom.access.lsb, atom.access.msb)); + let (initialized, _) = self.m.temp("comb_initialized", 1, false, false); + let init = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Load( + init, + stable(initialized), + SIROffset::Static(0), + 1, + )); + let mut changed = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Imm(changed, SIRValue::new(0u8))); + let mut snapshots = Vec::new(); + for source in &sources { + let width = source.access.msb - source.access.lsb + 1; + let (saved, _) = self.m.temp( + "comb_input", + width, + false, + self.m.four_state && self.m.var(source.id).is_4state, + ); + let current = self.b.alloc_logic(width); + let previous = self.b.alloc_logic(width); + let offset = sv_memory_offset(self.m.var(source.id), source.access.lsb, width); + self.b.emit(SIRInstruction::Load( + current, + stable(source.id), + offset, + width, + )); + self.b.emit(SIRInstruction::Load( + previous, + stable(saved), + SIROffset::Static(0), + width, + )); + let differs = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + differs, + current, + BinaryOp::NeCase, + previous, + )); + let next = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(next, changed, BinaryOp::Or, differs)); + changed = next; + snapshots.push((saved, width, current)); + } + let run = self.b.alloc_bit(1, false); + if always_comb { + let first = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Unary(first, UnaryOp::LogicNot, init)); + self.b + .emit(SIRInstruction::Binary(run, first, BinaryOp::Or, changed)); + } else { + self.b + .emit(SIRInstruction::Binary(run, init, BinaryOp::And, changed)); + } + // Snapshot before executing: writes in the body do not retrigger it. + for &(saved, width, current) in &snapshots { + self.store(saved, SIROffset::Static(0), width, current); + } + let one = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + self.store(initialized, SIROffset::Static(0), 1, one); + let execute = self.b.new_block(); + let done = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: run, + true_block: (execute, vec![]), + false_block: (done, vec![]), + }); + self.b.switch_to_block(execute); + self.b.inline_execution_unit(&body_unit); + if !always_comb { + // @* is not waiting during its body. Its own writes cannot wake + // the same activation, including when another output is published. + for (source, &(saved, width, _)) in sources.iter().zip(&snapshots) { + let current = self.b.alloc_logic(width); + let offset = sv_memory_offset(self.m.var(source.id), source.access.lsb, width); + self.b.emit(SIRInstruction::Load( + current, + stable(source.id), + offset, + width, + )); + self.store(saved, SIROffset::Static(0), width, current); + } + } + self.jump(done); + self.b.switch_to_block(done); + let mut private_locals = HashMap::default(); + let unit = seal_builder(self.b).into_map_addr(&mut |addr| { + let id = addr.var_id; + if !self.m.is_hidden(id) || self.m.created.contains(&id) { + return id; + } + *private_locals.entry(id).or_insert_with(|| { + let variable = self.m.var(id).clone(); + let (copy, name) = self.m.temp( + "comb_local", + variable.width, + variable.signed, + variable.is_4state, + ); + self.m.variables.insert( + copy, + SvVariable { + path: vec![name], + ..variable + }, + ); + copy + }) + }); + if targets.is_empty() { + targets.push(VarAtomBase::new(initialized, 0, 0)); + } + let mut paths = Vec::new(); + for target in targets { + let expr = arena + .alloc(SLTNode::Input { + variable: target.id, + signed: false, + index: Vec::new(), + access: target.access, + }) + .map_err(slt_error)?; + paths.push(LogicPath { + target: LogicPathTarget::Process { + process: initialized, + after_initials: kind == sv::ir::CombProcessKind::AlwaysComb, + target, + unit: Box::new(unit.clone()), + }, + sources: dependencies.clone(), + previous_sources: HashSet::default(), + address_sources: HashSet::default(), + local_inputs: Vec::new(), + order_before: HashSet::default(), + comb_capture_enable_sites: Vec::new(), + comb_capture_enable_always: false, + pre_lower_nodes: Vec::new(), + expr, + }); + } + Ok(paths) + } + /// Lower one `always_ff` body into its evaluation and commit units. pub fn lower_process( mut self, diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index fbc35d6d74a..43f1660a05b 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -143,6 +143,183 @@ impl<'a> ProcModule<'a> { } } + /// Whether a process calls the random 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 { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + let mut visited = HashSet::default(); + while let Some((name, args)) = calls.pop() { + if name == "$urandom" { + return true; + } + if let Some(subroutine) = self.subroutine(&name) { + default_calls(subroutine, &args, &mut calls); + if visited.insert(name) { + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + } + } + } + false + } + + /// Syntactic implicit sensitivity, including branches that constant folding + /// will remove. `always @*` sees arguments; `always_comb` also sees bodies. + pub fn implicit_reads( + &self, + body: &[sv::ir::Stmt], + include_functions: bool, + ) -> HashSet> { + fn expression( + m: &ProcModule<'_>, + expr: &sv::ir::Expr, + include_functions: bool, + visited: &mut HashSet, + reads: &mut HashSet>, + ) { + let mut exprs = Vec::new(); + use sv::ir::Expr; + match expr { + Expr::Call { name, args, .. } => { + exprs.extend(args.iter().flatten().cloned()); + if let Some(subroutine) = m.subroutine(name) { + for (i, param) in subroutine.params.iter().enumerate() { + if args.get(i).and_then(Option::as_ref).is_none() { + exprs.extend(param.default.clone()); + } + } + if include_functions && visited.insert(name.clone()) { + statements(m, &subroutine.body, true, visited, reads); + statements(m, &subroutine.sensitivity_body, true, visited, reads); + } + } + } + Expr::Select { + expr: base, + msb, + lsb, + .. + } => { + let selected = sv::typecheck::eval_const_expr_with_types( + msb, + m.constants, + m.parameter_types, + ) + .zip(sv::typecheck::eval_const_expr_with_types( + lsb, + m.constants, + m.parameter_types, + )) + .and_then(|(msb, lsb)| { + packed_expr_select_offsets(base, msb, lsb, m.variables, m.name_to_id) + }); + if let (Expr::Ident(name), Some((msb, lsb))) = (&**base, selected) + && let Some(id) = m.id(name).filter(|id| !m.is_hidden(*id)) + { + reads.insert(VarAtomBase::new(id, lsb.min(msb), lsb.max(msb))); + } else { + // A dynamic select's longest static prefix is its base. + exprs.push((**base).clone()); + } + exprs.extend(expr_from_const_expr(msb)); + exprs.extend(expr_from_const_expr(lsb)); + } + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => { + exprs.push((**expr).clone()) + } + Expr::Binary { left, right, .. } => { + exprs.push((**left).clone()); + exprs.push((**right).clone()); + } + Expr::Mux { + condition, + then_expr, + else_expr, + } => { + exprs.extend([ + (**condition).clone(), + (**then_expr).clone(), + (**else_expr).clone(), + ]); + } + Expr::Concat(parts) => exprs.extend(parts.iter().cloned()), + Expr::RepeatConcat { count, parts } => { + exprs.extend(expr_from_const_expr(count)); + exprs.extend(parts.iter().cloned()); + } + Expr::Inside { expr, items } => { + exprs.push((**expr).clone()); + for item in items { + exprs.extend(item.exprs().into_iter().cloned()); + } + } + Expr::Ident(name) => { + if let Some(id) = m.id(name).filter(|id| !m.is_hidden(*id)) { + reads.insert(VarAtomBase::new(id, 0, m.var(id).width - 1)); + } + } + Expr::Literal(_) => {} + } + for expr in exprs { + expression(m, &expr, include_functions, visited, reads); + } + } + fn statements( + m: &ProcModule<'_>, + body: &[sv::ir::Stmt], + include_functions: bool, + visited: &mut HashSet, + reads: &mut HashSet>, + ) { + let mut exprs = Vec::new(); + let mut positions = Vec::new(); + for stmt in body { + let _ = stmt.clone().map( + &mut |expr| { + exprs.push(expr); + }, + &mut |lhs| { + if let sv::ir::LValue::Select { msb, lsb, .. } = lhs { + positions.extend(expr_from_const_expr(&msb)); + positions.extend(expr_from_const_expr(&lsb)); + } + }, + ); + // A call statement carries its callee outside the expression visitor. + stmt.walk(&mut |stmt| { + if let sv::ir::Stmt::Call { + name, + args, + arg_order, + } = stmt + { + exprs.push(sv::ir::Expr::Call { + name: name.clone(), + args: args.clone(), + arg_order: arg_order.clone(), + }); + } + }); + } + for expr in exprs.into_iter().chain(positions) { + expression(m, &expr, include_functions, visited, reads); + } + } + let mut reads = HashSet::default(); + statements( + self, + body, + include_functions, + &mut HashSet::default(), + &mut reads, + ); + reads + } + /// The words `$readmemh`/`$readmemb` (IEEE 1800-2023 21.4) write, with /// the values of its optional start and finish addresses: the file is /// read when the design is compiled. @@ -341,17 +518,19 @@ impl<'a> ProcModule<'a> { self.subroutines.get(name) } - /// Whether an expression calls a user subroutine or a DPI-C import. + pub fn is_callee(&self, name: &str) -> bool { + name == "$urandom" + || self.subroutines.contains_key(name) + || self.dpi_imports.contains_key(name) + } + + /// Whether an expression contains a call whose evaluation has effects. pub fn lvalue_calls(&self, lvalue: &sv::ir::LValue) -> bool { - lvalue_calls(lvalue, &|name| { - self.subroutines.contains_key(name) || self.dpi_imports.contains_key(name) - }) + lvalue_calls(lvalue, &|name| self.is_callee(name)) } pub fn const_calls(&self, expr: &sv::ir::ConstExpr) -> bool { - const_calls(expr, &|name| { - self.subroutines.contains_key(name) || self.dpi_imports.contains_key(name) - }) + const_calls(expr, &|name| self.is_callee(name)) } /// The largest subexpressions of `expr` that call a subroutine and also @@ -362,19 +541,12 @@ impl<'a> ProcModule<'a> { other: &sv::ir::ConstExpr, ) -> Vec<&'e sv::ir::ConstExpr> { let mut shared = Vec::new(); - shared_calls( - expr, - other, - &|name| self.subroutines.contains_key(name) || self.dpi_imports.contains_key(name), - &mut shared, - ); + shared_calls(expr, other, &|name| self.is_callee(name), &mut shared); shared } pub fn calls(&self, expr: &sv::ir::Expr) -> bool { - expr_calls(expr, &|name| { - self.subroutines.contains_key(name) || self.dpi_imports.contains_key(name) - }) + expr_calls(expr, &|name| self.is_callee(name)) } /// The local index of the extern function `import` links to. Imports diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree.rs index b8dbdef069d..ee8f67d3832 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree.rs @@ -409,10 +409,12 @@ fn dump_comb_path_stats_if_requested( total_muxes += stats.muxes; total_inputs += stats.inputs; let target = match &path.target { - LogicPathTarget::Var(var) => module.variables.get(&var.id).map_or_else( - || var.to_string(), - |info| format!("{}[{}:{}]", info.path, var.access.msb, var.access.lsb), - ), + LogicPathTarget::Var(var) | LogicPathTarget::Process { target: var, .. } => { + module.variables.get(&var.id).map_or_else( + || var.to_string(), + |info| format!("{}[{}:{}]", info.path, var.access.msb, var.access.lsb), + ) + } LogicPathTarget::CombCaptureEvent { site_id, .. } => { format!("capture_event({site_id})") } diff --git a/crates/celox-sir/src/builder.rs b/crates/celox-sir/src/builder.rs index 36c4ded6333..2d2f999055e 100644 --- a/crates/celox-sir/src/builder.rs +++ b/crates/celox-sir/src/builder.rs @@ -209,6 +209,82 @@ impl SIRBuilder { } } + /// Append a control-flow unit, continuing after any normal return. + pub fn inline_execution_unit(&mut self, unit: &crate::ExecutionUnit) + where + Addr: Clone, + { + let ro = self.next_reg_id; + let bo = self.next_block_id; + let r = |id: RegisterId| RegisterId(id.0 + ro); + let b = |id: BlockId| BlockId(id.0 + bo); + self.next_reg_id += unit + .register_map + .keys() + .map(|id| id.0 + 1) + .max() + .unwrap_or(0); + self.next_block_id += unit.blocks.keys().map(|id| id.0 + 1).max().unwrap_or(0); + let done = self.new_block(); + self.seal_block(SIRTerminator::Jump(b(unit.entry_block_id), vec![])); + for (id, ty) in &unit.register_map { + self.registers.insert(r(*id), ty.clone()); + } + for (id, block) in &unit.blocks { + let terminator = match &block.terminator { + SIRTerminator::Return => SIRTerminator::Jump(done, vec![]), + SIRTerminator::Error(code) => SIRTerminator::Error(*code), + SIRTerminator::Jump(target, args) => { + SIRTerminator::Jump(b(*target), args.iter().copied().map(r).collect()) + } + SIRTerminator::Branch { + cond, + true_block, + false_block, + } => SIRTerminator::Branch { + cond: r(*cond), + true_block: ( + b(true_block.0), + true_block.1.iter().copied().map(r).collect(), + ), + false_block: ( + b(false_block.0), + false_block.1.iter().copied().map(r).collect(), + ), + }, + SIRTerminator::Switch { + selector, + cases, + default, + } => SIRTerminator::Switch { + selector: r(*selector), + cases: cases + .iter() + .map(|case| crate::SIRSwitchCase { + value: case.value.clone(), + target: b(case.target), + }) + .collect(), + default: b(*default), + }, + }; + self.blocks.insert( + b(*id), + BasicBlock { + id: b(*id), + params: block.params.iter().copied().map(r).collect(), + instructions: block + .instructions + .iter() + .map(|inst| crate::transform::renumber_sir_inst(inst, ro, bo)) + .collect(), + terminator, + }, + ); + } + self.switch_to_block(done); + } + /// Returns the total number of blocks currently in this builder. pub fn block_count(&self) -> usize { self.blocks.len() @@ -290,6 +366,151 @@ mod tests { } } + #[test] + fn inlines_sparse_control_flow_with_params_and_dynamic_offsets() { + let input = crate::ExecutionUnit:: { + entry_block_id: BlockId(17), + register_map: HashMap::from_iter([ + ( + RegisterId(41), + RegisterType::Bit { + width: 1, + signed: false, + }, + ), + ( + RegisterId(42), + RegisterType::Bit { + width: 8, + signed: false, + }, + ), + ( + RegisterId(72), + RegisterType::Bit { + width: 32, + signed: false, + }, + ), + ( + RegisterId(90), + RegisterType::Bit { + width: 1, + signed: false, + }, + ), + (RegisterId(91), RegisterType::Logic { width: 32 }), + ]), + blocks: HashMap::from_iter([ + ( + BlockId(17), + BasicBlock { + id: BlockId(17), + params: vec![], + instructions: vec![ + SIRInstruction::Imm(RegisterId(41), SIRValue::new(1u8)), + SIRInstruction::Imm(RegisterId(42), SIRValue::new(2u8)), + ], + terminator: SIRTerminator::Branch { + cond: RegisterId(41), + true_block: (BlockId(50), vec![RegisterId(41)]), + false_block: (BlockId(80), vec![]), + }, + }, + ), + ( + BlockId(50), + BasicBlock { + id: BlockId(50), + params: vec![RegisterId(90)], + instructions: vec![ + SIRInstruction::Imm(RegisterId(72), SIRValue::new(0u8)), + SIRInstruction::Load( + RegisterId(91), + 0, + crate::SIROffset::Dynamic(RegisterId(72)), + 32, + ), + SIRInstruction::Store( + 0, + crate::SIROffset::Dynamic(RegisterId(72)), + 32, + RegisterId(91), + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }, + ), + ( + BlockId(80), + BasicBlock { + id: BlockId(80), + params: vec![], + instructions: vec![], + terminator: SIRTerminator::Switch { + selector: RegisterId(42), + cases: vec![crate::SIRSwitchCase { + value: 2u8.into(), + target: BlockId(70), + }], + default: BlockId(100), + }, + }, + ), + ( + BlockId(70), + BasicBlock { + id: BlockId(70), + params: vec![], + instructions: vec![], + terminator: SIRTerminator::Return, + }, + ), + ( + BlockId(100), + BasicBlock { + id: BlockId(100), + params: vec![], + instructions: vec![], + terminator: SIRTerminator::Error(19), + }, + ), + ]), + }; + input.verify(); + let mut builder = SIRBuilder::new(); + let prefix = builder.alloc_bit(8, false); + builder.emit(SIRInstruction::Imm(prefix, SIRValue::new(7u8))); + builder.inline_execution_unit(&input); + builder.inline_execution_unit(&input); + builder.emit(SIRInstruction::Store( + 1, + crate::SIROffset::Static(0), + 8, + prefix, + vec![], + vec![], + )); + let unit = builder.flush_eu().unwrap(); + unit.verify(); + assert_eq!( + unit.blocks + .values() + .filter(|block| matches!(block.terminator, SIRTerminator::Return)) + .count(), + 1 + ); + assert_eq!( + unit.blocks + .values() + .filter(|block| matches!(block.terminator, SIRTerminator::Error(19))) + .count(), + 2 + ); + } + #[test] fn canonicalizes_logic_branch_condition() { let unit = branch_unit(RegisterType::Logic { width: 8 }); diff --git a/crates/celox-sir/src/transform.rs b/crates/celox-sir/src/transform.rs index 1bf8c5b11f7..7d3dfc4fdcd 100644 --- a/crates/celox-sir/src/transform.rs +++ b/crates/celox-sir/src/transform.rs @@ -349,7 +349,7 @@ fn replace_sir_terminator_uses( SIRTerminator::Return | SIRTerminator::Error(_) => {} } } -fn renumber_sir_inst( +pub(crate) fn renumber_sir_inst( inst: &SIRInstruction, ro: usize, _bo: usize, diff --git a/crates/celox-slt/src/path.rs b/crates/celox-slt/src/path.rs index a61e9175ee3..12f651bec8b 100644 --- a/crates/celox-slt/src/path.rs +++ b/crates/celox-slt/src/path.rs @@ -16,6 +16,14 @@ pub struct LogicPathId(pub usize); ))] pub enum LogicPathTarget { Var(VarAtomBase), + /// An imperative combinational process. All its output paths share a + /// sensitivity guard in the unit, so one activation executes it once. + Process { + process: A, + after_initials: bool, + target: VarAtomBase, + unit: Box>, + }, CombCaptureEvent { site_id: u32, guard: Option, @@ -30,7 +38,7 @@ pub enum LogicPathTarget { impl LogicPathTarget { pub fn var(&self) -> Option<&VarAtomBase> { match self { - LogicPathTarget::Var(var) => Some(var), + LogicPathTarget::Var(var) | LogicPathTarget::Process { target: var, .. } => Some(var), LogicPathTarget::CombCaptureEvent { .. } => None, } } @@ -40,6 +48,7 @@ impl fmt::Display for LogicPathTarget { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { LogicPathTarget::Var(var) => write!(f, "{var}"), + LogicPathTarget::Process { target, .. } => write!(f, "process({target})"), LogicPathTarget::CombCaptureEvent { site_id, .. } => { write!(f, "capture_event({site_id})") } @@ -94,6 +103,17 @@ impl LogicPath { LogicPathTarget::Var(var) => { LogicPathTarget::Var(VarAtomBase::new(f(&var.id), var.access.lsb, var.access.msb)) } + LogicPathTarget::Process { + process, + after_initials, + target, + unit, + } => LogicPathTarget::Process { + process: f(process), + after_initials: *after_initials, + target: VarAtomBase::new(f(&target.id), target.access.lsb, target.access.msb), + unit: Box::new((**unit).clone().into_map_addr(&mut |addr| f(&addr))), + }, LogicPathTarget::CombCaptureEvent { site_id, guard, diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs index 8c54305a498..ae4b329d326 100644 --- a/crates/celox-slt/src/scheduler.rs +++ b/crates/celox-slt/src/scheduler.rs @@ -692,6 +692,16 @@ where } } } + // A process publishes multiple outputs but owns one activation guard and + // RNG state. Keep its projections ordered, including in cyclic schedules. + let mut previous_process_path = HashMap::default(); + for (index, path) in input.iter().enumerate() { + if let LogicPathTarget::Process { process, .. } = &path.target { + if let Some(previous) = previous_process_path.insert(*process, index) { + dependencies.push(previous, index); + } + } + } dependencies.canonicalize(); values.canonicalize(); Ok(LogicPathMemorySsa { @@ -1015,6 +1025,13 @@ fn emit_logic_path_store_with_result { + // The unit can write every output of its process, not only this + // path's scheduling target. Do not reuse values across the call. + lower_cache.clear(); + builder.inline_execution_unit(unit); + lower_cache.clear(); + } LogicPathTarget::CombCaptureEvent { site_id, guard, @@ -1724,7 +1741,7 @@ fn build_fold_group_schedule_index( .map(|(_, node)| *node) .chain(path.pre_lower_nodes.iter().copied()) .chain(match &path.target { - LogicPathTarget::Var(_) => Vec::new(), + LogicPathTarget::Var(_) | LogicPathTarget::Process { .. } => Vec::new(), LogicPathTarget::CombCaptureEvent { guard, args, @@ -2906,8 +2923,10 @@ fn stable_topological_sccs( } fn logic_path_is_scheduling_barrier(path: &LogicPath) -> bool { - matches!(path.target, LogicPathTarget::CombCaptureEvent { .. }) - || !path.comb_capture_enable_sites.is_empty() + matches!( + path.target, + LogicPathTarget::CombCaptureEvent { .. } | LogicPathTarget::Process { .. } + ) || !path.comb_capture_enable_sites.is_empty() } fn cached_logic_path_roots(path: &LogicPath) -> Vec { diff --git a/crates/celox-slt/src/scheduler/lanes.rs b/crates/celox-slt/src/scheduler/lanes.rs index 7531126189b..4a6dd5ba470 100644 --- a/crates/celox-slt/src/scheduler/lanes.rs +++ b/crates/celox-slt/src/scheduler/lanes.rs @@ -287,6 +287,11 @@ impl PathCostWalk { LogicPathTarget::Var(target) => ((target.access.msb - target.access.lsb + 1) .div_ceil(64) as u64) .min(MAX_VALUE_WORDS), + LogicPathTarget::Process { unit, .. } => unit + .blocks + .values() + .map(|block| block.instructions.len() as u64 + 1) + .sum(), LogicPathTarget::CombCaptureEvent { guard, args, @@ -711,6 +716,16 @@ pub fn sort_lanes( } } } + // Output projections of one imperative process share mutable activation + // and RNG state, so they must execute on the same lane as one atomic item. + let mut process_work = HashMap::default(); + for (path, logic) in prepared.input.iter().enumerate() { + if let LogicPathTarget::Process { process, .. } = &logic.target { + if let Some(previous) = process_work.insert(*process, work_of_path[path]) { + union(&mut atomic, previous, work_of_path[path]); + } + } + } join_expensive_sharing(work, &prepared.input, arena, &mut atomic); let mut edges = Vec::new(); for (definition, users) in prepared.adj.iter().enumerate().take(path_count) { @@ -790,7 +805,12 @@ pub fn sort_lanes( // Runtime events append to the single-producer event ring. None => pinned = true, } - if !logic_path.comb_capture_enable_sites.is_empty() { + if !logic_path.comb_capture_enable_sites.is_empty() + || matches!(&logic_path.target, LogicPathTarget::Process { unit, .. } + if unit.blocks.values().any(|block| block.instructions.iter().any(|inst| + matches!(inst, SIRInstruction::RuntimeEvent { .. } | SIRInstruction::ExternCall { .. } | SIRInstruction::CombCaptureEnableIfChanged { .. } | SIRInstruction::CombCaptureEvent { .. }) + || matches!(inst, SIRInstruction::Store(_, _, _, _, _, sites) if !sites.is_empty())))) + { pinned = true; } if let Some(root) = prepared.fold_group_schedule_index.direct_group_by_path[path] { diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index e08fa1e8845..539e4975a46 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -973,9 +973,11 @@ impl Module { initial_processes.insert( first_block, InitialProcess { + creation_order: 0, condition: None, body: static_initializers, initializer: true, + synthetic: false, }, ); } @@ -1027,6 +1029,7 @@ impl Module { let body = |body: Vec| body.into_iter().map(|stmt| rename.stmt(stmt)).collect(); for process in &mut comb_processes { process.body = body(std::mem::take(&mut process.body)); + process.sensitivity_body = body(std::mem::take(&mut process.sensitivity_body)); for assignment in &mut process.assignments { assignment.rhs = rename.expr(assignment.rhs.clone()); } @@ -1822,9 +1825,9 @@ pub(crate) fn with_call_sites(f: impl FnOnce() -> T) -> T { } impl ConstExpr { - /// A call of `name`; a user subroutine call gets a site of its own. + /// Effectful calls get distinct sites; analyzer-created copies retain them. fn call(name: String, args: Vec) -> Self { - let site = (!system_functions::is_system_name(&name)) + let site = (name == "$urandom" || !system_functions::is_system_name(&name)) .then(|| NEXT_CALL_SITE.with(|next| next.replace(next.get() + 1))); ConstExpr::Function { name, args, site } } @@ -1919,13 +1922,25 @@ impl LValue { #[derive(Debug, Clone, PartialEq, Eq)] pub struct CombProcess { + creation_order: usize, kind: CombProcessKind, condition: Option, assignments: Vec, body: Vec, + sensitivity_body: Vec, } impl CombProcess { + /// Reads removed from executable branches still affect implicit sensitivity. + pub fn sensitivity_body(&self) -> &[Stmt] { + &self.sensitivity_body + } + + /// Position among the elaborated module items, shared across process kinds. + pub fn creation_order(&self) -> usize { + self.creation_order + } + fn new( kind: CombProcessKind, condition: Option, @@ -1940,6 +1955,8 @@ impl CombProcess { }) .collect(); Self { + creation_order: 0, + sensitivity_body: Vec::new(), kind, condition, assignments, @@ -1949,6 +1966,8 @@ impl CombProcess { fn procedural(kind: CombProcessKind, condition: Option, body: Vec) -> Self { Self { + creation_order: 0, + sensitivity_body: Vec::new(), kind, condition, assignments: Vec::new(), @@ -1977,17 +1996,28 @@ impl CombProcess { pub enum CombProcessKind { ContinuousAssign, AlwaysComb, + AlwaysStar, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct FfProcess { + creation_order: usize, events: Vec, body: Vec, } impl FfProcess { + /// Position among the elaborated module items, shared across process kinds. + pub fn creation_order(&self) -> usize { + self.creation_order + } + fn new(events: Vec, body: Vec) -> Self { - Self { events, body } + Self { + creation_order: 0, + events, + body, + } } pub fn events(&self) -> &[FfEvent] { @@ -2002,16 +2032,28 @@ impl FfProcess { /// An `initial` process. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { + creation_order: usize, condition: Option, body: Vec, initializer: bool, + synthetic: bool, } impl InitialProcess { + /// Position among the elaborated module items, shared across process kinds. + pub fn creation_order(&self) -> usize { + self.creation_order + } + pub fn condition(&self) -> Option<&ConstExpr> { self.condition.as_ref() } + /// Compiler-generated storage initialization, without a user static process. + pub fn is_synthetic(&self) -> bool { + self.synthetic + } + /// Whether this process holds variable declaration initializers. pub fn is_initializer(&self) -> bool { self.initializer diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index 836e6133896..ba8232a9b9f 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -195,6 +195,7 @@ impl ArrayParameter<'_> { patterns::expr_from_pattern(&self.pattern.nodes.1, &shape, tree, dims) }?; Ok(InitialProcess { + creation_order: 0, condition: None, body: vec![Stmt::Assign { lhs: LValue::Ident(name), @@ -202,6 +203,7 @@ impl ArrayParameter<'_> { nonblocking: false, }], initializer: false, + synthetic: true, }) } } diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 9668b7aa701..029cb3bd6a4 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -18,7 +18,7 @@ pub(super) fn comb_processes_from_module_node( &packed_dimensions.type_aliases, )?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); - for item in &active { + for (creation_order, item) in active.iter().enumerate() { let ScopeItem::Module(node) = item.node else { continue; }; @@ -51,10 +51,11 @@ pub(super) fn comb_processes_from_module_node( state, )?; for process in &mut processes[start..] { + process.creation_order = creation_order; for assignment in &mut process.assignments { item.assignment(assignment); } - for stmt in &mut process.body { + for stmt in process.body.iter_mut().chain(&mut process.sensitivity_body) { procedural::qualify_stmt(item, stmt); } } @@ -328,11 +329,19 @@ fn comb_process_from_always_construct( for stmt in &mut body { procedural::substitute_stmt_constants(stmt, &HashMap::default(), parameter_literals); } - Ok(Some(CombProcess::procedural( - CombProcessKind::AlwaysComb, - condition, - body, - ))) + let sensitivity_body = std::mem::take(&mut builder.sensitivity_body); + Ok(Some(CombProcess { + sensitivity_body, + ..CombProcess::procedural( + if matches!(always.nodes.0, sv_parser::AlwaysKeyword::AlwaysComb(_)) { + CombProcessKind::AlwaysComb + } else { + CombProcessKind::AlwaysStar + }, + condition, + body, + ) + })) } #[cfg(test)] diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index fa22125d0e1..b50df6ef985 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -248,6 +248,7 @@ impl ConstantFunctions { .iter() .map(|(name, function)| crate::ir::Subroutine { name: name.clone(), + sensitivity_body: Vec::new(), is_task: false, return_type: function.return_var.as_ref().map(|(_, ty)| ty.clone()), return_var: function.return_var.as_ref().map(|(name, _)| name.clone()), diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index ae99975172c..cd1eb31c444 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -164,6 +164,10 @@ pub(super) fn substitute_process_constants_with_parameter_literals( const_env: &HashMap, parameter_literals: &HashMap, ) -> CombProcess { + let mut sensitivity_body = process.sensitivity_body; + for stmt in &mut sensitivity_body { + procedural::substitute_stmt_constants(stmt, const_env, parameter_literals); + } let condition = process .condition .map(|condition| substitute_const_expr_constants(condition, const_env)); @@ -172,9 +176,13 @@ pub(super) fn substitute_process_constants_with_parameter_literals( for stmt in &mut body { procedural::substitute_stmt_constants(stmt, const_env, parameter_literals); } - return CombProcess::procedural(process.kind, condition, body); + return CombProcess { + creation_order: process.creation_order, + sensitivity_body, + ..CombProcess::procedural(process.kind, condition, body) + }; } - CombProcess::new( + let mut result = CombProcess::new( process.kind, condition, process @@ -188,7 +196,10 @@ pub(super) fn substitute_process_constants_with_parameter_literals( ) }) .collect(), - ) + ); + result.creation_order = process.creation_order; + result.sensitivity_body = sensitivity_body; + result } pub(super) fn substitute_assignment_constants_with_parameter_literals( diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 763d5324e60..c0d7ab362e3 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -601,6 +601,47 @@ fn expr_from_system_function_call( )?; let operand_error = || unsupported(format!("operand of `{name}`")); match name { + "$urandom" => { + let args = match call { + 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()), + }, + }; + Ok(Expr::Call { + name: name.into(), + args, + arg_order: Vec::new(), + }) + } "$timeunit" | "$timeprecision" => timescales::query(call, syntax_tree).map(|value| { Expr::Literal(format_typed_parameter_literal(i128::from(value), 32, true)) }), diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index 1b4a7e46b79..5c2fec12880 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -18,7 +18,7 @@ pub(super) fn ff_processes_from_module_node( &packed_dimensions.type_aliases, )?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); - for item in &active { + for (creation_order, item) in active.iter().enumerate() { let ScopeItem::Module(node) = item.node else { continue; }; @@ -40,6 +40,7 @@ pub(super) fn ff_processes_from_module_node( state, )?; for process in &mut processes[start..] { + process.creation_order = creation_order; for event in &mut process.events { event.signal = item.name(&event.signal); } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 5fe075afcdc..4f5149ea249 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -55,6 +55,7 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { body: system_functions::Body, /// Whether the body's variables are automatic by default. automatic: bool, + pub(super) sensitivity_body: Vec, } /// The packed and unpacked shape of a declared type, as selects see it. @@ -113,6 +114,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let automatic = state.automatic; Self { automatic, + sensitivity_body: Vec::new(), tree, dims: dims.clone(), scopes: vec![Scope { @@ -942,8 +944,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .and_then(|condition| eval_ast_const_expr(&condition, &self.dims.const_env)) }; if let Some(value) = constant { + // Implicit sensitivity is syntactic even for unreachable + // branches. Preserve reads separately from executable writes. + self.sensitivity_body.push(Stmt::Eval(condition.clone())); if value != 0 { + self.sensitivity_body.extend(else_body); else_body = then_body; + } else { + self.sensitivity_body.extend(then_body); } continue; } @@ -1884,8 +1892,13 @@ pub(super) fn subroutines_with_symbolic_parameters( params: lowered_params, return_var, body, + sensitivity_body: std::mem::take(&mut builder.sensitivity_body), }; - for stmt in &mut subroutine.body { + for stmt in subroutine + .body + .iter_mut() + .chain(&mut subroutine.sensitivity_body) + { qualify_stmt(item, stmt); substitute_stmt_constants(stmt, &declaration_env, literals); } @@ -1985,7 +1998,7 @@ pub(super) fn initial_processes_from_module_node( let mut processes = Vec::new(); let active = generate::items(node, tree, const_env, &type_aliases)?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); - for item in &active { + for (creation_order, item) in active.iter().enumerate() { if item.is_parameter_declaration() { continue; } @@ -2031,9 +2044,11 @@ pub(super) fn initial_processes_from_module_node( } if !body.is_empty() { initializers.push(InitialProcess { + creation_order, condition: None, body, initializer: true, + synthetic: false, }); } continue; @@ -2059,9 +2074,11 @@ pub(super) fn initial_processes_from_module_node( substitute_stmt_constants(stmt, const_env, parameter_literals); } processes.push(InitialProcess { + creation_order, condition: None, body, initializer: false, + synthetic: false, }); } initializers.extend(processes); diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index f0aaf67e0db..a9921807cfe 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -289,6 +289,7 @@ impl ScopeSymbols { .iter() .filter(|process| initializes(process, target)) .map(|process| InitialProcess { + creation_order: process.creation_order, condition: process.condition.clone(), body: process .body @@ -298,6 +299,7 @@ impl ScopeSymbols { .map(|stmt| rename.stmt(stmt)) .collect(), initializer: process.initializer, + synthetic: process.synthetic, }) .collect(); self.signals.push(signal); @@ -482,6 +484,7 @@ impl ScopeSymbols { .initial_processes .iter() .map(|process| InitialProcess { + creation_order: process.creation_order, condition: process .condition .clone() @@ -493,6 +496,7 @@ impl ScopeSymbols { .map(|stmt| rename.stmt(stmt)) .collect(), initializer: process.initializer, + synthetic: process.synthetic, }) .collect(), aliases: HashMap::default(), @@ -888,6 +892,11 @@ impl Renamer<'_> { }) .collect(), return_var: subroutine.return_var.map(|name| self.name(&name)), + sensitivity_body: subroutine + .sensitivity_body + .into_iter() + .map(|stmt| self.stmt(stmt)) + .collect(), body: subroutine .body .into_iter() diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 8340e7726ea..a5803570bc3 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -272,6 +272,7 @@ fn reject_silently_ignored_constructs_with_dimensions( syntax_tree: &SyntaxTree, indexed_dimensions: &PackedDimensions, ) -> Result<(), AnalyzerError> { + reject_constant_random_calls(node.clone(), syntax_tree)?; let const_env = &indexed_dimensions.const_env; let type_aliases = &indexed_dimensions.type_aliases; let is_module = matches!( @@ -821,6 +822,70 @@ fn reject_silently_ignored_constructs_with_dimensions( Ok(()) } +/// Type queries may inspect an impure call, but a constant value may not +/// execute it, including in an unused or short-circuited initializer. +fn reject_constant_random_calls(node: RefNode<'_>, tree: &SyntaxTree) -> Converted<()> { + let mut unevaluated = HashSet::<*const sv_parser::SystemTfCall>::default(); + for child in node.clone() { + let RefNode::SystemTfCall(call) = child else { + continue; + }; + if !system_tf_call_parts(call, tree).is_some_and(|(name, _)| { + matches!( + name, + "$bits" + | "$size" + | "$left" + | "$right" + | "$low" + | "$high" + | "$increment" + | "$dimensions" + | "$unpacked_dimensions" + ) + }) { + continue; + } + let sv_parser::SystemTfCall::ArgExpression(call) = call else { + continue; + }; + if let Some(Some(argument)) = call.nodes.1.nodes.1.0.contents().first() { + for descendant in argument.into_iter() { + if let RefNode::SystemTfCall(call) = descendant { + unevaluated.insert(call as *const _); + } + } + } + } + let mut constant = vec![false]; + for event in node.into_iter().event() { + match event { + sv_parser::NodeEvent::Leave(_) => { + constant.pop(); + } + sv_parser::NodeEvent::Enter(child) => { + let in_constant = *constant.last().unwrap() + || matches!( + child, + RefNode::ConstantExpression(_) | RefNode::ConstantParamExpression(_) + ); + constant.push(in_constant); + if in_constant + && let RefNode::SystemTfCall(call) = child + && system_tf_call_parts(call, tree).is_some_and(|(name, _)| name == "$urandom") + && !unevaluated.contains(&(call as *const _)) + { + return Err(AnalyzerError::InvalidSystemTfCall { + name: "$urandom".into(), + detail: "not permitted in a constant-value expression".into(), + }); + } + } + } + } + Ok(()) +} + fn non_input_function_port(node: RefNode<'_>) -> bool { let direction = match node { RefNode::TfPortItem(port) => port.nodes.1.as_ref(), diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 475cef8ea03..0a464ce998a 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -775,13 +775,25 @@ impl LValue { #[derive(Debug, Clone, PartialEq, Eq)] pub struct CombProcess { + creation_order: usize, kind: CombProcessKind, condition: Option, assignments: Vec, body: Vec, + sensitivity_body: Vec, } impl CombProcess { + /// Reads removed from executable branches still affect implicit sensitivity. + pub fn sensitivity_body(&self) -> &[Stmt] { + &self.sensitivity_body + } + + /// Position among elaborated module items, shared across process kinds. + pub fn creation_order(&self) -> usize { + self.creation_order + } + pub(crate) fn new( kind: CombProcessKind, condition: Option, @@ -789,6 +801,8 @@ impl CombProcess { body: Vec, ) -> Self { Self { + creation_order: 0, + sensitivity_body: Vec::new(), kind, condition, assignments, @@ -819,17 +833,28 @@ impl CombProcess { pub enum CombProcessKind { ContinuousAssign, AlwaysComb, + AlwaysStar, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct FfProcess { + creation_order: usize, events: Vec, body: Vec, } impl FfProcess { + /// Position among elaborated module items, shared across process kinds. + pub fn creation_order(&self) -> usize { + self.creation_order + } + pub(crate) fn new(events: Vec, body: Vec) -> Self { - Self { events, body } + Self { + creation_order: 0, + events, + body, + } } pub fn events(&self) -> &[FfEvent] { @@ -844,20 +869,34 @@ impl FfProcess { /// An `initial` process. #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { + creation_order: usize, condition: Option, body: Vec, initializer: bool, + synthetic: bool, } impl InitialProcess { + /// Position among elaborated module items, shared across process kinds. + pub fn creation_order(&self) -> usize { + self.creation_order + } + pub(crate) fn new(condition: Option, body: Vec, initializer: bool) -> Self { Self { + creation_order: 0, condition, body, initializer, + synthetic: false, } } + /// Compiler-generated storage initialization, without a user static process. + pub fn is_synthetic(&self) -> bool { + self.synthetic + } + /// Whether this process holds variable declaration initializers, which /// run before every `initial` and `always` procedure. pub fn is_initializer(&self) -> bool { @@ -1135,7 +1174,7 @@ impl From for LValue { impl From for CombProcess { fn from(process: ast::CombProcess) -> Self { - CombProcess::new( + let mut result = CombProcess::new( process.kind().into(), process.condition().cloned().map(Into::into), process @@ -1150,7 +1189,15 @@ impl From for CombProcess { .cloned() .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), - ) + ); + result.creation_order = process.creation_order(); + result.sensitivity_body = process + .sensitivity_body() + .iter() + .cloned() + .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) + .collect(); + result } } @@ -1159,13 +1206,14 @@ impl From for CombProcessKind { match kind { ast::CombProcessKind::ContinuousAssign => CombProcessKind::ContinuousAssign, ast::CombProcessKind::AlwaysComb => CombProcessKind::AlwaysComb, + ast::CombProcessKind::AlwaysStar => CombProcessKind::AlwaysStar, } } } impl From for FfProcess { fn from(process: ast::FfProcess) -> Self { - Self::new( + let mut result = Self::new( process.events().iter().cloned().map(Into::into).collect(), process .body() @@ -1173,13 +1221,15 @@ impl From for FfProcess { .cloned() .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), - ) + ); + result.creation_order = process.creation_order(); + result } } impl From for InitialProcess { fn from(process: ast::InitialProcess) -> Self { - Self::new( + let mut result = Self::new( process.condition().cloned().map(Into::into), process .body() @@ -1188,7 +1238,10 @@ impl From for InitialProcess { .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), process.is_initializer(), - ) + ); + result.creation_order = process.creation_order(); + result.synthetic = process.is_synthetic(); + result } } diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index c87018f22bd..29e73510cb2 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -419,6 +419,8 @@ pub struct SubroutineBase { /// a variable inside its body. `None` for a task or a `void` function. pub return_var: Option, pub body: Vec>, + /// Non-executable source retained for syntactic implicit sensitivity. + pub sensitivity_body: Vec>, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -455,6 +457,11 @@ impl SubroutineBase { .collect(), return_var: self.return_var, body: self.body.into_iter().map(|stmt| stmt.map(fe, fl)).collect(), + sensitivity_body: self + .sensitivity_body + .into_iter() + .map(|stmt| stmt.map(fe, fl)) + .collect(), } } } diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index a6e7b606e05..902fecffa83 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -223,7 +223,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$load_coverage_db", Task), // 20.15 Probabilistic distribution functions unsupported("$random", Function), - unsupported("$urandom", Function), + function("$urandom", 0, 1), unsupported("$urandom_range", Function), unsupported("$dist_uniform", Function), unsupported("$dist_normal", Function), diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 696d1038ecf..568500ee22a 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -55,6 +55,9 @@ impl std::fmt::Display for UnpackedArrayType { /// Width and signedness of the supported integral system functions. pub fn bit_vector_function_return_type(name: &str, arity: usize) -> Option<(usize, bool)> { + if name == "$urandom" { + return (arity <= 1).then_some((32, false)); + } if matches!(name, "$timeunit" | "$timeprecision") { return (arity <= 1).then_some((32, true)); } diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 181729bf298..06ea500687e 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -431,6 +431,11 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_verilator_printtimescale_special_scopes` | compile | verilator | 1 | Verilator 5.052 rejects standalone $unit and $root operands of $printtimescale, expecting :: and a dotted hierarchy respectively. IEEE 1800-2023 20.4.2 explicitly accepts both special scope operands. | | `sv_verilator_printtimescale_scope` | execute | verilator | 1 | Verilator 5.052 prints the Top caller scale for a package operand of $printtimescale, reports 1ps instead of the declared 10ps precision inside the package procedure, and omits the required parentheses around the design element name. IEEE 1800-2023 20.4.2 selects the queried/current design element and specifies the display format; 3.14.2.3 preserves its declared precision. | | `sv_icarus_printtimescale_operands` | compile | icarus | 2 | Icarus 13.0 rejects standalone $unit and bare package operands of $printtimescale with syntax errors. IEEE 1800-2023 20.4.2 accepts a design element argument and explicitly includes $unit and $root. The shared assertions retain their standard output and precision. | +| `sv_verilator_urandom_zero_seed` | execute | verilator | 2 | 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. | +| `sv_verilator_urandom_process_state` | execute | verilator | 1 | Verilator 5.052 uses the host thread/context RNG for $urandom, so separately seeded design processes interfere when clocked independently. IEEE 1800-2023 18.14.1-2 requires a separate stream per SystemVerilog process, independent of thread execution order. The shared case seeds two module-instance processes identically and compares their streams after alternating activations. | +| `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. | 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 50d22e74b4b..d058e89b145 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2424,3 +2424,201 @@ endmodule (top Top) (tick clk) (expect_output (bytes 128 255 124 255 1 128 124 32 32 254 124 15 128 195 169 10))) + +; IEEE 1800-2023 18.13.1: compare reproducibility, not simulator-specific values. +(case urandom_reseeds_and_shares_the_calling_process_stream + (source "urandom_reseed.sv" #" + module Top(input logic clk, enabled, input int seed, output logic ok, unchanged, + output int width, output logic unsigned_result); + int unsigned a, b, c, replay_b, replay_c; + int saved; + function automatic int unsigned draw(); return $urandom; endfunction + always_ff @(posedge clk) if (enabled) begin + saved = seed; + a = $urandom(seed); b = draw(); + width <= $bits($urandom()); + c = $urandom(); + void'($urandom(seed)); replay_b = draw(); replay_c = $urandom; + ok <= b == replay_b && c == replay_c && a != b && b != c; + unchanged <= seed == saved; + unsigned_result <= $urandom(seed) >= 0; + end + endmodule + "#) + (top Top) + (modify (set enabled 1)) + (for value (list 0 1 123 0x80000000 0xffffffff) + (modify (set seed value)) + (tick clk) + (assert_eq ok 1) + (assert_eq unchanged 1) + (assert_eq width 32) + (assert_eq unsigned_result 1))) + +(case urandom_keeps_process_and_instance_streams_independent + (source "urandom_processes.sv" #" + module Generator(input logic clk, enabled, reseed, output int unsigned value); + always_ff @(posedge clk) if (enabled) begin + if (reseed) value <= $urandom(123); + else value <= $urandom; + end + endmodule + module Top(input logic clk, a_enabled, b_enabled, reseed, output logic same); + int unsigned a, b; + Generator first(clk, a_enabled, reseed, a); + Generator second(clk, b_enabled, reseed, b); + assign same = a == b; + endmodule + "#) + (top Top) + (modify (set a_enabled 1) (set b_enabled 1) (set reseed 1)) + (tick clk) + (assert_eq same 1) + (modify (set reseed 0)) + (for i (range 0 8) + (modify (set a_enabled 1) (set b_enabled 0)) + (tick clk) + (assert_eq same 0) + (modify (set a_enabled 0) (set b_enabled 1)) + (tick clk) + (assert_eq same 1))) + +(case urandom_respects_short_circuits_and_evaluates_indices_once + (source "urandom_evaluation.sv" #" + module Top(input logic clk, enabled, output logic ok); + int unsigned ignored, second, third, actual; + logic [31:0] selected; + logic skipped; + always_ff @(posedge clk) if (enabled) begin + ignored = $urandom(42); second = $urandom; third = $urandom; + ignored = $urandom(42); + skipped = 0 && $urandom; + skipped = 1 || $urandom; + ignored = 1 ? 0 : $urandom; + selected = 0; + selected[$urandom & 31] = 1'b1; + actual = $urandom; + ok <= actual == third && selected == (32'b1 << (second & 31)); + end + endmodule + "#) + (top Top) + (modify (set enabled 1)) + (tick clk) + (assert_eq ok 1) + (tick clk) + (assert_eq ok 1)) + +(case urandom_has_an_unsigned_self_determined_result + (source "urandom_type.sv" #" + module Top(input logic clk, enabled, output logic ok, output int width); + logic [63:0] wide; + always_ff @(posedge clk) if (enabled) begin + wide = $urandom; + ok <= wide[63:32] == 0 && $urandom() >= 0; + width <= $bits($urandom); + end + endmodule + "#) + (top Top) + (modify (set enabled 1)) + (for i (range 0 8) + (tick clk) + (assert_eq ok 1) + (assert_eq width 32))) + +; IEEE 1800-2023 9.2.2.2, 18.13.1: legal in combinational procedures; +; subroutine calls use the same process stream and retain statement order. +(case urandom_comb_executes_in_statement_order + (source "urandom_comb.sv" #" + module Top(input logic enabled, input int seed, count, output logic ok); + function automatic int unsigned draw(); return $urandom(); endfunction + always_comb begin + int unsigned first, second, actual; + int working_seed; + logic skipped; + working_seed = seed; + first = $urandom(working_seed); + second = draw(); + working_seed = seed; + actual = $urandom(working_seed); + skipped = 0 && $urandom; + skipped = 1 || $urandom; + actual = enabled ? draw() : 0; + ok = !enabled || actual == second; + for (int i = 0; i < count; i++) begin + working_seed = seed; + first = $urandom(working_seed); + second = draw(); + working_seed = seed; + first = $urandom(working_seed); + actual = draw(); + ok &= actual == second; + end + end + endmodule + "#) + (top Top) + (modify (set enabled 1) (set seed 17) (set count 3)) + (assert_eq ok 1) + (eval) + (assert_eq ok 1) + (modify (set seed 23) (set count 5)) + (assert_eq ok 1) + (modify (set enabled 0)) + (assert_eq ok 1)) + +(case urandom_select_keeps_distinct_source_calls + (source "urandom_select_calls.sv" #" + module Top(input logic clk, enabled, output logic ff_ok, comb_ok); + function automatic logic check_calls(); + int seed; + int unsigned ignored, a, b, third, actual; + logic [31:0] selected; + seed = 17; + ignored = $urandom(seed); a = $urandom; b = $urandom; third = $urandom; + seed = 17; + ignored = $urandom(seed); + selected = 0; + selected[($urandom() + $urandom()) & 31] = 1'b1; + actual = $urandom; + return actual == third && selected == (32'b1 << ((a + b) & 31)); + endfunction + always_ff @(posedge clk) if (enabled) ff_ok <= check_calls(); + always_comb comb_ok = enabled ? check_calls() : 1; + endmodule + "#) + (top Top) + (modify (set enabled 1)) + (tick clk) + (assert_eq ff_ok 1) + (assert_eq comb_ok 1) + (tick clk) + (assert_eq ff_ok 1) + (assert_eq comb_ok 1)) + +; IEEE 1800-2023 18.13.1: convert the seed to int using its source signedness. +(case urandom_extends_signed_seed_values + (source "urandom_signed_seed.sv" #" + module Top(input logic clk, input logic [7:0] bits, output logic ff_ok, comb_ok); + function automatic logic check_seed(input logic [7:0] raw); + logic signed [7:0] narrow; + logic [7:0] unsigned_narrow; + int extended, unsigned_extended; + int unsigned a, b, c, d; + narrow = raw; unsigned_narrow = raw; + extended = int'(narrow); unsigned_extended = int'(unsigned_narrow); + a = $urandom(narrow); b = $urandom(extended); + c = $urandom(unsigned_narrow); d = $urandom(unsigned_extended); + return a == b && c == d; + endfunction + always_ff @(posedge clk) ff_ok <= check_seed(bits); + always_comb comb_ok = check_seed(bits); + endmodule + "#) + (top Top) + (for value (range 0 256) + (modify (set bits value)) + (tick clk) + (assert_eq ff_ok 1) + (assert_eq comb_ok 1))) diff --git a/crates/celox-test-suite/verification/repros/sv_urandom.json b/crates/celox-test-suite/verification/repros/sv_urandom.json new file mode 100644 index 00000000000..a6406426f43 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_urandom.json @@ -0,0 +1,175 @@ +{ + "standard": "IEEE 1800-2023 18.13.1 and 18.14.1-2", + "source": "module Top;\n int seed;\n int unsigned a, b, c, d, e, ignored;\n initial begin\n seed=0; a=$urandom(seed); b=$urandom;\n seed=0; c=$urandom(seed); d=$urandom;\n $display(\"zero_seed_repeat=%0d\", a==c && b==d);\n seed=123; a=$urandom(seed); b=$urandom; c=$urandom;\n seed=123; ignored=$urandom(seed); d=$urandom; e=$urandom;\n $display(\"nonzero_seed_repeat=%0d\", b==d && c==e);\n $finish;\n end\nendmodule\n", + "constant_source": "module Top;\n int unsigned a;\n initial begin a=$urandom(123); $display(\"finished=%0d\", a>=0); $finish; end\nendmodule\n", + "expected": [ + "zero_seed_repeat=1", + "nonzero_seed_repeat=1", + "finished=1" + ], + "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": "zero_seed_repeat=0\nnonzero_seed_repeat=1\n- /probe.sv:11: 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": "zero_seed_repeat=1\nnonzero_seed_repeat=1\n/probe.sv:11: $finish called at 0 (1s)\n" + }, + "icarus_constant_compile": { + "command": "iverilog -g2012 -s Top -o /constant.vvp /constant.sv", + "exit_code": 0 + }, + "icarus_constant_run": { + "command": "vvp /constant.vvp", + "exit_code": 1, + "output": "ERROR: /constant.sv:3: $urandom's seed must be an integer/time variable or a register.\n" + }, + "note": "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::urandom_keeps_process_and_instance_streams_independent at 2484:5: assert_eq same: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_keeps_process_and_instance_streams_independent", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream at 2453:5: assert_eq ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once at 2508:3: assert_eq ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_select_keeps_distinct_source_calls at 2594:3: assert_eq ff_ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_select_keeps_distinct_source_calls", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_extends_signed_seed_values at 2623:5: assert_eq ff_ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_extends_signed_seed_values", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ], + "icarus": [ + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_keeps_process_and_instance_streams_independent", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_extends_signed_seed_values", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] + }, + "verilator_generated_code_observation": "In the clocked short-circuit/index regression, the generated C++ assigns second = VL_RANDOM_I() before ignored = VL_URANDOM_SEEDED_II(42), reversing the original blocking statement order. In verilated.cpp, VL_URANDOM_SEEDED_II updates the host thread context seed; globalRNG is host thread_local. randSeedDefault64 obtains entropy when seed is zero.", + "tool_versions": { + "verilator": "Verilator 5.052 2026-09-05 rev v5.052", + "icarus": "Icarus Verilog version 13.0 (stable) (v13_0)" + }, + "distinct_index_calls_observation": { + "case": "system_functions::urandom_select_keeps_distinct_source_calls", + "verilator_version": "Verilator 5.052 2026-09-05 rev v5.052", + "icarus_result": "passed (Icarus 13.0)", + "generated_cpp": "a = VL_RANDOM_I(); b = VL_RANDOM_I(); ignored = VL_URANDOM_SEEDED_II(0x00000011U); third = VL_RANDOM_I(); selected |= 1U << ((VL_RANDOM_I() + VL_RANDOM_I()) & 31); actual = VL_RANDOM_I();", + "source_order": "seed = 17; ignored = $urandom(seed); a = $urandom; b = $urandom; third = $urandom; seed = 17; ignored = $urandom(seed); selected = 0; selected[($urandom() + $urandom()) & 31] = 1; actual = $urandom;", + "finding": "The generated code removes/reorders seeded calls before reference draws. The two calls in the select remain distinct; the mismatch is the existing seeded-statement-order disagreement. Original assertions are retained." + }, + "signed_seed_observation": { + "standard": "IEEE 1800-2023 18.13.1: any integral seed expression, with int seed formal", + "case": "system_functions::urandom_extends_signed_seed_values", + "source": "module Top;\n function automatic logic check_seed(input logic [7:0] raw);\n logic signed [7:0] narrow;\n logic [7:0] unsigned_narrow;\n int extended, unsigned_extended;\n int unsigned a, b, c, d;\n narrow = raw; unsigned_narrow = raw;\n extended = int'(narrow); unsigned_extended = int'(unsigned_narrow);\n a = $urandom(narrow); b = $urandom(extended);\n c = $urandom(unsigned_narrow); d = $urandom(unsigned_extended);\n return a == b && c == d;\n endfunction\n initial begin\n for (int i = 1; i < 256; i++) begin\n if (!check_seed(i)) $fatal(1, \"seed extension mismatch at %0d\", i);\n end\n $display(\"nonzero_seed_extension=1\");\n $finish;\n end\nendmodule\n", + "expected_nonzero_probe": "nonzero_seed_extension=1", + "verilator_nonzero_probe": { + "compile_exit_code": 0, + "run_exit_code": 0, + "output": "nonzero_seed_extension=1\n- /signed_seed.sv:18: 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_nonzero_probe": { + "compile_exit_code": 0, + "compile_output": "", + "run_exit_code": 1, + "run_output": "Error: /signed_seed.sv:9: $urandom's seed variable is less than 32 bits (8).\nError: /signed_seed.sv:10: $urandom's seed variable is less than 32 bits (8).\n" + }, + "icarus_shared_diagnostic": "Error: /source_0.sv:10: $urandom's seed variable is less than 32 bits (8).\nError: /source_0.sv:11: $urandom's seed variable is less than 32 bits (8).\n", + "finding": "The shared case retains all 256 input bit patterns, including zero. Verilator fails the zero input through its existing zero-seed entropy behavior; its generated C++ uses VL_EXTENDS_II(32,8,narrow) for the signed seed and zero extension for the unsigned seed. The standalone check passes all 255 nonzero patterns. Icarus rejects both narrow seed variables before executing the shared assertions." + } +} diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index 774779cc9e3..a99b8693025 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1431,6 +1431,98 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "detail": "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.", + "expectation": "Simulation", + "name": "system_functions::urandom_keeps_process_and_instance_streams_independent", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_urandom_seed_expression", + "category": "simulator_unsupported", + "observed_version": "Icarus 13.0", + "reason": "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." + } + }, + { + "category": "Functions", + "detail": "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.", + "expectation": "Simulation", + "name": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_urandom_seed_expression", + "category": "simulator_unsupported", + "observed_version": "Icarus 13.0", + "reason": "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." + } + }, + { + "category": "Functions", + "detail": "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.", + "expectation": "Simulation", + "name": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_urandom_seed_expression", + "category": "simulator_unsupported", + "observed_version": "Icarus 13.0", + "reason": "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." + } + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::urandom_extends_signed_seed_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "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.", + "phase": "skip", + "status": "ignored", + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_urandom_narrow_seed", + "category": "simulator_unsupported", + "observed_version": "Icarus 13.0", + "reason": "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." + } } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 632e6dace3e..9a22f120523 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1265,5 +1265,94 @@ "indexed_select::constant_parameter_initializers_preserve_unknown_indices" ] } + }, + { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_zero_seed", + "category": "simulator_disagreement", + "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.", + "cases": { + "verilator": [ + "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "system_functions::urandom_extends_signed_seed_values" + ] + } + }, + { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_process_state", + "category": "simulator_disagreement", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 uses the host thread/context RNG for $urandom, so separately seeded design processes interfere when clocked independently. IEEE 1800-2023 18.14.1-2 requires a separate stream per SystemVerilog process, independent of thread execution order. The shared case seeds two module-instance processes identically and compares their streams after alternating activations.", + "cases": { + "verilator": [ + "system_functions::urandom_keeps_process_and_instance_streams_independent" + ] + } + }, + { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_statement_order", + "category": "simulator_disagreement", + "observed_version": "Verilator 5.052", + "reason": "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.", + "cases": { + "verilator": [ + "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once", + "system_functions::urandom_select_keeps_distinct_source_calls" + ] + } + }, + { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_urandom_seed_expression", + "category": "simulator_unsupported", + "observed_version": "Icarus 13.0", + "reason": "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.", + "cases": { + "icarus": [ + "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "system_functions::urandom_keeps_process_and_instance_streams_independent", + "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once" + ] + } + }, + { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_urandom_narrow_seed", + "category": "simulator_unsupported", + "observed_version": "Icarus 13.0", + "reason": "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.", + "cases": { + "icarus": [ + "system_functions::urandom_extends_signed_seed_values" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 33a06fd54ef..318590cf075 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -10,7 +10,7 @@ "mismatch": 14, "emission_error": 0, "compile_error": 104, - "runtime_error": 3, + "runtime_error": 7, "unsupported": 0, "ignored": 0 }, @@ -1155,6 +1155,50 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_keeps_process_and_instance_streams_independent", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "native testbench failed: exit status: 1; see runtime.log and protocol.log\nnative testbench exited without reaching $finish\n", + "expectation": "Simulation", + "name": "system_functions::urandom_extends_signed_seed_values", + "phase": "execute", + "status": "runtime_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index 2ac7c5a03aa..3240e2ea1f1 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -7,7 +7,7 @@ "passed": 0, "rejected": 0, "unexpected_accept": 0, - "mismatch": 16, + "mismatch": 21, "emission_error": 0, "compile_error": 16, "runtime_error": 1, @@ -347,6 +347,61 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_keeps_process_and_instance_streams_independent at 2484:5: assert_eq same: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_keeps_process_and_instance_streams_independent", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream at 2453:5: assert_eq ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once at 2508:3: assert_eq ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_select_keeps_distinct_source_calls at 2594:3: assert_eq ff_ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_select_keeps_distinct_source_calls", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "system_functions::urandom_extends_signed_seed_values at 2623:5: assert_eq ff_ok: expected 0x1, got 0x0", + "expectation": "Simulation", + "name": "system_functions::urandom_extends_signed_seed_values", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } 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 4b25c27a083..f88ffba69b0 100644 --- a/crates/celox-test-suite/verification/sv/verilator/system_functions.json +++ b/crates/celox-test-suite/verification/sv/verilator/system_functions.json @@ -715,6 +715,121 @@ "LIMITATIONS.md#systemverilog-suite" ] } + }, + { + "category": "Functions", + "detail": "Verilator 5.052 uses the host thread/context RNG for $urandom, so separately seeded design processes interfere when clocked independently. IEEE 1800-2023 18.14.1-2 requires a separate stream per SystemVerilog process, independent of thread execution order. The shared case seeds two module-instance processes identically and compares their streams after alternating activations.", + "expectation": "Simulation", + "name": "system_functions::urandom_keeps_process_and_instance_streams_independent", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_process_state", + "category": "simulator_disagreement", + "observed_version": "Verilator 5.052", + "reason": "Verilator 5.052 uses the host thread/context RNG for $urandom, so separately seeded design processes interfere when clocked independently. IEEE 1800-2023 18.14.1-2 requires a separate stream per SystemVerilog process, independent of thread execution order. The shared case seeds two module-instance processes identically and compares their streams after alternating activations." + } + }, + { + "category": "Functions", + "detail": "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.", + "expectation": "Simulation", + "name": "system_functions::urandom_reseeds_and_shares_the_calling_process_stream", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_zero_seed", + "category": "simulator_disagreement", + "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 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.", + "expectation": "Simulation", + "name": "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_statement_order", + "category": "simulator_disagreement", + "observed_version": "Verilator 5.052", + "reason": "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." + } + }, + { + "category": "Functions", + "detail": "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.", + "expectation": "Simulation", + "name": "system_functions::urandom_select_keeps_distinct_source_calls", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_statement_order", + "category": "simulator_disagreement", + "observed_version": "Verilator 5.052", + "reason": "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." + } + }, + { + "category": "Functions", + "expectation": "Simulation", + "name": "system_functions::urandom_extends_signed_seed_values", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "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.", + "phase": "skip", + "status": "ignored", + "known_issue": { + "phase": "execute", + "upstream": [], + "evidence": [ + "verification/repros/sv_urandom.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_urandom_zero_seed", + "category": "simulator_disagreement", + "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." + } } ] } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 4449990d25c..58f4cadbccf 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -487,6 +487,9 @@ impl NativeProgramImage { testbench_read_roots: self.runtime_schema.testbench_read_roots.clone(), rtl_writes: self.runtime_schema.rtl_writes.clone(), comb_writes: self.runtime_schema.comb_writes.iter().copied().collect(), + // The image retains the final classification in comb_writes; + // optimization-time classification roots are no longer used. + persistent_comb_state: Default::default(), dead_store_policy: self.runtime_schema.dead_store_policy, live_signals: self.runtime_schema.live_signals.iter().copied().collect(), processes: self.runtime_schema.processes.clone(), diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index ffb968f88c4..3f2b06e1fe5 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -765,6 +765,8 @@ fn collect_comb_writes(program: &mut OptimizedSir) { } } } + let persistent = &program.runtime.runtime_schema.persistent_comb_state; + comb_writes.retain(|address| !persistent.contains(address)); program.runtime.runtime_schema.comb_writes = comb_writes; } diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d341f306c25..bb8978a3737 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -657,6 +657,25 @@ mod host { backend: B, program: RuntimeProgram, warnings: Vec, + ) -> Self { + let mut sim = Self::with_backend_and_program_for_simulation(backend, program, warnings); + // Simulator does not execute initial kernels. Release combinational + // time-zero gates that would otherwise wait forever for them. + for process in &sim.program.runtime_schema.processes { + let status = sim.backend.resolve_signal(&process.status); + if sim.backend.get_as::(status) == 0 { + sim.backend + .set(status, celox_design::ProcessStatus::Done.code()); + } + } + sim + } + + /// Construct the engine before a timed scheduler starts initial kernels. + pub(crate) fn with_backend_and_program_for_simulation( + backend: B, + program: RuntimeProgram, + warnings: Vec, ) -> Self { let mut sim = Self { backend, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index c8fdf179793..e578ae835fa 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -3000,8 +3000,11 @@ mod host { )))] let backend = crate::backend::JitBackend::new(&laid_out, &self.options, None)?; - let mut sim = - Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); + let mut sim = Simulator::with_backend_and_program_for_simulation( + backend, + laid_out.into_runtime(), + warnings, + ); sim.components.set_injected(self.injected_components); sim.diagnostics = self.options.diagnostics.clone(); if let Some(path) = self.vcd_path { diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index c26721ae5a7..8ee46ec308d 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -60,7 +60,384 @@ fn veryl_assert_unknown_conditions_are_eager_on_interpreter() { } } +const URANDOM_SKIPPED_INITIAL_SOURCE: &str = r#" + module Top(input int seed, output int unsigned value, reference); + initial $display("skipped initial"); + always_comb value = $urandom(seed); + always_comb reference = $urandom(17); + endmodule +"#; + +#[test] +fn urandom_comb_skipped_initials_work_on_interpreter_and_tiered() { + fn check(mut sim: Simulator) { + let value = sim.signal("value"); + assert_ne!(sim.get(value), 0u8.into()); + let seed = sim.signal("seed"); + sim.modify(|io| io.set(seed, 17u8)).unwrap(); + assert_eq!(sim.get(value), sim.get(sim.signal("reference"))); + assert!(sim.drain_runtime_events().is_empty()); + } + let builder = || { + Simulator::from_sv_sources( + vec![( + URANDOM_SKIPPED_INITIAL_SOURCE, + Path::new("random_skipped_initial.sv"), + )], + "Top", + ) + .four_state(true) + }; + check(builder().build_interpreter().unwrap()); + check(builder().build_tiered().unwrap()); +} + +#[test] +fn urandom_initial_extends_signed_seed_values() { + let mut sim = initial_simulation( + r#" + module Top(output logic ok); + byte narrow; + int wide; + int unsigned a, b; + initial begin + ok = 1; + for (int i = -128; i < 128; i++) begin + narrow = i; wide = i; + a = $urandom(narrow); b = $urandom(wide); + ok &= a == b; + end + end + endmodule + "#, + ); + sim.step().unwrap(); + assert_eq!(sim.get(sim.signal("ok")), 1u8.into()); +} + sv_backends! { + fn urandom_sibling_default_streams_have_independent_state(sim) { + @setup { let source = r#" + module Child(input logic clk, output int unsigned value); + always_ff @(posedge clk) value <= $urandom; + endmodule + module Top(input logic clk_a, clk_b, output int unsigned a, b); + Child left(clk_a, a); + Child right(clk_b, b); + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_siblings.sv"))], "Top").four_state(false); + let a = sim.signal("a"); + let b = sim.signal("b"); + sim.tick(sim.event("clk_a")).unwrap(); + let first = sim.get(a); + assert_eq!(sim.get(b), 0u8.into()); + sim.tick(sim.event("clk_b")).unwrap(); + assert_eq!(sim.get(b), first); + sim.tick(sim.event("clk_a")).unwrap(); + let second = sim.get(a); + assert_ne!(first, second); + assert_eq!(sim.get(b), first); + sim.tick(sim.event("clk_b")).unwrap(); + assert_eq!(sim.get(b), second); + } + + fn urandom_comb_runs_when_untimed_initials_are_skipped(sim) { + @setup { let source = URANDOM_SKIPPED_INITIAL_SOURCE; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_skipped_initial.sv"))], "Top").four_state(true); + let value = sim.signal("value"); + let seed = sim.signal("seed"); + assert_ne!(sim.get(value), 0u8.into()); + sim.modify(|io| io.set(seed, 17u8)).unwrap(); + assert_eq!(sim.get(value), sim.get(sim.signal("reference"))); + let saved = sim.checkpoint().unwrap(); + let first = sim.get(value); + sim.modify(|io| io.set(seed, 23u8)).unwrap(); + assert_ne!(sim.get(value), first); + sim.restore(&saved).unwrap(); + sim.eval_comb().unwrap(); + assert_eq!(sim.get(value), first); + assert!(sim.drain_runtime_events().is_empty()); + } + + fn urandom_extends_signed_seed_values(sim) { + @case "system_functions::urandom_extends_signed_seed_values"; + } + + fn urandom_comb_executes_in_statement_order(sim) { + @case "system_functions::urandom_comb_executes_in_statement_order"; + } + + fn urandom_comb_uses_only_process_activations(sim) { + @setup { let source = r#" + module Top(input logic trigger, unrelated, reseed, output int unsigned value, next_value, replay, expected); + function automatic int unsigned draw(); return $urandom; endfunction + always_comb begin + if (trigger) begin + if (reseed) value = $urandom(17); + else value = draw(); + next_value = draw(); + end else begin value = 0; next_value = 0; end + end + always_comb begin + replay = $urandom(17); + replay = draw(); + expected = draw(); + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_comb.sv"))], "Top").four_state(true); + let value = sim.signal("value"); + let next_value = sim.signal("next_value"); + let trigger = sim.signal("trigger"); + let reseed = sim.signal("reseed"); + sim.modify(|io| { io.set(trigger, 1u8); io.set(reseed, 1u8); }).unwrap(); + let seeded = sim.get(value); + let second = sim.get(next_value); + assert_eq!(second, sim.get(sim.signal("replay"))); + for bit in [1u8, 0, 1] { + sim.set(sim.signal("unrelated"), bit); + sim.eval_comb().unwrap(); + assert_eq!(sim.get(value), seeded); + assert_eq!(sim.get(next_value), second); + } + let checkpoint = sim.checkpoint().unwrap(); + let file = sim.save_state().unwrap(); + assert!(file.objects.iter().filter(|object| object.path.contains("urandom_state")).all(|object| object.role == celox_runtime::StateRole::State)); + sim.modify(|io| io.set(reseed, 0u8)).unwrap(); + let third = sim.get(value); + assert_eq!(third, sim.get(sim.signal("expected"))); + let fourth = sim.get(next_value); + sim.restore(&checkpoint).unwrap(); + assert_eq!(sim.get(value), seeded); + assert_eq!(sim.get(next_value), second); + sim.modify(|io| io.set(reseed, 0u8)).unwrap(); + assert_eq!(sim.get(value), third); + assert_eq!(sim.get(next_value), fourth); + sim.load_state(&file).unwrap(); + assert_eq!(sim.get(value), seeded); + assert_eq!(sim.get(next_value), second); + sim.modify(|io| io.set(reseed, 0u8)).unwrap(); + assert_eq!(sim.get(value), third); + assert_eq!(sim.get(next_value), fourth); + let mut incomplete = file.clone(); + incomplete.objects.retain(|object| !object.path.contains("urandom_state")); + assert!(sim.load_state(&incomplete).is_err()); + } + + fn urandom_comb_distinguishes_time_zero_and_function_sensitivity(sim) { + @setup { let source = r#" + module Top(input logic trigger, global_input, output int unsigned a, b, initial_draw, star_draw); + function automatic int unsigned draw(input logic unused); + if (global_input) return $urandom; + return $urandom; + endfunction + always_comb a = draw(trigger); + always @* b = draw(trigger); + always_comb initial_draw = $urandom; + always @* star_draw = $urandom; + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_sensitivity.sv"))], "Top").four_state(false); + let a = sim.signal("a"); + let b = sim.signal("b"); + let first = sim.get(a); + assert_ne!(first, 0u8.into()); + assert_eq!(sim.get(b), 0u8.into()); + let initial_draw = sim.get(sim.signal("initial_draw")); + assert_ne!(initial_draw, 0u8.into()); + assert_eq!(sim.get(sim.signal("star_draw")), 0u8.into()); + let global_input = sim.signal("global_input"); + sim.modify(|io| io.set(global_input, 1u8)).unwrap(); + assert_ne!(sim.get(a), first); + assert_eq!(sim.get(b), 0u8.into()); + let trigger = sim.signal("trigger"); + sim.modify(|io| io.set(trigger, 1u8)).unwrap(); + assert_ne!(sim.get(b), 0u8.into()); + assert_eq!(sim.get(sim.signal("initial_draw")), initial_draw); + assert_eq!(sim.get(sim.signal("star_draw")), 0u8.into()); + } + + fn urandom_select_keeps_distinct_source_calls(sim) { + @case "system_functions::urandom_select_keeps_distinct_source_calls"; + } + + fn urandom_comb_tracks_static_bits_dead_branches_and_unknown_changes(sim) { + @setup { let source = r#" + module Top(input logic [1:0] trigger, input logic dead_input, output logic echo, output int unsigned value); + always_comb begin + echo = trigger[0]; + value = $urandom; + if (0) $display("%b", dead_input); + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_bits.sv"))], "Top").four_state(true); + let trigger = sim.signal("trigger"); + let value = sim.signal("value"); + let dead_input = sim.signal("dead_input"); + sim.modify(|io| { io.set(trigger, 0u8); io.set(dead_input, 0u8); }).unwrap(); + let first = sim.get(value); + sim.modify(|io| io.set(trigger, 2u8)).unwrap(); + assert_eq!(sim.get(value), first); + sim.modify(|io| io.set_four_state(trigger, 2u8.into(), 1u8.into())).unwrap(); + let second = sim.get(value); + assert_ne!(second, first); + sim.eval_comb().unwrap(); + assert_eq!(sim.get(value), second); + sim.modify(|io| io.set(dead_input, 1u8)).unwrap(); + assert_ne!(sim.get(value), second); + assert!(sim.drain_runtime_events().is_empty()); + } + + fn urandom_comb_propagates_all_outputs_and_hierarchical_events(sim) { + @setup { let source = r#" + module Child(input logic enabled, input int seed, output int unsigned a, b); + function automatic int unsigned draw(); return $urandom; endfunction + always_comb begin + if (enabled) begin + a = $urandom(seed); b = draw(); b[0] = 0; + $display("inside=%0d", seed); + end else begin a = 0; b = 0; end + end + endmodule + module Top(input logic clk, enabled, unrelated, input int data, output int unsigned q, b); + int unsigned a; + wire [31:0] adjusted = data + 1; + Child child(enabled, adjusted, a, b); + assign q = a ^ b; + always_comb if (enabled) $display("observed=%0h", b); + always_ff @(posedge clk) $display("clock"); + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_events.sv"))], "Top").four_state(true); + sim.drain_runtime_events(); + let enabled = sim.signal("enabled"); + let data = sim.signal("data"); + sim.modify(|io| { io.set(enabled, 1u8); io.set(data, 7u8); }).unwrap(); + let first = sim.get(sim.signal("q")); + let messages = sim.drain_runtime_events(); + assert_eq!(messages.len(), 2, "{messages:?}"); + assert!(messages.contains(&celox::RuntimeEvent::Display { message: b"inside=8".to_vec() })); + sim.modify(|io| io.set(data, 8u8)).unwrap(); + assert_ne!(sim.get(sim.signal("q")), first); + let messages = sim.drain_runtime_events(); + assert_eq!(messages.len(), 2, "{messages:?}"); + assert!(messages.contains(&celox::RuntimeEvent::Display { message: b"inside=9".to_vec() })); + sim.set(sim.signal("unrelated"), 1u8); + sim.eval_comb().unwrap(); + assert!(sim.drain_runtime_events().is_empty()); + sim.tick(sim.event("clk")).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![celox::RuntimeEvent::Display { message: b"clock".to_vec() }]); + } + + fn urandom_comb_notifies_only_observed_bits(sim) { + @setup { let source = r#" + module Static(input logic low, input logic [6:0] high, output logic [7:0] q); + always_comb begin q[0] = low; q[7:1] = high; void'($urandom); end + always_comb $display("static=%b", q[0]); + endmodule + module Dynamic(input logic low, high, input logic [2:0] index, output logic [7:0] q); + always_comb begin + q[0] = low; q[7:1] = 0; q[index] = high; void'($urandom); + end + always_comb $display("dynamic=%b", q[0]); + endmodule + module Array(input logic low, input logic [6:0] high, input logic [2:0] index, output logic [7:0] q); + logic [7:0] words[0:1]; + always_comb begin + words[0] = {high, low}; words[1] = 0; + words[(index == 0) ? 0 : 1] = {7'b0, high[0]}; void'($urandom); + end + assign q = words[0]; + always_comb $display("array=%b", words[0][0]); + endmodule + module Top(input logic low, input logic [6:0] high, input logic [2:0] index, + output logic [7:0] q_static, q_dynamic, q_array); + Static s(low, high, q_static); + Dynamic d(low, high[0], index, q_dynamic); + Array a(low, high, index, q_array); + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_observed_bits.sv"))], "Top").four_state(true); + let low = sim.signal("low"); + let high = sim.signal("high"); + let index = sim.signal("index"); + sim.modify(|io| { io.set(low, 0u8); io.set(high, 0u8); io.set(index, 4u8); }).unwrap(); + sim.drain_runtime_events(); + sim.modify(|io| io.set(high, 1u8)).unwrap(); + let events = sim.drain_runtime_events(); + let array_value = sim.get(sim.signal("q_array")); + assert!(events.is_empty(), "{events:?}; array={array_value:?}"); + assert_eq!(array_value, 2u8.into()); + sim.modify(|io| io.set(low, 1u8)).unwrap(); + let mut messages: Vec<_> = sim.drain_runtime_events().into_iter().map(|event| match event { + celox::RuntimeEvent::Display { message } => message, + event => panic!("unexpected event: {event:?}"), + }).collect(); + messages.sort(); + assert_eq!(messages, vec![b"array=1".to_vec(), b"dynamic=1".to_vec(), b"static=1".to_vec()]); + sim.modify(|io| io.set_four_state(high, 1u8.into(), 64u8.into())).unwrap(); + let events = sim.drain_runtime_events(); + assert!(events.is_empty(), "{events:?}"); + sim.modify(|io| { io.set(high, 0u8); io.set(index, 5u8); }).unwrap(); + let events = sim.drain_runtime_events(); + assert!(events.is_empty(), "{events:?}"); + sim.modify(|io| io.set(index, 0u8)).unwrap(); + let mut messages: Vec<_> = sim.drain_runtime_events().into_iter().map(|event| match event { + celox::RuntimeEvent::Display { message } => message, + event => panic!("unexpected event: {event:?}"), + }).collect(); + messages.sort(); + assert_eq!(messages, vec![b"array=0".to_vec(), b"dynamic=0".to_vec()]); + } + + fn urandom_has_an_unsigned_self_determined_result(sim) { + @case "system_functions::urandom_has_an_unsigned_self_determined_result"; + } + + fn urandom_respects_short_circuits_and_evaluates_indices_once(sim) { + @case "system_functions::urandom_respects_short_circuits_and_evaluates_indices_once"; + } + + fn urandom_checkpoint_restores_the_stream(sim) { + @setup { let source = r#" + module Top(input logic clk, reseed, output int unsigned value); + always_ff @(posedge clk) begin + if (reseed) value <= $urandom(17); + else value <= $urandom; + end + endmodule + "#; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_state.sv"))], "Top").four_state(true); + let clk = sim.event("clk"); + let reseed = sim.signal("reseed"); + let value = sim.signal("value"); + sim.set(reseed, 1u8); + sim.tick(clk).unwrap(); + sim.set(reseed, 0u8); + let checkpoint = sim.checkpoint().unwrap(); + let mut expected = Vec::new(); + for _ in 0..4 { + sim.tick(clk).unwrap(); + let (value, mask) = sim.get_four_state(value); + assert_eq!(mask, 0u8.into()); + expected.push(value); + } + sim.restore(&checkpoint).unwrap(); + for value_expected in expected { + sim.tick(clk).unwrap(); + assert_eq!(sim.get(value), value_expected); + } + } + + fn urandom_reseeds_and_shares_the_calling_process_stream(sim) { + @case "system_functions::urandom_reseeds_and_shares_the_calling_process_stream"; + } + fn urandom_keeps_process_and_instance_streams_independent(sim) { + @case "system_functions::urandom_keeps_process_and_instance_streams_independent"; + } + fn display_expressions_propagate_operand_widths(sim) { @case "system_functions::display_expressions_propagate_operand_widths"; } fn character_formats_preserve_non_utf8_bytes(sim) { @case "system_functions::character_formats_preserve_non_utf8_bytes"; } @@ -1512,3 +1889,200 @@ fn dimension_queries_reject_invalid_indices() { } } } + +#[test] +fn urandom_initial_processes_have_separate_default_streams() { + let source = r#" + module Top(output int unsigned a, b, replay_a, replay_b); + function automatic int unsigned draw(); return $urandom(); endfunction + initial begin a = draw(); a = draw(); end + initial begin b = draw(); b = draw(); end + initial begin + replay_a = $urandom(123); replay_a = draw(); + replay_b = $urandom(123); replay_b = draw(); + end + endmodule + "#; + let mut sim = initial_simulation(source); + sim.step().unwrap(); + assert_ne!(sim.get(sim.signal("a")), sim.get(sim.signal("b"))); + assert_eq!( + sim.get(sim.signal("replay_a")), + sim.get(sim.signal("replay_b")) + ); +} + +#[test] +fn urandom_rejects_invalid_seeds_and_constant_value_contexts() { + for item in [ + "always_ff @(posedge clk) y <= $urandom(1, 2);", + "always_ff @(posedge clk) y <= $urandom(,);", + "always_ff @(posedge clk) y <= $urandom(.seed(1));", + "always_ff @(posedge clk) y <= $urandom(int);", + "always_ff @(posedge clk) y <= $urandom(1.5);", + "int seeds[2]; always_ff @(posedge clk) y <= $urandom(seeds);", + "localparam UNUSED = $urandom; assign y=0;", + "localparam UNUSED = 0 && $urandom; assign y=0;", + ] { + let source = format!("module Top(input logic clk, output int y); {item} endmodule"); + let error = build_error(&source); + assert!(error.contains("urandom"), "{item}: {error}"); + } + // A query inspects the return type without executing the RNG; an + // element of an unpacked array is still a valid integral seed. + let source = "module Top(input logic clk, output int width, value); int seeds[2]; localparam W=$bits($urandom()); assign width=W; always_ff @(posedge clk) value <= $urandom(seeds[0]); endmodule"; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("random_query.sv"))], "Top") + .build_cranelift() + .unwrap(); + assert_eq!(sim.get(sim.signal("width")), 32u32.into()); +} + +#[test] +fn urandom_default_seeds_follow_mixed_static_process_order() { + fn draws(extra: &str) -> Vec { + let source = format!( + r#" + module Top(input logic clk, output int unsigned early, comb, clocked, late, extra); + initial early = $urandom; + always_comb comb = $urandom; + always_ff @(posedge clk) clocked <= $urandom; + initial late = $urandom; + {extra} + endmodule + "# + ); + let mut sim = initial_simulation(&source); + sim.add_clock("clk", 2, 1); + sim.step().unwrap(); + sim.step().unwrap(); + ["early", "comb", "clocked", "late"] + .into_iter() + .map(|name| sim.get(sim.signal(name))) + .collect() + } + let baseline = draws(""); + for extra in [ + "always_ff @(posedge clk) extra <= $urandom;", + "initial extra = $urandom;", + "always_comb extra = $urandom;", + "always @* extra = $urandom;", + ] { + assert_eq!(draws(extra), baseline, "appended process: {extra}"); + } + for (i, value) in baseline.iter().enumerate() { + for other in &baseline[i + 1..] { + assert_ne!(value, other); + } + } +} + +#[test] +fn urandom_comb_starts_after_initial_procedures() { + let source = r#" + module Child(input int seed, output int unsigned value); + always_comb begin value = $urandom(seed); $display("comb=%0d", seed); end + endmodule + module Top(output int unsigned value); + int seed; + Child child(seed, value); + initial begin seed = 17; $display("initial"); end + endmodule + "#; + let mut sim = initial_simulation(source); + assert!(sim.drain_runtime_events().is_empty()); + sim.step().unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![ + celox::RuntimeEvent::Display { + message: b"initial".to_vec() + }, + celox::RuntimeEvent::Display { + message: b"comb=17".to_vec() + }, + ] + ); + let value = sim.get(sim.signal("value")); + sim.eval_comb().unwrap(); + assert_eq!(sim.get(sim.signal("value")), value); + assert!(sim.drain_runtime_events().is_empty()); +} + +#[test] +fn urandom_comb_interpreter_preserves_activation_and_unknown_masks() { + let source = r#" + module Top(input logic trigger, output logic echo, output int unsigned value); + function automatic int unsigned draw(); return $urandom; endfunction + always_comb begin echo = trigger; value = draw(); end + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("random_interp.sv"))], "Top") + .four_state(true) + .build_interpreter() + .unwrap(); + let trigger = sim.signal("trigger"); + let value = sim.signal("value"); + sim.modify(|io| io.set(trigger, 0u8)).unwrap(); + let first = sim.get(value); + sim.modify(|io| io.set_four_state(trigger, 0u8.into(), 1u8.into())) + .unwrap(); + let second = sim.get(value); + assert_ne!(first, second); + assert_eq!(sim.get_four_state(value).1, 0u8.into()); + sim.eval_comb().unwrap(); + assert_eq!(sim.get(value), second); +} + +#[test] +fn urandom_declaration_initializers_have_distinct_stable_streams() { + fn run(extra: &str) -> Vec { + let source = format!( + r#" + module Top(output int unsigned first, second, observed_first, observed_second); + int unsigned a = $urandom; + int unsigned b = $urandom; + assign first = a; + assign second = b; + initial begin observed_first = a; observed_second = b; end + {extra} + endmodule + "# + ); + let mut sim = initial_simulation(&source); + sim.step().unwrap(); + ["first", "second", "observed_first", "observed_second"] + .map(|name| sim.get(sim.signal(name))) + .to_vec() + } + let baseline = run(""); + assert_ne!(baseline[0], 0u8.into()); + assert_ne!(baseline[1], 0u8.into()); + assert_ne!(baseline[0], baseline[1]); + assert_eq!(baseline[0], baseline[2]); + assert_eq!(baseline[1], baseline[3]); + assert_eq!(baseline, run("int unsigned later = $urandom;")); +} + +#[test] +fn urandom_parameter_storage_does_not_consume_default_seeds() { + fn run(parameter: &str) -> BigUint { + let source = format!( + r#" + module Top(output int unsigned value); + {parameter} + initial value = $urandom; + endmodule + "# + ); + let mut sim = initial_simulation(&source); + sim.step().unwrap(); + sim.get(sim.signal("value")) + } + let baseline = run(""); + for parameter in [ + "parameter logic [7:0] A[0:0] = '{0};", + "localparam logic [7:0] A[0:0] = '{0};", + ] { + assert_eq!(run(parameter), baseline, "{parameter}"); + } +} diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 9b945b5449a..23af8333ba1 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -85,6 +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 | | 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 | @@ -370,3 +371,14 @@ resolved using their bound interface type before flattening, including generic interface ports and handles declared within a generate block. Scalar paths to interface instances inside child modules, such as `child.info`, are resolved before those instances are flattened away. + +`$urandom` uses a deterministic, full-period 32-bit linear congruential generator +(IEEE 1800-2023 18.13.1 and 18.14). Reseeding repeats the sequence without +modifying the seed argument. Calls through subroutines use their caller's +stream. The generator state participates in checkpoints and state restoration. +The default seed is implementation-defined; random values need not match those +of other simulators. In combinational procedures, draws occur when the process +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. diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 44de8ed3f33..f564c966a54 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -71,6 +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符号なしの乱数列 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 状態 | 2 値・4 値シミュレーション | @@ -223,3 +224,13 @@ Veryl の適合性スイートは、Veryl が出力する SystemVerilog に対 interface型から解決します。generic interfaceポートとgenerate内のローカルハンドルも 対象です。`child.info`のように子module内のinterfaceインスタンスを指定する スカラー階層も、インスタンスが展開で消える前に解決します。 + +`$urandom` は周期が2の32乗の決定的な線形合同法を使います +(IEEE 1800-2023 18.13.1、18.14)。同じシードで同じ列を再現し、 +シード引数は変更しません。サブルーチン内では呼び出し元プロセスの列を使い、 +乱数状態はチェックポイントの保存・復元に含まれます。 +既定シードと具体的な乱数値は実装依存です。 +組み合わせプロセスでは、プロセスの起動時にだけ乱数列が進みます。 +`always_comb` は時刻0と暗黙の感度リストの入力変化時に実行され、 +`always @*` は入力変化を待ちます。入力が変わらない再評価では乱数列は進みません。 +定数値を要求する文脈では診断を返します。 diff --git a/package.json b/package.json index 04f309ffba4..06913a417c0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "private": true, - "packageManager": "pnpm@12.10.1", + "packageManager": "pnpm@12.11.0", "scripts": { "build": "pnpm --filter=\"!@celox-sim/celox-napi\" --filter=\"!@celox-sim/playground\" -r build", "build:napi": "pnpm --filter @celox-sim/celox-napi build:debug", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 96dd32fc560..fa11ce838ab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,153 +7,153 @@ importers: configDependencies: {} packageManagerDependencies: pnpm: - specifier: 12.10.1 - version: 12.10.1 + specifier: 12.11.0 + version: 12.11.0 packages: - '@pnpm/exe.android-arm64@12.10.1': - resolution: {integrity: sha512-CVTlHPwNvadQCJD9bGSMzWIhFX8QpjtqC2c27dhdnn/9iKzEjZ3qL62o3gHpKbIuo6qn4WxTKRoaokgNdReBig==} + '@pnpm/exe.android-arm64@12.11.0': + resolution: {integrity: sha512-iaRous2TG9l3evU4PlfpyHEQYk7FgePfIUd/Duc1Ev2V+xAcN5IgsDRstvMSxa4zo04xtiGKTG06X1RW+knSVw==} cpu: [arm64] os: [android] - '@pnpm/exe.android-x64@12.10.1': - resolution: {integrity: sha512-NFiYLIaodY7da0XIebwcU3JoP7IK/lzF7zgKSSP+9H+QcFnQ1GDfBkuBKCYJzZ+Xu0WH54neIPLBBCaOjaaauA==} + '@pnpm/exe.android-x64@12.11.0': + resolution: {integrity: sha512-3SFkB+pF5cdV0KdTUrNvH6Xjp1CJ81w0u4HD5aI5pLWsqOHCi90s78Ja2v9aSnNsONMzJ+TSSEStPRyMQLNh4A==} cpu: [x64] os: [android] - '@pnpm/exe.darwin-arm64@12.10.1': - resolution: {integrity: sha512-0O8tdQ8ijlPJudXspLMTcitMkdBEz6uUflazL5uQE0WMs85oQIp0U+5hfEktMFB64QqEhjqlvvujTwbzdr9oMg==} + '@pnpm/exe.darwin-arm64@12.11.0': + resolution: {integrity: sha512-xlh3Cuv2s0aTjStWpmO0VVifQSUEn0UPLn/KilQv893OdJ6kjfWReB/hI55OV1ppjO/xPiJ4CoS9KIGz3TdjSw==} cpu: [arm64] os: [darwin] - '@pnpm/exe.darwin-x64@12.10.1': - resolution: {integrity: sha512-ud+1/uZOKEo8P/AsPynOJc/LNwfI0j6WwCElibj71rU9l4nIBnsSn+wWTIPZPkZ4BBSH5+82azSnAARMyJ1lNA==} + '@pnpm/exe.darwin-x64@12.11.0': + resolution: {integrity: sha512-/nDHVuVK+3gc9MtBi3fKmqWuukp8I6cfi0hLxtBDqJVCWPEhKx7auoH59RLg1WsAKsrULgs8FDHFtJKzscqSGg==} cpu: [x64] os: [darwin] - '@pnpm/exe.freebsd-x64@12.10.1': - resolution: {integrity: sha512-mj9PE5rf8uAfQQ2K66HSATMSut+lNiB4eSqFd5+azFVCMnxNSy/32xpZQJT21PhnN3Y4qbK+iKHe5nWAxSuRhw==} + '@pnpm/exe.freebsd-x64@12.11.0': + resolution: {integrity: sha512-XVkee+Ltk+WujwIhoOYTJrxxjiVvnjJDrjrhkZ4fcB4N6Klw129xEmUWGc5GCqQ5fIP0lQKgi/gERqtTDF76lg==} cpu: [x64] os: [freebsd] - '@pnpm/exe.linux-arm64-musl@12.10.1': - resolution: {integrity: sha512-xba+00wZJ8Um6rBJJjWl88uJj0tydB8dtomvjlCLvi0uL32vpa9CRP8Vv26FIXvbiZ1bo2RCzYt/eChxJVV52w==} + '@pnpm/exe.linux-arm64-musl@12.11.0': + resolution: {integrity: sha512-P/dDOnqFG5t3oR6zBvxZ/19gpGCRTqTzDxY9XYhP56csybJrQ96WTCLh+E5/2VlOCps/Ote7dh127h5Z6fJEOQ==} cpu: [arm64] os: [linux] libc: [musl] - '@pnpm/exe.linux-arm64@12.10.1': - resolution: {integrity: sha512-oBdMp69ScC9UnniG4qZAQVr2fBDSXjm4yk/72vkEVyrlwS23yMxcRQl7Qdo3sgXPAygY6TWnPRKm4rXzjoyW7w==} + '@pnpm/exe.linux-arm64@12.11.0': + resolution: {integrity: sha512-i8pwzaDfiyE6Aq6zOSUSWsUdSUP9aJw648q8HvAAhDCvd2ywYNkop2BvUfC3tcmg7gYt3XuEHNDKbp5FcIKAPg==} cpu: [arm64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-ppc64@12.10.1': - resolution: {integrity: sha512-Yyb3wu09h3c7mLme270uHFiVaAIUHC411Ru9LIU2BKUIstrGlXa9OqqVWoXaRgYRdFdOFknkwG7GNn6ygwLbnw==} + '@pnpm/exe.linux-ppc64@12.11.0': + resolution: {integrity: sha512-J0y8s/0d43yqYs69mu3v4mGS9UczmI99jNOo2XrrFAJw6XUWBSsjwiN6xd6OwiRa/1QP+joooGMUMOMgmSj5/A==} cpu: [ppc64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-riscv64@12.10.1': - resolution: {integrity: sha512-PdkeUFFkybknnGkWP0H22eMpIiS4OZXL5BcQzF4lh+vmrW3IaC2HOkbANKgot/PKO0Kl77pzA/6PKFxgbgfXIQ==} + '@pnpm/exe.linux-riscv64@12.11.0': + resolution: {integrity: sha512-XRJMy9cpSa/WqeQRwJJENBvZNg4o6iOjSlG/Nj3cR8p19367YP0WGDFsMn5QYSwUsQivFvZtQ7AHasGYoKOunA==} cpu: [riscv64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-s390x@12.10.1': - resolution: {integrity: sha512-1okKuHKJwJPAbofDxfhZWAUxEWtee4ZSf7Pah8kcvocaJkf2WxFJ5KVTiNIvDml5GLidDQsgf7Pcf/WHbCak7Q==} + '@pnpm/exe.linux-s390x@12.11.0': + resolution: {integrity: sha512-oN2T6oMjPdav6WOsF0Zr3jh9KvLLUEDnwVy4kgOpWb2decAUhZKxO0bcEG1ozEJVQqe99Y96L8URLo9AYAiopA==} cpu: [s390x] os: [linux] libc: [glibc] - '@pnpm/exe.linux-x64-musl@12.10.1': - resolution: {integrity: sha512-e6IqzVNkPa7srFKJKnY23uWJ+qz0LaRWiTUo/sHfFXRRMRzB5uNOr6qWWip/jqhdGwU91n9J7LrEYZ6e0tRczw==} + '@pnpm/exe.linux-x64-musl@12.11.0': + resolution: {integrity: sha512-ThGTDSSTlBqsn5LOXrioEoNQXq7UBmiMmGWgThwRaZ4u9q8dEipeqYgXGOuYWuNkHOFr9QpDjgT4Ty2xmnU5ng==} cpu: [x64] os: [linux] libc: [musl] - '@pnpm/exe.linux-x64@12.10.1': - resolution: {integrity: sha512-ZByV0DRgWzGaDSjT5ddRBASdwz+r/qPMYh7o6RGmPQjtRGNFbSl94xY2DcAM8mqCOZJUUDtAXQ+wpBXcdpKlkg==} + '@pnpm/exe.linux-x64@12.11.0': + resolution: {integrity: sha512-H78vY3QwTjPjj45Jke9XC4zcwDTBVVJHjvYbvh36xsG9Lz/UDtzUaHgIc6V3xZd5N4eWVldAETjHWPKe0lWpnQ==} cpu: [x64] os: [linux] libc: [glibc] - '@pnpm/exe.win32-arm64@12.10.1': - resolution: {integrity: sha512-I7QZHcjioG7orFeCRUFUHByJ1G0zFPnAlaGGyrUvb6MGkv5oeNwNPl7t+Gp+7zHfnMcgLGJ1a+Wfim0IDw3lOw==} + '@pnpm/exe.win32-arm64@12.11.0': + resolution: {integrity: sha512-VKMsGYtmRtrqCbwKIJRwebR1qF4ODPqiOMCb5N2+qUHfjp3qdZ7IomSrt8QdwbJYcGe+ZMVcRL80zSbLgSNDLg==} cpu: [arm64] os: [win32] - '@pnpm/exe.win32-x64@12.10.1': - resolution: {integrity: sha512-4WJFdp58EKlCj0zLobrXU0vpszSZIr4X/3y/uNbAQqGW0zE+VdruZB0gFc3L2kzsUzVwTYbaCn+XEhnCYSAlTg==} + '@pnpm/exe.win32-x64@12.11.0': + resolution: {integrity: sha512-tCIMq219fSc5xr+sd2ZTFr31sE5Shi9E6kka4VqlxwkwVSarKrhzMiArqaofcSDuUyPwHmjFfXmgE7cNee46kw==} cpu: [x64] os: [win32] - pnpm@12.10.1: - resolution: {integrity: sha512-ukCjfrGjcNYP6oxM8dNkwTvMzvUY6YrSvO6VT1OdONo3RY5YJho/pV4GUjRQ6g//+fSXsTW+QfLBXBZCusrObA==} + pnpm@12.11.0: + resolution: {integrity: sha512-Kcy01B+twbOJBgyn4FuzABLKBLHRUCx1vAkwQh6ibYz7lKZ04YwA3E6BzAZhqxDTDQJZvr0SK8wEz/ahL2gs+w==} engines: {node: '>=18.*'} hasBin: true snapshots: - '@pnpm/exe.android-arm64@12.10.1': + '@pnpm/exe.android-arm64@12.11.0': optional: true - '@pnpm/exe.android-x64@12.10.1': + '@pnpm/exe.android-x64@12.11.0': optional: true - '@pnpm/exe.darwin-arm64@12.10.1': + '@pnpm/exe.darwin-arm64@12.11.0': optional: true - '@pnpm/exe.darwin-x64@12.10.1': + '@pnpm/exe.darwin-x64@12.11.0': optional: true - '@pnpm/exe.freebsd-x64@12.10.1': + '@pnpm/exe.freebsd-x64@12.11.0': optional: true - '@pnpm/exe.linux-arm64-musl@12.10.1': + '@pnpm/exe.linux-arm64-musl@12.11.0': optional: true - '@pnpm/exe.linux-arm64@12.10.1': + '@pnpm/exe.linux-arm64@12.11.0': optional: true - '@pnpm/exe.linux-ppc64@12.10.1': + '@pnpm/exe.linux-ppc64@12.11.0': optional: true - '@pnpm/exe.linux-riscv64@12.10.1': + '@pnpm/exe.linux-riscv64@12.11.0': optional: true - '@pnpm/exe.linux-s390x@12.10.1': + '@pnpm/exe.linux-s390x@12.11.0': optional: true - '@pnpm/exe.linux-x64-musl@12.10.1': + '@pnpm/exe.linux-x64-musl@12.11.0': optional: true - '@pnpm/exe.linux-x64@12.10.1': + '@pnpm/exe.linux-x64@12.11.0': optional: true - '@pnpm/exe.win32-arm64@12.10.1': + '@pnpm/exe.win32-arm64@12.11.0': optional: true - '@pnpm/exe.win32-x64@12.10.1': + '@pnpm/exe.win32-x64@12.11.0': optional: true - pnpm@12.10.1: + pnpm@12.11.0: optionalDependencies: - '@pnpm/exe.android-arm64': 12.10.1 - '@pnpm/exe.android-x64': 12.10.1 - '@pnpm/exe.darwin-arm64': 12.10.1 - '@pnpm/exe.darwin-x64': 12.10.1 - '@pnpm/exe.freebsd-x64': 12.10.1 - '@pnpm/exe.linux-arm64': 12.10.1 - '@pnpm/exe.linux-arm64-musl': 12.10.1 - '@pnpm/exe.linux-ppc64': 12.10.1 - '@pnpm/exe.linux-riscv64': 12.10.1 - '@pnpm/exe.linux-s390x': 12.10.1 - '@pnpm/exe.linux-x64': 12.10.1 - '@pnpm/exe.linux-x64-musl': 12.10.1 - '@pnpm/exe.win32-arm64': 12.10.1 - '@pnpm/exe.win32-x64': 12.10.1 + '@pnpm/exe.android-arm64': 12.11.0 + '@pnpm/exe.android-x64': 12.11.0 + '@pnpm/exe.darwin-arm64': 12.11.0 + '@pnpm/exe.darwin-x64': 12.11.0 + '@pnpm/exe.freebsd-x64': 12.11.0 + '@pnpm/exe.linux-arm64': 12.11.0 + '@pnpm/exe.linux-arm64-musl': 12.11.0 + '@pnpm/exe.linux-ppc64': 12.11.0 + '@pnpm/exe.linux-riscv64': 12.11.0 + '@pnpm/exe.linux-s390x': 12.11.0 + '@pnpm/exe.linux-x64': 12.11.0 + '@pnpm/exe.linux-x64-musl': 12.11.0 + '@pnpm/exe.win32-arm64': 12.11.0 + '@pnpm/exe.win32-x64': 12.11.0 --- lockfileVersion: '9.0'