Skip to content

feat(codegen): forward compiler-owned multi-result bundles - #888

Merged
nihalpasham merged 3 commits into
NVIDIA:mainfrom
lucifer1004:pr/compiler-result-forwarding
Aug 16, 2026
Merged

nihalpasham merged 3 commits into
NVIDIA:mainfrom
lucifer1004:pr/compiler-result-forwarding

Conversation

@lucifer1004

@lucifer1004 lucifer1004 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

  • Multi-result inline PTX (a generated intrinsic like tcgen05_ld returning [u32; 32]) comes back from the importer as an aggregate bundle that gets spilled to stack memory, even though the compiler created it itself and knows it never escapes. Downstream opt -O2 cleans that up today, so the spill reaches final PTX only in CUDA_OXIDE_NO_OPT=1 builds; the pass makes the compiler's own MIR output clean without leaning on LLVM to fix it:
let regs = tcgen05_ld_32x32b_x4(addr);   // 1 instruction, 4 registers
out[0] = regs.get::<0>() + regs.get::<3>();

What the compiler hands to LLVM without this pass (and what reaches
final PTX under CUDA_OXIDE_NO_OPT=1):
         tcgen05.ld {%r1,%r2,%r3,%r4}, [taddr];
         st.local x4 ... ld.local x2 ...     // spill and reload
         add.u32  %r7, %r5, %r6;
With the pass:
         tcgen05.ld {%r1,%r2,%r3,%r4}, [taddr];
         add.u32  %r7, %r1, %r4;             // registers used directly

Measured on tcgen05_matmul (sm_100a), pass on vs off:
  default pipeline (opt -O2):  final PTX byte-identical (SROA cleans the
                               spills downstream either way)
  CUDA_OXIDE_NO_OPT=1:         8 fewer st.local + 8 fewer ld.local,
                               local depot 68B -> 36B, 8 fewer .b32 regs
  • Separately, ptx_asm! capped outputs at 16, which is too small for tcgen05-scale loads.

Fix

  • the importer marks bundles it created as compiler-owned
  • a new mir-transforms pass (forward_compiler_result_bundles) runs before mem2reg and forwards each element read straight to the producing value, then deletes the bundle once every use is forwarded
  • anything it cannot prove is safe (dynamic index, escape, partial read) drops the whole plan and keeps the memory path, so behavior is never guessed
  • raised the ptx_asm! output arity from 16 to 64
  • review follow-up 2d42ced: a whole-array read through a struct-wrapped bundle (the CuSimd::to_array() pattern) used to make the pass erase one of its own construct ops while it still had uses, which pliron panics on; that case now bails out to the memory path

Gotchas

  • ordinary Rust arrays never qualify; only the importer can attach the marker. So Scalarize small local arrays consumed through iterator adapters #399 (keeping iterator-chain arrays in SSA) stays open by design, this pass is not that
  • non-constant indices reject the whole bundle rather than partially forwarding
  • 14 ldmatrix sites still use the older bundling helper and do not forward yet; reasonable follow-up

Testing and validation

  • mir-transforms suite green, including a regression test for the erase panic (verified it fires when the guard is disabled)
  • 64-output ptx_asm! accept test sits next to the existing 65-output reject test; full cuda-macros and trybuild suites green
  • generator consistency check clean
  • CI green (43/43)

@nihalpasham nihalpasham added enhancement New feature or request codegen Device code-generation pipeline (Rust MIR to IR to PTX) perf Performance of generated code or of the compiler itself intrinsics Device intrinsics and libdevice math mappings cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) labels Aug 16, 2026
…rding

A struct-wrapped bundle (e.g. the CuSimd wrapper the importer emits for
multi-result intrinsics) read back in one piece via a field-addr plus a
whole-array load resolves the replacement to one of the bundle's own
construct ops. Forwarding that load and then erasing the bundle nodes
left live uses of an erased operation, which panics in pliron's
Operation::erase. Reject such replacements in analyze_projection so the
plan falls back to the memory path.

Also widen the pass unit fixture to a parameterized result width and add
a positive 64-result forwarding test plus a 64-output ptx_asm! accept
test (the trybuild suite only covered rejection at 65).
@nihalpasham

nihalpasham commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Gist: good pass, and it earns its keep: compiler-owned multi-result bundles stay in registers instead of bouncing through .local. One real crash found in review: a whole-array read through a struct-wrapped bundle (the CuSimd::to_array() pattern) made the pass hand back one of its own construct ops as the replacement, then erase it while it still had uses, which pliron panics on.

