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/packed_structs.rs b/crates/celox-sv-analyzer/src/ast/packed_structs.rs index eb684292cb3..55f7b038349 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs.rs @@ -7,7 +7,7 @@ mod selects; #[cfg(test)] mod tests; -pub(super) use layout::native_type; +pub(super) use layout::{AggregateKind, native_type}; pub(super) use selects::{select_member, whole_member}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index c3908e74344..c7cda41d379 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -2,6 +2,13 @@ use super::*; +#[derive(Clone, Copy)] +pub(in crate::ast) enum AggregateKind { + Struct, + HardUnion, + SoftUnion, +} + /// Freeze member bounds in the declaration environment before generated scopes /// can shadow their parameter names. Shared by both syntax owners. pub(in crate::ast) fn capture_member_type( @@ -30,7 +37,7 @@ pub(in crate::ast) fn capture_member_type( /// Syntax-independent IEEE7.2.1/7.3.1 layout kernel. pub(in crate::ast) fn native_type( state: &AnalysisState, - union: bool, + kind: AggregateKind, signed: bool, owner: Arc, fields: Vec<(String, Type)>, @@ -52,11 +59,11 @@ pub(in crate::ast) fn native_type( }) }) .collect::>>()?; - finish_type(state, union, signed, members, ranges, env) + finish_type(state, kind, signed, members, ranges, env) } fn finish_type( state: &AnalysisState, - union: bool, + kind: AggregateKind, signed: bool, mut members: Vec, ranges: Vec, @@ -66,13 +73,14 @@ fn finish_type( // The first declared member occupies the most significant bits. for member in members.iter_mut().rev() { let member_width = expr_type_from_type(state, &member.r#type, const_env)?.width; - if union { + if !matches!(kind, AggregateKind::Struct) { // IEEE 1800-2023 7.3.1: hard packed members share all bits // and must have the same width. - if width != 0 && width != member_width { + if matches!(kind, AggregateKind::HardUnion) && width != 0 && width != member_width { return None; } - width = member_width; + // Soft members are right-justified in the largest member width. + width = width.max(member_width); } else { member.offset = width; width = width.checked_add(member_width)?; diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs index 95def768938..a9a0fd594aa 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs @@ -12,6 +12,9 @@ fn preserves_layout_signedness_and_state_kind() { mixed_t mixed; union packed signed { logic signed [7:0] a; bit [7:0] b; } mixed_union; union packed { bit [129:0] a; bit [129:0] b; } wide_union; + union soft { bit [3:0] narrow_value; bit [15:0] wide_value; } soft_union; + union soft packed signed { logic [15:0] wide_value; bit [3:0] narrow_value; } signed_soft; + union soft { bit [2:0] narrow_value; union soft { bit [129:0] wide; bit flag; } nested; } nested_soft; signed_t signed_value; struct packed { byte a; shortint b; int c; longint d; } atoms; endmodule @@ -26,6 +29,9 @@ fn preserves_layout_signedness_and_state_kind() { ("atoms", 120, false, ir::TypeKind::Bit), ("mixed_union", 8, true, ir::TypeKind::Logic), ("wide_union", 130, false, ir::TypeKind::Bit), + ("soft_union", 16, false, ir::TypeKind::Bit), + ("signed_soft", 16, true, ir::TypeKind::Logic), + ("nested_soft", 130, false, ir::TypeKind::Bit), ] { let ty = signals .iter() @@ -44,6 +50,9 @@ fn rejects_invalid_or_unsupported_struct_shapes() { "struct { logic a; } value;", "union packed { logic a; logic [1:0] b; } value;", "union tagged packed { logic a; logic b; } value;", + "union soft { real a; bit [63:0] b; } value;", + "union soft { logic a[2]; logic b; } value;", + "union soft { logic a; logic a; } value;", "union packed { logic a; logic b; } value; always_comb value = '{a: 1'b1, b: 1'b0};", "struct packed { real a; } value;", "struct packed { logic a[2]; } value;", 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-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 6f96b7edded..30e61323785 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -22,6 +22,7 @@ pub(in crate::ast) fn bind_in( Aggregate { owner: Arc, union: bool, + soft: bool, signed: bool, names: Vec, ranges: Vec, @@ -89,11 +90,12 @@ pub(in crate::ast) fn bind_in( } DataTypeKind::Struct { union, + soft, tagged, packed, fields, } => { - if !packed || *tagged { + if (!packed && !soft) || *tagged { return Ok(None); } let mut names = Vec::new(); @@ -125,6 +127,7 @@ pub(in crate::ast) fn bind_in( jobs.push(Job::Aggregate { owner, union: *union, + soft: *soft, signed: data.signed.unwrap_or(false), names, ranges, @@ -169,6 +172,7 @@ pub(in crate::ast) fn bind_in( Job::Aggregate { owner, union, + soft, signed, names, ranges, @@ -180,7 +184,13 @@ pub(in crate::ast) fn bind_in( let fields = names.into_iter().zip(values.split_off(start)).collect(); let Some(ty) = packed_structs::native_type( &tree.state, - union, + if soft { + packed_structs::AggregateKind::SoftUnion + } else if union { + packed_structs::AggregateKind::HardUnion + } else { + packed_structs::AggregateKind::Struct + }, signed, owner, fields, diff --git a/crates/celox-sv-syntax/src/lexer.rs b/crates/celox-sv-syntax/src/lexer.rs index e31d0a1db31..fa03703681f 100644 --- a/crates/celox-sv-syntax/src/lexer.rs +++ b/crates/celox-sv-syntax/src/lexer.rs @@ -278,8 +278,12 @@ fn lex_with_context( "::", "+:", "-:", "~&", "~|", "~^", "^~", "->", "=>", "*>", "##", "@@", ":=", ":/", ".*", "(*", "*)", ]; + // `:` followed by a comment (`3'b0://`, `x:/*`) is not `:/`. + let comment_after_colon = source[at..].starts_with(":/") + && matches!(bytes.get(at + 2), Some(b'/' | b'*')); let length = OPERATORS .iter() + .filter(|op| !(comment_after_colon && **op == ":/")) .find(|op| source[at..].starts_with(**op)) .map_or(1, |op| op.len()); at += length; @@ -403,6 +407,20 @@ mod tests { } } + #[test] + fn colon_before_comment_is_not_dist_weight() { + let text = "3'b0://c\n3'b1:/*c*/ x :/ 2"; + let mut sources = SourceMap::default(); + let file = sources.add("colon.sv", text); + let tokens = lex(&sources, file).unwrap(); + let significant = tokens + .iter() + .filter(|token| !token.is_trivia()) + .map(|token| token.text.as_str()) + .collect::>(); + assert_eq!(significant, ["3'b0", ":", "3'b1", ":", "x", ":/", "2"]); + } + #[test] fn strings_and_longest_operators_preserve_lexical_boundaries() { let text = "\"continued\\\r\nstring\" \"continued\\\nstring\" \"\"\"multi\nline\"\"\" <<<= >>>= |-> |=> ->> <->"; diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index b52c7abebc2..4840e19a39f 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -183,6 +183,7 @@ pub enum DataTypeKind { TypeOf(ExprId), Struct { union: bool, + soft: bool, tagged: bool, packed: bool, fields: Vec, 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..f3729a98254 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2003,6 +2003,10 @@ fn datatype_contexts_reject_general_dimension_and_signing_grammar() { "struct signed {int x;}", "struct packed {int x;} unsigned", "struct tagged {int x;}", + "struct soft {int x;}", + "union soft signed {int x;}", + "union soft tagged {int x;}", + "union tagged soft {int x;}", "struct packed {}", "union {}", "enum real {A}", @@ -2036,6 +2040,8 @@ fn datatype_contexts_preserve_enum_ranges_and_aggregate_qualifiers() { "struct packed signed {logic[3:0] x;}", "union packed unsigned {int x; bit[31:0] y;}", "union tagged {int x; void nothing;}", + "union soft {int x; bit y;}", + "union soft packed signed {int x; bit y;}", "enum {A}", "enum int unsigned {A}", "enum logic [3:0] {A}", @@ -2245,6 +2251,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 +2715,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); diff --git a/crates/celox-sv-syntax/src/parser/types.rs b/crates/celox-sv-syntax/src/parser/types.rs index 5a0e1c38bd6..1d90a9287fb 100644 --- a/crates/celox-sv-syntax/src/parser/types.rs +++ b/crates/celox-sv-syntax/src/parser/types.rs @@ -4,6 +4,7 @@ use super::*; pub(super) struct Aggregate { start: usize, union: bool, + soft: bool, tagged: bool, packed: bool, signed: Option, @@ -166,7 +167,11 @@ impl Parser<'_> { if !union { self.expect("struct")?; } - let tagged = self.eat("tagged"); + let soft = self.eat("soft"); + if soft && !union { + return Err(self.error("only a union can be soft")); + } + let tagged = !soft && self.eat("tagged"); let packed = self.eat("packed"); let signed = self.signing(); if tagged && !union { @@ -179,6 +184,7 @@ impl Parser<'_> { jobs.push(Job::Type(TypeJob::StructNext(Aggregate { start, union, + soft, tagged, packed, signed, @@ -424,6 +430,7 @@ impl Parser<'_> { let Aggregate { start, union, + soft, tagged, packed, signed, @@ -434,6 +441,7 @@ impl Parser<'_> { start, kind: DataTypeKind::Struct { union, + soft, tagged, packed, fields, diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 518436a082f..6a96fd7d4de 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -695,3 +695,27 @@ Verilator 5.052 has two narrower exclusions, recorded in the The setter's formal is `bit` (18.8), so the required conversion truncates 2 to 0. Generated C++ confirms that Verilator uses 1. The normal 0/1 mode control, inline member selection and pre-hook control cases pass Verilator. + +## SystemVerilog packed unions + +The `unions` shared group covers hard and soft packed untagged unions. With +Verilator 5.052, `packed_overlay`, `soft_overlay`, and `soft_signed_ports` pass; +the two four-state cases report `unsupported` through the existing state-mode +check. + +Icarus 13.0 rejects `union soft` declarations in `soft_overlay`, +`soft_signed_ports`, and `soft_wide_four_state` during compilation. +`packed_overlay` passes. `packed_mixed_state` fails when reading a `bit` member +from mixed `logic`/`bit` union storage: for `8'b1010xxxx`, it returns +`8'b1010xxxx` instead of `8'b10100000`. A direct procedural probe reproduces +this independently of the shared harness; writing through the `bit` member +converts X to zero correctly. IEEE 1800-2023 7.3.1 requires conversion from +four-state to two-state when reading a two-state member. + +These cases remain enabled with their original assertions and no exclusions. +The [retained Icarus evidence](verification/sv/icarus/unions.json) records the +three compilation failures and the read mismatch with their exact diagnostics; +the full-suite gate accepts only those unchanged failures, never a passing +result in their place. Reproduce with `verify-sv-verilator` or +`verify-sv-icarus` and `--filter unions::`. Normal reports are written under +`target/sv-verilator/` and `target/sv-icarus/`. 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-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 8adeddf9279..66a5ad1db5a 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -7,6 +7,10 @@ pub(super) struct Group { } pub(super) const GROUPS: &[Group] = &[ + Group { + file: "src/sv/cases/unions.vtest", + text: include_str!("unions.vtest"), + }, Group { file: "src/sv/cases/real_extensions.vtest", text: include_str!("real_extensions.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/unions.vtest b/crates/celox-test-suite/src/sv/cases/unions.vtest new file mode 100644 index 00000000000..edb2f605c72 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/unions.vtest @@ -0,0 +1,146 @@ +(group unions (category types)) + +(case packed_overlay + (source "union.sv" #" +module Top(input bit clk, input logic [15:0] raw, input logic [3:0] nibble, + output logic [15:0] value, saved, output logic [7:0] low, + output logic signed [31:0] extended); + typedef union packed signed { + logic [15:0] bits; + struct packed { logic [7:0] hi, lo; } parts; + } overlay_t; + overlay_t data, stored; + always_comb begin + data.bits = raw; + data.parts.lo[3:0] = nibble; + end + always_ff @(posedge clk) stored <= data; + assign value = data.bits; + assign low = data.parts.lo; + assign extended = data; + assign saved = stored.parts; +endmodule +"#) + (top Top) + (for (r n) (list (0 15) (0xa53c 6) (0x7fff 0) (0xffff 1)) + (modify (set raw r) (set nibble n)) + (let expected (| (& r 0xfff0) n)) + (assert_eq value expected) + (assert_eq low (& expected 255)) + (if (& expected 0x8000) + (assert_eq extended (| expected 0xffff0000)) + (assert_eq extended expected)) + (tick clk) + (assert_eq saved expected))) + +(case soft_overlay + (source "soft_union.sv" #" +module Top(input bit clk, input logic [15:0] raw, input logic [3:0] nibble, + output logic [15:0] value, saved, output logic [7:0] low, + output logic [31:0] width); + typedef union soft packed { + logic [15:0] bits; + union soft { logic [7:0] byte_value; logic [3:0] nibble_value; } nested; + } overlay_t; + overlay_t data, stored; + always_comb begin + data.bits = raw; + data.nested.nibble_value = nibble; + end + always_ff @(posedge clk) begin + stored.bits <= raw; + stored.nested.nibble_value <= nibble; + end + assign value = data; + assign low = data.nested.byte_value; + assign saved = stored; + assign width = $bits(overlay_t); +endmodule +"#) + (top Top) + (assert_eq width 16) + (for (r n) (list (0 15) (0xa53c 6) (0x7fff 0) (0xffff 1)) + (modify (set raw r) (set nibble n)) + (let expected (| (& r 0xfff0) n)) + (assert_eq value expected) + (assert_eq low (& expected 255)) + (tick clk) + (assert_eq saved expected))) + +(case packed_mixed_state + (four_state) + (source "union_state.sv" #" +module Top(input logic [7:0] raw, output logic [7:0] four, two, written); + union packed { logic [7:0] four_value; bit [7:0] two_value; } data, clean; + assign data.four_value = raw; + assign clean.two_value = raw; + assign four = data.four_value; + assign two = data.two_value; + assign written = clean.four_value; +endmodule +"#) + (top Top) + (for (v m) (list (0xa5 0) (0xa5 0x0f) (0xff 0xff) (0 0xff)) + (modify (set raw (fourstate v m))) + (assert_eq four (fourstate v m)) + (assert_eq two (& v (^ m 255))) + (assert_eq written (& v (^ m 255))))) + +(case soft_wide_four_state + (four_state) + (source "soft_union_wide.sv" #" +module Top(input bit clk, input logic [129:0] raw, input logic [7:0] byte_value, + output logic [129:0] value, saved); + union soft { logic [129:0] wide; logic [7:0] narrow_value; } data, stored; + always_comb begin + data.wide = raw; + data.narrow_value = byte_value; + end + always_ff @(posedge clk) stored <= data; + assign value = data.wide; + assign saved = stored.wide; +endmodule +"#) + (top Top) + (for bit (list 0 7 8 63 64 127 128 129) + (let v (| (<< 1 bit) 0x5a)) + (let m (<< 1 bit)) + (modify (set raw (fourstate v m)) (set byte_value (fourstate 0xa5 0x0f))) + (let upper_mask (- (<< 1 130) 256)) + (let expected (fourstate (| (& v upper_mask) 0xa5) (| (& m upper_mask) 0x0f))) + (assert_eq value expected) + (tick clk) + (assert_eq saved expected))) + +(case soft_signed_ports + (source "soft_union_ports.sv" #" +package Types; + typedef union soft packed signed { + logic signed [3:0] nibble_value; + logic [7:0] byte_value; + } overlay_t; +endpackage +module Update(input Types::overlay_t incoming, input logic [3:0] nibble, + output Types::overlay_t outgoing); + always_comb begin + outgoing = incoming; + outgoing.nibble_value = nibble; + end +endmodule +module Top(input logic [7:0] raw, input logic [3:0] nibble, + output logic [15:0] extended, member_extended, + output logic [7:0] value); + Types::overlay_t incoming, outgoing; + assign incoming = raw; + Update update_value(.incoming(incoming), .nibble(nibble), .outgoing(outgoing)); + assign value = outgoing; + assign extended = outgoing; + assign member_extended = outgoing.nibble_value; +endmodule +"#) + (top Top) + (for (r n e me) (list (0xa5 6 0xffa6 6) (0x75 15 0x7f 0xffff) (0 8 8 0xfff8)) + (modify (set raw r) (set nibble n)) + (assert_eq value (& e 255)) + (assert_eq extended e) + (assert_eq member_extended me))) diff --git a/crates/celox-test-suite/tests/retained_reports.rs b/crates/celox-test-suite/tests/retained_reports.rs index 2f60a838b46..a071551e694 100644 --- a/crates/celox-test-suite/tests/retained_reports.rs +++ b/crates/celox-test-suite/tests/retained_reports.rs @@ -122,7 +122,7 @@ fn retained_reports_are_valid_historical_evidence_for_the_live_catalogue() { } #[test] -fn systemverilog_retained_reports_explain_every_recorded_exclusion() { +fn systemverilog_retained_reports_explain_exclusions_and_executed_failures() { let catalogue: BTreeSet<_> = celox_test_suite::sv::cases() .map(|case| case.name) .collect(); @@ -159,8 +159,8 @@ fn systemverilog_retained_reports_explain_every_recorded_exclusion() { let name = row["name"].as_str().unwrap(); let case = celox_test_suite::sv::case(name).unwrap(); let status = row["status"].as_str().unwrap(); - // Every case passes, is rejected as expected, needs four-state - // simulation the tool lacks, or has a reviewed exclusion. + // Reviewed failures stay executable and retain their diagnostics; + // they are distinct from exclusions and passing cases. match status { "passed" => { assert_eq!(case.expectation, celox_test_suite::Expectation::Simulation) @@ -186,6 +186,31 @@ fn systemverilog_retained_reports_explain_every_recorded_exclusion() { ); } } + "compile_error" | "mismatch" => { + assert_eq!(tool, "icarus", "{name}"); + let (expected_status, phase, diagnostic) = match name { + "unions::packed_mixed_state" => ( + "mismatch", + "execute", + "assert_eq two: expected 0xa0, got 0xaX", + ), + "unions::soft_overlay" + | "unions::soft_signed_ports" + | "unions::soft_wide_four_state" => { + ("compile_error", "compile", "syntax error") + } + _ => panic!("unreviewed failure: {tool} {name}: {status}"), + }; + assert_eq!(status, expected_status, "{name}"); + assert_eq!(row["phase"], phase, "{name}"); + assert!( + row["detail"].as_str().unwrap().contains(diagnostic), + "{name}" + ); + assert_eq!(case.expectation, celox_test_suite::Expectation::Simulation); + assert!(row.get("known_issue").is_none(), "{name}"); + assert!(celox_test_suite::sv::verification::known_issue(tool, name).is_none()); + } _ => panic!("{tool} {name}: {status}"), } } diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index da5488b278d..cca4d440665 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -17,7 +17,8 @@ "icarus/synthesizable.json", "icarus/system_functions.json", "icarus/timing.json", - "icarus/types.json" + "icarus/types.json", + "icarus/unions.json" ], "exclude_stronger_than_sv": false, "include_ignored": false, diff --git a/crates/celox-test-suite/verification/sv/icarus/unions.json b/crates/celox-test-suite/verification/sv/icarus/unions.json new file mode 100644 index 00000000000..555e15b3ba4 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/unions.json @@ -0,0 +1,59 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "unions::packed_mixed_state at 86:5: assert_eq two: expected 0xa0, got 0xaX", + "expectation": "Simulation", + "name": "unions::packed_mixed_state", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "unions::packed_overlay", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 10; see /build.log\n/source_0.sv:5: syntax error\n/source_0.sv:5: error: Syntax error in typedef clause.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Invalid module item.\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Invalid module item.\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "unions::soft_overlay", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:3: syntax error\n/source_0.sv:3: error: Syntax error in typedef clause.\n/source_0.sv:6: syntax error\nI give up.\n", + "expectation": "Simulation", + "name": "unions::soft_signed_ports", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n/source_0.sv:4: syntax error\n/source_0.sv:4: error: Invalid module item.\n", + "expectation": "Simulation", + "name": "unions::soft_wide_four_state", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} 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. 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" + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/unions.rs b/crates/celox/tests/frontends/systemverilog/unions.rs new file mode 100644 index 00000000000..724237db369 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/unions.rs @@ -0,0 +1,17 @@ +sv_backends! { + fn soft_signed_ports(sim) { + @case "unions::soft_signed_ports"; + } + fn packed_overlay(sim) { + @case "unions::packed_overlay"; + } + fn soft_overlay(sim) { + @case "unions::soft_overlay"; + } + fn packed_mixed_state(sim) { + @case "unions::packed_mixed_state"; + } + fn soft_wide_four_state(sim) { + @case "unions::soft_wide_four_state"; + } +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 52af4da8702..5edb5ce8c0b 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -237,3 +237,6 @@ mod floating_point; #[path = "frontends/systemverilog/real_extensions.rs"] mod real_extensions; + +#[path = "frontends/systemverilog/unions.rs"] +mod unions; diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 5aa24a66073..8daa10c3303 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -25,7 +25,7 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs and hard packed untagged unions, enums (with implicit values), `typedef`, unpacked arrays used as memories, signed and unsigned | +| Types | `logic`, `bit`, `reg`, packed vectors, multidimensional packed arrays with ascending or descending ranges and arbitrary constant bounds, packed structs, hard and soft packed untagged unions, enums (with implicit values), `typedef`, unpacked arrays used as memories, signed and unsigned | | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | @@ -184,7 +184,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: ([#427](https://github.com/celox-sim/celox/issues/427)), wildcard `.*` connections ([#442](https://github.com/celox-sim/celox/issues/442)), gate primitives ([#457](https://github.com/celox-sim/celox/issues/457)), `bind`. - Declarations: variable declaration initializers of members of an interface - array, ANSI port default values, tagged unions, soft packed unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), + array, ANSI port default values, tagged unions, unpacked unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), unpacked structs and `real`. - Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) in event lists, and in `always_ff` edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)), multi-bit @@ -369,10 +369,27 @@ parameters; recursive specializations and nesting beyond 64 levels are rejected. Block-local variables have lexical scope in `always_comb` and `always_ff`. Locals may shadow module signals and reuse names in separate blocks or processes. -### Hard packed untagged unions +### Packed untagged unions Hard packed untagged unions share one bit vector between all members; every member must have the same width (IEEE 1800-2023 7.3.1). +Soft packed unions (`union soft` or `union soft packed`) allow different member +widths. Their size is the largest member width, each member starts at the least +significant bit, and writing a smaller member preserves the remaining upper +bits. Nested packed unions and structures use the same layout rules. + +```systemverilog +union soft packed { + logic [15:0] word_value; + logic [7:0] byte_value; +} data; +// After data.word_value = 16'h1234, data.byte_value = 8'hab leaves data = 16'h12ab. +``` + +Whole-union operations use the declared signedness (unsigned by default). +Mixed `bit`/`logic` unions retain four-state storage, with X/Z converted to zero +when reading or writing a two-state member. Tagged and unpacked unions remain +unsupported. ### Named subroutine arguments diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index c2ec6c42dbe..304d2ff25a1 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -84,7 +84,9 @@ signedness, and mixed two-state/four-state member conversions follow IEEE This first structure extension supports constant in-range member selections. Arrays of structures with member access, dynamic or out-of-range member selections, struct-valued parameter member evaluation, assignment patterns, -unpacked structures, and unions remain unsupported. Member access on function +unpacked structures, and tagged/unpacked unions remain unsupported. +Hard and soft packed untagged unions share offset-zero member storage; soft +unions use the largest member width and preserve upper bits on narrower writes. Member access on function formals is also deferred. These forms must be diagnosed rather than silently lowered as accesses to the entire structure. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f49f8709926..cf956ea3325 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -24,7 +24,7 @@ outline: [2, 3] | 領域 | サポート内容 | | --- | --- | -| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard packed untagged union、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | +| 型 | `logic`、`bit`、`reg`、packed ベクタ、任意の定数境界と昇順・降順の多次元 packed 配列、packed 構造体、hard / soft packed untagged union、enum(暗黙値を含む)、`typedef`、メモリとして使う unpacked 配列、符号付き・符号なし | | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | @@ -164,7 +164,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、unpacked union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 - 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))、および `always_ff` での 単純な信号以外のエッジオペランド([#464](https://github.com/celox-sim/celox/issues/464))、複数ビットのエッジ信号、 非同期リセットを持たない複数のエッジ。 @@ -257,10 +257,27 @@ package が `p` から実際に import した名前だけです。export を経 ブロックローカル変数は、`always_comb` と `always_ff` で字句スコープを持ちます。 モジュールの信号と同名の変数や、別のブロック・プロセスでの同名変数を扱えます。 -### hard packed untagged union +### packed untagged union hard packed untagged union のメンバーは、同じビットベクタを共有します。 全メンバーの幅が一致する必要があります(IEEE 1800-2023 7.3.1)。 +`union soft` / `union soft packed` は幅の異なるメンバーを許容します。 +全体の幅は最大メンバーの幅となり、各メンバーは最下位ビットから配置されます。 +小さいメンバーへの書き込みでは残りの上位ビットを保持します。 +packed union と packed 構造体の入れ子にも対応します。 + +```systemverilog +union soft packed { + logic [15:0] word_value; + logic [7:0] byte_value; +} data; +// data.word_value = 16'h1234 の後で data.byte_value = 8'hab とすると data = 16'h12ab。 +``` + +union 全体の演算は宣言時の符号指定に従います(既定は unsigned)。 +`bit` / `logic` 混在時は 4-state の領域を共有し、2-state メンバーを +読み書きする際には X/Z を 0 に変換します。 +tagged union と unpacked union は未対応です。 ### 名前付きサブルーチン引数 diff --git a/scripts/check-external-suite-report.test.mjs b/scripts/check-external-suite-report.test.mjs index af96eddb62d..4013d41a552 100644 --- a/scripts/check-external-suite-report.test.mjs +++ b/scripts/check-external-suite-report.test.mjs @@ -271,10 +271,21 @@ test("all four retained baselines accept only their existing failures", () => { exitStatus, suite, ); - assert.equal( - result.accepted_failures.length, - suite === "sv" ? 0 : tool === "icarus" ? 11 : 2, - ); + if (suite === "sv") { + assert.deepEqual( + result.accepted_failures, + tool === "icarus" + ? [ + "unions::packed_mixed_state", + "unions::soft_overlay", + "unions::soft_signed_ports", + "unions::soft_wide_four_state", + ] + : [], + ); + } else { + assert.equal(result.accepted_failures.length, tool === "icarus" ? 11 : 2); + } } } });