Skip to content

fix(mir-lower): genericize named-space pointer values - #626

Merged
nihalpasham merged 6 commits into
NVIDIA:mainfrom
niklebedenko:upstreaming/named-space-pointer-representation
Aug 1, 2026
Merged

nihalpasham merged 6 commits into
NVIDIA:mainfrom
niklebedenko:upstreaming/named-space-pointer-representation

Conversation

@niklebedenko

@niklebedenko niklebedenko commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Closes #625.

Summary

CUDA named-space pointers are offsets within a memory space, while Rust
pointer-address operations and aggregate layout require one stable logical
pointer representation. This change casts named-space pointers to CUDA generic
space before exposing them as integers and stores direct shared-pointer enum
payloads in generic pointer slots. A valid shared allocation at local offset
zero is therefore non-null, and enum storage remains 64-bit in both legacy PTX
and modern NVVM modes.

What changed

Central pointer-address representation

  • Added one emit_ptr_to_int boundary used by PointerExposeAddress,
    pointer-to-integer semantic casts, and the pointer-to-integer transmute that
    implements ptr::addr in core.
  • Generic pointers continue directly to ptrtoint. Every nonzero CUDA address
    space first receives addrspacecast to generic space, so the integer
    contains both the address and memory-space identity.
  • Audited the remaining direct ptrtoint sites. ldmatrix intentionally
    consumes a native 32-bit shared offset, while enum niche discrimination
    reads a carrier that is already stored as a generic pointer; neither is a
    Rust pointer-address exposure boundary.
  • Kept pointer-bearing aggregate transmutes rejected because lowering still
    lacks target-mode-specific physical width at that boundary. (Maintainer
    follow-up: the reverse integer-to-pointer as-cast boundary is now
    handled rather than left as a bare inttoptr; see below.)

Target-stable enum storage

  • build_enum_slot_map now distinguishes a direct shared-pointer field from
    an aggregate that merely contains one. A direct field claims a generic
    physical pointer slot, while field_llvm_types retains its semantic shared
    type.
  • Enum construction and payload extraction use one narrow pointer coercion
    helper to cross between semantic and physical address spaces.
  • Niche discrimination reads the generic physical carrier, so direct shared
    payload construction, discriminant inspection, and extraction round-trip
    through two explicit address-space casts.
  • Extended the repo-native addressof_sharedarray example with a noinline
    Rust function that conditionally constructs a direct shared-pointer enum,
    matches its discriminant, extracts the pointer, and compares its address
    with the original. The same kernel now observes both ptr::addr() and
    is_null().
  • Unit coverage checks the address-exposure boundary for global, shared,
    constant, and local pointers, plus the no-op generic-pointer case.
  • Focused tests retain fail-closed behavior for nested shared-pointer fields,
    shared-pointer niche carriers, shared-pointer vectors, and unsupported
    reverse or aggregate transmutes. The existing shared-pointer error example
    now protects the unsupported nested-aggregate boundary instead of expecting
    direct pointer fields to fail.

Known separate limitations

  • Only direct pointer fields receive the representation boundary. Rebuilding
    arbitrary nested pointer-bearing aggregates would need a recursive,
    layout-aware conversion and remains deliberately unsupported.
  • A niche carrier that is itself declared in shared address space remains
    target-mode dependent and is rejected; the supported niche shape uses a
    generic physical carrier with a semantic direct shared-pointer payload.
  • (Resolved since filing.) Runtime LTOIR smoke on CUDA 12.8 was independently
    blocked by the cubin e_version validation; that fix landed separately in
    fix(finalizer): accept CUDA cubin ELF format versions #622, so the runtime LTOIR route is unblocked on current main.
  • Raw shared-array API design and multi-artifact module lookup are unchanged.

Maintainer follow-ups on this branch

Four commits stacked during review and landing, so the branch as merged is
the author's fix plus:

  • d515c07e -- the reverse boundary. usize as *mut SharedArray<T, N>
    lowered as a bare inttoptr, reinterpreting the now-generic exposed
    integer as a space-local offset. emit_int_to_ptr mirrors this PR's
    emit_ptr_to_int (enter named spaces through generic), wired into
    PointerWithExposedProvenance, the pointer-cast int arm, and the
    transmute int arms. Unit tests cover all four named spaces, and the
    addressof_sharedarray kernel now recovers a pointer from its exposed
    integer through a noinline function and compares pointer values (a wrong
    value can still store to the right slot because hardware masks the
    shared-window base, so the value comparison is the real check).
  • fce395d5 + rename in 32882d26 -- cvta_generic_to_shared_offset, a
    first-class intrinsic (device stub, nvvm.cvta_generic_to_shared_offset
    op, exact importer recognizer, PTX-free lowering: addrspacecast to
    addrspace(3) + ptrtoint). Hardware SMEM descriptors encode
    (start_address >> 4) & 0x3FFF over the raw .shared offset, so
    descriptor bases must not be derived from ptr as u64 (a generic address)
    once this PR lands. All raw-address exposure sites now route through it:
    gemm_sol (28 per-stage descriptor bases + 5 cluster::map_shared_rank
    barrier addresses feeding mbarrier_arrive_cluster, whose PTX consumes a
    raw shared::cluster address), gemm_sol_final (16 + 4),
    tcgen05/tcgen05_matmul (8), and mcast_barrier_test (2). Emitted PTX
    verified register-pure for both classes.
  • c1322d55 -- compiler_features asserted the pre-PR semantics (a direct
    as u64 had to yield the small raw offset) and failed at runtime under
    the new contract. It now asserts the generic-address contract and
    executes the new intrinsic on GPU (generic 0x..00000400 vs raw offset
    0x400).
  • 3700dcd5 -- merge with main resolving the two textual conflicts with
    feat(cuda-device): expose raw shared-array pointer #624 (the exact SharedArray recognizer and the shared example, whose
    kernels collided on one output slot; both extensions kept).

Maintainer validation: full executing smoketest 177/177 on an RTX 5090
(sm_120, CUDA 13.3), 1270 tests across the four touched crates, the
reverse-boundary regression red on the branch as submitted and green with
the fix, and per-example cargo fmt --check clean.

Testing

  • Upstream-red: with the address and enum regression source applied to
    bead880cd7461c67a14bc69d10fa7def538f3394,
    cargo oxide run addressof_sharedarray --arch=sm_86 failed with cargo exit
    101 because SharedPointerPayload contained a target-dependent shared
    pointer. The earlier address-only form of the same command failed at the
    pointer-to-integer transmute boundary.
  • Patched-green: the exact same command passed on an RTX 3080 (sm_86),
    preserving the original issue-54 result (21), observing is_null() == false and a nonzero address, and round-tripping the direct enum payload.
  • Modern NVVM/LTOIR:
    cargo oxide emit-ltoir addressof_sharedarray --arch=sm_100 passed on the
    clean branch and produced a 4,900-byte compute_100 LTOIR artifact. The
    unoptimized IR records p3:32, stores the enum as { i64, ptr }, casts the
    shared pointer to generic on construction, restores shared space on
    extraction, and genericizes again before ptrtoint.
  • LTOIR integration: with only the separate CUDA-ELF validator condition
    applied transiently,
    scripts/smoketest.sh --only '^addressof_sharedarray$' --no-color passed
    1/1 on the RTX 3080 and observed the same address and enum runtime results.
    Without that condition, the clean branch reaches host execution and fails
    solely with Finalizer(InvalidCubin). The unrelated edit was reverted before
    commit.
  • cargo test -p mir-lower --all-targets passed all 149 unit tests and 76
    lowering integration tests.
  • scripts/smoketest.sh --compile-only --no-color --keep-logs passed all
    178 examples, including real-libNVVM verification lanes and the repurposed
    nested shared-pointer expected-failure fixture.
  • scripts/check-error-example-status.sh passed.
  • cargo clippy --workspace --all-targets -- -D warnings, both changed-example
    clippy checks, workspace and example formatting checks, and
    git diff --check passed.

Checklist

  • The branch is based on current upstream main, or its dependency is explicit.
  • The regression fails on upstream main and passes on this branch.
  • Relevant sibling paths and edge cases are covered or called out above.
  • Formatting, focused tests, and relevant broader checks pass.
  • Commits include DCO signoff and new files have required headers.

@niklebedenko
niklebedenko force-pushed the upstreaming/named-space-pointer-representation branch from fe71c19 to aaf57da Compare August 1, 2026 01:36
@nihalpasham nihalpasham added bug Something isn't working miscompile Produces incorrect PTX/IR (wrong generated code) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Aug 1, 2026
…to-ptr

PointerExposeAddress now yields the CUDA generic address, so the reverse
boundary must interpret the integer the same way. A bare inttoptr into a
named space reinterprets the generic address as a space-local offset and
silently breaks the expose/recover round trip (usize -> *mut SharedArray).

emit_int_to_ptr mirrors emit_ptr_to_int: inttoptr to the generic space,
then addrspacecast into the destination space. Wired into
PointerWithExposedProvenance, emit_pointer_cast's int-to-ptr arm, and
emit_transmute's int-to-ptr arms (the shared-width rejection still fires
first for transmutes involving shared pointers). The
addressof_sharedarray example now stores through a pointer recovered
from the exposed integer and observes the write through the original
allocation.
…ptors

