From fa42ab43e957b0f540c62680737131b52d2e9e4f Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 27 Oct 2026 01:50:20 +0900 Subject: [PATCH] perf(sv): avoid redundant scope discovery and constant evaluation Repeated literal arithmetic in aggregate port defaults rediscovered declaration scopes and copied growing scope snapshots. Runtime select lowering also repeatedly attempted constant evaluation of large inlined expressions. Skip declaration discovery for expression trees composed entirely of literals, reject required unbound runtime operands before constant substitution, reuse binary operands already evaluated for type context, and return width one for identical runtime bit-select bounds. Keep names in unselected query arms on the discovery path and preserve short-circuit evaluation. Local compile measurements against master ee675d820f, using frozen CLI binaries and identical options: - 128 aggregate-default ports: 20.62 s to 0.69 s. - 256 aggregate-default ports: 90 s timeout to 0.50 s. - Original Taxi 32-channel Ethernet configuration: 123.971 s to 99.821 s, about 20% faster. - VCU108 still exceeds the 300 s compile limit with both binaries. This remains unresolved. Taxi sources were unchanged at cc70b270b910d369ab1ad7b3855e76399fd461f1. Taxi measurements cover compilation only, with O1 and two-state operation; cocotb runtime tests were not rerun. These are local measurements rather than timing assertions in CI. Validation: - Analyzer/frontend unit tests: 846 passed; 2 doctests passed. - Full SystemVerilog backend suite: 5,664 passed; 20 existing skips. - Clippy for celox-sv-analyzer, celox-frontend-sv and celox tests with systemverilog, cranelift and wasm-runtime: passed with -D warnings. - cargo fmt --all -- --check and git diff --check: passed. Regression tests assert discovery/evaluation counts and width semantics without wall-clock thresholds. Shared executable cases and external adapters are unchanged. Change-Id: Ia023a992051109e82c9ae3ae147c313b49f70e54 --- crates/celox-frontend-sv/src/lowering.rs | 37 ++++ .../src/ast/dimensions/query_binding.rs | 45 +++-- .../src/ast/dimensions/tests.rs | 68 ++++++++ crates/celox-sv-analyzer/src/typecheck.rs | 164 +++++++++++++++++- 4 files changed, 303 insertions(+), 11 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d7029c83308..9c85e3b5931 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -8827,6 +8827,12 @@ fn runtime_select_width( if constant(msb).is_some() && constant(lsb).is_some() { return None; } + // A bit select has width one regardless of its runtime position. Sampling + // both bounds evaluates the same (potentially inlined) expression twice, + // and the zero sample need not even be a valid index computation. + if msb == lsb { + return Some(1); + } // The width is the same for every value of the runtime operands. let mut sample = constants.clone(); for name in name_to_id.keys() { @@ -10510,6 +10516,37 @@ fn inferred_clock( mod tests { use super::*; + #[test] + fn bit_select_width_does_not_evaluate_a_runtime_zero_sample() { + let index = sv::ir::ConstExpr::Ident("index".into()); + let bound = sv::ir::ConstExpr::Binary { + left: Box::new(sv::ir::ConstExpr::Literal("255".into())), + op: sv::ir::BinaryOp::Div, + right: Box::new(index.clone()), + }; + let names = HashMap::from_iter([("index".into(), SourceVarId(0))]); + let constants = HashMap::default(); + let types = HashMap::default(); + assert_eq!( + runtime_select_width(&bound, &bound, &names, &constants, &types), + Some(1) + ); + let high = sv::ir::ConstExpr::Binary { + left: Box::new(index.clone()), + op: sv::ir::BinaryOp::Add, + right: Box::new(sv::ir::ConstExpr::Literal("7".into())), + }; + assert_eq!( + runtime_select_width(&high, &index, &names, &constants, &types), + Some(8) + ); + let constant = sv::ir::ConstExpr::Literal("3".into()); + assert_eq!( + runtime_select_width(&constant, &constant, &names, &constants, &types), + None + ); + } + /// The per-name driver scan [`ModuleDrivers`] replaced, which walks every /// process for each name. mod per_name_scan { diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 353055ff483..83c870dbb80 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -21,21 +21,46 @@ fn query_context(context: &PackedDimensions) -> PackedDimensions { query } +/// These operands carry all type information in their literal leaves. Walking +/// declaration scopes cannot change their shape or signedness. Keep calls, +/// casts and names on the discovery path, including names in unevaluated arms. +fn literal_operand(root: ExprId, native: &celox_sv_syntax::Declarations) -> bool { + let root = expression_binding::ungroup(root, native); + if matches!(native.expression(root).kind, ExprKind::Literal(_)) { + return true; + } + let mut pending = vec![root]; + while let Some(id) = pending.pop() { + match &native.expression(id).kind { + ExprKind::Literal(_) => {} + ExprKind::Group(inner) + | ExprKind::Unary { + expression: inner, .. + } => { + pending.push(*inner); + } + ExprKind::Binary { left, right, .. } => pending.extend([*left, *right]), + ExprKind::Conditional { + condition, + then_expression, + else_expression, + } => { + pending.extend([*condition, *then_expression, *else_expression]); + } + _ => return false, + } + } + true +} + pub(in crate::ast) fn query_context_for_operand( root: ExprId, tree: &AnalysisContext<'_>, context: &PackedDimensions, ) -> Converted { - // Literals carry their type in their spelling and cannot reference lexical - // declarations. Pattern elements otherwise rediscover the whole scope for - // each literal while the surrounding declaration is still being bound. - let operand = expression_binding::ungroup(root, tree.declarations()); - if context.scope_types_complete - || matches!( - tree.declarations().expression(operand).kind, - ExprKind::Literal(_) - ) - { + // Aggregate port defaults commonly repeat literal arithmetic. Rediscovering + // all declarations for each item repeatedly snapshots the growing prefix. + if context.scope_types_complete || literal_operand(root, tree.declarations()) { return Ok(query_context(context)); } Ok(query_context(&query_operand_dimensions_id( diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index f29dadcf3e5..eeeac9bcae6 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -45,6 +45,74 @@ fn query_number( .and_then(|value| usize::try_from(value).ok()) } +#[test] +fn repeated_literal_port_defaults_do_not_rediscover_declarations() { + for count in [8, 32, 128] { + let ports = (0..count) + .map(|i| format!("input logic [7:0] p{i}[2] = '{{2{{8'd60-1}}}}")) + .collect::>() + .join(","); + let code = format!("module Top({ports}, output wire [7:0] y); assign y=p0[0]; endmodule"); + let tree = + crate::source_tree::parse_scope_fixture(&code, Path::new("literal-port-defaults.sv")) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + let source = Source::from_syntax(&tree).unwrap(); + assert_eq!(source.modules()[0].ports().len(), count + 1); + assert_eq!( + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()), + 0, + "{count} ports" + ); + } +} + +#[test] +fn literal_arithmetic_queries_keep_widths_and_skip_scope_discovery() { + let code = "module Top; assign y=$bits(8'd60-1)+$bits(-8'sd1+16'sd2)+$bits(1'b0 ? 8'hff : 16'hffff)+$bits(~8'hff)+$bits(32'd1<<64'd40); endmodule"; + let tree = + crate::source_tree::parse_scope_fixture(code, Path::new("literal-query-types.sv")).unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + let input = PackedDimensions::default(); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + let values = native_calls(&tree) + .into_iter() + .map(|root| { + query_number( + root, + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&input), + ) + }) + .collect::>(); + assert_eq!(values, [Some(32), Some(16), Some(16), Some(8), Some(32)]); + assert_eq!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()), 0); +} + +#[test] +fn queries_still_discover_names_in_unselected_conditional_arms() { + let code = "module Top; logic [15:0] data; assign y=$bits(1'b0 ? data : 8'hff); endmodule"; + let tree = + crate::source_tree::parse_scope_fixture(code, Path::new("conditional-query-types.sv")) + .unwrap(); + let tree = AnalysisContext::unspecialized(&tree); + SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.set(0)); + assert_eq!( + query_number( + native_calls(&tree)[0], + &tree, + &HashMap::default(), + &HashMap::default(), + Some(&PackedDimensions::default()) + ), + Some(16) + ); + assert!(SYNTAX_TYPE_DISCOVERIES.with(|queries| queries.get()) > 0); +} + #[test] fn function_result_queries_preserve_expression_bodies() { let tree = crate::source_tree::parse_scope_fixture( diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 460881888e5..f795cfb1994 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -345,6 +345,11 @@ pub fn eval_const_expr_with_types( constants: &HashMap, types: &HashMap, ) -> Option { + // Runtime select bounds often contain large inlined expressions. Reject a + // required runtime value before attempting literal folding at every node. + if requires_unbound_value(expr, constants) { + return None; + } // Substitution only replaces the identifiers of typed constants. if !has_typed_constant(expr, constants, types) { return eval_const_expr(expr, constants); @@ -353,6 +358,38 @@ pub fn eval_const_expr_with_types( eval_const_expr(&expr, constants) } +fn requires_unbound_value(expr: &ConstExpr, constants: &HashMap) -> bool { + match expr { + ConstExpr::Literal(_) | ConstExpr::Function { .. } => return false, + ConstExpr::Ident(name) => return !constants.contains_key(name), + _ => {} + } + let mut pending = vec![expr]; + while let Some(expr) = pending.pop() { + match expr { + ConstExpr::Ident(name) if !constants.contains_key(name) => return true, + ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => pending.push(expr), + ConstExpr::Select { expr, bit } => pending.extend([bit.as_ref(), expr.as_ref()]), + ConstExpr::SelectRange { expr, msb, lsb, .. } => { + pending.extend([lsb.as_ref(), msb.as_ref(), expr.as_ref()]); + } + ConstExpr::Binary { left, op, right } => { + // A right logical operand can be skipped. The left operand is + // required; preserve the evaluator's short-circuiting policy. + if !matches!(op, BinaryOp::LogicAnd | BinaryOp::LogicOr) { + pending.push(right); + } + pending.push(left); + } + ConstExpr::Mux { condition, .. } => pending.push(condition), + // Argument evaluation belongs to the callee (including checked + // accesses). Do not infer whether a call needs its actuals here. + ConstExpr::Function { .. } | ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} + } + } + false +} + /// Whether `expr` names a constant that has a type, which /// [`substitute_typed_constants`] replaces with a sized literal. fn has_typed_constant( @@ -714,6 +751,15 @@ fn context_binary_operands( right: &ConstExpr, ) -> Option<(IntegralLiteral, IntegralLiteral, bool)> { let (left_type, right_type) = integral_binary_operands(left, right)?; + context_binary_values(left, right, left_type, right_type) +} + +fn context_binary_values( + left: &ConstExpr, + right: &ConstExpr, + left_type: IntegralLiteral, + right_type: IntegralLiteral, +) -> Option<(IntegralLiteral, IntegralLiteral, bool)> { let width = left_type.width.max(right_type.width); let signed = left_type.signed && right_type.signed; // These values were already evaluated in their own expression contexts. @@ -783,7 +829,7 @@ fn eval_literal_binary( ); return eval_four_state_binary(&left, op, &right, signed); } - let (left, right, signed) = context_binary_operands(left_expr, right_expr)?; + let (left, right, signed) = context_binary_values(left_expr, right_expr, left, right)?; eval_four_state_binary(&left, op, &right, signed) } @@ -1089,7 +1135,14 @@ fn self_determined_integral_literal(expr: &ConstExpr) -> Option } } +#[cfg(test)] +thread_local! { + static LITERAL_EVALUATIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + fn integral_literal_from_const_expr(expr: &ConstExpr) -> Option { + #[cfg(test)] + LITERAL_EVALUATIONS.with(|count| count.set(count.get() + 1)); match expr { ConstExpr::Literal(literal) => parse_integral_literal(literal), ConstExpr::Resize { @@ -2015,6 +2068,115 @@ fn extension_for_leading_digit(ch: char) -> (bool, bool) { mod literal_tests { use super::*; + #[test] + fn numeric_binary_operands_are_evaluated_once_before_type_context() { + let expr = ConstExpr::Binary { + left: Box::new(ConstExpr::Literal("2".into())), + op: BinaryOp::Add, + right: Box::new(ConstExpr::Literal("3".into())), + }; + LITERAL_EVALUATIONS.with(|count| count.set(0)); + assert_eq!( + eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()), + Some(5) + ); + assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 2); + } + + #[test] + fn runtime_bounds_skip_literal_evaluation_before_substitution() { + let mut bound = ConstExpr::Ident("runtime_index".into()); + for _ in 0..64 { + bound = ConstExpr::Resize { + expr: Box::new(ConstExpr::Binary { + left: Box::new(bound), + op: BinaryOp::Add, + right: Box::new(ConstExpr::Ident("P".into())), + }), + width: 32, + signed: false, + }; + } + LITERAL_EVALUATIONS.with(|count| count.set(0)); + assert_eq!( + eval_const_expr_with_types( + &bound, + &HashMap::from_iter([("P".into(), 7)]), + &HashMap::from_iter([("P".into(), (32, false))]) + ), + None + ); + assert_eq!(LITERAL_EVALUATIONS.with(|count| count.get()), 0); + } + + #[test] + fn runtime_bound_probe_preserves_short_circuiting_and_sampled_values() { + let literal = |text: &str| ConstExpr::Literal(text.into()); + let missing = || ConstExpr::Ident("runtime_index".into()); + let expressions = [ + ( + ConstExpr::Binary { + left: Box::new(literal("0")), + op: BinaryOp::LogicAnd, + right: Box::new(missing()), + }, + Some(0), + ), + ( + ConstExpr::Binary { + left: Box::new(literal("1")), + op: BinaryOp::LogicOr, + right: Box::new(missing()), + }, + Some(1), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("1")), + then_expr: Box::new(literal("13")), + else_expr: Box::new(missing()), + }, + Some(13), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("0")), + then_expr: Box::new(missing()), + else_expr: Box::new(literal("19")), + }, + Some(19), + ), + ( + ConstExpr::Mux { + condition: Box::new(literal("1'bx")), + then_expr: Box::new(literal("17")), + else_expr: Box::new(literal("17")), + }, + Some(17), + ), + ]; + for (expr, expected) in expressions { + assert_eq!( + eval_const_expr_with_types(&expr, &HashMap::default(), &HashMap::default()), + expected, + "{expr:?}" + ); + } + let sample = ConstExpr::Binary { + left: Box::new(missing()), + op: BinaryOp::Mul, + right: Box::new(ConstExpr::Ident("P".into())), + }; + assert_eq!( + eval_const_expr_with_types( + &sample, + &HashMap::from_iter([("runtime_index".into(), 3), ("P".into(), 7)]), + &HashMap::from_iter([("P".into(), (32, false))]) + ), + Some(21) + ); + } + /// Expressions without typed constants evaluate as their substituted /// copies do, and typed constants still take their declared type. #[test]