From be0775b9a7e7ddea8c970ece13ae192f22650df4 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 14:12:03 +0900 Subject: [PATCH 1/4] fix(sv): join based-literal digits supplied by a macro A based literal whose digits come from a macro, such as `5'd`TDT_DM_PB_SIZE` in XuanTie C906, left the digits in separate tokens after expansion and was rejected as an invalid numeric literal. IEEE 1800-2023 5.7.1 lets the value follow the base format after optional white space. When a literal ends at its base, the parser now appends the following digit tokens; a macro body such as `0f` lexes as `0` and `f`, so tokens adjacent in their spelling are joined too. Validation: - celox-sv-syntax: 121 tests passed, with new cases for decimal, hex, signed binary and split hex digit macros and the compact expression value; Clippy with -D warnings and formatting passed. - No sv-tests case at the pinned revision has a base format followed by a macro, so conformance expectations are unchanged. Change-Id: I36ee2d3897db10b757989f5a565ba6e6b2a792a2 --- .../celox-sv-syntax/src/parser/expressions.rs | 38 +++++++++++++++++++ crates/celox-sv-syntax/src/parser/tests.rs | 16 ++++++++ 2 files changed, 54 insertions(+) diff --git a/crates/celox-sv-syntax/src/parser/expressions.rs b/crates/celox-sv-syntax/src/parser/expressions.rs index f9b967a3034..5c0dce906c0 100644 --- a/crates/celox-sv-syntax/src/parser/expressions.rs +++ b/crates/celox-sv-syntax/src/parser/expressions.rs @@ -671,6 +671,33 @@ impl Parser<'_> { self.at += 1; } } + // A macro can supply the digits of a based literal + // (`5'd`WIDTH`), leaving them in separate tokens; a + // body such as `0f` lexes as `0` and `f`, adjacent + // in their spelling. + if let ExprKind::Literal(value) = &mut kind + && numeric + && based_without_digits(value) + { + let mut previous: Option = None; + while let Some(next) = self.token() + && matches!( + next.kind, + TokenKind::Number | TokenKind::Identifier + ) + && next.text.bytes().all(|b| { + b.is_ascii_alphanumeric() || matches!(b, b'_' | b'?') + }) + && previous.is_none_or(|span| { + span.file == next.origin.spelling.file + && span.end == next.origin.spelling.start + }) + { + value.push_str(&next.text); + previous = Some(next.origin.spelling); + self.at += 1; + } + } if numeric && matches!(&kind, ExprKind::Literal(value) if !super::numbers::literal(value)) { @@ -1591,6 +1618,17 @@ pub(super) fn builtin(word: &str) -> bool { ) } +/// A sized or unsized based literal spelled up to its base, such as `5'd`. +fn based_without_digits(value: &str) -> bool { + let based = value + .trim_start_matches(|c: char| c.is_ascii_digit() || c == '_' || c.is_ascii_whitespace()); + let Some(base) = based.strip_prefix('\'') else { + return false; + }; + let base = base.strip_prefix(['s', 'S']).unwrap_or(base); + matches!(base, "b" | "B" | "o" | "O" | "d" | "D" | "h" | "H") +} + fn constant_dimension_operands(dimension: &Dimension, pending: &mut Vec) { match dimension.kind { DimensionKind::Index(value) => pending.push(value), diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index d66393e16f5..b71b04b93dc 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2245,6 +2245,16 @@ fn numeric_literal_grammar_keeps_integer_real_time_and_macro_base_spellings() { parse(&format!("module M #(parameter P={literal}); endmodule")); } parse("`define BASE 'h ff\nmodule M #(parameter P=8 `BASE); endmodule"); + for (definitions, literal) in [ + ("`define W 4", "5'd`W"), + ("`define V ff", "8'h`V"), + ("`define V 1x", "'sb`V"), + ("`define V 0f", "8'h`V"), + ] { + parse(&format!( + "{definitions}\nmodule M #(parameter P={literal}); endmodule" + )); + } } #[test] @@ -2699,6 +2709,12 @@ fn resetall_is_only_legal_outside_design_elements() { #[test] fn based_literal_expression_values_are_compact_without_losing_source_tokens() { + let native = parse("`define W 4\nmodule M; initial x=5'd`W; endmodule"); + assert!( + native.expressions.iter().any( + |expression| matches!(&expression.kind, ExprKind::Literal(text) if text == "5'd4") + ) + ); for (authored, value) in [("'h x", "'hx"), ("8'd 6", "8'd6"), ("4 'h f", "4'hf")] { let source = format!("module M; initial x={authored}; endmodule"); let native = parse(&source); From 491b133e81869ff294f5f4130db65e693d85b380 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 11:53:29 +0900 Subject: [PATCH 2/4] refactor(runtime): generate the edges of derived clock domains as SIR A derived-edge generator emits one edge of an event's signal as SIR, with the rules of DerivedTickPlan: gated clocks judged from their gate programs at the signal's old and new level and fired with the event's domain (one at a time first when they are independent), a settle, then cascade rounds that fire every state-derived or gated domain whose clock moved to its active edge, each at most once, until none does. One fire section serves the edge and the rounds; the mask of domains to fire and those fired so far are its block parameters. It covers two-state plans whose gated clocks all have gate programs. Nothing runs it yet: its tests attach a unit per edge case and compare each edge with the Rust plan walk on gated, inverted, falling-edge, divided and commit-enabled clocks and independent gated domains. Change-Id: If25bbf2ad20810c16ad37ad44998d8059c25be02 --- crates/celox/src/derived_edge.rs | 934 ++++++++++++++++++++++++++ crates/celox/src/lib.rs | 4 + crates/celox/src/simulator.rs | 6 + crates/celox/src/simulator/builder.rs | 20 + 4 files changed, 964 insertions(+) create mode 100644 crates/celox/src/derived_edge.rs diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs new file mode 100644 index 00000000000..2debba1c98c --- /dev/null +++ b/crates/celox/src/derived_edge.rs @@ -0,0 +1,934 @@ +//! Derived clock domains of an event edge as SIR. +//! +//! An edge of an event's signal runs the event's own domain and the domains +//! of the clocks derived from it, with the rules of `celox_runtime`'s +//! `DerivedTickPlan`: clocks computed combinationally from the signal +//! (`clk & en`, `~clk`) are judged from their gate programs at the signal's +//! old and new level and evaluate together with the event's domain; after +//! the commit and a settle, the domains whose clocks moved to their active +//! edge run together, in rounds, until none does, each at most once. +//! +//! [`EdgePlan`] is that plan over the program's units, and +//! [`EdgePlan::emit`] emits one edge as SIR, so that a host can run it +//! without walking the plan in Rust. It covers the plans the Rust walk runs +//! without settling for gates: two-state designs whose gated clocks all have +//! gate programs. + +use celox_design::{DomainKind, GateOp, STABLE_REGION, schedule::ScheduleModel}; +use celox_sir::{BinaryOp, BlockId, SIRBuilder, SIRTerminator, SIRValue, UnaryOp}; + +use crate::ir::{ + AbsoluteAddr, ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, SIRInstruction, + SIROffset, +}; + +type Unit = ExecutionUnit; +type Builder = SIRBuilder; + +/// Width of the values a gate program computes with. +const GATE_WIDTH: usize = 64; + +/// The deepest stack a gate program may use, as the Rust walk allows. +const GATE_STACK: usize = 16; + +/// The most domains one edge can fire: one bit each in a fire mask. +const MAX_ENTRIES: usize = 64; + +/// The units of one event domain. +#[derive(Clone, Debug)] +pub(crate) struct DomainUnits { + eval_apply: Vec, + /// Evaluation without commit; without it, the domain evaluates and + /// commits at once when it fires with others, as the Rust walk does. + eval_only: Option>, + apply: Option>, +} + +impl DomainUnits { + fn of(program: &LaidOutProgram, address: AbsoluteAddr) -> Self { + let sir = &program.sir; + Self { + eval_apply: sir + .eval_apply_ffs + .get(&address) + .cloned() + .unwrap_or_default(), + eval_only: sir.eval_only_ffs.get(&address).cloned(), + apply: sir.apply_ffs.get(&address).cloned(), + } + } +} + +/// A clock whose edges an edge of the event can cause. +#[derive(Clone, Debug)] +struct Derived { + signal: AbsoluteAddr, + width: usize, + kind: Option, + units: DomainUnits, +} + +/// A clock computed combinationally from the event's signal. +#[derive(Clone, Debug)] +struct Gated { + derived: Derived, + gate: Vec>, +} + +/// The derived domains an edge of one event runs. +#[derive(Clone, Debug)] +pub(crate) struct EdgePlan { + /// The event's own domain. + source: DomainUnits, + /// Domains clocked from state the event's domain writes. + domains: Vec, + /// Clocks computed combinationally from the event's signal. + gated: Vec, + /// The gated domains read and write no state the event's domain writes, + /// nor one another's: at the edge they run first, one at a time. + independent: bool, +} + +impl EdgePlan { + /// The plan of the canonical event `event`: `Ok(None)` when no clock + /// derives from it, an error when the plan is one this module does not + /// emit. + pub(crate) fn new( + program: &LaidOutProgram, + model: &ScheduleModel, + event: AbsoluteAddr, + ) -> Result, &'static str> { + let events = &model.events; + let domains = events + .derived_events + .get(&event) + .map_or(&[][..], Vec::as_slice); + let gated = events + .combinational_derived + .get(&event) + .map_or(&[][..], Vec::as_slice); + if domains.is_empty() && gated.is_empty() { + return Ok(None); + } + let layout = program.layout(); + if layout.four_state { + return Err("the design is four-state"); + } + if domains.len() + gated.len() + 1 > MAX_ENTRIES { + return Err("an edge reaches too many derived domains"); + } + // A derived clock without a domain of its own is left out, as the + // Rust walk leaves out a clock without an event. + let derived = |address: AbsoluteAddr| -> Result, &'static str> { + if !program.sir.eval_apply_ffs.contains_key(&address) { + return Ok(None); + } + Ok(Some(Derived { + signal: address, + width: *layout + .widths + .get(&address) + .ok_or("a derived clock has no storage")?, + kind: model.kind(&address), + units: DomainUnits::of(program, address), + })) + }; + let loadable = |address: &AbsoluteAddr, lsb: u32, width: u32| { + layout + .widths + .get(address) + .is_some_and(|&stored| stored <= GATE_WIDTH && (lsb + width) as usize <= stored) + && !layout.unpacked_arrays.contains_key(address) + }; + let mut gated_domains = Vec::with_capacity(gated.len()); + for clock in gated { + let Some(derived) = derived(clock.clock)? else { + continue; + }; + let gate = clock + .gate + .clone() + .ok_or("a gated clock has no gate program")?; + if !gate_fits(&gate, loadable) { + return Err("a gated clock has no gate program"); + } + gated_domains.push(Gated { derived, gate }); + } + let mut state_domains = Vec::with_capacity(domains.len()); + for &address in domains { + if let Some(derived) = derived(address)? { + state_domains.push(derived); + } + } + if state_domains.is_empty() && gated_domains.is_empty() { + return Ok(None); + } + Ok(Some(Self { + source: DomainUnits::of(program, event), + domains: state_domains, + gated: gated_domains, + independent: events.independent_derived.contains(&event), + })) + } + + /// The entries of a fire mask: the event's domain, then the + /// state-derived domains, then the gated ones. + fn entries(&self) -> impl Iterator + '_ { + std::iter::once(&self.source) + .chain(self.domains.iter().map(|domain| &domain.units)) + .chain(self.gated.iter().map(|gated| &gated.derived.units)) + } + + fn gated_bit(&self, index: usize) -> usize { + 1 + self.domains.len() + index + } + + /// Emit one edge of the event's signal, which has already moved from + /// level `from` to `to` (one-bit registers). `fires` says whether the + /// event's own domain sees its active edge, `settle` whether + /// combinational logic must settle before the domains evaluate. The code + /// continues at `settled` after the domains ran and logic settled, and + /// at `unsettled` when nothing ran (no gated clock and no own edge). + #[allow(clippy::too_many_arguments)] + pub(crate) fn emit( + &self, + b: &mut Builder, + comb: &[Unit], + from: RegisterId, + to: RegisterId, + fires: RegisterId, + settle: RegisterId, + settled: BlockId, + unsettled: BlockId, + ) { + let mut e = Emitter { + b, + after: Vec::new(), + }; + // The state-derived clocks' levels before the edge, the baseline of + // their edges for the whole phase. + let was: Vec = self + .domains + .iter() + .map(|domain| e.level(domain.signal, domain.width)) + .collect(); + // The fire section's parameters: the domains to fire, those fired so + // far, whether to settle first, and whether the gated domains run + // first one at a time (`fire_with_gated`). + let mask = e.b.alloc_bit(MAX_ENTRIES, false); + let fired = e.b.alloc_bit(MAX_ENTRIES, false); + let settle_first = e.b.alloc_bit(1, false); + let alone = e.b.alloc_bit(1, false); + let fire = e.b.new_block_with(vec![mask, fired, settle_first, alone]); + let source = e.bit(fires, 0); + if self.gated.is_empty() { + let zero = e.constant(0, MAX_ENTRIES); + let none = e.binary(1, source, BinaryOp::Eq, zero); + let no = e.constant(0, 1); + let start = e.b.new_block(); + e.b.seal_block(SIRTerminator::Branch { + cond: none, + true_block: (unsettled, Vec::new()), + false_block: (start, Vec::new()), + }); + e.b.switch_to_block(start); + e.b.seal_block(SIRTerminator::Jump(fire, vec![source, zero, settle, no])); + } else { + // The edge: each gated clock judged from its gate program with + // the signal at its old and new level. + let mut ready = source; + let mut gated_fired = e.constant(0, MAX_ENTRIES); + let mut after = Vec::with_capacity(self.gated.len()); + for (index, gated) in self.gated.iter().enumerate() { + let before = e.gate(&gated.gate, from); + let level = e.gate(&gated.gate, to); + let edge = e.edge(gated.derived.kind, before, level); + let bit = e.bit(edge, self.gated_bit(index)); + ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); + gated_fired = e.binary(MAX_ENTRIES, gated_fired, BinaryOp::Or, bit); + after.push(level); + } + let alone = e.constant(u64::from(self.independent), 1); + e.b.seal_block(SIRTerminator::Jump( + fire, + vec![ready, gated_fired, settle, alone], + )); + e.after = after; + } + + // The fire section, shared by the edge and the rounds. + e.b.switch_to_block(fire); + let fire_end = e.b.new_block(); + e.settle_if(settle_first, comb); + let zero = e.constant(0, MAX_ENTRIES); + let gated_mask = self + .gated + .iter() + .enumerate() + .fold(0u64, |mask, (index, _)| mask | 1 << self.gated_bit(index)); + let gated_bits = e.constant(gated_mask, MAX_ENTRIES); + let gated_ready = e.binary(MAX_ENTRIES, mask, BinaryOp::And, gated_bits); + let any_gated = e.binary(1, gated_ready, BinaryOp::Ne, zero); + let in_turn = e.binary(1, alone, BinaryOp::And, any_gated); + let one_at_a_time = e.b.new_block(); + let together = e.b.new_block(); + e.b.seal_block(SIRTerminator::Branch { + cond: in_turn, + true_block: (one_at_a_time, Vec::new()), + false_block: (together, Vec::new()), + }); + + // Independent gated domains, then the event's own, each fused. + e.b.switch_to_block(one_at_a_time); + let order: Vec = (0..self.gated.len()) + .map(|index| self.gated_bit(index)) + .chain(std::iter::once(0)) + .collect(); + for entry in order { + let units = self.entries().nth(entry).expect("an entry of the mask"); + e.if_bit(mask, entry, |e| e.inline_all(&units.eval_apply)); + } + e.b.seal_block(SIRTerminator::Jump(fire_end, Vec::new())); + + // The domains together: one evaluates and commits at once, several + // evaluate, then commit, in entry order. + e.b.switch_to_block(together); + let one = e.constant(1, MAX_ENTRIES); + let lower = e.binary(MAX_ENTRIES, mask, BinaryOp::Sub, one); + let others = e.binary(MAX_ENTRIES, mask, BinaryOp::And, lower); + let single = e.binary(1, others, BinaryOp::Eq, zero); + let one_domain = e.b.new_block(); + let several = e.b.new_block(); + e.b.seal_block(SIRTerminator::Branch { + cond: single, + true_block: (one_domain, Vec::new()), + false_block: (several, Vec::new()), + }); + e.b.switch_to_block(one_domain); + for (entry, units) in self.entries().enumerate() { + e.if_bit(mask, entry, |e| e.inline_all(&units.eval_apply)); + } + e.b.seal_block(SIRTerminator::Jump(fire_end, Vec::new())); + e.b.switch_to_block(several); + for (entry, units) in self.entries().enumerate() { + e.if_bit(mask, entry, |e| match &units.eval_only { + Some(eval_only) => e.inline_all(eval_only), + None => e.inline_all(&units.eval_apply), + }); + } + for (entry, units) in self.entries().enumerate() { + if let Some(apply) = &units.apply { + e.if_bit(mask, entry, |e| e.inline_all(apply)); + } + } + e.b.seal_block(SIRTerminator::Jump(fire_end, Vec::new())); + + // Combinational logic settles after every fire; then a round: the + // domains not fired yet whose clocks moved to their active edge. + e.b.switch_to_block(fire_end); + e.inline_all(comb); + let mut ready = e.constant(0, MAX_ENTRIES); + for (index, domain) in self.domains.iter().enumerate() { + let is = e.level(domain.signal, domain.width); + let edge = e.edge(domain.kind, was[index], is); + let bit = e.bit(edge, 1 + index); + ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); + } + let after = std::mem::take(&mut e.after); + for (index, gated) in self.gated.iter().enumerate() { + let is = e.gate(&gated.gate, to); + let edge = e.edge(gated.derived.kind, after[index], is); + let bit = e.bit(edge, self.gated_bit(index)); + ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); + } + let all = e.constant(u64::MAX, MAX_ENTRIES); + let unfired = e.binary(MAX_ENTRIES, fired, BinaryOp::Xor, all); + let ready = e.binary(MAX_ENTRIES, ready, BinaryOp::And, unfired); + let quiet = e.binary(1, ready, BinaryOp::Eq, zero); + let round = e.b.new_block(); + e.b.seal_block(SIRTerminator::Branch { + cond: quiet, + true_block: (settled, Vec::new()), + false_block: (round, Vec::new()), + }); + e.b.switch_to_block(round); + let now_fired = e.binary(MAX_ENTRIES, fired, BinaryOp::Or, ready); + let no = e.constant(0, 1); + e.b.seal_block(SIRTerminator::Jump(fire, vec![ready, now_fired, no, no])); + } +} + +/// Whether `gate` is a program the emitter runs: its loads read state of at +/// most 64 bits, and its stack stays within the Rust walk's bound and ends +/// with one value. +fn gate_fits( + gate: &[GateOp], + loadable: impl Fn(&AbsoluteAddr, u32, u32) -> bool, +) -> bool { + let mut depth = 0usize; + for op in gate { + let pops = match op { + GateOp::Load { + address, + lsb, + width, + } => { + if !loadable(address, *lsb, *width) { + return false; + } + 0 + } + GateOp::Source | GateOp::Const(_) => 0, + GateOp::Not { .. } + | GateOp::LogicNot + | GateOp::ReduceAnd { .. } + | GateOp::ReduceOr + | GateOp::ReduceXor + | GateOp::Slice { .. } => 1, + GateOp::And + | GateOp::Or + | GateOp::Xor + | GateOp::Eq + | GateOp::Ne + | GateOp::LogicAnd + | GateOp::LogicOr => 2, + GateOp::Mux => 3, + }; + let Some(next) = depth.checked_sub(pops) else { + return false; + }; + depth = next + 1; + if depth > GATE_STACK { + return false; + } + } + depth == 1 +} + +fn mask(width: u32) -> u64 { + if width >= 64 { + u64::MAX + } else { + (1u64 << width) - 1 + } +} + +struct Emitter<'b> { + b: &'b mut Builder, + /// The gated clocks' levels just after the edge, the baseline of their + /// further edges in the rounds. + after: Vec, +} + +impl Emitter<'_> { + fn constant(&mut self, value: u64, width: usize) -> RegisterId { + let register = self.b.alloc_bit(width, false); + self.b + .emit(SIRInstruction::Imm(register, SIRValue::new(value))); + register + } + + fn binary( + &mut self, + width: usize, + lhs: RegisterId, + op: BinaryOp, + rhs: RegisterId, + ) -> RegisterId { + let register = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Binary(register, lhs, op, rhs)); + register + } + + fn unary(&mut self, width: usize, op: UnaryOp, value: RegisterId) -> RegisterId { + let register = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Unary(register, op, value)); + register + } + + /// `value` as a gate value, zero-extended. + fn widen(&mut self, value: RegisterId) -> RegisterId { + self.unary(GATE_WIDTH, UnaryOp::Ident, value) + } + + fn load(&mut self, address: AbsoluteAddr, lsb: usize, width: usize) -> RegisterId { + let register = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Load( + register, + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address), + SIROffset::Static(lsb), + width, + )); + register + } + + /// The edge level of a signal as the runtime reads it: whether its low + /// byte, within its width, is not zero. + fn level(&mut self, signal: AbsoluteAddr, width: usize) -> RegisterId { + let width = width.min(8); + let value = self.load(signal, 0, width); + let zero = self.constant(0, width); + self.binary(1, value, BinaryOp::Ne, zero) + } + + /// Whether a change of a domain's clock from `was` to `is` (one-bit + /// levels) is its active edge, as `settled_edge` judges two-state levels. + fn edge(&mut self, kind: Option, was: RegisterId, is: RegisterId) -> RegisterId { + let changed = self.binary(1, was, BinaryOp::Ne, is); + match kind { + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + self.binary(1, changed, BinaryOp::And, is) + } + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + self.binary(1, changed, BinaryOp::And, was) + } + _ => changed, + } + } + + /// Bit `index` of a fire mask, set when `condition` holds. + fn bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { + let set = self.constant(1 << index, MAX_ENTRIES); + let unset = self.constant(0, MAX_ENTRIES); + let bit = self.b.alloc_bit(MAX_ENTRIES, false); + self.b.emit(SIRInstruction::Mux(bit, condition, set, unset)); + bit + } + + /// The level of a gated clock from its program, with the event's signal + /// at `source` (a one-bit register). + fn gate(&mut self, gate: &[GateOp], source: RegisterId) -> RegisterId { + let mut stack: Vec = Vec::with_capacity(GATE_STACK); + for op in gate { + let value = match *op { + GateOp::Source => self.widen(source), + GateOp::Load { + address, + lsb, + width, + } => { + let value = self.load(address, lsb as usize, width as usize); + self.widen(value) + } + GateOp::Const(value) => self.constant(value, GATE_WIDTH), + GateOp::Not { width } => { + let value = stack.pop().expect("checked by gate_fits"); + let mask = self.constant(mask(width), GATE_WIDTH); + self.binary(GATE_WIDTH, value, BinaryOp::Xor, mask) + } + GateOp::LogicNot => { + let value = stack.pop().expect("checked by gate_fits"); + let zero = self.constant(0, GATE_WIDTH); + let is = self.binary(1, value, BinaryOp::Eq, zero); + self.widen(is) + } + GateOp::ReduceAnd { width } => { + let value = stack.pop().expect("checked by gate_fits"); + let mask = self.constant(mask(width), GATE_WIDTH); + let bits = self.binary(GATE_WIDTH, value, BinaryOp::And, mask); + let is = self.binary(1, bits, BinaryOp::Eq, mask); + self.widen(is) + } + GateOp::ReduceOr => { + let value = stack.pop().expect("checked by gate_fits"); + let zero = self.constant(0, GATE_WIDTH); + let is = self.binary(1, value, BinaryOp::Ne, zero); + self.widen(is) + } + GateOp::ReduceXor => { + let value = stack.pop().expect("checked by gate_fits"); + let parity = self.unary(1, UnaryOp::Xor, value); + self.widen(parity) + } + GateOp::Slice { lsb, width } => { + let value = stack.pop().expect("checked by gate_fits"); + let shift = self.constant(u64::from(lsb), GATE_WIDTH); + let shifted = self.binary(GATE_WIDTH, value, BinaryOp::Shr, shift); + let mask = self.constant(mask(width), GATE_WIDTH); + self.binary(GATE_WIDTH, shifted, BinaryOp::And, mask) + } + GateOp::Mux => { + let otherwise = stack.pop().expect("checked by gate_fits"); + let then = stack.pop().expect("checked by gate_fits"); + let condition = stack.pop().expect("checked by gate_fits"); + let zero = self.constant(0, GATE_WIDTH); + let holds = self.binary(1, condition, BinaryOp::Ne, zero); + let value = self.b.alloc_bit(GATE_WIDTH, false); + self.b + .emit(SIRInstruction::Mux(value, holds, then, otherwise)); + value + } + GateOp::And + | GateOp::Or + | GateOp::Xor + | GateOp::Eq + | GateOp::Ne + | GateOp::LogicAnd + | GateOp::LogicOr => { + let rhs = stack.pop().expect("checked by gate_fits"); + let lhs = stack.pop().expect("checked by gate_fits"); + match *op { + GateOp::And => self.binary(GATE_WIDTH, lhs, BinaryOp::And, rhs), + GateOp::Or => self.binary(GATE_WIDTH, lhs, BinaryOp::Or, rhs), + GateOp::Xor => self.binary(GATE_WIDTH, lhs, BinaryOp::Xor, rhs), + GateOp::Eq => { + let is = self.binary(1, lhs, BinaryOp::Eq, rhs); + self.widen(is) + } + GateOp::Ne => { + let is = self.binary(1, lhs, BinaryOp::Ne, rhs); + self.widen(is) + } + GateOp::LogicAnd => { + let is = self.binary(1, lhs, BinaryOp::LogicAnd, rhs); + self.widen(is) + } + _ => { + let is = self.binary(1, lhs, BinaryOp::LogicOr, rhs); + self.widen(is) + } + } + } + }; + stack.push(value); + } + let value = stack.pop().expect("checked by gate_fits"); + let one = self.constant(1, GATE_WIDTH); + let low = self.binary(GATE_WIDTH, value, BinaryOp::And, one); + let zero = self.constant(0, GATE_WIDTH); + self.binary(1, low, BinaryOp::Ne, zero) + } + + fn inline_all(&mut self, units: &[Unit]) { + for unit in units { + self.b.inline_execution_unit(unit); + } + } + + /// Settle combinational logic when the one-bit `condition` holds. + fn settle_if(&mut self, condition: RegisterId, comb: &[Unit]) { + let settle = self.b.new_block(); + let next = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (settle, Vec::new()), + false_block: (next, Vec::new()), + }); + self.b.switch_to_block(settle); + self.inline_all(comb); + self.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + self.b.switch_to_block(next); + } + + /// Run `body` when bit `index` of `mask` is set. + fn if_bit(&mut self, mask: RegisterId, index: usize, body: impl FnOnce(&mut Self)) { + let selector = self.constant(1 << index, MAX_ENTRIES); + let selected = self.binary(MAX_ENTRIES, mask, BinaryOp::And, selector); + let zero = self.constant(0, MAX_ENTRIES); + let set = self.binary(1, selected, BinaryOp::Ne, zero); + let run = self.b.new_block(); + let next = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: set, + true_block: (run, Vec::new()), + false_block: (next, Vec::new()), + }); + self.b.switch_to_block(run); + body(self); + self.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + self.b.switch_to_block(next); + } +} + +impl EdgePlan { + /// A unit that runs one edge of the event whose signal its caller + /// already moved, rising or falling, with `settle` and `fires` fixed. + #[cfg(all(test, feature = "systemverilog"))] + fn unit(&self, comb: &[Unit], rising: bool, settle: bool, fires: bool) -> Unit { + let mut b = Builder::new(); + let constant = |b: &mut Builder, value: bool| { + let register = b.alloc_bit(1, false); + b.emit(SIRInstruction::Imm( + register, + SIRValue::new(u64::from(value)), + )); + register + }; + let from = constant(&mut b, !rising); + let to = constant(&mut b, rising); + let fires = constant(&mut b, fires); + let settle = constant(&mut b, settle); + let done = b.new_block(); + self.emit(&mut b, comb, from, to, fires, settle, done, done); + b.switch_to_block(done); + b.seal_block(SIRTerminator::Return); + let (blocks, register_map, _) = b.drain(); + Unit { + entry_block_id: BlockId(0), + blocks, + register_map, + } + } +} + +/// A generated edge unit and the edge it runs, for the tests. +#[cfg(all(test, feature = "systemverilog"))] +#[derive(Clone, Copy, Debug)] +pub(crate) struct TestEdgeUnit { + pub(crate) event: AbsoluteAddr, + pub(crate) rising: bool, + pub(crate) settle: bool, + pub(crate) fires: bool, + pub(crate) index: usize, +} + +#[cfg(all(test, feature = "systemverilog"))] +pub(crate) type TestEdgeUnits = std::sync::Arc>>; + +/// Append an edge unit of every event with a plan this module emits, for +/// each edge, settle and own-edge case, and record them in `sink`. +#[cfg(all(test, feature = "systemverilog"))] +pub(crate) fn attach_test_units(program: &mut LaidOutProgram, sink: &TestEdgeUnits) { + let model = ScheduleModel::derive(&program.design, &program.runtime.runtime_schema); + for event in crate::edge_plans::event_addresses(program) { + let Ok(Some(plan)) = EdgePlan::new(program, &model, event) else { + continue; + }; + for rising in [false, true] { + for settle in [false, true] { + for fires in [false, true] { + let unit = plan.unit(&program.sir.eval_comb, rising, settle, fires); + let index = program.sir.processes.len(); + program.sir.processes.push(unit); + sink.lock().expect("unpoisoned").push(TestEdgeUnit { + event, + rising, + settle, + fires, + index, + }); + } + } + } + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod tests { + use std::path::Path; + + use celox_runtime::{ + BackendExecutor, DerivedTickScratch, Edge, EdgeOutcome, run_edge, set_level, + }; + + use super::TestEdgeUnits; + use crate::{ + Simulator, + backend::{EventHandle, SimBackend}, + }; + + /// The design state: the stable region after its header. + fn state(backend: &B) -> Vec { + let (ptr, len) = backend.memory_as_ptr(); + let size = backend.layout().total_size; + assert!(size <= len); + // Safety: the backend exposes `len` readable bytes at `ptr`. + let memory = unsafe { std::slice::from_raw_parts(ptr, len) }; + memory[celox_state_layout::STATE_HEADER_SIZE..size].to_vec() + } + + /// Whether combinational logic is stale after an edge with `outcome`, + /// as `run_tick` keeps it. + fn stale(dirty: bool, outcome: EdgeOutcome) -> bool { + match outcome { + EdgeOutcome::Unchanged | EdgeOutcome::Stored => dirty, + EdgeOutcome::Moved => true, + EdgeOutcome::Settled => false, + } + } + + /// Run edges of `clk` and host writes of `en`, when the design has it, + /// through the Rust plan walk and through the generated units, and + /// compare the state after each. + fn agrees(source: &str) { + let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); + // The Cranelift backend runs extra units without an image to check. + let mut walked = build().build_cranelift().unwrap(); + let sink = TestEdgeUnits::default(); + let mut generated = build() + .derived_edge_units(sink.clone()) + .build_cranelift() + .unwrap(); + let units = sink.lock().unwrap().clone(); + assert!(!units.is_empty(), "no edge unit was generated"); + let clk = walked.event("clk"); + let address = walked.backend.id_to_addr_slice()[clk.id()]; + let plans = walked.derived_tick_plans(); + let plan = plans.get(clk.id()).and_then(Option::as_ref); + assert!(plan.is_some(), "clk has no derived plan"); + let gated = plan.is_some_and(|plan| plan.lever_signals().next().is_some()); + let info = walked.event_edge(clk); + let en = walked.try_signal("en").ok(); + let mut scratch = DerivedTickScratch::default(); + assert!( + state(&generated.backend) == state(&walked.backend), + "the simulators start in other states" + ); + let (mut walked_dirty, mut generated_dirty) = (false, false); + let edges = [ + Edge::Rising, + Edge::Falling, + Edge::Falling, + Edge::Rising, + Edge::Falling, + ]; + for step in 0..60usize { + if let Some(en) = en + && step % 7 < 2 + { + let value = u8::from(step % 3 != 0); + walked.backend.set(en, value); + generated.backend.set(en, value); + walked_dirty = true; + generated_dirty = true; + } + let edge = edges[step % edges.len()]; + let outcome = run_edge( + &mut BackendExecutor(&mut walked.backend), + plan, + info, + &mut scratch, + clk, + edge, + walked_dirty, + set_level, + ) + .unwrap(); + walked_dirty = stale(walked_dirty, outcome); + + let from = u8::from(generated.backend.get_as::(info.signal) & 1 != 0); + let outcome = if from == edge.level() { + EdgeOutcome::Unchanged + } else { + generated.backend.set(info.signal, edge.level()); + let fires = info.fires(Some(from != 0), edge); + let settle = generated_dirty || info.comb_read; + let unit = units + .iter() + .find(|unit| { + unit.event == address + && unit.rising == (edge == Edge::Rising) + && unit.settle == settle + && unit.fires == fires + }) + .expect("a unit for every case"); + generated.backend.run_process(unit.index).unwrap(); + if gated || fires { + EdgeOutcome::Settled + } else if info.comb_read { + EdgeOutcome::Moved + } else { + EdgeOutcome::Stored + } + }; + generated_dirty = stale(generated_dirty, outcome); + assert_eq!(generated_dirty, walked_dirty, "step {step}"); + let (left, right) = (state(&generated.backend), state(&walked.backend)); + if let Some(offset) = left.iter().zip(&right).position(|(a, b)| a != b) { + let offset = offset + celox_state_layout::STATE_HEADER_SIZE; + let name = walked + .named_signals() + .into_iter() + .find(|named| { + let start = named.signal.offset; + (start..start + named.signal.width.div_ceil(8)).contains(&offset) + }) + .map_or_else(|| "no named signal".to_string(), |named| named.name); + panic!( + "step {step} ({edge:?}): the generated edge left state byte {offset} ({name}) otherwise" + ); + } + } + } + + #[test] + fn gated_clocks_run_as_the_plan_walk() { + agrees( + "module Top(input logic clk, input logic en, output logic [7:0] q); + logic gclk; + logic [7:0] r = 0; + logic [7:0] g = 0; + assign gclk = clk & en; + always_ff @(posedge clk) r <= r + 8'd1; + always_ff @(posedge gclk) g <= g + r; + assign q = g; + endmodule", + ); + } + + #[test] + fn inverted_and_falling_gated_clocks_run_as_the_plan_walk() { + agrees( + "module Top(input logic clk, input logic en, output logic [7:0] q); + logic nclk; + logic gclk; + logic [7:0] r = 0; + logic [7:0] n = 0; + logic [7:0] g = 0; + assign nclk = ~clk; + assign gclk = clk & en; + always_ff @(posedge clk) r <= r + 8'd1; + always_ff @(posedge nclk) n <= n + r; + always_ff @(negedge gclk) g <= g ^ n; + assign q = n + g; + endmodule", + ); + } + + #[test] + fn dividers_run_as_the_plan_walk() { + agrees( + "module Top(input logic clk, output logic [7:0] q); + logic half = 0; + logic quarter = 0; + logic [7:0] h = 0; + logic [7:0] w = 0; + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) quarter <= ~quarter; + always_ff @(posedge half) h <= h + 8'd1; + always_ff @(posedge quarter) w <= w + h; + assign q = h + w; + endmodule", + ); + } + + #[test] + fn enables_the_commit_raises_run_as_the_plan_walk() { + agrees( + "module Top(input logic clk, output logic [7:0] q); + logic en = 0; + logic gclk; + logic [7:0] g = 0; + assign gclk = clk & en; + always_ff @(posedge clk) en <= ~en; + always_ff @(posedge gclk) g <= g + 8'd1; + assign q = g; + endmodule", + ); + } + + #[test] + fn independent_gated_domains_run_as_the_plan_walk() { + agrees( + "module Top(input logic clk, input logic en, input logic [7:0] d, output logic [7:0] q); + logic gclk; + logic [7:0] r = 0; + logic [7:0] g = 0; + assign gclk = clk & en; + always_ff @(posedge clk) r <= r + d; + always_ff @(posedge gclk) g <= g + 8'd3; + assign q = r ^ g; + endmodule", + ); + } +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index f8c7072b4f3..ae4fb81ffe3 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -19,6 +19,10 @@ pub use component::{ register_static_component_manifest, }; mod debug; +// Only its tests run the generator until a host does. +#[cfg(feature = "host-runtime")] +#[cfg_attr(not(all(test, feature = "systemverilog")), allow(dead_code))] +mod derived_edge; mod edge_plans; pub use edge_plans::{ EdgePlanDomain, EdgePlanEvent, EdgePlanSignal, EdgePlans, edge_plans, event_addresses, diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 4579bc5414e..2ce6b6afe92 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -2200,6 +2200,12 @@ mod host { Ok(()) } + /// The edge facts of `event`. + #[cfg(all(test, feature = "systemverilog"))] + pub(crate) fn event_edge(&self, event: B::Event) -> celox_runtime::EventEdge { + self.event_edges[event.id()] + } + /// Whether a period of `event`'s signal, a rise and a fall, runs /// domains only at its active edge: the event's own and those derived /// from it, while the inactive edge runs nothing. diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 0df87c12b46..68400436bc8 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1679,6 +1679,9 @@ mod host { /// When true, JIT-compiled functions emit trigger detection code for /// edge-based event discovery. Only needed by [`crate::Simulation`]. pub emit_triggers: bool, + /// Generated derived-edge units the tests run, recorded here. + #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + pub(crate) derived_edge_units: Option, /// Emit the additional combinational entries needed to reapply foreign /// force overrides between procedural store boundaries. pub native_force_support: bool, @@ -1924,6 +1927,8 @@ mod host { diagnostic_policy: Default::default(), sv_timescale: None, emit_triggers: false, + #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + derived_edge_units: None, native_force_support: false, signal_access: crate::SignalAccessOptions::default(), dead_store_policy: DeadStorePolicy::Off, @@ -2080,6 +2085,17 @@ mod host { self } + /// Append the generated derived-edge units of every event and record + /// them in `sink`. + #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + pub(crate) fn derived_edge_units( + mut self, + sink: crate::derived_edge::TestEdgeUnits, + ) -> Self { + self.options.derived_edge_units = Some(sink); + self + } + /// Set the ordered arguments queried by `$test$plusargs` and /// `$value$plusargs`. A leading `+` is optional on each argument. /// Queries currently require a timed procedural process, such as an @@ -2832,6 +2848,10 @@ mod host { { crate::scheduler::attach(&mut laid_out); } + #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] + if let Some(sink) = &self.options.derived_edge_units { + crate::derived_edge::attach_test_units(&mut laid_out, sink); + } // Link DPI-C imports before code generation, so a missing C // function fails the build early; the backends reuse the result. From ba12d6659609d1558b964393a44766d3f234e9ea Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 14:36:35 +0900 Subject: [PATCH 3/4] fix(sv): bind unpacked array values in module parameter arguments Taxi forwarded unpacked parameter elements to scalar child parameters, but the constant-binding path retained the array name after resolving the selection coordinates. Apply the existing immutable initializer and preserve the selected width, signedness and X/Z mask. Keep whole-array conditional arguments in the typed array binding path. Check both branch shapes, including the unselected branch, then select the array for a fully resolved integral predicate. Nested conditions are handled iteratively; ambiguous and nonintegral array predicates remain unsupported. Add six shared regressions covering generated numeric/string elements, signedness, bounds, package multidimensional arrays, 129-bit values, specializations, four-state conversion, and whole-array conditionals. Consumer tests reject runtime arguments and incompatible inactive branches. Validation after syncing master c3177672e7 (except where noted): - Full SystemVerilog suite: 4,425 passed, 20 existing ignored. Focused regressions: 32 passed across five backends and two rejection tests. - Analyzer: 796 passed, 3 existing ignored; frontend: 5 passed. Affected doctests passed. The shared suite passed all 30 tests before syncing master. - Affected analyzer/frontend libraries and tests and the SV consumer harness passed Clippy with -D warnings; formatting and diff checks passed. - All four retained original minimal reproductions now return FRONTEND_OK. - Slang 12 elaborates all six exact shared sources without semantic errors and confirms the expected child parameter values. - Verilator 5.052: three passed; one package-array compile error; one conditional-array ordering mismatch; one four-state case unsupported by the adapter. The ordering expectation follows IEEE 1800-2023 7.6 and agrees with Slang. Standalone lint reproduces the package-array rejection. - Icarus 13 rejects all six sources because unpacked array parameters are unsupported. No baseline or exclusions were changed to conceal failures. Before syncing with current master, replayed the same 25 Taxi configurations with original RTL/parameters, release frontend binaries, two workers, 120-second limits, two-state mode and the previous diagnostic settings. All 18 GT_TX_DIFFCTRL and seven STAT_PREFIX_STR blockers advance to undriven GT nets: 19 gt_rxdata and six gt_rxbyteisaligned. There are zero timeouts. These remain frontend errors; no complete FPGA-core configuration or upstream cocotb test pass is claimed. All 188 resolved upstream SV sources match the earlier hashes. Unrelated parameter arithmetic widening and wide scalar parameter array initializer limitations are retained as separate follow-up reproductions. Change-Id: Icd56e125c141961d6e79242b1fad03ccdb79b992 --- .../src/ast/constant_binding.rs | 15 +- crates/celox-sv-analyzer/src/ast/instances.rs | 86 ++++++++++- crates/celox-sv-analyzer/src/ast/selects.rs | 3 + .../src/sv/cases/hierarchy.vtest | 144 ++++++++++++++++++ .../frontends/systemverilog/hierarchy.rs | 73 +++++++++ 5 files changed, 315 insertions(+), 6 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 125bcc4a2ca..091cd7568a8 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -267,9 +267,20 @@ fn bind_in_context( }) { let value = indexed_expression(id, native, tree, query_dimensions)?; - values.push( + let value = if query_dimensions + .array_parameter_values + .contains_key(&name_key) + { + selects::indexed_expression_value( + &tree.state, + value, + query_dimensions, + ) + } else { expr_to_index_const(&tree.state, value, query_dimensions) - .ok_or_else(|| unsupported("parameter selection shape"))?, + }; + values.push( + value.ok_or_else(|| unsupported("parameter selection shape"))?, ); continue; } diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 2f10cf8e479..f1442ad9380 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -344,6 +344,60 @@ pub(crate) fn normalize_identifier(text: &str) -> String { } } +/// Keep whole-array conditional arguments out of the scalar constant path. +/// Traverse branch types iteratively, including branches a constant condition +/// does not select. Array sizes and integral element types must agree. +fn array_argument_shape( + root: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dims: &PackedDimensions, +) -> Option { + use celox_sv_syntax::{ExprId, ExprKind}; + enum Job { + Enter(ExprId), + Conditional, + } + let native = tree.declarations(); + let mut jobs = vec![Job::Enter(root)]; + let mut values = Vec::::new(); + while let Some(job) = jobs.pop() { + match job { + Job::Enter(id) => { + let id = expression_binding::ungroup(id, native); + if let ExprKind::Conditional { + then_expression, + else_expression, + .. + } = native.expression(id).kind + { + jobs.push(Job::Conditional); + jobs.push(Job::Enter(else_expression)); + jobs.push(Job::Enter(then_expression)); + } else { + values.push(array_compatibility::native_unpacked_shape( + id, native, dims, + )?); + } + } + Job::Conditional => { + let right = values.pop()?; + let left = values.pop()?; + let left_type = array_compatibility::unpacked_array_type(&tree.state, &left, dims)?; + let right_type = + array_compatibility::unpacked_array_type(&tree.state, &right, dims)?; + if left_type != right_type + || left.packed != right.packed + || left.members != right.members + { + return None; + } + values.push(left); + } + } + } + values.pop() +} + /// One `.name(expr)` binding: a `parameter type` when `expr` is a data type or /// the name of a type, a value otherwise. fn parameter_override( @@ -383,11 +437,35 @@ fn parameter_override( } pending.extend(parameters::skipped::children(id, declarations)); } - if let Some(shape) = - array_compatibility::native_unpacked_shape(native, declarations, packed_dimensions) - { + if let Some(shape) = array_argument_shape(native, syntax_tree, packed_dimensions) { + // Aggregate conditional expressions require equivalent branch types + // (11.4.11). A known condition selects a whole array before element + // binding; treating it as a packed mux would use the wrong X merge rule. + let mut selected = root; + while let ExprKind::Conditional { + condition, + then_expression, + else_expression, + } = declarations.expression(selected).kind + { + let condition = constant_binding::bind(condition, syntax_tree, packed_dimensions)? + .and_then(|value| { + eval_ast_const_expr(&syntax_tree.state, &value, &packed_dimensions.const_env) + }) + .ok_or_else(|| { + unsupported("nonconstant or ambiguous condition in array parameter argument") + })?; + selected = expression_binding::ungroup( + if condition != 0 { + then_expression + } else { + else_expression + }, + declarations, + ); + } let pattern = - bound_patterns::from_array_parameter(native, syntax_tree, packed_dimensions, &shape)?; + bound_patterns::from_array_parameter(selected, syntax_tree, packed_dimensions, &shape)?; let mut bound = ParameterOverride::new(name, None); bound.bound_pattern = Some(pattern); return Ok(bound); diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index 3945c4f45eb..c0c475936f4 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -1058,6 +1058,9 @@ fn substitute_indexed_parameter_values( expression: Expr, dimensions: &PackedDimensions, ) -> Expr { + // Unpacked parameter values use the declared array layout, while selections + // have already been translated to bit offsets in that layout. + let expression = substitute_expr_idents(expression, &dimensions.array_parameter_values); // Known values come from the current environment, which may include a // generate index shadowing a parameter. Supply expressions only for values // absent from that numeric environment, including X/Z parameters. diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 3644c826083..5fa3f849094 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1246,3 +1246,147 @@ (top Top) (assert_eq default_rows 0x34123412) (assert_eq explicit_rows 0xcdabcdab)) + + +; IEEE 1800-2023 6.20.2: an aggregate parameter member can be used in an expression. +(case array_parameter_elements_forward_generated_values + (source "array_parameter_elements.sv" #" + module Number #(parameter logic [4:0] P=0)(output wire [4:0] y); + assign y=P; + endmodule + module Text #(parameter logic [63:0] P="MAC")(output wire [63:0] y); + assign y=P; + endmodule + module Relay #(parameter logic [4:0] N[6:7]='{0,0}, + parameter logic [63:0] S[-2:-1]='{"D0","D1"}) + (output wire [9:0] numbers, output wire [127:0] strings); + for(genvar i=6;i<=7;i++) begin:g + Number #(.P(N[i])) n(.y(numbers[(i-6)*5 +: 5])); + Text #(.P(S[i-8])) s(.y(strings[(i-6)*64 +: 64])); + end + endmodule + module Top(output wire [9:0] numbers, output wire [127:0] strings); + localparam logic [4:0] N[2]='{5'h12,5'h1b}; + localparam logic [63:0] S[2]='{"A0","A1"}; + Relay #(.N(N),.S(S)) relay(.numbers(numbers),.strings(strings)); + endmodule + "#) + (top Top) (eval) + (assert_eq numbers 0x372) + (assert_eq strings 0x00000000000041310000000000004130)) + +(case array_parameter_elements_keep_signed_element_types + (source "signed_array_parameter_elements.sv" #" + module Sink #(parameter P=0, parameter logic signed [15:0] Q=0) + (output wire [31:0] value, width, output wire [15:0] sum, output wire negative); + assign value=P; + assign width=$bits(P); + assign sum=Q; + assign negative=P<0; + endmodule + module Top(output wire [31:0] value, width, output wire [15:0] sum, + output wire negative); + localparam logic signed [4:0] A[3:2]='{5'sd15,-5'sd2}; + Sink #(.P(A[2]),.Q(A[3]-5'sd1)) sink(.value(value),.width(width),.sum(sum),.negative(negative)); + endmodule + "#) + (top Top) (eval) + (assert_eq value 0xfffffffe) + (assert_eq width 5) + (assert_eq negative 1) + (assert_eq sum 14)) + +(case array_parameter_elements_select_package_multidimensional_values + (source "package_array_parameter_elements.sv" #" + package Values; + localparam logic [1:0][3:0] TABLE[3:2][-1:0]= + '{'{8'h12,8'h34},'{8'h56,8'h78}}; + endpackage + module Sink #(parameter P=0)(output wire [7:0] y, output wire [31:0] width); + assign y=P; + assign width=$bits(P); + endmodule + module Top(output wire [7:0] whole, nibble, grouped, + output wire [31:0] whole_width, nibble_width, grouped_width); + import Values::*; + Sink #(.P(TABLE[2][0])) a(.y(whole),.width(whole_width)); + Sink #(.P(TABLE[3][-1][1])) b(.y(nibble),.width(nibble_width)); + Sink #(.P((Values::TABLE[3][-1]))) c(.y(grouped),.width(grouped_width)); + endmodule + "#) + (top Top) (eval) + (assert_eq whole 0x78) (assert_eq whole_width 8) + (assert_eq nibble 1) (assert_eq nibble_width 4) + (assert_eq grouped 0x12) (assert_eq grouped_width 8)) + +(case array_parameter_elements_preserve_four_state_and_conversion + (four_state) + (source "state_array_parameter_elements.sv" #" + module Sink #(parameter logic [7:0] U=0, parameter logic signed [7:0] S=0, + parameter bit [7:0] B=0)(output wire [7:0] u,s,b); + assign u=U; + assign s=S; + assign b=B; + endmodule + module Top(output wire [15:0] unsigned_value, signed_value, two_state_value); + localparam logic [3:0] A[-1:0]='{4'b10xz,4'bz01x}; + localparam logic signed [3:0] S[-1:0]='{4'b10xz,4'bz01x}; + for(genvar i=-1;i<=0;i++) begin:g + Sink #(.U(A[i]),.S(S[i]),.B(A[i])) sink( + .u(unsigned_value[(0-i)*8 +: 8]), + .s(signed_value[(0-i)*8 +: 8]), + .b(two_state_value[(0-i)*8 +: 8])); + end + endmodule + "#) + (top Top) (eval) + (assert_eq unsigned_value (fourstate 0x0a03 0x0309)) + (assert_eq signed_value (fourstate 0xfa03 0x03f9)) + (assert_eq two_state_value 0x0802)) + + +(case array_parameter_elements_preserve_wide_specializations + (source "wide_array_parameter_elements.sv" #" + module Sink #(parameter P=0)(output wire [128:0] value, output wire [31:0] width); + assign value=P; + assign width=$bits(P); + endmodule + module Parent #(parameter SELECT=0) + (output wire [128:0] value, output wire [31:0] width); + localparam logic [128:0] TABLE[-2:-1]='{129'h100000000000000000000000000000001,129'd2}; + Sink #(.P(TABLE[SELECT-2])) sink(.value(value),.width(width)); + endmodule + module Top(output wire [128:0] first, second, output wire [31:0] first_width, second_width); + Parent #(.SELECT(0)) a(.value(first),.width(first_width)); + Parent #(.SELECT(1)) b(.value(second),.width(second_width)); + endmodule + "#) + (top Top) (eval) + (assert_eq first 0x100000000000000000000000000000001) + (assert_eq second 2) + (assert_eq first_width 129) (assert_eq second_width 129)) + + +(case array_parameter_elements_select_conditional_whole_arrays + (source "conditional_array_parameter_elements.sv" #" + module Sink #(parameter logic [63:0] P=0)(output wire [63:0] y); + assign y=P; + endmodule + module Relay #(parameter logic [63:0] A[3:2]='{0,0})(output wire [127:0] y); + for(genvar i=2;i<=3;i++) begin:g + Sink #(.P(A[i])) sink(.y(y[(3-i)*64 +: 64])); + end + endmodule + module Parent #(parameter SELECT=1)(output wire [127:0] y); + localparam logic [63:0] A[2]='{"A0","A1"}; + localparam logic [63:0] B[2]='{"B0","B1"}; + Relay #(.A(SELECT ? A : (SELECT==0 ? B : A))) relay(.y(y)); + endmodule + module Top(output wire [127:0] first, second); + Parent #(.SELECT(1)) a(.y(first)); + Parent #(.SELECT(0)) b(.y(second)); + endmodule + "#) + (top Top) (eval) + (assert_eq first 0x00000000000041310000000000004130) + (assert_eq second 0x00000000000042310000000000004230)) diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 51913fe38fb..13d628a419a 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,25 @@ use super::*; sv_backends! { + fn array_parameter_elements_select_conditional_whole_arrays(sim) { + @case "hierarchy::array_parameter_elements_select_conditional_whole_arrays"; + } + fn array_parameter_elements_preserve_wide_specializations(sim) { + @case "hierarchy::array_parameter_elements_preserve_wide_specializations"; + } + fn array_parameter_elements_forward_generated_values(sim) { + @case "hierarchy::array_parameter_elements_forward_generated_values"; + } + fn array_parameter_elements_keep_signed_element_types(sim) { + @case "hierarchy::array_parameter_elements_keep_signed_element_types"; + } + fn array_parameter_elements_select_package_multidimensional_values(sim) { + @case "hierarchy::array_parameter_elements_select_package_multidimensional_values"; + } + fn array_parameter_elements_preserve_four_state_and_conversion(sim) { + @case "hierarchy::array_parameter_elements_preserve_four_state_and_conversion"; + } + fn port_pattern_constant_unpacked_defaults(sim) { @case "hierarchy::port_pattern_constant_unpacked_defaults"; } @@ -614,3 +633,57 @@ fn rejects_recursive_port_pattern_defaults_for_packed_unions() { ); } } + +#[test] +fn array_parameter_elements_reject_runtime_values() { + for (declaration, expression) in [ + ("logic [4:0] A[2]='{5'd3,5'd4};", "A[0]"), + ("localparam logic [4:0] A[2]='{5'd3,5'd4};", "A[index]"), + ] { + let source = format!( + "module Child #(parameter P=0)(output wire[4:0] y);assign y=P;endmodule\n\ + module Top(input int index,output wire[4:0] y);{declaration}\n\ + Child #(.P({expression})) child(.y(y));endmodule" + ); + let error = match Simulator::from_sv_sources( + vec![(&source, Path::new("runtime_array_parameter.sv"))], + "Top", + ) + .build_cranelift() + { + Err(error) => error, + Ok(_) => panic!("runtime parameter argument {expression} must be rejected"), + }; + assert!( + error.to_string().contains("parameter"), + "{expression}: {error}" + ); + } +} + +#[test] +fn array_parameter_elements_check_unselected_conditional_branch_types() { + for declaration in [ + "logic[4:0] B[2]='{1,2};", + "logic[3:0] B[3]='{1,2,3};", + "logic signed[3:0] B[2]='{1,2};", + "bit[3:0] B[2]='{1,2};", + ] { + let source = format!( + "module Child #(parameter logic[3:0] Q[2]='{{0,0}})(output wire[3:0] y);\n\ + assign y=Q[0];endmodule\n\ + module Top(output wire[3:0] y);localparam logic[3:0] A[2]='{{3,4}};\n\ + localparam {declaration}\n\ + Child #(.Q(1 ? A : B)) child(.y(y));endmodule" + ); + assert!( + Simulator::from_sv_sources( + vec![(&source, Path::new("conditional_array_type.sv"))], + "Top" + ) + .build_cranelift() + .is_err(), + "unselected conditional branch with {declaration} must be rejected" + ); + } +} From 3880dfb74baf567e08ffa832a125d3377bee7eed Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 14:58:41 +0900 Subject: [PATCH 4/4] perf(sv): skip the always_comb alternative nothing can watch In a design with a wait, every always_comb that may store a variable twice was also lowered as an imperative unit, which assembly drops unless a wait or flip-flop domain counts one of its targets. A module now collects what may name its variables: wait terms, triggers, event copies, package variables, instance connections, ports of an instantiated module, and whatever a same-width write and read of a combinational process connects to them. The second lowering runs only for a process whose targets meet that set. Designs with a nonblocking switch or with foreign modules lower every alternative as before. Closes #1754 Change-Id: I6ca8cdf3e1561a784cd9ac5536b8d42b3618b9a3 --- crates/celox-frontend-sv/src/lowering.rs | 203 ++++++++++++++++++ .../src/lowering/procedural.rs | 28 +++ 2 files changed, 231 insertions(+) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 605b02f32bb..f7e7390e94b 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1817,6 +1817,7 @@ fn prepare_external_hierarchy_collecting( &lowered_modules, four_state, allow_inferred_latches, + true, warnings, )?; modules.insert( @@ -2331,6 +2332,7 @@ fn schedule_sources_collecting( &lowered_modules, four_state, allow_inferred_latches, + false, warnings, )?; module_names.insert(module_id, key.name.clone()); @@ -3554,6 +3556,7 @@ pub(crate) fn attach_instance_glue( lowered_modules: &HashMap, four_state: bool, allow_inferred_latches: bool, + foreign: bool, warnings: &mut Vec, ) -> Result<(), ParserError> { let mut signal_names = lowered.signal_names.clone(); @@ -3683,6 +3686,67 @@ pub(crate) fn attach_instance_glue( let waits = lowered_modules .values() .any(|module| !module.sim_module.wait_sites.is_empty()); + // An `always_comb` alternative is kept only if a wait or a flip-flop + // domain counts one of its targets. Within the module, they name its + // wait terms, its triggers and whole-variable copies of them; beyond + // it, ports, instance connections and package variables. Every counter + // a design declares also keeps nonblocking writes queued, so a design + // with a nonblocking switch lowers every alternative, and so does a + // module of a design with foreign modules, which this module does not see. + let watch_seeds = (waits + && !foreign + && !lowered_modules + .values() + .any(|module| !module.sim_module.nba_switches.is_empty())) + .then(|| { + let mut seeds: HashSet = module + .wait_sites + .iter() + .flat_map(|site| site.terms.iter().map(|&(signal, _)| signal)) + .collect(); + let triggers = module + .eval_only_ff_blocks + .keys() + .chain(module.apply_ff_blocks.keys()) + .chain(module.eval_apply_ff_blocks.keys()) + .chain(module.split_commit_ff_blocks.keys()) + .chain(module.parallel_ff_parts.keys()); + for trigger in triggers { + seeds.insert(trigger.clock); + seeds.extend(trigger.resets.iter().copied()); + } + for &(copy, signal) in &lowered.event_copies { + seeds.extend([copy, signal]); + } + seeds.extend(lowered.package_variables.iter().map(|(id, _, _)| *id)); + let instantiated = lowered_modules.values().any(|other| { + other + .instances + .iter() + .any(|instance| &LoweredSvModuleKey::instance_key(instance) == current_key) + }); + if instantiated { + seeds.extend( + parent_variables + .iter() + .filter(|(_, variable)| variable.kind.is_port()) + .map(|(id, _)| *id), + ); + } + let mut names = HashSet::default(); + for (_, _, _, connections) in &resolved_instances { + for actual in connections.iter().filter_map(|c| c.actual_expr.as_ref()) { + procedural::expr_idents(actual, &mut names); + } + } + seeds.extend( + names + .iter() + .filter_map(|name| signal_names.get(name).copied()), + ); + seeds.extend(port_assignments.iter().map(|(target, _)| *target)); + seeds + }); let (comb_blocks, arena, created, comb_observers, comb_sites, comb_alternatives) = lower_comb_processes( &lowered.source, @@ -3697,6 +3761,7 @@ pub(crate) fn attach_instance_glue( &mut module.extern_functions, warnings, waits, + watch_seeds.as_ref(), ) .map_err(|error| match error { sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile { @@ -4264,6 +4329,7 @@ fn lower_comb_processes( extern_functions: &mut Vec, warnings: &mut Vec, waits: bool, + watch_seeds: Option<&HashSet>, ) -> Result< ( Vec>, @@ -4292,6 +4358,8 @@ fn lower_comb_processes( pm.runtime_errors = std::mem::take(runtime_errors); pm.extern_functions = std::mem::take(extern_functions); let random_seeds = process_random_seeds(module); + let watchable = + watch_seeds.map(|seeds| watchable_variables(&pm, module, port_assignments, seeds)); for (index, process) in module.comb_processes().iter().enumerate() { if let Some(condition) = process.condition() { let condition = @@ -4352,6 +4420,15 @@ fn lower_comb_processes( targets.sort_unstable(); targets.dedup(); comb_blocks.extend(paths); + if let Some(watchable) = &watchable + && targets + .iter() + .map(|target| target.id) + .chain(pm.written_variables(process.body())) + .all(|id| !watchable.contains(&id)) + { + continue; + } if let Some((paths, alternative)) = lower_comb_alternative( &mut pm, process, @@ -4490,6 +4567,65 @@ fn lower_comb_processes( Ok((comb_blocks, arena, created, observers, sites, alternatives)) } +/// `seeds` and the variables a whole-variable copy of a combinational +/// process or a port assignment may connect to them, in either direction. +/// Any variable a process writes may copy any variable of the same width +/// the process writes or reads. +fn watchable_variables( + pm: &procedural::ProcModule<'_>, + module: &sv::ir::Module, + port_assignments: &[(SourceVarId, Vec)], + seeds: &HashSet, +) -> HashSet { + let mut groups: HashMap<(usize, usize), Vec> = HashMap::default(); + let mut group = |index: usize, writes: HashSet, reads: Vec| { + let widths: HashSet = writes.iter().map(|&id| pm.var(id).width).collect(); + for id in writes.into_iter().chain(reads) { + let width = pm.var(id).width; + if widths.contains(&width) { + groups.entry((index, width)).or_default().push(id); + } + } + }; + let processes = module.comb_processes(); + for (index, process) in processes.iter().enumerate() { + let mut reads = pm.implicit_reads(process.body(), true); + reads.extend(pm.implicit_reads(process.sensitivity_body(), true)); + group( + index, + pm.written_variables(process.body()), + reads.iter().map(|read| read.id).collect(), + ); + } + for (index, (target, body)) in port_assignments.iter().enumerate() { + let mut writes = pm.written_variables(body); + writes.insert(*target); + group( + processes.len() + index, + writes, + pm.implicit_reads(body, true) + .iter() + .map(|read| read.id) + .collect(), + ); + } + let mut watchable = seeds.clone(); + let mut groups: Vec<_> = groups.into_values().collect(); + loop { + let before = groups.len(); + groups.retain(|group| { + if !group.iter().any(|id| watchable.contains(id)) { + return true; + } + watchable.extend(group.iter().copied()); + false + }); + if groups.len() == before { + return watchable; + } + } +} + /// The imperative unit of an `always_comb` process lowered symbolically to /// `targets`, and its [`CombAlternative`], if the unit may store a variable /// of the design twice in one execution. Otherwise nothing of the attempt @@ -9164,6 +9300,73 @@ mod tests { .count() } + /// The `always_comb` alternatives the modules of `source` lowered. + fn comb_alternatives(source: &str) -> usize { + let mut trace = FrontendTrace::default(); + schedule_sources( + &[(source, Path::new("top.sv"))], + "Top", + &[], + &[], + &[], + false, + &celox_frontend_core::ParallelScheduleOptions::default(), + &FrontendTraceOptions { + sim_modules: true, + ..Default::default() + }, + Some(&mut trace), + &mut Vec::new(), + ) + .unwrap_or_else(|error| panic!("{error}")); + trace + .sim_modules + .expect("traced modules") + .values() + .map(|module| module.comb_alternatives.len()) + .sum() + } + + /// An `always_comb` that stores a variable twice gets its imperative + /// alternative only where a wait or a flip-flop domain may watch it. + #[test] + fn comb_alternatives_only_for_watchable_targets() { + let multi_store = "always_comb begin w = 0; if (s[0]) w = 1; end"; + for (case, body, alternatives) in [ + ("unwatched", "initial forever @(s) ;", 0), + ("waited", "initial forever @(w) ;", 1), + ( + "aliased clock", + "bit c; assign c = w; bit q; always_ff @(posedge c) q <= ~q; + initial forever @(s) ;", + 1, + ), + ( + "nonblocking switch", + "bit [7:0] t; initial forever @(s) t <= s;", + 1, + ), + ] { + let source = format!( + "module Top(input bit [7:0] s); + bit w; + {multi_store} + {body} + endmodule" + ); + assert_eq!(comb_alternatives(&source), alternatives, "{case}"); + } + let child_port = "module Child(input bit [7:0] s, output bit w); + always_comb begin w = 0; if (s[0]) w = 1; end + endmodule + module Top(input bit [7:0] s); + bit w; + Child child(.s(s), .w(w)); + initial forever @(w) ; + endmodule"; + assert_eq!(comb_alternatives(child_port), 1, "child output port"); + } + /// Only the `always @(list)` processes of a combinational loop stay /// processes; one `initial` block drives each design. #[test] diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 54a49321b97..51298818d29 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -319,6 +319,34 @@ impl<'a> ProcModule<'a> { false } + /// The variables `body` may write, directly or in the bodies of its + /// callees. Names a callee declares itself may resolve to a variable of + /// the module too, so the set may be larger than the writes. + pub fn written_variables(&self, body: &[sv::ir::Stmt]) -> HashSet { + let mut names = HashSet::default(); + let mut calls = Vec::new(); + written_names(body, &mut names); + for stmt in body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + let mut visited = HashSet::default(); + while let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + if let Some(subroutine) = self.subroutine(&name) { + default_calls(subroutine, &args, &mut calls); + if visited.insert(name) { + written_names(&subroutine.body, &mut names); + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + } + } + } + names.iter().filter_map(|name| self.id(name)).collect() + } + /// Whether `always @(items) body` is `always @* body`: no item has an edge /// or a select, the items name exactly the variables the implicit event /// expression of `body` has (IEEE 1800-2023 9.4.2.2), and the body neither