Skip to content

The C compiler specializes calls with a known callback - #1288

Closed
mizchi wants to merge 2 commits into
bendlang:mainfrom
mizchi:perf/known-callback-specialization
Closed

mizchi wants to merge 2 commits into
bendlang:mainfrom
mizchi:perf/known-callback-specialization

Conversation

@mizchi

@mizchi mizchi commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Based on main 5a0b523f (Bend 2.0.35); reproduced locally on Apple M5/macOS.

What Bend should do

Specialize calls that pass a known callback, avoiding closure allocation and dynamic application while keeping ordinary function types:

def apply(x: U32, callback: U32 -> U32) -> U32:
  callback(x)

def run(+bias: U32, x: U32) -> U32:
  a = apply(x, y => U32.add(y, bias))
  apply(a, y => U32.add(y, bias))

Why

I started this while building Bend bindings for GPUI, connecting Bend-computed particle state to rendering without CPU readback. Small callbacks used to thread linear arrays through element reads became a bottleneck. The generated update had fourteen closure segments; rewriting those callbacks as explicit arguments made it much faster.

This lets the compiler remove that cost for supported calls while keeping the callback API. CPU and GPU share the C emitter. With unchanged Bend particle sources, update closure segments fall from fourteen to zero; two UI/IO closures remain.

One million particles on Apple M5, measured on main 947db722 vs fork b59588e2. Rebased particle C outputs are byte-identical:

Update Baseline Optimized Speedup
CPU, 1 thread 160.881 ms 69.830 ms 2.30×
CPU, 10 threads 24.472 ms 12.108 ms 2.02×
Metal, including completion wait 8.653 ms 1.625 ms 5.32×

GPUI is the application example. This PR changes the general compiler; application code is available as a reusable Bend/GPUI library, a minimal Bend application, and a particle rendering example. The benchmark reference implementation remains pinned to the measured versions.

Change

Two commits: first shorten type/import notation and comments without changing generated output, then add specialization (+69/-15 compiler lines) and two regression fixtures. comp.ts is 63,956 ttok; the 64,000 cap stays unchanged.

Specialize saturated defs with one literal lambda and unboxed captures. Reuse fusion and argument binding, preserve typed lambdas/constructor patterns and caller capture lifetimes, and cache admission across ANF rebuilding and fuel exhaustion.

Dynamic callbacks, boxed captures, multiple lambdas and foreign/bang calls retain the existing path. Callees with direct self-reference or parallel bindings are excluded. Non-tail expansion also excludes non-flat calls and callbacks with parallel bindings. Budget exhaustion falls back to closures.

Separate from #1286 (foreign-callback C emission). The notation/comment commit shares the size-reduction goal of open #1281.

Verification

