Skip to content

feat(mir-transforms): recognize eq-wrapped range-for unroll guards - #559

Closed
Ayush7614 wants to merge 3 commits into
NVIDIA:mainfrom
Ayush7614:feat/557-unroll-range-for
Closed

Ayush7614 wants to merge 3 commits into
NVIDIA:mainfrom
Ayush7614:feat/557-unroll-range-for

Conversation

@Ayush7614

Copy link
Copy Markdown
Contributor

Summary

  • Extend induction guard matching to peel MirEq/MirNe wrapping </<=/>/>= vs a bool constant (post-switchInt range-for shape).
  • Unit tests: induction recovers trip count; full #[unroll] removes the loop.
  • Update #[unroll] docs in mir-transforms / cuda-device / cuda-macros.
  • Out of scope: step_by, inclusive ranges, custom iterators, Option-discriminant-only headers without a recoverable relational cmp.

Closes #557

Test plan

  • cargo test -p mir-transforms analyzes_range_for_eq_wrapped_guard
  • cargo test -p mir-transforms full_unroll_range_for_eq_wrapped_removes_the_loop
  • cargo test -p mir-transforms (full suite, 30 passed)

Ayush7614 and others added 3 commits July 28, 2026 20:06
Teach induction to see through MirEq/MirNe of a relational comparison
against a boolean constant—the common post-import shape of
`for i in 0..N` after switchInt lowering—so #[unroll] can fully unroll
those loops. Add fixtures and update attribute docs.

Closes NVIDIA#557

Signed-off-by: Ayush7614 <[email protected]>
The eq-wrapped guard matcher this PR added is correct, but nothing in
the pipeline produces that shape for range loops: rustc desugars
'for i in lo..hi' through Iterator::next into an Option discriminant
test in a separate merge block, the importer emits bool switches as
direct/not conditions, and the counter is fed back unchanged on the
None arm. Verified by building the new range kernels with only the
matcher in place: all four still warned 'no recognized induction
variable' / 'early break or multiple exits' and stayed rolled.

Fix at the layer issue NVIDIA#557's scope names first: the #[kernel]/#[device]
macro already owns the loop AST (LoopUnrollAttrVisitor), so an annotated
'for pat in lo..hi' over an exclusive range is desugared into the
counted while form the pass recognizes. Bounds evaluate once in order,
the binding is a fresh copy per iteration, labels move to the while,
and the increment precedes the body so continue still advances the
counter. Inclusive ranges, step_by, and arbitrary iterators keep the
marker-in-body path and its warning.

The matcher stays as defense in depth for guards that genuinely arrive
eq-wrapped (hand-written '(i < n) == true', foreign producers); its
fixture is renamed eq_wrapped_guard_loop and its comments and the three
doc claims now describe the real mechanism instead of a fictional
post-import range-for shape.

Validation on hardware (RTX 5090): unroll_smoke's four new range
kernels (full_range, partial_range, full_range_continue,
full_range_break) produce correct sums; full_range* emit zero backedges
in the .ll, matching full_unroll's structure, and partial_range matches
partial_unroll (main + remainder). The only remaining warnings are the
two deliberately-rejected fixtures. 95 cuda-macros tests (4 new
desugar pins) and all mir-transforms suites pass.

Closes NVIDIA#557
- The loop's remaining attributes now ride the wrapper block instead of
  the generated while, so #[cfg(off)] strips the bound evaluations too
  (previously they still executed, and their lets drew unused warnings).
- The user pattern binds a per-iteration item temp instead of the live
  counter, restoring 'for ref i in ...' (previously E0506 against an
  internal name) while keeping the increment ahead of the body.
- The generated locals use Span::mixed_site() hygiene, so user variables
  spelled __cuda_oxide_unroll_* can neither shadow nor be captured by
  the desugar's bookkeeping.
- A duplicate #[unroll] attribute on one loop is now a clear macro error
  (it previously either hit an opaque rustc error on while loops or
  silently planted two hints on desugared for loops).
- New pins: parenthesized-range desugar, cfg-on-wrapper ordering,
  duplicate-attr rejection, and a mir-transforms fixture for the
  eq-wrapped FALSE guard with the body on the false edge (the flip
  path of the truth table had no coverage).

Re-verified on hardware: unroll_smoke PASS, full_range* kernels at zero
backedges, partial_range at the designed two.
@nihalpasham

Copy link
Copy Markdown
Collaborator

A couple of things: before we talk about the implementation, I want to step back to motivation.

  • Do you have a real use case where unrolling an iterator-based for-loop bought you a measurable perf win? If yes, could you elaborate? In general, all such hot loops (register-resident accumulators, staged GEMM k-loops, and the like) are written on the standard while path: an induction variable, a test, an increment. That shape is fully supported today.

For background on why this PR doesn't get us there: rustc desugars for i in 0..N through Iterator::next into an Option discriminant test, so the eq-wrapped guard this PR matches never actually occurs for range loops in our pipeline. #[unroll] for i in 0..8 still warns and stays rolled with this change applied. So the real question is whether range-for support is worth building at all, and there are only three ways to do it:

  • Rewrite #[unroll] for i in lo..hi: into the counted while form inside the kernel macro at expansion time. Scoped, but the frontend starts owning loop semantics for user code, and we don't know that it can ever be made sound and complete.
  • A dialect-mir canonicalization pass: that recognizes the imported iterator shape and collapses it back into a counted loop. This is the principled, sound and complete solution, but it needs a full pass implemented and reviewed carefully.
  • Document the limitation:

Right now we're going with option 3. Rust's for loops aren't simple counted loops, they're iterators, and treating them as anything else honestly requires option 2's machinery. The one narrow case where a rewrite is even conceivable is literal integer ranges like 0..8, and if your loop is that simple, you're better off writing the while loop: it's the same number of lines and it unrolls today.

@nihalpasham nihalpasham added on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves enhancement New feature or request codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Jul 29, 2026
@Ayush7614

Copy link
Copy Markdown
Contributor Author

Thanks @nihalpasham — you’re right that the original eq-wrapped shape wasn’t what range-for produces in-pipeline; that was a mistaken assumption on my side.

I don’t have a measured GPU perf win for iterator-for vs while; the goal was ergonomics / matching the advertised #[unroll] story.

Happy to close this and leave docs-only for now, or keep your macro desugar commits if the project wants that path. Prefer your call.

@nihalpasham

nihalpasham commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for confirming, closing this one. We'll stay docs-only for now;

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) enhancement New feature or request on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recognize range-based for loops in #[unroll] (start with 0..const)

2 participants