Skip to content

fix(mir-lower): single source of truth for struct field -> LLVM slot mapping - #154

Merged
nihalpasham merged 4 commits into
mainfrom
fix/issue128-struct-field-llvm-index
Jun 10, 2026
Merged

nihalpasham merged 4 commits into
mainfrom
fix/issue128-struct-field-llvm-index

Conversation

@nihalpasham

Copy link
Copy Markdown
Collaborator

Fixes #128.

repr(Rust) structs lower to LLVM structs with explicit [N x i8] padding slots, but every value-level field accessor recomputed "declaration index -> LLVM slot" by counting only non-ZST fields, ignoring the pads the type converter interleaves; extract/insert additionally had a silent identity fallback when the operand's MirStructType lookup missed. Depending on neighbor types this failed loudly ("IntToInt: source is not an integer" / insertvalue type mismatch) or silently read/wrote the WRONG FIELD.

LLVM:  { { i8, i32 }, [3 x i8], i64, i32, i32 }
         layout=0     pad=1     big=2 cap=3 stride=4
before: cap -> slot 2 (the pad), stride -> slot 3 (cap's slot)
after:  cap -> slot 3, stride -> slot 4, big -> slot 2
  1. build_struct_slot_map (convert/types.rs) produces, in one walk, BOTH the padded LLVM struct type AND a decl_index -> Option<llvm_slot> map (None for stripped ZSTs). The MirStructType/MirTupleType type converters return its type and every value-level site consumes its map: extract_field, insert_field, construct_struct, construct_tuple, field_addr (aggregate.rs), flatten_arguments struct args (call.rs), entry-prologue reconstruct_struct (lowering.rs). The silent identity fallback is now recover-or-error: identity only for arrays and slice fat pointers { ptr, i64 }, loud error otherwise.
  2. Offset bookkeeping prefers rustc's stored sizes (MirStructType total_size, arrays thereof) over the LLVM sum approximation. Enum sizing intentionally untouched (deferred to the fix(mir-importer): honour explicit repr integer widths for enums #119 branch).
  3. Seven hardware-free unit tests for the helper + tracked example struct_layout_repro that verifies every lane computes cap*1000+stride+big and exits 1 on mismatch.

Verification: before/after compile-only on both #128 triage repros; prove-it-bites file-revert re-breaks with the original error; cargo test -p mir-lower 39 green; clippy/fmt clean; 8-example struct-heavy compile sweep clean. GPU-verified on sm_120 (RTX 5090): all 256 lanes of struct_layout_repro read the right fields.

Two sites beyond the issue's four were routed through the same map: flatten_arguments (call.rs) and the entry-prologue reconstruct_struct (lowering.rs) used the identical pad-ignoring count, which would have kept a live miscompile for by-value padded struct params crossing internal device-fn boundaries.

…mapping

repr(Rust) structs lower to LLVM structs with explicit [N x i8] padding
slots (build_struct_with_explicit_padding), but every value-level field
accessor recomputed "decl index -> LLVM index" by counting only non-ZST
fields in memory order, ignoring the padding slots the type converter
interleaves. Depending on neighbor types this either failed loudly
(insertvalue/extractvalue landing on a pad slot: "IntToInt: source is
not an integer", "Value being inserted / extracted does not match the
type of the indexed aggregate") or compiled cleanly and silently read
or wrote the WRONG FIELD. Issue #128.

Replace the per-site index math with one helper, build_struct_slot_map
(convert/types.rs), that produces in a single walk BOTH the padded LLVM
struct type AND a decl_index -> Option<llvm_slot> map (None for stripped
ZST fields). The MirStructType/MirTupleType type converters now return
the helper's struct type, and every value-level site consumes the
helper's slot map, so indices can never diverge from the type again:

  - convert_extract_field / convert_insert_field (aggregate.rs)
  - convert_construct_struct / convert_construct_tuple (aggregate.rs)
  - convert_field_addr GEP indices (aggregate.rs); ZST-ness is now
    decided on the converted LLVM field type like the other sites
    (it previously tested the raw MIR type, which never matched)
  - flatten_arguments struct args at internal call sites (call.rs)
  - reconstruct_struct in the entry prologue (lowering.rs)

The silent identity fallback in extract/insert (used when the operand's
MirStructType lookup missed) is replaced by recover-or-error
(resolve_aggregate_slots): identity indexing is only accepted for
aggregates whose lowered layout is index-preserving by construction,
i.e. arrays and slice fat pointers ({ ptr, i64 }); anything else is now
a loud lowering error instead of a guessed (and wrong) field index.

The helper also validates layout metadata (mem_to_decl must be a
permutation, offsets vector length must match) and no longer emits a
pad in front of a stripped ZST field, so a single gap can no longer be
split into two pad slots.

Evidence (compile-only, cargo oxide build <ex> --arch sm_90):

  before: issue128_repro  fails  "Lowering failed: Compilation error:
          invalid input program. IntToInt: source is not an integer"
  before: issue128_repro2 fails  "Value being inserted / extracted does
          not match the type of the indexed aggregate" (insert_value
          v229[1] where slot 1 is the [3 x i8] pad)
  after:  both compile; for Arena = { {i8,i32}, [3 x i8], i64, i32, i32 }
          construct inserts at slots 0/2/3/4 (pad slot 1 skipped) and
          field reads extract big=2, cap=3, stride=4; field_addr GEPs
          emit "i32 0, i32 2" past the pad.

cargo test -p mir-lower: 31 passed.
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 #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.
Hardware-free unit tests for build_struct_slot_map covering the layout
shapes from issue #128:

  - reorder-only struct (no rustc offsets)
  - padding-only struct (pad consumes an LLVM slot)
  - reorder + padding (trailing pad)
  - ZST interleaving (stripped field gets no slot, no pad split)
  - the issue's exact Arena shape: a reordered u64 field next to an
    8-byte enum that lowers to the 5-byte { i8, i32 }, forcing the
    interior [3 x i8] pad at slot 1 (cap=3, stride=4, big=2)
  - nested struct whose stored rustc total_size exceeds the sum of its
    converted LLVM field sizes (proves the stored-size advance)
  - malformed memory-order metadata is rejected loudly

Also promote the issue #128 triage repro into the tracked example
struct_layout_repro: the kernel builds the reordered/padded Arena,
reads cap/stride/big back through &Arena, and the host verifies every
lane computes cap * 1000 + stride + big, exiting 1 on any mismatch. A
wrong-field read produces a visibly different value, so a regression is
a hard runtime failure (and pre-fix it does not even lower). The
example falls in the smoketest standard category (prints SUCCESS).

cargo test -p mir-lower: 38 passed. Compile-only .ll check: construct
inserts at slots 0/2/3/4 of { { i8, i32 }, [3 x i8], i64, i32, i32 }
and field reads extract big=2, cap=3, stride=4.

Issue #128.
@nihalpasham nihalpasham added bug Something isn't working miscompile Produces incorrect PTX/IR (wrong generated code) codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels 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
nihalpasham merged commit c49850f into main Jun 10, 2026
23 checks passed
nihalpasham added a commit to advpropsys/cuda-oxide that referenced this pull request Jun 10, 2026
Clean auto-merge plus one test-arity fix: the slot-map unit test's
MirEnumType::get call gains the variant_discriminants argument this
branch added.
@nihalpasham
nihalpasham deleted the fix/issue128-struct-field-llvm-index branch June 12, 2026 10:19
@elibol elibol mentioned this pull request Oct 7, 2026
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.

kernel silently reads the wrong struct field on the GPU (reordered/padded repr(Rust) struct)

1 participant