What I checked and did:

  • reproduced the panic with the guard disabled, so the regression test provably hits the bug
  • pushed 2d42ced: fail-closed rejection in analyze_projection when the replacement is one of the bundle's own construct ops (the memory path plus mem2reg picks those up instead), plus the regression test and positive 64-output ptx_asm! coverage next to the 65-reject test
  • pushed 79f39bd: two clippy nits in the new code
  • element-wise loads through the struct wrapper still forward; generator consistency check clean; all suites green

Also confirmed #399 stays open: that issue wants ordinary iterator-chain arrays in SSA, which this pass rules out by design.

Update, measured evidence (pass on vs off, same commit): under the default pipeline the final PTX is byte-identical for tcgen05_matmul, gemm_sol, tcgen05, and vecadd; downstream opt -O2 (SROA/mem2reg) already removes every bundle spill. The pass pays off in CUDA_OXIDE_NO_OPT=1 builds: on tcgen05_matmul it removes 8 st.local + 8 ld.local round-trips, shrinks the kernel local depot from 68B to 36B, and saves 8 .b32 registers, with tcgen05.ld results feeding cvt.rn.bf16x2.f32 directly. So the honest framing: no final-PTX change under default settings today; the win is clean MIR-level output that does not depend on LLVM's optimizer, plus the NO_OPT escape hatch, plus the arity raise.

@nihalpasham

Copy link
Copy Markdown
Collaborator

Gist of the decision: taking this, and I want to be precise about why, since I measured it. Under the default pipeline this pass changes nothing today: final PTX is byte-identical with it on or off, because opt -O2 already cleans up the bundle spills downstream.

What I'm taking it for:

  • the compiler stops depending on LLVM's optimizer to clean up spills it generated itself; the MIR we hand downstream is right by construction, which keeps options open for a pipeline that leans less on LLVM
  • CUDA_OXIDE_NO_OPT=1 builds (the mode you reach for when debugging the optimizer) get the proven win: 8 fewer st.local + 8 fewer ld.local, local depot 68B down to 36B, 8 fewer registers on tcgen05_matmul
  • the ptx_asm! arity raise to 64 is needed regardless of any of the above

So: accepted for self-sufficiency and the escape hatch, with eyes open that default-pipeline PTX is unchanged today. If the pipeline ever routes around LLVM's optimizer, this pass is already sitting where it needs to be.

@nihalpasham
nihalpasham merged commit b6f263a into NVIDIA:main Aug 16, 2026
44 checks passed
nihalpasham pushed a commit that referenced this pull request Aug 18, 2026
…alves #965 missed (#972)

#965 corrected this README's type and operation tables. It left the other two
inventories on the same page, and both are stale in the same way -- one of them
now contradicting the tables #965 just fixed.

**Attributes: "four" -> seven.** `src/attributes.rs` has seven
`#[pliron_attr(...)]` declarations; the table lists four. The three missing
ones are all recent, and two pair directly with ops the README already lists:

  mir.fp16_attr               MirFP16Attr                `f16` constant values,
                                                         paired with MirFP16Type
  mir.unroll                  UnrollAttr                 the factor carried by
                                                         `mir.unroll_hint`
  mir.compiler_result_bundle  CompilerResultBundleAttr    the multi-result return
                                                         ABI marker from #888

`mir.unroll` is the clearest case: #965 added `mir.unroll_hint` to the
operations table, and the attribute that op exists to carry was three rows
below, undocumented.

**Source Layout tree.** It contradicts the page above it:

  types.rs        "# 7 MIR types"      -- the Types table now says nine
  attributes.rs   "# 4 ... attributes" -- see above
  ops/            no `debug.rs`        -- the Operations table now lists it
  src/            no `const_fold.rs`, `rust_intrinsics.rs`, `side_effects.rs`

So a reader who trusted the tree came away with different numbers than a reader
who trusted the tables, on one page. Three module comments were also narrower
than their files (`control_flow` also carries unroll hints, `memory` also
`memcpy`/`memmove`, `aggregate` also slices) -- all ops #965 added to the table
without the tree following.

Both inventories now state the rule that makes them checkable, as the
operations table does: one row per `#[pliron_attr(...)]`, one tree entry per
file.

Verified by script against the tree: the attributes table matches all seven
`(name, Rust type)` pairs exactly -- `MirCastKindAttr` is a `pub enum`, the
rest are `pub struct` -- and the Source Layout tree matches `src/*.rs` plus
`src/ops/*.rs` exactly, 19 files listed and 19 on disk, none missing and none
invented. check-crate-inventory passes.

Signed-off-by: Vyncint Ng <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codegen Device code-generation pipeline (Rust MIR to IR to PTX) cuda-feature A CUDA hardware/toolkit feature (TMA, tcgen05, WGMMA) enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants