Skip to content

feat(unroll): loop-unrolling pass with opt-independent constant folding - #284

Merged
nihalpasham merged 24 commits into
mainfrom
feat/loop-unroll-pass
Jun 27, 2026
Merged

nihalpasham merged 24 commits into
mainfrom
feat/loop-unroll-pass

Conversation

@nihalpasham

@nihalpasham nihalpasham commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds cuda-oxide's first custom dialect-mir optimization pass: annotation-driven loop unrolling with #[unroll] and #[unroll(N)]. The pass runs after mem2reg and before LLVM-dialect lowering, so loop structure and counter-derived expressions can be simplified in cuda-oxide's own IR.

What changed

  • Full unrolling — #[unroll]
    • Requires a compile-time-known trip count.
    • Removes the loop and creates one body copy per original iteration.
    • Preserves supported early break paths, live-out values, and multiple exit targets.
  • Partial unrolling — #[unroll(N)]
    • Builds a main loop that performs N original iterations per trip.
    • Keeps a remainder loop, so runtime trip counts do not need to be divisible by N.
    • Conservatively warns and skips loops with unsupported extra exits or changing bounds.
  • Loop analysis and canonicalization
    • Adds reusable loop and induction analyses.
    • Joins multiple continue/back-edge paths through one internal latch.
    • Applies explicit copy/block/operation budgets before cloning.
    • Processes annotated nested loops from the inside out.

Capability coverage

  • Multi-block loop bodies with internal control flow
  • Loops nested inside an annotated loop
  • Annotated inner and outer loops
  • Multiple continue paths / loop latches with a consistent counter step
  • Full unrolling with early break and multiple exit targets
  • Safe warning-and-skip behavior for unsupported partial exits and loop-carried bounds

Constant stage-index folding

Partial unrolling includes a small peephole for counter-derived power-of-two indices:

#[unroll(4)]
while k_idx < k_iters {
    let stage = k_idx & 3;
    consume_stage(stage);
    k_idx += 1;
}

The four main-loop copies fold to stages 0, 1, 2, and 3. This removes the runtime stage dispatch before LLVM lowering. Unsigned power-of-two remainder expressions such as k_idx % 4 are handled as well.

The fold deliberately requires a loop-local counter expression. A runtime base such as (tile_k_base + k_idx) & 3 is not folded unless the source algorithm can safely rewrite it using a separately enforced alignment/period contract.

GEMM validation

The Phase 4D GEMM uses the foldable loop-local stage index and explicitly enforces K % 256 == 0, which makes the producer's global stage and consumer's local stage equivalent. The combined K-loop unroll and L2 N-band swizzle produce:

Size Throughput Live cuBLAS SoL
4096³ 312.467 TFLOPS 68.81%
8192³ 330.799 TFLOPS 62.39%
16384³ 341.426 TFLOPS 79.77%

All GEMM correctness checks pass.

Compiler and documentation integration

  • Adds mir-transforms to the compiler pipeline and unit-test CI matrix.
  • Uses pliron's block cloning and APInt support from revision 222dd962.
  • Adds and expands unroll_smoke coverage for full, partial, nested, multi-latch, and safe-fallback cases.
  • Documents the user-facing annotation in the kernel guide and API reference.
  • Adds a new Compiler Optimizations book chapter covering MIR transforms, full/partial unrolling, the stage-index peephole, supported shapes, and future pass structure.

Testing

  • Formatting: root workspace, codegen backend, and all 118 examples
  • Clippy with -D warnings: root workspace, backend, and all 118 examples
  • Complete 14-package PR unit-test matrix
  • Warning-free workspace rustdoc and all doctests
  • cargo deny check
  • GPU-less device compilation: 118/118 examples passed
  • Strict Sphinx build with warnings treated as errors
  • cargo oxide run unroll_smoke on sm_100a
  • cargo oxide run gemm_sol correctness and performance validation on sm_100a

Checklist

  • All 24 PR commits include Signed-off-by
  • No files under crates/cuda-bindings/ are modified
  • New Rust source files include SPDX headers

@nihalpasham nihalpasham added enhancement New feature or request build-related Build scripts, toolchain discovery, or compilation setup perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Jun 25, 2026
nihalpasham and others added 24 commits June 27, 2026 05:48
Foundation for the loop-unroll pass (transform body still TODO):
- [patch] pliron -> local ~/dev/pliron (feat/op-clone: master + IrMapping/clone).
  DEV-ONLY; drop before any push/PR.
- UnrollAttr (mir.unroll) on dialect-mir func ops.
- #[unroll]/#[unroll(N)] proc-macro -> __unroll_config marker -> UnrollAttr(factor)
  on MirFuncOp (0=full, n=by-n); confirmed on dumps.
- mir-transforms crate scaffold (unroll_annotated_loops stub).
- examples/unroll_smoke (full + partial unroll kernels).

Known: marker call/fn leak into IR (drop-arm matches demangled, not mangled
callee). Transform body (loop detect + clone/rewire) not yet wired.

Signed-off-by: Nihal Pasham <[email protected]>
LoopInfo: dominator + back-edge based natural-loop detection (LLVM-style),
the reusable analysis future loop passes (LICM, LSR) consume too. Per loop:
header, latch(es), body set, preheader, exiting/exit blocks, nesting forest.

Wired unroll_annotated_loops into pipeline.rs right after mem2reg (no-op
without #[unroll]); detects + logs loops under CUDA_OXIDE_VERBOSE. Validated
on unroll_smoke: both loops found with correct header/preheader/latch/exit,
no false positives from the Option-match cond_br chains.

Signed-off-by: Nihal Pasham <[email protected]>
Per-loop IV analysis: classifies each header block-arg as basic IV
(latch feeds arg+const), reduction (carried, non-constant recurrence like
acc), or invariant; derives {init,step} from the preheader/latch edges and
the trip count from the exit guard (IV <pred> bound). Conservative: anything
off the counted-loop shape yields Unknown/None, never a guess.

Validated on unroll_smoke: full -> IV i {init:0,step:1} bound:8 trip:8, acc
tagged Reduction; partial -> same IV, runtime bound (trip None).

Signed-off-by: Nihal Pasham <[email protected]>
…tep 3)

For a constant-trip counted loop, lay T straight-line copies of the body
into the preheader, substituting the induction variable with the literal
(init + k*step) per copy and threading the other carried values; redirect
the preheader back-edge to the exit and let simplify_cfg delete the dead
header/latch. Built on LoopInfo + IV analysis + pliron IR cloning. Canonical
{header, latch} shape only (bails gracefully otherwise).

Validated on unroll_smoke full_unroll (while i<8 { acc += i & 3 }): emitted
IR is 8 straight-line copies with i a literal 0..7, so i&3 are constants;
opt -O2 folds the whole loop to `add i32 %base, 12` (= 0+1+2+3+0+1+2+3).
Loop gone, result provably base+12, verifies + lowers + PTX OK.

Signed-off-by: Nihal Pasham <[email protected]>
Move loop_info.rs + induction.rs into mir-transforms/src/analyses/, mirroring
pliron (analyses/liveness.rs, graph/dominance.rs): concept-named files, no
-analysis suffix, the directory marks them as read-only analyses. The transform
(unroll.rs) stays at the crate root, keeping analysis vs transform separated.

Signed-off-by: Nihal Pasham <[email protected]>
For a counted loop unrolled by N, keep the original header/latch as the
REMAINDER (runs the trip % N tail one iteration at a time) and prepend a MAIN
loop that lays N body copies per trip and steps the counter by N*step. The
main guard "(i + (N-1)*step) <pred> bound" runs the main loop only while a full
group of N remains, then falls into the remainder. Counting-up loops only;
bails otherwise. IV analysis extended with the runtime bound value.

Validated on unroll_smoke partial_unroll (#[unroll(4)] while i<n { acc+=i }):
IR shows main loop = 4 copies (acc+=i,i+1,i+2,i+3) stepping by 4 + a remainder
loop for the tail; acc threaded correctly; all verifies pass; lowers to PTX.
For n=10 -> 2 main passes (i=0..7) + remainder (i=8,9) = sum 0..9 = 45.

Signed-off-by: Nihal Pasham <[email protected]>
…(step 5)

After partial unroll the main-loop counter is a multiple of factor*step
(starts at init, steps by factor*step), so mh_iv ≡ init (mod factor*step).
fold_iv_congruences folds `(affine-in-IV) & mask` to the literal that
congruence guarantees, when mask+1 is a power of two dividing the modulus:
`(k+j) & (N-1)` -> j. This makes the gemm "stage index" fold deterministically
in OUR IR, not relying on opt -O2 (which was verified NOT to recover it).
Runs dce + simplify_cfg cleanup after unrolling.

New unroll_smoke kernel partial_fold (#[unroll(4)] while i<n { acc += i&3 }):
our .ll main loop now does acc += 0,1,2,3 (literals); opt folds to acc += 6;
remainder keeps runtime i&3. n=10 -> 2*6 + (8&3)+(9&3) = 13 = sum(i&3,0..10).

Known follow-up: mir arithmetic ops do not yet declare side-effect-freedom, so
our dce leaves the now-dead bitands (opt removes them); impl SideEffects on the
pure mir ops to let dce clean them.

Signed-off-by: Nihal Pasham <[email protected]>
This pass is the reference example for writing optimization passes in oxide, so
the docs must teach. Every compiler term (induction variable, recurrence,
congruence, affine, dominates, back-edge, natural loop, reducible CFG, latch,
preheader, trip count, reduction, block arguments/phi) is now defined inline on
first use, with small worked examples (e.g. (iv+j)&3 -> 0,1,2,3; for i in 0..4
-> f(0);f(1);f(2);f(3)). Comments only; zero code/behavior change (verified).

Signed-off-by: Nihal Pasham <[email protected]>
A locatable marker op planted inside a loop body, carrying an UnrollAttr
factor (0 = full, n = by n). The #[kernel] macro turns an on-the-loop
#[unroll]/#[unroll(N)] into one of these at the loop body start; because it
physically sits in the loop, the unroll pass maps it back to the exact loop
via LoopInfo (no source-span matching). The pass reads the factor, unrolls,
and deletes the hint, so it never reaches lowering. First brick of per-loop
precision (replacing the function-level UnrollAttr marker).

Signed-off-by: Nihal Pasham <[email protected]>
…form

Move loop unrolling from a whole-function attribute to a per-loop one:
`#[unroll]` / `#[unroll(N)]` now go directly on the loop they target, so a
function can unroll one loop and leave its neighbours alone.

Pipeline:
- cuda-macros: #[kernel] walks the body and, for each for/while/loop
  carrying #[unroll], strips the attr and injects a
  `__unroll_config::<FACTOR>()` marker as that loop's first statement.
- mir-importer: the marker call is rewritten in place to a
  `mir.unroll_hint` op (factor = const generic, 0 = full), planted inside
  the loop body. Matches both the re-exported and full marker paths.
- mir-transforms: the pass collects hints, maps each to its enclosing loop
  via LoopInfo, removes the hint, and full- or partial-unrolls just that
  loop. A simplify_cfg normalization runs first so the marker call's block
  split (an extra block inside the loop body) is merged away, restoring the
  simple loop shape the transform expects; a fresh AnalysisManager is used
  afterwards since that rewrites the CFG.
- mir-lower: drop any stray `mir.unroll_hint` during lowering (safety net
  for debug builds that bypass the pass).
- collector: skip the empty `__unroll_config` marker fn so it no longer
  leaks as a dead `.func` into the generated PTX.

Retire the old function-level `#[unroll]` proc macro and its dead
detection path. It was a stop-gap; unrolling "the whole function" has no
well-defined meaning, and under the per-loop design its marker landed in
the entry block and did nothing. Removes the macro, its cuda-device
re-export, and body.rs's detect_unroll_config / set_unroll_attr* /
UNROLL_ATTR_KEY plus their test. UnrollAttr stays as the hint op's factor.

Verified on RTX 5090 (sm_120a): unroll_smoke PASS. Proven at the
dialect-mir level with CUDA_OXIDE_NO_OPT=1 (so the transform, not LLVM,
does the work): full unroll collapses `while i<8 { acc += i&3 }` to
`out = tid + 12`; `#[unroll(4)]` produces a main loop (acc += 6 via the
IV-congruence index fold) plus a remainder loop for the tail.

Signed-off-by: Nihal Pasham <[email protected]>
…-set clone)

The unroller previously handled only loops whose body was a single basic
block (header + latch). That excludes essentially every real kernel loop,
since any `if`/`else`/`match`/`&&`/`||` inside the body makes it several
blocks. Generalize it the way LLVM does: clone the loop's whole body block
set per unrolled copy and rewire the boundary edges.

How:
- analyze_shape gathers the loop facts and enforces the v1 shape (single
  latch, single exit taken only by the header test, recognized counter,
  dedicated preheader, no nested loops), returning a plain-English reason
  on any miss.
- full_unroll / partial_unroll clone the body blocks (in RPO) via pliron's
  clone_blocks_into + IrMapping, which auto-remaps intra-body branches and
  block-arg passes; we substitute the header's carried values per copy and
  wire copy-to-copy edges (the header is not cloned, so the counter stays a
  literal per copy and the index fold still fires). partial reuses the
  original loop as the remainder. fold_iv_congruences now scans all copy
  blocks.

No more silent no-op: a `#[unroll]` on a loop we cannot handle now emits a
loud warning naming the exact reason instead of doing nothing. The pass
also runs verify_operation after cleanup as a self-check, turning any
malformed-IR bug into a loud failure rather than a downstream miscompile.

Correctness fixes (found via adversarial review + bringup):
- live-outs: the exit can read a header block-argument directly by
  dominance (this IR is not loop-closed SSA), so full unroll repoints
  out-of-loop uses of header args to the final values; otherwise they
  dangle once the header is deleted.
- partial unroll requires a loop-invariant bound: the "does a group of N
  iterations fit" guard is only sound when the bound does not change inside
  the loop. Bail loudly on a loop-carried/in-loop bound (would otherwise
  miscompile), rather than the unsound remap.
- reject header-computed live-outs on the exit edge (would dangle on header
  deletion); leave that shape to the header-cloning follow-up.
- materialize IV constants with APInt::from_i128, not from_i64 (avoids
  truncation for wide counters).

Validated on RTX 5090 (sm_120a): unroll_smoke now exercises 6 kernels,
including two with internal control flow (full_mb -> tid+52, partial_mb ->
520) and a loop-carried-bound guard (carried_bound, which must bail and run
correctly). PASS with and without opt (CUDA_OXIDE_NO_OPT=1), so the pass
itself does the unrolling. Nested-loop unrolling (which gemm's mma loop
needs) is the next follow-up.

Signed-off-by: Nihal Pasham <[email protected]>
Allow `#[unroll]` / `#[unroll(N)]` on a loop that sits inside another loop,
as long as the annotated loop does not itself contain a further inner loop.
This is what real kernels need: gemm's mma loop is an inner loop nested in
the K-loop.

The change is small because the body-set clone already does the right
thing. analyze_shape's nesting guard relaxes from "bail if the loop has a
parent or children" to "bail only if it has children" (a loop that contains
another would have to duplicate that inner loop too, which is a follow-up).
An inner loop's body reads the outer loop's values (the outer counter,
outer-carried accumulators) by dominance; clone_one_copy seeds only the
inner header's arguments into the mapping, so those outer values pass
through untouched and still dominate the clones.

Also fix constant bounds in partial unroll: the literal in `while j < 4`
has its constant op inside the loop, which the loop-invariant-bound guard
wrongly rejected. A constant's value never changes regardless of where its
op sits, so re-materialize it in the new main header (where it dominates the
guard). Non-constant bounds must still be loop-invariant (defined outside
the loop) or the pass bails.

Hardening (from adversarial review, which found no correctness bugs):
- process hinted loops in a stable order (by id) so diagnostics are
  deterministic.
- document why the once-computed LoopInfo stays valid across sequential
  unrolls (disjoint loops keep distinct blocks; an outer+inner pair is never
  both unrolled), and why the children-guard is load-bearing.

Validated on RTX 5090 (sm_120a): unroll_smoke now runs 9 kernels including
nested_full (inner full unroll reading the outer counter -> 270),
nested_partial (inner partial-by-2, constant bound -> 240), and
nested_var_bound (inner partial with the outer counter as bound -> 120), all
PASS with and without opt. On gemm_sol_clc_multicast_4_stage_pipeline the
nested mma loop unrolls to 4 tcgen05.mma at NO_OPT while the other seven
kernels stay at 1, so the pass does the work on exactly the annotated loop.

Signed-off-by: Nihal Pasham <[email protected]>
pliron's `dce` only removes a dead-result op when the op reports it has no
side effects (the `SideEffects` interface); with no impl it conservatively
keeps the op. Our mir value ops didn't implement it, so dead ops a transform
leaves behind (e.g. the `x & mask` the unroller folds to a constant, or an
induction-variable increment that goes unused after full unroll) survived our
own dce and were only cleaned up later by LLVM's `opt`.

Implement `SideEffects { has_side_effects = false }` for the pure ops:
arithmetic (wrapping + overflow-checked, bitwise, shifts, div/rem), the
comparisons, constants, and cast. Memory ops, calls, asserts, debug, storage
markers, and terminators are deliberately left out (the safe default keeps
them). div/rem are included because on the GPU target a zero divisor doesn't
trap, and removing a dead div/rem is a sound refinement regardless.

Validated: with CUDA_OXIDE_NO_OPT=1, unroll_smoke's partial_fold goes from ~5
`and` ops in the pre-opt LLVM IR (4 dead folded masks + the remainder's real
one) down to 1, and the example still passes on the GPU.

Signed-off-by: Nihal Pasham <[email protected]>
…check

mir-transforms had no in-crate tests; the analyses were only exercised
end-to-end on the GPU via the unroll_smoke example. Add a small test-support
module that builds dialect-mir CFGs by hand (a canonical counted loop
`while i < n { acc += i; i += 1 }` in post-mem2reg shape), and three unit
tests on it:

- LoopInfo finds the single natural loop with the right header/latch/body,
  preheader, exit, exiting block, and innermost-loop mapping.
- induction recognizes `i` as a BasicIv (init 0, step 1), `acc` as a
  reduction, the continue predicate as `<`, and the trip count as 8.
- analyze_shape accepts the canonical loop and reports the right facts
  (single-block body, iv index/init/step).

These pin the analyses' behavior independent of the GPU pipeline and give a
foundation for testing more loop shapes.

Signed-off-by: Nihal Pasham <[email protected]>
…ependent)

Run sccp -> simplify_cfg -> dce inside the unroll pass, gated on `changed`, so the
index math an unroll exposes (`i & 3` / `i % 4`, the gemm pipeline-stage index)
folds to constants in our own middle-end rather than relying on `opt -O2` (and,
later, the NVVM backend). Scoped to functions actually unrolled; other kernels
are untouched and lowered exactly as before.

- dialect-mir: implement pliron's ConstFoldInterface on the pure integer ops
  (arith / bitwise / shift / div / rem / comparison) and on mir.constant (the
  lattice seed), and BranchOpFoldInterface on mir.cond_br (so simplify_cfg
  collapses a constant-condition branch). Folds compute on APInt with Rust
  semantics: wrapping add/sub/mul, signedness read from the operand type, and
  div/rem-by-zero left unfolded.
- mir-lower: sccp materialises constants as `builtin.constant` carrying the MIR
  signed/unsigned integer type; normalise a non-signless `builtin.constant` to
  signless during lowering (like mir.constant), gated so the DialectConversion
  worklist converges instead of re-feeding itself.
