Skip to content

fix(mir-lower): keep scalar float math on the LLVM-to-PTX path - #391

Merged
nihalpasham merged 2 commits into
NVIDIA:mainfrom
niklebedenko:upstreaming/float-math-llvm-intrinsics
Jul 28, 2026
Merged

nihalpasham merged 2 commits into
NVIDIA:mainfrom
niklebedenko:upstreaming/float-math-llvm-intrinsics

Conversation

@niklebedenko

Copy link
Copy Markdown
Contributor

Closes #390.

Summary

Simple scalar abs, copysign, max, and min operations were routed
through libdevice even though LLVM and NVPTX can lower them directly. This
keeps those operations on the ordinary LLVM-to-PTX path while preserving
Rust's NaN and signed-zero semantics for both f32 and f64.

Before: these operations forced NVVM IR emission and CUDA Toolkit runtime
linking. After: focused kernels containing only these operations emit PTX
directly.

What changed

Direct scalar lowering

  • abs and copysign select the width-correct llvm.fabs and
    llvm.copysign intrinsics.
  • Rust's _nsz max and min use the ordered compare/select definition from
    core::intrinsics instead of libdevice.
  • The existing libdevice table remains the fallback for operations without a
    correct LLVM-only route.

Rust semantics and sibling paths

  • The explicit max/min sequence avoids LLVM 21's legacy maxnum/minnum
    behavior, which propagates signaling NaNs contrary to Rust's contract.
  • Every RustFloatMathIntrinsic variant was audited. Transcendentals, rounding
    operations, FMA, and remaining functions retain their __nv_* lowering.
  • Rust methods and libm/cmath spellings that share these importer placeholders
    intentionally receive the same direct lowering; unrelated external math
    calls and the fast-arithmetic path are unchanged.

Known separate limitations

  • This does not move transcendental, rounding, FMA, or other libdevice-owned
    operations onto the direct PTX path.
  • Max/min deliberately retain an explicit compare/select sequence until the
    available LLVM intrinsic semantics match Rust's signaling-NaN contract.
  • All-target clippy still exposes ten pre-existing unnecessary_mut_passed
    warnings in unchanged tests/lowering_test.rs; library and focused-example
    clippy are clean.

Testing

  • Added unit coverage for width-specific LLVM names, min/max predicates, and
    the libdevice fallback.
  • Expanded fmaxmin_smoke across both widths, quiet/signaling NaNs in either
    operand, both-NaN results, both signed-zero orders, finite values, abs sign
    behavior, and exact copysign NaN-payload preservation.
  • Verified generated LLVM IR contains the expected compare/select sequences
    and width-specific fabs/copysign declarations, without legacy
    maxnum/minnum or matching __nv_* references.
  • On upstream main, the example emitted LTOIR with
    __nv_fmax{f}/__nv_fmin{f} calls; this branch emits PTX directly.
  • cargo fmt --all -- --check
  • cargo fmt --manifest-path crates/rustc-codegen-cuda/examples/fmaxmin_smoke/Cargo.toml -- --check
  • LIBRARY_PATH=/tmp/cuda-oxide-libffi-link cargo test -p mir-lower --all-targets
  • LIBRARY_PATH=/tmp/cuda-oxide-libffi-link cargo clippy -p mir-lower --lib -- -D warnings
  • cargo clippy --manifest-path crates/rustc-codegen-cuda/examples/fmaxmin_smoke/Cargo.toml --all-targets -- -D warnings
  • Optimized and CUDA_OXIDE_NO_OPT=1 GPU executions passed on an NVIDIA RTX
    3080 (sm_86).

Checklist

  • The branch is based on current upstream main.
  • The routing regression fails on upstream main and passes on this branch.
  • Both widths, NaN classes, signed zeros, and exact sign/payload behavior are covered.
  • Unrelated libdevice and fast-arithmetic paths remain unchanged.
  • Formatting, focused tests, library clippy, example clippy, and GPU runs pass.
  • Commits include DCO signoff and new example files have required headers.

@nihalpasham nihalpasham added enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves perf Performance of generated code or of the compiler itself labels Jul 22, 2026
@honeyspoon

Copy link
Copy Markdown
Contributor

Measurement that may let the min/max path drop from two instructions to one.

I checked what LLVM 21.1 actually emits for the NVPTX target (llc -march=nvptx64 -mcpu=sm_80, body only):

llvm.minnum.f32  ->  min.f32     (1 instruction)
llvm.maxnum.f32  ->  max.f32     (1 instruction)

So the backend already selects the single instruction; the sNaN problem this PR works around is at the IR level, where the optimizer may fold minnum(sNaN, x) to a NaN, rather than in codegen. PTX min/max without the .NaN modifier return the non-NaN operand when exactly one operand is NaN, and a canonical NaN when both are, which is the behaviour Rust asks for and is independent of qNaN vs sNaN. (The .NaN modifier is what opts into propagation, which is why the generated *_nan_* variants exist separately.)

If that reading is right, emitting the PTX instruction directly through inline asm would give the correct Rust semantics in 1 instruction, where the ordered compare/select is setp + selp. The compare/select is certainly the safer default and I would not block on this; it just seemed worth recording so the choice is deliberate rather than forced.

Context: this came out of a duplicate branch of mine that I have closed in favour of this PR, since making f32::max/f32::min themselves stop calling libdevice is the general fix and named wrapper functions are not.

Separately, on the fabs/copysign overlap with my #466: this PR is the more general treatment, so I am stripping fabs and copysign out of #466 and leaving it as rounding only. No action needed on your side.

honeyspoon added a commit to honeyspoon/cuda-oxide that referenced this pull request Jul 24, 2026
NVIDIA#391 ("keep scalar float math on the LLVM-to-PTX path") also moves fabs and
copysign off libdevice, and does it as part of a broader change that
additionally handles max/min. That makes it the more general treatment of the
overlap, so this PR drops fabs and copysign and keeps only the rounding
operations, which NVIDIA#391 does not cover.

max/min stay out of scope here for a reason worth stating: they cannot use
`llvm.maxnum`/`llvm.minnum` at all, because under LLVM 21 those propagate
signaling NaNs and contradict Rust's contract. NVIDIA#391 lowers them as an ordered
compare/select instead.

With fabs gone the method no longer needs the context or result type, since
every rounding variant is already type-specific (`FloorF32` vs `FloorF64`), so
the signature loses both parameters. The test now asserts fabs and copysign
return `None` here, which is what pins the scope boundary and will fail
loudly if the two PRs start overlapping again.

Also reduces the conflict surface: both PRs restructure the same fabs path,
this one via a method and NVIDIA#391 via a standalone `fabs_llvm_intrinsic_name`.

Signed-off-by: abder <[email protected]>
nihalpasham added a commit that referenced this pull request Jul 25, 2026
#466)

* fix(mir-lower): lower fabs and copysign to LLVM intrinsics instead of libdevice

`f32::abs()`, `f64::abs()`, `f32::copysign()`, and `f64::copysign()` are
pure sign-bit operations with direct LLVM intrinsic equivalents
(`llvm.fabs.*`, `llvm.copysign.*`). Routing them through libdevice
(`__nv_fabsf`, `__nv_copysignf`) added an unnecessary function call and
forced the kernel onto the heavier libNVVM pipeline even when no
transcendental math was used.

This is the first step toward resolving #390. The `max`/`min` operations
are left on the libdevice path for now because their NaN semantics need
more careful treatment.

Signed-off-by: abder <[email protected]>

* fix(mir-lower): lower rounding ops to LLVM intrinsics instead of libdevice

Extend llvm_intrinsic_name() to route floor, ceil, trunc, round, and
roundeven through their LLVM intrinsic equivalents instead of libdevice
calls. The NVPTX backend lowers these to single PTX cvt instructions
(cvt.rmi/rpi/rzi/rni), avoiding the libdevice function-call overhead.

