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

            Bug ID: 122435
           Summary: Optimization failure with trivial loop
           Product: gcc
           Version: 15.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: tobi at gcc dot gnu.org
  Target Milestone: ---

I stumbled over code like this in one of our projects.  The function g is just
a wordy no-op.

https://godbolt.org/z/4crT5xrc7

======================= code follows =================
using size_t = unsigned long int;

template<class T>
struct Span {
    T *data;
    size_t size;
};

Span<int> g(Span<unsigned> sp)
{
    auto* p = reinterpret_cast<int *>(sp.data);
    Span sp2{p, sp.size};
    for (size_t i = 0; i < sp.size; ++i)
        sp2.data[i] = static_cast<int>(sp.data[i]);
    return sp2;
}

bool f() // Returns true
{
    unsigned a[] = {1, 2, 3, 4};
    Span sp{ a, 4 };
    Span sp2 = g(sp);
    for (int i = 0; i < 4; ++i) {
        if (sp2.data[i] != i + 1)
            return false;
    }
    return true;
}
===================== Code ends ==================

Observations: clang manages to trivialize the code for both functions.  gcc
fails for g() no matter the optimization settings.  The code for f() becomes
worse at -O3 than at -O.  Nevertheless, gcc with -O3 succeeds at simplifying
f().

Reply via email to