Skip to content

A call whose arguments a recursion never changes is computed once, in a copy of the def that carries the value - #2180

Closed
nicolas-abril wants to merge 1 commit into
bendlang:mainfrom
nicolas-abril:opt/loop-fixed-calls
Closed

nicolas-abril wants to merge 1 commit into
bendlang:mainfrom
nicolas-abril:opt/loop-fixed-calls

Conversation

@nicolas-abril

Copy link
Copy Markdown
Collaborator

comp.ts is 68,310 ttok, 2,310 over the 66,000 cap (main is 65,981), 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. The branch is on main b8a88499, one commit behind 8c329c1b (#2178), with which comp.ts merges without conflict. Independent of every other open draft; it shares lt_any, FL.made and the tld_of line with #2031, word for word, so whichever merges second drops its copy.

Reach, said first: this was found on a benchmark built to reward it, and it fires on very little else. Of the 980 programs under bench/runtime, demos, tests and the 39 Bend ports of the koru osprey kernels that build, 6 emit different C (8 sites): the two binarytrees ports and four tests. No bench of the suite, no demo and no def of Base changes.

What it does

A def that calls itself may make, on every turn, a call that reads nothing the turns change:

def go(+i: Nat, acc: Nat) -> Nat:
  match i:
    case 0n:
      acc
    case 1n+p:
      go(p, Nat.add(acc, check(make(13n))))

check(make(13n)) builds and walks the same tree 1,200 times. The def now computes it once: the arm that holds the call binds it and goes on in go~fix, a copy of the def that takes the value as a last parameter and reads it where the call was.

def go(+i: Nat, acc: Nat) -> Nat:          # as compiled
  match i:
    case 0n:
      acc
    case 1n+p:
      +c = check(make(13n))
      go~fix(p, Nat.add(acc, c), c)

def go~fix(+i: Nat, acc: Nat, +c: Nat) -> Nat:
  match i:
    case 0n:
      acc
    case 1n+p:
      go~fix(p, Nat.add(acc, c), c)

The rule (def_fix, run at the end of file_book on each def that calls itself, on the checked terms, so both the C and the JS lane take it):

  • A loop is a def with a direct call to itself, in tail position or not (a tree walk that passes a context down is covered; the value rides down every call below the first).
  • Fixed is a call whose every variable is a parameter that each live self call of the def, in every arm, passes back as the same variable. A parameter that one self call passes back and another changes, one that is matched and rebuilt, and a name bound again by a let are not fixed.
  • Worth it is a call that runs a def that loops or is not flat, directly or through flat callees. The largest such term is taken (check(make(13n)), not make(13n)). A call to a flat def without a loop (Bool.not(s), half(n), a constant def) is left: 57 such sites in the corpus, 44 of them a float-literal helper or a constant def.
  • Words only. The call's result is a word, or a record laid out as words (a Bool, a pair of numbers). A result that is a box is left where it is; see Not covered for the measurement.
  • Evaluated where it was. go keeps its body. Only an arm that holds the call binds it, at the head of the statement that holds it, and only self calls of that statement and later ones go to the copy. So a loop that turns zero times, or never reaches that arm, never makes the call; a call that stops the program or does not return does so in the arm that reached it.
  • Never a call the def may not evaluate: one under a lambda, in a partial application (its arguments run when it is applied), in an unused let, in an erased argument, or inside a call the emitter unfolds at compile time (emit_fold: the unfolded body may drop the argument).
  • Not across a write. In an @unsafe def a + parameter may hold an Array, and a write through one handle shows through the others; so there a parameter whose type holds an Array, or anything but datatypes (a closure, a type variable), is never fixed. In a checked def a + parameter is Data, which holds neither.
  • Not a call with a !, a foreign def, a lambda or a let inside it, or a call to the def itself.
  • One call per def, the first found in an arm that also calls the def; the same call written in other arms reads the same value in the copy.

Where the line with compile-time folding is: a call the emitter can unfold within FOLD_FUEL (a flat def on constants, tri(3n, 0n)) is unfolded as before and never taken; one it cannot (check(make(13n)): make is not flat) is computed once at run time.

Results

One M4, one thread, GPU off; instructions retired and cycles from /usr/bin/time -l, the least of 9 interleaved runs; wall time from hyperfine -N, 30 runs. binarytrees is the kernel of korulang/koru-benchmarks (suites/osprey-compute-kernels/bend), not added to this repo.

binarytrees instructions cycles wall
C reference (cc -O2) 6,946.0M 1,053.8M 276.3 ms
main 1,639.2M 275.1M 71.9 ms
#2031 (fuses check(make(d))) 955.9M 171.5M 46.0 ms
this 13.6M 4.2M 1.2 ms
this on #2031 (it takes the fused check<make(13n)) 12.9M 4.2M 1.2 ms
the call passed into the loop by hand 13.6M 4.2M 1.2 ms

A Bend program that prints a constant runs 12.2M instructions, so what is left is start-up. The forked port (bend-par) goes from 165.5 ms to 1.6 ms at the default thread count and from 70.7 ms to 1.3 ms at one thread.

A recursion that is no tail call, as a scratch program: a walk of 2^18 nodes that passes k down and adds tri(k, 0n) at every node runs 286.3M instructions on main and 24.2M here with k = 200; with k = 0, where the call costs nothing, 24.2M on both, so carrying the word is free there.

Every other program whose C changes, same method (7 runs):

program instructions, main this
tests/rfc/share_loop 17.42M 12.21M -29.9%
tests/reg/array_half_loop 14.79M 12.34M -16.6%
tests/reg/array_node_loop 13.31M 12.27M -7.8%
tests/compile/literal_reads (a loop of two turns) 12.20M 12.22M +0.2%

Those four tests are loops written around exactly this shape as regression witnesses (a tree shared per turn, an Array built and dropped per turn). They print their lines, but they now make the call once, so what they were written to exercise on every turn runs on the first turn only. They are left as they are here; keeping their point needs the call to read something the turn changes.

The bench suite: all 17 bench/runtime programs emit byte-identical C, so nothing was measured there. Demos: the 18 that build emit identical C. Base: rooting all 299 defs of a file that only imports Base (65 call themselves; templates come in through the tests that instantiate them) finds no site.

Compile time: no difference above the noise. Timed inside the compiler, the pass takes 0.8 to 1.4 ms of compile_book's 26 to 54 ms on lexer, terrain, merkle and symreg, 4.7 ms of 260 ms on pure_hvm5_mini and 6.2 ms of 576 ms on app_slash_boss_3d (about 1% of a whole bend file.bend -o file.c, checker included). hyperfine on that command, 7 runs each: the median over the 17 benches moves by +0.7% (from -7.3% to +4.8%, which is the spread of the runs), app_slash_boss_3d 677.6 ms to 680.4 ms, pure_hvm5_mini 337.0 ms to 343.6 ms; emitting C for all 904 tests with #| lines, one after the other, took 130.8 s on main and 131.0 s and 132.8 s here.

Emitted C grows by 0.4% to 1.2% in the six programs (the def's body is emitted twice).

Checks

All local, against main b8a88499:

  • Native lane (every test built and run with the GPU off, compared with its #| lines): 883 pass on main and 884 here (the new test); no status of an existing test differs. It ran before two edits to the pass that change no emitted C (all 980 programs emit byte-identical C before and after them); the two new tests were run again afterwards, on both lanes.
  • Emitted C of the 980 programs that build: 974 byte-identical, 6 differ (above). Emitted JS of the 1,033 that build: 1,027 byte-identical, the same 6 differ; those 6 print the same as main under bend file.bend and as a built .js.
  • Memory: the 4 tests whose C differs, the 2 new tests and both binarytrees ports, built with -DBEND_POISON and a count of live heap words at exit: the same output, exit code and count as main.
  • Adversarial programs (35, kept outside the repo), each on main and here: C with poisoned frees and the live count at one thread, C at the default thread count, and the JS lane; output, exit code, first line of stderr and live words all equal, and the defs the pass fired on are the ones each program names. They cover: zero turns around a call that stops the program, and around one that never returns; one turn around a call that stops it (it stops); the call in one arm of two, reached late, and never; a parameter passed back by one self call and changed by another; swapped parameters; a rebuilt parameter; a rebound name; nested loops; two fixed parameters under one def; forks (the loop under a fork, the call in a fork's branch, a forking tree walk); ! calls; a second entry through another def with another value; closures (a call under a lambda never applied, a self call under a lambda); a partial application; an unused let and an unfolded call that drops its argument; boxed and Array parameters; an Array an @unsafe loop writes through one handle and reads through the one it passes back; results of two words and of a Bool; a U32 loop with a default arm; a def that opens a lambda past its parameters; erased type parameters with function types as type arguments; an IO loop; a ! fork tree.
  • Wrong versions: ten deliberately wrong versions of the pass were built as compilers and run on those programs; each is caught by at least one. Taking every parameter for fixed; reading only the first self call; binding the call in arms that do not hold it; looking under lambdas; into partial applications; into unused lets; dropping the unfold test; a key that ignores which variable a call reads; allowing Arrays in @unsafe defs (prints 370 where main prints 750); binding at the head of the arm instead of the statement.
  • Metal: none of the six changed programs makes a ! call. Two scratch programs do (a loop that calls itself with a !, and a ! fork tree whose leaves run a loop the pass fires on): both print the same with --gpu on and --gpu off, on main and here; the tree's value was computed apart in Python.
  • New tests: tests/run/loop_fixed_call.bend, 14 shapes whose numbers were computed apart in Python, every count scaled by the command line's length so nothing folds; the pass fires on 10 of its defs and must leave 5 alone. tests/run/loop_fixed_call_stop.bend: one turn whose arm first binds a call past the Nat wall and then holds a fixed call that never returns stops with the Nat message. Both print their lines on the C lane and under bend file.bend, on main and here. Of the ten wrong versions, the first test fails eight and the second the one that binds at the head of the arm; the tenth (no unfold test) cannot be pinned by a repo test, because main's own lanes disagree on its case: the C lane unfolds pick(boom(k), 0n, acc) and drops the argument, the JS lane evaluates it and stops.
  • tsc reports the same 3 errors in comp.ts as on main.

Not covered

Every way the order of evaluation or the sharing can differ from main:

  • Within one statement the fixed call is bound first, so it runs before calls written to its left in that statement (main runs a statement's calls that are not flat first, left to right, then the flat ones in place). A program differs only if two calls of one statement both go wrong: Nat.add(boom(i), hang(k)) stops with the Nat message on main and never returns here. Statements before it (earlier lets) still run first.
  • A call in a fork's branch is bound before the fork, so on the first turn it runs before the other branch starts, not beside it.
  • Later turns no longer make the call. A program that would have died in a later turn's call (out of memory or stack) no longer does.
  • A def tail-called from exactly one place in the loop has two callers after the copy and is no longer emitted in place at that tail.
  • No sharing changes: the value is a word. A boxed parameter the call read is kept and dropped as before, on the first turn only.

Left out:

  • Boxed results. Measured with a variant of the pass that takes them (20,000 turns, a 1,000-node list, instructions / cycles against main): a consumer that only reads the list 2.12x / 1.49x; one that rebuilds it 1.34x / 1.47x; a small record after a costly call 7.4x / 5.9x. But the cost is not local: with a second, unrelated loop over the same list type in the file, 20 turns of a shared list make that loop run 2.7x the instructions and 1.74x the cycles (1,796M / 368M to 4,898M / 638M). The mechanism is inferred from facts_hot, not traced: a shared value forces its type hot for the whole program. Not clearly a gain, so left out; taking them only where the type is already shared would need the emitter's facts.
  • A second fixed call in the same def, and the same call when no arm that holds it also calls the def (a call only in the exit arm).
  • A self call bound by a let before the statement that holds the call keeps calling the def itself: only later calls can take the value.
  • Loops through another def (a helper that matches a computed value and calls back): only a def's direct calls to itself are read.
  • IO loops: an action is a function of its continuation, so its calls sit under a lambda.
  • @unsafe defs: parameters whose type holds an Array, a closure or a type variable.
  • Cluster gates, CUDA, Linux and x86 have not run.

Cost

+2,329 ttok. Each def the pass fires on is emitted twice.

🤖 Generated with Claude Code

A def that calls itself may make, on every turn, a call that reads only
parameters each self call passes back as they are (binarytrees' go builds
and checks the same tree 1,200 times). def_fix, run at the end of
file_book on the checked terms, takes the largest such call that yields
words and runs a def that loops or is not flat: the arm that holds it
binds it at the head of its statement and goes on in k~fix, a copy of the
def that takes the value as a last parameter and reads it where the call
was. The def keeps its body, so a loop that never reaches that arm never
makes the call, and one that reaches it makes it there.

Not taken: a call under a lambda, in a partial application, in an unused
let or an erased argument, inside a call the emitter unfolds, with a bang
or a foreign def in it; a result that is a box; and, in an @unsafe def, a
call that reads a parameter holding an Array or anything but datatypes (a
write through one handle shows through the others).

binarytrees (koru osprey kernel), one thread: 1,639M instructions and
71.9 ms to 13.6M and 1.2 ms. Of 980 programs under bench/runtime, demos,
tests and the koru kernels, 6 emit different C: the two binarytrees ports
and four tests. comp.ts is 68,310 ttok (cap 66,000).

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 added a commit to nicolas-abril/bend that referenced this pull request Nov 22, 2026
mix_sink_calls: bendlang#2217's U32 lets that sink below a non-tail call, in a
tree recursion whose returning arms run at the call (bendlang#2177), in sum loops
of two and three self calls and one whose arm answers 0 (bendlang#2175), next to a
fixed call (bendlang#2180), a let the call reads (stays), and a parallel call.
mix_reform_slots: trees in an Array's slots (bendlang#2135: read borrowed, taken
and written back) walked by a selector-first lookup and insert (bendlang#2211),
split by colour and re-formed (bendlang#2207), lent to a flat def, with the node's
U32, Bool and colour in one word (bendlang#2218), in @unsafe helper cycles.
Both print main's numbers on C at 1 and 8 threads and on JS.

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

Copy link
Copy Markdown
Collaborator Author

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

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