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

            Bug ID: 128826
           Summary: Regression: optional<T> initialization unconditionally
                    zeroes the contained storage
           Product: gcc
           Version: 16.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: barry.revzin at gmail dot com
  Target Milestone: ---

This example (https://compiler-explorer.com/z/aWj8EKf9W):

#include <optional>

struct T {
    int data[32];
};

auto test(bool b) -> std::optional<T> {
    if (b) [[likely]] {
        return T();
    }
    return {};
}

On gcc 14.2 -std=c++23 -O3 produced this assembly:

test(bool):
        mov     rax, rdi
        test    sil, sil
        je      .L2
        mov     DWORD PTR [rdi+128], 1
        pxor    xmm0, xmm0
        movups  XMMWORD PTR [rdi], xmm0
        movups  XMMWORD PTR [rdi+16], xmm0
        movups  XMMWORD PTR [rdi+32], xmm0
        movups  XMMWORD PTR [rdi+48], xmm0
        movups  XMMWORD PTR [rdi+64], xmm0
        movups  XMMWORD PTR [rdi+80], xmm0
        movups  XMMWORD PTR [rdi+96], xmm0
        movups  XMMWORD PTR [rdi+112], xmm0
        ret
.L2:
        mov     BYTE PTR [rdi+128], 0
        ret

On gcc 16.2 -std=c++23 -O3 produces this assembly:

"test(bool)":
        pxor    xmm0, xmm0
        mov     rax, rdi
        mov     DWORD PTR [rdi+128], 0
        movups  XMMWORD PTR [rdi], xmm0
        movups  XMMWORD PTR [rdi+16], xmm0
        movups  XMMWORD PTR [rdi+32], xmm0
        movups  XMMWORD PTR [rdi+48], xmm0
        movups  XMMWORD PTR [rdi+64], xmm0
        movups  XMMWORD PTR [rdi+80], xmm0
        movups  XMMWORD PTR [rdi+96], xmm0
        movups  XMMWORD PTR [rdi+112], xmm0
        test    sil, sil
        je      .L2
        mov     BYTE PTR [rdi+128], 1
        ret
.L2:
        ret

That is, test(false) now zero-initializes the whole blob whereas it used to
only zero the flag. This seems unrelated to erroneous behavior (both because
C++23 and it's the same behavior with -ftrivial-auto-var-init=uninitialized).

I've been trying to reduce this to not use std::optional and instead use a
hand-written class with a union: https://compiler-explorer.com/z/MnWW8jozo

namespace std {

struct Empty { };

template <class T>
union storage {
    Empty empty_;
    T val_;

    constexpr storage() : empty_() { }
    constexpr storage(T&& rhs) : val_((T&&)rhs) { }
};

template <class T>
struct optional {
    storage<T> val_;
    bool flag_;

    constexpr optional() noexcept : val_(), flag_(false) { }

    constexpr optional(T&& rhs) noexcept
        : val_(static_cast<T&&>(rhs)), flag_(true)
    { }
};
}

The actual union template seems relevant to the reproduction.

Reply via email to