Skip to content

fix(cuda-oxide): unroll libdevice loops like clang - #1732

Merged
nihalpasham merged 4 commits into
NVIDIA:mainfrom
praveenperera:fix/libdevice-unroll-1705
Nov 9, 2026
Merged

nihalpasham merged 4 commits into
NVIDIA:mainfrom
praveenperera:fix/libdevice-unroll-1705

Conversation

@praveenperera

@praveenperera praveenperera commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What This PR Does

Passes -mcpu=<target_sm> and the libdevice precision reflect flags (__CUDA_PREC_SQRT=1, __CUDA_PREC_DIV=1) to opt in cuda-oxide-codegen so NVVMReflectPass folds __nvvm_reflect branches before LLVM's loop unroller and inliner run:

  1. Subtarget & Reflect Flags on opt (crates/cuda-oxide-codegen/src/ptx.rs)
  2. Counted erff Loop & sqrt.rn Regressions (examples/libm_math)

1. Folding __nvvm_reflect During opt -O2

LLVM's NVPTXTargetMachine::registerPassBuilderCallbacks registers NVVMReflectPass in opt only when -mcpu=<sm> is provided. Previously, opt ran without -mcpu, so every inlined libdevice body (__nv_erff, __nv_expf, __nv_sqrtf) kept both its FTZ and non-FTZ branches until llc ran, making the loop body look roughly twice its real size to opt's loop unroller:

BEFORE (`opt -passes=internalize,default<O2>` without `-mcpu`):
  1. `__nv_erff` inlined into `for e in 0..4 { r[e] = gelu(x[e]); }`
  2. Both `__CUDA_FTZ` arms survive in `opt` -> loop body exceeds unroll threshold
  3. `r: [f32; 4]` spills to a 16-byte `.local` stack frame

AFTER (`opt -passes=internalize,default<O2> -mcpu=<target_sm> --nvvm-reflect-add=__CUDA_PREC_SQRT=1 ...`):
  1. `NVVMReflectPass` folds `__CUDA_FTZ` and `__CUDA_PREC_SQRT` at the start of `opt`
  2. `erf_fill_loop` unrolls cleanly with `0 B` `.local` stack frame (`opt` stays at `-O2`)
  3. `f32::sqrt` / `f64::sqrt` fold to `sqrt.rn.f32` / `sqrt.rn.f64`

Verification

  • GPU Execution (RTX 5090, sm_120a): cargo oxide run libm_math and verify-code-shape.sh pass (0 B .local stack frame, sqrt.rn.f32 / sqrt.rn.f64 verified).
  • Tests & CI Gates:
    • cargo test -p cuda-oxide-codegen --all-targets: PASS
    • cargo clippy -p cuda-oxide-codegen --all-targets -- -D warnings: PASS

Closes #1705

@copy-pr-bot

copy-pr-bot Bot commented Nov 4, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@praveenperera
praveenperera force-pushed the fix/libdevice-unroll-1705 branch from 4c72f79 to 156c3a7 Compare November 4, 2026 05:39
Small counted loops whose bodies call libdevice math (erff, expf) stayed
rolled, so the arrays they fill by the loop counter went to .local:
32 B for a 4-step erff fill, 96-128 B in bias+GELU and layernorm
kernels. nvcc and clang -O3 unroll the same loops.

Two pipeline differences caused it. opt ran without -mcpu, and LLVM's
NVPTX target only adds NVVMReflectPass to opt's pipeline when it has a
CPU, so every inlined libdevice body kept both __CUDA_FTZ arms and
looked twice its size to the unroller. And opt ran default<O2>, whose
full-unroll threshold is half of O3's, although rustc builds device
code at opt-level=3.

Pass -mcpu to opt on both optimization routes and run O3, which
matches clang -O3 on these kernels. With -mcpu, opt folds reflect
itself, so it also gets the __CUDA_PREC_SQRT/__CUDA_PREC_DIV values
llc uses; without them sqrt would fold to sqrt.approx.f32.
Optimization::O2 becomes O3.

Fixes NVIDIA#1705

Signed-off-by: Praveen Perera <[email protected]>
Add erf_fill_loop and erf_pair_loop: counted loops calling libm::erff
that fill per-thread arrays by the loop counter, with no #[unroll].
verify-code-shape.sh asserts both use no local memory, and that
f32::sqrt and f64::sqrt, which reach libdevice's __nv_sqrtf/__nv_sqrt,
lower to sqrt.rn now that opt folds __CUDA_PREC_SQRT itself.

Those are PTX checks, and the NVVM route taken when no llvm-link
matches llc writes only the .ll and .target. The script always checks
that the IR calls libdevice's erff and sqrt, and checks the PTX only
when a current one exists, as function_item_call does, so that build
still passes. smoketest.sh runs the script in compile-only CI, which
takes the PTX route.

Signed-off-by: Praveen Perera <[email protected]>
@praveenperera
praveenperera force-pushed the fix/libdevice-unroll-1705 branch from 156c3a7 to 0e6244b Compare November 4, 2026 06:43
praveenperera added a commit to praveenperera/cuda-rust that referenced this pull request Nov 4, 2026
A small counted loop that fills an array by its counter, such as
`for e in 0..4 { r[e] = erff(a[e]) }`, keeps the array in registers
only if LLVM unrolls it. When the body is over the unroll threshold
the array silently moves to .local, and only a verbose build said so.

Report that case in every optimized build, with a help line pointing
at #[unroll]. A counter qualifies only when every phi of its
recurrence is a loop-header phi with a literal start, a literal
compare of it alone ends the loop (judged by which target is the back
edge), and it steps by a literal or by the widened compare of Rust's
range desugaring that the back edge itself requires. The local is
reported only when its address does not escape and every index into
it comes from such counters and literals through phis that pick by
iteration, not by a runtime branch. Anything unsure stays quiet.
Every other local-memory diagnostic remains verbose-only.

The analysis runs on every optimized build now, so it is linear in
the function: Tarjan SCCs for recurrences, one memoized operand walk,
one branch index, and one pointer and escape pass per function, all
with explicit stacks.

The standalone API now reports the pipeline's `warning: ` diagnostics,
this one included, as warnings instead of notes.

Refs NVIDIA#1705

Stacked on NVIDIA#1732, which changed the same three sentences from -O2 to
-O3: the local_memory_diagnostic module doc, the with_verbose doc and
the compiler-optimizations scalar-replacement sentence keep this
change's wording, which names no optimization level.

Signed-off-by: Praveen Perera <[email protected]>
praveenperera added a commit to praveenperera/cuda-rust that referenced this pull request Nov 5, 2026
A small counted loop that fills an array by its counter, such as
`for e in 0..4 { r[e] = erff(a[e]) }`, keeps the array in registers
only if LLVM unrolls it. When the body is over the unroll threshold
the array silently moves to .local, and only a verbose build said so.

Report that case in every optimized build, with a help line pointing
at #[unroll]. A counter qualifies only when every phi of its
recurrence is a loop-header phi with a literal start, a literal
compare of it alone ends the loop (judged by which target is the back
edge), and it steps by a literal or by the widened compare of Rust's
range desugaring that the back edge itself requires. The local is
reported only when its address does not escape and every index into
it comes from such counters and literals through phis that pick by
iteration, not by a runtime branch. Anything unsure stays quiet.
Every other local-memory diagnostic remains verbose-only.

The analysis runs on every optimized build now, so it is linear in
the function: Tarjan SCCs for recurrences, one memoized operand walk,
one branch index, and one pointer and escape pass per function, all
with explicit stacks.

The standalone API now reports the pipeline's `warning: ` diagnostics,
this one included, as warnings instead of notes.

Refs NVIDIA#1705

Stacked on NVIDIA#1732, which changed the same three sentences from -O2 to
-O3: the local_memory_diagnostic module doc, the with_verbose doc and
the compiler-optimizations scalar-replacement sentence keep this
change's wording, which names no optimization level.

Signed-off-by: Praveen Perera <[email protected]>
@nihalpasham nihalpasham added cuda-oxide SIMT programming model: rustc backend, cargo oxide, cuda-device, cuda-host, book bug Something isn't working perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Nov 9, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks, passing -mcpu=<target_sm> and LIBDEVICE_PRECISION_REFLECT_ARGS to opt so NVVMReflectPass folds __CUDA_FTZ and __CUDA_PREC_SQRT before loop unrolling is the right fix for #1705. Layered one follow-up on top:

  • Keep opt at default<O2> (with #[unroll] on erf_pair_loop) to avoid the O3 register increases on tiled_gemm and hashmap_v3.

At 708f9c6c, cuda-oxide-codegen tests, libm_math on RTX 5090, and verify-code-shape.sh all pass. Merging once CI is green.

@NVIDIA NVIDIA deleted a comment from copy-pr-bot Bot Nov 9, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

/ok to test 708f9c6

@nihalpasham
nihalpasham merged commit 015ff69 into NVIDIA:main Nov 9, 2026
78 checks passed
@copy-pr-bot

copy-pr-bot Bot commented Nov 9, 2026

Copy link
Copy Markdown

/ok to test 708f9c6c1be8aa67fcbe0ba2889b2d032ff0b8d7

@nihalpasham, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

@praveenperera
praveenperera deleted the fix/libdevice-unroll-1705 branch November 9, 2026 14:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working codegen Device code-generation pipeline (Rust MIR to IR to PTX) cuda-oxide SIMT programming model: rustc backend, cargo oxide, cuda-device, cuda-host, book perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: constant-trip loops calling libdevice math stay rolled and put their arrays in .local; nvcc and clang unroll them

2 participants