Local checks on main 5a0b523f plus this patch:

  • gates/repo.ts: 49/49.
  • Thirteen callback contracts pass, including capture reuse, linear arrays, dependent types, non-flat calls, fallback, repeated compilation and fuel exhaustion.
  • Sixteen upstream programs (including the two new fixtures and main's two new ownership regressions) agree across interpreter, JS and C with 1/4 threads: 64 executions.
  • The compaction alone preserves generated C/JS byte-for-byte for fourteen programs. The eight particle C outputs match the published measured versions, including both flat controls.
  • TypeScript reports the same two existing bend.ts errors on baseline and branch. Full cluster test/perf/safe gates and CUDA hardware have not been run.

Start with tests/run/known_callback.bend (stdout 42); commands below.

Reproduction and measurement details

Small regression (stdout 42):

bun bend2/main.ts tests/run/known_callback.bend -o /tmp/known_callback.c
clang -O3 -std=c11 -pthread /tmp/known_callback.c -lm -o /tmp/known_callback
/tmp/known_callback --gpu off --threads 1
/tmp/known_callback --gpu off --threads 4

The table was measured on main 947db722 versus fork b59588e2. After rebasing onto main 5a0b523 and compacting, all eight measured particle C outputs remain byte-identical in their respective lanes; timings were not rerun.

Apple M5 (10 CPU/10 GPU cores), macOS 26.6.2, Bun 1.3.5, clang 21.0.0. One million particles, 64 noise rounds, CPU grain 1,024, GPU grain 16,384, 960×540 offscreen output. Five warmup frames and fifteen measured frames per run; median of three run medians, configurations shuffled and run serially. Builds/startup/verification are excluded. Measured frames have zero CPU readback. This measures update time, not display/presentation latency.

The machine was shared. The byte-identical flat GPU control ranged 1.543–1.841 ms on main and 1.514–1.725 ms on the fork, so small timing differences should not be attributed to the compiler. Eight application binaries were checked with float32/image oracles: 36 configurations and 144 verified frames.

Raw timings and application validation, with pinned source/compiler revisions and reproduction commands in the reference README.

Implemented and checked with OpenAI Codex assistance.

@nicolas-abril nicolas-abril self-assigned this Oct 5, 2026
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Thanks for this, and for the careful measurements. Removing the closure cost of a known callback is worth doing, and the 2–5× on the particle update shows it. We're closing this PR, though, because we'd rather get there another way.

Why not this approach

The PR inlines the callee's body at the call site with the lambda substituted. That only works for callees that don't call themselves, so a callback passed through a loop or traversal gets nothing. It's also hard to keep correct in the compiler: it needs a fuel budget, a cache that survives ANF rebuilds, and a list of exclusions. A review reproduced three crashes where the interpreter and main both give the right answer:

  • An unused or type-level lambda argument: ignore(x, y => ...) or dapply(y => U32, x) hits tele_unbind on a null type in the new emit_unfold branch.
  • A callback right before a parameter opened as a tuple: bake's field positions overlap the callback's, so the body becomes callback(callback, b).
  • Two @unsafe defs that tail-call each other passing the callback: they inline into each other until the compiler's stack overflows, because the cache hit costs no fuel.

It's also C-only, and the first commit now conflicts with #1281.

The direction we'd like instead

Bend already specializes known callbacks with templates. List.map, filter, any, all, find, sort and Array.map in Base take the callback as a ~ parameter, and each call mints an instance. That covers recursive callees and both the C and JS lanes, and the checker checks the instance like any other def. The missing piece is captures:

List.map(~U32, ~U32, ~(y => U32.add(y, bias)), xs)
# today: "a template applied to closed ~ arguments (bias is a variable here, not comptime: pass it at run time)"

The plan is to allow this: when an instance is minted, each variable the callback captures becomes an extra runtime parameter of the instance, which recursive calls pass along. Your apply(x, callback) would then declare ~callback, and run would compile to a direct call with bias passed in, with no closure. We're prototyping it now and will link it here. Your fixtures (known_callback, known_callback_array) are the first tests we're running against it, and the particle example would be a great benchmark for it.

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Update: we went a different way than the templates idea above. Making ~ accept capturing callbacks worked, but it changed what ~ means, put these programs out of reach of --verdict, and needed annotations at every callee. The compiler is the right place for this, as this PR had it.

The prototype is #1356 (draft). It only touches comp.ts, and like this PR it specializes calls that pass a literal callback, with two differences:

  • One specialized def per callee and source lambda, not one inlined copy per call site. The lambda's captures become parameters of that def, and a self-call inside it is a plain call to the same def. That covers recursive callees passing the callback on unchanged, such as the even/odd shape.
  • No fuel. A substituted lambda is never used as a specialization key, so keys are pairs of a callee and a lambda written in the source, which are finite. A callback that a recursion wraps keeps its closure.

Your two fixtures are in it unchanged, credited to you. Both print 42 in every lane with no closures. A helper called each step with a fresh capturing lambda runs in 0.07 s instead of 0.25 s, the same as hand-written. It's 306 tokens over the comp.ts cap for now, which is why it's a draft. Running your particle example against it would be very welcome.

nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Oct 30, 2026
…e, through a leading one-arm match

A call whose argument in a live position is a source lambda inlines a
non-recursive callee at the call site, so the lambda is applied in place
and no closure is built. Inlining passes through a callee's leading match
on a one-constructor type (tuples, records): def_at puts the callback into
the match arm. A lambda applied directly to its arguments is reduced in
anf. In the emitter, a let bound to a one-arm match moves the rest of the
code into that arm, and a tail one-arm match is emitted directly.

Skipped: multi-arm matches, recursive callees, callees with more than one
non-callback argument left at the match.

Replaces bendlang#1356. Fixtures from bendlang#1288 (by @mizchi) included unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <[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