Skip to content

perf(mir-lower): keep an over-aligned aggregate's alignment on its field loads - #746

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
vyncint:perf/field-load-alignment
Aug 10, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
vyncint:perf/field-load-alignment

Conversation

@vyncint

@vyncint vyncint commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Partially addresses #745: this fixes the named-field spelling (c.x + c.y). The array-newtype lane spelling (c.0[0] + c.0[1]) still splits, because array-element addresses do not stamp their proved alignment yet; that is a follow-up.

A load takes its alignment from its own result type, and mir_type_abi_align
records one only for aggregates — a scalar answers None. So p.x on an
#[repr(C, align(8))] struct exported with LLVM's default align 4, and the
guarantee rustc gave the aggregate was dropped at the projection.
LoadStoreVectorizer will not widen past an alignment it cannot prove, so two
adjacent field reads stayed two loads.

The same struct copied whole already vectorized, because there the load's
result type is the aggregate. The cost depended on how the read was spelled
rather than on the data.

The arithmetic

The aggregate is aligned to abi_align, so its field at byte offset is aligned
to gcd(abi_align, offset), and to abi_align itself at offset zero. Both
numbers are rustc's own layout, so this claims nothing the source did not already
guarantee. Every uncertain case — no recorded abi_align, no recorded offset —
declines and leaves the previous, weaker-but-sound behaviour.

Where it had to go

convert_load cannot recompute this: by the time it runs, mir.field_addr is
already a GEP and the MIR aggregate type is no longer reachable from the load's
operands. (I verified that by forcing a distinctive alignment through each step —
the GEP matches and its indices destructure, but
operands_info.lookup_most_recent_of_type returns None for the GEP's base,
which is not an operand of the load.)

So convert_field_addr, which still holds the aggregate, stamps what the address
proves onto the GEP, and the load reads it back. The attribute is
lowering-internal and never exported — it deliberately uses a key distinct
from the one the exporter prints as align N, so a future emit_gep cannot
mistake it for the GEP's own access alignment.

PTX

A (f32, f32) element read field-wise:

element before after
repr(C) — align 4 2 ld.global.b32 2 ld.global.b32
repr(C, align(8)) 2 ld.global.b32 1 ld.global.v2.b32

The align-4 element is the control and must not change: nothing proves
8-byte alignment there, and widening it would be wrong.

Measured

A10G (sm_86, driver 595.71.05), 4194304 threads, 30 timed launches after 5
warmup, every kernel bit-correct against a host reference. Same example built by
both compilers, nothing else changed:

kernel stock main this branch speedup
packed_pair (streaming) 104.8 us 104.6 us 1.00x
aligned_pair (streaming) 104.8 us 104.8 us 1.00x
hot_packed (control) 1254.0 us 1253.7 us 1.00x
hot_aligned 1253.9 us 628.8 us 1.99x

Evidence: stock .gpu-evidence/20260809T010634Z.log, this branch
20260809T005928Z.log.

Streaming does not move, and should not. At ~480 GB/s it is bandwidth-bound,
and two loads from consecutive addresses already coalesce into the same
transactions — halving the instruction count buys nothing there, and it would be
wrong to claim otherwise. The win is where load count is the limit rather than
bandwidth: a 4096-entry table with 64 dependent lookups per thread, which is the
lookup-table shape #684 and #694 already optimised. There it tracks the 2:1 load
ratio almost exactly.

hot_packed holds at ~1254 us across both builds, so this is a controlled
comparison rather than two unrelated timings — and it is the same control that
shows the change does not over-claim alignment.

Gates

  • Full smoketest on the A10G: 192 / 192 pass, 0 fail, 722s
    (.gpu-evidence/20260809T012219Z.log). A codegen change touches every field
    load in the corpus, so this is the full sweep rather than a scoped one.
  • Locally: cargo fmt --check (root, codegen workspace, and the new example),
    clippy --all-targets --lib --tests -D warnings, and the unit-test set
    including -p mir-lower and -p mir-importer (11 suites).

Note on a neighbour

#716 also adds an attribute key to crates/llvm-export/src/lib.rs
(GLOBAL_RETAINED_KEY). It is an independent change in the same region — whichever
lands first, the other rebases trivially. Flagging it so it is not a surprise at
merge time.

vyncint and others added 2 commits August 9, 2026 08:22
…eld loads

A load takes its alignment from its own result type, and `mir_type_abi_align`
records one only for aggregates -- a scalar answers `None`. So `p.x` on an
`#[repr(C, align(8))]` struct exported with LLVM's default `align 4` and the
guarantee rustc gave the aggregate was dropped at the projection.
LoadStoreVectorizer will not widen past an alignment it cannot prove, so two
adjacent field reads stayed two loads. The same struct copied whole already
vectorized, because there the load's result type *is* the aggregate: the cost
depended on how the read was spelled rather than on the data.

The aggregate is aligned to `abi_align`, so its field at byte `offset` is
aligned to `gcd(abi_align, offset)`, and to `abi_align` itself at offset zero.
Both numbers are rustc's own layout, so nothing is claimed the source did not
already guarantee.

`convert_load` cannot recompute that: by the time it runs, `mir.field_addr` is
already a GEP and the MIR aggregate type is no longer reachable from the load's
operands. So `convert_field_addr`, which still holds the aggregate, stamps what
the address proves onto the GEP, and the load reads it back. The attribute is
lowering-internal and never exported -- it uses a key distinct from the one the
exporter prints as `align N`, so a future `emit_gep` cannot mistake it for the
access alignment of the GEP itself.

PTX, on a `(f32, f32)` element read field-wise:

    element                        before                after
    repr(C)          align 4       2 ld.global.b32       2 ld.global.b32
    repr(C, align(8))              2 ld.global.b32       1 ld.global.v2.b32

The align-4 element is the control and must not change: nothing proves 8-byte
alignment there, and widening it would be wrong.

Measured on an A10G (sm_86, driver 595.71.05), 4194304 threads, 30 timed
launches after 5 warmup, every kernel bit-correct against a host reference:

    kernel                           stock      this   speedup
    packed_pair    (streaming)       104.8     104.6      1.00x
    aligned_pair   (streaming)       104.8     104.8      1.00x
    hot_packed     (control)        1254.0    1253.7      1.00x
    hot_aligned                     1253.9     628.8      1.99x

Streaming access does not move, and should not: at ~480 GB/s it is
bandwidth-bound, and two loads from consecutive addresses already coalesce into
the same transactions. The win is where load count is the limit rather than
bandwidth -- a 4096-entry table with 64 dependent lookups per thread -- and
there it tracks the 2:1 load ratio. `hot_packed` holds at 1254us across both
builds, so the comparison is controlled rather than two unrelated timings.

Closes NVIDIA#745

Signed-off-by: Vyncint Ng <[email protected]>
- Decline the stamp for a non-power-of-two abi_align: dialect-mir only
  verifier-enforces power-of-two alignment for unions and enums, and a
  malformed struct/tuple layout would otherwise export an `align N`
  that llc rejects.
- Document the accepted fidelity limit where a `&raw`-escaped field
  projection inherits the aggregate's alignment after mem2reg, and why
  full fidelity would need the stamp during MIR translation instead.
- Unit-test the stamp end to end through lower_mir_to_llvm: aggregate
  alignment at offset zero, gcd narrowing at a nonzero offset, natural
  alignment unchanged, and the non-power-of-two decline.
- Assert the PTX shape in the example via verify-code-shape.sh (run by
  smoketest): the align(8) kernels must fuse to ld.global.v2.b32 and
  the align-4 controls must not, so the perf property holds without a
  GPU. Fix the example's copied authors field and build comment.
@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) codegen Device code-generation pipeline (Rust MIR to IR to PTX) llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate) labels Aug 10, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Really nice work.

GPU-verified on an RTX 5090:

  • 1.96x on the hot lookup kernel (you measured 1.99x on A10G),
  • the PTX fusion with the align-4 control unchanged, and
  • a full 192/192 smoketest sweep on this branch.

I pushed a hardening commit:

  • a power-of-two guard on the stamp, the &raw fidelity corner documented,
  • four mir-lower unit tests, and a verify-code-shape.sh so the fusion is CI-checked without a GPU.

One scope note: issue #745 shows two ways of writing the same slow read. This PR fixes the first one, reading named fields (c.x + c.y). The second one wraps the values in an array (c.0[0] + c.0[1]), and indexing into an array goes through a different address-computation path that doesn't yet record the alignment, so those reads still come out as two narrow loads instead of one wide one. That makes this a partial fix for #745; doing the same trick for array elements in a follow-up would finish it.

@nihalpasham
nihalpasham merged commit a362ecc into NVIDIA:main Aug 10, 2026
36 checks passed
nihalpasham added a commit that referenced this pull request Aug 10, 2026
…ess (#777)

* perf(mir-lower): carry proved alignment through an array-element address

#746 taught a *field* address to record what it proves, so `c.x + c.y` on an
`#[repr(C, align(8))]` element fuses into one `ld.global.v2.b32`. An element
address recorded nothing, so the same two f32 reached through an array index
still exported two `align 4` loads and LoadStoreVectorizer refused to fuse them.

The failing shape is narrower than it first looks, which is worth stating because
it decides what the example has to cover. Copying the element into a local first
already fused -- SROA then loads the whole aggregate and the alignment comes from
its type. Only reading *through* the place keeps the access on the address path:

    let c = pts[i]; c.0[0] + c.0[1]      // already one wide load
    pts[i].0[0] + pts[i].0[1]            // two narrow loads
    let l = &pts[i].0; l[0] + l[1]       // two narrow loads

So the cost depended on whether the source copied the element or read through it,
which is not a distinction the programmer should have to know about.

Two facts combine at an element address. Whatever the base pointer already proved
is stronger than the array type alone when the array is a field of an
over-aligned aggregate -- `&table[i].lanes` carries the outer struct's alignment,
which `[f32; 2]` does not know. Element `i` then sits at byte `i * stride`, so it
proves `gcd(base, i * stride)`, and `base` itself at index zero. A runtime index
can land anywhere, so it claims only `gcd(base, stride)`, which every element
satisfies. All of it comes from rustc's layout; nothing is claimed that the
source did not already guarantee, and every uncertain case declines.

PTX, two adjacent f32 lanes of an `#[repr(C, align(8))]` element:

    kernel               before                 after
    lanes_through_ref    2 ld.global.b32        1 ld.global.v2.b32
    hot_lanes            4 ld.global.b32        2 ld.global.v2.b32
    packed_pair          2 ld.global.b32        2 ld.global.b32     (align-4 control)
    hot_packed           4 ld.global.b32        4 ld.global.b32     (align-4 control)

Measured on an A10G (sm_86, driver 595.71.05), 4194304 threads, 30 timed launches
after 5 warmup, every kernel bit-correct against a host reference:

    kernel               stock      this   speedup
    packed_pair          105.0     104.6     1.00x
    aligned_pair         104.9     104.8     1.00x
    lanes_through_ref    104.9     105.0     1.00x
    hot_packed          1253.5    1253.5     1.00x
    hot_aligned          628.6     633.0     1.00x
    hot_lanes           1253.6     629.5     1.99x

As with #746, streaming access does not move and should not: at ~480 GB/s it is
bandwidth-bound, and two loads from consecutive addresses already coalesce into
the same transactions. The win is where load count is the limit -- a 4096-entry
table with 64 dependent lookups per thread. `hot_packed` is identical to the
byte across both builds, so the comparison is controlled, and it is also the
guard that this claims no alignment an align-4 base never had.

Refs #745

Signed-off-by: Vyncint Ng <[email protected]>

* fix(mir-lower): take element stride from rustc layout, fail closed

The element-address alignment claim multiplied the index by
get_type_size(element_ty), an LLVM-level approximation that answers a
guessed 8 for the MIR dialect element types it does not model:
MirStructType, MirTupleType, MirEnumType, nested MirArrayType, and
also MirFP16Type, the importer's f16 scalar. For [[f32; 3]; 4] under
an align-8 base the real stride is 12, so a runtime element address is
only 4-aligned, but the guess claimed 8; the inner index-0 address
inherits that stamp, the scalar f32 load exports align 8, and
LoadStoreVectorizer then legally fuses two lanes into a v2.b32 that
faults at runtime for odd indexes. An [f16; N] array had the same
over-claim (guessed stride 8, real 2).

Strides now come from mir_element_stride: exact scalar sizes
(including MirFP16Type at 2 bytes), generic-pointer 8, rustc's stored
total_size (padding included) for MIR aggregates via mir_stored_size,
arrays multiplied out with checked_mul on both the aggregate and
scalar recursion paths, and None for anything else so the claim
declines instead of guessing. mir_stored_size learns the MirTupleType
arm it was missing (tuples record total_size like structs do), which
also sharpens the struct-slot-map field advance that already
preferred it.

constant_index_value additionally fails closed on constants wider
than 64 bits, matching integer_constant_u64 in the extract-element
fast path: APInt::to_u64 truncates, and a truncated index would feed
the gcd a wrong byte offset.

The five new lowering tests each fail on the previous stride sourcing
and pass now: nested [f32; 3] elements claim gcd(8, 12) = 4 for
runtime and index-1 addresses (the miscompile chain above), constant
index 2 proves the full 8 again from the exact byte offset, tuple
strides come from recorded layout, f16 elements claim their exact
stride of 2, and an element with no recorded size claims nothing.

---------

Signed-off-by: Vyncint Ng <[email protected]>
Co-authored-by: nik <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) llvm-export Textual LLVM/NVVM IR exporter (llvm-export crate) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants