Skip to content

fix(interp): repair tail-call and native store ownership - #182

Merged
siyul-park merged 6 commits into
mainfrom
fix/179-tailloop-ownership
Aug 9, 2026
Merged

siyul-park merged 6 commits into
mainfrom
fix/179-tailloop-ownership

Conversation

@siyul-park

@siyul-park siyul-park commented Aug 9, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes #179 across threaded and ARM64 JIT execution.

  • make ARRAY_SET/STRUCT_SET terminal exits obey the lowering contract
  • unify native stores on the fresh-register heap path
  • fix ref stores, including BoxedNull, and per-exit RC state
  • release retiring frame refs on threaded RETURN_CALL and JIT tail transitions
  • preserve returned refs before frame retirement
  • keep generated interpreter output in sync
  • simplify related JIT naming and remove obsolete store register-recycling state

Validation

  • go test -race ./interp
  • make generate
  • make check-generated
  • make lint
  • make fuzz
  • make benchmark-pr

The change was also repeatedly exercised against the ARM64 deferred-ref, self-call, hoisted-container, and native struct/array store regressions.

Closes #179.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reference cleanup during calls, tail calls, frame replacement, and stack updates.
    • Prevented accidental release of the permanent null reference.
    • Improved safety when updating array and structure values, including reference handling and bounds checks.
  • Performance

    • Expanded ARM64 native support for array and structure mutations.
    • Added graceful fallback to threaded execution when native register limits are exceeded.
  • Documentation

    • Clarified memory management, heap behavior, frame ownership, tail calls, and native mutation support.

@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@siyul-park, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 20 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0959872c-978a-457d-a3c2-729757e46760

📥 Commits

Reviewing files that changed from the base of the PR and between 9f437fa and fd96ee7.

📒 Files selected for processing (4)
  • docs/compatibility.md
  • docs/jit-internals.md
  • docs/memory-model.md
  • interp/jit_arm64.go
📝 Walkthrough

Walkthrough

The change updates ARM64 JIT reference ownership, tail-call frame replacement, guarded array and struct stores, register handling, interpreter stack cleanup, and related documentation and regression tests.

Changes

JIT ownership and mutation handling

Layer / File(s) Summary
Reference cleanup before frame reuse
internal/cmd/geninterp/lower.go, interp/threaded.go, interp/interp.go
Interpreter paths release overwritten boxed references before copying call parameters. Null references are not released.
Tail-call frame ownership and release
interp/jit_arm64.go, docs/architecture.md, docs/memory-model.md, docs/instruction-set.md, docs/jit-internals.md
Tail-loop and tail-morph paths initialize replacement frames and release retiring frames. Cleanup covers register-backed and VM-stack-backed references with refcount preflight checks.
Guarded array and struct stores
interp/jit_arm64.go, docs/compatibility.md, docs/instruction-set.md, docs/jit-internals.md
Native lowering supports guarded primitive and reference mutations for runtime arrays and structs. Reference stores remain terminal, and register exhaustion preserves threaded fallback.
Register and reference-counting support
interp/jit.go, interp/jit_arm64.go
Reusable-register state and helper variants are removed. Fresh registers and equality-aware release and retain helpers are used.
Ownership contracts and regression expectations
docs/*.md, interp/interp_test.go
Documentation records null-sentinel, tail-call, mutation, and no-spill rules. Regression tests require positive learned branch-hit counts.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RETURN_CALL
  participant ARM64JIT
  participant initLocals
  participant releaseFrame
  participant iterate
  RETURN_CALL->>ARM64JIT: lower tail call
  ARM64JIT->>initLocals: initialize replacement activation
  initLocals-->>ARM64JIT: transfer argument ownership
  ARM64JIT->>releaseFrame: release retiring activation
  releaseFrame-->>ARM64JIT: guarded reference cleanup
  ARM64JIT->>iterate: continue execution
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main fixes for tail-call ownership and native store handling.
Description check ✅ Passed The description provides the changes, related issue, validation, and additional context, although its headings differ from the template.
Linked Issues check ✅ Passed The changes address issue #179 by fixing tail-call ownership, frame cleanup, native store safety, and threaded/JIT parity.
Out of Scope Changes check ✅ Passed The code and documentation changes support the linked issue and stated objectives without identifiable unrelated work.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/179-tailloop-ownership

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (5)
interp/jit_arm64.go (3)

668-672: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Restore the single-expression form for STRUCT_GET.

STRUCT_GET still returns one result. Every other single-result case in this switch assigns directly to ok. The expanded form adds no behavior and breaks the local pattern.

♻️ Proposed simplification
 		case instr.STRUCT_GET:
-			if !l.structGet(ctx, op) {
-				return false, false
-			}
-			ok = true
+			ok = l.structGet(ctx, op)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@interp/jit_arm64.go` around lines 668 - 672, Update the STRUCT_GET case in
the instruction switch to assign the return value of structGet directly to ok,
preserving the existing single-result handling pattern and false-return
behavior.

2791-2805: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Reuse the masked address registers across the two loops.

Both loops emit the identical ANDI / CMPI / BEQ prologue and each allocates a fresh addr register per ref. For a frame with N ref locals that is 2N address registers plus N refcount registers.

Mutation plans are no-spill, and noSpillArch.Frame() returns nil, so register exhaustion rejects native compilation. Reusing the preflight addresses halves the pressure and removes the duplicated emission.

♻️ Proposed refactor
 	rcBase := l.rcBase(ctx)
 	// Preflight every owned ref before mutating any count. A later guard must
 	// deopt without leaving earlier native releases applied.
+	addrs := make([]asm.VReg, len(refs))
 	for i, ref := range refs {
 		skip := ctx.assembler.Label()
 		addr := ctx.assembler.Reg(asm.RegTypeInt, asm.Width64)
 		ctx.assembler.Emit(arm64.ANDI(addr, ref, maskI32), arm64.CMPI(addr, 0), arm64.BCondLabel(arm64.OpBEQ, skip))
 		l.guardRC(ctx, addr, rcBase, fail)
 		ctx.assembler.Bind(skip)
+		addrs[i] = addr
 	}
-	for _, ref := range refs {
+	for _, addr := range addrs {
 		skip := ctx.assembler.Label()
-		addr := ctx.assembler.Reg(asm.RegTypeInt, asm.Width64)
-		ctx.assembler.Emit(arm64.ANDI(addr, ref, maskI32), arm64.CMPI(addr, 0), arm64.BCondLabel(arm64.OpBEQ, skip))
+		ctx.assembler.Emit(arm64.CMPI(addr, 0), arm64.BCondLabel(arm64.OpBEQ, skip))
 		rc := ctx.assembler.Reg(asm.RegTypeInt, asm.Width64)
 		ctx.assembler.Emit(arm64.LDRR(rc, rcBase, addr), arm64.SUBI(rc, rc, 1), arm64.STRR(rc, rcBase, addr))
 		ctx.assembler.Bind(skip)
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@interp/jit_arm64.go` around lines 2791 - 2805, Update the two ref-processing
loops in the surrounding function to compute each masked address once and reuse
it in the refcount guard and decrement phases. Retain the existing skip behavior
and refcount operations, but store the per-ref address registers from the first
loop for use in the second, eliminating the duplicated ANDI/CMPI/BEQ emission
and fresh addr allocations.

3369-3373: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Move own after the sideExit allocations.

arraySet calls l.own at Line 3370 and structSet calls it at Line 3561. Both run before the sideExit calls that can return false. own mutates ctx.values[len-1].backing and emits a retain.

The lowerer contract requires a false return to leave the stack, facts, and labels unmutated. A rejected build discards the lowering context, so there is no runtime effect today. The ordering still breaks the stated contract and is fragile against future reuse of a partially lowered context.

Allocate the exits first, then own the value, then take pre.

As per coding guidelines: "on type mismatch or unsupported lowering, return false without mutating IR, stack, parameters, facts, or labels".

Also applies to: 3560-3564

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@interp/jit_arm64.go` around lines 3369 - 3373, Reorder the lowering steps in
arraySet and structSet so all sideExit allocations complete before calling own
on the reference value. After successful exit allocation, invoke own, then
capture pre, ensuring any false return from sideExit leaves the lowering context
and emitted retain unchanged.

Source: Coding guidelines

docs/jit-internals.md (1)

457-457: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Separate the store sentence from the reads list.

Line 457 begins with the list of native full-trace reads, then appends ARRAY_SET and STRUCT_SET, which are stores. Lines 465-469 already own the store rules. Move the store sentence there so the reads paragraph stays about reads.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/jit-internals.md` at line 457, In the native full-trace paragraph,
remove the ARRAY_SET and STRUCT_SET store sentence so the reads list contains
only read operations. Add that sentence to the existing store-rules section
around lines 465-469, preserving its wording and the documented guarded
fresh-register heap behavior.
docs/architecture.md (1)

138-143: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Merge the duplicated null-sentinel bullet.

Line 138 already states that heap index 0 is permanently Null. Line 143 repeats it and adds only "never reclaimed". Combine the two bullets to keep the invariant list terse.

♻️ Proposed consolidation
-- Heap index `0` is permanently `Null`.
+- Heap index `0` is permanently `Null` and is never reclaimed.
 - Only `KindRef` values participate in reference counting.
 - Heap indices are stable and must not move.
 - Values that contain refs must implement `types.Traceable`.
 - Large `i64` values may spill to the heap while preserving bytecode semantics.
-- Heap index 0 is a permanent null sentinel and is never reclaimed.

As per coding guidelines: "keep edits terse, factual, current, and correctly formatted".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/architecture.md` around lines 138 - 143, Consolidate the two heap index
0 bullets in the invariant list: retain a single statement that identifies it as
the permanent Null sentinel and includes that it is never reclaimed. Remove the
duplicate bullet while preserving the remaining invariants and formatting.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/compatibility.md`:
- Around line 43-46: Update the ARM64 mutation-lowering paragraph to state that
primitive STRUCT_SET stores continue tracing, while reference-field STRUCT_SET
operations report a terminal status; retain the existing description of guarded
fresh-register stores and threaded fallback.

In `@interp/jit_arm64.go`:
- Around line 2521-2530: The frame-retirement paths emit ownership retains
before releaseFrame’s deoptimization preflight, allowing retains to be repeated
after a side exit. In interp/jit_arm64.go:2521-2530 (tailLoop), 2560-2569
(tailMorph), 2707 (stitch), and 2732 (ret), move the releaseFrame preflight
guard before initLocals or l.own retains; in tailMorph preserve f.base ==
old.base so retiring values remain on the VM stack during release.
- Around line 903-905: Fix self-store retain accounting in interp/jit_arm64.go
at localSet (903-905), globalSet (1002-1004), upvalSet (2990), arraySet
(3427-3434), and structSet (3613-3620): consuming stores must release the
overwritten value even when it equals the stored value. In localSet and
globalSet, retain the release for pop=true and skip the release/retain pair only
for TEE; in upvalSet, use unconditional releaseBox; apply unconditional release
of the overwritten element or field in arraySet and structSet.
- Around line 2788-2805: Update the release logic around guardRC and the two
refs loops to account for duplicate addresses: aggregate pending releases per
address and deopt when the current reference count cannot safely cover all
decrements, including the rc == 2 case with two frame refs. Preserve the
preflight-before-mutation ordering and only emit native decrements when every
address has sufficient remaining count.

---

Nitpick comments:
In `@docs/architecture.md`:
- Around line 138-143: Consolidate the two heap index 0 bullets in the invariant
list: retain a single statement that identifies it as the permanent Null
sentinel and includes that it is never reclaimed. Remove the duplicate bullet
while preserving the remaining invariants and formatting.

In `@docs/jit-internals.md`:
- Line 457: In the native full-trace paragraph, remove the ARRAY_SET and
STRUCT_SET store sentence so the reads list contains only read operations. Add
that sentence to the existing store-rules section around lines 465-469,
preserving its wording and the documented guarded fresh-register heap behavior.

In `@interp/jit_arm64.go`:
- Around line 668-672: Update the STRUCT_GET case in the instruction switch to
assign the return value of structGet directly to ok, preserving the existing
single-result handling pattern and false-return behavior.
- Around line 2791-2805: Update the two ref-processing loops in the surrounding
function to compute each masked address once and reuse it in the refcount guard
and decrement phases. Retain the existing skip behavior and refcount operations,
but store the per-ref address registers from the first loop for use in the
second, eliminating the duplicated ANDI/CMPI/BEQ emission and fresh addr
allocations.
- Around line 3369-3373: Reorder the lowering steps in arraySet and structSet so
all sideExit allocations complete before calling own on the reference value.
After successful exit allocation, invoke own, then capture pre, ensuring any
false return from sideExit leaves the lowering context and emitted retain
unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 97d13dfa-4e77-4fe4-be93-b8ab3d51cee0

📥 Commits

Reviewing files that changed from the base of the PR and between 610d72b and 9f437fa.

📒 Files selected for processing (11)
  • docs/architecture.md
  • docs/compatibility.md
  • docs/instruction-set.md
  • docs/jit-internals.md
  • docs/memory-model.md
  • internal/cmd/geninterp/lower.go
  • interp/interp.go
  • interp/interp_test.go
  • interp/jit.go
  • interp/jit_arm64.go
  • interp/threaded.go

Comment thread docs/compatibility.md Resolved
Comment thread interp/jit_arm64.go Resolved
Comment thread interp/jit_arm64.go Resolved
Comment thread interp/jit_arm64.go Resolved

Copy link
Copy Markdown
Owner Author

Addressed the review findings in e42a9d9.

  • Store ownership is now guarded before any retain can make a later side exit repeat ownership. Deferred self-stores release the overwritten value; equal backingStack stores preserve the existing destination ownership.
  • Frame teardown now separates preflight (guardFrame) from mutation (releaseFrame). Duplicate runtime addresses are counted together, so native teardown deopts when one address cannot cover all pending releases.
  • tailLoop, tailMorph, stitch, and ret all preflight before acquiring replacement/return ownership.
  • Compatibility, JIT internals, and memory-model docs now describe the terminal store boundary and frame-release ordering.

Validation: go test ./interp, go test -race ./interp, make test, make lint, make generate, make check-generated, make benchmark-pr, and make fuzz pass. make benchmark-core is running separately and has passed all completed packages so far.

@siyul-park
siyul-park merged commit 4d3ba6c into main Aug 9, 2026
3 checks passed
@siyul-park
siyul-park deleted the fix/179-tailloop-ownership branch August 9, 2026 14:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ARM64 JIT: deferred refcount imbalance through self tail call

1 participant