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

            Bug ID: 125863
           Summary: False positive -Warray-bounds in context of -O3 +
                    __builtin_unreachable()
           Product: gcc
           Version: 16.1.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: nicula at nicula dot xyz
  Target Milestone: ---

Created attachment 64761
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=64761&action=edit
false positive -Warray-bounds

Here is some code that does a `std::vector::resize()` to a size of 1, while
trying to get rid of the branch that may need to reallocate (i.e. the
`current_size < new_size` branch).

    #include <vector>

    void foo(std::vector<int> &vec) {
        if (vec.empty())
            __builtin_unreachable();
        vec.resize(1);
    }

GCC 16.1 result with `-O3`:

"foo(std::vector<int, std::allocator<int>>&)":
        mov     rdx, QWORD PTR [rdi+8]
        mov     rax, QWORD PTR [rdi]
        mov     rcx, rdx
        sub     rcx, rax
        cmp     rcx, 4
        jle     .L1
        add     rax, 4
        cmp     rdx, rax
        je      .L1
        mov     QWORD PTR [rdi+8], rax
.L1:
        ret

The problem is that you get a false positive `-Warray-bounds` when compiling
with `-O3 -Wall`. See the logs.txt file for the warning.

Note: if you do the same thing, but with `std::vector<Foo>` instead, where
`Foo` is `struct Foo { int x; }` you also get the warning. But if you change it
to `struct Foo { int x{}; }`, the warning goes away.

Also, changing the `__builtin_unreachable()`'s condition to `vec.size() < 1`
instead of `vec.empty()` achieves the same intended optimization but you don't
get the false positive `-Warray-bounds`.

Reply via email to