Repository navigation
feat(mir): preserve Rust pointer provenance with a typed fact oracle - #1186
Merged
Merged
Conversation
Signed-off-by: Raul Estrada <[email protected]>
…nt Erased tail slices DisjointSlice::get_thread_local is not declared anywhere in cuda-device, so both dispatch arms and the emitter were unreachable. The emitter also built its *mut T result through the kind-erased constructor and stored it into a rustc-typed destination, which the new kind-aware verification would reject if the path ever became reachable. The three DST-tail reconstruction sites keep MirSliceType::get on purpose; comments now state the invariant (projection-internal values stay Erased until an Rvalue::Ref/AddressOf boundary retypes them). Signed-off-by: nihalpasham <[email protected]>
Three example kernels exposed two gaps in the kind-preservation policy this PR documents: 1. Intrinsic results were stored with the normalization-only path, so an emitter-internal Erased pointer result could not take the destination slot's rustc-declared kind and MirStoreOp verification failed (mathdx_ffi_test: *mut i8 in AS3, mcast_barrier_test: *const u64 in AS7). A compiler-recognized device operation is one of the documented Rust-typed boundaries, so emit_store_result_and_goto now stores through store_local_at_rust_boundary, which establishes the declared kind while still requiring the same pointee shape. 2. The Rvalue::Ref boundary now emits a kind-only mir.cast <PtrToPtr> between wgmma_fence and the MMA, which the deferred-accumulator region matchers treated as an unsupported op, so fusion silently declined and lowering failed (wgmma_mma_bf16). Kind-only retypes between thin pointers with the same pointee and address space lower to nothing, so both the linear/pipeline walker and the counted-loop whitelist now look through them. Signed-off-by: nihalpasham <[email protected]>
Verify exact Rust and ABI call boundaries, including closure receivers and drop glue, and make pointer-producing casts, projections, aggregates, intrinsics, and storage operations preserve or explicitly establish their authority. Close aggregate and canonical-function-token laundering paths, preserve raw kinds through NVVM cluster mapping, and run whole-tree producer checks before pointer kinds are erased. Canonicalize harmless pointer-kind reborrows in deferred WGMMA accumulator matching, with counted-loop, verifier-negative, and real Rust pipeline coverage. Signed-off-by: nihalpasham <[email protected]>
Signed-off-by: nihalpasham <[email protected]>
A kind-only mir.cast lowers to a plain value forwarding with no LLVM instruction. convert_ptr_offset derived the GEP element type from the pointer operand's recorded type history, which does not follow that replacement edge, and on a miss silently fell back to a byte-sized element. wrapping_offset on *const i32 then stepped back N bytes instead of N elements and the kernel faulted with a misaligned address at run time (ptr_offset_from example, CUDA error 716). Take the element type from the mir.ptr_offset result type instead, which still carries the exact MIR pointee when the converter runs, and make a missing pointer fact a hard compile error rather than a guessed i8. Signed-off-by: nihalpasham <[email protected]>
…istory Four converters derived semantic facts (element size, aggregate layout, enum layout) by walking the pointer operand's recorded type history. That history does not follow the value forwarding a kind-only mir.cast lowers to, so a miss produced a spurious error, and a stale hit could silently misscale a GEP stride, write an enum tag at the wrong offset, or multiply a memcpy byte count. Each fact now rides the op itself: - mir.array_element_addr: element type from the op's own result type; single-index GEP over the element (same address as the old two-index [N x T] form). - mir.memcpy / mir.memmove: new memcpy_elem_type / memmove_elem_type TypeAttr stamped by typed build() constructors from dst's build-time pointer type; verifiers require it to equal the dst/src pointee. - mir.set_discriminant: new set_discriminant_enum_ty TypeAttr, same treatment. - mir.field_addr: new aggregate_ty TypeAttr plus a build() constructor; every importer construction site goes through it. A missing fact is now a hard compile error, never a guessed i8 or a stale history hit. Attribute keys are op-prefixed because pliron registers attribute dictionary keys globally. Validated: 216/216 examples compile and run on sm_120a, gemm_views bench at parity (safe == raw bitwise), workspace suites, fmt, clippy. Signed-off-by: nihalpasham <[email protected]>
Enum discriminants were scraped out of format!("{:?}") Debug output
with silent defaults on a miss. The worst consumer was the atomic
memory-ordering decoder: an ordering constant whose Debug string did
not parse became discriminant 0, which is Relaxed, silently deleting
the fences the source asked for.
- extract_enum_variant reads the tag with Allocation::read_uint (hard
error on unreadable or uninitialized bytes; the old byte-OR loop
invented values from partial data), allows ZeroSized only for
single-variant enums, rejects Unevaluated/Param, and maps the tag to
a variant through AdtDef::discriminant_for_variant, masked to the
stored tag width.
- extract_ordering matches the variant by NAME, so a cuda-device
renumber cannot silently remap orderings, and every unknown case is
a hard compile error. The Relaxed and SeqCst fallbacks are gone.
Validated: workspace suites, 216/216 examples compile and run on
sm_120a (atomics and scoped_atomic_load_store execute correctly),
gemm_views bench at parity, fmt, clippy.
Signed-off-by: nihalpasham <[email protected]>
SharedArray's N and ALIGN const generics were decoded by scraping the TyConst Debug string, and unparseable consts were silently dropped from the list before positional indexing, so a failed N parse let ALIGN be read as the element count: an undersized shared-memory allocation. DynamicSharedArray's ALIGN defaulted to 16 on every read failure, silently misaligning extern shared memory declared with a larger alignment (a runtime TMA hazard). - N and ALIGN now come from TyConst::eval_target_usize at their exact declaration positions; any non-evaluable const is a hard error, and ALIGN defaults only when the parameter is genuinely absent. - The two SharedArray substs checks (call classification and intrinsic dispatch) share one typed predicate: Self at position 0, ADT named SharedArray, defined in the cuda_device crate. Debug-string contains() matching is gone from both, so a user type named SharedArray can no longer be classified as shared memory here. - DynamicSharedArray dispatch is anchored to the cuda_device crate and its ALIGN read hard-errors instead of assuming 16. Validated: workspace suites, 216/216 examples compile and run on sm_120a (dynamic_smem, addressof_sharedarray, swizzle_smem, compiler_features execute correctly), gemm_views bench at parity, fmt, clippy. Signed-off-by: nihalpasham <[email protected]>
Integer and raw-pointer constant values were recovered by substring
parsing of format!("{:?}") output. A parse miss produced 0 (a null
pointer or a zero integer), and the pointer parser COMPACTED
partially-uninitialized bytes, so bytes [None, Some(1)] decoded as
address 1: a wrong address, not even a default.
- Raw-pointer constants: read exactly target_pointer_width bytes from
the backing allocation with Allocation::read_partial_uint; hard
error when the allocation is missing, short, or uninitialized, and
a debug_assert that provenance-carrying constants took their own
branch earlier.
- Integer constants: the ASCII-digit fallback is deleted; the value
comes from the allocation with the same uninitialized-byte and
provenance hard errors (the old helper zero-filled uninit bytes, so
its error path alone could not catch them).
- format!("{:?}") on constants survives only as diagnostics text.
Validated: workspace suites, 216/216 examples compile and run on
sm_120a (option_ref_transmute, transmute_scalar_struct, cast_tests,
checked_arith execute correctly), gemm_views bench at parity, fmt,
clippy.
Signed-off-by: nihalpasham <[email protected]>
Fn/FnMut/FnOnce Output and Index/IndexMut Output projections were detected by substring-matching the DefId Debug string, so any user trait whose path contained Fn+Output (or Index+Output) silently resolved to the wrong type. Closure and fn-item struct names embedded the Debug id field, which depends on first-touch order, making type names nondeterministic across compilations. - The driver resolves FnOnceOutput, Index, and IndexMut once inside rustc_internal::run and hands them to the importer as KnownDefs; the importer stores them in a per-run cell that is overwritten at every pipeline entry so stale ids cannot leak. - One FnOnceOutput DefId equality replaces all three Fn-trait substring tests (Output lives only on FnOnce); Index/IndexMut resolve via DefId::parent(). Non-matches fall through to the existing hard error, never a guess. - The SharedArray projection arm gains the cuda_device crate anchor. - Closure and fn-item type names come from CrateDef::name(), stable across runs. Validated: workspace suites, 216/216 examples compile and run on sm_120a (device_closures, unchecked_indexing, addressof_sharedarray, vecadd execute correctly), gemm_views bench at parity, fmt, clippy. Signed-off-by: nihalpasham <[email protected]>
Seven cuda-device types (SharedArray, Barrier, DisjointSlice, ThreadIndex, TmaDescriptor, RangeToken, ConstantMemory) were recognized by bare trimmed_name() comparison, so a user struct with the same name was silently mistranslated (a user ThreadIndex became a bare usize; a user SharedArray became shared memory). The bounds-check call deleter matched any function whose path merely CONTAINED precondition_check, so a user fn named my_precondition_check was silently deleted from the kernel. - One helper, is_cuda_device_adt, carries the name + defining-crate check; every ADT identity site routes through it. A non-match falls through to ordinary handling, never an error. - The compiler-marker fns (__cluster_config, __dynamic_shared_alignment) gained the same crate anchor. - Call deletion is now is_std_precondition_check: defining crate must be core or alloc (alloc's Vec expands the same macro and those shim bodies are intentionally not collected) AND the exact last path segment must be precondition_check. User functions translate as normal calls. Validated: workspace suites, 216/216 examples compile and run on sm_120a (slice_index_bounds_check still traps out-of-bounds and unchecked_indexing still elides, proving the anchored deletion fires for core's shims), gemm_views bench at parity, fmt, clippy. Signed-off-by: nihalpasham <[email protected]>
Two helpers ended in a literal 8. get_type_size summed struct fields with no padding and answered 8 for anything unknown, and that number became real memcpy byte counts and layout offsets. natural_alignment emitted 'align 8' for unknown types and non-power-of-two values like 'align 3' for odd integer widths (invalid LLVM IR). - get_type_size is deleted. memcpy/memmove sizes come from the rustc stride of the stamped MIR element type, then exact LLVM layout, else a hard error naming the type. The relocation storage check and the struct-slot-map offset advance use the exact helpers with an explicit refusal instead of a guess. - natural_alignment returns Option: None for unknown types, any non-power-of-two, and integers wider than i128 (the old code over-claimed there too). Loads, stores, and allocas omit the align attribute on None, which LLVM soundly reads as the type's ABI alignment. Atomic load/store, where the syntax mandates alignment, hard-error instead of guessing. Validated: workspace suites, 216/216 examples compile and run on sm_120a; vectorization's per-type table is byte-identical, so LoadStoreVectorizer behavior is unchanged; regenerated .ll files show zero newly-omitted align attributes in practice; gemm_views bench at parity; fmt, clippy. Signed-off-by: nihalpasham <[email protected]>
Adds ptr_without_provenance: a minimal example minting non-null integer-address pointer constants (ptr::without_provenance), the path where the retired Debug-string parser could compact partially initialized bytes into a wrong address. The .ll shows the exact inttoptr constants under test. Also adapts the ex2 negative lowering test (landed on main in #1104) to the messages that surface on this branch: the generated op verifier rejects malformed scalar-math ops before the lowering recipe check runs. Signed-off-by: nihalpasham <[email protected]>
Pure move, zero behavior change. Every helper whose job is reading a fact from rustc through typed APIs now lives in one module, translator/facts.rs, with the oracle contract in its doc: rustc (typed APIs) ──► facts.rs ──► the rest of the importer a fact is exact, or it is a hard error; never a guess, never a Debug string. New rustc questions go here, nowhere else. Gathered: KnownDefs and its per-run cell, is_cuda_device_adt, is_cuda_device_fn, is_std_precondition_check, self_ty_is_shared_array, eval_usize_const (shared extraction of the SharedArray and DynamicSharedArray const-generic readers, error strings unchanged), extract_enum_variant. Translation machinery that merely consumes the facts stays where it was. Validated: full workspace suites, 218/218 examples compile and run on sm_120a, gemm_views bench at parity, fmt, clippy. Signed-off-by: nihalpasham <[email protected]>
A concrete pointer kind (SharedRef, UniqueRef, RawConst, RawMut) can
now only be minted by presenting a PointerOrigin, a fact value with
private fields that facts.rs alone can construct, from one of:
rustc evidence named ABI rules (documented)
Ty (Ref/RawPtr) ─┐ DynamicSharedArray result = RawMut
BorrowKind ─┼► PointerOrigin ◄─ DisjointSlice data = RawMut
RawPtrKind ─┤ │
carrier kind ─┘ ▼ (propagate, never strengthen)
mint_* helpers = the only kinded-type path
A new root clippy.toml bans the raw kind constructors everywhere
else (CI runs clippy with -D warnings, so a future direct mint is a
build error pointing at PointerOrigin). The two previously hardcoded
RawMut literals became the named ABI-rule constructors. Dialect-side
one-way verifiers from the kind model remain the runtime backstop.
Pure coupling refactor: regenerated vecadd and dynamic_smem .ll are
byte-identical to before the change.
Validated: workspace suites, clippy across both workspaces, 218/218
examples compile and run on sm_120a, gemm_views bench at parity, fmt.
Signed-off-by: nihalpasham <[email protected]>
nihalpasham
added a commit
that referenced
this pull request
Aug 28, 2026
Reworked onto main's #1186 device-global declaration cache: debug identity rides DeviceGlobalDeclaration as an equality-checked field instead of a parallel record type, the promoted-key fingerprint keeps main's align component under the domain tag, and the encoder covers the TypedPointer debug type from #1126. Signed-off-by: nihalp <[email protected]>
nihalpasham
added a commit
that referenced
this pull request
Aug 28, 2026
…storage #1186 tightened classify_union_constant_storage so SharedRef union alternatives with different pointee types fail closed. That is right for SSA reconstruction, which mints the carrier field's own reference type and could claim validity for a pointee the program never wrote. But the device-static initializer gate shares the classifier while emitting only exact bytes plus one integer-width relocation slot; no typed reference is ever minted, and device code reads the storage through its own field types. Release builds hid the regression because optimized MIR folds the example's union load away; any unoptimized device build (including CUDA_OXIDE_DEBUG=full) materializes the static and failed to compile device_global's documented union { word: &'static u32, byte: &'static u8 } shape. Thread a UnionConstantUse through the classifier so the SSA path keeps the pointee-identity rejection and the physical-storage gate does not, and cover the SharedRef mixed-pointee shape at both call sites. Signed-off-by: nihalp <[email protected]>
nihalpasham
added a commit
that referenced
this pull request
Aug 28, 2026
* debug: describe AS1 device globals Reworked onto main's #1186 device-global declaration cache: debug identity rides DeviceGlobalDeclaration as an equality-checked field instead of a parallel record type, the promoted-key fingerprint keeps main's align component under the domain tag, and the encoder covers the TypedPointer debug type from #1126. Signed-off-by: nihalp <[email protected]> * fix(mir): keep mixed-pointee reference unions valid as device-static storage #1186 tightened classify_union_constant_storage so SharedRef union alternatives with different pointee types fail closed. That is right for SSA reconstruction, which mints the carrier field's own reference type and could claim validity for a pointee the program never wrote. But the device-static initializer gate shares the classifier while emitting only exact bytes plus one integer-width relocation slot; no typed reference is ever minted, and device code reads the storage through its own field types. Release builds hid the regression because optimized MIR folds the example's union load away; any unoptimized device build (including CUDA_OXIDE_DEBUG=full) materializes the static and failed to compile device_global's documented union { word: &'static u32, byte: &'static u8 } shape. Thread a UnionConstantUse through the classifier so the SSA path keeps the pointee-identity rejection and the physical-storage gate does not, and cover the SharedRef mixed-pointee shape at both call sites. Signed-off-by: nihalp <[email protected]> --------- Signed-off-by: nihalp <[email protected]>
nihalpasham
added a commit
that referenced
this pull request
Aug 28, 2026
Reworked onto main's #1186 shared-globals cache: the debug identity (variable info plus owner function) rides SharedGlobalDeclaration next to the storage fields, physical mismatches keep main's incompatible- declaration error, and divergent debug identities on one alloc_key now fail open by dropping the attachment instead of failing full-debug builds that release accepts. The physical gate uses llvm_type_size_align (get_type_size was removed by #1186), the owner subprogram cache is keyed by the exported linkage name to compose with #1127's source/ linkage split, and typed thin pointers from #1126 are admitted through the shared debug-type gate. Signed-off-by: nihalp <[email protected]>
4 of 5 tasks
nihalpasham
added a commit
that referenced
this pull request
Aug 28, 2026
Reworked onto main's #1186 shared-globals cache: the debug identity (variable info plus owner function) rides SharedGlobalDeclaration next to the storage fields, physical mismatches keep main's incompatible- declaration error, and divergent debug identities on one alloc_key now fail open by dropping the attachment instead of failing full-debug builds that release accepts. The physical gate uses llvm_type_size_align (get_type_size was removed by #1186), the owner subprogram cache is keyed by the exported linkage name to compose with #1127's source/ linkage split, and typed thin pointers from #1126 are admitted through the shared debug-type gate. Signed-off-by: nihalp <[email protected]>
This was referenced Aug 28, 2026
nihalpasham
added a commit
that referenced
this pull request
Aug 28, 2026
Reworked onto main's #1186 shared-globals cache: the debug identity (variable info plus owner function) rides SharedGlobalDeclaration next to the storage fields, physical mismatches keep main's incompatible- declaration error, and divergent debug identities on one alloc_key now fail open by dropping the attachment instead of failing full-debug builds that release accepts. The physical gate uses llvm_type_size_align (get_type_size was removed by #1186), the owner subprogram cache is keyed by the exported linkage name to compose with #1127's source/ linkage split, and typed thin pointers from #1126 are admitted through the shared debug-type gate. Signed-off-by: nihalp <[email protected]>
This was referenced Aug 28, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #413.
Preserve which Rust pointer form every device pointer came from (
&T,&mut T,*const T,*mut T), backed by a typed fact oracle so the compiler asks rustc instead of guessing. Builds on the pointer-kind model from #1062.1The problem
The compiler forgot which Rust pointer form a value came from, and several
of the facts it did keep were guessed rather than asked.
Concrete example of where that becomes a problem (this PR's first fixed miscompile):
And the guessed facts were worse than the forgotten ones:
The fix, in three layers
no
noalias/readonly/dereferenceable. Those need a separate proofand stay off.
(attributes and result types), never the operand type history, which
breaks across value-forwarded kind-only casts:
Worked example
Bugs squashed along the way
Each of these was live before this PR; each now has a fix and, where
runtime-visible, an executing example:
wrapping_offseton*const i32emitted a byte-scaled GEP (4x short):runtime misaligned-address fault. Fixed;
ptr_offset_fromruns.wrong GEP stride, wrong enum tag offset, memcpy byte count N times too
large. Facts now ride the ops.
Relaxed, deleting fences. Now a hard error; orderings match by variantname.
SharedArray<T, N, ALIGN>: a failedNparse silently readALIGNasthe element count (undersized shared memory). Typed positional reads.
DynamicSharedArrayalignment defaulted to 16 on any read failure(silent TMA misalignment hazard). Hard errors.
wrong address; integer constants defaulted to 0. Typed allocation reads;
new
ptr_without_provenanceexample locks the path.struct ThreadIndextranslated as a bareusize. Crate-anchored now.precondition_checkwas silentlydeleted from the kernel. Anchored to core/alloc's real shims.
contains("Fn"): user traits couldresolve to wrong types; closure type names were nondeterministic across
runs. Lang-item DefIds and def-path names now.
get_type_sizefell back to 8 bytes (fed real memcpy lengths);natural_alignmentemitted unjustifiedalign 8and invalidalign 3.Sizes and alignments are exact or absent, never guessed.
Validation
compile sweep, full GPU execution sweep, bench, fmt, clippy.
ex2_approx_f16andptr_without_provenance).gemm_views --bench(1024³, avg of 5, RTX 5090), reference vs this PR:fact attributes, and malformed constants all fail loudly with messages
naming the missing fact.
.llfor representative kernels is byte-identical before and after, and the
clippy ban was verified non-vacuous (a deliberate out-of-bounds mint
fails the build, then was removed).
Notes for reviewers
2026-08-24). What changed since: the facts underneath the labels are now
typed and centralized, and minting is signature-coupled to evidence, which
is the piece whose absence motivated closing feat(mir): preserve Rust pointer and reference kind #1062.
verifier one stage earlier than on main (feat(intrinsics): add ex2 approximate f16 #1104's negative test was adapted
accordingly).
alloc_keydedup strings still use Debugformatting (never parsed back); upstream pliron issue for OperandsInfo
history across value-forwarding replacements;
noaliasemission behind areal proof.
Footnotes
Design credit: the pointer-kind model (kind on the type, Erased default, one-way transitions established only at rustc-typed boundaries) is @uurl's, proposed in the Preserve Rust reference kind and exclusivity through MIR import and lowering #413 thread and implemented in feat(mir): preserve Rust pointer and reference kind #1062, whose cornerstone commit he authored and which this PR builds directly upon. This PR would not exist without that groundwork. ↩