Skip to content

perf(mir-importer): materialize a bare array constant as one immutable global - #684

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
vyncint:perf/const-array-immutable-global
Aug 7, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
vyncint:perf/const-array-immutable-global

Conversation

@vyncint

@vyncint vyncint commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Refs #397.

Summary

const TABLE: [T; N] indexed by a runtime value was built element by element and
stored into the local's stack slot, so every thread wrote its own copy of data
the module image already carries
: one st.local per element, then ld.local
reads of thread-private memory. The identical data written &[T; N] has always
become a single immutable device global read with one load, so two spellings of
one table cost very different amounts.

This assigns the constant with mir.memcpy from that same promoted global.

Three parts:

  • mir-importer — a new arm in the existing "array initializers assigned to
    an addressable local" fast-path block emits mir.global_alloc + mir.memcpy
    instead of building the array as a value. The promoted-global emission is
    factored out of translate_ptr_to_array_constant, so both spellings now share
    one code path and one content-keyed dedup.
  • dialect-mir / mir-lower / llvm-export — MirGlobalAllocOp carries a
    global_immutable marker through to llvm::GlobalOp, and the exporter writes
    LLVM constant rather than global for it.
  • a write-once guard, without which this would regress the mutable case.

Why a copy, and not the global's address

The local is ordinary mutable storage — let mut t = TABLE; t[0] = x; is legal —
so handing out the global's address would be wrong in general, and proving the
local is never written is exactly the analysis I wanted to avoid writing.

A memcpy from constant storage is unconditionally correct, and opt already
supplies that proof
: isOnlyCopiedFromConstantMemory deletes the copy and
rewrites the reads to the global wherever the local is never written, and keeps
the copy wherever it is.

That is also why the constant keyword is load-bearing rather than cosmetic. It
is what makes reads of the storage invariant, which both enables the elimination
and makes llc select ld.global.nc (the read-only data cache).

A whole-array load cannot reach the global however it is spelled. I probed
four shapes through opt -passes='default<O2>' at LLVM 22.1.2 on the pinned
toolchain, NVPTX triple, 256 x f32:

shape after opt -O2
alloca + insertvalue chain + aggregate store (today) 256 st.local survive
constant global + whole-array load + store to alloca fails — SROA splits the FCA load (.fca.N.gep) and folds it back into per-element stores
constant global + llvm.memcpy into alloca collapses to gep @global; load
same, but the alloca is also written copy retained

So only a memcpy survives to where the proof runs. Plain external linkage is
enough — no private/unnamed_addr needed — which is why the exporter change is
one keyword.

The marker is a property of storage, not of a pointer

global_immutable is set only at the promoted-constant sites, never for a
Rust static, whose bytes the host can still overwrite by symbol
(ensure_static_global_alloc is untouched). MirPtrType::is_mutable is
deliberately not consulted: a shared reference to a mutable static is an
immutable pointer to mutable storage, and #413 records that is_mutable must not
be read as a promise about the pointee. There is a test asserting lowering does
not infer immutability.

The write-once guard

Without it this trades one cost for another. When the local is written the
copy survives, and NVPTX expands a surviving memcpy into a byte loop —
measurably worse than the element-wise stores it replaced. So
constant_local_is_written_once rejects a local that is assigned more than once,
borrowed at all (either mutability), or written by a call.

The guard only chooses between two correct lowerings — both give the local a
private copy — so an unrecognised write form costs performance, never
correctness. That is why its statement match ends in a catch-all rather than an
error.

Checked directly: a kernel doing let mut t = TABLE; t[0] = input[i] as f32;
still emits 64 st.local.b32 with no memcpy loop, while the read-only kernel
beside it emits no depot and one ld.global.nc.b32.

Measured

A10G, from the evidence log's nvidia-smi block:

name, compute_cap, memory.total [MiB], driver_version
NVIDIA A10G, 8.6, 23028 MiB, 595.71.05

8388608 threads x 64 divergent lookups per thread (536870912 lookups per launch),
50 timed launches after 10 warmup. Same kernels and same workload in both runs;
only the report's labels differ. Every kernel bit-correct against a host
reference in both.

Before (.gpu-evidence/20260807T001402Z.log):