tcgen05 SMEM descriptors encode (start_address >> 4) & 0x3FFF over the
raw .shared window offset (PTX ISA), but the examples derived descriptor
bases from Rust pointer casts, which yield the CUDA generic address.
Those bits are only correct when the undocumented shared-window base
happens to be 2^18-aligned.

Add the CUDA C++ __cvta_generic_to_shared analog as a first-class
intrinsic: a cuda-device stub, an nvvm.cvta_generic_to_shared dialect op
(verified: generic/shared MIR pointer operand, u64 result), an exact
importer recognizer, and a PTX-free lowering (addrspacecast to
addrspace(3) + ptrtoint, which llc selects as cvta.to.shared). gemm_sol,
tcgen05, and tcgen05_matmul now derive descriptor bases through it, and
the Tcgen05SmemDescriptor doc examples show the same shape. The emitted
PTX packs descriptors from the shared-space symbol address directly,
spec-exact with no window-alignment dependence.
The shared-memory address-casting test asserted the pre-NVIDIA#626 behavior:
a direct 'as u64' on a shared static had to yield the small space-local
offset, and the genericizing cvta was documented as a codegen quirk to
eliminate. The contract is now the opposite (the nvcc model): both cast
routes must agree on the nonzero generic address, and the raw .shared
offset is available only through the explicit cvta_generic_to_shared
intrinsic, which the test now also executes on GPU (generic
0x..00000400 vs offset 0x400 on sm_120).

Also documents why the intrinsic must not gain a crate-root re-export:
the importer recognizes the exact rendered def-path, and a root pub use
changes rustc's visible path and silently breaks interception.
@nihalpasham

Copy link
Copy Markdown
Collaborator

LGTM on the approach — Rust-visible pointer values are generic addresses, never null for a valid allocation).

I pushed fixes for 3 gaps:

  • The reverse boundary: usize as *mut SharedArray still lowered as a bare inttoptr, so the exposed generic address got reinterpreted as a shared offset — a silent wrong pointer. It hides well: llc folds visible cast pairs and the hardware masks wrong upper bits out of st.shared, so the new regression crosses a non-inlined boundary and compares pointer values (int enters named spaces through generic, mirroring your forward helper).
  • tcgen05 SMEM descriptors: gemm_sol/tcgen05_matmul packed descriptor address bits from ptr as u64, which this PR turns into a generic address; the PTX ISA defines those bits over the raw .shared offset. Added cvta_generic_to_shared (the CUDA C++ analog) as a first-class intrinsic and routed the examples and docs through it — the emitted PTX now derives descriptors from the shared-space symbol directly.
  • A test asserting the old semantics: compiler_features required the small raw offset at runtime and failed under the new contract (invisible to --compile-only). Rewritten to assert the new contract; it also gives the intrinsic a runtime GPU proof (generic 0x7e3700000400 vs offset 0x400).

Verified on hardware:

Merging after #624;

closes #625.

# Conflicts:
#	crates/mir-importer/src/translator/terminator/mod.rs
#	crates/rustc-codegen-cuda/examples/addressof_sharedarray/src/main.rs
…all raw-address sites

The name now says what the result is: the raw .shared window offset, not
a pointer. Renamed across the device stub, the nvvm dialect op, the
importer recognizer, the lowering, and all callers.

Sweep every example that exposes a shared address as an integer through
the intrinsic, not just the first two descriptor sites:

- gemm_sol: all 28 per-stage SMEM descriptor bases across its kernels,
  plus 5 cluster::map_shared_rank addresses feeding
  mbarrier_arrive_cluster (the mapa result is a raw shared::cluster
  address; a bare 'as u64' would now genericize it)
- gemm_sol_final: 16 SMEM descriptor bases and 4 mapped barrier
  addresses across both kernels
- mcast_barrier_test: 2 mapped barrier addresses

The emitted PTX keeps every chain register-pure: mapa results feed
mbarrier.arrive.release.cluster directly and descriptor packing derives
from shared-symbol movs, with all round-trip casts folded.
@nihalpasham
nihalpasham force-pushed the upstreaming/named-space-pointer-representation branch from ffafe56 to 32882d2 Compare August 1, 2026 12:52
@nihalpasham
nihalpasham merged commit 3f1cdaa into NVIDIA:main Aug 1, 2026
33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) miscompile Produces incorrect PTX/IR (wrong generated code)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Named-space pointers lose Rust address semantics when their representation is observed

2 participants