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

            Bug ID: 97151
           Summary: GCC fails to optimize away uselessly allocated arrays
                    (C++)
           Product: gcc
           Version: 10.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: marat at slonopotamus dot org
  Target Milestone: ---

A test program:

int main()
{
    int *a = new int[10]();
    delete[] a;

    return 0;
}


Tested against: gcc 10.2.0 and gcc trunk as of 20200920 on codebolt.org with
-O2, -O3 and -Ofast

Expected: new/delete are optimized away under -O2 and higher because "a" is
never used for anything useful (like, side effects or whatever).

Actual: new/delete are present in assembly:

main:
        sub     rsp, 8
        mov     edi, 40
        call    operator new[](unsigned long)
        pxor    xmm0, xmm0
        mov     QWORD PTR [rax+32], 0
        mov     rdi, rax
        movups  XMMWORD PTR [rax], xmm0
        movups  XMMWORD PTR [rax+16], xmm0
        call    operator delete[](void*)
        xor     eax, eax
        add     rsp, 8
        ret

Interesting observations:

1. if "delete[]" is commented out, whole program is optimized away
2. if "new int[10]()" is replaced with "new int[10]", whole program is
optimized away
3. if new/delete is replaced with matching malloc/free, whole program is
optimized away

If someone wants to play with this example online, here it is:
https://godbolt.org/z/YoGzxo

Reply via email to