Why is GCC 4.8.2 complaining about addition under strict overflow?

后端 未结 2 654
温柔的废话
温柔的废话 2020-12-11 17:00

Consider this code (bits.c):

#include 
#include 
#include 

static uint64_t pick_bits(unsigned          


        
相关标签:
2条回答
  • 2020-12-11 17:07

    My assumption is that gcc is inlining pick_bits and thus compiling with the knowledge that hi == lo+3 which allows it to assume that hi >= lo is always true as long as lo is low enough that lo+3 doesn't overflow.

    0 讨论(0)
  • 2020-12-11 17:15

    It's inlining the function, and then generating the error. You can see for yourself:

    __attribute__((noinline))
    static uint64_t pick_bits(unsigned char *bytes, size_t nbytes, int lo, int hi)
    

    On my system, the original version generates the same warning, but the noinline version does not.

    GCC then optimizes out hi >= lo, because it's really u+3 >= u, and generates a warning because it's not good enough at figuring out that u+3 doesn't overflow. A shame.

    Documentation

    From the GCC documentation, section 3.8:

    An optimization that assumes that signed overflow does not occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Therefore this warning can easily give a false positive: a warning about code that is not actually a problem. To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires, in particular when determining whether a loop will be executed at all.

    Emphasis added. My personal recommendation is to use -Wno-error=strict-overflow, or to use a #pragma to disable the warning in the offending code.

    0 讨论(0)
提交回复
热议问题