Skip to content

perf(comp): a wide def's boxed record stays boxed until a use needs it - #2036

Merged
nicolas-abril merged 2 commits into
bendlang:mainfrom
nicolas-abril:perf/wide-node-codegen
Nov 4, 2026
Merged

nicolas-abril merged 2 commits into
bendlang:mainfrom
nicolas-abril:perf/wide-node-codegen

Conversation

@nicolas-abril

@nicolas-abril nicolas-abril commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

A def whose parameters span past WIDE words takes its wide records boxed, but binding a parameter opened it to its flat words at once. sum4 in compile/record_wide_node unpacked all four 64-word records on entry, so sum4_j0, the join after its first fork, took the two still-unread records as 128 registers. The widest segment sets WL_BANK and every segment takes the whole bank, so the file had 131 registers; clang -O3 spent most of its time in Branch Probability Basic Block Placement and the Control Flow Optimizer (-ftime-report). The volume of unrolled word moves does not matter: folding them into loops cut the C by 21% and changed no clang time.

The change (second commit)

Wide parameters bind boxed. A parameter that arrives boxed, whose type is more than one word with no box words, and that its def's own segment binds now binds boxed; val_to opens it where a use needs the words, and an unread one drops with one term_sink.

  • A type with box words still opens on entry. Opened at a call, its fields would be fresh values, and passing them to a callee that borrows them (emit_args) would make that callee an owner for every caller in the program.
  • Closures (whose arguments always arrive boxed), continuation segments and inlined calls bind as before.

A lazy binding read again stays boxed. A read that needs its words peeks them (term_peek, as for a borrowed root); a read that takes it whole shares the node as before. Main took a reference (term_keep) at every read, which marked its types shared and sealed their words at every construction in the program (one program went from 1 rfc_seal site to 257), and opened the node again at every use. Since the binding's words never change:

  • a fork's stack frame and its join keep the words they took at the fork, on any thread count;
  • a closure capturing it shares the node;
  • a later read that lends it to a borrowing callee lends the node itself. An earlier version of this PR opened the binding at its first read instead; that held its words in registers, rebuilt the node for a later borrowing callee (making that callee an owner for every caller: rfc_seal sites 73 → 137 in the new test), and needed a flag to keep a fork's later calls from opening it.

A match on a lazy record reads it in place. One dispatch on the node's tag, taking only the fields its arm reads, instead of copying every field through a chain on the tag and switching again on the copy. In record_deep_boxed, matching a nested record took apart all eight sub-nodes; now it takes the one its arm reads and sinks the rest.

Closures and continuations bind lazy parameters boxed too, which the earlier version excluded: with the binding's words fixed, nothing ties the rule to the def's own segment.

Numbers (Apple M-series, clang -O3, best of 2; on main after #2033)

test registers C node opens (ctr_take) clang
compile_record_wide_node 131 → 65 194 → 167 KB 9 → 13 1.14 → 0.31 s
compile_record_deep_boxed 3 → 3 229 → 181 KB 221 → 81
compile_closure_record_shared 3 → 3 79 KB 4 → 2 term_keep 4 → 3, rfc_seal 3 → 1

24 more tests' C changes (check_do_bind_desugar, 18 io tests, run_family_arg_hot, run_family_field_hot, run_list_rebox_generic_sum, run_list_rebox_sum, run_rle_roundtrip): none larger, none with more registers, node opens, references or seals; most lose node opens (io_chan_rendezvous 9 → 3, io_chan_try_wake_timers 10 → 5). Every bench in bench/runtime emits byte-identical C and JS, so the perf gate cannot move.

Room under the cap (first commit)

comp.ts was over its 66,000 cap with this change, so the first commit makes fifteen simplifications with no output change (every test's and bench's C and JS byte-identical, checked on its own against main):

  • file_push indents through seg_text, which already does it;
  • fact_when asks fact() instead of rebuilding its key for the same lookup;
  • let_live and emit_clo count uses with rest_use, as arm_self does, so term_use, a one-line wrapper with no other caller, folds into it;
  • c_ids drops a !k that can't be true when p is set (both groups exist only in the regex's last alternative, and k needs a character);
  • emit_args returns v instead of a copy that only reset stat, which none of its results' readers looks at;
  • js_expr folds a non-Ref head into the call_eta fallback, as emit_expr already does;
  • emit_intr converts and owns each argument in one pass, then aliases;
  • op_bare reads FL.js instead of a js flag its two callers set to it;
  • emit_fork names the continuation's fid once instead of three times;
  • js_text takes a String literal's text as it is: lit_of only builds one from valid code points, on which char_new is String.fromCodePoint;
  • lay_eq drops its arms test: a lay without arms is W32, W64 or BOX, so the words or the arm keys already differ;
  • call_eta drops its Def test: fun_of gives a non-Def no live parameters;
  • loop_of leaves a bodiless callee to visit, which already skips it;
  • ctr_flds takes the constructor term: all five callers passed its own k and fields;
  • emit_ctr's word branch drops vs.length === 1: only U32 and F32 reach it, Base's own, whose one field is data.

Checks

  • On the branch merged onto main 4024f04: repo 54/54, test 1829/1829, perf 124/124, ping 81/83 (main's own run fails the same two BendHub publish checks against the local site checkout); comp.ts is 65,988 ttok (cap 66,000).
  • Every C-lane test (1,012) was built and run with +RTS --threads 1 as well as the default on the earlier version: none passed one way and failed the other. The 25 tests whose C changed since then were run both ways again and print their expected output.
  • The changed tests and the probes (a wide record holding a list passed to a borrowing callee, a constant fold that adds a read, a wide sum matched on its tag, a boxed record a closure captures and uses after, a closure's 2-word record read first by a later fork call, a closure's W stored by one read and lent to a wide callee by two, a wide record read and then lent) print the same on C, C with one thread, and JS as on main. In the read-then-lent case the callee keeps borrowing: the lender peeks and lends with no node open or rebuild.

compile/record_wide_boxed_params is new and covers those paths: wide records matched in place, passed back whole, dropped unread, threaded through a 1000-step loop, read twice, a sum matched on its tag, a read a constant fold adds, a record holding a list passed to a borrowing callee, a wide callee that borrows a closure's W around a read that stores it, a wide record read and then lent (lend), a boxed record a closure captures and uses after, and a 4096-leaf fork tree, wide enough that some of its forks run in sequence on any thread count, whose leaves read a record in a fork's call and again after its join (forked, the review's repro; the earlier versions of this PR printed garbage there at the default thread count). Interpreter, C (default and one thread) and JS print the same ten lines. compile/closure_record_shared's header is updated: its binding now stays boxed: the first use peeks its words and the last takes the node.

🤖 Generated with Claude Code

@nicolas-abril
nicolas-abril force-pushed the perf/wide-node-codegen branch 4 times, most recently from d6aaaab to cfe5b77 Compare November 3, 2026 21:01
@nicolas-abril nicolas-abril changed the title perf(comp): a boxed wide record stays boxed until a use needs its words perf(comp): a wide def's boxed record stays boxed until a use needs it Nov 3, 2026
@nicolas-abril
nicolas-abril force-pushed the perf/wide-node-codegen branch 2 times, most recently from 4d696ea to e827da8 Compare November 4, 2026 01:05
@Lorenzobattistela Lorenzobattistela self-assigned this Nov 4, 2026

@Lorenzobattistela Lorenzobattistela left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Gates on this branch merged onto main ea66e00 are green (test 1829/1829, safe 0 false rejects, perf matches main, comp.ts 66,000/66k), but there's a miscompile on the sequential fork path.

Wide boxed param opened inside a fork reads unpushed stack slots. emit_fork pushes a boxed param as 1 word. bind_pop now opens it later in a continuation (1 → 64 words), and the next continuation pops 4 words but reads STK(1..64). Repro, using R1/sum1 from record_wide_boxed_params plus def own(r: R1) -> U32: sum1(r):

def f(a: R1, b: R1, +c: R1, d: R1) -> U32:
  x y = sum1(a) own(c)
  U32.add(U32.add(x, y), U32.add(sum1(c), U32.add(sum1(b), sum1(d))))

f(r1(1), r1(2), r1(3), r1(4)) prints 102827529 with +RTS --threads 1 (main and --threads 8 print 832). The gate misses it because with more threads the fork runs in parallel and skips this path. The frame slot also keeps the box whose node the open freed, so a later read of that slot would be a use-after-free even with the layout fixed.

Suggestion: only open in bind_pop when no frame or fork state exists, or open at the use (val_to) without writing the opened value back into sc.uses. Please also add this case to the test, run with --threads 1.

Smaller:

  • bind_pop opens any boxed multi-word binding, including types with box words, which the Lam rule deliberately keeps opening on entry. The two rules should agree.
  • A boxed wide result passed twice to a callee that takes it boxed used to share one node (term_keep); now each use rebuilds a 64-word node.
  • ctr_tail now goes through the memoized tele_unbind, so every constructor site stores a cache entry for a fresh term that is never read again.
  • emit_clo computes rest_use([x], p) twice per captured value; bind_pop computes lay_at before checking open && lay === BOX.

The cleanup commit looks behaviour-preserving to me.

@nicolas-abril
nicolas-abril force-pushed the perf/wide-node-codegen branch from e827da8 to 3b7da82 Compare November 4, 2026 11:29
No output change (every test's and bench's C and JS is byte-identical):
- file_push indents through seg_text, which already does it;
- fact_when asks fact() instead of rebuilding its key for the lookup;
- let_live and emit_clo count uses with rest_use, as arm_self does, so
  term_use, a one-line wrapper with no other caller, folds into it;
- c_ids drops `!k`: both groups exist only in the last alternative of
  ID_WORDS and k needs a character, so k is set whenever p is;
- emit_args returns v instead of a copy that only reset `stat`, which no
  reader of its results (their words, val_hold) looks at;
- js_expr folds a non-Ref head into the call_eta fallback, as emit_expr
  already does;
- emit_intr converts and owns each argument in one pass, then aliases;
- op_bare reads FL.js instead of a js flag its two callers set to it;
- emit_fork names the continuation's fid once instead of three times;
- js_text takes a String literal's text as it is: lit_of only builds one
  from valid code points, on which char_new is String.fromCodePoint;
- lay_eq drops its arms test: a lay without arms is W32, W64 or BOX, so
  the words or the arm keys already differ;
- call_eta drops its Def test: fun_of gives a non-Def no live params;
- loop_of leaves a bodiless callee to visit, which already skips it;
- ctr_flds takes the constructor term: all five callers passed its own
  k and fields;
- emit_ctr's word branch drops `vs.length === 1`: only U32 and F32 reach
  it, Base's own, whose one field is data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nicolas-abril
nicolas-abril force-pushed the perf/wide-node-codegen branch from 3b7da82 to 48c3676 Compare November 4, 2026 14:49
A def whose parameters span past WIDE words takes its wide records boxed,
but binding a parameter opened it to its flat words at once. sum4 in
compile/record_wide_node unpacked all four 64-word records on entry, so
its join after the first fork carried the two unread records as 128
registers. The widest segment sets WL_BANK, and every segment takes the
whole bank, so the file had 131 registers and clang -O3 spent most of
its time in block placement and the control-flow optimizer.

A lazy record, boxed, more than one word and with no box words, now
binds boxed (lay_lazy); val_to opens it where a use needs the words, and
an unread one drops with one term_sink. A type with box words still
opens on entry: opened at a call, its fields would be fresh values, and
passing them to a callee that borrows them would make that callee an
owner for every caller.

Read again, a lazy binding stays boxed: a read that needs its words
peeks them (term_peek, as for a borrowed root), and a read that takes it
whole shares the node as before. The binding's words never change, so a
fork's frame and join keep theirs on any thread count, a closure that
captures it shares the node, and a later read that lends it lends the
node itself. Opening it at the first read instead held its words in
registers, rebuilt the node for a later borrowing callee, which made
that callee an owner everywhere (rfc_seal sites 73 -> 137 in the test),
and had to stay shut in a fork's later calls.

A match on a lazy record reads it in place, one dispatch on the node's
tag, taking only the fields its arm reads: it no longer copies every
field through a chain on the tag and then switches on the copy.

- compile_record_wide_node: 131 -> 65 registers, clang 1.14 -> 0.31 s
- compile_record_deep_boxed: C 229 -> 181 KB, node opens 221 -> 81
- compile_closure_record_shared: term_keep 4 -> 3, rfc_seal 3 -> 1
- 22 more tests' C changes, none larger, none with more registers or
  node opens; every bench in bench/runtime emits byte-identical C and JS

compile/record_wide_boxed_params covers wide records matched in place,
passed back whole, dropped unread, threaded through a loop, read twice,
a sum matched on its tag, a read a constant fold adds, a record holding
a list passed to a borrowing callee, one a wide callee borrows around a
read that stores it, one read and then lent (lend), a boxed record a
closure captures and uses after, and a fork tree wide enough that some
of its forks run in sequence, whose leaves read a record in a fork's call
and again after its join (forked).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nicolas-abril
nicolas-abril force-pushed the perf/wide-node-codegen branch from 48c3676 to a51ed86 Compare November 4, 2026 14:55
@nicolas-abril
nicolas-abril merged commit 3c1f0d3 into bendlang:main Nov 4, 2026
1 check passed
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Every point is handled in what merged (3c1f0d3):

  • Sequential fork miscompile: your repro now prints 832 on the default thread count and with +RTS --threads 1, as on main. As you suggested, a read no longer opens the binding and writes it back: a read that needs a wide record's words reads them in place (term_peek), and the binding stays boxed, so a fork's frame and join keep the words they took at the fork and the slot never holds a freed node.
  • The test: your f is in compile/record_wide_boxed_params as forked, called from each of the 4096 leaves of its fork tree, which runs some forks in sequence on any thread count. The compiler at e827da8 prints a different wrong number on every default-thread run of it, so the gate catches it now.
  • Box words: a record with box words stays as before, both at entry and when read again; the two rules agree.
  • Passed twice whole to a boxed callee: a read that takes it whole shares the node with term_keep again; no rebuild.
  • ctr_tail: reverted.
  • emit_clo / bind_pop nits: emit_clo is unchanged from main; bind_pop still computes lay_at first, since the check needs it.

Gates on the branch merged onto main 4024f04: repo 54/54, test 1829/1829, perf 124/124 (every bench's C and JS is byte-identical to main's).

nicolas-abril added a commit that referenced this pull request Nov 4, 2026
Merged with main, comp.ts was 66,006 / 66,000 ttok (#2036 took 6 of the
headroom). The serial step keeps one frame offset, top, in place of
last, and the first step tests !i: 66,000 / 66,000. Generated C is
byte-identical to main for every existing test, demo and bench.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
raymond-w-ko added a commit to raymond-w-ko/bend that referenced this pull request Nov 29, 2026
Two conflicts in bend2/comp.ts:
- OPERATIONS: upstream keys intrinsics by Base's def name (bendlang#2129), so
  the fork's vec_* entries become "Vec.length", "Vec.get", ...; and
  bool_pick calls intr_of(k), which no longer takes a JS flag.
- loop_of: keep the fork's walk through Bool.and/or and picks in tail
  position, and drop the done_live check on the callee as upstream did
  (bendlang#2036).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

2 participants