https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89698

            Bug ID: 89698
           Summary: Run-time error due to optimization of field access
                    after cast at -Os/-O2 and higher
           Product: gcc
           Version: 7.3.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: marcel at solidsands dot nl
  Target Milestone: ---

Created attachment 45956
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=45956&action=edit
Preprocessed version of example code

The following program (also attached) fails at a run-time assert when compiled
with -Os, -O2 or higher optimization. It fails on any recent g++ on 64-bit x86
and ARM64 platforms.

When compiled with -O1, the object fields are correctly initialized in the
test() function with:

        movl    $1, 8(%rsp)
        movl    $2, 12(%rsp)

When compiled with -Os, the second field is not initialized:

        movl    $1, 8(%rsp)


Compile with "g++ -O2 castoptim.i", execute with "./a.out"

See also:
https://www.solidsands.nl/wp-content/uploads/2019/03/201902LightGppError.pdf
See also: https://godbolt.org/z/q8b-cB

-----------------------------------------------

#include <cassert>

class A {
        virtual void f(){};
    public:
        int x;
        A(int in): x(in) {};
};

class B: public A {
    public:
        int y;
        B(int in):A(in-1), y(in) {};
};

int test(void) {
    int res;
    B b(2);
    A* bp = &b;
    void* vp = dynamic_cast<void*>(bp);
    if (  ((A*)vp)->x == 1
       && ((B*)vp)->y == 2
       ){
        return 1; // PASS
    } else {
        return 0; // FAIL
    }
}

int main (void) {
    assert (test ());
}

Reply via email to