Repository navigation
fix(codegen): compile step_by by translating Pat types and rebuilding niched Option aggregates - #64
Conversation
…he info on Transmute.
Sibling regression for issue NVIDIA#21. step_by exercises the integer-source form of the niched-enum Transmute (Option<NonZeroUsize> -> { i8, {{i64}} }); this kernel exercises the pointer-source form (Option<&T> -> { i8, { ptr } }) via an explicit mem::transmute::<*const u32, Option<&u32>>. Currently fails at IR construction time with a pliron verifier error: Value being inserted / extracted does not match the type of the indexed aggregate v248 = llvm.insert_value v247[0], v215 : llvm.struct <{ builtin.integer i8, llvm.ptr addrspace(0) }> because the existing src_is_ptr && dst_is_struct branch in emit_pointer_cast was written for fat-pointer construction (field 0 = ptr) and assumes the destination's field 0 is pointer-typed. For a niched enum field 0 is the i8 discriminant, so the insertvalue is type-invalid. Committed before the fix so the regression is recorded; subsequent commits in this branch make the example pass.
Replaces the string-keyed `niche_start` / `niche_variant_idx` / `untagged_variant_idx` IntegerAttrs that PR NVIDIA#64 attached to MirCastOp via raw `attributes.0.insert` calls with a typed pliron attribute. * `NicheEncodingAttr { niche_start: u64, niche_variant_idx: u32, untagged_variant_idx: u32 }` declared with #[pliron_attr], registered in the dialect, and listed in `MirCastOp`'s `attributes = (...)` slot so pliron generates `get_attr_niche_encoding` / `set_attr_niche_encoding` accessors. * MirCastOp::verify rejects `niche_encoding` on any non-Transmute cast, pinning the contract in one place. * `niche_start` stored as `u64` rather than the i64 PR NVIDIA#64 used: niched scalars are at most 64 bits wide, so we lose no information and stop spuriously rejecting niches with the top bit set. This is the pliron-shaped fix for nit NVIDIA#2 in the PR review thread: no more cross-crate string contract, no "keep in sync with cast.rs" comment, one typed accessor per side.
Drops the hand-rolled `set_niche_transmute_attrs` helper and its three
private string constants (`NICHE_START_ATTR`, `NICHE_VARIANT_IDX_ATTR`,
`UNTAGGED_VARIANT_IDX_ATTR`) in favour of pliron's macro-generated
`cast_op.set_attr_niche_encoding(ctx, NicheEncodingAttr { ... })`.
Carries `niche_start` as `u64` to match the new attribute. Rejects
niches with bit patterns wider than 64 bits up front with a clear
"not supported" error instead of silently truncating to i64.
…ct->scalar Three layered fixes on top of PR NVIDIA#64's cast lowering. 1. Niche path runs first in emit_pointer_cast (was a late else-if): if the importer attached a `niche_encoding` attribute and the destination is a struct, take the niche reconstruction branch regardless of source type. This stops `Option<&T>` / `Option<NonNull<T>>` / `Option<Box<T>>` Transmutes from being miscompiled by the older `src_is_ptr && dst_is_struct` arm, which was written for fat-pointer construction and would put the source pointer into field 0 (the discriminant slot in a niched enum). 2. emit_scalar_to_niched_enum now accepts pointer-scalar sources, not just integer scalars. The discriminant comparison is built in the source's own type (icmp eq ptr %src, inttoptr i64 niche_start), which folds to `null` for the niche_start == 0 case rustc emits today. Reads the niche encoding through the new typed getter `MirCastOp::get_attr_niche_encoding`; the old string-keyed `read_niche_info` helper is gone. 3. emit_struct_to_scalar gains a size guard. The previous version did alloca + store + load with no check that the destination scalar width matched the deepest scalar inside the source aggregate; a mismatch would silently truncate or pull padding bytes. We now walk the single-field newtype chain (capped at MAX_NEWTYPE_DEPTH), compare widths, and bail loudly with a "size mismatch" diagnostic if they differ or if the aggregate is not a single-scalar wrapper. Also: replaced the magic `path.len() > 8` cap in `deep_scalar_index_path` with the named `MAX_NEWTYPE_DEPTH` const and reordered its checks so the width-equivalent shortcut runs in the same iteration as the pointer-equality check. Doc table at the top of the file updated to reflect the new dispatch order. Verified locally: * step_by example: PASS (integer-source niche, regressionn from PR NVIDIA#64). * option_ref_transmute example: PASS (pointer-source niche, the gap this commit closes). * vecadd, sharedmem, cast_tests, hashmap: PASS (smoke test).
ed0fd9a to
8909b30
Compare
nihalpasham
left a comment
There was a problem hiding this comment.
Thanks for the PR. It needed some additions, which I've layered on top of your branch
The importants ones:
-
Pointer-source niche transmutes: Your fix handled the integer-source case (
Option<NonZeroUsize>-> aggregate) but missed the pointer-source case (Option<&T>,Option<NonNull<T>>,Option<Box<T>>). I added a sibling example (option_ref_transmute) that reproduced the bug as a pliron verifier error, reordered the dispatch inemit_pointer_castso the niche reconstruction runs first whenever the importer attached a niche encoding, regardless of whether the source is an integer or a pointer. The helper now also accepts pointer sources directly (icmp eq ptr %src, inttoptr i64 niche_start). -
Typed
NicheEncodingAttrinstead of string-keyed attributes: The three looseIntegerAttrentries (niche_start,niche_variant_idx,untagged_variant_idx) glued together by a "keep in sync" string contract between importer and lowering are replaced with a proper#[pliron_attr]struct declared indialect-mir, wired ontoMirCastOpvia itsattributes = (...)slot. Both sides now use the macro-generatedget_attr_niche_encoding/set_attr_niche_encoding. You can check howcast_kinddid this before. Removed the cross-crate string contract, the hand-rolledread_niche_info/set_niche_transmute_attrshelpers, and the "keep in sync" comment. -
Size guard on struct -> scalar: The reverse direction (
emit_struct_to_scalar) was doing an unchecked alloca + store + load, which would silently truncate or pull padding bytes on any size mismatch. It now walks the single-field newtype chain, compares widths, and errors loudly with a "size mismatch" diagnostic if they differ. Same loud-failure as the scalar -> struct direction.
Also just some nits that were addressed in this PR
niche_startis now carried asu64instead ofi64, so we drop the bogus overflow rejection on niches with the top bit set.- The magic
path.len() > 8cap indeep_scalar_index_pathis now a namedMAX_NEWTYPE_DEPTH = 8constant with a comment explaining the choice. read_niche_infois a one-liner now, it just forwards to the typed getter.MirCastOp::verifyrejectsniche_encodingon non-Transmute casts, so the contract is enforced in one place.
Under -O, MIR const-folds the None arm of
`Option<&u32>::unwrap_or(&77)` into an Operand::Constant of type
`&u32`: a ConstantKind::Allocated whose data bytes are a pointer-sized
placeholder and whose provenance entry names the allocation holding the
literal 77.
The pointer-constant arm of translate_operand only followed that
provenance when the pointee was a MirStructType (arrays take a separate
path). Every other pointee fell through to the raw-pointer path, which
parses the placeholder bytes as an address and emits
MirConstantOp(0) + inttoptr, i.e. a null pointer. The subsequent
dereference became `load i32, ptr null`: an illegal memory access
(CUDA error 700) at runtime, and under opt -O2 the UB even deletes the
out[1] store outright.
Fix: after the existing struct branch, follow the provenance for ALL
remaining pointee types. Resolve the entry via GlobalAlloc
(GlobalAlloc::Memory directly, GlobalAlloc::Static via
eval_initializer), honor the byte offset that the pointer's own data
bytes encode into the target allocation, materialize the pointee
through the existing shared constant-from-bytes path
(translate_constant_value_from_bytes: integer / f16 / f32 / f64 /
enum / ZST / nested pointer), and take its address with MirRefOp
exactly like the struct branch. mem2reg/lowering turn the MirRefOp
into alloca + store + address, which is sound because promoted
constants are immutable.
The raw-pointer fallthrough now only handles constants WITHOUT
provenance (true null / int-to-ptr values). Provenance pointing at a
non-memory allocation (e.g. a function) is a hard translation error
instead of a silent null, matching the array path's existing behavior.
Evidence on the issue repro (compile-only, --arch sm_90):
before: %v14 = inttoptr i64 0 to ptr
%v15 = load i32, ptr %v14, align 4
after: %v14 = alloca i32, align 4
store i32 77, ptr %v14, align 4
%v15 = load i32, ptr %v14, align 4
and post-opt the kernel stores [5, 77] as expected.
Issue: NVIDIA#132 (const-operand half; the niche-optimized aggregate half
was issue NVIDIA#64).
Fixes #21.
for i in (a..b).step_by(s)compiles and runs after this. Verified on a real GPU: thestep_bykernel and an equivalentwhile-loop kernel produce identical sums for all 32 threads and match host-computed expected values.Issue
Two compiler gaps, exposed by
StepBy::nextafter MIR inlining:TyKind::Patwas unsupported in the importer.coreencodesNonZeroUsizeasPat<usize, 1..=usize::MAX>, so importer bailed before reaching lowering.Pat, mir-lower emittedbitcast i64 to { i8, { { i64 } } }for rustc'sTransmute usize -> Option<NonZeroUsize>. rustc treats thatOptionas a niche-optimised 8-byte scalar (0 = None, non-zero =Some(x));MirEnumTypelowers it to the un-niched aggregate. Abitcastacross the scalar/aggregate boundary is invalid LLVM and showed up asinvalid cast opcodefrom llc.Fix
mir-importer/.../types.rs: lowerRigidTy::Pat(base, _)as the base type, with an in-source note on the layout assumption.mir-importer/.../rvalue.rs: when a Transmute targets a niche-optimised enum, attach the niche encoding (niche_start,niche_variant_idx,untagged_variant_idx) as attributes on the cast op, read straight fromty.layout().mir-lower/.../cast.rs: forscalar -> structcasts, rebuild the un-niched aggregate explicitly using those attributes:icmp eq val, niche_start->selectfor the discriminant, plus a nestedinsertvaluethat lands the payload at the deepest scalar slot of the variant struct. if the importer did not classify the destination as niched, we error out rather than fall through to an invalid bitcast.dialect-llvm/.../export.rs: emitSelectOpin the LLVM IR exporter. The op was registered but unprinted, so the new lowering needed it.examples/step_by/: positive regression with thestep_bykernel and awhile-loop control.The discriminant computation is driven by the niche encoding rustc hands us, so this is not limited to
niche_value = 0: any single-niche enum that fits in a scalar (Option<NonZeroT>,Option<&T>,Option<NonNull<T>>,Option<Box<T>>,Option<bool>,Option<char>, ...) takes the same path.