From f52c00e577c9205bd2332b2bf0bf8d5b50a85b1b Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 18:56:33 +0900 Subject: [PATCH 1/4] perf(native): deduplicate compile tasks by unit classes instead of deep comparison The native backend found an existing task for each trigger by comparing its unit list with every task so far, unit by unit and block by block. An unfused comb-apply task starts with all of `eval_comb`, so each comparison walked the whole combinational program: O(triggers^2 x program size). On C906 the backend sat in compile_program for 19+ minutes, mostly in memcmp and HashMap::eq. Each distinct execution unit is now hashed once and assigned a class of structurally equal units, and tasks are looked up by their list of classes. Two unit lists have the same classes exactly when they compare equal, and tasks are visited in the same order, so the tasks, their order and their bindings are the same as before and the generated code does not change. Closes #1982 Change-Id: I03837ef8fa9804562d781436411449be6cb1c9b8 --- crates/celox/src/backend/native/backend.rs | 198 ++++++++++++++++++--- 1 file changed, 170 insertions(+), 28 deletions(-) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index b452f9474b6..bb0b9c8ea91 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -1320,42 +1320,101 @@ struct NativeCompileTask<'a> { type NativeTaskBindings = HashMap<(&'static str, AbsoluteAddr), usize>; +type NativeUnit = crate::ir::ExecutionUnit; + +/// Classes of structurally equal execution units. Each distinct unit is +/// hashed once and compared only against the units of its hash, so tasks +/// whose unit lists share whole programs, such as every unfused comb-apply +/// task starting with all of `eval_comb`, are told apart by their class +/// lists instead of by comparing the programs again for each trigger. +#[derive(Default)] +struct NativeUnitClasses<'a> { + by_unit: HashMap<*const NativeUnit, usize>, + by_hash: HashMap>, + count: usize, +} + +impl<'a> NativeUnitClasses<'a> { + fn class(&mut self, unit: &'a NativeUnit) -> usize { + if let Some(class) = self.by_unit.get(&std::ptr::from_ref(unit)) { + return *class; + } + let bucket = self.by_hash.entry(native_unit_hash(unit)).or_default(); + let class = match bucket.iter().find(|(other, _)| *other == unit) { + Some((_, class)) => *class, + None => { + let class = self.count; + self.count += 1; + bucket.push((unit, class)); + class + } + }; + self.by_unit.insert(std::ptr::from_ref(unit), class); + class + } + + fn classes(&mut self, units: &[&'a NativeUnit]) -> Vec { + units.iter().map(|unit| self.class(unit)).collect() + } +} + +/// A hash of `unit` that equal units share, independent of the iteration +/// order of its maps. +fn native_unit_hash(unit: &NativeUnit) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = fxhash::FxHasher::default(); + unit.entry_block_id.hash(&mut hasher); + let mut blocks = unit.blocks.iter().collect::>(); + blocks.sort_unstable_by_key(|(id, _)| **id); + for (id, block) in blocks { + id.hash(&mut hasher); + block.id.hash(&mut hasher); + block.params.hash(&mut hasher); + block.instructions.hash(&mut hasher); + block.terminator.hash(&mut hasher); + } + let mut registers = unit.register_map.iter().collect::>(); + registers.sort_unstable_by_key(|(id, _)| **id); + registers.hash(&mut hasher); + hasher.finish() +} + fn collect_ff_compile_tasks( sir: &LaidOutProgram, ) -> (Vec>, NativeTaskBindings) { let mut tasks = Vec::new(); let mut task_bindings = HashMap::default(); - collect_ff_compile_tasks_from( - sir, - &sir.sir.eval_apply_ffs, - "eval_apply_ff", - &mut tasks, - &mut task_bindings, - ); - collect_ff_compile_tasks_from( - sir, - &sir.sir.eval_only_ffs, - "eval_only_ff", - &mut tasks, - &mut task_bindings, - ); - collect_ff_compile_tasks_from( - sir, - &sir.sir.apply_ffs, - "apply_ff", - &mut tasks, - &mut task_bindings, - ); - collect_comb_apply_compile_tasks(sir, &mut tasks, &mut task_bindings); + let mut classes = NativeUnitClasses::default(); + // Edge tasks of every label share one index: a task is reused for any + // edge trigger with equal units. + let mut ff_tasks = HashMap::default(); + for (ff_map, label) in [ + (&sir.sir.eval_apply_ffs, "eval_apply_ff"), + (&sir.sir.eval_only_ffs, "eval_only_ff"), + (&sir.sir.apply_ffs, "apply_ff"), + ] { + collect_ff_compile_tasks_from( + sir, + ff_map, + label, + &mut classes, + &mut ff_tasks, + &mut tasks, + &mut task_bindings, + ); + } + collect_comb_apply_compile_tasks(sir, &mut classes, &mut tasks, &mut task_bindings); (tasks, task_bindings) } fn collect_comb_apply_compile_tasks<'a>( sir: &'a LaidOutProgram, + classes: &mut NativeUnitClasses<'a>, tasks: &mut Vec>, task_bindings: &mut NativeTaskBindings, ) { const LABEL: &str = "eval_comb_apply_ff"; + let mut comb_tasks = HashMap::<(Option, Vec), usize>::default(); for (addr, ff_units) in &sir.sir.eval_apply_ffs { let fused_units = sir.sir.eval_comb_apply_ffs.get(addr); let (unit_refs, first_ff_unit) = if let Some(fused_units) = fused_units { @@ -1368,11 +1427,8 @@ fn collect_comb_apply_compile_tasks<'a>( (unit_refs, first_ff_unit) }; let binding = format!("{LABEL} trigger={}", sir.get_path(addr)); - let index = if let Some(index) = tasks.iter().position(|task| { - task.merge_kind == NativeMergeKind::FusedCombAndFf - && task.first_ff_unit == first_ff_unit - && task.units == unit_refs - }) { + let key = (first_ff_unit, classes.classes(&unit_refs)); + let index = if let Some(&index) = comb_tasks.get(&key) { tasks[index].bindings.push(binding); index } else { @@ -1384,6 +1440,7 @@ fn collect_comb_apply_compile_tasks<'a>( first_ff_unit, bindings: vec![binding], }); + comb_tasks.insert(key, index); index }; task_bindings.insert((LABEL, *addr), index); @@ -1397,13 +1454,16 @@ fn collect_ff_compile_tasks_from<'a>( Vec>, >, label: &'static str, + classes: &mut NativeUnitClasses<'a>, + ff_tasks: &mut HashMap, usize>, tasks: &mut Vec>, task_bindings: &mut NativeTaskBindings, ) { for (addr, units) in ff_map { let unit_refs = units.iter().collect::>(); let binding = format!("{label} trigger={}", sir.get_path(addr)); - let index = if let Some(index) = tasks.iter().position(|task| task.units == unit_refs) { + let key = classes.classes(&unit_refs); + let index = if let Some(&index) = ff_tasks.get(&key) { tasks[index].bindings.push(binding); index } else { @@ -1415,6 +1475,7 @@ fn collect_ff_compile_tasks_from<'a>( first_ff_unit: None, bindings: vec![binding], }); + ff_tasks.insert(key, index); index }; task_bindings.insert((label, *addr), index); @@ -3515,3 +3576,84 @@ impl super::super::SimBackend for NativeBackend { celox_runtime::backend::triggered_bits_from_bytes(&self.mem_bytes()[offset..offset + size]) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir::{ + BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue, + }; + + /// A unit of `blocks` blocks loading `value`, with its maps filled in + /// forward or reverse order. + fn unit(blocks: usize, value: u8, width: usize, reverse: bool) -> NativeUnit { + let mut ids = (0..blocks).collect::>(); + if reverse { + ids.reverse(); + } + NativeUnit { + entry_block_id: BlockId(0), + blocks: ids + .iter() + .map(|&id| { + let terminator = if id + 1 < blocks { + SIRTerminator::Jump(BlockId(id + 1), vec![]) + } else { + SIRTerminator::Return + }; + let block = BasicBlock { + id: BlockId(id), + params: vec![], + instructions: vec![SIRInstruction::Imm( + RegisterId(id), + SIRValue::new(value), + )], + terminator, + }; + (BlockId(id), block) + }) + .collect(), + register_map: ids + .iter() + .map(|&id| (RegisterId(id), RegisterType::Logic { width })) + .collect(), + } + } + + #[test] + fn unit_classes_match_deep_comparison() { + let mut pool = Vec::new(); + for blocks in 1..4 { + for value in 0..2 { + for width in [1, 8] { + for reverse in [false, true] { + pool.push(unit(blocks, value, width, reverse)); + } + } + } + } + let units = pool.iter().collect::>(); + // Lists of up to two units, repeating the same references as the + // shared prefix of comb-apply tasks does. + let lists = std::iter::once(Vec::new()) + .chain(units.iter().map(|unit| vec![*unit])) + .chain( + units + .iter() + .flat_map(|a| units.iter().map(move |b| vec![*a, *b])), + ) + .collect::>(); + let mut classes = NativeUnitClasses::default(); + let keys = lists + .iter() + .map(|list| classes.classes(list)) + .collect::>(); + for (a, key_a) in lists.iter().zip(&keys) { + for (b, key_b) in lists.iter().zip(&keys) { + assert_eq!(a == b, key_a == key_b, "{a:?} {b:?}"); + } + } + // The pool has equal units with differently ordered maps. + assert!(classes.count < pool.len()); + } +} From f8985cfe5d0d9376f6da1908b6b91afd82140ba8 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 20:22:49 +0900 Subject: [PATCH 2/4] perf(sv): instrument each unit once for all probes Closes #1991 Change-Id: Ied3fc477003f360c2ea17b71e19b6fd1a4559abb --- .../src/symbolic/assembly.rs | 256 ++++++++++-------- crates/celox-frontend-core/src/watch.rs | 226 +++++++++++++++- 2 files changed, 374 insertions(+), 108 deletions(-) diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index f53a2af7176..c42896d21be 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -936,85 +936,126 @@ pub fn schedule_symbolic_rtl_reporting_loops( // working state is seeded with the stable value first, so a store // compares with the value its update replaces. let ff_multi_stored = ff_multi_stored(&eval_apply_ffs, &eval_only_ffs, ¶llel_ff_units); - for (source, counter) in probes { - let width = source.access.msb - source.access.lsb + 1; - let four_state = four_state && variables[&source.id].1; - let offset = match unpacked_element_widths.get(&source.id) { - Some(&element_width) - if width > element_width - && source.access.lsb.is_multiple_of(element_width) - && width.is_multiple_of(element_width) => - { - celox_sir::SIROffset::PackedElements { - bit_offset: source.access.lsb, - element_width, + // Each unit is instrumented once for all probes. Probe `p` is pass + // `2p` over the stable state and pass `2p + 1` over a flip-flop + // evaluation's working state, the order of instrumenting probe by + // probe. + let probe_codes: Vec<_> = probes + .iter() + .map(|&(source, counter)| { + let width = source.access.msb - source.access.lsb + 1; + let four_state = four_state && variables[&source.id].1; + let offset = match unpacked_element_widths.get(&source.id) { + Some(&element_width) + if width > element_width + && source.access.lsb.is_multiple_of(element_width) + && width.is_multiple_of(element_width) => + { + celox_sir::SIROffset::PackedElements { + bit_offset: source.access.lsb, + element_width, + } } - } - _ => celox_sir::SIROffset::Static(source.access.lsb), - }; - let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == STABLE_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: stable(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for process in &mut processes { - crate::watch::instrument_unit(&mut process.kernel, code); + _ => celox_sir::SIROffset::Static(source.access.lsb), + }; + (counter, width, four_state, offset) + }) + .collect(); + let mut probes_of: HashMap> = HashMap::default(); + for (index, (source, _)) in probes.iter().enumerate() { + probes_of.entry(source.id).or_default().push(index); + } + // The first probe of `signal` whose `pass` is `after` or later. + let first_probe = |signal: AbsoluteAddr, pass: fn(usize) -> usize, after: usize| { + let indices = probes_of.get(&signal)?; + indices + .get(indices.partition_point(|&index| pass(index) < after)) + .copied() + }; + fn probe_code( + probe: &(AbsoluteAddr, usize, bool, celox_sir::SIROffset), + signal: A, + counter: A, + ) -> crate::watch::WatchCode { + let &(_, width, four_state, ref offset) = probe; + crate::watch::WatchCode { + signal, + width, + offset: offset.clone(), + four_state, + counters: vec![(CounterKind::Changes, counter)], } - for units in eval_apply_ffs - .values_mut() - .chain(eval_only_ffs.values_mut()) - .chain(apply_ffs.values_mut()) + } + let stable = |address| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address); + let working = |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); + let stable_code = |instruction: &SIRInstruction, after: usize| { + let address = crate::watch::write_destination(instruction)?; + if address.region != STABLE_REGION { + return None; + } + let index = first_probe(address.absolute_addr(), |index| 2 * index, after)?; + Some(( + 2 * index, + probe_code( + &probe_codes[index], + stable(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )) + }; + // A flip-flop evaluation's stores to a signal of `ff_multi_stored`; + // the commits that seed its working state are not writes of the + // process. + let evaluation_code = |instruction: &SIRInstruction, after: usize| { + if let SIRInstruction::Store(address, ..) = instruction + && address.region == WORKING_REGION + && ff_multi_stored.contains(&address.absolute_addr()) + && let Some(index) = + first_probe(address.absolute_addr(), |index| 2 * index + 1, after) { - for unit in units { - crate::watch::instrument_unit(unit, code); - } + return Some(( + 2 * index + 1, + probe_code( + &probe_codes[index], + working(address.absolute_addr()), + stable(probe_codes[index].0), + ), + )); } - for parts in parallel_ff_units.values_mut() { - for (_, part) in parts { - crate::watch::instrument_unit(&mut part.evaluate, code); - crate::watch::instrument_unit(&mut part.apply, code); - } + stable_code(instruction, after) + }; + for process in &mut processes { + crate::watch::instrument_writes_in_passes(&mut process.kernel, stable_code); + } + for units in eval_apply_ffs + .values_mut() + .chain(eval_only_ffs.values_mut()) + { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, evaluation_code); } - if ff_multi_stored.contains(&source.id) { - let working = - |address| RegionedAbsoluteAddr::from_absolute_addr(WORKING_REGION, address); - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == source.id).then( - || crate::watch::WatchCode { - signal: working(source.id), - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, stable(counter))], - }, - ) - }; - for_each_ff_evaluation( - &mut eval_apply_ffs, - &mut eval_only_ffs, - &mut parallel_ff_units, - |unit| instrument_stores(unit, code), - ); + } + for units in apply_ffs.values_mut() { + for unit in units { + crate::watch::instrument_writes_in_passes(unit, stable_code); } - for path in &mut comb_blocks { - if let LogicPathTarget::Process { unit, .. } = &mut path.target { - crate::watch::instrument_unit(unit, |address| { - (*address == source.id).then(|| crate::watch::WatchCode { - signal: source.id, - width, - offset: offset.clone(), - four_state, - counters: vec![(CounterKind::Changes, counter)], - }) - }); - } + } + for parts in parallel_ff_units.values_mut() { + for (_, part) in parts { + crate::watch::instrument_writes_in_passes(&mut part.evaluate, evaluation_code); + crate::watch::instrument_writes_in_passes(&mut part.apply, stable_code); + } + } + for path in &mut comb_blocks { + if let LogicPathTarget::Process { unit, .. } = &mut path.target { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let &address = crate::watch::write_destination(instruction)?; + let index = first_probe(address, |index| index, after)?; + Some(( + index, + probe_code(&probe_codes[index], address, probe_codes[index].0), + )) + }); } } let ff_units = eval_apply_ffs @@ -1052,31 +1093,45 @@ pub fn schedule_symbolic_rtl_reporting_loops( .iter() .map(|slots| slots.signal) .collect(); - for (signal, slots) in &counted { - if !ff_multi_stored.contains(signal) || pending.contains(signal) { - continue; - } - let (width, is_4state) = variables[signal]; - let regioned = RegionedAbsoluteAddr::from_absolute_addr; - let code = |address: &RegionedAbsoluteAddr| { - (address.region == WORKING_REGION && address.absolute_addr() == *signal).then( - || crate::watch::WatchCode { - signal: regioned(WORKING_REGION, *signal), - offset: celox_sir::SIROffset::Static(0), - width, - four_state: four_state && is_4state, - counters: CounterKind::ALL - .into_iter() - .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) - .collect(), - }, - ) - }; + // One pass per signal, in signal order; each pass watches only its + // own signal. + let regioned = RegionedAbsoluteAddr::from_absolute_addr; + let multi_stored: HashMap)> = counted + .iter() + .filter(|(signal, _)| ff_multi_stored.contains(signal) && !pending.contains(signal)) + .enumerate() + .map(|(pass, (&signal, slots))| { + let (width, is_4state) = variables[&signal]; + let code = crate::watch::WatchCode { + signal: regioned(WORKING_REGION, signal), + offset: celox_sir::SIROffset::Static(0), + width, + four_state: four_state && is_4state, + counters: CounterKind::ALL + .into_iter() + .map(|kind| (kind, regioned(STABLE_REGION, slots.counter(kind)))) + .collect(), + }; + (signal, (pass, code)) + }) + .collect(); + if !multi_stored.is_empty() { for_each_ff_evaluation( &mut eval_apply_ffs, &mut eval_only_ffs, &mut parallel_ff_units, - |unit| instrument_stores(unit, code), + |unit| { + crate::watch::instrument_writes_in_passes(unit, |instruction, after| { + let SIRInstruction::Store(address, ..) = instruction else { + return None; + }; + if address.region != WORKING_REGION { + return None; + } + let (pass, code) = multi_stored.get(&address.absolute_addr())?; + (*pass >= after).then(|| (*pass, code.clone())) + }) + }, ); } counted @@ -4012,19 +4067,6 @@ fn ff_multi_stored( .collect() } -/// [`crate::watch::instrument_unit`] for the stores alone: the commits that -/// seed a flip-flop evaluation's working state are not writes of the -/// process. -fn instrument_stores( - unit: &mut ExecutionUnit, - watch_for: impl Fn(&RegionedAbsoluteAddr) -> Option>, -) { - crate::watch::instrument_writes(unit, |instruction| match instruction { - SIRInstruction::Store(address, ..) => watch_for(address), - _ => None, - }); -} - /// Run `f` on every flip-flop evaluation. fn for_each_ff_evaluation( eval_apply_ffs: &mut FfUnits, diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index 40a2bdbbc5c..b29ce3188b5 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -641,6 +641,113 @@ pub fn instrument_writes( } } +/// The result of [`instrument_writes`] once per pass, in pass order, in one +/// walk over `unit`. `watch_for(instruction, after)` gives the first pass +/// from `after` on that watches `instruction`, and its code. +/// +/// A later pass also sees the code an earlier one added, and wraps the write +/// inside it, so a write watched by several passes is surrounded by their +/// code from the first pass outward in. The new registers are numbered as +/// the passes one after another would number them. +pub fn instrument_writes_in_passes( + unit: &mut ExecutionUnit, + watch_for: impl Fn(&SIRInstruction, usize) -> Option<(usize, WatchCode)>, +) { + let ExecutionUnit { + blocks, + register_map, + .. + } = unit; + let first_new = register_map.keys().map(|id| id.0 + 1).max().unwrap_or(0); + let mut next_register = first_new; + // The pass, block and first register of every piece of code added, in + // the order the walk adds them. + let mut added: Vec<(usize, usize, usize)> = Vec::new(); + let mut instrumented = Vec::new(); + for (order, block) in blocks.values_mut().enumerate() { + if !block + .instructions + .iter() + .any(|instruction| watch_for(instruction, 0).is_some()) + { + continue; + } + let mut instructions = Vec::with_capacity(block.instructions.len()); + let mut work: Vec<(SIRInstruction, usize)> = Vec::new(); + for instruction in std::mem::take(&mut block.instructions) { + work.push((instruction, 0)); + while let Some((instruction, after)) = work.pop() { + let Some((pass, watch)) = watch_for(&instruction, after) else { + instructions.push(instruction); + continue; + }; + let value_type = match &instruction { + SIRInstruction::Store(_, _, _, value, ..) => register_map.get(value).cloned(), + _ => None, + }; + let mut b = SIRBuilder::new_with(next_register); + emit_watched(&mut b, &watch, instruction, value_type.as_ref()); + b.seal_block(SIRTerminator::Return); + let (mut emitted, registers, next) = b.drain(); + added.push((pass, order, next_register)); + next_register = next; + register_map.extend(registers); + let emitted = emitted + .remove(&celox_sir::BlockId(0)) + .expect("the emitted block") + .instructions; + work.extend(emitted.into_iter().rev().map(|emitted| (emitted, pass + 1))); + } + } + block.instructions = instructions; + instrumented.push(block.id); + } + if added.is_empty() { + return; + } + + // Renumber the new registers pass by pass, then block by block in the + // order a pass visits them; within a block the walk already added each + // pass's code in order. + let mut ends: Vec = added.iter().skip(1).map(|&(.., first)| first).collect(); + ends.push(next_register); + let mut pieces: Vec<(usize, usize, usize, usize)> = added + .iter() + .zip(ends) + .map(|(&(pass, order, first), end)| (pass, order, first, end)) + .collect(); + pieces.sort_by_key(|&(pass, order, ..)| (pass, order)); + let mut renumbered = vec![0; next_register - first_new]; + let mut next = first_new; + for (.., first, end) in pieces { + for register in first..end { + renumbered[register - first_new] = next; + next += 1; + } + } + let renumber = |register: &mut RegisterId| { + if register.0 >= first_new { + register.0 = renumbered[register.0 - first_new]; + } + }; + for id in instrumented { + let block = blocks.get_mut(&id).expect("an instrumented block"); + for instruction in &mut block.instructions { + if let Some(register) = instruction.defined_register_mut() { + renumber(register); + } + instruction.for_each_use_mut(renumber); + } + } + let new_registers: Vec<_> = (first_new..next_register) + .filter_map(|id| register_map.remove_entry(&RegisterId(id))) + .collect(); + register_map.extend(new_registers.into_iter().map(|(mut id, ty)| { + renumber(&mut id); + (id, ty) + })); +} + /// Objects that hold back the occurrences of one flip-flop evaluation's /// writes to a signal until the commit that publishes them. /// @@ -1281,7 +1388,10 @@ pub fn declare_pending_slots( mod tests { use celox_sir::{SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue}; - use super::{multi_store_candidates, multi_write_candidates, successors, write_destination}; + use super::{ + WatchCode, instrument_writes, instrument_writes_in_passes, multi_store_candidates, + multi_write_candidates, successors, write_destination, + }; /// Store a constant to `address` at the open block. fn store(b: &mut SIRBuilder, address: u32) { @@ -1556,4 +1666,118 @@ mod tests { let found = multi_store_candidates(&unit, |address| Some(*address)); assert_eq!(found, (0..10000).step_by(2).collect::>()); } + + /// One pass of the equivalence test: the writes it watches and the + /// code it adds. + struct Pass { + address: u32, + stores_only: bool, + code: WatchCode, + } + + impl Pass { + fn watches(&self, instruction: &SIRInstruction) -> bool { + match instruction { + SIRInstruction::Store(address, ..) => *address == self.address, + _ => !self.stores_only && write_destination(instruction) == Some(&self.address), + } + } + } + + /// A random unit of a few blocks writing a few addresses, and random + /// passes over the same addresses; a pass's counters may be written + /// by another pass's code. + fn random_instrumentation(seed: u64) -> (celox_sir::ExecutionUnit, Vec) { + use celox_design::CounterKind; + let state = std::cell::Cell::new(seed); + let next = |bound: u64| { + state.set( + state + .get() + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ); + (state.get() >> 33) % bound + }; + let addresses = 1 + next(6) as u32; + let widths = [1, 4, 8]; + let mut b = SIRBuilder::new(); + let blocks = 1 + next(4); + for block in 0..blocks { + for _ in 0..next(6) { + let width = widths[next(3) as usize]; + let value = if next(2) == 0 { + b.alloc_logic(width) + } else { + b.alloc_bit(width, false) + }; + b.emit(SIRInstruction::Imm(value, SIRValue::new(next(256) as u8))); + let address = next(addresses as u64) as u32; + b.emit(match next(3) { + 0 => SIRInstruction::Commit( + address, + address, + SIROffset::Static(0), + width, + Vec::new(), + ), + _ => SIRInstruction::Store( + address, + SIROffset::Static(next(2) as usize * 2), + width, + value, + Vec::new(), + Vec::new(), + ), + }); + } + if block + 1 < blocks { + let following = b.new_block(); + b.seal_block(SIRTerminator::Jump(following, Vec::new())); + b.switch_to_block(following); + } + } + let value = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm(value, SIRValue::new(0u8))); + let unit = b.flush_eu().unwrap(); + let passes = (0..1 + next(8)) + .map(|_| Pass { + address: next(addresses as u64) as u32, + stores_only: next(2) == 0, + code: WatchCode { + signal: next(addresses as u64) as u32, + width: widths[next(3) as usize], + offset: SIROffset::Static(next(2) as usize * 2), + four_state: next(2) == 0, + counters: CounterKind::ALL + .into_iter() + .filter(|_| next(2) == 0) + .map(|kind| (kind, next(addresses as u64 + 2) as u32)) + .collect(), + }, + }) + .collect(); + (unit, passes) + } + + #[test] + fn instrumenting_in_passes_matches_one_pass_after_another() { + for seed in 0..3000 { + let (unit, passes) = random_instrumentation(seed); + let mut one_by_one = unit.clone(); + for pass in &passes { + instrument_writes(&mut one_by_one, |instruction| { + pass.watches(instruction).then(|| pass.code.clone()) + }); + } + let mut at_once = unit; + instrument_writes_in_passes(&mut at_once, |instruction, after| { + let found = passes[after.min(passes.len())..] + .iter() + .position(|pass| pass.watches(instruction))?; + Some((after + found, passes[after + found].code.clone())) + }); + assert_eq!(at_once, one_by_one, "seed {seed}"); + } + } } From 10dc5a2c4cee23d796d7f84404043cc60fb54144 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 21:28:08 +0900 Subject: [PATCH 3/4] perf(sv)!: run initial loops without a static trip count as a process An `initial` block is first folded into initial state by symbolic execution, and runs as a process only when that fails. A loop whose trip count the folding could not determine beforehand was unrolled one iteration at a time until `MAX_UNROLLED_ITERATIONS` (10000) failed the fold, so the block cost up to 10000 iterations of its body before running as the process it becomes anyway. The C906 testbench loads its program with two such loops (`for (j = 0; i < 32'h4000; i = j/4)` with 64 hierarchical memory writes per iteration), about 450 s each. While folding an `initial` block, a loop now proceeds only when its trip count is known before it runs; otherwise the fold fails at once and the block runs as a process: - `repeat` loops, and canonical `for` loops whose body does not write the loop variable (their trip count was already checked by `loop_needs_fold`); - `while` and `do`-`while` loops shaped like one (`counted_while_loop`): the condition compares a variable with a bound, the last statement steps that variable as a canonical `for` step would, and no other statement writes the variable or the bound. They start from the variable's current value and keep folding when their trip count fits the unroll limit. Other loops, such as a condition on a variable that another one derives, `forever`, or a `while` whose counter is stepped elsewhere, are not folded. The check costs one pass over the body, not iterations of it. The SystemVerilog reference lists the loops that fold. BREAKING CHANGE: an `initial` block with such a loop is no longer folded even when it would finish within the unroll limit. It runs as a process, which a `Simulator` rejects ("`initial` ... is a process, which Simulator does not run"); build a `Simulation` instead. Closes #1992. - Shared cases `procedural::initial_loops_without_a_static_trip_count_run_as_a_process` (the testbench's load-loop shape with hierarchical memory writes, plus `while` and `do`-`while`, matching Icarus and Verilator) and `procedural::initial_while_loops_define_the_state` (a counted `while` loop still defines the state a `Simulator` sees). - A reduction of the C906 memory load (the C906 `f_spsram_524288x128` and `ram` modules with the testbench's wipe and load loops) now takes 3.3 s instead of 223 s, with identical output; the load loop alone (`memC2.v`) takes 1.9 s instead of not finishing in 300 s. Change-Id: I596c31f5ce2d71957b3e39e8c7afa7ac159dccee --- crates/celox-frontend-sv/src/lowering/comb.rs | 34 ++++++++++- .../src/lowering/procedural.rs | 30 ++++++++++ .../src/sv/cases/procedural.vtest | 59 +++++++++++++++++++ .../frontends/systemverilog/procedural.rs | 9 +++ docs/guide/systemverilog-reference.md | 2 +- docs/ja/guide/systemverilog-reference.md | 2 +- 6 files changed, 132 insertions(+), 4 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 27fabd04104..a7a1d8c72ba 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2678,8 +2678,38 @@ impl<'p, 'a> Comb<'p, 'a> { continue_flag, }); - if let sv::ir::LoopKind::For = kind - && let Some(canonical) = canonical_for_loop(init, condition, step) + let canonical = match kind { + sv::ir::LoopKind::For => canonical_for_loop(init, condition, step), + _ => None, + }; + // An `initial` block runs as a process when it cannot be folded into + // initial state, so a loop whose trip count is not known before it + // runs goes there instead of being unrolled until the limit. + if self.initial { + let counted = match kind { + sv::ir::LoopKind::Repeat(_) => true, + sv::ir::LoopKind::For => canonical.as_ref().is_some_and(|canonical| { + let mut written = HashSet::default(); + written_names(body, &mut written); + !written.contains(&canonical.var) + }), + sv::ir::LoopKind::While | sv::ir::LoopKind::DoWhile => { + match counted_while_loop(condition, body) { + Some((counted, rest)) => { + !self.loop_needs_fold(&store, frames, &counted, rest)? + } + None => false, + } + } + sv::ir::LoopKind::Forever => false, + }; + if !counted { + return Err(unsupported( + "initial block loop without a static trip count", + )); + } + } + if let Some(canonical) = canonical && self.loop_needs_fold(&store, frames, &canonical, body)? { self.folding += 1; diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index def194c3e1d..a1a1c6bddb8 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -2320,6 +2320,36 @@ pub(super) fn canonical_for_loop( }) } +/// The counted loop a `while` or `do`-`while` loop is when its condition +/// compares a variable with a bound and its last statement steps that +/// variable, as the step of a [`canonical_for_loop`] would; the loop starts +/// from the variable's current value. Also returns the statements before +/// the step, which must not write the variable or the bound. +pub(super) fn counted_while_loop<'s>( + condition: Option<&sv::ir::Expr>, + body: &'s [sv::ir::Stmt], +) -> Option<(CanonicalLoop, &'s [sv::ir::Stmt])> { + let (step, rest) = body.split_last()?; + let sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(var), + .. + } = step + else { + return None; + }; + let init = [sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(var.clone()), + rhs: sv::ir::Expr::Ident(var.clone()), + nonblocking: false, + }]; + let canonical = canonical_for_loop(&init, condition, std::slice::from_ref(step))?; + let mut written = HashSet::default(); + written_names(rest, &mut written); + let mut bound = HashSet::default(); + expr_idents(&canonical.end, &mut bound); + (!written.contains(&canonical.var) && written.is_disjoint(&bound)).then_some((canonical, rest)) +} + /// The identifiers an expression reads. pub(super) fn expr_idents(expr: &sv::ir::Expr, names: &mut HashSet) { fn const_idents(expr: &sv::ir::ConstExpr, names: &mut HashSet) { diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 867a5ff44e3..576be5cc0ee 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -280,6 +280,65 @@ (assert_eq y (+ (* i 3) 1)) (assert_eq z 0x5a))) +; An initial block whose loops have no static trip count (a condition on +; another variable than the one the step assigns, `while`, `do`-`while`) runs +; as a process instead of being unrolled into initial state (#1992). +(case initial_loops_without_a_static_trip_count_run_as_a_process + (source "initial_loops.sv" #" + module Ram; + logic [7:0] mem [16]; + endmodule + module Top; + Ram r0(), r1(); + logic [31:0] src [32]; + logic [7:0] w [8]; + integer i, j, n; + initial begin + for (n = 0; n < 32; n = n + 1) src[n] = 32'h01010101 * n; + i = 0; + for (j = 0; i < 16; i = j / 2) begin + r0.mem[i] = src[j][15:8]; + j = j + 1; + r1.mem[i] = src[j][31:24]; + j = j + 1; + end + n = 0; + while (n < 8) begin + w[n] = 8'(n * 5); + n = n + 1; + end + do n = n - 3; while (n > 0); + #1 $display("%0d %0d %h %h %h %h %h %0d", i, j, r0.mem[0], r0.mem[15], + r1.mem[0], r1.mem[15], w[7], n); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "16 32 00 1e 01 1f 23 -1\n")) + +; The state such an initial block writes is visible like folded initial state. +(case initial_while_loops_define_the_state + (source "initial_while.sv" #" + module Top(input logic [1:0] index, output logic [7:0] y); + logic [7:0] mem [4]; + int n; + initial begin + n = 0; + while (n < 4) begin + mem[n] = 8'(n * 3 + 1); + n++; + end + end + assign y = mem[index]; + endmodule + "#) + (top Top) + (for i (range 0 4) + (modify (set index i)) + (assert_eq y (+ (* i 3) 1)))) + (case loop_initializer_widens_by_its_own_signedness (source "loop_start.sv" #" module Top(input logic [7:0] value, output logic [7:0] count, output logic [7:0] registered, diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 11835e6e428..b05942b9658 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -253,3 +253,12 @@ sv_backends! { @case "procedural::static_function_wide_packed_storage_keeps_all_bits"; } } + +sv_backends! { + fn initial_loops_without_a_static_trip_count_run_as_a_process(sim) { + @case "procedural::initial_loops_without_a_static_trip_count_run_as_a_process"; + } + fn initial_while_loops_define_the_state(sim) { + @case "procedural::initial_while_loops_define_the_state"; + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 04c403a1f49..ebf7590fcf2 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -42,7 +42,7 @@ synthesis and is tested at the design level. | Continuous logic | `assign`, `wire w = expr;` | | Combinational processes | `always_comb`, `always @*`, blocking `always_latch`, block-local variables, sequential and dependent blocking assignments, reads of a variable before the process writes it (its previous value) | | Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | -| Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if` / `for` and `$readmemh` / `$readmemb`, defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | +| Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if`, `$readmemh` / `$readmemb`, and loops whose trip count is known before they run (`repeat`, and `for`, `while` or `do`-`while` loops that step one variable by a constant up to a fixed bound), defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | | Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate and deferred immediate assertions | | Functions | `function` and `task` with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 5de49f53e7f..ef745e2e4bf 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -40,7 +40,7 @@ outline: [2, 3] | 連続論理 | `assign`、`wire w = expr;` | | 組み合わせプロセス | `always_comb`、`always @*`、ブロッキング代入の `always_latch`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | | 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | -| initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if` / `for`、`$readmemh` / `$readmemb` を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | +| initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if`、`$readmemh` / `$readmemb`、実行前に反復回数が分かるループ(`repeat` と、1 つの変数を定数ずつ固定の境界まで進める `for` / `while` / `do`-`while`)を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | | 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーションと遅延付き即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | From eef1fe65381bd397cfc0587ef182686d486e517d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 22:57:36 +0900 Subject: [PATCH 4/4] feat(cli): save state files at chosen cycles or times of a SystemVerilog run Refs #2025 Change-Id: Ib71719ee9f5f4d322b2b673915f907156e26e1a0 --- crates/celox-vpi/src/bin/celox.rs | 230 +++++++++++++++++++++++++++++- crates/celox-vpi/tests/run_cli.rs | 74 ++++++++++ crates/celox/src/simulation.rs | 10 ++ docs/guide/checkpoints.md | 4 + docs/guide/cocotb.md | 20 +++ docs/ja/guide/checkpoints.md | 2 + docs/ja/guide/cocotb.md | 14 ++ 7 files changed, 350 insertions(+), 4 deletions(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index dce33a96a11..0f04453b598 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -32,6 +32,8 @@ struct Cli { } #[derive(Subcommand)] +// Parsed once per process; boxing would only complicate the matches. +#[allow(clippy::large_enum_variant)] enum CliCommand { /// Run a SystemVerilog or Veryl native testbench. Run(RunArgs), @@ -53,6 +55,41 @@ struct RunArgs { /// Does not bound compilation or work within a single step/tick. #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] max_steps: Option, + + #[command(flatten)] + save_state: SaveStateArgs, +} + +/// When `celox run` saves state files for `celox state dump/diff`. +#[derive(Args, Clone, Default)] +struct SaveStateArgs { + /// Count the cycles of this signal for --save-state-at, such as + /// `tb.clk`: a cycle is a change of the signal to 1. + #[arg(long, value_name = "SIGNAL", requires = "save_state_at")] + save_state_on: Option, + /// Save the state after these cycles of --save-state-on, counted from 1. + #[arg( + long, + value_name = "N", + value_delimiter = ',', + requires = "save_state_on", + value_parser = clap::value_parser!(u64).range(1..) + )] + save_state_at: Vec, + /// Save the state at these simulation times (SystemVerilog), in units of + /// the design's global time precision. + #[arg(long, value_name = "T", value_delimiter = ',')] + save_state_at_time: Vec, + /// The directory of the saved files, `-.state` and + /// `time-.state` (default: the current directory). + #[arg(long, value_name = "DIR")] + save_state_dir: Option, +} + +impl SaveStateArgs { + fn is_empty(&self) -> bool { + self.save_state_on.is_none() && self.save_state_at_time.is_empty() + } } struct RunConfig { @@ -60,6 +97,7 @@ struct RunConfig { design: Design, opt_level: celox::OptLevel, max_steps: u64, + save_state: SaveStateArgs, } fn resolve_design(arguments: DesignArgs) -> Design { @@ -114,6 +152,7 @@ fn resolve_run_config(arguments: RunArgs) -> RunConfig { .or(design.max_steps) .unwrap_or(1_000_000), design, + save_state: arguments.save_state, } } @@ -137,6 +176,12 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { { return Err("pass .sv/.v sources, or Veryl project sources".into()); } + if !arguments.save_state.is_empty() { + return Err( + "--save-state-on and --save-state-at-time currently require a SystemVerilog testbench" + .into(), + ); + } runner::run(arguments.execution, arguments.design, arguments.max_steps).map_err(|error| { if let runner::RunError::InvalidConfiguration { .. } = &error { clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, error.to_string()).exit(); @@ -174,7 +219,8 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .$build() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulation.warnings())?; - simulate_sv(simulation, max_steps, &mut std::io::stdout().lock()) + let saves = StateSaves::new(&simulation, &arguments.design.top, &arguments.save_state)?; + simulate_sv(simulation, max_steps, saves, &mut std::io::stdout().lock()) }}; } match arguments.execution.backend() { @@ -192,30 +238,206 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { fn simulate_sv( mut simulation: celox::Simulation, max_steps: u64, + mut saves: StateSaves, output: &mut impl Write, ) -> Result<(), String> { let mut failed = false; let initial = simulation.eval_comb(); drain_sv_output(&mut simulation, output, &mut failed)?; initial.map_err(|error| error.to_string())?; + saves.start(&mut simulation); let mut steps = 0; - while !simulation.is_finished() && simulation.next_event_time().is_some() { + while !simulation.is_finished() + && let Some(next) = simulation.next_event_time() + { if steps == max_steps { return Err(format!("simulation exceeded --max-steps {}", max_steps)); } + saves.before(&mut simulation, next)?; let step = simulation.step(); drain_sv_output(&mut simulation, output, &mut failed)?; if step.map_err(|error| error.to_string())?.is_none() { break; } + saves.after_step(&mut simulation)?; steps += 1; } + saves.finish(&mut simulation)?; if failed { return Err("SystemVerilog testbench reported an assertion failure or $error".to_string()); } Ok(()) } +/// The state files a SystemVerilog run saves (`--save-state-*`). +/// +/// A cycle of the counted signal is a time step at whose end the signal is +/// 1 while it was not at the end of the previous one (or after the initial +/// settle). Its file is saved right after that time step, with every region +/// of the time done. A file for time `T` holds the state after everything +/// due at times up to `T`, saved before the run advances past `T`. +#[cfg(feature = "systemverilog")] +#[derive(Default)] +struct StateSaves { + counted: Option<(String, celox::SignalRef)>, + /// The cycles still to save, in descending order. + cycles: Vec, + count: u64, + high: bool, + /// The times still to save, in descending order. + times: Vec, + directory: PathBuf, +} + +#[cfg(feature = "systemverilog")] +impl StateSaves { + fn new( + simulation: &celox::Simulation, + top: &str, + arguments: &SaveStateArgs, + ) -> Result { + let counted = match &arguments.save_state_on { + Some(path) => Some((path.clone(), resolve_signal_path(simulation, top, path)?)), + None => None, + }; + let descending = |values: &[u64]| { + let mut values = values.to_vec(); + values.sort_unstable_by(|a, b| b.cmp(a)); + values.dedup(); + values + }; + let directory = arguments + .save_state_dir + .clone() + .unwrap_or_else(|| PathBuf::from(".")); + if !arguments.is_empty() { + std::fs::create_dir_all(&directory) + .map_err(|error| format!("cannot create {}: {error}", directory.display()))?; + } + Ok(Self { + counted, + cycles: descending(&arguments.save_state_at), + count: 0, + high: false, + times: descending(&arguments.save_state_at_time), + directory, + }) + } + + fn level( + simulation: &mut celox::Simulation, + signal: celox::SignalRef, + ) -> bool { + let (value, mask) = simulation.get_four_state(signal); + value == 1u8.into() && mask == 0u8.into() + } + + fn start(&mut self, simulation: &mut celox::Simulation) { + if let Some((_, signal)) = self.counted { + self.high = Self::level(simulation, signal); + } + } + + /// Save the times before `next`, the time the next step runs. + fn before( + &mut self, + simulation: &mut celox::Simulation, + next: u64, + ) -> Result<(), String> { + while let Some(&time) = self.times.last() + && time < next + { + self.times.pop(); + self.save(simulation, format!("time-{time}.state"))?; + } + Ok(()) + } + + fn after_step( + &mut self, + simulation: &mut celox::Simulation, + ) -> Result<(), String> { + let Some((name, signal)) = &self.counted else { + return Ok(()); + }; + let (name, signal) = (name.clone(), *signal); + let high = Self::level(simulation, signal); + let rose = high && !self.high; + self.high = high; + if rose { + self.count += 1; + if self.cycles.last() == Some(&self.count) { + self.cycles.pop(); + self.save(simulation, format!("{name}-{}.state", self.count))?; + } + } + Ok(()) + } + + /// After the run: nothing changes any more, so the state at a later + /// time is the final one; a cycle not reached is an error. + fn finish( + &mut self, + simulation: &mut celox::Simulation, + ) -> Result<(), String> { + self.before(simulation, u64::MAX)?; + if let Some(cycle) = self.cycles.last() { + let (name, _) = self.counted.as_ref().expect("cycles count a signal"); + return Err(format!( + "the run ended after {} cycles of {name}, before cycle {cycle} of --save-state-at", + self.count + )); + } + Ok(()) + } + + fn save( + &self, + simulation: &mut celox::Simulation, + name: String, + ) -> Result<(), String> { + let path = self.directory.join(name); + let state = simulation + .save_state() + .map_err(|error| format!("cannot save {}: {error}", path.display()))?; + let mut bytes = Vec::new(); + state + .write_to(&mut bytes) + .and_then(|()| std::fs::write(&path, bytes)) + .map_err(|error| format!("cannot write {}: {error}", path.display())) + } +} + +/// Resolve `path`, a hierarchical signal name such as `tb.cpu.clk` or +/// `cpu[1].clk`, which may start with the top module's name. +#[cfg(feature = "systemverilog")] +fn resolve_signal_path( + simulation: &celox::Simulation, + top: &str, + path: &str, +) -> Result { + let mut segments: Vec<&str> = path.split('.').collect(); + if segments.len() > 1 && segments[0] == top { + segments.remove(0); + } + let var = segments.pop().unwrap_or_default(); + let instances = segments + .iter() + .map( + |segment| match segment.strip_suffix(']').and_then(|s| s.split_once('[')) { + Some((name, index)) => index + .parse() + .map(|index| (name, index)) + .map_err(|_| format!("invalid instance index in `{path}`")), + None => Ok((*segment, 0)), + }, + ) + .collect::, _>>()?; + simulation + .try_child_signal(&instances, var) + .map_err(|error| format!("--save-state-on {path}: {error}")) +} + #[cfg(feature = "systemverilog")] fn drain_sv_output( simulation: &mut celox::Simulation, @@ -924,7 +1146,7 @@ mod tests { .unwrap(); simulation.add_clock("clk", 2, 1); let mut output = Vec::new(); - let error = simulate_sv(simulation, 3, &mut output).unwrap_err(); + let error = simulate_sv(simulation, 3, StateSaves::default(), &mut output).unwrap_err(); assert!(error.contains("exceeded --max-steps 3")); assert!(String::from_utf8(output).unwrap().contains("tick")); } @@ -943,7 +1165,7 @@ mod tests { .build() .unwrap(); let mut output = Vec::new(); - let result = simulate_sv(simulation, 10, &mut output); + let result = simulate_sv(simulation, 10, StateSaves::default(), &mut output); (result, String::from_utf8(output).unwrap()) }; let (result, output) = run("$info"); diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index 9947d41f80c..1c7365115b8 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -636,3 +636,77 @@ fn interface_array_query_policy_flows_through_manifest_and_cli_overrides() { } } } + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_saves_state_files_at_cycles_and_times() { + let source = "`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] count = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 8'd1; + initial #100 $finish; +endmodule +"; + let states = tempfile::tempdir().unwrap(); + let directory = states.path().to_str().unwrap(); + for backend in ["tiered", "interpreter", "native"] { + let output = run( + &[("top.sv", source)], + &[ + "--backend", + backend, + "--save-state-on", + "Top.clk", + "--save-state-at", + "2,5", + "--save-state-at-time", + "32", + "--save-state-dir", + directory, + ], + ); + assert!(output.status.success(), "{backend}: {output:?}"); + // Cycle N is the N-th rising edge of clk, at 10N - 5; the file holds + // the state after that time step, its nonblocking updates included. + for (file, time, count) in [ + ("Top.clk-2.state", 15, 2), + ("Top.clk-5.state", 45, 5), + // Time 32 has no activity; the state is that after time 30. + ("time-32.state", 30, 3), + ] { + let dump = std::process::Command::new(env!("CARGO_BIN_EXE_celox")) + .args(["state", "dump"]) + .arg(states.path().join(file)) + .output() + .unwrap(); + assert!(dump.status.success(), "{backend} {file}: {dump:?}"); + let text = String::from_utf8_lossy(&dump.stdout); + assert!( + text.contains(&format!("count[8] = {count:02x}\n")), + "{backend} {file}:\n{text}" + ); + assert!( + text.contains(&format!("time: {time}\n")), + "{backend} {file}:\n{text}" + ); + } + } + let output = run( + &[("top.sv", source)], + &[ + "--save-state-on", + "clk", + "--save-state-at", + "50", + "--save-state-dir", + directory, + ], + ); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("before cycle 50"), + "{output:?}" + ); +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 2bcd39299f2..967e6da71b4 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1103,6 +1103,16 @@ impl Simulation { self.simulator.child_signal(instance_path, var) } + /// Like [`Self::child_signal`], returning an error for a path that does + /// not resolve. + pub fn try_child_signal( + &self, + instance_path: &[(&str, usize)], + var: &str, + ) -> Result { + self.simulator.try_child_signal(instance_path, var) + } + /// Registers a clock signal by event ID. /// /// Invalid IDs and IDs that do not resolve to events are ignored for diff --git a/docs/guide/checkpoints.md b/docs/guide/checkpoints.md index e1b762c5d19..36a22fb532d 100644 --- a/docs/guide/checkpoints.md +++ b/docs/guide/checkpoints.md @@ -141,6 +141,10 @@ celox state dump before_failure.state celox state diff native.state interpreter.state ``` +`celox run` saves state files at chosen cycles or times of a SystemVerilog run +with `--save-state-on`, `--save-state-at` and `--save-state-at-time` (see +[the command line](cocotb.md#save-state-files-during-a-systemverilog-run)). + `diff` exits with status 1 when the files differ. Both commands skip combinational signals unless you pass `--comb`. Dead store elimination at `O2` leaves unread combinational signals unwritten, so their saved values are diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index ba8bae593a9..713f6c42825 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -72,6 +72,26 @@ safe point while preserving pending events. For example: celox run test/Top.sv --top Top --backend tiered --threads 4 ``` +### Save state files during a SystemVerilog run + +To compare two runs or two simulators, `celox run` can save +[state files](checkpoints.md#state-files) for `celox state dump` and `celox state diff`: + +| Options | Purpose | +| --- | --- | +| `--save-state-on SIGNAL` | Count the cycles of `SIGNAL`, a hierarchical path such as `tb.clk` (the top module's name may be left out). A cycle is a time step at whose end the signal is 1 while it was not at the end of the previous time step. | +| `--save-state-at N[,M...]` | Save the state after cycles N, M, ... of `--save-state-on`, counted from 1, as `-.state`. The file is written right after that time step, with every region of the time done, so its nonblocking updates are included. | +| `--save-state-at-time T[,U...]` | Save the state after everything due at times up to T, before the run advances past T, as `time-.state`. T is in units of the design's global time precision. | +| `--save-state-dir DIR` | Write the files to `DIR` (default: the current directory). | + +A cycle that the run never reaches is an error. These options are available for +SystemVerilog testbenches on every backend. + +```sh +celox run c906.v --top tb --save-state-on tb.clk --save-state-at 1000,2000 --save-state-dir states +celox state diff states/tb.clk-1000.state other/tb.clk-1000.state +``` + For Veryl native testbenches it also provides: | Options | Purpose | diff --git a/docs/ja/guide/checkpoints.md b/docs/ja/guide/checkpoints.md index addac63cba6..3da2f5e7098 100644 --- a/docs/ja/guide/checkpoints.md +++ b/docs/ja/guide/checkpoints.md @@ -125,6 +125,8 @@ celox state dump before_failure.state celox state diff native.state interpreter.state ``` +SystemVerilog の実行中に、指定したサイクルや時刻で状態ファイルを保存するには `celox run` の `--save-state-on`、`--save-state-at`、`--save-state-at-time` を使います([コマンドライン](cocotb.md)を参照)。 + `diff` は、ファイルに差があると終了コード 1 で終わります。 どちらのコマンドも、`--comb` を付けない限り組み合わせ回路の信号を表示しません。 `O2` の dead store elimination は、どこからも読まれない組み合わせ回路の信号を書かないので、その信号の保存値は古いままになっているためです。 diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index c06aefbe3c4..b2318bdef50 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -66,6 +66,20 @@ celox run test/Top.veryl --top Top --four-state celox run --project /path/to/veryl-project --top smoke --report --unlimited ``` +SVのtestbenchでは、実行中に[状態ファイル](checkpoints.md#状態ファイル)を保存して +`celox state dump`/`celox state diff`で2つの実行やシミュレーターを比較できます(全バックエンド対応)。 +`--save-state-on SIGNAL`で数える信号(`tb.clk`のような階層パス、トップモジュール名は省略可)を指定し、 +`--save-state-at N[,M...]`で保存するサイクル(1から数える)を指定します。 +サイクルは、終了時に信号が1で、直前のタイムステップの終了時には1でなかったタイムステップです。 +ファイル`-.state`はそのタイムステップの全リージョンが終わった直後に書くので、ノンブロッキング代入の更新も含みます。 +`--save-state-at-time T[,U...]`は時刻T以前の処理をすべて終え、Tを越えて進む前の状態を`time-.state`に保存します(単位はデザインのグローバル時間精度)。 +`--save-state-dir DIR`で出力先を指定します(既定はカレントディレクトリ)。 +実行が指定のサイクルに達しなかった場合はエラーです。 + +```sh +celox run c906.v --top tb --save-state-on tb.clk --save-state-at 1000,2000 --save-state-dir states +``` + Veryl用の`--report`は設定・コンパイル時間・実行時間・tiered昇格統計・結果を 機械可読な`CELOX_*`レコードとして標準出力に出します。通常実行では出しません。 Heliodorベンチも専用Celoxバイナリではなく、このCLIを呼びます。