Compiling the following code with -O2 or higher in g++ 4.1.2 produces incorrect results. The problem doesn't occur in version 4.2.1. I compile like this: g++ -W -Wall -Werror -O2 -fPIC -o gccbug gccbug.cpp The last line of output should show the number 27, but it shows 0 when optimizing with -O2. A tar archive containing the source file and a Makefile to build it is here: http://dooglus.rincevent.net/random/gccbug.1190912601.tgz Defining any of FIX0, FIX1 or FIX2 fixes the problem. Here's the source file: ----- #include <iostream> #include <string> #include <vector> using namespace std; struct Vector { float _x, _y; Vector(): _x(0), _y(0) {}; float &m(const int &i) { return i?_y:_x; } }; struct Node { vector<Node*> nl; Node() {nl.push_back(this);}; string get_name() const {return "x";}; vector<Node*> get_children() { return nl;}; }; int six() { return 6; } Vector parse_vector(Node *element) { Vector vect; Node *node = element->get_children()[0]; if(node->get_name()=="x") { // true #ifdef FIX0 cout << "1. vect.m(0) <= 27" << endl; #else printf("1. vect.m(0) <= 27\n"); #endif vect.m(0)=27; #ifdef FIX1 // printing the value stops the over-optimization cout << "2. vect.m(0) == " << vect.m(0) << endl; #endif } else if(six() == 6 && node->get_children().empty()) { // false exit(0); return Vector(); } #ifdef FIX2 // checking the value also stops the over optimization if (vect.m(0) + vect.m(1) == 24234.657) cout << "har" << endl; #endif return vect; } int main() { cout << "3. vect.m(0) == " << parse_vector(new Node).m(0) << " <-- should be 27" << endl; } -----
Created attachment 14259 [details] the source file
Created attachment 14260 [details] the Makefile
The problem only affects the 4.1 branch. It does not appear on the 4.2 branch or mainline.
Well, actually this seems to be a duplicate of PR 30088. *** This bug has been marked as a duplicate of 30088 ***