max/min are intentionally left on the libdevice path: LLVM 21's
maxnum/minnum propagate signaling NaNs, contradicting Rust's contract.
These need compare/select lowering instead (see #390).

Signed-off-by: abder <[email protected]>

* docs: correct the PTX mapping claimed for the routed intrinsics

The comment claimed every routed intrinsic lowers to a single PTX
instruction and listed `round` among the `cvt` conversions. That is wrong
for `round`: it rounds halfway cases away from zero, and none of the four
hardware `cvt` modes does that (`rni` is ties-to-even), so no single
instruction can express it.

Measured with LLVM 21.1 `llc -march=nvptx64 -mcpu=sm_80`, body only:

  fabs, copysign, floor, ceil, trunc, roundeven -> 1 instruction each
  round                                         -> 11 (f32), 8 (f64)

`round` is still worth routing here: LLVM expands it inline into
compare/select over `cvt.rzi` rather than emitting a `roundf` libcall, so
the libdevice call goes away without leaving an unresolved symbol. The doc
now states that instead of implying a single `cvt`, and carries the table
so the next reader does not have to re-measure.

No functional change.

Signed-off-by: abder <[email protected]>

* refactor: narrow to rounding, ceding fabs/copysign to #391

#391 ("keep scalar float math on the LLVM-to-PTX path") also moves fabs and
copysign off libdevice, and does it as part of a broader change that
additionally handles max/min. That makes it the more general treatment of the
overlap, so this PR drops fabs and copysign and keeps only the rounding
operations, which #391 does not cover.

max/min stay out of scope here for a reason worth stating: they cannot use
`llvm.maxnum`/`llvm.minnum` at all, because under LLVM 21 those propagate
signaling NaNs and contradict Rust's contract. #391 lowers them as an ordered
compare/select instead.

With fabs gone the method no longer needs the context or result type, since
every rounding variant is already type-specific (`FloorF32` vs `FloorF64`), so
the signature loses both parameters. The test now asserts fabs and copysign
return `None` here, which is what pins the scope boundary and will fail
loudly if the two PRs start overlapping again.

Also reduces the conflict surface: both PRs restructure the same fabs path,
this one via a method and #391 via a standalone `fabs_llvm_intrinsic_name`.

Signed-off-by: abder <[email protected]>

* fix(mir-lower): encode rounding intrinsic symbols as pliron identifiers

Pliron identifiers reject dots, so the dotted LLVM names
("llvm.floor.f32", ...) in the new rounding routing table failed
symbol creation inside ensure_intrinsic_declared and every
rounding-only kernel aborted with:

  Failed to declare intrinsic: Invalid intrinsic name 'llvm.floor.f32':
  ... MalformedIdentifierErr("llvm.floor.f32")

Use the underscore encoding ("llvm_floor_f32") that the rest of the
lowering already uses for llvm_ctpop_i*/llvm_bswap_i* and friends; the
textual .ll exporter decodes it back to the dotted LLVM intrinsic name
on export.

* fix(dialect-mir): reclassify rounding placeholders as backend-dependent libdevice

The ten rounding placeholders (floor/ceil/trunc/round/roundeven x
f32/f64) no longer lower to libdevice on the LLVM NVPTX path; they
lower to the native llvm.floor.*-family intrinsics. Leaving them in
is_libdevice_backed_placeholder made the pre-lowering predictor claim
libdevice for rounding-only kernels while the lowered module contained
no __nv_* symbol, so the pipeline consistency check aborted every
rounding-only compilation with "libdevice backend selection changed
during MIR lowering".

Split the classification in two exact, mutually disjoint allow-lists:

* is_libdevice_backed_placeholder: ops that need libdevice under every
  intrinsic backend (transcendentals, fma, fabs/copysign, max/min).
* is_backend_dependent_libdevice_placeholder: exactly the ten rounding
  ops, which need libdevice only when the pipeline emits NVVM IR (the
  legacy LLVM 7-based NVVM dialect predates llvm.roundeven.*).

The classification test now asserts every placeholder in the module
against both predicates, so the sets stay exact and disjoint.

* fix(codegen): dispatch rounding intrinsics on the intrinsic backend

The rounding routing table applied unconditionally, so a module headed
to libNVVM would receive llvm.roundeven.* and friends: the legacy
LLVM 7-based NVVM IR dialect predates llvm.roundeven (LLVM 11) and
admits only a small intrinsic allow-list, so those forms do not exist
there. Every sibling intrinsic conversion (tma, mbarrier, dotprod,
cp_async) already branches on the pipeline-selected IntrinsicBackend;
do the same for float math:

* LlvmNvptx: rounding uses the native LLVM intrinsics (new capability,
  no libdevice); everything else stays on libdevice.
* LibNvvm: every float-math op stays on libdevice (__nv_floorf, ...),
  the only spelling portable across all libNVVM input dialects.

Make the pre-lowering libdevice prediction backend-aware to match,
keeping the post-lowering consistency check sound in both directions:
only strict libdevice use (transcendentals, direct __nv_* calls) can
force the NVVM IR fallback, and the predicted needs_libdevice adds the
backend-dependent rounding placeholders exactly when the LibNvvm
backend was selected. Without this, a rounding-only kernel built with
--emit-nvvm-ir would emit __nv_floorf while the prediction said no
libdevice, tripping the same consistency abort in the other direction.

Also fixes the stale "(abs, copysign, rounding)" comment at the
routing site (the narrowed scope is rounding only) and generalizes the
typed-MIR walker to take a callee predicate instead of duplicating the
traversal.

* test(examples): add rounding-only float_rounding example

A kernel whose only math-library usage is rounding now compiles on the
self-contained PTX path with zero libdevice involvement; this example
locks that capability in (the generated float_rounding.ll must contain
no __nv_ symbols) and pins the rounding semantics on device with
bit-exact host comparisons:

* round is ties-away-from-zero: round(2.5)==3.0, round(-2.5)==-3.0
* round_ties_even is ties-to-even: 2.5 -> 2.0, 3.5 -> 4.0
* signed zero survives: round(-0.4) == -0.0
* floor(-1.5)==-2.0, ceil(-1.5)==-1.0, trunc(-1.7)==-1.0

Both float widths run all five ops over halfway ties, signed zeros,
fractions on both sides of .5, exact integers, and large values.

Before the preceding fixes this example failed to compile: first with
the malformed-identifier error from the dotted intrinsic names, then
(names fixed) with the "libdevice backend selection changed during MIR
lowering" consistency abort from the stale pre-lowering predictor.

---------

Signed-off-by: abder <[email protected]>
Co-authored-by: nihalpasham <[email protected]>
niklebedenko and others added 2 commits July 28, 2026 08:56
…ibdevice prediction

Completes the rebase of NVIDIA#391 onto the IntrinsicBackend dispatch that NVIDIA#466
introduced after the PR was written; this part of the contributor's change
could not be expressed as a rebase of their diff, so it is re-implemented
here as a maintainer integration commit.

Without this, select_pre_lowering_backend still classified fabs/copysign
and the float max/min placeholders as strict libdevice, so kernels using
only those ops were forced onto the NVVM-IR / libdevice route and the
LLVM-to-PTX lowering from the previous commit never engaged (and the
post-lowering consistency check would abort the build once it did).

- rust_intrinsics: move CALLEE_FABS / CALLEE_COPYSIGN_F32/F64 from
  is_libdevice_backed_placeholder to
  is_backend_dependent_libdevice_placeholder (llvm.fabs/llvm.copysign on
  the NVPTX path, __nv_fabs*/__nv_copysign* only under libNVVM), and drop
  CALLEE_MAXNUM_NSZ_* / CALLEE_MINNUM_NSZ_* from both lists (they expand
  to an ordered compare/select under every backend and never use
  libdevice). Classification test arrays updated to match.
- mir-lower: the now-unreachable max/min arms of libdevice_name are a
  hard error, mirroring the f*_fast arm; backend-dispatch test covers the
  fabs/copysign split.
- cuda-oxide-codegen: backend-selection docs updated; new prediction
  tests for sign-only/minmax-only modules on both output policies.
@nihalpasham
nihalpasham force-pushed the upstreaming/float-math-llvm-intrinsics branch from 2e99d30 to 8a58a9b Compare July 28, 2026 05:02
@nihalpasham nihalpasham added the codegen Device code-generation pipeline (Rust MIR to IR to PTX) label Jul 28, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks, this design makes sense to me.

Gist: width-correct llvm.fabs/llvm.copysign, and a compare/select expansion for f32/f64 max/min since LLVM 21's llvm.maxnum/minnum propagate signaling NaNs against Rust's contract.

It landed after a substantive rebase onto the IntrinsicBackend dispatch from #466 (merged while this was on hold), plus one maintainer commit that reclassifies fabs/copysign as backend-dependent and max/min as never-libdevice in the pipeline's backend prediction so these kernels stay on the direct LLVM-to-PTX path.

Validated on 2x RTX 5090 (sm_120): the expanded fmaxmin_smoke passes with and without opt -O2 on llc/opt 21 and 22 (opt does not re-form maxnum/minnum), emits PTX directly with zero __nv_* calls, the --emit-nvvm-ir route still resolves __nv_fabs*/__nv_copysign*, and the workspace test suite plus a 172/172 compile-only smoketest sweep are green.

Closes #390; dropping on-hold.

@nihalpasham nihalpasham removed the on-hold Paused: valid but deferred until a prerequisite decision or dependency resolves label Jul 28, 2026
@nihalpasham
nihalpasham merged commit ab2c03e into NVIDIA:main Jul 28, 2026
33 checks passed
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 intrinsics Device intrinsics and libdevice math mappings IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) perf Performance of generated code or of the compiler itself

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Simple scalar float operations unnecessarily require libdevice

3 participants