0235. Compact C for large integer matches
- Status: Accepted (maintainer, 2026-11-22)
- Date: 2026-11-14
- Plan: optimization round 1 (Optimization Researcher findings)
- Review: Compiler and backend
Context
lower::integer_match turns each arm into a private
done/matched flag plus
>=/<= predicates, and the C
backend printed that as a nested if chain with a
#line per statement.
plugins/tui/unicode.hn has matches of several hundred
range arms (gcb, wide); they were 61% of
the TUI dashboard's generated C. A 588-arm microbenchmark took gcc
-O2 about 100 s (207 s under load) to compile and 470 ms to
run.
Patterns are half-open (lo..hi), literals are
n..n+1, alternatives use |, and the
checker allows overlapping arms: first match wins.
Decision
Only C emission changes; Core IR and
harness interp keep the if chain as the independent
reference. cgen_match recognizes exactly the
predicate shape integer_match emits, for 8 or more
consecutive integer-pattern arms on one scrutinee (_
and later arms are emitted as before). It resolves overlaps at
compile time with an endpoint sweep that keeps the lowest arm
index, producing disjoint inclusive ranges, then:
- If the ranges cover at most 256 values: a C
switchwith onecaseper value (gcc, clang and TinyCC; nocase a ... bextension). - Otherwise: a sorted
static consttable of{lo, hi, payload}and a binary search. - If every arm body only assigns one shared destination a
constant integer expression that folds without overflow or
division by zero in the destination's type, the payload is that
value. Otherwise the payload is the arm index and a
gotodispatches to the arm bodies, which stay outside any Cswitchso sourcebreak/continuekeep their loop targets.
Byte (u8) decision trees keep the existing
256-entry table (cgen_byte), which is tried first.
Matches with fewer than 8 arms emit unchanged C.
Alternatives considered
- Lowering a new IR switch node: would change Core IR, the interpreter and IR goldens for a backend-only cost problem.
- gcc case ranges: not portable C11; TinyCC and strict modes reject them.
- Aliasing constant
vec<int>literals to static data (task part B): skipped.hrt_vecis a plain{data, len, cap}arena buffer with no refcount or copy-on-write, so in-place element writes and pushes would write into read-only memory. Proving a literal is never written needs whole-program escape analysis through calls; part A already removes the vec-based workaround that motivated it.
Consequences
The 588-arm microbenchmark compiles in 0.23 s and runs in about
45 ms with identical output; the TUI dashboard's emitted C halves
(2.69 MB to 1.43 MB). Emitted C changes only for programs with
such matches (TUI plugins, the http reason table and
generated codec field dispatch). Runtime traps, results and
evaluation order are unchanged;
tests/programs/integer-match-table checks boundaries,
overlaps, widths and loop control against the interpreter.