Repository navigation
fix(mir-lower): lower rounding intrinsics to LLVM instead of libdevice - #466
Conversation
… 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 NVIDIA#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]>
|
Note: there is overlap between this PR and #391 from @niklebedenko, which takes a broader approach (also covers |
…evice 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 NVIDIA#390). Signed-off-by: abder <[email protected]>
b8ee2af to
b778635
Compare
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]>
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]>
|
Narrowed to rounding only, to remove the overlap with #391. #391 moves While measuring, one correction to what this PR originally claimed. It said every routed intrinsic lowers to a single PTX instruction and listed
Happy to rebase on top of #391 once it lands if you would prefer these stacked. |
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.
…nt 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.
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.
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.
|
Thanks, this makes sense. The PTX mapping table in the PR is quite useful. As diffed it could not compile a rounding kernel though, so I pushed four commits on top:
Verified on an RTX 5090: rounding-only kernels now build self-contained PTX with zero libdevice, |
…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.
* fix(mir-lower): keep scalar float math on the LLVM-to-PTX path Signed-off-by: nik <[email protected]> * fix(dialect-mir): reclassify fabs/copysign and float max/min in the libdevice prediction Completes the rebase of #391 onto the IntrinsicBackend dispatch that #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. --------- Signed-off-by: nik <[email protected]> Co-authored-by: nihalpasham <[email protected]>
Summary
Lower Rust math intrinsics with direct LLVM equivalents to their native
LLVM intrinsic names instead of routing through libdevice. The NVPTX
backend lowers each to a single PTX instruction, avoiding the libdevice
function-call overhead.
Partial fix for #390.
Operations routed to LLVM intrinsics
f32::abs()/f64::abs()llvm.fabs.*abs.f32/abs.f64f32::copysign()/f64::copysign()llvm.copysign.*copysign.f32/copysign.f64f32::floor()/f64::floor()llvm.floor.*cvt.rmi.f32.f32f32::ceil()/f64::ceil()llvm.ceil.*cvt.rpi.f32.f32f32::trunc()/f64::trunc()llvm.trunc.*cvt.rzi.f32.f32f32::round()/f64::round()llvm.round.*f32::round_ties_even()llvm.roundeven.*cvt.rni.f32.f32Motivation
These operations are pure register-to-register transforms with exact LLVM
intrinsic equivalents. Routing them through libdevice adds an unnecessary
function call and forces the kernel onto the heavier libNVVM/nvJitLink
pipeline even when no transcendental math is used.
For rounding specifically, this eliminates the need for hand-written
IEEE-754 bit tricks (e.g., a ~10-instruction
round_ties_away()function)in user kernels --
x.floor(),x.ceil(), etc. now compile to singlePTX instructions.
Deliberate exclusions
max/minare intentionally left on the libdevice path. LLVM 21'smaxnum/minnumpropagate signaling NaNs, which contradicts Rust'scontract (
f32::maxreturns the non-NaN operand). These needcompare/select lowering instead, as addressed by #391.
Implementation
Added
RustFloatMathIntrinsic::llvm_intrinsic_name()incrates/mir-lower/src/convert/ops/call.rswhich returns the width-qualifiedLLVM intrinsic name for ops that can bypass libdevice. The existing
convert_rust_float_math_intrinsic()checks this method first, fallingthrough to
libdevice_name()only for transcendentals (sin, cos, exp,log, pow, etc.) that have no single-instruction PTX equivalent.
Testing
Unit test
test_llvm_intrinsic_name_routingverifies:llvm.fabs.f32/llvm.fabs.f64llvm.copysign.f32/llvm.copysign.f64MaxNumNsz/MinNumNszreturnNone(libdevice path, per Simple scalar float operations unnecessarily require libdevice #390)SinF32,SqrtF64) returnNone(libdevice path)