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

--- Comment #8 from Giuseppe D'Angelo <peppe at gcc dot gnu.org> ---
For the record, Clang >= 21 optimizes the code (the changelog mentions "New
LLVM optimizations have been implemented that optimize pointer arithmetic on
null pointers more aggressively").

https://gcc.godbolt.org/z/d6jer56hW

int& test(std::variant<int, bool> &v)
{
    return *std::get_if<int>(&v);
}


GCC 16.1 (-O2) still produces:

"test(std::variant<int, bool>&)":
        xor     eax, eax
        cmp     BYTE PTR [rdi+4], 0
        cmove   rax, rdi
        ret


Whereas Clang 22 under -O2 no longer has the branch: 

test(std::variant<int, bool>&):
        mov     rax, rdi
        ret


I'm not sure I understand the arguments about security. Are we talking about a
scenario where a compiler can (for instance) prove that the variant does NOT
contain the `int` alternative, reason that it's therefore dereferencing a null
pointer, which is UB, and then aggressively optimize backwards (with the usual
assumption that "UB can't happen") and this could wreck havok?

Reply via email to