Skip to content

[clang++] LLVM 18 Possible Optimization Bug: Ignored Float ComparisonΒ #112002

@lmglmg

Description

@lmglmg

Summary

There appears to be a change in behavior in LLVM 18 where a float comparison is ignored during optimization with specific compiler flags. This issue is not present in LLVM 17. I've encountered this issue while debugging wrong sigmoid calculation in Eigen library.

Environment

  • LLVM Version: 18
  • Architecture: aarch64
  • Compiler Options: -O3 -ffast-math -fno-exceptions

Reproduction Code

The following code demonstrates the issue:

#include <cstring>

namespace 
{
    inline float
    my_ptrue( const float & a ) 
    {
        float b;
        std::memset( static_cast< void * >( &b ), 0xff, sizeof( float ) );
        return b;
    }
}

int foo( float const & x )
{
    const float cutoff_lower{ -9.0f };

    // Reproduces the error
    float const lt_mask = x < cutoff_lower ? my_ptrue( x ) : 0.0f; 

    // Does not reproduce the error
    // float const lt_mask = x < cutoff_lower ? 1.0f : 0.0f; 

    bool const any_small = lt_mask != 0.f;

    if ( any_small )
    {
        // Good
        return 0;
    }
    else 
    {
        // Bad
        return 1;
    }
}

LLVM 17 generates the following assembly code, which correctly includes the float comparison:

foo(float const&):
        fmov    s0, #-9.00000000
        ldr     s1, [x0]
        fcmp    s1, s0
        cset    w0, ge
        ret

LLVM 18 generates the following assembly code, which omits the float comparison:

foo(float const&):
        mov     w0, #1
        ret

Godbolt link: https://godbolt.org/z/x7z13W8b6

This behavior when used with the new compiler and -ffast-math:
https://godbolt.org/z/v3qj6vd3W

Is this new behavior expected when the code is compiled with -ffast-math ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    floating-pointFloating-point mathllvm:optimizationsquestionA question, not bug report. Check out https://llvm.org/docs/GettingInvolved.html instead!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions