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

            Bug ID: 113353
           Summary: Wrong rounding in std::nearbyint when vectorized with
                    -funsafe-math-optimizations on PPC
           Product: gcc
           Version: 12.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: target
          Assignee: unassigned at gcc dot gnu.org
          Reporter: alexander.gr...@tu-dresden.de
  Target Milestone: ---

According to the standard `std::nearbyint` and `std::rint` are supposed to give
the same results. However the former does not tie to even in halfway cases when
used in a tight loop.

The following code basically rounding "-8.5" produces `-9` when compiled with
`-funsafe-math-optimizations` but (as actually correct) `-8` when compiled
without it or when using `std::rint` instead. (Additional flags: `-O3
-mcpu=power9`)

This is at least unexpected given that
> The only difference between std::nearbyint and std::rint is that 
> std::nearbyint never raises FE_INEXACT. 

which in this case does not hold.

#include <iostream>
#include <cmath>
#include <vector>

extern "C" void kernel(const double* in_ptr,
                       double* out_ptr,
                       const long ks)
{
    for(long i=0; i<ks; i+=1)
        out_ptr[i] = std::nearbyint(in_ptr[i]);
}


int main()
{
    std::vector<double> in(16, -8.5);
    decltype(in) out(in.size());
    kernel(in.data(), out.data(), in.size());
    for(const auto t: out)
        std::cout << t << ", ";
    std::cout << '\n';
}

Is this an intended effect of -funsafe-math-optimizations? I'd expect to at
least be able to workaround this with -frounding-math or so.

Reply via email to