gcc -O2 generates wrong code
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
gcc-4.1 (Ubuntu) |
Invalid
|
Undecided
|
Unassigned |
Bug Description
Binary package hint: gcc-4.1
When compiling this code with the -O2 flag the result is different than when compiling with -O, or when disabling tree-pre or strict-aliasing optimizations.
$ gcc -v
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --enable-
Thread model: posix
gcc version 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)
$ gcc -O test.c ; ./a.out
$ gcc -O2 test.c ; ./a.out
Ohhh
$ gcc -O2 -fno-tree-pre test.c ; ./a.out
$ gcc -O2 -fno-strict-
$ cat test.c
#include <stdlib.h>
#include <stdio.h>
int bmemcmp(void *a1, void *a2, unsigned len)
{
int dwlen = len / 4;
while (dwlen)
{
int res = *(int *)a1 - *(int *)a2;
if (res)
}
return 0;
}
int main(int argc, char *argv[])
{
int *p1 = (int*)calloc(
int *p2 = (int*)calloc(
p1[3] = 1;
if (bmemcmp(p1, p2, 1024 * 1024 * 4) == 0)
return 0;
}
description: | updated |
I believe that compiler is optimizing this lines:
return res;
int res = *(int *)a1 - *(int *)a2;
if (res)
So bmemcmp always return 0.