Repository navigation
feat(mir): support SetDiscriminant lowering for niche-encoded enums (incl. multi-field payloads) - #349
Conversation
0ef21ca to
313b1e6
Compare
…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]>
6954c52 to
5220903
Compare
|
Thanks for the PR. The original
For example: 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. |
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]>
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]>
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>andOption<&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:
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-
SetDiscriminantsupport 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
u128niche 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.
Niche enums hide the discriminant in invalid payload values, using rustc's exact wrapping arithmetic:
Tuples know their real field offsets. rustc reorders tuple fields exactly like struct fields, and the importer now records where they landed:
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.
LLVM's
i1leaves seven undefined bits in its byte, so enum storage never contains a rawi1: 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
i8carrier inside a 4-aligned enum, orrepr(align(8))), a zero-sized anchor field raises it, the same trick union storage already uses.Examples
error_set_discriminant_nichesupport-gap fixture is now the positiveset_discriminant_nicheABI regression, covering seven niche shapes with byte-level host/device verification, including a device-verifiedOption<(u32, u32, &u32)>tuple pointer niche and anOption<struct { u32, bool }>nested-bool niche.set_discriminant_niche_multifieldexample.error_set_discriminant_uninhabitedremains a required negative test.error_enum_nested_bool_nichefixture is retired: its shape is now supported and runtime-verified.Remaining boundaries (fail closed with diagnostics)
repr(C)unions of pointer and bits).Option<(&T, &U)>-style second pointer words without their own pointer slot.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
dialect-mir,mir-importer(802), andmir-lower(131 unit + 73 integration) suites.set_discriminant_nicheandoption_ref_transmuteexecuted 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.