Skip to content

[BUG]: mir-importer rejects a zero-sized aggregate containing a ZST array ("Zero-sized constant synthesis does not support type MirArrayType") #1886

Backlog

Description

@ubmaxxer

Description

A kernel that builds a value whose type is entirely zero-sized and contains an array member, such as S { a: [Z; 4] } or ([Z; 4], Z, Z, Z) with struct Z {}, fails device codegen with Unsupported construct: Zero-sized constant synthesis does not support type MirArrayType. rustc folds the whole value into one zero-sized constant operand, and the importer's translate_zero_sized_constant_value can synthesize a zero-sized struct, union or the empty tuple from its type alone but has no case for an array or a non-empty tuple, so it fails closed when the per-field recursion reaches the array. The same program compiles and runs on the host. Both device routes fail, since this happens before route selection. The shape is reachable from ordinary generic code once a type parameter is zero-sized, for example Buf<(), 4> with struct Buf<T, const N: usize> { data: [T; N] }, or a tag struct holding [PhantomData<A>; 2]. Reproduced on main at a412e09.

Error / actual behavior

$ cargo oxide run repro
   Compiling repro v0.1.0
error: [rustc_codegen_cuda] Device codegen failed: PTX generation failed: Translation failed: k: ["src/main.rs": line: 17, column: 32] Compilation error: invalid input program.
       Unsupported construct: Zero-sized constant synthesis does not support type MirArrayType { element_ty: TypeHandle(23), size: 4 }
error: could not compile `repro` (bin "repro") due to 1 previous error; 3 warnings emitted

The NVVM route (--emit-nvvm-ir) fails identically; the error is raised in the importer, before the route split.

Shapes checked, one kernel per build:

value device build
[Z; 4] ok
([Z; 4],) ok
(Z, Z) ok
([Z; 4], u32) ok
([Z; 4], Z, Z, Z) fails
S { a: [Z; 4] } fails
Buf<(), 4> where struct Buf<T, const N: usize> { data: [T; N] } fails
Tags { a: [PhantomData<A>; 2], b: PhantomData<B> } fails

Nothing in the last two definitions is ZST-specific; Buf<u32, 4> compiles.

Expected behavior

The kernel compiles and the program prints 8. The value is zero-sized and contributes nothing at run time, so there is nothing to lower; the importer only needs to spell a value of that type.

Replacing the kernel body line with *slot = x as u64 + consume_m(([Z {}, Z {}, Z {}, Z {}], 3)); (one sized member) compiles and prints 10, which is the behavior the zero-sized forms should also have.

Minimal reproduction example

use cuda_core::{CudaContext, DeviceBuffer, LaunchConfig};
use cuda_device::{DisjointSlice, cuda_module, kernel, thread};

#[derive(Clone, Copy)] pub struct Z {}
#[derive(Clone, Copy)] pub struct S { a: [Z; 4] }

#[inline(never)] fn consume_s(_v: S) -> u64 { 1 }
#[inline(never)] fn consume_t(_v: ([Z; 4], Z, Z, Z)) -> u64 { 2 }
#[inline(never)] fn consume_m(v: ([Z; 4], u32)) -> u64 { v.1 as u64 }

#[cuda_module]
mod kernels {
    use super::*;
    #[kernel]
    pub fn k(x: u32, mut out: DisjointSlice<u64>) {
        if let Some(slot) = out.get_mut(thread::index_1d()) {
            *slot = x as u64 + consume_s(S { a: [Z {}, Z {}, Z {}, Z {}] });
            // Also fails:   *slot = x as u64 + consume_t(([Z {}, Z {}, Z {}, Z {}], Z {}, Z {}, Z {}));
            // Compiles (10): *slot = x as u64 + consume_m(([Z {}, Z {}, Z {}, Z {}], 3));
        }
    }
}

fn main() {
    let ctx = CudaContext::new(0).unwrap();
    let stream = ctx.default_stream();
    let module = kernels::load(&ctx).unwrap();
    let cfg = LaunchConfig { grid_dim: (1, 1, 1), block_dim: (1, 1, 1), shared_mem_bytes: 0 };
    let mut out = DeviceBuffer::<u64>::zeroed(&stream, 1).unwrap();
    unsafe { module.k(&stream, cfg, 7u32, &mut out) }.unwrap();
    println!("{}", out.to_host_vec(&stream).unwrap()[0]);
}

// Standalone example crate; Cargo.toml as examples/vecadd. Run with `cargo oxide run <crate>`.

Operating System

Ubuntu 24.04.3 LTS (Linux 6.14.0-29-generic)

GPU and GPU Architecture

NVIDIA GeForce RTX 4070 (sm_89). Not GPU-dependent: the failure is at build time, in the importer.

CUDA driver version

580.178.04

cargo oxide doctor

cargo-oxide environment check
==============================

Rust toolchain... ✓ rustc 1.99.1 (58cf8f9c3 2026-10-13)
rust-toolchain.toml... ✓ channel 1.99.1
Pinned toolchain active... ✓ 1.99.1-x86_64-unknown-linux-gnu
Required rustup components... ✓ rust-src, rustc-dev, rust-analyzer, clippy, rustfmt, llvm-tools
Codegen backend... ✓ <repo>/cuda-oxide/crates/rustc-codegen-cuda/target/x86_64-unknown-linux-gnu/debug/librustc_codegen_cuda.so
Project config (.cargo/cuda-oxide.toml)... - not present (using defaults)
CUDA headers (cuda.h)... ✓ /usr/local/cuda-13.3/include/cuda.h (discovered; neither CUDA_TOOLKIT_PATH nor CUDA_HOME is set)
CUDA toolkit (nvcc)... ✓ Cuda compilation tools, release 12.0, V12.0.140 (/bin/nvcc)
libNVVM (libnvvm.so)... ✓ libNVVM 2.0
nvJitLink (libnvJitLink.so)... ✓ nvJitLink 13.3
libdevice (libdevice.10.bc)... ✓ /usr/local/cuda/nvvm/libdevice/libdevice.10.bc
llc (LLVM)... ✓ LLVM version 23.1.1-rust-1.99.1-stable ($RUSTUP_HOME/toolchains/1.99.1-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/bin/llc)
clang / libclang resource dir... ✓ /usr/lib/llvm-18/lib/clang/18 (via clang)
NVIDIA driver / GPU... ✓ NVIDIA GeForce RTX 4070 (compute capability 8.9, driver 580.178.04)
cuda-gdb (optional)... ✓ NVIDIA (R) CUDA Debugger (/bin/cuda-gdb)
compute-sanitizer (optional)... ✓ Version 2022.4.1 (/bin/compute-sanitizer)
wild linker (optional)... - not found (only needed for CUDA_OXIDE_LINKER=wild)

✅ Environment looks good!

rustc version

rustc 1.99.1 (58cf8f9c3 2026-10-13), host x86_64-unknown-linux-gnu, LLVM version 23.1.1

llc version

LLVM version 23.1.1-rust-1.99.1-stable (rustup llvm-tools component)

Additional context

No .ll or .ptx is produced; the pipeline stops in mir-importer.

What the importer receives. rustc hands over a single constant operand for the whole aggregate. Optimized MIR for the host twin of the kernel (rustc -O --emit=mir, pinned toolchain):

_3 = consume_s(const S {{ a: [Z {{  }}, Z {{  }}, Z {{  }}, Z {{  }}] }}) -> [return: bb1, unwind continue];

The constant has no allocation behind it (ConstantKind::ZeroSized), so the importer has to build a value of type S from the type alone. The mixed tuple ([Z; 4], u32) also arrives as one constant, but it is 4 bytes long and therefore ConstantKind::Allocated; that takes the allocation-backed tuple path, which lowers the array field through the general array-constant code, so it compiles. Only the fully zero-sized case ends up in the synthesis helper.

Where it comes from (cuda-oxide/crates/mir-importer/src/translator/, at a412e09). Both forms reach translate_zero_sized_constant_value in rvalue/const_bytes.rs. types::is_zst_type only recognizes the empty tuple, a struct with no fields, or a zero-size union, so the constant takes the ordinary struct or tuple path; with no allocation, each zero-size field is synthesized from its type via that helper (the struct path calls it on S directly and its Struct arm recurses into the fields; the tuple path reaches it per field through translate_constant_value_from_bytes). The helper's ZeroSizedKind has Struct, Union, EmptyTuple and Unsupported; a MirArrayType falls into Unsupported, as would a non-empty MirTupleType reached this way ("Only empty tuple constants can be synthesized as zero-sized values"). A bare [Z; 4] constant is lowered by the separate bare-array path and is fine, which is why only the aggregate case fails.

Suggested fix. In translate_zero_sized_constant_value, add an Array kind that synthesizes the element type size times and emits MirConstructArrayOp, and a Tuple kind that synthesizes one value per member and emits MirConstructTupleOp, reusing the recursion the Struct arm already has. Everything else keeps failing closed. Happy to open a PR if that approach is acceptable.

This problem was found with a fuzzer; the reproducer above was reduced from its test case. The report was written with LLM assistance.

Activity

  1. ubmaxxer commented on Nov 27, 2026

    @ubmaxxer
    MemberAuthor

    A third case for the same helper, found after filing: a zero-sized enum (one unit variant) inside a zero-sized aggregate takes the same path and has no arm either.

    #[derive(Clone, Copy)] pub enum Z { V0 }
    #[derive(Clone, Copy)] pub struct S1 { pub f0: Z }
    
    #[inline(never)] pub fn consume_s1(s: S1, x: u32) -> u32 { match s.f0 { Z::V0 => x.wrapping_add(1) } }
    
    // in a kernel:
    *slot = consume_s1(S1 { f0: Z::V0 }, x);
    Translation failed: k: ["src/main.rs": line: 15, column: 71] Compilation error: invalid input program.
    Unsupported construct: Zero-sized constant synthesis does not support type MirEnumType { name: "Z", variant_names: ["V0"], variant_field_counts: [0], total_size: 0, … }
    

    Passing Z::V0 by itself compiles, exactly as a bare [Z; 4] does above; only the zero-sized aggregate that contains it reaches translate_zero_sized_constant_value. So the helper needs Array, non-empty Tuple and single-variant Enum kinds. Reproduced on main at a412e09; the importer is unchanged at the current main (8b91bb7). Returning such an enum from a device function fails separately, in the return-operand verifier (#1890).

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions