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

            Bug ID: 115267
           Summary: Undue warning about undefined behavior in
           Product: gcc
           Version: 14.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: tobi at gcc dot gnu.org
  Target Milestone: ---

This seems to be a simpler case of PR103724. I originally observed it with 4.9
but was able to reproduce it with gcc 14.

Godbolt: https://godbolt.org/z/6h8bEYsvP


=== Testcase ===================
#include <iostream>
#include <sstream>

double arr[4];

void read(std::istream& is) {
    for (unsigned int i = 0; i < 2; ++i) {
        for (unsigned int j = i; j < 2; ++j) {
            is >> arr[2*i+j];
            if (i != j) {
                arr[2*j+i] = arr[2*i+j];
            }
        }
    }
}

int main()
{
    std::stringstream ss("1 2 3");
    read(ss);
    return int(arr[0] + arr[1]);
}
===

Gives with -O3 -Wall:
=========================
<source>:11:39: warning: iteration 4 invokes undefined behavior
[-Waggressive-loop-optimizations]
   11 |                 arr[2*j+i] = arr[2*i+j];
      |                              ~~~~~~~~~^
<source>:8:36: note: within this loop
    8 |         for (unsigned int j = i; j < 2; ++j) {
      |                           
==========================
Try as I might, I don't see the undefined behavior, the matrix is also
correctly filled in, no infinite loop obtains.  Signedness of the loop index
doesn't play a role.  The original code used a Eigen::Matrix2d instead of
manually indexing the 2x2 matirx, and then the warning is about iteration 2. 
The stringstream seems to be necessary to confuse the compiler enough, but
maybe there's a way of getting the same behavior with a less complex thing
inside the loop.

Reply via email to