Strict overflow warning

Hi all,

a few days ago I ran across code that relied on signed overflow being defined. With gcc this worked fine, clang optimized and the program broke.

With gcc it is possible to specify -Wstrict-overflow=x to get a warning in cases where the compiler relies on undefined behaviour (which will usually happen only with -O2 or above).

I tried this with clang, but got no warning (but clang seems to know the option). Am I doing something wrong?

overflow.cpp

#include <iostream>
using namespace std;

class A {
public:
    int func()
    {
        unsigned long &unsignedValue = (unsigned long&)signedValue;
        unsignedValue = 9223372036854775808ul;
        cout << "signedValue " << signedValue << endl;
        signedValue = -signedValue;
        if (signedValue > 0)
        {
            return 1;
        }
        return 0;
    }
private:
    long signedValue;
} ;

int main()
{
    return A().func();
}

clang++ -O3 -Wstrict-overflow=5 -o overflow overflow.cpp
--> produces no warning

./overflow
$? == 1 afterwards

Best regards,
Martin

Hi Martin,

I don’t think there is such warning in clang, but you could use the -fwrapv option to define signed integer arithmetic to wrap around on overflow – this is the easy option. You could also use the -fcatch-undefined-behavior option to catch signed overflow at runtime and turn it into a crash so that you can debug and fix it.

Dmitri

Hi Martin,

I don't think there is such warning in clang, but you could use the -fwrapv option to define signed integer arithmetic to wrap around on overflow -- this is the easy option. You could also use the -fcatch-undefined-behavior option to catch signed overflow at runtime and turn it into a crash so that you can debug and fix it.

Dmitri

Hi Dimitri,

yes, -fwrapv or -fno-strict-overflow could be used here. But I would like to see which places are affected, so it would be great if -Wstrict-overflow would work. The option also seems to be recognized by the driver otherwise there would be a warning. It just does not seem to work internally which is bad if you rely on it (e.g. porting a GCC codebase).

Best regards,
Martin

Clang deliberately does not have any warnings which are dependent on optimization level, or any warnings which are produced by the optimizer. GCC’s warnings in this category tend to be flaky and very version-dependent, have false positives (due to dead code after inlining, usually), and can’t preserve enough information to provide useful diagnostics.

We have checking for some specific forms of overflow at compile time, but nothing flow-sensitive like this. It would probably be relatively straightforward to add overflow checking to the static analyzer, if you’re interested in doing so. If you want to catch this problem at runtime, you can use -ftrapv or -fcatch-undefined-behavior as Dmitri suggested.