成功启用-fno-finite-math-only-NaN删除方法

And*_*der 3 c++ gcc nan compiler-optimization

在查找NaN运行我的代码的优化版本(编译g++ 4.8.24.9.3)时,一切都变为s 的错误,我发现问题是-Ofast选项,特别是-ffinite-math-only它包含的标志.

代码的一部分涉及从FILE*使用中读取浮点数fscanf,然后用NaN数值替换所有s.然而,正如可以预料的那样,-ffinite-math-only开始并删除这些检查,从而离开了NaNs.

在试图解决这个问题,我迷迷糊糊uppon 这个,这表明添加-fno-finite-math-only的方法属性禁用特定方法的优化.以下说明了问题和尝试修复(实际上没有修复它):

#include <cstdio>
#include <cmath>

__attribute__((optimize("-fno-finite-math-only"))) 
void replaceNaN(float * arr, int size, float newValue){
    for(int i = 0; i < size; i++) if (std::isnan(arr[i])) arr[i] = newValue;
}

int main(void){
    const size_t cnt = 10;
    float val[cnt];
    for(int i = 0; i < cnt; i++) scanf("%f", val + i);
    replaceNaN(val, cnt, -1.0f);
    for(int i = 0; i < cnt; i++) printf("%f ", val[i]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果使用编译/运行代码,则代码不会按预期运行echo 1 2 3 4 5 6 7 8 nan 10 | (g++ -ffinite-math-only test.cpp -o test && ./test),具体而言,它输出a nan(应该已被a替换-1.0f) - 如果-ffinite-math-only标记被省略则表现良好.这不应该工作吗?我是否遗漏了gcc中属性语法的内容,或者这是另外一个"与某些版本的GCC相关的问题"(来自链接的SO问题)

我知道的一些解决方案,但宁愿更清洁/更便携的东西:

  • -fno-finite-math-only(我的interrim解决方案)编译代码:我怀疑这个优化在我的上下文中可能在程序的其余部分中非常有用;
  • 手动"nan"在输入流中查找字符串,然后在那里替换值(输入读取器位于库的不相关部分,产生不良设计以包含此测试).
  • 假设一个特定的浮点架构并使我自己isNaN:我可能会这样做,但它有点hackish和不可移植.
  • 使用没有-ffinite-math-only标志的单独编译的程序预过滤数据,然后将其提供给主程序:维护两个二进制文件并让它们相互通信的额外复杂性是不值得的.

编辑:在接受的答案中,似乎这是旧版本中的编译器"bug" g++,例如4.824.9.3,在较新版本中修复,例如5.16.1.1.

如果由于某种原因更新编译器不是一个相当容易的选项(例如:没有root访问权限),或者将此属性添加到单个函数仍然不能完全解决NaN检查问题,另一种解决方案,如果您可以确定代码将始终在IEEE754浮点环境中运行,是手动检查浮点的位以进行NaN签名.

接受的答案建议使用位字段来执行此操作,但是,编译器将元素放在位字段中的顺序是非标准的,事实上,旧版本和较新版本之间的更改g++,甚至拒绝遵循无论它们在代码中出现的顺序如何,都希望在旧版本中定位(4.8.24.9.3始终将尾数放在第一位).

但是,使用位操作的解决方案可以保证在所有IEEE754兼容的编译器上运行.下面是我的这种实现,我最终用来解决我的问题.它检查是否IEEE754符合要求,并且我已将其扩展为允许双精度,以及其他更常规的浮点操作.

#include <limits> // IEEE754 compliance test
#include <type_traits> // enable_if

template<
    typename T, 
    typename = typename std::enable_if<std::is_floating_point<T>::value>::type,
    typename = typename std::enable_if<std::numeric_limits<T>::is_iec559>::type,
    typename u_t = typename std::conditional<std::is_same<T, float>::value, uint32_t, uint64_t>::type
>
struct IEEE754 {

    enum class WIDTH : size_t {
        SIGN = 1, 
        EXPONENT = std::is_same<T, float>::value ? 8 : 11,
        MANTISSA = std::is_same<T, float>::value ? 23 : 52
    };
    enum class MASK : u_t {
        SIGN = (u_t)1 << (sizeof(u_t) * 8 - 1),
        EXPONENT = ((~(u_t)0) << (size_t)WIDTH::MANTISSA) ^ (u_t)MASK::SIGN,
        MANTISSA = (~(u_t)0) >> ((size_t)WIDTH::SIGN + (size_t)WIDTH::EXPONENT)
    };
    union {
        T f;
        u_t u;
    };

    IEEE754(T f) : f(f) {}

    inline u_t sign() const { return u & (u_t)MASK::SIGN >> ((size_t)WIDTH::EXPONENT + (size_t)WIDTH::MANTISSA); }
    inline u_t exponent() const { return u & (u_t)MASK::EXPONENT >> (size_t)WIDTH::MANTISSA; }
    inline u_t mantissa() const { return u & (u_t)MASK::MANTISSA; }

    inline bool isNan() const {
        return (mantissa() != 0) && ((u & ((u_t)MASK::EXPONENT)) == (u_t)MASK::EXPONENT);
    }
};
template<typename T>
inline IEEE754<T> toIEEE754(T val) { return IEEE754<T>(val); }
Run Code Online (Sandbox Code Playgroud)

replaceNaN功能现在变成:

void replaceNaN(float * arr, int size, float newValue){
    for(int i = 0; i < size; i++) 
        if (toIEEE754(arr[i]).isNan()) arr[i] = newValue;
}
Run Code Online (Sandbox Code Playgroud)

检查这些函数的汇编表明,正如预期的那样,所有掩码都成为编译时常量,从而产生以下(看似)高效的代码:

# In loop of replaceNaN
movl    (%rcx), %eax       # eax = arr[i] 
testl   $8388607, %eax     # Check if mantissa is empty
je  .L3                    # If it is, it's not a nan (it's inf), continue loop
andl    $2139095040, %eax  # Mask leaves only exponent
cmpl    $2139095040, %eax  # Test if exponent is all 1s
jne .L3                    # If it isn't, it's not a nan, so continue loop
Run Code Online (Sandbox Code Playgroud)

这是一条指令少于工作位字段解决方案(无移位),并且使用相同数量的寄存器(虽然很容易说这一点使其更有效率,但还有其他问题,例如流水线可能会成为一个解决方案或多或少效率高于另一个).

Cod*_*ray 5

看起来像编译器错误给我.通过GCC 4.9.2,该属性被完全忽略.GCC 5.1及其后的注意事项.也许是时候升级你的编译器了?

__attribute__((optimize("-fno-finite-math-only"))) 
void replaceNaN(float * arr, int size, float newValue){
    for(int i = 0; i < size; i++) if (std::isnan(arr[i])) arr[i] = newValue;
}
Run Code Online (Sandbox Code Playgroud)

编译-ffinite-math-only的GCC 4.9.2:

replaceNaN(float*, int, float):
        rep ret
Run Code Online (Sandbox Code Playgroud)

但是在GCC 5.1上使用完全相同的设置:

replaceNaN(float*, int, float):
        test    esi, esi
        jle     .L26
        sub     rsp, 8
        call    std::isnan(float) [clone .isra.0]
        test    al, al
        je      .L2
        mov     rax, rdi
        and     eax, 15
        shr     rax, 2
        neg     rax
        and     eax, 3
        cmp     eax, esi
        cmova   eax, esi
        cmp     esi, 6
        jg      .L28
        mov     eax, esi
.L5:
        cmp     eax, 1
        movss   DWORD PTR [rdi], xmm0
        je      .L16
        cmp     eax, 2
        movss   DWORD PTR [rdi+4], xmm0
        je      .L17
        cmp     eax, 3
        movss   DWORD PTR [rdi+8], xmm0
        je      .L18
        cmp     eax, 4
        movss   DWORD PTR [rdi+12], xmm0
        je      .L19
        cmp     eax, 5
        movss   DWORD PTR [rdi+16], xmm0
        je      .L20
        movss   DWORD PTR [rdi+20], xmm0
        mov     edx, 6
.L7:
        cmp     esi, eax
        je      .L2
.L6:
        mov     r9d, esi
        lea     r8d, [rsi-1]
        mov     r11d, eax
        sub     r9d, eax
        lea     ecx, [r9-4]
        sub     r8d, eax
        shr     ecx, 2
        add     ecx, 1
        cmp     r8d, 2
        lea     r10d, [0+rcx*4]
        jbe     .L9
        movaps  xmm1, xmm0
        lea     r8, [rdi+r11*4]
        xor     eax, eax
        shufps  xmm1, xmm1, 0
.L11:
        add     eax, 1
        add     r8, 16
        movaps  XMMWORD PTR [r8-16], xmm1
        cmp     ecx, eax
        ja      .L11
        add     edx, r10d
        cmp     r9d, r10d
        je      .L2
.L9:
        movsx   rax, edx
        movss   DWORD PTR [rdi+rax*4], xmm0
        lea     eax, [rdx+1]
        cmp     eax, esi
        jge     .L2
        add     edx, 2
        cdqe
        cmp     esi, edx
        movss   DWORD PTR [rdi+rax*4], xmm0
        jle     .L2
        movsx   rdx, edx
        movss   DWORD PTR [rdi+rdx*4], xmm0
.L2:
        add     rsp, 8
.L26:
        rep ret
.L28:
        test    eax, eax
        jne     .L5
        xor     edx, edx
        jmp     .L6
.L20:
        mov     edx, 5
        jmp     .L7
.L19:
        mov     edx, 4
        jmp     .L7
.L18:
        mov     edx, 3
        jmp     .L7
.L17:
        mov     edx, 2
        jmp     .L7
.L16:
        mov     edx, 1
        jmp     .L7
Run Code Online (Sandbox Code Playgroud)

GCC 6.1的输出类似,但并不完全相同.

用.替换属性

#pragma GCC push_options
#pragma GCC optimize ("-fno-finite-math-only")
void replaceNaN(float * arr, int size, float newValue){
    for(int i = 0; i < size; i++) if (std::isnan(arr[i])) arr[i] = newValue;
}
#pragma GCC pop_options
Run Code Online (Sandbox Code Playgroud)

完全没有区别,因此不仅仅是属性被忽略的问题.这些旧版本的编译器显然不支持在功能级粒度上控制浮点优化行为.

但请注意,在没有交换机的情况下,GCC 5.1及更高版本上生成的代码仍然比编译函数差得多-ffinite-math-only:

replaceNaN(float*, int, float):
        test    esi, esi
        jle     .L1
        lea     eax, [rsi-1]
        lea     rax, [rdi+4+rax*4]
.L5:
        movss   xmm1, DWORD PTR [rdi]
        ucomiss xmm1, xmm1
        jnp     .L6
        movss   DWORD PTR [rdi], xmm0
.L6:
        add     rdi, 4
        cmp     rdi, rax
        jne     .L5
        rep ret
.L1:
        rep ret
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会出现这种差异.有些东西让编译器严重抛弃它的游戏; 这是比完全禁用优化的代码更糟糕的代码.如果我不得不猜测,我推测这是实施的std::isnan.如果这种replaceNaN方法不是速度关键的,那么它可能无关紧要.如果需要重复解析文件中的值,则可能更倾向于具有合理有效的实现.

就个人而言,我会编写自己的非便携式实现std::isnan.IEEE 754格式都有很好的文档记录,并且假设您对代码进行了全面的测试和评论,我无法看到它的危害,除非您绝对需要将代码移植到所有不同的体系结构中.它会将纯粹主义者推向墙上,但也应该使用非标准选项-ffinite-math-only.对于单精度浮点数,类似于:

bool my_isnan(float value)
{
  union IEEE754_Single
  {
    float f;
    struct
    {
    #if BIG_ENDIAN
        uint32_t sign     : 1;
        uint32_t exponent : 8;
        uint32_t mantissa : 23;
    #else
        uint32_t mantissa : 23;
        uint32_t exponent : 8;
        uint32_t sign     : 1;
    #endif
    } bits;
  } u = { value };

  // In the IEEE 754 representation, a float is NaN when
  // the mantissa is non-zero, and the exponent is all ones
  // (2^8 - 1 == 255).
  return (u.bits.mantissa != 0) && (u.bits.exponent == 255);
}
Run Code Online (Sandbox Code Playgroud)

现在,不需要注释,只需使用my_isnan而不是std::isnan.使用-ffinite-math-onlyenabled 编译时生成以下对象代码:

replaceNaN(float*, int, float):
        test    esi, esi
        jle     .L6
        lea     eax, [rsi-1]
        lea     rdx, [rdi+4+rax*4]
.L13:
        mov     eax, DWORD PTR [rdi]     ; get original floating-point value
        test    eax, 8388607             ; test if mantissa != 0
        je      .L9
        shr     eax, 16                  ; test if exponent has all bits set
        and     ax, 32640
        cmp     ax, 32640
        jne     .L9
        movss   DWORD PTR [rdi], xmm0    ; set newValue if original was NaN
.L9:
        add     rdi, 4
        cmp     rdx, rdi
        jne     .L13
        rep ret
.L6:
        rep ret
Run Code Online (Sandbox Code Playgroud)

NaN检查稍微复杂一点,ucomiss然后是奇偶校验标志的测试,但只要您的编译器符合IEEE 754标准,它就保证是正确的.这适用于所有版本的GCC和任何其他编译器.