Skip to content

perf(mir): scalarize bounded small-array iterator reads - #1151

Closed
uurl wants to merge 2 commits into
NVIDIA:mainfrom
uurl:perf/399-typed-array-iterator-scalarization
Closed

uurl wants to merge 2 commits into
NVIDIA:mainfrom
uurl:perf/399-typed-array-iterator-scalarization

Conversation

@uurl

@uurl uurl commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Addresses #399.

This PR handles the memory-resident
Take<Copied<slice::Iter<_>>> form. Other iterator-adapter shapes remain
tracked by #399.

This adds a typed-MIR canonicalization for the memory-resident iterator state
produced by bounded iteration over small local arrays.

The transformation recognizes the structural form emitted for cases such as:

let coefficients = [4.0_f32, -3.0, 4.0 / 3.0, -0.25];

for coefficient in coefficients
    .iter()
    .copied()
    .take(runtime_levels.min(4))
{
    consume(coefficient);
}

and replaces the final pointer-backed element load with a bounded SSA array
extraction.

The resulting mir.extract_array_element can then use the existing aggregate
scalarization/lowering path instead of preserving the source array as local
memory.

Implementation

The pass recognizes a narrow structural pattern rather than matching Rust type
names.

For a candidate memory-resident iterator, it proves that:

  • the source is a small local array within the existing scalarization bound;
  • every array element is initialized exactly once before iterator construction;
  • the array has no additional writes or visible escapes;
  • iterator initialization is dominated by the array initialization;
  • the iterator structurally contains current-pointer, end-pointer, and count
    state;
  • both current and end pointers originate from the same local array;
  • the end pointer is exactly base + N;
  • the remaining-count path is guarded and decremented by one;
  • the current pointer advances by exactly one element;
  • the final value is obtained through a non-volatile load derived from the
    current pointer.

For a successful match, the pass reconstructs the array value in SSA and derives
the element index from the iterator count:

index = initial_count - current_count

The index is bounded before emitting mir.extract_array_element.

Unsupported or ambiguous shapes are left unchanged.

Scope

This intentionally does not attempt to recognize arbitrary Rust iterators.

It targets the memory-resident pointer-walk form generated for bounded
Take<Copied<slice::Iter<_>>>-like iteration over small local arrays.

The implementation does not add:

  • textual LLVM rewriting;
  • loop unrolling;
  • an additional LLVM optimization stage;
  • environment-variable-controlled optimization behavior.

Tests

Added transform coverage for:

  • successful scalarization of the memory-resident small-array iterator form;
  • rejection of a non-unit pointer step;
  • rejection of an end pointer that does not match the exact array bound;
  • rejection when the source array has an additional read;
  • rejection when the source array address escapes;
  • rejection when the iterator-state address escapes.

Regression suites:

mir-transforms:
  31 passed

mir-lower:
  270 unit tests passed
  127 lowering tests passed

cuda-oxide-codegen:
  176 unit tests passed
  18 compile-to-PTX tests passed
  additional PTX/linking/concurrency integration suites passed

cargo clippy -- -D warnings and git diff --check also pass.

End-to-end result

For the Rust reproducer, the preparation pipeline reports:

small-array pointer-walk scalarization: rewrote 1 loop(s)

The local-memory diagnostic for coefficients disappears.

The resulting target kernel contains no:

.local
ld.local
st.local

The optimized PTX keeps the operation register-resident and reduces the bounded
iteration to runtime selection over the four scalar values.

Runtime correctness

Validated on a real CUDA device for runtime levels 0..=4:

issue_399_iter_take: PASS
array_for_loop: PASS

Performance

CUDA-event timings were collected with a runtime runtime_levels parameter,
20 warmup launches, and 51 timed launches per level.

Median-of-five process runs:

runtime_levels main this PR improvement
1 0.030784 ms 0.028480 ms 7.5%
2 0.037056 ms 0.028480 ms 23.1%
3 0.044832 ms 0.028512 ms 36.4%
4 0.051712 ms 0.026336 ms 49.1%

A final post-cleanup smoke run remained in the same range.

This is also materially different from the earlier textual-LLVM approach, which
removed local memory but regressed runtime performance.

Result

The change eliminates stack-backed iterator access for this bounded local-array
case while keeping the transformation in typed MIR and reusing the existing
bounded aggregate scalarization path.

@uurl
uurl force-pushed the perf/399-typed-array-iterator-scalarization branch from abd7169 to 06ecacb Compare August 23, 2026 05:36
@nihalpasham nihalpasham added declined PR intentionally not merged (closed without merging) perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) miscompile Produces incorrect PTX/IR (wrong generated code) safety Memory safety, soundness, or undefined behavior labels Aug 24, 2026
@nihalpasham

nihalpasham commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closing this PR because the optimization is not semantics-preserving.

  • For *u8 -> *[u8; 2] -> offset(1) -> *u8, pointer arithmetic advances two bytes. Stripping the cast makes the matcher treat that as one source-array element, changing reads at byte offsets 0, 2, 4, 6 into 0, 1, 2, 3.
  • Its escape analysis stops at pointer-valued iterator-field loads. Backing initialization can then be removed while an escaped pointer still observes that storage.
  • This is an always-on compiler transform, so either valid counterexample blocks the approach.

A replacement needs exact layout semantics and adversarial escape controls, consistent with the root-cause and full-path requirements in the Discord announcement.

@uurl
uurl deleted the perf/399-typed-array-iterator-scalarization branch August 31, 2026 14:09
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) declined PR intentionally not merged (closed without merging) miscompile Produces incorrect PTX/IR (wrong generated code) perf Performance of generated code or of the compiler itself safety Memory safety, soundness, or undefined behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants