Repository navigation
fix(mir-importer): honour explicit repr integer widths for enums - #119
Merged
nihalpasham merged 5 commits intoJun 10, 2026
Merged
Conversation
niklebedenko
force-pushed
the
repr-enum-discriminant-layout
branch
3 times, most recently
from
June 6, 2026 11:09
2fb11d9 to
7209655
Compare
This was referenced Jun 7, 2026
Closed
Previously the discriminant width was chosen purely from variant count
(8 bits for ≤256 variants), so a `#[repr(u32)]` enum was lowered with an
i8 discriminant. Pointer arithmetic over `*const E` then used a 1-byte
GEP stride, producing single-byte loads against a 4-byte-strided array
— callers saw garbage for every element except index 0.
Consult `AdtDef::repr().int` and emit the requested integer type
(`Fixed { length, is_signed }` → matching width, `Pointer` → 64-bit on
NVPTX). Fallback path (no explicit repr) is unchanged.
Adds `examples/repr_u32_enum_stride` as a minimal repro:
- `read_via_u32` (control) reads `[u32; N]` correctly before and after.
- `read_via_enum` (test) reads `[Bc; N]` (`#[repr(u32)]`); without the
fix it returns variant 0 for every index. With the fix it matches the
source array.
Follows the pattern of `examples/closure_index_miscompile` (repro +
fix in one commit).
Signed-off-by: nik <[email protected]>
Supersede the repr().int mechanism with layout truth. The enum branch of
translate_type now queries rust_ty.layout() (hard error on failure; no
silent guess) and matches the layout shape:
- VariantsShape::Multiple + TagEncoding::Direct: build the discriminant
IntegerType from the tag scalar's Primitive::Int { length, signed }.
This single arm covers everything the repr().int match handled, plus
shapes it could not see:
* #[repr(uN/iN)]: width AND signedness (repr(i8) N = -1 is Signed)
* #[repr(usize/isize)]: pointer width comes from the layout, no
hardcoded 64
* #[repr(C)]: C-int-sized tag, which repr().int reports as None
* default-repr sparse discriminants (enum { A = 0, B = 1_000_000 }):
u32 tag, where the variant-count fallback picked u8
* default-repr negative discriminants (enum { N = -1, Z = 0 }):
SIGNED i8 tag. The old fallback hardcoded Unsigned, so a later
"e as i32" zero-extended 0xFF to 255 instead of sign-extending
to -1.
- TagEncoding::Niche: deliberately KEEP the variant-count tag. The
un-niched MirEnumType model is a contract relied on by
NicheEncodingAttr + emit_scalar_to_niched_enum; rustc's niche tag is
the payload scalar itself and must not leak in here.
- VariantsShape::Single: not an error. rustc reports Single for
multi-syntactic-variant enums where all but one variant is
uninhabited (e.g. Result<T, Infallible> from TryFrom). No tag exists
in memory; the variant-count tag keeps in-kernel
construct+discriminant use self-consistent.
- VariantsShape::Empty (fully uninhabited, e.g. Infallible): also not
an error. These appear in statically-dead paths of core library code
(a hard error here broke the compiler_features example via
Enumerate's Iterator::next). The type keeps the variant-count tag;
materializing a VALUE of one still fails loudly in rvalue.rs.
This mirrors the struct path's layout query a few lines above and the
constant-path precedent (read_enum_tag_value /
enum_variant_index_from_bytes in rvalue.rs).
Evidence: repr_u32_enum_stride (the regression example from PR NVIDIA#119)
now lowers the enum-pointer path as
getelementptr inbounds { i32 }, ptr %v15, i64 %v12
load { i32 }, ptr %v16, align 4
i.e. 4-byte stride, matching the u32 control kernel.
Refs issue NVIDIA#118, PR NVIDIA#119.
A Direct-tag enum's discriminant width alone does not pin down its
memory footprint: trailing padding (repr(align(N)), unit variants
alongside sized payloads) and overlapping multi-payload variants both
make the concatenated {tag, fields...} struct diverge from rustc's
allocation size, which mis-strides every GEP over *const E.
MirEnumType now carries total_size and abi_align (0 = unknown),
parallel to MirStructType::get_with_full_layout. translate_type
populates them from the layout shape for Direct-tag enums only: niched
and single-variant shapes use a deliberately un-niched model whose
size has nothing to do with rustc's, so they stay 0 and lowering
leaves them untouched.
In mir-lower, the MirEnumType conversion (convert_enum_to_llvm)
compares the structural size of {tag, fields...} under LLVM natural
layout (new natural_struct_layout/llvm_type_size_align helpers,
alignment-aware unlike get_type_size) against rustc's total_size:
- equal: unchanged.
- structural < total (trailing shortfall): append a trailing [N x i8]
pad so the LLVM struct allocation size equals rustc's. Appending at
the END keeps all existing insertvalue/extractvalue indices valid.
- structural > total (multi-payload enums whose variants overlap in
Rust but concatenate in our model, e.g. #[repr(u32)] enum E { A(u32),
B(u32) } is 8 bytes vs 12 structural): padding is impossible. The
SSA model stays as-is (in-kernel construct + match keep working; the
payload field OFFSETS remain the concatenated model, NOT Rust's
overlapped layout), and memory traversal is rejected LOUDLY at the
three sites where the type sizes an access: mir.ptr_offset over such
a pointee, and mir.load / mir.store of such a value
(reject_divergent_enum_memory_access). Silent mis-striding is gone;
field-faithful multi-payload layout is follow-up work in the
issues NVIDIA#146/NVIDIA#128 class.
convert_construct_enum now builds values of the CONVERTED type (via
convert_type) instead of assembling a local StructType::get_unnamed,
so constructed values and the converted type cannot diverge; a trailing
pad field is simply never written.
Refs issue NVIDIA#118, PR NVIDIA#119.
Extend the repr_u32_enum_stride example with one kernel per tag shape
the layout query must get right, each reading a device buffer through
`*const E` with `add(i)`:
- read_via_repr_c_enum: #[repr(C)] tag is C `int` (4 bytes; invisible
to repr().int, which reports None for repr(C)).
- read_via_sparse_enum: default repr, B = 1_000_000 forces a u32 tag
where the variant-count guess picked u8.
- read_via_neg_enum: default repr, N = -1 forces a SIGNED i8 tag; the
memory-loaded `e as i32` must emit sext (host expects -1, not 255).
- read_via_usize_enum: #[repr(usize)] pointer-width tag, stride 8.
Compile-only .ll evidence (sm_90):
read_via_enum: getelementptr inbounds { i32 } / load { i32 }, align 4
read_via_repr_c_enum: getelementptr inbounds { i32 } / load { i32 }, align 4
read_via_sparse_enum: getelementptr inbounds { i32 } / load { i32 }, align 4
read_via_usize_enum: getelementptr inbounds { i64 } / load { i64 }, align 8
read_via_neg_enum: load { i8 } ... %v23 = sext i8 %v22 to i64
mir-lower unit tests (next to the existing ptr_offset GEP test):
- enum_conversion_strides_by_rustc_size: converted allocation size per
shape (repr(u32) 4B, repr(usize) 8B, u8 tag padded to rustc's 8B with
a trailing pad field, u8 tag + i64 payload naturally 16B with no pad).
- convert_ptr_offset_rejects_layout_divergent_enum and
convert_load_rejects_layout_divergent_enum: the loud lowering error
fires for a multi-payload enum (structural 12B > rustc 8B), naming
the enum and the field-faithfulness gap.
Doc fixes: the example's stale "stride is buggy (8)" text (the buggy
stride is 1), the README's repr().int description (superseded by the
layout query), and dialect-mir's stale "integer type based on variant
count" / "usually u8, u16, or u32" heuristic descriptions. Also
refresh mir-lower's enum-representation module doc (concatenated
fields plus pad/reject, not "union sized to largest").
Refs issue NVIDIA#118, PR NVIDIA#119.
nihalpasham
force-pushed
the
repr-enum-discriminant-layout
branch
from
June 10, 2026 09:34
7209655 to
7db8f16
Compare
RUSTDOCFLAGS=-Dwarnings rejects public docs linking private items (rustdoc::private-intra-doc-links). Name it in plain code font instead.
Collaborator
|
Thanks for the PR. Took it a step further on top:
|
nihalpasham
added a commit
to advpropsys/cuda-oxide
that referenced
this pull request
Jun 10, 2026
…ared discriminant values PR NVIDIA#147 threads per-variant discriminant VALUES through MirEnumType (fixing the issue NVIDIA#146 class of miscompiles where tags were variant indices), but selects the tag TYPE via Ty::discriminant_ty(), which is isize for default-repr enums. That is the type 'discriminant reads are performed at', not the physical tag storage: a default-repr 3-variant enum stores an i8 tag, not an i64. The width mismatch corrupts the in-memory model for every enum that round-trips through memory. Replace the tag-type selection with the layout-truth dispatch over rustc's VariantsShape (identical text to the tested PR NVIDIA#119 branch, so the future rebase is trivial): - Direct-tag enums take width AND signedness from the layout scalar. repr(uN/iN), repr(usize/isize), repr(C), sparse discriminants (u32 tag for { A = 0, B = 1_000_000 }) and negative discriminants (SIGNED i8 tag for { N = -1, Z = 0 }, so 'e as i32' sign-extends) all fall out of the one arm. Total size / ABI alignment are recorded on the type (new MirEnumType::get_with_layout; 0 = unknown). - Niched, single-variant (all-but-one-uninhabited) and fully uninhabited enums keep the synthetic unsigned variant-count tag: the un-niched MirEnumType model is deliberately self-consistent rather than memory-faithful there. The PR's variant_discriminants threading is KEPT, with the u128 -> u64 narrowing now checked: discriminant_for_variant().val that does not fit in 64 bits input_errs instead of silently truncating. The same checked narrowing is applied to both SwitchInt sites in terminator/mod.rs (single-branch and multi-way chain) so switch values and stored discriminants share one 64-bit contract. Issue NVIDIA#136 (BinOp::Cmp), issue NVIDIA#146 (discriminant-value tags).
nihalpasham
added a commit
that referenced
this pull request
Jun 10, 2026
…index Real semantic merge, not just textual: both sides rewrote the sizing region of mir-lower/src/convert/types.rs. - Kept both helper sets: this branch's mir_stored_size (rustc stored sizes for structs/arrays) and main's llvm_type_size_align / natural_struct_layout / convert_enum_to_llvm / enum_memory_divergence (PR #119's enum machinery). - Completed the composition this branch's comment anticipated: now that MirEnumType carries rustc's total_size, mir_stored_size returns it for Direct-tag enums, so struct-nested enum fields size exactly instead of falling back to the LLVM approximation. - Import unions in types.rs / type_interface_impls.rs; dropped a now-unused TypeObj import in aggregate.rs. Verified on sm_120: struct_layout_repro (256 lanes, right fields) and repr_u32_enum_stride (all enum shapes) both pass on the merged tree; mir-lower/mir-importer/dialect-mir tests, workspace clippy -D warnings, and fmt all green.
nihalpasham
added a commit
to advpropsys/cuda-oxide
that referenced
this pull request
Jun 10, 2026
When build_struct_slot_map advances the running offset past a field, it previously always used get_type_size on the converted LLVM type. For a nested struct that approximation sums the field sizes, which ignores interior padding/alignment that rustc's layout has; the parent struct then inserts interior [N x i8] padding where rustc has none (shifting every later field) or, when the sum overshoots, places the next field past its true offset. Prefer rustc layout truth instead: MirStructType stores total_size (interior and trailing padding included), and arrays of such structs multiply it out (new mir_stored_size helper). Only when no stored size exists do we fall back to the LLVM-level approximation. MirEnumType intentionally keeps the approximation: enums do not carry a rustc size yet (enum layout totals are being added on the PR NVIDIA#119 branch, and this commit must not collide with that work). The enum-size gap is benign for offsets today because the under-estimate is always re-padded up to the next field's rustc offset by the slot-map walk (and the slot map from the previous commit keeps all indices correct in the presence of those pads). cargo test -p mir-lower: 31 passed; issue128_repro still compiles with the same slot assignment.
nihalpasham
added a commit
to advpropsys/cuda-oxide
that referenced
this pull request
Jun 10, 2026
…nto fix/binaryop-cmp Semantic merge of the enum work: main's NVIDIA#119 (layout-truth tag, enum total_size/abi_align, divergence guard) meets this branch's variant_discriminants threading. - dialect-mir MirEnumType: kept this branch's variant_discriminants field/format/constructor arity, main's richer layout doc text. - importer translate_type: kept the discriminant-value loop and the variant_discriminants argument on top of the canonical layout-tag selection both sides share. - mir-lower convert_construct_enum: main's converted-type construction (type converter is the single source of the padded struct) composed with this branch's declared-discriminant tag writes and loud errors. - mir-lower memory.rs unit tests: enum constructors gain sequential discriminants (the layout tests exercise width/size, not values). Known issue carried forward (pre-existing on main, fixed in a follow-up commit on this branch): the NVIDIA#119 divergence guard rejects in-kernel loads of multi-payload enums, breaking the enum_array_match example that merged via PR NVIDIA#156.
nihalpasham
added a commit
to advpropsys/cuda-oxide
that referenced
this pull request
Jun 10, 2026
The PR NVIDIA#119 guard rejected every load/store/GEP of a multi-payload enum whose concatenated {tag, fields...} model is larger than rustc's layout. That premise is too broad: device-LOCAL memory (allocas, in-kernel arrays) is written and read through the same lowered struct type, so the structural layout is self-consistent and correct. The guard broke the enum_array_match example (PR NVIDIA#156) on main, which builds [E; 4] arrays of a two-payload enum entirely in-kernel. Divergence only bites where device code traverses memory laid out by RUST's real layout: kernel parameters (by value via cuLaunchKernel, or behind pointers/slices into DeviceBuffer memory). So: - convert_func now walks each KERNEL parameter's pre-conversion MIR type (through pointers, slices, arrays, structs, tuples and enum payloads, cycle-safe) and rejects the first divergent enum with a host/device ABI boundary diagnostic. Non-kernel device functions are internal (both sides structural) and stay unchecked. - The load/store/ptr_offset rejections are removed. - Unit tests updated: device-local GEP+load of a divergent enum must lower; a gpu_kernel-attributed function with a divergent-enum pointer param must fail with the boundary message. GPU-verified on sm_120: enum_array_match passes again; ord_cmp, repr_u32_enum_stride, struct_layout_repro, option_ref_unwrap_or and the 10-example sweep all pass.
nihalpasham
added a commit
to haixuanTao/cuda-oxide
that referenced
this pull request
Jun 11, 2026
…-only The NVIDIA#119 + NVIDIA#156 composition break (each PR green alone, main broken together) was invisible because no CI job runs the device pipeline over the examples: clippy checks them without the codegen backend, so device codegen never executes. - scripts/smoketest.sh --compile-only: build every example with `cargo oxide build` instead of running it. Non-error categories must exit 0 and emit a fresh, non-empty {crate}.ptx or {crate}.ll; error examples must still fail with a diagnostic. Interop examples (whose PTX lands in their configured ptx_dir and is verified by cargo-oxide itself) are trusted on exit code, matched by anchored TOML shapes only. Also hardens nvidia-smi probing (failure text on stdout no longer corrupts LTOIR_ARCH) and fails loudly if an examples/ dir has no top-level Cargo.toml (silent coverage shrinkage). - .github/workflows/examples-compile.yml: ubuntu-latest, CUDA headers via Jimver (bindgen + libcuda stub), LLVM 21 from apt.llvm.org (the documented llc floor, now CI-enforced), libcuda.so.1 stub shadow so the cargo-oxide binary loads GPU-less, shared CARGO_TARGET_DIR, and failure-log upload (step-level timeout so the upload still fires on a hang). - cargo-oxide: artifact filenames are crate-named, and cargo maps hyphens to underscores (rustlantis-smoke emits rustlantis_smoke.ptx). clean_generated_files/show_generated_artifacts and the interop PTX check now normalize via artifact_stem; .opt.ll is cleaned too. Without this, hyphenated examples keep stale artifacts forever. Validated: 75/75 examples pass compile-only locally (llc-21); at the historical breaking merge 14747f7 the job fails on enum_array_match with the divergent-enum fatal, proving it catches that break class.
meefs
pushed a commit
to meefs/cuda-oxide
that referenced
this pull request
Sep 30, 2026
Signed-off-by: Melih Elibol <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #118.
Previously, cuda-oxide selected the lowered discriminant width from the number of variants. A small
#[repr(u32)]enum therefore lowered as ani8discriminant, which made pointer arithmetic over*const Enumuse the wrong stride.The fix: consult
AdtDef::repr().intwhen selecting the MIR enum discriminant type, and preserve the old variant-count heuristic only when no explicit integer repr is present.Repro / regression test:
repr_u32_enum_stride, a reduced example that compares pointer reads through[u32]and[#[repr(u32)] enum].Btw I have a ton of other correctness / missing feature fixes I discovered while porting a large codebase from Rust_CUDA to cuda-oxide (roughly 10 PRs worth I think) -- pls lmk if there's any style changes I should make, would love to contribute!