Skip to content

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

Closed

Description

@hbtweb

I hit this building a struct inside a kernel and reading a field back — the value came back wrong, with no error at all. On other structs the same thing fails loudly instead, in a few different shapes depending on version:

# LLVM module verification:
Value being inserted / extracted does not match the type of the indexed aggregate
# or (v0.2.0):
Lowering failed: IntToInt: source is not an integer
# or (v0.1.0):
Compilation error: invalid input program

So it's the same underlying bug showing up as either a wrong value (scary) or a confusing build error. It doesn't need generics or a custom trait — the kernel just has to build a repr(Rust) struct whose fields rustc reorders/pads.

Reproduce

The trigger is a repr(Rust) struct whose fields rustc reorders, with a multi-word align-4 enum field that forces interior [N x i8] padding. To also hit the silent identity-fallback path, put the generic struct in a sibling crate so its MirStructType is reconstructed across the crate boundary at monomorphization.

arena_core (a small no_std crate):

#![no_std]

#[derive(Copy, Clone)]
pub enum Layout { Aos, Soa, AoSoA(u32) }   // payload variant -> align-4, multi-word enum

pub trait CellStore {
    fn bump(&self, n: u32) -> u32;
    fn store(&self, idx: u32, val: u32);
}

// declaration order: store, cap, stride, layout. rustc reorders in memory
// (fat-pointer store first, then u32s, then the enum) -> decl index != LLVM
// field index, and the lowered struct gets [N x i8] padding after the enum.
pub struct ScratchArena<S: CellStore> { store: S, cap: u32, stride: u32, layout: Layout }

impl<S: CellStore> ScratchArena<S> {
    pub fn new(store: S, cap: u32, stride: u32, layout: Layout) -> Self {
        Self { store, cap, stride, layout }
    }
    pub fn alloc(&self) -> Option<u32> {
        let s = self.store.bump(1);
        if s >= self.cap { None } else { Some(s) }
    }
    pub fn write(&self, slot: u32, field: u32, val: u32) {
        let i = match self.layout {                 // reads layout, cap, stride, store off &self
            Layout::Soa => field.wrapping_mul(self.cap).wrapping_add(slot),
            _           => slot.wrapping_mul(self.stride).wrapping_add(field),
        };
        self.store.store(i, val);
    }
}

#[inline(never)]   // keep the receiver a pointer-to-struct across the crate boundary
pub fn alloc_and_fill<S: CellStore>(a: &ScratchArena<S>) {
    if let Some(slot) = a.alloc() {
        a.write(slot, 0, slot);
        a.write(slot, 1, slot.wrapping_mul(10));
    }
}

The kernel supplies a CellStore backed by a device buffer + atomic cursor, builds the arena, and drives it through the &self methods:

#[kernel]
pub fn fill(cursor: &[u32], data: &[u32], params: &[u32]) {
    let cur = unsafe { &*(cursor.as_ptr() as *const DeviceAtomicU32) };
    let store = DeviceStore { cursor: cur, data };   // impl CellStore: bump = atomic fetch_add, store = raw write
    let arena = ScratchArena::new(store, params[0] /*cap*/, params[1] /*stride*/, Layout::Soa);
    alloc_and_fill(&arena);                          // every field access here goes through the mis-mapped index
}

Under Layout::Soa, slot s's two fields should land at data[s] and data[cap + s]. Pre-fix the build fails LLVM verification — an insert_value whose index lands on the struct's [N x i8] padding field; post-fix all cap slots verify. (The padding-unaware index defect shows even single-crate; the silent identity fallback additionally needs the cross-crate generic above.)

What I found digging in

Root cause (mir-lower / aggregate.rs)

convert/ops/aggregate.rs maps a declaration-order field index to the LLVM-struct field index in four places, and each diverges from the struct the type converter actually builds (build_struct_with_explicit_padding):

  1. convert_extract_field — when the operand's MirStructType isn't in the type-history, it falls back to a silent identity mapping (llvm_index = decl_index). On a reordered struct that extracts a different field. This is the dangerous, silent path.
  2. convert_insert_field — same silent identity fallback.
  3. convert_field_addr — honours reorder but not the [N x i8] padding, so the GEP index is off by the pad count.
  4. convert_construct_struct — builds the padded LLVM struct but inserts fields counting only real fields, ignoring pad slots → off-by-pad indices.

cast.rs (the IntToInt message) and the importer are fine — they just forward the wrong operand they were handed.

What worked for me: one padding/reorder-aware llvm_field_index helper that all four sites go through, and replacing the silent identity fallback with recover-or-error (only allowing identity for an already-lowered LLVM struct, whose order is final — slices/fat pointers — otherwise erroring instead of guessing). That last part is in the same spirit as #27 (no silent miscompiles).

Related

Suggested labels: miscompile, codegen, safety.

I've got the fix + this repro on a fork (DCO-signed) and can open a PR. (Heads-up for PR time: I still owe a cargo fmt pass and want to add a hardware-free unit test for the index helper.)

Activity

  1. changed the title [-]Device codegen mis-indexes reordered / padded `repr(Rust)` struct fields[/-] [+]kernel silently reads the wrong struct field on the GPU (reordered/padded repr(Rust) struct)[/+] on Jun 7, 2026
  2. added
    bug
    miscompile
    codegen
    on Jun 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugcodegenmiscompile

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions