How to force GCC to assume that a floating-point expression is non-negative?

前端 未结 4 1671
说谎
说谎 2020-12-13 08:41

There are cases where you know that a certain floating-point expression will always be non-negative. For example, when computing the length of a vector, one does sqrt(

4条回答
  •  醉梦人生
    2020-12-13 08:58

    After about a week, I asked on the matter on GCC Bugzilla & they've provided a solution which is the closest to what I had in mind

    float test (float x)
    {
        float y = x*x;
        if (std::isless(y, 0.f))
            __builtin_unreachable();
        return std::sqrt(y);
    }
    

    that compiles to the following assembly:

    test(float):
        mulss   xmm0, xmm0
        sqrtss  xmm0, xmm0
        ret
    

    I'm still not quite sure what exactly happens here, though.

提交回复
热议问题