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

            Bug ID: 101436
           Summary: Yet another bogus "array subscript is partly outside
                    array bounds"
           Product: gcc
           Version: 11.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: cassio.neri at gmail dot com
  Target Milestone: ---

This bogus warning was reported at least twice recently: #98266 and #101374.
Below is a new case that, it seems, hasn't been addressed yet.

#include <typeinfo>

struct A {
  virtual ~A();
};

template <typename T>
struct B : A {
  T x;
};

struct C1 {
  int i;
  double j;
};

struct C2 {
  int i;
};

void do_something(int);
B<C2> get_BC2();

void h(A& a) {
  if (typeid(a) == typeid(B<C1>)) {
    B<C1>& b = static_cast<B<C1>&>(a);
    int i = b.x.i;
    do_something(i);
  }
}

void foo() {
  B<C2> x = get_BC2();
  h(x);
}

Compiled with '-O3 -Warray-bounds' yields:

<source>: In function 'void foo()':
<source>:27:9: warning: array subscript 'B<C1>[0]' is partly outside array
bounds of 'B<C2> [1]' [-Warray-bounds]
   27 |     int i = b.x.i;
      |         ^
<source>:33:9: note: while referencing 'x'
   33 |   B<C2> x = get_BC2();

FWIW:

1) This is a regression from GCC 10.3.

2) The warning goes away if any of the following changes are made:
  * Remove C1::j.
  * Change type of C1::j to any of int, char, bool, unsigned or float. (Perhaps
any type T such that sizeof(T) <= sizeof(int)).
  * Compile with '-fPIC' (however, if h is marked inline then the warning comes
back).

3) If b is declared as B<C1> (as opposed to B<C1>&), then the warning points to
line 'struct B: A {'.

4) The test case could be simplified further by removing A's virtual destructor
and the typeid check. However, this would make the code to invoke UB and I hope
the code above doesn't.

5) #98266 regards virtual inheritance which does not appear here and a test
cases therein issues no warning when compiled with GCC 11.1.

6) IIUC the warning reported by #101374 happens in GCC's own code and was
caused by some recent change that is not part of GCC 11.1. Indeed a test case
reported therein compiles fine with GCC 11.1 whereas the one above doesn't.

See also:

Test case above: https://godbolt.org/z/n4obaohPs
Test case from  #98266: https://godbolt.org/z/PEjfhs3T6
Test case from #101374: https://godbolt.org/z/Ebb8YszT5

Reply via email to