in reply to Re^2: Why does $Config{ccflags} include "-fwrapv" on many gcc builds of perl ?
in thread Why does $Config{ccflags} include "-fwrapv" on many gcc builds of perl ?

-fwrapv gives implementation defined behaviour for wrapping variables but not constants.

#include <limits.h> #include <stdio.h> int main() { printf(" LONG_MIN %ld\n", LONG_MIN); printf(" LONG_MAX %ld\n", LONG_MAX); printf("-LONG_MAX %ld\n", -LONG_MIN); // line 9 long lval = LONG_MIN; lval = lval * -1; // this is okay with -fwrapv printf("wrap lval %ld\n", lval); }
$ gcc -Wall -Wextra -Woverflow -fwrapv -fsanitize=undefined t.c -o t & +& ./t t.c: In function ‘main’: t.c:9:31: warning: integer overflow in expression ‘-922337203685477580 +8’ of type ‘long int’ results in ‘-9223372036854775808’ [-Woverflow] 9 | printf("-LONG_MAX %ld\n", -LONG_MIN); // line 9 | ^ LONG_MIN -9223372036854775808 LONG_MAX 9223372036854775807 -LONG_MAX -9223372036854775808 wrap lval 9223372036854775807

I see that the patch fixes it by changing to unsigned int so it seems the wrapping is irrelevant there.

Replies are listed 'Best First'.
Re^4: Why does $Config{ccflags} include "-fwrapv" on many gcc builds of perl ?
by syphilis (Archbishop) on Apr 24, 2021 at 01:04 UTC
    I've since noticed that -fwrapv is omitted from CCFLAGS when I build perl on Windows using gcc-10.2.0. So I created an issue about that, wherein I again queried the need for the -fwrapv switch. In that thread, Tomasz Konojacki (@xenu) explains it clearly:

    <quote>
    -fwrapv basically means "signed integer overflow won't cause undefined behavior".
    In practice, gcc with this flag disabled will still wrap signed integers on overflow, because that's how virtually all CPUs implement signed integer arithmetic.
    However, what does change is the behavior of the optimizer: it will assume that all signed integers will never overflow.
    Because of that, the breakage caused by omission of this flag is very subtle and unpredictable, and there's no reasonable way to test for it.
    </quote>

    That makes good sense to me, and I also provided a patch to win32/GNUmakefile that fixes that issue with gcc-10.x.x and (presumably) later.

    Cheers,
    Rob