Skip to content

Scalarize small local arrays used by iterator adapters - #636

Closed
uurl wants to merge 1 commit into
NVIDIA:mainfrom
uurl:fix/399-small-array-iterator-scalarization
Closed

uurl wants to merge 1 commit into
NVIDIA:mainfrom
uurl:fix/399-small-array-iterator-scalarization

Conversation

@uurl

@uurl uurl commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part of #399.

This PR adds an opt-in optimization path for small compiler-owned local arrays consumed through Rust iterator adapters.

When enabled with:

CUDA_OXIDE_MIR_OPTS=small-array-iterators

the compiler:

  1. Detects bounded iterator loops derived from small fixed-size local arrays.
  2. Annotates those loops with a compiler-proven maximum iteration count.
  3. Fully unrolls bounded loops while preserving multiple ordinary exit edges.
  4. Scalarizes immutable local-array loads after LLVM inlining.
  5. Runs a final LLVM cleanup pipeline so the arrays can be promoted and eliminated.

This removes the .local, ld.local, and st.local PTX operations previously emitted for iterator chains such as:

  • iter().copied().take(...)
  • iter().copied().skip(...).take(...).enumerate()

Motivation

Rust slice iterators are lowered through helper functions such as Iter::next and Iter::nth. Before inlining, the local array and its dynamic accesses are distributed across several functions, so the ordinary MIR-to-LLVM lowering cannot reliably scalarize them.

After LLVM inlining, the accesses become visible as dynamic GEP/load operations rooted in a small immutable stack array. This PR adds a conservative post-inline scalarization step for that shape.

Implementation

MIR iterator analysis

mir-importer now:

  • recognizes compiler-owned fixed arrays with at most 16 elements;
  • propagates iterator-state and control-state provenance;
  • identifies natural loops whose exit conditions derive from the iterator state;
  • emits bounded-unroll hints only when the array does not escape or become invalidated;
  • retains a narrow structural fallback for public-MIR shapes where rustc has distributed the exit predicate across projections and merged temporaries.

The optimization remains disabled unless explicitly requested through CUDA_OXIDE_MIR_OPTS.

Bounded loop unrolling

The bounded unroller now supports loops with:

  • multiple edges to a shared exit;
  • multiple distinct ordinary exit targets.

Each ordinary exit is preserved in every cloned iteration. The impossible backedge of the final guard copy is replaced with mir.unreachable.

Post-inline array scalarization

cuda-oxide-codegen performs the following opt-in sequence:

internalize,default<O2>
small local-array scalarization
default<O2>
llc

The scalarizer is deliberately conservative. It only rewrites arrays that are:

  • fixed-size;
  • no larger than 16 elements or 128 bytes;
  • composed of supported scalar element types;
  • completely initialized with immutable constants;
  • free of dynamic, repeated, volatile, or atomic stores.

Pointer provenance is followed through GEPs, casts, freezes, selects, and phi nodes.

The LLVM 22 GEP modifiers nuw, nusw, and nsw are accepted when parsing byte-offset GEPs.

Dynamic loads are replaced with select chains over the known constant element values. The subsequent LLVM optimization pass eliminates the original array allocation and stores.

Validation

The focused scalarization tests cover:

  • dynamically indexed scalar stores;
  • byte-offset GEPs produced by slice iterators;
  • LLVM 22 getelementptr inbounds nuw syntax;
  • constant aggregate stores;
  • select and phi pointer provenance;
  • partial initialization rejection;
  • oversized-array rejection.
  • volatile and atomic store rejection;
  • atomicrmw and cmpxchg rejection;
  • pointer-escape rejection through calls and stores;
  • benign LLVM lifetime intrinsic handling;
  • a negative regression case where an iterator is used before an unrelated loop.

Validation completed successfully:

14 scalarization tests passed
151 cuda-oxide-codegen tests passed
893 mir-importer tests passed
cargo clippy --all-targets -- -D warnings passed
array_iterator_adapters: PASS
small-array scalarization: replaced 3 dynamic load(s)
array_iterator_adapters PTX shape: PASS

The final PTX for both regression kernels contains no prohibited:

.local
ld.local
st.local

Scope

This is an experimental, opt-in optimization. The default compilation pipeline remains unchanged when small-array-iterators is not enabled.

@uurl
uurl force-pushed the fix/399-small-array-iterator-scalarization branch from ed9d81f to d8f52e5 Compare August 2, 2026 03:56
@uurl
uurl force-pushed the fix/399-small-array-iterator-scalarization branch from d8f52e5 to 345d912 Compare August 2, 2026 04:13
@nihalpasham nihalpasham added perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves labels Aug 3, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR.

I'm putting this on hold, same as #398. In short, the mechanism can't land in this form, and before any reshape I'd like to to see the benefit measured.

What this PR is about:

Direct indexing is already handled by default since #397/#398:

let c = coeffs[i];                     // i runtime
// today: c = select(i==0, 4.0, select(i==1, -3.0, ...))  -> no .local

The iterator form escapes that pass because the access reaches us in a different shape:

for v in coeffs.iter().copied().take(k) { ... }
// reaches the scalarizer as a pointer walk, not arr[i]:
//   p = p + 4;  v = *p;  p != end
// so the landed pass doesn't match, the array stays in memory,
// and PTX keeps a per-thread .local slot

What we'd need before we go further:

  • The PR shows the .local ops disappear from two example kernels. That's good but its just a code-gen change, not a benefit.
  • What we'd need to look at are some performance measurements in the PR: like which workload, what's the before/after timing.
  • A reference for a diff this size (~5,400 lines): feat(unroll): loop-unrolling pass with opt-independent constant folding #284 landed with gemm_sol measured at 208.9 → 308 TFLOPS.
  • What would be ideal is an actual real-world kernel (example) where this moves a measured number.

Findings from building and running this branch (pinned toolchain, RTX 5090):

  • The MIR stages never fire: zero mir.bounded_unroll_hint ops planted, including for the PR's own example. The textual scalarizer does all the work.
  • The textual layer is the part that can't come upstream. The direction we settled on in fix(mir): keep small runtime-indexed arrays in SSA #398 was that opt-in passes like this one should be written as pliron passes and plugged into the pass manager, so they operate on the compiler's own IR with types, SSA, and the verifier behind them. This PR instead re-parses the text that opt prints, rewrites it as strings, and feeds it back in. That couples us to the exact printing of one LLVM version (it already needs special handling for LLVM 22's nuw/nusw/nsw GEP flags), and the failure mode is bad: when a future opt prints something slightly differently, the pass doesn't error, it just quietly stops matching, or worse, mis-reads what it matched.
  • Two soundness corners:
    • the bound proof shows the exit derives from iterator state, not that the iterator advances every iteration; a loop calling next() every second pass exceeds the bound and executes the synthesized unreachable;
    • the phi provenance merge skips untracked incomings, so phi [&arr[0]], [&arr[1]], [external] still gets rewritten to constants. I'll share a small failing test for this.

What I'd recommend instead, if the measurement pans out:

  • Teach the existing mir-lower scalarizer to follow pointer walks rooted at small compiler-owned arrays and emit the same select chains it already emits for arr[i]. That way the iterator case becomes an extension of the pass that already does this rewrite, and it inherits everything that pass already enforces: the size caps, the compiler-owned-locals restriction, and the escape checks. No unrolling, no extra opt stage, no env plumbing.
  • Independently worth exploring: place fully-constant arrays in .const space, so any remaining dynamic loads leave .local regardless.

Your fail-closed analysis rules (escape/volatile/atomic rejection, full-initialization requirement) are good and would carry straight over.

@nihalpasham nihalpasham added the optional-opts Opt-in optimization passes for the oxide-owned opt registry (off by default) label Aug 3, 2026
@uurl

uurl commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. I measured the current prototype on an RTX 5060 Laptop GPU using a pointwise polynomial workload over small compiler-owned local arrays.

The comparison used the PR's original base commit (868f8ec4) against the PR commit (345d912d). The same benchmark source was compiled in separate worktrees, and both PTX modules were loaded into the same host process. Kernel timing used CUDA events, with the execution order rotated between variants.

The MIR detector emitted zero bounded-unroll hints, matching your observation. The textual scalarizer performed the transformation and reported six replaced dynamic loads.

A first matrix covering 1M, 4M, and 8M elements, traversal lengths of 4 and 8, and three independent runs showed the prototype consistently slower, with median relative performance of 0.8774x.

I then repeated the measurement with a heavier workload:

  • 8,388,608 elements;
  • traversal lengths 4 and 8;
  • 128 evaluation rounds per thread;
  • 20 warm-up launches;
  • 20 batches of 5 measured launches;
  • 5 independent runs.

Results:

  • length 4: 22.429 ms baseline vs 26.093 ms prototype;
  • length 8: 41.617 ms baseline vs 49.460 ms prototype;
  • aggregate median relative performance: 0.8530x;
  • observed range: 0.8402x to 0.8641x.

This corresponds to approximately 16–19% longer execution time for the prototype.

Native sm_120 assembly confirmed that the baseline cubin contains local-memory LDL/STL instructions and that the prototype removes them. Both iterator kernels use 18 registers, with no reported stack frame or spills. Therefore, removing the local-memory operations through the current textual scalarization mechanism did not produce a performance benefit and instead caused a reproducible regression for this workload.

Given the measurement and the architectural concerns you identified, I will not continue developing the textual scalarizer, bounded-unroll path, or environment-option plumbing in this PR. I will preserve the branch and benchmark artifacts as an experimental result.

I may revisit issue #399 only if I find a real workload that demonstrates a material benefit and can justify a new typed implementation in mir-lower.

I will leave the PR open for now in case you would like to keep the discussion and measurements as a reference. Please feel free to close it if you consider the experiment concluded.

@nihalpasham

Copy link
Copy Markdown
Collaborator

Closing as concluded, per the measurements included:

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) on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves optional-opts Opt-in optimization passes for the oxide-owned opt registry (off by default) 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