Skip to content

evaluate unevaluated array length constant for code generation - #236

Closed
haixuanTao wants to merge 3 commits into
NVIDIA:mainfrom
haixuanTao:fix/const-eval-array-length-bridge
Closed

haixuanTao wants to merge 3 commits into
NVIDIA:mainfrom
haixuanTao:fix/const-eval-array-length-bridge

Conversation

@haixuanTao

Copy link
Copy Markdown
Contributor

Summary

Here's the core constraint: by the time you're in codegen, array length consts should be fully monomorphized and evaluatable. But stable_mir's TyConst::eval_target_usize() fails on TyConstKind::Unevaluated — it can't reduce those to a u64 through stable_mir's API alone.

The TyCtxt bridge is necessary because:

  • TyCtxt::normalize_erasing_regions(fully_monomorphized, const) is the actual rustc mechanism to force-evaluate an unevaluated const in a monomorphized context
  • That API is only available through rustc internals (rustc_middle), not through stable_mir
  • The type translator lives in mir-importer, which intentionally has no direct TyCtxt dependency — hence the callback bridge rather than passing tcx directly
  • The alternative would be to pass tcx directly into run_pipeline and down to the type translator, but that would couple mir-importer tightly to rustc internals, defeating its design goal of being stable_mir-only.

So the bridge is a pragmatic workaround for a gap in stable_mir's const evaluation API. If stable_mir ever exposes a way to evaluate Unevaluated consts in a fully-monomorphized context, the whole bridge could be deleted.

haixuanTao and others added 2 commits June 17, 2026 19:32
[Vector; SUB_LEN] (a generic/anonymous const array length) reaches the type
translator as TyConstKind::Unevaluated, which stable_mir eval_target_usize()
cannot evaluate ("cannot be encoded as u64").

The codegen backend holds TyCtxt, which can. It installs a lifetime-erased eval
callback into a mir-importer thread-local for the duration of one
rustc_internal::run scope; the callback does
tcx.normalize_erasing_regions(fully_monomorphized, const) then try_to_target_usize.
The array type arm falls back to this when eval_target_usize() returns None.

mir-importer gains install/clear/eval_array_len; rustc-codegen-cuda builds and
installs the callback around run_pipeline.
Replace manual clear_array_len_eval() call after run_pipeline with a
drop guard, so the thread-local is always cleared even if run_pipeline
panics — preventing a dangling lifetime-erased closure from remaining
in the thread-local after tcx is released.

https://claude.ai/code/session_01A5hja53wWguuVfwGxzzhdU
@nihalpasham
nihalpasham force-pushed the fix/const-eval-array-length-bridge branch from 5f2cee7 to d758839 Compare June 17, 2026 14:15
@nihalpasham nihalpasham added bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Jun 17, 2026
The lifetime-erasing transmute on the array-length eval callback spelled
out Box<dyn Fn(&TyConst) -> Option<u64>> three times, tripping
clippy::type_complexity (-D warnings) in the rustc-codegen-cuda clippy
job. Factor it into a local `EvalFn<'a>` alias.
@nihalpasham nihalpasham added the TBD Not yet triaged; scope or disposition undecided label Jun 17, 2026
@nihalpasham

nihalpasham commented Jun 17, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for the PR.

A couple of points:

Upon reviewing this, I don't think we can take it in its current form. Wanted to explain why rather than just close it.

The change moves the compiler context (tcx) into mir-importer through a global thread-local plus an unsafe transmute that erases the closure's lifetime. That's a problem on two fronts:

  • mir-importer is intentionally built only on rustc_public (the stable-track API). We keep compiler internals (rustc_middle / rustc_internal) out of that crate on purpose, so it stays portable as that API stabilizes — this change pulls them back in.
  • The global plus a lifetime-erasing unsafe isn't something we can sign off on for soundness, even with the cleanup guard.

Before we land any fix, could you share a small self-contained kernel that reproduces the failure? I tried to trigger the "unevaluated array length" path from ordinary cuda-oxide code (const generics, const-item lengths) and it all compiles fine today, so I'd like to see exactly what you're compiling that hits it.

If it turns out to be a real gap, I'm fairly sure it lives upstream: rustc_public's eval_target_usize calls try_to_target_usize without normalizing the const first, so it just gives up on an unevaluated one. The proper fix is a small change there (normalize, then read), and we'd gladly help get that into rustc_public rather than work around it on our side.

@nihalpasham nihalpasham added the on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves label Jun 18, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

I'm closing this. Feel free to re-open if you have any updates.

haixuanTao added a commit to haixuanTao/cuda-oxide that referenced this pull request Jul 8, 2026
The thread-local tcx bridge (rejected upstream in NVIDIA#236 for
crossing the rustc_public-only boundary of mir-importer and for the
lifetime-erasing unsafe) is dead code after the rebase onto upstream main:
the nexus shader crate — the original trigger, with const-expr array lengths
like `SPATIAL_DIM * 2` — now builds with plain `eval_target_usize()`.
Verified: full cubin builds + pendulum PPO on CUDA, all tests green.

Keeps `eval_target_usize()` in translate_type (rather than upstream's manual
little-endian byte parse of the Value allocation), which is the API-shaped
version of the same read.

Co-Authored-By: Claude Fable 5 <[email protected]>
@haixuanTao

Copy link
Copy Markdown
Contributor Author

Following up to close the loop: this is now obsolete — the problem no longer reproduces on current main.

I retested the original trigger (the dimforge nexus physics shaders, whose constraint banks use const-expression array lengths like [JointConstraintElement; MAX_CONSTRAINTS_PER_JOINT] with const MAX_CONSTRAINTS_PER_JOINT: usize = SPATIAL_DIM * 2) against latest main with our workaround fully removed: the whole crate (265 device functions) compiles to a working sm_120 cubin, and plain TyConst::eval_target_usize() handles every length const the build produces — nothing Unevaluated reaches the type translator anymore. Somewhere between the June base this PR was written against and current main, the gap closed.

We've dropped the tcx bridge from our fork accordingly. Thanks for the review notes — agreed in hindsight on both the crate-boundary and soundness points. No need to reopen.

meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
NVIDIA#236)

* refactor: resolve check-placement policy once per compile

The bounds-check gates were scattered environment reads:
check_hoisting_disabled() and force_device_checks() consulted process
globals at seven sites across classification, relocation, and proof
discharge. They become one CheckOptimizations policy — three
independent axes (hoist_to_preheaders, relocate_to_launch,
discharge_proofs) with named constructors: release() (all on),
device_debug() (checks stay where the source puts them; proofs still
discharge), and disabled() (the differential harness's semantic
reference, which inherits no proofs; 2026-08-12 review, S2).

The policy is resolved from the environment once at compiler
construction and carried on the function compiler, so it cannot
change between classification and emission within a compile. The
ablation env vars keep their names and semantics; behavior is
unchanged under every existing switch combination (differential
placement harness green). This is groundwork for NVIDIA#210, where
--device-debug selects device_debug() per compile and joins the
cache keys.

Signed-off-by: Melih Elibol <[email protected]>

* feat: device-debug, lineinfo, sanitizer, and opt-level compile options

CompileOptions gains opt_level, device_debug, lineinfo, and
sanitize_memcheck; a TileirasOptions carrier resolves them once and
threads through run_tileiras (--opt-level / --device-debug /
--lineinfo / --sanitize=memcheck), the disk-cache path, and both cache
keys. device_debug implies --opt-level 0 unless a level is set
explicitly, and selects the device_debug check policy: no preheader
hoisting, so every device-resident bounds check sits at the source
line that wrote it and inlined regions stay contiguous for the
rangeless -O0 -G DWARF contract. Proof discharge and launch relocation
are deliberately untouched — both remove a check from device code
entirely, and the bounded family's launch checks are load-bearing
(without relocation its undischarged checks are compile errors).

Cache correctness: the flags join the L1 key via CompileOptions and
the L2 key as new key material (existing disk entries recompile once),
and cache entries validate the flags through a formerly-padding header
byte — old release entries carry 0 there, which is exactly the release
encoding, so they keep validating without a format bump.

Tests: placement pins under device_debug (a hoistable check falls back
in place; discharge and launch checks undisturbed), key separation per
flag, entry-validation flag mismatches with legacy-zero acceptance,
option resolution, and GPU end-to-end launches of debug, lineinfo, and
memcheck-instrumented cubins through the real tileiras.

Closes NVIDIA#210. Closes NVIDIA#219 (opt_level reaches KernelCompiler via
.options(CompileOptions::new().opt_level(n)) and both cache keys).

Signed-off-by: Melih Elibol <[email protected]>

* docs: align device_debug and cache-entry comments with the implementation

The CompileOptions doc claimed device_debug disables launch relocation;
it only disables hoisting (relocation is load-bearing for the bounded
family). And three comments claimed old cache entries keep validating
via the flags byte — they cannot be reached at all, since the flags
also joined the key material and orphaned pre-flags entries; the byte
is defense in depth, now described as such, with a note on why the
entry format version was deliberately not bumped.

Signed-off-by: Melih Elibol <[email protected]>

---------

Signed-off-by: Melih Elibol <[email protected]>
meefs pushed a commit to meefs/cuda-oxide that referenced this pull request Sep 30, 2026
* fix: version persisted tuning cache keys

Persist the L2 key encoding alongside each tuning-record digest so key-preimage migrations are distinguishable from workspace drift.

Keep legacy bare-string records wire-compatible and preserve strict verification whenever stored and current keys are comparable.

Signed-off-by: Sam, Joochul Chang <[email protected]>

* test: pin the l2 key preimage to L2_KEY_SCHEMA

The schema bump was enforced by convention only; nothing failed when
the preimage changed, which is exactly how NVIDIA#236 changed every key
without a test noticing. This asserts one exact digest from fixed
inputs, so any preimage change fails loudly with instructions: bump
L2_KEY_SCHEMA, update the digest, extend the schema history.

Signed-off-by: Melih Elibol <[email protected]>

---------

Signed-off-by: Sam, Joochul Chang <[email protected]>
Signed-off-by: Melih Elibol <[email protected]>
Co-authored-by: Melih Elibol <[email protected]>
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) on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves TBD Not yet triaged; scope or disposition undecided

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants