Skip to content

perf(comp): a statement's call unfolds into a def that is not flat - #2162

Closed
nicolas-abril wants to merge 1 commit into
bendlang:mainfrom
nicolas-abril:opt/unfold-statements
Closed

nicolas-abril wants to merge 1 commit into
bendlang:mainfrom
nicolas-abril:opt/unfold-statements

Conversation

@nicolas-abril

Copy link
Copy Markdown
Collaborator

comp.ts is 67,137 ttok, 1,137 over the 66,000 cap (main is 65,966; this adds 1,171), so repo-gate fails until that is settled. Measured on one Mac (M4), not on the cluster: the test and perf gates have not been run.

What it buys: lexer runs 25.5% fewer instructions and 22.9% fewer cycles (its gap to the C twin goes from 1.96x to 1.52x), symreg 0.8% fewer instructions; the other 15 benches emit byte-identical C.

Independent of the other open drafts: it branches from main f0cf0a7c. It was found while breaking down what lexer loses to its C twin: more than half of that gap is the line generator, a recursion over a template that is a literal.

What it does

emit_unfold already unfolds a call whose constant arguments decide its matches, but only into a flat def, because its residue is emitted as an expression. lexer's gen walks a literal template with a call that is not a tail call, so it is not flat: every line paid 39 frames, 39 returns through the segment table, and a comparison chain per template character to pick its slot, all on constants.

Now a call in statement position (a tail call, or the call a let binds, which is where ANF puts every call into a def that is not flat) unfolds into such a def too. Its residue is a statement, so ANF cuts the calls it makes, and they unfold in turn where they stand. Four things make the unfold go through there, all behind the one flag, so an expression's fold is what it was:

  • A flat argument folds to its end, not one step, so slot(105) is Id{} by the time expand matches on it.
  • An op on constants is its constant (a U32 or a Bool, by the op's JS, as a match table's cells already are): U32.is_eq(105, 105) is True{}, and the template position k + 1 is a literal.
  • A def with no match of its own unfolds if its body's tail call does, and a residue's tail call unfolds in place: gen.at(105, t, rest) is expand(slot(105), 105, t, rest), which is ident(n, t, rest).
  • An argument that calls a def that is not flat is bound first, so no later argument is held across it in a frame. An argument bound this way is typed by the arguments before it (the flat unfold types it by the callee's own parameter names), since its uses are read in the caller.

When it does not unfold:

  • No constant argument: not tried.
  • The fuel is FOLD_FUEL, as for the flat unfold: a unit for every term of every body unfolded, all of it or none. A try that fails gives its fuel back, and a def whose unfold ran out is not tried again in that unit.
  • A recursion the constants do not carry to its end: a residue that keeps a call leading back to the def unfolded is refused, or the recursion would only be peeled once (U32.show's digit loop, with its literal fuel, would be, in every program).
  • A residue that forks or bangs is refused, so no segment starts or stops forking because of an unfold (a def that forks runs on the device, one that does not runs on the host).
  • A lambda argument, or a match left in the residue, as before.

For lexer the whole of gen, gen.at, expand, slot and slot.go is gone from a line: its literal characters are SCon nodes built in place (the tail " ;" is static), and the seven identifiers and numbers are seven calls with one word, the line's seed, in each frame. It takes 5,451 of the 8,192 fuel, so a template half as long again would stay a call. symreg's gen(5n, h) builds its 63-node candidate without a frame.

Elsewhere it is mostly "literal" ++ x: Base's String.append is not flat, and now a literal in front is consed on directly.

Results

One M4, GPU off, instructions retired and cycles from /usr/bin/time -l, the least of five interleaved runs.

lexer main this C twin
instructions, 1 thread 53.407G 39.784G -25.5% 17.757G
cycles, 1 thread 8.380G 6.524G -22.1% 4.284G
wall, 1 thread 2.08 s 1.62 s 1.28x 1.01 s
cycles, 8 threads 10.433G 7.917G -24.1%
wall, 8 threads 0.39 s 0.30 s 1.30x
per line, generating it: instructions / cycles 3,449 / 596 1,825 / 379 1,087 / 248
per line, lexing it: instructions / cycles 3,012 / 522 3,012 / 522 988 / 304

The per-line rows are from builds that generate 64 lines, then lex them, with a counter read between (so their cycles are a little above a plain run's).

The gain was checked against placement, since any change to the C moves the code: both builds at 16 placements (the segments shifted in 4-byte steps), three alternating rounds, the least per placement.

build least median most
main 8.383G 8.442G 8.765G
this 6.464G 6.508G 6.577G

No overlap; -22.9% on the median.

Bench suite. 15 of the 17 bench/runtime programs emit byte-identical C. The other two:

bench main, instructions this main, cycles this
lexer 53.407G 39.784G -25.51% 8.380G 6.524G
symreg 50.767G 50.364G -0.79% 12.368G 12.308G

Size and compile time. Over the 883 tests that pass on main, the 17 benches and two more programs, 464 emit different C and 438 the same; the C is 0.02% larger in all (from 0.26x on reg/show_shared_layout to 2.16x on base/list_sort), and compiling them all takes 6% longer. Of the 15 demos with a main.bend, 8 emit the same C and 7 change: app_slash_boss_3d 2.92 MB to 3.07 MB of C (+5.1%) and 0.65 s to 0.94 s to emit it; pure_hvm5_mini +2.3% and 0.33 s to 0.42 s; io_http_server +4.0%; the other four shrink by 1% to 3%.

Checks

All local, against main f0cf0a7c:

  • Native lane: every test that passes on main (883) passes here, the GPU off; the 22 that do not pass on main in this local lane end the same way.
  • Every program whose C changes (464 of 902: tests, benches at full size, the two new tests): built with -DBEND_POISON and a count of live heap words at exit, and run at one thread: the same output, the same exit code and the same count as main on every one; then at 8 threads: the same output.
  • JS: the JS emitted is byte-identical to main's on 40 programs sampled from those whose C changes; the change is in the C emitter only.
  • New tests. tests/run/unfold_statements.bend: a fold over a constant list whose step is not flat; an arm that drops a constant and frees a value; a value the caller keeps, shared by two arguments of a def that walks it, handed to an arm that drops it, and again at its last use; a def with no match that unfolds through its callee, with its character's class decided by ops on constants; a def that forks (it must stay a call); a count too long for the fuel and a call tree that is; Base's String.append and List.append on literals; an unboxed pair out of a def that is not flat; and a template expanded as lexer's is. Its inputs come from a list built at run time, so C folds none of it. tests/run/unfold_generic.bend: a generic def unfolded over a literal list whose other argument is computed, bound and shared, with boxed elements, called from a def whose own type parameter has the same name and place. Both pass on the C lane at 1 and 8 threads, on Metal, in JS, and with poisoned frees and no live word at exit. In the emitted C the segments of fold, step, pick, both, wrap, reads, two, gen, glue, twice and List.append are gone, and those of tsum, count and fib are not.
  • Wrong versions the tests catch: an op on constants folded to the wrong Bool, or to a U32 one too high (the first test and lexer print wrong); a use the unfold adds not counted (the compiler stops); a residue that forks unfolded into a ! def (Metal: stack overflow, the def now runs on the device). Found on the way and fixed: a bare reference to an op (no arguments) folded to a constant, which stopped the compiler on tests/reg/array_clone_runs.bend.
  • Wrong versions they do not catch: a use the unfold drops left counted (bind_dead recounts the binding at the next statement, so nothing leaks); the argument that calls bound last (slower, not wrong); an argument bound with the callee's own type names, as the flat unfold does (no program I wrote makes it matter: a call nearby marks the same types shared).
  • Demos: the four whose C changes and that run without a window (proof_insertion_sort, proof_numerics, proof_typed_eval, pure_hvm5_mini) print what they print on main.
  • Metal: lexer (2.51 s to 1.48 s), symreg and the two new tests print the same results with --gpu on.
  • Hard inputs: fib-shaped and million-deep recursions on literals, alone and as arguments: same output, same compile time, no unfold.
  • repo.ts fails only on the ttok cap.

Not covered

  • Cluster gates, CUDA, Linux and x86, tsc have not run. lexer's pin would move.
  • Compile time and size grow where constants drive a recursion: 45% on the largest demo, more than twice the C on one test (base/list_sort, literal lists sorted). The fuel caps it for a unit, not for a program.
  • The fuel is a cliff. lexer's template takes two thirds of it; a longer one unfolds nothing.
  • A constant that reaches only a call that is not the tail of a def with no match is not seen: both(o, w) = kl_sum(w, step(o, w)) stays a call for a constant o.
  • An op whose result is a Nat or an F32 is not folded, so ident(U32.to_nat(3), ...) is not unrolled.
  • JS gets none of this: the JS emitter does not go through emit_body.
  • Which programs gain beyond the two benches and a literal in front of ++ was not measured.

🤖 Generated with Claude Code

emit_unfold took a call whose constant arguments decide its matches,
but only into a flat def: its residue is an expression. A call in
statement position (a tail call, or the one a let binds, where ANF puts
every call into a def that is not flat) now unfolds into such a def
too. Its residue is a statement, so ANF cuts the calls it makes and
they unfold where they stand.

There, and only there: a flat argument folds to its end; an op on
constants is its constant (a U32 or a Bool, by the op's JS, as a match
table's cells are); a def with no match of its own unfolds if its
body's tail call does, and a residue's tail call unfolds in place; an
argument that calls a def not flat is bound first, so no later one is
held across it, and is typed by the arguments before it.

A call with no constant argument is not tried. A residue that forks or
bangs is refused, and so is one that keeps a call leading back to the
def unfolded (the constants must carry a recursion to its end, or it
would only be peeled). A try that fails gives its fuel back, and a def
whose unfold ran out of fuel is not tried again in that unit.

lexer's gen walks a literal template: its frames, its returns and its
slot dispatch are gone from a line (53.41G to 39.78G instructions,
8.44G to 6.51G cycles). symreg's gen(5n, h) builds its candidate
without a frame. The other 15 benches emit the same C.

tests/run/unfold_statements.bend and tests/run/unfold_generic.bend.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 22, 2026
… non-tail call that does not read it

Conflict in comp.ts, emit_body's choice of the next form (bendlang#2217 against
bendlang#2162): bendlang#2162 tries emit_deep on a statement's call before anf, bendlang#2217 tries
let_sink on a let first. They apply to disjoint heads (emit_deep only to a
call, let_sink only to a let), so both stay: let_sink first, then bendlang#2162's
emit_deep-or-anf as before. let_sink only reorders total U32 lets past a
frame-pushing call; acc_def (bendlang#2175), def_fix (bendlang#2180) and bendlang#2177's call-site
returns rewrite defs before emission and see the lets as written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Moved to nicolas-abril#17, which keeps it saved off the main queue until it can be accepted.

nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 24, 2026
, bendlang#2224-bendlang#2226, bendlang#2231, bendlang#2285, bendlang#2286, bendlang#2288 and others)

One conflict, in emit_unfold: bendlang#2288 annotates an unfolded call's lets with
the argument types instantiated by the earlier arguments; bendlang#2162's deep unfold
keeps its arguments unannotated there and annotates them the same way after
folding (its type walk renamed D, beside bendlang#2288's T). Both kept.

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.

1 participant