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

            Bug ID: 129140
           Summary: wrong code at -O2: virtual call through the
                    constructor's this, made from a helper during
                    construction of a global object, devirtualized to the
                    derived class (decl_maybe_in_construction_p), since
                    r5-1694
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: ipa
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jeffchen006 at gmail dot com
  Target Milestone: ---
            Target: x86_64-pc-linux-gnu

extern "C" int printf(const char *, ...);
unsigned H;
namespace {
struct C0 {
  virtual int f0(int) { return 0; }
  virtual int f1(int) { return 0; }
  C0();
};
int h0(C0 *p) { return p->f0(4) * 3 + p->f1(2) * 4; }
struct C3 : C0 { int f1(int) { return 1; } };
struct C6 : C0 { int f0(int) { return 5; } };
C0::C0() { H = h0(this); }
C3 G4;
}
int main() {
  for (int t = 0; t;)
    new C6;
  printf("%u\n", H);
}

$ g++ -O1 t.cc && ./a.out
0
$ g++ -O2 t.cc && ./a.out
4

-O3 too; -O2 -fno-devirtualize gives 0. clang gives 0.

h0 is called with the constructor's own this while G4 is being constructed, so
both calls must go to the C0 functions ([class.cdtor]/4) and H is 0. ipa-cp
makes a clone of h0 for p = &G4, and in the clone decl_maybe_in_construction_p
(ipa-polymorphic-call.cc) says the global G4 is not in construction, because
the current function is not a constructor or destructor and has no inlined one.
So p->f1 becomes a direct call to C3::f1.

Bisected to r5-1694-g058d0a90597, which added decl_maybe_in_construction_p; its
parent prints 0. A shorter form where B::B () itself calls &d->f () on a global
D d also prints the derived result, but there the pointer is not obtained from
this, so I used the longer one.

gcc version 17.0.0 20261128 (experimental), r17-6781-gd10e6c3818a,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release
  • [Bug ipa/129140] New: wrong code... jeffchen006 at gmail dot com via Gcc-bugs

Reply via email to