Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ use celox_sv_analyzer as sv;
use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use num_bigint::BigUint;

mod case_equality;
mod comb;
mod comb_retention;
mod ff;
Expand Down Expand Up @@ -5015,6 +5016,17 @@ fn expr_for_state_mode(expr: &sv::ir::Expr, four_state: bool) -> sv::ir::Expr {
op: *op,
expr: Box::new(expr_for_state_mode(expr, four_state)),
},
sv::ir::Expr::Binary { left, op, right }
if !four_state && matches!(op, sv::ir::BinaryOp::EqCase | sv::ir::BinaryOp::NeCase) =>
{
// Storage remains two-state; exact comparison operands retain
// literal X/Z until value and mask are compared (11.4.5).
sv::ir::Expr::Binary {
left: Box::new(expr_for_state_mode(left, true)),
op: *op,
right: Box::new(expr_for_state_mode(right, true)),
}
}
sv::ir::Expr::Binary { left, op, right } => sv::ir::Expr::Binary {
left: Box::new(expr_for_state_mode(left, four_state)),
op: *op,
Expand Down
445 changes: 445 additions & 0 deletions crates/celox-frontend-sv/src/lowering/case_equality.rs

Large diffs are not rendered by default.

84 changes: 69 additions & 15 deletions crates/celox-frontend-sv/src/lowering/comb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,7 +583,18 @@ impl<'p, 'a> Comb<'p, 'a> {
expr: &sv::ir::Expr,
context: Option<(usize, bool)>,
) -> Result<Value, sv::AnalyzerError> {
let expr = expr_for_state_mode(expr, self.m.four_state);
self.eval_mode(store, frames, expr, context, false)
}

fn eval_mode(
&mut self,
store: &mut Store,
frames: &[Frame],
expr: &sv::ir::Expr,
context: Option<(usize, bool)>,
preserve_literals: bool,
) -> Result<Value, sv::AnalyzerError> {
let expr = expr_for_state_mode(expr, self.m.four_state || preserve_literals);
let expr = if self.m.calls(&expr) {
self.hoist(store, frames, &expr)?
} else {
Expand Down Expand Up @@ -847,11 +858,14 @@ impl<'p, 'a> Comb<'p, 'a> {
}
}
sources.extend(r_sources);
let rebuilt = if l == left && r == right {
node
} else {
self.alloc(SLTNode::Binary(l, op, r))?
};
let rebuilt =
if !self.m.four_state && matches!(op, BinaryOp::EqCase | BinaryOp::NeCase) {
super::case_equality::compare(self.arena, l, op, r).map_err(slt_error)?
} else if l == left && r == right {
node
} else {
self.alloc(SLTNode::Binary(l, op, r))?
};
(rebuilt, sources)
}
SLTNode::Unary(op, inner) => {
Expand Down Expand Up @@ -2285,7 +2299,13 @@ impl<'p, 'a> Comb<'p, 'a> {
return Ok(conditions);
}
let selector_signed = self.expr_signed(selector);
let (selector_node, selector_sources) = self.eval(store, frames, selector, None)?;
let (selector_node, selector_sources) = self.eval_mode(
store,
frames,
selector,
None,
kind == sv::ir::CaseKind::Exact,
)?;
let mut labels = Vec::with_capacity(items.len());
let mut width = self.width(selector_node);
let mut all_signed = selector_signed;
Expand All @@ -2296,7 +2316,8 @@ impl<'p, 'a> Comb<'p, 'a> {
return Err(unsupported("range label outside case inside"));
};
all_signed &= self.expr_signed(value);
let (node, sources) = self.eval(store, frames, value, None)?;
let (node, sources) =
self.eval_mode(store, frames, value, None, kind == sv::ir::CaseKind::Exact)?;
width = width.max(self.width(node));
item_labels.push((node, sources));
}
Expand All @@ -2307,8 +2328,14 @@ impl<'p, 'a> Comb<'p, 'a> {
// equality: an unsigned operand also turns the others' operands
// unsigned (11.8.2).
let selector_node = if self.width(selector_node) < width || selector_signed != all_signed {
self.eval(store, frames, selector, Some((width, all_signed)))?
.0
self.eval_mode(
store,
frames,
selector,
Some((width, all_signed)),
kind == sv::ir::CaseKind::Exact,
)?
.0
} else {
selector_node
};
Expand All @@ -2322,7 +2349,13 @@ impl<'p, 'a> Comb<'p, 'a> {
&& (self.width(*node) < width || self.expr_signed(value) != all_signed)
{
*node = self
.eval(store, frames, value, Some((width, all_signed)))?
.eval_mode(
store,
frames,
value,
Some((width, all_signed)),
kind == sv::ir::CaseKind::Exact,
)?
.0;
}
}
Expand All @@ -2337,7 +2370,12 @@ impl<'p, 'a> Comb<'p, 'a> {
for (node, mut sources) in item_labels {
let node = coerce_node_width(self.arena, node, Some(width), all_signed)
.map_err(slt_error)?;
let matched = self.alloc(SLTNode::Binary(selector_node, op, node))?;
let matched = if !self.m.four_state && kind == sv::ir::CaseKind::Exact {
super::case_equality::compare(self.arena, selector_node, op, node)
.map_err(slt_error)?
} else {
self.alloc(SLTNode::Binary(selector_node, op, node))?
};
let matched = if kind == sv::ir::CaseKind::X {
// A wildcard comparison returns X when only selector
// unknowns prevent a definite match. casex ignores those
Expand Down Expand Up @@ -2538,11 +2576,21 @@ impl<'p, 'a> Comb<'p, 'a> {
) -> Result<Vec<bool>, sv::AnalyzerError> {
let none = vec![false; items.len()];
let mut probe = store.fork();
let (selector_node, _) = self.eval(&mut probe, frames, selector, None)?;
let (selector_node, _) = self.eval_mode(
&mut probe,
frames,
selector,
None,
kind == sv::ir::CaseKind::Exact,
)?;
let selector_width = self.width(selector_node);
// A four-state selector also takes X and Z bits; only exact
// comparisons of a narrow selector are enumerated.
let four_state_selector = !self.two_state(selector_node);
let four_state_selector = if self.m.four_state {
!self.two_state(selector_node)
} else {
!super::case_equality::is_known(self.arena, selector_node).map_err(slt_error)?
};
if four_state_selector && (kind != sv::ir::CaseKind::Exact || selector_width > 6) {
return Ok(none);
}
Expand All @@ -2558,7 +2606,13 @@ impl<'p, 'a> Comb<'p, 'a> {
sv::AnalyzerError,
> {
let signed = this.expr_signed(expr);
let (node, _) = this.eval(&mut probe, frames, expr, None)?;
let (node, _) = this.eval_mode(
&mut probe,
frames,
expr,
None,
kind == sv::ir::CaseKind::Exact,
)?;
Ok(slt_const4(this.arena, &mut this.consts, node)
.map(|(value, mask, width)| (value, mask, width, signed)))
};
Expand Down
21 changes: 21 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -969,6 +969,27 @@ impl<'p, 'a> Ff<'p, 'a> {
stable(*id)
}
};
if !self.m.four_state {
// Node IDs are topological. Cache exact comparisons before mapping
// their parents, reusing the existing graph/loop remapper.
for (index, expression) in arena.iter().enumerate() {
if let SLTNode::Binary(left, op @ (BinaryOp::EqCase | BinaryOp::NeCase), right) =
expression
{
let left = arena
.get(*left)
.map_addr(*left, arena, &mut mapped_arena, &mut cache, &map)
.map_err(slt_error)?;
let right = arena
.get(*right)
.map_addr(*right, arena, &mut mapped_arena, &mut cache, &map)
.map_err(slt_error)?;
let equal = super::case_equality::compare(&mut mapped_arena, left, *op, right)
.map_err(slt_error)?;
cache.insert(NodeId(index), equal);
}
}
}
let mapped = arena
.get(node)
.map_addr(node, arena, &mut mapped_arena, &mut cache, &map)
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-frontend-sv/src/lowering/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2211,7 +2211,7 @@ pub(super) fn slt_unknown<A: std::hash::Hash + Eq + Clone>(
) -> Result<NodeId, sv::AnalyzerError> {
let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8);
arena
.alloc(SLTNode::Constant(BigUint::default(), mask, width, false))
.alloc(SLTNode::Constant(mask.clone(), mask, width, false))
.map_err(slt_error)
}

Expand Down
144 changes: 141 additions & 3 deletions crates/celox-slt/src/const_inline.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! Constant variable inlining for combinational logic paths.
//!
//! Detects variables whose *every* LogicPath target is a constant expression
//! (no runtime inputs), then rewrites all `SLTNode::Input` references to those
//! variables with `SLTNode::Constant` nodes containing the precomputed value.
//! (no runtime inputs), whose reads are all covered by those drivers, then
//! rewrites their `SLTNode::Input` references to precomputed constants.
//! Variables with reads of undriven ranges retain their state dependencies.
//! This eliminates the Store→Load memory roundtrip for compile-time constants
//! such as genvar-expanded parity-check matrices.

Expand Down Expand Up @@ -226,6 +227,17 @@ struct ConstVar {
payload: BigUint,
/// Combined 4-state mask.
mask: BigUint,
/// Sorted, merged driven ranges. Bits outside them retain their state.
written: Vec<BitAccess>,
}

impl ConstVar {
fn covers(&self, access: BitAccess) -> bool {
let index = self.written.partition_point(|range| range.msb < access.lsb);
self.written
.get(index)
.is_some_and(|range| range.lsb <= access.lsb && range.msb >= access.msb)
}
}

/// Inline constant variables: rewrite Input references → Constant nodes.
Expand Down Expand Up @@ -305,9 +317,42 @@ pub fn inline_constant_variables<A: Clone + Eq + Hash + Debug + Display>(
if mask != BigUint::from(0u32) {
continue;
}
const_vars.insert(var.clone(), ConstVar { payload, mask });
// Do not invent zeroes for undriven bits. Keep coverage as ranges,
// so a sparse driver does not allocate a mask up to its bit offset.
let mut written: Vec<_> = entries.iter().map(|(access, _)| *access).collect();
written.sort_unstable_by_key(|access| access.lsb);
written.dedup_by(|next, previous| {
if next.lsb <= previous.msb.saturating_add(1) {
previous.msb = previous.msb.max(next.msb);
true
} else {
false
}
});
const_vars.insert(
var.clone(),
ConstVar {
payload,
mask,
written,
},
);
}

// All reads must be covered before removing a variable's dependency
// edges. A read can include undriven bits even above the highest driver,
// or a hole between drivers; those bits retain their initial state.
for node in arena.iter() {
if let SLTNode::Input {
variable, access, ..
} = node
&& const_vars
.get(variable)
.is_some_and(|cv| !cv.covers(*access))
{
const_vars.remove(variable);
}
}
if const_vars.is_empty() {
return Ok(false);
}
Expand Down Expand Up @@ -559,6 +604,99 @@ mod tests {

use super::eval_const_expr;

#[test]
fn only_inlines_reads_covered_by_constant_drivers() {
use crate::{LogicPath, LogicPathTarget};
use celox_design::{BitAccess, VarAtomBase};

for bridge_gap in [false, true] {
for access in [
BitAccess::new(2, 3),
BitAccess::new(0, 3),
BitAccess::new(4, 7),
BitAccess::new(0, 7),
] {
let mut arena = SLTNodeArena::<u32>::new();
let one = arena
.alloc(SLTNode::Constant(1u8.into(), 0u8.into(), 1, false))
.unwrap();
let zero = arena
.alloc(SLTNode::Constant(0u8.into(), 0u8.into(), 1, false))
.unwrap();
let three = arena
.alloc(SLTNode::Constant(3u8.into(), 0u8.into(), 2, false))
.unwrap();
let make_path = |variable, access, expr, sources: crate::HashSet<_>| LogicPath {
transparent_copy: false,
target: LogicPathTarget::Var(VarAtomBase {
id: variable,
access,
}),
previous_sources: sources.clone(),
address_sources: sources.clone(),
sources,
local_inputs: vec![],
order_before: Default::default(),
comb_capture_enable_sites: vec![],
comb_capture_enable_always: false,
pre_lower_nodes: vec![],
expr,
};
// Non-sorted fragments. Filling bit 1 makes 0..=3 contiguous,
// but never covers higher bits. Unobserved gaps do not stop
// reads confined to the driven bits from being inlined.
let mut paths = vec![
make_path(1, BitAccess::new(2, 3), three, Default::default()),
make_path(1, BitAccess::new(0, 0), one, Default::default()),
];
if bridge_gap {
paths.push(make_path(1, BitAccess::new(1, 1), zero, Default::default()));
}
let input = arena
.alloc(SLTNode::Input {
variable: 1,
signed: false,
index: vec![],
access,
})
.unwrap();
let source = VarAtomBase { id: 1, access };
paths.push(make_path(
2,
BitAccess::new(0, access.msb - access.lsb),
input,
[source].into_iter().collect(),
));
let inlined = access == BitAccess::new(2, 3)
|| (access == BitAccess::new(0, 3) && bridge_gap);
assert_eq!(
super::inline_constant_variables(&mut paths, &mut arena).unwrap(),
inlined
);
let path = paths.last().unwrap();
if inlined {
let expected = if access.lsb == 2 { 3u8 } else { 13u8 };
assert_eq!(
super::eval_const_expr(path.expr, &arena),
(expected.into(), 0u8.into(), access.msb - access.lsb + 1)
);
} else {
assert_eq!(
path.expr, input,
"read of an undriven bit became a constant"
);
}
for edges in [&path.sources, &path.previous_sources, &path.address_sources] {
assert_eq!(
edges.contains(&source),
!inlined,
"dependency of an unrewritten read was removed"
);
}
}
}
}

#[test]
fn floating_operations_fold_ieee_payloads_and_result_widths() {
use celox_design::{BinaryOp, FloatBinaryOp, FloatPrecision, FloatUnaryOp};
Expand Down
Loading
Loading