Repository navigation
feat(sv): support hierarchical references - #1893
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a993e8b834
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if foreign_writes.contains(signal.name()) { | ||
| if !drivers.is_empty() { | ||
| memories.insert(signal.name().into()); |
There was a problem hiding this comment.
Preserve foreign writes to packed variables during FF commits
When another instance writes a packed variable that also has an edge-triggered writer, this protection is never applied because the enclosing loop only visits unpacked arrays. The ordinary FF path still seeds and commits the entire potentially written range (Ff::lower_process and emit_ff_commits), rather than only the bits actually assigned. For example, with a child executing q[idx] <= 1'b1 where idx is 7, a parent executing child.q[0] = 1'b1 on the same edge loses its update when the child's whole-vector NBA commit runs. These assignments affect different bits and should both survive. Extend the foreign-writer handling to packed variables with conditional or dynamic-select edge writes, rather than leaving them on the unconditional seed/commit path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: with a #0 foreign bit write next to q[idx] <= 1'b1 Icarus prints 81 and Celox printed 80. Writers through hierarchical names now go through the module's own driver checks: two repeating writers of a variable that is not a shared memory are rejected ("multiple variable drivers for q, which another module writes through a hierarchical name: another process writes it too"), as the same two processes inside one module are. An initial-only foreign write is allowed. It lands in the window before the NBA region, so the variable joins kernel_window_writes and the bit write updates only its bit (shared case foreign_inactive_writes_precede_nonblocking_bit_writes, 81). Fixed in 8d425ec.
| .get(at + 1) | ||
| .is_some_and(|token| token.kind == TokenKind::Number) | ||
| && text(at + 2) == Some("]") | ||
| && text(at + 3) == Some(".") | ||
| && let Ok(index) = text(at + 1).unwrap().replace('_', "").parse::<u64>() |
There was a problem hiding this comment.
Evaluate constant expressions in hierarchical instance indices
For an instance-array reference such as cells[IDX].value with localparam IDX = 1, the analyzer already evaluates the index and requests the normalized hierarchical name cells[1].value, but this scanner only recognizes a single decimal-number token between brackets. Consequently it never supplies that binding, and the second analysis still fails with an unresolved hierarchical reference. Based literals such as cells[1'b1].value fail for the same reason. Extract and evaluate these constant indices using the specialization's constant environment so ordinary constant-expression spellings reach the same instance as the supported decimal spelling.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed (cells[IDX].value failed to resolve). When the analysis reports a name the token scan did not resolve, the frontend resolves it from the normalized path, with constant indices evaluated, and analyzes again. Shared case names_instance_array_elements_by_constant_expressions. Fixed in 8d425ec.
| .iter() | ||
| .find(|candidate| candidate.name() == module.name) | ||
| .ok_or_else(|| sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)))?; | ||
| hierarchy::ElaboratedModule::from_declarations(specialized) |
There was a problem hiding this comment.
Propagate force targets during declarations-only elaboration
When a module contains a hierarchical reference and SignalAccessOptions.force_signals names a signal below that module, the declarations-only fallback builds its children through lower_instances, which initializes every child's force_signals to an empty list. Unlike specialize_module, this path never propagates key.force_signals to those children. The BFS therefore registers unforced child specialization keys, but the final lowering produces forced child keys, and validate_sv_module_graph rejects them because they are absent from module_ids. For example, a top module that reads c.v cannot be built with the force target Top.c.q. Apply the same child-force propagation in both elaboration paths before registering specialization keys.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. The declarations-only specialization now carries the force targets (propagate_force_signals). Test forced_targets_of_hierarchical_names_stay_forceable. Fixed in 8d425ec.
| let analyzed = &hierarchy.analyzed[&hierarchy.keys[&module].name]; | ||
| let elaborated = &hierarchy.elaborated[&module]; | ||
| let mut references: Vec<HierarchicalReference> = Vec::new(); | ||
| for components in analyzed.source.hierarchical_names(&analyzed.name) { |
There was a problem hiding this comment.
Scan the authored module behind generic-interface specializations
For a module with a generic interface port, interface planning creates a cloned module name using clone_module_name, while ParsedSource indexes syntax scopes under the original authored name. Passing analyzed.name here therefore makes hierarchical_names return an empty list for that specialization. A module such as Leaf(interface bus) containing a downward read of c.v consequently reaches the declarations-only fallback but never receives a binding, so its final analysis fails with an unresolved hierarchical reference. Resolve the interface plan's original module name before scanning, as Source::from_indexed_syntax_module already does when analyzing these specializations.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. The scan now uses the authored module's scopes (Packages::authored_module_name). Test names_resolve_below_instances_with_interface_ports. Fixed in 8d425ec.
| AbsoluteAddr { | ||
| instance_id: target_instance, | ||
| var_id: binding.var_id, |
There was a problem hiding this comment.
Apply folded hierarchical initials after target declarations
When a parent's constant initial assignment is folded by lower_initial_processes, this binding redirects its initial-state write to the child, but assembly still concatenates each module's initial_memory_values in instance-ID order, with the parent before its children. The child's default value and declaration initializer therefore overwrite the parent's procedural assignment before simulation starts. For example, Child c(); initial c.v = 8'd5; with logic [7:0] v = 8'd0; in Child leaves c.v at zero instead of five when a separate delayed process observes it. Assemble all declaration/default writes before folded procedural initial writes, or retain these hierarchical assignments as runtime processes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: initial c.v = 5 against logic [7:0] v = 0 printed 0. Initial values written through bindings are now applied after the declaration initializers (IEEE 1800-2023 6.8). Shared case initial_writes_through_names_follow_declaration_initializers. Fixed in 8d425ec.
|
Queued — the merge queue status continues in this comment ↓. |
e660bf9 to
180120f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 180120fd2f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| written_names(stmts, names); | ||
| let mut calls = Vec::new(); | ||
| for stmt in stmts { | ||
| stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); |
There was a problem hiding this comment.
Respect argument directions when collecting foreign writes
When a task receives a hierarchical signal through an input argument, this helper incorrectly classifies the argument as written: written_names adds every identifier in every Stmt::Call argument without checking parameter directions. For example, passing c.n to a read-only task causes validate_specialized_instance_net_drivers to reject the design as a driver of a net through a hierarchical name; passing a continuously driven variable similarly triggers the foreign-driver rejection. Inspect the callee's parameter directions, as DriverScan::body already does, rather than treating input arguments as assignment targets.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: show(c.n) with an input argument was rejected as a net driver. Writes are now collected by the direction-aware walker that kernel_written_names already uses: written arguments only, through called subroutines, plus $readmem destinations. Shared case input_arguments_read_through_hierarchical_names. Fixed in 8d425ec.
| let mut written = HashSet::default(); | ||
| procedural::written_names_with_calls(module, process.body(), &mut written); | ||
| hierarchical.any(|signal| written.contains(signal.name())) |
There was a problem hiding this comment.
Preserve blocking-write visibility through hierarchical aliases
When an edge process writes a local variable with a blocking assignment and then reads the same object through a hierarchical name, this predicate leaves it on the ordinary FF path because the hierarchical alias is only read. For example, with q initially zero, always @(posedge clk) begin q = 8'd1; r <= Top.q; end in Top assigns zero to r on the first edge instead of one. Ff::lower_slt selects the working region by local SourceVarId, so the distinct alias reads stable state; assembly's later binding preserves that region. Canonicalize aliases before FF lowering or route these blocking-write/alias-read processes through the process kernel too.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: always @(posedge clk) begin q = 1; r <= Top.q; end gave 0 (Icarus/Verilator 1). A name that starts at the module's own name and names no instance now denotes the module's own signal (IEEE 1800-2023 23.8), so there is no alias left to read stale state from. The analyzer maps the path to the local declaration (HierarchicalSignal::local). Every other name denotes another instance, so it cannot alias a variable of the same process. Shared case names_from_the_module_name_denote_its_own_signals covers always and always_ff. Fixed in 8d425ec.
| for components in analyzed | ||
| .source | ||
| .hierarchical_names(&analyzed.name, &analyzed.packages) | ||
| { | ||
| resolve_name(hierarchy, module, &components, &mut references)?; |
There was a problem hiding this comment.
Resolve only hierarchical names used by active generate branches
When a module has an active hierarchical reference, this eager pass also resolves names from inactive generate branches because hierarchical_names scans the entire authored token range. For example, with C declaring bit v and real r, a Top containing initial $display(c.v); and if (0) begin initial $display(c.r); end fails: resolving the inactive c.r reaches resolved_type and returns an unsupported-type error before reanalysis can discard that branch. The existing generate elaborator explicitly lowers only the selected branch. Resolve names requested by specialized analysis, or filter these candidates through active elaboration before allowing resolution errors to reject the design.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed. The eager scan no longer turns resolution errors into rejections. A name the specialized analysis actually uses comes back through resolve_name and reports its error there, so names in inactive generate branches are ignored. Shared case names_in_inactive_generate_branches_are_ignored. Fixed in 8d425ec.
| if components[0] == self.keys[&module].name { | ||
| return self.walk(module, components, 1); |
There was a problem hiding this comment.
Match authored module names in interface-specialized hierarchies
For a module with a generic interface port, this comparison uses the interface-specialized clone name rather than the authored module name. Thus module Leaf(interface bus); bit q = 1; initial $display(Leaf.q); endmodule cannot resolve its otherwise-supported self-qualified reference, and a child referring upward to Leaf.q fails for the same reason. Although hierarchical_names now restores plan.original when scanning, the downstream name comparisons here and in resolve_name still use key.name; this is separate evidence beyond the previously fixed scanner lookup. Use the interface plan's original name when matching module-name components.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: Leaf.q inside an interface-specialized Leaf did not resolve. Module-name components are now matched against the authored name, both downward and upward and in the diagnostics. Extended names_resolve_below_instances_with_interface_ports with Leaf.q. Fixed in 8d425ec.
| Some(sv::ast::Type::resolved( | ||
| kind, | ||
| r#type.is_signed(), | ||
| &packed, | ||
| &unpacked, |
There was a problem hiding this comment.
Preserve signed element types when reconstructing hierarchical types
When the target is a packed array of a signed typedef, reconstructing its type from only the overall signedness and ranges loses signed_element_depth. For example, if a child declares typedef logic signed [3:0] nibble_t; nibble_t [1:0] a = 8'h80;, assigning c.a[1] to a 16-bit result produces 16'h0008 instead of 16'hfff8. The whole array is unsigned, but its selected typedef element is signed; the ordinary analyzer preserves this distinction through selects_signed_element, whereas Type::resolved initializes that metadata to None. Carry the target's signed-element metadata through elaboration and into the synthesized hierarchical signal type.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: c.a[1] gave 0008 (Icarus/Verilator fff8). ir::Type now keeps signed_element_depth, and ast::Type::resolved takes it, so the hierarchical signal's dimensions select signed elements as the declaration does. Shared case signed_elements_through_hierarchical_names. Fixed in 8d425ec.
180120f to
745ae21
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 745ae21797
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } else if starts_at_instance(elaborated, components) | ||
| || components[0] == hierarchy.keys[&module].name | ||
| { | ||
| hierarchy | ||
| .downward(module, components)? |
There was a problem hiding this comment.
Resolve hierarchical names relative to their generate scope
When a hierarchical reference is written inside a generate block, resolution starts at the containing module rather than the reference's lexical scope. For example, if (1) begin : g C u(); initial $display(u.q); end elaborates the instance as g.u, but both the token scanner and the analyzer request u.q; this lookup cannot find g.u, so final analysis rejects the reference as unresolved. If a module-level u also exists, it can instead bind to the wrong instance. Preserve the reference's generate scope and search it before searching enclosing scopes.
Useful? React with 👍 / 👎.
| .entry(*target_module) | ||
| .or_default() | ||
| .entry(target.clone()) | ||
| .or_default(); | ||
| entry.repeating += usize::from(repeating); |
There was a problem hiding this comment.
Count foreign writers per target instance, not specialization
When a process writes signals in two instances of the same specialization, their distinct objects are merged into the same (ModuleId, signal name) entry and each reference increments its writer count. For example, with module C; bit q; endmodule, a parent containing C a(), b(); and always @(posedge clk) begin a.q = 1; b.q = 0; end produces repeating == 2 for C.q. Consequently, validate_foreign_drivers rejects the design with “another process writes it too”, although each object has exactly one writer. Preserve target-instance identity when counting writers so writes to separate instances do not become competing drivers.
Useful? React with 👍 / 👎.
745ae21 to
8d425ec
Compare
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Resolve hierarchical names (IEEE 1800-2023 23.6, 23.8) against the elaborated hierarchy: reads of nets and variables of other instances and procedural writes of their variables, including selects of unpacked array elements, through names that start at an instance of the module, at the module's own name, at an enclosing module's name or at `$root`. The analyzer works on one specialization at a time. A module whose analysis meets a dotted name it cannot bind is first elaborated from its declarations, so the hierarchy below it can be specialized. The frontend then follows each of its dotted names through the specialized instances to a signal and analyzes the module again with a local signal of that type for each name. `SimModule::hierarchical_bindings` binds the local signal, per instance, to the object of the instance it denotes, like package variables, so every later analysis sees one object. Designs without hierarchical names take the same path as before. A signal written through a hierarchical name gains writers outside its module, which its module's driver checks count as its own (IEEE 1800-2023 6.5, 9.2.2.2, 9.2.2.4): a continuous or always_comb driver, or an always_ff writer, next to a write through a name is rejected, and so are two repeating writers of a variable other than a memory with edge writers, which takes the shared-memory NBA path. Such arrays keep whole-array commits, their variables join the writes that may land before the NBA region, and the variables a name reaches stay watchable for the imperative always_comb alternative. An edge `always` that writes through a name runs as a process, and a hierarchically named edge event is sensed on a copy. Continuous drivers of variables and any driver of a net through a hierarchical name are rejected by name. Change-Id: I09a93d48d51198e452dd9b47e9ab240dba7c9241
8d425ec to
3a78c7e
Compare
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Merge Queue Status
This pull request spent 36 minutes 21 seconds in the queue, including 34 minutes 7 seconds running CI. Required conditions to merge
|
Closes #1856 (language support; the C906 acceptance run is blocked by #426, see below).
What
Hierarchical references (IEEE 1800-2023 23.6, 23.8) in the SystemVerilog frontend:
tb.x_soc.u.ram0.mem[i][7:0] = 8'h0);g[1].uand array elementsu[3]), at the module's own name (tb.x_soc...insidetb), at an enclosing module's name (upward, 23.8) or at$root;always @(posedge $root.tb.clk)).Rejected by name: continuous assignments to a variable and any driver of a net through a hierarchical name; writes through a name that the module's own driver rules would not allow if the writer were local (IEEE 1800-2023 6.5, 9.2.2.2, 9.2.2.4): next to a continuous/always_comb driver or an always_ff writer, or a second repeating writer of a variable that is not a shared memory; names in port connections, names of subroutines/blocks/parameters/struct members of another scope,
real/string/class signals, and upward names that denote different relative objects from different instances of one module.How
Resolution is static; there is no run-time lookup.
AnalyzerError::HierarchicalReference.ParsedSource::analyze_module_hierarchy), so the hierarchy below it is specialized as usual.lowering/hierarchy.rsscans the module's dotted names (ParsedSource::hierarchical_names) and follows each through the specialized instances to a signal. The module is analyzed again with a local signal of that type per name (analyze_module_with_hierarchy; the names bind through the same path map as interface members).SimModule::hierarchical_bindingsbinds the local signal, per instance, to the target instance's object.PackageBindings(assembly) locates it there like a package variable. Comb scheduling, FF/process relocation, clock domains, DSE roots and NBA site analysis therefore all see one object at design level. The local signal has no state or initial value of its own.Writers outside a module:
alwaysthat writes through a hierarchical name runs as a process, so its blocking store lands immediately rather than in a second seed/commit of the same object.edge_only_memories, perf(sv): publish only written elements of nonblocking array writes #1869), every variable written through a name joinskernel_window_writes(fix(sv): keep other processes' writes made before an edge's NBA region #1884), and the variables a name reaches seed the watchable set for the imperative always_comb alternative (perf(sv): skip the always_comb alternative nothing can watch #1859).Relation to #1855/#1864: once #1855 makes the shared-memory commit exact, foreign writes keep riding on that path; nothing here duplicates its mask work. The shared-suite cases below cover the interleavings. #1865 (the always_ff overlap diagnostic should count foreign writers) is not in scope.
Validation
hierarchical_references(17 cases: downward reads, memory element writes, instance arrays/generate scopes, upward names, foreign writes interleaved with NBA element writes, mutual writes, same-element bit writes, constant-expression indices, initial order, parameterized upward parents, subroutine writes, inactive-region writes before an NBA bit write, waits that see intermediate always_comb writes, input arguments, names from the module's own name, inactive generate branches, and signed typedef elements).verify-sv-icarus17/17;verify-sv-verilator16/16 plus one reviewed exclusion (the intermediate-write case joinssv_verilator_intermediate_writes, with a standalone probe: Verilator n=2, Icarus n=3). Expected outputs were cross-checked with xezim where it conforms (xezim 0.11.3 gives 80 for the inactive-region case; IEEE 4.4.2.3/10.4.2 and Icarus give 81).$root, a module with interface ports, forced targets, and the rejection diagnostics.cargo nextest run -p celox -p celox-sv-analyzer -p celox-frontend-sv -p celox-frontend-core -p celox-test-suite --features celox/systemverilog: 15362 passed.retained_reportspasses; the sv-tests official runner reproducesexpected.tsvexactly. Clippy (workspace, all targets) and fmt are clean.Performance
Designs without hierarchical names are unaffected. Callgrind, release profile,
b2_vm_dispatch_bit.sv(200k cycles), master c430061 vs this branch:SimulationState::step_until, inclusive)The cost is per referenced signal: one bound local variable, plus re-analysis of only the modules that contain hierarchical names.
C906
With this PR, rtlmeter's unmodified C906
tbanalyzes, and its references resolve. The next blocker is unrelated: 277 of C906's 289 modules use non-ANSI port declarations, which the frontend rejects (#426). That's next, as a separate PR.