kernel            entries    space   us/launch   Glookups/s   correct
----------------------------------------------------------------------
lut16_value            16   .local      1282.3       418.67       yes
lut16_ref              16  .global       374.3      1434.36       yes
lut16_constant         16   .const      1283.3       418.35       yes
lut256_value          256   .local     16044.1        33.46       yes
lut256_ref            256  .global       321.8      1668.22       yes
lut256_constant       256   .const     16045.2        33.46       yes

After (.gpu-evidence/20260807T012016Z.log):

kernel            entries     spelling   us/launch   Glookups/s   correct
--------------------------------------------------------------------------
lut16_value            16     [f32; N]       374.3      1434.52       yes
lut16_ref              16    &[f32; N]       374.2      1434.60       yes
lut16_constant         16  ConstantMem      1294.6       414.70       yes
lut256_value          256     [f32; N]       324.1      1656.52       yes
lut256_ref            256    &[f32; N]       324.1      1656.52       yes
lut256_constant       256  ConstantMem     16053.5        33.44       yes

time relative to the `&[f32; N]` spelling (1.00x = same cost):
--------------------------------------------------------------------------
   16 entries:  [f32; N]   1.00x   ConstantMem    3.46x
  256 entries:  [f32; N]   1.00x   ConstantMem   49.53x
entries spelling before after speedup
16 [f32; N] 1282.3 us 374.3 us 3.43x
256 [f32; N] 16044.1 us 324.1 us 49.50x
16 &[f32; N] 374.3 us 374.2 us 1.00x (control)
256 &[f32; N] 321.8 us 324.1 us 0.99x (control)

[f32; N] now costs what &[f32; N] costs, to within 1%, and the controls did
not move. PTX for the 256-entry kernel goes from 309 instructions with a 1 KiB
local depot and 256 st.local
to 70 instructions with no depot, and the
table read becomes ld.global.nc.

Two entry counts are measured because ptxas can rescue a small table on its
own. Worth flagging: ptxas -v reported "0 bytes stack frame" for every one of
these kernels, before and after
— it is not a usable signal for this, and only
the runtime measurement exposed it.

How this differs from #398 and #636

Both were closed for good reasons that this does not reproduce.

  • They attacked the read, replacing a dynamic load with a select chain. Scalarize small local arrays used by iterator adapters #636
    measured 16-19% slower on the workload it targeted. The dominant cost here
    is the initialization — N stores per thread against K reads — which select
    chains do not touch. That is also why the small-table case only moves 3.4x
    while the 256-entry case moves 49.5x: the cost is linear in N.
  • fix(mir): keep small runtime-indexed arrays in SSA #398 was rejected partly because gemm_sol's PTX grew ~64%. This shrinks
    PTX (309 -> 70 on the affected kernel) and adds no pipeline stage: no extra
    opt run, no unroller, no env plumbing. Kernels that never materialize an
    array constant are untouched.
  • No textual IR rewriting. The transformation is in the typed MIR the importer
    already builds, and the elimination is opt's own existing pass.

I have not tried to close #397 with this — the iterator-adapter half (#399) and
mutable local scratch arrays are untouched, and the guard deliberately declines
anything it cannot see is write-once.

Also here, deliberately unfixed

ConstantMemory::get() returns T by value, so a ConstantMemory<[f32; N]>
reads all N entries out of .const and writes them into a local depot. It still
measures 3.46x / 49.53x off the other two spellings, so .const cannot back a
lookup table today. This is a separate defect in cuda-device's API shape rather
than in lowering, so I left it alone and kept it in the example as the contrast.
Happy to file it separately if useful.

New example

const_table_lookup measures the three spellings of one table side by side and
keeps their agreement checked. The index comes from a per-thread LCG so it is
unpredictable and lane-divergent, and the kernel is lookup-bound rather than
bandwidth-bound (4 bytes in, 4 bytes out per thread). All six kernels verify
bit-exactly against a host reference computed with the same add order.

Validation

Local (fmt, clippy, unit tests, docs, doctests all clean):

cargo fmt --check
cargo clippy --all-targets --lib --tests -- -D warnings
cargo test -p mir-lower -p llvm-export -p dialect-mir -p dialect-nvvm \
           -p mir-importer -p cuda-oxide-codegen --lib --tests     # 17 suites ok
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace
cargo test --doc --workspace --exclude cuda-bindings
bash scripts/check-dependency-licenses.sh                          # OK
bash scripts/check-error-example-status.sh                          # OK

