Bug 20729 - Bitwise operations work wrong with -O2 or -O3 optimization
Summary: Bitwise operations work wrong with -O2 or -O3 optimization
Status: RESOLVED DUPLICATE of bug 21920
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 3.4.3
: P2 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2005-04-02 12:36 UTC by Evgeny
Modified: 2005-07-23 22:49 UTC (History)
1 user (show)

See Also:
Host: i686-pc-linux-gnu
Target: i686-pc-linux-gnu
Build: i686-pc-linux-gnu
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Evgeny 2005-04-02 12:36:16 UTC
I wrote the following testcase:

#include <iostream>

using namespace std;

inline bool sign(double x){return !((*(((unsigned int*)&(x)) + 1))&0x80000000);}
inline bool sign1(double x){return (x>=0.0);}

inline bool cmp(double x,double y){
return ((*(((unsigned int*)&(x)) + 1))&0x80000000)^((*(((unsigned int*)&(y)) +
1))&0x80000000);
}

inline bool cmp1(double x,double y){
return ((x>=0.0)!=(y>=0.0));
}

int main(void){
double a(1.0),b(1.0);

cout << sign(a) << " " << sign(b) << " " << sign1(a) << " " << sign1(b) << endl;
cout << cmp(a,b) << " " << cmp1(a,b) << endl;
cout << a << " " << b << endl;
}

Its output is:
g++-3.4 test.cpp -O3 && ./a.out
0 1 1 1
1 0
1 1

g++ test.cpp -O3 && ./a.out
1 1 1 1
1 0
1 1

g++-3.4 -v
Reading specs from /usr/local/lib/gcc/i686-pc-linux-gnu/3.4.3/specs
Configured with: ./configure --prefix=/usr/local --program-suffix=-3.4
--enable-threads=posix --with-cpu=i686 --with-arch=i686 --disable-nls
Thread model: posix
gcc version 3.4.3

g++ -v
Reading specs from /usr/lib/gcc-lib/i586-suse-linux/3.3.2/specs
Configured with: ../configure --enable-threads=posix --prefix=/usr
--with-local-prefix=/usr/local --infodir=/usr/share/info --mandir=/usr/share/man
--libdir=/usr/lib --enable-languages=c,c++,f77,objc,java,ada --disable-checking
--enable-libgcj --with-gxx-include-dir=/usr/include/g++--with-slibdir=/lib
--with-system-zlib --enable-shared --enable-__cxa_atexit i586-suse-linux
Thread model: posix
gcc version 3.3.2 20031216 (prerelease) (SuSE Linux)

But the right output is:
1 1 1 1
0 0
1 1 

It can be reached at any optimization level by using flag -fno-schedule-insns2.
Comment 1 Andrew Pinski 2005-04-02 12:45:53 UTC
You are violating the C aliasing rules.
Either use an union or use -fno-strict-aliasing.
Comment 2 Andrew Pinski 2005-06-05 09:14:28 UTC
Reopening to ... 
Comment 3 Andrew Pinski 2005-06-05 09:14:47 UTC
Mark as a dup of bug 21920

*** This bug has been marked as a duplicate of 21920 ***