Skip to content

ConstantMemory<[T; N]> cannot be indexed at a runtime index: get() returns T by value, so the table is copied into the local depot #690

Closed

Description

@vyncint

Problem

ConstantMemory<T> exposes exactly one accessor, [get], which returns T
by value. That is right for a scalar, but it leaves no way to index a
ConstantMemory<[T; N]> at a runtime index without materializing the whole
array first. 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.

The canonical CUDA constant-memory use case is exactly this:

__constant__ float coeffs[256];
__global__ void k(...) { acc += coeffs[i & 255]; }   // runtime index

so today #[constant] cannot express the shape it exists for.

The existing examples do not show it because they index at compile-time
constants (constant_memory_coeffs does c[0], c[1]; constant_memory
destructures let [c0, c1, c2, c3] = COEFFS.get();). SROA cleans those up
completely. Only a runtime index falls off the cliff.

The documented workaround makes it worse

get's doc currently advises:

For large T (e.g. ConstantMemory<[f32; 1024]>) call .get() once before
the loop and reuse the local

"Reuse the local" is the pathology — a local reused across a runtime-indexed
read is precisely what forces the array into the depot. There is no fast path
today, so the advice cannot be followed to a good outcome.

Reproducer

#[constant]
static TABLE: ConstantMemory<[f32; 256]> = ConstantMemory::UNINIT;

#[kernel]
pub fn lut(input: &[u32], mut output: DisjointSlice<f32>) {
    let idx = thread::index_1d();
    let i = idx.get();
    if i >= input.len() { return; }
    let v = TABLE.get()[(input[i] >> 24) as usize & 255];
    if let Some(o) = output.get_mut(idx) { *o = v; }
}

PTX on sm_86, one kernel, one lookup:

555 instructions, .local depot 1024 bytes
  ld.const.b32  x256      <- reads the whole table
  st.local.b32  x256      <- writes it into the thread's own depot
  ld.local.b32  x1        <- the actual lookup

The same kernel reading through a reference to the storage is 42
instructions, no depot, one ld.const.b32
.

The lowering is already correct

This is an API gap, not a codegen defect. A reference into a #[constant]
static already keeps address space 4 all the way down — the symbol stays
addrspace(4) global in LLVM IR (so a host set_<name> remains visible) and a
runtime-indexed read emits a single ld.const.b32. Nothing in mir-lower or
llvm-export needs to change; there is simply no safe way to obtain that
reference.

Measured cost

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. All variants
bit-identical against a host reference:

index pattern get() copy reference to storage const [f32; N] (global)
divergent 16048.3 us 7616.3 us 321.7 us
warp-uniform 16065.4 us 258.5 us 322.4 us

So a reference is 2.1x the throughput of the get() copy on a divergent
index and 62x on a warp-uniform one.

Note the get() row barely moves between the two index patterns (16048 vs
16065): the per-thread depot copy dominates so completely that the access
pattern stops mattering.

A second finding worth documenting

The table above also shows constant memory is not simply "faster memory",
which the current docs do not say anywhere:

  • warp-uniform index — .const wins, 258.5 us vs 322.4 us (1.25x). One
    broadcast per warp. This is what the constant cache is for.
  • divergent index — .const loses badly, 7616.3 us vs 321.7 us
    (23.7x slower). The constant cache serves distinct addresses in sequence,
    so a warp asking for up to 32 different entries serializes, while the same
    table in global memory coalesces and stays resident in L1.

A divergent lookup table should therefore be a plain const TABLE: [f32; N],
which since #684 is materialized as one immutable device global read with
ld.global.nc — no host upload and no #[constant] needed. Choosing .const
by the qualifier rather than by the access pattern is a 23.7x mistake.

Proposed fix

Add a borrowing accessor beside get:

pub fn get_ref(&self) -> &T

It is safe under the same 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
in the first place.

Plus documentation: correct get's "reuse the local" advice, and record which
address space suits which access pattern, with the numbers above.

I have this working and measured, and will open a PR.

Not proposed here

impl Index for ConstantMemory<[T; N]> would be nicer at the call site than
get_ref()[i], but it only helps arrays, while get_ref also covers structs.
Happy to add it on top if preferred.

Activity

  1. added
    perf
    intrinsics
    cuda-feature
    on Aug 8, 2026
  2. added a commit that references this issue on Aug 8, 2026
    b803005
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    cuda-featureintrinsicsperf

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions