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}"); + } + } } 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/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 269dbefb940..488c9fc9c90 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); @@ -3522,3 +3583,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()); + } +} 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 4ad09f74189..b3059ada2d8 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 2a9c1edfbb2..3396d7837ff 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`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 |