Skip to content

ADR 0001: The QBE backend

Status: Final Type: Architecture Created: 2026-07-10 (originally notes/01-qbe-port.md, moved into postc) Amended-By: 0055 (the loop passes read the counted loop the frontend records) Related-ADRs: 0002 (modes are the frontend's; release IR stays byte-stable because some passes match exact shapes). Current measured figures live in the benchmarking guide, not here.

Context

The C backend emits C99 and leans on the system C compiler for optimization, libm, and the CPython/NumPy extension glue. A second code generator was wanted: smaller, self-contained, dependency-light, fast to compile, and a vehicle for direct control over code generation. QBE's type system is minimal (w/l/s/d, with b/h in memory). qbe itself performs none of LICM, strength reduction, inlining or vectorization, and the assemble-only cc -c step that follows it cannot add any of them back.

Decision

QBE ships as an opt-in second backend over the same typed SSA IR the C backend consumes: emit QBE IL, qbe turns it into native assembly, cc assembles and links. The default backend stays c.

The correctness oracle is byte-identical output to the C backend. A second backend must be provably in agreement with the first; parity is verified end-to-end through the real NumPy generalized-ufunc ABI, across dtypes and with byte strides taken straight from NumPy. The oracle is the concrete expression of the project's standing rule: reject unsupported semantics clearly, never accept code and change its behavior.

Anything the backend cannot lower raises a typed error (QBEUnsupported), so a build fails with that error. Nothing routes a program to the C backend: the user chooses a backend. What a program may contain is the frontend's business, held alike for every backend. Complex numbers are the decided narrowing: QBE has no complex type, the C backend uses double _Complex and libm's cpow/cabs, and reproducing that would mean hand-implemented double-pair arithmetic. Complex64/Complex128 therefore refuse clearly and the user picks the C backend.

QBE follows the platform C ABI. A QBE function d $f(d, d, d) is call-compatible with a C double f(double, double, double). QBE-produced objects therefore link unchanged against the stable pp_<name> export wrappers (compiled as C for all backends) and against the shared C runtime helpers (integer ** calls a small C ipow runtime, linked only when a module uses it).

The backend has its own IR-level optimization passes. qbe supplies none and nothing later in the pipeline can. The passes are array-metadata LICM (an array parameter is an immutable pointer available in the entry block, which dominates every loop, so hoisting is correct by construction). Two more are ufunc-loop strength reduction with view hoisting and scalar-kernel fusion into the ufunc loop. The last two are kernel-loop strength reduction over dominator-derived natural loops (nested summed-index accesses included, processed innermost-first) and unrolling of counted reduction loops that preserves the exact serial reduction order. Every pass is held to the byte-identical oracle. Each fires only when it can prove its pattern; anything unclear falls back to the unoptimized-but-correct lowering.

No -ffast-math, ever. Reassociation and FP contraction change results, which would break the byte-identical oracle that is the correctness story. cc -O2 operates under the same constraint once postpile passes -ffp-contract=off, which every build does: it emits neither SIMD nor FMA for FP reductions, because either would change the bits. Without the flag, GCC fuses a multiplication and the addition after it into one rounding wherever the target has the instruction (accept-then-wrong §99). Bit-exactness therefore holds on both sides.

Float ** calls a runtime helper, never pow directly. Clang and LLVM rewrite pow with a constant exponent under strict floating point: pow(x, 0.5) as sqrt(x), pow(x, 2.0) as x * x, pow(x, -1.0) as 1.0 / x. Each rewrite is exact only if pow is correctly rounded. Apple's libm pow is not (one ulp on about one input in a thousand), so the C and LLVM backends printed floats that differed from CPython's and from QBE's (accept-then-wrong §68). Float ** therefore calls __pp_fpow_f64 (and __pp_fpow_f32) on every backend, defined once in the runtime's float-arithmetic unit beside __pp_fmod_f64, which reaches libm's pow through a volatile function pointer. -fno-builtin-pow does not stop Apple clang; -fno-builtin would, at the cost of the memcpy and memset idioms in every unit. The cost is a real pow call per power, as in CPython: Shed Skin's nbody runs in 5.1 s on c instead of 1.3 s, against CPython's 35 s.

The remaining architectural ceiling (SIMD, for which QBE has no vector types) only matters under a reassociation contract this project does not adopt.

Codegen invariants

These hold regardless of how the passes evolve:

  • Counter elimination is unsafe. Replacing a loop's i < n bound test with an induction-pointer-vs-end comparison assumes the stride is positive, but NumPy passes negative strides for reversed views (a[::-1]), which the compiler cannot detect: the pointer then moves backward and ptr < end is the wrong test from the first iteration. A pointer bumped by a runtime stride of either sign accesses the right elements, but only the counter gives a sign-independent bound, so the loop passes keep the counter.
  • C integer-promotion conformance. Sub-word arithmetic results are re-narrowed to their width (QBE keeps the full 32-bit word where C truncates on assignment: Int8 must see 100+100 as −56), and sub-word operands are promoted to signed 32-bit before a comparison is chosen (Int8(-1) < UInt8(1) compares signed, as C does).
  • Mutable locals get stack slots; instruction results are fresh names. The IR is not strictly SSA: a local reassigned in a loop, or an output-by-pointer parameter, takes a stack slot in the entry block, seeded from its incoming register at entry; instruction results stay single-assignment. qbe's own register allocator promotes most slots back into registers, so the discipline costs little.
  • Integer % is C-truncated, matching the C backend exactly; the frontend compensates where Python semantics require flooring. Mixed-type operands get explicit coercions (QBE has no implicit promotion), and conversion into Bool is a compare-against-zero.

Consequences

  • The two backends validate each other, which turned out to be the single most valuable design choice: "byte-identical to C" is a testable oracle for the whole port. The parity fuzzing found real codegen bugs (uninitialized reassigned-parameter slots, missing coercions, non-canonical sub-word results) that no per-backend test would have seen.
  • The strength reduction and the unroll read the counted-loop record the frontend writes (0055); the other passes match exact shapes, which is why release IR must stay byte-stable (0002) and why the cross-backend benchmark doubles as a regression gate.
  • Within the no-reassociation constraint the IR-level passes bring QBE to near-parity with cc -O2; the figures, and the methodology for trusting them, live in the benchmarking guide.

Alternatives considered

  • Routing unsupported constructs to the C backend automatically: never built. The user picks a backend; the compiler's job is a clear diagnostic.
  • A fast-math mode, or forking QBE to grow vector types: rejected. Both give up bit-exactness with the C backend (the correctness oracle). A fork would also reimplement a slice of LLVM. Reassociating speed, if ever wanted, belongs in a separate opt-in backend with its own stated contract.
  • Lowering complex numbers to double-pairs in QBE: deferred as scope. Large, hand-written complex arithmetic against libm's semantics. The payoff depends on how much real code uses complex. Refusing clearly costs nothing.