On the A10G:

  • full smoketest 188/188, 0 fail (.gpu-evidence/20260807T005028Z.log)
  • scoped re-run 16/16 with the guard in place
    (.gpu-evidence/20260807T012016Z.log), covering array_constants,
    array_index, array_init, enum_array_match, cast_tests,
    tuple_array_provenance, tuple_constant_provenance, uninit_const,
    device_global, constant_memory_coeffs, place_read_fallbacks,
    ref_index_projections, plus vecadd / vectorization as passing controls
    and tma_copy as a skip control

array_constants is the existing regression test for array-constant values, so
it is the one that matters most here; it passes in both runs.

New test: immutable_marking_survives_lowering_and_is_not_assumed asserts the
marker survives MIR -> LLVM lowering and that a plain static does not acquire
it.

Not verified: SASS. nvdisasm is not on the image I used, so the
instruction-level evidence above is PTX only.

…e global

A `const TABLE: [T; N]` indexed by a runtime value was built element by
element and stored into the local's stack slot, so every thread wrote its
own copy of data the module image already carries: one `st.local` per
element, then `ld.local` reads of thread-private memory. The identical
data written `&[T; N]` has always become a single immutable device global
read with one load, so the two spellings of one table cost wildly
different amounts.

Assign the constant with `mir.memcpy` from that same promoted global
instead. The copy is what keeps this correct without new analysis: the
local is ordinary mutable storage, and `opt` supplies the proof that
removes the copy, rewriting the reads to the global wherever the local is
never written (`isOnlyCopiedFromConstantMemory`). A whole-array *load*
cannot reach the global however it is spelled, because LLVM splits every
first-class-aggregate load and folds it straight back into per-element
stores; only a memcpy survives to where that proof runs.

For the exporter to write `constant` rather than `global` -- which is
what makes reads of the storage invariant, and what selects
`ld.global.nc` -- `MirGlobalAllocOp` carries a `global_immutable` marker
through to `llvm::GlobalOp`. It is set only at the promoted-constant
sites, never for a Rust `static`, whose bytes the host can still
overwrite by symbol. It describes the storage, not a pointer:
`MirPtrType::is_mutable` is deliberately not consulted, per NVIDIA#413.

A write-once guard keeps the two lowerings from trading places. When the
local *is* written the copy survives, and NVPTX expands a surviving
memcpy into a byte loop -- worse than the element-wise stores it
replaced -- so a local that is assigned more than once, borrowed, or
written by a call keeps today's path. The guard only chooses between two
correct lowerings, so an unrecognised write form costs performance, not
correctness.

Measured on an A10G (sm_86, driver 595.71.05), 8388608 threads x 64
divergent lookups per thread, 50 timed launches after 10 warmup, every
kernel bit-correct against a host reference:

  entries  spelling     before      after    speedup
       16  [f32; N]    1282.3us    374.3us      3.43x
      256  [f32; N]   16044.1us    324.1us     49.50x
       16  &[f32; N]    374.3us    374.2us      1.00x  (control)
      256  &[f32; N]    321.8us    324.1us      0.99x  (control)

`[f32; N]` now costs what `&[f32; N]` costs, to within 1%. PTX for the
256-entry kernel goes from 309 instructions with a 1 KiB local depot and
256 `st.local` to 70 instructions with no depot, and the table read
becomes `ld.global.nc`.

Adds `const_table_lookup`, which measures the three spellings of one
table side by side and keeps their agreement checked. `ConstantMemory` is
deliberately not addressed here and stays as the contrast: `get()`
returns `T` by value, so a `ConstantMemory<[f32; N]>` copies all N
entries out of `.const` into a local depot and still measures 3.46x /
49.53x, so `.const` cannot back a lookup table today.

Refs NVIDIA#397.

Signed-off-by: Vyncint Ng <[email protected]>
@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate) examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples labels Aug 7, 2026
…and the written-copy fallback

Three pieces of coverage layered on the lowering, none changing it:

- llvm-export: a marked global must export as 'constant' and an
  unmarked one must stay 'global'. The keyword is the load-bearing bit
  of the whole design (it is what lets opt delete the copy and llc
  select ld.global.nc), and nothing asserted it textually.
- mir-importer: emit_promoted_immutable_global marks the promoted
  global immutable and keys dedup by the full (type, bytes) image, so
  the same table reached twice shares one global and distinct byte
  images never alias.
- const_table_lookup: a lut256_mut_copy kernel that writes its copy
  before reading it, with a bit-exact host reference. This checks the
  write-once guard's fallback end to end through real MIR: the memcpy
  path must not fire, the copy stays per-thread and element-
  materialized (262 .local lines in the PTX, vs 0 for lut256_value),
  and each thread's unique overwrite proves no cross-thread aliasing.

Verified on an RTX 5090 (sm_120): all 7 kernels bit-correct,
lut256_value at 1.00x of lut256_ref, .ll carries 'addrspace(1)
constant' for both promoted tables.
@nihalpasham

nihalpasham commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Gist: This PR uses the established lowering for this problem:

I pushed one commit on top:

  • llvm-export test for the load-bearing keyword: a marked global exports constant, an unmarked twin stays global, on both NVVM dialects;
  • importer test that promoted globals are marked immutable and dedup by the full (type, bytes) image;
  • a lut256_mut_copy kernel + bit-exact host reference covering the write-once guard's fallback end to end: the written copy stays per-thread and element-materialized (262 .local lines vs 0 for lut256_value).

Verified on an RTX 5090 (sm_120):

  • all 7 kernels bit-correct, lut256_value at 1.00x of lut256_ref with ld.global.nc and
  • zero .local; full smoketest sweep 187/187.

Partially addresses #397 (the read-only by-value subcase; written scratch arrays and #399's iterator shapes stay open).

@nihalpasham
nihalpasham merged commit 2db9713 into NVIDIA:main Aug 7, 2026
34 checks passed
nihalpasham added a commit to nh13/cuda-oxide that referenced this pull request Aug 8, 2026
…m-export against NVIDIA#684's GLOBAL_IMMUTABLE_KEY additions)
nihalpasham added a commit that referenced this pull request Aug 8, 2026
…integer one (#694)

* perf(mir-importer): promote a field-less enum array constant like an integer one

#684 stopped bare array constants being built per thread, but its element gate
admits only primitive scalars and nested arrays of those. A field-less enum array
was left out, even though it holds nothing but discriminants and so is
byte-identical to the `[u32; N]` of its values. It was still materialized into the
per-thread local depot -- one `st.local` per element in every thread, for data the
module image already carries -- and the lookup then read thread-private memory.
There was no way to spell around it either: `&[Op; N]`, the reference form that
works for scalar tables, is rejected outright.

Replace the borrowed `&[T; N]` gate with a predicate of this path's own, which
admits primitive scalars, field-less enums, and nested arrays of either. The byte
image is rustc's evaluated allocation, so the discriminants were never the
question; what the gate has to establish is that reading an element back is
cheap, and for a field-less enum the whole element *is* its discriminant.

Payload-carrying enums, tuples and structs stay out, and not because a byte image
would be wrong. Projecting one field of a tuple element out of a local array
copies the whole array to a fresh stack slot, once per field (#693). Those copies
dominate: promoting a `[(u8, u32); 256]` table leaves its 925 PTX instructions,
4096-byte depot and 878 `st.local` exactly as they were and merely adds a 2 KiB
global. Verified both ways on the A10G before excluding them.

A size guard backs the widening: the copy is sized from the destination's
converted type while the bytes come from rustc, so the two must agree before a
byte image is trusted. `dialect_stored_size` answers from the `total_size` the
storage builders reproduce, and any disagreement falls through to the
element-wise path rather than copying over a differently-sized local.

Measured on an A10G (sm_86, driver 595.71.05), 64 dependent divergent lookups per
thread over 8388608 threads, 50 timed launches after 10 warmup. Every kernel
bit-correct against a host reference in both runs, and each enum table is paired
with a `[u32; N]` table over the same discriminants so the pair isolates the
element type:

  entries  table       before      after    speedup   u32 pair (control)
       16  [Op; N]    1309.4us    361.4us      3.62x    361.4 -> 361.6us
      256  [Op; N]   16073.3us    330.2us     48.68x    327.3 -> 330.0us

An enum table now costs what the integer table of the same values costs, to
within 1% at both sizes, and the controls did not move. PTX for the 256-entry
enum kernel goes from 309 instructions with a 1 KiB depot and 256 `st.local` to
70 with no depot, reading through `ld.global.nc`.

`array_constants`' `verify-code-shape.sh` pinned the enum array's `insertvalue`
chain, so it now asserts the shape that replaced it: the discriminants in the
read-only global's initializer, the copy out of that global, and the same runtime
index and element load. Pinning the whole byte image in one pattern also fixes
their order, which the previous per-discriminant search did not -- a permuted or
truncated table now fails where before it passed. That example's runtime
assertions were unaffected; the values were never in question.

Adds `enum_table_lookup`, which measures both pairs and keeps their agreement
checked.

Closes #692.

Signed-off-by: Vyncint Ng <[email protected]>

* fix(mir-importer): admit a field-less enum table through its reference spelling

The bare-array widening left the second defect of #692 open: the pointer
path still checked elements with its own validator, so
`const R: &[Op; N] = &OPS` kept hard-erroring with "invalid input
program" while `OPS[i]` promoted cleanly.

Route both promoted-constant paths through the one element gate.
`validate_ptr_to_array_constant_type` now asks
`promotable_array_element`, which absorbs the zero-length vacuous
admission (`&[]` for any element type) so nothing the pointer path
accepted is lost, and the two boundaries cannot drift apart again. The
pointer path also gains the same byte-size agreement the bare-array
promotion demands, except here disagreement is an input error because
there is no element-wise lowering to fall back to.

A unit test holds the reference form to the bare-array gate: field-less
enum arrays pass, payload-carrying enums stay out, and the promoted
empty-slice admission survives the rerouting. `enum_table_lookup` gains
`enum256_ref_table`, which reads through `const R: &[Op; 256] = &OPS`
against the same host reference. On an RTX 5090 it runs bit-correct at
the bare enum table's exact cost (106.5us per launch, 1.21x the u32
control for both spellings), and the emitted IR shows it reading the
same deduplicated immutable global the bare table copies from.

---------

Signed-off-by: Vyncint Ng <[email protected]>
Co-authored-by: nihalpasham <[email protected]>
nihalpasham pushed a commit that referenced this pull request Aug 8, 2026
…dex (#691)

`ConstantMemory<T>` had one accessor, `get`, returning `T` by value. That is
right for a scalar but leaves no way to index a `ConstantMemory<[T; N]>` at a
runtime index: a value has no address, so the copy is spilled to the thread's
local depot -- one `st.local` per element in every thread -- and the lookup then
reads thread-private memory. `#[constant]` could not express the shape constant
memory exists for.

Add `get_ref(&self) -> &T`, which borrows the storage in place so the index stays
in constant space. Safe under the contract `get` already relies on: device code
only reads this storage, so no `&mut` exists to alias, and the host writes only
between launches via `cuMemcpyHtoD`. Borrowing through the `UnsafeCell` keeps the
storage mutable as far as the compiler is concerned, so a `set_<name>` between
launches stays visible -- the property that makes the wrapper necessary at all.

No codegen change: a reference into a `#[constant]` static already keeps address
space 4 all the way down. The symbol stays `addrspace(4) global` in LLVM IR and
the read emits one `ld.const.b32`. Only the safe way to obtain that reference was
missing. For the reproducer kernel, 555 PTX instructions with a 1 KiB depot
become 42 with none.

Also corrects `get`'s own advice. It recommended calling `.get()` once for a
large `T` and reusing the local, which is the pathology rather than a way around
it: a local reused across a runtime-indexed read is exactly what forces the
array into the depot.

Measured on an A10G (sm_86, driver 595.71.05), 256-entry f32 table, 64 dependent
lookups per thread over 8388608 threads, 50 timed launches after 10 warmup, every
variant bit-identical against a host reference:

  index pattern    get()      get_ref()   const [f32; N]
  divergent        16048.3us    7616.3us        321.7us
  warp-uniform     16065.4us     258.5us        322.4us

So `get_ref` is 2.1x the throughput of `get` on a divergent index and 62x on a
warp-uniform one. The `get()` row barely moves between the two patterns, because
the per-thread depot copy dominates so completely that the access pattern stops
mattering.

The same measurement settles which address space a table belongs in, which the
docs did not say anywhere. Constant memory is not simply faster memory: its cache
broadcasts, so it wins on a warp-uniform index (258.5us vs 322.4us) and loses
23.7x on a divergent one (7616.3us vs 321.7us), where distinct addresses are
served in sequence while the same table in global memory coalesces and stays in
L1. A divergent lookup table should be a plain `const TABLE: [f32; N]`, which
since #684 is one immutable device global read with `ld.global.nc`. Both the
guidance and the numbers are now in `get_ref`'s docs.

Adds `constant_memory_table`, which measures all six combinations and checks each
against a host reference.

Closes #690.

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) examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Small runtime-indexed local arrays spill to PTX local memory

2 participants