Skip to content

feat(mir): support SetDiscriminant lowering for niche-encoded enums (incl. multi-field payloads) - #349

Merged
nihalpasham merged 6 commits into
NVIDIA:mainfrom
goog00:feat-set-discriminant-niche
Jul 21, 2026
Merged

nihalpasham merged 6 commits into
NVIDIA:mainfrom
goog00:feat-set-discriminant-niche

Conversation

@goog00

@goog00 goog00 commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

What this PR fixes

cuda-oxide previously represented some Rust enums differently on the GPU by adding a synthetic discriminant. That could disagree with the memory layout chosen by rustc, especially for niche-encoded enums such as Option<NonZeroU32> and Option<&T>.

This PR makes device enums use rustc's real physical layout. The same checked layout model is used for construction, matching, SetDiscriminant, payload access, constants, and transmute lowering.

For example:

Option<NonZeroU32>::Some(7) -> physical word 7
SetDiscriminant(None)       -> physical word 0
                               no extra tag is added

Why this matters

Host and device code must agree on the bytes used to represent an enum. Using rustc's layout avoids inventing a second GPU-only representation and fixes the original niche-SetDiscriminant support gap without creating ABI mismatches elsewhere.

How it works

One rule drives everything: the device uses exactly the bytes rustc chose on the host. Anything the compiler cannot reproduce byte-for-byte is a clear compile error, never an approximation.

  • The dialect records rustc's real layout. For each enum the importer stores what rustc decided: the layout kind (direct tag, niche, single, empty), total size and alignment, where the tag or niche carrier lives, and the byte offset of every payload field. The encoding API is typed (real enums for the kinds, one u128 niche start, named constructor fields), so a malformed encoding is a compile error or verifier failure, not a silently transposed integer.

  • Direct tags store the declared value.

    #[repr(i8)] enum E { Below = -1, Zero = 0 }
    // tag byte is 0xFF for Below; reading sign-extends it back to -1
    
  • Niche enums hide the discriminant in invalid payload values, using rustc's exact wrapping arithmetic:

    Option<NonZeroU32>:  None = 0,  Some(n) = n      (no extra tag byte)
    Option<&T>:          None = null pointer
    // SetDiscriminant to the Some/payload variant never touches
    // the payload bytes it shares storage with
    
  • Tuples know their real field offsets. rustc reorders tuple fields exactly like struct fields, and the importer now records where they landed:

    Option<(u32, u32, &T)>          // rustc puts the pointer FIRST
    bytes 0..8   = &T               // also the niche: null here = None
    bytes 8..12  = u32
    bytes 12..16 = u32
    

    Structs and tuples flow through the same lowering. When a payload shares bytes with a pointer carrier, lowering accepts it only if the pointer sits at the same offset, with the same width and address space, on both sides. A pointer is never rebuilt from integer bits.

  • Bools are one canonical byte, even nested inside a payload.

    Option<struct { pad: u32, flag: bool }>
    // flag byte at offset 4:  0 = false,  1 = true,  2 = None
    

    LLVM's i1 leaves seven undefined bits in its byte, so enum storage never contains a raw i1: writes zero-extend each bool into its byte, reads load it back as a bool.

  • Alignment always matches rustc. If the payload bytes alone would under-align the LLVM struct (say an i8 carrier inside a 4-aligned enum, or repr(align(8))), a zero-sized anchor field raises it, the same trick union storage already uses.

Examples

  • The former error_set_discriminant_niche support-gap fixture is now the positive set_discriminant_niche ABI regression, covering seven niche shapes with byte-level host/device verification, including a device-verified Option<(u32, u32, &u32)> tuple pointer niche and an Option<struct { u32, bool }> nested-bool niche.
  • Its later-field case replaces the separate set_discriminant_niche_multifield example.
  • error_set_discriminant_uninhabited remains a required negative test.
  • The former error_enum_nested_bool_niche fixture is retired: its shape is now supported and runtime-verified.
  • Three negative fixtures cover the remaining honest boundaries: enum-constant pointer provenance, pointer/integer overlapping payloads, and target-mode-dependent shared-memory pointers.

Remaining boundaries (fail closed with diagnostics)

  • Enum constants containing pointer relocations (needs device-global materialization).
  • Pointer payloads overlapping integer storage (repr(C) unions of pointer and bits).
  • Shared-memory (AS3) pointers in enum layouts, until the exporter's pointer-width mode is threaded into lowering.
  • Pointer-bearing arrays/vectors in overlapping payload positions, and Option<(&T, &U)>-style second pointer words without their own pointer slot.
  • Bools hidden behind union byte blobs.

This partially addresses #306, which should remain open for the boundaries above. Issues #382 and #393 are related but are not fixed by this PR.

Validation

  • Full dialect-mir, mir-importer (802), and mir-lower (131 unit + 73 integration) suites.
  • Workspace Clippy with warnings denied, rustdoc with warnings denied.
  • All 148 examples in the GPU-less compile gate.
  • set_discriminant_niche and option_ref_transmute executed on real hardware (sm_120) with byte-level host/device agreement checks.

History

The contributor-authored, DCO-compliant commit is preserved, followed by signed maintainer commits: the rustc-layout rebuild, Clippy/rustdoc cleanup, the nested-pointer provenance repair, tuple field-offset support (removing the interim two-word shape restriction), and the typed encoding API plus nested-bool canonicalization.

@nihalpasham nihalpasham added 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) tests Adds or improves test coverage examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples enhancement New feature or request labels Jul 20, 2026
@nihalpasham
nihalpasham force-pushed the feat-set-discriminant-niche branch from 0ef21ca to 313b1e6 Compare July 21, 2026 08:34
goog00 and others added 6 commits July 21, 2026 23:21
…ncoded enums

Extends MirSetDiscriminantOp with optional niche-encoding metadata so that
niche-encoded enums (e.g. Option<&T>, Option<NonZeroU32>) can be mutated via
StatementKind::SetDiscriminant on the device.

For the niche variant we now write both the synthetic discriminant and the
niche bit pattern into the payload scalar; for non-niche variants we only
update the synthetic discriminant, leaving the payload untouched.

Changes:
- Added set_niche_encoding and is_niche_variant attributes to
  MirSetDiscriminantOp and updated its verifier.
- Updated mir-importer to query rustc's TagEncoding::Niche layout and attach
  the attributes instead of rejecting niche-encoded enums.
- Added deep_scalar_path helper and updated mir-lower to emit the extra
  payload store for niche variants.
- Added dialect-mir and mir-lower unit tests plus a positive end-to-end
  example (set_discriminant_niche) using Option<NonZeroU32>.
- Fixed a duplicate import in mir-lower's interface_impls.

Signed-off-by: sunteng <[email protected]>
Signed-off-by: nihalp <[email protected]>
Replace the synthetic-tag enum representation with exact rustc Direct, Niche, Single, and Empty physical-layout metadata. Share one checked storage model across construction, discriminant operations, payload access, constants, and transmute; use full-width wrapping niche arithmetic; preserve pointer provenance and canonical bool storage; and fail closed when target-dependent or non-byte-faithful representation cannot be proven.

Convert the former niche diagnostic into a comprehensive positive ABI regression, retain the uninhabited rejection, fold later-field coverage into the main example, and add focused negative fixtures for pointer provenance, nested bool storage, overlapping representations, and target-dependent shared pointers.

Signed-off-by: nihalp <[email protected]>
Keep the shared-pointer negative fixture's raw-pointer semantics without triggering deref_addrof, make the intentionally wide ABI regression kernel explicit, elide its needless lifetime, and avoid linking public rustdoc to a private lowering helper.

Signed-off-by: nihalp <[email protected]>
Treat an aggregate payload and its niche carrier as the same pointer storage only when their pointer leaves match exactly in byte offset, width, and address space. Keep unmodeled tuple layouts fail-closed outside the proven two-word pointer-niche shape, and cover the complete construction, extraction, and discriminant path.

Signed-off-by: nihalp <[email protected]>
MirTupleType now records rustc's exact layout (field offsets, memory
order, total size, ABI alignment) exactly like MirStructType, populated
in the importer's Tuple arm from the same layout query the struct,
union, and closure arms already use. Synthetic tuple result types
(checked arithmetic, atomic cmpxchg, tuple aggregates) are translated
from their rustc MIR type so every tuple uniques to the one
layout-carrying instance; only the zero-sized unit tuple stays
layout-less.

With real offsets available, the enum slot map validates aggregate
pointer payloads uniformly through the physical-layout walk
(pointer_storage_matches_claims) for structs and tuples alike. The
hard-coded two-word pointer-niche tuple proof and its helper predicates
are deleted, and initialized globals accept tuples through the same
offset validation as structs instead of failing closed.

Newly accepted shapes include multi-field tuple pointer niches such as
Option<(u32, u32, &T)>; the set_discriminant_niche example now
constructs, reads, and SetDiscriminant-clears one on device with
runtime verification. Pointer/integer overlaps, address-space
mismatches, and unproven layouts still fail closed with the existing
diagnostics.

Signed-off-by: nihalp <[email protected]>
…ytes

Two remaining principled-fix items for the enum layout rebuild.

MirEnumType's physical encoding is now first-class: layout_kind and
carrier_kind are #[format] Rust enums (EnumLayoutKind, EnumCarrierKind)
instead of raw u8 codes, niche_start is one lossless u128 NicheStart
newtype with its own Printable/Parsable instead of two u64 halves, and
get_with_encoding takes a named-field EnumEncoding spec instead of 19
positional parameters, ten of them undifferentiated integers. The
compiler now rejects transposed or nonsense encodings that the old
signature accepted silently, and formerly defensive wildcard match arms
over kind codes are gone because the type system proves them
unreachable.

Bools nested inside aggregate enum payloads lower through their
byte-faithful twin: the slot map claims storage with every i1 leaf
widened to its canonical i8 memory byte, construction zero-extends each
bool recursively (generalizing the existing scalar-bool mechanism), and
extraction re-loads the original shape from the canonical bytes. When
byte claims alone under-align the storage (an i8 carrier inside a
4-aligned enum, or repr(align) padding), a zero-length anchor field
raises the LLVM struct's alignment, the same mechanism union storage
already uses; this also un-regresses repr(align(8)) direct-tag enums to
compiling with correct alignment. Option<struct { u32, bool }> and
friends now construct, match, and SetDiscriminant on device with
rustc's exact bytes, so the error_enum_nested_bool_niche support-gap
fixture is retired and the shape joins set_discriminant_niche as
runtime-verified positive coverage. Bools hidden behind union byte
blobs still fail closed.

Signed-off-by: nihalp <[email protected]>
@nihalpasham
nihalpasham force-pushed the feat-set-discriminant-niche branch from 6954c52 to 5220903 Compare July 21, 2026 17:54
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR. The original SetDiscriminant support gap is fixed. I pushed maintainer follow-ups that rebuilt the enum path on rustc's real layouts so the fix holds for every enum shape the compiler accepts, not just the initial niche case.

  • Device enums now use rustc's exact physical layout for construction, matching, SetDiscriminant, payload access, constants, and transmutes. No synthetic device-only tag is introduced.
  • Niche encodings write the discriminant into the carrier rustc chose, and selecting the untagged variant never touches the payload bytes it shares storage with.
  • Tuples carry rustc's field offsets like structs do, so reordered multi-field payloads such as Option<(u32, u32, &T)> lower byte-identically to the host.
  • Bools use canonical byte storage even nested inside payloads (Option<struct { u32, bool }> works), and enum storage alignment always matches rustc.
  • Layouts that cannot be reproduced byte-for-byte fail with a clear diagnostic; the remaining boundaries are listed in the description and covered by negative fixtures.

For example:

Option<NonZeroU32>::Some(7) -> physical word 7
SetDiscriminant(None)       -> physical word 0   (no extra tag)

Option<(u32, u32, &T)>      -> pointer first in memory, per rustc;
                               null in that slot means None

Reviewer note: 1037 unit and integration tests across dialect-mir, mir-importer, and mir-lower passed, plus all 148 examples in the GPU-less compile gate. Workspace clippy with warnings denied, rustdoc, and formatting are clean. set_discriminant_niche (64 byte-verified host/device roundtrips across seven niche shapes) and option_ref_transmute executed successfully on an RTX 5090 (sm_120). The branch is rebased onto current main; hosted CI on the final head is the remaining merge gate.

This partially addresses #306, which stays open for the documented unsupported layouts. #382 and #393 are related but not fixed here.

@nihalpasham
nihalpasham merged commit f2ba244 into NVIDIA:main Jul 21, 2026
33 checks passed
nihalpasham added a commit to niklebedenko/cuda-oxide that referenced this pull request Jul 22, 2026
The rebased array::map support exposed a chain of dead-path shapes main's
enum verifiers (from NVIDIA#349) rightly refuse as real operations:
array::try_from_fn keeps the residual ControlFlow arms in MIR even though
NeverShortCircuitResidual is uninhabited, so the importer emitted
mir.enum_payload on an uninhabited variant, mir.construct_enum of an
uninhabited variant, and mir.get_discriminant on a fully uninhabited
enum -- each failing verification.

No value can inhabit those paths, so the reads and constructions are
dynamically dead. Translate each to a typed mir.undef instead (the same
treatment [T; 0] extraction and uninit union constants already get),
keeping the dead path representable while the dialect verifiers stay the
loud stop against real uninhabited-variant operations. New dialect tests
lock in the fail-loud half for construct_enum and get_discriminant.

The undef placeholders also exposed a textual-export ordering bug: undef
results were only named at op-emit time, so a use in an earlier-printed
block (a PHI incoming from a later-printed defining block) failed with
'missing exported name'. Pre-register undef results in the naming
pre-pass like constants and addressof, which are the other two virtual
ops.

The map_over_aligned_array kernel in array_for_loop exercises the whole
chain end to end on GPU.

Signed-off-by: nihalp <[email protected]>
nihalpasham added a commit to niklebedenko/cuda-oxide that referenced this pull request Jul 22, 2026
The rebased array::map support exposed a chain of dead-path shapes main's
enum verifiers (from NVIDIA#349) rightly refuse as real operations:
array::try_from_fn keeps the residual ControlFlow arms in MIR even though
NeverShortCircuitResidual is uninhabited, so the importer emitted
mir.enum_payload on an uninhabited variant, mir.construct_enum of an
uninhabited variant, and mir.get_discriminant on a fully uninhabited
enum -- each failing verification.

No value can inhabit those paths, so the reads and constructions are
dynamically dead. Translate each to a typed mir.undef instead (the same
treatment [T; 0] extraction and uninit union constants already get),
keeping the dead path representable while the dialect verifiers stay the
loud stop against real uninhabited-variant operations. New dialect tests
lock in the fail-loud half for construct_enum and get_discriminant.

The undef placeholders also exposed a textual-export ordering bug: undef
results were only named at op-emit time, so a use in an earlier-printed
block (a PHI incoming from a later-printed defining block) failed with
'missing exported name'. Pre-register undef results in the naming
pre-pass like constants and addressof, which are the other two virtual
ops.

The map_over_aligned_array kernel in array_for_loop exercises the whole
chain end to end on GPU.

Signed-off-by: nihalp <[email protected]>
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) enhancement New feature or request examples Example kernels and host harnesses under crates/rustc-codegen-cuda/examples IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) tests Adds or improves test coverage

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants