Skip to content

Preserve NaN when narrowing to half in InstCombine - #762

Closed
pavelsavara wants to merge 1 commit into
dotnet:dotnet/mainfrom
pavelsavara:pavelsavara/fix-mono-nan
Closed

pavelsavara wants to merge 1 commit into
dotnet:dotnet/mainfrom
pavelsavara:pavelsavara/fix-mono-nan

Conversation

@pavelsavara

Copy link
Copy Markdown
Member

Summary

Some targets/toolchains mishandle NaN payloads when narrowing a floating-point
value to half (fp16) and can produce an infinity for a NaN input. This
change teaches InstCombinerImpl::visitFPTrunc to preserve NaN semantics by
guarding fptrunc … to half with an explicit isnan check, so a NaN input is
always lowered to a (quiet) NaN result rather than risking an infinity.

Motivation

A fptrunc of a NaN must yield a NaN. On the affected lowering paths this
invariant was broken, turning NaN inputs into infinities and producing wrong
numerical results in Mono workloads. Materializing the NaN guard at the IR
level makes the result correct regardless of how the backend lowers the
narrowing.

Change

File: llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp

When the destination scalar type is half and the fptrunc is not marked
nnan, the truncation is rewritten as:

%isnan = fcmp uno <T> %src, %src
%trunc = fptrunc <T> %src to <half...>     ; original FMF preserved
%res   = select <i1...> %isnan, <half...> qnan, <half...> %trunc

i.e. select(isnan(src), qnan, fptrunc(src)).

Behavior details:

  • Applies to both scalar half and vectors of half; the quiet-NaN constant is
    splatted for vector destinations.
  • Skips truncations that already carry the nnan fast-math flag (NaN can't
    occur, so no guard is needed).
  • Fast-math flags from the original fptrunc are propagated to the inner
    truncation.
  • Replaces the NaN payload/sign with a canonical quiet NaN (getQNaN). NaN-ness
    is preserved; the exact payload is not (which is the intent, since the
    affected lowering mishandled payloads).

Idempotency / termination

visitFPTrunc revisits the inner fptrunc it creates, so the transform must
recognize its own output and not re-fire. An IsProtectedHalfTrunc helper
detects the already-guarded pattern and bails out. Two subtleties are handled so
InstCombine reliably reaches a fixed point:

  • Compare canonicalization. InstCombine canonicalizes fcmp uno %src, %src
    to fcmp uno %src, 0.0 (see InstCombineCompares.cpp). The guard therefore
    accepts either the %src, %src form or a zero right-hand side
    (m_AnyZeroFP()).
  • Vector NaN constants. The guarding NaN arm of the select is a
    ConstantFP for scalars but a splat (ConstantVector) for vectors. The check
    uses m_NaN(), which matches both scalar and splat NaN constants.

Without these, the protection check would fail to recognize the freshly emitted
guard and InstCombine would not converge (repeated re-expansion / infinite-loop
detection).

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates LLVM InstCombine’s visitFPTrunc to preserve NaN semantics when narrowing floating-point values to half (fp16), by rewriting eligible fptrunc ... to half instructions into an explicit isnan-guarded select that yields a quiet NaN on NaN inputs.

Changes:

  • Add an isnan (fcmp uno) + select guard around fptrunc to half when the trunc is not marked nnan.
  • Support both scalar half and vector-of-half destinations, including splatted NaN constants for vectors.
  • Add a pattern check (IsProtectedHalfTrunc) intended to prevent re-applying the transform on the newly-created inner truncation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +2233 to +2234
return (Sel->getTrueValue() == &FPT && IsNaNConst(Sel->getFalseValue())) ||
(Sel->getFalseValue() == &FPT && IsNaNConst(Sel->getTrueValue()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants