Skip to content

fix(mir-importer): advance place-walker type via ProjectionElem::ty - #156

Merged
nihalpasham merged 2 commits into
mainfrom
fix/issue131-place-walker-projection-ty
Jun 10, 2026
Merged

nihalpasham merged 2 commits into
mainfrom
fix/issue131-place-walker-projection-ty

Conversation

@nihalpasham

Copy link
Copy Markdown
Collaborator

Fixes #131.

match xs[i] over an array of enums failed to import:

Unsupported construct: Downcast on non-ADT type: ... RigidTy(Array(... Adt(... E ...) ...))

In translate_place_iterative (the mir-importer place walker), the running current_rust_ty was only advanced by the Field arm. For the projection chain [Index, Downcast, Field] produced by a match payload binding on xs[i], the Downcast/Field handler (apply_enum_field_projection) received the stale outer Array type instead of the element's enum ADT and bailed. The same staleness affected ConstantIndex (xs[0] with a runtime-unknown discriminant) and Deref ((*p)[i], which surfaced the Ref type at the Downcast).

Fix

One uniform fold using rustc_public's own projection typing: each walker iteration now advances current_rust_ty = projection.ty(current_rust_ty)? (rustc_public::mir::ProjectionElem::ty) after the arm processes its element, so every arm observes the type before its own projection and the next iteration sees the narrowed type. This covers Deref, Field, Index, ConstantIndex, Subslice, Downcast (returns the enum Ty unchanged, exactly what apply_enum_field_projection expects), and OpaqueCast. The now-redundant Field-arm update is removed; the fold is the single source of truth.

Before: [Index, Downcast, Field]  type stays [E; 4]   -> Downcast bails (non-ADT)
After:  [Index, Downcast, Field]  [E; 4] -> E -> E    -> payload extracted

Test

New tracked example enum_array_match, three kernels pinning each previously-stale chain:

Kernel Chain Source shape
match_runtime_index [Index, Downcast, Field] match xs[i]
match_const_index [ConstantIndex, Downcast, Field] match xs[0]
match_deref_index [Deref, Index, Downcast, Field] (*p)[i]

The enum has payload (A(u32), B(u32)) and fieldless (C) variants. The deref shape goes through a #[device] helper taking &[E; 4] so ReferencePropagation cannot fold the Deref away. The host sweeps all index/discriminant combinations and exits 1 on any mismatch.

Verification

  • Baseline reproduces the exact issue match xs[i] over an array of an enum fails to import (Downcast on non-ADT type: Array) #131 error; with the fix, all three kernels compile and the .ll shows the tag load, discriminant branch chain, and extractvalue payload extraction.
  • GPU-verified on sm_120 (RTX 5090): runtime/const/deref index chains all match.
  • Prove-it-bites: reverting the fold re-breaks both the Index chain (Array error) and the Deref chain (Ref error).
  • cargo test -p mir-importer green; clippy and fmt clean; compile sweep of 8 projection-heavy examples clean.

translate_place_iterative tracked the running Rust type of the walked
place by hand, but only the Field arm ever advanced it. For the
projection chain [Index, Downcast, Field] produced by a match payload
binding on `xs[i]` (array of enums), the Downcast/Field handler
(apply_enum_field_projection) received the stale outer Array type
instead of the element's enum ADT and bailed with:

  Unsupported construct: Downcast on non-ADT type:
    ... RigidTy(Array(... Adt(... E ...) ...))

The same staleness affected ConstantIndex (`match xs[0]` with a
runtime-unknown discriminant) and Deref (`(*p)[i]` through a reference
parameter, which surfaced the Ref type at the Downcast instead).

Replace the per-arm bookkeeping with one uniform fold: each loop
iteration now advances the type with rustc_public's own projection
typing, `current_rust_ty = projection.ty(current_rust_ty)?`, after the
arm has processed its element. ProjectionElem::ty handles Deref, Field,
Index, ConstantIndex, Subslice, Downcast (returns the enum Ty
unchanged, exactly what apply_enum_field_projection expects) and
OpaqueCast, so every arm observes the type before its own element and
the next iteration sees the narrowed type. The now-redundant Field-arm
update is removed; the fold is the single source of truth.

If the fold itself fails (malformed MIR), the bail-out reports the
projection element and the type it was applied to so the error stays
actionable.

Issue: #131
Promotes the issue #131 repro into a tracked example with three
kernels, one per previously-stale projection chain:

  match_runtime_index  [Index, Downcast, Field]          match xs[i]
  match_const_index    [ConstantIndex, Downcast, Field]  match xs[0]
  match_deref_index    [Deref, Index, Downcast, Field]   (*p)[i]

The enum carries payload (A(u32), B(u32)) and fieldless (C) variants,
so the match exercises MirEnumPayloadOp extraction as well as the bare
discriminant switch. The deref shape goes through a #[device] helper
taking &[E; 4]: a reference parameter is opaque to
ReferencePropagation, so the Deref projection reaches the importer
intact (an inline `let p = &xs;` would be folded away before
translation). The const-index kernel derives the array contents from a
kernel parameter because a fully-constant `match xs[0]` is folded away
by rustc's MIR optimizations before it reaches the importer.

The host sweeps every array element for the runtime/deref kernels and
both discriminant branches for the const-index kernel, and exits 1 on
any mismatch. Standard smoketest category; no script change needed.

Issue: #131
@nihalpasham nihalpasham added bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Jun 10, 2026
@nihalpasham
nihalpasham merged commit d24d098 into main Jun 10, 2026
23 checks passed
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.
@nihalpasham
nihalpasham deleted the fix/issue131-place-walker-projection-ty branch June 12, 2026 10:19
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)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

match xs[i] over an array of an enum fails to import (Downcast on non-ADT type: Array)

1 participant