[Bug middle-end/96733] std::clamp for floats and doubles produces worse code than a combo of std::min / std::max

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Fri Aug 21 10:42:43 GMT 2020


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96733

Jonathan Wakely <redi at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
          Component|c++                         |middle-end
   Last reconfirmed|                            |2020-08-21
             Status|UNCONFIRMED                 |NEW
     Ever confirmed|0                           |1

--- Comment #1 from Jonathan Wakely <redi at gcc dot gnu.org> ---
Without the library dependency:

namespace std
{
  template<typename _Tp>
    constexpr const _Tp&
    min(const _Tp& __a, const _Tp& __b)
    {
      //return __b < __a ? __b : __a;
      if (__b < __a)
        return __b;
      return __a;
    }

  template<typename _Tp>
    constexpr const _Tp&
    max(const _Tp& __a, const _Tp& __b)
    {
      //return  __a < __b ? __b : __a;
      if (__a < __b)
        return __b;
      return __a;
    }

  template<typename _Tp>
    constexpr const _Tp&
    clamp(const _Tp& __val, const _Tp& __lo, const _Tp& __hi)
    {
      return (__val < __lo) ? __lo : (__hi < __val) ? __hi : __val;
    }
}

// This version is good in gcc, not so on vc++
double clamp_minmax( double x, double i, double ax )
{
    return std::min( std::max( x, i ), ax );
}

// This version should be identical but is not.
// gcc compiles to scalar comparisons
// vc++ code is outright horrible, compiles into RAM access.
double clamp_builtin( double x, double i, double ax )
{
    return std::clamp( x, i, ax );
}


More information about the Gcc-bugs mailing list