- unroll: extend the in-pass index fold to `% 2^k` (not just `& mask`) and rename
  it `fold_constant_index_in_copies`; drop the now-moot RPO-for-cloning ordering
  (PR #134 made clone_blocks_into order-independent), keeping the reachability
  check; fix a doc comment misattached to extract_unroll_factor; add a
  partial_mod (`i % 4`) kernel to unroll_smoke.

unroll_smoke PASSES all kernels on RTX 5090; full_unroll's `i & 3` folds to
literals in the pre-opt .ll (no reliance on opt).

Signed-off-by: Nihal Pasham <[email protected]>
The loop-unroll pass depends on pliron op-cloning (IRMapping +
clone_blocks_into) and APInt bitwise ops, which have now landed on
pliron master (PR #134 + #131). Bump the rev 847561916 -> 222dd962
and drop the local [patch] override that pointed at a working-copy
checkout (it could never build on CI).

Master's signature change (IntegerType/FuncType/PointerType::get now
take &Context, not &mut) surfaces as clippy unnecessary_mut_passed
across the workspace; fix those &mut ctx -> &ctx sites.

mir-transforms tests: move the inline unit tests out to tests/, split
by area (shared builders in common/, plus loop_info / induction /
unroll-pass suites). The unroll-pass test now drives the public
unroll_annotated_loops end to end (full unroll deletes the loop)
instead of poking the private shape analysis. Add mir-transforms to
the unit-tests CI matrix (it was missing).

dialect-mir: replace the temporary const-fold repro harness with real
asserting tests for the fold interfaces (arithmetic, bitwise, shifts,
div/rem with the div-by-zero guard, comparisons with signedness, and
the cond_br successor fold).

Signed-off-by: Nihal Pasham <[email protected]>
…fold example

Style pass on the const_fold module doc: replace the one em-dash with a
colon, break the nested-parenthetical opening sentence into two, and add
a one-line example of what does and does not fold (5/2 folds, 5/0 and an
over-wide shift do not).

Signed-off-by: Nihal Pasham <[email protected]>
The examples clippy CI step (cargo clippy --all-targets -- -D warnings,
run per example) flagged `.flat_map(|k| (0..k).map(|j| j))` in the host
verification harness. `(0..k)` already yields `j`, so the `.map` is the
identity. Drop it: `.flat_map(|k| 0..k)`.

Signed-off-by: Nihal Pasham <[email protected]>
Lift the `!children` bail in analyze_shape and rework unroll_annotated_loops into a per-function round loop that recomputes DomTree+LoopInfo each round (innermost-first) before unrolling one loop. An outer loop whose body contains a loop now unrolls by cloning the inner loop wholesale (it stays a loop, never recursively unrolled); the recompute re-registers the cloned inner loops. clone_blocks_into and the partial index-fold were already general enough and are unchanged.

Tests: nested_outer_full/partial unit tests, plus outer_full/outer_partial kernels in unroll_smoke (PASS on RTX 5090).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Nihal Pasham <[email protected]>
#[unroll(4)] on the MMA-warp K-loop with a loop-local stage index (k_idx & 3, sound since k_iters % 4 == 0) folds the 4-way buffer/barrier select away so the MMAs issue back-to-back: +47.7% @4096 (208.9 -> 308 TFLOPS). SWIZZLE_G=8 cache-blocking rasterization carries the large sizes (16384 goes 43% -> 79.7% of cuBLAS SoL). Sweep is now 313/331/341 TFLOPS at 4k/8k/16k, within ~2% of the hand-optimized autocuda kernel.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: Nihal Pasham <[email protected]>
@nihalpasham
nihalpasham force-pushed the feat/loop-unroll-pass branch from 964a308 to 47b0da7 Compare June 27, 2026 05:58
@nihalpasham
nihalpasham merged commit 9e923e9 into main Jun 27, 2026
25 checks passed
@nihalpasham
nihalpasham deleted the feat/loop-unroll-pass branch June 27, 2026 06:13
meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

build-related Build scripts, toolchain discovery, or compilation setup codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant